eaf46659f85c95057ce5d87e30a25ad095dc1350
[platform/upstream/gcc.git] / gcc / cp / pt.c
1 /* Handle parameterized types (templates) for GNU -*- C++ -*-.
2    Copyright (C) 1992-2021 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      Fixed by: C++20 modules.  */
28
29 #include "config.h"
30 #include "system.h"
31 #include "coretypes.h"
32 #include "cp-tree.h"
33 #include "timevar.h"
34 #include "stringpool.h"
35 #include "varasm.h"
36 #include "attribs.h"
37 #include "stor-layout.h"
38 #include "intl.h"
39 #include "c-family/c-objc.h"
40 #include "cp-objcp-common.h"
41 #include "toplev.h"
42 #include "tree-iterator.h"
43 #include "type-utils.h"
44 #include "gimplify.h"
45 #include "gcc-rich-location.h"
46 #include "selftest.h"
47 #include "target.h"
48
49 /* The type of functions taking a tree, and some additional data, and
50    returning an int.  */
51 typedef int (*tree_fn_t) (tree, void*);
52
53 /* The PENDING_TEMPLATES is a list of templates whose instantiations
54    have been deferred, either because their definitions were not yet
55    available, or because we were putting off doing the work.  */
56 struct GTY ((chain_next ("%h.next"))) pending_template
57 {
58   struct pending_template *next;
59   struct tinst_level *tinst;
60 };
61
62 static GTY(()) struct pending_template *pending_templates;
63 static GTY(()) struct pending_template *last_pending_template;
64
65 int processing_template_parmlist;
66 static int template_header_count;
67
68 static vec<int> inline_parm_levels;
69
70 static GTY(()) struct tinst_level *current_tinst_level;
71
72 static GTY(()) vec<tree, va_gc> *saved_access_scope;
73
74 /* Live only within one (recursive) call to tsubst_expr.  We use
75    this to pass the statement expression node from the STMT_EXPR
76    to the EXPR_STMT that is its result.  */
77 static tree cur_stmt_expr;
78
79 // -------------------------------------------------------------------------- //
80 // Local Specialization Stack
81 //
82 // Implementation of the RAII helper for creating new local
83 // specializations.
84 local_specialization_stack::local_specialization_stack (lss_policy policy)
85   : saved (local_specializations)
86 {
87   if (policy == lss_nop)
88     ;
89   else if (policy == lss_blank || !saved)
90     local_specializations = new hash_map<tree, tree>;
91   else
92     local_specializations = new hash_map<tree, tree>(*saved);
93 }
94
95 local_specialization_stack::~local_specialization_stack ()
96 {
97   if (local_specializations != saved)
98     {
99       delete local_specializations;
100       local_specializations = saved;
101     }
102 }
103
104 /* True if we've recursed into fn_type_unification too many times.  */
105 static bool excessive_deduction_depth;
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 /* The general template is not in these tables.  */
114 typedef hash_table<spec_hasher> spec_hash_table;
115 static GTY (()) spec_hash_table *decl_specializations;
116 static GTY (()) spec_hash_table *type_specializations;
117
118 /* Contains canonical template parameter types. The vector is indexed by
119    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
120    TREE_LIST, whose TREE_VALUEs contain the canonical template
121    parameters of various types and levels.  */
122 static GTY(()) vec<tree, va_gc> *canonical_template_parms;
123
124 #define UNIFY_ALLOW_NONE 0
125 #define UNIFY_ALLOW_MORE_CV_QUAL 1
126 #define UNIFY_ALLOW_LESS_CV_QUAL 2
127 #define UNIFY_ALLOW_DERIVED 4
128 #define UNIFY_ALLOW_INTEGER 8
129 #define UNIFY_ALLOW_OUTER_LEVEL 16
130 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
131 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
132
133 enum template_base_result {
134   tbr_incomplete_type,
135   tbr_ambiguous_baseclass,
136   tbr_success
137 };
138
139 static bool resolve_overloaded_unification (tree, tree, tree, tree,
140                                             unification_kind_t, int,
141                                             bool);
142 static int try_one_overload (tree, tree, tree, tree, tree,
143                              unification_kind_t, int, bool, bool);
144 static int unify (tree, tree, tree, tree, int, bool);
145 static void add_pending_template (tree);
146 static tree reopen_tinst_level (struct tinst_level *);
147 static tree tsubst_initializer_list (tree, tree);
148 static tree get_partial_spec_bindings (tree, tree, tree);
149 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
150                                    bool, bool);
151 static tree coerce_innermost_template_parms (tree, tree, tree, tsubst_flags_t,
152                                               bool, bool);
153 static void tsubst_enum (tree, tree, tree);
154 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
155 static int check_non_deducible_conversion (tree, tree, int, int,
156                                            struct conversion **, bool);
157 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
158                                              tree);
159 static int type_unification_real (tree, tree, tree, const tree *,
160                                   unsigned int, int, unification_kind_t,
161                                   vec<deferred_access_check, va_gc> **,
162                                   bool);
163 static void note_template_header (int);
164 static tree convert_nontype_argument_function (tree, tree, tsubst_flags_t);
165 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
166 static tree convert_template_argument (tree, tree, tree,
167                                        tsubst_flags_t, int, tree);
168 static tree for_each_template_parm (tree, tree_fn_t, void*,
169                                     hash_set<tree> *, bool, tree_fn_t = NULL);
170 static tree expand_template_argument_pack (tree);
171 static tree build_template_parm_index (int, int, int, tree, tree);
172 static bool inline_needs_template_parms (tree, bool);
173 static void push_inline_template_parms_recursive (tree, int);
174 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
175 static int mark_template_parm (tree, void *);
176 static int template_parm_this_level_p (tree, void *);
177 static tree tsubst_friend_function (tree, tree);
178 static tree tsubst_friend_class (tree, tree);
179 static int can_complete_type_without_circularity (tree);
180 static tree get_bindings (tree, tree, tree, bool);
181 static int template_decl_level (tree);
182 static int check_cv_quals_for_unify (int, tree, tree);
183 static int unify_pack_expansion (tree, tree, tree,
184                                  tree, unification_kind_t, bool, bool);
185 static tree copy_template_args (tree);
186 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
187 tree most_specialized_partial_spec (tree, tsubst_flags_t);
188 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
189 static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
190 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
191 static bool check_specialization_scope (void);
192 static tree process_partial_specialization (tree);
193 static void set_current_access_from_decl (tree);
194 static enum template_base_result get_template_base (tree, tree, tree, tree,
195                                                     bool , tree *);
196 static tree try_class_unification (tree, tree, tree, tree, bool);
197 static bool class_nttp_const_wrapper_p (tree t);
198 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
199                                            tree, tree);
200 static bool template_template_parm_bindings_ok_p (tree, tree);
201 static void tsubst_default_arguments (tree, tsubst_flags_t);
202 static tree for_each_template_parm_r (tree *, int *, void *);
203 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
204 static void copy_default_args_to_explicit_spec (tree);
205 static bool invalid_nontype_parm_type_p (tree, tsubst_flags_t);
206 static bool dependent_template_arg_p (tree);
207 static bool any_template_arguments_need_structural_equality_p (tree);
208 static bool dependent_type_p_r (tree);
209 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
210 static tree tsubst_decl (tree, tree, tsubst_flags_t);
211 static void perform_instantiation_time_access_checks (tree, tree);
212 static tree listify (tree);
213 static tree listify_autos (tree, tree);
214 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
215 static tree instantiate_alias_template (tree, tree, tsubst_flags_t);
216 static bool complex_alias_template_p (const_tree tmpl);
217 static tree get_underlying_template (tree);
218 static tree tsubst_attributes (tree, tree, tsubst_flags_t, tree);
219 static tree canonicalize_expr_argument (tree, tsubst_flags_t);
220 static tree make_argument_pack (tree);
221 static void register_parameter_specializations (tree, tree);
222 static tree enclosing_instantiation_of (tree tctx);
223 static void instantiate_body (tree pattern, tree args, tree d, bool nested);
224
225 /* Make the current scope suitable for access checking when we are
226    processing T.  T can be FUNCTION_DECL for instantiated function
227    template, VAR_DECL for static member variable, or TYPE_DECL for
228    alias template (needed by instantiate_decl).  */
229
230 void
231 push_access_scope (tree t)
232 {
233   gcc_assert (VAR_OR_FUNCTION_DECL_P (t)
234               || TREE_CODE (t) == TYPE_DECL);
235
236   if (DECL_FRIEND_CONTEXT (t))
237     push_nested_class (DECL_FRIEND_CONTEXT (t));
238   else if (DECL_CLASS_SCOPE_P (t))
239     push_nested_class (DECL_CONTEXT (t));
240   else
241     push_to_top_level ();
242
243   if (TREE_CODE (t) == FUNCTION_DECL)
244     {
245       vec_safe_push (saved_access_scope, current_function_decl);
246       current_function_decl = t;
247     }
248 }
249
250 /* Restore the scope set up by push_access_scope.  T is the node we
251    are processing.  */
252
253 void
254 pop_access_scope (tree t)
255 {
256   if (TREE_CODE (t) == FUNCTION_DECL)
257     current_function_decl = saved_access_scope->pop();
258
259   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
260     pop_nested_class ();
261   else
262     pop_from_top_level ();
263 }
264
265 /* Do any processing required when DECL (a member template
266    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
267    to DECL, unless it is a specialization, in which case the DECL
268    itself is returned.  */
269
270 tree
271 finish_member_template_decl (tree decl)
272 {
273   if (decl == error_mark_node)
274     return error_mark_node;
275
276   gcc_assert (DECL_P (decl));
277
278   if (TREE_CODE (decl) == TYPE_DECL)
279     {
280       tree type;
281
282       type = TREE_TYPE (decl);
283       if (type == error_mark_node)
284         return error_mark_node;
285       if (MAYBE_CLASS_TYPE_P (type)
286           && CLASSTYPE_TEMPLATE_INFO (type)
287           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
288         {
289           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
290           check_member_template (tmpl);
291           return tmpl;
292         }
293       return NULL_TREE;
294     }
295   else if (TREE_CODE (decl) == FIELD_DECL)
296     error_at (DECL_SOURCE_LOCATION (decl),
297               "data member %qD cannot be a member template", decl);
298   else if (DECL_TEMPLATE_INFO (decl))
299     {
300       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
301         {
302           check_member_template (DECL_TI_TEMPLATE (decl));
303           return DECL_TI_TEMPLATE (decl);
304         }
305       else
306         return decl;
307     }
308   else
309     error_at (DECL_SOURCE_LOCATION (decl),
310               "invalid member template declaration %qD", decl);
311
312   return error_mark_node;
313 }
314
315 /* Create a template info node.  */
316
317 tree
318 build_template_info (tree template_decl, tree template_args)
319 {
320   tree result = make_node (TEMPLATE_INFO);
321   TI_TEMPLATE (result) = template_decl;
322   TI_ARGS (result) = template_args;
323   return result;
324 }
325
326 /* Return the template info node corresponding to T, whatever T is.  */
327
328 tree
329 get_template_info (const_tree t)
330 {
331   tree tinfo = NULL_TREE;
332
333   if (!t || t == error_mark_node)
334     return NULL;
335
336   if (TREE_CODE (t) == NAMESPACE_DECL
337       || TREE_CODE (t) == PARM_DECL)
338     return NULL;
339
340   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
341     tinfo = DECL_TEMPLATE_INFO (t);
342
343   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
344     t = TREE_TYPE (t);
345
346   if (OVERLOAD_TYPE_P (t))
347     tinfo = TYPE_TEMPLATE_INFO (t);
348   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
349     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
350
351   return tinfo;
352 }
353
354 /* Returns the template nesting level of the indicated class TYPE.
355
356    For example, in:
357      template <class T>
358      struct A
359      {
360        template <class U>
361        struct B {};
362      };
363
364    A<T>::B<U> has depth two, while A<T> has depth one.
365    Both A<T>::B<int> and A<int>::B<U> have depth one, if
366    they are instantiations, not specializations.
367
368    This function is guaranteed to return 0 if passed NULL_TREE so
369    that, for example, `template_class_depth (current_class_type)' is
370    always safe.  */
371
372 int
373 template_class_depth (tree type)
374 {
375   int depth;
376
377   for (depth = 0; type && TREE_CODE (type) != NAMESPACE_DECL; )
378     {
379       tree tinfo = get_template_info (type);
380
381       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
382           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
383         ++depth;
384
385       if (DECL_P (type))
386         {
387           if (tree fctx = DECL_FRIEND_CONTEXT (type))
388             type = fctx;
389           else
390             type = CP_DECL_CONTEXT (type);
391         }
392       else if (LAMBDA_TYPE_P (type) && LAMBDA_TYPE_EXTRA_SCOPE (type))
393         type = LAMBDA_TYPE_EXTRA_SCOPE (type);
394       else
395         type = CP_TYPE_CONTEXT (type);
396     }
397
398   return depth;
399 }
400
401 /* Return TRUE if NODE instantiates a template that has arguments of
402    its own, be it directly a primary template or indirectly through a
403    partial specializations.  */
404 static bool
405 instantiates_primary_template_p (tree node)
406 {
407   tree tinfo = get_template_info (node);
408   if (!tinfo)
409     return false;
410
411   tree tmpl = TI_TEMPLATE (tinfo);
412   if (PRIMARY_TEMPLATE_P (tmpl))
413     return true;
414
415   if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
416     return false;
417
418   /* So now we know we have a specialization, but it could be a full
419      or a partial specialization.  To tell which, compare the depth of
420      its template arguments with those of its context.  */
421
422   tree ctxt = DECL_CONTEXT (tmpl);
423   tree ctinfo = get_template_info (ctxt);
424   if (!ctinfo)
425     return true;
426
427   return (TMPL_ARGS_DEPTH (TI_ARGS (tinfo))
428           > TMPL_ARGS_DEPTH (TI_ARGS (ctinfo)));
429 }
430
431 /* Subroutine of maybe_begin_member_template_processing.
432    Returns true if processing DECL needs us to push template parms.  */
433
434 static bool
435 inline_needs_template_parms (tree decl, bool nsdmi)
436 {
437   if (!decl || (!nsdmi && ! DECL_TEMPLATE_INFO (decl)))
438     return false;
439
440   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
441           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
442 }
443
444 /* Subroutine of maybe_begin_member_template_processing.
445    Push the template parms in PARMS, starting from LEVELS steps into the
446    chain, and ending at the beginning, since template parms are listed
447    innermost first.  */
448
449 static void
450 push_inline_template_parms_recursive (tree parmlist, int levels)
451 {
452   tree parms = TREE_VALUE (parmlist);
453   int i;
454
455   if (levels > 1)
456     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
457
458   ++processing_template_decl;
459   current_template_parms
460     = tree_cons (size_int (processing_template_decl),
461                  parms, current_template_parms);
462   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
463
464   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
465                NULL);
466   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
467     {
468       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
469
470       if (error_operand_p (parm))
471         continue;
472
473       gcc_assert (DECL_P (parm));
474
475       switch (TREE_CODE (parm))
476         {
477         case TYPE_DECL:
478         case TEMPLATE_DECL:
479           pushdecl (parm);
480           break;
481
482         case PARM_DECL:
483           /* Push the CONST_DECL.  */
484           pushdecl (TEMPLATE_PARM_DECL (DECL_INITIAL (parm)));
485           break;
486
487         default:
488           gcc_unreachable ();
489         }
490     }
491 }
492
493 /* Restore the template parameter context for a member template, a
494    friend template defined in a class definition, or a non-template
495    member of template class.  */
496
497 void
498 maybe_begin_member_template_processing (tree decl)
499 {
500   tree parms;
501   int levels = 0;
502   bool nsdmi = TREE_CODE (decl) == FIELD_DECL;
503
504   if (nsdmi)
505     {
506       tree ctx = DECL_CONTEXT (decl);
507       decl = (CLASSTYPE_TEMPLATE_INFO (ctx)
508               /* Disregard full specializations (c++/60999).  */
509               && uses_template_parms (ctx)
510               ? CLASSTYPE_TI_TEMPLATE (ctx) : NULL_TREE);
511     }
512
513   if (inline_needs_template_parms (decl, nsdmi))
514     {
515       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
516       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
517
518       if (DECL_TEMPLATE_SPECIALIZATION (decl))
519         {
520           --levels;
521           parms = TREE_CHAIN (parms);
522         }
523
524       push_inline_template_parms_recursive (parms, levels);
525     }
526
527   /* Remember how many levels of template parameters we pushed so that
528      we can pop them later.  */
529   inline_parm_levels.safe_push (levels);
530 }
531
532 /* Undo the effects of maybe_begin_member_template_processing.  */
533
534 void
535 maybe_end_member_template_processing (void)
536 {
537   int i;
538   int last;
539
540   if (inline_parm_levels.length () == 0)
541     return;
542
543   last = inline_parm_levels.pop ();
544   for (i = 0; i < last; ++i)
545     {
546       --processing_template_decl;
547       current_template_parms = TREE_CHAIN (current_template_parms);
548       poplevel (0, 0, 0);
549     }
550 }
551
552 /* Return a new template argument vector which contains all of ARGS,
553    but has as its innermost set of arguments the EXTRA_ARGS.  */
554
555 tree
556 add_to_template_args (tree args, tree extra_args)
557 {
558   tree new_args;
559   int extra_depth;
560   int i;
561   int j;
562
563   if (args == NULL_TREE || extra_args == error_mark_node)
564     return extra_args;
565
566   extra_depth = TMPL_ARGS_DEPTH (extra_args);
567   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
568
569   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
570     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
571
572   for (j = 1; j <= extra_depth; ++j, ++i)
573     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
574
575   return new_args;
576 }
577
578 /* Like add_to_template_args, but only the outermost ARGS are added to
579    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
580    (EXTRA_ARGS) levels are added.  This function is used to combine
581    the template arguments from a partial instantiation with the
582    template arguments used to attain the full instantiation from the
583    partial instantiation.
584
585    If ARGS is a TEMPLATE_DECL, use its parameters as args.  */
586
587 tree
588 add_outermost_template_args (tree args, tree extra_args)
589 {
590   tree new_args;
591
592   if (!args)
593     return extra_args;
594   if (TREE_CODE (args) == TEMPLATE_DECL)
595     {
596       tree ti = get_template_info (DECL_TEMPLATE_RESULT (args));
597       args = TI_ARGS (ti);
598     }
599
600   /* If there are more levels of EXTRA_ARGS than there are ARGS,
601      something very fishy is going on.  */
602   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
603
604   /* If *all* the new arguments will be the EXTRA_ARGS, just return
605      them.  */
606   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
607     return extra_args;
608
609   /* For the moment, we make ARGS look like it contains fewer levels.  */
610   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
611
612   new_args = add_to_template_args (args, extra_args);
613
614   /* Now, we restore ARGS to its full dimensions.  */
615   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
616
617   return new_args;
618 }
619
620 /* Return the N levels of innermost template arguments from the ARGS.  */
621
622 tree
623 get_innermost_template_args (tree args, int n)
624 {
625   tree new_args;
626   int extra_levels;
627   int i;
628
629   gcc_assert (n >= 0);
630
631   /* If N is 1, just return the innermost set of template arguments.  */
632   if (n == 1)
633     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
634
635   /* If we're not removing anything, just return the arguments we were
636      given.  */
637   extra_levels = TMPL_ARGS_DEPTH (args) - n;
638   gcc_assert (extra_levels >= 0);
639   if (extra_levels == 0)
640     return args;
641
642   /* Make a new set of arguments, not containing the outer arguments.  */
643   new_args = make_tree_vec (n);
644   for (i = 1; i <= n; ++i)
645     SET_TMPL_ARGS_LEVEL (new_args, i,
646                          TMPL_ARGS_LEVEL (args, i + extra_levels));
647
648   return new_args;
649 }
650
651 /* The inverse of get_innermost_template_args: Return all but the innermost
652    EXTRA_LEVELS levels of template arguments from the ARGS.  */
653
654 static tree
655 strip_innermost_template_args (tree args, int extra_levels)
656 {
657   tree new_args;
658   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
659   int i;
660
661   gcc_assert (n >= 0);
662
663   /* If N is 1, just return the outermost set of template arguments.  */
664   if (n == 1)
665     return TMPL_ARGS_LEVEL (args, 1);
666
667   /* If we're not removing anything, just return the arguments we were
668      given.  */
669   gcc_assert (extra_levels >= 0);
670   if (extra_levels == 0)
671     return args;
672
673   /* Make a new set of arguments, not containing the inner arguments.  */
674   new_args = make_tree_vec (n);
675   for (i = 1; i <= n; ++i)
676     SET_TMPL_ARGS_LEVEL (new_args, i,
677                          TMPL_ARGS_LEVEL (args, i));
678
679   return new_args;
680 }
681
682 /* We've got a template header coming up; push to a new level for storing
683    the parms.  */
684
685 void
686 begin_template_parm_list (void)
687 {
688   /* We use a non-tag-transparent scope here, which causes pushtag to
689      put tags in this scope, rather than in the enclosing class or
690      namespace scope.  This is the right thing, since we want
691      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
692      global template class, push_template_decl handles putting the
693      TEMPLATE_DECL into top-level scope.  For a nested template class,
694      e.g.:
695
696        template <class T> struct S1 {
697          template <class T> struct S2 {};
698        };
699
700      pushtag contains special code to insert the TEMPLATE_DECL for S2
701      at the right scope.  */
702   begin_scope (sk_template_parms, NULL);
703   ++processing_template_decl;
704   ++processing_template_parmlist;
705   note_template_header (0);
706
707   /* Add a dummy parameter level while we process the parameter list.  */
708   current_template_parms
709     = tree_cons (size_int (processing_template_decl),
710                  make_tree_vec (0),
711                  current_template_parms);
712 }
713
714 /* This routine is called when a specialization is declared.  If it is
715    invalid to declare a specialization here, an error is reported and
716    false is returned, otherwise this routine will return true.  */
717
718 static bool
719 check_specialization_scope (void)
720 {
721   tree scope = current_scope ();
722
723   /* [temp.expl.spec]
724
725      An explicit specialization shall be declared in the namespace of
726      which the template is a member, or, for member templates, in the
727      namespace of which the enclosing class or enclosing class
728      template is a member.  An explicit specialization of a member
729      function, member class or static data member of a class template
730      shall be declared in the namespace of which the class template
731      is a member.  */
732   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
733     {
734       error ("explicit specialization in non-namespace scope %qD", scope);
735       return false;
736     }
737
738   /* [temp.expl.spec]
739
740      In an explicit specialization declaration for a member of a class
741      template or a member template that appears in namespace scope,
742      the member template and some of its enclosing class templates may
743      remain unspecialized, except that the declaration shall not
744      explicitly specialize a class member template if its enclosing
745      class templates are not explicitly specialized as well.  */
746   if (current_template_parms)
747     {
748       error ("enclosing class templates are not explicitly specialized");
749       return false;
750     }
751
752   return true;
753 }
754
755 /* We've just seen template <>.  */
756
757 bool
758 begin_specialization (void)
759 {
760   begin_scope (sk_template_spec, NULL);
761   note_template_header (1);
762   return check_specialization_scope ();
763 }
764
765 /* Called at then end of processing a declaration preceded by
766    template<>.  */
767
768 void
769 end_specialization (void)
770 {
771   finish_scope ();
772   reset_specialization ();
773 }
774
775 /* Any template <>'s that we have seen thus far are not referring to a
776    function specialization.  */
777
778 void
779 reset_specialization (void)
780 {
781   processing_specialization = 0;
782   template_header_count = 0;
783 }
784
785 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
786    it was of the form template <>.  */
787
788 static void
789 note_template_header (int specialization)
790 {
791   processing_specialization = specialization;
792   template_header_count++;
793 }
794
795 /* We're beginning an explicit instantiation.  */
796
797 void
798 begin_explicit_instantiation (void)
799 {
800   gcc_assert (!processing_explicit_instantiation);
801   processing_explicit_instantiation = true;
802 }
803
804
805 void
806 end_explicit_instantiation (void)
807 {
808   gcc_assert (processing_explicit_instantiation);
809   processing_explicit_instantiation = false;
810 }
811
812 /* An explicit specialization or partial specialization of TMPL is being
813    declared.  Check that the namespace in which the specialization is
814    occurring is permissible.  Returns false iff it is invalid to
815    specialize TMPL in the current namespace.  */
816
817 static bool
818 check_specialization_namespace (tree tmpl)
819 {
820   tree tpl_ns = decl_namespace_context (tmpl);
821
822   /* [tmpl.expl.spec]
823
824      An explicit specialization shall be declared in a namespace enclosing the
825      specialized template. An explicit specialization whose declarator-id is
826      not qualified shall be declared in the nearest enclosing namespace of the
827      template, or, if the namespace is inline (7.3.1), any namespace from its
828      enclosing namespace set.  */
829   if (current_scope() != DECL_CONTEXT (tmpl)
830       && !at_namespace_scope_p ())
831     {
832       error ("specialization of %qD must appear at namespace scope", tmpl);
833       return false;
834     }
835
836   if (is_nested_namespace (current_namespace, tpl_ns, cxx_dialect < cxx11))
837     /* Same or enclosing namespace.  */
838     return true;
839   else
840     {
841       auto_diagnostic_group d;
842       if (permerror (input_location,
843                      "specialization of %qD in different namespace", tmpl))
844         inform (DECL_SOURCE_LOCATION (tmpl),
845                 "  from definition of %q#D", tmpl);
846       return false;
847     }
848 }
849
850 /* SPEC is an explicit instantiation.  Check that it is valid to
851    perform this explicit instantiation in the current namespace.  */
852
853 static void
854 check_explicit_instantiation_namespace (tree spec)
855 {
856   tree ns;
857
858   /* DR 275: An explicit instantiation shall appear in an enclosing
859      namespace of its template.  */
860   ns = decl_namespace_context (spec);
861   if (!is_nested_namespace (current_namespace, ns))
862     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
863                "(which does not enclose namespace %qD)",
864                spec, current_namespace, ns);
865 }
866
867 /* Returns the type of a template specialization only if that
868    specialization needs to be defined. Otherwise (e.g., if the type has
869    already been defined), the function returns NULL_TREE.  */
870
871 static tree
872 maybe_new_partial_specialization (tree type)
873 {
874   /* An implicit instantiation of an incomplete type implies
875      the definition of a new class template.
876
877         template<typename T>
878           struct S;
879
880         template<typename T>
881           struct S<T*>;
882
883      Here, S<T*> is an implicit instantiation of S whose type
884      is incomplete.  */
885   if (CLASSTYPE_IMPLICIT_INSTANTIATION (type) && !COMPLETE_TYPE_P (type))
886     return type;
887
888   /* It can also be the case that TYPE is a completed specialization.
889      Continuing the previous example, suppose we also declare:
890
891         template<typename T>
892           requires Integral<T>
893             struct S<T*>;
894
895      Here, S<T*> refers to the specialization S<T*> defined
896      above. However, we need to differentiate definitions because
897      we intend to define a new partial specialization. In this case,
898      we rely on the fact that the constraints are different for
899      this declaration than that above.
900
901      Note that we also get here for injected class names and
902      late-parsed template definitions. We must ensure that we
903      do not create new type declarations for those cases.  */
904   if (flag_concepts && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
905     {
906       tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
907       tree args = CLASSTYPE_TI_ARGS (type);
908
909       /* If there are no template parameters, this cannot be a new
910          partial template specialization?  */
911       if (!current_template_parms)
912         return NULL_TREE;
913
914       /* The injected-class-name is not a new partial specialization.  */
915       if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
916         return NULL_TREE;
917
918       /* If the constraints are not the same as those of the primary
919          then, we can probably create a new specialization.  */
920       tree type_constr = current_template_constraints ();
921
922       if (type == TREE_TYPE (tmpl))
923         {
924           tree main_constr = get_constraints (tmpl);
925           if (equivalent_constraints (type_constr, main_constr))
926             return NULL_TREE;
927         }
928
929       /* Also, if there's a pre-existing specialization with matching
930          constraints, then this also isn't new.  */
931       tree specs = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
932       while (specs)
933         {
934           tree spec_tmpl = TREE_VALUE (specs);
935           tree spec_args = TREE_PURPOSE (specs);
936           tree spec_constr = get_constraints (spec_tmpl);
937           if (comp_template_args (args, spec_args)
938               && equivalent_constraints (type_constr, spec_constr))
939             return NULL_TREE;
940           specs = TREE_CHAIN (specs);
941         }
942
943       /* Create a new type node (and corresponding type decl)
944          for the newly declared specialization.  */
945       tree t = make_class_type (TREE_CODE (type));
946       CLASSTYPE_DECLARED_CLASS (t) = CLASSTYPE_DECLARED_CLASS (type);
947       SET_TYPE_TEMPLATE_INFO (t, build_template_info (tmpl, args));
948
949       /* We only need a separate type node for storing the definition of this
950          partial specialization; uses of S<T*> are unconstrained, so all are
951          equivalent.  So keep TYPE_CANONICAL the same.  */
952       TYPE_CANONICAL (t) = TYPE_CANONICAL (type);
953
954       /* Build the corresponding type decl.  */
955       tree d = create_implicit_typedef (DECL_NAME (tmpl), t);
956       DECL_CONTEXT (d) = TYPE_CONTEXT (t);
957       DECL_SOURCE_LOCATION (d) = input_location;
958       TREE_PRIVATE (d) = (current_access_specifier == access_private_node);
959       TREE_PROTECTED (d) = (current_access_specifier == access_protected_node);
960
961       set_instantiating_module (d);
962       DECL_MODULE_EXPORT_P (d) = DECL_MODULE_EXPORT_P (tmpl);
963
964       return t;
965     }
966
967   return NULL_TREE;
968 }
969
970 /* The TYPE is being declared.  If it is a template type, that means it
971    is a partial specialization.  Do appropriate error-checking.  */
972
973 tree
974 maybe_process_partial_specialization (tree type)
975 {
976   tree context;
977
978   if (type == error_mark_node)
979     return error_mark_node;
980
981   /* A lambda that appears in specialization context is not itself a
982      specialization.  */
983   if (CLASS_TYPE_P (type) && CLASSTYPE_LAMBDA_EXPR (type))
984     return type;
985
986   /* An injected-class-name is not a specialization.  */
987   if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
988     return type;
989
990   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
991     {
992       error ("name of class shadows template template parameter %qD",
993              TYPE_NAME (type));
994       return error_mark_node;
995     }
996
997   context = TYPE_CONTEXT (type);
998
999   if (TYPE_ALIAS_P (type))
1000     {
1001       tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (type);
1002
1003       if (tinfo && DECL_ALIAS_TEMPLATE_P (TI_TEMPLATE (tinfo)))
1004         error ("specialization of alias template %qD",
1005                TI_TEMPLATE (tinfo));
1006       else
1007         error ("explicit specialization of non-template %qT", type);
1008       return error_mark_node;
1009     }
1010   else if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
1011     {
1012       /* This is for ordinary explicit specialization and partial
1013          specialization of a template class such as:
1014
1015            template <> class C<int>;
1016
1017          or:
1018
1019            template <class T> class C<T*>;
1020
1021          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
1022
1023       if (tree t = maybe_new_partial_specialization (type))
1024         {
1025           if (!check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (t))
1026               && !at_namespace_scope_p ())
1027             return error_mark_node;
1028           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (t);
1029           DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (t)) = input_location;
1030           if (processing_template_decl)
1031             {
1032               tree decl = push_template_decl (TYPE_MAIN_DECL (t));
1033               if (decl == error_mark_node)
1034                 return error_mark_node;
1035               return TREE_TYPE (decl);
1036             }
1037         }
1038       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
1039         error ("specialization of %qT after instantiation", type);
1040       else if (errorcount && !processing_specialization
1041                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (type)
1042                && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
1043         /* Trying to define a specialization either without a template<> header
1044            or in an inappropriate place.  We've already given an error, so just
1045            bail now so we don't actually define the specialization.  */
1046         return error_mark_node;
1047     }
1048   else if (CLASS_TYPE_P (type)
1049            && !CLASSTYPE_USE_TEMPLATE (type)
1050            && CLASSTYPE_TEMPLATE_INFO (type)
1051            && context && CLASS_TYPE_P (context)
1052            && CLASSTYPE_TEMPLATE_INFO (context))
1053     {
1054       /* This is for an explicit specialization of member class
1055          template according to [temp.expl.spec/18]:
1056
1057            template <> template <class U> class C<int>::D;
1058
1059          The context `C<int>' must be an implicit instantiation.
1060          Otherwise this is just a member class template declared
1061          earlier like:
1062
1063            template <> class C<int> { template <class U> class D; };
1064            template <> template <class U> class C<int>::D;
1065
1066          In the first case, `C<int>::D' is a specialization of `C<T>::D'
1067          while in the second case, `C<int>::D' is a primary template
1068          and `C<T>::D' may not exist.  */
1069
1070       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
1071           && !COMPLETE_TYPE_P (type))
1072         {
1073           tree t;
1074           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
1075
1076           if (current_namespace
1077               != decl_namespace_context (tmpl))
1078             {
1079               if (permerror (input_location,
1080                              "specialization of %qD in different namespace",
1081                              type))
1082                 inform (DECL_SOURCE_LOCATION (tmpl),
1083                         "from definition of %q#D", tmpl);
1084             }
1085
1086           /* Check for invalid specialization after instantiation:
1087
1088                template <> template <> class C<int>::D<int>;
1089                template <> template <class U> class C<int>::D;  */
1090
1091           for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
1092                t; t = TREE_CHAIN (t))
1093             {
1094               tree inst = TREE_VALUE (t);
1095               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst)
1096                   || !COMPLETE_OR_OPEN_TYPE_P (inst))
1097                 {
1098                   /* We already have a full specialization of this partial
1099                      instantiation, or a full specialization has been
1100                      looked up but not instantiated.  Reassign it to the
1101                      new member specialization template.  */
1102                   spec_entry elt;
1103                   spec_entry *entry;
1104
1105                   elt.tmpl = most_general_template (tmpl);
1106                   elt.args = CLASSTYPE_TI_ARGS (inst);
1107                   elt.spec = inst;
1108
1109                   type_specializations->remove_elt (&elt);
1110
1111                   elt.tmpl = tmpl;
1112                   CLASSTYPE_TI_ARGS (inst)
1113                     = elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
1114
1115                   spec_entry **slot
1116                     = type_specializations->find_slot (&elt, INSERT);
1117                   entry = ggc_alloc<spec_entry> ();
1118                   *entry = elt;
1119                   *slot = entry;
1120                 }
1121               else
1122                 /* But if we've had an implicit instantiation, that's a
1123                    problem ([temp.expl.spec]/6).  */
1124                 error ("specialization %qT after instantiation %qT",
1125                        type, inst);
1126             }
1127
1128           /* Mark TYPE as a specialization.  And as a result, we only
1129              have one level of template argument for the innermost
1130              class template.  */
1131           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1132           DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1133           CLASSTYPE_TI_ARGS (type)
1134             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
1135         }
1136     }
1137   else if (processing_specialization)
1138     {
1139        /* Someday C++0x may allow for enum template specialization.  */
1140       if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
1141           && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
1142         pedwarn (input_location, OPT_Wpedantic, "template specialization "
1143                  "of %qD not allowed by ISO C++", type);
1144       else
1145         {
1146           error ("explicit specialization of non-template %qT", type);
1147           return error_mark_node;
1148         }
1149     }
1150
1151   return type;
1152 }
1153
1154 /* Returns nonzero if we can optimize the retrieval of specializations
1155    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
1156    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
1157
1158 static inline bool
1159 optimize_specialization_lookup_p (tree tmpl)
1160 {
1161   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
1162           && DECL_CLASS_SCOPE_P (tmpl)
1163           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
1164              parameter.  */
1165           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
1166           /* The optimized lookup depends on the fact that the
1167              template arguments for the member function template apply
1168              purely to the containing class, which is not true if the
1169              containing class is an explicit or partial
1170              specialization.  */
1171           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
1172           && !DECL_MEMBER_TEMPLATE_P (tmpl)
1173           && !DECL_CONV_FN_P (tmpl)
1174           /* It is possible to have a template that is not a member
1175              template and is not a member of a template class:
1176
1177              template <typename T>
1178              struct S { friend A::f(); };
1179
1180              Here, the friend function is a template, but the context does
1181              not have template information.  The optimized lookup relies
1182              on having ARGS be the template arguments for both the class
1183              and the function template.  */
1184           && !DECL_UNIQUE_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
1185 }
1186
1187 /* Make sure ARGS doesn't use any inappropriate typedefs; we should have
1188    gone through coerce_template_parms by now.  */
1189
1190 static void
1191 verify_unstripped_args_1 (tree inner)
1192 {
1193   for (int i = 0; i < TREE_VEC_LENGTH (inner); ++i)
1194     {
1195       tree arg = TREE_VEC_ELT (inner, i);
1196       if (TREE_CODE (arg) == TEMPLATE_DECL)
1197         /* OK */;
1198       else if (TYPE_P (arg))
1199         gcc_assert (strip_typedefs (arg, NULL) == arg);
1200       else if (ARGUMENT_PACK_P (arg))
1201         verify_unstripped_args_1 (ARGUMENT_PACK_ARGS (arg));
1202       else if (strip_typedefs (TREE_TYPE (arg), NULL) != TREE_TYPE (arg))
1203         /* Allow typedefs on the type of a non-type argument, since a
1204            parameter can have them.  */;
1205       else
1206         gcc_assert (strip_typedefs_expr (arg, NULL) == arg);
1207     }
1208 }
1209
1210 static void
1211 verify_unstripped_args (tree args)
1212 {
1213   ++processing_template_decl;
1214   if (!any_dependent_template_arguments_p (args))
1215     verify_unstripped_args_1 (INNERMOST_TEMPLATE_ARGS (args));
1216   --processing_template_decl;
1217 }
1218
1219 /* Retrieve the specialization (in the sense of [temp.spec] - a
1220    specialization is either an instantiation or an explicit
1221    specialization) of TMPL for the given template ARGS.  If there is
1222    no such specialization, return NULL_TREE.  The ARGS are a vector of
1223    arguments, or a vector of vectors of arguments, in the case of
1224    templates with more than one level of parameters.
1225
1226    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
1227    then we search for a partial specialization matching ARGS.  This
1228    parameter is ignored if TMPL is not a class template.
1229
1230    We can also look up a FIELD_DECL, if it is a lambda capture pack; the
1231    result is a NONTYPE_ARGUMENT_PACK.  */
1232
1233 static tree
1234 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1235 {
1236   if (tmpl == NULL_TREE)
1237     return NULL_TREE;
1238
1239   if (args == error_mark_node)
1240     return NULL_TREE;
1241
1242   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL
1243               || TREE_CODE (tmpl) == FIELD_DECL);
1244
1245   /* There should be as many levels of arguments as there are
1246      levels of parameters.  */
1247   gcc_assert (TMPL_ARGS_DEPTH (args)
1248               == (TREE_CODE (tmpl) == TEMPLATE_DECL
1249                   ? TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl))
1250                   : template_class_depth (DECL_CONTEXT (tmpl))));
1251
1252   if (flag_checking)
1253     verify_unstripped_args (args);
1254
1255   /* Lambda functions in templates aren't instantiated normally, but through
1256      tsubst_lambda_expr.  */
1257   if (lambda_fn_in_template_p (tmpl))
1258     return NULL_TREE;
1259
1260   if (optimize_specialization_lookup_p (tmpl))
1261     {
1262       /* The template arguments actually apply to the containing
1263          class.  Find the class specialization with those
1264          arguments.  */
1265       tree class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
1266       tree class_specialization
1267         = retrieve_specialization (class_template, args, 0);
1268       if (!class_specialization)
1269         return NULL_TREE;
1270
1271       /* Find the instance of TMPL.  */
1272       tree fns = get_class_binding (class_specialization, DECL_NAME (tmpl));
1273       for (ovl_iterator iter (fns); iter; ++iter)
1274         {
1275           tree fn = *iter;
1276           if (tree ti = get_template_info (fn))
1277             if (TI_TEMPLATE (ti) == tmpl
1278                 /* using-declarations can bring in a different
1279                    instantiation of tmpl as a member of a different
1280                    instantiation of tmpl's class.  We don't want those
1281                    here.  */
1282                 && DECL_CONTEXT (fn) == class_specialization)
1283               return fn;
1284         }
1285       return NULL_TREE;
1286     }
1287   else
1288     {
1289       spec_entry *found;
1290       spec_entry elt;
1291       spec_hash_table *specializations;
1292
1293       elt.tmpl = tmpl;
1294       elt.args = args;
1295       elt.spec = NULL_TREE;
1296
1297       if (DECL_CLASS_TEMPLATE_P (tmpl))
1298         specializations = type_specializations;
1299       else
1300         specializations = decl_specializations;
1301
1302       if (hash == 0)
1303         hash = spec_hasher::hash (&elt);
1304       found = specializations->find_with_hash (&elt, hash);
1305       if (found)
1306         return found->spec;
1307     }
1308
1309   return NULL_TREE;
1310 }
1311
1312 /* Like retrieve_specialization, but for local declarations.  */
1313
1314 tree
1315 retrieve_local_specialization (tree tmpl)
1316 {
1317   if (local_specializations == NULL)
1318     return NULL_TREE;
1319
1320   tree *slot = local_specializations->get (tmpl);
1321   return slot ? *slot : NULL_TREE;
1322 }
1323
1324 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1325
1326 int
1327 is_specialization_of (tree decl, tree tmpl)
1328 {
1329   tree t;
1330
1331   if (TREE_CODE (decl) == FUNCTION_DECL)
1332     {
1333       for (t = decl;
1334            t != NULL_TREE;
1335            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1336         if (t == tmpl)
1337           return 1;
1338     }
1339   else
1340     {
1341       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1342
1343       for (t = TREE_TYPE (decl);
1344            t != NULL_TREE;
1345            t = CLASSTYPE_USE_TEMPLATE (t)
1346              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1347         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1348           return 1;
1349     }
1350
1351   return 0;
1352 }
1353
1354 /* Returns nonzero iff DECL is a specialization of friend declaration
1355    FRIEND_DECL according to [temp.friend].  */
1356
1357 bool
1358 is_specialization_of_friend (tree decl, tree friend_decl)
1359 {
1360   bool need_template = true;
1361   int template_depth;
1362
1363   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1364               || TREE_CODE (decl) == TYPE_DECL);
1365
1366   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1367      of a template class, we want to check if DECL is a specialization
1368      if this.  */
1369   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1370       && DECL_TEMPLATE_INFO (friend_decl)
1371       && !DECL_USE_TEMPLATE (friend_decl))
1372     {
1373       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1374       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1375       need_template = false;
1376     }
1377   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1378            && !PRIMARY_TEMPLATE_P (friend_decl))
1379     need_template = false;
1380
1381   /* There is nothing to do if this is not a template friend.  */
1382   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1383     return false;
1384
1385   if (is_specialization_of (decl, friend_decl))
1386     return true;
1387
1388   /* [temp.friend/6]
1389      A member of a class template may be declared to be a friend of a
1390      non-template class.  In this case, the corresponding member of
1391      every specialization of the class template is a friend of the
1392      class granting friendship.
1393
1394      For example, given a template friend declaration
1395
1396        template <class T> friend void A<T>::f();
1397
1398      the member function below is considered a friend
1399
1400        template <> struct A<int> {
1401          void f();
1402        };
1403
1404      For this type of template friend, TEMPLATE_DEPTH below will be
1405      nonzero.  To determine if DECL is a friend of FRIEND, we first
1406      check if the enclosing class is a specialization of another.  */
1407
1408   template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1409   if (template_depth
1410       && DECL_CLASS_SCOPE_P (decl)
1411       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1412                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1413     {
1414       /* Next, we check the members themselves.  In order to handle
1415          a few tricky cases, such as when FRIEND_DECL's are
1416
1417            template <class T> friend void A<T>::g(T t);
1418            template <class T> template <T t> friend void A<T>::h();
1419
1420          and DECL's are
1421
1422            void A<int>::g(int);
1423            template <int> void A<int>::h();
1424
1425          we need to figure out ARGS, the template arguments from
1426          the context of DECL.  This is required for template substitution
1427          of `T' in the function parameter of `g' and template parameter
1428          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1429
1430       tree context = DECL_CONTEXT (decl);
1431       tree args = NULL_TREE;
1432       int current_depth = 0;
1433
1434       while (current_depth < template_depth)
1435         {
1436           if (CLASSTYPE_TEMPLATE_INFO (context))
1437             {
1438               if (current_depth == 0)
1439                 args = TYPE_TI_ARGS (context);
1440               else
1441                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1442               current_depth++;
1443             }
1444           context = TYPE_CONTEXT (context);
1445         }
1446
1447       if (TREE_CODE (decl) == FUNCTION_DECL)
1448         {
1449           bool is_template;
1450           tree friend_type;
1451           tree decl_type;
1452           tree friend_args_type;
1453           tree decl_args_type;
1454
1455           /* Make sure that both DECL and FRIEND_DECL are templates or
1456              non-templates.  */
1457           is_template = DECL_TEMPLATE_INFO (decl)
1458                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1459           if (need_template ^ is_template)
1460             return false;
1461           else if (is_template)
1462             {
1463               /* If both are templates, check template parameter list.  */
1464               tree friend_parms
1465                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1466                                          args, tf_none);
1467               if (!comp_template_parms
1468                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1469                       friend_parms))
1470                 return false;
1471
1472               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1473             }
1474           else
1475             decl_type = TREE_TYPE (decl);
1476
1477           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1478                                               tf_none, NULL_TREE);
1479           if (friend_type == error_mark_node)
1480             return false;
1481
1482           /* Check if return types match.  */
1483           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1484             return false;
1485
1486           /* Check if function parameter types match, ignoring the
1487              `this' parameter.  */
1488           friend_args_type = TYPE_ARG_TYPES (friend_type);
1489           decl_args_type = TYPE_ARG_TYPES (decl_type);
1490           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1491             friend_args_type = TREE_CHAIN (friend_args_type);
1492           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1493             decl_args_type = TREE_CHAIN (decl_args_type);
1494
1495           return compparms (decl_args_type, friend_args_type);
1496         }
1497       else
1498         {
1499           /* DECL is a TYPE_DECL */
1500           bool is_template;
1501           tree decl_type = TREE_TYPE (decl);
1502
1503           /* Make sure that both DECL and FRIEND_DECL are templates or
1504              non-templates.  */
1505           is_template
1506             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1507               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1508
1509           if (need_template ^ is_template)
1510             return false;
1511           else if (is_template)
1512             {
1513               tree friend_parms;
1514               /* If both are templates, check the name of the two
1515                  TEMPLATE_DECL's first because is_friend didn't.  */
1516               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1517                   != DECL_NAME (friend_decl))
1518                 return false;
1519
1520               /* Now check template parameter list.  */
1521               friend_parms
1522                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1523                                          args, tf_none);
1524               return comp_template_parms
1525                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1526                  friend_parms);
1527             }
1528           else
1529             return (DECL_NAME (decl)
1530                     == DECL_NAME (friend_decl));
1531         }
1532     }
1533   return false;
1534 }
1535
1536 /* Register the specialization SPEC as a specialization of TMPL with
1537    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1538    is actually just a friend declaration.  ATTRLIST is the list of
1539    attributes that the specialization is declared with or NULL when
1540    it isn't.  Returns SPEC, or an equivalent prior declaration, if
1541    available.
1542
1543    We also store instantiations of field packs in the hash table, even
1544    though they are not themselves templates, to make lookup easier.  */
1545
1546 static tree
1547 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1548                          hashval_t hash)
1549 {
1550   tree fn;
1551   spec_entry **slot = NULL;
1552   spec_entry elt;
1553
1554   gcc_assert ((TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec))
1555               || (TREE_CODE (tmpl) == FIELD_DECL
1556                   && TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK));
1557
1558   if (TREE_CODE (spec) == FUNCTION_DECL
1559       && uses_template_parms (DECL_TI_ARGS (spec)))
1560     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1561        register it; we want the corresponding TEMPLATE_DECL instead.
1562        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1563        the more obvious `uses_template_parms (spec)' to avoid problems
1564        with default function arguments.  In particular, given
1565        something like this:
1566
1567           template <class T> void f(T t1, T t = T())
1568
1569        the default argument expression is not substituted for in an
1570        instantiation unless and until it is actually needed.  */
1571     return spec;
1572
1573   if (optimize_specialization_lookup_p (tmpl))
1574     /* We don't put these specializations in the hash table, but we might
1575        want to give an error about a mismatch.  */
1576     fn = retrieve_specialization (tmpl, args, 0);
1577   else
1578     {
1579       elt.tmpl = tmpl;
1580       elt.args = args;
1581       elt.spec = spec;
1582
1583       if (hash == 0)
1584         hash = spec_hasher::hash (&elt);
1585
1586       slot = decl_specializations->find_slot_with_hash (&elt, hash, INSERT);
1587       if (*slot)
1588         fn = (*slot)->spec;
1589       else
1590         fn = NULL_TREE;
1591     }
1592
1593   /* We can sometimes try to re-register a specialization that we've
1594      already got.  In particular, regenerate_decl_from_template calls
1595      duplicate_decls which will update the specialization list.  But,
1596      we'll still get called again here anyhow.  It's more convenient
1597      to simply allow this than to try to prevent it.  */
1598   if (fn == spec)
1599     return spec;
1600   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1601     {
1602       if (DECL_TEMPLATE_INSTANTIATION (fn))
1603         {
1604           if (DECL_ODR_USED (fn)
1605               || DECL_EXPLICIT_INSTANTIATION (fn))
1606             {
1607               error ("specialization of %qD after instantiation",
1608                      fn);
1609               return error_mark_node;
1610             }
1611           else
1612             {
1613               tree clone;
1614               /* This situation should occur only if the first
1615                  specialization is an implicit instantiation, the
1616                  second is an explicit specialization, and the
1617                  implicit instantiation has not yet been used.  That
1618                  situation can occur if we have implicitly
1619                  instantiated a member function and then specialized
1620                  it later.
1621
1622                  We can also wind up here if a friend declaration that
1623                  looked like an instantiation turns out to be a
1624                  specialization:
1625
1626                    template <class T> void foo(T);
1627                    class S { friend void foo<>(int) };
1628                    template <> void foo(int);
1629
1630                  We transform the existing DECL in place so that any
1631                  pointers to it become pointers to the updated
1632                  declaration.
1633
1634                  If there was a definition for the template, but not
1635                  for the specialization, we want this to look as if
1636                  there were no definition, and vice versa.  */
1637               DECL_INITIAL (fn) = NULL_TREE;
1638               duplicate_decls (spec, fn, /*hiding=*/is_friend);
1639               /* The call to duplicate_decls will have applied
1640                  [temp.expl.spec]:
1641
1642                    An explicit specialization of a function template
1643                    is inline only if it is explicitly declared to be,
1644                    and independently of whether its function template
1645                    is.
1646
1647                 to the primary function; now copy the inline bits to
1648                 the various clones.  */
1649               FOR_EACH_CLONE (clone, fn)
1650                 {
1651                   DECL_DECLARED_INLINE_P (clone)
1652                     = DECL_DECLARED_INLINE_P (fn);
1653                   DECL_SOURCE_LOCATION (clone)
1654                     = DECL_SOURCE_LOCATION (fn);
1655                   DECL_DELETED_FN (clone)
1656                     = DECL_DELETED_FN (fn);
1657                 }
1658               check_specialization_namespace (tmpl);
1659
1660               return fn;
1661             }
1662         }
1663       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1664         {
1665           tree dd = duplicate_decls (spec, fn, /*hiding=*/is_friend);
1666           if (dd == error_mark_node)
1667             /* We've already complained in duplicate_decls.  */
1668             return error_mark_node;
1669
1670           if (dd == NULL_TREE && DECL_INITIAL (spec))
1671             /* Dup decl failed, but this is a new definition. Set the
1672                line number so any errors match this new
1673                definition.  */
1674             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1675
1676           return fn;
1677         }
1678     }
1679   else if (fn)
1680     return duplicate_decls (spec, fn, /*hiding=*/is_friend);
1681
1682   /* A specialization must be declared in the same namespace as the
1683      template it is specializing.  */
1684   if (DECL_P (spec) && DECL_TEMPLATE_SPECIALIZATION (spec)
1685       && !check_specialization_namespace (tmpl))
1686     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1687
1688   if (slot != NULL /* !optimize_specialization_lookup_p (tmpl) */)
1689     {
1690       spec_entry *entry = ggc_alloc<spec_entry> ();
1691       gcc_assert (tmpl && args && spec);
1692       *entry = elt;
1693       *slot = entry;
1694       if ((TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1695            && PRIMARY_TEMPLATE_P (tmpl)
1696            && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1697           || variable_template_p (tmpl))
1698         /* If TMPL is a forward declaration of a template function, keep a list
1699            of all specializations in case we need to reassign them to a friend
1700            template later in tsubst_friend_function.
1701
1702            Also keep a list of all variable template instantiations so that
1703            process_partial_specialization can check whether a later partial
1704            specialization would have used it.  */
1705         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1706           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1707     }
1708
1709   return spec;
1710 }
1711
1712 /* Restricts tree and type comparisons.  */
1713 int comparing_specializations;
1714 int comparing_dependent_aliases;
1715
1716 /* Returns true iff two spec_entry nodes are equivalent.  */
1717
1718 bool
1719 spec_hasher::equal (spec_entry *e1, spec_entry *e2)
1720 {
1721   int equal;
1722
1723   ++comparing_specializations;
1724   ++comparing_dependent_aliases;
1725   ++processing_template_decl;
1726   equal = (e1->tmpl == e2->tmpl
1727            && comp_template_args (e1->args, e2->args));
1728   if (equal && flag_concepts
1729       /* tmpl could be a FIELD_DECL for a capture pack.  */
1730       && TREE_CODE (e1->tmpl) == TEMPLATE_DECL
1731       && VAR_P (DECL_TEMPLATE_RESULT (e1->tmpl))
1732       && uses_template_parms (e1->args))
1733     {
1734       /* Partial specializations of a variable template can be distinguished by
1735          constraints.  */
1736       tree c1 = e1->spec ? get_constraints (e1->spec) : NULL_TREE;
1737       tree c2 = e2->spec ? get_constraints (e2->spec) : NULL_TREE;
1738       equal = equivalent_constraints (c1, c2);
1739     }
1740   --processing_template_decl;
1741   --comparing_dependent_aliases;
1742   --comparing_specializations;
1743
1744   return equal;
1745 }
1746
1747 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1748
1749 static hashval_t
1750 hash_tmpl_and_args (tree tmpl, tree args)
1751 {
1752   hashval_t val = iterative_hash_object (DECL_UID (tmpl), 0);
1753   return iterative_hash_template_arg (args, val);
1754 }
1755
1756 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1757    ignoring SPEC.  */
1758
1759 hashval_t
1760 spec_hasher::hash (spec_entry *e)
1761 {
1762   return hash_tmpl_and_args (e->tmpl, e->args);
1763 }
1764
1765 /* Recursively calculate a hash value for a template argument ARG, for use
1766    in the hash tables of template specializations.   We must be
1767    careful to (at least) skip the same entities template_args_equal
1768    does.  */
1769
1770 hashval_t
1771 iterative_hash_template_arg (tree arg, hashval_t val)
1772 {
1773   if (arg == NULL_TREE)
1774     return iterative_hash_object (arg, val);
1775
1776   if (!TYPE_P (arg))
1777     /* Strip nop-like things, but not the same as STRIP_NOPS.  */
1778     while (CONVERT_EXPR_P (arg)
1779            || TREE_CODE (arg) == NON_LVALUE_EXPR
1780            || class_nttp_const_wrapper_p (arg))
1781       arg = TREE_OPERAND (arg, 0);
1782
1783   enum tree_code code = TREE_CODE (arg);
1784
1785   val = iterative_hash_object (code, val);
1786
1787   switch (code)
1788     {
1789     case ARGUMENT_PACK_SELECT:
1790       gcc_unreachable ();
1791
1792     case ERROR_MARK:
1793       return val;
1794
1795     case IDENTIFIER_NODE:
1796       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1797
1798     case TREE_VEC:
1799       for (int i = 0, len = TREE_VEC_LENGTH (arg); i < len; ++i)
1800         val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1801       return val;
1802
1803     case TYPE_PACK_EXPANSION:
1804     case EXPR_PACK_EXPANSION:
1805       val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1806       return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1807
1808     case TYPE_ARGUMENT_PACK:
1809     case NONTYPE_ARGUMENT_PACK:
1810       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1811
1812     case TREE_LIST:
1813       for (; arg; arg = TREE_CHAIN (arg))
1814         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1815       return val;
1816
1817     case OVERLOAD:
1818       for (lkp_iterator iter (arg); iter; ++iter)
1819         val = iterative_hash_template_arg (*iter, val);
1820       return val;
1821
1822     case CONSTRUCTOR:
1823       {
1824         tree field, value;
1825         unsigned i;
1826         iterative_hash_template_arg (TREE_TYPE (arg), val);
1827         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1828           {
1829             val = iterative_hash_template_arg (field, val);
1830             val = iterative_hash_template_arg (value, val);
1831           }
1832         return val;
1833       }
1834
1835     case PARM_DECL:
1836       if (!DECL_ARTIFICIAL (arg))
1837         {
1838           val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1839           val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1840         }
1841       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1842
1843     case TARGET_EXPR:
1844       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1845
1846     case PTRMEM_CST:
1847       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1848       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1849
1850     case TEMPLATE_PARM_INDEX:
1851       val = iterative_hash_template_arg
1852         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1853       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1854       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1855
1856     case TRAIT_EXPR:
1857       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1858       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1859       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1860
1861     case BASELINK:
1862       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1863                                          val);
1864       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1865                                           val);
1866
1867     case MODOP_EXPR:
1868       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1869       code = TREE_CODE (TREE_OPERAND (arg, 1));
1870       val = iterative_hash_object (code, val);
1871       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1872
1873     case LAMBDA_EXPR:
1874       /* [temp.over.link] Two lambda-expressions are never considered
1875          equivalent.
1876
1877          So just hash the closure type.  */
1878       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1879
1880     case CAST_EXPR:
1881     case IMPLICIT_CONV_EXPR:
1882     case STATIC_CAST_EXPR:
1883     case REINTERPRET_CAST_EXPR:
1884     case CONST_CAST_EXPR:
1885     case DYNAMIC_CAST_EXPR:
1886     case NEW_EXPR:
1887       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1888       /* Now hash operands as usual.  */
1889       break;
1890
1891     case CALL_EXPR:
1892       {
1893         tree fn = CALL_EXPR_FN (arg);
1894         if (tree name = dependent_name (fn))
1895           {
1896             if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
1897               val = iterative_hash_template_arg (TREE_OPERAND (fn, 1), val);
1898             fn = name;
1899           }
1900         val = iterative_hash_template_arg (fn, val);
1901         call_expr_arg_iterator ai;
1902         for (tree x = first_call_expr_arg (arg, &ai); x;
1903              x = next_call_expr_arg (&ai))
1904           val = iterative_hash_template_arg (x, val);
1905         return val;
1906       }
1907
1908     default:
1909       break;
1910     }
1911
1912   char tclass = TREE_CODE_CLASS (code);
1913   switch (tclass)
1914     {
1915     case tcc_type:
1916       if (tree ats = alias_template_specialization_p (arg, nt_transparent))
1917         {
1918           // We want an alias specialization that survived strip_typedefs
1919           // to hash differently from its TYPE_CANONICAL, to avoid hash
1920           // collisions that compare as different in template_args_equal.
1921           // These could be dependent specializations that strip_typedefs
1922           // left alone, or untouched specializations because
1923           // coerce_template_parms returns the unconverted template
1924           // arguments if it sees incomplete argument packs.
1925           tree ti = TYPE_ALIAS_TEMPLATE_INFO (ats);
1926           return hash_tmpl_and_args (TI_TEMPLATE (ti), TI_ARGS (ti));
1927         }
1928
1929       switch (TREE_CODE (arg))
1930         {
1931         case TEMPLATE_TEMPLATE_PARM:
1932           {
1933             tree tpi = TEMPLATE_TYPE_PARM_INDEX (arg);
1934
1935             /* Do not recurse with TPI directly, as that is unbounded
1936                recursion.  */
1937             val = iterative_hash_object (TEMPLATE_PARM_LEVEL (tpi), val);
1938             val = iterative_hash_object (TEMPLATE_PARM_IDX (tpi), val);
1939           }
1940           break;
1941
1942         case  DECLTYPE_TYPE:
1943           val = iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1944           break;
1945
1946         default:
1947           if (tree canonical = TYPE_CANONICAL (arg))
1948             val = iterative_hash_object (TYPE_HASH (canonical), val);
1949           break;
1950         }
1951
1952       return val;
1953
1954     case tcc_declaration:
1955     case tcc_constant:
1956       return iterative_hash_expr (arg, val);
1957
1958     default:
1959       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1960       for (int i = 0, n = cp_tree_operand_length (arg); i < n; ++i)
1961         val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1962       return val;
1963     }
1964
1965   gcc_unreachable ();
1966   return 0;
1967 }
1968
1969 /* Unregister the specialization SPEC as a specialization of TMPL.
1970    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1971    if the SPEC was listed as a specialization of TMPL.
1972
1973    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1974
1975 bool
1976 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1977 {
1978   spec_entry *entry;
1979   spec_entry elt;
1980
1981   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1982   elt.args = TI_ARGS (tinfo);
1983   elt.spec = NULL_TREE;
1984
1985   entry = decl_specializations->find (&elt);
1986   if (entry != NULL)
1987     {
1988       gcc_assert (entry->spec == spec || entry->spec == new_spec);
1989       gcc_assert (new_spec != NULL_TREE);
1990       entry->spec = new_spec;
1991       return 1;
1992     }
1993
1994   return 0;
1995 }
1996
1997 /* Like register_specialization, but for local declarations.  We are
1998    registering SPEC, an instantiation of TMPL.  */
1999
2000 void
2001 register_local_specialization (tree spec, tree tmpl)
2002 {
2003   gcc_assert (tmpl != spec);
2004   local_specializations->put (tmpl, spec);
2005 }
2006
2007 /* TYPE is a class type.  Returns true if TYPE is an explicitly
2008    specialized class.  */
2009
2010 bool
2011 explicit_class_specialization_p (tree type)
2012 {
2013   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
2014     return false;
2015   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
2016 }
2017
2018 /* Print the list of functions at FNS, going through all the overloads
2019    for each element of the list.  Alternatively, FNS cannot be a
2020    TREE_LIST, in which case it will be printed together with all the
2021    overloads.
2022
2023    MORE and *STR should respectively be FALSE and NULL when the function
2024    is called from the outside.  They are used internally on recursive
2025    calls.  print_candidates manages the two parameters and leaves NULL
2026    in *STR when it ends.  */
2027
2028 static void
2029 print_candidates_1 (tree fns, char **str, bool more = false)
2030 {
2031   if (TREE_CODE (fns) == TREE_LIST)
2032     for (; fns; fns = TREE_CHAIN (fns))
2033       print_candidates_1 (TREE_VALUE (fns), str, more || TREE_CHAIN (fns));
2034   else
2035     for (lkp_iterator iter (fns); iter;)
2036       {
2037         tree cand = *iter;
2038         ++iter;
2039
2040         const char *pfx = *str;
2041         if (!pfx)
2042           {
2043             if (more || iter)
2044               pfx = _("candidates are:");
2045             else
2046               pfx = _("candidate is:");
2047             *str = get_spaces (pfx);
2048           }
2049         inform (DECL_SOURCE_LOCATION (cand), "%s %#qD", pfx, cand);
2050       }
2051 }
2052
2053 /* Print the list of candidate FNS in an error message.  FNS can also
2054    be a TREE_LIST of non-functions in the case of an ambiguous lookup.  */
2055
2056 void
2057 print_candidates (tree fns)
2058 {
2059   char *str = NULL;
2060   print_candidates_1 (fns, &str);
2061   free (str);
2062 }
2063
2064 /* Get a (possibly) constrained template declaration for the
2065    purpose of ordering candidates.  */
2066 static tree
2067 get_template_for_ordering (tree list)
2068 {
2069   gcc_assert (TREE_CODE (list) == TREE_LIST);
2070   tree f = TREE_VALUE (list);
2071   if (tree ti = DECL_TEMPLATE_INFO (f))
2072     return TI_TEMPLATE (ti);
2073   return f;
2074 }
2075
2076 /* Among candidates having the same signature, return the
2077    most constrained or NULL_TREE if there is no best candidate.
2078    If the signatures of candidates vary (e.g., template
2079    specialization vs. member function), then there can be no
2080    most constrained.
2081
2082    Note that we don't compare constraints on the functions
2083    themselves, but rather those of their templates. */
2084 static tree
2085 most_constrained_function (tree candidates)
2086 {
2087   // Try to find the best candidate in a first pass.
2088   tree champ = candidates;
2089   for (tree c = TREE_CHAIN (champ); c; c = TREE_CHAIN (c))
2090     {
2091       int winner = more_constrained (get_template_for_ordering (champ),
2092                                      get_template_for_ordering (c));
2093       if (winner == -1)
2094         champ = c; // The candidate is more constrained
2095       else if (winner == 0)
2096         return NULL_TREE; // Neither is more constrained
2097     }
2098
2099   // Verify that the champ is better than previous candidates.
2100   for (tree c = candidates; c != champ; c = TREE_CHAIN (c)) {
2101     if (!more_constrained (get_template_for_ordering (champ),
2102                            get_template_for_ordering (c)))
2103       return NULL_TREE;
2104   }
2105
2106   return champ;
2107 }
2108
2109
2110 /* Returns the template (one of the functions given by TEMPLATE_ID)
2111    which can be specialized to match the indicated DECL with the
2112    explicit template args given in TEMPLATE_ID.  The DECL may be
2113    NULL_TREE if none is available.  In that case, the functions in
2114    TEMPLATE_ID are non-members.
2115
2116    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
2117    specialization of a member template.
2118
2119    The TEMPLATE_COUNT is the number of references to qualifying
2120    template classes that appeared in the name of the function. See
2121    check_explicit_specialization for a more accurate description.
2122
2123    TSK indicates what kind of template declaration (if any) is being
2124    declared.  TSK_TEMPLATE indicates that the declaration given by
2125    DECL, though a FUNCTION_DECL, has template parameters, and is
2126    therefore a template function.
2127
2128    The template args (those explicitly specified and those deduced)
2129    are output in a newly created vector *TARGS_OUT.
2130
2131    If it is impossible to determine the result, an error message is
2132    issued.  The error_mark_node is returned to indicate failure.  */
2133
2134 static tree
2135 determine_specialization (tree template_id,
2136                           tree decl,
2137                           tree* targs_out,
2138                           int need_member_template,
2139                           int template_count,
2140                           tmpl_spec_kind tsk)
2141 {
2142   tree fns;
2143   tree targs;
2144   tree explicit_targs;
2145   tree candidates = NULL_TREE;
2146
2147   /* A TREE_LIST of templates of which DECL may be a specialization.
2148      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
2149      corresponding TREE_PURPOSE is the set of template arguments that,
2150      when used to instantiate the template, would produce a function
2151      with the signature of DECL.  */
2152   tree templates = NULL_TREE;
2153   int header_count;
2154   cp_binding_level *b;
2155
2156   *targs_out = NULL_TREE;
2157
2158   if (template_id == error_mark_node || decl == error_mark_node)
2159     return error_mark_node;
2160
2161   /* We shouldn't be specializing a member template of an
2162      unspecialized class template; we already gave an error in
2163      check_specialization_scope, now avoid crashing.  */
2164   if (!VAR_P (decl)
2165       && template_count && DECL_CLASS_SCOPE_P (decl)
2166       && template_class_depth (DECL_CONTEXT (decl)) > 0)
2167     {
2168       gcc_assert (errorcount);
2169       return error_mark_node;
2170     }
2171
2172   fns = TREE_OPERAND (template_id, 0);
2173   explicit_targs = TREE_OPERAND (template_id, 1);
2174
2175   if (fns == error_mark_node)
2176     return error_mark_node;
2177
2178   /* Check for baselinks.  */
2179   if (BASELINK_P (fns))
2180     fns = BASELINK_FUNCTIONS (fns);
2181
2182   if (TREE_CODE (decl) == FUNCTION_DECL && !is_overloaded_fn (fns))
2183     {
2184       error_at (DECL_SOURCE_LOCATION (decl),
2185                 "%qD is not a function template", fns);
2186       return error_mark_node;
2187     }
2188   else if (VAR_P (decl) && !variable_template_p (fns))
2189     {
2190       error ("%qD is not a variable template", fns);
2191       return error_mark_node;
2192     }
2193
2194   /* Count the number of template headers specified for this
2195      specialization.  */
2196   header_count = 0;
2197   for (b = current_binding_level;
2198        b->kind == sk_template_parms;
2199        b = b->level_chain)
2200     ++header_count;
2201
2202   tree orig_fns = fns;
2203   bool header_mismatch = false;
2204
2205   if (variable_template_p (fns))
2206     {
2207       tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (fns));
2208       targs = coerce_template_parms (parms, explicit_targs, fns,
2209                                      tf_warning_or_error,
2210                                      /*req_all*/true, /*use_defarg*/true);
2211       if (targs != error_mark_node)
2212         templates = tree_cons (targs, fns, templates);
2213     }
2214   else for (lkp_iterator iter (fns); iter; ++iter)
2215     {
2216       tree fn = *iter;
2217
2218       if (TREE_CODE (fn) == TEMPLATE_DECL)
2219         {
2220           tree decl_arg_types;
2221           tree fn_arg_types;
2222           tree insttype;
2223
2224           /* In case of explicit specialization, we need to check if
2225              the number of template headers appearing in the specialization
2226              is correct. This is usually done in check_explicit_specialization,
2227              but the check done there cannot be exhaustive when specializing
2228              member functions. Consider the following code:
2229
2230              template <> void A<int>::f(int);
2231              template <> template <> void A<int>::f(int);
2232
2233              Assuming that A<int> is not itself an explicit specialization
2234              already, the first line specializes "f" which is a non-template
2235              member function, whilst the second line specializes "f" which
2236              is a template member function. So both lines are syntactically
2237              correct, and check_explicit_specialization does not reject
2238              them.
2239
2240              Here, we can do better, as we are matching the specialization
2241              against the declarations. We count the number of template
2242              headers, and we check if they match TEMPLATE_COUNT + 1
2243              (TEMPLATE_COUNT is the number of qualifying template classes,
2244              plus there must be another header for the member template
2245              itself).
2246
2247              Notice that if header_count is zero, this is not a
2248              specialization but rather a template instantiation, so there
2249              is no check we can perform here.  */
2250           if (header_count && header_count != template_count + 1)
2251             {
2252               header_mismatch = true;
2253               continue;
2254             }
2255
2256           /* Check that the number of template arguments at the
2257              innermost level for DECL is the same as for FN.  */
2258           if (current_binding_level->kind == sk_template_parms
2259               && !current_binding_level->explicit_spec_p
2260               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
2261                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
2262                                       (current_template_parms))))
2263             continue;
2264
2265           /* DECL might be a specialization of FN.  */
2266           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2267           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
2268
2269           /* For a non-static member function, we need to make sure
2270              that the const qualification is the same.  Since
2271              get_bindings does not try to merge the "this" parameter,
2272              we must do the comparison explicitly.  */
2273           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
2274             {
2275               if (!same_type_p (TREE_VALUE (fn_arg_types),
2276                                 TREE_VALUE (decl_arg_types)))
2277                 continue;
2278
2279               /* And the ref-qualification.  */
2280               if (type_memfn_rqual (TREE_TYPE (decl))
2281                   != type_memfn_rqual (TREE_TYPE (fn)))
2282                 continue;
2283             }
2284
2285           /* Skip the "this" parameter and, for constructors of
2286              classes with virtual bases, the VTT parameter.  A
2287              full specialization of a constructor will have a VTT
2288              parameter, but a template never will.  */
2289           decl_arg_types
2290             = skip_artificial_parms_for (decl, decl_arg_types);
2291           fn_arg_types
2292             = skip_artificial_parms_for (fn, fn_arg_types);
2293
2294           /* Function templates cannot be specializations; there are
2295              no partial specializations of functions.  Therefore, if
2296              the type of DECL does not match FN, there is no
2297              match.
2298
2299              Note that it should never be the case that we have both
2300              candidates added here, and for regular member functions
2301              below. */
2302           if (tsk == tsk_template)
2303             {
2304               if (!comp_template_parms (DECL_TEMPLATE_PARMS (fn),
2305                                         current_template_parms))
2306                 continue;
2307               if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2308                                 TREE_TYPE (TREE_TYPE (fn))))
2309                 continue;
2310               if (!compparms (fn_arg_types, decl_arg_types))
2311                 continue;
2312
2313               tree freq = get_trailing_function_requirements (fn);
2314               tree dreq = get_trailing_function_requirements (decl);
2315               if (!freq != !dreq)
2316                 continue;
2317               if (freq)
2318                 {
2319                   tree fargs = DECL_TI_ARGS (fn);
2320                   tsubst_flags_t complain = tf_none;
2321                   freq = tsubst_constraint (freq, fargs, complain, fn);
2322                   if (!cp_tree_equal (freq, dreq))
2323                     continue;
2324                 }
2325
2326               candidates = tree_cons (NULL_TREE, fn, candidates);
2327               continue;
2328             }
2329
2330           /* See whether this function might be a specialization of this
2331              template.  Suppress access control because we might be trying
2332              to make this specialization a friend, and we have already done
2333              access control for the declaration of the specialization.  */
2334           push_deferring_access_checks (dk_no_check);
2335           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
2336           pop_deferring_access_checks ();
2337
2338           if (!targs)
2339             /* We cannot deduce template arguments that when used to
2340                specialize TMPL will produce DECL.  */
2341             continue;
2342
2343           if (uses_template_parms (targs))
2344             /* We deduced something involving 'auto', which isn't a valid
2345                template argument.  */
2346             continue;
2347
2348           /* Remove, from the set of candidates, all those functions
2349              whose constraints are not satisfied. */
2350           if (flag_concepts && !constraints_satisfied_p (fn, targs))
2351             continue;
2352
2353           // Then, try to form the new function type.
2354           insttype = tsubst (TREE_TYPE (fn), targs, tf_fndecl_type, NULL_TREE);
2355           if (insttype == error_mark_node)
2356             continue;
2357           fn_arg_types
2358             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (insttype));
2359           if (!compparms (fn_arg_types, decl_arg_types))
2360             continue;
2361
2362           /* Save this template, and the arguments deduced.  */
2363           templates = tree_cons (targs, fn, templates);
2364         }
2365       else if (need_member_template)
2366         /* FN is an ordinary member function, and we need a
2367            specialization of a member template.  */
2368         ;
2369       else if (TREE_CODE (fn) != FUNCTION_DECL)
2370         /* We can get IDENTIFIER_NODEs here in certain erroneous
2371            cases.  */
2372         ;
2373       else if (!DECL_FUNCTION_MEMBER_P (fn))
2374         /* This is just an ordinary non-member function.  Nothing can
2375            be a specialization of that.  */
2376         ;
2377       else if (DECL_ARTIFICIAL (fn))
2378         /* Cannot specialize functions that are created implicitly.  */
2379         ;
2380       else
2381         {
2382           tree decl_arg_types;
2383
2384           /* This is an ordinary member function.  However, since
2385              we're here, we can assume its enclosing class is a
2386              template class.  For example,
2387
2388                template <typename T> struct S { void f(); };
2389                template <> void S<int>::f() {}
2390
2391              Here, S<int>::f is a non-template, but S<int> is a
2392              template class.  If FN has the same type as DECL, we
2393              might be in business.  */
2394
2395           if (!DECL_TEMPLATE_INFO (fn))
2396             /* Its enclosing class is an explicit specialization
2397                of a template class.  This is not a candidate.  */
2398             continue;
2399
2400           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2401                             TREE_TYPE (TREE_TYPE (fn))))
2402             /* The return types differ.  */
2403             continue;
2404
2405           /* Adjust the type of DECL in case FN is a static member.  */
2406           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2407           if (DECL_STATIC_FUNCTION_P (fn)
2408               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2409             decl_arg_types = TREE_CHAIN (decl_arg_types);
2410
2411           if (!compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2412                          decl_arg_types))
2413             continue;
2414
2415           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2416               && (type_memfn_rqual (TREE_TYPE (decl))
2417                   != type_memfn_rqual (TREE_TYPE (fn))))
2418             continue;
2419
2420           // If the deduced arguments do not satisfy the constraints,
2421           // this is not a candidate.
2422           if (flag_concepts && !constraints_satisfied_p (fn))
2423             continue;
2424
2425           // Add the candidate.
2426           candidates = tree_cons (NULL_TREE, fn, candidates);
2427         }
2428     }
2429
2430   if (templates && TREE_CHAIN (templates))
2431     {
2432       /* We have:
2433
2434            [temp.expl.spec]
2435
2436            It is possible for a specialization with a given function
2437            signature to be instantiated from more than one function
2438            template.  In such cases, explicit specification of the
2439            template arguments must be used to uniquely identify the
2440            function template specialization being specialized.
2441
2442          Note that here, there's no suggestion that we're supposed to
2443          determine which of the candidate templates is most
2444          specialized.  However, we, also have:
2445
2446            [temp.func.order]
2447
2448            Partial ordering of overloaded function template
2449            declarations is used in the following contexts to select
2450            the function template to which a function template
2451            specialization refers:
2452
2453            -- when an explicit specialization refers to a function
2454               template.
2455
2456          So, we do use the partial ordering rules, at least for now.
2457          This extension can only serve to make invalid programs valid,
2458          so it's safe.  And, there is strong anecdotal evidence that
2459          the committee intended the partial ordering rules to apply;
2460          the EDG front end has that behavior, and John Spicer claims
2461          that the committee simply forgot to delete the wording in
2462          [temp.expl.spec].  */
2463       tree tmpl = most_specialized_instantiation (templates);
2464       if (tmpl != error_mark_node)
2465         {
2466           templates = tmpl;
2467           TREE_CHAIN (templates) = NULL_TREE;
2468         }
2469     }
2470
2471   // Concepts allows multiple declarations of member functions
2472   // with the same signature. Like above, we need to rely on
2473   // on the partial ordering of those candidates to determine which
2474   // is the best.
2475   if (flag_concepts && candidates && TREE_CHAIN (candidates))
2476     {
2477       if (tree cand = most_constrained_function (candidates))
2478         {
2479           candidates = cand;
2480           TREE_CHAIN (cand) = NULL_TREE;
2481         }
2482     }
2483
2484   if (templates == NULL_TREE && candidates == NULL_TREE)
2485     {
2486       error ("template-id %qD for %q+D does not match any template "
2487              "declaration", template_id, decl);
2488       if (header_mismatch)
2489         inform (DECL_SOURCE_LOCATION (decl),
2490                 "saw %d %<template<>%>, need %d for "
2491                 "specializing a member function template",
2492                 header_count, template_count + 1);
2493       print_candidates (orig_fns);
2494       return error_mark_node;
2495     }
2496   else if ((templates && TREE_CHAIN (templates))
2497            || (candidates && TREE_CHAIN (candidates))
2498            || (templates && candidates))
2499     {
2500       error ("ambiguous template specialization %qD for %q+D",
2501              template_id, decl);
2502       candidates = chainon (candidates, templates);
2503       print_candidates (candidates);
2504       return error_mark_node;
2505     }
2506
2507   /* We have one, and exactly one, match.  */
2508   if (candidates)
2509     {
2510       tree fn = TREE_VALUE (candidates);
2511       *targs_out = copy_node (DECL_TI_ARGS (fn));
2512
2513       /* Propagate the candidate's constraints to the declaration.  */
2514       if (tsk != tsk_template)
2515         set_constraints (decl, get_constraints (fn));
2516
2517       /* DECL is a re-declaration or partial instantiation of a template
2518          function.  */
2519       if (TREE_CODE (fn) == TEMPLATE_DECL)
2520         return fn;
2521       /* It was a specialization of an ordinary member function in a
2522          template class.  */
2523       return DECL_TI_TEMPLATE (fn);
2524     }
2525
2526   /* It was a specialization of a template.  */
2527   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2528   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2529     {
2530       *targs_out = copy_node (targs);
2531       SET_TMPL_ARGS_LEVEL (*targs_out,
2532                            TMPL_ARGS_DEPTH (*targs_out),
2533                            TREE_PURPOSE (templates));
2534     }
2535   else
2536     *targs_out = TREE_PURPOSE (templates);
2537   return TREE_VALUE (templates);
2538 }
2539
2540 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2541    but with the default argument values filled in from those in the
2542    TMPL_TYPES.  */
2543
2544 static tree
2545 copy_default_args_to_explicit_spec_1 (tree spec_types,
2546                                       tree tmpl_types)
2547 {
2548   tree new_spec_types;
2549
2550   if (!spec_types)
2551     return NULL_TREE;
2552
2553   if (spec_types == void_list_node)
2554     return void_list_node;
2555
2556   /* Substitute into the rest of the list.  */
2557   new_spec_types =
2558     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2559                                           TREE_CHAIN (tmpl_types));
2560
2561   /* Add the default argument for this parameter.  */
2562   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2563                          TREE_VALUE (spec_types),
2564                          new_spec_types);
2565 }
2566
2567 /* DECL is an explicit specialization.  Replicate default arguments
2568    from the template it specializes.  (That way, code like:
2569
2570      template <class T> void f(T = 3);
2571      template <> void f(double);
2572      void g () { f (); }
2573
2574    works, as required.)  An alternative approach would be to look up
2575    the correct default arguments at the call-site, but this approach
2576    is consistent with how implicit instantiations are handled.  */
2577
2578 static void
2579 copy_default_args_to_explicit_spec (tree decl)
2580 {
2581   tree tmpl;
2582   tree spec_types;
2583   tree tmpl_types;
2584   tree new_spec_types;
2585   tree old_type;
2586   tree new_type;
2587   tree t;
2588   tree object_type = NULL_TREE;
2589   tree in_charge = NULL_TREE;
2590   tree vtt = NULL_TREE;
2591
2592   /* See if there's anything we need to do.  */
2593   tmpl = DECL_TI_TEMPLATE (decl);
2594   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2595   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2596     if (TREE_PURPOSE (t))
2597       break;
2598   if (!t)
2599     return;
2600
2601   old_type = TREE_TYPE (decl);
2602   spec_types = TYPE_ARG_TYPES (old_type);
2603
2604   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2605     {
2606       /* Remove the this pointer, but remember the object's type for
2607          CV quals.  */
2608       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2609       spec_types = TREE_CHAIN (spec_types);
2610       tmpl_types = TREE_CHAIN (tmpl_types);
2611
2612       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2613         {
2614           /* DECL may contain more parameters than TMPL due to the extra
2615              in-charge parameter in constructors and destructors.  */
2616           in_charge = spec_types;
2617           spec_types = TREE_CHAIN (spec_types);
2618         }
2619       if (DECL_HAS_VTT_PARM_P (decl))
2620         {
2621           vtt = spec_types;
2622           spec_types = TREE_CHAIN (spec_types);
2623         }
2624     }
2625
2626   /* Compute the merged default arguments.  */
2627   new_spec_types =
2628     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2629
2630   /* Compute the new FUNCTION_TYPE.  */
2631   if (object_type)
2632     {
2633       if (vtt)
2634         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2635                                          TREE_VALUE (vtt),
2636                                          new_spec_types);
2637
2638       if (in_charge)
2639         /* Put the in-charge parameter back.  */
2640         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2641                                          TREE_VALUE (in_charge),
2642                                          new_spec_types);
2643
2644       new_type = build_method_type_directly (object_type,
2645                                              TREE_TYPE (old_type),
2646                                              new_spec_types);
2647     }
2648   else
2649     new_type = build_function_type (TREE_TYPE (old_type),
2650                                     new_spec_types);
2651   new_type = cp_build_type_attribute_variant (new_type,
2652                                               TYPE_ATTRIBUTES (old_type));
2653   new_type = cxx_copy_lang_qualifiers (new_type, old_type);
2654
2655   TREE_TYPE (decl) = new_type;
2656 }
2657
2658 /* Return the number of template headers we expect to see for a definition
2659    or specialization of CTYPE or one of its non-template members.  */
2660
2661 int
2662 num_template_headers_for_class (tree ctype)
2663 {
2664   int num_templates = 0;
2665
2666   while (ctype && CLASS_TYPE_P (ctype))
2667     {
2668       /* You're supposed to have one `template <...>' for every
2669          template class, but you don't need one for a full
2670          specialization.  For example:
2671
2672          template <class T> struct S{};
2673          template <> struct S<int> { void f(); };
2674          void S<int>::f () {}
2675
2676          is correct; there shouldn't be a `template <>' for the
2677          definition of `S<int>::f'.  */
2678       if (!CLASSTYPE_TEMPLATE_INFO (ctype))
2679         /* If CTYPE does not have template information of any
2680            kind,  then it is not a template, nor is it nested
2681            within a template.  */
2682         break;
2683       if (explicit_class_specialization_p (ctype))
2684         break;
2685       if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (ctype)))
2686         ++num_templates;
2687
2688       ctype = TYPE_CONTEXT (ctype);
2689     }
2690
2691   return num_templates;
2692 }
2693
2694 /* Do a simple sanity check on the template headers that precede the
2695    variable declaration DECL.  */
2696
2697 void
2698 check_template_variable (tree decl)
2699 {
2700   tree ctx = CP_DECL_CONTEXT (decl);
2701   int wanted = num_template_headers_for_class (ctx);
2702   if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
2703       && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
2704     {
2705       if (cxx_dialect < cxx14)
2706         pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2707                  "variable templates only available with "
2708                  "%<-std=c++14%> or %<-std=gnu++14%>");
2709
2710       // Namespace-scope variable templates should have a template header.
2711       ++wanted;
2712     }
2713   if (template_header_count > wanted)
2714     {
2715       auto_diagnostic_group d;
2716       bool warned = pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2717                              "too many template headers for %qD "
2718                              "(should be %d)",
2719                              decl, wanted);
2720       if (warned && CLASS_TYPE_P (ctx)
2721           && CLASSTYPE_TEMPLATE_SPECIALIZATION (ctx))
2722         inform (DECL_SOURCE_LOCATION (decl),
2723                 "members of an explicitly specialized class are defined "
2724                 "without a template header");
2725     }
2726 }
2727
2728 /* An explicit specialization whose declarator-id or class-head-name is not
2729    qualified shall be declared in the nearest enclosing namespace of the
2730    template, or, if the namespace is inline (7.3.1), any namespace from its
2731    enclosing namespace set.
2732
2733    If the name declared in the explicit instantiation is an unqualified name,
2734    the explicit instantiation shall appear in the namespace where its template
2735    is declared or, if that namespace is inline (7.3.1), any namespace from its
2736    enclosing namespace set.  */
2737
2738 void
2739 check_unqualified_spec_or_inst (tree t, location_t loc)
2740 {
2741   tree tmpl = most_general_template (t);
2742   if (DECL_NAMESPACE_SCOPE_P (tmpl)
2743       && !is_nested_namespace (current_namespace,
2744                                CP_DECL_CONTEXT (tmpl), true))
2745     {
2746       if (processing_specialization)
2747         permerror (loc, "explicit specialization of %qD outside its "
2748                    "namespace must use a nested-name-specifier", tmpl);
2749       else if (processing_explicit_instantiation
2750                && cxx_dialect >= cxx11)
2751         /* This was allowed in C++98, so only pedwarn.  */
2752         pedwarn (loc, OPT_Wpedantic, "explicit instantiation of %qD "
2753                  "outside its namespace must use a nested-name-"
2754                  "specifier", tmpl);
2755     }
2756 }
2757
2758 /* Warn for a template specialization SPEC that is missing some of a set
2759    of function or type attributes that the template TEMPL is declared with.
2760    ATTRLIST is a list of additional attributes that SPEC should be taken
2761    to ultimately be declared with.  */
2762
2763 static void
2764 warn_spec_missing_attributes (tree tmpl, tree spec, tree attrlist)
2765 {
2766   if (DECL_FUNCTION_TEMPLATE_P (tmpl))
2767     tmpl = DECL_TEMPLATE_RESULT (tmpl);
2768
2769   /* Avoid warning if the difference between the primary and
2770      the specialization is not in one of the attributes below.  */
2771   const char* const blacklist[] = {
2772     "alloc_align", "alloc_size", "assume_aligned", "format",
2773     "format_arg", "malloc", "nonnull", NULL
2774   };
2775
2776   /* Put together a list of the black listed attributes that the primary
2777      template is declared with that the specialization is not, in case
2778      it's not apparent from the most recent declaration of the primary.  */
2779   pretty_printer str;
2780   unsigned nattrs = decls_mismatched_attributes (tmpl, spec, attrlist,
2781                                                  blacklist, &str);
2782
2783   if (!nattrs)
2784     return;
2785
2786   auto_diagnostic_group d;
2787   if (warning_at (DECL_SOURCE_LOCATION (spec), OPT_Wmissing_attributes,
2788                   "explicit specialization %q#D may be missing attributes",
2789                   spec))
2790     inform (DECL_SOURCE_LOCATION (tmpl),
2791             nattrs > 1
2792             ? G_("missing primary template attributes %s")
2793             : G_("missing primary template attribute %s"),
2794             pp_formatted_text (&str));
2795 }
2796
2797 /* Check to see if the function just declared, as indicated in
2798    DECLARATOR, and in DECL, is a specialization of a function
2799    template.  We may also discover that the declaration is an explicit
2800    instantiation at this point.
2801
2802    Returns DECL, or an equivalent declaration that should be used
2803    instead if all goes well.  Issues an error message if something is
2804    amiss.  Returns error_mark_node if the error is not easily
2805    recoverable.
2806
2807    FLAGS is a bitmask consisting of the following flags:
2808
2809    2: The function has a definition.
2810    4: The function is a friend.
2811
2812    The TEMPLATE_COUNT is the number of references to qualifying
2813    template classes that appeared in the name of the function.  For
2814    example, in
2815
2816      template <class T> struct S { void f(); };
2817      void S<int>::f();
2818
2819    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2820    classes are not counted in the TEMPLATE_COUNT, so that in
2821
2822      template <class T> struct S {};
2823      template <> struct S<int> { void f(); }
2824      template <> void S<int>::f();
2825
2826    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2827    invalid; there should be no template <>.)
2828
2829    If the function is a specialization, it is marked as such via
2830    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2831    is set up correctly, and it is added to the list of specializations
2832    for that template.  */
2833
2834 tree
2835 check_explicit_specialization (tree declarator,
2836                                tree decl,
2837                                int template_count,
2838                                int flags,
2839                                tree attrlist)
2840 {
2841   int have_def = flags & 2;
2842   int is_friend = flags & 4;
2843   bool is_concept = flags & 8;
2844   int specialization = 0;
2845   int explicit_instantiation = 0;
2846   int member_specialization = 0;
2847   tree ctype = DECL_CLASS_CONTEXT (decl);
2848   tree dname = DECL_NAME (decl);
2849   tmpl_spec_kind tsk;
2850
2851   if (is_friend)
2852     {
2853       if (!processing_specialization)
2854         tsk = tsk_none;
2855       else
2856         tsk = tsk_excessive_parms;
2857     }
2858   else
2859     tsk = current_tmpl_spec_kind (template_count);
2860
2861   switch (tsk)
2862     {
2863     case tsk_none:
2864       if (processing_specialization && !VAR_P (decl))
2865         {
2866           specialization = 1;
2867           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2868         }
2869       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2870         {
2871           if (is_friend)
2872             /* This could be something like:
2873
2874                template <class T> void f(T);
2875                class S { friend void f<>(int); }  */
2876             specialization = 1;
2877           else
2878             {
2879               /* This case handles bogus declarations like template <>
2880                  template <class T> void f<int>(); */
2881
2882               error_at (cp_expr_loc_or_input_loc (declarator),
2883                         "template-id %qE in declaration of primary template",
2884                         declarator);
2885               return decl;
2886             }
2887         }
2888       break;
2889
2890     case tsk_invalid_member_spec:
2891       /* The error has already been reported in
2892          check_specialization_scope.  */
2893       return error_mark_node;
2894
2895     case tsk_invalid_expl_inst:
2896       error ("template parameter list used in explicit instantiation");
2897
2898       /* Fall through.  */
2899
2900     case tsk_expl_inst:
2901       if (have_def)
2902         error ("definition provided for explicit instantiation");
2903
2904       explicit_instantiation = 1;
2905       break;
2906
2907     case tsk_excessive_parms:
2908     case tsk_insufficient_parms:
2909       if (tsk == tsk_excessive_parms)
2910         error ("too many template parameter lists in declaration of %qD",
2911                decl);
2912       else if (template_header_count)
2913         error("too few template parameter lists in declaration of %qD", decl);
2914       else
2915         error("explicit specialization of %qD must be introduced by "
2916               "%<template <>%>", decl);
2917
2918       /* Fall through.  */
2919     case tsk_expl_spec:
2920       if (is_concept)
2921         error ("explicit specialization declared %<concept%>");
2922
2923       if (VAR_P (decl) && TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2924         /* In cases like template<> constexpr bool v = true;
2925            We'll give an error in check_template_variable.  */
2926         break;
2927
2928       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2929       if (ctype)
2930         member_specialization = 1;
2931       else
2932         specialization = 1;
2933       break;
2934
2935     case tsk_template:
2936       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2937         {
2938           /* This case handles bogus declarations like template <>
2939              template <class T> void f<int>(); */
2940
2941           if (!uses_template_parms (TREE_OPERAND (declarator, 1)))
2942             error_at (cp_expr_loc_or_input_loc (declarator),
2943                       "template-id %qE in declaration of primary template",
2944                       declarator);
2945           else if (variable_template_p (TREE_OPERAND (declarator, 0)))
2946             {
2947               /* Partial specialization of variable template.  */
2948               SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2949               specialization = 1;
2950               goto ok;
2951             }
2952           else if (cxx_dialect < cxx14)
2953             error_at (cp_expr_loc_or_input_loc (declarator),
2954                       "non-type partial specialization %qE "
2955                       "is not allowed", declarator);
2956           else
2957             error_at (cp_expr_loc_or_input_loc (declarator),
2958                       "non-class, non-variable partial specialization %qE "
2959                       "is not allowed", declarator);
2960           return decl;
2961         ok:;
2962         }
2963
2964       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2965         /* This is a specialization of a member template, without
2966            specialization the containing class.  Something like:
2967
2968              template <class T> struct S {
2969                template <class U> void f (U);
2970              };
2971              template <> template <class U> void S<int>::f(U) {}
2972
2973            That's a specialization -- but of the entire template.  */
2974         specialization = 1;
2975       break;
2976
2977     default:
2978       gcc_unreachable ();
2979     }
2980
2981   if ((specialization || member_specialization)
2982       /* This doesn't apply to variable templates.  */
2983       && FUNC_OR_METHOD_TYPE_P (TREE_TYPE (decl)))
2984     {
2985       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2986       for (; t; t = TREE_CHAIN (t))
2987         if (TREE_PURPOSE (t))
2988           {
2989             permerror (input_location,
2990                        "default argument specified in explicit specialization");
2991             break;
2992           }
2993     }
2994
2995   if (specialization || member_specialization || explicit_instantiation)
2996     {
2997       tree tmpl = NULL_TREE;
2998       tree targs = NULL_TREE;
2999       bool was_template_id = (TREE_CODE (declarator) == TEMPLATE_ID_EXPR);
3000       bool found_hidden = false;
3001
3002       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
3003       if (!was_template_id)
3004         {
3005           tree fns;
3006
3007           gcc_assert (identifier_p (declarator));
3008           if (ctype)
3009             fns = dname;
3010           else
3011             {
3012               /* If there is no class context, the explicit instantiation
3013                  must be at namespace scope.  */
3014               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
3015
3016               /* Find the namespace binding, using the declaration
3017                  context.  */
3018               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
3019                                            LOOK_want::NORMAL, true);
3020               if (fns == error_mark_node)
3021                 {
3022                   /* If lookup fails, look for a friend declaration so we can
3023                      give a better diagnostic.  */
3024                   fns = (lookup_qualified_name
3025                          (CP_DECL_CONTEXT (decl), dname,
3026                           LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND,
3027                           /*complain*/true));
3028                   found_hidden = true;
3029                 }
3030
3031               if (fns == error_mark_node || !is_overloaded_fn (fns))
3032                 {
3033                   error ("%qD is not a template function", dname);
3034                   fns = error_mark_node;
3035                 }
3036             }
3037
3038           declarator = lookup_template_function (fns, NULL_TREE);
3039         }
3040
3041       if (declarator == error_mark_node)
3042         return error_mark_node;
3043
3044       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
3045         {
3046           if (!explicit_instantiation)
3047             /* A specialization in class scope.  This is invalid,
3048                but the error will already have been flagged by
3049                check_specialization_scope.  */
3050             return error_mark_node;
3051           else
3052             {
3053               /* It's not valid to write an explicit instantiation in
3054                  class scope, e.g.:
3055
3056                    class C { template void f(); }
3057
3058                    This case is caught by the parser.  However, on
3059                    something like:
3060
3061                    template class C { void f(); };
3062
3063                    (which is invalid) we can get here.  The error will be
3064                    issued later.  */
3065               ;
3066             }
3067
3068           return decl;
3069         }
3070       else if (ctype != NULL_TREE
3071                && (identifier_p (TREE_OPERAND (declarator, 0))))
3072         {
3073           // We'll match variable templates in start_decl.
3074           if (VAR_P (decl))
3075             return decl;
3076
3077           /* Find the list of functions in ctype that have the same
3078              name as the declared function.  */
3079           tree name = TREE_OPERAND (declarator, 0);
3080
3081           if (constructor_name_p (name, ctype))
3082             {
3083               if (DECL_CONSTRUCTOR_P (decl)
3084                   ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
3085                   : !CLASSTYPE_DESTRUCTOR (ctype))
3086                 {
3087                   /* From [temp.expl.spec]:
3088
3089                      If such an explicit specialization for the member
3090                      of a class template names an implicitly-declared
3091                      special member function (clause _special_), the
3092                      program is ill-formed.
3093
3094                      Similar language is found in [temp.explicit].  */
3095                   error ("specialization of implicitly-declared special member function");
3096                   return error_mark_node;
3097                 }
3098
3099               name = DECL_NAME (decl);
3100             }
3101
3102           /* For a type-conversion operator, We might be looking for
3103              `operator int' which will be a specialization of
3104              `operator T'.  Grab all the conversion operators, and
3105              then select from them.  */
3106           tree fns = get_class_binding (ctype, IDENTIFIER_CONV_OP_P (name)
3107                                         ? conv_op_identifier : name);
3108
3109           if (fns == NULL_TREE)
3110             {
3111               error ("no member function %qD declared in %qT", name, ctype);
3112               return error_mark_node;
3113             }
3114           else
3115             TREE_OPERAND (declarator, 0) = fns;
3116         }
3117
3118       /* Figure out what exactly is being specialized at this point.
3119          Note that for an explicit instantiation, even one for a
3120          member function, we cannot tell a priori whether the
3121          instantiation is for a member template, or just a member
3122          function of a template class.  Even if a member template is
3123          being instantiated, the member template arguments may be
3124          elided if they can be deduced from the rest of the
3125          declaration.  */
3126       tmpl = determine_specialization (declarator, decl,
3127                                        &targs,
3128                                        member_specialization,
3129                                        template_count,
3130                                        tsk);
3131
3132       if (!tmpl || tmpl == error_mark_node)
3133         /* We couldn't figure out what this declaration was
3134            specializing.  */
3135         return error_mark_node;
3136       else
3137         {
3138           if (found_hidden && TREE_CODE (decl) == FUNCTION_DECL)
3139             {
3140               auto_diagnostic_group d;
3141               if (pedwarn (DECL_SOURCE_LOCATION (decl), 0,
3142                            "friend declaration %qD is not visible to "
3143                            "explicit specialization", tmpl))
3144                 inform (DECL_SOURCE_LOCATION (tmpl),
3145                         "friend declaration here");
3146             }
3147
3148           if (!ctype && !is_friend
3149               && CP_DECL_CONTEXT (decl) == current_namespace)
3150             check_unqualified_spec_or_inst (tmpl, DECL_SOURCE_LOCATION (decl));
3151
3152           tree gen_tmpl = most_general_template (tmpl);
3153
3154           if (explicit_instantiation)
3155             {
3156               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
3157                  is done by do_decl_instantiation later.  */
3158
3159               int arg_depth = TMPL_ARGS_DEPTH (targs);
3160               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
3161
3162               if (arg_depth > parm_depth)
3163                 {
3164                   /* If TMPL is not the most general template (for
3165                      example, if TMPL is a friend template that is
3166                      injected into namespace scope), then there will
3167                      be too many levels of TARGS.  Remove some of them
3168                      here.  */
3169                   int i;
3170                   tree new_targs;
3171
3172                   new_targs = make_tree_vec (parm_depth);
3173                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
3174                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
3175                       = TREE_VEC_ELT (targs, i);
3176                   targs = new_targs;
3177                 }
3178
3179               return instantiate_template (tmpl, targs, tf_error);
3180             }
3181
3182           /* If we thought that the DECL was a member function, but it
3183              turns out to be specializing a static member function,
3184              make DECL a static member function as well.  */
3185           if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3186               && DECL_STATIC_FUNCTION_P (tmpl)
3187               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
3188             revert_static_member_fn (decl);
3189
3190           /* If this is a specialization of a member template of a
3191              template class, we want to return the TEMPLATE_DECL, not
3192              the specialization of it.  */
3193           if (tsk == tsk_template && !was_template_id)
3194             {
3195               tree result = DECL_TEMPLATE_RESULT (tmpl);
3196               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3197               DECL_INITIAL (result) = NULL_TREE;
3198               if (have_def)
3199                 {
3200                   tree parm;
3201                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
3202                   DECL_SOURCE_LOCATION (result)
3203                     = DECL_SOURCE_LOCATION (decl);
3204                   /* We want to use the argument list specified in the
3205                      definition, not in the original declaration.  */
3206                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
3207                   for (parm = DECL_ARGUMENTS (result); parm;
3208                        parm = DECL_CHAIN (parm))
3209                     DECL_CONTEXT (parm) = result;
3210                 }
3211               return register_specialization (tmpl, gen_tmpl, targs,
3212                                               is_friend, 0);
3213             }
3214
3215           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
3216           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
3217
3218           if (was_template_id)
3219             TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl)) = true;
3220
3221           /* Inherit default function arguments from the template
3222              DECL is specializing.  */
3223           if (DECL_FUNCTION_TEMPLATE_P (tmpl))
3224             copy_default_args_to_explicit_spec (decl);
3225
3226           /* This specialization has the same protection as the
3227              template it specializes.  */
3228           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
3229           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
3230
3231           /* 7.1.1-1 [dcl.stc]
3232
3233              A storage-class-specifier shall not be specified in an
3234              explicit specialization...
3235
3236              The parser rejects these, so unless action is taken here,
3237              explicit function specializations will always appear with
3238              global linkage.
3239
3240              The action recommended by the C++ CWG in response to C++
3241              defect report 605 is to make the storage class and linkage
3242              of the explicit specialization match the templated function:
3243
3244              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
3245            */
3246           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
3247             {
3248               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
3249               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
3250
3251               /* A concept cannot be specialized.  */
3252               if (DECL_DECLARED_CONCEPT_P (tmpl_func))
3253                 {
3254                   error ("explicit specialization of function concept %qD",
3255                          gen_tmpl);
3256                   return error_mark_node;
3257                 }
3258
3259               /* This specialization has the same linkage and visibility as
3260                  the function template it specializes.  */
3261               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
3262               if (! TREE_PUBLIC (decl))
3263                 {
3264                   DECL_INTERFACE_KNOWN (decl) = 1;
3265                   DECL_NOT_REALLY_EXTERN (decl) = 1;
3266                 }
3267               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
3268               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
3269                 {
3270                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
3271                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
3272                 }
3273             }
3274
3275           /* If DECL is a friend declaration, declared using an
3276              unqualified name, the namespace associated with DECL may
3277              have been set incorrectly.  For example, in:
3278
3279                template <typename T> void f(T);
3280                namespace N {
3281                  struct S { friend void f<int>(int); }
3282                }
3283
3284              we will have set the DECL_CONTEXT for the friend
3285              declaration to N, rather than to the global namespace.  */
3286           if (DECL_NAMESPACE_SCOPE_P (decl))
3287             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
3288
3289           if (is_friend && !have_def)
3290             /* This is not really a declaration of a specialization.
3291                It's just the name of an instantiation.  But, it's not
3292                a request for an instantiation, either.  */
3293             SET_DECL_IMPLICIT_INSTANTIATION (decl);
3294           else if (TREE_CODE (decl) == FUNCTION_DECL)
3295             /* A specialization is not necessarily COMDAT.  */
3296             DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
3297                                   && DECL_DECLARED_INLINE_P (decl));
3298           else if (VAR_P (decl))
3299             DECL_COMDAT (decl) = false;
3300
3301           /* If this is a full specialization, register it so that we can find
3302              it again.  Partial specializations will be registered in
3303              process_partial_specialization.  */
3304           if (!processing_template_decl)
3305             {
3306               warn_spec_missing_attributes (gen_tmpl, decl, attrlist);
3307
3308               decl = register_specialization (decl, gen_tmpl, targs,
3309                                               is_friend, 0);
3310             }
3311
3312
3313           /* A 'structor should already have clones.  */
3314           gcc_assert (decl == error_mark_node
3315                       || variable_template_p (tmpl)
3316                       || !(DECL_CONSTRUCTOR_P (decl)
3317                            || DECL_DESTRUCTOR_P (decl))
3318                       || DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
3319         }
3320     }
3321
3322   return decl;
3323 }
3324
3325 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
3326    parameters.  These are represented in the same format used for
3327    DECL_TEMPLATE_PARMS.  */
3328
3329 int
3330 comp_template_parms (const_tree parms1, const_tree parms2)
3331 {
3332   const_tree p1;
3333   const_tree p2;
3334
3335   if (parms1 == parms2)
3336     return 1;
3337
3338   for (p1 = parms1, p2 = parms2;
3339        p1 != NULL_TREE && p2 != NULL_TREE;
3340        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
3341     {
3342       tree t1 = TREE_VALUE (p1);
3343       tree t2 = TREE_VALUE (p2);
3344       int i;
3345
3346       gcc_assert (TREE_CODE (t1) == TREE_VEC);
3347       gcc_assert (TREE_CODE (t2) == TREE_VEC);
3348
3349       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
3350         return 0;
3351
3352       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
3353         {
3354           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
3355           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
3356
3357           /* If either of the template parameters are invalid, assume
3358              they match for the sake of error recovery. */
3359           if (error_operand_p (parm1) || error_operand_p (parm2))
3360             return 1;
3361
3362           if (TREE_CODE (parm1) != TREE_CODE (parm2))
3363             return 0;
3364
3365           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
3366               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
3367                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
3368             continue;
3369           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
3370             return 0;
3371         }
3372     }
3373
3374   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3375     /* One set of parameters has more parameters lists than the
3376        other.  */
3377     return 0;
3378
3379   return 1;
3380 }
3381
3382 /* Returns true if two template parameters are declared with
3383    equivalent constraints.  */
3384
3385 static bool
3386 template_parameter_constraints_equivalent_p (const_tree parm1, const_tree parm2)
3387 {
3388   tree req1 = TREE_TYPE (parm1);
3389   tree req2 = TREE_TYPE (parm2);
3390   if (!req1 != !req2)
3391     return false;
3392   if (req1)
3393     return cp_tree_equal (req1, req2);
3394   return true;
3395 }
3396
3397 /* Returns true when two template parameters are equivalent.  */
3398
3399 static bool
3400 template_parameters_equivalent_p (const_tree parm1, const_tree parm2)
3401 {
3402   tree decl1 = TREE_VALUE (parm1);
3403   tree decl2 = TREE_VALUE (parm2);
3404
3405   /* If either of the template parameters are invalid, assume
3406      they match for the sake of error recovery. */
3407   if (error_operand_p (decl1) || error_operand_p (decl2))
3408     return true;
3409
3410   /* ... they declare parameters of the same kind.  */
3411   if (TREE_CODE (decl1) != TREE_CODE (decl2))
3412     return false;
3413
3414   /* ... one parameter was introduced by a parameter declaration, then
3415      both are. This case arises as a result of eagerly rewriting declarations
3416      during parsing.  */
3417   if (DECL_VIRTUAL_P (decl1) != DECL_VIRTUAL_P (decl2))
3418     return false;
3419
3420   /* ... if either declares a pack, they both do.  */
3421   if (template_parameter_pack_p (decl1) != template_parameter_pack_p (decl2))
3422     return false;
3423
3424   if (TREE_CODE (decl1) == PARM_DECL)
3425     {
3426       /* ... if they declare non-type parameters, the types are equivalent.  */
3427       if (!same_type_p (TREE_TYPE (decl1), TREE_TYPE (decl2)))
3428         return false;
3429     }
3430   else if (TREE_CODE (decl2) == TEMPLATE_DECL)
3431     {
3432       /* ... if they declare template template parameters, their template
3433          parameter lists are equivalent.  */
3434       if (!template_heads_equivalent_p (decl1, decl2))
3435         return false;
3436     }
3437
3438   /* ... if they are declared with a qualified-concept name, they both
3439      are, and those names are equivalent.  */
3440   return template_parameter_constraints_equivalent_p (parm1, parm2);
3441 }
3442
3443 /* Returns true if two template parameters lists are equivalent.
3444    Two template parameter lists are equivalent if they have the
3445    same length and their corresponding parameters are equivalent.
3446
3447    PARMS1 and PARMS2 are TREE_LISTs containing TREE_VECs: the
3448    data structure returned by DECL_TEMPLATE_PARMS.
3449
3450    This is generally the same implementation as comp_template_parms
3451    except that it also the concept names and arguments used to
3452    introduce parameters.  */
3453
3454 static bool
3455 template_parameter_lists_equivalent_p (const_tree parms1, const_tree parms2)
3456 {
3457   if (parms1 == parms2)
3458     return true;
3459
3460   const_tree p1 = parms1;
3461   const_tree p2 = parms2;
3462   while (p1 != NULL_TREE && p2 != NULL_TREE)
3463     {
3464       tree list1 = TREE_VALUE (p1);
3465       tree list2 = TREE_VALUE (p2);
3466
3467       if (TREE_VEC_LENGTH (list1) != TREE_VEC_LENGTH (list2))
3468         return 0;
3469
3470       for (int i = 0; i < TREE_VEC_LENGTH (list2); ++i)
3471         {
3472           tree parm1 = TREE_VEC_ELT (list1, i);
3473           tree parm2 = TREE_VEC_ELT (list2, i);
3474           if (!template_parameters_equivalent_p (parm1, parm2))
3475             return false;
3476         }
3477
3478       p1 = TREE_CHAIN (p1);
3479       p2 = TREE_CHAIN (p2);
3480     }
3481
3482   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3483     return false;
3484
3485   return true;
3486 }
3487
3488 /* Return true if the requires-clause of the template parameter lists are
3489    equivalent and false otherwise.  */
3490 static bool
3491 template_requirements_equivalent_p (const_tree parms1, const_tree parms2)
3492 {
3493   tree req1 = TEMPLATE_PARMS_CONSTRAINTS (parms1);
3494   tree req2 = TEMPLATE_PARMS_CONSTRAINTS (parms2);
3495   if ((req1 != NULL_TREE) != (req2 != NULL_TREE))
3496     return false;
3497   if (!cp_tree_equal (req1, req2))
3498     return false;
3499   return true;
3500 }
3501
3502 /* Returns true if two template heads are equivalent. 17.6.6.1p6:
3503    Two template heads are equivalent if their template parameter
3504    lists are equivalent and their requires clauses are equivalent.
3505
3506    In pre-C++20, this is equivalent to calling comp_template_parms
3507    for the template parameters of TMPL1 and TMPL2.  */
3508
3509 bool
3510 template_heads_equivalent_p (const_tree tmpl1, const_tree tmpl2)
3511 {
3512   tree parms1 = DECL_TEMPLATE_PARMS (tmpl1);
3513   tree parms2 = DECL_TEMPLATE_PARMS (tmpl2);
3514
3515   /* Don't change the matching rules for pre-C++20.  */
3516   if (cxx_dialect < cxx20)
3517     return comp_template_parms (parms1, parms2);
3518
3519   /* ... have the same number of template parameters, and their
3520      corresponding parameters are equivalent.  */
3521   if (!template_parameter_lists_equivalent_p (parms1, parms2))
3522     return false;
3523
3524   /* ... if either has a requires-clause, they both do and their
3525      corresponding constraint-expressions are equivalent.  */
3526   return template_requirements_equivalent_p (parms1, parms2);
3527 }
3528
3529 /* Determine whether PARM is a parameter pack.  */
3530
3531 bool
3532 template_parameter_pack_p (const_tree parm)
3533 {
3534   /* Determine if we have a non-type template parameter pack.  */
3535   if (TREE_CODE (parm) == PARM_DECL)
3536     return (DECL_TEMPLATE_PARM_P (parm)
3537             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
3538   if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
3539     return TEMPLATE_PARM_PARAMETER_PACK (parm);
3540
3541   /* If this is a list of template parameters, we could get a
3542      TYPE_DECL or a TEMPLATE_DECL.  */
3543   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
3544     parm = TREE_TYPE (parm);
3545
3546   /* Otherwise it must be a type template parameter.  */
3547   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
3548            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
3549           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
3550 }
3551
3552 /* Determine if T is a function parameter pack.  */
3553
3554 bool
3555 function_parameter_pack_p (const_tree t)
3556 {
3557   if (t && TREE_CODE (t) == PARM_DECL)
3558     return DECL_PACK_P (t);
3559   return false;
3560 }
3561
3562 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
3563    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
3564
3565 tree
3566 get_function_template_decl (const_tree primary_func_tmpl_inst)
3567 {
3568   if (! primary_func_tmpl_inst
3569       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
3570       || ! primary_template_specialization_p (primary_func_tmpl_inst))
3571     return NULL;
3572
3573   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
3574 }
3575
3576 /* Return true iff the function parameter PARAM_DECL was expanded
3577    from the function parameter pack PACK.  */
3578
3579 bool
3580 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
3581 {
3582   if (DECL_ARTIFICIAL (param_decl)
3583       || !function_parameter_pack_p (pack))
3584     return false;
3585
3586   /* The parameter pack and its pack arguments have the same
3587      DECL_PARM_INDEX.  */
3588   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
3589 }
3590
3591 /* Determine whether ARGS describes a variadic template args list,
3592    i.e., one that is terminated by a template argument pack.  */
3593
3594 static bool
3595 template_args_variadic_p (tree args)
3596 {
3597   int nargs;
3598   tree last_parm;
3599
3600   if (args == NULL_TREE)
3601     return false;
3602
3603   args = INNERMOST_TEMPLATE_ARGS (args);
3604   nargs = TREE_VEC_LENGTH (args);
3605
3606   if (nargs == 0)
3607     return false;
3608
3609   last_parm = TREE_VEC_ELT (args, nargs - 1);
3610
3611   return ARGUMENT_PACK_P (last_parm);
3612 }
3613
3614 /* Generate a new name for the parameter pack name NAME (an
3615    IDENTIFIER_NODE) that incorporates its */
3616
3617 static tree
3618 make_ith_pack_parameter_name (tree name, int i)
3619 {
3620   /* Munge the name to include the parameter index.  */
3621 #define NUMBUF_LEN 128
3622   char numbuf[NUMBUF_LEN];
3623   char* newname;
3624   int newname_len;
3625
3626   if (name == NULL_TREE)
3627     return name;
3628   snprintf (numbuf, NUMBUF_LEN, "%i", i);
3629   newname_len = IDENTIFIER_LENGTH (name)
3630                 + strlen (numbuf) + 2;
3631   newname = (char*)alloca (newname_len);
3632   snprintf (newname, newname_len,
3633             "%s#%i", IDENTIFIER_POINTER (name), i);
3634   return get_identifier (newname);
3635 }
3636
3637 /* Return true if T is a primary function, class or alias template
3638    specialization, not including the template pattern.  */
3639
3640 bool
3641 primary_template_specialization_p (const_tree t)
3642 {
3643   if (!t)
3644     return false;
3645
3646   if (VAR_OR_FUNCTION_DECL_P (t))
3647     return (DECL_LANG_SPECIFIC (t)
3648             && DECL_USE_TEMPLATE (t)
3649             && DECL_TEMPLATE_INFO (t)
3650             && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t)));
3651   else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
3652     return (CLASSTYPE_TEMPLATE_INFO (t)
3653             && CLASSTYPE_USE_TEMPLATE (t)
3654             && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)));
3655   else if (alias_template_specialization_p (t, nt_transparent))
3656     return true;
3657   return false;
3658 }
3659
3660 /* Return true if PARM is a template template parameter.  */
3661
3662 bool
3663 template_template_parameter_p (const_tree parm)
3664 {
3665   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
3666 }
3667
3668 /* Return true iff PARM is a DECL representing a type template
3669    parameter.  */
3670
3671 bool
3672 template_type_parameter_p (const_tree parm)
3673 {
3674   return (parm
3675           && (TREE_CODE (parm) == TYPE_DECL
3676               || TREE_CODE (parm) == TEMPLATE_DECL)
3677           && DECL_TEMPLATE_PARM_P (parm));
3678 }
3679
3680 /* Return the template parameters of T if T is a
3681    primary template instantiation, NULL otherwise.  */
3682
3683 tree
3684 get_primary_template_innermost_parameters (const_tree t)
3685 {
3686   tree parms = NULL, template_info = NULL;
3687
3688   if ((template_info = get_template_info (t))
3689       && primary_template_specialization_p (t))
3690     parms = INNERMOST_TEMPLATE_PARMS
3691         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
3692
3693   return parms;
3694 }
3695
3696 /* Return the template parameters of the LEVELth level from the full list
3697    of template parameters PARMS.  */
3698
3699 tree
3700 get_template_parms_at_level (tree parms, int level)
3701 {
3702   tree p;
3703   if (!parms
3704       || TREE_CODE (parms) != TREE_LIST
3705       || level > TMPL_PARMS_DEPTH (parms))
3706     return NULL_TREE;
3707
3708   for (p = parms; p; p = TREE_CHAIN (p))
3709     if (TMPL_PARMS_DEPTH (p) == level)
3710       return p;
3711
3712   return NULL_TREE;
3713 }
3714
3715 /* Returns the template arguments of T if T is a template instantiation,
3716    NULL otherwise.  */
3717
3718 tree
3719 get_template_innermost_arguments (const_tree t)
3720 {
3721   tree args = NULL, template_info = NULL;
3722
3723   if ((template_info = get_template_info (t))
3724       && TI_ARGS (template_info))
3725     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
3726
3727   return args;
3728 }
3729
3730 /* Return the argument pack elements of T if T is a template argument pack,
3731    NULL otherwise.  */
3732
3733 tree
3734 get_template_argument_pack_elems (const_tree t)
3735 {
3736   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
3737       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
3738     return NULL;
3739
3740   return ARGUMENT_PACK_ARGS (t);
3741 }
3742
3743 /* In an ARGUMENT_PACK_SELECT, the actual underlying argument that the
3744    ARGUMENT_PACK_SELECT represents. */
3745
3746 static tree
3747 argument_pack_select_arg (tree t)
3748 {
3749   tree args = ARGUMENT_PACK_ARGS (ARGUMENT_PACK_SELECT_FROM_PACK (t));
3750   tree arg = TREE_VEC_ELT (args, ARGUMENT_PACK_SELECT_INDEX (t));
3751
3752   /* If the selected argument is an expansion E, that most likely means we were
3753      called from gen_elem_of_pack_expansion_instantiation during the
3754      substituting of an argument pack (of which the Ith element is a pack
3755      expansion, where I is ARGUMENT_PACK_SELECT_INDEX) into a pack expansion.
3756      In this case, the Ith element resulting from this substituting is going to
3757      be a pack expansion, which pattern is the pattern of E.  Let's return the
3758      pattern of E, and gen_elem_of_pack_expansion_instantiation will build the
3759      resulting pack expansion from it.  */
3760   if (PACK_EXPANSION_P (arg))
3761     {
3762       /* Make sure we aren't throwing away arg info.  */
3763       gcc_assert (!PACK_EXPANSION_EXTRA_ARGS (arg));
3764       arg = PACK_EXPANSION_PATTERN (arg);
3765     }
3766
3767   return arg;
3768 }
3769
3770
3771 /* True iff FN is a function representing a built-in variadic parameter
3772    pack.  */
3773
3774 bool
3775 builtin_pack_fn_p (tree fn)
3776 {
3777   if (!fn
3778       || TREE_CODE (fn) != FUNCTION_DECL
3779       || !DECL_IS_UNDECLARED_BUILTIN (fn))
3780     return false;
3781
3782   if (id_equal (DECL_NAME (fn), "__integer_pack"))
3783     return true;
3784
3785   return false;
3786 }
3787
3788 /* True iff CALL is a call to a function representing a built-in variadic
3789    parameter pack.  */
3790
3791 static bool
3792 builtin_pack_call_p (tree call)
3793 {
3794   if (TREE_CODE (call) != CALL_EXPR)
3795     return false;
3796   return builtin_pack_fn_p (CALL_EXPR_FN (call));
3797 }
3798
3799 /* Return a TREE_VEC for the expansion of __integer_pack(HI).  */
3800
3801 static tree
3802 expand_integer_pack (tree call, tree args, tsubst_flags_t complain,
3803                      tree in_decl)
3804 {
3805   tree ohi = CALL_EXPR_ARG (call, 0);
3806   tree hi = tsubst_copy_and_build (ohi, args, complain, in_decl,
3807                                    false/*fn*/, true/*int_cst*/);
3808
3809   if (value_dependent_expression_p (hi))
3810     {
3811       if (hi != ohi)
3812         {
3813           call = copy_node (call);
3814           CALL_EXPR_ARG (call, 0) = hi;
3815         }
3816       tree ex = make_pack_expansion (call, complain);
3817       tree vec = make_tree_vec (1);
3818       TREE_VEC_ELT (vec, 0) = ex;
3819       return vec;
3820     }
3821   else
3822     {
3823       hi = cxx_constant_value (hi);
3824       int len = valid_constant_size_p (hi) ? tree_to_shwi (hi) : -1;
3825
3826       /* Calculate the largest value of len that won't make the size of the vec
3827          overflow an int.  The compiler will exceed resource limits long before
3828          this, but it seems a decent place to diagnose.  */
3829       int max = ((INT_MAX - sizeof (tree_vec)) / sizeof (tree)) + 1;
3830
3831       if (len < 0 || len > max)
3832         {
3833           if ((complain & tf_error)
3834               && hi != error_mark_node)
3835             error ("argument to %<__integer_pack%> must be between 0 and %d",
3836                    max);
3837           return error_mark_node;
3838         }
3839
3840       tree vec = make_tree_vec (len);
3841
3842       for (int i = 0; i < len; ++i)
3843         TREE_VEC_ELT (vec, i) = size_int (i);
3844
3845       return vec;
3846     }
3847 }
3848
3849 /* Return a TREE_VEC for the expansion of built-in template parameter pack
3850    CALL.  */
3851
3852 static tree
3853 expand_builtin_pack_call (tree call, tree args, tsubst_flags_t complain,
3854                           tree in_decl)
3855 {
3856   if (!builtin_pack_call_p (call))
3857     return NULL_TREE;
3858
3859   tree fn = CALL_EXPR_FN (call);
3860
3861   if (id_equal (DECL_NAME (fn), "__integer_pack"))
3862     return expand_integer_pack (call, args, complain, in_decl);
3863
3864   return NULL_TREE;
3865 }
3866
3867 /* Structure used to track the progress of find_parameter_packs_r.  */
3868 struct find_parameter_pack_data
3869 {
3870   /* TREE_LIST that will contain all of the parameter packs found by
3871      the traversal.  */
3872   tree* parameter_packs;
3873
3874   /* Set of AST nodes that have been visited by the traversal.  */
3875   hash_set<tree> *visited;
3876
3877   /* True iff we're making a type pack expansion.  */
3878   bool type_pack_expansion_p;
3879 };
3880
3881 /* Identifies all of the argument packs that occur in a template
3882    argument and appends them to the TREE_LIST inside DATA, which is a
3883    find_parameter_pack_data structure. This is a subroutine of
3884    make_pack_expansion and uses_parameter_packs.  */
3885 static tree
3886 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
3887 {
3888   tree t = *tp;
3889   struct find_parameter_pack_data* ppd =
3890     (struct find_parameter_pack_data*)data;
3891   bool parameter_pack_p = false;
3892
3893 #define WALK_SUBTREE(NODE)                              \
3894   cp_walk_tree (&(NODE), &find_parameter_packs_r,       \
3895                 ppd, ppd->visited)                      \
3896
3897   /* Don't look through typedefs; we are interested in whether a
3898      parameter pack is actually written in the expression/type we're
3899      looking at, not the target type.  */
3900   if (TYPE_P (t) && typedef_variant_p (t))
3901     {
3902       /* But do look at arguments for an alias template.  */
3903       if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
3904         cp_walk_tree (&TI_ARGS (tinfo),
3905                       &find_parameter_packs_r,
3906                       ppd, ppd->visited);
3907       *walk_subtrees = 0;
3908       return NULL_TREE;
3909     }
3910
3911   /* Identify whether this is a parameter pack or not.  */
3912   switch (TREE_CODE (t))
3913     {
3914     case TEMPLATE_PARM_INDEX:
3915       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3916         parameter_pack_p = true;
3917       break;
3918
3919     case TEMPLATE_TYPE_PARM:
3920       t = TYPE_MAIN_VARIANT (t);
3921       /* FALLTHRU */
3922     case TEMPLATE_TEMPLATE_PARM:
3923       /* If the placeholder appears in the decl-specifier-seq of a function
3924          parameter pack (14.6.3), or the type-specifier-seq of a type-id that
3925          is a pack expansion, the invented template parameter is a template
3926          parameter pack.  */
3927       if (ppd->type_pack_expansion_p && is_auto (t))
3928         TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
3929       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3930         parameter_pack_p = true;
3931       break;
3932
3933     case FIELD_DECL:
3934     case PARM_DECL:
3935       if (DECL_PACK_P (t))
3936         {
3937           /* We don't want to walk into the type of a PARM_DECL,
3938              because we don't want to see the type parameter pack.  */
3939           *walk_subtrees = 0;
3940           parameter_pack_p = true;
3941         }
3942       break;
3943
3944     case VAR_DECL:
3945       if (DECL_PACK_P (t))
3946         {
3947           /* We don't want to walk into the type of a variadic capture proxy,
3948              because we don't want to see the type parameter pack.  */
3949           *walk_subtrees = 0;
3950           parameter_pack_p = true;
3951         }
3952       else if (variable_template_specialization_p (t))
3953         {
3954           cp_walk_tree (&DECL_TI_ARGS (t),
3955                         find_parameter_packs_r,
3956                         ppd, ppd->visited);
3957           *walk_subtrees = 0;
3958         }
3959       break;
3960
3961     case CALL_EXPR:
3962       if (builtin_pack_call_p (t))
3963         parameter_pack_p = true;
3964       break;
3965
3966     case BASES:
3967       parameter_pack_p = true;
3968       break;
3969     default:
3970       /* Not a parameter pack.  */
3971       break;
3972     }
3973
3974   if (parameter_pack_p)
3975     {
3976       /* Add this parameter pack to the list.  */
3977       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
3978     }
3979
3980   if (TYPE_P (t))
3981     cp_walk_tree (&TYPE_CONTEXT (t),
3982                   &find_parameter_packs_r, ppd, ppd->visited);
3983
3984   /* This switch statement will return immediately if we don't find a
3985      parameter pack.  ??? Should some of these be in cp_walk_subtrees?  */
3986   switch (TREE_CODE (t))
3987     {
3988     case BOUND_TEMPLATE_TEMPLATE_PARM:
3989       /* Check the template itself.  */
3990       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)),
3991                     &find_parameter_packs_r, ppd, ppd->visited);
3992       return NULL_TREE;
3993
3994     case DECL_EXPR:
3995       {
3996         tree decl = DECL_EXPR_DECL (t);
3997         /* Ignore the declaration of a capture proxy for a parameter pack.  */
3998         if (is_capture_proxy (decl))
3999           *walk_subtrees = 0;
4000         if (is_typedef_decl (decl))
4001           /* Since we stop at typedefs above, we need to look through them at
4002              the point of the DECL_EXPR.  */
4003           cp_walk_tree (&DECL_ORIGINAL_TYPE (decl),
4004                         &find_parameter_packs_r, ppd, ppd->visited);
4005         return NULL_TREE;
4006       }
4007
4008     case TEMPLATE_DECL:
4009       if (!DECL_TEMPLATE_TEMPLATE_PARM_P (t))
4010         return NULL_TREE;
4011       cp_walk_tree (&TREE_TYPE (t),
4012                     &find_parameter_packs_r, ppd, ppd->visited);
4013       return NULL_TREE;
4014
4015     case TYPE_PACK_EXPANSION:
4016     case EXPR_PACK_EXPANSION:
4017       *walk_subtrees = 0;
4018       return NULL_TREE;
4019
4020     case INTEGER_TYPE:
4021       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r,
4022                     ppd, ppd->visited);
4023       *walk_subtrees = 0;
4024       return NULL_TREE;
4025
4026     case IDENTIFIER_NODE:
4027       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd,
4028                     ppd->visited);
4029       *walk_subtrees = 0;
4030       return NULL_TREE;
4031
4032     case LAMBDA_EXPR:
4033       {
4034         /* Since we defer implicit capture, look in the parms and body.  */
4035         tree fn = lambda_function (t);
4036         cp_walk_tree (&TREE_TYPE (fn), &find_parameter_packs_r, ppd,
4037                       ppd->visited);
4038         cp_walk_tree (&DECL_SAVED_TREE (fn), &find_parameter_packs_r, ppd,
4039                       ppd->visited);
4040         return NULL_TREE;
4041       }
4042
4043     case DECLTYPE_TYPE:
4044       {
4045         /* When traversing a DECLTYPE_TYPE_EXPR, we need to set
4046            type_pack_expansion_p to false so that any placeholders
4047            within the expression don't get marked as parameter packs.  */
4048         bool type_pack_expansion_p = ppd->type_pack_expansion_p;
4049         ppd->type_pack_expansion_p = false;
4050         cp_walk_tree (&DECLTYPE_TYPE_EXPR (t), &find_parameter_packs_r,
4051                       ppd, ppd->visited);
4052         ppd->type_pack_expansion_p = type_pack_expansion_p;
4053         *walk_subtrees = 0;
4054         return NULL_TREE;
4055       }
4056
4057     case IF_STMT:
4058       cp_walk_tree (&IF_COND (t), &find_parameter_packs_r,
4059                     ppd, ppd->visited);
4060       cp_walk_tree (&THEN_CLAUSE (t), &find_parameter_packs_r,
4061                     ppd, ppd->visited);
4062       cp_walk_tree (&ELSE_CLAUSE (t), &find_parameter_packs_r,
4063                     ppd, ppd->visited);
4064       /* Don't walk into IF_STMT_EXTRA_ARGS.  */
4065       *walk_subtrees = 0;
4066       return NULL_TREE;
4067
4068     case TAG_DEFN:
4069       t = TREE_TYPE (t);
4070       if (CLASS_TYPE_P (t))
4071         /* Local class, need to look through the whole definition.  */
4072         for (tree bb : BINFO_BASE_BINFOS (TYPE_BINFO (t)))
4073           cp_walk_tree (&BINFO_TYPE (bb), &find_parameter_packs_r,
4074                         ppd, ppd->visited);
4075       else
4076         /* Enum, look at the values.  */
4077         for (tree l = TYPE_VALUES (t); l; l = TREE_CHAIN (l))
4078           cp_walk_tree (&DECL_INITIAL (TREE_VALUE (l)),
4079                         &find_parameter_packs_r,
4080                         ppd, ppd->visited);
4081       return NULL_TREE;
4082
4083     case FUNCTION_TYPE:
4084     case METHOD_TYPE:
4085       WALK_SUBTREE (TYPE_RAISES_EXCEPTIONS (t));
4086       break;
4087
4088     default:
4089       return NULL_TREE;
4090     }
4091
4092 #undef WALK_SUBTREE
4093
4094   return NULL_TREE;
4095 }
4096
4097 /* Determines if the expression or type T uses any parameter packs.  */
4098 tree
4099 uses_parameter_packs (tree t)
4100 {
4101   tree parameter_packs = NULL_TREE;
4102   struct find_parameter_pack_data ppd;
4103   ppd.parameter_packs = &parameter_packs;
4104   ppd.visited = new hash_set<tree>;
4105   ppd.type_pack_expansion_p = false;
4106   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4107   delete ppd.visited;
4108   return parameter_packs;
4109 }
4110
4111 /* Turn ARG, which may be an expression, type, or a TREE_LIST
4112    representation a base-class initializer into a parameter pack
4113    expansion. If all goes well, the resulting node will be an
4114    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
4115    respectively.  */
4116 tree
4117 make_pack_expansion (tree arg, tsubst_flags_t complain)
4118 {
4119   tree result;
4120   tree parameter_packs = NULL_TREE;
4121   bool for_types = false;
4122   struct find_parameter_pack_data ppd;
4123
4124   if (!arg || arg == error_mark_node)
4125     return arg;
4126
4127   if (TREE_CODE (arg) == TREE_LIST && TREE_PURPOSE (arg))
4128     {
4129       /* A TREE_LIST with a non-null TREE_PURPOSE is for a base
4130          class initializer.  In this case, the TREE_PURPOSE will be a
4131          _TYPE node (representing the base class expansion we're
4132          initializing) and the TREE_VALUE will be a TREE_LIST
4133          containing the initialization arguments. 
4134
4135          The resulting expansion looks somewhat different from most
4136          expansions. Rather than returning just one _EXPANSION, we
4137          return a TREE_LIST whose TREE_PURPOSE is a
4138          TYPE_PACK_EXPANSION containing the bases that will be
4139          initialized.  The TREE_VALUE will be identical to the
4140          original TREE_VALUE, which is a list of arguments that will
4141          be passed to each base.  We do not introduce any new pack
4142          expansion nodes into the TREE_VALUE (although it is possible
4143          that some already exist), because the TREE_PURPOSE and
4144          TREE_VALUE all need to be expanded together with the same
4145          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
4146          resulting TREE_PURPOSE will mention the parameter packs in
4147          both the bases and the arguments to the bases.  */
4148       tree purpose;
4149       tree value;
4150       tree parameter_packs = NULL_TREE;
4151
4152       /* Determine which parameter packs will be used by the base
4153          class expansion.  */
4154       ppd.visited = new hash_set<tree>;
4155       ppd.parameter_packs = &parameter_packs;
4156       ppd.type_pack_expansion_p = false;
4157       gcc_assert (TYPE_P (TREE_PURPOSE (arg)));
4158       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r,
4159                     &ppd, ppd.visited);
4160
4161       if (parameter_packs == NULL_TREE)
4162         {
4163           if (complain & tf_error)
4164             error ("base initializer expansion %qT contains no parameter packs",
4165                    arg);
4166           delete ppd.visited;
4167           return error_mark_node;
4168         }
4169
4170       if (TREE_VALUE (arg) != void_type_node)
4171         {
4172           /* Collect the sets of parameter packs used in each of the
4173              initialization arguments.  */
4174           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
4175             {
4176               /* Determine which parameter packs will be expanded in this
4177                  argument.  */
4178               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
4179                             &ppd, ppd.visited);
4180             }
4181         }
4182
4183       delete ppd.visited;
4184
4185       /* Create the pack expansion type for the base type.  */
4186       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
4187       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
4188       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
4189       PACK_EXPANSION_LOCAL_P (purpose) = at_function_scope_p ();
4190
4191       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4192          they will rarely be compared to anything.  */
4193       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
4194
4195       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
4196     }
4197
4198   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
4199     for_types = true;
4200
4201   /* Build the PACK_EXPANSION_* node.  */
4202   result = for_types
4203      ? cxx_make_type (TYPE_PACK_EXPANSION)
4204      : make_node (EXPR_PACK_EXPANSION);
4205   SET_PACK_EXPANSION_PATTERN (result, arg);
4206   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
4207     {
4208       /* Propagate type and const-expression information.  */
4209       TREE_TYPE (result) = TREE_TYPE (arg);
4210       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
4211       /* Mark this read now, since the expansion might be length 0.  */
4212       mark_exp_read (arg);
4213     }
4214   else
4215     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4216        they will rarely be compared to anything.  */
4217     SET_TYPE_STRUCTURAL_EQUALITY (result);
4218
4219   /* Determine which parameter packs will be expanded.  */
4220   ppd.parameter_packs = &parameter_packs;
4221   ppd.visited = new hash_set<tree>;
4222   ppd.type_pack_expansion_p = TYPE_P (arg);
4223   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
4224   delete ppd.visited;
4225
4226   /* Make sure we found some parameter packs.  */
4227   if (parameter_packs == NULL_TREE)
4228     {
4229       if (complain & tf_error)
4230         {
4231           if (TYPE_P (arg))
4232             error ("expansion pattern %qT contains no parameter packs", arg);
4233           else
4234             error ("expansion pattern %qE contains no parameter packs", arg);
4235         }
4236       return error_mark_node;
4237     }
4238   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
4239
4240   PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
4241
4242   return result;
4243 }
4244
4245 /* Checks T for any "bare" parameter packs, which have not yet been
4246    expanded, and issues an error if any are found. This operation can
4247    only be done on full expressions or types (e.g., an expression
4248    statement, "if" condition, etc.), because we could have expressions like:
4249
4250      foo(f(g(h(args)))...)
4251
4252    where "args" is a parameter pack. check_for_bare_parameter_packs
4253    should not be called for the subexpressions args, h(args),
4254    g(h(args)), or f(g(h(args))), because we would produce erroneous
4255    error messages.
4256
4257    Returns TRUE and emits an error if there were bare parameter packs,
4258    returns FALSE otherwise.  */
4259 bool
4260 check_for_bare_parameter_packs (tree t, location_t loc /* = UNKNOWN_LOCATION */)
4261 {
4262   tree parameter_packs = NULL_TREE;
4263   struct find_parameter_pack_data ppd;
4264
4265   if (!processing_template_decl || !t || t == error_mark_node)
4266     return false;
4267
4268   if (TREE_CODE (t) == TYPE_DECL)
4269     t = TREE_TYPE (t);
4270
4271   ppd.parameter_packs = &parameter_packs;
4272   ppd.visited = new hash_set<tree>;
4273   ppd.type_pack_expansion_p = false;
4274   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4275   delete ppd.visited;
4276
4277   /* It's OK for a lambda to have an unexpanded parameter pack from the
4278      containing context, but do complain about unexpanded capture packs.  */
4279   if (current_class_type && LAMBDA_TYPE_P (current_class_type)
4280       && CLASSTYPE_TEMPLATE_INFO (current_class_type))
4281     for (; parameter_packs;
4282          parameter_packs = TREE_CHAIN (parameter_packs))
4283       {
4284         tree pack = TREE_VALUE (parameter_packs);
4285         if (is_capture_proxy (pack))
4286           break;
4287       }
4288
4289   if (parameter_packs)
4290     {
4291       if (loc == UNKNOWN_LOCATION)
4292         loc = cp_expr_loc_or_input_loc (t);
4293       error_at (loc, "parameter packs not expanded with %<...%>:");
4294       while (parameter_packs)
4295         {
4296           tree pack = TREE_VALUE (parameter_packs);
4297           tree name = NULL_TREE;
4298
4299           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
4300               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
4301             name = TYPE_NAME (pack);
4302           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
4303             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
4304           else if (TREE_CODE (pack) == CALL_EXPR)
4305             name = DECL_NAME (CALL_EXPR_FN (pack));
4306           else
4307             name = DECL_NAME (pack);
4308
4309           if (name)
4310             inform (loc, "        %qD", name);
4311           else
4312             inform (loc, "        %s", "<anonymous>");
4313
4314           parameter_packs = TREE_CHAIN (parameter_packs);
4315         }
4316
4317       return true;
4318     }
4319
4320   return false;
4321 }
4322
4323 /* Expand any parameter packs that occur in the template arguments in
4324    ARGS.  */
4325 tree
4326 expand_template_argument_pack (tree args)
4327 {
4328   if (args == error_mark_node)
4329     return error_mark_node;
4330
4331   tree result_args = NULL_TREE;
4332   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
4333   int num_result_args = -1;
4334   int non_default_args_count = -1;
4335
4336   /* First, determine if we need to expand anything, and the number of
4337      slots we'll need.  */
4338   for (in_arg = 0; in_arg < nargs; ++in_arg)
4339     {
4340       tree arg = TREE_VEC_ELT (args, in_arg);
4341       if (arg == NULL_TREE)
4342         return args;
4343       if (ARGUMENT_PACK_P (arg))
4344         {
4345           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
4346           if (num_result_args < 0)
4347             num_result_args = in_arg + num_packed;
4348           else
4349             num_result_args += num_packed;
4350         }
4351       else
4352         {
4353           if (num_result_args >= 0)
4354             num_result_args++;
4355         }
4356     }
4357
4358   /* If no expansion is necessary, we're done.  */
4359   if (num_result_args < 0)
4360     return args;
4361
4362   /* Expand arguments.  */
4363   result_args = make_tree_vec (num_result_args);
4364   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
4365     non_default_args_count =
4366       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
4367   for (in_arg = 0; in_arg < nargs; ++in_arg)
4368     {
4369       tree arg = TREE_VEC_ELT (args, in_arg);
4370       if (ARGUMENT_PACK_P (arg))
4371         {
4372           tree packed = ARGUMENT_PACK_ARGS (arg);
4373           int i, num_packed = TREE_VEC_LENGTH (packed);
4374           for (i = 0; i < num_packed; ++i, ++out_arg)
4375             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
4376           if (non_default_args_count > 0)
4377             non_default_args_count += num_packed - 1;
4378         }
4379       else
4380         {
4381           TREE_VEC_ELT (result_args, out_arg) = arg;
4382           ++out_arg;
4383         }
4384     }
4385   if (non_default_args_count >= 0)
4386     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
4387   return result_args;
4388 }
4389
4390 /* Checks if DECL shadows a template parameter.
4391
4392    [temp.local]: A template-parameter shall not be redeclared within its
4393    scope (including nested scopes).
4394
4395    Emits an error and returns TRUE if the DECL shadows a parameter,
4396    returns FALSE otherwise.  */
4397
4398 bool
4399 check_template_shadow (tree decl)
4400 {
4401   tree olddecl;
4402
4403   /* If we're not in a template, we can't possibly shadow a template
4404      parameter.  */
4405   if (!current_template_parms)
4406     return true;
4407
4408   /* Figure out what we're shadowing.  */
4409   decl = OVL_FIRST (decl);
4410   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
4411
4412   /* If there's no previous binding for this name, we're not shadowing
4413      anything, let alone a template parameter.  */
4414   if (!olddecl)
4415     return true;
4416
4417   /* If we're not shadowing a template parameter, we're done.  Note
4418      that OLDDECL might be an OVERLOAD (or perhaps even an
4419      ERROR_MARK), so we can't just blithely assume it to be a _DECL
4420      node.  */
4421   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
4422     return true;
4423
4424   /* We check for decl != olddecl to avoid bogus errors for using a
4425      name inside a class.  We check TPFI to avoid duplicate errors for
4426      inline member templates.  */
4427   if (decl == olddecl
4428       || (DECL_TEMPLATE_PARM_P (decl)
4429           && TEMPLATE_PARMS_FOR_INLINE (current_template_parms)))
4430     return true;
4431
4432   /* Don't complain about the injected class name, as we've already
4433      complained about the class itself.  */
4434   if (DECL_SELF_REFERENCE_P (decl))
4435     return false;
4436
4437   if (DECL_TEMPLATE_PARM_P (decl))
4438     error ("declaration of template parameter %q+D shadows "
4439            "template parameter", decl);
4440   else
4441     error ("declaration of %q+#D shadows template parameter", decl);
4442   inform (DECL_SOURCE_LOCATION (olddecl),
4443           "template parameter %qD declared here", olddecl);
4444   return false;
4445 }
4446
4447 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
4448    ORIG_LEVEL, DECL, and TYPE.  */
4449
4450 static tree
4451 build_template_parm_index (int index,
4452                            int level,
4453                            int orig_level,
4454                            tree decl,
4455                            tree type)
4456 {
4457   tree t = make_node (TEMPLATE_PARM_INDEX);
4458   TEMPLATE_PARM_IDX (t) = index;
4459   TEMPLATE_PARM_LEVEL (t) = level;
4460   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
4461   TEMPLATE_PARM_DECL (t) = decl;
4462   TREE_TYPE (t) = type;
4463   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
4464   TREE_READONLY (t) = TREE_READONLY (decl);
4465
4466   return t;
4467 }
4468
4469 /* Find the canonical type parameter for the given template type
4470    parameter.  Returns the canonical type parameter, which may be TYPE
4471    if no such parameter existed.  */
4472
4473 tree
4474 canonical_type_parameter (tree type)
4475 {
4476   int idx = TEMPLATE_TYPE_IDX (type);
4477
4478   gcc_assert (TREE_CODE (type) != TEMPLATE_TEMPLATE_PARM);
4479
4480   if (vec_safe_length (canonical_template_parms) <= (unsigned) idx)
4481     vec_safe_grow_cleared (canonical_template_parms, idx + 1, true);
4482
4483   for (tree list = (*canonical_template_parms)[idx];
4484        list; list = TREE_CHAIN (list))
4485     if (comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
4486       return TREE_VALUE (list);
4487
4488   (*canonical_template_parms)[idx]
4489     = tree_cons (NULL_TREE, type, (*canonical_template_parms)[idx]);
4490   return type;
4491 }
4492
4493 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
4494    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
4495    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
4496    new one is created.  */
4497
4498 static tree
4499 reduce_template_parm_level (tree index, tree type, int levels, tree args,
4500                             tsubst_flags_t complain)
4501 {
4502   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
4503       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
4504           != TEMPLATE_PARM_LEVEL (index) - levels)
4505       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
4506     {
4507       tree orig_decl = TEMPLATE_PARM_DECL (index);
4508
4509       tree decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
4510                               TREE_CODE (orig_decl), DECL_NAME (orig_decl),
4511                               type);
4512       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
4513       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
4514       DECL_VIRTUAL_P (decl) = DECL_VIRTUAL_P (orig_decl);
4515       DECL_ARTIFICIAL (decl) = 1;
4516       SET_DECL_TEMPLATE_PARM_P (decl);
4517
4518       tree tpi = build_template_parm_index (TEMPLATE_PARM_IDX (index),
4519                                             TEMPLATE_PARM_LEVEL (index) - levels,
4520                                             TEMPLATE_PARM_ORIG_LEVEL (index),
4521                                             decl, type);
4522       TEMPLATE_PARM_DESCENDANTS (index) = tpi;
4523       TEMPLATE_PARM_PARAMETER_PACK (tpi)
4524         = TEMPLATE_PARM_PARAMETER_PACK (index);
4525
4526       /* Template template parameters need this.  */
4527       tree inner = decl;
4528       if (TREE_CODE (decl) == TEMPLATE_DECL)
4529         {
4530           inner = build_decl (DECL_SOURCE_LOCATION (decl),
4531                               TYPE_DECL, DECL_NAME (decl), type);
4532           DECL_TEMPLATE_RESULT (decl) = inner;
4533           DECL_ARTIFICIAL (inner) = true;
4534           DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
4535             (DECL_TEMPLATE_PARMS (orig_decl), args, complain);
4536         }
4537
4538       /* Attach the TPI to the decl.  */
4539       if (TREE_CODE (inner) == TYPE_DECL)
4540         TEMPLATE_TYPE_PARM_INDEX (type) = tpi;
4541       else
4542         DECL_INITIAL (decl) = tpi;
4543     }
4544
4545   return TEMPLATE_PARM_DESCENDANTS (index);
4546 }
4547
4548 /* Process information from new template parameter PARM and append it
4549    to the LIST being built.  This new parameter is a non-type
4550    parameter iff IS_NON_TYPE is true. This new parameter is a
4551    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
4552    is in PARM_LOC.  */
4553
4554 tree
4555 process_template_parm (tree list, location_t parm_loc, tree parm,
4556                        bool is_non_type, bool is_parameter_pack)
4557 {
4558   gcc_assert (TREE_CODE (parm) == TREE_LIST);
4559   tree prev = NULL_TREE;
4560   int idx = 0;
4561
4562   if (list)
4563     {
4564       prev = tree_last (list);
4565
4566       tree p = TREE_VALUE (prev);
4567       if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
4568         idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
4569       else if (TREE_CODE (p) == PARM_DECL)
4570         idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
4571
4572       ++idx;
4573     }
4574
4575   tree decl = NULL_TREE;
4576   tree defval = TREE_PURPOSE (parm);
4577   tree constr = TREE_TYPE (parm);
4578
4579   if (is_non_type)
4580     {
4581       parm = TREE_VALUE (parm);
4582
4583       SET_DECL_TEMPLATE_PARM_P (parm);
4584
4585       if (TREE_TYPE (parm) != error_mark_node)
4586         {
4587           /* [temp.param]
4588
4589              The top-level cv-qualifiers on the template-parameter are
4590              ignored when determining its type.  */
4591           TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
4592           if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
4593             TREE_TYPE (parm) = error_mark_node;
4594           else if (uses_parameter_packs (TREE_TYPE (parm))
4595                    && !is_parameter_pack
4596                    /* If we're in a nested template parameter list, the template
4597                       template parameter could be a parameter pack.  */
4598                    && processing_template_parmlist == 1)
4599             {
4600               /* This template parameter is not a parameter pack, but it
4601                  should be. Complain about "bare" parameter packs.  */
4602               check_for_bare_parameter_packs (TREE_TYPE (parm));
4603
4604               /* Recover by calling this a parameter pack.  */
4605               is_parameter_pack = true;
4606             }
4607         }
4608
4609       /* A template parameter is not modifiable.  */
4610       TREE_CONSTANT (parm) = 1;
4611       TREE_READONLY (parm) = 1;
4612       decl = build_decl (parm_loc,
4613                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
4614       TREE_CONSTANT (decl) = 1;
4615       TREE_READONLY (decl) = 1;
4616       DECL_INITIAL (parm) = DECL_INITIAL (decl)
4617         = build_template_parm_index (idx, processing_template_decl,
4618                                      processing_template_decl,
4619                                      decl, TREE_TYPE (parm));
4620
4621       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4622         = is_parameter_pack;
4623     }
4624   else
4625     {
4626       tree t;
4627       parm = TREE_VALUE (TREE_VALUE (parm));
4628
4629       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
4630         {
4631           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
4632           /* This is for distinguishing between real templates and template
4633              template parameters */
4634           TREE_TYPE (parm) = t;
4635
4636           /* any_template_parm_r expects to be able to get the targs of a
4637              DECL_TEMPLATE_RESULT.  */
4638           tree result = DECL_TEMPLATE_RESULT (parm);
4639           TREE_TYPE (result) = t;
4640           tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (parm));
4641           tree tinfo = build_template_info (parm, args);
4642           retrofit_lang_decl (result);
4643           DECL_TEMPLATE_INFO (result) = tinfo;
4644
4645           decl = parm;
4646         }
4647       else
4648         {
4649           t = cxx_make_type (TEMPLATE_TYPE_PARM);
4650           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
4651           decl = build_decl (parm_loc,
4652                              TYPE_DECL, parm, t);
4653         }
4654
4655       TYPE_NAME (t) = decl;
4656       TYPE_STUB_DECL (t) = decl;
4657       parm = decl;
4658       TEMPLATE_TYPE_PARM_INDEX (t)
4659         = build_template_parm_index (idx, processing_template_decl,
4660                                      processing_template_decl,
4661                                      decl, TREE_TYPE (parm));
4662       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
4663       if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
4664         SET_TYPE_STRUCTURAL_EQUALITY (t);
4665       else
4666         TYPE_CANONICAL (t) = canonical_type_parameter (t);
4667     }
4668   DECL_ARTIFICIAL (decl) = 1;
4669   SET_DECL_TEMPLATE_PARM_P (decl);
4670
4671   /* Build requirements for the type/template parameter.
4672      This must be done after SET_DECL_TEMPLATE_PARM_P or
4673      process_template_parm could fail. */
4674   tree reqs = finish_shorthand_constraint (parm, constr);
4675
4676   decl = pushdecl (decl);
4677   if (!is_non_type)
4678     parm = decl;
4679
4680   /* Build the parameter node linking the parameter declaration,
4681      its default argument (if any), and its constraints (if any). */
4682   parm = build_tree_list (defval, parm);
4683   TEMPLATE_PARM_CONSTRAINTS (parm) = reqs;
4684
4685   if (prev)
4686     TREE_CHAIN (prev) = parm;
4687   else
4688     list = parm;
4689
4690   return list;
4691 }
4692
4693 /* The end of a template parameter list has been reached.  Process the
4694    tree list into a parameter vector, converting each parameter into a more
4695    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
4696    as PARM_DECLs.  */
4697
4698 tree
4699 end_template_parm_list (tree parms)
4700 {
4701   tree saved_parmlist = make_tree_vec (list_length (parms));
4702
4703   /* Pop the dummy parameter level and add the real one.  We do not
4704      morph the dummy parameter in place, as it might have been
4705      captured by a (nested) template-template-parm.  */
4706   current_template_parms = TREE_CHAIN (current_template_parms);
4707
4708   current_template_parms
4709     = tree_cons (size_int (processing_template_decl),
4710                  saved_parmlist, current_template_parms);
4711
4712   for (unsigned ix = 0; parms; ix++)
4713     {
4714       tree parm = parms;
4715       parms = TREE_CHAIN (parms);
4716       TREE_CHAIN (parm) = NULL_TREE;
4717
4718       TREE_VEC_ELT (saved_parmlist, ix) = parm;
4719     }
4720
4721   --processing_template_parmlist;
4722
4723   return saved_parmlist;
4724 }
4725
4726 // Explicitly indicate the end of the template parameter list. We assume
4727 // that the current template parameters have been constructed and/or
4728 // managed explicitly, as when creating new template template parameters
4729 // from a shorthand constraint.
4730 void
4731 end_template_parm_list ()
4732 {
4733   --processing_template_parmlist;
4734 }
4735
4736 /* end_template_decl is called after a template declaration is seen.  */
4737
4738 void
4739 end_template_decl (void)
4740 {
4741   reset_specialization ();
4742
4743   if (! processing_template_decl)
4744     return;
4745
4746   /* This matches the pushlevel in begin_template_parm_list.  */
4747   finish_scope ();
4748
4749   --processing_template_decl;
4750   current_template_parms = TREE_CHAIN (current_template_parms);
4751 }
4752
4753 /* Takes a TEMPLATE_PARM_P or DECL_TEMPLATE_PARM_P node or a TREE_LIST
4754    thereof, and converts it into an argument suitable to be passed to
4755    the type substitution functions.  Note that if the TREE_LIST contains
4756    an error_mark node, the returned argument is error_mark_node.  */
4757
4758 tree
4759 template_parm_to_arg (tree t)
4760 {
4761   if (!t)
4762     return NULL_TREE;
4763
4764   if (TREE_CODE (t) == TREE_LIST)
4765     t = TREE_VALUE (t);
4766
4767   if (error_operand_p (t))
4768     return error_mark_node;
4769
4770   if (DECL_P (t) && DECL_TEMPLATE_PARM_P (t))
4771     {
4772       if (TREE_CODE (t) == TYPE_DECL
4773           || TREE_CODE (t) == TEMPLATE_DECL)
4774         t = TREE_TYPE (t);
4775       else
4776         t = DECL_INITIAL (t);
4777     }
4778
4779   gcc_assert (TEMPLATE_PARM_P (t));
4780
4781   if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
4782       || TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
4783     {
4784       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
4785         {
4786           /* Turn this argument into a TYPE_ARGUMENT_PACK
4787              with a single element, which expands T.  */
4788           tree vec = make_tree_vec (1);
4789           if (CHECKING_P)
4790             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4791
4792           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4793
4794           t = cxx_make_type (TYPE_ARGUMENT_PACK);
4795           SET_ARGUMENT_PACK_ARGS (t, vec);
4796         }
4797     }
4798   else
4799     {
4800       if (TEMPLATE_PARM_PARAMETER_PACK (t))
4801         {
4802           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
4803              with a single element, which expands T.  */
4804           tree vec = make_tree_vec (1);
4805           if (CHECKING_P)
4806             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4807
4808           t = convert_from_reference (t);
4809           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4810
4811           t  = make_node (NONTYPE_ARGUMENT_PACK);
4812           SET_ARGUMENT_PACK_ARGS (t, vec);
4813         }
4814       else
4815         t = convert_from_reference (t);
4816     }
4817   return t;
4818 }
4819
4820 /* Given a single level of template parameters (a TREE_VEC), return it
4821    as a set of template arguments.  */
4822
4823 tree
4824 template_parms_level_to_args (tree parms)
4825 {
4826   tree a = copy_node (parms);
4827   TREE_TYPE (a) = NULL_TREE;
4828   for (int i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4829     TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4830
4831   if (CHECKING_P)
4832     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4833
4834   return a;
4835 }
4836
4837 /* Given a set of template parameters, return them as a set of template
4838    arguments.  The template parameters are represented as a TREE_VEC, in
4839    the form documented in cp-tree.h for template arguments.  */
4840
4841 tree
4842 template_parms_to_args (tree parms)
4843 {
4844   tree header;
4845   tree args = NULL_TREE;
4846   int length = TMPL_PARMS_DEPTH (parms);
4847   int l = length;
4848
4849   /* If there is only one level of template parameters, we do not
4850      create a TREE_VEC of TREE_VECs.  Instead, we return a single
4851      TREE_VEC containing the arguments.  */
4852   if (length > 1)
4853     args = make_tree_vec (length);
4854
4855   for (header = parms; header; header = TREE_CHAIN (header))
4856     {
4857       tree a = template_parms_level_to_args (TREE_VALUE (header));
4858
4859       if (length > 1)
4860         TREE_VEC_ELT (args, --l) = a;
4861       else
4862         args = a;
4863     }
4864
4865   return args;
4866 }
4867
4868 /* Within the declaration of a template, return the currently active
4869    template parameters as an argument TREE_VEC.  */
4870
4871 static tree
4872 current_template_args (void)
4873 {
4874   return template_parms_to_args (current_template_parms);
4875 }
4876
4877 /* Return the fully generic arguments for of TMPL, i.e. what
4878    current_template_args would be while parsing it.  */
4879
4880 tree
4881 generic_targs_for (tree tmpl)
4882 {
4883   if (tmpl == NULL_TREE)
4884     return NULL_TREE;
4885   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
4886       || DECL_TEMPLATE_SPECIALIZATION (tmpl))
4887     /* DECL_TEMPLATE_RESULT doesn't have the arguments we want.  For a template
4888        template parameter, it has no TEMPLATE_INFO; for a partial
4889        specialization, it has the arguments for the primary template, and we
4890        want the arguments for the partial specialization.  */;
4891   else if (tree result = DECL_TEMPLATE_RESULT (tmpl))
4892     if (tree ti = get_template_info (result))
4893       return TI_ARGS (ti);
4894   return template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl));
4895 }
4896
4897 /* Update the declared TYPE by doing any lookups which were thought to be
4898    dependent, but are not now that we know the SCOPE of the declarator.  */
4899
4900 tree
4901 maybe_update_decl_type (tree orig_type, tree scope)
4902 {
4903   tree type = orig_type;
4904
4905   if (type == NULL_TREE)
4906     return type;
4907
4908   if (TREE_CODE (orig_type) == TYPE_DECL)
4909     type = TREE_TYPE (type);
4910
4911   if (scope && TYPE_P (scope) && dependent_type_p (scope)
4912       && dependent_type_p (type)
4913       /* Don't bother building up the args in this case.  */
4914       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4915     {
4916       /* tsubst in the args corresponding to the template parameters,
4917          including auto if present.  Most things will be unchanged, but
4918          make_typename_type and tsubst_qualified_id will resolve
4919          TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
4920       tree args = current_template_args ();
4921       tree auto_node = type_uses_auto (type);
4922       tree pushed;
4923       if (auto_node)
4924         {
4925           tree auto_vec = make_tree_vec (1);
4926           TREE_VEC_ELT (auto_vec, 0) = auto_node;
4927           args = add_to_template_args (args, auto_vec);
4928         }
4929       pushed = push_scope (scope);
4930       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4931       if (pushed)
4932         pop_scope (scope);
4933     }
4934
4935   if (type == error_mark_node)
4936     return orig_type;
4937
4938   if (TREE_CODE (orig_type) == TYPE_DECL)
4939     {
4940       if (same_type_p (type, TREE_TYPE (orig_type)))
4941         type = orig_type;
4942       else
4943         type = TYPE_NAME (type);
4944     }
4945   return type;
4946 }
4947
4948 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4949    template PARMS and constraints, CONSTR.  If MEMBER_TEMPLATE_P is true,
4950    the new  template is a member template. */
4951
4952 static tree
4953 build_template_decl (tree decl, tree parms, bool member_template_p)
4954 {
4955   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4956   SET_DECL_LANGUAGE (tmpl, DECL_LANGUAGE (decl));
4957   DECL_TEMPLATE_PARMS (tmpl) = parms;
4958   DECL_TEMPLATE_RESULT (tmpl) = decl;
4959   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4960   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4961   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
4962   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4963
4964   /* Propagate module information from the decl.  */
4965   DECL_MODULE_EXPORT_P (tmpl) = DECL_MODULE_EXPORT_P (decl);
4966
4967   return tmpl;
4968 }
4969
4970 struct template_parm_data
4971 {
4972   /* The level of the template parameters we are currently
4973      processing.  */
4974   int level;
4975
4976   /* The index of the specialization argument we are currently
4977      processing.  */
4978   int current_arg;
4979
4980   /* An array whose size is the number of template parameters.  The
4981      elements are nonzero if the parameter has been used in any one
4982      of the arguments processed so far.  */
4983   int* parms;
4984
4985   /* An array whose size is the number of template arguments.  The
4986      elements are nonzero if the argument makes use of template
4987      parameters of this level.  */
4988   int* arg_uses_template_parms;
4989 };
4990
4991 /* Subroutine of push_template_decl used to see if each template
4992    parameter in a partial specialization is used in the explicit
4993    argument list.  If T is of the LEVEL given in DATA (which is
4994    treated as a template_parm_data*), then DATA->PARMS is marked
4995    appropriately.  */
4996
4997 static int
4998 mark_template_parm (tree t, void* data)
4999 {
5000   int level;
5001   int idx;
5002   struct template_parm_data* tpd = (struct template_parm_data*) data;
5003
5004   template_parm_level_and_index (t, &level, &idx);
5005
5006   if (level == tpd->level)
5007     {
5008       tpd->parms[idx] = 1;
5009       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
5010     }
5011
5012   /* In C++17 the type of a non-type argument is a deduced context.  */
5013   if (cxx_dialect >= cxx17
5014       && TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5015     for_each_template_parm (TREE_TYPE (t),
5016                             &mark_template_parm,
5017                             data,
5018                             NULL,
5019                             /*include_nondeduced_p=*/false);
5020
5021   /* Return zero so that for_each_template_parm will continue the
5022      traversal of the tree; we want to mark *every* template parm.  */
5023   return 0;
5024 }
5025
5026 /* Process the partial specialization DECL.  */
5027
5028 static tree
5029 process_partial_specialization (tree decl)
5030 {
5031   tree type = TREE_TYPE (decl);
5032   tree tinfo = get_template_info (decl);
5033   tree maintmpl = TI_TEMPLATE (tinfo);
5034   tree specargs = TI_ARGS (tinfo);
5035   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
5036   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
5037   tree inner_parms;
5038   tree inst;
5039   int nargs = TREE_VEC_LENGTH (inner_args);
5040   int ntparms;
5041   int  i;
5042   bool did_error_intro = false;
5043   struct template_parm_data tpd;
5044   struct template_parm_data tpd2;
5045
5046   gcc_assert (current_template_parms);
5047
5048   /* A concept cannot be specialized.  */
5049   if (flag_concepts && variable_concept_p (maintmpl))
5050     {
5051       error ("specialization of variable concept %q#D", maintmpl);
5052       return error_mark_node;
5053     }
5054
5055   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
5056   ntparms = TREE_VEC_LENGTH (inner_parms);
5057
5058   /* We check that each of the template parameters given in the
5059      partial specialization is used in the argument list to the
5060      specialization.  For example:
5061
5062        template <class T> struct S;
5063        template <class T> struct S<T*>;
5064
5065      The second declaration is OK because `T*' uses the template
5066      parameter T, whereas
5067
5068        template <class T> struct S<int>;
5069
5070      is no good.  Even trickier is:
5071
5072        template <class T>
5073        struct S1
5074        {
5075           template <class U>
5076           struct S2;
5077           template <class U>
5078           struct S2<T>;
5079        };
5080
5081      The S2<T> declaration is actually invalid; it is a
5082      full-specialization.  Of course,
5083
5084           template <class U>
5085           struct S2<T (*)(U)>;
5086
5087      or some such would have been OK.  */
5088   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
5089   tpd.parms = XALLOCAVEC (int, ntparms);
5090   memset (tpd.parms, 0, sizeof (int) * ntparms);
5091
5092   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5093   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
5094   for (i = 0; i < nargs; ++i)
5095     {
5096       tpd.current_arg = i;
5097       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
5098                               &mark_template_parm,
5099                               &tpd,
5100                               NULL,
5101                               /*include_nondeduced_p=*/false);
5102     }
5103   for (i = 0; i < ntparms; ++i)
5104     if (tpd.parms[i] == 0)
5105       {
5106         /* One of the template parms was not used in a deduced context in the
5107            specialization.  */
5108         if (!did_error_intro)
5109           {
5110             error ("template parameters not deducible in "
5111                    "partial specialization:");
5112             did_error_intro = true;
5113           }
5114
5115         inform (input_location, "        %qD",
5116                 TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
5117       }
5118
5119   if (did_error_intro)
5120     return error_mark_node;
5121
5122   /* [temp.class.spec]
5123
5124      The argument list of the specialization shall not be identical to
5125      the implicit argument list of the primary template.  */
5126   tree main_args
5127     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
5128   if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args))
5129       && (!flag_concepts
5130           || !strictly_subsumes (current_template_constraints (), maintmpl)))
5131     {
5132       if (!flag_concepts)
5133         error ("partial specialization %q+D does not specialize "
5134                "any template arguments; to define the primary template, "
5135                "remove the template argument list", decl);
5136       else
5137         error ("partial specialization %q+D does not specialize any "
5138                "template arguments and is not more constrained than "
5139                "the primary template; to define the primary template, "
5140                "remove the template argument list", decl);
5141       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5142     }
5143
5144   /* A partial specialization that replaces multiple parameters of the
5145      primary template with a pack expansion is less specialized for those
5146      parameters.  */
5147   if (nargs < DECL_NTPARMS (maintmpl))
5148     {
5149       error ("partial specialization is not more specialized than the "
5150              "primary template because it replaces multiple parameters "
5151              "with a pack expansion");
5152       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5153       /* Avoid crash in process_partial_specialization.  */
5154       return decl;
5155     }
5156
5157   else if (nargs > DECL_NTPARMS (maintmpl))
5158     {
5159       error ("too many arguments for partial specialization %qT", type);
5160       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5161       /* Avoid crash below.  */
5162       return decl;
5163     }
5164
5165   /* If we aren't in a dependent class, we can actually try deduction.  */
5166   else if (tpd.level == 1
5167            /* FIXME we should be able to handle a partial specialization of a
5168               partial instantiation, but currently we can't (c++/41727).  */
5169            && TMPL_ARGS_DEPTH (specargs) == 1
5170            && !get_partial_spec_bindings (maintmpl, maintmpl, specargs))
5171     {
5172       auto_diagnostic_group d;
5173       if (permerror (input_location, "partial specialization %qD is not "
5174                      "more specialized than", decl))
5175         inform (DECL_SOURCE_LOCATION (maintmpl), "primary template %qD",
5176                 maintmpl);
5177     }
5178
5179   /* [temp.class.spec]
5180
5181      A partially specialized non-type argument expression shall not
5182      involve template parameters of the partial specialization except
5183      when the argument expression is a simple identifier.
5184
5185      The type of a template parameter corresponding to a specialized
5186      non-type argument shall not be dependent on a parameter of the
5187      specialization.
5188
5189      Also, we verify that pack expansions only occur at the
5190      end of the argument list.  */
5191   tpd2.parms = 0;
5192   for (i = 0; i < nargs; ++i)
5193     {
5194       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
5195       tree arg = TREE_VEC_ELT (inner_args, i);
5196       tree packed_args = NULL_TREE;
5197       int j, len = 1;
5198
5199       if (ARGUMENT_PACK_P (arg))
5200         {
5201           /* Extract the arguments from the argument pack. We'll be
5202              iterating over these in the following loop.  */
5203           packed_args = ARGUMENT_PACK_ARGS (arg);
5204           len = TREE_VEC_LENGTH (packed_args);
5205         }
5206
5207       for (j = 0; j < len; j++)
5208         {
5209           if (packed_args)
5210             /* Get the Jth argument in the parameter pack.  */
5211             arg = TREE_VEC_ELT (packed_args, j);
5212
5213           if (PACK_EXPANSION_P (arg))
5214             {
5215               /* Pack expansions must come at the end of the
5216                  argument list.  */
5217               if ((packed_args && j < len - 1)
5218                   || (!packed_args && i < nargs - 1))
5219                 {
5220                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5221                     error ("parameter pack argument %qE must be at the "
5222                            "end of the template argument list", arg);
5223                   else
5224                     error ("parameter pack argument %qT must be at the "
5225                            "end of the template argument list", arg);
5226                 }
5227             }
5228
5229           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5230             /* We only care about the pattern.  */
5231             arg = PACK_EXPANSION_PATTERN (arg);
5232
5233           if (/* These first two lines are the `non-type' bit.  */
5234               !TYPE_P (arg)
5235               && TREE_CODE (arg) != TEMPLATE_DECL
5236               /* This next two lines are the `argument expression is not just a
5237                  simple identifier' condition and also the `specialized
5238                  non-type argument' bit.  */
5239               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
5240               && !((REFERENCE_REF_P (arg)
5241                     || TREE_CODE (arg) == VIEW_CONVERT_EXPR)
5242                    && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
5243             {
5244               if ((!packed_args && tpd.arg_uses_template_parms[i])
5245                   || (packed_args && uses_template_parms (arg)))
5246                 error_at (cp_expr_loc_or_input_loc (arg),
5247                           "template argument %qE involves template "
5248                           "parameter(s)", arg);
5249               else 
5250                 {
5251                   /* Look at the corresponding template parameter,
5252                      marking which template parameters its type depends
5253                      upon.  */
5254                   tree type = TREE_TYPE (parm);
5255
5256                   if (!tpd2.parms)
5257                     {
5258                       /* We haven't yet initialized TPD2.  Do so now.  */
5259                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5260                       /* The number of parameters here is the number in the
5261                          main template, which, as checked in the assertion
5262                          above, is NARGS.  */
5263                       tpd2.parms = XALLOCAVEC (int, nargs);
5264                       tpd2.level = 
5265                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
5266                     }
5267
5268                   /* Mark the template parameters.  But this time, we're
5269                      looking for the template parameters of the main
5270                      template, not in the specialization.  */
5271                   tpd2.current_arg = i;
5272                   tpd2.arg_uses_template_parms[i] = 0;
5273                   memset (tpd2.parms, 0, sizeof (int) * nargs);
5274                   for_each_template_parm (type,
5275                                           &mark_template_parm,
5276                                           &tpd2,
5277                                           NULL,
5278                                           /*include_nondeduced_p=*/false);
5279
5280                   if (tpd2.arg_uses_template_parms [i])
5281                     {
5282                       /* The type depended on some template parameters.
5283                          If they are fully specialized in the
5284                          specialization, that's OK.  */
5285                       int j;
5286                       int count = 0;
5287                       for (j = 0; j < nargs; ++j)
5288                         if (tpd2.parms[j] != 0
5289                             && tpd.arg_uses_template_parms [j])
5290                           ++count;
5291                       if (count != 0)
5292                         error_n (input_location, count,
5293                                  "type %qT of template argument %qE depends "
5294                                  "on a template parameter",
5295                                  "type %qT of template argument %qE depends "
5296                                  "on template parameters",
5297                                  type,
5298                                  arg);
5299                     }
5300                 }
5301             }
5302         }
5303     }
5304
5305   /* We should only get here once.  */
5306   if (TREE_CODE (decl) == TYPE_DECL)
5307     gcc_assert (!COMPLETE_TYPE_P (type));
5308
5309   // Build the template decl.
5310   tree tmpl = build_template_decl (decl, current_template_parms,
5311                                    DECL_MEMBER_TEMPLATE_P (maintmpl));
5312   SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5313   DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
5314   DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
5315
5316   /* Give template template parms a DECL_CONTEXT of the template
5317      for which they are a parameter.  */
5318   for (i = 0; i < ntparms; ++i)
5319     {
5320       tree parm = TREE_VALUE (TREE_VEC_ELT (inner_parms, i));
5321       if (TREE_CODE (parm) == TEMPLATE_DECL)
5322         DECL_CONTEXT (parm) = tmpl;
5323     }
5324
5325   if (VAR_P (decl))
5326     /* We didn't register this in check_explicit_specialization so we could
5327        wait until the constraints were set.  */
5328     decl = register_specialization (decl, maintmpl, specargs, false, 0);
5329   else
5330     associate_classtype_constraints (type);
5331
5332   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
5333     = tree_cons (specargs, tmpl,
5334                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
5335   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
5336
5337   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
5338        inst = TREE_CHAIN (inst))
5339     {
5340       tree instance = TREE_VALUE (inst);
5341       if (TYPE_P (instance)
5342           ? (COMPLETE_TYPE_P (instance)
5343              && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
5344           : DECL_TEMPLATE_INSTANTIATION (instance))
5345         {
5346           tree spec = most_specialized_partial_spec (instance, tf_none);
5347           tree inst_decl = (DECL_P (instance)
5348                             ? instance : TYPE_NAME (instance));
5349           if (!spec)
5350             /* OK */;
5351           else if (spec == error_mark_node)
5352             permerror (input_location,
5353                        "declaration of %qD ambiguates earlier template "
5354                        "instantiation for %qD", decl, inst_decl);
5355           else if (TREE_VALUE (spec) == tmpl)
5356             permerror (input_location,
5357                        "partial specialization of %qD after instantiation "
5358                        "of %qD", decl, inst_decl);
5359         }
5360     }
5361
5362   return decl;
5363 }
5364
5365 /* PARM is a template parameter of some form; return the corresponding
5366    TEMPLATE_PARM_INDEX.  */
5367
5368 static tree
5369 get_template_parm_index (tree parm)
5370 {
5371   if (TREE_CODE (parm) == PARM_DECL
5372       || TREE_CODE (parm) == CONST_DECL)
5373     parm = DECL_INITIAL (parm);
5374   else if (TREE_CODE (parm) == TYPE_DECL
5375            || TREE_CODE (parm) == TEMPLATE_DECL)
5376     parm = TREE_TYPE (parm);
5377   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
5378       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM
5379       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
5380     parm = TEMPLATE_TYPE_PARM_INDEX (parm);
5381   gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
5382   return parm;
5383 }
5384
5385 /* Subroutine of fixed_parameter_pack_p below.  Look for any template
5386    parameter packs used by the template parameter PARM.  */
5387
5388 static void
5389 fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
5390 {
5391   /* A type parm can't refer to another parm.  */
5392   if (TREE_CODE (parm) == TYPE_DECL || parm == error_mark_node)
5393     return;
5394   else if (TREE_CODE (parm) == PARM_DECL)
5395     {
5396       cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
5397                     ppd, ppd->visited);
5398       return;
5399     }
5400
5401   gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
5402
5403   tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
5404   for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
5405     {
5406       tree p = TREE_VALUE (TREE_VEC_ELT (vec, i));
5407       if (template_parameter_pack_p (p))
5408         /* Any packs in the type are expanded by this parameter.  */;
5409       else
5410         fixed_parameter_pack_p_1 (p, ppd);
5411     }
5412 }
5413
5414 /* PARM is a template parameter pack.  Return any parameter packs used in
5415    its type or the type of any of its template parameters.  If there are
5416    any such packs, it will be instantiated into a fixed template parameter
5417    list by partial instantiation rather than be fully deduced.  */
5418
5419 tree
5420 fixed_parameter_pack_p (tree parm)
5421 {
5422   /* This can only be true in a member template.  */
5423   if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
5424     return NULL_TREE;
5425   /* This can only be true for a parameter pack.  */
5426   if (!template_parameter_pack_p (parm))
5427     return NULL_TREE;
5428   /* A type parm can't refer to another parm.  */
5429   if (TREE_CODE (parm) == TYPE_DECL)
5430     return NULL_TREE;
5431
5432   tree parameter_packs = NULL_TREE;
5433   struct find_parameter_pack_data ppd;
5434   ppd.parameter_packs = &parameter_packs;
5435   ppd.visited = new hash_set<tree>;
5436   ppd.type_pack_expansion_p = false;
5437
5438   fixed_parameter_pack_p_1 (parm, &ppd);
5439
5440   delete ppd.visited;
5441   return parameter_packs;
5442 }
5443
5444 /* Check that a template declaration's use of default arguments and
5445    parameter packs is not invalid.  Here, PARMS are the template
5446    parameters.  IS_PRIMARY is true if DECL is the thing declared by
5447    a primary template.  IS_PARTIAL is true if DECL is a partial
5448    specialization.
5449
5450    IS_FRIEND_DECL is nonzero if DECL is either a non-defining friend
5451    function template declaration or a friend class template
5452    declaration.  In the function case, 1 indicates a declaration, 2
5453    indicates a redeclaration.  When IS_FRIEND_DECL=2, no errors are
5454    emitted for extraneous default arguments.
5455
5456    Returns TRUE if there were no errors found, FALSE otherwise. */
5457
5458 bool
5459 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
5460                          bool is_partial, int is_friend_decl)
5461 {
5462   const char *msg;
5463   int last_level_to_check;
5464   tree parm_level;
5465   bool no_errors = true;
5466
5467   /* [temp.param]
5468
5469      A default template-argument shall not be specified in a
5470      function template declaration or a function template definition, nor
5471      in the template-parameter-list of the definition of a member of a
5472      class template.  */
5473
5474   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
5475       || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_DECL_P (decl)))
5476     /* You can't have a function template declaration in a local
5477        scope, nor you can you define a member of a class template in a
5478        local scope.  */
5479     return true;
5480
5481   if ((TREE_CODE (decl) == TYPE_DECL
5482        && TREE_TYPE (decl)
5483        && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5484       || (TREE_CODE (decl) == FUNCTION_DECL
5485           && LAMBDA_FUNCTION_P (decl)))
5486     /* A lambda doesn't have an explicit declaration; don't complain
5487        about the parms of the enclosing class.  */
5488     return true;
5489
5490   if (current_class_type
5491       && !TYPE_BEING_DEFINED (current_class_type)
5492       && DECL_LANG_SPECIFIC (decl)
5493       && DECL_DECLARES_FUNCTION_P (decl)
5494       /* If this is either a friend defined in the scope of the class
5495          or a member function.  */
5496       && (DECL_FUNCTION_MEMBER_P (decl)
5497           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
5498           : DECL_FRIEND_CONTEXT (decl)
5499           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
5500           : false)
5501       /* And, if it was a member function, it really was defined in
5502          the scope of the class.  */
5503       && (!DECL_FUNCTION_MEMBER_P (decl)
5504           || DECL_INITIALIZED_IN_CLASS_P (decl)))
5505     /* We already checked these parameters when the template was
5506        declared, so there's no need to do it again now.  This function
5507        was defined in class scope, but we're processing its body now
5508        that the class is complete.  */
5509     return true;
5510
5511   /* Core issue 226 (C++0x only): the following only applies to class
5512      templates.  */
5513   if (is_primary
5514       && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
5515     {
5516       /* [temp.param]
5517
5518          If a template-parameter has a default template-argument, all
5519          subsequent template-parameters shall have a default
5520          template-argument supplied.  */
5521       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
5522         {
5523           tree inner_parms = TREE_VALUE (parm_level);
5524           int ntparms = TREE_VEC_LENGTH (inner_parms);
5525           int seen_def_arg_p = 0;
5526           int i;
5527
5528           for (i = 0; i < ntparms; ++i)
5529             {
5530               tree parm = TREE_VEC_ELT (inner_parms, i);
5531
5532               if (parm == error_mark_node)
5533                 continue;
5534
5535               if (TREE_PURPOSE (parm))
5536                 seen_def_arg_p = 1;
5537               else if (seen_def_arg_p
5538                        && !template_parameter_pack_p (TREE_VALUE (parm)))
5539                 {
5540                   error ("no default argument for %qD", TREE_VALUE (parm));
5541                   /* For better subsequent error-recovery, we indicate that
5542                      there should have been a default argument.  */
5543                   TREE_PURPOSE (parm) = error_mark_node;
5544                   no_errors = false;
5545                 }
5546               else if (!is_partial
5547                        && !is_friend_decl
5548                        /* Don't complain about an enclosing partial
5549                           specialization.  */
5550                        && parm_level == parms
5551                        && (TREE_CODE (decl) == TYPE_DECL || VAR_P (decl))
5552                        && i < ntparms - 1
5553                        && template_parameter_pack_p (TREE_VALUE (parm))
5554                        /* A fixed parameter pack will be partially
5555                           instantiated into a fixed length list.  */
5556                        && !fixed_parameter_pack_p (TREE_VALUE (parm)))
5557                 {
5558                   /* A primary class template, primary variable template
5559                      (DR 2032), or alias template can only have one
5560                      parameter pack, at the end of the template
5561                      parameter list.  */
5562
5563                   error ("parameter pack %q+D must be at the end of the"
5564                          " template parameter list", TREE_VALUE (parm));
5565
5566                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
5567                     = error_mark_node;
5568                   no_errors = false;
5569                 }
5570             }
5571         }
5572     }
5573
5574   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
5575       || is_partial
5576       || !is_primary
5577       || is_friend_decl)
5578     /* For an ordinary class template, default template arguments are
5579        allowed at the innermost level, e.g.:
5580          template <class T = int>
5581          struct S {};
5582        but, in a partial specialization, they're not allowed even
5583        there, as we have in [temp.class.spec]:
5584
5585          The template parameter list of a specialization shall not
5586          contain default template argument values.
5587
5588        So, for a partial specialization, or for a function template
5589        (in C++98/C++03), we look at all of them.  */
5590     ;
5591   else
5592     /* But, for a primary class template that is not a partial
5593        specialization we look at all template parameters except the
5594        innermost ones.  */
5595     parms = TREE_CHAIN (parms);
5596
5597   /* Figure out what error message to issue.  */
5598   if (is_friend_decl == 2)
5599     msg = G_("default template arguments may not be used in function template "
5600              "friend re-declaration");
5601   else if (is_friend_decl)
5602     msg = G_("default template arguments may not be used in template "
5603              "friend declarations");
5604   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
5605     msg = G_("default template arguments may not be used in function templates "
5606              "without %<-std=c++11%> or %<-std=gnu++11%>");
5607   else if (is_partial)
5608     msg = G_("default template arguments may not be used in "
5609              "partial specializations");
5610   else if (current_class_type && CLASSTYPE_IS_TEMPLATE (current_class_type))
5611     msg = G_("default argument for template parameter for class enclosing %qD");
5612   else
5613     /* Per [temp.param]/9, "A default template-argument shall not be
5614        specified in the template-parameter-lists of the definition of
5615        a member of a class template that appears outside of the member's
5616        class.", thus if we aren't handling a member of a class template
5617        there is no need to examine the parameters.  */
5618     return true;
5619
5620   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
5621     /* If we're inside a class definition, there's no need to
5622        examine the parameters to the class itself.  On the one
5623        hand, they will be checked when the class is defined, and,
5624        on the other, default arguments are valid in things like:
5625          template <class T = double>
5626          struct S { template <class U> void f(U); };
5627        Here the default argument for `S' has no bearing on the
5628        declaration of `f'.  */
5629     last_level_to_check = template_class_depth (current_class_type) + 1;
5630   else
5631     /* Check everything.  */
5632     last_level_to_check = 0;
5633
5634   for (parm_level = parms;
5635        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
5636        parm_level = TREE_CHAIN (parm_level))
5637     {
5638       tree inner_parms = TREE_VALUE (parm_level);
5639       int i;
5640       int ntparms;
5641
5642       ntparms = TREE_VEC_LENGTH (inner_parms);
5643       for (i = 0; i < ntparms; ++i)
5644         {
5645           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
5646             continue;
5647
5648           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
5649             {
5650               if (msg)
5651                 {
5652                   no_errors = false;
5653                   if (is_friend_decl == 2)
5654                     return no_errors;
5655
5656                   error (msg, decl);
5657                   msg = 0;
5658                 }
5659
5660               /* Clear out the default argument so that we are not
5661                  confused later.  */
5662               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
5663             }
5664         }
5665
5666       /* At this point, if we're still interested in issuing messages,
5667          they must apply to classes surrounding the object declared.  */
5668       if (msg)
5669         msg = G_("default argument for template parameter for class "
5670                  "enclosing %qD");
5671     }
5672
5673   return no_errors;
5674 }
5675
5676 /* Worker for push_template_decl_real, called via
5677    for_each_template_parm.  DATA is really an int, indicating the
5678    level of the parameters we are interested in.  If T is a template
5679    parameter of that level, return nonzero.  */
5680
5681 static int
5682 template_parm_this_level_p (tree t, void* data)
5683 {
5684   int this_level = *(int *)data;
5685   int level;
5686
5687   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5688     level = TEMPLATE_PARM_LEVEL (t);
5689   else
5690     level = TEMPLATE_TYPE_LEVEL (t);
5691   return level == this_level;
5692 }
5693
5694 /* Worker for uses_outer_template_parms, called via for_each_template_parm.
5695    DATA is really an int, indicating the innermost outer level of parameters.
5696    If T is a template parameter of that level or further out, return
5697    nonzero.  */
5698
5699 static int
5700 template_parm_outer_level (tree t, void *data)
5701 {
5702   int this_level = *(int *)data;
5703   int level;
5704
5705   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5706     level = TEMPLATE_PARM_LEVEL (t);
5707   else
5708     level = TEMPLATE_TYPE_LEVEL (t);
5709   return level <= this_level;
5710 }
5711
5712 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
5713    parameters given by current_template_args, or reuses a
5714    previously existing one, if appropriate.  Returns the DECL, or an
5715    equivalent one, if it is replaced via a call to duplicate_decls.
5716
5717    If IS_FRIEND is true, DECL is a friend declaration.  */
5718
5719 tree
5720 push_template_decl (tree decl, bool is_friend)
5721 {
5722   if (decl == error_mark_node || !current_template_parms)
5723     return error_mark_node;
5724
5725   /* See if this is a partial specialization.  */
5726   bool is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
5727                       && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
5728                       && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
5729                      || (VAR_P (decl)
5730                          && DECL_LANG_SPECIFIC (decl)
5731                          && DECL_TEMPLATE_SPECIALIZATION (decl)
5732                          && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
5733
5734   /* No surprising friend functions.  */
5735   gcc_checking_assert (is_friend
5736                        || !(TREE_CODE (decl) == FUNCTION_DECL
5737                             && DECL_UNIQUE_FRIEND_P (decl)));
5738
5739   tree ctx;
5740   if (is_friend)
5741     /* For a friend, we want the context of the friend, not
5742        the type of which it is a friend.  */
5743     ctx = CP_DECL_CONTEXT (decl);
5744   else if (CP_DECL_CONTEXT (decl)
5745            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
5746     /* In the case of a virtual function, we want the class in which
5747        it is defined.  */
5748     ctx = CP_DECL_CONTEXT (decl);
5749   else
5750     /* Otherwise, if we're currently defining some class, the DECL
5751        is assumed to be a member of the class.  */
5752     ctx = current_scope ();
5753
5754   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
5755     ctx = NULL_TREE;
5756
5757   if (!DECL_CONTEXT (decl))
5758     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5759
5760   /* See if this is a primary template.  */
5761   bool is_primary = false;
5762   if (is_friend && ctx
5763       && uses_template_parms_level (ctx, processing_template_decl))
5764     /* A friend template that specifies a class context, i.e.
5765          template <typename T> friend void A<T>::f();
5766        is not primary.  */
5767     ;
5768   else if (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5769     /* Lambdas are not primary.  */
5770     ;
5771   else
5772     is_primary = template_parm_scope_p ();
5773
5774   /* True if the template is a member template, in the sense of
5775      [temp.mem].  */
5776   bool member_template_p = false;
5777
5778   if (is_primary)
5779     {
5780       warning (OPT_Wtemplates, "template %qD declared", decl);
5781
5782       if (DECL_CLASS_SCOPE_P (decl))
5783         member_template_p = true;
5784
5785       if (TREE_CODE (decl) == TYPE_DECL
5786           && IDENTIFIER_ANON_P (DECL_NAME (decl)))
5787         {
5788           error ("template class without a name");
5789           return error_mark_node;
5790         }
5791       else if (TREE_CODE (decl) == FUNCTION_DECL)
5792         {
5793           if (member_template_p)
5794             {
5795               if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
5796                 error ("member template %qD may not have virt-specifiers", decl);
5797             }
5798           if (DECL_DESTRUCTOR_P (decl))
5799             {
5800               /* [temp.mem]
5801
5802                  A destructor shall not be a member template.  */
5803               error_at (DECL_SOURCE_LOCATION (decl),
5804                         "destructor %qD declared as member template", decl);
5805               return error_mark_node;
5806             }
5807           if (IDENTIFIER_NEWDEL_OP_P (DECL_NAME (decl))
5808               && (!prototype_p (TREE_TYPE (decl))
5809                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
5810                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5811                   || (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5812                       == void_list_node)))
5813             {
5814               /* [basic.stc.dynamic.allocation]
5815
5816                  An allocation function can be a function
5817                  template. ... Template allocation functions shall
5818                  have two or more parameters.  */
5819               error ("invalid template declaration of %qD", decl);
5820               return error_mark_node;
5821             }
5822         }
5823       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5824                && CLASS_TYPE_P (TREE_TYPE (decl)))
5825         {
5826           /* Class template, set TEMPLATE_TYPE_PARM_FOR_CLASS.  */
5827           tree parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
5828           for (int i = 0; i < TREE_VEC_LENGTH (parms); ++i)
5829             {
5830               tree t = TREE_VALUE (TREE_VEC_ELT (parms, i));
5831               if (TREE_CODE (t) == TYPE_DECL)
5832                 t = TREE_TYPE (t);
5833               if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
5834                 TEMPLATE_TYPE_PARM_FOR_CLASS (t) = true;
5835             }
5836         }
5837       else if (TREE_CODE (decl) == TYPE_DECL
5838                && TYPE_DECL_ALIAS_P (decl))
5839         /* alias-declaration */
5840         gcc_assert (!DECL_ARTIFICIAL (decl));
5841       else if (VAR_P (decl))
5842         /* C++14 variable template. */;
5843       else if (TREE_CODE (decl) == CONCEPT_DECL)
5844         /* C++20 concept definitions.  */;
5845       else
5846         {
5847           error ("template declaration of %q#D", decl);
5848           return error_mark_node;
5849         }
5850     }
5851
5852   bool local_p = (!DECL_IMPLICIT_TYPEDEF_P (decl)
5853                   && ((ctx && TREE_CODE (ctx) == FUNCTION_DECL)
5854                       || (VAR_OR_FUNCTION_DECL_P (decl)
5855                           && DECL_LOCAL_DECL_P (decl))));
5856
5857   /* Check to see that the rules regarding the use of default
5858      arguments are not being violated.  We check args for a friend
5859      functions when we know whether it's a definition, introducing
5860      declaration or re-declaration.  */
5861   if (!local_p && (!is_friend || TREE_CODE (decl) != FUNCTION_DECL))
5862     check_default_tmpl_args (decl, current_template_parms,
5863                              is_primary, is_partial, is_friend);
5864
5865   /* Ensure that there are no parameter packs in the type of this
5866      declaration that have not been expanded.  */
5867   if (TREE_CODE (decl) == FUNCTION_DECL)
5868     {
5869       /* Check each of the arguments individually to see if there are
5870          any bare parameter packs.  */
5871       tree type = TREE_TYPE (decl);
5872       tree arg = DECL_ARGUMENTS (decl);
5873       tree argtype = TYPE_ARG_TYPES (type);
5874
5875       while (arg && argtype)
5876         {
5877           if (!DECL_PACK_P (arg)
5878               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
5879             {
5880             /* This is a PARM_DECL that contains unexpanded parameter
5881                packs. We have already complained about this in the
5882                check_for_bare_parameter_packs call, so just replace
5883                these types with ERROR_MARK_NODE.  */
5884               TREE_TYPE (arg) = error_mark_node;
5885               TREE_VALUE (argtype) = error_mark_node;
5886             }
5887
5888           arg = DECL_CHAIN (arg);
5889           argtype = TREE_CHAIN (argtype);
5890         }
5891
5892       /* Check for bare parameter packs in the return type and the
5893          exception specifiers.  */
5894       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
5895         /* Errors were already issued, set return type to int
5896            as the frontend doesn't expect error_mark_node as
5897            the return type.  */
5898         TREE_TYPE (type) = integer_type_node;
5899       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
5900         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
5901     }
5902   else if (check_for_bare_parameter_packs (is_typedef_decl (decl)
5903                                            ? DECL_ORIGINAL_TYPE (decl)
5904                                            : TREE_TYPE (decl)))
5905     {
5906       TREE_TYPE (decl) = error_mark_node;
5907       return error_mark_node;
5908     }
5909
5910   if (is_partial)
5911     return process_partial_specialization (decl);
5912
5913   tree args = current_template_args ();
5914   tree tmpl = NULL_TREE;
5915   bool new_template_p = false;
5916   if (local_p)
5917     {
5918       /* Does not get a template head.  */
5919       tmpl = NULL_TREE;
5920       gcc_checking_assert (!is_primary);
5921     }
5922   else if (!ctx
5923            || TREE_CODE (ctx) == FUNCTION_DECL
5924            || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
5925            || (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5926            || (is_friend && !(DECL_LANG_SPECIFIC (decl)
5927                               && DECL_TEMPLATE_INFO (decl))))
5928     {
5929       if (DECL_LANG_SPECIFIC (decl)
5930           && DECL_TEMPLATE_INFO (decl)
5931           && DECL_TI_TEMPLATE (decl))
5932         tmpl = DECL_TI_TEMPLATE (decl);
5933       /* If DECL is a TYPE_DECL for a class-template, then there won't
5934          be DECL_LANG_SPECIFIC.  The information equivalent to
5935          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
5936       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5937                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
5938                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
5939         {
5940           /* Since a template declaration already existed for this
5941              class-type, we must be redeclaring it here.  Make sure
5942              that the redeclaration is valid.  */
5943           redeclare_class_template (TREE_TYPE (decl),
5944                                     current_template_parms,
5945                                     current_template_constraints ());
5946           /* We don't need to create a new TEMPLATE_DECL; just use the
5947              one we already had.  */
5948           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
5949         }
5950       else
5951         {
5952           tmpl = build_template_decl (decl, current_template_parms,
5953                                       member_template_p);
5954           new_template_p = true;
5955
5956           if (DECL_LANG_SPECIFIC (decl)
5957               && DECL_TEMPLATE_SPECIALIZATION (decl))
5958             {
5959               /* A specialization of a member template of a template
5960                  class.  */
5961               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5962               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
5963               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
5964             }
5965         }
5966     }
5967   else
5968     {
5969       tree a, t, current, parms;
5970       int i;
5971       tree tinfo = get_template_info (decl);
5972
5973       if (!tinfo)
5974         {
5975           error ("template definition of non-template %q#D", decl);
5976           return error_mark_node;
5977         }
5978
5979       tmpl = TI_TEMPLATE (tinfo);
5980
5981       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
5982           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
5983           && DECL_TEMPLATE_SPECIALIZATION (decl)
5984           && DECL_MEMBER_TEMPLATE_P (tmpl))
5985         {
5986           /* The declaration is a specialization of a member
5987              template, declared outside the class.  Therefore, the
5988              innermost template arguments will be NULL, so we
5989              replace them with the arguments determined by the
5990              earlier call to check_explicit_specialization.  */
5991           args = DECL_TI_ARGS (decl);
5992
5993           tree new_tmpl
5994             = build_template_decl (decl, current_template_parms,
5995                                    member_template_p);
5996           DECL_TI_TEMPLATE (decl) = new_tmpl;
5997           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
5998           DECL_TEMPLATE_INFO (new_tmpl)
5999             = build_template_info (tmpl, args);
6000
6001           register_specialization (new_tmpl,
6002                                    most_general_template (tmpl),
6003                                    args,
6004                                    is_friend, 0);
6005           return decl;
6006         }
6007
6008       /* Make sure the template headers we got make sense.  */
6009
6010       parms = DECL_TEMPLATE_PARMS (tmpl);
6011       i = TMPL_PARMS_DEPTH (parms);
6012       if (TMPL_ARGS_DEPTH (args) != i)
6013         {
6014           error ("expected %d levels of template parms for %q#D, got %d",
6015                  i, decl, TMPL_ARGS_DEPTH (args));
6016           DECL_INTERFACE_KNOWN (decl) = 1;
6017           return error_mark_node;
6018         }
6019       else
6020         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
6021           {
6022             a = TMPL_ARGS_LEVEL (args, i);
6023             t = INNERMOST_TEMPLATE_PARMS (parms);
6024
6025             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
6026               {
6027                 if (current == decl)
6028                   error ("got %d template parameters for %q#D",
6029                          TREE_VEC_LENGTH (a), decl);
6030                 else
6031                   error ("got %d template parameters for %q#T",
6032                          TREE_VEC_LENGTH (a), current);
6033                 error ("  but %d required", TREE_VEC_LENGTH (t));
6034                 /* Avoid crash in import_export_decl.  */
6035                 DECL_INTERFACE_KNOWN (decl) = 1;
6036                 return error_mark_node;
6037               }
6038
6039             if (current == decl)
6040               current = ctx;
6041             else if (current == NULL_TREE)
6042               /* Can happen in erroneous input.  */
6043               break;
6044             else
6045               current = get_containing_scope (current);
6046           }
6047
6048       /* Check that the parms are used in the appropriate qualifying scopes
6049          in the declarator.  */
6050       if (!comp_template_args
6051           (TI_ARGS (tinfo),
6052            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
6053         {
6054           error ("template arguments to %qD do not match original "
6055                  "template %qD", decl, DECL_TEMPLATE_RESULT (tmpl));
6056           if (!uses_template_parms (TI_ARGS (tinfo)))
6057             inform (input_location, "use %<template<>%> for"
6058                     " an explicit specialization");
6059           /* Avoid crash in import_export_decl.  */
6060           DECL_INTERFACE_KNOWN (decl) = 1;
6061           return error_mark_node;
6062         }
6063     }
6064
6065   gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
6066
6067   if (new_template_p)
6068     {
6069       /* Push template declarations for global functions and types.
6070          Note that we do not try to push a global template friend
6071          declared in a template class; such a thing may well depend on
6072          the template parameters of the class and we'll push it when
6073          instantiating the befriending class.  */
6074       if (!ctx
6075           && !(is_friend && template_class_depth (current_class_type) > 0))
6076         {
6077           tree pushed = pushdecl_namespace_level (tmpl, /*hiding=*/is_friend);
6078           if (pushed == error_mark_node)
6079             return error_mark_node;
6080
6081           /* pushdecl may have found an existing template.  */
6082           if (pushed != tmpl)
6083             {
6084               decl = DECL_TEMPLATE_RESULT (pushed);
6085               tmpl = NULL_TREE;
6086             }
6087         }
6088       else if (is_friend)
6089         {
6090           /* Record this decl as belonging to the current class.  It's
6091              not chained onto anything else.  */
6092           DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (tmpl) = true;
6093           gcc_checking_assert (!DECL_CHAIN (tmpl));
6094           DECL_CHAIN (tmpl) = current_scope ();
6095         }
6096     }
6097   else if (tmpl)
6098     /* The type may have been completed, or (erroneously) changed.  */
6099     TREE_TYPE (tmpl) = TREE_TYPE (decl);
6100
6101   if (tmpl)
6102     {
6103       if (is_primary)
6104         {
6105           tree parms = DECL_TEMPLATE_PARMS (tmpl);
6106
6107           DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6108
6109           /* Give template template parms a DECL_CONTEXT of the template
6110              for which they are a parameter.  */
6111           parms = INNERMOST_TEMPLATE_PARMS (parms);
6112           for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
6113             {
6114               tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6115               if (TREE_CODE (parm) == TEMPLATE_DECL)
6116                 DECL_CONTEXT (parm) = tmpl;
6117             }
6118
6119           if (TREE_CODE (decl) == TYPE_DECL
6120               && TYPE_DECL_ALIAS_P (decl))
6121             {
6122               if (tree constr
6123                   = TEMPLATE_PARMS_CONSTRAINTS (DECL_TEMPLATE_PARMS (tmpl)))
6124                 {
6125                   /* ??? Why don't we do this here for all templates?  */
6126                   constr = build_constraints (constr, NULL_TREE);
6127                   set_constraints (decl, constr);
6128                 }
6129               if (complex_alias_template_p (tmpl))
6130                 TEMPLATE_DECL_COMPLEX_ALIAS_P (tmpl) = true;
6131             }
6132         }
6133
6134       /* The DECL_TI_ARGS of DECL contains full set of arguments
6135          referring wback to its most general template.  If TMPL is a
6136          specialization, ARGS may only have the innermost set of
6137          arguments.  Add the missing argument levels if necessary.  */
6138       if (DECL_TEMPLATE_INFO (tmpl))
6139         args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
6140
6141       tree info = build_template_info (tmpl, args);
6142
6143       if (DECL_IMPLICIT_TYPEDEF_P (decl))
6144         SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
6145       else
6146         {
6147           retrofit_lang_decl (decl);
6148           DECL_TEMPLATE_INFO (decl) = info;
6149         }
6150     }
6151
6152   if (flag_implicit_templates
6153       && !is_friend
6154       && TREE_PUBLIC (decl)
6155       && VAR_OR_FUNCTION_DECL_P (decl))
6156     /* Set DECL_COMDAT on template instantiations; if we force
6157        them to be emitted by explicit instantiation,
6158        mark_needed will tell cgraph to do the right thing.  */
6159     DECL_COMDAT (decl) = true;
6160
6161   gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
6162
6163   return decl;
6164 }
6165
6166 /* FN is an inheriting constructor that inherits from the constructor
6167    template INHERITED; turn FN into a constructor template with a matching
6168    template header.  */
6169
6170 tree
6171 add_inherited_template_parms (tree fn, tree inherited)
6172 {
6173   tree inner_parms
6174     = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
6175   inner_parms = copy_node (inner_parms);
6176   tree parms
6177     = tree_cons (size_int (processing_template_decl + 1),
6178                  inner_parms, current_template_parms);
6179   tree tmpl = build_template_decl (fn, parms, /*member*/true);
6180   tree args = template_parms_to_args (parms);
6181   DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
6182   DECL_ARTIFICIAL (tmpl) = true;
6183   DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6184   return tmpl;
6185 }
6186
6187 /* Called when a class template TYPE is redeclared with the indicated
6188    template PARMS, e.g.:
6189
6190      template <class T> struct S;
6191      template <class T> struct S {};  */
6192
6193 bool
6194 redeclare_class_template (tree type, tree parms, tree cons)
6195 {
6196   tree tmpl;
6197   tree tmpl_parms;
6198   int i;
6199
6200   if (!TYPE_TEMPLATE_INFO (type))
6201     {
6202       error ("%qT is not a template type", type);
6203       return false;
6204     }
6205
6206   tmpl = TYPE_TI_TEMPLATE (type);
6207   if (!PRIMARY_TEMPLATE_P (tmpl))
6208     /* The type is nested in some template class.  Nothing to worry
6209        about here; there are no new template parameters for the nested
6210        type.  */
6211     return true;
6212
6213   if (!parms)
6214     {
6215       error ("template specifiers not specified in declaration of %qD",
6216              tmpl);
6217       return false;
6218     }
6219
6220   parms = INNERMOST_TEMPLATE_PARMS (parms);
6221   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
6222
6223   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
6224     {
6225       error_n (input_location, TREE_VEC_LENGTH (parms),
6226                "redeclared with %d template parameter",
6227                "redeclared with %d template parameters",
6228                TREE_VEC_LENGTH (parms));
6229       inform_n (DECL_SOURCE_LOCATION (tmpl), TREE_VEC_LENGTH (tmpl_parms),
6230                 "previous declaration %qD used %d template parameter",
6231                 "previous declaration %qD used %d template parameters",
6232                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
6233       return false;
6234     }
6235
6236   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
6237     {
6238       tree tmpl_parm;
6239       tree parm;
6240       tree tmpl_default;
6241       tree parm_default;
6242
6243       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
6244           || TREE_VEC_ELT (parms, i) == error_mark_node)
6245         continue;
6246
6247       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
6248       if (error_operand_p (tmpl_parm))
6249         return false;
6250
6251       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6252       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
6253       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
6254
6255       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
6256          TEMPLATE_DECL.  */
6257       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
6258           || (TREE_CODE (tmpl_parm) != TYPE_DECL
6259               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
6260           || (TREE_CODE (tmpl_parm) != PARM_DECL
6261               && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
6262                   != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
6263           || (TREE_CODE (tmpl_parm) == PARM_DECL
6264               && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
6265                   != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
6266         {
6267           auto_diagnostic_group d;
6268           error ("template parameter %q+#D", tmpl_parm);
6269           inform (input_location, "redeclared here as %q#D", parm);
6270           return false;
6271         }
6272
6273       /* The parameters can be declared to introduce different
6274          constraints.  */
6275       tree p1 = TREE_VEC_ELT (tmpl_parms, i);
6276       tree p2 = TREE_VEC_ELT (parms, i);
6277       if (!template_parameter_constraints_equivalent_p (p1, p2))
6278         {
6279           auto_diagnostic_group d;
6280           error ("declaration of template parameter %q+#D with different "
6281                  "constraints", parm);
6282           inform (DECL_SOURCE_LOCATION (tmpl_parm),
6283                   "original declaration appeared here");
6284           return false;
6285         }
6286
6287       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
6288         {
6289           /* We have in [temp.param]:
6290
6291              A template-parameter may not be given default arguments
6292              by two different declarations in the same scope.  */
6293           auto_diagnostic_group d;
6294           error_at (input_location, "redefinition of default argument for %q#D", parm);
6295           inform (DECL_SOURCE_LOCATION (tmpl_parm),
6296                   "original definition appeared here");
6297           return false;
6298         }
6299
6300       if (parm_default != NULL_TREE)
6301         /* Update the previous template parameters (which are the ones
6302            that will really count) with the new default value.  */
6303         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
6304       else if (tmpl_default != NULL_TREE)
6305         /* Update the new parameters, too; they'll be used as the
6306            parameters for any members.  */
6307         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
6308
6309       /* Give each template template parm in this redeclaration a
6310          DECL_CONTEXT of the template for which they are a parameter.  */
6311       if (TREE_CODE (parm) == TEMPLATE_DECL)
6312         {
6313           gcc_assert (DECL_CONTEXT (parm) == NULL_TREE);
6314           DECL_CONTEXT (parm) = tmpl;
6315         }
6316
6317       if (TREE_CODE (parm) == TYPE_DECL)
6318         TEMPLATE_TYPE_PARM_FOR_CLASS (TREE_TYPE (parm)) = true;
6319     }
6320
6321   tree ci = get_constraints (tmpl);
6322   tree req1 = ci ? CI_TEMPLATE_REQS (ci) : NULL_TREE;
6323   tree req2 = cons ? CI_TEMPLATE_REQS (cons) : NULL_TREE;
6324
6325   /* Two classes with different constraints declare different entities.  */
6326   if (!cp_tree_equal (req1, req2))
6327     {
6328       auto_diagnostic_group d;
6329       error_at (input_location, "redeclaration %q#D with different "
6330                                 "constraints", tmpl);
6331       inform (DECL_SOURCE_LOCATION (tmpl),
6332               "original declaration appeared here");
6333       return false;
6334     }
6335
6336     return true;
6337 }
6338
6339 /* The actual substitution part of instantiate_non_dependent_expr_sfinae,
6340    to be used when the caller has already checked
6341    (processing_template_decl
6342     && !instantiation_dependent_expression_p (expr)
6343     && potential_constant_expression (expr))
6344    and cleared processing_template_decl.  */
6345
6346 tree
6347 instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
6348 {
6349   return tsubst_copy_and_build (expr,
6350                                 /*args=*/NULL_TREE,
6351                                 complain,
6352                                 /*in_decl=*/NULL_TREE,
6353                                 /*function_p=*/false,
6354                                 /*integral_constant_expression_p=*/true);
6355 }
6356
6357 /* Simplify EXPR if it is a non-dependent expression.  Returns the
6358    (possibly simplified) expression.  */
6359
6360 tree
6361 instantiate_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
6362 {
6363   if (expr == NULL_TREE)
6364     return NULL_TREE;
6365
6366   /* If we're in a template, but EXPR isn't value dependent, simplify
6367      it.  We're supposed to treat:
6368
6369        template <typename T> void f(T[1 + 1]);
6370        template <typename T> void f(T[2]);
6371
6372      as two declarations of the same function, for example.  */
6373   if (processing_template_decl
6374       && is_nondependent_constant_expression (expr))
6375     {
6376       processing_template_decl_sentinel s;
6377       expr = instantiate_non_dependent_expr_internal (expr, complain);
6378     }
6379   return expr;
6380 }
6381
6382 tree
6383 instantiate_non_dependent_expr (tree expr)
6384 {
6385   return instantiate_non_dependent_expr_sfinae (expr, tf_error);
6386 }
6387
6388 /* Like instantiate_non_dependent_expr, but return NULL_TREE rather than
6389    an uninstantiated expression.  */
6390
6391 tree
6392 instantiate_non_dependent_or_null (tree expr)
6393 {
6394   if (expr == NULL_TREE)
6395     return NULL_TREE;
6396   if (processing_template_decl)
6397     {
6398       if (!is_nondependent_constant_expression (expr))
6399         expr = NULL_TREE;
6400       else
6401         {
6402           processing_template_decl_sentinel s;
6403           expr = instantiate_non_dependent_expr_internal (expr, tf_error);
6404         }
6405     }
6406   return expr;
6407 }
6408
6409 /* True iff T is a specialization of a variable template.  */
6410
6411 bool
6412 variable_template_specialization_p (tree t)
6413 {
6414   if (!VAR_P (t) || !DECL_LANG_SPECIFIC (t) || !DECL_TEMPLATE_INFO (t))
6415     return false;
6416   tree tmpl = DECL_TI_TEMPLATE (t);
6417   return variable_template_p (tmpl);
6418 }
6419
6420 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
6421    template declaration, or a TYPE_DECL for an alias declaration.  */
6422
6423 bool
6424 alias_type_or_template_p (tree t)
6425 {
6426   if (t == NULL_TREE)
6427     return false;
6428   return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
6429           || (TYPE_P (t)
6430               && TYPE_NAME (t)
6431               && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
6432           || DECL_ALIAS_TEMPLATE_P (t));
6433 }
6434
6435 /* If T is a specialization of an alias template, return it; otherwise return
6436    NULL_TREE.  If TRANSPARENT_TYPEDEFS is true, look through other aliases.  */
6437
6438 tree
6439 alias_template_specialization_p (const_tree t,
6440                                  bool transparent_typedefs)
6441 {
6442   if (!TYPE_P (t))
6443     return NULL_TREE;
6444
6445   /* It's an alias template specialization if it's an alias and its
6446      TYPE_NAME is a specialization of a primary template.  */
6447   if (typedef_variant_p (t))
6448     {
6449       if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
6450         if (PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo)))
6451           return CONST_CAST_TREE (t);
6452       if (transparent_typedefs)
6453         return alias_template_specialization_p (DECL_ORIGINAL_TYPE
6454                                                 (TYPE_NAME (t)),
6455                                                 transparent_typedefs);
6456     }
6457
6458   return NULL_TREE;
6459 }
6460
6461 /* An alias template is complex from a SFINAE perspective if a template-id
6462    using that alias can be ill-formed when the expansion is not, as with
6463    the void_t template.  We determine this by checking whether the
6464    expansion for the alias template uses all its template parameters.  */
6465
6466 struct uses_all_template_parms_data
6467 {
6468   int level;
6469   bool *seen;
6470 };
6471
6472 static int
6473 uses_all_template_parms_r (tree t, void *data_)
6474 {
6475   struct uses_all_template_parms_data &data
6476     = *(struct uses_all_template_parms_data*)data_;
6477   tree idx = get_template_parm_index (t);
6478
6479   if (TEMPLATE_PARM_LEVEL (idx) == data.level)
6480     data.seen[TEMPLATE_PARM_IDX (idx)] = true;
6481   return 0;
6482 }
6483
6484 /* for_each_template_parm any_fn callback for complex_alias_template_p.  */
6485
6486 static int
6487 complex_pack_expansion_r (tree t, void *data_)
6488 {
6489   /* An alias template with a pack expansion that expands a pack from the
6490      enclosing class needs to be considered complex, to avoid confusion with
6491      the same pack being used as an argument to the alias's own template
6492      parameter (91966).  */
6493   if (!PACK_EXPANSION_P (t))
6494     return 0;
6495   struct uses_all_template_parms_data &data
6496     = *(struct uses_all_template_parms_data*)data_;
6497   for (tree pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
6498        pack = TREE_CHAIN (pack))
6499     {
6500       tree parm_pack = TREE_VALUE (pack);
6501       if (!TEMPLATE_PARM_P (parm_pack))
6502         continue;
6503       int idx, level;
6504       template_parm_level_and_index (parm_pack, &level, &idx);
6505       if (level < data.level)
6506         return 1;
6507     }
6508   return 0;
6509 }
6510
6511 static bool
6512 complex_alias_template_p (const_tree tmpl)
6513 {
6514   /* A renaming alias isn't complex.  */
6515   if (get_underlying_template (CONST_CAST_TREE (tmpl)) != tmpl)
6516     return false;
6517
6518   /* Any other constrained alias is complex.  */
6519   if (get_constraints (tmpl))
6520     return true;
6521
6522   struct uses_all_template_parms_data data;
6523   tree pat = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6524   tree parms = DECL_TEMPLATE_PARMS (tmpl);
6525   data.level = TMPL_PARMS_DEPTH (parms);
6526   int len = TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS (parms));
6527   data.seen = XALLOCAVEC (bool, len);
6528   for (int i = 0; i < len; ++i)
6529     data.seen[i] = false;
6530
6531   if (for_each_template_parm (pat, uses_all_template_parms_r, &data,
6532                               NULL, true, complex_pack_expansion_r))
6533     return true;
6534   for (int i = 0; i < len; ++i)
6535     if (!data.seen[i])
6536       return true;
6537   return false;
6538 }
6539
6540 /* If T is a specialization of a complex alias template with dependent
6541    template-arguments, return it; otherwise return NULL_TREE.  If T is a
6542    typedef to such a specialization, return the specialization.  */
6543
6544 tree
6545 dependent_alias_template_spec_p (const_tree t, bool transparent_typedefs)
6546 {
6547   if (t == error_mark_node)
6548     return NULL_TREE;
6549   gcc_assert (TYPE_P (t));
6550
6551   if (!typedef_variant_p (t))
6552     return NULL_TREE;
6553
6554   tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t);
6555   if (tinfo
6556       && TEMPLATE_DECL_COMPLEX_ALIAS_P (TI_TEMPLATE (tinfo))
6557       && (any_dependent_template_arguments_p
6558           (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)))))
6559     return CONST_CAST_TREE (t);
6560
6561   if (transparent_typedefs)
6562     {
6563       tree utype = DECL_ORIGINAL_TYPE (TYPE_NAME (t));
6564       return dependent_alias_template_spec_p (utype, transparent_typedefs);
6565     }
6566
6567   return NULL_TREE;
6568 }
6569
6570 /* Return the number of innermost template parameters in TMPL.  */
6571
6572 static int
6573 num_innermost_template_parms (const_tree tmpl)
6574 {
6575   tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6576   return TREE_VEC_LENGTH (parms);
6577 }
6578
6579 /* Return either TMPL or another template that it is equivalent to under DR
6580    1286: An alias that just changes the name of a template is equivalent to
6581    the other template.  */
6582
6583 static tree
6584 get_underlying_template (tree tmpl)
6585 {
6586   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
6587   while (DECL_ALIAS_TEMPLATE_P (tmpl))
6588     {
6589       /* Determine if the alias is equivalent to an underlying template.  */
6590       tree orig_type = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6591       /* The underlying type may have been ill-formed. Don't proceed.  */
6592       if (!orig_type)
6593         break;
6594       tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (orig_type);
6595       if (!tinfo)
6596         break;
6597
6598       tree underlying = TI_TEMPLATE (tinfo);
6599       if (!PRIMARY_TEMPLATE_P (underlying)
6600           || (num_innermost_template_parms (tmpl)
6601               != num_innermost_template_parms (underlying)))
6602         break;
6603
6604       /* Does the alias add cv-quals?  */
6605       if (TYPE_QUALS (TREE_TYPE (underlying)) != TYPE_QUALS (TREE_TYPE (tmpl)))
6606         break;
6607
6608       tree alias_args = INNERMOST_TEMPLATE_ARGS (generic_targs_for (tmpl));
6609       if (!comp_template_args (TI_ARGS (tinfo), alias_args))
6610         break;
6611
6612       /* If TMPL adds or changes any constraints, it isn't equivalent.  I think
6613          it's appropriate to treat a less-constrained alias as equivalent.  */
6614       if (!at_least_as_constrained (underlying, tmpl))
6615         break;
6616
6617       /* Alias is equivalent.  Strip it and repeat.  */
6618       tmpl = underlying;
6619     }
6620
6621   return tmpl;
6622 }
6623
6624 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
6625    must be a reference-to-function or a pointer-to-function type, as specified
6626    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
6627    and check that the resulting function has external linkage.  */
6628
6629 static tree
6630 convert_nontype_argument_function (tree type, tree expr,
6631                                    tsubst_flags_t complain)
6632 {
6633   tree fns = expr;
6634   tree fn, fn_no_ptr;
6635   linkage_kind linkage;
6636
6637   fn = instantiate_type (type, fns, tf_none);
6638   if (fn == error_mark_node)
6639     return error_mark_node;
6640
6641   if (value_dependent_expression_p (fn))
6642     goto accept;
6643
6644   fn_no_ptr = strip_fnptr_conv (fn);
6645   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
6646     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6647   if (BASELINK_P (fn_no_ptr))
6648     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
6649
6650   /* [temp.arg.nontype]/1
6651
6652      A template-argument for a non-type, non-template template-parameter
6653      shall be one of:
6654      [...]
6655      -- the address of an object or function with external [C++11: or
6656         internal] linkage.  */
6657
6658   STRIP_ANY_LOCATION_WRAPPER (fn_no_ptr);
6659   if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
6660     {
6661       if (complain & tf_error)
6662         {
6663           location_t loc = cp_expr_loc_or_input_loc (expr);
6664           error_at (loc, "%qE is not a valid template argument for type %qT",
6665                     expr, type);
6666           if (TYPE_PTR_P (type))
6667             inform (loc, "it must be the address of a function "
6668                     "with external linkage");
6669           else
6670             inform (loc, "it must be the name of a function with "
6671                     "external linkage");
6672         }
6673       return NULL_TREE;
6674     }
6675
6676   linkage = decl_linkage (fn_no_ptr);
6677   if (cxx_dialect >= cxx11 ? linkage == lk_none : linkage != lk_external)
6678     {
6679       if (complain & tf_error)
6680         {
6681           location_t loc = cp_expr_loc_or_input_loc (expr);
6682           if (cxx_dialect >= cxx11)
6683             error_at (loc, "%qE is not a valid template argument for type "
6684                       "%qT because %qD has no linkage",
6685                       expr, type, fn_no_ptr);
6686           else
6687             error_at (loc, "%qE is not a valid template argument for type "
6688                       "%qT because %qD does not have external linkage",
6689                       expr, type, fn_no_ptr);
6690         }
6691       return NULL_TREE;
6692     }
6693
6694  accept:
6695   if (TYPE_REF_P (type))
6696     {
6697       if (REFERENCE_REF_P (fn))
6698         fn = TREE_OPERAND (fn, 0);
6699       else
6700         fn = build_address (fn);
6701     }
6702   if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (fn)))
6703     fn = build_nop (type, fn);
6704
6705   return fn;
6706 }
6707
6708 /* Subroutine of convert_nontype_argument.
6709    Check if EXPR of type TYPE is a valid pointer-to-member constant.
6710    Emit an error otherwise.  */
6711
6712 static bool
6713 check_valid_ptrmem_cst_expr (tree type, tree expr,
6714                              tsubst_flags_t complain)
6715 {
6716   tree orig_expr = expr;
6717   STRIP_NOPS (expr);
6718   if (null_ptr_cst_p (expr))
6719     return true;
6720   if (TREE_CODE (expr) == PTRMEM_CST
6721       && same_type_p (TYPE_PTRMEM_CLASS_TYPE (type),
6722                       PTRMEM_CST_CLASS (expr)))
6723     return true;
6724   if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
6725     return true;
6726   if (processing_template_decl
6727       && TREE_CODE (expr) == ADDR_EXPR
6728       && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
6729     return true;
6730   if (complain & tf_error)
6731     {
6732       location_t loc = cp_expr_loc_or_input_loc (orig_expr);
6733       error_at (loc, "%qE is not a valid template argument for type %qT",
6734                 orig_expr, type);
6735       if (TREE_CODE (expr) != PTRMEM_CST)
6736         inform (loc, "it must be a pointer-to-member of the form %<&X::Y%>");
6737       else
6738         inform (loc, "because it is a member of %qT", PTRMEM_CST_CLASS (expr));
6739     }
6740   return false;
6741 }
6742
6743 /* Returns TRUE iff the address of OP is value-dependent.
6744
6745    14.6.2.4 [temp.dep.temp]:
6746    A non-integral non-type template-argument is dependent if its type is
6747    dependent or it has either of the following forms
6748      qualified-id
6749      & qualified-id
6750    and contains a nested-name-specifier which specifies a class-name that
6751    names a dependent type.
6752
6753    We generalize this to just say that the address of a member of a
6754    dependent class is value-dependent; the above doesn't cover the
6755    address of a static data member named with an unqualified-id.  */
6756
6757 static bool
6758 has_value_dependent_address (tree op)
6759 {
6760   STRIP_ANY_LOCATION_WRAPPER (op);
6761
6762   /* We could use get_inner_reference here, but there's no need;
6763      this is only relevant for template non-type arguments, which
6764      can only be expressed as &id-expression.  */
6765   if (DECL_P (op))
6766     {
6767       tree ctx = CP_DECL_CONTEXT (op);
6768       if (TYPE_P (ctx) && dependent_type_p (ctx))
6769         return true;
6770     }
6771
6772   return false;
6773 }
6774
6775 /* The next set of functions are used for providing helpful explanatory
6776    diagnostics for failed overload resolution.  Their messages should be
6777    indented by two spaces for consistency with the messages in
6778    call.c  */
6779
6780 static int
6781 unify_success (bool /*explain_p*/)
6782 {
6783   return 0;
6784 }
6785
6786 /* Other failure functions should call this one, to provide a single function
6787    for setting a breakpoint on.  */
6788
6789 static int
6790 unify_invalid (bool /*explain_p*/)
6791 {
6792   return 1;
6793 }
6794
6795 static int
6796 unify_parameter_deduction_failure (bool explain_p, tree parm)
6797 {
6798   if (explain_p)
6799     inform (input_location,
6800             "  couldn%'t deduce template parameter %qD", parm);
6801   return unify_invalid (explain_p);
6802 }
6803
6804 static int
6805 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
6806 {
6807   if (explain_p)
6808     inform (input_location,
6809             "  types %qT and %qT have incompatible cv-qualifiers",
6810             parm, arg);
6811   return unify_invalid (explain_p);
6812 }
6813
6814 static int
6815 unify_type_mismatch (bool explain_p, tree parm, tree arg)
6816 {
6817   if (explain_p)
6818     inform (input_location, "  mismatched types %qT and %qT", parm, arg);
6819   return unify_invalid (explain_p);
6820 }
6821
6822 static int
6823 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
6824 {
6825   if (explain_p)
6826     inform (input_location,
6827             "  template parameter %qD is not a parameter pack, but "
6828             "argument %qD is",
6829             parm, arg);
6830   return unify_invalid (explain_p);
6831 }
6832
6833 static int
6834 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
6835 {
6836   if (explain_p)
6837     inform (input_location,
6838             "  template argument %qE does not match "
6839             "pointer-to-member constant %qE",
6840             arg, parm);
6841   return unify_invalid (explain_p);
6842 }
6843
6844 static int
6845 unify_expression_unequal (bool explain_p, tree parm, tree arg)
6846 {
6847   if (explain_p)
6848     inform (input_location, "  %qE is not equivalent to %qE", parm, arg);
6849   return unify_invalid (explain_p);
6850 }
6851
6852 static int
6853 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
6854 {
6855   if (explain_p)
6856     inform (input_location,
6857             "  inconsistent parameter pack deduction with %qT and %qT",
6858             old_arg, new_arg);
6859   return unify_invalid (explain_p);
6860 }
6861
6862 static int
6863 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
6864 {
6865   if (explain_p)
6866     {
6867       if (TYPE_P (parm))
6868         inform (input_location,
6869                 "  deduced conflicting types for parameter %qT (%qT and %qT)",
6870                 parm, first, second);
6871       else
6872         inform (input_location,
6873                 "  deduced conflicting values for non-type parameter "
6874                 "%qE (%qE and %qE)", parm, first, second);
6875     }
6876   return unify_invalid (explain_p);
6877 }
6878
6879 static int
6880 unify_vla_arg (bool explain_p, tree arg)
6881 {
6882   if (explain_p)
6883     inform (input_location,
6884             "  variable-sized array type %qT is not "
6885             "a valid template argument",
6886             arg);
6887   return unify_invalid (explain_p);
6888 }
6889
6890 static int
6891 unify_method_type_error (bool explain_p, tree arg)
6892 {
6893   if (explain_p)
6894     inform (input_location,
6895             "  member function type %qT is not a valid template argument",
6896             arg);
6897   return unify_invalid (explain_p);
6898 }
6899
6900 static int
6901 unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
6902 {
6903   if (explain_p)
6904     {
6905       if (least_p)
6906         inform_n (input_location, wanted,
6907                   "  candidate expects at least %d argument, %d provided",
6908                   "  candidate expects at least %d arguments, %d provided",
6909                   wanted, have);
6910       else
6911         inform_n (input_location, wanted,
6912                   "  candidate expects %d argument, %d provided",
6913                   "  candidate expects %d arguments, %d provided",
6914                   wanted, have);
6915     }
6916   return unify_invalid (explain_p);
6917 }
6918
6919 static int
6920 unify_too_many_arguments (bool explain_p, int have, int wanted)
6921 {
6922   return unify_arity (explain_p, have, wanted);
6923 }
6924
6925 static int
6926 unify_too_few_arguments (bool explain_p, int have, int wanted,
6927                          bool least_p = false)
6928 {
6929   return unify_arity (explain_p, have, wanted, least_p);
6930 }
6931
6932 static int
6933 unify_arg_conversion (bool explain_p, tree to_type,
6934                       tree from_type, tree arg)
6935 {
6936   if (explain_p)
6937     inform (cp_expr_loc_or_input_loc (arg),
6938             "  cannot convert %qE (type %qT) to type %qT",
6939             arg, from_type, to_type);
6940   return unify_invalid (explain_p);
6941 }
6942
6943 static int
6944 unify_no_common_base (bool explain_p, enum template_base_result r,
6945                       tree parm, tree arg)
6946 {
6947   if (explain_p)
6948     switch (r)
6949       {
6950       case tbr_ambiguous_baseclass:
6951         inform (input_location, "  %qT is an ambiguous base class of %qT",
6952                 parm, arg);
6953         break;
6954       default:
6955         inform (input_location, "  %qT is not derived from %qT", arg, parm);
6956         break;
6957       }
6958   return unify_invalid (explain_p);
6959 }
6960
6961 static int
6962 unify_inconsistent_template_template_parameters (bool explain_p)
6963 {
6964   if (explain_p)
6965     inform (input_location,
6966             "  template parameters of a template template argument are "
6967             "inconsistent with other deduced template arguments");
6968   return unify_invalid (explain_p);
6969 }
6970
6971 static int
6972 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
6973 {
6974   if (explain_p)
6975     inform (input_location,
6976             "  cannot deduce a template for %qT from non-template type %qT",
6977             parm, arg);
6978   return unify_invalid (explain_p);
6979 }
6980
6981 static int
6982 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
6983 {
6984   if (explain_p)
6985     inform (input_location,
6986             "  template argument %qE does not match %qE", arg, parm);
6987   return unify_invalid (explain_p);
6988 }
6989
6990 /* True if T is a C++20 template parameter object to store the argument for a
6991    template parameter of class type.  */
6992
6993 bool
6994 template_parm_object_p (const_tree t)
6995 {
6996   return (TREE_CODE (t) == VAR_DECL && DECL_ARTIFICIAL (t) && DECL_NAME (t)
6997           && !strncmp (IDENTIFIER_POINTER (DECL_NAME (t)), "_ZTA", 4));
6998 }
6999
7000 /* Subroutine of convert_nontype_argument, to check whether EXPR, as an
7001    argument for TYPE, points to an unsuitable object.
7002
7003    Also adjust the type of the index in C++20 array subobject references.  */
7004
7005 static bool
7006 invalid_tparm_referent_p (tree type, tree expr, tsubst_flags_t complain)
7007 {
7008   switch (TREE_CODE (expr))
7009     {
7010     CASE_CONVERT:
7011       return invalid_tparm_referent_p (type, TREE_OPERAND (expr, 0),
7012                                        complain);
7013
7014     case TARGET_EXPR:
7015       return invalid_tparm_referent_p (type, TARGET_EXPR_INITIAL (expr),
7016                                        complain);
7017
7018     case CONSTRUCTOR:
7019       {
7020         unsigned i; tree elt;
7021         FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expr), i, elt)
7022           if (invalid_tparm_referent_p (TREE_TYPE (elt), elt, complain))
7023             return true;
7024       }
7025       break;
7026
7027     case ADDR_EXPR:
7028       {
7029         tree decl = TREE_OPERAND (expr, 0);
7030
7031         if (cxx_dialect >= cxx20)
7032           while (TREE_CODE (decl) == COMPONENT_REF
7033                  || TREE_CODE (decl) == ARRAY_REF)
7034             {
7035               tree &op = TREE_OPERAND (decl, 1);
7036               if (TREE_CODE (decl) == ARRAY_REF
7037                   && TREE_CODE (op) == INTEGER_CST)
7038                 /* Canonicalize array offsets to ptrdiff_t; how they were
7039                    written doesn't matter for subobject identity.  */
7040                 op = fold_convert (ptrdiff_type_node, op);
7041               decl = TREE_OPERAND (decl, 0);
7042             }
7043
7044         if (!VAR_P (decl))
7045           {
7046             if (complain & tf_error)
7047               error_at (cp_expr_loc_or_input_loc (expr),
7048                         "%qE is not a valid template argument of type %qT "
7049                         "because %qE is not a variable", expr, type, decl);
7050             return true;
7051           }
7052         else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
7053           {
7054             if (complain & tf_error)
7055               error_at (cp_expr_loc_or_input_loc (expr),
7056                         "%qE is not a valid template argument of type %qT "
7057                         "in C++98 because %qD does not have external linkage",
7058                         expr, type, decl);
7059             return true;
7060           }
7061         else if ((cxx_dialect >= cxx11 && cxx_dialect < cxx17)
7062                  && decl_linkage (decl) == lk_none)
7063           {
7064             if (complain & tf_error)
7065               error_at (cp_expr_loc_or_input_loc (expr),
7066                         "%qE is not a valid template argument of type %qT "
7067                         "because %qD has no linkage", expr, type, decl);
7068             return true;
7069           }
7070         /* C++17: For a non-type template-parameter of reference or pointer
7071            type, the value of the constant expression shall not refer to (or
7072            for a pointer type, shall not be the address of):
7073            * a subobject (4.5),
7074            * a temporary object (15.2),
7075            * a string literal (5.13.5),
7076            * the result of a typeid expression (8.2.8), or
7077            * a predefined __func__ variable (11.4.1).  */
7078         else if (DECL_ARTIFICIAL (decl))
7079           {
7080             if (complain & tf_error)
7081               error ("the address of %qD is not a valid template argument",
7082                      decl);
7083             return true;
7084           }
7085         else if (cxx_dialect < cxx20
7086                  && !(same_type_ignoring_top_level_qualifiers_p
7087                       (strip_array_types (TREE_TYPE (type)),
7088                        strip_array_types (TREE_TYPE (decl)))))
7089           {
7090             if (complain & tf_error)
7091               error ("the address of the %qT subobject of %qD is not a "
7092                      "valid template argument", TREE_TYPE (type), decl);
7093             return true;
7094           }
7095         else if (!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
7096           {
7097             if (complain & tf_error)
7098               error ("the address of %qD is not a valid template argument "
7099                      "because it does not have static storage duration",
7100                      decl);
7101             return true;
7102           }
7103       }
7104       break;
7105
7106     default:
7107       if (!INDIRECT_TYPE_P (type))
7108         /* We're only concerned about pointers and references here.  */;
7109       else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7110         /* Null pointer values are OK in C++11.  */;
7111       else
7112         {
7113           if (VAR_P (expr))
7114             {
7115               if (complain & tf_error)
7116                 error ("%qD is not a valid template argument "
7117                        "because %qD is a variable, not the address of "
7118                        "a variable", expr, expr);
7119               return true;
7120             }
7121           else
7122             {
7123               if (complain & tf_error)
7124                 error ("%qE is not a valid template argument for %qT "
7125                        "because it is not the address of a variable",
7126                        expr, type);
7127               return true;
7128             }
7129         }
7130     }
7131   return false;
7132
7133 }
7134
7135 /* The template arguments corresponding to template parameter objects of types
7136    that contain pointers to members.  */
7137
7138 static GTY(()) hash_map<tree, tree> *tparm_obj_values;
7139
7140 /* Return a VAR_DECL for the C++20 template parameter object corresponding to
7141    template argument EXPR.  */
7142
7143 static tree
7144 get_template_parm_object (tree expr, tsubst_flags_t complain)
7145 {
7146   if (TREE_CODE (expr) == TARGET_EXPR)
7147     expr = TARGET_EXPR_INITIAL (expr);
7148
7149   if (!TREE_CONSTANT (expr))
7150     {
7151       if ((complain & tf_error)
7152           && require_rvalue_constant_expression (expr))
7153         cxx_constant_value (expr);
7154       return error_mark_node;
7155     }
7156   if (invalid_tparm_referent_p (TREE_TYPE (expr), expr, complain))
7157     return error_mark_node;
7158
7159   /* This is no longer a compound literal.  */
7160   TREE_HAS_CONSTRUCTOR (expr) = 0;
7161
7162   tree name = mangle_template_parm_object (expr);
7163   tree decl = get_global_binding (name);
7164   if (decl)
7165     return decl;
7166
7167   tree type = cp_build_qualified_type (TREE_TYPE (expr), TYPE_QUAL_CONST);
7168   decl = create_temporary_var (type);
7169   DECL_CONTEXT (decl) = NULL_TREE;
7170   TREE_STATIC (decl) = true;
7171   DECL_DECLARED_CONSTEXPR_P (decl) = true;
7172   TREE_READONLY (decl) = true;
7173   DECL_NAME (decl) = name;
7174   SET_DECL_ASSEMBLER_NAME (decl, name);
7175   comdat_linkage (decl);
7176
7177   if (!zero_init_p (type))
7178     {
7179       /* If EXPR contains any PTRMEM_CST, they will get clobbered by
7180          lower_var_init before we're done mangling.  So store the original
7181          value elsewhere.  */
7182       tree copy = unshare_constructor (expr);
7183       hash_map_safe_put<hm_ggc> (tparm_obj_values, decl, copy);
7184     }
7185
7186   pushdecl_top_level_and_finish (decl, expr);
7187
7188   return decl;
7189 }
7190
7191 /* Return the actual template argument corresponding to template parameter
7192    object VAR.  */
7193
7194 tree
7195 tparm_object_argument (tree var)
7196 {
7197   if (zero_init_p (TREE_TYPE (var)))
7198     return DECL_INITIAL (var);
7199   return *(tparm_obj_values->get (var));
7200 }
7201
7202 /* Attempt to convert the non-type template parameter EXPR to the
7203    indicated TYPE.  If the conversion is successful, return the
7204    converted value.  If the conversion is unsuccessful, return
7205    NULL_TREE if we issued an error message, or error_mark_node if we
7206    did not.  We issue error messages for out-and-out bad template
7207    parameters, but not simply because the conversion failed, since we
7208    might be just trying to do argument deduction.  Both TYPE and EXPR
7209    must be non-dependent.
7210
7211    The conversion follows the special rules described in
7212    [temp.arg.nontype], and it is much more strict than an implicit
7213    conversion.
7214
7215    This function is called twice for each template argument (see
7216    lookup_template_class for a more accurate description of this
7217    problem). This means that we need to handle expressions which
7218    are not valid in a C++ source, but can be created from the
7219    first call (for instance, casts to perform conversions). These
7220    hacks can go away after we fix the double coercion problem.  */
7221
7222 static tree
7223 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
7224 {
7225   tree expr_type;
7226   location_t loc = cp_expr_loc_or_input_loc (expr);
7227
7228   /* Detect immediately string literals as invalid non-type argument.
7229      This special-case is not needed for correctness (we would easily
7230      catch this later), but only to provide better diagnostic for this
7231      common user mistake. As suggested by DR 100, we do not mention
7232      linkage issues in the diagnostic as this is not the point.  */
7233   if (TREE_CODE (expr) == STRING_CST && !CLASS_TYPE_P (type))
7234     {
7235       if (complain & tf_error)
7236         error ("%qE is not a valid template argument for type %qT "
7237                "because string literals can never be used in this context",
7238                expr, type);
7239       return NULL_TREE;
7240     }
7241
7242   /* Add the ADDR_EXPR now for the benefit of
7243      value_dependent_expression_p.  */
7244   if (TYPE_PTROBV_P (type)
7245       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
7246     {
7247       expr = decay_conversion (expr, complain);
7248       if (expr == error_mark_node)
7249         return error_mark_node;
7250     }
7251
7252   /* If we are in a template, EXPR may be non-dependent, but still
7253      have a syntactic, rather than semantic, form.  For example, EXPR
7254      might be a SCOPE_REF, rather than the VAR_DECL to which the
7255      SCOPE_REF refers.  Preserving the qualifying scope is necessary
7256      so that access checking can be performed when the template is
7257      instantiated -- but here we need the resolved form so that we can
7258      convert the argument.  */
7259   bool non_dep = false;
7260   if (TYPE_REF_OBJ_P (type)
7261       && has_value_dependent_address (expr))
7262     /* If we want the address and it's value-dependent, don't fold.  */;
7263   else if (processing_template_decl
7264            && is_nondependent_constant_expression (expr))
7265     non_dep = true;
7266   if (error_operand_p (expr))
7267     return error_mark_node;
7268   expr_type = TREE_TYPE (expr);
7269
7270   /* If the argument is non-dependent, perform any conversions in
7271      non-dependent context as well.  */
7272   processing_template_decl_sentinel s (non_dep);
7273   if (non_dep)
7274     expr = instantiate_non_dependent_expr_internal (expr, complain);
7275
7276   const bool val_dep_p = value_dependent_expression_p (expr);
7277   if (val_dep_p)
7278     expr = canonicalize_expr_argument (expr, complain);
7279
7280   /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
7281      to a non-type argument of "nullptr".  */
7282   if (NULLPTR_TYPE_P (expr_type) && TYPE_PTR_OR_PTRMEM_P (type))
7283     expr = fold_simple (convert (type, expr));
7284
7285   /* In C++11, integral or enumeration non-type template arguments can be
7286      arbitrary constant expressions.  Pointer and pointer to
7287      member arguments can be general constant expressions that evaluate
7288      to a null value, but otherwise still need to be of a specific form.  */
7289   if (cxx_dialect >= cxx11)
7290     {
7291       if (TREE_CODE (expr) == PTRMEM_CST && TYPE_PTRMEM_P (type))
7292         /* A PTRMEM_CST is already constant, and a valid template
7293            argument for a parameter of pointer to member type, we just want
7294            to leave it in that form rather than lower it to a
7295            CONSTRUCTOR.  */;
7296       else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7297                || cxx_dialect >= cxx17)
7298         {
7299           /* C++17: A template-argument for a non-type template-parameter shall
7300              be a converted constant expression (8.20) of the type of the
7301              template-parameter.  */
7302           expr = build_converted_constant_expr (type, expr, complain);
7303           if (expr == error_mark_node)
7304             /* Make sure we return NULL_TREE only if we have really issued
7305                an error, as described above.  */
7306             return (complain & tf_error) ? NULL_TREE : error_mark_node;
7307           else if (TREE_CODE (expr) == IMPLICIT_CONV_EXPR)
7308             {
7309               IMPLICIT_CONV_EXPR_NONTYPE_ARG (expr) = true;
7310               return expr;
7311             }
7312           expr = maybe_constant_value (expr, NULL_TREE,
7313                                        /*manifestly_const_eval=*/true);
7314           expr = convert_from_reference (expr);
7315         }
7316       else if (TYPE_PTR_OR_PTRMEM_P (type))
7317         {
7318           tree folded = maybe_constant_value (expr, NULL_TREE,
7319                                               /*manifestly_const_eval=*/true);
7320           if (TYPE_PTR_P (type) ? integer_zerop (folded)
7321               : null_member_pointer_value_p (folded))
7322             expr = folded;
7323         }
7324     }
7325
7326   if (TYPE_REF_P (type))
7327     expr = mark_lvalue_use (expr);
7328   else
7329     expr = mark_rvalue_use (expr);
7330
7331   /* HACK: Due to double coercion, we can get a
7332      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
7333      which is the tree that we built on the first call (see
7334      below when coercing to reference to object or to reference to
7335      function). We just strip everything and get to the arg.
7336      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
7337      for examples.  */
7338   if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
7339     {
7340       tree probe_type, probe = expr;
7341       if (REFERENCE_REF_P (probe))
7342         probe = TREE_OPERAND (probe, 0);
7343       probe_type = TREE_TYPE (probe);
7344       if (TREE_CODE (probe) == NOP_EXPR)
7345         {
7346           /* ??? Maybe we could use convert_from_reference here, but we
7347              would need to relax its constraints because the NOP_EXPR
7348              could actually change the type to something more cv-qualified,
7349              and this is not folded by convert_from_reference.  */
7350           tree addr = TREE_OPERAND (probe, 0);
7351           if (TYPE_REF_P (probe_type)
7352               && TREE_CODE (addr) == ADDR_EXPR
7353               && TYPE_PTR_P (TREE_TYPE (addr))
7354               && (same_type_ignoring_top_level_qualifiers_p
7355                   (TREE_TYPE (probe_type),
7356                    TREE_TYPE (TREE_TYPE (addr)))))
7357             {
7358               expr = TREE_OPERAND (addr, 0);
7359               expr_type = TREE_TYPE (probe_type);
7360             }
7361         }
7362     }
7363
7364   /* [temp.arg.nontype]/5, bullet 1
7365
7366      For a non-type template-parameter of integral or enumeration type,
7367      integral promotions (_conv.prom_) and integral conversions
7368      (_conv.integral_) are applied.  */
7369   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7370       || TREE_CODE (type) == REAL_TYPE)
7371     {
7372       if (cxx_dialect < cxx11)
7373         {
7374           tree t = build_converted_constant_expr (type, expr, complain);
7375           t = maybe_constant_value (t);
7376           if (t != error_mark_node)
7377             expr = t;
7378         }
7379
7380       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
7381         return error_mark_node;
7382
7383       /* Notice that there are constant expressions like '4 % 0' which
7384          do not fold into integer constants.  */
7385       if (!CONSTANT_CLASS_P (expr) && !val_dep_p)
7386         {
7387           if (complain & tf_error)
7388             {
7389               int errs = errorcount, warns = warningcount + werrorcount;
7390               if (!require_potential_constant_expression (expr))
7391                 expr = error_mark_node;
7392               else
7393                 expr = cxx_constant_value (expr);
7394               if (errorcount > errs || warningcount + werrorcount > warns)
7395                 inform (loc, "in template argument for type %qT", type);
7396               if (expr == error_mark_node)
7397                 return NULL_TREE;
7398               /* else cxx_constant_value complained but gave us
7399                  a real constant, so go ahead.  */
7400               if (!CONSTANT_CLASS_P (expr))
7401                 {
7402                   /* Some assemble time constant expressions like
7403                      (intptr_t)&&lab1 - (intptr_t)&&lab2 or
7404                      4 + (intptr_t)&&var satisfy reduced_constant_expression_p
7405                      as we can emit them into .rodata initializers of
7406                      variables, yet they can't fold into an INTEGER_CST at
7407                      compile time.  Refuse them here.  */
7408                   gcc_checking_assert (reduced_constant_expression_p (expr));
7409                   error_at (loc, "template argument %qE for type %qT not "
7410                                  "a compile-time constant", expr, type);
7411                   return NULL_TREE;
7412                 }
7413             }
7414           else
7415             return NULL_TREE;
7416         }
7417
7418       /* Avoid typedef problems.  */
7419       if (TREE_TYPE (expr) != type)
7420         expr = fold_convert (type, expr);
7421     }
7422   /* [temp.arg.nontype]/5, bullet 2
7423
7424      For a non-type template-parameter of type pointer to object,
7425      qualification conversions (_conv.qual_) and the array-to-pointer
7426      conversion (_conv.array_) are applied.  */
7427   else if (TYPE_PTROBV_P (type))
7428     {
7429       tree decayed = expr;
7430
7431       /* Look through any NOP_EXPRs around an ADDR_EXPR, whether they come from
7432          decay_conversion or an explicit cast.  If it's a problematic cast,
7433          we'll complain about it below.  */
7434       if (TREE_CODE (expr) == NOP_EXPR)
7435         {
7436           tree probe = expr;
7437           STRIP_NOPS (probe);
7438           if (TREE_CODE (probe) == ADDR_EXPR
7439               && TYPE_PTR_P (TREE_TYPE (probe)))
7440             {
7441               expr = probe;
7442               expr_type = TREE_TYPE (expr);
7443             }
7444         }
7445
7446       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
7447
7448          A template-argument for a non-type, non-template template-parameter
7449          shall be one of: [...]
7450
7451          -- the name of a non-type template-parameter;
7452          -- the address of an object or function with external linkage, [...]
7453             expressed as "& id-expression" where the & is optional if the name
7454             refers to a function or array, or if the corresponding
7455             template-parameter is a reference.
7456
7457         Here, we do not care about functions, as they are invalid anyway
7458         for a parameter of type pointer-to-object.  */
7459
7460       if (val_dep_p)
7461         /* Non-type template parameters are OK.  */
7462         ;
7463       else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7464         /* Null pointer values are OK in C++11.  */;
7465       else if (TREE_CODE (expr) != ADDR_EXPR
7466                && !INDIRECT_TYPE_P (expr_type))
7467         /* Other values, like integer constants, might be valid
7468            non-type arguments of some other type.  */
7469         return error_mark_node;
7470       else if (invalid_tparm_referent_p (type, expr, complain))
7471         return NULL_TREE;
7472
7473       expr = decayed;
7474
7475       expr = perform_qualification_conversions (type, expr);
7476       if (expr == error_mark_node)
7477         return error_mark_node;
7478     }
7479   /* [temp.arg.nontype]/5, bullet 3
7480
7481      For a non-type template-parameter of type reference to object, no
7482      conversions apply. The type referred to by the reference may be more
7483      cv-qualified than the (otherwise identical) type of the
7484      template-argument. The template-parameter is bound directly to the
7485      template-argument, which must be an lvalue.  */
7486   else if (TYPE_REF_OBJ_P (type))
7487     {
7488       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
7489                                                       expr_type))
7490         return error_mark_node;
7491
7492       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
7493         {
7494           if (complain & tf_error)
7495             error ("%qE is not a valid template argument for type %qT "
7496                    "because of conflicts in cv-qualification", expr, type);
7497           return NULL_TREE;
7498         }
7499
7500       if (!lvalue_p (expr))
7501         {
7502           if (complain & tf_error)
7503             error ("%qE is not a valid template argument for type %qT "
7504                    "because it is not an lvalue", expr, type);
7505           return NULL_TREE;
7506         }
7507
7508       /* [temp.arg.nontype]/1
7509
7510          A template-argument for a non-type, non-template template-parameter
7511          shall be one of: [...]
7512
7513          -- the address of an object or function with external linkage.  */
7514       if (INDIRECT_REF_P (expr)
7515           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
7516         {
7517           expr = TREE_OPERAND (expr, 0);
7518           if (DECL_P (expr))
7519             {
7520               if (complain & tf_error)
7521                 error ("%q#D is not a valid template argument for type %qT "
7522                        "because a reference variable does not have a constant "
7523                        "address", expr, type);
7524               return NULL_TREE;
7525             }
7526         }
7527
7528       if (TYPE_REF_OBJ_P (TREE_TYPE (expr)) && val_dep_p)
7529         /* OK, dependent reference.  We don't want to ask whether a DECL is
7530            itself value-dependent, since what we want here is its address.  */;
7531       else
7532         {
7533           expr = build_address (expr);
7534
7535           if (invalid_tparm_referent_p (type, expr, complain))
7536             return NULL_TREE;
7537         }
7538
7539       if (!same_type_p (type, TREE_TYPE (expr)))
7540         expr = build_nop (type, expr);
7541     }
7542   /* [temp.arg.nontype]/5, bullet 4
7543
7544      For a non-type template-parameter of type pointer to function, only
7545      the function-to-pointer conversion (_conv.func_) is applied. If the
7546      template-argument represents a set of overloaded functions (or a
7547      pointer to such), the matching function is selected from the set
7548      (_over.over_).  */
7549   else if (TYPE_PTRFN_P (type))
7550     {
7551       /* If the argument is a template-id, we might not have enough
7552          context information to decay the pointer.  */
7553       if (!type_unknown_p (expr_type))
7554         {
7555           expr = decay_conversion (expr, complain);
7556           if (expr == error_mark_node)
7557             return error_mark_node;
7558         }
7559
7560       if (cxx_dialect >= cxx11 && integer_zerop (expr))
7561         /* Null pointer values are OK in C++11.  */
7562         return perform_qualification_conversions (type, expr);
7563
7564       expr = convert_nontype_argument_function (type, expr, complain);
7565       if (!expr || expr == error_mark_node)
7566         return expr;
7567     }
7568   /* [temp.arg.nontype]/5, bullet 5
7569
7570      For a non-type template-parameter of type reference to function, no
7571      conversions apply. If the template-argument represents a set of
7572      overloaded functions, the matching function is selected from the set
7573      (_over.over_).  */
7574   else if (TYPE_REFFN_P (type))
7575     {
7576       if (TREE_CODE (expr) == ADDR_EXPR)
7577         {
7578           if (complain & tf_error)
7579             {
7580               error ("%qE is not a valid template argument for type %qT "
7581                      "because it is a pointer", expr, type);
7582               inform (input_location, "try using %qE instead",
7583                       TREE_OPERAND (expr, 0));
7584             }
7585           return NULL_TREE;
7586         }
7587
7588       expr = convert_nontype_argument_function (type, expr, complain);
7589       if (!expr || expr == error_mark_node)
7590         return expr;
7591     }
7592   /* [temp.arg.nontype]/5, bullet 6
7593
7594      For a non-type template-parameter of type pointer to member function,
7595      no conversions apply. If the template-argument represents a set of
7596      overloaded member functions, the matching member function is selected
7597      from the set (_over.over_).  */
7598   else if (TYPE_PTRMEMFUNC_P (type))
7599     {
7600       expr = instantiate_type (type, expr, tf_none);
7601       if (expr == error_mark_node)
7602         return error_mark_node;
7603
7604       /* [temp.arg.nontype] bullet 1 says the pointer to member
7605          expression must be a pointer-to-member constant.  */
7606       if (!val_dep_p
7607           && !check_valid_ptrmem_cst_expr (type, expr, complain))
7608         return NULL_TREE;
7609
7610       /* Repeated conversion can't deal with a conversion that turns PTRMEM_CST
7611          into a CONSTRUCTOR, so build up a new PTRMEM_CST instead.  */
7612       if (fnptr_conv_p (type, TREE_TYPE (expr)))
7613         expr = make_ptrmem_cst (type, PTRMEM_CST_MEMBER (expr));
7614     }
7615   /* [temp.arg.nontype]/5, bullet 7
7616
7617      For a non-type template-parameter of type pointer to data member,
7618      qualification conversions (_conv.qual_) are applied.  */
7619   else if (TYPE_PTRDATAMEM_P (type))
7620     {
7621       /* [temp.arg.nontype] bullet 1 says the pointer to member
7622          expression must be a pointer-to-member constant.  */
7623       if (!val_dep_p
7624           && !check_valid_ptrmem_cst_expr (type, expr, complain))
7625         return NULL_TREE;
7626
7627       expr = perform_qualification_conversions (type, expr);
7628       if (expr == error_mark_node)
7629         return expr;
7630     }
7631   else if (NULLPTR_TYPE_P (type))
7632     {
7633       if (!NULLPTR_TYPE_P (TREE_TYPE (expr)))
7634         {
7635           if (complain & tf_error)
7636             error ("%qE is not a valid template argument for type %qT "
7637                    "because it is of type %qT", expr, type, TREE_TYPE (expr));
7638           return NULL_TREE;
7639         }
7640       return expr;
7641     }
7642   else if (CLASS_TYPE_P (type))
7643     {
7644       /* Replace the argument with a reference to the corresponding template
7645          parameter object.  */
7646       if (!val_dep_p)
7647         expr = get_template_parm_object (expr, complain);
7648       if (expr == error_mark_node)
7649         return NULL_TREE;
7650     }
7651   /* A template non-type parameter must be one of the above.  */
7652   else
7653     gcc_unreachable ();
7654
7655   /* Sanity check: did we actually convert the argument to the
7656      right type?  */
7657   gcc_assert (same_type_ignoring_top_level_qualifiers_p
7658               (type, TREE_TYPE (expr)));
7659   return convert_from_reference (expr);
7660 }
7661
7662 /* Subroutine of coerce_template_template_parms, which returns 1 if
7663    PARM_PARM and ARG_PARM match using the rule for the template
7664    parameters of template template parameters. Both PARM and ARG are
7665    template parameters; the rest of the arguments are the same as for
7666    coerce_template_template_parms.
7667  */
7668 static int
7669 coerce_template_template_parm (tree parm,
7670                               tree arg,
7671                               tsubst_flags_t complain,
7672                               tree in_decl,
7673                               tree outer_args)
7674 {
7675   if (arg == NULL_TREE || error_operand_p (arg)
7676       || parm == NULL_TREE || error_operand_p (parm))
7677     return 0;
7678
7679   if (TREE_CODE (arg) != TREE_CODE (parm))
7680     return 0;
7681
7682   switch (TREE_CODE (parm))
7683     {
7684     case TEMPLATE_DECL:
7685       /* We encounter instantiations of templates like
7686          template <template <template <class> class> class TT>
7687          class C;  */
7688       {
7689         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
7690         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
7691
7692         if (!coerce_template_template_parms
7693             (parmparm, argparm, complain, in_decl, outer_args))
7694           return 0;
7695       }
7696       /* Fall through.  */
7697
7698     case TYPE_DECL:
7699       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
7700           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7701         /* Argument is a parameter pack but parameter is not.  */
7702         return 0;
7703       break;
7704
7705     case PARM_DECL:
7706       /* The tsubst call is used to handle cases such as
7707
7708            template <int> class C {};
7709            template <class T, template <T> class TT> class D {};
7710            D<int, C> d;
7711
7712          i.e. the parameter list of TT depends on earlier parameters.  */
7713       if (!uses_template_parms (TREE_TYPE (arg)))
7714         {
7715           tree t = tsubst (TREE_TYPE (parm), outer_args, complain, in_decl);
7716           if (!uses_template_parms (t)
7717               && !same_type_p (t, TREE_TYPE (arg)))
7718             return 0;
7719         }
7720
7721       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
7722           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7723         /* Argument is a parameter pack but parameter is not.  */
7724         return 0;
7725
7726       break;
7727
7728     default:
7729       gcc_unreachable ();
7730     }
7731
7732   return 1;
7733 }
7734
7735 /* Coerce template argument list ARGLIST for use with template
7736    template-parameter TEMPL.  */
7737
7738 static tree
7739 coerce_template_args_for_ttp (tree templ, tree arglist,
7740                               tsubst_flags_t complain)
7741 {
7742   /* Consider an example where a template template parameter declared as
7743
7744      template <class T, class U = std::allocator<T> > class TT
7745
7746      The template parameter level of T and U are one level larger than
7747      of TT.  To proper process the default argument of U, say when an
7748      instantiation `TT<int>' is seen, we need to build the full
7749      arguments containing {int} as the innermost level.  Outer levels,
7750      available when not appearing as default template argument, can be
7751      obtained from the arguments of the enclosing template.
7752
7753      Suppose that TT is later substituted with std::vector.  The above
7754      instantiation is `TT<int, std::allocator<T> >' with TT at
7755      level 1, and T at level 2, while the template arguments at level 1
7756      becomes {std::vector} and the inner level 2 is {int}.  */
7757
7758   tree outer = DECL_CONTEXT (templ);
7759   if (outer)
7760     outer = generic_targs_for (outer);
7761   else if (current_template_parms)
7762     {
7763       /* This is an argument of the current template, so we haven't set
7764          DECL_CONTEXT yet.  */
7765       tree relevant_template_parms;
7766
7767       /* Parameter levels that are greater than the level of the given
7768          template template parm are irrelevant.  */
7769       relevant_template_parms = current_template_parms;
7770       while (TMPL_PARMS_DEPTH (relevant_template_parms)
7771              != TEMPLATE_TYPE_LEVEL (TREE_TYPE (templ)))
7772         relevant_template_parms = TREE_CHAIN (relevant_template_parms);
7773
7774       outer = template_parms_to_args (relevant_template_parms);
7775     }
7776
7777   if (outer)
7778     arglist = add_to_template_args (outer, arglist);
7779
7780   tree parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7781   return coerce_template_parms (parmlist, arglist, templ,
7782                                 complain,
7783                                 /*require_all_args=*/true,
7784                                 /*use_default_args=*/true);
7785 }
7786
7787 /* A cache of template template parameters with match-all default
7788    arguments.  */
7789 static GTY((deletable)) hash_map<tree,tree> *defaulted_ttp_cache;
7790
7791 /* T is a bound template template-parameter.  Copy its arguments into default
7792    arguments of the template template-parameter's template parameters.  */
7793
7794 static tree
7795 add_defaults_to_ttp (tree otmpl)
7796 {
7797   if (tree *c = hash_map_safe_get (defaulted_ttp_cache, otmpl))
7798     return *c;
7799
7800   tree ntmpl = copy_node (otmpl);
7801
7802   tree ntype = copy_node (TREE_TYPE (otmpl));
7803   TYPE_STUB_DECL (ntype) = TYPE_NAME (ntype) = ntmpl;
7804   TYPE_MAIN_VARIANT (ntype) = ntype;
7805   TYPE_POINTER_TO (ntype) = TYPE_REFERENCE_TO (ntype) = NULL_TREE;
7806   TYPE_NAME (ntype) = ntmpl;
7807   SET_TYPE_STRUCTURAL_EQUALITY (ntype);
7808
7809   tree idx = TEMPLATE_TYPE_PARM_INDEX (ntype)
7810     = copy_node (TEMPLATE_TYPE_PARM_INDEX (ntype));
7811   TEMPLATE_PARM_DECL (idx) = ntmpl;
7812   TREE_TYPE (ntmpl) = TREE_TYPE (idx) = ntype;
7813
7814   tree oparms = DECL_TEMPLATE_PARMS (otmpl);
7815   tree parms = DECL_TEMPLATE_PARMS (ntmpl) = copy_node (oparms);
7816   TREE_CHAIN (parms) = TREE_CHAIN (oparms);
7817   tree vec = TREE_VALUE (parms) = copy_node (TREE_VALUE (parms));
7818   for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
7819     {
7820       tree o = TREE_VEC_ELT (vec, i);
7821       if (!template_parameter_pack_p (TREE_VALUE (o)))
7822         {
7823           tree n = TREE_VEC_ELT (vec, i) = copy_node (o);
7824           TREE_PURPOSE (n) = any_targ_node;
7825         }
7826     }
7827
7828   hash_map_safe_put<hm_ggc> (defaulted_ttp_cache, otmpl, ntmpl);
7829   return ntmpl;
7830 }
7831
7832 /* ARG is a bound potential template template-argument, and PARGS is a list
7833    of arguments for the corresponding template template-parameter.  Adjust
7834    PARGS as appropriate for application to ARG's template, and if ARG is a
7835    BOUND_TEMPLATE_TEMPLATE_PARM, possibly adjust it to add default template
7836    arguments to the template template parameter.  */
7837
7838 static tree
7839 coerce_ttp_args_for_tta (tree& arg, tree pargs, tsubst_flags_t complain)
7840 {
7841   ++processing_template_decl;
7842   tree arg_tmpl = TYPE_TI_TEMPLATE (arg);
7843   if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
7844     {
7845       /* When comparing two template template-parameters in partial ordering,
7846          rewrite the one currently being used as an argument to have default
7847          arguments for all parameters.  */
7848       arg_tmpl = add_defaults_to_ttp (arg_tmpl);
7849       pargs = coerce_template_args_for_ttp (arg_tmpl, pargs, complain);
7850       if (pargs != error_mark_node)
7851         arg = bind_template_template_parm (TREE_TYPE (arg_tmpl),
7852                                            TYPE_TI_ARGS (arg));
7853     }
7854   else
7855     {
7856       tree aparms
7857         = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (arg_tmpl));
7858       pargs = coerce_template_parms (aparms, pargs, arg_tmpl, complain,
7859                                        /*require_all*/true,
7860                                        /*use_default*/true);
7861     }
7862   --processing_template_decl;
7863   return pargs;
7864 }
7865
7866 /* Subroutine of unify for the case when PARM is a
7867    BOUND_TEMPLATE_TEMPLATE_PARM.  */
7868
7869 static int
7870 unify_bound_ttp_args (tree tparms, tree targs, tree parm, tree& arg,
7871                       bool explain_p)
7872 {
7873   tree parmvec = TYPE_TI_ARGS (parm);
7874   tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
7875
7876   /* The template template parm might be variadic and the argument
7877      not, so flatten both argument lists.  */
7878   parmvec = expand_template_argument_pack (parmvec);
7879   argvec = expand_template_argument_pack (argvec);
7880
7881   if (flag_new_ttp)
7882     {
7883       /* In keeping with P0522R0, adjust P's template arguments
7884          to apply to A's template; then flatten it again.  */
7885       tree nparmvec = coerce_ttp_args_for_tta (arg, parmvec, tf_none);
7886       nparmvec = expand_template_argument_pack (nparmvec);
7887
7888       if (unify (tparms, targs, nparmvec, argvec,
7889                  UNIFY_ALLOW_NONE, explain_p))
7890         return 1;
7891
7892       /* If the P0522 adjustment eliminated a pack expansion, deduce
7893          empty packs.  */
7894       if (flag_new_ttp
7895           && TREE_VEC_LENGTH (nparmvec) < TREE_VEC_LENGTH (parmvec)
7896           && unify_pack_expansion (tparms, targs, parmvec, argvec,
7897                                    DEDUCE_EXACT, /*sub*/true, explain_p))
7898         return 1;
7899     }
7900   else
7901     {
7902       /* Deduce arguments T, i from TT<T> or TT<i>.
7903          We check each element of PARMVEC and ARGVEC individually
7904          rather than the whole TREE_VEC since they can have
7905          different number of elements, which is allowed under N2555.  */
7906
7907       int len = TREE_VEC_LENGTH (parmvec);
7908
7909       /* Check if the parameters end in a pack, making them
7910          variadic.  */
7911       int parm_variadic_p = 0;
7912       if (len > 0
7913           && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
7914         parm_variadic_p = 1;
7915
7916       for (int i = 0; i < len - parm_variadic_p; ++i)
7917         /* If the template argument list of P contains a pack
7918            expansion that is not the last template argument, the
7919            entire template argument list is a non-deduced
7920            context.  */
7921         if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
7922           return unify_success (explain_p);
7923
7924       if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
7925         return unify_too_few_arguments (explain_p,
7926                                         TREE_VEC_LENGTH (argvec), len);
7927
7928       for (int i = 0; i < len - parm_variadic_p; ++i)
7929         if (unify (tparms, targs,
7930                    TREE_VEC_ELT (parmvec, i),
7931                    TREE_VEC_ELT (argvec, i),
7932                    UNIFY_ALLOW_NONE, explain_p))
7933           return 1;
7934
7935       if (parm_variadic_p
7936           && unify_pack_expansion (tparms, targs,
7937                                    parmvec, argvec,
7938                                    DEDUCE_EXACT,
7939                                    /*subr=*/true, explain_p))
7940         return 1;
7941     }
7942
7943   return 0;
7944 }
7945
7946 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
7947    template template parameters.  Both PARM_PARMS and ARG_PARMS are
7948    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
7949    or PARM_DECL.
7950
7951    Consider the example:
7952      template <class T> class A;
7953      template<template <class U> class TT> class B;
7954
7955    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
7956    the parameters to A, and OUTER_ARGS contains A.  */
7957
7958 static int
7959 coerce_template_template_parms (tree parm_parms,
7960                                 tree arg_parms,
7961                                 tsubst_flags_t complain,
7962                                 tree in_decl,
7963                                 tree outer_args)
7964 {
7965   int nparms, nargs, i;
7966   tree parm, arg;
7967   int variadic_p = 0;
7968
7969   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
7970   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
7971
7972   nparms = TREE_VEC_LENGTH (parm_parms);
7973   nargs = TREE_VEC_LENGTH (arg_parms);
7974
7975   if (flag_new_ttp)
7976     {
7977       /* P0522R0: A template template-parameter P is at least as specialized as
7978          a template template-argument A if, given the following rewrite to two
7979          function templates, the function template corresponding to P is at
7980          least as specialized as the function template corresponding to A
7981          according to the partial ordering rules for function templates
7982          ([temp.func.order]). Given an invented class template X with the
7983          template parameter list of A (including default arguments):
7984
7985          * Each of the two function templates has the same template parameters,
7986          respectively, as P or A.
7987
7988          * Each function template has a single function parameter whose type is
7989          a specialization of X with template arguments corresponding to the
7990          template parameters from the respective function template where, for
7991          each template parameter PP in the template parameter list of the
7992          function template, a corresponding template argument AA is formed. If
7993          PP declares a parameter pack, then AA is the pack expansion
7994          PP... ([temp.variadic]); otherwise, AA is the id-expression PP.
7995
7996          If the rewrite produces an invalid type, then P is not at least as
7997          specialized as A.  */
7998
7999       /* So coerce P's args to apply to A's parms, and then deduce between A's
8000          args and the converted args.  If that succeeds, A is at least as
8001          specialized as P, so they match.*/
8002       tree pargs = template_parms_level_to_args (parm_parms);
8003       pargs = add_outermost_template_args (outer_args, pargs);
8004       ++processing_template_decl;
8005       pargs = coerce_template_parms (arg_parms, pargs, NULL_TREE, tf_none,
8006                                      /*require_all*/true, /*use_default*/true);
8007       --processing_template_decl;
8008       if (pargs != error_mark_node)
8009         {
8010           tree targs = make_tree_vec (nargs);
8011           tree aargs = template_parms_level_to_args (arg_parms);
8012           if (!unify (arg_parms, targs, aargs, pargs, UNIFY_ALLOW_NONE,
8013                       /*explain*/false))
8014             return 1;
8015         }
8016     }
8017
8018   /* Determine whether we have a parameter pack at the end of the
8019      template template parameter's template parameter list.  */
8020   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
8021     {
8022       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
8023
8024       if (error_operand_p (parm))
8025         return 0;
8026
8027       switch (TREE_CODE (parm))
8028         {
8029         case TEMPLATE_DECL:
8030         case TYPE_DECL:
8031           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
8032             variadic_p = 1;
8033           break;
8034
8035         case PARM_DECL:
8036           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
8037             variadic_p = 1;
8038           break;
8039
8040         default:
8041           gcc_unreachable ();
8042         }
8043     }
8044
8045   if (nargs != nparms
8046       && !(variadic_p && nargs >= nparms - 1))
8047     return 0;
8048
8049   /* Check all of the template parameters except the parameter pack at
8050      the end (if any).  */
8051   for (i = 0; i < nparms - variadic_p; ++i)
8052     {
8053       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
8054           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
8055         continue;
8056
8057       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
8058       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
8059
8060       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
8061                                           outer_args))
8062         return 0;
8063
8064     }
8065
8066   if (variadic_p)
8067     {
8068       /* Check each of the template parameters in the template
8069          argument against the template parameter pack at the end of
8070          the template template parameter.  */
8071       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
8072         return 0;
8073
8074       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
8075
8076       for (; i < nargs; ++i)
8077         {
8078           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
8079             continue;
8080
8081           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
8082
8083           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
8084                                               outer_args))
8085             return 0;
8086         }
8087     }
8088
8089   return 1;
8090 }
8091
8092 /* Verifies that the deduced template arguments (in TARGS) for the
8093    template template parameters (in TPARMS) represent valid bindings,
8094    by comparing the template parameter list of each template argument
8095    to the template parameter list of its corresponding template
8096    template parameter, in accordance with DR150. This
8097    routine can only be called after all template arguments have been
8098    deduced. It will return TRUE if all of the template template
8099    parameter bindings are okay, FALSE otherwise.  */
8100 bool
8101 template_template_parm_bindings_ok_p (tree tparms, tree targs)
8102 {
8103   int i, ntparms = TREE_VEC_LENGTH (tparms);
8104   bool ret = true;
8105
8106   /* We're dealing with template parms in this process.  */
8107   ++processing_template_decl;
8108
8109   targs = INNERMOST_TEMPLATE_ARGS (targs);
8110
8111   for (i = 0; i < ntparms; ++i)
8112     {
8113       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
8114       tree targ = TREE_VEC_ELT (targs, i);
8115
8116       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
8117         {
8118           tree packed_args = NULL_TREE;
8119           int idx, len = 1;
8120
8121           if (ARGUMENT_PACK_P (targ))
8122             {
8123               /* Look inside the argument pack.  */
8124               packed_args = ARGUMENT_PACK_ARGS (targ);
8125               len = TREE_VEC_LENGTH (packed_args);
8126             }
8127
8128           for (idx = 0; idx < len; ++idx)
8129             {
8130               tree targ_parms = NULL_TREE;
8131
8132               if (packed_args)
8133                 /* Extract the next argument from the argument
8134                    pack.  */
8135                 targ = TREE_VEC_ELT (packed_args, idx);
8136
8137               if (PACK_EXPANSION_P (targ))
8138                 /* Look at the pattern of the pack expansion.  */
8139                 targ = PACK_EXPANSION_PATTERN (targ);
8140
8141               /* Extract the template parameters from the template
8142                  argument.  */
8143               if (TREE_CODE (targ) == TEMPLATE_DECL)
8144                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
8145               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
8146                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
8147
8148               /* Verify that we can coerce the template template
8149                  parameters from the template argument to the template
8150                  parameter.  This requires an exact match.  */
8151               if (targ_parms
8152                   && !coerce_template_template_parms
8153                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
8154                         targ_parms,
8155                         tf_none,
8156                         tparm,
8157                         targs))
8158                 {
8159                   ret = false;
8160                   goto out;
8161                 }
8162             }
8163         }
8164     }
8165
8166  out:
8167
8168   --processing_template_decl;
8169   return ret;
8170 }
8171
8172 /* Since type attributes aren't mangled, we need to strip them from
8173    template type arguments.  */
8174
8175 tree
8176 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
8177 {
8178   if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
8179     return arg;
8180   bool removed_attributes = false;
8181   tree canon = strip_typedefs (arg, &removed_attributes);
8182   if (removed_attributes
8183       && (complain & tf_warning))
8184     warning (OPT_Wignored_attributes,
8185              "ignoring attributes on template argument %qT", arg);
8186   return canon;
8187 }
8188
8189 /* And from inside dependent non-type arguments like sizeof(Type).  */
8190
8191 static tree
8192 canonicalize_expr_argument (tree arg, tsubst_flags_t complain)
8193 {
8194   if (!arg || arg == error_mark_node)
8195     return arg;
8196   bool removed_attributes = false;
8197   tree canon = strip_typedefs_expr (arg, &removed_attributes);
8198   if (removed_attributes
8199       && (complain & tf_warning))
8200     warning (OPT_Wignored_attributes,
8201              "ignoring attributes in template argument %qE", arg);
8202   return canon;
8203 }
8204
8205 /* A template declaration can be substituted for a constrained
8206    template template parameter only when the argument is no more
8207    constrained than the parameter.  */
8208
8209 static bool
8210 is_compatible_template_arg (tree parm, tree arg)
8211 {
8212   tree parm_cons = get_constraints (parm);
8213
8214   /* For now, allow constrained template template arguments
8215      and unconstrained template template parameters.  */
8216   if (parm_cons == NULL_TREE)
8217     return true;
8218
8219   /* If the template parameter is constrained, we need to rewrite its
8220      constraints in terms of the ARG's template parameters. This ensures
8221      that all of the template parameter types will have the same depth.
8222
8223      Note that this is only valid when coerce_template_template_parm is
8224      true for the innermost template parameters of PARM and ARG. In other
8225      words, because coercion is successful, this conversion will be valid.  */
8226   tree new_args = NULL_TREE;
8227   if (parm_cons)
8228     {
8229       tree aparms = DECL_INNERMOST_TEMPLATE_PARMS (arg);
8230       new_args = template_parms_level_to_args (aparms);
8231       parm_cons = tsubst_constraint_info (parm_cons, new_args,
8232                                           tf_none, NULL_TREE);
8233       if (parm_cons == error_mark_node)
8234         return false;
8235     }
8236
8237   return weakly_subsumes (parm_cons, arg);
8238 }
8239
8240 // Convert a placeholder argument into a binding to the original
8241 // parameter. The original parameter is saved as the TREE_TYPE of
8242 // ARG.
8243 static inline tree
8244 convert_wildcard_argument (tree parm, tree arg)
8245 {
8246   TREE_TYPE (arg) = parm;
8247   return arg;
8248 }
8249
8250 /* We can't fully resolve ARG given as a non-type template argument to TYPE,
8251    because one of them is dependent.  But we need to represent the
8252    conversion for the benefit of cp_tree_equal.  */
8253
8254 static tree
8255 maybe_convert_nontype_argument (tree type, tree arg)
8256 {
8257   /* Auto parms get no conversion.  */
8258   if (type_uses_auto (type))
8259     return arg;
8260   /* We don't need or want to add this conversion now if we're going to use the
8261      argument for deduction.  */
8262   if (value_dependent_expression_p (arg))
8263     return arg;
8264
8265   type = cv_unqualified (type);
8266   tree argtype = TREE_TYPE (arg);
8267   if (same_type_p (type, argtype))
8268     return arg;
8269
8270   arg = build1 (IMPLICIT_CONV_EXPR, type, arg);
8271   IMPLICIT_CONV_EXPR_NONTYPE_ARG (arg) = true;
8272   return arg;
8273 }
8274
8275 /* Convert the indicated template ARG as necessary to match the
8276    indicated template PARM.  Returns the converted ARG, or
8277    error_mark_node if the conversion was unsuccessful.  Error and
8278    warning messages are issued under control of COMPLAIN.  This
8279    conversion is for the Ith parameter in the parameter list.  ARGS is
8280    the full set of template arguments deduced so far.  */
8281
8282 static tree
8283 convert_template_argument (tree parm,
8284                            tree arg,
8285                            tree args,
8286                            tsubst_flags_t complain,
8287                            int i,
8288                            tree in_decl)
8289 {
8290   tree orig_arg;
8291   tree val;
8292   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
8293
8294   if (parm == error_mark_node || error_operand_p (arg))
8295     return error_mark_node;
8296
8297   /* Trivially convert placeholders. */
8298   if (TREE_CODE (arg) == WILDCARD_DECL)
8299     return convert_wildcard_argument (parm, arg);
8300
8301   if (arg == any_targ_node)
8302     return arg;
8303
8304   if (TREE_CODE (arg) == TREE_LIST
8305       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
8306     {
8307       /* The template argument was the name of some
8308          member function.  That's usually
8309          invalid, but static members are OK.  In any
8310          case, grab the underlying fields/functions
8311          and issue an error later if required.  */
8312       TREE_TYPE (arg) = unknown_type_node;
8313     }
8314
8315   orig_arg = arg;
8316
8317   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
8318   requires_type = (TREE_CODE (parm) == TYPE_DECL
8319                    || requires_tmpl_type);
8320
8321   /* When determining whether an argument pack expansion is a template,
8322      look at the pattern.  */
8323   if (PACK_EXPANSION_P (arg))
8324     arg = PACK_EXPANSION_PATTERN (arg);
8325
8326   /* Deal with an injected-class-name used as a template template arg.  */
8327   if (requires_tmpl_type && CLASS_TYPE_P (arg))
8328     {
8329       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
8330       if (TREE_CODE (t) == TEMPLATE_DECL)
8331         {
8332           if (cxx_dialect >= cxx11)
8333             /* OK under DR 1004.  */;
8334           else if (complain & tf_warning_or_error)
8335             pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
8336                      " used as template template argument", TYPE_NAME (arg));
8337           else if (flag_pedantic_errors)
8338             t = arg;
8339
8340           arg = t;
8341         }
8342     }
8343
8344   is_tmpl_type =
8345     ((TREE_CODE (arg) == TEMPLATE_DECL
8346       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
8347      || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
8348      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8349      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
8350
8351   if (is_tmpl_type
8352       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8353           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
8354     arg = TYPE_STUB_DECL (arg);
8355
8356   is_type = TYPE_P (arg) || is_tmpl_type;
8357
8358   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
8359       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
8360     {
8361       if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
8362         {
8363           if (complain & tf_error)
8364             error ("invalid use of destructor %qE as a type", orig_arg);
8365           return error_mark_node;
8366         }
8367
8368       permerror (input_location,
8369                  "to refer to a type member of a template parameter, "
8370                  "use %<typename %E%>", orig_arg);
8371
8372       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
8373                                      TREE_OPERAND (arg, 1),
8374                                      typename_type,
8375                                      complain);
8376       arg = orig_arg;
8377       is_type = 1;
8378     }
8379   if (is_type != requires_type)
8380     {
8381       if (in_decl)
8382         {
8383           if (complain & tf_error)
8384             {
8385               error ("type/value mismatch at argument %d in template "
8386                      "parameter list for %qD",
8387                      i + 1, in_decl);
8388               if (is_type)
8389                 {
8390                   /* The template argument is a type, but we're expecting
8391                      an expression.  */
8392                   inform (input_location,
8393                           "  expected a constant of type %qT, got %qT",
8394                           TREE_TYPE (parm),
8395                           (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
8396                   /* [temp.arg]/2: "In a template-argument, an ambiguity
8397                      between a type-id and an expression is resolved to a
8398                      type-id, regardless of the form of the corresponding
8399                      template-parameter."  So give the user a clue.  */
8400                   if (TREE_CODE (arg) == FUNCTION_TYPE)
8401                     inform (input_location, "  ambiguous template argument "
8402                             "for non-type template parameter is treated as "
8403                             "function type");
8404                 }
8405               else if (requires_tmpl_type)
8406                 inform (input_location,
8407                         "  expected a class template, got %qE", orig_arg);
8408               else
8409                 inform (input_location,
8410                         "  expected a type, got %qE", orig_arg);
8411             }
8412         }
8413       return error_mark_node;
8414     }
8415   if (is_tmpl_type ^ requires_tmpl_type)
8416     {
8417       if (in_decl && (complain & tf_error))
8418         {
8419           error ("type/value mismatch at argument %d in template "
8420                  "parameter list for %qD",
8421                  i + 1, in_decl);
8422           if (is_tmpl_type)
8423             inform (input_location,
8424                     "  expected a type, got %qT", DECL_NAME (arg));
8425           else
8426             inform (input_location,
8427                     "  expected a class template, got %qT", orig_arg);
8428         }
8429       return error_mark_node;
8430     }
8431
8432   if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
8433     /* We already did the appropriate conversion when packing args.  */
8434     val = orig_arg;
8435   else if (is_type)
8436     {
8437       if (requires_tmpl_type)
8438         {
8439           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
8440             /* The number of argument required is not known yet.
8441                Just accept it for now.  */
8442             val = orig_arg;
8443           else
8444             {
8445               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
8446               tree argparm;
8447
8448               /* Strip alias templates that are equivalent to another
8449                  template.  */
8450               arg = get_underlying_template (arg);
8451               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
8452
8453               if (coerce_template_template_parms (parmparm, argparm,
8454                                                   complain, in_decl,
8455                                                   args))
8456                 {
8457                   val = arg;
8458
8459                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
8460                      TEMPLATE_DECL.  */
8461                   if (val != error_mark_node)
8462                     {
8463                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
8464                         val = TREE_TYPE (val);
8465                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
8466                         val = make_pack_expansion (val, complain);
8467                     }
8468                 }
8469               else
8470                 {
8471                   if (in_decl && (complain & tf_error))
8472                     {
8473                       error ("type/value mismatch at argument %d in "
8474                              "template parameter list for %qD",
8475                              i + 1, in_decl);
8476                       inform (input_location,
8477                               "  expected a template of type %qD, got %qT",
8478                               parm, orig_arg);
8479                     }
8480
8481                   val = error_mark_node;
8482                 }
8483
8484               // Check that the constraints are compatible before allowing the
8485               // substitution.
8486               if (val != error_mark_node)
8487                 if (!is_compatible_template_arg (parm, arg))
8488                   {
8489                     if (in_decl && (complain & tf_error))
8490                       {
8491                         error ("constraint mismatch at argument %d in "
8492                                "template parameter list for %qD",
8493                                i + 1, in_decl);
8494                         inform (input_location, "  expected %qD but got %qD",
8495                                 parm, arg);
8496                       }
8497                     val = error_mark_node;
8498                   }
8499             }
8500         }
8501       else
8502         val = orig_arg;
8503       /* We only form one instance of each template specialization.
8504          Therefore, if we use a non-canonical variant (i.e., a
8505          typedef), any future messages referring to the type will use
8506          the typedef, which is confusing if those future uses do not
8507          themselves also use the typedef.  */
8508       if (TYPE_P (val))
8509         val = canonicalize_type_argument (val, complain);
8510     }
8511   else
8512     {
8513       tree t = TREE_TYPE (parm);
8514
8515       if (TEMPLATE_PARM_LEVEL (get_template_parm_index (parm))
8516           > TMPL_ARGS_DEPTH (args))
8517         /* We don't have enough levels of args to do any substitution.  This
8518            can happen in the context of -fnew-ttp-matching.  */;
8519       else if (tree a = type_uses_auto (t))
8520         {
8521           t = do_auto_deduction (t, arg, a, complain, adc_unify, args);
8522           if (t == error_mark_node)
8523             return error_mark_node;
8524         }
8525       else
8526         t = tsubst (t, args, complain, in_decl);
8527
8528       if (invalid_nontype_parm_type_p (t, complain))
8529         return error_mark_node;
8530
8531       if (t != TREE_TYPE (parm))
8532         t = canonicalize_type_argument (t, complain);
8533
8534       if (!type_dependent_expression_p (orig_arg)
8535           && !uses_template_parms (t))
8536         /* We used to call digest_init here.  However, digest_init
8537            will report errors, which we don't want when complain
8538            is zero.  More importantly, digest_init will try too
8539            hard to convert things: for example, `0' should not be
8540            converted to pointer type at this point according to
8541            the standard.  Accepting this is not merely an
8542            extension, since deciding whether or not these
8543            conversions can occur is part of determining which
8544            function template to call, or whether a given explicit
8545            argument specification is valid.  */
8546         val = convert_nontype_argument (t, orig_arg, complain);
8547       else
8548         {
8549           val = canonicalize_expr_argument (orig_arg, complain);
8550           val = maybe_convert_nontype_argument (t, val);
8551         }
8552
8553
8554       if (val == NULL_TREE)
8555         val = error_mark_node;
8556       else if (val == error_mark_node && (complain & tf_error))
8557         error_at (cp_expr_loc_or_input_loc (orig_arg),
8558                   "could not convert template argument %qE from %qT to %qT",
8559                   orig_arg, TREE_TYPE (orig_arg), t);
8560
8561       if (INDIRECT_REF_P (val))
8562         {
8563           /* Reject template arguments that are references to built-in
8564              functions with no library fallbacks.  */
8565           const_tree inner = TREE_OPERAND (val, 0);
8566           const_tree innertype = TREE_TYPE (inner);
8567           if (innertype
8568               && TYPE_REF_P (innertype)
8569               && TREE_CODE (TREE_TYPE (innertype)) == FUNCTION_TYPE
8570               && TREE_OPERAND_LENGTH (inner) > 0
8571               && reject_gcc_builtin (TREE_OPERAND (inner, 0)))
8572               return error_mark_node;
8573         }
8574
8575       if (TREE_CODE (val) == SCOPE_REF)
8576         {
8577           /* Strip typedefs from the SCOPE_REF.  */
8578           tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
8579           tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
8580                                                    complain);
8581           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
8582                                       QUALIFIED_NAME_IS_TEMPLATE (val));
8583         }
8584     }
8585
8586   return val;
8587 }
8588
8589 /* Coerces the remaining template arguments in INNER_ARGS (from
8590    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
8591    Returns the coerced argument pack. PARM_IDX is the position of this
8592    parameter in the template parameter list. ARGS is the original
8593    template argument list.  */
8594 static tree
8595 coerce_template_parameter_pack (tree parms,
8596                                 int parm_idx,
8597                                 tree args,
8598                                 tree inner_args,
8599                                 int arg_idx,
8600                                 tree new_args,
8601                                 int* lost,
8602                                 tree in_decl,
8603                                 tsubst_flags_t complain)
8604 {
8605   tree parm = TREE_VEC_ELT (parms, parm_idx);
8606   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8607   tree packed_args;
8608   tree argument_pack;
8609   tree packed_parms = NULL_TREE;
8610
8611   if (arg_idx > nargs)
8612     arg_idx = nargs;
8613
8614   if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
8615     {
8616       /* When the template parameter is a non-type template parameter pack
8617          or template template parameter pack whose type or template
8618          parameters use parameter packs, we know exactly how many arguments
8619          we are looking for.  Build a vector of the instantiated decls for
8620          these template parameters in PACKED_PARMS.  */
8621       /* We can't use make_pack_expansion here because it would interpret a
8622          _DECL as a use rather than a declaration.  */
8623       tree decl = TREE_VALUE (parm);
8624       tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
8625       SET_PACK_EXPANSION_PATTERN (exp, decl);
8626       PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
8627       SET_TYPE_STRUCTURAL_EQUALITY (exp);
8628
8629       TREE_VEC_LENGTH (args)--;
8630       packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
8631       TREE_VEC_LENGTH (args)++;
8632
8633       if (packed_parms == error_mark_node)
8634         return error_mark_node;
8635
8636       /* If we're doing a partial instantiation of a member template,
8637          verify that all of the types used for the non-type
8638          template parameter pack are, in fact, valid for non-type
8639          template parameters.  */
8640       if (arg_idx < nargs
8641           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
8642         {
8643           int j, len = TREE_VEC_LENGTH (packed_parms);
8644           for (j = 0; j < len; ++j)
8645             {
8646               tree t = TREE_VEC_ELT (packed_parms, j);
8647               if (TREE_CODE (t) == PARM_DECL
8648                   && invalid_nontype_parm_type_p (TREE_TYPE (t), complain))
8649                 return error_mark_node;
8650             }
8651           /* We don't know how many args we have yet, just
8652              use the unconverted ones for now.  */
8653           return NULL_TREE;
8654         }
8655
8656       packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
8657     }
8658   /* Check if we have a placeholder pack, which indicates we're
8659      in the context of a introduction list.  In that case we want
8660      to match this pack to the single placeholder.  */
8661   else if (arg_idx < nargs
8662            && TREE_CODE (TREE_VEC_ELT (inner_args, arg_idx)) == WILDCARD_DECL
8663            && WILDCARD_PACK_P (TREE_VEC_ELT (inner_args, arg_idx)))
8664     {
8665       nargs = arg_idx + 1;
8666       packed_args = make_tree_vec (1);
8667     }
8668   else
8669     packed_args = make_tree_vec (nargs - arg_idx);
8670
8671   /* Convert the remaining arguments, which will be a part of the
8672      parameter pack "parm".  */
8673   int first_pack_arg = arg_idx;
8674   for (; arg_idx < nargs; ++arg_idx)
8675     {
8676       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
8677       tree actual_parm = TREE_VALUE (parm);
8678       int pack_idx = arg_idx - first_pack_arg;
8679
8680       if (packed_parms)
8681         {
8682           /* Once we've packed as many args as we have types, stop.  */
8683           if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
8684             break;
8685           else if (PACK_EXPANSION_P (arg))
8686             /* We don't know how many args we have yet, just
8687                use the unconverted ones for now.  */
8688             return NULL_TREE;
8689           else
8690             actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
8691         }
8692
8693       if (arg == error_mark_node)
8694         {
8695           if (complain & tf_error)
8696             error ("template argument %d is invalid", arg_idx + 1);
8697         }
8698       else
8699         arg = convert_template_argument (actual_parm,
8700                                          arg, new_args, complain, parm_idx,
8701                                          in_decl);
8702       if (arg == error_mark_node)
8703         (*lost)++;
8704       TREE_VEC_ELT (packed_args, pack_idx) = arg;
8705     }
8706
8707   if (arg_idx - first_pack_arg < TREE_VEC_LENGTH (packed_args)
8708       && TREE_VEC_LENGTH (packed_args) > 0)
8709     {
8710       if (complain & tf_error)
8711         error ("wrong number of template arguments (%d, should be %d)",
8712                arg_idx - first_pack_arg, TREE_VEC_LENGTH (packed_args));
8713       return error_mark_node;
8714     }
8715
8716   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
8717       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
8718     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
8719   else
8720     {
8721       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
8722       TREE_CONSTANT (argument_pack) = 1;
8723     }
8724
8725   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
8726   if (CHECKING_P)
8727     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
8728                                          TREE_VEC_LENGTH (packed_args));
8729   return argument_pack;
8730 }
8731
8732 /* Returns the number of pack expansions in the template argument vector
8733    ARGS.  */
8734
8735 static int
8736 pack_expansion_args_count (tree args)
8737 {
8738   int i;
8739   int count = 0;
8740   if (args)
8741     for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
8742       {
8743         tree elt = TREE_VEC_ELT (args, i);
8744         if (elt && PACK_EXPANSION_P (elt))
8745           ++count;
8746       }
8747   return count;
8748 }
8749
8750 /* Convert all template arguments to their appropriate types, and
8751    return a vector containing the innermost resulting template
8752    arguments.  If any error occurs, return error_mark_node. Error and
8753    warning messages are issued under control of COMPLAIN.
8754
8755    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
8756    for arguments not specified in ARGS.  Otherwise, if
8757    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
8758    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
8759    USE_DEFAULT_ARGS is false, then all arguments must be specified in
8760    ARGS.  */
8761
8762 static tree
8763 coerce_template_parms (tree parms,
8764                        tree args,
8765                        tree in_decl,
8766                        tsubst_flags_t complain,
8767                        bool require_all_args,
8768                        bool use_default_args)
8769 {
8770   int nparms, nargs, parm_idx, arg_idx, lost = 0;
8771   tree orig_inner_args;
8772   tree inner_args;
8773   tree new_args;
8774   tree new_inner_args;
8775
8776   /* When used as a boolean value, indicates whether this is a
8777      variadic template parameter list. Since it's an int, we can also
8778      subtract it from nparms to get the number of non-variadic
8779      parameters.  */
8780   int variadic_p = 0;
8781   int variadic_args_p = 0;
8782   int post_variadic_parms = 0;
8783
8784   /* Adjustment to nparms for fixed parameter packs.  */
8785   int fixed_pack_adjust = 0;
8786   int fixed_packs = 0;
8787   int missing = 0;
8788
8789   /* Likewise for parameters with default arguments.  */
8790   int default_p = 0;
8791
8792   if (args == error_mark_node)
8793     return error_mark_node;
8794
8795   nparms = TREE_VEC_LENGTH (parms);
8796
8797   /* Determine if there are any parameter packs or default arguments.  */
8798   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
8799     {
8800       tree parm = TREE_VEC_ELT (parms, parm_idx);
8801       if (variadic_p)
8802         ++post_variadic_parms;
8803       if (template_parameter_pack_p (TREE_VALUE (parm)))
8804         ++variadic_p;
8805       if (TREE_PURPOSE (parm))
8806         ++default_p;
8807     }
8808
8809   inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
8810   /* If there are no parameters that follow a parameter pack, we need to
8811      expand any argument packs so that we can deduce a parameter pack from
8812      some non-packed args followed by an argument pack, as in variadic85.C.
8813      If there are such parameters, we need to leave argument packs intact
8814      so the arguments are assigned properly.  This can happen when dealing
8815      with a nested class inside a partial specialization of a class
8816      template, as in variadic92.C, or when deducing a template parameter pack
8817      from a sub-declarator, as in variadic114.C.  */
8818   if (!post_variadic_parms)
8819     inner_args = expand_template_argument_pack (inner_args);
8820
8821   /* Count any pack expansion args.  */
8822   variadic_args_p = pack_expansion_args_count (inner_args);
8823
8824   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8825   if ((nargs - variadic_args_p > nparms && !variadic_p)
8826       || (nargs < nparms - variadic_p
8827           && require_all_args
8828           && !variadic_args_p
8829           && (!use_default_args
8830               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
8831                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
8832     {
8833     bad_nargs:
8834       if (complain & tf_error)
8835         {
8836           if (variadic_p || default_p)
8837             {
8838               nparms -= variadic_p + default_p;
8839               error ("wrong number of template arguments "
8840                      "(%d, should be at least %d)", nargs, nparms);
8841             }
8842           else
8843              error ("wrong number of template arguments "
8844                     "(%d, should be %d)", nargs, nparms);
8845
8846           if (in_decl)
8847             inform (DECL_SOURCE_LOCATION (in_decl),
8848                     "provided for %qD", in_decl);
8849         }
8850
8851       return error_mark_node;
8852     }
8853   /* We can't pass a pack expansion to a non-pack parameter of an alias
8854      template (DR 1430).  */
8855   else if (in_decl
8856            && (DECL_ALIAS_TEMPLATE_P (in_decl)
8857                || concept_definition_p (in_decl))
8858            && variadic_args_p
8859            && nargs - variadic_args_p < nparms - variadic_p)
8860     {
8861       if (complain & tf_error)
8862         {
8863           for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
8864             {
8865               tree arg = TREE_VEC_ELT (inner_args, i);
8866               tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
8867
8868               if (PACK_EXPANSION_P (arg)
8869                   && !template_parameter_pack_p (parm))
8870                 {
8871                   if (DECL_ALIAS_TEMPLATE_P (in_decl))
8872                     error_at (location_of (arg),
8873                               "pack expansion argument for non-pack parameter "
8874                               "%qD of alias template %qD", parm, in_decl);
8875                   else
8876                     error_at (location_of (arg),
8877                               "pack expansion argument for non-pack parameter "
8878                               "%qD of concept %qD", parm, in_decl);
8879                   inform (DECL_SOURCE_LOCATION (parm), "declared here");
8880                   goto found;
8881                 }
8882             }
8883           gcc_unreachable ();
8884         found:;
8885         }
8886       return error_mark_node;
8887     }
8888
8889   /* We need to evaluate the template arguments, even though this
8890      template-id may be nested within a "sizeof".  */
8891   cp_evaluated ev;
8892
8893   new_inner_args = make_tree_vec (nparms);
8894   new_args = add_outermost_template_args (args, new_inner_args);
8895   int pack_adjust = 0;
8896   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
8897     {
8898       tree arg;
8899       tree parm;
8900
8901       /* Get the Ith template parameter.  */
8902       parm = TREE_VEC_ELT (parms, parm_idx);
8903
8904       if (parm == error_mark_node)
8905         {
8906           TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
8907           continue;
8908         }
8909
8910       /* Calculate the next argument.  */
8911       if (arg_idx < nargs)
8912         arg = TREE_VEC_ELT (inner_args, arg_idx);
8913       else
8914         arg = NULL_TREE;
8915
8916       if (template_parameter_pack_p (TREE_VALUE (parm))
8917           && (arg || require_all_args || !(complain & tf_partial))
8918           && !(arg && ARGUMENT_PACK_P (arg)))
8919         {
8920           /* Some arguments will be placed in the
8921              template parameter pack PARM.  */
8922           arg = coerce_template_parameter_pack (parms, parm_idx, args,
8923                                                 inner_args, arg_idx,
8924                                                 new_args, &lost,
8925                                                 in_decl, complain);
8926
8927           if (arg == NULL_TREE)
8928             {
8929               /* We don't know how many args we have yet, just use the
8930                  unconverted (and still packed) ones for now.  */
8931               new_inner_args = orig_inner_args;
8932               arg_idx = nargs;
8933               break;
8934             }
8935
8936           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
8937
8938           /* Store this argument.  */
8939           if (arg == error_mark_node)
8940             {
8941               lost++;
8942               /* We are done with all of the arguments.  */
8943               arg_idx = nargs;
8944               break;
8945             }
8946           else
8947             {
8948               pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
8949               arg_idx += pack_adjust;
8950               if (fixed_parameter_pack_p (TREE_VALUE (parm)))
8951                 {
8952                   ++fixed_packs;
8953                   fixed_pack_adjust += pack_adjust;
8954                 }
8955             }
8956
8957           continue;
8958         }
8959       else if (arg)
8960         {
8961           if (PACK_EXPANSION_P (arg))
8962             {
8963               /* "If every valid specialization of a variadic template
8964                  requires an empty template parameter pack, the template is
8965                  ill-formed, no diagnostic required."  So check that the
8966                  pattern works with this parameter.  */
8967               tree pattern = PACK_EXPANSION_PATTERN (arg);
8968               tree conv = convert_template_argument (TREE_VALUE (parm),
8969                                                      pattern, new_args,
8970                                                      complain, parm_idx,
8971                                                      in_decl);
8972               if (conv == error_mark_node)
8973                 {
8974                   if (complain & tf_error)
8975                     inform (input_location, "so any instantiation with a "
8976                             "non-empty parameter pack would be ill-formed");
8977                   ++lost;
8978                 }
8979               else if (TYPE_P (conv) && !TYPE_P (pattern))
8980                 /* Recover from missing typename.  */
8981                 TREE_VEC_ELT (inner_args, arg_idx)
8982                   = make_pack_expansion (conv, complain);
8983
8984               /* We don't know how many args we have yet, just
8985                  use the unconverted ones for now.  */
8986               new_inner_args = inner_args;
8987               arg_idx = nargs;
8988               break;
8989             }
8990         }
8991       else if (require_all_args)
8992         {
8993           /* There must be a default arg in this case.  */
8994           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
8995                                      complain, in_decl);
8996           /* The position of the first default template argument,
8997              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
8998              Record that.  */
8999           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
9000             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
9001                                                  arg_idx - pack_adjust);
9002         }
9003       else
9004         break;
9005
9006       if (arg == error_mark_node)
9007         {
9008           if (complain & tf_error)
9009             error ("template argument %d is invalid", arg_idx + 1);
9010         }
9011       else if (!arg)
9012         {
9013           /* This can occur if there was an error in the template
9014              parameter list itself (which we would already have
9015              reported) that we are trying to recover from, e.g., a class
9016              template with a parameter list such as
9017              template<typename..., typename> (cpp0x/variadic150.C).  */
9018           ++lost;
9019
9020           /* This can also happen with a fixed parameter pack (71834).  */
9021           if (arg_idx >= nargs)
9022             ++missing;
9023         }
9024       else
9025         arg = convert_template_argument (TREE_VALUE (parm),
9026                                          arg, new_args, complain,
9027                                          parm_idx, in_decl);
9028
9029       if (arg == error_mark_node)
9030         lost++;
9031
9032       TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
9033     }
9034
9035   if (missing || arg_idx < nargs - variadic_args_p)
9036     {
9037       /* If we had fixed parameter packs, we didn't know how many arguments we
9038          actually needed earlier; now we do.  */
9039       nparms += fixed_pack_adjust;
9040       variadic_p -= fixed_packs;
9041       goto bad_nargs;
9042     }
9043
9044   if (arg_idx < nargs)
9045     {
9046       /* We had some pack expansion arguments that will only work if the packs
9047          are empty, but wait until instantiation time to complain.
9048          See variadic-ttp3.C.  */
9049
9050       /* Except that we can't provide empty packs to alias templates or
9051          concepts when there are no corresponding parameters. Basically,
9052          we can get here with this:
9053
9054              template<typename T> concept C = true;
9055
9056              template<typename... Args>
9057                requires C<Args...>
9058              void f();
9059
9060          When parsing C<Args...>, we try to form a concept check of
9061          C<?, Args...>. Without the extra check for substituting an empty
9062          pack past the last parameter, we can accept the check as valid.
9063
9064          FIXME: This may be valid for alias templates (but I doubt it).
9065
9066          FIXME: The error could be better also.   */
9067       if (in_decl && concept_definition_p (in_decl))
9068         {
9069           if (complain & tf_error)
9070             error_at (location_of (TREE_VEC_ELT (args, arg_idx)),
9071                       "too many arguments");
9072           return error_mark_node;
9073         }
9074
9075       int len = nparms + (nargs - arg_idx);
9076       tree args = make_tree_vec (len);
9077       int i = 0;
9078       for (; i < nparms; ++i)
9079         TREE_VEC_ELT (args, i) = TREE_VEC_ELT (new_inner_args, i);
9080       for (; i < len; ++i, ++arg_idx)
9081         TREE_VEC_ELT (args, i) = TREE_VEC_ELT (inner_args,
9082                                                arg_idx - pack_adjust);
9083       new_inner_args = args;
9084     }
9085
9086   if (lost)
9087     {
9088       gcc_assert (!(complain & tf_error) || seen_error ());
9089       return error_mark_node;
9090     }
9091
9092   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
9093     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
9094                                          TREE_VEC_LENGTH (new_inner_args));
9095
9096   return new_inner_args;
9097 }
9098
9099 /* Convert all template arguments to their appropriate types, and
9100    return a vector containing the innermost resulting template
9101    arguments.  If any error occurs, return error_mark_node. Error and
9102    warning messages are not issued.
9103
9104    Note that no function argument deduction is performed, and default
9105    arguments are used to fill in unspecified arguments. */
9106 tree
9107 coerce_template_parms (tree parms, tree args, tree in_decl)
9108 {
9109   return coerce_template_parms (parms, args, in_decl, tf_none, true, true);
9110 }
9111
9112 /* Convert all template arguments to their appropriate type, and
9113    instantiate default arguments as needed. This returns a vector
9114    containing the innermost resulting template arguments, or
9115    error_mark_node if unsuccessful.  */
9116 tree
9117 coerce_template_parms (tree parms, tree args, tree in_decl,
9118                        tsubst_flags_t complain)
9119 {
9120   return coerce_template_parms (parms, args, in_decl, complain, true, true);
9121 }
9122
9123 /* Like coerce_template_parms.  If PARMS represents all template
9124    parameters levels, this function returns a vector of vectors
9125    representing all the resulting argument levels.  Note that in this
9126    case, only the innermost arguments are coerced because the
9127    outermost ones are supposed to have been coerced already.
9128
9129    Otherwise, if PARMS represents only (the innermost) vector of
9130    parameters, this function returns a vector containing just the
9131    innermost resulting arguments.  */
9132
9133 static tree
9134 coerce_innermost_template_parms (tree parms,
9135                                   tree args,
9136                                   tree in_decl,
9137                                   tsubst_flags_t complain,
9138                                   bool require_all_args,
9139                                   bool use_default_args)
9140 {
9141   int parms_depth = TMPL_PARMS_DEPTH (parms);
9142   int args_depth = TMPL_ARGS_DEPTH (args);
9143   tree coerced_args;
9144
9145   if (parms_depth > 1)
9146     {
9147       coerced_args = make_tree_vec (parms_depth);
9148       tree level;
9149       int cur_depth;
9150
9151       for (level = parms, cur_depth = parms_depth;
9152            parms_depth > 0 && level != NULL_TREE;
9153            level = TREE_CHAIN (level), --cur_depth)
9154         {
9155           tree l;
9156           if (cur_depth == args_depth)
9157             l = coerce_template_parms (TREE_VALUE (level),
9158                                        args, in_decl, complain,
9159                                        require_all_args,
9160                                        use_default_args);
9161           else
9162             l = TMPL_ARGS_LEVEL (args, cur_depth);
9163
9164           if (l == error_mark_node)
9165             return error_mark_node;
9166
9167           SET_TMPL_ARGS_LEVEL (coerced_args, cur_depth, l);
9168         }
9169     }
9170   else
9171     coerced_args = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parms),
9172                                           args, in_decl, complain,
9173                                           require_all_args,
9174                                           use_default_args);
9175   return coerced_args;
9176 }
9177
9178 /* Returns true if T is a wrapper to make a C++20 template parameter
9179    object const.  */
9180
9181 static bool
9182 class_nttp_const_wrapper_p (tree t)
9183 {
9184   if (cxx_dialect < cxx20)
9185     return false;
9186   return (TREE_CODE (t) == VIEW_CONVERT_EXPR
9187           && CP_TYPE_CONST_P (TREE_TYPE (t))
9188           && TREE_CODE (TREE_OPERAND (t, 0)) == TEMPLATE_PARM_INDEX);
9189 }
9190
9191 /* Returns 1 if template args OT and NT are equivalent.  */
9192
9193 int
9194 template_args_equal (tree ot, tree nt, bool partial_order /* = false */)
9195 {
9196   if (nt == ot)
9197     return 1;
9198   if (nt == NULL_TREE || ot == NULL_TREE)
9199     return false;
9200   if (nt == any_targ_node || ot == any_targ_node)
9201     return true;
9202
9203   if (class_nttp_const_wrapper_p (nt))
9204     nt = TREE_OPERAND (nt, 0);
9205   if (class_nttp_const_wrapper_p (ot))
9206     ot = TREE_OPERAND (ot, 0);
9207
9208   /* DR 1558: Don't treat an alias template specialization with dependent
9209      arguments as equivalent to its underlying type when used as a template
9210      argument; we need them to be distinct so that we substitute into the
9211      specialization arguments at instantiation time.  And aliases can't be
9212      equivalent without being ==, so we don't need to look any deeper.
9213
9214      During partial ordering, however, we need to treat them normally so we can
9215      order uses of the same alias with different cv-qualification (79960).  */
9216   auto cso = make_temp_override (comparing_dependent_aliases);
9217   if (!partial_order)
9218     ++comparing_dependent_aliases;
9219
9220   if (TREE_CODE (nt) == TREE_VEC || TREE_CODE (ot) == TREE_VEC)
9221     /* For member templates */
9222     return TREE_CODE (ot) == TREE_CODE (nt) && comp_template_args (ot, nt);
9223   else if (PACK_EXPANSION_P (ot) || PACK_EXPANSION_P (nt))
9224     return (PACK_EXPANSION_P (ot) && PACK_EXPANSION_P (nt)
9225             && template_args_equal (PACK_EXPANSION_PATTERN (ot),
9226                                     PACK_EXPANSION_PATTERN (nt))
9227             && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
9228                                     PACK_EXPANSION_EXTRA_ARGS (nt)));
9229   else if (ARGUMENT_PACK_P (ot) || ARGUMENT_PACK_P (nt))
9230     return cp_tree_equal (ot, nt);
9231   else if (TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
9232     gcc_unreachable ();
9233   else if (TYPE_P (nt) || TYPE_P (ot))
9234     {
9235       if (!(TYPE_P (nt) && TYPE_P (ot)))
9236         return false;
9237       return same_type_p (ot, nt);
9238     }
9239   else
9240     {
9241       /* Try to treat a template non-type argument that has been converted
9242          to the parameter type as equivalent to one that hasn't yet.  */
9243       for (enum tree_code code1 = TREE_CODE (ot);
9244            CONVERT_EXPR_CODE_P (code1)
9245              || code1 == NON_LVALUE_EXPR;
9246            code1 = TREE_CODE (ot))
9247         ot = TREE_OPERAND (ot, 0);
9248
9249       for (enum tree_code code2 = TREE_CODE (nt);
9250            CONVERT_EXPR_CODE_P (code2)
9251              || code2 == NON_LVALUE_EXPR;
9252            code2 = TREE_CODE (nt))
9253         nt = TREE_OPERAND (nt, 0);
9254
9255       return cp_tree_equal (ot, nt);
9256     }
9257 }
9258
9259 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
9260    template arguments.  Returns 0 otherwise, and updates OLDARG_PTR and
9261    NEWARG_PTR with the offending arguments if they are non-NULL.  */
9262
9263 int
9264 comp_template_args (tree oldargs, tree newargs,
9265                     tree *oldarg_ptr, tree *newarg_ptr,
9266                     bool partial_order)
9267 {
9268   int i;
9269
9270   if (oldargs == newargs)
9271     return 1;
9272
9273   if (!oldargs || !newargs)
9274     return 0;
9275
9276   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
9277     return 0;
9278
9279   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
9280     {
9281       tree nt = TREE_VEC_ELT (newargs, i);
9282       tree ot = TREE_VEC_ELT (oldargs, i);
9283
9284       if (! template_args_equal (ot, nt, partial_order))
9285         {
9286           if (oldarg_ptr != NULL)
9287             *oldarg_ptr = ot;
9288           if (newarg_ptr != NULL)
9289             *newarg_ptr = nt;
9290           return 0;
9291         }
9292     }
9293   return 1;
9294 }
9295
9296 inline bool
9297 comp_template_args_porder (tree oargs, tree nargs)
9298 {
9299   return comp_template_args (oargs, nargs, NULL, NULL, true);
9300 }
9301
9302 /* Implement a freelist interface for objects of type T.
9303
9304    Head is a separate object, rather than a regular member, so that we
9305    can define it as a GTY deletable pointer, which is highly
9306    desirable.  A data member could be declared that way, but then the
9307    containing object would implicitly get GTY((user)), which would
9308    prevent us from instantiating freelists as global objects.
9309    Although this way we can create freelist global objects, they're
9310    such thin wrappers that instantiating temporaries at every use
9311    loses nothing and saves permanent storage for the freelist object.
9312
9313    Member functions next, anew, poison and reinit have default
9314    implementations that work for most of the types we're interested
9315    in, but if they don't work for some type, they should be explicitly
9316    specialized.  See the comments before them for requirements, and
9317    the example specializations for the tree_list_freelist.  */
9318 template <typename T>
9319 class freelist
9320 {
9321   /* Return the next object in a chain.  We could just do type
9322      punning, but if we access the object with its underlying type, we
9323      avoid strict-aliasing trouble.  This needs only work between
9324      poison and reinit.  */
9325   static T *&next (T *obj) { return obj->next; }
9326
9327   /* Return a newly allocated, uninitialized or minimally-initialized
9328      object of type T.  Any initialization performed by anew should
9329      either remain across the life of the object and the execution of
9330      poison, or be redone by reinit.  */
9331   static T *anew () { return ggc_alloc<T> (); }
9332
9333   /* Optionally scribble all over the bits holding the object, so that
9334      they become (mostly?) uninitialized memory.  This is called while
9335      preparing to make the object part of the free list.  */
9336   static void poison (T *obj) {
9337     T *p ATTRIBUTE_UNUSED = obj;
9338     T **q ATTRIBUTE_UNUSED = &next (obj);
9339
9340 #ifdef ENABLE_GC_CHECKING
9341     /* Poison the data, to indicate the data is garbage.  */
9342     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, sizeof (*p)));
9343     memset (p, 0xa5, sizeof (*p));
9344 #endif
9345     /* Let valgrind know the object is free.  */
9346     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, sizeof (*p)));
9347
9348     /* Let valgrind know the next portion of the object is available,
9349        but uninitialized.  */
9350     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9351   }
9352
9353   /* Bring an object that underwent at least one lifecycle after anew
9354      and before the most recent free and poison, back to a usable
9355      state, reinitializing whatever is needed for it to be
9356      functionally equivalent to an object just allocated and returned
9357      by anew.  This may poison or clear the next field, used by
9358      freelist housekeeping after poison was called.  */
9359   static void reinit (T *obj) {
9360     T **q ATTRIBUTE_UNUSED = &next (obj);
9361
9362 #ifdef ENABLE_GC_CHECKING
9363     memset (q, 0xa5, sizeof (*q));
9364 #endif
9365     /* Let valgrind know the entire object is available, but
9366        uninitialized.  */
9367     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (*obj)));
9368   }
9369
9370   /* Reference a GTY-deletable pointer that points to the first object
9371      in the free list proper.  */
9372   T *&head;
9373 public:
9374   /* Construct a freelist object chaining objects off of HEAD.  */
9375   freelist (T *&head) : head(head) {}
9376
9377   /* Add OBJ to the free object list.  The former head becomes OBJ's
9378      successor.  */
9379   void free (T *obj)
9380   {
9381     poison (obj);
9382     next (obj) = head;
9383     head = obj;
9384   }
9385
9386   /* Take an object from the free list, if one is available, or
9387      allocate a new one.  Objects taken from the free list should be
9388      regarded as filled with garbage, except for bits that are
9389      configured to be preserved across free and alloc.  */
9390   T *alloc ()
9391   {
9392     if (head)
9393       {
9394         T *obj = head;
9395         head = next (head);
9396         reinit (obj);
9397         return obj;
9398       }
9399     else
9400       return anew ();
9401   }
9402 };
9403
9404 /* Explicitly specialize the interfaces for freelist<tree_node>: we
9405    want to allocate a TREE_LIST using the usual interface, and ensure
9406    TREE_CHAIN remains functional.  Alas, we have to duplicate a bit of
9407    build_tree_list logic in reinit, so this could go out of sync.  */
9408 template <>
9409 inline tree &
9410 freelist<tree_node>::next (tree obj)
9411 {
9412   return TREE_CHAIN (obj);
9413 }
9414 template <>
9415 inline tree
9416 freelist<tree_node>::anew ()
9417 {
9418   return build_tree_list (NULL, NULL);
9419 }
9420 template <>
9421 inline void
9422 freelist<tree_node>::poison (tree obj ATTRIBUTE_UNUSED)
9423 {
9424   int size ATTRIBUTE_UNUSED = sizeof (tree_list);
9425   tree p ATTRIBUTE_UNUSED = obj;
9426   tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9427   tree *q ATTRIBUTE_UNUSED = &next (obj);
9428
9429 #ifdef ENABLE_GC_CHECKING
9430   gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9431
9432   /* Poison the data, to indicate the data is garbage.  */
9433   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, size));
9434   memset (p, 0xa5, size);
9435 #endif
9436   /* Let valgrind know the object is free.  */
9437   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, size));
9438   /* But we still want to use the TREE_CODE and TREE_CHAIN parts.  */
9439   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9440   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9441
9442 #ifdef ENABLE_GC_CHECKING
9443   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (b, sizeof (*b)));
9444   /* Keep TREE_CHAIN functional.  */
9445   TREE_SET_CODE (obj, TREE_LIST);
9446 #else
9447   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9448 #endif
9449 }
9450 template <>
9451 inline void
9452 freelist<tree_node>::reinit (tree obj ATTRIBUTE_UNUSED)
9453 {
9454   tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9455
9456 #ifdef ENABLE_GC_CHECKING
9457   gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9458   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9459   memset (obj, 0, sizeof (tree_list));
9460 #endif
9461
9462   /* Let valgrind know the entire object is available, but
9463      uninitialized.  */
9464   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9465
9466 #ifdef ENABLE_GC_CHECKING
9467   TREE_SET_CODE (obj, TREE_LIST);
9468 #else
9469   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9470 #endif
9471 }
9472
9473 /* Point to the first object in the TREE_LIST freelist.  */
9474 static GTY((deletable)) tree tree_list_freelist_head;
9475 /* Return the/an actual TREE_LIST freelist.  */
9476 static inline freelist<tree_node>
9477 tree_list_freelist ()
9478 {
9479   return tree_list_freelist_head;
9480 }
9481
9482 /* Point to the first object in the tinst_level freelist.  */
9483 static GTY((deletable)) tinst_level *tinst_level_freelist_head;
9484 /* Return the/an actual tinst_level freelist.  */
9485 static inline freelist<tinst_level>
9486 tinst_level_freelist ()
9487 {
9488   return tinst_level_freelist_head;
9489 }
9490
9491 /* Point to the first object in the pending_template freelist.  */
9492 static GTY((deletable)) pending_template *pending_template_freelist_head;
9493 /* Return the/an actual pending_template freelist.  */
9494 static inline freelist<pending_template>
9495 pending_template_freelist ()
9496 {
9497   return pending_template_freelist_head;
9498 }
9499
9500 /* Build the TREE_LIST object out of a split list, store it
9501    permanently, and return it.  */
9502 tree
9503 tinst_level::to_list ()
9504 {
9505   gcc_assert (split_list_p ());
9506   tree ret = tree_list_freelist ().alloc ();
9507   TREE_PURPOSE (ret) = tldcl;
9508   TREE_VALUE (ret) = targs;
9509   tldcl = ret;
9510   targs = NULL;
9511   gcc_assert (tree_list_p ());
9512   return ret;
9513 }
9514
9515 const unsigned short tinst_level::refcount_infinity;
9516
9517 /* Increment OBJ's refcount unless it is already infinite.  */
9518 static tinst_level *
9519 inc_refcount_use (tinst_level *obj)
9520 {
9521   if (obj && obj->refcount != tinst_level::refcount_infinity)
9522     ++obj->refcount;
9523   return obj;
9524 }
9525
9526 /* Release storage for OBJ and node, if it's a TREE_LIST.  */
9527 void
9528 tinst_level::free (tinst_level *obj)
9529 {
9530   if (obj->tree_list_p ())
9531     tree_list_freelist ().free (obj->get_node ());
9532   tinst_level_freelist ().free (obj);
9533 }
9534
9535 /* Decrement OBJ's refcount if not infinite.  If it reaches zero, release
9536    OBJ's DECL and OBJ, and start over with the tinst_level object that
9537    used to be referenced by OBJ's NEXT.  */
9538 static void
9539 dec_refcount_use (tinst_level *obj)
9540 {
9541   while (obj
9542          && obj->refcount != tinst_level::refcount_infinity
9543          && !--obj->refcount)
9544     {
9545       tinst_level *next = obj->next;
9546       tinst_level::free (obj);
9547       obj = next;
9548     }
9549 }
9550
9551 /* Modify PTR so that it points to OBJ, adjusting the refcounts of OBJ
9552    and of the former PTR.  Omitting the second argument is equivalent
9553    to passing (T*)NULL; this is allowed because passing the
9554    zero-valued integral constant NULL confuses type deduction and/or
9555    overload resolution.  */
9556 template <typename T>
9557 static void
9558 set_refcount_ptr (T *& ptr, T *obj = NULL)
9559 {
9560   T *save = ptr;
9561   ptr = inc_refcount_use (obj);
9562   dec_refcount_use (save);
9563 }
9564
9565 static void
9566 add_pending_template (tree d)
9567 {
9568   tree ti = (TYPE_P (d)
9569              ? CLASSTYPE_TEMPLATE_INFO (d)
9570              : DECL_TEMPLATE_INFO (d));
9571   struct pending_template *pt;
9572   int level;
9573
9574   if (TI_PENDING_TEMPLATE_FLAG (ti))
9575     return;
9576
9577   /* We are called both from instantiate_decl, where we've already had a
9578      tinst_level pushed, and instantiate_template, where we haven't.
9579      Compensate.  */
9580   gcc_assert (TREE_CODE (d) != TREE_LIST);
9581   level = !current_tinst_level
9582     || current_tinst_level->maybe_get_node () != d;
9583
9584   if (level)
9585     push_tinst_level (d);
9586
9587   pt = pending_template_freelist ().alloc ();
9588   pt->next = NULL;
9589   pt->tinst = NULL;
9590   set_refcount_ptr (pt->tinst, current_tinst_level);
9591   if (last_pending_template)
9592     last_pending_template->next = pt;
9593   else
9594     pending_templates = pt;
9595
9596   last_pending_template = pt;
9597
9598   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
9599
9600   if (level)
9601     pop_tinst_level ();
9602 }
9603
9604
9605 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
9606    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
9607    documentation for TEMPLATE_ID_EXPR.  */
9608
9609 tree
9610 lookup_template_function (tree fns, tree arglist)
9611 {
9612   if (fns == error_mark_node || arglist == error_mark_node)
9613     return error_mark_node;
9614
9615   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
9616
9617   if (!is_overloaded_fn (fns) && !identifier_p (fns))
9618     {
9619       error ("%q#D is not a function template", fns);
9620       return error_mark_node;
9621     }
9622
9623   if (BASELINK_P (fns))
9624     {
9625       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
9626                                          unknown_type_node,
9627                                          BASELINK_FUNCTIONS (fns),
9628                                          arglist);
9629       return fns;
9630     }
9631
9632   return build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, arglist);
9633 }
9634
9635 /* Within the scope of a template class S<T>, the name S gets bound
9636    (in build_self_reference) to a TYPE_DECL for the class, not a
9637    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
9638    or one of its enclosing classes, and that type is a template,
9639    return the associated TEMPLATE_DECL.  Otherwise, the original
9640    DECL is returned.
9641
9642    Also handle the case when DECL is a TREE_LIST of ambiguous
9643    injected-class-names from different bases.  */
9644
9645 tree
9646 maybe_get_template_decl_from_type_decl (tree decl)
9647 {
9648   if (decl == NULL_TREE)
9649     return decl;
9650
9651   /* DR 176: A lookup that finds an injected-class-name (10.2
9652      [class.member.lookup]) can result in an ambiguity in certain cases
9653      (for example, if it is found in more than one base class). If all of
9654      the injected-class-names that are found refer to specializations of
9655      the same class template, and if the name is followed by a
9656      template-argument-list, the reference refers to the class template
9657      itself and not a specialization thereof, and is not ambiguous.  */
9658   if (TREE_CODE (decl) == TREE_LIST)
9659     {
9660       tree t, tmpl = NULL_TREE;
9661       for (t = decl; t; t = TREE_CHAIN (t))
9662         {
9663           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
9664           if (!tmpl)
9665             tmpl = elt;
9666           else if (tmpl != elt)
9667             break;
9668         }
9669       if (tmpl && t == NULL_TREE)
9670         return tmpl;
9671       else
9672         return decl;
9673     }
9674
9675   return (decl != NULL_TREE
9676           && DECL_SELF_REFERENCE_P (decl)
9677           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
9678     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
9679 }
9680
9681 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
9682    parameters, find the desired type.
9683
9684    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
9685
9686    IN_DECL, if non-NULL, is the template declaration we are trying to
9687    instantiate.
9688
9689    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
9690    the class we are looking up.
9691
9692    Issue error and warning messages under control of COMPLAIN.
9693
9694    If the template class is really a local class in a template
9695    function, then the FUNCTION_CONTEXT is the function in which it is
9696    being instantiated.
9697
9698    ??? Note that this function is currently called *twice* for each
9699    template-id: the first time from the parser, while creating the
9700    incomplete type (finish_template_type), and the second type during the
9701    real instantiation (instantiate_template_class). This is surely something
9702    that we want to avoid. It also causes some problems with argument
9703    coercion (see convert_nontype_argument for more information on this).  */
9704
9705 static tree
9706 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
9707                          int entering_scope, tsubst_flags_t complain)
9708 {
9709   tree templ = NULL_TREE, parmlist;
9710   tree t;
9711   spec_entry **slot;
9712   spec_entry *entry;
9713   spec_entry elt;
9714   hashval_t hash;
9715
9716   if (identifier_p (d1))
9717     {
9718       tree value = innermost_non_namespace_value (d1);
9719       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
9720         templ = value;
9721       else
9722         {
9723           if (context)
9724             push_decl_namespace (context);
9725           templ = lookup_name (d1);
9726           templ = maybe_get_template_decl_from_type_decl (templ);
9727           if (context)
9728             pop_decl_namespace ();
9729         }
9730       if (templ)
9731         context = DECL_CONTEXT (templ);
9732     }
9733   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
9734     {
9735       tree type = TREE_TYPE (d1);
9736
9737       /* If we are declaring a constructor, say A<T>::A<T>, we will get
9738          an implicit typename for the second A.  Deal with it.  */
9739       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
9740         type = TREE_TYPE (type);
9741
9742       if (CLASSTYPE_TEMPLATE_INFO (type))
9743         {
9744           templ = CLASSTYPE_TI_TEMPLATE (type);
9745           d1 = DECL_NAME (templ);
9746         }
9747     }
9748   else if (TREE_CODE (d1) == ENUMERAL_TYPE
9749            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
9750     {
9751       templ = TYPE_TI_TEMPLATE (d1);
9752       d1 = DECL_NAME (templ);
9753     }
9754   else if (DECL_TYPE_TEMPLATE_P (d1))
9755     {
9756       templ = d1;
9757       d1 = DECL_NAME (templ);
9758       context = DECL_CONTEXT (templ);
9759     }
9760   else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
9761     {
9762       templ = d1;
9763       d1 = DECL_NAME (templ);
9764     }
9765
9766   /* Issue an error message if we didn't find a template.  */
9767   if (! templ)
9768     {
9769       if (complain & tf_error)
9770         error ("%qT is not a template", d1);
9771       return error_mark_node;
9772     }
9773
9774   if (TREE_CODE (templ) != TEMPLATE_DECL
9775          /* Make sure it's a user visible template, if it was named by
9776             the user.  */
9777       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
9778           && !PRIMARY_TEMPLATE_P (templ)))
9779     {
9780       if (complain & tf_error)
9781         {
9782           error ("non-template type %qT used as a template", d1);
9783           if (in_decl)
9784             error ("for template declaration %q+D", in_decl);
9785         }
9786       return error_mark_node;
9787     }
9788
9789   complain &= ~tf_user;
9790
9791   /* An alias that just changes the name of a template is equivalent to the
9792      other template, so if any of the arguments are pack expansions, strip
9793      the alias to avoid problems with a pack expansion passed to a non-pack
9794      alias template parameter (DR 1430).  */
9795   if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
9796     templ = get_underlying_template (templ);
9797
9798   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
9799     {
9800       tree parm;
9801       tree arglist2 = coerce_template_args_for_ttp (templ, arglist, complain);
9802       if (arglist2 == error_mark_node
9803           || (!uses_template_parms (arglist2)
9804               && check_instantiated_args (templ, arglist2, complain)))
9805         return error_mark_node;
9806
9807       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
9808       return parm;
9809     }
9810   else
9811     {
9812       tree template_type = TREE_TYPE (templ);
9813       tree gen_tmpl;
9814       tree type_decl;
9815       tree found = NULL_TREE;
9816       int arg_depth;
9817       int parm_depth;
9818       int is_dependent_type;
9819       int use_partial_inst_tmpl = false;
9820
9821       if (template_type == error_mark_node)
9822         /* An error occurred while building the template TEMPL, and a
9823            diagnostic has most certainly been emitted for that
9824            already.  Let's propagate that error.  */
9825         return error_mark_node;
9826
9827       gen_tmpl = most_general_template (templ);
9828       if (modules_p ())
9829         lazy_load_pendings (gen_tmpl);
9830
9831       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
9832       parm_depth = TMPL_PARMS_DEPTH (parmlist);
9833       arg_depth = TMPL_ARGS_DEPTH (arglist);
9834
9835       if (arg_depth == 1 && parm_depth > 1)
9836         {
9837           /* We've been given an incomplete set of template arguments.
9838              For example, given:
9839
9840                template <class T> struct S1 {
9841                  template <class U> struct S2 {};
9842                  template <class U> struct S2<U*> {};
9843                 };
9844
9845              we will be called with an ARGLIST of `U*', but the
9846              TEMPLATE will be `template <class T> template
9847              <class U> struct S1<T>::S2'.  We must fill in the missing
9848              arguments.  */
9849           tree ti = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (templ));
9850           arglist = add_outermost_template_args (TI_ARGS (ti), arglist);
9851           arg_depth = TMPL_ARGS_DEPTH (arglist);
9852         }
9853
9854       /* Now we should have enough arguments.  */
9855       gcc_assert (parm_depth == arg_depth);
9856
9857       /* From here on, we're only interested in the most general
9858          template.  */
9859
9860       /* Calculate the BOUND_ARGS.  These will be the args that are
9861          actually tsubst'd into the definition to create the
9862          instantiation.  */
9863       arglist = coerce_innermost_template_parms (parmlist, arglist, gen_tmpl,
9864                                                  complain,
9865                                                  /*require_all_args=*/true,
9866                                                  /*use_default_args=*/true);
9867
9868       if (arglist == error_mark_node)
9869         /* We were unable to bind the arguments.  */
9870         return error_mark_node;
9871
9872       /* In the scope of a template class, explicit references to the
9873          template class refer to the type of the template, not any
9874          instantiation of it.  For example, in:
9875
9876            template <class T> class C { void f(C<T>); }
9877
9878          the `C<T>' is just the same as `C'.  Outside of the
9879          class, however, such a reference is an instantiation.  */
9880       if (entering_scope
9881           || !PRIMARY_TEMPLATE_P (gen_tmpl)
9882           || currently_open_class (template_type))
9883         {
9884           tree tinfo = TYPE_TEMPLATE_INFO (template_type);
9885
9886           if (tinfo && comp_template_args (TI_ARGS (tinfo), arglist))
9887             return template_type;
9888         }
9889
9890       /* If we already have this specialization, return it.  */
9891       elt.tmpl = gen_tmpl;
9892       elt.args = arglist;
9893       elt.spec = NULL_TREE;
9894       hash = spec_hasher::hash (&elt);
9895       entry = type_specializations->find_with_hash (&elt, hash);
9896
9897       if (entry)
9898         return entry->spec;
9899
9900       /* If the template's constraints are not satisfied,
9901          then we cannot form a valid type.
9902
9903          Note that the check is deferred until after the hash
9904          lookup. This prevents redundant checks on previously
9905          instantiated specializations. */
9906       if (flag_concepts
9907           && !DECL_ALIAS_TEMPLATE_P (gen_tmpl)
9908           && !constraints_satisfied_p (gen_tmpl, arglist))
9909         {
9910           if (complain & tf_error)
9911             {
9912               auto_diagnostic_group d;
9913               error ("template constraint failure for %qD", gen_tmpl);
9914               diagnose_constraints (input_location, gen_tmpl, arglist);
9915             }
9916           return error_mark_node;
9917         }
9918
9919       is_dependent_type = uses_template_parms (arglist);
9920
9921       /* If the deduced arguments are invalid, then the binding
9922          failed.  */
9923       if (!is_dependent_type
9924           && check_instantiated_args (gen_tmpl,
9925                                       INNERMOST_TEMPLATE_ARGS (arglist),
9926                                       complain))
9927         return error_mark_node;
9928
9929       if (!is_dependent_type
9930           && !PRIMARY_TEMPLATE_P (gen_tmpl)
9931           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
9932           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
9933         /* This occurs when the user has tried to define a tagged type
9934            in a scope that forbids it.  We emitted an error during the
9935            parse.  We didn't complete the bail out then, so here we
9936            are.  */
9937         return error_mark_node;
9938
9939       context = DECL_CONTEXT (gen_tmpl);
9940       if (context && TYPE_P (context))
9941         {
9942           context = tsubst_aggr_type (context, arglist, complain, in_decl, true);
9943           context = complete_type (context);
9944         }
9945       else
9946         context = tsubst (context, arglist, complain, in_decl);
9947
9948       if (context == error_mark_node)
9949         return error_mark_node;
9950
9951       if (!context)
9952         context = global_namespace;
9953
9954       /* Create the type.  */
9955       if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9956         {
9957           /* The user referred to a specialization of an alias
9958             template represented by GEN_TMPL.
9959
9960             [temp.alias]/2 says:
9961
9962                 When a template-id refers to the specialization of an
9963                 alias template, it is equivalent to the associated
9964                 type obtained by substitution of its
9965                 template-arguments for the template-parameters in the
9966                 type-id of the alias template.  */
9967
9968           t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
9969           /* Note that the call above (by indirectly calling
9970              register_specialization in tsubst_decl) registers the
9971              TYPE_DECL representing the specialization of the alias
9972              template.  So next time someone substitutes ARGLIST for
9973              the template parms into the alias template (GEN_TMPL),
9974              she'll get that TYPE_DECL back.  */
9975
9976           if (t == error_mark_node)
9977             return t;
9978         }
9979       else if (TREE_CODE (template_type) == ENUMERAL_TYPE)
9980         {
9981           if (!is_dependent_type)
9982             {
9983               set_current_access_from_decl (TYPE_NAME (template_type));
9984               t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
9985                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
9986                                       arglist, complain, in_decl),
9987                               tsubst_attributes (TYPE_ATTRIBUTES (template_type),
9988                                                  arglist, complain, in_decl),
9989                               SCOPED_ENUM_P (template_type), NULL);
9990
9991               if (t == error_mark_node)
9992                 return t;
9993             }
9994           else
9995             {
9996               /* We don't want to call start_enum for this type, since
9997                  the values for the enumeration constants may involve
9998                  template parameters.  And, no one should be interested
9999                  in the enumeration constants for such a type.  */
10000               t = cxx_make_type (ENUMERAL_TYPE);
10001               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
10002             }
10003           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
10004           ENUM_FIXED_UNDERLYING_TYPE_P (t)
10005             = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
10006         }
10007       else if (CLASS_TYPE_P (template_type))
10008         {
10009           /* Lambda closures are regenerated in tsubst_lambda_expr, not
10010              instantiated here.  */
10011           gcc_assert (!LAMBDA_TYPE_P (template_type));
10012
10013           t = make_class_type (TREE_CODE (template_type));
10014           CLASSTYPE_DECLARED_CLASS (t)
10015             = CLASSTYPE_DECLARED_CLASS (template_type);
10016           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
10017
10018           /* A local class.  Make sure the decl gets registered properly.  */
10019           if (context == current_function_decl)
10020             if (pushtag (DECL_NAME (gen_tmpl), t)
10021                 == error_mark_node)
10022               return error_mark_node;
10023
10024           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
10025             /* This instantiation is another name for the primary
10026                template type. Set the TYPE_CANONICAL field
10027                appropriately. */
10028             TYPE_CANONICAL (t) = template_type;
10029           else if (any_template_arguments_need_structural_equality_p (arglist))
10030             /* Some of the template arguments require structural
10031                equality testing, so this template class requires
10032                structural equality testing. */
10033             SET_TYPE_STRUCTURAL_EQUALITY (t);
10034         }
10035       else
10036         gcc_unreachable ();
10037
10038       /* If we called start_enum or pushtag above, this information
10039          will already be set up.  */
10040       type_decl = TYPE_NAME (t);
10041       if (!type_decl)
10042         {
10043           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
10044
10045           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
10046           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
10047           DECL_SOURCE_LOCATION (type_decl)
10048             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
10049         }
10050
10051       set_instantiating_module (type_decl);
10052       /* Although GEN_TMPL is the TEMPLATE_DECL, it has the same value
10053          of export flag.  We want to propagate this because it might
10054          be a friend declaration that pushes a new hidden binding.  */
10055       DECL_MODULE_EXPORT_P (type_decl) = DECL_MODULE_EXPORT_P (gen_tmpl);
10056
10057       if (CLASS_TYPE_P (template_type))
10058         {
10059           TREE_PRIVATE (type_decl)
10060             = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
10061           TREE_PROTECTED (type_decl)
10062             = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
10063           if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
10064             {
10065               DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
10066               DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
10067             }
10068         }
10069
10070       if (OVERLOAD_TYPE_P (t)
10071           && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10072         {
10073           static const char *tags[] = {"abi_tag", "may_alias"};
10074
10075           for (unsigned ix = 0; ix != 2; ix++)
10076             {
10077               tree attributes
10078                 = lookup_attribute (tags[ix], TYPE_ATTRIBUTES (template_type));
10079
10080               if (attributes)
10081                 TYPE_ATTRIBUTES (t)
10082                   = tree_cons (TREE_PURPOSE (attributes),
10083                                TREE_VALUE (attributes),
10084                                TYPE_ATTRIBUTES (t));
10085             }
10086         }
10087
10088       /* Let's consider the explicit specialization of a member
10089          of a class template specialization that is implicitly instantiated,
10090          e.g.:
10091              template<class T>
10092              struct S
10093              {
10094                template<class U> struct M {}; //#0
10095              };
10096
10097              template<>
10098              template<>
10099              struct S<int>::M<char> //#1
10100              {
10101                int i;
10102              };
10103         [temp.expl.spec]/4 says this is valid.
10104
10105         In this case, when we write:
10106         S<int>::M<char> m;
10107
10108         M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
10109         the one of #0.
10110
10111         When we encounter #1, we want to store the partial instantiation
10112         of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
10113
10114         For all cases other than this "explicit specialization of member of a
10115         class template", we just want to store the most general template into
10116         the CLASSTYPE_TI_TEMPLATE of M.
10117
10118         This case of "explicit specialization of member of a class template"
10119         only happens when:
10120         1/ the enclosing class is an instantiation of, and therefore not
10121         the same as, the context of the most general template, and
10122         2/ we aren't looking at the partial instantiation itself, i.e.
10123         the innermost arguments are not the same as the innermost parms of
10124         the most general template.
10125
10126         So it's only when 1/ and 2/ happens that we want to use the partial
10127         instantiation of the member template in lieu of its most general
10128         template.  */
10129
10130       if (PRIMARY_TEMPLATE_P (gen_tmpl)
10131           && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
10132           /* the enclosing class must be an instantiation...  */
10133           && CLASS_TYPE_P (context)
10134           && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
10135         {
10136           TREE_VEC_LENGTH (arglist)--;
10137           ++processing_template_decl;
10138           tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (gen_tmpl));
10139           tree partial_inst_args =
10140             tsubst (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)),
10141                     arglist, complain, NULL_TREE);
10142           --processing_template_decl;
10143           TREE_VEC_LENGTH (arglist)++;
10144           if (partial_inst_args == error_mark_node)
10145             return error_mark_node;
10146           use_partial_inst_tmpl =
10147             /*...and we must not be looking at the partial instantiation
10148              itself. */
10149             !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
10150                                  partial_inst_args);
10151         }
10152
10153       if (!use_partial_inst_tmpl)
10154         /* This case is easy; there are no member templates involved.  */
10155         found = gen_tmpl;
10156       else
10157         {
10158           /* This is a full instantiation of a member template.  Find
10159              the partial instantiation of which this is an instance.  */
10160
10161           /* Temporarily reduce by one the number of levels in the ARGLIST
10162              so as to avoid comparing the last set of arguments.  */
10163           TREE_VEC_LENGTH (arglist)--;
10164           /* We don't use COMPLAIN in the following call because this isn't
10165              the immediate context of deduction.  For instance, tf_partial
10166              could be set here as we might be at the beginning of template
10167              argument deduction when any explicitly specified template
10168              arguments are substituted into the function type.  tf_partial
10169              could lead into trouble because we wouldn't find the partial
10170              instantiation that might have been created outside tf_partial
10171              context, because the levels of template parameters wouldn't
10172              match, because in a tf_partial context, tsubst doesn't reduce
10173              TEMPLATE_PARM_LEVEL.  */
10174           found = tsubst (gen_tmpl, arglist, tf_none, NULL_TREE);
10175           TREE_VEC_LENGTH (arglist)++;
10176           /* FOUND is either a proper class type, or an alias
10177              template specialization.  In the later case, it's a
10178              TYPE_DECL, resulting from the substituting of arguments
10179              for parameters in the TYPE_DECL of the alias template
10180              done earlier.  So be careful while getting the template
10181              of FOUND.  */
10182           found = (TREE_CODE (found) == TEMPLATE_DECL
10183                    ? found
10184                    : (TREE_CODE (found) == TYPE_DECL
10185                       ? DECL_TI_TEMPLATE (found)
10186                       : CLASSTYPE_TI_TEMPLATE (found)));
10187
10188           if (DECL_CLASS_TEMPLATE_P (found)
10189               && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (found)))
10190             {
10191               /* If this partial instantiation is specialized, we want to
10192                  use it for hash table lookup.  */
10193               elt.tmpl = found;
10194               elt.args = arglist = INNERMOST_TEMPLATE_ARGS (arglist);
10195               hash = spec_hasher::hash (&elt);
10196             }
10197         }
10198
10199       /* Build template info for the new specialization.  */
10200       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
10201
10202       elt.spec = t;
10203       slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
10204       gcc_checking_assert (*slot == NULL);
10205       entry = ggc_alloc<spec_entry> ();
10206       *entry = elt;
10207       *slot = entry;
10208
10209       /* Note this use of the partial instantiation so we can check it
10210          later in maybe_process_partial_specialization.  */
10211       DECL_TEMPLATE_INSTANTIATIONS (found)
10212         = tree_cons (arglist, t,
10213                      DECL_TEMPLATE_INSTANTIATIONS (found));
10214
10215       if (TREE_CODE (template_type) == ENUMERAL_TYPE
10216           && !uses_template_parms (current_nonlambda_scope ())
10217           && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10218         /* Now that the type has been registered on the instantiations
10219            list, we set up the enumerators.  Because the enumeration
10220            constants may involve the enumeration type itself, we make
10221            sure to register the type first, and then create the
10222            constants.  That way, doing tsubst_expr for the enumeration
10223            constants won't result in recursive calls here; we'll find
10224            the instantiation and exit above.  */
10225         tsubst_enum (template_type, t, arglist);
10226
10227       if (CLASS_TYPE_P (template_type) && is_dependent_type)
10228         /* If the type makes use of template parameters, the
10229            code that generates debugging information will crash.  */
10230         DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
10231
10232       /* Possibly limit visibility based on template args.  */
10233       TREE_PUBLIC (type_decl) = 1;
10234       determine_visibility (type_decl);
10235
10236       inherit_targ_abi_tags (t);
10237
10238       return t;
10239     }
10240 }
10241
10242 /* Wrapper for lookup_template_class_1.  */
10243
10244 tree
10245 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
10246                        int entering_scope, tsubst_flags_t complain)
10247 {
10248   tree ret;
10249   timevar_push (TV_TEMPLATE_INST);
10250   ret = lookup_template_class_1 (d1, arglist, in_decl, context,
10251                                  entering_scope, complain);
10252   timevar_pop (TV_TEMPLATE_INST);
10253   return ret;
10254 }
10255
10256 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST.  */
10257
10258 tree
10259 lookup_template_variable (tree templ, tree arglist)
10260 {
10261   if (flag_concepts && variable_concept_p (templ))
10262     return build_concept_check (templ, arglist, tf_none);
10263
10264   /* The type of the expression is NULL_TREE since the template-id could refer
10265      to an explicit or partial specialization. */
10266   return build2 (TEMPLATE_ID_EXPR, NULL_TREE, templ, arglist);
10267 }
10268
10269 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR for use. */
10270
10271 tree
10272 finish_template_variable (tree var, tsubst_flags_t complain)
10273 {
10274   tree templ = TREE_OPERAND (var, 0);
10275   tree arglist = TREE_OPERAND (var, 1);
10276
10277   tree tmpl_args = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (templ));
10278   arglist = add_outermost_template_args (tmpl_args, arglist);
10279
10280   templ = most_general_template (templ);
10281   tree parms = DECL_TEMPLATE_PARMS (templ);
10282   arglist = coerce_innermost_template_parms (parms, arglist, templ, complain,
10283                                              /*req_all*/true,
10284                                              /*use_default*/true);
10285   if (arglist == error_mark_node)
10286     return error_mark_node;
10287
10288   if (flag_concepts && !constraints_satisfied_p (templ, arglist))
10289     {
10290       if (complain & tf_error)
10291         {
10292           auto_diagnostic_group d;
10293           error ("use of invalid variable template %qE", var);
10294           diagnose_constraints (location_of (var), templ, arglist);
10295         }
10296       return error_mark_node;
10297     }
10298
10299   return instantiate_template (templ, arglist, complain);
10300 }
10301
10302 /* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
10303    TARGS template args, and instantiate it if it's not dependent.  */
10304
10305 tree
10306 lookup_and_finish_template_variable (tree templ, tree targs,
10307                                      tsubst_flags_t complain)
10308 {
10309   templ = lookup_template_variable (templ, targs);
10310   if (!any_dependent_template_arguments_p (targs))
10311     {
10312       templ = finish_template_variable (templ, complain);
10313       mark_used (templ);
10314     }
10315
10316   return convert_from_reference (templ);
10317 }
10318
10319 /* If the set of template parameters PARMS contains a template parameter
10320    at the given LEVEL and INDEX, then return this parameter.  Otherwise
10321    return NULL_TREE.  */
10322
10323 static tree
10324 corresponding_template_parameter (tree parms, int level, int index)
10325 {
10326   while (TMPL_PARMS_DEPTH (parms) > level)
10327     parms = TREE_CHAIN (parms);
10328
10329   if (TMPL_PARMS_DEPTH (parms) != level
10330       || TREE_VEC_LENGTH (TREE_VALUE (parms)) <= index)
10331     return NULL_TREE;
10332
10333   tree t = TREE_VALUE (TREE_VEC_ELT (TREE_VALUE (parms), index));
10334   /* As in template_parm_to_arg.  */
10335   if (TREE_CODE (t) == TYPE_DECL || TREE_CODE (t) == TEMPLATE_DECL)
10336     t = TREE_TYPE (t);
10337   else
10338     t = DECL_INITIAL (t);
10339
10340   gcc_assert (TEMPLATE_PARM_P (t));
10341   return t;
10342 }
10343
10344 /* Return the template parameter from PARMS that positionally corresponds
10345    to the template parameter PARM, or else return NULL_TREE.  */
10346
10347 static tree
10348 corresponding_template_parameter (tree parms, tree parm)
10349 {
10350   int level, index;
10351   template_parm_level_and_index (parm, &level, &index);
10352   return corresponding_template_parameter (parms, level, index);
10353 }
10354
10355 \f
10356 struct pair_fn_data
10357 {
10358   tree_fn_t fn;
10359   tree_fn_t any_fn;
10360   void *data;
10361   /* True when we should also visit template parameters that occur in
10362      non-deduced contexts.  */
10363   bool include_nondeduced_p;
10364   hash_set<tree> *visited;
10365 };
10366
10367 /* Called from for_each_template_parm via walk_tree.  */
10368
10369 static tree
10370 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
10371 {
10372   tree t = *tp;
10373   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
10374   tree_fn_t fn = pfd->fn;
10375   void *data = pfd->data;
10376   tree result = NULL_TREE;
10377
10378 #define WALK_SUBTREE(NODE)                                              \
10379   do                                                                    \
10380     {                                                                   \
10381       result = for_each_template_parm (NODE, fn, data, pfd->visited,    \
10382                                        pfd->include_nondeduced_p,       \
10383                                        pfd->any_fn);                    \
10384       if (result) goto out;                                             \
10385     }                                                                   \
10386   while (0)
10387
10388   if (pfd->any_fn && (*pfd->any_fn)(t, data))
10389     return t;
10390
10391   if (TYPE_P (t)
10392       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
10393     WALK_SUBTREE (TYPE_CONTEXT (t));
10394
10395   switch (TREE_CODE (t))
10396     {
10397     case RECORD_TYPE:
10398       if (TYPE_PTRMEMFUNC_P (t))
10399         break;
10400       /* Fall through.  */
10401
10402     case UNION_TYPE:
10403     case ENUMERAL_TYPE:
10404       if (!TYPE_TEMPLATE_INFO (t))
10405         *walk_subtrees = 0;
10406       else
10407         WALK_SUBTREE (TYPE_TI_ARGS (t));
10408       break;
10409
10410     case INTEGER_TYPE:
10411       WALK_SUBTREE (TYPE_MIN_VALUE (t));
10412       WALK_SUBTREE (TYPE_MAX_VALUE (t));
10413       break;
10414
10415     case METHOD_TYPE:
10416       /* Since we're not going to walk subtrees, we have to do this
10417          explicitly here.  */
10418       WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
10419       /* Fall through.  */
10420
10421     case FUNCTION_TYPE:
10422       /* Check the return type.  */
10423       WALK_SUBTREE (TREE_TYPE (t));
10424
10425       /* Check the parameter types.  Since default arguments are not
10426          instantiated until they are needed, the TYPE_ARG_TYPES may
10427          contain expressions that involve template parameters.  But,
10428          no-one should be looking at them yet.  And, once they're
10429          instantiated, they don't contain template parameters, so
10430          there's no point in looking at them then, either.  */
10431       {
10432         tree parm;
10433
10434         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
10435           WALK_SUBTREE (TREE_VALUE (parm));
10436
10437         /* Since we've already handled the TYPE_ARG_TYPES, we don't
10438            want walk_tree walking into them itself.  */
10439         *walk_subtrees = 0;
10440       }
10441
10442       if (flag_noexcept_type)
10443         {
10444           tree spec = TYPE_RAISES_EXCEPTIONS (t);
10445           if (spec)
10446             WALK_SUBTREE (TREE_PURPOSE (spec));
10447         }
10448       break;
10449
10450     case TYPEOF_TYPE:
10451     case DECLTYPE_TYPE:
10452     case UNDERLYING_TYPE:
10453       if (pfd->include_nondeduced_p
10454           && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
10455                                      pfd->visited,
10456                                      pfd->include_nondeduced_p,
10457                                      pfd->any_fn))
10458         return error_mark_node;
10459       *walk_subtrees = false;
10460       break;
10461
10462     case FUNCTION_DECL:
10463     case VAR_DECL:
10464       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10465         WALK_SUBTREE (DECL_TI_ARGS (t));
10466       /* Fall through.  */
10467
10468     case PARM_DECL:
10469     case CONST_DECL:
10470       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t))
10471         WALK_SUBTREE (DECL_INITIAL (t));
10472       if (DECL_CONTEXT (t)
10473           && pfd->include_nondeduced_p)
10474         WALK_SUBTREE (DECL_CONTEXT (t));
10475       break;
10476
10477     case BOUND_TEMPLATE_TEMPLATE_PARM:
10478       /* Record template parameters such as `T' inside `TT<T>'.  */
10479       WALK_SUBTREE (TYPE_TI_ARGS (t));
10480       /* Fall through.  */
10481
10482     case TEMPLATE_TEMPLATE_PARM:
10483     case TEMPLATE_TYPE_PARM:
10484     case TEMPLATE_PARM_INDEX:
10485       if (fn && (*fn)(t, data))
10486         return t;
10487       else if (!fn)
10488         return t;
10489       break;
10490
10491     case TEMPLATE_DECL:
10492       /* A template template parameter is encountered.  */
10493       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10494         WALK_SUBTREE (TREE_TYPE (t));
10495
10496       /* Already substituted template template parameter */
10497       *walk_subtrees = 0;
10498       break;
10499
10500     case TYPENAME_TYPE:
10501       /* A template-id in a TYPENAME_TYPE might be a deduced context after
10502          partial instantiation.  */
10503       WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
10504       *walk_subtrees = 0;
10505       break;
10506
10507     case CONSTRUCTOR:
10508       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
10509           && pfd->include_nondeduced_p)
10510         WALK_SUBTREE (TYPE_PTRMEMFUNC_FN_TYPE (TREE_TYPE (t)));
10511       break;
10512
10513     case INDIRECT_REF:
10514     case COMPONENT_REF:
10515       /* If there's no type, then this thing must be some expression
10516          involving template parameters.  */
10517       if (!fn && !TREE_TYPE (t))
10518         return error_mark_node;
10519       break;
10520
10521     case MODOP_EXPR:
10522     case CAST_EXPR:
10523     case IMPLICIT_CONV_EXPR:
10524     case REINTERPRET_CAST_EXPR:
10525     case CONST_CAST_EXPR:
10526     case STATIC_CAST_EXPR:
10527     case DYNAMIC_CAST_EXPR:
10528     case ARROW_EXPR:
10529     case DOTSTAR_EXPR:
10530     case TYPEID_EXPR:
10531     case PSEUDO_DTOR_EXPR:
10532       if (!fn)
10533         return error_mark_node;
10534       break;
10535
10536     case SCOPE_REF:
10537       if (pfd->include_nondeduced_p)
10538         WALK_SUBTREE (TREE_OPERAND (t, 0));
10539       break;
10540
10541     case REQUIRES_EXPR:
10542       {
10543         if (!fn)
10544           return error_mark_node;
10545
10546         /* Recursively walk the type of each constraint variable.  */
10547         tree p = TREE_OPERAND (t, 0);
10548         while (p)
10549           {
10550             WALK_SUBTREE (TREE_TYPE (p));
10551             p = TREE_CHAIN (p);
10552           }
10553       }
10554       break;
10555
10556     default:
10557       break;
10558     }
10559
10560   #undef WALK_SUBTREE
10561
10562   /* We didn't find any template parameters we liked.  */
10563  out:
10564   return result;
10565 }
10566
10567 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
10568    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
10569    call FN with the parameter and the DATA.
10570    If FN returns nonzero, the iteration is terminated, and
10571    for_each_template_parm returns 1.  Otherwise, the iteration
10572    continues.  If FN never returns a nonzero value, the value
10573    returned by for_each_template_parm is 0.  If FN is NULL, it is
10574    considered to be the function which always returns 1.
10575
10576    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
10577    parameters that occur in non-deduced contexts.  When false, only
10578    visits those template parameters that can be deduced.  */
10579
10580 static tree
10581 for_each_template_parm (tree t, tree_fn_t fn, void* data,
10582                         hash_set<tree> *visited,
10583                         bool include_nondeduced_p,
10584                         tree_fn_t any_fn)
10585 {
10586   struct pair_fn_data pfd;
10587   tree result;
10588
10589   /* Set up.  */
10590   pfd.fn = fn;
10591   pfd.any_fn = any_fn;
10592   pfd.data = data;
10593   pfd.include_nondeduced_p = include_nondeduced_p;
10594
10595   /* Walk the tree.  (Conceptually, we would like to walk without
10596      duplicates, but for_each_template_parm_r recursively calls
10597      for_each_template_parm, so we would need to reorganize a fair
10598      bit to use walk_tree_without_duplicates, so we keep our own
10599      visited list.)  */
10600   if (visited)
10601     pfd.visited = visited;
10602   else
10603     pfd.visited = new hash_set<tree>;
10604   result = cp_walk_tree (&t,
10605                          for_each_template_parm_r,
10606                          &pfd,
10607                          pfd.visited);
10608
10609   /* Clean up.  */
10610   if (!visited)
10611     {
10612       delete pfd.visited;
10613       pfd.visited = 0;
10614     }
10615
10616   return result;
10617 }
10618
10619 struct find_template_parameter_info
10620 {
10621   explicit find_template_parameter_info (tree ctx_parms)
10622     : parm_list (NULL_TREE),
10623       ctx_parms (ctx_parms),
10624       max_depth (TMPL_PARMS_DEPTH (ctx_parms))
10625   {}
10626
10627   hash_set<tree> visited;
10628   hash_set<tree> parms;
10629   tree parm_list;
10630   tree ctx_parms;
10631   int max_depth;
10632 };
10633
10634 /* Appends the declaration of T to the list in DATA.  */
10635
10636 static int
10637 keep_template_parm (tree t, void* data)
10638 {
10639   find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10640
10641   /* Template parameters declared within the expression are not part of
10642      the parameter mapping. For example, in this concept:
10643
10644        template<typename T>
10645        concept C = requires { <expr> } -> same_as<int>;
10646
10647      the return specifier same_as<int> declares a new decltype parameter
10648      that must not be part of the parameter mapping. The same is true
10649      for generic lambda parameters, lambda template parameters, etc.  */
10650   int level;
10651   int index;
10652   template_parm_level_and_index (t, &level, &index);
10653   if (level > ftpi->max_depth)
10654     return 0;
10655
10656   if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10657     /* We want the underlying TEMPLATE_TEMPLATE_PARM, not the
10658        BOUND_TEMPLATE_TEMPLATE_PARM itself.  */
10659     t = TREE_TYPE (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (t));
10660
10661   /* This template parameter might be an argument to a cached dependent
10662      specalization that was formed earlier inside some other template, in
10663      which case the parameter is not among the ones that are in-scope.
10664      Look in CTX_PARMS to find the corresponding in-scope template
10665      parameter, and use it instead.  */
10666   if (tree in_scope = corresponding_template_parameter (ftpi->ctx_parms, t))
10667     t = in_scope;
10668
10669   /* Arguments like const T yield parameters like const T. This means that
10670      a template-id like X<T, const T> would yield two distinct parameters:
10671      T and const T. Adjust types to their unqualified versions.  */
10672   if (TYPE_P (t))
10673     t = TYPE_MAIN_VARIANT (t);
10674   if (!ftpi->parms.add (t))
10675     ftpi->parm_list = tree_cons (NULL_TREE, t, ftpi->parm_list);
10676
10677   /* Verify the parameter we found has a valid index.  */
10678   if (flag_checking)
10679     {
10680       tree parms = ftpi->ctx_parms;
10681       while (TMPL_PARMS_DEPTH (parms) > level)
10682         parms = TREE_CHAIN (parms);
10683       if (int len = TREE_VEC_LENGTH (TREE_VALUE (parms)))
10684         gcc_assert (index < len);
10685     }
10686
10687   return 0;
10688 }
10689
10690 /* Ensure that we recursively examine certain terms that are not normally
10691    visited in for_each_template_parm_r.  */
10692
10693 static int
10694 any_template_parm_r (tree t, void *data)
10695 {
10696   find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10697
10698 #define WALK_SUBTREE(NODE)                                              \
10699   do                                                                    \
10700     {                                                                   \
10701       for_each_template_parm (NODE, keep_template_parm, data,           \
10702                               &ftpi->visited, true,                     \
10703                               any_template_parm_r);                     \
10704     }                                                                   \
10705   while (0)
10706
10707   /* A mention of a member alias/typedef is a use of all of its template
10708      arguments, including those from the enclosing class, so we don't use
10709      alias_template_specialization_p here.  */
10710   if (TYPE_P (t) && typedef_variant_p (t))
10711     if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
10712       WALK_SUBTREE (TI_ARGS (tinfo));
10713
10714   switch (TREE_CODE (t))
10715     {
10716     case TEMPLATE_TYPE_PARM:
10717       /* Type constraints of a placeholder type may contain parameters.  */
10718       if (is_auto (t))
10719         if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
10720           WALK_SUBTREE (constr);
10721       break;
10722
10723     case TEMPLATE_ID_EXPR:
10724       /* Search through references to variable templates.  */
10725       WALK_SUBTREE (TREE_OPERAND (t, 0));
10726       WALK_SUBTREE (TREE_OPERAND (t, 1));
10727       break;
10728
10729     case TEMPLATE_PARM_INDEX:
10730     case PARM_DECL:
10731       /* A parameter or constraint variable may also depend on a template
10732          parameter without explicitly naming it.  */
10733       WALK_SUBTREE (TREE_TYPE (t));
10734       break;
10735
10736     case TEMPLATE_DECL:
10737       {
10738         /* If T is a member template that shares template parameters with
10739            ctx_parms, we need to mark all those parameters for mapping.  */
10740         tree dparms = DECL_TEMPLATE_PARMS (t);
10741         tree cparms = ftpi->ctx_parms;
10742         while (TMPL_PARMS_DEPTH (dparms) > ftpi->max_depth)
10743           dparms = TREE_CHAIN (dparms);
10744         while (TMPL_PARMS_DEPTH (cparms) > TMPL_PARMS_DEPTH (dparms))
10745           cparms = TREE_CHAIN (cparms);
10746         while (dparms
10747                && (TREE_TYPE (TREE_VALUE (dparms))
10748                    != TREE_TYPE (TREE_VALUE (cparms))))
10749           dparms = TREE_CHAIN (dparms),
10750             cparms = TREE_CHAIN (cparms);
10751         if (dparms)
10752           {
10753             int ddepth = TMPL_PARMS_DEPTH (dparms);
10754             tree dargs = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (t)));
10755             for (int i = 0; i < ddepth; ++i)
10756               WALK_SUBTREE (TMPL_ARGS_LEVEL (dargs, i+1));
10757           }
10758       }
10759       break;
10760
10761     case LAMBDA_EXPR:
10762       {
10763         /* Look in the parms and body.  */
10764         tree fn = lambda_function (t);
10765         WALK_SUBTREE (TREE_TYPE (fn));
10766         WALK_SUBTREE (DECL_SAVED_TREE (fn));
10767       }
10768       break;
10769
10770     case IDENTIFIER_NODE:
10771       if (IDENTIFIER_CONV_OP_P (t))
10772         /* The conversion-type-id of a conversion operator may be dependent.  */
10773         WALK_SUBTREE (TREE_TYPE (t));
10774       break;
10775
10776     default:
10777       break;
10778     }
10779
10780   /* Keep walking.  */
10781   return 0;
10782 }
10783
10784 /* Returns a list of unique template parameters found within T, where CTX_PARMS
10785    are the template parameters in scope.  */
10786
10787 tree
10788 find_template_parameters (tree t, tree ctx_parms)
10789 {
10790   if (!ctx_parms)
10791     return NULL_TREE;
10792
10793   find_template_parameter_info ftpi (ctx_parms);
10794   for_each_template_parm (t, keep_template_parm, &ftpi, &ftpi.visited,
10795                           /*include_nondeduced*/true, any_template_parm_r);
10796   return ftpi.parm_list;
10797 }
10798
10799 /* Returns true if T depends on any template parameter.  */
10800
10801 int
10802 uses_template_parms (tree t)
10803 {
10804   if (t == NULL_TREE)
10805     return false;
10806
10807   bool dependent_p;
10808   int saved_processing_template_decl;
10809
10810   saved_processing_template_decl = processing_template_decl;
10811   if (!saved_processing_template_decl)
10812     processing_template_decl = 1;
10813   if (TYPE_P (t))
10814     dependent_p = dependent_type_p (t);
10815   else if (TREE_CODE (t) == TREE_VEC)
10816     dependent_p = any_dependent_template_arguments_p (t);
10817   else if (TREE_CODE (t) == TREE_LIST)
10818     dependent_p = (uses_template_parms (TREE_VALUE (t))
10819                    || uses_template_parms (TREE_CHAIN (t)));
10820   else if (TREE_CODE (t) == TYPE_DECL)
10821     dependent_p = dependent_type_p (TREE_TYPE (t));
10822   else if (t == error_mark_node)
10823     dependent_p = false;
10824   else
10825     dependent_p = instantiation_dependent_expression_p (t);
10826
10827   processing_template_decl = saved_processing_template_decl;
10828
10829   return dependent_p;
10830 }
10831
10832 /* Returns true iff we're processing an incompletely instantiated function
10833    template.  Useful instead of processing_template_decl because the latter
10834    is set to 0 during instantiate_non_dependent_expr.  */
10835
10836 bool
10837 in_template_function (void)
10838 {
10839   /* Inspect the less volatile cfun->decl instead of current_function_decl;
10840      the latter might get set for e.g. access checking during satisfaction.  */
10841   tree fn = cfun ? cfun->decl : NULL_TREE;
10842   bool ret;
10843   ++processing_template_decl;
10844   ret = (fn && DECL_LANG_SPECIFIC (fn)
10845          && DECL_TEMPLATE_INFO (fn)
10846          && any_dependent_template_arguments_p (DECL_TI_ARGS (fn)));
10847   --processing_template_decl;
10848   return ret;
10849 }
10850
10851 /* Returns true if T depends on any template parameter with level LEVEL.  */
10852
10853 bool
10854 uses_template_parms_level (tree t, int level)
10855 {
10856   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
10857                                  /*include_nondeduced_p=*/true);
10858 }
10859
10860 /* Returns true if the signature of DECL depends on any template parameter from
10861    its enclosing class.  */
10862
10863 bool
10864 uses_outer_template_parms (tree decl)
10865 {
10866   int depth = template_class_depth (CP_DECL_CONTEXT (decl));
10867   if (depth == 0)
10868     return false;
10869   if (for_each_template_parm (TREE_TYPE (decl), template_parm_outer_level,
10870                               &depth, NULL, /*include_nondeduced_p=*/true))
10871     return true;
10872   if (PRIMARY_TEMPLATE_P (decl)
10873       || DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
10874     {
10875       tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (decl));
10876       for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
10877         {
10878           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
10879           tree defarg = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
10880           if (TREE_CODE (parm) == PARM_DECL
10881               && for_each_template_parm (TREE_TYPE (parm),
10882                                          template_parm_outer_level,
10883                                          &depth, NULL, /*nondeduced*/true))
10884             return true;
10885           if (TREE_CODE (parm) == TEMPLATE_DECL
10886               && uses_outer_template_parms (parm))
10887             return true;
10888           if (defarg
10889               && for_each_template_parm (defarg, template_parm_outer_level,
10890                                          &depth, NULL, /*nondeduced*/true))
10891             return true;
10892         }
10893     }
10894   tree ci = get_constraints (decl);
10895   if (ci)
10896     ci = CI_ASSOCIATED_CONSTRAINTS (ci);
10897   if (ci && for_each_template_parm (ci, template_parm_outer_level,
10898                                     &depth, NULL, /*nondeduced*/true))
10899     return true;
10900   return false;
10901 }
10902
10903 /* Returns TRUE iff INST is an instantiation we don't need to do in an
10904    ill-formed translation unit, i.e. a variable or function that isn't
10905    usable in a constant expression.  */
10906
10907 static inline bool
10908 neglectable_inst_p (tree d)
10909 {
10910   return (d && DECL_P (d)
10911           && !undeduced_auto_decl (d)
10912           && !(TREE_CODE (d) == FUNCTION_DECL ? DECL_DECLARED_CONSTEXPR_P (d)
10913                : decl_maybe_constant_var_p (d)));
10914 }
10915
10916 /* Returns TRUE iff we should refuse to instantiate DECL because it's
10917    neglectable and instantiated from within an erroneous instantiation.  */
10918
10919 static bool
10920 limit_bad_template_recursion (tree decl)
10921 {
10922   struct tinst_level *lev = current_tinst_level;
10923   int errs = errorcount + sorrycount;
10924   if (lev == NULL || errs == 0 || !neglectable_inst_p (decl))
10925     return false;
10926
10927   for (; lev; lev = lev->next)
10928     if (neglectable_inst_p (lev->maybe_get_node ()))
10929       break;
10930
10931   return (lev && errs > lev->errors);
10932 }
10933
10934 static int tinst_depth;
10935 extern int max_tinst_depth;
10936 int depth_reached;
10937
10938 static GTY(()) struct tinst_level *last_error_tinst_level;
10939
10940 /* We're starting to instantiate D; record the template instantiation context
10941    at LOC for diagnostics and to restore it later.  */
10942
10943 bool
10944 push_tinst_level_loc (tree tldcl, tree targs, location_t loc)
10945 {
10946   struct tinst_level *new_level;
10947
10948   if (tinst_depth >= max_tinst_depth)
10949     {
10950       /* Tell error.c not to try to instantiate any templates.  */
10951       at_eof = 2;
10952       fatal_error (input_location,
10953                    "template instantiation depth exceeds maximum of %d"
10954                    " (use %<-ftemplate-depth=%> to increase the maximum)",
10955                    max_tinst_depth);
10956       return false;
10957     }
10958
10959   /* If the current instantiation caused problems, don't let it instantiate
10960      anything else.  Do allow deduction substitution and decls usable in
10961      constant expressions.  */
10962   if (!targs && limit_bad_template_recursion (tldcl))
10963     {
10964       /* Avoid no_linkage_errors and unused function warnings for this
10965          decl.  */
10966       TREE_NO_WARNING (tldcl) = 1;
10967       return false;
10968     }
10969
10970   /* When not -quiet, dump template instantiations other than functions, since
10971      announce_function will take care of those.  */
10972   if (!quiet_flag && !targs
10973       && TREE_CODE (tldcl) != TREE_LIST
10974       && TREE_CODE (tldcl) != FUNCTION_DECL)
10975     fprintf (stderr, " %s", decl_as_string (tldcl, TFF_DECL_SPECIFIERS));
10976
10977   new_level = tinst_level_freelist ().alloc ();
10978   new_level->tldcl = tldcl;
10979   new_level->targs = targs;
10980   new_level->locus = loc;
10981   new_level->errors = errorcount + sorrycount;
10982   new_level->next = NULL;
10983   new_level->refcount = 0;
10984   new_level->path = new_level->visible = nullptr;
10985   set_refcount_ptr (new_level->next, current_tinst_level);
10986   set_refcount_ptr (current_tinst_level, new_level);
10987
10988   ++tinst_depth;
10989   if (GATHER_STATISTICS && (tinst_depth > depth_reached))
10990     depth_reached = tinst_depth;
10991
10992   return true;
10993 }
10994
10995 /* We're starting substitution of TMPL<ARGS>; record the template
10996    substitution context for diagnostics and to restore it later.  */
10997
10998 bool
10999 push_tinst_level (tree tmpl, tree args)
11000 {
11001   return push_tinst_level_loc (tmpl, args, input_location);
11002 }
11003
11004 /* We're starting to instantiate D; record INPUT_LOCATION and the
11005    template instantiation context for diagnostics and to restore it
11006    later.  */
11007
11008 bool
11009 push_tinst_level (tree d)
11010 {
11011   return push_tinst_level_loc (d, input_location);
11012 }
11013
11014 /* Likewise, but record LOC as the program location.  */
11015
11016 bool
11017 push_tinst_level_loc (tree d, location_t loc)
11018 {
11019   gcc_assert (TREE_CODE (d) != TREE_LIST);
11020   return push_tinst_level_loc (d, NULL, loc);
11021 }
11022
11023 /* We're done instantiating this template; return to the instantiation
11024    context.  */
11025
11026 void
11027 pop_tinst_level (void)
11028 {
11029   /* Restore the filename and line number stashed away when we started
11030      this instantiation.  */
11031   input_location = current_tinst_level->locus;
11032   set_refcount_ptr (current_tinst_level, current_tinst_level->next);
11033   --tinst_depth;
11034 }
11035
11036 /* We're instantiating a deferred template; restore the template
11037    instantiation context in which the instantiation was requested, which
11038    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
11039
11040 static tree
11041 reopen_tinst_level (struct tinst_level *level)
11042 {
11043   struct tinst_level *t;
11044
11045   tinst_depth = 0;
11046   for (t = level; t; t = t->next)
11047     ++tinst_depth;
11048
11049   set_refcount_ptr (current_tinst_level, level);
11050   pop_tinst_level ();
11051   if (current_tinst_level)
11052     current_tinst_level->errors = errorcount+sorrycount;
11053   return level->maybe_get_node ();
11054 }
11055
11056 /* Returns the TINST_LEVEL which gives the original instantiation
11057    context.  */
11058
11059 struct tinst_level *
11060 outermost_tinst_level (void)
11061 {
11062   struct tinst_level *level = current_tinst_level;
11063   if (level)
11064     while (level->next)
11065       level = level->next;
11066   return level;
11067 }
11068
11069 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
11070    vector of template arguments, as for tsubst.
11071
11072    Returns an appropriate tsubst'd friend declaration.  */
11073
11074 static tree
11075 tsubst_friend_function (tree decl, tree args)
11076 {
11077   tree new_friend;
11078
11079   if (TREE_CODE (decl) == FUNCTION_DECL
11080       && DECL_TEMPLATE_INSTANTIATION (decl)
11081       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
11082     /* This was a friend declared with an explicit template
11083        argument list, e.g.:
11084
11085        friend void f<>(T);
11086
11087        to indicate that f was a template instantiation, not a new
11088        function declaration.  Now, we have to figure out what
11089        instantiation of what template.  */
11090     {
11091       tree template_id, arglist, fns;
11092       tree new_args;
11093       tree tmpl;
11094       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
11095
11096       /* Friend functions are looked up in the containing namespace scope.
11097          We must enter that scope, to avoid finding member functions of the
11098          current class with same name.  */
11099       push_nested_namespace (ns);
11100       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
11101                          tf_warning_or_error, NULL_TREE,
11102                          /*integral_constant_expression_p=*/false);
11103       pop_nested_namespace (ns);
11104       arglist = tsubst (DECL_TI_ARGS (decl), args,
11105                         tf_warning_or_error, NULL_TREE);
11106       template_id = lookup_template_function (fns, arglist);
11107
11108       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11109       tmpl = determine_specialization (template_id, new_friend,
11110                                        &new_args,
11111                                        /*need_member_template=*/0,
11112                                        TREE_VEC_LENGTH (args),
11113                                        tsk_none);
11114       return instantiate_template (tmpl, new_args, tf_error);
11115     }
11116
11117   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11118   if (new_friend == error_mark_node)
11119     return error_mark_node;
11120
11121   /* The NEW_FRIEND will look like an instantiation, to the
11122      compiler, but is not an instantiation from the point of view of
11123      the language.  For example, we might have had:
11124
11125      template <class T> struct S {
11126        template <class U> friend void f(T, U);
11127      };
11128
11129      Then, in S<int>, template <class U> void f(int, U) is not an
11130      instantiation of anything.  */
11131
11132   DECL_USE_TEMPLATE (new_friend) = 0;
11133   if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11134     {
11135       DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (new_friend) = false;
11136       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
11137       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
11138         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
11139
11140       /* Substitute TEMPLATE_PARMS_CONSTRAINTS so that parameter levels will
11141          match in decls_match.  */
11142       tree parms = DECL_TEMPLATE_PARMS (new_friend);
11143       tree treqs = TEMPLATE_PARMS_CONSTRAINTS (parms);
11144       treqs = maybe_substitute_reqs_for (treqs, new_friend);
11145       TEMPLATE_PARMS_CONSTRAINTS (parms) = treqs;
11146     }
11147
11148   /* The mangled name for the NEW_FRIEND is incorrect.  The function
11149      is not a template instantiation and should not be mangled like
11150      one.  Therefore, we forget the mangling here; we'll recompute it
11151      later if we need it.  */
11152   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
11153     {
11154       SET_DECL_RTL (new_friend, NULL);
11155       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
11156     }
11157
11158   if (DECL_NAMESPACE_SCOPE_P (new_friend))
11159     {
11160       tree old_decl;
11161       tree ns;
11162
11163       /* We must save some information from NEW_FRIEND before calling
11164          duplicate decls since that function will free NEW_FRIEND if
11165          possible.  */
11166       tree new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
11167       tree new_friend_result_template_info = NULL_TREE;
11168       bool new_friend_is_defn =
11169         (DECL_INITIAL (DECL_TEMPLATE_RESULT
11170                        (template_for_substitution (new_friend)))
11171          != NULL_TREE);
11172       tree not_tmpl = new_friend;
11173
11174       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11175         {
11176           /* This declaration is a `primary' template.  */
11177           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
11178
11179           not_tmpl = DECL_TEMPLATE_RESULT (new_friend);
11180           new_friend_result_template_info = DECL_TEMPLATE_INFO (not_tmpl);
11181         }
11182
11183       /* Inside pushdecl_namespace_level, we will push into the
11184          current namespace. However, the friend function should go
11185          into the namespace of the template.  */
11186       ns = decl_namespace_context (new_friend);
11187       push_nested_namespace (ns);
11188       old_decl = pushdecl_namespace_level (new_friend, /*hiding=*/true);
11189       pop_nested_namespace (ns);
11190
11191       if (old_decl == error_mark_node)
11192         return error_mark_node;
11193
11194       if (old_decl != new_friend)
11195         {
11196           /* This new friend declaration matched an existing
11197              declaration.  For example, given:
11198
11199                template <class T> void f(T);
11200                template <class U> class C {
11201                  template <class T> friend void f(T) {}
11202                };
11203
11204              the friend declaration actually provides the definition
11205              of `f', once C has been instantiated for some type.  So,
11206              old_decl will be the out-of-class template declaration,
11207              while new_friend is the in-class definition.
11208
11209              But, if `f' was called before this point, the
11210              instantiation of `f' will have DECL_TI_ARGS corresponding
11211              to `T' but not to `U', references to which might appear
11212              in the definition of `f'.  Previously, the most general
11213              template for an instantiation of `f' was the out-of-class
11214              version; now it is the in-class version.  Therefore, we
11215              run through all specialization of `f', adding to their
11216              DECL_TI_ARGS appropriately.  In particular, they need a
11217              new set of outer arguments, corresponding to the
11218              arguments for this class instantiation.
11219
11220              The same situation can arise with something like this:
11221
11222                friend void f(int);
11223                template <class T> class C {
11224                  friend void f(T) {}
11225                };
11226
11227              when `C<int>' is instantiated.  Now, `f(int)' is defined
11228              in the class.  */
11229
11230           if (!new_friend_is_defn)
11231             /* On the other hand, if the in-class declaration does
11232                *not* provide a definition, then we don't want to alter
11233                existing definitions.  We can just leave everything
11234                alone.  */
11235             ;
11236           else
11237             {
11238               tree new_template = TI_TEMPLATE (new_friend_template_info);
11239               tree new_args = TI_ARGS (new_friend_template_info);
11240
11241               /* Overwrite whatever template info was there before, if
11242                  any, with the new template information pertaining to
11243                  the declaration.  */
11244               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
11245
11246               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
11247                 {
11248                   /* We should have called reregister_specialization in
11249                      duplicate_decls.  */
11250                   gcc_assert (retrieve_specialization (new_template,
11251                                                        new_args, 0)
11252                               == old_decl);
11253
11254                   /* Instantiate it if the global has already been used.  */
11255                   if (DECL_ODR_USED (old_decl))
11256                     instantiate_decl (old_decl, /*defer_ok=*/true,
11257                                       /*expl_inst_class_mem_p=*/false);
11258                 }
11259               else
11260                 {
11261                   tree t;
11262
11263                   /* Indicate that the old function template is a partial
11264                      instantiation.  */
11265                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
11266                     = new_friend_result_template_info;
11267
11268                   gcc_assert (new_template
11269                               == most_general_template (new_template));
11270                   gcc_assert (new_template != old_decl);
11271
11272                   /* Reassign any specializations already in the hash table
11273                      to the new more general template, and add the
11274                      additional template args.  */
11275                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
11276                        t != NULL_TREE;
11277                        t = TREE_CHAIN (t))
11278                     {
11279                       tree spec = TREE_VALUE (t);
11280                       spec_entry elt;
11281
11282                       elt.tmpl = old_decl;
11283                       elt.args = DECL_TI_ARGS (spec);
11284                       elt.spec = NULL_TREE;
11285
11286                       decl_specializations->remove_elt (&elt);
11287
11288                       DECL_TI_ARGS (spec)
11289                         = add_outermost_template_args (new_args,
11290                                                        DECL_TI_ARGS (spec));
11291
11292                       register_specialization
11293                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
11294
11295                     }
11296                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
11297                 }
11298             }
11299
11300           /* The information from NEW_FRIEND has been merged into OLD_DECL
11301              by duplicate_decls.  */
11302           new_friend = old_decl;
11303         }
11304     }
11305   else
11306     {
11307       tree context = DECL_CONTEXT (new_friend);
11308       bool dependent_p;
11309
11310       /* In the code
11311            template <class T> class C {
11312              template <class U> friend void C1<U>::f (); // case 1
11313              friend void C2<T>::f ();                    // case 2
11314            };
11315          we only need to make sure CONTEXT is a complete type for
11316          case 2.  To distinguish between the two cases, we note that
11317          CONTEXT of case 1 remains dependent type after tsubst while
11318          this isn't true for case 2.  */
11319       ++processing_template_decl;
11320       dependent_p = dependent_type_p (context);
11321       --processing_template_decl;
11322
11323       if (!dependent_p
11324           && !complete_type_or_else (context, NULL_TREE))
11325         return error_mark_node;
11326
11327       if (COMPLETE_TYPE_P (context))
11328         {
11329           tree fn = new_friend;
11330           /* do_friend adds the TEMPLATE_DECL for any member friend
11331              template even if it isn't a member template, i.e.
11332                template <class T> friend A<T>::f();
11333              Look through it in that case.  */
11334           if (TREE_CODE (fn) == TEMPLATE_DECL
11335               && !PRIMARY_TEMPLATE_P (fn))
11336             fn = DECL_TEMPLATE_RESULT (fn);
11337           /* Check to see that the declaration is really present, and,
11338              possibly obtain an improved declaration.  */
11339           fn = check_classfn (context, fn, NULL_TREE);
11340
11341           if (fn)
11342             new_friend = fn;
11343         }
11344     }
11345
11346   return new_friend;
11347 }
11348
11349 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
11350    template arguments, as for tsubst.
11351
11352    Returns an appropriate tsubst'd friend type or error_mark_node on
11353    failure.  */
11354
11355 static tree
11356 tsubst_friend_class (tree friend_tmpl, tree args)
11357 {
11358   tree tmpl;
11359
11360   if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
11361     {
11362       tmpl = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
11363       return TREE_TYPE (tmpl);
11364     }
11365
11366   tree context = CP_DECL_CONTEXT (friend_tmpl);
11367   if (TREE_CODE (context) == NAMESPACE_DECL)
11368     push_nested_namespace (context);
11369   else
11370     {
11371       context = tsubst (context, args, tf_error, NULL_TREE);
11372       push_nested_class (context);
11373     }
11374
11375   tmpl = lookup_name (DECL_NAME (friend_tmpl), LOOK_where::CLASS_NAMESPACE,
11376                       LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND);
11377
11378   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
11379     {
11380       /* The friend template has already been declared.  Just
11381          check to see that the declarations match, and install any new
11382          default parameters.  We must tsubst the default parameters,
11383          of course.  We only need the innermost template parameters
11384          because that is all that redeclare_class_template will look
11385          at.  */
11386       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
11387           > TMPL_ARGS_DEPTH (args))
11388         {
11389           tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
11390                                               args, tf_warning_or_error);
11391           location_t saved_input_location = input_location;
11392           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
11393           tree cons = get_constraints (tmpl);
11394           redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
11395           input_location = saved_input_location;
11396         }
11397     }
11398   else
11399     {
11400       /* The friend template has not already been declared.  In this
11401          case, the instantiation of the template class will cause the
11402          injection of this template into the namespace scope.  */
11403       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
11404
11405       if (tmpl != error_mark_node)
11406         {
11407           /* The new TMPL is not an instantiation of anything, so we
11408              forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE
11409              for the new type because that is supposed to be the
11410              corresponding template decl, i.e., TMPL.  */
11411           DECL_USE_TEMPLATE (tmpl) = 0;
11412           DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
11413           CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
11414           CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
11415             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
11416
11417           /* Substitute into and set the constraints on the new declaration.  */
11418           if (tree ci = get_constraints (friend_tmpl))
11419             {
11420               ++processing_template_decl;
11421               ci = tsubst_constraint_info (ci, args, tf_warning_or_error,
11422                                            DECL_FRIEND_CONTEXT (friend_tmpl));
11423               --processing_template_decl;
11424               set_constraints (tmpl, ci);
11425             }
11426
11427           /* Inject this template into the enclosing namspace scope.  */
11428           tmpl = pushdecl_namespace_level (tmpl, /*hiding=*/true);
11429         }
11430     }
11431
11432   if (TREE_CODE (context) == NAMESPACE_DECL)
11433     pop_nested_namespace (context);
11434   else
11435     pop_nested_class ();
11436
11437   return TREE_TYPE (tmpl);
11438 }
11439
11440 /* Returns zero if TYPE cannot be completed later due to circularity.
11441    Otherwise returns one.  */
11442
11443 static int
11444 can_complete_type_without_circularity (tree type)
11445 {
11446   if (type == NULL_TREE || type == error_mark_node)
11447     return 0;
11448   else if (COMPLETE_TYPE_P (type))
11449     return 1;
11450   else if (TREE_CODE (type) == ARRAY_TYPE)
11451     return can_complete_type_without_circularity (TREE_TYPE (type));
11452   else if (CLASS_TYPE_P (type)
11453            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
11454     return 0;
11455   else
11456     return 1;
11457 }
11458
11459 static tree tsubst_omp_clauses (tree, enum c_omp_region_type, tree,
11460                                 tsubst_flags_t, tree);
11461
11462 /* Instantiate a single dependent attribute T (a TREE_LIST), and return either
11463    T or a new TREE_LIST, possibly a chain in the case of a pack expansion.  */
11464
11465 static tree
11466 tsubst_attribute (tree t, tree *decl_p, tree args,
11467                   tsubst_flags_t complain, tree in_decl)
11468 {
11469   gcc_assert (ATTR_IS_DEPENDENT (t));
11470
11471   tree val = TREE_VALUE (t);
11472   if (val == NULL_TREE)
11473     /* Nothing to do.  */;
11474   else if ((flag_openmp || flag_openmp_simd)
11475            && is_attribute_p ("omp declare simd",
11476                               get_attribute_name (t)))
11477     {
11478       tree clauses = TREE_VALUE (val);
11479       clauses = tsubst_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD, args,
11480                                     complain, in_decl);
11481       c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11482       clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11483       tree parms = DECL_ARGUMENTS (*decl_p);
11484       clauses
11485         = c_omp_declare_simd_clauses_to_numbers (parms, clauses);
11486       if (clauses)
11487         val = build_tree_list (NULL_TREE, clauses);
11488       else
11489         val = NULL_TREE;
11490     }
11491   else if (flag_openmp
11492            && is_attribute_p ("omp declare variant base",
11493                               get_attribute_name (t)))
11494     {
11495       ++cp_unevaluated_operand;
11496       tree varid
11497         = tsubst_expr (TREE_PURPOSE (val), args, complain,
11498                        in_decl, /*integral_constant_expression_p=*/false);
11499       --cp_unevaluated_operand;
11500       tree chain = TREE_CHAIN (val);
11501       location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
11502       tree ctx = copy_list (TREE_VALUE (val));
11503       tree simd = get_identifier ("simd");
11504       tree score = get_identifier (" score");
11505       tree condition = get_identifier ("condition");
11506       for (tree t1 = ctx; t1; t1 = TREE_CHAIN (t1))
11507         {
11508           const char *set = IDENTIFIER_POINTER (TREE_PURPOSE (t1));
11509           TREE_VALUE (t1) = copy_list (TREE_VALUE (t1));
11510           for (tree t2 = TREE_VALUE (t1); t2; t2 = TREE_CHAIN (t2))
11511             {
11512               if (TREE_PURPOSE (t2) == simd && set[0] == 'c')
11513                 {
11514                   tree clauses = TREE_VALUE (t2);
11515                   clauses = tsubst_omp_clauses (clauses,
11516                                                 C_ORT_OMP_DECLARE_SIMD, args,
11517                                                 complain, in_decl);
11518                   c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11519                   clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11520                   TREE_VALUE (t2) = clauses;
11521                 }
11522               else
11523                 {
11524                   TREE_VALUE (t2) = copy_list (TREE_VALUE (t2));
11525                   for (tree t3 = TREE_VALUE (t2); t3; t3 = TREE_CHAIN (t3))
11526                     if (TREE_VALUE (t3))
11527                       {
11528                         bool allow_string
11529                           = ((TREE_PURPOSE (t2) != condition || set[0] != 'u')
11530                              && TREE_PURPOSE (t3) != score);
11531                         tree v = TREE_VALUE (t3);
11532                         if (TREE_CODE (v) == STRING_CST && allow_string)
11533                           continue;
11534                         v = tsubst_expr (v, args, complain, in_decl, true);
11535                         v = fold_non_dependent_expr (v);
11536                         if (!INTEGRAL_TYPE_P (TREE_TYPE (v))
11537                             || (TREE_PURPOSE (t3) == score
11538                                 ? TREE_CODE (v) != INTEGER_CST
11539                                 : !tree_fits_shwi_p (v)))
11540                           {
11541                             location_t loc
11542                               = cp_expr_loc_or_loc (TREE_VALUE (t3),
11543                                                     match_loc);
11544                             if (TREE_PURPOSE (t3) == score)
11545                               error_at (loc, "score argument must be "
11546                                              "constant integer expression");
11547                             else if (allow_string)
11548                               error_at (loc, "property must be constant "
11549                                              "integer expression or string "
11550                                              "literal");
11551                             else
11552                               error_at (loc, "property must be constant "
11553                                              "integer expression");
11554                             return NULL_TREE;
11555                           }
11556                         else if (TREE_PURPOSE (t3) == score
11557                                  && tree_int_cst_sgn (v) < 0)
11558                           {
11559                             location_t loc
11560                               = cp_expr_loc_or_loc (TREE_VALUE (t3),
11561                                                     match_loc);
11562                             error_at (loc, "score argument must be "
11563                                            "non-negative");
11564                             return NULL_TREE;
11565                           }
11566                         TREE_VALUE (t3) = v;
11567                       }
11568                 }
11569             }
11570         }
11571       val = tree_cons (varid, ctx, chain);
11572     }
11573   /* If the first attribute argument is an identifier, don't
11574      pass it through tsubst.  Attributes like mode, format,
11575      cleanup and several target specific attributes expect it
11576      unmodified.  */
11577   else if (attribute_takes_identifier_p (get_attribute_name (t)))
11578     {
11579       tree chain
11580         = tsubst_expr (TREE_CHAIN (val), args, complain, in_decl,
11581                        /*integral_constant_expression_p=*/false);
11582       if (chain != TREE_CHAIN (val))
11583         val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
11584     }
11585   else if (PACK_EXPANSION_P (val))
11586     {
11587       /* An attribute pack expansion.  */
11588       tree purp = TREE_PURPOSE (t);
11589       tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
11590       if (pack == error_mark_node)
11591         return error_mark_node;
11592       int len = TREE_VEC_LENGTH (pack);
11593       tree list = NULL_TREE;
11594       tree *q = &list;
11595       for (int i = 0; i < len; ++i)
11596         {
11597           tree elt = TREE_VEC_ELT (pack, i);
11598           *q = build_tree_list (purp, elt);
11599           q = &TREE_CHAIN (*q);
11600         }
11601       return list;
11602     }
11603   else
11604     val = tsubst_expr (val, args, complain, in_decl,
11605                        /*integral_constant_expression_p=*/false);
11606
11607   if (val == error_mark_node)
11608     return error_mark_node;
11609   if (val != TREE_VALUE (t))
11610     return build_tree_list (TREE_PURPOSE (t), val);
11611   return t;
11612 }
11613
11614 /* Instantiate any dependent attributes in ATTRIBUTES, returning either it
11615    unchanged or a new TREE_LIST chain.  */
11616
11617 static tree
11618 tsubst_attributes (tree attributes, tree args,
11619                    tsubst_flags_t complain, tree in_decl)
11620 {
11621   tree last_dep = NULL_TREE;
11622
11623   for (tree t = attributes; t; t = TREE_CHAIN (t))
11624     if (ATTR_IS_DEPENDENT (t))
11625       {
11626         last_dep = t;
11627         attributes = copy_list (attributes);
11628         break;
11629       }
11630
11631   if (last_dep)
11632     for (tree *p = &attributes; *p; )
11633       {
11634         tree t = *p;
11635         if (ATTR_IS_DEPENDENT (t))
11636           {
11637             tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
11638             if (subst != t)
11639               {
11640                 *p = subst;
11641                 while (*p)
11642                   p = &TREE_CHAIN (*p);
11643                 *p = TREE_CHAIN (t);
11644                 continue;
11645               }
11646           }
11647         p = &TREE_CHAIN (*p);
11648       }
11649
11650   return attributes;
11651 }
11652
11653 /* Apply any attributes which had to be deferred until instantiation
11654    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
11655    ARGS, COMPLAIN, IN_DECL are as tsubst.  Returns true normally,
11656    false on error.  */
11657
11658 static bool
11659 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
11660                                 tree args, tsubst_flags_t complain, tree in_decl)
11661 {
11662   tree last_dep = NULL_TREE;
11663   tree t;
11664   tree *p;
11665
11666   if (attributes == NULL_TREE)
11667     return true;
11668
11669   if (DECL_P (*decl_p))
11670     {
11671       if (TREE_TYPE (*decl_p) == error_mark_node)
11672         return false;
11673       p = &DECL_ATTRIBUTES (*decl_p);
11674       /* DECL_ATTRIBUTES comes from copy_node in tsubst_decl, and is identical
11675          to our attributes parameter.  */
11676       gcc_assert (*p == attributes);
11677     }
11678   else
11679     {
11680       p = &TYPE_ATTRIBUTES (*decl_p);
11681       /* TYPE_ATTRIBUTES was set up (with abi_tag and may_alias) in
11682          lookup_template_class_1, and should be preserved.  */
11683       gcc_assert (*p != attributes);
11684       while (*p)
11685         p = &TREE_CHAIN (*p);
11686     }
11687
11688   for (t = attributes; t; t = TREE_CHAIN (t))
11689     if (ATTR_IS_DEPENDENT (t))
11690       {
11691         last_dep = t;
11692         attributes = copy_list (attributes);
11693         break;
11694       }
11695
11696   *p = attributes;
11697   if (last_dep)
11698     {
11699       tree late_attrs = NULL_TREE;
11700       tree *q = &late_attrs;
11701
11702       for (; *p; )
11703         {
11704           t = *p;
11705           if (ATTR_IS_DEPENDENT (t))
11706             {
11707               *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
11708               if (*q == error_mark_node)
11709                 return false;
11710               *p = TREE_CHAIN (t);
11711               TREE_CHAIN (t) = NULL_TREE;
11712               while (*q)
11713                 q = &TREE_CHAIN (*q);
11714             }
11715           else
11716             p = &TREE_CHAIN (t);
11717         }
11718
11719       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
11720     }
11721   return true;
11722 }
11723
11724 /* The template TMPL is being instantiated with the template arguments TARGS.
11725    Perform the access checks that we deferred when parsing the template.  */
11726
11727 static void
11728 perform_instantiation_time_access_checks (tree tmpl, tree targs)
11729 {
11730   unsigned i;
11731   deferred_access_check *chk;
11732
11733   if (!CLASS_TYPE_P (tmpl) && TREE_CODE (tmpl) != FUNCTION_DECL)
11734     return;
11735
11736   if (vec<deferred_access_check, va_gc> *access_checks
11737       = TI_DEFERRED_ACCESS_CHECKS (get_template_info (tmpl)))
11738     FOR_EACH_VEC_ELT (*access_checks, i, chk)
11739       {
11740         tree decl = chk->decl;
11741         tree diag_decl = chk->diag_decl;
11742         tree type_scope = TREE_TYPE (chk->binfo);
11743
11744         if (uses_template_parms (type_scope))
11745           type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
11746
11747         /* Make access check error messages point to the location
11748            of the use of the typedef.  */
11749         iloc_sentinel ils (chk->loc);
11750         perform_or_defer_access_check (TYPE_BINFO (type_scope),
11751                                        decl, diag_decl, tf_warning_or_error);
11752       }
11753 }
11754
11755 static tree
11756 instantiate_class_template_1 (tree type)
11757 {
11758   tree templ, args, pattern, t, member;
11759   tree typedecl;
11760   tree pbinfo;
11761   tree base_list;
11762   unsigned int saved_maximum_field_alignment;
11763   tree fn_context;
11764
11765   if (type == error_mark_node)
11766     return error_mark_node;
11767
11768   if (COMPLETE_OR_OPEN_TYPE_P (type)
11769       || uses_template_parms (type))
11770     return type;
11771
11772   /* Figure out which template is being instantiated.  */
11773   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
11774   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
11775
11776   /* Mark the type as in the process of being defined.  */
11777   TYPE_BEING_DEFINED (type) = 1;
11778
11779   /* We may be in the middle of deferred access check.  Disable
11780      it now.  */
11781   deferring_access_check_sentinel acs (dk_no_deferred);
11782
11783   /* Determine what specialization of the original template to
11784      instantiate.  */
11785   t = most_specialized_partial_spec (type, tf_warning_or_error);
11786   if (t == error_mark_node)
11787     return error_mark_node;
11788   else if (t)
11789     {
11790       /* This TYPE is actually an instantiation of a partial
11791          specialization.  We replace the innermost set of ARGS with
11792          the arguments appropriate for substitution.  For example,
11793          given:
11794
11795            template <class T> struct S {};
11796            template <class T> struct S<T*> {};
11797
11798          and supposing that we are instantiating S<int*>, ARGS will
11799          presently be {int*} -- but we need {int}.  */
11800       pattern = TREE_TYPE (t);
11801       args = TREE_PURPOSE (t);
11802     }
11803   else
11804     {
11805       pattern = TREE_TYPE (templ);
11806       args = CLASSTYPE_TI_ARGS (type);
11807     }
11808
11809   /* If the template we're instantiating is incomplete, then clearly
11810      there's nothing we can do.  */
11811   if (!COMPLETE_TYPE_P (pattern))
11812     {
11813       /* We can try again later.  */
11814       TYPE_BEING_DEFINED (type) = 0;
11815       return type;
11816     }
11817
11818   /* If we've recursively instantiated too many templates, stop.  */
11819   if (! push_tinst_level (type))
11820     return type;
11821
11822   int saved_unevaluated_operand = cp_unevaluated_operand;
11823   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
11824
11825   fn_context = decl_function_context (TYPE_MAIN_DECL (type));
11826   /* Also avoid push_to_top_level for a lambda in an NSDMI.  */
11827   if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
11828     fn_context = error_mark_node;
11829   if (!fn_context)
11830     push_to_top_level ();
11831   else
11832     {
11833       cp_unevaluated_operand = 0;
11834       c_inhibit_evaluation_warnings = 0;
11835     }
11836   /* Use #pragma pack from the template context.  */
11837   saved_maximum_field_alignment = maximum_field_alignment;
11838   maximum_field_alignment = TYPE_PRECISION (pattern);
11839
11840   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
11841
11842   /* Set the input location to the most specialized template definition.
11843      This is needed if tsubsting causes an error.  */
11844   typedecl = TYPE_MAIN_DECL (pattern);
11845   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
11846     DECL_SOURCE_LOCATION (typedecl);
11847
11848   set_instantiating_module (TYPE_NAME (type));
11849
11850   TYPE_PACKED (type) = TYPE_PACKED (pattern);
11851   SET_TYPE_ALIGN (type, TYPE_ALIGN (pattern));
11852   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
11853   CLASSTYPE_NON_AGGREGATE (type) = CLASSTYPE_NON_AGGREGATE (pattern);
11854   if (ANON_AGGR_TYPE_P (pattern))
11855     SET_ANON_AGGR_TYPE_P (type);
11856   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
11857     {
11858       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
11859       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
11860       /* Adjust visibility for template arguments.  */
11861       determine_visibility (TYPE_MAIN_DECL (type));
11862     }
11863   if (CLASS_TYPE_P (type))
11864     CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
11865
11866   pbinfo = TYPE_BINFO (pattern);
11867
11868   /* We should never instantiate a nested class before its enclosing
11869      class; we need to look up the nested class by name before we can
11870      instantiate it, and that lookup should instantiate the enclosing
11871      class.  */
11872   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
11873               || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
11874
11875   base_list = NULL_TREE;
11876   /* Defer access checking while we substitute into the types named in
11877      the base-clause.  */
11878   push_deferring_access_checks (dk_deferred);
11879   if (BINFO_N_BASE_BINFOS (pbinfo))
11880     {
11881       tree pbase_binfo;
11882       int i;
11883
11884       /* Substitute into each of the bases to determine the actual
11885          basetypes.  */
11886       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
11887         {
11888           tree base;
11889           tree access = BINFO_BASE_ACCESS (pbinfo, i);
11890           tree expanded_bases = NULL_TREE;
11891           int idx, len = 1;
11892
11893           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
11894             {
11895               expanded_bases = 
11896                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
11897                                        args, tf_error, NULL_TREE);
11898               if (expanded_bases == error_mark_node)
11899                 continue;
11900
11901               len = TREE_VEC_LENGTH (expanded_bases);
11902             }
11903
11904           for (idx = 0; idx < len; idx++)
11905             {
11906               if (expanded_bases)
11907                 /* Extract the already-expanded base class.  */
11908                 base = TREE_VEC_ELT (expanded_bases, idx);
11909               else
11910                 /* Substitute to figure out the base class.  */
11911                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
11912                                NULL_TREE);
11913
11914               if (base == error_mark_node)
11915                 continue;
11916
11917               base_list = tree_cons (access, base, base_list);
11918               if (BINFO_VIRTUAL_P (pbase_binfo))
11919                 TREE_TYPE (base_list) = integer_type_node;
11920             }
11921         }
11922
11923       /* The list is now in reverse order; correct that.  */
11924       base_list = nreverse (base_list);
11925     }
11926   /* Now call xref_basetypes to set up all the base-class
11927      information.  */
11928   xref_basetypes (type, base_list);
11929
11930   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
11931                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
11932                                   args, tf_error, NULL_TREE);
11933   fixup_attribute_variants (type);
11934
11935   /* Now that our base classes are set up, enter the scope of the
11936      class, so that name lookups into base classes, etc. will work
11937      correctly.  This is precisely analogous to what we do in
11938      begin_class_definition when defining an ordinary non-template
11939      class, except we also need to push the enclosing classes.  */
11940   push_nested_class (type);
11941
11942   /* Now check accessibility of the types named in its base-clause,
11943      relative to the scope of the class.  */
11944   pop_to_parent_deferring_access_checks ();
11945
11946   /* A vector to hold members marked with attribute used. */
11947   auto_vec<tree> used;
11948
11949   /* Now members are processed in the order of declaration.  */
11950   for (member = CLASSTYPE_DECL_LIST (pattern);
11951        member; member = TREE_CHAIN (member))
11952     {
11953       tree t = TREE_VALUE (member);
11954
11955       if (TREE_PURPOSE (member))
11956         {
11957           if (TYPE_P (t))
11958             {
11959               if (LAMBDA_TYPE_P (t))
11960                 /* A closure type for a lambda in an NSDMI or default argument.
11961                    Ignore it; it will be regenerated when needed.  */
11962                 continue;
11963
11964               bool class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
11965                                        && TYPE_LANG_SPECIFIC (t)
11966                                        && CLASSTYPE_IS_TEMPLATE (t));
11967
11968               /* If the member is a class template, then -- even after
11969                  substitution -- there may be dependent types in the
11970                  template argument list for the class.  We increment
11971                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
11972                  that function will assume that no types are dependent
11973                  when outside of a template.  */
11974               if (class_template_p)
11975                 ++processing_template_decl;
11976               tree newtag = tsubst (t, args, tf_error, NULL_TREE);
11977               if (class_template_p)
11978                 --processing_template_decl;
11979               if (newtag == error_mark_node)
11980                 continue;
11981
11982               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
11983                 {
11984                   tree name = TYPE_IDENTIFIER (t);
11985
11986                   if (class_template_p)
11987                     /* Unfortunately, lookup_template_class sets
11988                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
11989                        instantiation (i.e., for the type of a member
11990                        template class nested within a template class.)
11991                        This behavior is required for
11992                        maybe_process_partial_specialization to work
11993                        correctly, but is not accurate in this case;
11994                        the TAG is not an instantiation of anything.
11995                        (The corresponding TEMPLATE_DECL is an
11996                        instantiation, but the TYPE is not.) */
11997                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
11998
11999                   /* Now, install the tag.  We don't use pushtag
12000                      because that does too much work -- creating an
12001                      implicit typedef, which we've already done.  */
12002                   set_identifier_type_value (name, TYPE_NAME (newtag));
12003                   maybe_add_class_template_decl_list (type, newtag, false);
12004                   TREE_PUBLIC (TYPE_NAME (newtag)) = true;
12005                   determine_visibility (TYPE_NAME (newtag));
12006                 }
12007             }
12008           else if (DECL_DECLARES_FUNCTION_P (t))
12009             {
12010               tree r;
12011
12012               if (TREE_CODE (t) == TEMPLATE_DECL)
12013                 ++processing_template_decl;
12014               r = tsubst (t, args, tf_error, NULL_TREE);
12015               if (TREE_CODE (t) == TEMPLATE_DECL)
12016                 --processing_template_decl;
12017               set_current_access_from_decl (r);
12018               finish_member_declaration (r);
12019               /* Instantiate members marked with attribute used.  */
12020               if (r != error_mark_node && DECL_PRESERVE_P (r))
12021                 used.safe_push (r);
12022               if (TREE_CODE (r) == FUNCTION_DECL
12023                   && DECL_OMP_DECLARE_REDUCTION_P (r))
12024                 cp_check_omp_declare_reduction (r);
12025             }
12026           else if ((DECL_CLASS_TEMPLATE_P (t) || DECL_IMPLICIT_TYPEDEF_P (t))
12027                    && LAMBDA_TYPE_P (TREE_TYPE (t)))
12028             /* A closure type for a lambda in an NSDMI or default argument.
12029                Ignore it; it will be regenerated when needed.  */;
12030           else
12031             {
12032               /* Build new TYPE_FIELDS.  */
12033               if (TREE_CODE (t) == STATIC_ASSERT)
12034                 tsubst_expr (t, args, tf_warning_or_error, NULL_TREE,
12035                              /*integral_constant_expression_p=*/true);
12036               else if (TREE_CODE (t) != CONST_DECL)
12037                 {
12038                   tree r;
12039                   tree vec = NULL_TREE;
12040                   int len = 1;
12041
12042                   gcc_checking_assert (TREE_CODE (t) != CONST_DECL);
12043                   /* The file and line for this declaration, to
12044                      assist in error message reporting.  Since we
12045                      called push_tinst_level above, we don't need to
12046                      restore these.  */
12047                   input_location = DECL_SOURCE_LOCATION (t);
12048
12049                   if (TREE_CODE (t) == TEMPLATE_DECL)
12050                     ++processing_template_decl;
12051                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
12052                   if (TREE_CODE (t) == TEMPLATE_DECL)
12053                     --processing_template_decl;
12054
12055                   if (TREE_CODE (r) == TREE_VEC)
12056                     {
12057                       /* A capture pack became multiple fields.  */
12058                       vec = r;
12059                       len = TREE_VEC_LENGTH (vec);
12060                     }
12061
12062                   for (int i = 0; i < len; ++i)
12063                     {
12064                       if (vec)
12065                         r = TREE_VEC_ELT (vec, i);
12066                       if (VAR_P (r))
12067                         {
12068                           /* In [temp.inst]:
12069
12070                              [t]he initialization (and any associated
12071                              side-effects) of a static data member does
12072                              not occur unless the static data member is
12073                              itself used in a way that requires the
12074                              definition of the static data member to
12075                              exist.
12076
12077                              Therefore, we do not substitute into the
12078                              initialized for the static data member here.  */
12079                           finish_static_data_member_decl
12080                             (r,
12081                              /*init=*/NULL_TREE,
12082                              /*init_const_expr_p=*/false,
12083                              /*asmspec_tree=*/NULL_TREE,
12084                              /*flags=*/0);
12085                           /* Instantiate members marked with attribute used. */
12086                           if (r != error_mark_node && DECL_PRESERVE_P (r))
12087                             used.safe_push (r);
12088                         }
12089                       else if (TREE_CODE (r) == FIELD_DECL)
12090                         {
12091                           /* Determine whether R has a valid type and can be
12092                              completed later.  If R is invalid, then its type
12093                              is replaced by error_mark_node.  */
12094                           tree rtype = TREE_TYPE (r);
12095                           if (can_complete_type_without_circularity (rtype))
12096                             complete_type (rtype);
12097
12098                           if (!complete_or_array_type_p (rtype))
12099                             {
12100                               /* If R's type couldn't be completed and
12101                                  it isn't a flexible array member (whose
12102                                  type is incomplete by definition) give
12103                                  an error.  */
12104                               cxx_incomplete_type_error (r, rtype);
12105                               TREE_TYPE (r) = error_mark_node;
12106                             }
12107                           else if (TREE_CODE (rtype) == ARRAY_TYPE
12108                                    && TYPE_DOMAIN (rtype) == NULL_TREE
12109                                    && (TREE_CODE (type) == UNION_TYPE
12110                                        || TREE_CODE (type) == QUAL_UNION_TYPE))
12111                             {
12112                               error ("flexible array member %qD in union", r);
12113                               TREE_TYPE (r) = error_mark_node;
12114                             }
12115                           else if (!verify_type_context (input_location,
12116                                                          TCTX_FIELD, rtype))
12117                             TREE_TYPE (r) = error_mark_node;
12118                         }
12119
12120                       /* If it is a TYPE_DECL for a class-scoped
12121                          ENUMERAL_TYPE, such a thing will already have
12122                          been added to the field list by tsubst_enum
12123                          in finish_member_declaration case above.  */
12124                       if (!(TREE_CODE (r) == TYPE_DECL
12125                             && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
12126                             && DECL_ARTIFICIAL (r)))
12127                         {
12128                           set_current_access_from_decl (r);
12129                           finish_member_declaration (r);
12130                         }
12131                     }
12132                 }
12133             }
12134         }
12135       else
12136         {
12137           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
12138               || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
12139             {
12140               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
12141
12142               tree friend_type = t;
12143               bool adjust_processing_template_decl = false;
12144
12145               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12146                 {
12147                   /* template <class T> friend class C;  */
12148                   friend_type = tsubst_friend_class (friend_type, args);
12149                   adjust_processing_template_decl = true;
12150                 }
12151               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
12152                 {
12153                   /* template <class T> friend class C::D;  */
12154                   friend_type = tsubst (friend_type, args,
12155                                         tf_warning_or_error, NULL_TREE);
12156                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12157                     friend_type = TREE_TYPE (friend_type);
12158                   adjust_processing_template_decl = true;
12159                 }
12160               else if (TREE_CODE (friend_type) == TYPENAME_TYPE
12161                        || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
12162                 {
12163                   /* This could be either
12164
12165                        friend class T::C;
12166
12167                      when dependent_type_p is false or
12168
12169                        template <class U> friend class T::C;
12170
12171                      otherwise.  */
12172                   /* Bump processing_template_decl in case this is something like
12173                      template <class T> friend struct A<T>::B.  */
12174                   ++processing_template_decl;
12175                   friend_type = tsubst (friend_type, args,
12176                                         tf_warning_or_error, NULL_TREE);
12177                   if (dependent_type_p (friend_type))
12178                     adjust_processing_template_decl = true;
12179                   --processing_template_decl;
12180                 }
12181               else if (uses_template_parms (friend_type))
12182                 /* friend class C<T>;  */
12183                 friend_type = tsubst (friend_type, args,
12184                                       tf_warning_or_error, NULL_TREE);
12185               
12186               /* Otherwise it's
12187
12188                    friend class C;
12189
12190                  where C is already declared or
12191
12192                    friend class C<int>;
12193
12194                  We don't have to do anything in these cases.  */
12195
12196               if (adjust_processing_template_decl)
12197                 /* Trick make_friend_class into realizing that the friend
12198                    we're adding is a template, not an ordinary class.  It's
12199                    important that we use make_friend_class since it will
12200                    perform some error-checking and output cross-reference
12201                    information.  */
12202                 ++processing_template_decl;
12203
12204               if (friend_type != error_mark_node)
12205                 make_friend_class (type, friend_type, /*complain=*/false);
12206
12207               if (adjust_processing_template_decl)
12208                 --processing_template_decl;
12209             }
12210           else
12211             {
12212               /* Build new DECL_FRIENDLIST.  */
12213               tree r;
12214
12215               /* The file and line for this declaration, to
12216                  assist in error message reporting.  Since we
12217                  called push_tinst_level above, we don't need to
12218                  restore these.  */
12219               input_location = DECL_SOURCE_LOCATION (t);
12220
12221               if (TREE_CODE (t) == TEMPLATE_DECL)
12222                 {
12223                   ++processing_template_decl;
12224                   push_deferring_access_checks (dk_no_check);
12225                 }
12226
12227               r = tsubst_friend_function (t, args);
12228               add_friend (type, r, /*complain=*/false);
12229               if (TREE_CODE (t) == TEMPLATE_DECL)
12230                 {
12231                   pop_deferring_access_checks ();
12232                   --processing_template_decl;
12233                 }
12234             }
12235         }
12236     }
12237
12238   if (fn_context)
12239     {
12240       /* Restore these before substituting into the lambda capture
12241          initializers.  */
12242       cp_unevaluated_operand = saved_unevaluated_operand;
12243       c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
12244     }
12245
12246   /* Set the file and line number information to whatever is given for
12247      the class itself.  This puts error messages involving generated
12248      implicit functions at a predictable point, and the same point
12249      that would be used for non-template classes.  */
12250   input_location = DECL_SOURCE_LOCATION (typedecl);
12251
12252   unreverse_member_declarations (type);
12253   finish_struct_1 (type);
12254   TYPE_BEING_DEFINED (type) = 0;
12255
12256   /* We don't instantiate default arguments for member functions.  14.7.1:
12257
12258      The implicit instantiation of a class template specialization causes
12259      the implicit instantiation of the declarations, but not of the
12260      definitions or default arguments, of the class member functions,
12261      member classes, static data members and member templates....  */
12262
12263   perform_instantiation_time_access_checks (pattern, args);
12264   perform_deferred_access_checks (tf_warning_or_error);
12265   pop_nested_class ();
12266   maximum_field_alignment = saved_maximum_field_alignment;
12267   if (!fn_context)
12268     pop_from_top_level ();
12269   pop_tinst_level ();
12270
12271   /* The vtable for a template class can be emitted in any translation
12272      unit in which the class is instantiated.  When there is no key
12273      method, however, finish_struct_1 will already have added TYPE to
12274      the keyed_classes.  */
12275   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
12276     vec_safe_push (keyed_classes, type);
12277
12278   /* Now that we've gone through all the members, instantiate those
12279      marked with attribute used.  */
12280   for (tree x : used)
12281     mark_used (x);
12282
12283   return type;
12284 }
12285
12286 /* Wrapper for instantiate_class_template_1.  */
12287
12288 tree
12289 instantiate_class_template (tree type)
12290 {
12291   tree ret;
12292   timevar_push (TV_TEMPLATE_INST);
12293   ret = instantiate_class_template_1 (type);
12294   timevar_pop (TV_TEMPLATE_INST);
12295   return ret;
12296 }
12297
12298 tree
12299 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12300 {
12301   tree r;
12302
12303   if (!t)
12304     r = t;
12305   else if (TYPE_P (t))
12306     r = tsubst (t, args, complain, in_decl);
12307   else
12308     {
12309       if (!(complain & tf_warning))
12310         ++c_inhibit_evaluation_warnings;
12311       r = tsubst_expr (t, args, complain, in_decl,
12312                        /*integral_constant_expression_p=*/true);
12313       if (!(complain & tf_warning))
12314         --c_inhibit_evaluation_warnings;
12315     }
12316
12317   return r;
12318 }
12319
12320 /* Given a function parameter pack TMPL_PARM and some function parameters
12321    instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
12322    and set *SPEC_P to point at the next point in the list.  */
12323
12324 tree
12325 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
12326 {
12327   /* Collect all of the extra "packed" parameters into an
12328      argument pack.  */
12329   tree argpack;
12330   tree spec_parm = *spec_p;
12331   int len;
12332
12333   for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
12334     if (tmpl_parm
12335         && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
12336       break;
12337
12338   spec_parm = *spec_p;
12339   if (len == 1 && DECL_PACK_P (spec_parm))
12340     {
12341       /* The instantiation is still a parameter pack; don't wrap it in a
12342          NONTYPE_ARGUMENT_PACK.  */
12343       argpack = spec_parm;
12344       spec_parm = DECL_CHAIN (spec_parm);
12345     }
12346   else
12347     {
12348       /* Fill in PARMVEC with all of the parameters.  */
12349       tree parmvec = make_tree_vec (len);
12350       argpack = make_node (NONTYPE_ARGUMENT_PACK);
12351       for (int i = 0; i < len; i++)
12352         {
12353           tree elt = spec_parm;
12354           if (DECL_PACK_P (elt))
12355             elt = make_pack_expansion (elt);
12356           TREE_VEC_ELT (parmvec, i) = elt;
12357           spec_parm = DECL_CHAIN (spec_parm);
12358         }
12359
12360       /* Build the argument packs.  */
12361       SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
12362     }
12363   *spec_p = spec_parm;
12364
12365   return argpack;
12366 }
12367
12368 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
12369    NONTYPE_ARGUMENT_PACK.  */
12370
12371 static tree
12372 make_fnparm_pack (tree spec_parm)
12373 {
12374   return extract_fnparm_pack (NULL_TREE, &spec_parm);
12375 }
12376
12377 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
12378    pack expansion with no extra args, 2 if it has extra args, or 0
12379    if it is not a pack expansion.  */
12380
12381 static int
12382 argument_pack_element_is_expansion_p (tree arg_pack, int i)
12383 {
12384   if (TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12385     /* We're being called before this happens in tsubst_pack_expansion.  */
12386     arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12387   tree vec = ARGUMENT_PACK_ARGS (arg_pack);
12388   if (i >= TREE_VEC_LENGTH (vec))
12389     return 0;
12390   tree elt = TREE_VEC_ELT (vec, i);
12391   if (DECL_P (elt))
12392     /* A decl pack is itself an expansion.  */
12393     elt = TREE_TYPE (elt);
12394   if (!PACK_EXPANSION_P (elt))
12395     return 0;
12396   if (PACK_EXPANSION_EXTRA_ARGS (elt))
12397     return 2;
12398   return 1;
12399 }
12400
12401
12402 /* Creates and return an ARGUMENT_PACK_SELECT tree node.  */
12403
12404 static tree
12405 make_argument_pack_select (tree arg_pack, unsigned index)
12406 {
12407   tree aps = make_node (ARGUMENT_PACK_SELECT);
12408
12409   ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
12410   ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12411
12412   return aps;
12413 }
12414
12415 /*  This is a subroutine of tsubst_pack_expansion.
12416
12417     It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
12418     mechanism to store the (non complete list of) arguments of the
12419     substitution and return a non substituted pack expansion, in order
12420     to wait for when we have enough arguments to really perform the
12421     substitution.  */
12422
12423 static bool
12424 use_pack_expansion_extra_args_p (tree parm_packs,
12425                                  int arg_pack_len,
12426                                  bool has_empty_arg)
12427 {
12428   /* If one pack has an expansion and another pack has a normal
12429      argument or if one pack has an empty argument and an another
12430      one hasn't then tsubst_pack_expansion cannot perform the
12431      substitution and need to fall back on the
12432      PACK_EXPANSION_EXTRA mechanism.  */
12433   if (parm_packs == NULL_TREE)
12434     return false;
12435   else if (has_empty_arg)
12436     {
12437       /* If all the actual packs are pack expansions, we can still
12438          subsitute directly.  */
12439       for (tree p = parm_packs; p; p = TREE_CHAIN (p))
12440         {
12441           tree a = TREE_VALUE (p);
12442           if (TREE_CODE (a) == ARGUMENT_PACK_SELECT)
12443             a = ARGUMENT_PACK_SELECT_FROM_PACK (a);
12444           a = ARGUMENT_PACK_ARGS (a);
12445           if (TREE_VEC_LENGTH (a) == 1)
12446             a = TREE_VEC_ELT (a, 0);
12447           if (PACK_EXPANSION_P (a))
12448             continue;
12449           return true;
12450         }
12451       return false;
12452     }
12453
12454   bool has_expansion_arg = false;
12455   for (int i = 0 ; i < arg_pack_len; ++i)
12456     {
12457       bool has_non_expansion_arg = false;
12458       for (tree parm_pack = parm_packs;
12459            parm_pack;
12460            parm_pack = TREE_CHAIN (parm_pack))
12461         {
12462           tree arg = TREE_VALUE (parm_pack);
12463
12464           int exp = argument_pack_element_is_expansion_p (arg, i);
12465           if (exp == 2)
12466             /* We can't substitute a pack expansion with extra args into
12467                our pattern.  */
12468             return true;
12469           else if (exp)
12470             has_expansion_arg = true;
12471           else
12472             has_non_expansion_arg = true;
12473         }
12474
12475       if (has_expansion_arg && has_non_expansion_arg)
12476         return true;
12477     }
12478   return false;
12479 }
12480
12481 /* [temp.variadic]/6 says that:
12482
12483        The instantiation of a pack expansion [...]
12484        produces a list E1,E2, ..., En, where N is the number of elements
12485        in the pack expansion parameters.
12486
12487    This subroutine of tsubst_pack_expansion produces one of these Ei.
12488
12489    PATTERN is the pattern of the pack expansion.  PARM_PACKS is a
12490    TREE_LIST in which each TREE_PURPOSE is a parameter pack of
12491    PATTERN, and each TREE_VALUE is its corresponding argument pack.
12492    INDEX is the index 'i' of the element Ei to produce.  ARGS,
12493    COMPLAIN, and IN_DECL are the same parameters as for the
12494    tsubst_pack_expansion function.
12495
12496    The function returns the resulting Ei upon successful completion,
12497    or error_mark_node.
12498
12499    Note that this function possibly modifies the ARGS parameter, so
12500    it's the responsibility of the caller to restore it.  */
12501
12502 static tree
12503 gen_elem_of_pack_expansion_instantiation (tree pattern,
12504                                           tree parm_packs,
12505                                           unsigned index,
12506                                           tree args /* This parm gets
12507                                                        modified.  */,
12508                                           tsubst_flags_t complain,
12509                                           tree in_decl)
12510 {
12511   tree t;
12512   bool ith_elem_is_expansion = false;
12513
12514   /* For each parameter pack, change the substitution of the parameter
12515      pack to the ith argument in its argument pack, then expand the
12516      pattern.  */
12517   for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
12518     {
12519       tree parm = TREE_PURPOSE (pack);
12520       tree arg_pack = TREE_VALUE (pack);
12521       tree aps;                 /* instance of ARGUMENT_PACK_SELECT.  */
12522
12523       ith_elem_is_expansion |=
12524         argument_pack_element_is_expansion_p (arg_pack, index);
12525
12526       /* Select the Ith argument from the pack.  */
12527       if (TREE_CODE (parm) == PARM_DECL
12528           || VAR_P (parm)
12529           || TREE_CODE (parm) == FIELD_DECL)
12530         {
12531           if (index == 0)
12532             {
12533               aps = make_argument_pack_select (arg_pack, index);
12534               if (!mark_used (parm, complain) && !(complain & tf_error))
12535                 return error_mark_node;
12536               register_local_specialization (aps, parm);
12537             }
12538           else
12539             aps = retrieve_local_specialization (parm);
12540         }
12541       else
12542         {
12543           int idx, level;
12544           template_parm_level_and_index (parm, &level, &idx);
12545
12546           if (index == 0)
12547             {
12548               aps = make_argument_pack_select (arg_pack, index);
12549               /* Update the corresponding argument.  */
12550               TMPL_ARG (args, level, idx) = aps;
12551             }
12552           else
12553             /* Re-use the ARGUMENT_PACK_SELECT.  */
12554             aps = TMPL_ARG (args, level, idx);
12555         }
12556       ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12557     }
12558
12559   /* Substitute into the PATTERN with the (possibly altered)
12560      arguments.  */
12561   if (pattern == in_decl)
12562     /* Expanding a fixed parameter pack from
12563        coerce_template_parameter_pack.  */
12564     t = tsubst_decl (pattern, args, complain);
12565   else if (pattern == error_mark_node)
12566     t = error_mark_node;
12567   else if (!TYPE_P (pattern))
12568     t = tsubst_expr (pattern, args, complain, in_decl,
12569                      /*integral_constant_expression_p=*/false);
12570   else
12571     t = tsubst (pattern, args, complain, in_decl);
12572
12573   /*  If the Ith argument pack element is a pack expansion, then
12574       the Ith element resulting from the substituting is going to
12575       be a pack expansion as well.  */
12576   if (ith_elem_is_expansion)
12577     t = make_pack_expansion (t, complain);
12578
12579   return t;
12580 }
12581
12582 /* When the unexpanded parameter pack in a fold expression expands to an empty
12583    sequence, the value of the expression is as follows; the program is
12584    ill-formed if the operator is not listed in this table.
12585
12586    &&   true
12587    ||   false
12588    ,    void()  */
12589
12590 tree
12591 expand_empty_fold (tree t, tsubst_flags_t complain)
12592 {
12593   tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
12594   if (!FOLD_EXPR_MODIFY_P (t))
12595     switch (code)
12596       {
12597       case TRUTH_ANDIF_EXPR:
12598         return boolean_true_node;
12599       case TRUTH_ORIF_EXPR:
12600         return boolean_false_node;
12601       case COMPOUND_EXPR:
12602         return void_node;
12603       default:
12604         break;
12605       }
12606
12607   if (complain & tf_error)
12608     error_at (location_of (t),
12609               "fold of empty expansion over %O", code);
12610   return error_mark_node;
12611 }
12612
12613 /* Given a fold-expression T and a current LEFT and RIGHT operand,
12614    form an expression that combines the two terms using the
12615    operator of T. */
12616
12617 static tree
12618 fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
12619 {
12620   tree op = FOLD_EXPR_OP (t);
12621   tree_code code = (tree_code)TREE_INT_CST_LOW (op);
12622
12623   // Handle compound assignment operators.
12624   if (FOLD_EXPR_MODIFY_P (t))
12625     return build_x_modify_expr (input_location, left, code, right, complain);
12626
12627   warning_sentinel s(warn_parentheses);
12628   switch (code)
12629     {
12630     case COMPOUND_EXPR:
12631       return build_x_compound_expr (input_location, left, right, complain);
12632     default:
12633       return build_x_binary_op (input_location, code,
12634                                 left, TREE_CODE (left),
12635                                 right, TREE_CODE (right),
12636                                 /*overload=*/NULL,
12637                                 complain);
12638     }
12639 }
12640
12641 /* Substitute ARGS into the pack of a fold expression T. */
12642
12643 static inline tree
12644 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12645 {
12646   return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
12647 }
12648
12649 /* Substitute ARGS into the pack of a fold expression T. */
12650
12651 static inline tree
12652 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12653 {
12654   return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl, false);
12655 }
12656
12657 /* Expand a PACK of arguments into a grouped as left fold.
12658    Given a pack containing elements A0, A1, ..., An and an
12659    operator @, this builds the expression:
12660
12661       ((A0 @ A1) @ A2) ... @ An
12662
12663    Note that PACK must not be empty.
12664
12665    The operator is defined by the original fold expression T. */
12666
12667 static tree
12668 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
12669 {
12670   tree left = TREE_VEC_ELT (pack, 0);
12671   for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
12672     {
12673       tree right = TREE_VEC_ELT (pack, i);
12674       left = fold_expression (t, left, right, complain);
12675     }
12676   return left;
12677 }
12678
12679 /* Substitute into a unary left fold expression. */
12680
12681 static tree
12682 tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
12683                         tree in_decl)
12684 {
12685   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12686   if (pack == error_mark_node)
12687     return error_mark_node;
12688   if (PACK_EXPANSION_P (pack))
12689     {
12690       tree r = copy_node (t);
12691       FOLD_EXPR_PACK (r) = pack;
12692       return r;
12693     }
12694   if (TREE_VEC_LENGTH (pack) == 0)
12695     return expand_empty_fold (t, complain);
12696   else
12697     return expand_left_fold (t, pack, complain);
12698 }
12699
12700 /* Substitute into a binary left fold expression.
12701
12702    Do ths by building a single (non-empty) vector of argumnts and
12703    building the expression from those elements. */
12704
12705 static tree
12706 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
12707                          tree in_decl)
12708 {
12709   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12710   if (pack == error_mark_node)
12711     return error_mark_node;
12712   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
12713   if (init == error_mark_node)
12714     return error_mark_node;
12715
12716   if (PACK_EXPANSION_P (pack))
12717     {
12718       tree r = copy_node (t);
12719       FOLD_EXPR_PACK (r) = pack;
12720       FOLD_EXPR_INIT (r) = init;
12721       return r;
12722     }
12723
12724   tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
12725   TREE_VEC_ELT (vec, 0) = init;
12726   for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
12727     TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
12728
12729   return expand_left_fold (t, vec, complain);
12730 }
12731
12732 /* Expand a PACK of arguments into a grouped as right fold.
12733    Given a pack containing elementns A0, A1, ..., and an
12734    operator @, this builds the expression:
12735
12736       A0@ ... (An-2 @ (An-1 @ An))
12737
12738    Note that PACK must not be empty.
12739
12740    The operator is defined by the original fold expression T. */
12741
12742 tree
12743 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
12744 {
12745   // Build the expression.
12746   int n = TREE_VEC_LENGTH (pack);
12747   tree right = TREE_VEC_ELT (pack, n - 1);
12748   for (--n; n != 0; --n)
12749     {
12750       tree left = TREE_VEC_ELT (pack, n - 1);
12751       right = fold_expression (t, left, right, complain);
12752     }
12753   return right;
12754 }
12755
12756 /* Substitute into a unary right fold expression. */
12757
12758 static tree
12759 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
12760                          tree in_decl)
12761 {
12762   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12763   if (pack == error_mark_node)
12764     return error_mark_node;
12765   if (PACK_EXPANSION_P (pack))
12766     {
12767       tree r = copy_node (t);
12768       FOLD_EXPR_PACK (r) = pack;
12769       return r;
12770     }
12771   if (TREE_VEC_LENGTH (pack) == 0)
12772     return expand_empty_fold (t, complain);
12773   else
12774     return expand_right_fold (t, pack, complain);
12775 }
12776
12777 /* Substitute into a binary right fold expression.
12778
12779    Do ths by building a single (non-empty) vector of arguments and
12780    building the expression from those elements. */
12781
12782 static tree
12783 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
12784                          tree in_decl)
12785 {
12786   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12787   if (pack == error_mark_node)
12788     return error_mark_node;
12789   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
12790   if (init == error_mark_node)
12791     return error_mark_node;
12792
12793   if (PACK_EXPANSION_P (pack))
12794     {
12795       tree r = copy_node (t);
12796       FOLD_EXPR_PACK (r) = pack;
12797       FOLD_EXPR_INIT (r) = init;
12798       return r;
12799     }
12800
12801   int n = TREE_VEC_LENGTH (pack);
12802   tree vec = make_tree_vec (n + 1);
12803   for (int i = 0; i < n; ++i)
12804     TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
12805   TREE_VEC_ELT (vec, n) = init;
12806
12807   return expand_right_fold (t, vec, complain);
12808 }
12809
12810 /* Walk through the pattern of a pack expansion, adding everything in
12811    local_specializations to a list.  */
12812
12813 class el_data
12814 {
12815 public:
12816   /* Set of variables declared within the pattern.  */
12817   hash_set<tree> internal;
12818   /* Set of AST nodes that have been visited by the traversal.  */
12819   hash_set<tree> visited;
12820   /* List of local_specializations used within the pattern.  */
12821   tree extra;
12822   tsubst_flags_t complain;
12823
12824   el_data (tsubst_flags_t c)
12825     : extra (NULL_TREE), complain (c) {}
12826 };
12827 static tree
12828 extract_locals_r (tree *tp, int */*walk_subtrees*/, void *data_)
12829 {
12830   el_data &data = *reinterpret_cast<el_data*>(data_);
12831   tree *extra = &data.extra;
12832   tsubst_flags_t complain = data.complain;
12833
12834   if (TYPE_P (*tp) && typedef_variant_p (*tp))
12835     /* Remember local typedefs (85214).  */
12836     tp = &TYPE_NAME (*tp);
12837
12838   if (TREE_CODE (*tp) == DECL_EXPR)
12839     {
12840       tree decl = DECL_EXPR_DECL (*tp);
12841       data.internal.add (decl);
12842       if (VAR_P (decl)
12843           && DECL_DECOMPOSITION_P (decl)
12844           && TREE_TYPE (decl) != error_mark_node)
12845         {
12846           gcc_assert (DECL_NAME (decl) == NULL_TREE);
12847           for (tree decl2 = DECL_CHAIN (decl);
12848                decl2
12849                && VAR_P (decl2)
12850                && DECL_DECOMPOSITION_P (decl2)
12851                && DECL_NAME (decl2)
12852                && TREE_TYPE (decl2) != error_mark_node;
12853                decl2 = DECL_CHAIN (decl2))
12854             {
12855               gcc_assert (DECL_DECOMP_BASE (decl2) == decl);
12856               data.internal.add (decl2);
12857             }
12858         }
12859     }
12860   else if (TREE_CODE (*tp) == LAMBDA_EXPR)
12861     {
12862       /* Since we defer implicit capture, look in the parms and body.  */
12863       tree fn = lambda_function (*tp);
12864       cp_walk_tree (&TREE_TYPE (fn), &extract_locals_r, &data,
12865                     &data.visited);
12866       cp_walk_tree (&DECL_SAVED_TREE (fn), &extract_locals_r, &data,
12867                     &data.visited);
12868     }
12869   else if (tree spec = retrieve_local_specialization (*tp))
12870     {
12871       if (data.internal.contains (*tp))
12872         /* Don't mess with variables declared within the pattern.  */
12873         return NULL_TREE;
12874       if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
12875         {
12876           /* Maybe pull out the PARM_DECL for a partial instantiation.  */
12877           tree args = ARGUMENT_PACK_ARGS (spec);
12878           if (TREE_VEC_LENGTH (args) == 1)
12879             {
12880               tree elt = TREE_VEC_ELT (args, 0);
12881               if (PACK_EXPANSION_P (elt))
12882                 elt = PACK_EXPANSION_PATTERN (elt);
12883               if (DECL_PACK_P (elt))
12884                 spec = elt;
12885             }
12886           if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
12887             {
12888               /* Handle lambda capture here, since we aren't doing any
12889                  substitution now, and so tsubst_copy won't call
12890                  process_outer_var_ref.  */
12891               tree args = ARGUMENT_PACK_ARGS (spec);
12892               int len = TREE_VEC_LENGTH (args);
12893               for (int i = 0; i < len; ++i)
12894                 {
12895                   tree arg = TREE_VEC_ELT (args, i);
12896                   tree carg = arg;
12897                   if (outer_automatic_var_p (arg))
12898                     carg = process_outer_var_ref (arg, complain);
12899                   if (carg != arg)
12900                     {
12901                       /* Make a new NONTYPE_ARGUMENT_PACK of the capture
12902                          proxies.  */
12903                       if (i == 0)
12904                         {
12905                           spec = copy_node (spec);
12906                           args = copy_node (args);
12907                           SET_ARGUMENT_PACK_ARGS (spec, args);
12908                           register_local_specialization (spec, *tp);
12909                         }
12910                       TREE_VEC_ELT (args, i) = carg;
12911                     }
12912                 }
12913             }
12914         }
12915       if (outer_automatic_var_p (spec))
12916         spec = process_outer_var_ref (spec, complain);
12917       *extra = tree_cons (*tp, spec, *extra);
12918     }
12919   return NULL_TREE;
12920 }
12921 static tree
12922 extract_local_specs (tree pattern, tsubst_flags_t complain)
12923 {
12924   el_data data (complain);
12925   cp_walk_tree (&pattern, extract_locals_r, &data, &data.visited);
12926   return data.extra;
12927 }
12928
12929 /* Extract any uses of local_specializations from PATTERN and add them to ARGS
12930    for use in PACK_EXPANSION_EXTRA_ARGS.  */
12931
12932 tree
12933 build_extra_args (tree pattern, tree args, tsubst_flags_t complain)
12934 {
12935   tree extra = args;
12936   if (local_specializations)
12937     if (tree locals = extract_local_specs (pattern, complain))
12938       extra = tree_cons (NULL_TREE, extra, locals);
12939   return extra;
12940 }
12941
12942 /* Apply any local specializations from PACK_EXPANSION_EXTRA_ARGS and add the
12943    normal template args to ARGS.  */
12944
12945 tree
12946 add_extra_args (tree extra, tree args)
12947 {
12948   if (extra && TREE_CODE (extra) == TREE_LIST)
12949     {
12950       for (tree elt = TREE_CHAIN (extra); elt; elt = TREE_CHAIN (elt))
12951         {
12952           /* The partial instantiation involved local declarations collected in
12953              extract_local_specs; map from the general template to our local
12954              context.  */
12955           tree gen = TREE_PURPOSE (elt);
12956           tree inst = TREE_VALUE (elt);
12957           if (DECL_P (inst))
12958             if (tree local = retrieve_local_specialization (inst))
12959               inst = local;
12960           /* else inst is already a full instantiation of the pack.  */
12961           register_local_specialization (inst, gen);
12962         }
12963       gcc_assert (!TREE_PURPOSE (extra));
12964       extra = TREE_VALUE (extra);
12965     }
12966 #if 1
12967   /* I think we should always be able to substitute dependent args into the
12968      pattern.  If that turns out to be incorrect in some cases, enable the
12969      alternate code (and add complain/in_decl parms to this function).  */
12970   gcc_checking_assert (!uses_template_parms (extra));
12971 #else
12972   if (!uses_template_parms (extra))
12973     {
12974       gcc_unreachable ();
12975       extra = tsubst_template_args (extra, args, complain, in_decl);
12976       args = add_outermost_template_args (args, extra);
12977     }
12978   else
12979 #endif
12980     args = add_to_template_args (extra, args);
12981   return args;
12982 }
12983
12984 /* Substitute ARGS into T, which is an pack expansion
12985    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
12986    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
12987    (if only a partial substitution could be performed) or
12988    ERROR_MARK_NODE if there was an error.  */
12989 tree
12990 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
12991                        tree in_decl)
12992 {
12993   tree pattern;
12994   tree pack, packs = NULL_TREE;
12995   bool unsubstituted_packs = false;
12996   int i, len = -1;
12997   tree result;
12998   bool need_local_specializations = false;
12999   int levels;
13000
13001   gcc_assert (PACK_EXPANSION_P (t));
13002   pattern = PACK_EXPANSION_PATTERN (t);
13003
13004   /* Add in any args remembered from an earlier partial instantiation.  */
13005   args = add_extra_args (PACK_EXPANSION_EXTRA_ARGS (t), args);
13006
13007   levels = TMPL_ARGS_DEPTH (args);
13008
13009   /* Determine the argument packs that will instantiate the parameter
13010      packs used in the expansion expression. While we're at it,
13011      compute the number of arguments to be expanded and make sure it
13012      is consistent.  */
13013   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
13014        pack = TREE_CHAIN (pack))
13015     {
13016       tree parm_pack = TREE_VALUE (pack);
13017       tree arg_pack = NULL_TREE;
13018       tree orig_arg = NULL_TREE;
13019       int level = 0;
13020
13021       if (TREE_CODE (parm_pack) == BASES)
13022         {
13023           gcc_assert (parm_pack == pattern);
13024           if (BASES_DIRECT (parm_pack))
13025             return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
13026                                                         args, complain,
13027                                                         in_decl, false),
13028                                            complain);
13029           else
13030             return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
13031                                                  args, complain, in_decl,
13032                                                  false), complain);
13033         }
13034       else if (builtin_pack_call_p (parm_pack))
13035         {
13036           if (parm_pack != pattern)
13037             {
13038               if (complain & tf_error)
13039                 sorry ("%qE is not the entire pattern of the pack expansion",
13040                        parm_pack);
13041               return error_mark_node;
13042             }
13043           return expand_builtin_pack_call (parm_pack, args,
13044                                            complain, in_decl);
13045         }
13046       else if (TREE_CODE (parm_pack) == PARM_DECL)
13047         {
13048           /* We know we have correct local_specializations if this
13049              expansion is at function scope, or if we're dealing with a
13050              local parameter in a requires expression; for the latter,
13051              tsubst_requires_expr set it up appropriately.  */
13052           if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
13053             arg_pack = retrieve_local_specialization (parm_pack);
13054           else
13055             /* We can't rely on local_specializations for a parameter
13056                name used later in a function declaration (such as in a
13057                late-specified return type).  Even if it exists, it might
13058                have the wrong value for a recursive call.  */
13059             need_local_specializations = true;
13060
13061           if (!arg_pack)
13062             {
13063               /* This parameter pack was used in an unevaluated context.  Just
13064                  make a dummy decl, since it's only used for its type.  */
13065               ++cp_unevaluated_operand;
13066               arg_pack = tsubst_decl (parm_pack, args, complain);
13067               --cp_unevaluated_operand;
13068               if (arg_pack && DECL_PACK_P (arg_pack))
13069                 /* Partial instantiation of the parm_pack, we can't build
13070                    up an argument pack yet.  */
13071                 arg_pack = NULL_TREE;
13072               else
13073                 arg_pack = make_fnparm_pack (arg_pack);
13074             }
13075           else if (DECL_PACK_P (arg_pack))
13076             /* This argument pack isn't fully instantiated yet.  */
13077             arg_pack = NULL_TREE;
13078         }
13079       else if (is_capture_proxy (parm_pack))
13080         {
13081           arg_pack = retrieve_local_specialization (parm_pack);
13082           if (DECL_PACK_P (arg_pack))
13083             arg_pack = NULL_TREE;
13084         }
13085       else
13086         {
13087           int idx;
13088           template_parm_level_and_index (parm_pack, &level, &idx);
13089           if (level <= levels)
13090             arg_pack = TMPL_ARG (args, level, idx);
13091
13092           if (arg_pack && TREE_CODE (arg_pack) == TEMPLATE_TYPE_PARM
13093               && TEMPLATE_TYPE_PARAMETER_PACK (arg_pack))
13094             arg_pack = NULL_TREE;
13095         }
13096
13097       orig_arg = arg_pack;
13098       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
13099         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
13100
13101       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
13102         /* This can only happen if we forget to expand an argument
13103            pack somewhere else. Just return an error, silently.  */
13104         {
13105           result = make_tree_vec (1);
13106           TREE_VEC_ELT (result, 0) = error_mark_node;
13107           return result;
13108         }
13109
13110       if (arg_pack)
13111         {
13112           int my_len = 
13113             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
13114
13115           /* Don't bother trying to do a partial substitution with
13116              incomplete packs; we'll try again after deduction.  */
13117           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
13118             return t;
13119
13120           if (len < 0)
13121             len = my_len;
13122           else if (len != my_len)
13123             {
13124               if (!(complain & tf_error))
13125                 /* Fail quietly.  */;
13126               else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
13127                 error ("mismatched argument pack lengths while expanding %qT",
13128                        pattern);
13129               else
13130                 error ("mismatched argument pack lengths while expanding %qE",
13131                        pattern);
13132               return error_mark_node;
13133             }
13134
13135           /* Keep track of the parameter packs and their corresponding
13136              argument packs.  */
13137           packs = tree_cons (parm_pack, arg_pack, packs);
13138           TREE_TYPE (packs) = orig_arg;
13139         }
13140       else
13141         {
13142           /* We can't substitute for this parameter pack.  We use a flag as
13143              well as the missing_level counter because function parameter
13144              packs don't have a level.  */
13145           gcc_assert (processing_template_decl || is_auto (parm_pack));
13146           unsubstituted_packs = true;
13147         }
13148     }
13149
13150   /* If the expansion is just T..., return the matching argument pack, unless
13151      we need to call convert_from_reference on all the elements.  This is an
13152      important optimization; see c++/68422.  */
13153   if (!unsubstituted_packs
13154       && TREE_PURPOSE (packs) == pattern)
13155     {
13156       tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
13157
13158       /* If the argument pack is a single pack expansion, pull it out.  */
13159       if (TREE_VEC_LENGTH (args) == 1
13160           && pack_expansion_args_count (args))
13161         return TREE_VEC_ELT (args, 0);
13162
13163       /* Types need no adjustment, nor does sizeof..., and if we still have
13164          some pack expansion args we won't do anything yet.  */
13165       if (TREE_CODE (t) == TYPE_PACK_EXPANSION
13166           || PACK_EXPANSION_SIZEOF_P (t)
13167           || pack_expansion_args_count (args))
13168         return args;
13169       /* Also optimize expression pack expansions if we can tell that the
13170          elements won't have reference type.  */
13171       tree type = TREE_TYPE (pattern);
13172       if (type && !TYPE_REF_P (type)
13173           && !PACK_EXPANSION_P (type)
13174           && !WILDCARD_TYPE_P (type))
13175         return args;
13176       /* Otherwise use the normal path so we get convert_from_reference.  */
13177     }
13178
13179   /* We cannot expand this expansion expression, because we don't have
13180      all of the argument packs we need.  */
13181   if (use_pack_expansion_extra_args_p (packs, len, unsubstituted_packs))
13182     {
13183       /* We got some full packs, but we can't substitute them in until we
13184          have values for all the packs.  So remember these until then.  */
13185
13186       t = make_pack_expansion (pattern, complain);
13187       PACK_EXPANSION_EXTRA_ARGS (t)
13188         = build_extra_args (pattern, args, complain);
13189       return t;
13190     }
13191
13192   /* If NEED_LOCAL_SPECIALIZATIONS then we're in a late-specified return
13193      type, so create our own local specializations map; the current map is
13194      either NULL or (in the case of recursive unification) might have
13195      bindings that we don't want to use or alter.  */
13196   local_specialization_stack lss (need_local_specializations
13197                                   ? lss_blank : lss_nop);
13198
13199   if (unsubstituted_packs)
13200     {
13201       /* There were no real arguments, we're just replacing a parameter
13202          pack with another version of itself. Substitute into the
13203          pattern and return a PACK_EXPANSION_*. The caller will need to
13204          deal with that.  */
13205       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
13206         result = tsubst_expr (pattern, args, complain, in_decl,
13207                          /*integral_constant_expression_p=*/false);
13208       else
13209         result = tsubst (pattern, args, complain, in_decl);
13210       result = make_pack_expansion (result, complain);
13211       if (PACK_EXPANSION_AUTO_P (t))
13212         {
13213           /* This is a fake auto... pack expansion created in add_capture with
13214              _PACKS that don't appear in the pattern.  Copy one over.  */
13215           packs = PACK_EXPANSION_PARAMETER_PACKS (t);
13216           pack = retrieve_local_specialization (TREE_VALUE (packs));
13217           gcc_checking_assert (DECL_PACK_P (pack));
13218           PACK_EXPANSION_PARAMETER_PACKS (result)
13219             = build_tree_list (NULL_TREE, pack);
13220           PACK_EXPANSION_AUTO_P (result) = true;
13221         }
13222       return result;
13223     }
13224
13225   gcc_assert (len >= 0);
13226
13227   /* For each argument in each argument pack, substitute into the
13228      pattern.  */
13229   result = make_tree_vec (len);
13230   tree elem_args = copy_template_args (args);
13231   for (i = 0; i < len; ++i)
13232     {
13233       t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
13234                                                     i,
13235                                                     elem_args, complain,
13236                                                     in_decl);
13237       TREE_VEC_ELT (result, i) = t;
13238       if (t == error_mark_node)
13239         {
13240           result = error_mark_node;
13241           break;
13242         }
13243     }
13244
13245   /* Update ARGS to restore the substitution from parameter packs to
13246      their argument packs.  */
13247   for (pack = packs; pack; pack = TREE_CHAIN (pack))
13248     {
13249       tree parm = TREE_PURPOSE (pack);
13250
13251       if (TREE_CODE (parm) == PARM_DECL
13252           || VAR_P (parm)
13253           || TREE_CODE (parm) == FIELD_DECL)
13254         register_local_specialization (TREE_TYPE (pack), parm);
13255       else
13256         {
13257           int idx, level;
13258
13259           if (TREE_VALUE (pack) == NULL_TREE)
13260             continue;
13261
13262           template_parm_level_and_index (parm, &level, &idx);
13263
13264           /* Update the corresponding argument.  */
13265           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
13266             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
13267               TREE_TYPE (pack);
13268           else
13269             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
13270         }
13271     }
13272
13273   /* If the dependent pack arguments were such that we end up with only a
13274      single pack expansion again, there's no need to keep it in a TREE_VEC.  */
13275   if (len == 1 && TREE_CODE (result) == TREE_VEC
13276       && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
13277     return TREE_VEC_ELT (result, 0);
13278
13279   return result;
13280 }
13281
13282 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
13283    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
13284    parameter packs; all parms generated from a function parameter pack will
13285    have the same DECL_PARM_INDEX.  */
13286
13287 tree
13288 get_pattern_parm (tree parm, tree tmpl)
13289 {
13290   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
13291   tree patparm;
13292
13293   if (DECL_ARTIFICIAL (parm))
13294     {
13295       for (patparm = DECL_ARGUMENTS (pattern);
13296            patparm; patparm = DECL_CHAIN (patparm))
13297         if (DECL_ARTIFICIAL (patparm)
13298             && DECL_NAME (parm) == DECL_NAME (patparm))
13299           break;
13300     }
13301   else
13302     {
13303       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
13304       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
13305       gcc_assert (DECL_PARM_INDEX (patparm)
13306                   == DECL_PARM_INDEX (parm));
13307     }
13308
13309   return patparm;
13310 }
13311
13312 /* Make an argument pack out of the TREE_VEC VEC.  */
13313
13314 static tree
13315 make_argument_pack (tree vec)
13316 {
13317   tree pack;
13318
13319   if (TYPE_P (TREE_VEC_ELT (vec, 0)))
13320     pack = cxx_make_type (TYPE_ARGUMENT_PACK);
13321   else
13322     {
13323       pack = make_node (NONTYPE_ARGUMENT_PACK);
13324       TREE_CONSTANT (pack) = 1;
13325     }
13326   SET_ARGUMENT_PACK_ARGS (pack, vec);
13327   return pack;
13328 }
13329
13330 /* Return an exact copy of template args T that can be modified
13331    independently.  */
13332
13333 static tree
13334 copy_template_args (tree t)
13335 {
13336   if (t == error_mark_node)
13337     return t;
13338
13339   int len = TREE_VEC_LENGTH (t);
13340   tree new_vec = make_tree_vec (len);
13341
13342   for (int i = 0; i < len; ++i)
13343     {
13344       tree elt = TREE_VEC_ELT (t, i);
13345       if (elt && TREE_CODE (elt) == TREE_VEC)
13346         elt = copy_template_args (elt);
13347       TREE_VEC_ELT (new_vec, i) = elt;
13348     }
13349
13350   NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
13351     = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13352
13353   return new_vec;
13354 }
13355
13356 /* Substitute ARGS into the *_ARGUMENT_PACK orig_arg.  */
13357
13358 tree
13359 tsubst_argument_pack (tree orig_arg, tree args, tsubst_flags_t complain,
13360                       tree in_decl)
13361 {
13362   /* Substitute into each of the arguments.  */
13363   tree pack_args = tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
13364                                          args, complain, in_decl);
13365   tree new_arg = error_mark_node;
13366   if (pack_args != error_mark_node)
13367     {
13368       if (TYPE_P (orig_arg))
13369         {
13370           new_arg = cxx_make_type (TREE_CODE (orig_arg));
13371           SET_TYPE_STRUCTURAL_EQUALITY (new_arg);
13372         }
13373       else
13374         {
13375           new_arg = make_node (TREE_CODE (orig_arg));
13376           TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
13377         }
13378
13379       SET_ARGUMENT_PACK_ARGS (new_arg, pack_args);
13380     }
13381
13382   return new_arg;
13383 }
13384
13385 /* Substitute ARGS into the vector or list of template arguments T.  */
13386
13387 tree
13388 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
13389 {
13390   tree orig_t = t;
13391   int len, need_new = 0, i, expanded_len_adjust = 0, out;
13392   tree *elts;
13393
13394   if (t == error_mark_node)
13395     return error_mark_node;
13396
13397   len = TREE_VEC_LENGTH (t);
13398   elts = XALLOCAVEC (tree, len);
13399
13400   for (i = 0; i < len; i++)
13401     {
13402       tree orig_arg = TREE_VEC_ELT (t, i);
13403       tree new_arg;
13404
13405       if (TREE_CODE (orig_arg) == TREE_VEC)
13406         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
13407       else if (PACK_EXPANSION_P (orig_arg))
13408         {
13409           /* Substitute into an expansion expression.  */
13410           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
13411
13412           if (TREE_CODE (new_arg) == TREE_VEC)
13413             /* Add to the expanded length adjustment the number of
13414                expanded arguments. We subtract one from this
13415                measurement, because the argument pack expression
13416                itself is already counted as 1 in
13417                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
13418                the argument pack is empty.  */
13419             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
13420         }
13421       else if (ARGUMENT_PACK_P (orig_arg))
13422         new_arg = tsubst_argument_pack (orig_arg, args, complain, in_decl);
13423       else
13424         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
13425
13426       if (new_arg == error_mark_node)
13427         return error_mark_node;
13428
13429       elts[i] = new_arg;
13430       if (new_arg != orig_arg)
13431         need_new = 1;
13432     }
13433
13434   if (!need_new)
13435     return t;
13436
13437   /* Make space for the expanded arguments coming from template
13438      argument packs.  */
13439   t = make_tree_vec (len + expanded_len_adjust);
13440   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
13441      arguments for a member template.
13442      In that case each TREE_VEC in ORIG_T represents a level of template
13443      arguments, and ORIG_T won't carry any non defaulted argument count.
13444      It will rather be the nested TREE_VECs that will carry one.
13445      In other words, ORIG_T carries a non defaulted argument count only
13446      if it doesn't contain any nested TREE_VEC.  */
13447   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
13448     {
13449       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
13450       count += expanded_len_adjust;
13451       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
13452     }
13453   for (i = 0, out = 0; i < len; i++)
13454     {
13455       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
13456            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
13457           && TREE_CODE (elts[i]) == TREE_VEC)
13458         {
13459           int idx;
13460
13461           /* Now expand the template argument pack "in place".  */
13462           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
13463             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
13464         }
13465       else
13466         {
13467           TREE_VEC_ELT (t, out) = elts[i];
13468           out++;
13469         }
13470     }
13471
13472   return t;
13473 }
13474
13475 /* Substitute ARGS into one level PARMS of template parameters.  */
13476
13477 static tree
13478 tsubst_template_parms_level (tree parms, tree args, tsubst_flags_t complain)
13479 {
13480   if (parms == error_mark_node)
13481     return error_mark_node;
13482
13483   tree new_vec = make_tree_vec (TREE_VEC_LENGTH (parms));
13484
13485   for (int i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
13486     {
13487       tree tuple = TREE_VEC_ELT (parms, i);
13488
13489       if (tuple == error_mark_node)
13490         continue;
13491
13492       TREE_VEC_ELT (new_vec, i) =
13493         tsubst_template_parm (tuple, args, complain);
13494     }
13495
13496   return new_vec;
13497 }
13498
13499 /* Return the result of substituting ARGS into the template parameters
13500    given by PARMS.  If there are m levels of ARGS and m + n levels of
13501    PARMS, then the result will contain n levels of PARMS.  For
13502    example, if PARMS is `template <class T> template <class U>
13503    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
13504    result will be `template <int*, double, class V>'.  */
13505
13506 static tree
13507 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
13508 {
13509   tree r = NULL_TREE;
13510   tree* new_parms;
13511
13512   /* When substituting into a template, we must set
13513      PROCESSING_TEMPLATE_DECL as the template parameters may be
13514      dependent if they are based on one-another, and the dependency
13515      predicates are short-circuit outside of templates.  */
13516   ++processing_template_decl;
13517
13518   for (new_parms = &r;
13519        parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
13520        new_parms = &(TREE_CHAIN (*new_parms)),
13521          parms = TREE_CHAIN (parms))
13522     {
13523       tree new_vec = tsubst_template_parms_level (TREE_VALUE (parms),
13524                                                   args, complain);
13525       *new_parms =
13526         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
13527                              - TMPL_ARGS_DEPTH (args)),
13528                    new_vec, NULL_TREE);
13529       TEMPLATE_PARMS_CONSTRAINTS (*new_parms)
13530         = TEMPLATE_PARMS_CONSTRAINTS (parms);
13531     }
13532
13533   --processing_template_decl;
13534
13535   return r;
13536 }
13537
13538 /* Return the result of substituting ARGS into one template parameter
13539    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
13540    parameter and which TREE_PURPOSE is the default argument of the
13541    template parameter.  */
13542
13543 static tree
13544 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
13545 {
13546   tree default_value, parm_decl;
13547
13548   if (args == NULL_TREE
13549       || t == NULL_TREE
13550       || t == error_mark_node)
13551     return t;
13552
13553   gcc_assert (TREE_CODE (t) == TREE_LIST);
13554
13555   default_value = TREE_PURPOSE (t);
13556   parm_decl = TREE_VALUE (t);
13557   tree constraint = TEMPLATE_PARM_CONSTRAINTS (t);
13558
13559   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
13560   if (TREE_CODE (parm_decl) == PARM_DECL
13561       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
13562     parm_decl = error_mark_node;
13563   default_value = tsubst_template_arg (default_value, args,
13564                                        complain, NULL_TREE);
13565   constraint = tsubst_constraint (constraint, args, complain, NULL_TREE);
13566
13567   tree r = build_tree_list (default_value, parm_decl);
13568   TEMPLATE_PARM_CONSTRAINTS (r) = constraint;
13569   return r;
13570 }
13571
13572 /* Substitute the ARGS into the indicated aggregate (or enumeration)
13573    type T.  If T is not an aggregate or enumeration type, it is
13574    handled as if by tsubst.  IN_DECL is as for tsubst.  If
13575    ENTERING_SCOPE is nonzero, T is the context for a template which
13576    we are presently tsubst'ing.  Return the substituted value.  */
13577
13578 static tree
13579 tsubst_aggr_type (tree t,
13580                   tree args,
13581                   tsubst_flags_t complain,
13582                   tree in_decl,
13583                   int entering_scope)
13584 {
13585   if (t == NULL_TREE)
13586     return NULL_TREE;
13587
13588   switch (TREE_CODE (t))
13589     {
13590     case RECORD_TYPE:
13591       if (TYPE_PTRMEMFUNC_P (t))
13592         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
13593
13594       /* Fall through.  */
13595     case ENUMERAL_TYPE:
13596     case UNION_TYPE:
13597       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
13598         {
13599           tree argvec;
13600           tree context;
13601           tree r;
13602
13603           /* In "sizeof(X<I>)" we need to evaluate "I".  */
13604           cp_evaluated ev;
13605
13606           /* First, determine the context for the type we are looking
13607              up.  */
13608           context = TYPE_CONTEXT (t);
13609           if (context && TYPE_P (context))
13610             {
13611               context = tsubst_aggr_type (context, args, complain,
13612                                           in_decl, /*entering_scope=*/1);
13613               /* If context is a nested class inside a class template,
13614                  it may still need to be instantiated (c++/33959).  */
13615               context = complete_type (context);
13616             }
13617
13618           /* Then, figure out what arguments are appropriate for the
13619              type we are trying to find.  For example, given:
13620
13621                template <class T> struct S;
13622                template <class T, class U> void f(T, U) { S<U> su; }
13623
13624              and supposing that we are instantiating f<int, double>,
13625              then our ARGS will be {int, double}, but, when looking up
13626              S we only want {double}.  */
13627           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
13628                                          complain, in_decl);
13629           if (argvec == error_mark_node)
13630             r = error_mark_node;
13631           else if (!entering_scope
13632                    && cxx_dialect >= cxx17 && dependent_scope_p (context))
13633             {
13634               /* See maybe_dependent_member_ref.  */
13635               tree name = TYPE_IDENTIFIER (t);
13636               tree fullname = name;
13637               if (instantiates_primary_template_p (t))
13638                 fullname = build_nt (TEMPLATE_ID_EXPR, name,
13639                                      INNERMOST_TEMPLATE_ARGS (argvec));
13640               return build_typename_type (context, name, fullname,
13641                                           typename_type);
13642             }
13643           else
13644             {
13645               r = lookup_template_class (t, argvec, in_decl, context,
13646                                          entering_scope, complain);
13647               r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
13648             }
13649
13650           return r;
13651         }
13652       else
13653         /* This is not a template type, so there's nothing to do.  */
13654         return t;
13655
13656     default:
13657       return tsubst (t, args, complain, in_decl);
13658     }
13659 }
13660
13661 static GTY((cache)) decl_tree_cache_map *defarg_inst;
13662
13663 /* Substitute into the default argument ARG (a default argument for
13664    FN), which has the indicated TYPE.  */
13665
13666 tree
13667 tsubst_default_argument (tree fn, int parmnum, tree type, tree arg,
13668                          tsubst_flags_t complain)
13669 {
13670   int errs = errorcount + sorrycount;
13671
13672   /* This can happen in invalid code.  */
13673   if (TREE_CODE (arg) == DEFERRED_PARSE)
13674     return arg;
13675
13676   /* Shortcut {}.  */
13677   if (BRACE_ENCLOSED_INITIALIZER_P (arg)
13678       && CONSTRUCTOR_NELTS (arg) == 0)
13679     return arg;
13680
13681   tree parm = FUNCTION_FIRST_USER_PARM (fn);
13682   parm = chain_index (parmnum, parm);
13683   tree parmtype = TREE_TYPE (parm);
13684   if (DECL_BY_REFERENCE (parm))
13685     parmtype = TREE_TYPE (parmtype);
13686   if (parmtype == error_mark_node)
13687     return error_mark_node;
13688
13689   gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, parmtype));
13690
13691   tree *slot;
13692   if (defarg_inst && (slot = defarg_inst->get (parm)))
13693     return *slot;
13694
13695   /* This default argument came from a template.  Instantiate the
13696      default argument here, not in tsubst.  In the case of
13697      something like:
13698
13699        template <class T>
13700        struct S {
13701          static T t();
13702          void f(T = t());
13703        };
13704
13705      we must be careful to do name lookup in the scope of S<T>,
13706      rather than in the current class.  */
13707   push_to_top_level ();
13708   push_access_scope (fn);
13709   push_deferring_access_checks (dk_no_deferred);
13710   start_lambda_scope (parm);
13711
13712   /* The default argument expression may cause implicitly defined
13713      member functions to be synthesized, which will result in garbage
13714      collection.  We must treat this situation as if we were within
13715      the body of function so as to avoid collecting live data on the
13716      stack.  */
13717   ++function_depth;
13718   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
13719                      complain, NULL_TREE,
13720                      /*integral_constant_expression_p=*/false);
13721   --function_depth;
13722
13723   finish_lambda_scope ();
13724
13725   /* Make sure the default argument is reasonable.  */
13726   arg = check_default_argument (type, arg, complain);
13727
13728   if (errorcount+sorrycount > errs
13729       && (complain & tf_warning_or_error))
13730     inform (input_location,
13731             "  when instantiating default argument for call to %qD", fn);
13732
13733   pop_deferring_access_checks ();
13734   pop_access_scope (fn);
13735   pop_from_top_level ();
13736
13737   if (arg != error_mark_node && !cp_unevaluated_operand)
13738     {
13739       if (!defarg_inst)
13740         defarg_inst = decl_tree_cache_map::create_ggc (37);
13741       defarg_inst->put (parm, arg);
13742     }
13743
13744   return arg;
13745 }
13746
13747 /* Substitute into all the default arguments for FN.  */
13748
13749 static void
13750 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
13751 {
13752   tree arg;
13753   tree tmpl_args;
13754
13755   tmpl_args = DECL_TI_ARGS (fn);
13756
13757   /* If this function is not yet instantiated, we certainly don't need
13758      its default arguments.  */
13759   if (uses_template_parms (tmpl_args))
13760     return;
13761   /* Don't do this again for clones.  */
13762   if (DECL_CLONED_FUNCTION_P (fn))
13763     return;
13764
13765   int i = 0;
13766   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
13767        arg;
13768        arg = TREE_CHAIN (arg), ++i)
13769     if (TREE_PURPOSE (arg))
13770       TREE_PURPOSE (arg) = tsubst_default_argument (fn, i,
13771                                                     TREE_VALUE (arg),
13772                                                     TREE_PURPOSE (arg),
13773                                                     complain);
13774 }
13775
13776 /* Hash table mapping a FUNCTION_DECL to its dependent explicit-specifier.  */
13777 static GTY((cache)) decl_tree_cache_map *explicit_specifier_map;
13778
13779 /* Store a pair to EXPLICIT_SPECIFIER_MAP.  */
13780
13781 void
13782 store_explicit_specifier (tree v, tree t)
13783 {
13784   if (!explicit_specifier_map)
13785     explicit_specifier_map = decl_tree_cache_map::create_ggc (37);
13786   DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (v) = true;
13787   explicit_specifier_map->put (v, t);
13788 }
13789
13790 /* Lookup an element in EXPLICIT_SPECIFIER_MAP.  */
13791
13792 static tree
13793 lookup_explicit_specifier (tree v)
13794 {
13795   return *explicit_specifier_map->get (v);
13796 }
13797
13798 /* Given T, a FUNCTION_TYPE or METHOD_TYPE, construct and return a corresponding
13799    FUNCTION_TYPE or METHOD_TYPE whose return type is RETURN_TYPE, argument types
13800    are ARG_TYPES, and exception specification is RAISES, and otherwise is
13801    identical to T.  */
13802
13803 static tree
13804 rebuild_function_or_method_type (tree t, tree return_type, tree arg_types,
13805                                  tree raises, tsubst_flags_t complain)
13806 {
13807   gcc_assert (FUNC_OR_METHOD_TYPE_P (t));
13808
13809   tree new_type;
13810   if (TREE_CODE (t) == FUNCTION_TYPE)
13811     {
13812       new_type = build_function_type (return_type, arg_types);
13813       new_type = apply_memfn_quals (new_type, type_memfn_quals (t));
13814     }
13815   else
13816     {
13817       tree r = TREE_TYPE (TREE_VALUE (arg_types));
13818       /* Don't pick up extra function qualifiers from the basetype.  */
13819       r = cp_build_qualified_type_real (r, type_memfn_quals (t), complain);
13820       if (! MAYBE_CLASS_TYPE_P (r))
13821         {
13822           /* [temp.deduct]
13823
13824              Type deduction may fail for any of the following
13825              reasons:
13826
13827              -- Attempting to create "pointer to member of T" when T
13828              is not a class type.  */
13829           if (complain & tf_error)
13830             error ("creating pointer to member function of non-class type %qT",
13831                    r);
13832           return error_mark_node;
13833         }
13834
13835       new_type = build_method_type_directly (r, return_type,
13836                                              TREE_CHAIN (arg_types));
13837     }
13838   new_type = cp_build_type_attribute_variant (new_type, TYPE_ATTRIBUTES (t));
13839
13840   cp_ref_qualifier rqual = type_memfn_rqual (t);
13841   bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
13842   return build_cp_fntype_variant (new_type, rqual, raises, late_return_type_p);
13843 }
13844
13845 /* Check if the function type of DECL, a FUNCTION_DECL, agrees with the type of
13846    each of its formal parameters.  If there is a disagreement then rebuild
13847    DECL's function type according to its formal parameter types, as part of a
13848    resolution for Core issues 1001/1322.  */
13849
13850 static void
13851 maybe_rebuild_function_decl_type (tree decl)
13852 {
13853   bool function_type_needs_rebuilding = false;
13854   if (tree parm_list = FUNCTION_FIRST_USER_PARM (decl))
13855     {
13856       tree parm_type_list = FUNCTION_FIRST_USER_PARMTYPE (decl);
13857       while (parm_type_list && parm_type_list != void_list_node)
13858         {
13859           tree parm_type = TREE_VALUE (parm_type_list);
13860           tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
13861           if (!same_type_p (parm_type, formal_parm_type_unqual))
13862             {
13863               function_type_needs_rebuilding = true;
13864               break;
13865             }
13866
13867           parm_list = DECL_CHAIN (parm_list);
13868           parm_type_list = TREE_CHAIN (parm_type_list);
13869         }
13870     }
13871
13872   if (!function_type_needs_rebuilding)
13873     return;
13874
13875   const tree fntype = TREE_TYPE (decl);
13876   tree parm_list = DECL_ARGUMENTS (decl);
13877   tree old_parm_type_list = TYPE_ARG_TYPES (fntype);
13878   tree new_parm_type_list = NULL_TREE;
13879   tree *q = &new_parm_type_list;
13880   for (int skip = num_artificial_parms_for (decl); skip > 0; skip--)
13881     {
13882       *q = copy_node (old_parm_type_list);
13883       parm_list = DECL_CHAIN (parm_list);
13884       old_parm_type_list = TREE_CHAIN (old_parm_type_list);
13885       q = &TREE_CHAIN (*q);
13886     }
13887   while (old_parm_type_list && old_parm_type_list != void_list_node)
13888     {
13889       *q = copy_node (old_parm_type_list);
13890       tree *new_parm_type = &TREE_VALUE (*q);
13891       tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
13892       if (!same_type_p (*new_parm_type, formal_parm_type_unqual))
13893         *new_parm_type = formal_parm_type_unqual;
13894
13895       parm_list = DECL_CHAIN (parm_list);
13896       old_parm_type_list = TREE_CHAIN (old_parm_type_list);
13897       q = &TREE_CHAIN (*q);
13898     }
13899   if (old_parm_type_list == void_list_node)
13900     *q = void_list_node;
13901
13902   TREE_TYPE (decl)
13903     = rebuild_function_or_method_type (fntype,
13904                                        TREE_TYPE (fntype), new_parm_type_list,
13905                                        TYPE_RAISES_EXCEPTIONS (fntype), tf_none);
13906 }
13907
13908 /* Subroutine of tsubst_decl for the case when T is a FUNCTION_DECL.  */
13909
13910 static tree
13911 tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
13912                       tree lambda_fntype)
13913 {
13914   tree gen_tmpl = NULL_TREE, argvec = NULL_TREE;
13915   hashval_t hash = 0;
13916   tree in_decl = t;
13917
13918   /* Nobody should be tsubst'ing into non-template functions.  */
13919   gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE
13920               || DECL_LOCAL_DECL_P (t));
13921
13922   if (DECL_LOCAL_DECL_P (t))
13923     {
13924       if (tree spec = retrieve_local_specialization (t))
13925         return spec;
13926     }
13927   else if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
13928     {
13929       /* If T is not dependent, just return it.  */
13930       if (!uses_template_parms (DECL_TI_ARGS (t))
13931           && !LAMBDA_FUNCTION_P (t))
13932         return t;
13933
13934       /* Calculate the most general template of which R is a
13935          specialization.  */
13936       gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
13937
13938       /* We're substituting a lambda function under tsubst_lambda_expr but not
13939          directly from it; find the matching function we're already inside.
13940          But don't do this if T is a generic lambda with a single level of
13941          template parms, as in that case we're doing a normal instantiation. */
13942       if (LAMBDA_FUNCTION_P (t) && !lambda_fntype
13943           && (!generic_lambda_fn_p (t)
13944               || TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)) > 1))
13945         return enclosing_instantiation_of (t);
13946
13947       /* Calculate the complete set of arguments used to
13948          specialize R.  */
13949       argvec = tsubst_template_args (DECL_TI_ARGS
13950                                      (DECL_TEMPLATE_RESULT
13951                                       (DECL_TI_TEMPLATE (t))),
13952                                      args, complain, in_decl);
13953       if (argvec == error_mark_node)
13954         return error_mark_node;
13955
13956       /* Check to see if we already have this specialization.  */
13957       if (!lambda_fntype)
13958         {
13959           hash = hash_tmpl_and_args (gen_tmpl, argvec);
13960           if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
13961             return spec;
13962         }
13963
13964       /* We can see more levels of arguments than parameters if
13965          there was a specialization of a member template, like
13966          this:
13967
13968          template <class T> struct S { template <class U> void f(); }
13969          template <> template <class U> void S<int>::f(U);
13970
13971          Here, we'll be substituting into the specialization,
13972          because that's where we can find the code we actually
13973          want to generate, but we'll have enough arguments for
13974          the most general template.
13975
13976          We also deal with the peculiar case:
13977
13978          template <class T> struct S {
13979            template <class U> friend void f();
13980          };
13981          template <class U> void f() {}
13982          template S<int>;
13983          template void f<double>();
13984
13985          Here, the ARGS for the instantiation of will be {int,
13986          double}.  But, we only need as many ARGS as there are
13987          levels of template parameters in CODE_PATTERN.  We are
13988          careful not to get fooled into reducing the ARGS in
13989          situations like:
13990
13991          template <class T> struct S { template <class U> void f(U); }
13992          template <class T> template <> void S<T>::f(int) {}
13993
13994          which we can spot because the pattern will be a
13995          specialization in this case.  */
13996       int args_depth = TMPL_ARGS_DEPTH (args);
13997       int parms_depth =
13998         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
13999
14000       if (args_depth > parms_depth && !DECL_TEMPLATE_SPECIALIZATION (t))
14001         args = get_innermost_template_args (args, parms_depth);
14002     }
14003   else
14004     {
14005       /* This special case arises when we have something like this:
14006
14007          template <class T> struct S {
14008          friend void f<int>(int, double);
14009          };
14010
14011          Here, the DECL_TI_TEMPLATE for the friend declaration
14012          will be an IDENTIFIER_NODE.  We are being called from
14013          tsubst_friend_function, and we want only to create a
14014          new decl (R) with appropriate types so that we can call
14015          determine_specialization.  */
14016       gen_tmpl = NULL_TREE;
14017       argvec = NULL_TREE;
14018     }
14019
14020   tree closure = (lambda_fntype ? TYPE_METHOD_BASETYPE (lambda_fntype)
14021                   : NULL_TREE);
14022   tree ctx = closure ? closure : DECL_CONTEXT (t);
14023   bool member = ctx && TYPE_P (ctx);
14024
14025   if (member && !closure)
14026     ctx = tsubst_aggr_type (ctx, args,
14027                             complain, t, /*entering_scope=*/1);
14028
14029   tree type = (lambda_fntype ? lambda_fntype
14030                : tsubst (TREE_TYPE (t), args,
14031                          complain | tf_fndecl_type, in_decl));
14032   if (type == error_mark_node)
14033     return error_mark_node;
14034
14035   /* If we hit excessive deduction depth, the type is bogus even if
14036      it isn't error_mark_node, so don't build a decl.  */
14037   if (excessive_deduction_depth)
14038     return error_mark_node;
14039
14040   /* We do NOT check for matching decls pushed separately at this
14041      point, as they may not represent instantiations of this
14042      template, and in any case are considered separate under the
14043      discrete model.  */
14044   tree r = copy_decl (t);
14045   DECL_USE_TEMPLATE (r) = 0;
14046   TREE_TYPE (r) = type;
14047   /* Clear out the mangled name and RTL for the instantiation.  */
14048   SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
14049   SET_DECL_RTL (r, NULL);
14050   /* Leave DECL_INITIAL set on deleted instantiations.  */
14051   if (!DECL_DELETED_FN (r))
14052     DECL_INITIAL (r) = NULL_TREE;
14053   DECL_CONTEXT (r) = ctx;
14054   set_instantiating_module (r);
14055
14056   /* Handle explicit(dependent-expr).  */
14057   if (DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (t))
14058     {
14059       tree spec = lookup_explicit_specifier (t);
14060       spec = tsubst_copy_and_build (spec, args, complain, in_decl,
14061                                     /*function_p=*/false,
14062                                     /*i_c_e_p=*/true);
14063       spec = build_explicit_specifier (spec, complain);
14064       DECL_NONCONVERTING_P (r) = (spec == boolean_true_node);
14065     }
14066
14067   /* OpenMP UDRs have the only argument a reference to the declared
14068      type.  We want to diagnose if the declared type is a reference,
14069      which is invalid, but as references to references are usually
14070      quietly merged, diagnose it here.  */
14071   if (DECL_OMP_DECLARE_REDUCTION_P (t))
14072     {
14073       tree argtype
14074         = TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
14075       argtype = tsubst (argtype, args, complain, in_decl);
14076       if (TYPE_REF_P (argtype))
14077         error_at (DECL_SOURCE_LOCATION (t),
14078                   "reference type %qT in "
14079                   "%<#pragma omp declare reduction%>", argtype);
14080       if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
14081         DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
14082                                           argtype);
14083     }
14084
14085   if (member && DECL_CONV_FN_P (r))
14086     /* Type-conversion operator.  Reconstruct the name, in
14087        case it's the name of one of the template's parameters.  */
14088     DECL_NAME (r) = make_conv_op_name (TREE_TYPE (type));
14089
14090   tree parms = DECL_ARGUMENTS (t);
14091   if (closure)
14092     parms = DECL_CHAIN (parms);
14093   parms = tsubst (parms, args, complain, t);
14094   for (tree parm = parms; parm; parm = DECL_CHAIN (parm))
14095     DECL_CONTEXT (parm) = r;
14096   if (closure)
14097     {
14098       tree tparm = build_this_parm (r, closure, type_memfn_quals (type));
14099       DECL_NAME (tparm) = closure_identifier;
14100       DECL_CHAIN (tparm) = parms;
14101       parms = tparm;
14102     }
14103   DECL_ARGUMENTS (r) = parms;
14104   DECL_RESULT (r) = NULL_TREE;
14105
14106   maybe_rebuild_function_decl_type (r);
14107
14108   TREE_STATIC (r) = 0;
14109   TREE_PUBLIC (r) = TREE_PUBLIC (t);
14110   DECL_EXTERNAL (r) = 1;
14111   /* If this is an instantiation of a function with internal
14112      linkage, we already know what object file linkage will be
14113      assigned to the instantiation.  */
14114   DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
14115   DECL_DEFER_OUTPUT (r) = 0;
14116   DECL_CHAIN (r) = NULL_TREE;
14117   DECL_PENDING_INLINE_INFO (r) = 0;
14118   DECL_PENDING_INLINE_P (r) = 0;
14119   DECL_SAVED_TREE (r) = NULL_TREE;
14120   DECL_STRUCT_FUNCTION (r) = NULL;
14121   TREE_USED (r) = 0;
14122   /* We'll re-clone as appropriate in instantiate_template.  */
14123   DECL_CLONED_FUNCTION (r) = NULL_TREE;
14124
14125   /* If we aren't complaining now, return on error before we register
14126      the specialization so that we'll complain eventually.  */
14127   if ((complain & tf_error) == 0
14128       && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14129       && !grok_op_properties (r, /*complain=*/false))
14130     return error_mark_node;
14131
14132   /* Associate the constraints directly with the instantiation. We
14133      don't substitute through the constraints; that's only done when
14134      they are checked.  */
14135   if (tree ci = get_constraints (t))
14136     set_constraints (r, ci);
14137
14138   if (DECL_FRIEND_CONTEXT (t))
14139     SET_DECL_FRIEND_CONTEXT (r,
14140                              tsubst (DECL_FRIEND_CONTEXT (t),
14141                                      args, complain, in_decl));
14142
14143   if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14144                                        args, complain, in_decl))
14145     return error_mark_node;
14146
14147   /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
14148      this in the special friend case mentioned above where
14149      GEN_TMPL is NULL.  */
14150   if (gen_tmpl && !closure)
14151     {
14152       DECL_TEMPLATE_INFO (r)
14153         = build_template_info (gen_tmpl, argvec);
14154       SET_DECL_IMPLICIT_INSTANTIATION (r);
14155
14156       tree new_r
14157         = register_specialization (r, gen_tmpl, argvec, false, hash);
14158       if (new_r != r)
14159         /* We instantiated this while substituting into
14160            the type earlier (template/friend54.C).  */
14161         return new_r;
14162
14163       /* We're not supposed to instantiate default arguments
14164          until they are called, for a template.  But, for a
14165          declaration like:
14166
14167          template <class T> void f ()
14168          { extern void g(int i = T()); }
14169
14170          we should do the substitution when the template is
14171          instantiated.  We handle the member function case in
14172          instantiate_class_template since the default arguments
14173          might refer to other members of the class.  */
14174       if (!member
14175           && !PRIMARY_TEMPLATE_P (gen_tmpl)
14176           && !uses_template_parms (argvec))
14177         tsubst_default_arguments (r, complain);
14178     }
14179   else if (DECL_LOCAL_DECL_P (r))
14180     {
14181       if (!cp_unevaluated_operand)
14182         register_local_specialization (r, t);
14183     }
14184   else
14185     DECL_TEMPLATE_INFO (r) = NULL_TREE;
14186
14187   /* Copy the list of befriending classes.  */
14188   for (tree *friends = &DECL_BEFRIENDING_CLASSES (r);
14189        *friends;
14190        friends = &TREE_CHAIN (*friends))
14191     {
14192       *friends = copy_node (*friends);
14193       TREE_VALUE (*friends)
14194         = tsubst (TREE_VALUE (*friends), args, complain, in_decl);
14195     }
14196
14197   if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
14198     {
14199       maybe_retrofit_in_chrg (r);
14200       if (DECL_CONSTRUCTOR_P (r) && !grok_ctor_properties (ctx, r))
14201         return error_mark_node;
14202       /* If this is an instantiation of a member template, clone it.
14203          If it isn't, that'll be handled by
14204          clone_constructors_and_destructors.  */
14205       if (PRIMARY_TEMPLATE_P (gen_tmpl))
14206         clone_cdtor (r, /*update_methods=*/false);
14207     }
14208   else if ((complain & tf_error) != 0
14209            && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14210            && !grok_op_properties (r, /*complain=*/true))
14211     return error_mark_node;
14212
14213   /* Possibly limit visibility based on template args.  */
14214   DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
14215   if (DECL_VISIBILITY_SPECIFIED (t))
14216     {
14217       DECL_VISIBILITY_SPECIFIED (r) = 0;
14218       DECL_ATTRIBUTES (r)
14219         = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
14220     }
14221   determine_visibility (r);
14222   if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
14223       && !processing_template_decl)
14224     defaulted_late_check (r);
14225
14226   if (flag_openmp)
14227     if (tree attr = lookup_attribute ("omp declare variant base",
14228                                       DECL_ATTRIBUTES (r)))
14229       omp_declare_variant_finalize (r, attr);
14230
14231   return r;
14232 }
14233
14234 /* Subroutine of tsubst_decl for the case when T is a TEMPLATE_DECL.  */
14235
14236 static tree
14237 tsubst_template_decl (tree t, tree args, tsubst_flags_t complain,
14238                       tree lambda_fntype)
14239 {
14240   /* We can get here when processing a member function template,
14241      member class template, or template template parameter.  */
14242   tree decl = DECL_TEMPLATE_RESULT (t);
14243   tree in_decl = t;
14244   tree spec;
14245   tree tmpl_args;
14246   tree full_args;
14247   tree r;
14248   hashval_t hash = 0;
14249
14250   if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
14251     {
14252       /* Template template parameter is treated here.  */
14253       tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14254       if (new_type == error_mark_node)
14255         r = error_mark_node;
14256       /* If we get a real template back, return it.  This can happen in
14257          the context of most_specialized_partial_spec.  */
14258       else if (TREE_CODE (new_type) == TEMPLATE_DECL)
14259         r = new_type;
14260       else
14261         /* The new TEMPLATE_DECL was built in
14262            reduce_template_parm_level.  */
14263         r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
14264       return r;
14265     }
14266
14267   if (!lambda_fntype)
14268     {
14269       /* We might already have an instance of this template.
14270          The ARGS are for the surrounding class type, so the
14271          full args contain the tsubst'd args for the context,
14272          plus the innermost args from the template decl.  */
14273       tmpl_args = DECL_CLASS_TEMPLATE_P (t)
14274         ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
14275         : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
14276       /* Because this is a template, the arguments will still be
14277          dependent, even after substitution.  If
14278          PROCESSING_TEMPLATE_DECL is not set, the dependency
14279          predicates will short-circuit.  */
14280       ++processing_template_decl;
14281       full_args = tsubst_template_args (tmpl_args, args,
14282                                         complain, in_decl);
14283       --processing_template_decl;
14284       if (full_args == error_mark_node)
14285         return error_mark_node;
14286
14287       /* If this is a default template template argument,
14288          tsubst might not have changed anything.  */
14289       if (full_args == tmpl_args)
14290         return t;
14291
14292       hash = hash_tmpl_and_args (t, full_args);
14293       spec = retrieve_specialization (t, full_args, hash);
14294       if (spec != NULL_TREE)
14295         {
14296           if (TYPE_P (spec))
14297             /* Type partial instantiations are stored as the type by
14298                lookup_template_class_1, not here as the template.  */
14299             spec = CLASSTYPE_TI_TEMPLATE (spec);
14300           return spec;
14301         }
14302     }
14303
14304   /* Make a new template decl.  It will be similar to the
14305      original, but will record the current template arguments.
14306      We also create a new function declaration, which is just
14307      like the old one, but points to this new template, rather
14308      than the old one.  */
14309   r = copy_decl (t);
14310   gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
14311   DECL_CHAIN (r) = NULL_TREE;
14312
14313   // Build new template info linking to the original template decl.
14314   if (!lambda_fntype)
14315     {
14316       DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
14317       SET_DECL_IMPLICIT_INSTANTIATION (r);
14318     }
14319   else
14320     DECL_TEMPLATE_INFO (r) = NULL_TREE;
14321
14322   /* The template parameters for this new template are all the
14323      template parameters for the old template, except the
14324      outermost level of parameters.  */
14325   auto tparm_guard = make_temp_override (current_template_parms);
14326   DECL_TEMPLATE_PARMS (r)
14327     = current_template_parms
14328     = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
14329                              complain);
14330
14331   bool class_p = false;
14332   tree inner = decl;
14333   ++processing_template_decl;
14334   if (TREE_CODE (inner) == FUNCTION_DECL)
14335     inner = tsubst_function_decl (inner, args, complain, lambda_fntype);
14336   else
14337     {
14338       if (TREE_CODE (inner) == TYPE_DECL && !TYPE_DECL_ALIAS_P (inner))
14339         {
14340           class_p = true;
14341           inner = TREE_TYPE (inner);
14342         }
14343       if (class_p)
14344         inner = tsubst_aggr_type (inner, args, complain,
14345                                   in_decl, /*entering*/1);
14346       else
14347         inner = tsubst (inner, args, complain, in_decl);
14348     }
14349   --processing_template_decl;
14350   if (inner == error_mark_node)
14351     return error_mark_node;
14352
14353   if (class_p)
14354     {
14355       /* For a partial specialization, we need to keep pointing to
14356          the primary template.  */
14357       if (!DECL_TEMPLATE_SPECIALIZATION (t))
14358         CLASSTYPE_TI_TEMPLATE (inner) = r;
14359
14360       DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (inner);
14361       inner = TYPE_MAIN_DECL (inner);
14362     }
14363   else if (lambda_fntype)
14364     {
14365       tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (r));
14366       DECL_TEMPLATE_INFO (inner) = build_template_info (r, args);
14367     }
14368   else
14369     {
14370       DECL_TI_TEMPLATE (inner) = r;
14371       DECL_TI_ARGS (r) = DECL_TI_ARGS (inner);
14372     }
14373
14374   DECL_TEMPLATE_RESULT (r) = inner;
14375   TREE_TYPE (r) = TREE_TYPE (inner);
14376   DECL_CONTEXT (r) = DECL_CONTEXT (inner);
14377
14378   if (modules_p ())
14379     {
14380       /* Propagate module information from the decl.  */
14381       DECL_MODULE_EXPORT_P (r) = DECL_MODULE_EXPORT_P (inner);
14382       if (DECL_LANG_SPECIFIC (inner))
14383         /* If this is a constrained template, the above tsubst of
14384            inner can find the unconstrained template, which may have
14385            come from an import.  This is ok, because we don't
14386            register this instantiation (see below).  */
14387         gcc_checking_assert (!DECL_MODULE_IMPORT_P (inner)
14388                              || (TEMPLATE_PARMS_CONSTRAINTS
14389                                  (DECL_TEMPLATE_PARMS (t))));
14390     }
14391
14392   DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
14393   DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
14394
14395   if (PRIMARY_TEMPLATE_P (t))
14396     DECL_PRIMARY_TEMPLATE (r) = r;
14397
14398   if (TREE_CODE (decl) == FUNCTION_DECL && !lambda_fntype)
14399     /* Record this non-type partial instantiation.  */
14400     register_specialization (r, t,
14401                              DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
14402                              false, hash);
14403
14404   return r;
14405 }
14406
14407 /* True if FN is the op() for a lambda in an uninstantiated template.  */
14408
14409 bool
14410 lambda_fn_in_template_p (tree fn)
14411 {
14412   if (!fn || !LAMBDA_FUNCTION_P (fn))
14413     return false;
14414   tree closure = DECL_CONTEXT (fn);
14415   return CLASSTYPE_TEMPLATE_INFO (closure) != NULL_TREE;
14416 }
14417
14418 /* True if FN is the substitution (via tsubst_lambda_expr) of a function for
14419    which the above is true.  */
14420
14421 bool
14422 regenerated_lambda_fn_p (tree fn)
14423 {
14424   if (!fn || !LAMBDA_FUNCTION_P (fn))
14425     return false;
14426   tree closure = DECL_CONTEXT (fn);
14427   tree lam = CLASSTYPE_LAMBDA_EXPR (closure);
14428   return LAMBDA_EXPR_REGEN_INFO (lam) != NULL_TREE;
14429 }
14430
14431 /* Return the LAMBDA_EXPR from which T was ultimately regenerated.
14432    If T is not a regenerated LAMBDA_EXPR, return T.  */
14433
14434 tree
14435 most_general_lambda (tree t)
14436 {
14437   while (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
14438     t = TI_TEMPLATE (ti);
14439   return t;
14440 }
14441
14442 /* We're instantiating a variable from template function TCTX.  Return the
14443    corresponding current enclosing scope.  This gets complicated because lambda
14444    functions in templates are regenerated rather than instantiated, but generic
14445    lambda functions are subsequently instantiated.  */
14446
14447 static tree
14448 enclosing_instantiation_of (tree otctx)
14449 {
14450   tree tctx = otctx;
14451   tree fn = current_function_decl;
14452   int lambda_count = 0;
14453
14454   for (; tctx && (lambda_fn_in_template_p (tctx)
14455                   || regenerated_lambda_fn_p (tctx));
14456        tctx = decl_function_context (tctx))
14457     ++lambda_count;
14458
14459   if (!tctx)
14460     {
14461       /* Match using DECL_SOURCE_LOCATION, which is unique for all lambdas.
14462
14463          For GCC 11 the above condition limits this to the previously failing
14464          case where all enclosing functions are lambdas (95870).  FIXME.  */
14465       for (tree ofn = fn; ofn; ofn = decl_function_context (ofn))
14466         if (DECL_SOURCE_LOCATION (ofn) == DECL_SOURCE_LOCATION (otctx))
14467           return ofn;
14468       gcc_unreachable ();
14469     }
14470
14471   for (; fn; fn = decl_function_context (fn))
14472     {
14473       tree ofn = fn;
14474       int flambda_count = 0;
14475       for (; fn && regenerated_lambda_fn_p (fn);
14476            fn = decl_function_context (fn))
14477         ++flambda_count;
14478       if ((fn && DECL_TEMPLATE_INFO (fn))
14479           ? most_general_template (fn) != most_general_template (tctx)
14480           : fn != tctx)
14481         continue;
14482       if (flambda_count != lambda_count)
14483         {
14484           gcc_assert (flambda_count > lambda_count);
14485           for (; flambda_count > lambda_count; --flambda_count)
14486             ofn = decl_function_context (ofn);
14487         }
14488       gcc_assert (DECL_NAME (ofn) == DECL_NAME (otctx)
14489                   || DECL_CONV_FN_P (ofn));
14490       return ofn;
14491     }
14492   gcc_unreachable ();
14493 }
14494
14495 /* Substitute the ARGS into the T, which is a _DECL.  Return the
14496    result of the substitution.  Issue error and warning messages under
14497    control of COMPLAIN.  */
14498
14499 static tree
14500 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
14501 {
14502 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
14503   location_t saved_loc;
14504   tree r = NULL_TREE;
14505   tree in_decl = t;
14506   hashval_t hash = 0;
14507
14508   /* Set the filename and linenumber to improve error-reporting.  */
14509   saved_loc = input_location;
14510   input_location = DECL_SOURCE_LOCATION (t);
14511
14512   switch (TREE_CODE (t))
14513     {
14514     case TEMPLATE_DECL:
14515       r = tsubst_template_decl (t, args, complain, /*lambda*/NULL_TREE);
14516       break;
14517
14518     case FUNCTION_DECL:
14519       r = tsubst_function_decl (t, args, complain, /*lambda*/NULL_TREE);
14520       break;
14521
14522     case PARM_DECL:
14523       {
14524         tree type = NULL_TREE;
14525         int i, len = 1;
14526         tree expanded_types = NULL_TREE;
14527         tree prev_r = NULL_TREE;
14528         tree first_r = NULL_TREE;
14529
14530         if (DECL_PACK_P (t))
14531           {
14532             /* If there is a local specialization that isn't a
14533                parameter pack, it means that we're doing a "simple"
14534                substitution from inside tsubst_pack_expansion. Just
14535                return the local specialization (which will be a single
14536                parm).  */
14537             tree spec = retrieve_local_specialization (t);
14538             if (spec 
14539                 && TREE_CODE (spec) == PARM_DECL
14540                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
14541               RETURN (spec);
14542
14543             /* Expand the TYPE_PACK_EXPANSION that provides the types for
14544                the parameters in this function parameter pack.  */
14545             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
14546                                                     complain, in_decl);
14547             if (TREE_CODE (expanded_types) == TREE_VEC)
14548               {
14549                 len = TREE_VEC_LENGTH (expanded_types);
14550
14551                 /* Zero-length parameter packs are boring. Just substitute
14552                    into the chain.  */
14553                 if (len == 0 && !cp_unevaluated_operand)
14554                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
14555                                   TREE_CHAIN (t)));
14556               }
14557             else
14558               {
14559                 /* All we did was update the type. Make a note of that.  */
14560                 type = expanded_types;
14561                 expanded_types = NULL_TREE;
14562               }
14563           }
14564
14565         /* Loop through all of the parameters we'll build. When T is
14566            a function parameter pack, LEN is the number of expanded
14567            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
14568         r = NULL_TREE;
14569         for (i = 0; i < len; ++i)
14570           {
14571             prev_r = r;
14572             r = copy_node (t);
14573             if (DECL_TEMPLATE_PARM_P (t))
14574               SET_DECL_TEMPLATE_PARM_P (r);
14575
14576             if (expanded_types)
14577               /* We're on the Ith parameter of the function parameter
14578                  pack.  */
14579               {
14580                 /* Get the Ith type.  */
14581                 type = TREE_VEC_ELT (expanded_types, i);
14582
14583                 /* Rename the parameter to include the index.  */
14584                 DECL_NAME (r)
14585                   = make_ith_pack_parameter_name (DECL_NAME (r), i);
14586               }
14587             else if (!type)
14588               /* We're dealing with a normal parameter.  */
14589               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14590
14591             type = type_decays_to (type);
14592             TREE_TYPE (r) = type;
14593             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14594
14595             if (DECL_INITIAL (r))
14596               {
14597                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
14598                   DECL_INITIAL (r) = TREE_TYPE (r);
14599                 else
14600                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
14601                                              complain, in_decl);
14602               }
14603
14604             DECL_CONTEXT (r) = NULL_TREE;
14605
14606             if (!DECL_TEMPLATE_PARM_P (r))
14607               DECL_ARG_TYPE (r) = type_passed_as (type);
14608
14609             if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14610                                                  args, complain, in_decl))
14611               return error_mark_node;
14612
14613             /* Keep track of the first new parameter we
14614                generate. That's what will be returned to the
14615                caller.  */
14616             if (!first_r)
14617               first_r = r;
14618
14619             /* Build a proper chain of parameters when substituting
14620                into a function parameter pack.  */
14621             if (prev_r)
14622               DECL_CHAIN (prev_r) = r;
14623           }
14624
14625         /* If cp_unevaluated_operand is set, we're just looking for a
14626            single dummy parameter, so don't keep going.  */
14627         if (DECL_CHAIN (t) && !cp_unevaluated_operand)
14628           DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
14629                                    complain, DECL_CHAIN (t));
14630
14631         /* FIRST_R contains the start of the chain we've built.  */
14632         r = first_r;
14633       }
14634       break;
14635
14636     case FIELD_DECL:
14637       {
14638         tree type = NULL_TREE;
14639         tree vec = NULL_TREE;
14640         tree expanded_types = NULL_TREE;
14641         int len = 1;
14642
14643         if (PACK_EXPANSION_P (TREE_TYPE (t)))
14644           {
14645             /* This field is a lambda capture pack.  Return a TREE_VEC of
14646                the expanded fields to instantiate_class_template_1.  */
14647             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
14648                                                     complain, in_decl);
14649             if (TREE_CODE (expanded_types) == TREE_VEC)
14650               {
14651                 len = TREE_VEC_LENGTH (expanded_types);
14652                 vec = make_tree_vec (len);
14653               }
14654             else
14655               {
14656                 /* All we did was update the type. Make a note of that.  */
14657                 type = expanded_types;
14658                 expanded_types = NULL_TREE;
14659               }
14660           }
14661
14662         for (int i = 0; i < len; ++i)
14663           {
14664             r = copy_decl (t);
14665             if (expanded_types)
14666               {
14667                 type = TREE_VEC_ELT (expanded_types, i);
14668                 DECL_NAME (r)
14669                   = make_ith_pack_parameter_name (DECL_NAME (r), i);
14670               }
14671             else if (!type)
14672               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14673
14674             if (type == error_mark_node)
14675               RETURN (error_mark_node);
14676             TREE_TYPE (r) = type;
14677             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14678
14679             if (DECL_C_BIT_FIELD (r))
14680               /* For bit-fields, DECL_BIT_FIELD_REPRESENTATIVE gives the
14681                  number of bits.  */
14682               DECL_BIT_FIELD_REPRESENTATIVE (r)
14683                 = tsubst_expr (DECL_BIT_FIELD_REPRESENTATIVE (t), args,
14684                                complain, in_decl,
14685                                /*integral_constant_expression_p=*/true);
14686             if (DECL_INITIAL (t))
14687               {
14688                 /* Set up DECL_TEMPLATE_INFO so that we can get at the
14689                    NSDMI in perform_member_init.  Still set DECL_INITIAL
14690                    so that we know there is one.  */
14691                 DECL_INITIAL (r) = void_node;
14692                 gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
14693                 retrofit_lang_decl (r);
14694                 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
14695               }
14696             /* We don't have to set DECL_CONTEXT here; it is set by
14697                finish_member_declaration.  */
14698             DECL_CHAIN (r) = NULL_TREE;
14699
14700             if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14701                                                  args, complain, in_decl))
14702               return error_mark_node;
14703
14704             if (vec)
14705               TREE_VEC_ELT (vec, i) = r;
14706           }
14707
14708         if (vec)
14709           r = vec;
14710       }
14711       break;
14712
14713     case USING_DECL:
14714       /* We reach here only for member using decls.  We also need to check
14715          uses_template_parms because DECL_DEPENDENT_P is not set for a
14716          using-declaration that designates a member of the current
14717          instantiation (c++/53549).  */
14718       if (DECL_DEPENDENT_P (t)
14719           || uses_template_parms (USING_DECL_SCOPE (t)))
14720         {
14721           tree scope = USING_DECL_SCOPE (t);
14722           tree name = tsubst_copy (DECL_NAME (t), args, complain, in_decl);
14723           if (PACK_EXPANSION_P (scope))
14724             {
14725               tree vec = tsubst_pack_expansion (scope, args, complain, in_decl);
14726               int len = TREE_VEC_LENGTH (vec);
14727               r = make_tree_vec (len);
14728               for (int i = 0; i < len; ++i)
14729                 {
14730                   tree escope = TREE_VEC_ELT (vec, i);
14731                   tree elt = do_class_using_decl (escope, name);
14732                   if (!elt)
14733                     {
14734                       r = error_mark_node;
14735                       break;
14736                     }
14737                   else
14738                     {
14739                       TREE_PROTECTED (elt) = TREE_PROTECTED (t);
14740                       TREE_PRIVATE (elt) = TREE_PRIVATE (t);
14741                     }
14742                   TREE_VEC_ELT (r, i) = elt;
14743                 }
14744             }
14745           else
14746             {
14747               tree inst_scope = tsubst_copy (USING_DECL_SCOPE (t), args,
14748                                              complain, in_decl);
14749               r = do_class_using_decl (inst_scope, name);
14750               if (!r)
14751                 r = error_mark_node;
14752               else
14753                 {
14754                   TREE_PROTECTED (r) = TREE_PROTECTED (t);
14755                   TREE_PRIVATE (r) = TREE_PRIVATE (t);
14756                 }
14757             }
14758         }
14759       else
14760         {
14761           r = copy_node (t);
14762           DECL_CHAIN (r) = NULL_TREE;
14763         }
14764       break;
14765
14766     case TYPE_DECL:
14767     case VAR_DECL:
14768       {
14769         tree argvec = NULL_TREE;
14770         tree gen_tmpl = NULL_TREE;
14771         tree tmpl = NULL_TREE;
14772         tree type = NULL_TREE;
14773
14774         if (TREE_TYPE (t) == error_mark_node)
14775           RETURN (error_mark_node);
14776
14777         if (TREE_CODE (t) == TYPE_DECL
14778             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
14779           {
14780             /* If this is the canonical decl, we don't have to
14781                mess with instantiations, and often we can't (for
14782                typename, template type parms and such).  Note that
14783                TYPE_NAME is not correct for the above test if
14784                we've copied the type for a typedef.  */
14785             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14786             if (type == error_mark_node)
14787               RETURN (error_mark_node);
14788             r = TYPE_NAME (type);
14789             break;
14790           }
14791
14792         /* Check to see if we already have the specialization we
14793            need.  */
14794         tree spec = NULL_TREE;
14795         bool local_p = false;
14796         tree ctx = DECL_CONTEXT (t);
14797         if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t))
14798             && (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t)))
14799           {
14800             local_p = false;
14801             if (DECL_CLASS_SCOPE_P (t))
14802               {
14803                 ctx = tsubst_aggr_type (ctx, args,
14804                                         complain,
14805                                         in_decl, /*entering_scope=*/1);
14806                 /* If CTX is unchanged, then T is in fact the
14807                    specialization we want.  That situation occurs when
14808                    referencing a static data member within in its own
14809                    class.  We can use pointer equality, rather than
14810                    same_type_p, because DECL_CONTEXT is always
14811                    canonical...  */
14812                 if (ctx == DECL_CONTEXT (t)
14813                     /* ... unless T is a member template; in which
14814                        case our caller can be willing to create a
14815                        specialization of that template represented
14816                        by T.  */
14817                     && !(DECL_TI_TEMPLATE (t)
14818                          && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
14819                   spec = t;
14820               }
14821
14822             if (!spec)
14823               {
14824                 tmpl = DECL_TI_TEMPLATE (t);
14825                 gen_tmpl = most_general_template (tmpl);
14826                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
14827                 if (argvec != error_mark_node)
14828                   argvec = (coerce_innermost_template_parms
14829                             (DECL_TEMPLATE_PARMS (gen_tmpl),
14830                              argvec, t, complain,
14831                              /*all*/true, /*defarg*/true));
14832                 if (argvec == error_mark_node)
14833                   RETURN (error_mark_node);
14834                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
14835                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
14836               }
14837           }
14838         else
14839           {
14840             if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t)))
14841               /* Subsequent calls to pushdecl will fill this in.  */
14842               ctx = NULL_TREE;
14843             /* A local variable.  */
14844             local_p = true;
14845             /* Unless this is a reference to a static variable from an
14846                enclosing function, in which case we need to fill it in now.  */
14847             if (TREE_STATIC (t))
14848               {
14849                 tree fn = enclosing_instantiation_of (DECL_CONTEXT (t));
14850                 if (fn != current_function_decl)
14851                   ctx = fn;
14852               }
14853             spec = retrieve_local_specialization (t);
14854           }
14855         /* If we already have the specialization we need, there is
14856            nothing more to do.  */
14857         if (spec)
14858           {
14859             r = spec;
14860             break;
14861           }
14862
14863         /* Create a new node for the specialization we need.  */
14864         if (type == NULL_TREE)
14865           {
14866             if (is_typedef_decl (t))
14867               type = DECL_ORIGINAL_TYPE (t);
14868             else
14869               type = TREE_TYPE (t);
14870             if (VAR_P (t)
14871                 && VAR_HAD_UNKNOWN_BOUND (t)
14872                 && type != error_mark_node)
14873               type = strip_array_domain (type);
14874             tree sub_args = args;
14875             if (tree auto_node = type_uses_auto (type))
14876               {
14877                 /* Mask off any template args past the variable's context so we
14878                    don't replace the auto with an unrelated argument.  */
14879                 int nouter = TEMPLATE_TYPE_LEVEL (auto_node) - 1;
14880                 int extra = TMPL_ARGS_DEPTH (args) - nouter;
14881                 if (extra > 0)
14882                   /* This should never happen with the new lambda instantiation
14883                      model, but keep the handling just in case.  */
14884                   gcc_assert (!CHECKING_P),
14885                   sub_args = strip_innermost_template_args (args, extra);
14886               }
14887             type = tsubst (type, sub_args, complain, in_decl);
14888             /* Substituting the type might have recursively instantiated this
14889                same alias (c++/86171).  */
14890             if (gen_tmpl && DECL_ALIAS_TEMPLATE_P (gen_tmpl)
14891                 && (spec = retrieve_specialization (gen_tmpl, argvec, hash)))
14892               {
14893                 r = spec;
14894                 break;
14895               }
14896           }
14897         r = copy_decl (t);
14898         if (VAR_P (r))
14899           {
14900             DECL_INITIALIZED_P (r) = 0;
14901             DECL_TEMPLATE_INSTANTIATED (r) = 0;
14902             if (type == error_mark_node)
14903               RETURN (error_mark_node);
14904             if (TREE_CODE (type) == FUNCTION_TYPE)
14905               {
14906                 /* It may seem that this case cannot occur, since:
14907
14908                    typedef void f();
14909                    void g() { f x; }
14910
14911                    declares a function, not a variable.  However:
14912
14913                    typedef void f();
14914                    template <typename T> void g() { T t; }
14915                    template void g<f>();
14916
14917                    is an attempt to declare a variable with function
14918                    type.  */
14919                 error ("variable %qD has function type",
14920                        /* R is not yet sufficiently initialized, so we
14921                           just use its name.  */
14922                        DECL_NAME (r));
14923                 RETURN (error_mark_node);
14924               }
14925             type = complete_type (type);
14926             /* Wait until cp_finish_decl to set this again, to handle
14927                circular dependency (template/instantiate6.C). */
14928             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
14929             type = check_var_type (DECL_NAME (r), type,
14930                                    DECL_SOURCE_LOCATION (r));
14931             if (DECL_HAS_VALUE_EXPR_P (t))
14932               {
14933                 tree ve = DECL_VALUE_EXPR (t);
14934                 /* If the DECL_VALUE_EXPR is converted to the declared type,
14935                    preserve the identity so that gimplify_type_sizes works.  */
14936                 bool nop = (TREE_CODE (ve) == NOP_EXPR);
14937                 if (nop)
14938                   ve = TREE_OPERAND (ve, 0);
14939                 ve = tsubst_expr (ve, args, complain, in_decl,
14940                                   /*constant_expression_p=*/false);
14941                 if (REFERENCE_REF_P (ve))
14942                   {
14943                     gcc_assert (TYPE_REF_P (type));
14944                     ve = TREE_OPERAND (ve, 0);
14945                   }
14946                 if (nop)
14947                   ve = build_nop (type, ve);
14948                 else if (DECL_LANG_SPECIFIC (t)
14949                          && DECL_OMP_PRIVATIZED_MEMBER (t)
14950                          && TREE_CODE (ve) == COMPONENT_REF
14951                          && TREE_CODE (TREE_OPERAND (ve, 1)) == FIELD_DECL
14952                          && DECL_BIT_FIELD_TYPE (TREE_OPERAND (ve, 1)) == type)
14953                   type = TREE_TYPE (ve);
14954                 else
14955                   gcc_checking_assert (TYPE_MAIN_VARIANT (TREE_TYPE (ve))
14956                                        == TYPE_MAIN_VARIANT (type));
14957                 SET_DECL_VALUE_EXPR (r, ve);
14958               }
14959             if (CP_DECL_THREAD_LOCAL_P (r)
14960                 && !processing_template_decl)
14961               set_decl_tls_model (r, decl_default_tls_model (r));
14962           }
14963         else if (DECL_SELF_REFERENCE_P (t))
14964           SET_DECL_SELF_REFERENCE_P (r);
14965         TREE_TYPE (r) = type;
14966         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14967         DECL_CONTEXT (r) = ctx;
14968         /* Clear out the mangled name and RTL for the instantiation.  */
14969         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
14970         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
14971           SET_DECL_RTL (r, NULL);
14972         set_instantiating_module (r);
14973
14974         /* The initializer must not be expanded until it is required;
14975            see [temp.inst].  */
14976         DECL_INITIAL (r) = NULL_TREE;
14977         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
14978         if (VAR_P (r))
14979           {
14980             if (DECL_LANG_SPECIFIC (r))
14981               SET_DECL_DEPENDENT_INIT_P (r, false);
14982
14983             SET_DECL_MODE (r, VOIDmode);
14984
14985             /* Possibly limit visibility based on template args.  */
14986             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
14987             if (DECL_VISIBILITY_SPECIFIED (t))
14988               {
14989                 DECL_VISIBILITY_SPECIFIED (r) = 0;
14990                 DECL_ATTRIBUTES (r)
14991                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
14992               }
14993             determine_visibility (r);
14994           }
14995
14996         if (!local_p)
14997           {
14998             /* A static data member declaration is always marked
14999                external when it is declared in-class, even if an
15000                initializer is present.  We mimic the non-template
15001                processing here.  */
15002             DECL_EXTERNAL (r) = 1;
15003             if (DECL_NAMESPACE_SCOPE_P (t))
15004               DECL_NOT_REALLY_EXTERN (r) = 1;
15005
15006             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
15007             SET_DECL_IMPLICIT_INSTANTIATION (r);
15008             if (!error_operand_p (r) || (complain & tf_error))
15009               register_specialization (r, gen_tmpl, argvec, false, hash);
15010           }
15011         else
15012           {
15013             if (DECL_LANG_SPECIFIC (r))
15014               DECL_TEMPLATE_INFO (r) = NULL_TREE;
15015             if (!cp_unevaluated_operand)
15016               register_local_specialization (r, t);
15017           }
15018
15019         DECL_CHAIN (r) = NULL_TREE;
15020
15021         if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
15022                                              /*flags=*/0,
15023                                              args, complain, in_decl))
15024           return error_mark_node;
15025
15026         /* Preserve a typedef that names a type.  */
15027         if (is_typedef_decl (r) && type != error_mark_node)
15028           {
15029             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
15030             set_underlying_type (r);
15031           }
15032
15033         layout_decl (r, 0);
15034       }
15035       break;
15036
15037     default:
15038       gcc_unreachable ();
15039     }
15040 #undef RETURN
15041
15042  out:
15043   /* Restore the file and line information.  */
15044   input_location = saved_loc;
15045
15046   return r;
15047 }
15048
15049 /* Substitute into the complete parameter type list PARMS.  */
15050
15051 tree
15052 tsubst_function_parms (tree parms,
15053                        tree args,
15054                        tsubst_flags_t complain,
15055                        tree in_decl)
15056 {
15057   return tsubst_arg_types (parms, args, NULL_TREE, complain, in_decl);
15058 }
15059
15060 /* Substitute into the ARG_TYPES of a function type.
15061    If END is a TREE_CHAIN, leave it and any following types
15062    un-substituted.  */
15063
15064 static tree
15065 tsubst_arg_types (tree arg_types,
15066                   tree args,
15067                   tree end,
15068                   tsubst_flags_t complain,
15069                   tree in_decl)
15070 {
15071   tree remaining_arg_types;
15072   tree type = NULL_TREE;
15073   int i = 1;
15074   tree expanded_args = NULL_TREE;
15075   tree default_arg;
15076
15077   if (!arg_types || arg_types == void_list_node || arg_types == end)
15078     return arg_types;
15079
15080   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
15081                                           args, end, complain, in_decl);
15082   if (remaining_arg_types == error_mark_node)
15083     return error_mark_node;
15084
15085   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
15086     {
15087       /* For a pack expansion, perform substitution on the
15088          entire expression. Later on, we'll handle the arguments
15089          one-by-one.  */
15090       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
15091                                             args, complain, in_decl);
15092
15093       if (TREE_CODE (expanded_args) == TREE_VEC)
15094         /* So that we'll spin through the parameters, one by one.  */
15095         i = TREE_VEC_LENGTH (expanded_args);
15096       else
15097         {
15098           /* We only partially substituted into the parameter
15099              pack. Our type is TYPE_PACK_EXPANSION.  */
15100           type = expanded_args;
15101           expanded_args = NULL_TREE;
15102         }
15103     }
15104
15105   while (i > 0) {
15106     --i;
15107
15108     if (expanded_args)
15109       type = TREE_VEC_ELT (expanded_args, i);
15110     else if (!type)
15111       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
15112
15113     if (type == error_mark_node)
15114       return error_mark_node;
15115     if (VOID_TYPE_P (type))
15116       {
15117         if (complain & tf_error)
15118           {
15119             error ("invalid parameter type %qT", type);
15120             if (in_decl)
15121               error ("in declaration %q+D", in_decl);
15122           }
15123         return error_mark_node;
15124     }
15125
15126     /* Do array-to-pointer, function-to-pointer conversion, and ignore
15127        top-level qualifiers as required.  */
15128     type = cv_unqualified (type_decays_to (type));
15129
15130     /* We do not substitute into default arguments here.  The standard
15131        mandates that they be instantiated only when needed, which is
15132        done in build_over_call.  */
15133     default_arg = TREE_PURPOSE (arg_types);
15134
15135     /* Except that we do substitute default arguments under tsubst_lambda_expr,
15136        since the new op() won't have any associated template arguments for us
15137        to refer to later.  */
15138     if (lambda_fn_in_template_p (in_decl))
15139       default_arg = tsubst_copy_and_build (default_arg, args, complain, in_decl,
15140                                            false/*fn*/, false/*constexpr*/);
15141
15142     if (default_arg && TREE_CODE (default_arg) == DEFERRED_PARSE)
15143       {
15144         /* We've instantiated a template before its default arguments
15145            have been parsed.  This can happen for a nested template
15146            class, and is not an error unless we require the default
15147            argument in a call of this function.  */
15148         remaining_arg_types = 
15149           tree_cons (default_arg, type, remaining_arg_types);
15150         vec_safe_push (DEFPARSE_INSTANTIATIONS (default_arg),
15151                        remaining_arg_types);
15152       }
15153     else
15154       remaining_arg_types =
15155         hash_tree_cons (default_arg, type, remaining_arg_types);
15156   }
15157
15158   return remaining_arg_types;
15159 }
15160
15161 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
15162    *not* handle the exception-specification for FNTYPE, because the
15163    initial substitution of explicitly provided template parameters
15164    during argument deduction forbids substitution into the
15165    exception-specification:
15166
15167      [temp.deduct]
15168
15169      All references in the function type of the function template to  the
15170      corresponding template parameters are replaced by the specified tem-
15171      plate argument values.  If a substitution in a template parameter or
15172      in  the function type of the function template results in an invalid
15173      type, type deduction fails.  [Note: The equivalent  substitution  in
15174      exception specifications is done only when the function is instanti-
15175      ated, at which point a program is  ill-formed  if  the  substitution
15176      results in an invalid type.]  */
15177
15178 static tree
15179 tsubst_function_type (tree t,
15180                       tree args,
15181                       tsubst_flags_t complain,
15182                       tree in_decl)
15183 {
15184   tree return_type;
15185   tree arg_types = NULL_TREE;
15186
15187   /* The TYPE_CONTEXT is not used for function/method types.  */
15188   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
15189
15190   /* DR 1227: Mixing immediate and non-immediate contexts in deduction
15191      failure.  */
15192   bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
15193
15194   if (late_return_type_p)
15195     {
15196       /* Substitute the argument types.  */
15197       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15198                                     complain, in_decl);
15199       if (arg_types == error_mark_node)
15200         return error_mark_node;
15201
15202       tree save_ccp = current_class_ptr;
15203       tree save_ccr = current_class_ref;
15204       tree this_type = (TREE_CODE (t) == METHOD_TYPE
15205                         ? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
15206       bool do_inject = this_type && CLASS_TYPE_P (this_type);
15207       if (do_inject)
15208         {
15209           /* DR 1207: 'this' is in scope in the trailing return type.  */
15210           inject_this_parameter (this_type, cp_type_quals (this_type));
15211         }
15212
15213       /* Substitute the return type.  */
15214       return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15215
15216       if (do_inject)
15217         {
15218           current_class_ptr = save_ccp;
15219           current_class_ref = save_ccr;
15220         }
15221     }
15222   else
15223     /* Substitute the return type.  */
15224     return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15225
15226   if (return_type == error_mark_node)
15227     return error_mark_node;
15228   /* DR 486 clarifies that creation of a function type with an
15229      invalid return type is a deduction failure.  */
15230   if (TREE_CODE (return_type) == ARRAY_TYPE
15231       || TREE_CODE (return_type) == FUNCTION_TYPE)
15232     {
15233       if (complain & tf_error)
15234         {
15235           if (TREE_CODE (return_type) == ARRAY_TYPE)
15236             error ("function returning an array");
15237           else
15238             error ("function returning a function");
15239         }
15240       return error_mark_node;
15241     }
15242
15243   if (!late_return_type_p)
15244     {
15245       /* Substitute the argument types.  */
15246       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15247                                     complain, in_decl);
15248       if (arg_types == error_mark_node)
15249         return error_mark_node;
15250     }
15251
15252   /* Construct a new type node and return it.  */
15253   return rebuild_function_or_method_type (t, return_type, arg_types,
15254                                           /*raises=*/NULL_TREE, complain);
15255 }
15256
15257 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
15258    ARGS into that specification, and return the substituted
15259    specification.  If there is no specification, return NULL_TREE.  */
15260
15261 static tree
15262 tsubst_exception_specification (tree fntype,
15263                                 tree args,
15264                                 tsubst_flags_t complain,
15265                                 tree in_decl,
15266                                 bool defer_ok)
15267 {
15268   tree specs;
15269   tree new_specs;
15270
15271   specs = TYPE_RAISES_EXCEPTIONS (fntype);
15272   new_specs = NULL_TREE;
15273   if (specs && TREE_PURPOSE (specs))
15274     {
15275       /* A noexcept-specifier.  */
15276       tree expr = TREE_PURPOSE (specs);
15277       if (TREE_CODE (expr) == INTEGER_CST)
15278         new_specs = expr;
15279       else if (defer_ok)
15280         {
15281           /* Defer instantiation of noexcept-specifiers to avoid
15282              excessive instantiations (c++/49107).  */
15283           new_specs = make_node (DEFERRED_NOEXCEPT);
15284           if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15285             {
15286               /* We already partially instantiated this member template,
15287                  so combine the new args with the old.  */
15288               DEFERRED_NOEXCEPT_PATTERN (new_specs)
15289                 = DEFERRED_NOEXCEPT_PATTERN (expr);
15290               DEFERRED_NOEXCEPT_ARGS (new_specs)
15291                 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
15292             }
15293           else
15294             {
15295               DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
15296               DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
15297             }
15298         }
15299       else
15300         {
15301           if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15302             {
15303               args = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr),
15304                                            args);
15305               expr = DEFERRED_NOEXCEPT_PATTERN (expr);
15306             }
15307           new_specs = tsubst_copy_and_build
15308             (expr, args, complain, in_decl, /*function_p=*/false,
15309              /*integral_constant_expression_p=*/true);
15310         }
15311       new_specs = build_noexcept_spec (new_specs, complain);
15312       /* We've instantiated a template before a noexcept-specifier
15313          contained therein has been parsed.  This can happen for
15314          a nested template class:
15315
15316           struct S {
15317             template<typename> struct B { B() noexcept(...); };
15318             struct A : B<int> { ... use B() ... };
15319           };
15320
15321          where completing B<int> will trigger instantiating the
15322          noexcept, even though we only parse it at the end of S.  */
15323       if (UNPARSED_NOEXCEPT_SPEC_P (specs))
15324         {
15325           gcc_checking_assert (defer_ok);
15326           vec_safe_push (DEFPARSE_INSTANTIATIONS (expr), new_specs);
15327         }
15328     }
15329   else if (specs)
15330     {
15331       if (! TREE_VALUE (specs))
15332         new_specs = specs;
15333       else
15334         while (specs)
15335           {
15336             tree spec;
15337             int i, len = 1;
15338             tree expanded_specs = NULL_TREE;
15339
15340             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
15341               {
15342                 /* Expand the pack expansion type.  */
15343                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
15344                                                        args, complain,
15345                                                        in_decl);
15346
15347                 if (expanded_specs == error_mark_node)
15348                   return error_mark_node;
15349                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
15350                   len = TREE_VEC_LENGTH (expanded_specs);
15351                 else
15352                   {
15353                     /* We're substituting into a member template, so
15354                        we got a TYPE_PACK_EXPANSION back.  Add that
15355                        expansion and move on.  */
15356                     gcc_assert (TREE_CODE (expanded_specs)
15357                                 == TYPE_PACK_EXPANSION);
15358                     new_specs = add_exception_specifier (new_specs,
15359                                                          expanded_specs,
15360                                                          complain);
15361                     specs = TREE_CHAIN (specs);
15362                     continue;
15363                   }
15364               }
15365
15366             for (i = 0; i < len; ++i)
15367               {
15368                 if (expanded_specs)
15369                   spec = TREE_VEC_ELT (expanded_specs, i);
15370                 else
15371                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
15372                 if (spec == error_mark_node)
15373                   return spec;
15374                 new_specs = add_exception_specifier (new_specs, spec, 
15375                                                      complain);
15376               }
15377
15378             specs = TREE_CHAIN (specs);
15379           }
15380     }
15381   return new_specs;
15382 }
15383
15384 /* Substitute through a TREE_LIST of types or expressions, handling pack
15385    expansions.  */
15386
15387 tree
15388 tsubst_tree_list (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15389 {
15390   if (t == void_list_node)
15391     return t;
15392
15393   tree purpose = TREE_PURPOSE (t);
15394   tree purposevec = NULL_TREE;
15395   if (!purpose)
15396     ;
15397   else if (PACK_EXPANSION_P (purpose))
15398     {
15399       purpose = tsubst_pack_expansion (purpose, args, complain, in_decl);
15400       if (TREE_CODE (purpose) == TREE_VEC)
15401         purposevec = purpose;
15402     }
15403   else if (TYPE_P (purpose))
15404     purpose = tsubst (purpose, args, complain, in_decl);
15405   else
15406     purpose = tsubst_copy_and_build (purpose, args, complain, in_decl);
15407   if (purpose == error_mark_node || purposevec == error_mark_node)
15408     return error_mark_node;
15409
15410   tree value = TREE_VALUE (t);
15411   tree valuevec = NULL_TREE;
15412   if (!value)
15413     ;
15414   else if (PACK_EXPANSION_P (value))
15415     {
15416       value = tsubst_pack_expansion (value, args, complain, in_decl);
15417       if (TREE_CODE (value) == TREE_VEC)
15418         valuevec = value;
15419     }
15420   else if (TYPE_P (value))
15421     value = tsubst (value, args, complain, in_decl);
15422   else
15423     value = tsubst_copy_and_build (value, args, complain, in_decl);
15424   if (value == error_mark_node || valuevec == error_mark_node)
15425     return error_mark_node;
15426
15427   tree chain = TREE_CHAIN (t);
15428   if (!chain)
15429     ;
15430   else if (TREE_CODE (chain) == TREE_LIST)
15431     chain = tsubst_tree_list (chain, args, complain, in_decl);
15432   else if (TYPE_P (chain))
15433     chain = tsubst (chain, args, complain, in_decl);
15434   else
15435     chain = tsubst_copy_and_build (chain, args, complain, in_decl);
15436   if (chain == error_mark_node)
15437     return error_mark_node;
15438
15439   if (purpose == TREE_PURPOSE (t)
15440       && value == TREE_VALUE (t)
15441       && chain == TREE_CHAIN (t))
15442     return t;
15443
15444   int len;
15445   /* Determine the number of arguments.  */
15446   if (purposevec)
15447     {
15448       len = TREE_VEC_LENGTH (purposevec);
15449       gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
15450     }
15451   else if (valuevec)
15452     len = TREE_VEC_LENGTH (valuevec);
15453   else
15454     len = 1;
15455
15456   for (int i = len; i-- > 0; )
15457     {
15458       if (purposevec)
15459         purpose = TREE_VEC_ELT (purposevec, i);
15460       if (valuevec)
15461         value = TREE_VEC_ELT (valuevec, i);
15462
15463       if (value && TYPE_P (value))
15464         chain = hash_tree_cons (purpose, value, chain);
15465       else
15466         chain = tree_cons (purpose, value, chain);
15467     }
15468
15469   return chain;
15470 }
15471
15472 /* Take the tree structure T and replace template parameters used
15473    therein with the argument vector ARGS.  IN_DECL is an associated
15474    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
15475    Issue error and warning messages under control of COMPLAIN.  Note
15476    that we must be relatively non-tolerant of extensions here, in
15477    order to preserve conformance; if we allow substitutions that
15478    should not be allowed, we may allow argument deductions that should
15479    not succeed, and therefore report ambiguous overload situations
15480    where there are none.  In theory, we could allow the substitution,
15481    but indicate that it should have failed, and allow our caller to
15482    make sure that the right thing happens, but we don't try to do this
15483    yet.
15484
15485    This function is used for dealing with types, decls and the like;
15486    for expressions, use tsubst_expr or tsubst_copy.  */
15487
15488 tree
15489 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15490 {
15491   enum tree_code code;
15492   tree type, r = NULL_TREE;
15493
15494   if (t == NULL_TREE || t == error_mark_node
15495       || t == integer_type_node
15496       || t == void_type_node
15497       || t == char_type_node
15498       || t == unknown_type_node
15499       || TREE_CODE (t) == NAMESPACE_DECL
15500       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
15501     return t;
15502
15503   if (DECL_P (t))
15504     return tsubst_decl (t, args, complain);
15505
15506   if (args == NULL_TREE)
15507     return t;
15508
15509   code = TREE_CODE (t);
15510
15511   gcc_assert (code != IDENTIFIER_NODE);
15512   type = TREE_TYPE (t);
15513
15514   gcc_assert (type != unknown_type_node);
15515
15516   /* Reuse typedefs.  We need to do this to handle dependent attributes,
15517      such as attribute aligned.  */
15518   if (TYPE_P (t)
15519       && typedef_variant_p (t))
15520     {
15521       tree decl = TYPE_NAME (t);
15522
15523       if (alias_template_specialization_p (t, nt_opaque))
15524         {
15525           /* DECL represents an alias template and we want to
15526              instantiate it.  */
15527           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15528           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15529           r = instantiate_alias_template (tmpl, gen_args, complain);
15530         }
15531       else if (DECL_CLASS_SCOPE_P (decl)
15532                && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
15533                && uses_template_parms (DECL_CONTEXT (decl)))
15534         {
15535           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15536           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15537           r = retrieve_specialization (tmpl, gen_args, 0);
15538         }
15539       else if (DECL_FUNCTION_SCOPE_P (decl)
15540                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
15541                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
15542         r = retrieve_local_specialization (decl);
15543       else
15544         /* The typedef is from a non-template context.  */
15545         return t;
15546
15547       if (r)
15548         {
15549           r = TREE_TYPE (r);
15550           r = cp_build_qualified_type_real
15551             (r, cp_type_quals (t) | cp_type_quals (r),
15552              complain | tf_ignore_bad_quals);
15553           return r;
15554         }
15555       else
15556         {
15557           /* We don't have an instantiation yet, so drop the typedef.  */
15558           int quals = cp_type_quals (t);
15559           t = DECL_ORIGINAL_TYPE (decl);
15560           t = cp_build_qualified_type_real (t, quals,
15561                                             complain | tf_ignore_bad_quals);
15562         }
15563     }
15564
15565   bool fndecl_type = (complain & tf_fndecl_type);
15566   complain &= ~tf_fndecl_type;
15567
15568   if (type
15569       && code != TYPENAME_TYPE
15570       && code != TEMPLATE_TYPE_PARM
15571       && code != TEMPLATE_PARM_INDEX
15572       && code != IDENTIFIER_NODE
15573       && code != FUNCTION_TYPE
15574       && code != METHOD_TYPE)
15575     type = tsubst (type, args, complain, in_decl);
15576   if (type == error_mark_node)
15577     return error_mark_node;
15578
15579   switch (code)
15580     {
15581     case RECORD_TYPE:
15582     case UNION_TYPE:
15583     case ENUMERAL_TYPE:
15584       return tsubst_aggr_type (t, args, complain, in_decl,
15585                                /*entering_scope=*/0);
15586
15587     case ERROR_MARK:
15588     case IDENTIFIER_NODE:
15589     case VOID_TYPE:
15590     case OPAQUE_TYPE:
15591     case REAL_TYPE:
15592     case COMPLEX_TYPE:
15593     case VECTOR_TYPE:
15594     case BOOLEAN_TYPE:
15595     case NULLPTR_TYPE:
15596     case LANG_TYPE:
15597       return t;
15598
15599     case INTEGER_TYPE:
15600       if (t == integer_type_node)
15601         return t;
15602
15603       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
15604           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
15605         return t;
15606
15607       {
15608         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
15609
15610         max = tsubst_expr (omax, args, complain, in_decl,
15611                            /*integral_constant_expression_p=*/false);
15612
15613         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
15614            needed.  */
15615         if (TREE_CODE (max) == NOP_EXPR
15616             && TREE_SIDE_EFFECTS (omax)
15617             && !TREE_TYPE (max))
15618           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
15619
15620         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
15621            with TREE_SIDE_EFFECTS that indicates this is not an integral
15622            constant expression.  */
15623         if (processing_template_decl
15624             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
15625           {
15626             gcc_assert (TREE_CODE (max) == NOP_EXPR);
15627             TREE_SIDE_EFFECTS (max) = 1;
15628           }
15629
15630         return compute_array_index_type (NULL_TREE, max, complain);
15631       }
15632
15633     case TEMPLATE_TYPE_PARM:
15634     case TEMPLATE_TEMPLATE_PARM:
15635     case BOUND_TEMPLATE_TEMPLATE_PARM:
15636     case TEMPLATE_PARM_INDEX:
15637       {
15638         int idx;
15639         int level;
15640         int levels;
15641         tree arg = NULL_TREE;
15642
15643         r = NULL_TREE;
15644
15645         gcc_assert (TREE_VEC_LENGTH (args) > 0);
15646         template_parm_level_and_index (t, &level, &idx);
15647
15648         levels = TMPL_ARGS_DEPTH (args);
15649         if (level <= levels
15650             && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
15651           {
15652             arg = TMPL_ARG (args, level, idx);
15653
15654             /* See through ARGUMENT_PACK_SELECT arguments. */
15655             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
15656               arg = argument_pack_select_arg (arg);
15657           }
15658
15659         if (arg == error_mark_node)
15660           return error_mark_node;
15661         else if (arg != NULL_TREE)
15662           {
15663             if (ARGUMENT_PACK_P (arg))
15664               /* If ARG is an argument pack, we don't actually want to
15665                  perform a substitution here, because substitutions
15666                  for argument packs are only done
15667                  element-by-element. We can get to this point when
15668                  substituting the type of a non-type template
15669                  parameter pack, when that type actually contains
15670                  template parameter packs from an outer template, e.g.,
15671
15672                  template<typename... Types> struct A {
15673                    template<Types... Values> struct B { };
15674                  };  */
15675               return t;
15676
15677             if (code == TEMPLATE_TYPE_PARM)
15678               {
15679                 int quals;
15680
15681                 /* When building concept checks for the purpose of
15682                    deducing placeholders, we can end up with wildcards
15683                    where types are expected. Adjust this to the deduced
15684                    value.  */
15685                 if (TREE_CODE (arg) == WILDCARD_DECL)
15686                   arg = TREE_TYPE (TREE_TYPE (arg));
15687
15688                 gcc_assert (TYPE_P (arg));
15689
15690                 quals = cp_type_quals (arg) | cp_type_quals (t);
15691
15692                 return cp_build_qualified_type_real
15693                   (arg, quals, complain | tf_ignore_bad_quals);
15694               }
15695             else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
15696               {
15697                 /* We are processing a type constructed from a
15698                    template template parameter.  */
15699                 tree argvec = tsubst (TYPE_TI_ARGS (t),
15700                                       args, complain, in_decl);
15701                 if (argvec == error_mark_node)
15702                   return error_mark_node;
15703
15704                 gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
15705                             || TREE_CODE (arg) == TEMPLATE_DECL
15706                             || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
15707
15708                 if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
15709                   /* Consider this code:
15710
15711                         template <template <class> class Template>
15712                         struct Internal {
15713                         template <class Arg> using Bind = Template<Arg>;
15714                         };
15715
15716                         template <template <class> class Template, class Arg>
15717                         using Instantiate = Template<Arg>; //#0
15718
15719                         template <template <class> class Template,
15720                                   class Argument>
15721                         using Bind =
15722                           Instantiate<Internal<Template>::template Bind,
15723                                       Argument>; //#1
15724
15725                      When #1 is parsed, the
15726                      BOUND_TEMPLATE_TEMPLATE_PARM representing the
15727                      parameter `Template' in #0 matches the
15728                      UNBOUND_CLASS_TEMPLATE representing the argument
15729                      `Internal<Template>::template Bind'; We then want
15730                      to assemble the type `Bind<Argument>' that can't
15731                      be fully created right now, because
15732                      `Internal<Template>' not being complete, the Bind
15733                      template cannot be looked up in that context.  So
15734                      we need to "store" `Bind<Argument>' for later
15735                      when the context of Bind becomes complete.  Let's
15736                      store that in a TYPENAME_TYPE.  */
15737                   return make_typename_type (TYPE_CONTEXT (arg),
15738                                              build_nt (TEMPLATE_ID_EXPR,
15739                                                        TYPE_IDENTIFIER (arg),
15740                                                        argvec),
15741                                              typename_type,
15742                                              complain);
15743
15744                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
15745                    are resolving nested-types in the signature of a
15746                    member function templates.  Otherwise ARG is a
15747                    TEMPLATE_DECL and is the real template to be
15748                    instantiated.  */
15749                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
15750                   arg = TYPE_NAME (arg);
15751
15752                 r = lookup_template_class (arg,
15753                                            argvec, in_decl,
15754                                            DECL_CONTEXT (arg),
15755                                             /*entering_scope=*/0,
15756                                            complain);
15757                 return cp_build_qualified_type_real
15758                   (r, cp_type_quals (t) | cp_type_quals (r), complain);
15759               }
15760             else if (code == TEMPLATE_TEMPLATE_PARM)
15761               return arg;
15762             else
15763               /* TEMPLATE_PARM_INDEX.  */
15764               return convert_from_reference (unshare_expr (arg));
15765           }
15766
15767         if (level == 1)
15768           /* This can happen during the attempted tsubst'ing in
15769              unify.  This means that we don't yet have any information
15770              about the template parameter in question.  */
15771           return t;
15772
15773         /* Early in template argument deduction substitution, we don't
15774            want to reduce the level of 'auto', or it will be confused
15775            with a normal template parm in subsequent deduction.
15776            Similarly, don't reduce the level of template parameters to
15777            avoid mismatches when deducing their types.  */
15778         if (complain & tf_partial)
15779           return t;
15780
15781         /* If we get here, we must have been looking at a parm for a
15782            more deeply nested template.  Make a new version of this
15783            template parameter, but with a lower level.  */
15784         switch (code)
15785           {
15786           case TEMPLATE_TYPE_PARM:
15787           case TEMPLATE_TEMPLATE_PARM:
15788           case BOUND_TEMPLATE_TEMPLATE_PARM:
15789             if (cp_type_quals (t))
15790               {
15791                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
15792                 r = cp_build_qualified_type_real
15793                   (r, cp_type_quals (t),
15794                    complain | (code == TEMPLATE_TYPE_PARM
15795                                ? tf_ignore_bad_quals : 0));
15796               }
15797             else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
15798                      && PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t)
15799                      && (r = (TEMPLATE_PARM_DESCENDANTS
15800                               (TEMPLATE_TYPE_PARM_INDEX (t))))
15801                      && (r = TREE_TYPE (r))
15802                      && !PLACEHOLDER_TYPE_CONSTRAINTS_INFO (r))
15803               /* Break infinite recursion when substituting the constraints
15804                  of a constrained placeholder.  */;
15805             else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
15806                      && !PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t)
15807                      && !CLASS_PLACEHOLDER_TEMPLATE (t)
15808                      && (arg = TEMPLATE_TYPE_PARM_INDEX (t),
15809                          r = TEMPLATE_PARM_DESCENDANTS (arg))
15810                      && (TEMPLATE_PARM_LEVEL (r)
15811                          == TEMPLATE_PARM_LEVEL (arg) - levels))
15812                 /* Cache the simple case of lowering a type parameter.  */
15813               r = TREE_TYPE (r);
15814             else
15815               {
15816                 r = copy_type (t);
15817                 TEMPLATE_TYPE_PARM_INDEX (r)
15818                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
15819                                                 r, levels, args, complain);
15820                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
15821                 TYPE_MAIN_VARIANT (r) = r;
15822                 TYPE_POINTER_TO (r) = NULL_TREE;
15823                 TYPE_REFERENCE_TO (r) = NULL_TREE;
15824
15825                 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
15826                   {
15827                     /* Propagate constraints on placeholders since they are
15828                        only instantiated during satisfaction.  */
15829                     if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t))
15830                       PLACEHOLDER_TYPE_CONSTRAINTS_INFO (r) = ci;
15831                     else if (tree pl = CLASS_PLACEHOLDER_TEMPLATE (t))
15832                       {
15833                         pl = tsubst_copy (pl, args, complain, in_decl);
15834                         if (TREE_CODE (pl) == TEMPLATE_TEMPLATE_PARM)
15835                           pl = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (pl);
15836                         CLASS_PLACEHOLDER_TEMPLATE (r) = pl;
15837                       }
15838                   }
15839
15840                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
15841                   /* We have reduced the level of the template
15842                      template parameter, but not the levels of its
15843                      template parameters, so canonical_type_parameter
15844                      will not be able to find the canonical template
15845                      template parameter for this level. Thus, we
15846                      require structural equality checking to compare
15847                      TEMPLATE_TEMPLATE_PARMs. */
15848                   SET_TYPE_STRUCTURAL_EQUALITY (r);
15849                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
15850                   SET_TYPE_STRUCTURAL_EQUALITY (r);
15851                 else
15852                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
15853
15854                 if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
15855                   {
15856                     tree tinfo = TYPE_TEMPLATE_INFO (t);
15857                     /* We might need to substitute into the types of non-type
15858                        template parameters.  */
15859                     tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
15860                                         complain, in_decl);
15861                     if (tmpl == error_mark_node)
15862                       return error_mark_node;
15863                     tree argvec = tsubst (TI_ARGS (tinfo), args,
15864                                           complain, in_decl);
15865                     if (argvec == error_mark_node)
15866                       return error_mark_node;
15867
15868                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
15869                       = build_template_info (tmpl, argvec);
15870                   }
15871               }
15872             break;
15873
15874           case TEMPLATE_PARM_INDEX:
15875             /* OK, now substitute the type of the non-type parameter.  We
15876                couldn't do it earlier because it might be an auto parameter,
15877                and we wouldn't need to if we had an argument.  */
15878             type = tsubst (type, args, complain, in_decl);
15879             if (type == error_mark_node)
15880               return error_mark_node;
15881             r = reduce_template_parm_level (t, type, levels, args, complain);
15882             break;
15883
15884           default:
15885             gcc_unreachable ();
15886           }
15887
15888         return r;
15889       }
15890
15891     case TREE_LIST:
15892       return tsubst_tree_list (t, args, complain, in_decl);
15893
15894     case TREE_BINFO:
15895       /* We should never be tsubsting a binfo.  */
15896       gcc_unreachable ();
15897
15898     case TREE_VEC:
15899       /* A vector of template arguments.  */
15900       gcc_assert (!type);
15901       return tsubst_template_args (t, args, complain, in_decl);
15902
15903     case POINTER_TYPE:
15904     case REFERENCE_TYPE:
15905       {
15906         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
15907           return t;
15908
15909         /* [temp.deduct]
15910
15911            Type deduction may fail for any of the following
15912            reasons:
15913
15914            -- Attempting to create a pointer to reference type.
15915            -- Attempting to create a reference to a reference type or
15916               a reference to void.
15917
15918           Core issue 106 says that creating a reference to a reference
15919           during instantiation is no longer a cause for failure. We
15920           only enforce this check in strict C++98 mode.  */
15921         if ((TYPE_REF_P (type)
15922              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
15923             || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
15924           {
15925             static location_t last_loc;
15926
15927             /* We keep track of the last time we issued this error
15928                message to avoid spewing a ton of messages during a
15929                single bad template instantiation.  */
15930             if (complain & tf_error
15931                 && last_loc != input_location)
15932               {
15933                 if (VOID_TYPE_P (type))
15934                   error ("forming reference to void");
15935                else if (code == POINTER_TYPE)
15936                  error ("forming pointer to reference type %qT", type);
15937                else
15938                   error ("forming reference to reference type %qT", type);
15939                 last_loc = input_location;
15940               }
15941
15942             return error_mark_node;
15943           }
15944         else if (TREE_CODE (type) == FUNCTION_TYPE
15945                  && (type_memfn_quals (type) != TYPE_UNQUALIFIED
15946                      || type_memfn_rqual (type) != REF_QUAL_NONE))
15947           {
15948             if (complain & tf_error)
15949               {
15950                 if (code == POINTER_TYPE)
15951                   error ("forming pointer to qualified function type %qT",
15952                          type);
15953                 else
15954                   error ("forming reference to qualified function type %qT",
15955                          type);
15956               }
15957             return error_mark_node;
15958           }
15959         else if (code == POINTER_TYPE)
15960           {
15961             r = build_pointer_type (type);
15962             if (TREE_CODE (type) == METHOD_TYPE)
15963               r = build_ptrmemfunc_type (r);
15964           }
15965         else if (TYPE_REF_P (type))
15966           /* In C++0x, during template argument substitution, when there is an
15967              attempt to create a reference to a reference type, reference
15968              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
15969
15970              "If a template-argument for a template-parameter T names a type
15971              that is a reference to a type A, an attempt to create the type
15972              'lvalue reference to cv T' creates the type 'lvalue reference to
15973              A,' while an attempt to create the type type rvalue reference to
15974              cv T' creates the type T"
15975           */
15976           r = cp_build_reference_type
15977               (TREE_TYPE (type),
15978                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
15979         else
15980           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
15981         r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
15982
15983         if (r != error_mark_node)
15984           /* Will this ever be needed for TYPE_..._TO values?  */
15985           layout_type (r);
15986
15987         return r;
15988       }
15989     case OFFSET_TYPE:
15990       {
15991         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
15992         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
15993           {
15994             /* [temp.deduct]
15995
15996                Type deduction may fail for any of the following
15997                reasons:
15998
15999                -- Attempting to create "pointer to member of T" when T
16000                   is not a class type.  */
16001             if (complain & tf_error)
16002               error ("creating pointer to member of non-class type %qT", r);
16003             return error_mark_node;
16004           }
16005         if (TYPE_REF_P (type))
16006           {
16007             if (complain & tf_error)
16008               error ("creating pointer to member reference type %qT", type);
16009             return error_mark_node;
16010           }
16011         if (VOID_TYPE_P (type))
16012           {
16013             if (complain & tf_error)
16014               error ("creating pointer to member of type void");
16015             return error_mark_node;
16016           }
16017         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
16018         if (TREE_CODE (type) == FUNCTION_TYPE)
16019           {
16020             /* The type of the implicit object parameter gets its
16021                cv-qualifiers from the FUNCTION_TYPE. */
16022             tree memptr;
16023             tree method_type
16024               = build_memfn_type (type, r, type_memfn_quals (type),
16025                                   type_memfn_rqual (type));
16026             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
16027             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
16028                                                  complain);
16029           }
16030         else
16031           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
16032                                                cp_type_quals (t),
16033                                                complain);
16034       }
16035     case FUNCTION_TYPE:
16036     case METHOD_TYPE:
16037       {
16038         tree fntype;
16039         tree specs;
16040         fntype = tsubst_function_type (t, args, complain, in_decl);
16041         if (fntype == error_mark_node)
16042           return error_mark_node;
16043
16044         /* Substitute the exception specification.  */
16045         specs = tsubst_exception_specification (t, args, complain, in_decl,
16046                                                 /*defer_ok*/fndecl_type);
16047         if (specs == error_mark_node)
16048           return error_mark_node;
16049         if (specs)
16050           fntype = build_exception_variant (fntype, specs);
16051         return fntype;
16052       }
16053     case ARRAY_TYPE:
16054       {
16055         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
16056         if (domain == error_mark_node)
16057           return error_mark_node;
16058
16059         /* As an optimization, we avoid regenerating the array type if
16060            it will obviously be the same as T.  */
16061         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
16062           return t;
16063
16064         /* These checks should match the ones in create_array_type_for_decl.
16065
16066            [temp.deduct]
16067
16068            The deduction may fail for any of the following reasons:
16069
16070            -- Attempting to create an array with an element type that
16071               is void, a function type, or a reference type, or [DR337]
16072               an abstract class type.  */
16073         if (VOID_TYPE_P (type)
16074             || TREE_CODE (type) == FUNCTION_TYPE
16075             || (TREE_CODE (type) == ARRAY_TYPE
16076                 && TYPE_DOMAIN (type) == NULL_TREE)
16077             || TYPE_REF_P (type))
16078           {
16079             if (complain & tf_error)
16080               error ("creating array of %qT", type);
16081             return error_mark_node;
16082           }
16083
16084         if (!verify_type_context (input_location, TCTX_ARRAY_ELEMENT, type,
16085                                   !(complain & tf_error)))
16086           return error_mark_node;
16087
16088         r = build_cplus_array_type (type, domain);
16089
16090         if (!valid_array_size_p (input_location, r, in_decl,
16091                                  (complain & tf_error)))
16092           return error_mark_node;
16093
16094         if (TYPE_USER_ALIGN (t))
16095           {
16096             SET_TYPE_ALIGN (r, TYPE_ALIGN (t));
16097             TYPE_USER_ALIGN (r) = 1;
16098           }
16099
16100         return r;
16101       }
16102
16103     case TYPENAME_TYPE:
16104       {
16105         tree ctx = TYPE_CONTEXT (t);
16106         if (TREE_CODE (ctx) == TYPE_PACK_EXPANSION)
16107           {
16108             ctx = tsubst_pack_expansion (ctx, args, complain, in_decl);
16109             if (ctx == error_mark_node
16110                 || TREE_VEC_LENGTH (ctx) > 1)
16111               return error_mark_node;
16112             if (TREE_VEC_LENGTH (ctx) == 0)
16113               {
16114                 if (complain & tf_error)
16115                   error ("%qD is instantiated for an empty pack",
16116                          TYPENAME_TYPE_FULLNAME (t));
16117                 return error_mark_node;
16118               }
16119             ctx = TREE_VEC_ELT (ctx, 0);
16120           }
16121         else
16122           ctx = tsubst_aggr_type (ctx, args, complain, in_decl,
16123                                   /*entering_scope=*/1);
16124         if (ctx == error_mark_node)
16125           return error_mark_node;
16126
16127         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
16128                               complain, in_decl);
16129         if (f == error_mark_node)
16130           return error_mark_node;
16131
16132         if (!MAYBE_CLASS_TYPE_P (ctx))
16133           {
16134             if (complain & tf_error)
16135               error ("%qT is not a class, struct, or union type", ctx);
16136             return error_mark_node;
16137           }
16138         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
16139           {
16140             /* Normally, make_typename_type does not require that the CTX
16141                have complete type in order to allow things like:
16142
16143                  template <class T> struct S { typename S<T>::X Y; };
16144
16145                But, such constructs have already been resolved by this
16146                point, so here CTX really should have complete type, unless
16147                it's a partial instantiation.  */
16148             if (!complete_type_or_maybe_complain (ctx, NULL_TREE, complain))
16149               return error_mark_node;
16150           }
16151
16152         f = make_typename_type (ctx, f, typename_type,
16153                                 complain | tf_keep_type_decl);
16154         if (f == error_mark_node)
16155           return f;
16156         if (TREE_CODE (f) == TYPE_DECL)
16157           {
16158             complain |= tf_ignore_bad_quals;
16159             f = TREE_TYPE (f);
16160           }
16161
16162         if (TREE_CODE (f) != TYPENAME_TYPE)
16163           {
16164             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
16165               {
16166                 if (complain & tf_error)
16167                   error ("%qT resolves to %qT, which is not an enumeration type",
16168                          t, f);
16169                 else
16170                   return error_mark_node;
16171               }
16172             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
16173               {
16174                 if (complain & tf_error)
16175                   error ("%qT resolves to %qT, which is not a class type",
16176                          t, f);
16177                 else
16178                   return error_mark_node;
16179               }
16180           }
16181
16182         return cp_build_qualified_type_real
16183           (f, cp_type_quals (f) | cp_type_quals (t), complain);
16184       }
16185
16186     case UNBOUND_CLASS_TEMPLATE:
16187       {
16188         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
16189                                      in_decl, /*entering_scope=*/1);
16190         tree name = TYPE_IDENTIFIER (t);
16191         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
16192
16193         if (ctx == error_mark_node || name == error_mark_node)
16194           return error_mark_node;
16195
16196         if (parm_list)
16197           parm_list = tsubst_template_parms (parm_list, args, complain);
16198         return make_unbound_class_template (ctx, name, parm_list, complain);
16199       }
16200
16201     case TYPEOF_TYPE:
16202       {
16203         tree type;
16204
16205         ++cp_unevaluated_operand;
16206         ++c_inhibit_evaluation_warnings;
16207
16208         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
16209                             complain, in_decl,
16210                             /*integral_constant_expression_p=*/false);
16211
16212         --cp_unevaluated_operand;
16213         --c_inhibit_evaluation_warnings;
16214
16215         type = finish_typeof (type);
16216         return cp_build_qualified_type_real (type,
16217                                              cp_type_quals (t)
16218                                              | cp_type_quals (type),
16219                                              complain);
16220       }
16221
16222     case DECLTYPE_TYPE:
16223       {
16224         tree type;
16225
16226         ++cp_unevaluated_operand;
16227         ++c_inhibit_evaluation_warnings;
16228
16229         type = tsubst_copy_and_build (DECLTYPE_TYPE_EXPR (t), args,
16230                                       complain|tf_decltype, in_decl,
16231                                       /*function_p*/false,
16232                                       /*integral_constant_expression*/false);
16233
16234         --cp_unevaluated_operand;
16235         --c_inhibit_evaluation_warnings;
16236
16237         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
16238           type = lambda_capture_field_type (type,
16239                                             false /*explicit_init*/,
16240                                             DECLTYPE_FOR_REF_CAPTURE (t));
16241         else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
16242           type = lambda_proxy_type (type);
16243         else
16244           {
16245             bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
16246             if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
16247                 && EXPR_P (type))
16248               /* In a template ~id could be either a complement expression
16249                  or an unqualified-id naming a destructor; if instantiating
16250                  it produces an expression, it's not an id-expression or
16251                  member access.  */
16252               id = false;
16253             type = finish_decltype_type (type, id, complain);
16254           }
16255         return cp_build_qualified_type_real (type,
16256                                              cp_type_quals (t)
16257                                              | cp_type_quals (type),
16258                                              complain | tf_ignore_bad_quals);
16259       }
16260
16261     case UNDERLYING_TYPE:
16262       {
16263         tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
16264                             complain, in_decl);
16265         return finish_underlying_type (type);
16266       }
16267
16268     case TYPE_ARGUMENT_PACK:
16269     case NONTYPE_ARGUMENT_PACK:
16270       return tsubst_argument_pack (t, args, complain, in_decl);
16271
16272     case VOID_CST:
16273     case INTEGER_CST:
16274     case REAL_CST:
16275     case STRING_CST:
16276     case PLUS_EXPR:
16277     case MINUS_EXPR:
16278     case NEGATE_EXPR:
16279     case NOP_EXPR:
16280     case INDIRECT_REF:
16281     case ADDR_EXPR:
16282     case CALL_EXPR:
16283     case ARRAY_REF:
16284     case SCOPE_REF:
16285       /* We should use one of the expression tsubsts for these codes.  */
16286       gcc_unreachable ();
16287
16288     default:
16289       sorry ("use of %qs in template", get_tree_code_name (code));
16290       return error_mark_node;
16291     }
16292 }
16293
16294 /* tsubst a BASELINK.  OBJECT_TYPE, if non-NULL, is the type of the
16295    expression on the left-hand side of the "." or "->" operator.  We
16296    only do the lookup if we had a dependent BASELINK.  Otherwise we
16297    adjust it onto the instantiated heirarchy.  */
16298
16299 static tree
16300 tsubst_baselink (tree baselink, tree object_type,
16301                  tree args, tsubst_flags_t complain, tree in_decl)
16302 {
16303   bool qualified_p = BASELINK_QUALIFIED_P (baselink);
16304   tree qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
16305   qualifying_scope = tsubst (qualifying_scope, args, complain, in_decl);
16306
16307   tree optype = BASELINK_OPTYPE (baselink);
16308   optype = tsubst (optype, args, complain, in_decl);
16309
16310   tree template_args = NULL_TREE;
16311   bool template_id_p = false;
16312   tree fns = BASELINK_FUNCTIONS (baselink);
16313   if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
16314     {
16315       template_id_p = true;
16316       template_args = TREE_OPERAND (fns, 1);
16317       fns = TREE_OPERAND (fns, 0);
16318       if (template_args)
16319         template_args = tsubst_template_args (template_args, args,
16320                                               complain, in_decl);
16321     }
16322
16323   tree binfo_type = BINFO_TYPE (BASELINK_BINFO (baselink));
16324   binfo_type = tsubst (binfo_type, args, complain, in_decl);
16325   bool dependent_p = binfo_type != BINFO_TYPE (BASELINK_BINFO (baselink));
16326
16327   if (dependent_p)
16328     {
16329       tree name = OVL_NAME (fns);
16330       if (IDENTIFIER_CONV_OP_P (name))
16331         name = make_conv_op_name (optype);
16332
16333       /* See maybe_dependent_member_ref.  */
16334       if (dependent_scope_p (qualifying_scope))
16335         {
16336           if (template_id_p)
16337             name = build2 (TEMPLATE_ID_EXPR, unknown_type_node, name,
16338                            template_args);
16339           return build_qualified_name (NULL_TREE, qualifying_scope, name,
16340                                        /* ::template */false);
16341         }
16342
16343       if (name == complete_dtor_identifier)
16344         /* Treat as-if non-dependent below.  */
16345         dependent_p = false;
16346
16347       baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1,
16348                                   complain);
16349       if (!baselink)
16350         {
16351           if ((complain & tf_error)
16352               && constructor_name_p (name, qualifying_scope))
16353             error ("cannot call constructor %<%T::%D%> directly",
16354                    qualifying_scope, name);
16355           return error_mark_node;
16356         }
16357
16358       if (BASELINK_P (baselink))
16359         fns = BASELINK_FUNCTIONS (baselink);
16360     }
16361   else
16362     /* We're going to overwrite pieces below, make a duplicate.  */
16363     baselink = copy_node (baselink);
16364
16365   /* If lookup found a single function, mark it as used at this point.
16366      (If lookup found multiple functions the one selected later by
16367      overload resolution will be marked as used at that point.)  */
16368   if (!template_id_p && !really_overloaded_fn (fns))
16369     {
16370       tree fn = OVL_FIRST (fns);
16371       bool ok = mark_used (fn, complain);
16372       if (!ok && !(complain & tf_error))
16373         return error_mark_node;
16374       if (ok && BASELINK_P (baselink))
16375         /* We might have instantiated an auto function.  */
16376         TREE_TYPE (baselink) = TREE_TYPE (fn);
16377     }
16378
16379   if (BASELINK_P (baselink))
16380     {
16381       /* Add back the template arguments, if present.  */
16382       if (template_id_p)
16383         BASELINK_FUNCTIONS (baselink)
16384           = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, template_args);
16385
16386       /* Update the conversion operator type.  */
16387       BASELINK_OPTYPE (baselink) = optype;
16388     }
16389
16390   if (!object_type)
16391     object_type = current_class_type;
16392
16393   if (qualified_p || !dependent_p)
16394     {
16395       baselink = adjust_result_of_qualified_name_lookup (baselink,
16396                                                          qualifying_scope,
16397                                                          object_type);
16398       if (!qualified_p)
16399         /* We need to call adjust_result_of_qualified_name_lookup in case the
16400            destructor names a base class, but we unset BASELINK_QUALIFIED_P
16401            so that we still get virtual function binding.  */
16402         BASELINK_QUALIFIED_P (baselink) = false;
16403     }
16404
16405   return baselink;
16406 }
16407
16408 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
16409    true if the qualified-id will be a postfix-expression in-and-of
16410    itself; false if more of the postfix-expression follows the
16411    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
16412    of "&".  */
16413
16414 static tree
16415 tsubst_qualified_id (tree qualified_id, tree args,
16416                      tsubst_flags_t complain, tree in_decl,
16417                      bool done, bool address_p)
16418 {
16419   tree expr;
16420   tree scope;
16421   tree name;
16422   bool is_template;
16423   tree template_args;
16424   location_t loc = EXPR_LOCATION (qualified_id);
16425
16426   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
16427
16428   /* Figure out what name to look up.  */
16429   name = TREE_OPERAND (qualified_id, 1);
16430   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
16431     {
16432       is_template = true;
16433       template_args = TREE_OPERAND (name, 1);
16434       if (template_args)
16435         template_args = tsubst_template_args (template_args, args,
16436                                               complain, in_decl);
16437       if (template_args == error_mark_node)
16438         return error_mark_node;
16439       name = TREE_OPERAND (name, 0);
16440     }
16441   else
16442     {
16443       is_template = false;
16444       template_args = NULL_TREE;
16445     }
16446
16447   /* Substitute into the qualifying scope.  When there are no ARGS, we
16448      are just trying to simplify a non-dependent expression.  In that
16449      case the qualifying scope may be dependent, and, in any case,
16450      substituting will not help.  */
16451   scope = TREE_OPERAND (qualified_id, 0);
16452   if (args)
16453     {
16454       scope = tsubst (scope, args, complain, in_decl);
16455       expr = tsubst_copy (name, args, complain, in_decl);
16456     }
16457   else
16458     expr = name;
16459
16460   if (dependent_scope_p (scope))
16461     {
16462       if (is_template)
16463         expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr, template_args);
16464       tree r = build_qualified_name (NULL_TREE, scope, expr,
16465                                      QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
16466       REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (qualified_id);
16467       return r;
16468     }
16469
16470   if (!BASELINK_P (name) && !DECL_P (expr))
16471     {
16472       if (TREE_CODE (expr) == BIT_NOT_EXPR)
16473         {
16474           /* A BIT_NOT_EXPR is used to represent a destructor.  */
16475           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
16476             {
16477               error ("qualifying type %qT does not match destructor name ~%qT",
16478                      scope, TREE_OPERAND (expr, 0));
16479               expr = error_mark_node;
16480             }
16481           else
16482             expr = lookup_qualified_name (scope, complete_dtor_identifier,
16483                                           LOOK_want::NORMAL, false);
16484         }
16485       else
16486         expr = lookup_qualified_name (scope, expr, LOOK_want::NORMAL, false);
16487       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
16488                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
16489         {
16490           if (complain & tf_error)
16491             {
16492               error ("dependent-name %qE is parsed as a non-type, but "
16493                      "instantiation yields a type", qualified_id);
16494               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
16495             }
16496           return error_mark_node;
16497         }
16498     }
16499
16500   if (DECL_P (expr))
16501     {
16502       if (!check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
16503                                                 scope, complain))
16504         return error_mark_node;
16505       /* Remember that there was a reference to this entity.  */
16506       if (!mark_used (expr, complain) && !(complain & tf_error))
16507         return error_mark_node;
16508     }
16509
16510   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
16511     {
16512       if (complain & tf_error)
16513         qualified_name_lookup_error (scope,
16514                                      TREE_OPERAND (qualified_id, 1),
16515                                      expr, input_location);
16516       return error_mark_node;
16517     }
16518
16519   if (is_template)
16520     {
16521       /* We may be repeating a check already done during parsing, but
16522          if it was well-formed and passed then, it will pass again
16523          now, and if it didn't, we wouldn't have got here.  The case
16524          we want to catch is when we couldn't tell then, and can now,
16525          namely when templ prior to substitution was an
16526          identifier.  */
16527       if (flag_concepts && check_auto_in_tmpl_args (expr, template_args))
16528         return error_mark_node;
16529
16530       if (variable_template_p (expr))
16531         expr = lookup_and_finish_template_variable (expr, template_args,
16532                                                     complain);
16533       else
16534         expr = lookup_template_function (expr, template_args);
16535     }
16536
16537   if (expr == error_mark_node && complain & tf_error)
16538     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
16539                                  expr, input_location);
16540   else if (TYPE_P (scope))
16541     {
16542       expr = (adjust_result_of_qualified_name_lookup
16543               (expr, scope, current_nonlambda_class_type ()));
16544       expr = (finish_qualified_id_expr
16545               (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
16546                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
16547                /*template_arg_p=*/false, complain));
16548     }
16549
16550   /* Expressions do not generally have reference type.  */
16551   if (TREE_CODE (expr) != SCOPE_REF
16552       /* However, if we're about to form a pointer-to-member, we just
16553          want the referenced member referenced.  */
16554       && TREE_CODE (expr) != OFFSET_REF)
16555     expr = convert_from_reference (expr);
16556
16557   if (REF_PARENTHESIZED_P (qualified_id))
16558     expr = force_paren_expr (expr);
16559
16560   expr = maybe_wrap_with_location (expr, loc);
16561
16562   return expr;
16563 }
16564
16565 /* tsubst the initializer for a VAR_DECL.  INIT is the unsubstituted
16566    initializer, DECL is the substituted VAR_DECL.  Other arguments are as
16567    for tsubst.  */
16568
16569 static tree
16570 tsubst_init (tree init, tree decl, tree args,
16571              tsubst_flags_t complain, tree in_decl)
16572 {
16573   if (!init)
16574     return NULL_TREE;
16575
16576   init = tsubst_expr (init, args, complain, in_decl, false);
16577
16578   tree type = TREE_TYPE (decl);
16579
16580   if (!init && type != error_mark_node)
16581     {
16582       if (tree auto_node = type_uses_auto (type))
16583         {
16584           if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
16585             {
16586               if (complain & tf_error)
16587                 error ("initializer for %q#D expands to an empty list "
16588                        "of expressions", decl);
16589               return error_mark_node;
16590             }
16591         }
16592       else if (!dependent_type_p (type))
16593         {
16594           /* If we had an initializer but it
16595              instantiated to nothing,
16596              value-initialize the object.  This will
16597              only occur when the initializer was a
16598              pack expansion where the parameter packs
16599              used in that expansion were of length
16600              zero.  */
16601           init = build_value_init (type, complain);
16602           if (TREE_CODE (init) == AGGR_INIT_EXPR)
16603             init = get_target_expr_sfinae (init, complain);
16604           if (TREE_CODE (init) == TARGET_EXPR)
16605             TARGET_EXPR_DIRECT_INIT_P (init) = true;
16606         }
16607     }
16608
16609   return init;
16610 }
16611
16612 /* If T is a reference to a dependent member of the current instantiation C and
16613    we are trying to refer to that member in a partial instantiation of C,
16614    return a SCOPE_REF; otherwise, return NULL_TREE.
16615
16616    This can happen when forming a C++17 deduction guide, as in PR96199.  */
16617
16618 static tree
16619 maybe_dependent_member_ref (tree t, tree args, tsubst_flags_t complain,
16620                             tree in_decl)
16621 {
16622   if (cxx_dialect < cxx17)
16623     return NULL_TREE;
16624
16625   tree ctx = context_for_name_lookup (t);
16626   if (!CLASS_TYPE_P (ctx))
16627     return NULL_TREE;
16628
16629   ctx = tsubst (ctx, args, complain, in_decl);
16630   if (dependent_scope_p (ctx))
16631     return build_qualified_name (NULL_TREE, ctx, DECL_NAME (t),
16632                                  /*template_p=*/false);
16633
16634   return NULL_TREE;
16635 }
16636
16637 /* Like tsubst, but deals with expressions.  This function just replaces
16638    template parms; to finish processing the resultant expression, use
16639    tsubst_copy_and_build or tsubst_expr.  */
16640
16641 static tree
16642 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
16643 {
16644   enum tree_code code;
16645   tree r;
16646
16647   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
16648     return t;
16649
16650   code = TREE_CODE (t);
16651
16652   switch (code)
16653     {
16654     case PARM_DECL:
16655       r = retrieve_local_specialization (t);
16656
16657       if (r == NULL_TREE)
16658         {
16659           /* We get here for a use of 'this' in an NSDMI.  */
16660           if (DECL_NAME (t) == this_identifier && current_class_ptr)
16661             return current_class_ptr;
16662
16663           /* This can happen for a parameter name used later in a function
16664              declaration (such as in a late-specified return type).  Just
16665              make a dummy decl, since it's only used for its type.  */
16666           gcc_assert (cp_unevaluated_operand != 0);
16667           r = tsubst_decl (t, args, complain);
16668           /* Give it the template pattern as its context; its true context
16669              hasn't been instantiated yet and this is good enough for
16670              mangling.  */
16671           DECL_CONTEXT (r) = DECL_CONTEXT (t);
16672         }
16673
16674       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
16675         r = argument_pack_select_arg (r);
16676       if (!mark_used (r, complain) && !(complain & tf_error))
16677         return error_mark_node;
16678       return r;
16679
16680     case CONST_DECL:
16681       {
16682         tree enum_type;
16683         tree v;
16684
16685         if (DECL_TEMPLATE_PARM_P (t))
16686           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
16687         /* There is no need to substitute into namespace-scope
16688            enumerators.  */
16689         if (DECL_NAMESPACE_SCOPE_P (t))
16690           return t;
16691         /* If ARGS is NULL, then T is known to be non-dependent.  */
16692         if (args == NULL_TREE)
16693           return scalar_constant_value (t);
16694
16695         if (tree ref = maybe_dependent_member_ref (t, args, complain, in_decl))
16696           return ref;
16697
16698         /* Unfortunately, we cannot just call lookup_name here.
16699            Consider:
16700
16701              template <int I> int f() {
16702              enum E { a = I };
16703              struct S { void g() { E e = a; } };
16704              };
16705
16706            When we instantiate f<7>::S::g(), say, lookup_name is not
16707            clever enough to find f<7>::a.  */
16708         enum_type
16709           = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
16710                               /*entering_scope=*/0);
16711
16712         for (v = TYPE_VALUES (enum_type);
16713              v != NULL_TREE;
16714              v = TREE_CHAIN (v))
16715           if (TREE_PURPOSE (v) == DECL_NAME (t))
16716             return TREE_VALUE (v);
16717
16718           /* We didn't find the name.  That should never happen; if
16719              name-lookup found it during preliminary parsing, we
16720              should find it again here during instantiation.  */
16721         gcc_unreachable ();
16722       }
16723       return t;
16724
16725     case FIELD_DECL:
16726       if (DECL_CONTEXT (t))
16727         {
16728           tree ctx;
16729
16730           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
16731                                   /*entering_scope=*/1);
16732           if (ctx != DECL_CONTEXT (t))
16733             {
16734               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
16735               if (!r)
16736                 {
16737                   if (complain & tf_error)
16738                     error ("using invalid field %qD", t);
16739                   return error_mark_node;
16740                 }
16741               return r;
16742             }
16743         }
16744
16745       return t;
16746
16747     case VAR_DECL:
16748       if (tree ref = maybe_dependent_member_ref (t, args, complain, in_decl))
16749         return ref;
16750       gcc_fallthrough();
16751     case FUNCTION_DECL:
16752       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
16753         r = tsubst (t, args, complain, in_decl);
16754       else if (DECL_LOCAL_DECL_P (t))
16755         {
16756           /* Local specialization will usually have been created when
16757              we instantiated the DECL_EXPR_DECL. */
16758           r = retrieve_local_specialization (t);
16759           if (!r)
16760             {
16761               /* We're in a generic lambda referencing a local extern
16762                  from an outer block-scope of a non-template.  */
16763               gcc_checking_assert (LAMBDA_FUNCTION_P (current_function_decl));
16764               r = t;
16765             }
16766         }
16767       else if (local_variable_p (t)
16768                && uses_template_parms (DECL_CONTEXT (t)))
16769         {
16770           r = retrieve_local_specialization (t);
16771           if (r == NULL_TREE)
16772             {
16773               /* First try name lookup to find the instantiation.  */
16774               r = lookup_name (DECL_NAME (t));
16775               if (r)
16776                 {
16777                   if (!VAR_P (r))
16778                     {
16779                       /* During error-recovery we may find a non-variable,
16780                          even an OVERLOAD: just bail out and avoid ICEs and
16781                          duplicate diagnostics (c++/62207).  */
16782                       gcc_assert (seen_error ());
16783                       return error_mark_node;
16784                     }
16785                   if (!is_capture_proxy (r))
16786                     {
16787                       /* Make sure the one we found is the one we want.  */
16788                       tree ctx = enclosing_instantiation_of (DECL_CONTEXT (t));
16789                       if (ctx != DECL_CONTEXT (r))
16790                         r = NULL_TREE;
16791                     }
16792                 }
16793
16794               if (r)
16795                 /* OK */;
16796               else
16797                 {
16798                   /* This can happen for a variable used in a
16799                      late-specified return type of a local lambda, or for a
16800                      local static or constant.  Building a new VAR_DECL
16801                      should be OK in all those cases.  */
16802                   r = tsubst_decl (t, args, complain);
16803                   if (local_specializations)
16804                     /* Avoid infinite recursion (79640).  */
16805                     register_local_specialization (r, t);
16806                   if (decl_maybe_constant_var_p (r))
16807                     {
16808                       /* We can't call cp_finish_decl, so handle the
16809                          initializer by hand.  */
16810                       tree init = tsubst_init (DECL_INITIAL (t), r, args,
16811                                                complain, in_decl);
16812                       if (!processing_template_decl)
16813                         init = maybe_constant_init (init);
16814                       if (processing_template_decl
16815                           ? potential_constant_expression (init)
16816                           : reduced_constant_expression_p (init))
16817                         DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
16818                           = TREE_CONSTANT (r) = true;
16819                       DECL_INITIAL (r) = init;
16820                       if (tree auto_node = type_uses_auto (TREE_TYPE (r)))
16821                         TREE_TYPE (r)
16822                           = do_auto_deduction (TREE_TYPE (r), init, auto_node,
16823                                                complain, adc_variable_type);
16824                     }
16825                   gcc_assert (cp_unevaluated_operand || TREE_STATIC (r)
16826                               || decl_constant_var_p (r)
16827                               || seen_error ());
16828                   if (!processing_template_decl
16829                       && !TREE_STATIC (r))
16830                     r = process_outer_var_ref (r, complain);
16831                 }
16832               /* Remember this for subsequent uses.  */
16833               if (local_specializations)
16834                 register_local_specialization (r, t);
16835             }
16836           if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
16837             r = argument_pack_select_arg (r);
16838         }
16839       else
16840         r = t;
16841       if (!mark_used (r, complain))
16842         return error_mark_node;
16843       return r;
16844
16845     case NAMESPACE_DECL:
16846       return t;
16847
16848     case OVERLOAD:
16849       return t;
16850
16851     case BASELINK:
16852       return tsubst_baselink (t, current_nonlambda_class_type (),
16853                               args, complain, in_decl);
16854
16855     case TEMPLATE_DECL:
16856       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
16857         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
16858                        args, complain, in_decl);
16859       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
16860         return tsubst (t, args, complain, in_decl);
16861       else if (DECL_CLASS_SCOPE_P (t)
16862                && uses_template_parms (DECL_CONTEXT (t)))
16863         {
16864           /* Template template argument like the following example need
16865              special treatment:
16866
16867                template <template <class> class TT> struct C {};
16868                template <class T> struct D {
16869                  template <class U> struct E {};
16870                  C<E> c;                                // #1
16871                };
16872                D<int> d;                                // #2
16873
16874              We are processing the template argument `E' in #1 for
16875              the template instantiation #2.  Originally, `E' is a
16876              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
16877              have to substitute this with one having context `D<int>'.  */
16878
16879           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
16880           if (dependent_scope_p (context))
16881             {
16882               /* When rewriting a constructor into a deduction guide, a
16883                  non-dependent name can become dependent, so memtmpl<args>
16884                  becomes context::template memtmpl<args>.  */
16885               tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16886               return build_qualified_name (type, context, DECL_NAME (t),
16887                                            /*template*/true);
16888             }
16889           return lookup_field (context, DECL_NAME(t), 0, false);
16890         }
16891       else
16892         /* Ordinary template template argument.  */
16893         return t;
16894
16895     case NON_LVALUE_EXPR:
16896     case VIEW_CONVERT_EXPR:
16897         {
16898           /* Handle location wrappers by substituting the wrapped node
16899              first, *then* reusing the resulting type.  Doing the type
16900              first ensures that we handle template parameters and
16901              parameter pack expansions.  */
16902           if (location_wrapper_p (t))
16903             {
16904               tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args,
16905                                       complain, in_decl);
16906               return maybe_wrap_with_location (op0, EXPR_LOCATION (t));
16907             }
16908           tree op = TREE_OPERAND (t, 0);
16909           if (code == VIEW_CONVERT_EXPR
16910               && TREE_CODE (op) == TEMPLATE_PARM_INDEX)
16911             {
16912               /* Wrapper to make a C++20 template parameter object const.  */
16913               op = tsubst_copy (op, args, complain, in_decl);
16914               if (!CP_TYPE_CONST_P (TREE_TYPE (op)))
16915                 {
16916                   /* The template argument is not const, presumably because
16917                      it is still dependent, and so not the const template parm
16918                      object.  */
16919                   tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16920                   gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
16921                                        (type, TREE_TYPE (op)));
16922                   if (TREE_CODE (op) == CONSTRUCTOR
16923                       || TREE_CODE (op) == IMPLICIT_CONV_EXPR)
16924                     {
16925                       /* Don't add a wrapper to these.  */
16926                       op = copy_node (op);
16927                       TREE_TYPE (op) = type;
16928                     }
16929                   else
16930                     /* Do add a wrapper otherwise (in particular, if op is
16931                        another TEMPLATE_PARM_INDEX).  */
16932                     op = build1 (code, type, op);
16933                 }
16934               return op;
16935             }
16936           /* force_paren_expr can also create a VIEW_CONVERT_EXPR.  */
16937           else if (code == VIEW_CONVERT_EXPR && REF_PARENTHESIZED_P (t))
16938             {
16939               op = tsubst_copy (op, args, complain, in_decl);
16940               op = build1 (code, TREE_TYPE (op), op);
16941               REF_PARENTHESIZED_P (op) = true;
16942               return op;
16943             }
16944           /* We shouldn't see any other uses of these in templates.  */
16945           gcc_unreachable ();
16946         }
16947
16948     case CAST_EXPR:
16949     case REINTERPRET_CAST_EXPR:
16950     case CONST_CAST_EXPR:
16951     case STATIC_CAST_EXPR:
16952     case DYNAMIC_CAST_EXPR:
16953     case IMPLICIT_CONV_EXPR:
16954     case CONVERT_EXPR:
16955     case NOP_EXPR:
16956       {
16957         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16958         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16959         return build1 (code, type, op0);
16960       }
16961
16962     case BIT_CAST_EXPR:
16963       {
16964         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16965         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16966         r = build_min (BIT_CAST_EXPR, type, op0);
16967         SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
16968         return r;
16969       }
16970
16971     case SIZEOF_EXPR:
16972       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
16973           || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
16974         {
16975           tree expanded, op = TREE_OPERAND (t, 0);
16976           int len = 0;
16977
16978           if (SIZEOF_EXPR_TYPE_P (t))
16979             op = TREE_TYPE (op);
16980
16981           ++cp_unevaluated_operand;
16982           ++c_inhibit_evaluation_warnings;
16983           /* We only want to compute the number of arguments.  */
16984           if (PACK_EXPANSION_P (op))
16985             expanded = tsubst_pack_expansion (op, args, complain, in_decl);
16986           else
16987             expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
16988                                              args, complain, in_decl);
16989           --cp_unevaluated_operand;
16990           --c_inhibit_evaluation_warnings;
16991
16992           if (TREE_CODE (expanded) == TREE_VEC)
16993             {
16994               len = TREE_VEC_LENGTH (expanded);
16995               /* Set TREE_USED for the benefit of -Wunused.  */
16996               for (int i = 0; i < len; i++)
16997                 if (DECL_P (TREE_VEC_ELT (expanded, i)))
16998                   TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
16999             }
17000
17001           if (expanded == error_mark_node)
17002             return error_mark_node;
17003           else if (PACK_EXPANSION_P (expanded)
17004                    || (TREE_CODE (expanded) == TREE_VEC
17005                        && pack_expansion_args_count (expanded)))
17006
17007             {
17008               if (PACK_EXPANSION_P (expanded))
17009                 /* OK.  */;
17010               else if (TREE_VEC_LENGTH (expanded) == 1)
17011                 expanded = TREE_VEC_ELT (expanded, 0);
17012               else
17013                 expanded = make_argument_pack (expanded);
17014
17015               if (TYPE_P (expanded))
17016                 return cxx_sizeof_or_alignof_type (input_location,
17017                                                    expanded, SIZEOF_EXPR,
17018                                                    false,
17019                                                    complain & tf_error);
17020               else
17021                 return cxx_sizeof_or_alignof_expr (input_location,
17022                                                    expanded, SIZEOF_EXPR,
17023                                                    false,
17024                                                    complain & tf_error);
17025             }
17026           else
17027             return build_int_cst (size_type_node, len);
17028         }
17029       if (SIZEOF_EXPR_TYPE_P (t))
17030         {
17031           r = tsubst (TREE_TYPE (TREE_OPERAND (t, 0)),
17032                       args, complain, in_decl);
17033           r = build1 (NOP_EXPR, r, error_mark_node);
17034           r = build1 (SIZEOF_EXPR,
17035                       tsubst (TREE_TYPE (t), args, complain, in_decl), r);
17036           SIZEOF_EXPR_TYPE_P (r) = 1;
17037           return r;
17038         }
17039       /* Fall through */
17040
17041     case INDIRECT_REF:
17042     case NEGATE_EXPR:
17043     case TRUTH_NOT_EXPR:
17044     case BIT_NOT_EXPR:
17045     case ADDR_EXPR:
17046     case UNARY_PLUS_EXPR:      /* Unary + */
17047     case ALIGNOF_EXPR:
17048     case AT_ENCODE_EXPR:
17049     case ARROW_EXPR:
17050     case THROW_EXPR:
17051     case TYPEID_EXPR:
17052     case REALPART_EXPR:
17053     case IMAGPART_EXPR:
17054     case PAREN_EXPR:
17055       {
17056         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17057         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17058         r = build1 (code, type, op0);
17059         if (code == ALIGNOF_EXPR)
17060           ALIGNOF_EXPR_STD_P (r) = ALIGNOF_EXPR_STD_P (t);
17061         return r;
17062       }
17063
17064     case COMPONENT_REF:
17065       {
17066         tree object;
17067         tree name;
17068
17069         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17070         name = TREE_OPERAND (t, 1);
17071         if (TREE_CODE (name) == BIT_NOT_EXPR)
17072           {
17073             name = tsubst_copy (TREE_OPERAND (name, 0), args,
17074                                 complain, in_decl);
17075             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
17076           }
17077         else if (TREE_CODE (name) == SCOPE_REF
17078                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
17079           {
17080             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
17081                                      complain, in_decl);
17082             name = TREE_OPERAND (name, 1);
17083             name = tsubst_copy (TREE_OPERAND (name, 0), args,
17084                                 complain, in_decl);
17085             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
17086             name = build_qualified_name (/*type=*/NULL_TREE,
17087                                          base, name,
17088                                          /*template_p=*/false);
17089           }
17090         else if (BASELINK_P (name))
17091           name = tsubst_baselink (name,
17092                                   non_reference (TREE_TYPE (object)),
17093                                   args, complain,
17094                                   in_decl);
17095         else
17096           name = tsubst_copy (name, args, complain, in_decl);
17097         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
17098       }
17099
17100     case PLUS_EXPR:
17101     case MINUS_EXPR:
17102     case MULT_EXPR:
17103     case TRUNC_DIV_EXPR:
17104     case CEIL_DIV_EXPR:
17105     case FLOOR_DIV_EXPR:
17106     case ROUND_DIV_EXPR:
17107     case EXACT_DIV_EXPR:
17108     case BIT_AND_EXPR:
17109     case BIT_IOR_EXPR:
17110     case BIT_XOR_EXPR:
17111     case TRUNC_MOD_EXPR:
17112     case FLOOR_MOD_EXPR:
17113     case TRUTH_ANDIF_EXPR:
17114     case TRUTH_ORIF_EXPR:
17115     case TRUTH_AND_EXPR:
17116     case TRUTH_OR_EXPR:
17117     case RSHIFT_EXPR:
17118     case LSHIFT_EXPR:
17119     case EQ_EXPR:
17120     case NE_EXPR:
17121     case MAX_EXPR:
17122     case MIN_EXPR:
17123     case LE_EXPR:
17124     case GE_EXPR:
17125     case LT_EXPR:
17126     case GT_EXPR:
17127     case COMPOUND_EXPR:
17128     case DOTSTAR_EXPR:
17129     case MEMBER_REF:
17130     case PREDECREMENT_EXPR:
17131     case PREINCREMENT_EXPR:
17132     case POSTDECREMENT_EXPR:
17133     case POSTINCREMENT_EXPR:
17134       {
17135         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17136         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17137         return build_nt (code, op0, op1);
17138       }
17139
17140     case SCOPE_REF:
17141       {
17142         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17143         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17144         return build_qualified_name (/*type=*/NULL_TREE, op0, op1,
17145                                      QUALIFIED_NAME_IS_TEMPLATE (t));
17146       }
17147
17148     case ARRAY_REF:
17149       {
17150         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17151         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17152         return build_nt (ARRAY_REF, op0, op1, NULL_TREE, NULL_TREE);
17153       }
17154
17155     case CALL_EXPR:
17156       {
17157         int n = VL_EXP_OPERAND_LENGTH (t);
17158         tree result = build_vl_exp (CALL_EXPR, n);
17159         int i;
17160         for (i = 0; i < n; i++)
17161           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
17162                                              complain, in_decl);
17163         return result;
17164       }
17165
17166     case COND_EXPR:
17167     case MODOP_EXPR:
17168     case PSEUDO_DTOR_EXPR:
17169     case VEC_PERM_EXPR:
17170       {
17171         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17172         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17173         tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
17174         r = build_nt (code, op0, op1, op2);
17175         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
17176         return r;
17177       }
17178
17179     case NEW_EXPR:
17180       {
17181         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17182         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17183         tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
17184         r = build_nt (code, op0, op1, op2);
17185         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
17186         return r;
17187       }
17188
17189     case DELETE_EXPR:
17190       {
17191         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17192         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17193         r = build_nt (code, op0, op1);
17194         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
17195         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
17196         return r;
17197       }
17198
17199     case TEMPLATE_ID_EXPR:
17200       {
17201         /* Substituted template arguments */
17202         tree tmpl = TREE_OPERAND (t, 0);
17203         tree targs = TREE_OPERAND (t, 1);
17204
17205         tmpl = tsubst_copy (tmpl, args, complain, in_decl);
17206         if (targs)
17207           targs = tsubst_template_args (targs, args, complain, in_decl);
17208
17209         if (variable_template_p (tmpl))
17210           return lookup_template_variable (tmpl, targs);
17211         else
17212           return lookup_template_function (tmpl, targs);
17213       }
17214
17215     case TREE_LIST:
17216       {
17217         tree purpose, value, chain;
17218
17219         if (t == void_list_node)
17220           return t;
17221
17222         purpose = TREE_PURPOSE (t);
17223         if (purpose)
17224           purpose = tsubst_copy (purpose, args, complain, in_decl);
17225         value = TREE_VALUE (t);
17226         if (value)
17227           value = tsubst_copy (value, args, complain, in_decl);
17228         chain = TREE_CHAIN (t);
17229         if (chain && chain != void_type_node)
17230           chain = tsubst_copy (chain, args, complain, in_decl);
17231         if (purpose == TREE_PURPOSE (t)
17232             && value == TREE_VALUE (t)
17233             && chain == TREE_CHAIN (t))
17234           return t;
17235         return tree_cons (purpose, value, chain);
17236       }
17237
17238     case RECORD_TYPE:
17239     case UNION_TYPE:
17240     case ENUMERAL_TYPE:
17241     case INTEGER_TYPE:
17242     case TEMPLATE_TYPE_PARM:
17243     case TEMPLATE_TEMPLATE_PARM:
17244     case BOUND_TEMPLATE_TEMPLATE_PARM:
17245     case TEMPLATE_PARM_INDEX:
17246     case POINTER_TYPE:
17247     case REFERENCE_TYPE:
17248     case OFFSET_TYPE:
17249     case FUNCTION_TYPE:
17250     case METHOD_TYPE:
17251     case ARRAY_TYPE:
17252     case TYPENAME_TYPE:
17253     case UNBOUND_CLASS_TEMPLATE:
17254     case TYPEOF_TYPE:
17255     case DECLTYPE_TYPE:
17256     case TYPE_DECL:
17257       return tsubst (t, args, complain, in_decl);
17258
17259     case USING_DECL:
17260       t = DECL_NAME (t);
17261       /* Fall through.  */
17262     case IDENTIFIER_NODE:
17263       if (IDENTIFIER_CONV_OP_P (t))
17264         {
17265           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17266           return make_conv_op_name (new_type);
17267         }
17268       else
17269         return t;
17270
17271     case CONSTRUCTOR:
17272       /* This is handled by tsubst_copy_and_build.  */
17273       gcc_unreachable ();
17274
17275     case VA_ARG_EXPR:
17276       {
17277         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17278         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17279         return build_x_va_arg (EXPR_LOCATION (t), op0, type);
17280       }
17281
17282     case CLEANUP_POINT_EXPR:
17283       /* We shouldn't have built any of these during initial template
17284          generation.  Instead, they should be built during instantiation
17285          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
17286       gcc_unreachable ();
17287
17288     case OFFSET_REF:
17289       {
17290         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17291         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17292         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17293         r = build2 (code, type, op0, op1);
17294         PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
17295         if (!mark_used (TREE_OPERAND (r, 1), complain)
17296             && !(complain & tf_error))
17297           return error_mark_node;
17298         return r;
17299       }
17300
17301     case EXPR_PACK_EXPANSION:
17302       error ("invalid use of pack expansion expression");
17303       return error_mark_node;
17304
17305     case NONTYPE_ARGUMENT_PACK:
17306       error ("use %<...%> to expand argument pack");
17307       return error_mark_node;
17308
17309     case VOID_CST:
17310       gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
17311       return t;
17312
17313     case INTEGER_CST:
17314     case REAL_CST:
17315     case COMPLEX_CST:
17316       {
17317         /* Instantiate any typedefs in the type.  */
17318         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17319         r = fold_convert (type, t);
17320         gcc_assert (TREE_CODE (r) == code);
17321         return r;
17322       }
17323
17324     case STRING_CST:
17325       {
17326         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17327         r = t;
17328         if (type != TREE_TYPE (t))
17329           {
17330             r = copy_node (t);
17331             TREE_TYPE (r) = type;
17332           }
17333         return r;
17334       }
17335
17336     case PTRMEM_CST:
17337       /* These can sometimes show up in a partial instantiation, but never
17338          involve template parms.  */
17339       gcc_assert (!uses_template_parms (t));
17340       return t;
17341
17342     case UNARY_LEFT_FOLD_EXPR:
17343       return tsubst_unary_left_fold (t, args, complain, in_decl);
17344     case UNARY_RIGHT_FOLD_EXPR:
17345       return tsubst_unary_right_fold (t, args, complain, in_decl);
17346     case BINARY_LEFT_FOLD_EXPR:
17347       return tsubst_binary_left_fold (t, args, complain, in_decl);
17348     case BINARY_RIGHT_FOLD_EXPR:
17349       return tsubst_binary_right_fold (t, args, complain, in_decl);
17350     case PREDICT_EXPR:
17351       return t;
17352
17353     case DEBUG_BEGIN_STMT:
17354       /* ??? There's no point in copying it for now, but maybe some
17355          day it will contain more information, such as a pointer back
17356          to the containing function, inlined copy or so.  */
17357       return t;
17358
17359     case CO_AWAIT_EXPR:
17360       return tsubst_expr (t, args, complain, in_decl,
17361                           /*integral_constant_expression_p=*/false);
17362       break;
17363
17364     default:
17365       /* We shouldn't get here, but keep going if !flag_checking.  */
17366       if (flag_checking)
17367         gcc_unreachable ();
17368       return t;
17369     }
17370 }
17371
17372 /* Helper function for tsubst_omp_clauses, used for instantiation of
17373    OMP_CLAUSE_DECL of clauses.  */
17374
17375 static tree
17376 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
17377                         tree in_decl, tree *iterator_cache)
17378 {
17379   if (decl == NULL_TREE)
17380     return NULL_TREE;
17381
17382   /* Handle OpenMP iterators.  */
17383   if (TREE_CODE (decl) == TREE_LIST
17384       && TREE_PURPOSE (decl)
17385       && TREE_CODE (TREE_PURPOSE (decl)) == TREE_VEC)
17386     {
17387       tree ret;
17388       if (iterator_cache[0] == TREE_PURPOSE (decl))
17389         ret = iterator_cache[1];
17390       else
17391         {
17392           tree *tp = &ret;
17393           begin_scope (sk_omp, NULL);
17394           for (tree it = TREE_PURPOSE (decl); it; it = TREE_CHAIN (it))
17395             {
17396               *tp = copy_node (it);
17397               TREE_VEC_ELT (*tp, 0)
17398                 = tsubst_decl (TREE_VEC_ELT (it, 0), args, complain);
17399               TREE_VEC_ELT (*tp, 1)
17400                 = tsubst_expr (TREE_VEC_ELT (it, 1), args, complain, in_decl,
17401                                /*integral_constant_expression_p=*/false);
17402               TREE_VEC_ELT (*tp, 2)
17403                 = tsubst_expr (TREE_VEC_ELT (it, 2), args, complain, in_decl,
17404                                /*integral_constant_expression_p=*/false);
17405               TREE_VEC_ELT (*tp, 3)
17406                 = tsubst_expr (TREE_VEC_ELT (it, 3), args, complain, in_decl,
17407                                /*integral_constant_expression_p=*/false);
17408               TREE_CHAIN (*tp) = NULL_TREE;
17409               tp = &TREE_CHAIN (*tp);
17410             }
17411           TREE_VEC_ELT (ret, 5) = poplevel (1, 1, 0);
17412           iterator_cache[0] = TREE_PURPOSE (decl);
17413           iterator_cache[1] = ret;
17414         }
17415       return build_tree_list (ret, tsubst_omp_clause_decl (TREE_VALUE (decl),
17416                                                            args, complain,
17417                                                            in_decl, NULL));
17418     }
17419
17420   /* Handle an OpenMP array section represented as a TREE_LIST (or
17421      OMP_CLAUSE_DEPEND_KIND).  An OMP_CLAUSE_DEPEND (with a depend
17422      kind of OMP_CLAUSE_DEPEND_SINK) can also be represented as a
17423      TREE_LIST.  We can handle it exactly the same as an array section
17424      (purpose, value, and a chain), even though the nomenclature
17425      (low_bound, length, etc) is different.  */
17426   if (TREE_CODE (decl) == TREE_LIST)
17427     {
17428       tree low_bound
17429         = tsubst_expr (TREE_PURPOSE (decl), args, complain, in_decl,
17430                        /*integral_constant_expression_p=*/false);
17431       tree length = tsubst_expr (TREE_VALUE (decl), args, complain, in_decl,
17432                                  /*integral_constant_expression_p=*/false);
17433       tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
17434                                            in_decl, NULL);
17435       if (TREE_PURPOSE (decl) == low_bound
17436           && TREE_VALUE (decl) == length
17437           && TREE_CHAIN (decl) == chain)
17438         return decl;
17439       tree ret = tree_cons (low_bound, length, chain);
17440       OMP_CLAUSE_DEPEND_SINK_NEGATIVE (ret)
17441         = OMP_CLAUSE_DEPEND_SINK_NEGATIVE (decl);
17442       return ret;
17443     }
17444   tree ret = tsubst_expr (decl, args, complain, in_decl,
17445                           /*integral_constant_expression_p=*/false);
17446   /* Undo convert_from_reference tsubst_expr could have called.  */
17447   if (decl
17448       && REFERENCE_REF_P (ret)
17449       && !REFERENCE_REF_P (decl))
17450     ret = TREE_OPERAND (ret, 0);
17451   return ret;
17452 }
17453
17454 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
17455
17456 static tree
17457 tsubst_omp_clauses (tree clauses, enum c_omp_region_type ort,
17458                     tree args, tsubst_flags_t complain, tree in_decl)
17459 {
17460   tree new_clauses = NULL_TREE, nc, oc;
17461   tree linear_no_step = NULL_TREE;
17462   tree iterator_cache[2] = { NULL_TREE, NULL_TREE };
17463
17464   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
17465     {
17466       nc = copy_node (oc);
17467       OMP_CLAUSE_CHAIN (nc) = new_clauses;
17468       new_clauses = nc;
17469
17470       switch (OMP_CLAUSE_CODE (nc))
17471         {
17472         case OMP_CLAUSE_LASTPRIVATE:
17473           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
17474             {
17475               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
17476               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
17477                            in_decl, /*integral_constant_expression_p=*/false);
17478               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
17479                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
17480             }
17481           /* FALLTHRU */
17482         case OMP_CLAUSE_PRIVATE:
17483         case OMP_CLAUSE_SHARED:
17484         case OMP_CLAUSE_FIRSTPRIVATE:
17485         case OMP_CLAUSE_COPYIN:
17486         case OMP_CLAUSE_COPYPRIVATE:
17487         case OMP_CLAUSE_UNIFORM:
17488         case OMP_CLAUSE_DEPEND:
17489         case OMP_CLAUSE_FROM:
17490         case OMP_CLAUSE_TO:
17491         case OMP_CLAUSE_MAP:
17492         case OMP_CLAUSE__CACHE_:
17493         case OMP_CLAUSE_NONTEMPORAL:
17494         case OMP_CLAUSE_USE_DEVICE_PTR:
17495         case OMP_CLAUSE_USE_DEVICE_ADDR:
17496         case OMP_CLAUSE_IS_DEVICE_PTR:
17497         case OMP_CLAUSE_INCLUSIVE:
17498         case OMP_CLAUSE_EXCLUSIVE:
17499           OMP_CLAUSE_DECL (nc)
17500             = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17501                                       in_decl, iterator_cache);
17502           break;
17503         case OMP_CLAUSE_TILE:
17504         case OMP_CLAUSE_IF:
17505         case OMP_CLAUSE_NUM_THREADS:
17506         case OMP_CLAUSE_SCHEDULE:
17507         case OMP_CLAUSE_COLLAPSE:
17508         case OMP_CLAUSE_FINAL:
17509         case OMP_CLAUSE_DEVICE:
17510         case OMP_CLAUSE_DIST_SCHEDULE:
17511         case OMP_CLAUSE_NUM_TEAMS:
17512         case OMP_CLAUSE_THREAD_LIMIT:
17513         case OMP_CLAUSE_SAFELEN:
17514         case OMP_CLAUSE_SIMDLEN:
17515         case OMP_CLAUSE_NUM_TASKS:
17516         case OMP_CLAUSE_GRAINSIZE:
17517         case OMP_CLAUSE_PRIORITY:
17518         case OMP_CLAUSE_ORDERED:
17519         case OMP_CLAUSE_HINT:
17520         case OMP_CLAUSE_NUM_GANGS:
17521         case OMP_CLAUSE_NUM_WORKERS:
17522         case OMP_CLAUSE_VECTOR_LENGTH:
17523         case OMP_CLAUSE_WORKER:
17524         case OMP_CLAUSE_VECTOR:
17525         case OMP_CLAUSE_ASYNC:
17526         case OMP_CLAUSE_WAIT:
17527         case OMP_CLAUSE_DETACH:
17528           OMP_CLAUSE_OPERAND (nc, 0)
17529             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain,
17530                            in_decl, /*integral_constant_expression_p=*/false);
17531           break;
17532         case OMP_CLAUSE_REDUCTION:
17533         case OMP_CLAUSE_IN_REDUCTION:
17534         case OMP_CLAUSE_TASK_REDUCTION:
17535           if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
17536             {
17537               tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
17538               if (TREE_CODE (placeholder) == SCOPE_REF)
17539                 {
17540                   tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
17541                                        complain, in_decl);
17542                   OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
17543                     = build_qualified_name (NULL_TREE, scope,
17544                                             TREE_OPERAND (placeholder, 1),
17545                                             false);
17546                 }
17547               else
17548                 gcc_assert (identifier_p (placeholder));
17549             }
17550           OMP_CLAUSE_DECL (nc)
17551             = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17552                                       in_decl, NULL);
17553           break;
17554         case OMP_CLAUSE_GANG:
17555         case OMP_CLAUSE_ALIGNED:
17556         case OMP_CLAUSE_ALLOCATE:
17557           OMP_CLAUSE_DECL (nc)
17558             = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17559                                       in_decl, NULL);
17560           OMP_CLAUSE_OPERAND (nc, 1)
17561             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain,
17562                            in_decl, /*integral_constant_expression_p=*/false);
17563           break;
17564         case OMP_CLAUSE_LINEAR:
17565           OMP_CLAUSE_DECL (nc)
17566             = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17567                                       in_decl, NULL);
17568           if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
17569             {
17570               gcc_assert (!linear_no_step);
17571               linear_no_step = nc;
17572             }
17573           else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
17574             OMP_CLAUSE_LINEAR_STEP (nc)
17575               = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
17576                                         complain, in_decl, NULL);
17577           else
17578             OMP_CLAUSE_LINEAR_STEP (nc)
17579               = tsubst_expr (OMP_CLAUSE_LINEAR_STEP (oc), args, complain,
17580                              in_decl,
17581                              /*integral_constant_expression_p=*/false);
17582           break;
17583         case OMP_CLAUSE_NOWAIT:
17584         case OMP_CLAUSE_DEFAULT:
17585         case OMP_CLAUSE_UNTIED:
17586         case OMP_CLAUSE_MERGEABLE:
17587         case OMP_CLAUSE_INBRANCH:
17588         case OMP_CLAUSE_NOTINBRANCH:
17589         case OMP_CLAUSE_PROC_BIND:
17590         case OMP_CLAUSE_FOR:
17591         case OMP_CLAUSE_PARALLEL:
17592         case OMP_CLAUSE_SECTIONS:
17593         case OMP_CLAUSE_TASKGROUP:
17594         case OMP_CLAUSE_NOGROUP:
17595         case OMP_CLAUSE_THREADS:
17596         case OMP_CLAUSE_SIMD:
17597         case OMP_CLAUSE_DEFAULTMAP:
17598         case OMP_CLAUSE_ORDER:
17599         case OMP_CLAUSE_BIND:
17600         case OMP_CLAUSE_INDEPENDENT:
17601         case OMP_CLAUSE_AUTO:
17602         case OMP_CLAUSE_SEQ:
17603         case OMP_CLAUSE_IF_PRESENT:
17604         case OMP_CLAUSE_FINALIZE:
17605           break;
17606         default:
17607           gcc_unreachable ();
17608         }
17609       if ((ort & C_ORT_OMP_DECLARE_SIMD) == C_ORT_OMP)
17610         switch (OMP_CLAUSE_CODE (nc))
17611           {
17612           case OMP_CLAUSE_SHARED:
17613           case OMP_CLAUSE_PRIVATE:
17614           case OMP_CLAUSE_FIRSTPRIVATE:
17615           case OMP_CLAUSE_LASTPRIVATE:
17616           case OMP_CLAUSE_COPYPRIVATE:
17617           case OMP_CLAUSE_LINEAR:
17618           case OMP_CLAUSE_REDUCTION:
17619           case OMP_CLAUSE_IN_REDUCTION:
17620           case OMP_CLAUSE_TASK_REDUCTION:
17621           case OMP_CLAUSE_USE_DEVICE_PTR:
17622           case OMP_CLAUSE_USE_DEVICE_ADDR:
17623           case OMP_CLAUSE_IS_DEVICE_PTR:
17624           case OMP_CLAUSE_INCLUSIVE:
17625           case OMP_CLAUSE_EXCLUSIVE:
17626           case OMP_CLAUSE_ALLOCATE:
17627             /* tsubst_expr on SCOPE_REF results in returning
17628                finish_non_static_data_member result.  Undo that here.  */
17629             if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
17630                 && (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
17631                     == IDENTIFIER_NODE))
17632               {
17633                 tree t = OMP_CLAUSE_DECL (nc);
17634                 tree v = t;
17635                 while (v)
17636                   switch (TREE_CODE (v))
17637                     {
17638                     case COMPONENT_REF:
17639                     case MEM_REF:
17640                     case INDIRECT_REF:
17641                     CASE_CONVERT:
17642                     case POINTER_PLUS_EXPR:
17643                       v = TREE_OPERAND (v, 0);
17644                       continue;
17645                     case PARM_DECL:
17646                       if (DECL_CONTEXT (v) == current_function_decl
17647                           && DECL_ARTIFICIAL (v)
17648                           && DECL_NAME (v) == this_identifier)
17649                         OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
17650                       /* FALLTHRU */
17651                     default:
17652                       v = NULL_TREE;
17653                       break;
17654                     }
17655               }
17656             else if (VAR_P (OMP_CLAUSE_DECL (oc))
17657                      && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
17658                      && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
17659                      && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
17660                      && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
17661               {
17662                 tree decl = OMP_CLAUSE_DECL (nc);
17663                 if (VAR_P (decl))
17664                   {
17665                     retrofit_lang_decl (decl);
17666                     DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
17667                   }
17668               }
17669             break;
17670           default:
17671             break;
17672           }
17673     }
17674
17675   new_clauses = nreverse (new_clauses);
17676   if (ort != C_ORT_OMP_DECLARE_SIMD)
17677     {
17678       new_clauses = finish_omp_clauses (new_clauses, ort);
17679       if (linear_no_step)
17680         for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
17681           if (nc == linear_no_step)
17682             {
17683               OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
17684               break;
17685             }
17686     }
17687   return new_clauses;
17688 }
17689
17690 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
17691
17692 static tree
17693 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
17694                           tree in_decl)
17695 {
17696 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
17697
17698   tree purpose, value, chain;
17699
17700   if (t == NULL)
17701     return t;
17702
17703   if (TREE_CODE (t) != TREE_LIST)
17704     return tsubst_copy_and_build (t, args, complain, in_decl,
17705                                   /*function_p=*/false,
17706                                   /*integral_constant_expression_p=*/false);
17707
17708   if (t == void_list_node)
17709     return t;
17710
17711   purpose = TREE_PURPOSE (t);
17712   if (purpose)
17713     purpose = RECUR (purpose);
17714   value = TREE_VALUE (t);
17715   if (value)
17716     {
17717       if (TREE_CODE (value) != LABEL_DECL)
17718         value = RECUR (value);
17719       else
17720         {
17721           value = lookup_label (DECL_NAME (value));
17722           gcc_assert (TREE_CODE (value) == LABEL_DECL);
17723           TREE_USED (value) = 1;
17724         }
17725     }
17726   chain = TREE_CHAIN (t);
17727   if (chain && chain != void_type_node)
17728     chain = RECUR (chain);
17729   return tree_cons (purpose, value, chain);
17730 #undef RECUR
17731 }
17732
17733 /* Used to temporarily communicate the list of #pragma omp parallel
17734    clauses to #pragma omp for instantiation if they are combined
17735    together.  */
17736
17737 static tree *omp_parallel_combined_clauses;
17738
17739 static tree tsubst_decomp_names (tree, tree, tree, tsubst_flags_t, tree,
17740                                  tree *, unsigned int *);
17741
17742 /* Substitute one OMP_FOR iterator.  */
17743
17744 static bool
17745 tsubst_omp_for_iterator (tree t, int i, tree declv, tree &orig_declv,
17746                          tree initv, tree condv, tree incrv, tree *clauses,
17747                          tree args, tsubst_flags_t complain, tree in_decl,
17748                          bool integral_constant_expression_p)
17749 {
17750 #define RECUR(NODE)                             \
17751   tsubst_expr ((NODE), args, complain, in_decl, \
17752                integral_constant_expression_p)
17753   tree decl, init, cond = NULL_TREE, incr = NULL_TREE;
17754   bool ret = false;
17755
17756   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
17757   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
17758
17759   decl = TREE_OPERAND (init, 0);
17760   init = TREE_OPERAND (init, 1);
17761   tree decl_expr = NULL_TREE;
17762   bool range_for = TREE_VEC_ELT (OMP_FOR_COND (t), i) == global_namespace;
17763   if (range_for)
17764     {
17765       bool decomp = false;
17766       if (decl != error_mark_node && DECL_HAS_VALUE_EXPR_P (decl))
17767         {
17768           tree v = DECL_VALUE_EXPR (decl);
17769           if (TREE_CODE (v) == ARRAY_REF
17770               && VAR_P (TREE_OPERAND (v, 0))
17771               && DECL_DECOMPOSITION_P (TREE_OPERAND (v, 0)))
17772             {
17773               tree decomp_first = NULL_TREE;
17774               unsigned decomp_cnt = 0;
17775               tree d = tsubst_decl (TREE_OPERAND (v, 0), args, complain);
17776               maybe_push_decl (d);
17777               d = tsubst_decomp_names (d, TREE_OPERAND (v, 0), args, complain,
17778                                        in_decl, &decomp_first, &decomp_cnt);
17779               decomp = true;
17780               if (d == error_mark_node)
17781                 decl = error_mark_node;
17782               else
17783                 for (unsigned int i = 0; i < decomp_cnt; i++)
17784                   {
17785                     if (!DECL_HAS_VALUE_EXPR_P (decomp_first))
17786                       {
17787                         tree v = build_nt (ARRAY_REF, d,
17788                                            size_int (decomp_cnt - i - 1),
17789                                            NULL_TREE, NULL_TREE);
17790                         SET_DECL_VALUE_EXPR (decomp_first, v);
17791                         DECL_HAS_VALUE_EXPR_P (decomp_first) = 1;
17792                       }
17793                     fit_decomposition_lang_decl (decomp_first, d);
17794                     decomp_first = DECL_CHAIN (decomp_first);
17795                   }
17796             }
17797         }
17798       decl = tsubst_decl (decl, args, complain);
17799       if (!decomp)
17800         maybe_push_decl (decl);
17801     }
17802   else if (init && TREE_CODE (init) == DECL_EXPR)
17803     {
17804       /* We need to jump through some hoops to handle declarations in the
17805          init-statement, since we might need to handle auto deduction,
17806          but we need to keep control of initialization.  */
17807       decl_expr = init;
17808       init = DECL_INITIAL (DECL_EXPR_DECL (init));
17809       decl = tsubst_decl (decl, args, complain);
17810     }
17811   else
17812     {
17813       if (TREE_CODE (decl) == SCOPE_REF)
17814         {
17815           decl = RECUR (decl);
17816           if (TREE_CODE (decl) == COMPONENT_REF)
17817             {
17818               tree v = decl;
17819               while (v)
17820                 switch (TREE_CODE (v))
17821                   {
17822                   case COMPONENT_REF:
17823                   case MEM_REF:
17824                   case INDIRECT_REF:
17825                   CASE_CONVERT:
17826                   case POINTER_PLUS_EXPR:
17827                     v = TREE_OPERAND (v, 0);
17828                     continue;
17829                   case PARM_DECL:
17830                     if (DECL_CONTEXT (v) == current_function_decl
17831                         && DECL_ARTIFICIAL (v)
17832                         && DECL_NAME (v) == this_identifier)
17833                       {
17834                         decl = TREE_OPERAND (decl, 1);
17835                         decl = omp_privatize_field (decl, false);
17836                       }
17837                     /* FALLTHRU */
17838                   default:
17839                     v = NULL_TREE;
17840                     break;
17841                   }
17842             }
17843         }
17844       else
17845         decl = RECUR (decl);
17846     }
17847   if (init && TREE_CODE (init) == TREE_VEC)
17848     {
17849       init = copy_node (init);
17850       TREE_VEC_ELT (init, 0)
17851         = tsubst_decl (TREE_VEC_ELT (init, 0), args, complain);
17852       TREE_VEC_ELT (init, 1) = RECUR (TREE_VEC_ELT (init, 1));
17853       TREE_VEC_ELT (init, 2) = RECUR (TREE_VEC_ELT (init, 2));
17854     }
17855   else
17856     init = RECUR (init);
17857
17858   if (orig_declv && OMP_FOR_ORIG_DECLS (t))
17859     {
17860       tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
17861       if (TREE_CODE (o) == TREE_LIST)
17862         TREE_VEC_ELT (orig_declv, i)
17863           = tree_cons (RECUR (TREE_PURPOSE (o)),
17864                        RECUR (TREE_VALUE (o)),
17865                        NULL_TREE);
17866       else
17867         TREE_VEC_ELT (orig_declv, i) = RECUR (o);
17868     }
17869
17870   if (range_for)
17871     {
17872       tree this_pre_body = NULL_TREE;
17873       tree orig_init = NULL_TREE;
17874       tree orig_decl = NULL_TREE;
17875       cp_convert_omp_range_for (this_pre_body, NULL, decl, orig_decl, init,
17876                                 orig_init, cond, incr);
17877       if (orig_decl)
17878         {
17879           if (orig_declv == NULL_TREE)
17880             orig_declv = copy_node (declv);
17881           TREE_VEC_ELT (orig_declv, i) = orig_decl;
17882           ret = true;
17883         }
17884       else if (orig_declv)
17885         TREE_VEC_ELT (orig_declv, i) = decl;
17886     }
17887
17888   tree auto_node = type_uses_auto (TREE_TYPE (decl));
17889   if (!range_for && auto_node && init)
17890     TREE_TYPE (decl)
17891       = do_auto_deduction (TREE_TYPE (decl), init, auto_node, complain);
17892
17893   gcc_assert (!type_dependent_expression_p (decl));
17894
17895   if (!CLASS_TYPE_P (TREE_TYPE (decl)) || range_for)
17896     {
17897       if (decl_expr)
17898         {
17899           /* Declare the variable, but don't let that initialize it.  */
17900           tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
17901           DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
17902           RECUR (decl_expr);
17903           DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
17904         }
17905
17906       if (!range_for)
17907         {
17908           cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
17909           if (COMPARISON_CLASS_P (cond)
17910               && TREE_CODE (TREE_OPERAND (cond, 1)) == TREE_VEC)
17911             {
17912               tree lhs = RECUR (TREE_OPERAND (cond, 0));
17913               tree rhs = copy_node (TREE_OPERAND (cond, 1));
17914               TREE_VEC_ELT (rhs, 0)
17915                 = tsubst_decl (TREE_VEC_ELT (rhs, 0), args, complain);
17916               TREE_VEC_ELT (rhs, 1) = RECUR (TREE_VEC_ELT (rhs, 1));
17917               TREE_VEC_ELT (rhs, 2) = RECUR (TREE_VEC_ELT (rhs, 2));
17918               cond = build2 (TREE_CODE (cond), TREE_TYPE (cond),
17919                              lhs, rhs);       
17920             }
17921           else
17922             cond = RECUR (cond);
17923           incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
17924           if (TREE_CODE (incr) == MODIFY_EXPR)
17925             {
17926               tree lhs = RECUR (TREE_OPERAND (incr, 0));
17927               tree rhs = RECUR (TREE_OPERAND (incr, 1));
17928               incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
17929                                           NOP_EXPR, rhs, complain);
17930             }
17931           else
17932             incr = RECUR (incr);
17933           if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
17934             TREE_VEC_ELT (orig_declv, i) = decl;
17935         }
17936       TREE_VEC_ELT (declv, i) = decl;
17937       TREE_VEC_ELT (initv, i) = init;
17938       TREE_VEC_ELT (condv, i) = cond;
17939       TREE_VEC_ELT (incrv, i) = incr;
17940       return ret;
17941     }
17942
17943   if (decl_expr)
17944     {
17945       /* Declare and initialize the variable.  */
17946       RECUR (decl_expr);
17947       init = NULL_TREE;
17948     }
17949   else if (init)
17950     {
17951       tree *pc;
17952       int j;
17953       for (j = ((omp_parallel_combined_clauses == NULL
17954                 || TREE_CODE (t) == OMP_LOOP) ? 1 : 0); j < 2; j++)
17955         {
17956           for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
17957             {
17958               if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
17959                   && OMP_CLAUSE_DECL (*pc) == decl)
17960                 break;
17961               else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
17962                        && OMP_CLAUSE_DECL (*pc) == decl)
17963                 {
17964                   if (j)
17965                     break;
17966                   /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES.  */
17967                   tree c = *pc;
17968                   *pc = OMP_CLAUSE_CHAIN (c);
17969                   OMP_CLAUSE_CHAIN (c) = *clauses;
17970                   *clauses = c;
17971                 }
17972               else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
17973                        && OMP_CLAUSE_DECL (*pc) == decl)
17974                 {
17975                   error ("iteration variable %qD should not be firstprivate",
17976                          decl);
17977                   *pc = OMP_CLAUSE_CHAIN (*pc);
17978                 }
17979               else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
17980                        && OMP_CLAUSE_DECL (*pc) == decl)
17981                 {
17982                   error ("iteration variable %qD should not be reduction",
17983                          decl);
17984                   *pc = OMP_CLAUSE_CHAIN (*pc);
17985                 }
17986               else
17987                 pc = &OMP_CLAUSE_CHAIN (*pc);
17988             }
17989           if (*pc)
17990             break;
17991         }
17992       if (*pc == NULL_TREE)
17993         {
17994           tree c = build_omp_clause (input_location,
17995                                      TREE_CODE (t) == OMP_LOOP
17996                                      ? OMP_CLAUSE_LASTPRIVATE
17997                                      : OMP_CLAUSE_PRIVATE);
17998           OMP_CLAUSE_DECL (c) = decl;
17999           c = finish_omp_clauses (c, C_ORT_OMP);
18000           if (c)
18001             {
18002               OMP_CLAUSE_CHAIN (c) = *clauses;
18003               *clauses = c;
18004             }
18005         }
18006     }
18007   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
18008   if (COMPARISON_CLASS_P (cond))
18009     {
18010       tree op0 = RECUR (TREE_OPERAND (cond, 0));
18011       tree op1 = RECUR (TREE_OPERAND (cond, 1));
18012       cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
18013     }
18014   else
18015     cond = RECUR (cond);
18016   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
18017   switch (TREE_CODE (incr))
18018     {
18019     case PREINCREMENT_EXPR:
18020     case PREDECREMENT_EXPR:
18021     case POSTINCREMENT_EXPR:
18022     case POSTDECREMENT_EXPR:
18023       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
18024                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
18025       break;
18026     case MODIFY_EXPR:
18027       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
18028           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
18029         {
18030           tree rhs = TREE_OPERAND (incr, 1);
18031           tree lhs = RECUR (TREE_OPERAND (incr, 0));
18032           tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
18033           tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
18034           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18035                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
18036                                  rhs0, rhs1));
18037         }
18038       else
18039         incr = RECUR (incr);
18040       break;
18041     case MODOP_EXPR:
18042       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
18043           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
18044         {
18045           tree lhs = RECUR (TREE_OPERAND (incr, 0));
18046           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18047                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
18048                                  TREE_TYPE (decl), lhs,
18049                                  RECUR (TREE_OPERAND (incr, 2))));
18050         }
18051       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
18052                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
18053                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
18054         {
18055           tree rhs = TREE_OPERAND (incr, 2);
18056           tree lhs = RECUR (TREE_OPERAND (incr, 0));
18057           tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
18058           tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
18059           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18060                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
18061                                  rhs0, rhs1));
18062         }
18063       else
18064         incr = RECUR (incr);
18065       break;
18066     default:
18067       incr = RECUR (incr);
18068       break;
18069     }
18070
18071   if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
18072     TREE_VEC_ELT (orig_declv, i) = decl;
18073   TREE_VEC_ELT (declv, i) = decl;
18074   TREE_VEC_ELT (initv, i) = init;
18075   TREE_VEC_ELT (condv, i) = cond;
18076   TREE_VEC_ELT (incrv, i) = incr;
18077   return false;
18078 #undef RECUR
18079 }
18080
18081 /* Helper function of tsubst_expr, find OMP_TEAMS inside
18082    of OMP_TARGET's body.  */
18083
18084 static tree
18085 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
18086 {
18087   *walk_subtrees = 0;
18088   switch (TREE_CODE (*tp))
18089     {
18090     case OMP_TEAMS:
18091       return *tp;
18092     case BIND_EXPR:
18093     case STATEMENT_LIST:
18094       *walk_subtrees = 1;
18095       break;
18096     default:
18097       break;
18098     }
18099   return NULL_TREE;
18100 }
18101
18102 /* Helper function for tsubst_expr.  For decomposition declaration
18103    artificial base DECL, which is tsubsted PATTERN_DECL, tsubst
18104    also the corresponding decls representing the identifiers
18105    of the decomposition declaration.  Return DECL if successful
18106    or error_mark_node otherwise, set *FIRST to the first decl
18107    in the list chained through DECL_CHAIN and *CNT to the number
18108    of such decls.  */
18109
18110 static tree
18111 tsubst_decomp_names (tree decl, tree pattern_decl, tree args,
18112                      tsubst_flags_t complain, tree in_decl, tree *first,
18113                      unsigned int *cnt)
18114 {
18115   tree decl2, decl3, prev = decl;
18116   *cnt = 0;
18117   gcc_assert (DECL_NAME (decl) == NULL_TREE);
18118   for (decl2 = DECL_CHAIN (pattern_decl);
18119        decl2
18120        && VAR_P (decl2)
18121        && DECL_DECOMPOSITION_P (decl2)
18122        && DECL_NAME (decl2);
18123        decl2 = DECL_CHAIN (decl2))
18124     {
18125       if (TREE_TYPE (decl2) == error_mark_node && *cnt == 0)
18126         {
18127           gcc_assert (errorcount);
18128           return error_mark_node;
18129         }
18130       (*cnt)++;
18131       gcc_assert (DECL_DECOMP_BASE (decl2) == pattern_decl);
18132       gcc_assert (DECL_HAS_VALUE_EXPR_P (decl2));
18133       tree v = DECL_VALUE_EXPR (decl2);
18134       DECL_HAS_VALUE_EXPR_P (decl2) = 0;
18135       SET_DECL_VALUE_EXPR (decl2, NULL_TREE);
18136       decl3 = tsubst (decl2, args, complain, in_decl);
18137       SET_DECL_VALUE_EXPR (decl2, v);
18138       DECL_HAS_VALUE_EXPR_P (decl2) = 1;
18139       if (VAR_P (decl3))
18140         DECL_TEMPLATE_INSTANTIATED (decl3) = 1;
18141       else
18142         {
18143           gcc_assert (errorcount);
18144           decl = error_mark_node;
18145           continue;
18146         }
18147       maybe_push_decl (decl3);
18148       if (error_operand_p (decl3))
18149         decl = error_mark_node;
18150       else if (decl != error_mark_node
18151                && DECL_CHAIN (decl3) != prev
18152                && decl != prev)
18153         {
18154           gcc_assert (errorcount);
18155           decl = error_mark_node;
18156         }
18157       else
18158         prev = decl3;
18159     }
18160   *first = prev;
18161   return decl;
18162 }
18163
18164 /* Return the proper local_specialization for init-capture pack DECL.  */
18165
18166 static tree
18167 lookup_init_capture_pack (tree decl)
18168 {
18169   /* We handle normal pack captures by forwarding to the specialization of the
18170      captured parameter.  We can't do that for pack init-captures; we need them
18171      to have their own local_specialization.  We created the individual
18172      VAR_DECLs (if any) under build_capture_proxy, and we need to collect them
18173      when we process the DECL_EXPR for the pack init-capture in the template.
18174      So, how do we find them?  We don't know the capture proxy pack when
18175      building the individual resulting proxies, and we don't know the
18176      individual proxies when instantiating the pack.  What we have in common is
18177      the FIELD_DECL.
18178
18179      So...when we instantiate the FIELD_DECL, we stick the result in
18180      local_specializations.  Then at the DECL_EXPR we look up that result, see
18181      how many elements it has, synthesize the names, and look them up.  */
18182
18183   tree cname = DECL_NAME (decl);
18184   tree val = DECL_VALUE_EXPR (decl);
18185   tree field = TREE_OPERAND (val, 1);
18186   gcc_assert (TREE_CODE (field) == FIELD_DECL);
18187   tree fpack = retrieve_local_specialization (field);
18188   if (fpack == error_mark_node)
18189     return error_mark_node;
18190
18191   int len = 1;
18192   tree vec = NULL_TREE;
18193   tree r = NULL_TREE;
18194   if (TREE_CODE (fpack) == TREE_VEC)
18195     {
18196       len = TREE_VEC_LENGTH (fpack);
18197       vec = make_tree_vec (len);
18198       r = make_node (NONTYPE_ARGUMENT_PACK);
18199       SET_ARGUMENT_PACK_ARGS (r, vec);
18200     }
18201   for (int i = 0; i < len; ++i)
18202     {
18203       tree ename = vec ? make_ith_pack_parameter_name (cname, i) : cname;
18204       tree elt = lookup_name (ename);
18205       if (vec)
18206         TREE_VEC_ELT (vec, i) = elt;
18207       else
18208         r = elt;
18209     }
18210   return r;
18211 }
18212
18213 /* Like tsubst_copy for expressions, etc. but also does semantic
18214    processing.  */
18215
18216 tree
18217 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
18218              bool integral_constant_expression_p)
18219 {
18220 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
18221 #define RECUR(NODE)                             \
18222   tsubst_expr ((NODE), args, complain, in_decl, \
18223                integral_constant_expression_p)
18224
18225   tree stmt, tmp;
18226   tree r;
18227   location_t loc;
18228
18229   if (t == NULL_TREE || t == error_mark_node)
18230     return t;
18231
18232   loc = input_location;
18233   if (location_t eloc = cp_expr_location (t))
18234     input_location = eloc;
18235   if (STATEMENT_CODE_P (TREE_CODE (t)))
18236     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
18237
18238   switch (TREE_CODE (t))
18239     {
18240     case STATEMENT_LIST:
18241       {
18242         tree_stmt_iterator i;
18243         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
18244           RECUR (tsi_stmt (i));
18245         break;
18246       }
18247
18248     case CTOR_INITIALIZER:
18249       finish_mem_initializers (tsubst_initializer_list
18250                                (TREE_OPERAND (t, 0), args));
18251       break;
18252
18253     case RETURN_EXPR:
18254       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
18255       break;
18256
18257     case CO_RETURN_EXPR:
18258       finish_co_return_stmt (input_location, RECUR (TREE_OPERAND (t, 0)));
18259       break;
18260
18261     case CO_YIELD_EXPR:
18262       stmt = finish_co_yield_expr (input_location,
18263                                    RECUR (TREE_OPERAND (t, 0)));
18264       RETURN (stmt);
18265       break;
18266
18267     case CO_AWAIT_EXPR:
18268       stmt = finish_co_await_expr (input_location,
18269                                    RECUR (TREE_OPERAND (t, 0)));
18270       RETURN (stmt);
18271       break;
18272
18273     case EXPR_STMT:
18274       tmp = RECUR (EXPR_STMT_EXPR (t));
18275       if (EXPR_STMT_STMT_EXPR_RESULT (t))
18276         finish_stmt_expr_expr (tmp, cur_stmt_expr);
18277       else
18278         finish_expr_stmt (tmp);
18279       break;
18280
18281     case USING_STMT:
18282       finish_using_directive (USING_STMT_NAMESPACE (t), /*attribs=*/NULL_TREE);
18283       break;
18284
18285     case DECL_EXPR:
18286       {
18287         tree decl, pattern_decl;
18288         tree init;
18289
18290         pattern_decl = decl = DECL_EXPR_DECL (t);
18291         if (TREE_CODE (decl) == LABEL_DECL)
18292           finish_label_decl (DECL_NAME (decl));
18293         else if (TREE_CODE (decl) == USING_DECL)
18294           {
18295             tree scope = USING_DECL_SCOPE (decl);
18296             if (DECL_DEPENDENT_P (decl))
18297               {
18298                 scope = tsubst (scope, args, complain, in_decl);
18299                 if (!MAYBE_CLASS_TYPE_P (scope)
18300                     && TREE_CODE (scope) != ENUMERAL_TYPE)
18301                   {
18302                     if (complain & tf_error)
18303                       error_at (DECL_SOURCE_LOCATION (decl), "%qT is not a "
18304                                 "class, namespace, or enumeration", scope);
18305                     return error_mark_node;
18306                   }
18307                 finish_nonmember_using_decl (scope, DECL_NAME (decl));
18308               }
18309             else
18310               {
18311                 /* This is a non-dependent using-decl, and we'll have
18312                    used the names it found during template parsing.  We do
18313                    not want to do the lookup again, because we might not
18314                    find the things we found then.  */
18315                 gcc_checking_assert (scope == tsubst (scope, args,
18316                                                       complain, in_decl));
18317                 /* We still need to push the bindings so that we can look up
18318                    this name later.  */
18319                 push_using_decl_bindings (DECL_NAME (decl),
18320                                           USING_DECL_DECLS (decl));
18321               }
18322           }
18323         else if (is_capture_proxy (decl)
18324                  && !DECL_TEMPLATE_INSTANTIATION (current_function_decl))
18325           {
18326             /* We're in tsubst_lambda_expr, we've already inserted a new
18327                capture proxy, so look it up and register it.  */
18328             tree inst;
18329             if (!DECL_PACK_P (decl))
18330               {
18331                 inst = lookup_name (DECL_NAME (decl), LOOK_where::BLOCK,
18332                                     LOOK_want::HIDDEN_LAMBDA);
18333                 gcc_assert (inst != decl && is_capture_proxy (inst));
18334               }
18335             else if (is_normal_capture_proxy (decl))
18336               {
18337                 inst = (retrieve_local_specialization
18338                         (DECL_CAPTURED_VARIABLE (decl)));
18339                 gcc_assert (TREE_CODE (inst) == NONTYPE_ARGUMENT_PACK
18340                             || DECL_PACK_P (inst));
18341               }
18342             else
18343               inst = lookup_init_capture_pack (decl);
18344
18345             register_local_specialization (inst, decl);
18346             break;
18347           }
18348         else if (DECL_PRETTY_FUNCTION_P (decl))
18349           decl = make_fname_decl (DECL_SOURCE_LOCATION (decl),
18350                                   DECL_NAME (decl),
18351                                   true/*DECL_PRETTY_FUNCTION_P (decl)*/);
18352         else if (DECL_IMPLICIT_TYPEDEF_P (decl)
18353                  && LAMBDA_TYPE_P (TREE_TYPE (decl)))
18354           /* Don't copy the old closure; we'll create a new one in
18355              tsubst_lambda_expr.  */
18356           break;
18357         else
18358           {
18359             init = DECL_INITIAL (decl);
18360             decl = tsubst (decl, args, complain, in_decl);
18361             if (decl != error_mark_node)
18362               {
18363                 /* By marking the declaration as instantiated, we avoid
18364                    trying to instantiate it.  Since instantiate_decl can't
18365                    handle local variables, and since we've already done
18366                    all that needs to be done, that's the right thing to
18367                    do.  */
18368                 if (VAR_P (decl))
18369                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
18370                 if (VAR_P (decl) && !DECL_NAME (decl)
18371                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
18372                   /* Anonymous aggregates are a special case.  */
18373                   finish_anon_union (decl);
18374                 else if (is_capture_proxy (DECL_EXPR_DECL (t)))
18375                   {
18376                     DECL_CONTEXT (decl) = current_function_decl;
18377                     if (DECL_NAME (decl) == this_identifier)
18378                       {
18379                         tree lam = DECL_CONTEXT (current_function_decl);
18380                         lam = CLASSTYPE_LAMBDA_EXPR (lam);
18381                         LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
18382                       }
18383                     insert_capture_proxy (decl);
18384                   }
18385                 else if (DECL_IMPLICIT_TYPEDEF_P (t))
18386                   /* We already did a pushtag.  */;
18387                 else if (VAR_OR_FUNCTION_DECL_P (decl)
18388                          && DECL_LOCAL_DECL_P (decl))
18389                   {
18390                     if (TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL)
18391                       DECL_CONTEXT (decl) = NULL_TREE;
18392                     decl = pushdecl (decl);
18393                     if (TREE_CODE (decl) == FUNCTION_DECL
18394                         && DECL_OMP_DECLARE_REDUCTION_P (decl)
18395                         && cp_check_omp_declare_reduction (decl))
18396                       instantiate_body (pattern_decl, args, decl, true);
18397                   }
18398                 else
18399                   {
18400                     bool const_init = false;
18401                     unsigned int cnt = 0;
18402                     tree first = NULL_TREE, ndecl = error_mark_node;
18403                     tree asmspec_tree = NULL_TREE;
18404                     maybe_push_decl (decl);
18405
18406                     if (VAR_P (decl)
18407                         && DECL_DECOMPOSITION_P (decl)
18408                         && TREE_TYPE (pattern_decl) != error_mark_node)
18409                       ndecl = tsubst_decomp_names (decl, pattern_decl, args,
18410                                                    complain, in_decl, &first,
18411                                                    &cnt);
18412
18413                     init = tsubst_init (init, decl, args, complain, in_decl);
18414
18415                     if (VAR_P (decl))
18416                       const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
18417                                     (pattern_decl));
18418
18419                     if (ndecl != error_mark_node)
18420                       cp_maybe_mangle_decomp (ndecl, first, cnt);
18421
18422                     /* In a non-template function, VLA type declarations are
18423                        handled in grokdeclarator; for templates, handle them
18424                        now.  */
18425                     predeclare_vla (decl);
18426
18427                     if (VAR_P (decl) && DECL_HARD_REGISTER (pattern_decl))
18428                       {
18429                         tree id = DECL_ASSEMBLER_NAME (pattern_decl);
18430                         const char *asmspec = IDENTIFIER_POINTER (id);
18431                         gcc_assert (asmspec[0] == '*');
18432                         asmspec_tree
18433                           = build_string (IDENTIFIER_LENGTH (id) - 1,
18434                                           asmspec + 1);
18435                         TREE_TYPE (asmspec_tree) = char_array_type_node;
18436                       }
18437
18438                     cp_finish_decl (decl, init, const_init, asmspec_tree, 0);
18439
18440                     if (ndecl != error_mark_node)
18441                       cp_finish_decomp (ndecl, first, cnt);
18442                   }
18443               }
18444           }
18445
18446         break;
18447       }
18448
18449     case FOR_STMT:
18450       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
18451       RECUR (FOR_INIT_STMT (t));
18452       finish_init_stmt (stmt);
18453       tmp = RECUR (FOR_COND (t));
18454       finish_for_cond (tmp, stmt, false, 0);
18455       tmp = RECUR (FOR_EXPR (t));
18456       finish_for_expr (tmp, stmt);
18457       {
18458         bool prev = note_iteration_stmt_body_start ();
18459         RECUR (FOR_BODY (t));
18460         note_iteration_stmt_body_end (prev);
18461       }
18462       finish_for_stmt (stmt);
18463       break;
18464
18465     case RANGE_FOR_STMT:
18466       {
18467         /* Construct another range_for, if this is not a final
18468            substitution (for inside a generic lambda of a
18469            template).  Otherwise convert to a regular for.  */
18470         tree decl, expr;
18471         stmt = (processing_template_decl
18472                 ? begin_range_for_stmt (NULL_TREE, NULL_TREE)
18473                 : begin_for_stmt (NULL_TREE, NULL_TREE));
18474         RECUR (RANGE_FOR_INIT_STMT (t));
18475         decl = RANGE_FOR_DECL (t);
18476         decl = tsubst (decl, args, complain, in_decl);
18477         maybe_push_decl (decl);
18478         expr = RECUR (RANGE_FOR_EXPR (t));
18479
18480         tree decomp_first = NULL_TREE;
18481         unsigned decomp_cnt = 0;
18482         if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
18483           decl = tsubst_decomp_names (decl, RANGE_FOR_DECL (t), args,
18484                                       complain, in_decl,
18485                                       &decomp_first, &decomp_cnt);
18486
18487         if (processing_template_decl)
18488           {
18489             RANGE_FOR_IVDEP (stmt) = RANGE_FOR_IVDEP (t);
18490             RANGE_FOR_UNROLL (stmt) = RANGE_FOR_UNROLL (t);
18491             finish_range_for_decl (stmt, decl, expr);
18492             if (decomp_first && decl != error_mark_node)
18493               cp_finish_decomp (decl, decomp_first, decomp_cnt);
18494           }
18495         else
18496           {
18497             unsigned short unroll = (RANGE_FOR_UNROLL (t)
18498                                      ? tree_to_uhwi (RANGE_FOR_UNROLL (t)) : 0);
18499             stmt = cp_convert_range_for (stmt, decl, expr,
18500                                          decomp_first, decomp_cnt,
18501                                          RANGE_FOR_IVDEP (t), unroll);
18502           }
18503
18504         bool prev = note_iteration_stmt_body_start ();
18505         RECUR (RANGE_FOR_BODY (t));
18506         note_iteration_stmt_body_end (prev);
18507         finish_for_stmt (stmt);
18508       }
18509       break;
18510
18511     case WHILE_STMT:
18512       stmt = begin_while_stmt ();
18513       tmp = RECUR (WHILE_COND (t));
18514       finish_while_stmt_cond (tmp, stmt, false, 0);
18515       {
18516         bool prev = note_iteration_stmt_body_start ();
18517         RECUR (WHILE_BODY (t));
18518         note_iteration_stmt_body_end (prev);
18519       }
18520       finish_while_stmt (stmt);
18521       break;
18522
18523     case DO_STMT:
18524       stmt = begin_do_stmt ();
18525       {
18526         bool prev = note_iteration_stmt_body_start ();
18527         RECUR (DO_BODY (t));
18528         note_iteration_stmt_body_end (prev);
18529       }
18530       finish_do_body (stmt);
18531       tmp = RECUR (DO_COND (t));
18532       finish_do_stmt (tmp, stmt, false, 0);
18533       break;
18534
18535     case IF_STMT:
18536       stmt = begin_if_stmt ();
18537       IF_STMT_CONSTEXPR_P (stmt) = IF_STMT_CONSTEXPR_P (t);
18538       if (IF_STMT_CONSTEXPR_P (t))
18539         args = add_extra_args (IF_STMT_EXTRA_ARGS (t), args);
18540       tmp = RECUR (IF_COND (t));
18541       tmp = finish_if_stmt_cond (tmp, stmt);
18542       if (IF_STMT_CONSTEXPR_P (t)
18543           && instantiation_dependent_expression_p (tmp))
18544         {
18545           /* We're partially instantiating a generic lambda, but the condition
18546              of the constexpr if is still dependent.  Don't substitute into the
18547              branches now, just remember the template arguments.  */
18548           do_poplevel (IF_SCOPE (stmt));
18549           IF_COND (stmt) = IF_COND (t);
18550           THEN_CLAUSE (stmt) = THEN_CLAUSE (t);
18551           ELSE_CLAUSE (stmt) = ELSE_CLAUSE (t);
18552           IF_STMT_EXTRA_ARGS (stmt) = build_extra_args (t, args, complain);
18553           add_stmt (stmt);
18554           break;
18555         }
18556       if (IF_STMT_CONSTEXPR_P (t) && integer_zerop (tmp))
18557         /* Don't instantiate the THEN_CLAUSE. */;
18558       else
18559         {
18560           tree folded = fold_non_dependent_expr (tmp, complain);
18561           bool inhibit = integer_zerop (folded);
18562           if (inhibit)
18563             ++c_inhibit_evaluation_warnings;
18564           RECUR (THEN_CLAUSE (t));
18565           if (inhibit)
18566             --c_inhibit_evaluation_warnings;
18567         }
18568       finish_then_clause (stmt);
18569
18570       if (IF_STMT_CONSTEXPR_P (t) && integer_nonzerop (tmp))
18571         /* Don't instantiate the ELSE_CLAUSE. */;
18572       else if (ELSE_CLAUSE (t))
18573         {
18574           tree folded = fold_non_dependent_expr (tmp, complain);
18575           bool inhibit = integer_nonzerop (folded);
18576           begin_else_clause (stmt);
18577           if (inhibit)
18578             ++c_inhibit_evaluation_warnings;
18579           RECUR (ELSE_CLAUSE (t));
18580           if (inhibit)
18581             --c_inhibit_evaluation_warnings;
18582           finish_else_clause (stmt);
18583         }
18584
18585       finish_if_stmt (stmt);
18586       break;
18587
18588     case BIND_EXPR:
18589       if (BIND_EXPR_BODY_BLOCK (t))
18590         stmt = begin_function_body ();
18591       else
18592         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
18593                                     ? BCS_TRY_BLOCK : 0);
18594
18595       RECUR (BIND_EXPR_BODY (t));
18596
18597       if (BIND_EXPR_BODY_BLOCK (t))
18598         finish_function_body (stmt);
18599       else
18600         finish_compound_stmt (stmt);
18601       break;
18602
18603     case BREAK_STMT:
18604       finish_break_stmt ();
18605       break;
18606
18607     case CONTINUE_STMT:
18608       finish_continue_stmt ();
18609       break;
18610
18611     case SWITCH_STMT:
18612       stmt = begin_switch_stmt ();
18613       tmp = RECUR (SWITCH_STMT_COND (t));
18614       finish_switch_cond (tmp, stmt);
18615       RECUR (SWITCH_STMT_BODY (t));
18616       finish_switch_stmt (stmt);
18617       break;
18618
18619     case CASE_LABEL_EXPR:
18620       {
18621         tree decl = CASE_LABEL (t);
18622         tree low = RECUR (CASE_LOW (t));
18623         tree high = RECUR (CASE_HIGH (t));
18624         tree l = finish_case_label (EXPR_LOCATION (t), low, high);
18625         if (l && TREE_CODE (l) == CASE_LABEL_EXPR)
18626           {
18627             tree label = CASE_LABEL (l);
18628             FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
18629             if (DECL_ATTRIBUTES (decl) != NULL_TREE)
18630               cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
18631           }
18632       }
18633       break;
18634
18635     case LABEL_EXPR:
18636       {
18637         tree decl = LABEL_EXPR_LABEL (t);
18638         tree label;
18639
18640         label = finish_label_stmt (DECL_NAME (decl));
18641         if (TREE_CODE (label) == LABEL_DECL)
18642           FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
18643         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
18644           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
18645       }
18646       break;
18647
18648     case GOTO_EXPR:
18649       tmp = GOTO_DESTINATION (t);
18650       if (TREE_CODE (tmp) != LABEL_DECL)
18651         /* Computed goto's must be tsubst'd into.  On the other hand,
18652            non-computed gotos must not be; the identifier in question
18653            will have no binding.  */
18654         tmp = RECUR (tmp);
18655       else
18656         tmp = DECL_NAME (tmp);
18657       finish_goto_stmt (tmp);
18658       break;
18659
18660     case ASM_EXPR:
18661       {
18662         tree string = RECUR (ASM_STRING (t));
18663         tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
18664                                                  complain, in_decl);
18665         tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
18666                                                 complain, in_decl);
18667         tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
18668                                                   complain, in_decl);
18669         tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
18670                                                 complain, in_decl);
18671         tmp = finish_asm_stmt (EXPR_LOCATION (t), ASM_VOLATILE_P (t), string,
18672                                outputs, inputs, clobbers, labels,
18673                                ASM_INLINE_P (t));
18674         tree asm_expr = tmp;
18675         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
18676           asm_expr = TREE_OPERAND (asm_expr, 0);
18677         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
18678       }
18679       break;
18680
18681     case TRY_BLOCK:
18682       if (CLEANUP_P (t))
18683         {
18684           stmt = begin_try_block ();
18685           RECUR (TRY_STMTS (t));
18686           finish_cleanup_try_block (stmt);
18687           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
18688         }
18689       else
18690         {
18691           tree compound_stmt = NULL_TREE;
18692
18693           if (FN_TRY_BLOCK_P (t))
18694             stmt = begin_function_try_block (&compound_stmt);
18695           else
18696             stmt = begin_try_block ();
18697
18698           RECUR (TRY_STMTS (t));
18699
18700           if (FN_TRY_BLOCK_P (t))
18701             finish_function_try_block (stmt);
18702           else
18703             finish_try_block (stmt);
18704
18705           RECUR (TRY_HANDLERS (t));
18706           if (FN_TRY_BLOCK_P (t))
18707             finish_function_handler_sequence (stmt, compound_stmt);
18708           else
18709             finish_handler_sequence (stmt);
18710         }
18711       break;
18712
18713     case HANDLER:
18714       {
18715         tree decl = HANDLER_PARMS (t);
18716
18717         if (decl)
18718           {
18719             decl = tsubst (decl, args, complain, in_decl);
18720             /* Prevent instantiate_decl from trying to instantiate
18721                this variable.  We've already done all that needs to be
18722                done.  */
18723             if (decl != error_mark_node)
18724               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
18725           }
18726         stmt = begin_handler ();
18727         finish_handler_parms (decl, stmt);
18728         RECUR (HANDLER_BODY (t));
18729         finish_handler (stmt);
18730       }
18731       break;
18732
18733     case TAG_DEFN:
18734       tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
18735       if (CLASS_TYPE_P (tmp))
18736         {
18737           /* Local classes are not independent templates; they are
18738              instantiated along with their containing function.  And this
18739              way we don't have to deal with pushing out of one local class
18740              to instantiate a member of another local class.  */
18741           /* Closures are handled by the LAMBDA_EXPR.  */
18742           gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
18743           complete_type (tmp);
18744           for (tree fld = TYPE_FIELDS (tmp); fld; fld = DECL_CHAIN (fld))
18745             if ((VAR_P (fld)
18746                  || (TREE_CODE (fld) == FUNCTION_DECL
18747                      && !DECL_ARTIFICIAL (fld)))
18748                 && DECL_TEMPLATE_INSTANTIATION (fld))
18749               instantiate_decl (fld, /*defer_ok=*/false,
18750                                 /*expl_inst_class=*/false);
18751         }
18752       break;
18753
18754     case STATIC_ASSERT:
18755       {
18756         tree condition;
18757
18758         ++c_inhibit_evaluation_warnings;
18759         condition =
18760           tsubst_expr (STATIC_ASSERT_CONDITION (t),
18761                        args,
18762                        complain, in_decl,
18763                        /*integral_constant_expression_p=*/true);
18764         --c_inhibit_evaluation_warnings;
18765
18766         finish_static_assert (condition,
18767                               STATIC_ASSERT_MESSAGE (t),
18768                               STATIC_ASSERT_SOURCE_LOCATION (t),
18769                               /*member_p=*/false, /*show_expr_p=*/true);
18770       }
18771       break;
18772
18773     case OACC_KERNELS:
18774     case OACC_PARALLEL:
18775     case OACC_SERIAL:
18776       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_ACC, args, complain,
18777                                 in_decl);
18778       stmt = begin_omp_parallel ();
18779       RECUR (OMP_BODY (t));
18780       finish_omp_construct (TREE_CODE (t), stmt, tmp);
18781       break;
18782
18783     case OMP_PARALLEL:
18784       r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
18785       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), C_ORT_OMP, args,
18786                                 complain, in_decl);
18787       if (OMP_PARALLEL_COMBINED (t))
18788         omp_parallel_combined_clauses = &tmp;
18789       stmt = begin_omp_parallel ();
18790       RECUR (OMP_PARALLEL_BODY (t));
18791       gcc_assert (omp_parallel_combined_clauses == NULL);
18792       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
18793         = OMP_PARALLEL_COMBINED (t);
18794       pop_omp_privatization_clauses (r);
18795       break;
18796
18797     case OMP_TASK:
18798       if (OMP_TASK_BODY (t) == NULL_TREE)
18799         {
18800           tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
18801                                     complain, in_decl);
18802           t = copy_node (t);
18803           OMP_TASK_CLAUSES (t) = tmp;
18804           add_stmt (t);
18805           break;
18806         }
18807       r = push_omp_privatization_clauses (false);
18808       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
18809                                 complain, in_decl);
18810       stmt = begin_omp_task ();
18811       RECUR (OMP_TASK_BODY (t));
18812       finish_omp_task (tmp, stmt);
18813       pop_omp_privatization_clauses (r);
18814       break;
18815
18816     case OMP_FOR:
18817     case OMP_LOOP:
18818     case OMP_SIMD:
18819     case OMP_DISTRIBUTE:
18820     case OMP_TASKLOOP:
18821     case OACC_LOOP:
18822       {
18823         tree clauses, body, pre_body;
18824         tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
18825         tree orig_declv = NULL_TREE;
18826         tree incrv = NULL_TREE;
18827         enum c_omp_region_type ort = C_ORT_OMP;
18828         bool any_range_for = false;
18829         int i;
18830
18831         if (TREE_CODE (t) == OACC_LOOP)
18832           ort = C_ORT_ACC;
18833
18834         r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
18835         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), ort, args, complain,
18836                                       in_decl);
18837         if (OMP_FOR_INIT (t) != NULL_TREE)
18838           {
18839             declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18840             if (OMP_FOR_ORIG_DECLS (t))
18841               orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18842             initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18843             condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18844             incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18845           }
18846
18847         keep_next_level (true);
18848         stmt = begin_omp_structured_block ();
18849
18850         pre_body = push_stmt_list ();
18851         RECUR (OMP_FOR_PRE_BODY (t));
18852         pre_body = pop_stmt_list (pre_body);
18853
18854         if (OMP_FOR_INIT (t) != NULL_TREE)
18855           for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
18856             any_range_for
18857               |= tsubst_omp_for_iterator (t, i, declv, orig_declv, initv,
18858                                           condv, incrv, &clauses, args,
18859                                           complain, in_decl,
18860                                           integral_constant_expression_p);
18861         omp_parallel_combined_clauses = NULL;
18862
18863         if (any_range_for)
18864           {
18865             gcc_assert (orig_declv);
18866             body = begin_omp_structured_block ();
18867             for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
18868               if (TREE_VEC_ELT (orig_declv, i) != TREE_VEC_ELT (declv, i)
18869                   && TREE_CODE (TREE_VEC_ELT (orig_declv, i)) == TREE_LIST
18870                   && TREE_CHAIN (TREE_VEC_ELT (orig_declv, i)))
18871                 cp_finish_omp_range_for (TREE_VEC_ELT (orig_declv, i),
18872                                          TREE_VEC_ELT (declv, i));
18873           }
18874         else
18875           body = push_stmt_list ();
18876         RECUR (OMP_FOR_BODY (t));
18877         if (any_range_for)
18878           body = finish_omp_structured_block (body);
18879         else
18880           body = pop_stmt_list (body);
18881
18882         if (OMP_FOR_INIT (t) != NULL_TREE)
18883           t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
18884                               orig_declv, initv, condv, incrv, body, pre_body,
18885                               NULL, clauses);
18886         else
18887           {
18888             t = make_node (TREE_CODE (t));
18889             TREE_TYPE (t) = void_type_node;
18890             OMP_FOR_BODY (t) = body;
18891             OMP_FOR_PRE_BODY (t) = pre_body;
18892             OMP_FOR_CLAUSES (t) = clauses;
18893             SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
18894             add_stmt (t);
18895           }
18896
18897         add_stmt (finish_omp_for_block (finish_omp_structured_block (stmt),
18898                                         t));
18899         pop_omp_privatization_clauses (r);
18900       }
18901       break;
18902
18903     case OMP_SECTIONS:
18904       omp_parallel_combined_clauses = NULL;
18905       /* FALLTHRU */
18906     case OMP_SINGLE:
18907     case OMP_TEAMS:
18908     case OMP_CRITICAL:
18909     case OMP_TASKGROUP:
18910     case OMP_SCAN:
18911       r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
18912                                           && OMP_TEAMS_COMBINED (t));
18913       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_OMP, args, complain,
18914                                 in_decl);
18915       if (TREE_CODE (t) == OMP_TEAMS)
18916         {
18917           keep_next_level (true);
18918           stmt = begin_omp_structured_block ();
18919           RECUR (OMP_BODY (t));
18920           stmt = finish_omp_structured_block (stmt);
18921         }
18922       else
18923         {
18924           stmt = push_stmt_list ();
18925           RECUR (OMP_BODY (t));
18926           stmt = pop_stmt_list (stmt);
18927         }
18928
18929       if (TREE_CODE (t) == OMP_CRITICAL
18930           && tmp != NULL_TREE
18931           && integer_nonzerop (OMP_CLAUSE_HINT_EXPR (tmp)))
18932         {
18933           error_at (OMP_CLAUSE_LOCATION (tmp),
18934                     "%<#pragma omp critical%> with %<hint%> clause requires "
18935                     "a name, except when %<omp_sync_hint_none%> is used");
18936           RETURN (error_mark_node);
18937         }
18938       t = copy_node (t);
18939       OMP_BODY (t) = stmt;
18940       OMP_CLAUSES (t) = tmp;
18941       add_stmt (t);
18942       pop_omp_privatization_clauses (r);
18943       break;
18944
18945     case OMP_DEPOBJ:
18946       r = RECUR (OMP_DEPOBJ_DEPOBJ (t));
18947       if (OMP_DEPOBJ_CLAUSES (t) && OMP_DEPOBJ_CLAUSES (t) != error_mark_node)
18948         {
18949           enum omp_clause_depend_kind kind = OMP_CLAUSE_DEPEND_SOURCE;
18950           if (TREE_CODE (OMP_DEPOBJ_CLAUSES (t)) == OMP_CLAUSE)
18951             {
18952               tmp = tsubst_omp_clauses (OMP_DEPOBJ_CLAUSES (t), C_ORT_OMP,
18953                                         args, complain, in_decl);
18954               if (tmp == NULL_TREE)
18955                 tmp = error_mark_node;
18956             }
18957           else
18958             {
18959               kind = (enum omp_clause_depend_kind)
18960                      tree_to_uhwi (OMP_DEPOBJ_CLAUSES (t));
18961               tmp = NULL_TREE;
18962             }
18963           finish_omp_depobj (EXPR_LOCATION (t), r, kind, tmp);
18964         }
18965       else
18966         finish_omp_depobj (EXPR_LOCATION (t), r,
18967                            OMP_CLAUSE_DEPEND_SOURCE,
18968                            OMP_DEPOBJ_CLAUSES (t));
18969       break;
18970
18971     case OACC_DATA:
18972     case OMP_TARGET_DATA:
18973     case OMP_TARGET:
18974       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), (TREE_CODE (t) == OACC_DATA)
18975                                 ? C_ORT_ACC : C_ORT_OMP, args, complain,
18976                                 in_decl);
18977       keep_next_level (true);
18978       stmt = begin_omp_structured_block ();
18979
18980       RECUR (OMP_BODY (t));
18981       stmt = finish_omp_structured_block (stmt);
18982
18983       t = copy_node (t);
18984       OMP_BODY (t) = stmt;
18985       OMP_CLAUSES (t) = tmp;
18986       if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
18987         {
18988           tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
18989           if (teams)
18990             {
18991               /* For combined target teams, ensure the num_teams and
18992                  thread_limit clause expressions are evaluated on the host,
18993                  before entering the target construct.  */
18994               tree c;
18995               for (c = OMP_TEAMS_CLAUSES (teams);
18996                    c; c = OMP_CLAUSE_CHAIN (c))
18997                 if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
18998                      || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
18999                     && TREE_CODE (OMP_CLAUSE_OPERAND (c, 0)) != INTEGER_CST)
19000                   {
19001                     tree expr = OMP_CLAUSE_OPERAND (c, 0);
19002                     expr = force_target_expr (TREE_TYPE (expr), expr, tf_none);
19003                     if (expr == error_mark_node)
19004                       continue;
19005                     tmp = TARGET_EXPR_SLOT (expr);
19006                     add_stmt (expr);
19007                     OMP_CLAUSE_OPERAND (c, 0) = expr;
19008                     tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
19009                                                 OMP_CLAUSE_FIRSTPRIVATE);
19010                     OMP_CLAUSE_DECL (tc) = tmp;
19011                     OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
19012                     OMP_TARGET_CLAUSES (t) = tc;
19013                   }
19014             }
19015         }
19016       add_stmt (t);
19017       break;
19018
19019     case OACC_DECLARE:
19020       t = copy_node (t);
19021       tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), C_ORT_ACC, args,
19022                                 complain, in_decl);
19023       OACC_DECLARE_CLAUSES (t) = tmp;
19024       add_stmt (t);
19025       break;
19026
19027     case OMP_TARGET_UPDATE:
19028     case OMP_TARGET_ENTER_DATA:
19029     case OMP_TARGET_EXIT_DATA:
19030       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_OMP, args,
19031                                 complain, in_decl);
19032       t = copy_node (t);
19033       OMP_STANDALONE_CLAUSES (t) = tmp;
19034       add_stmt (t);
19035       break;
19036
19037     case OACC_CACHE:
19038     case OACC_ENTER_DATA:
19039     case OACC_EXIT_DATA:
19040     case OACC_UPDATE:
19041       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_ACC, args,
19042                                 complain, in_decl);
19043       t = copy_node (t);
19044       OMP_STANDALONE_CLAUSES (t) = tmp;
19045       add_stmt (t);
19046       break;
19047
19048     case OMP_ORDERED:
19049       tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), C_ORT_OMP, args,
19050                                 complain, in_decl);
19051       stmt = push_stmt_list ();
19052       RECUR (OMP_BODY (t));
19053       stmt = pop_stmt_list (stmt);
19054
19055       t = copy_node (t);
19056       OMP_BODY (t) = stmt;
19057       OMP_ORDERED_CLAUSES (t) = tmp;
19058       add_stmt (t);
19059       break;
19060
19061     case OMP_MASTER:
19062       omp_parallel_combined_clauses = NULL;
19063       /* FALLTHRU */
19064     case OMP_SECTION:
19065       stmt = push_stmt_list ();
19066       RECUR (OMP_BODY (t));
19067       stmt = pop_stmt_list (stmt);
19068
19069       t = copy_node (t);
19070       OMP_BODY (t) = stmt;
19071       add_stmt (t);
19072       break;
19073
19074     case OMP_ATOMIC:
19075       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
19076       tmp = NULL_TREE;
19077       if (TREE_CODE (TREE_OPERAND (t, 0)) == OMP_CLAUSE)
19078         tmp = tsubst_omp_clauses (TREE_OPERAND (t, 0), C_ORT_OMP, args,
19079                                   complain, in_decl);
19080       if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
19081         {
19082           tree op1 = TREE_OPERAND (t, 1);
19083           tree rhs1 = NULL_TREE;
19084           tree lhs, rhs;
19085           if (TREE_CODE (op1) == COMPOUND_EXPR)
19086             {
19087               rhs1 = RECUR (TREE_OPERAND (op1, 0));
19088               op1 = TREE_OPERAND (op1, 1);
19089             }
19090           lhs = RECUR (TREE_OPERAND (op1, 0));
19091           rhs = RECUR (TREE_OPERAND (op1, 1));
19092           finish_omp_atomic (EXPR_LOCATION (t), OMP_ATOMIC, TREE_CODE (op1),
19093                              lhs, rhs, NULL_TREE, NULL_TREE, rhs1, tmp,
19094                              OMP_ATOMIC_MEMORY_ORDER (t));
19095         }
19096       else
19097         {
19098           tree op1 = TREE_OPERAND (t, 1);
19099           tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
19100           tree rhs1 = NULL_TREE;
19101           enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
19102           enum tree_code opcode = NOP_EXPR;
19103           if (code == OMP_ATOMIC_READ)
19104             {
19105               v = RECUR (TREE_OPERAND (op1, 0));
19106               lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19107             }
19108           else if (code == OMP_ATOMIC_CAPTURE_OLD
19109                    || code == OMP_ATOMIC_CAPTURE_NEW)
19110             {
19111               tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
19112               v = RECUR (TREE_OPERAND (op1, 0));
19113               lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19114               if (TREE_CODE (op11) == COMPOUND_EXPR)
19115                 {
19116                   rhs1 = RECUR (TREE_OPERAND (op11, 0));
19117                   op11 = TREE_OPERAND (op11, 1);
19118                 }
19119               lhs = RECUR (TREE_OPERAND (op11, 0));
19120               rhs = RECUR (TREE_OPERAND (op11, 1));
19121               opcode = TREE_CODE (op11);
19122               if (opcode == MODIFY_EXPR)
19123                 opcode = NOP_EXPR;
19124             }
19125           else
19126             {
19127               code = OMP_ATOMIC;
19128               lhs = RECUR (TREE_OPERAND (op1, 0));
19129               rhs = RECUR (TREE_OPERAND (op1, 1));
19130             }
19131           finish_omp_atomic (EXPR_LOCATION (t), code, opcode, lhs, rhs, v,
19132                              lhs1, rhs1, tmp, OMP_ATOMIC_MEMORY_ORDER (t));
19133         }
19134       break;
19135
19136     case TRANSACTION_EXPR:
19137       {
19138         int flags = 0;
19139         flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
19140         flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
19141
19142         if (TRANSACTION_EXPR_IS_STMT (t))
19143           {
19144             tree body = TRANSACTION_EXPR_BODY (t);
19145             tree noex = NULL_TREE;
19146             if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
19147               {
19148                 noex = MUST_NOT_THROW_COND (body);
19149                 if (noex == NULL_TREE)
19150                   noex = boolean_true_node;
19151                 body = TREE_OPERAND (body, 0);
19152               }
19153             stmt = begin_transaction_stmt (input_location, NULL, flags);
19154             RECUR (body);
19155             finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
19156           }
19157         else
19158           {
19159             stmt = build_transaction_expr (EXPR_LOCATION (t),
19160                                            RECUR (TRANSACTION_EXPR_BODY (t)),
19161                                            flags, NULL_TREE);
19162             RETURN (stmt);
19163           }
19164       }
19165       break;
19166
19167     case MUST_NOT_THROW_EXPR:
19168       {
19169         tree op0 = RECUR (TREE_OPERAND (t, 0));
19170         tree cond = RECUR (MUST_NOT_THROW_COND (t));
19171         RETURN (build_must_not_throw_expr (op0, cond));
19172       }
19173
19174     case EXPR_PACK_EXPANSION:
19175       error ("invalid use of pack expansion expression");
19176       RETURN (error_mark_node);
19177
19178     case NONTYPE_ARGUMENT_PACK:
19179       error ("use %<...%> to expand argument pack");
19180       RETURN (error_mark_node);
19181
19182     case COMPOUND_EXPR:
19183       tmp = RECUR (TREE_OPERAND (t, 0));
19184       if (tmp == NULL_TREE)
19185         /* If the first operand was a statement, we're done with it.  */
19186         RETURN (RECUR (TREE_OPERAND (t, 1)));
19187       RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
19188                                     RECUR (TREE_OPERAND (t, 1)),
19189                                     complain));
19190
19191     case ANNOTATE_EXPR:
19192       tmp = RECUR (TREE_OPERAND (t, 0));
19193       RETURN (build3_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
19194                           TREE_TYPE (tmp), tmp,
19195                           RECUR (TREE_OPERAND (t, 1)),
19196                           RECUR (TREE_OPERAND (t, 2))));
19197
19198     case PREDICT_EXPR:
19199       RETURN (add_stmt (copy_node (t)));
19200
19201     default:
19202       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
19203
19204       RETURN (tsubst_copy_and_build (t, args, complain, in_decl,
19205                                     /*function_p=*/false,
19206                                     integral_constant_expression_p));
19207     }
19208
19209   RETURN (NULL_TREE);
19210  out:
19211   input_location = loc;
19212   return r;
19213 #undef RECUR
19214 #undef RETURN
19215 }
19216
19217 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
19218    function.  For description of the body see comment above
19219    cp_parser_omp_declare_reduction_exprs.  */
19220
19221 static void
19222 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19223 {
19224   if (t == NULL_TREE || t == error_mark_node)
19225     return;
19226
19227   gcc_assert (TREE_CODE (t) == STATEMENT_LIST && current_function_decl);
19228
19229   tree_stmt_iterator tsi;
19230   int i;
19231   tree stmts[7];
19232   memset (stmts, 0, sizeof stmts);
19233   for (i = 0, tsi = tsi_start (t);
19234        i < 7 && !tsi_end_p (tsi);
19235        i++, tsi_next (&tsi))
19236     stmts[i] = tsi_stmt (tsi);
19237   gcc_assert (tsi_end_p (tsi));
19238
19239   if (i >= 3)
19240     {
19241       gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
19242                   && TREE_CODE (stmts[1]) == DECL_EXPR);
19243       tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
19244                              args, complain, in_decl);
19245       tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
19246                             args, complain, in_decl);
19247       /* tsubsting a local var_decl leaves DECL_CONTEXT null, as we
19248          expect to be pushing it.  */
19249       DECL_CONTEXT (omp_out) = current_function_decl;
19250       DECL_CONTEXT (omp_in) = current_function_decl;
19251       keep_next_level (true);
19252       tree block = begin_omp_structured_block ();
19253       tsubst_expr (stmts[2], args, complain, in_decl, false);
19254       block = finish_omp_structured_block (block);
19255       block = maybe_cleanup_point_expr_void (block);
19256       add_decl_expr (omp_out);
19257       if (TREE_NO_WARNING (DECL_EXPR_DECL (stmts[0])))
19258         TREE_NO_WARNING (omp_out) = 1;
19259       add_decl_expr (omp_in);
19260       finish_expr_stmt (block);
19261     }
19262   if (i >= 6)
19263     {
19264       gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
19265                   && TREE_CODE (stmts[4]) == DECL_EXPR);
19266       tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
19267                               args, complain, in_decl);
19268       tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
19269                               args, complain, in_decl);
19270       DECL_CONTEXT (omp_priv) = current_function_decl;
19271       DECL_CONTEXT (omp_orig) = current_function_decl;
19272       keep_next_level (true);
19273       tree block = begin_omp_structured_block ();
19274       tsubst_expr (stmts[5], args, complain, in_decl, false);
19275       block = finish_omp_structured_block (block);
19276       block = maybe_cleanup_point_expr_void (block);
19277       cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
19278       add_decl_expr (omp_priv);
19279       add_decl_expr (omp_orig);
19280       finish_expr_stmt (block);
19281       if (i == 7)
19282         add_decl_expr (omp_orig);
19283     }
19284 }
19285
19286 /* T is a postfix-expression that is not being used in a function
19287    call.  Return the substituted version of T.  */
19288
19289 static tree
19290 tsubst_non_call_postfix_expression (tree t, tree args,
19291                                     tsubst_flags_t complain,
19292                                     tree in_decl)
19293 {
19294   if (TREE_CODE (t) == SCOPE_REF)
19295     t = tsubst_qualified_id (t, args, complain, in_decl,
19296                              /*done=*/false, /*address_p=*/false);
19297   else
19298     t = tsubst_copy_and_build (t, args, complain, in_decl,
19299                                /*function_p=*/false,
19300                                /*integral_constant_expression_p=*/false);
19301
19302   return t;
19303 }
19304
19305 /* Subroutine of tsubst_lambda_expr: add the FIELD/INIT capture pair to the
19306    LAMBDA_EXPR_CAPTURE_LIST passed in LIST.  Do deduction for a previously
19307    dependent init-capture.  */
19308
19309 static void
19310 prepend_one_capture (tree field, tree init, tree &list,
19311                      tsubst_flags_t complain)
19312 {
19313   if (tree auto_node = type_uses_auto (TREE_TYPE (field)))
19314     {
19315       tree type = NULL_TREE;
19316       if (!init)
19317         {
19318           if (complain & tf_error)
19319             error ("empty initializer in lambda init-capture");
19320           init = error_mark_node;
19321         }
19322       else if (TREE_CODE (init) == TREE_LIST)
19323         init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19324       if (!type)
19325         type = do_auto_deduction (TREE_TYPE (field), init, auto_node, complain);
19326       TREE_TYPE (field) = type;
19327       cp_apply_type_quals_to_decl (cp_type_quals (type), field);
19328     }
19329   list = tree_cons (field, init, list);
19330 }
19331
19332 /* T is a LAMBDA_EXPR.  Generate a new LAMBDA_EXPR for the current
19333    instantiation context.  Instantiating a pack expansion containing a lambda
19334    might result in multiple lambdas all based on the same lambda in the
19335    template.  */
19336
19337 tree
19338 tsubst_lambda_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19339 {
19340   tree oldfn = lambda_function (t);
19341   in_decl = oldfn;
19342
19343   tree r = build_lambda_expr ();
19344
19345   LAMBDA_EXPR_LOCATION (r)
19346     = LAMBDA_EXPR_LOCATION (t);
19347   LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
19348     = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
19349   LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
19350   if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
19351     LAMBDA_EXPR_REGEN_INFO (r)
19352       = build_template_info (t, add_to_template_args (TI_ARGS (ti), args));
19353   else
19354     LAMBDA_EXPR_REGEN_INFO (r)
19355       = build_template_info (t, args);
19356
19357   gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
19358               && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
19359
19360   vec<tree,va_gc>* field_packs = NULL;
19361
19362   for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t); cap;
19363        cap = TREE_CHAIN (cap))
19364     {
19365       tree ofield = TREE_PURPOSE (cap);
19366       tree init = TREE_VALUE (cap);
19367       if (PACK_EXPANSION_P (init))
19368         init = tsubst_pack_expansion (init, args, complain, in_decl);
19369       else
19370         init = tsubst_copy_and_build (init, args, complain, in_decl,
19371                                       /*fn*/false, /*constexpr*/false);
19372
19373       if (init == error_mark_node)
19374         return error_mark_node;
19375
19376       if (init && TREE_CODE (init) == TREE_LIST)
19377         init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19378
19379       if (!processing_template_decl
19380           && init && TREE_CODE (init) != TREE_VEC
19381           && variably_modified_type_p (TREE_TYPE (init), NULL_TREE))
19382         {
19383           /* For a VLA, simply tsubsting the field type won't work, we need to
19384              go through add_capture again.  XXX do we want to do this for all
19385              captures?  */
19386           tree name = (get_identifier
19387                        (IDENTIFIER_POINTER (DECL_NAME (ofield)) + 2));
19388           tree ftype = TREE_TYPE (ofield);
19389           bool by_ref = (TYPE_REF_P (ftype)
19390                          || (TREE_CODE (ftype) == DECLTYPE_TYPE
19391                              && DECLTYPE_FOR_REF_CAPTURE (ftype)));
19392           add_capture (r, name, init, by_ref, !DECL_NORMAL_CAPTURE_P (ofield));
19393           continue;
19394         }
19395
19396       if (PACK_EXPANSION_P (ofield))
19397         ofield = PACK_EXPANSION_PATTERN (ofield);
19398       tree field = tsubst_decl (ofield, args, complain);
19399
19400       if (DECL_PACK_P (ofield) && !DECL_NORMAL_CAPTURE_P (ofield))
19401         {
19402           /* Remember these for when we've pushed local_specializations.  */
19403           vec_safe_push (field_packs, ofield);
19404           vec_safe_push (field_packs, field);
19405         }
19406
19407       if (field == error_mark_node)
19408         return error_mark_node;
19409
19410       if (TREE_CODE (field) == TREE_VEC)
19411         {
19412           int len = TREE_VEC_LENGTH (field);
19413           gcc_assert (TREE_CODE (init) == TREE_VEC
19414                       && TREE_VEC_LENGTH (init) == len);
19415           for (int i = 0; i < len; ++i)
19416             prepend_one_capture (TREE_VEC_ELT (field, i),
19417                                  TREE_VEC_ELT (init, i),
19418                                  LAMBDA_EXPR_CAPTURE_LIST (r),
19419                                  complain);
19420         }
19421       else
19422         {
19423           prepend_one_capture (field, init, LAMBDA_EXPR_CAPTURE_LIST (r),
19424                                complain);
19425
19426           if (id_equal (DECL_NAME (field), "__this"))
19427             LAMBDA_EXPR_THIS_CAPTURE (r) = field;
19428         }
19429     }
19430
19431   tree type = begin_lambda_type (r);
19432   if (type == error_mark_node)
19433     return error_mark_node;
19434
19435   if (LAMBDA_EXPR_EXTRA_SCOPE (t) == NULL_TREE)
19436     /* A lambda in a default argument outside a class gets no
19437        LAMBDA_EXPR_EXTRA_SCOPE, as specified by the ABI.  But
19438        tsubst_default_argument calls start_lambda_scope, so we need to
19439        specifically ignore it here, and use the global scope.  */
19440     record_null_lambda_scope (r);
19441   else
19442     record_lambda_scope (r);
19443
19444   /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
19445   determine_visibility (TYPE_NAME (type));
19446
19447   register_capture_members (LAMBDA_EXPR_CAPTURE_LIST (r));
19448
19449   tree oldtmpl = (generic_lambda_fn_p (oldfn)
19450                   ? DECL_TI_TEMPLATE (oldfn)
19451                   : NULL_TREE);
19452
19453   tree fntype = static_fn_type (oldfn);
19454   if (oldtmpl)
19455     ++processing_template_decl;
19456   fntype = tsubst (fntype, args, complain, in_decl);
19457   if (oldtmpl)
19458     --processing_template_decl;
19459
19460   if (fntype == error_mark_node)
19461     r = error_mark_node;
19462   else
19463     {
19464       /* The body of a lambda-expression is not a subexpression of the
19465          enclosing expression.  Parms are to have DECL_CHAIN tsubsted,
19466          which would be skipped if cp_unevaluated_operand.  */
19467       cp_evaluated ev;
19468
19469       /* Fix the type of 'this'.  */
19470       fntype = build_memfn_type (fntype, type,
19471                                  type_memfn_quals (fntype),
19472                                  type_memfn_rqual (fntype));
19473       tree fn, tmpl;
19474       if (oldtmpl)
19475         {
19476           tmpl = tsubst_template_decl (oldtmpl, args, complain, fntype);
19477           if (tmpl == error_mark_node)
19478             {
19479               r = error_mark_node;
19480               goto out;
19481             }
19482           fn = DECL_TEMPLATE_RESULT (tmpl);
19483           finish_member_declaration (tmpl);
19484         }
19485       else
19486         {
19487           tmpl = NULL_TREE;
19488           fn = tsubst_function_decl (oldfn, args, complain, fntype);
19489           if (fn == error_mark_node)
19490             {
19491               r = error_mark_node;
19492               goto out;
19493             }
19494           finish_member_declaration (fn);
19495         }
19496
19497       /* Let finish_function set this.  */
19498       DECL_DECLARED_CONSTEXPR_P (fn) = false;
19499
19500       bool nested = cfun;
19501       if (nested)
19502         push_function_context ();
19503       else
19504         /* Still increment function_depth so that we don't GC in the
19505            middle of an expression.  */
19506         ++function_depth;
19507
19508       local_specialization_stack s (lss_copy);
19509
19510       tree body = start_lambda_function (fn, r);
19511
19512       /* Now record them for lookup_init_capture_pack.  */
19513       int fplen = vec_safe_length (field_packs);
19514       for (int i = 0; i < fplen; )
19515         {
19516           tree pack = (*field_packs)[i++];
19517           tree inst = (*field_packs)[i++];
19518           register_local_specialization (inst, pack);
19519         }
19520       release_tree_vector (field_packs);
19521
19522       register_parameter_specializations (oldfn, fn);
19523
19524       if (oldtmpl)
19525         {
19526           /* We might not partially instantiate some parts of the function, so
19527              copy these flags from the original template.  */
19528           language_function *ol = DECL_STRUCT_FUNCTION (oldfn)->language;
19529           current_function_returns_value = ol->returns_value;
19530           current_function_returns_null = ol->returns_null;
19531           current_function_returns_abnormally = ol->returns_abnormally;
19532           current_function_infinite_loop = ol->infinite_loop;
19533         }
19534
19535       /* [temp.deduct] A lambda-expression appearing in a function type or a
19536          template parameter is not considered part of the immediate context for
19537          the purposes of template argument deduction. */
19538       complain = tf_warning_or_error;
19539
19540       tree saved = DECL_SAVED_TREE (oldfn);
19541       if (TREE_CODE (saved) == BIND_EXPR && BIND_EXPR_BODY_BLOCK (saved))
19542         /* We already have a body block from start_lambda_function, we don't
19543            need another to confuse NRV (91217).  */
19544         saved = BIND_EXPR_BODY (saved);
19545
19546       tsubst_expr (saved, args, complain, r, /*constexpr*/false);
19547
19548       finish_lambda_function (body);
19549
19550       if (nested)
19551         pop_function_context ();
19552       else
19553         --function_depth;
19554
19555       /* The capture list was built up in reverse order; fix that now.  */
19556       LAMBDA_EXPR_CAPTURE_LIST (r)
19557         = nreverse (LAMBDA_EXPR_CAPTURE_LIST (r));
19558
19559       LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
19560
19561       maybe_add_lambda_conv_op (type);
19562     }
19563
19564 out:
19565   finish_struct (type, /*attr*/NULL_TREE);
19566
19567   insert_pending_capture_proxies ();
19568
19569   return r;
19570 }
19571
19572 /* Like tsubst but deals with expressions and performs semantic
19573    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)" or
19574    "F<TARGS> (ARGS)".  */
19575
19576 tree
19577 tsubst_copy_and_build (tree t,
19578                        tree args,
19579                        tsubst_flags_t complain,
19580                        tree in_decl,
19581                        bool function_p,
19582                        bool integral_constant_expression_p)
19583 {
19584 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
19585 #define RECUR(NODE)                                             \
19586   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
19587                          /*function_p=*/false,                  \
19588                          integral_constant_expression_p)
19589
19590   tree retval, op1;
19591   location_t save_loc;
19592
19593   if (t == NULL_TREE || t == error_mark_node)
19594     return t;
19595
19596   save_loc = input_location;
19597   if (location_t eloc = cp_expr_location (t))
19598     input_location = eloc;
19599
19600   /* N3276 decltype magic only applies to calls at the top level or on the
19601      right side of a comma.  */
19602   tsubst_flags_t decltype_flag = (complain & tf_decltype);
19603   complain &= ~tf_decltype;
19604
19605   switch (TREE_CODE (t))
19606     {
19607     case USING_DECL:
19608       t = DECL_NAME (t);
19609       /* Fall through.  */
19610     case IDENTIFIER_NODE:
19611       {
19612         tree decl;
19613         cp_id_kind idk;
19614         bool non_integral_constant_expression_p;
19615         const char *error_msg;
19616
19617         if (IDENTIFIER_CONV_OP_P (t))
19618           {
19619             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19620             t = make_conv_op_name (new_type);
19621           }
19622
19623         /* Look up the name.  */
19624         decl = lookup_name (t);
19625
19626         /* By convention, expressions use ERROR_MARK_NODE to indicate
19627            failure, not NULL_TREE.  */
19628         if (decl == NULL_TREE)
19629           decl = error_mark_node;
19630
19631         decl = finish_id_expression (t, decl, NULL_TREE,
19632                                      &idk,
19633                                      integral_constant_expression_p,
19634           /*allow_non_integral_constant_expression_p=*/(cxx_dialect >= cxx11),
19635                                      &non_integral_constant_expression_p,
19636                                      /*template_p=*/false,
19637                                      /*done=*/true,
19638                                      /*address_p=*/false,
19639                                      /*template_arg_p=*/false,
19640                                      &error_msg,
19641                                      input_location);
19642         if (error_msg)
19643           error (error_msg);
19644         if (!function_p && identifier_p (decl))
19645           {
19646             if (complain & tf_error)
19647               unqualified_name_lookup_error (decl);
19648             decl = error_mark_node;
19649           }
19650         RETURN (decl);
19651       }
19652
19653     case TEMPLATE_ID_EXPR:
19654       {
19655         tree object;
19656         tree templ = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
19657                                             complain, in_decl,
19658                                             function_p,
19659                                             integral_constant_expression_p);
19660         tree targs = TREE_OPERAND (t, 1);
19661
19662         if (targs)
19663           targs = tsubst_template_args (targs, args, complain, in_decl);
19664         if (targs == error_mark_node)
19665           RETURN (error_mark_node);
19666
19667         if (TREE_CODE (templ) == SCOPE_REF)
19668           {
19669             tree name = TREE_OPERAND (templ, 1);
19670             tree tid = lookup_template_function (name, targs);
19671             TREE_OPERAND (templ, 1) = tid;
19672             RETURN (templ);
19673           }
19674
19675         if (concept_definition_p (templ))
19676           {
19677             tree check = build_concept_check (templ, targs, complain);
19678             if (check == error_mark_node)
19679               RETURN (error_mark_node);
19680
19681             tree id = unpack_concept_check (check);
19682
19683             /* If we built a function concept check, return the underlying
19684                template-id. So we can evaluate it as a function call.  */
19685             if (function_concept_p (TREE_OPERAND (id, 0)))
19686               RETURN (id);
19687
19688             RETURN (check);
19689           }
19690
19691         if (variable_template_p (templ))
19692           {
19693             tree r = lookup_and_finish_template_variable (templ, targs,
19694                                                           complain);
19695             r = maybe_wrap_with_location (r, EXPR_LOCATION (t));
19696             RETURN (r);
19697           }
19698
19699         if (TREE_CODE (templ) == COMPONENT_REF)
19700           {
19701             object = TREE_OPERAND (templ, 0);
19702             templ = TREE_OPERAND (templ, 1);
19703           }
19704         else
19705           object = NULL_TREE;
19706
19707         tree tid = lookup_template_function (templ, targs);
19708
19709         if (object)
19710           RETURN (build3 (COMPONENT_REF, TREE_TYPE (tid),
19711                          object, tid, NULL_TREE));
19712         else if (identifier_p (templ))
19713           {
19714             /* C++20 P0846: we can encounter an IDENTIFIER_NODE here when
19715                name lookup found nothing when parsing the template name.  */
19716             gcc_assert (cxx_dialect >= cxx20 || seen_error ());
19717             RETURN (tid);
19718           }
19719         else
19720           RETURN (baselink_for_fns (tid));
19721       }
19722
19723     case INDIRECT_REF:
19724       {
19725         tree r = RECUR (TREE_OPERAND (t, 0));
19726
19727         if (REFERENCE_REF_P (t))
19728           {
19729             /* A type conversion to reference type will be enclosed in
19730                such an indirect ref, but the substitution of the cast
19731                will have also added such an indirect ref.  */
19732             r = convert_from_reference (r);
19733           }
19734         else
19735           r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
19736                                     complain|decltype_flag);
19737
19738         if (REF_PARENTHESIZED_P (t))
19739           r = force_paren_expr (r);
19740
19741         RETURN (r);
19742       }
19743
19744     case NOP_EXPR:
19745       {
19746         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19747         tree op0 = RECUR (TREE_OPERAND (t, 0));
19748         RETURN (build_nop (type, op0));
19749       }
19750
19751     case IMPLICIT_CONV_EXPR:
19752       {
19753         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19754         tree expr = RECUR (TREE_OPERAND (t, 0));
19755         if (dependent_type_p (type) || type_dependent_expression_p (expr))
19756           {
19757             retval = copy_node (t);
19758             TREE_TYPE (retval) = type;
19759             TREE_OPERAND (retval, 0) = expr;
19760             RETURN (retval);
19761           }
19762         if (IMPLICIT_CONV_EXPR_NONTYPE_ARG (t))
19763           /* We'll pass this to convert_nontype_argument again, we don't need
19764              to actually perform any conversion here.  */
19765           RETURN (expr);
19766         int flags = LOOKUP_IMPLICIT;
19767         if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
19768           flags = LOOKUP_NORMAL;
19769         if (IMPLICIT_CONV_EXPR_BRACED_INIT (t))
19770           flags |= LOOKUP_NO_NARROWING;
19771         RETURN (perform_implicit_conversion_flags (type, expr, complain,
19772                                                   flags));
19773       }
19774
19775     case CONVERT_EXPR:
19776       {
19777         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19778         tree op0 = RECUR (TREE_OPERAND (t, 0));
19779         if (op0 == error_mark_node)
19780           RETURN (error_mark_node);
19781         RETURN (build1 (CONVERT_EXPR, type, op0));
19782       }
19783
19784     case CAST_EXPR:
19785     case REINTERPRET_CAST_EXPR:
19786     case CONST_CAST_EXPR:
19787     case DYNAMIC_CAST_EXPR:
19788     case STATIC_CAST_EXPR:
19789       {
19790         tree type;
19791         tree op, r = NULL_TREE;
19792
19793         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19794         if (integral_constant_expression_p
19795             && !cast_valid_in_integral_constant_expression_p (type))
19796           {
19797             if (complain & tf_error)
19798               error ("a cast to a type other than an integral or "
19799                      "enumeration type cannot appear in a constant-expression");
19800             RETURN (error_mark_node);
19801           }
19802
19803         op = RECUR (TREE_OPERAND (t, 0));
19804
19805         warning_sentinel s(warn_useless_cast);
19806         warning_sentinel s2(warn_ignored_qualifiers);
19807         switch (TREE_CODE (t))
19808           {
19809           case CAST_EXPR:
19810             r = build_functional_cast (input_location, type, op, complain);
19811             break;
19812           case REINTERPRET_CAST_EXPR:
19813             r = build_reinterpret_cast (input_location, type, op, complain);
19814             break;
19815           case CONST_CAST_EXPR:
19816             r = build_const_cast (input_location, type, op, complain);
19817             break;
19818           case DYNAMIC_CAST_EXPR:
19819             r = build_dynamic_cast (input_location, type, op, complain);
19820             break;
19821           case STATIC_CAST_EXPR:
19822             r = build_static_cast (input_location, type, op, complain);
19823             if (IMPLICIT_RVALUE_P (t))
19824               set_implicit_rvalue_p (r);
19825             break;
19826           default:
19827             gcc_unreachable ();
19828           }
19829
19830         RETURN (r);
19831       }
19832
19833     case BIT_CAST_EXPR:
19834       {
19835         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19836         tree op0 = RECUR (TREE_OPERAND (t, 0));
19837         RETURN (cp_build_bit_cast (EXPR_LOCATION (t), type, op0, complain));
19838       }
19839
19840     case POSTDECREMENT_EXPR:
19841     case POSTINCREMENT_EXPR:
19842       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
19843                                                 args, complain, in_decl);
19844       RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
19845                                 complain|decltype_flag));
19846
19847     case PREDECREMENT_EXPR:
19848     case PREINCREMENT_EXPR:
19849     case NEGATE_EXPR:
19850     case BIT_NOT_EXPR:
19851     case ABS_EXPR:
19852     case TRUTH_NOT_EXPR:
19853     case UNARY_PLUS_EXPR:  /* Unary + */
19854     case REALPART_EXPR:
19855     case IMAGPART_EXPR:
19856       RETURN (build_x_unary_op (input_location, TREE_CODE (t),
19857                                 RECUR (TREE_OPERAND (t, 0)),
19858                                 complain|decltype_flag));
19859
19860     case FIX_TRUNC_EXPR:
19861       /* convert_like should have created an IMPLICIT_CONV_EXPR.  */
19862       gcc_unreachable ();
19863
19864     case ADDR_EXPR:
19865       op1 = TREE_OPERAND (t, 0);
19866       if (TREE_CODE (op1) == LABEL_DECL)
19867         RETURN (finish_label_address_expr (DECL_NAME (op1),
19868                                           EXPR_LOCATION (op1)));
19869       if (TREE_CODE (op1) == SCOPE_REF)
19870         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
19871                                    /*done=*/true, /*address_p=*/true);
19872       else
19873         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
19874                                                   in_decl);
19875       RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
19876                                 complain|decltype_flag));
19877
19878     case PLUS_EXPR:
19879     case MINUS_EXPR:
19880     case MULT_EXPR:
19881     case TRUNC_DIV_EXPR:
19882     case CEIL_DIV_EXPR:
19883     case FLOOR_DIV_EXPR:
19884     case ROUND_DIV_EXPR:
19885     case EXACT_DIV_EXPR:
19886     case BIT_AND_EXPR:
19887     case BIT_IOR_EXPR:
19888     case BIT_XOR_EXPR:
19889     case TRUNC_MOD_EXPR:
19890     case FLOOR_MOD_EXPR:
19891     case TRUTH_ANDIF_EXPR:
19892     case TRUTH_ORIF_EXPR:
19893     case TRUTH_AND_EXPR:
19894     case TRUTH_OR_EXPR:
19895     case RSHIFT_EXPR:
19896     case LSHIFT_EXPR:
19897     case EQ_EXPR:
19898     case NE_EXPR:
19899     case MAX_EXPR:
19900     case MIN_EXPR:
19901     case LE_EXPR:
19902     case GE_EXPR:
19903     case LT_EXPR:
19904     case GT_EXPR:
19905     case SPACESHIP_EXPR:
19906     case MEMBER_REF:
19907     case DOTSTAR_EXPR:
19908       {
19909         /* If either OP0 or OP1 was value- or type-dependent, suppress
19910            warnings that depend on the range of the types involved.  */
19911         tree op0 = TREE_OPERAND (t, 0);
19912         tree op1 = TREE_OPERAND (t, 1);
19913         auto dep_p = [](tree t) {
19914           ++processing_template_decl;
19915           bool r = (potential_constant_expression (t)
19916                     ? value_dependent_expression_p (t)
19917                     : type_dependent_expression_p (t));
19918           --processing_template_decl;
19919           return r;
19920         };
19921         const bool was_dep = dep_p (op0) || dep_p (op1);
19922         op0 = RECUR (op0);
19923         op1 = RECUR (op1);
19924
19925         warning_sentinel s1(warn_type_limits, was_dep);
19926         warning_sentinel s2(warn_div_by_zero, was_dep);
19927         warning_sentinel s3(warn_logical_op, was_dep);
19928         warning_sentinel s4(warn_tautological_compare, was_dep);
19929
19930         tree r = build_x_binary_op
19931           (input_location, TREE_CODE (t),
19932            op0,
19933            (TREE_NO_WARNING (TREE_OPERAND (t, 0))
19934             ? ERROR_MARK
19935             : TREE_CODE (TREE_OPERAND (t, 0))),
19936            op1,
19937            (TREE_NO_WARNING (TREE_OPERAND (t, 1))
19938             ? ERROR_MARK
19939             : TREE_CODE (TREE_OPERAND (t, 1))),
19940            /*overload=*/NULL,
19941            complain|decltype_flag);
19942         if (EXPR_P (r) && TREE_NO_WARNING (t))
19943           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
19944
19945         RETURN (r);
19946       }
19947
19948     case POINTER_PLUS_EXPR:
19949       {
19950         tree op0 = RECUR (TREE_OPERAND (t, 0));
19951         if (op0 == error_mark_node)
19952           RETURN (error_mark_node);
19953         tree op1 = RECUR (TREE_OPERAND (t, 1));
19954         if (op1 == error_mark_node)
19955           RETURN (error_mark_node);
19956         RETURN (fold_build_pointer_plus (op0, op1));
19957       }
19958
19959     case SCOPE_REF:
19960       RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
19961                                   /*address_p=*/false));
19962
19963     case BASELINK:
19964       RETURN (tsubst_baselink (t, current_nonlambda_class_type (),
19965                                args, complain, in_decl));
19966
19967     case ARRAY_REF:
19968       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
19969                                                 args, complain, in_decl);
19970       RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
19971                                  RECUR (TREE_OPERAND (t, 1)),
19972                                  complain|decltype_flag));
19973
19974     case SIZEOF_EXPR:
19975       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
19976           || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
19977         RETURN (tsubst_copy (t, args, complain, in_decl));
19978       /* Fall through */
19979
19980     case ALIGNOF_EXPR:
19981       {
19982         tree r;
19983
19984         op1 = TREE_OPERAND (t, 0);
19985         if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
19986           op1 = TREE_TYPE (op1);
19987         bool std_alignof = (TREE_CODE (t) == ALIGNOF_EXPR
19988                             && ALIGNOF_EXPR_STD_P (t));
19989         if (!args)
19990           {
19991             /* When there are no ARGS, we are trying to evaluate a
19992                non-dependent expression from the parser.  Trying to do
19993                the substitutions may not work.  */
19994             if (!TYPE_P (op1))
19995               op1 = TREE_TYPE (op1);
19996           }
19997         else
19998           {
19999             ++cp_unevaluated_operand;
20000             ++c_inhibit_evaluation_warnings;
20001             if (TYPE_P (op1))
20002               op1 = tsubst (op1, args, complain, in_decl);
20003             else
20004               op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
20005                                            /*function_p=*/false,
20006                                            /*integral_constant_expression_p=*/
20007                                            false);
20008             --cp_unevaluated_operand;
20009             --c_inhibit_evaluation_warnings;
20010           }
20011         if (TYPE_P (op1))
20012           r = cxx_sizeof_or_alignof_type (input_location,
20013                                           op1, TREE_CODE (t), std_alignof,
20014                                           complain & tf_error);
20015         else
20016           r = cxx_sizeof_or_alignof_expr (input_location,
20017                                           op1, TREE_CODE (t), std_alignof,
20018                                           complain & tf_error);
20019         if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
20020           {
20021             if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
20022               {
20023                 if (!processing_template_decl && TYPE_P (op1))
20024                   {
20025                     r = build_min (SIZEOF_EXPR, size_type_node,
20026                                    build1 (NOP_EXPR, op1, error_mark_node));
20027                     SIZEOF_EXPR_TYPE_P (r) = 1;
20028                   }
20029                 else
20030                   r = build_min (SIZEOF_EXPR, size_type_node, op1);
20031                 TREE_SIDE_EFFECTS (r) = 0;
20032                 TREE_READONLY (r) = 1;
20033               }
20034             SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
20035           }
20036         RETURN (r);
20037       }
20038
20039     case AT_ENCODE_EXPR:
20040       {
20041         op1 = TREE_OPERAND (t, 0);
20042         ++cp_unevaluated_operand;
20043         ++c_inhibit_evaluation_warnings;
20044         op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
20045                                      /*function_p=*/false,
20046                                      /*integral_constant_expression_p=*/false);
20047         --cp_unevaluated_operand;
20048         --c_inhibit_evaluation_warnings;
20049         RETURN (objc_build_encode_expr (op1));
20050       }
20051
20052     case NOEXCEPT_EXPR:
20053       op1 = TREE_OPERAND (t, 0);
20054       ++cp_unevaluated_operand;
20055       ++c_inhibit_evaluation_warnings;
20056       ++cp_noexcept_operand;
20057       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
20058                                    /*function_p=*/false,
20059                                    /*integral_constant_expression_p=*/false);
20060       --cp_unevaluated_operand;
20061       --c_inhibit_evaluation_warnings;
20062       --cp_noexcept_operand;
20063       RETURN (finish_noexcept_expr (op1, complain));
20064
20065     case MODOP_EXPR:
20066       {
20067         warning_sentinel s(warn_div_by_zero);
20068         tree lhs = RECUR (TREE_OPERAND (t, 0));
20069         tree rhs = RECUR (TREE_OPERAND (t, 2));
20070         tree r = build_x_modify_expr
20071           (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
20072            complain|decltype_flag);
20073         /* TREE_NO_WARNING must be set if either the expression was
20074            parenthesized or it uses an operator such as >>= rather
20075            than plain assignment.  In the former case, it was already
20076            set and must be copied.  In the latter case,
20077            build_x_modify_expr sets it and it must not be reset
20078            here.  */
20079         if (TREE_NO_WARNING (t))
20080           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
20081
20082         RETURN (r);
20083       }
20084
20085     case ARROW_EXPR:
20086       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20087                                                 args, complain, in_decl);
20088       /* Remember that there was a reference to this entity.  */
20089       if (DECL_P (op1)
20090           && !mark_used (op1, complain) && !(complain & tf_error))
20091         RETURN (error_mark_node);
20092       RETURN (build_x_arrow (input_location, op1, complain));
20093
20094     case NEW_EXPR:
20095       {
20096         tree placement = RECUR (TREE_OPERAND (t, 0));
20097         tree init = RECUR (TREE_OPERAND (t, 3));
20098         vec<tree, va_gc> *placement_vec;
20099         vec<tree, va_gc> *init_vec;
20100         tree ret;
20101         location_t loc = EXPR_LOCATION (t);
20102
20103         if (placement == NULL_TREE)
20104           placement_vec = NULL;
20105         else if (placement == error_mark_node)
20106           RETURN (error_mark_node);
20107         else
20108           {
20109             placement_vec = make_tree_vector ();
20110             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
20111               vec_safe_push (placement_vec, TREE_VALUE (placement));
20112           }
20113
20114         /* If there was an initializer in the original tree, but it
20115            instantiated to an empty list, then we should pass a
20116            non-NULL empty vector to tell build_new that it was an
20117            empty initializer() rather than no initializer.  This can
20118            only happen when the initializer is a pack expansion whose
20119            parameter packs are of length zero.  */
20120         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
20121           init_vec = NULL;
20122         else if (init == error_mark_node)
20123           RETURN (error_mark_node);
20124         else
20125           {
20126             init_vec = make_tree_vector ();
20127             if (init == void_node)
20128               gcc_assert (init_vec != NULL);
20129             else
20130               {
20131                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
20132                   vec_safe_push (init_vec, TREE_VALUE (init));
20133               }
20134           }
20135
20136         /* Avoid passing an enclosing decl to valid_array_size_p.  */
20137         in_decl = NULL_TREE;
20138
20139         tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
20140         tree op2 = RECUR (TREE_OPERAND (t, 2));
20141         ret = build_new (loc, &placement_vec, op1, op2,
20142                          &init_vec, NEW_EXPR_USE_GLOBAL (t),
20143                          complain);
20144
20145         if (placement_vec != NULL)
20146           release_tree_vector (placement_vec);
20147         if (init_vec != NULL)
20148           release_tree_vector (init_vec);
20149
20150         RETURN (ret);
20151       }
20152
20153     case DELETE_EXPR:
20154       {
20155         tree op0 = RECUR (TREE_OPERAND (t, 0));
20156         tree op1 = RECUR (TREE_OPERAND (t, 1));
20157         RETURN (delete_sanity (input_location, op0, op1,
20158                                DELETE_EXPR_USE_VEC (t),
20159                                DELETE_EXPR_USE_GLOBAL (t),
20160                                complain));
20161       }
20162
20163     case COMPOUND_EXPR:
20164       {
20165         tree op0 = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
20166                                           complain & ~tf_decltype, in_decl,
20167                                           /*function_p=*/false,
20168                                           integral_constant_expression_p);
20169         RETURN (build_x_compound_expr (EXPR_LOCATION (t),
20170                                        op0,
20171                                        RECUR (TREE_OPERAND (t, 1)),
20172                                        complain|decltype_flag));
20173       }
20174
20175     case CALL_EXPR:
20176       {
20177         tree function;
20178         unsigned int nargs, i;
20179         bool qualified_p;
20180         bool koenig_p;
20181         tree ret;
20182
20183         function = CALL_EXPR_FN (t);
20184         /* Internal function with no arguments.  */
20185         if (function == NULL_TREE && call_expr_nargs (t) == 0)
20186           RETURN (t);
20187
20188         /* When we parsed the expression, we determined whether or
20189            not Koenig lookup should be performed.  */
20190         koenig_p = KOENIG_LOOKUP_P (t);
20191         if (function == NULL_TREE)
20192           {
20193             koenig_p = false;
20194             qualified_p = false;
20195           }
20196         else if (TREE_CODE (function) == SCOPE_REF)
20197           {
20198             qualified_p = true;
20199             function = tsubst_qualified_id (function, args, complain, in_decl,
20200                                             /*done=*/false,
20201                                             /*address_p=*/false);
20202           }
20203         else if (koenig_p && identifier_p (function))
20204           {
20205             /* Do nothing; calling tsubst_copy_and_build on an identifier
20206                would incorrectly perform unqualified lookup again.
20207
20208                Note that we can also have an IDENTIFIER_NODE if the earlier
20209                unqualified lookup found a member function; in that case
20210                koenig_p will be false and we do want to do the lookup
20211                again to find the instantiated member function.
20212
20213                FIXME but doing that causes c++/15272, so we need to stop
20214                using IDENTIFIER_NODE in that situation.  */
20215             qualified_p = false;
20216           }
20217         else
20218           {
20219             if (TREE_CODE (function) == COMPONENT_REF)
20220               {
20221                 tree op = TREE_OPERAND (function, 1);
20222
20223                 qualified_p = (TREE_CODE (op) == SCOPE_REF
20224                                || (BASELINK_P (op)
20225                                    && BASELINK_QUALIFIED_P (op)));
20226               }
20227             else
20228               qualified_p = false;
20229
20230             if (TREE_CODE (function) == ADDR_EXPR
20231                 && TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
20232               /* Avoid error about taking the address of a constructor.  */
20233               function = TREE_OPERAND (function, 0);
20234
20235             function = tsubst_copy_and_build (function, args, complain,
20236                                               in_decl,
20237                                               !qualified_p,
20238                                               integral_constant_expression_p);
20239
20240             if (BASELINK_P (function))
20241               qualified_p = true;
20242           }
20243
20244         nargs = call_expr_nargs (t);
20245         releasing_vec call_args;
20246         for (i = 0; i < nargs; ++i)
20247           {
20248             tree arg = CALL_EXPR_ARG (t, i);
20249
20250             if (!PACK_EXPANSION_P (arg))
20251               vec_safe_push (call_args, RECUR (CALL_EXPR_ARG (t, i)));
20252             else
20253               {
20254                 /* Expand the pack expansion and push each entry onto
20255                    CALL_ARGS.  */
20256                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
20257                 if (TREE_CODE (arg) == TREE_VEC)
20258                   {
20259                     unsigned int len, j;
20260
20261                     len = TREE_VEC_LENGTH (arg);
20262                     for (j = 0; j < len; ++j)
20263                       {
20264                         tree value = TREE_VEC_ELT (arg, j);
20265                         if (value != NULL_TREE)
20266                           value = convert_from_reference (value);
20267                         vec_safe_push (call_args, value);
20268                       }
20269                   }
20270                 else
20271                   {
20272                     /* A partial substitution.  Add one entry.  */
20273                     vec_safe_push (call_args, arg);
20274                   }
20275               }
20276           }
20277
20278         /* Stripped-down processing for a call in a thunk.  Specifically, in
20279            the thunk template for a generic lambda.  */
20280         if (call_from_lambda_thunk_p (t))
20281           {
20282             /* Now that we've expanded any packs, the number of call args
20283                might be different.  */
20284             unsigned int cargs = call_args->length ();
20285             tree thisarg = NULL_TREE;
20286             if (TREE_CODE (function) == COMPONENT_REF)
20287               {
20288                 thisarg = TREE_OPERAND (function, 0);
20289                 if (TREE_CODE (thisarg) == INDIRECT_REF)
20290                   thisarg = TREE_OPERAND (thisarg, 0);
20291                 function = TREE_OPERAND (function, 1);
20292                 if (TREE_CODE (function) == BASELINK)
20293                   function = BASELINK_FUNCTIONS (function);
20294               }
20295             /* We aren't going to do normal overload resolution, so force the
20296                template-id to resolve.  */
20297             function = resolve_nondeduced_context (function, complain);
20298             for (unsigned i = 0; i < cargs; ++i)
20299               {
20300                 /* In a thunk, pass through args directly, without any
20301                    conversions.  */
20302                 tree arg = (*call_args)[i];
20303                 while (TREE_CODE (arg) != PARM_DECL)
20304                   arg = TREE_OPERAND (arg, 0);
20305                 (*call_args)[i] = arg;
20306               }
20307             if (thisarg)
20308               {
20309                 /* If there are no other args, just push 'this'.  */
20310                 if (cargs == 0)
20311                   vec_safe_push (call_args, thisarg);
20312                 else
20313                   {
20314                     /* Otherwise, shift the other args over to make room.  */
20315                     tree last = (*call_args)[cargs - 1];
20316                     vec_safe_push (call_args, last);
20317                     for (int i = cargs - 1; i > 0; --i)
20318                       (*call_args)[i] = (*call_args)[i - 1];
20319                     (*call_args)[0] = thisarg;
20320                   }
20321               }
20322             ret = build_call_a (function, call_args->length (),
20323                                 call_args->address ());
20324             /* The thunk location is not interesting.  */
20325             SET_EXPR_LOCATION (ret, UNKNOWN_LOCATION);
20326             CALL_FROM_THUNK_P (ret) = true;
20327             if (CLASS_TYPE_P (TREE_TYPE (ret)))
20328               CALL_EXPR_RETURN_SLOT_OPT (ret) = true;
20329
20330             RETURN (ret);
20331           }
20332
20333         /* We do not perform argument-dependent lookup if normal
20334            lookup finds a non-function, in accordance with the
20335            resolution of DR 218.  */
20336         if (koenig_p
20337             && ((is_overloaded_fn (function)
20338                  /* If lookup found a member function, the Koenig lookup is
20339                     not appropriate, even if an unqualified-name was used
20340                     to denote the function.  */
20341                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
20342                 || identifier_p (function)
20343                 /* C++20 P0846: Lookup found nothing.  */
20344                 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
20345                     && identifier_p (TREE_OPERAND (function, 0))))
20346             /* Only do this when substitution turns a dependent call
20347                into a non-dependent call.  */
20348             && type_dependent_expression_p_push (t)
20349             && !any_type_dependent_arguments_p (call_args))
20350           function = perform_koenig_lookup (function, call_args, tf_none);
20351
20352         if (function != NULL_TREE
20353             && (identifier_p (function)
20354                 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
20355                     && identifier_p (TREE_OPERAND (function, 0))))
20356             && !any_type_dependent_arguments_p (call_args))
20357           {
20358             if (TREE_CODE (function) == TEMPLATE_ID_EXPR)
20359               function = TREE_OPERAND (function, 0);
20360             if (koenig_p && (complain & tf_warning_or_error))
20361               {
20362                 /* For backwards compatibility and good diagnostics, try
20363                    the unqualified lookup again if we aren't in SFINAE
20364                    context.  */
20365                 tree unq = (tsubst_copy_and_build
20366                             (function, args, complain, in_decl, true,
20367                              integral_constant_expression_p));
20368                 if (unq == error_mark_node)
20369                   RETURN (error_mark_node);
20370
20371                 if (unq != function)
20372                   {
20373                     /* In a lambda fn, we have to be careful to not
20374                        introduce new this captures.  Legacy code can't
20375                        be using lambdas anyway, so it's ok to be
20376                        stricter.  */
20377                     bool in_lambda = (current_class_type
20378                                       && LAMBDA_TYPE_P (current_class_type));
20379                     char const *const msg
20380                       = G_("%qD was not declared in this scope, "
20381                            "and no declarations were found by "
20382                            "argument-dependent lookup at the point "
20383                            "of instantiation");
20384
20385                     bool diag = true;
20386                     if (in_lambda)
20387                       error_at (cp_expr_loc_or_input_loc (t),
20388                                 msg, function);
20389                     else
20390                       diag = permerror (cp_expr_loc_or_input_loc (t),
20391                                         msg, function);
20392                     if (diag)
20393                       {
20394                         tree fn = unq;
20395
20396                         if (INDIRECT_REF_P (fn))
20397                           fn = TREE_OPERAND (fn, 0);
20398                         if (is_overloaded_fn (fn))
20399                           fn = get_first_fn (fn);
20400
20401                         if (!DECL_P (fn))
20402                           /* Can't say anything more.  */;
20403                         else if (DECL_CLASS_SCOPE_P (fn))
20404                           {
20405                             location_t loc = cp_expr_loc_or_input_loc (t);
20406                             inform (loc,
20407                                     "declarations in dependent base %qT are "
20408                                     "not found by unqualified lookup",
20409                                     DECL_CLASS_CONTEXT (fn));
20410                             if (current_class_ptr)
20411                               inform (loc,
20412                                       "use %<this->%D%> instead", function);
20413                             else
20414                               inform (loc,
20415                                       "use %<%T::%D%> instead",
20416                                       current_class_name, function);
20417                           }
20418                         else
20419                           inform (DECL_SOURCE_LOCATION (fn),
20420                                   "%qD declared here, later in the "
20421                                   "translation unit", fn);
20422                         if (in_lambda)
20423                           RETURN (error_mark_node);
20424                       }
20425
20426                     function = unq;
20427                   }
20428               }
20429             if (identifier_p (function))
20430               {
20431                 if (complain & tf_error)
20432                   unqualified_name_lookup_error (function);
20433                 RETURN (error_mark_node);
20434               }
20435           }
20436
20437         /* Remember that there was a reference to this entity.  */
20438         if (function != NULL_TREE
20439             && DECL_P (function)
20440             && !mark_used (function, complain) && !(complain & tf_error))
20441           RETURN (error_mark_node);
20442
20443         /* Put back tf_decltype for the actual call.  */
20444         complain |= decltype_flag;
20445
20446         if (function == NULL_TREE)
20447           switch (CALL_EXPR_IFN (t))
20448             {
20449             case IFN_LAUNDER:
20450               gcc_assert (nargs == 1);
20451               if (vec_safe_length (call_args) != 1)
20452                 {
20453                   error_at (cp_expr_loc_or_input_loc (t),
20454                             "wrong number of arguments to "
20455                             "%<__builtin_launder%>");
20456                   ret = error_mark_node;
20457                 }
20458               else
20459                 ret = finish_builtin_launder (cp_expr_loc_or_input_loc (t),
20460                                               (*call_args)[0], complain);
20461               break;
20462
20463             case IFN_VEC_CONVERT:
20464               gcc_assert (nargs == 1);
20465               if (vec_safe_length (call_args) != 1)
20466                 {
20467                   error_at (cp_expr_loc_or_input_loc (t),
20468                             "wrong number of arguments to "
20469                             "%<__builtin_convertvector%>");
20470                   ret = error_mark_node;
20471                   break;
20472                 }
20473               ret = cp_build_vec_convert ((*call_args)[0], input_location,
20474                                           tsubst (TREE_TYPE (t), args,
20475                                                   complain, in_decl),
20476                                           complain);
20477               if (TREE_CODE (ret) == VIEW_CONVERT_EXPR)
20478                 RETURN (ret);
20479               break;
20480
20481             default:
20482               /* Unsupported internal function with arguments.  */
20483               gcc_unreachable ();
20484             }
20485         else if (TREE_CODE (function) == OFFSET_REF
20486                  || TREE_CODE (function) == DOTSTAR_EXPR
20487                  || TREE_CODE (function) == MEMBER_REF)
20488           ret = build_offset_ref_call_from_tree (function, &call_args,
20489                                                  complain);
20490         else if (TREE_CODE (function) == COMPONENT_REF)
20491           {
20492             tree instance = TREE_OPERAND (function, 0);
20493             tree fn = TREE_OPERAND (function, 1);
20494
20495             if (processing_template_decl
20496                 && (type_dependent_expression_p (instance)
20497                     || (!BASELINK_P (fn)
20498                         && TREE_CODE (fn) != FIELD_DECL)
20499                     || type_dependent_expression_p (fn)
20500                     || any_type_dependent_arguments_p (call_args)))
20501               ret = build_min_nt_call_vec (function, call_args);
20502             else if (!BASELINK_P (fn))
20503               ret = finish_call_expr (function, &call_args,
20504                                        /*disallow_virtual=*/false,
20505                                        /*koenig_p=*/false,
20506                                        complain);
20507             else
20508               ret = (build_new_method_call
20509                       (instance, fn,
20510                        &call_args, NULL_TREE,
20511                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
20512                        /*fn_p=*/NULL,
20513                        complain));
20514           }
20515         else if (concept_check_p (function))
20516           {
20517             /* FUNCTION is a template-id referring to a concept definition.  */
20518             tree id = unpack_concept_check (function);
20519             tree tmpl = TREE_OPERAND (id, 0);
20520             tree args = TREE_OPERAND (id, 1);
20521
20522             /* Calls to standard and variable concepts should have been
20523                previously diagnosed.  */
20524             gcc_assert (function_concept_p (tmpl));
20525
20526             /* Ensure the result is wrapped as a call expression.  */
20527             ret = build_concept_check (tmpl, args, tf_warning_or_error);
20528           }
20529         else
20530           ret = finish_call_expr (function, &call_args,
20531                                   /*disallow_virtual=*/qualified_p,
20532                                   koenig_p,
20533                                   complain);
20534
20535         if (ret != error_mark_node)
20536           {
20537             bool op = CALL_EXPR_OPERATOR_SYNTAX (t);
20538             bool ord = CALL_EXPR_ORDERED_ARGS (t);
20539             bool rev = CALL_EXPR_REVERSE_ARGS (t);
20540             if (op || ord || rev)
20541               {
20542                 function = extract_call_expr (ret);
20543                 CALL_EXPR_OPERATOR_SYNTAX (function) = op;
20544                 CALL_EXPR_ORDERED_ARGS (function) = ord;
20545                 CALL_EXPR_REVERSE_ARGS (function) = rev;
20546               }
20547           }
20548
20549         RETURN (ret);
20550       }
20551
20552     case COND_EXPR:
20553       {
20554         tree cond = RECUR (TREE_OPERAND (t, 0));
20555         cond = mark_rvalue_use (cond);
20556         tree folded_cond = fold_non_dependent_expr (cond, complain);
20557         tree exp1, exp2;
20558
20559         if (TREE_CODE (folded_cond) == INTEGER_CST)
20560           {
20561             if (integer_zerop (folded_cond))
20562               {
20563                 ++c_inhibit_evaluation_warnings;
20564                 exp1 = RECUR (TREE_OPERAND (t, 1));
20565                 --c_inhibit_evaluation_warnings;
20566                 exp2 = RECUR (TREE_OPERAND (t, 2));
20567               }
20568             else
20569               {
20570                 exp1 = RECUR (TREE_OPERAND (t, 1));
20571                 ++c_inhibit_evaluation_warnings;
20572                 exp2 = RECUR (TREE_OPERAND (t, 2));
20573                 --c_inhibit_evaluation_warnings;
20574               }
20575             cond = folded_cond;
20576           }
20577         else
20578           {
20579             exp1 = RECUR (TREE_OPERAND (t, 1));
20580             exp2 = RECUR (TREE_OPERAND (t, 2));
20581           }
20582
20583         warning_sentinel s(warn_duplicated_branches);
20584         RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
20585                                          cond, exp1, exp2, complain));
20586       }
20587
20588     case PSEUDO_DTOR_EXPR:
20589       {
20590         tree op0 = RECUR (TREE_OPERAND (t, 0));
20591         tree op1 = RECUR (TREE_OPERAND (t, 1));
20592         tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
20593         RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
20594                                                input_location));
20595       }
20596
20597     case TREE_LIST:
20598       RETURN (tsubst_tree_list (t, args, complain, in_decl));
20599
20600     case COMPONENT_REF:
20601       {
20602         tree object;
20603         tree object_type;
20604         tree member;
20605         tree r;
20606
20607         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20608                                                      args, complain, in_decl);
20609         /* Remember that there was a reference to this entity.  */
20610         if (DECL_P (object)
20611             && !mark_used (object, complain) && !(complain & tf_error))
20612           RETURN (error_mark_node);
20613         object_type = TREE_TYPE (object);
20614
20615         member = TREE_OPERAND (t, 1);
20616         if (BASELINK_P (member))
20617           member = tsubst_baselink (member,
20618                                     non_reference (TREE_TYPE (object)),
20619                                     args, complain, in_decl);
20620         else
20621           member = tsubst_copy (member, args, complain, in_decl);
20622         if (member == error_mark_node)
20623           RETURN (error_mark_node);
20624
20625         if (TREE_CODE (member) == FIELD_DECL)
20626           {
20627             r = finish_non_static_data_member (member, object, NULL_TREE);
20628             if (TREE_CODE (r) == COMPONENT_REF)
20629               REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
20630             RETURN (r);
20631           }
20632         else if (type_dependent_expression_p (object))
20633           /* We can't do much here.  */;
20634         else if (!CLASS_TYPE_P (object_type))
20635           {
20636             if (scalarish_type_p (object_type))
20637               {
20638                 tree s = NULL_TREE;
20639                 tree dtor = member;
20640
20641                 if (TREE_CODE (dtor) == SCOPE_REF)
20642                   {
20643                     s = TREE_OPERAND (dtor, 0);
20644                     dtor = TREE_OPERAND (dtor, 1);
20645                   }
20646                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
20647                   {
20648                     dtor = TREE_OPERAND (dtor, 0);
20649                     if (TYPE_P (dtor))
20650                       RETURN (finish_pseudo_destructor_expr
20651                               (object, s, dtor, input_location));
20652                   }
20653               }
20654           }
20655         else if (TREE_CODE (member) == SCOPE_REF
20656                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
20657           {
20658             /* Lookup the template functions now that we know what the
20659                scope is.  */
20660             tree scope = TREE_OPERAND (member, 0);
20661             tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
20662             tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
20663             member = lookup_qualified_name (scope, tmpl, LOOK_want::NORMAL,
20664                                             /*complain=*/false);
20665             if (BASELINK_P (member))
20666               {
20667                 BASELINK_FUNCTIONS (member)
20668                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
20669                               args);
20670                 member = (adjust_result_of_qualified_name_lookup
20671                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
20672                            object_type));
20673               }
20674             else
20675               {
20676                 qualified_name_lookup_error (scope, tmpl, member,
20677                                              input_location);
20678                 RETURN (error_mark_node);
20679               }
20680           }
20681         else if (TREE_CODE (member) == SCOPE_REF
20682                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
20683                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
20684           {
20685             if (complain & tf_error)
20686               {
20687                 if (TYPE_P (TREE_OPERAND (member, 0)))
20688                   error ("%qT is not a class or namespace",
20689                          TREE_OPERAND (member, 0));
20690                 else
20691                   error ("%qD is not a class or namespace",
20692                          TREE_OPERAND (member, 0));
20693               }
20694             RETURN (error_mark_node);
20695           }
20696
20697         r = finish_class_member_access_expr (object, member,
20698                                              /*template_p=*/false,
20699                                              complain);
20700         if (TREE_CODE (r) == COMPONENT_REF)
20701           REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
20702         RETURN (r);
20703       }
20704
20705     case THROW_EXPR:
20706       RETURN (build_throw
20707        (input_location, RECUR (TREE_OPERAND (t, 0))));
20708
20709     case CONSTRUCTOR:
20710       {
20711         vec<constructor_elt, va_gc> *n;
20712         constructor_elt *ce;
20713         unsigned HOST_WIDE_INT idx;
20714         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20715         bool process_index_p;
20716         int newlen;
20717         bool need_copy_p = false;
20718         tree r;
20719
20720         if (type == error_mark_node)
20721           RETURN (error_mark_node);
20722
20723         /* We do not want to process the index of aggregate
20724            initializers as they are identifier nodes which will be
20725            looked up by digest_init.  */
20726         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
20727
20728         if (null_member_pointer_value_p (t))
20729           {
20730             gcc_assert (same_type_p (type, TREE_TYPE (t)));
20731             RETURN (t);
20732           }
20733
20734         n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
20735         newlen = vec_safe_length (n);
20736         FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
20737           {
20738             if (ce->index && process_index_p
20739                 /* An identifier index is looked up in the type
20740                    being initialized, not the current scope.  */
20741                 && TREE_CODE (ce->index) != IDENTIFIER_NODE)
20742               ce->index = RECUR (ce->index);
20743
20744             if (PACK_EXPANSION_P (ce->value))
20745               {
20746                 /* Substitute into the pack expansion.  */
20747                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
20748                                                   in_decl);
20749
20750                 if (ce->value == error_mark_node
20751                     || PACK_EXPANSION_P (ce->value))
20752                   ;
20753                 else if (TREE_VEC_LENGTH (ce->value) == 1)
20754                   /* Just move the argument into place.  */
20755                   ce->value = TREE_VEC_ELT (ce->value, 0);
20756                 else
20757                   {
20758                     /* Update the length of the final CONSTRUCTOR
20759                        arguments vector, and note that we will need to
20760                        copy.*/
20761                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
20762                     need_copy_p = true;
20763                   }
20764               }
20765             else
20766               ce->value = RECUR (ce->value);
20767           }
20768
20769         if (need_copy_p)
20770           {
20771             vec<constructor_elt, va_gc> *old_n = n;
20772
20773             vec_alloc (n, newlen);
20774             FOR_EACH_VEC_ELT (*old_n, idx, ce)
20775               {
20776                 if (TREE_CODE (ce->value) == TREE_VEC)
20777                   {
20778                     int i, len = TREE_VEC_LENGTH (ce->value);
20779                     for (i = 0; i < len; ++i)
20780                       CONSTRUCTOR_APPEND_ELT (n, 0,
20781                                               TREE_VEC_ELT (ce->value, i));
20782                   }
20783                 else
20784                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
20785               }
20786           }
20787
20788         r = build_constructor (init_list_type_node, n);
20789         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
20790         CONSTRUCTOR_IS_DESIGNATED_INIT (r)
20791           = CONSTRUCTOR_IS_DESIGNATED_INIT (t);
20792
20793         if (TREE_HAS_CONSTRUCTOR (t))
20794           {
20795             fcl_t cl = fcl_functional;
20796             if (CONSTRUCTOR_C99_COMPOUND_LITERAL (t))
20797               cl = fcl_c99;
20798             RETURN (finish_compound_literal (type, r, complain, cl));
20799           }
20800
20801         TREE_TYPE (r) = type;
20802         RETURN (r);
20803       }
20804
20805     case TYPEID_EXPR:
20806       {
20807         tree operand_0 = TREE_OPERAND (t, 0);
20808         if (TYPE_P (operand_0))
20809           {
20810             operand_0 = tsubst (operand_0, args, complain, in_decl);
20811             RETURN (get_typeid (operand_0, complain));
20812           }
20813         else
20814           {
20815             operand_0 = RECUR (operand_0);
20816             RETURN (build_typeid (operand_0, complain));
20817           }
20818       }
20819
20820     case VAR_DECL:
20821       if (!args)
20822         RETURN (t);
20823       /* Fall through */
20824
20825     case PARM_DECL:
20826       {
20827         tree r = tsubst_copy (t, args, complain, in_decl);
20828         /* ??? We're doing a subset of finish_id_expression here.  */
20829         if (tree wrap = maybe_get_tls_wrapper_call (r))
20830           /* Replace an evaluated use of the thread_local variable with
20831              a call to its wrapper.  */
20832           r = wrap;
20833         else if (outer_automatic_var_p (r))
20834           r = process_outer_var_ref (r, complain);
20835
20836         if (!TYPE_REF_P (TREE_TYPE (t)))
20837           /* If the original type was a reference, we'll be wrapped in
20838              the appropriate INDIRECT_REF.  */
20839           r = convert_from_reference (r);
20840         RETURN (r);
20841       }
20842
20843     case VA_ARG_EXPR:
20844       {
20845         tree op0 = RECUR (TREE_OPERAND (t, 0));
20846         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20847         RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
20848       }
20849
20850     case OFFSETOF_EXPR:
20851       {
20852         tree object_ptr
20853           = tsubst_copy_and_build (TREE_OPERAND (t, 1), args, complain,
20854                                    in_decl, /*function_p=*/false,
20855                                    /*integral_constant_expression_p=*/false);
20856         RETURN (finish_offsetof (object_ptr,
20857                                  RECUR (TREE_OPERAND (t, 0)),
20858                                  EXPR_LOCATION (t)));
20859       }
20860
20861     case ADDRESSOF_EXPR:
20862       RETURN (cp_build_addressof (EXPR_LOCATION (t),
20863                                   RECUR (TREE_OPERAND (t, 0)), complain));
20864
20865     case TRAIT_EXPR:
20866       {
20867         tree type1 = tsubst (TRAIT_EXPR_TYPE1 (t), args,
20868                              complain, in_decl);
20869         tree type2 = tsubst (TRAIT_EXPR_TYPE2 (t), args,
20870                              complain, in_decl);
20871         RETURN (finish_trait_expr (TRAIT_EXPR_LOCATION (t),
20872                                    TRAIT_EXPR_KIND (t), type1, type2));
20873       }
20874
20875     case STMT_EXPR:
20876       {
20877         tree old_stmt_expr = cur_stmt_expr;
20878         tree stmt_expr = begin_stmt_expr ();
20879
20880         cur_stmt_expr = stmt_expr;
20881         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
20882                      integral_constant_expression_p);
20883         stmt_expr = finish_stmt_expr (stmt_expr, false);
20884         cur_stmt_expr = old_stmt_expr;
20885
20886         /* If the resulting list of expression statement is empty,
20887            fold it further into void_node.  */
20888         if (empty_expr_stmt_p (stmt_expr))
20889           stmt_expr = void_node;
20890
20891         RETURN (stmt_expr);
20892       }
20893
20894     case LAMBDA_EXPR:
20895       {
20896         if (complain & tf_partial)
20897           {
20898             /* We don't have a full set of template arguments yet; don't touch
20899                the lambda at all.  */
20900             gcc_assert (processing_template_decl);
20901             return t;
20902           }
20903         tree r = tsubst_lambda_expr (t, args, complain, in_decl);
20904
20905         RETURN (build_lambda_object (r));
20906       }
20907
20908     case TARGET_EXPR:
20909       /* We can get here for a constant initializer of non-dependent type.
20910          FIXME stop folding in cp_parser_initializer_clause.  */
20911       {
20912         tree r = get_target_expr_sfinae (RECUR (TARGET_EXPR_INITIAL (t)),
20913                                          complain);
20914         RETURN (r);
20915       }
20916
20917     case TRANSACTION_EXPR:
20918       RETURN (tsubst_expr(t, args, complain, in_decl,
20919              integral_constant_expression_p));
20920
20921     case PAREN_EXPR:
20922       RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
20923
20924     case VEC_PERM_EXPR:
20925       {
20926         tree op0 = RECUR (TREE_OPERAND (t, 0));
20927         tree op1 = RECUR (TREE_OPERAND (t, 1));
20928         tree op2 = RECUR (TREE_OPERAND (t, 2));
20929         RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
20930                                        complain));
20931       }
20932
20933     case REQUIRES_EXPR:
20934       {
20935         tree r = tsubst_requires_expr (t, args, tf_none, in_decl);
20936         RETURN (r);
20937       }
20938
20939     case RANGE_EXPR:
20940       /* No need to substitute further, a RANGE_EXPR will always be built
20941          with constant operands.  */
20942       RETURN (t);
20943
20944     case NON_LVALUE_EXPR:
20945     case VIEW_CONVERT_EXPR:
20946       if (location_wrapper_p (t))
20947         /* We need to do this here as well as in tsubst_copy so we get the
20948            other tsubst_copy_and_build semantics for a PARM_DECL operand.  */
20949         RETURN (maybe_wrap_with_location (RECUR (TREE_OPERAND (t, 0)),
20950                                           EXPR_LOCATION (t)));
20951       /* fallthrough.  */
20952
20953     default:
20954       /* Handle Objective-C++ constructs, if appropriate.  */
20955       {
20956         tree subst
20957           = objcp_tsubst_copy_and_build (t, args, complain,
20958                                          in_decl, /*function_p=*/false);
20959         if (subst)
20960           RETURN (subst);
20961       }
20962       RETURN (tsubst_copy (t, args, complain, in_decl));
20963     }
20964
20965 #undef RECUR
20966 #undef RETURN
20967  out:
20968   input_location = save_loc;
20969   return retval;
20970 }
20971
20972 /* Verify that the instantiated ARGS are valid. For type arguments,
20973    make sure that the type's linkage is ok. For non-type arguments,
20974    make sure they are constants if they are integral or enumerations.
20975    Emit an error under control of COMPLAIN, and return TRUE on error.  */
20976
20977 static bool
20978 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
20979 {
20980   if (dependent_template_arg_p (t))
20981     return false;
20982   if (ARGUMENT_PACK_P (t))
20983     {
20984       tree vec = ARGUMENT_PACK_ARGS (t);
20985       int len = TREE_VEC_LENGTH (vec);
20986       bool result = false;
20987       int i;
20988
20989       for (i = 0; i < len; ++i)
20990         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
20991           result = true;
20992       return result;
20993     }
20994   else if (TYPE_P (t))
20995     {
20996       /* [basic.link]: A name with no linkage (notably, the name
20997          of a class or enumeration declared in a local scope)
20998          shall not be used to declare an entity with linkage.
20999          This implies that names with no linkage cannot be used as
21000          template arguments
21001
21002          DR 757 relaxes this restriction for C++0x.  */
21003       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
21004                  : no_linkage_check (t, /*relaxed_p=*/false));
21005
21006       if (nt)
21007         {
21008           /* DR 488 makes use of a type with no linkage cause
21009              type deduction to fail.  */
21010           if (complain & tf_error)
21011             {
21012               if (TYPE_UNNAMED_P (nt))
21013                 error ("%qT is/uses unnamed type", t);
21014               else
21015                 error ("template argument for %qD uses local type %qT",
21016                        tmpl, t);
21017             }
21018           return true;
21019         }
21020       /* In order to avoid all sorts of complications, we do not
21021          allow variably-modified types as template arguments.  */
21022       else if (variably_modified_type_p (t, NULL_TREE))
21023         {
21024           if (complain & tf_error)
21025             error ("%qT is a variably modified type", t);
21026           return true;
21027         }
21028     }
21029   /* Class template and alias template arguments should be OK.  */
21030   else if (DECL_TYPE_TEMPLATE_P (t))
21031     ;
21032   /* A non-type argument of integral or enumerated type must be a
21033      constant.  */
21034   else if (TREE_TYPE (t)
21035            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
21036            && !REFERENCE_REF_P (t)
21037            && !TREE_CONSTANT (t))
21038     {
21039       if (complain & tf_error)
21040         error ("integral expression %qE is not constant", t);
21041       return true;
21042     }
21043   return false;
21044 }
21045
21046 static bool
21047 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
21048 {
21049   int ix, len = DECL_NTPARMS (tmpl);
21050   bool result = false;
21051
21052   for (ix = 0; ix != len; ix++)
21053     {
21054       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
21055         result = true;
21056     }
21057   if (result && (complain & tf_error))
21058     error ("  trying to instantiate %qD", tmpl);
21059   return result;
21060 }
21061
21062 /* We're out of SFINAE context now, so generate diagnostics for the access
21063    errors we saw earlier when instantiating D from TMPL and ARGS.  */
21064
21065 static void
21066 recheck_decl_substitution (tree d, tree tmpl, tree args)
21067 {
21068   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
21069   tree type = TREE_TYPE (pattern);
21070   location_t loc = input_location;
21071
21072   push_access_scope (d);
21073   push_deferring_access_checks (dk_no_deferred);
21074   input_location = DECL_SOURCE_LOCATION (pattern);
21075   tsubst (type, args, tf_warning_or_error, d);
21076   input_location = loc;
21077   pop_deferring_access_checks ();
21078   pop_access_scope (d);
21079 }
21080
21081 /* Instantiate the indicated variable, function, or alias template TMPL with
21082    the template arguments in TARG_PTR.  */
21083
21084 static tree
21085 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
21086 {
21087   tree targ_ptr = orig_args;
21088   tree fndecl;
21089   tree gen_tmpl;
21090   tree spec;
21091   bool access_ok = true;
21092
21093   if (tmpl == error_mark_node)
21094     return error_mark_node;
21095
21096   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
21097
21098   if (modules_p ())
21099     lazy_load_pendings (tmpl);
21100
21101   /* If this function is a clone, handle it specially.  */
21102   if (DECL_CLONED_FUNCTION_P (tmpl))
21103     {
21104       tree spec;
21105       tree clone;
21106
21107       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
21108          DECL_CLONED_FUNCTION.  */
21109       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
21110                                    targ_ptr, complain);
21111       if (spec == error_mark_node)
21112         return error_mark_node;
21113
21114       /* Look for the clone.  */
21115       FOR_EACH_CLONE (clone, spec)
21116         if (DECL_NAME (clone) == DECL_NAME (tmpl))
21117           return clone;
21118       /* We should always have found the clone by now.  */
21119       gcc_unreachable ();
21120       return NULL_TREE;
21121     }
21122
21123   if (targ_ptr == error_mark_node)
21124     return error_mark_node;
21125
21126   /* Check to see if we already have this specialization.  */
21127   gen_tmpl = most_general_template (tmpl);
21128   if (TMPL_ARGS_DEPTH (targ_ptr)
21129       < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)))
21130     /* targ_ptr only has the innermost template args, so add the outer ones
21131        from tmpl, which could be either a partial instantiation or gen_tmpl (in
21132        the case of a non-dependent call within a template definition).  */
21133     targ_ptr = (add_outermost_template_args
21134                 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (tmpl)),
21135                  targ_ptr));
21136
21137   /* It would be nice to avoid hashing here and then again in tsubst_decl,
21138      but it doesn't seem to be on the hot path.  */
21139   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
21140
21141   gcc_checking_assert (tmpl == gen_tmpl
21142                        || ((fndecl
21143                             = retrieve_specialization (tmpl, orig_args, 0))
21144                            == spec)
21145                        || fndecl == NULL_TREE);
21146
21147   if (spec != NULL_TREE)
21148     {
21149       if (FNDECL_HAS_ACCESS_ERRORS (spec))
21150         {
21151           if (complain & tf_error)
21152             recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
21153           return error_mark_node;
21154         }
21155       return spec;
21156     }
21157
21158   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
21159                                complain))
21160     return error_mark_node;
21161
21162   /* We are building a FUNCTION_DECL, during which the access of its
21163      parameters and return types have to be checked.  However this
21164      FUNCTION_DECL which is the desired context for access checking
21165      is not built yet.  We solve this chicken-and-egg problem by
21166      deferring all checks until we have the FUNCTION_DECL.  */
21167   push_deferring_access_checks (dk_deferred);
21168
21169   /* Instantiation of the function happens in the context of the function
21170      template, not the context of the overload resolution we're doing.  */
21171   push_to_top_level ();
21172   /* If there are dependent arguments, e.g. because we're doing partial
21173      ordering, make sure processing_template_decl stays set.  */
21174   if (uses_template_parms (targ_ptr))
21175     ++processing_template_decl;
21176   if (DECL_CLASS_SCOPE_P (gen_tmpl))
21177     {
21178       tree ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
21179                                    complain, gen_tmpl, true);
21180       push_nested_class (ctx);
21181     }
21182
21183   tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
21184
21185   fndecl = NULL_TREE;
21186   if (VAR_P (pattern))
21187     {
21188       /* We need to determine if we're using a partial or explicit
21189          specialization now, because the type of the variable could be
21190          different.  */
21191       tree tid = lookup_template_variable (gen_tmpl, targ_ptr);
21192       tree elt = most_specialized_partial_spec (tid, complain);
21193       if (elt == error_mark_node)
21194         pattern = error_mark_node;
21195       else if (elt)
21196         {
21197           tree partial_tmpl = TREE_VALUE (elt);
21198           tree partial_args = TREE_PURPOSE (elt);
21199           tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
21200           fndecl = tsubst (partial_pat, partial_args, complain, gen_tmpl);
21201         }
21202     }
21203
21204   /* Substitute template parameters to obtain the specialization.  */
21205   if (fndecl == NULL_TREE)
21206     fndecl = tsubst (pattern, targ_ptr, complain, gen_tmpl);
21207   if (DECL_CLASS_SCOPE_P (gen_tmpl))
21208     pop_nested_class ();
21209   pop_from_top_level ();
21210
21211   if (fndecl == error_mark_node)
21212     {
21213       pop_deferring_access_checks ();
21214       return error_mark_node;
21215     }
21216
21217   /* The DECL_TI_TEMPLATE should always be the immediate parent
21218      template, not the most general template.  */
21219   DECL_TI_TEMPLATE (fndecl) = tmpl;
21220   DECL_TI_ARGS (fndecl) = targ_ptr;
21221
21222   set_instantiating_module (fndecl);
21223
21224   /* Now we know the specialization, compute access previously
21225      deferred.  Do no access control for inheriting constructors,
21226      as we already checked access for the inherited constructor.  */
21227   if (!(flag_new_inheriting_ctors
21228         && DECL_INHERITED_CTOR (fndecl)))
21229     {
21230       push_access_scope (fndecl);
21231       if (!perform_deferred_access_checks (complain))
21232         access_ok = false;
21233       pop_access_scope (fndecl);
21234     }
21235   pop_deferring_access_checks ();
21236
21237   /* If we've just instantiated the main entry point for a function,
21238      instantiate all the alternate entry points as well.  We do this
21239      by cloning the instantiation of the main entry point, not by
21240      instantiating the template clones.  */
21241   if (tree chain = DECL_CHAIN (gen_tmpl))
21242     if (DECL_P (chain) && DECL_CLONED_FUNCTION_P (chain))
21243       clone_cdtor (fndecl, /*update_methods=*/false);
21244
21245   if (!access_ok)
21246     {
21247       if (!(complain & tf_error))
21248         {
21249           /* Remember to reinstantiate when we're out of SFINAE so the user
21250              can see the errors.  */
21251           FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
21252         }
21253       return error_mark_node;
21254     }
21255   return fndecl;
21256 }
21257
21258 /* Wrapper for instantiate_template_1.  */
21259
21260 tree
21261 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
21262 {
21263   tree ret;
21264   timevar_push (TV_TEMPLATE_INST);
21265   ret = instantiate_template_1 (tmpl, orig_args,  complain);
21266   timevar_pop (TV_TEMPLATE_INST);
21267   return ret;
21268 }
21269
21270 /* Instantiate the alias template TMPL with ARGS.  Also push a template
21271    instantiation level, which instantiate_template doesn't do because
21272    functions and variables have sufficient context established by the
21273    callers.  */
21274
21275 static tree
21276 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
21277 {
21278   if (tmpl == error_mark_node || args == error_mark_node)
21279     return error_mark_node;
21280
21281   args =
21282     coerce_innermost_template_parms (DECL_TEMPLATE_PARMS (tmpl),
21283                                      args, tmpl, complain,
21284                                      /*require_all_args=*/true,
21285                                      /*use_default_args=*/true);
21286
21287   /* FIXME check for satisfaction in check_instantiated_args.  */
21288   if (flag_concepts
21289       && !any_dependent_template_arguments_p (args)
21290       && !constraints_satisfied_p (tmpl, args))
21291     {
21292       if (complain & tf_error)
21293         {
21294           auto_diagnostic_group d;
21295           error ("template constraint failure for %qD", tmpl);
21296           diagnose_constraints (input_location, tmpl, args);
21297         }
21298       return error_mark_node;
21299     }
21300
21301   if (!push_tinst_level (tmpl, args))
21302     return error_mark_node;
21303   tree r = instantiate_template (tmpl, args, complain);
21304   pop_tinst_level ();
21305
21306   if (tree d = dependent_alias_template_spec_p (TREE_TYPE (r), nt_opaque))
21307     {
21308       /* An alias template specialization can be dependent
21309          even if its underlying type is not.  */
21310       TYPE_DEPENDENT_P (d) = true;
21311       TYPE_DEPENDENT_P_VALID (d) = true;
21312       /* Sometimes a dependent alias spec is equivalent to its expansion,
21313          sometimes not.  So always use structural_comptypes.  */
21314       SET_TYPE_STRUCTURAL_EQUALITY (d);
21315     }
21316
21317   return r;
21318 }
21319
21320 /* PARM is a template parameter pack for FN.  Returns true iff
21321    PARM is used in a deducible way in the argument list of FN.  */
21322
21323 static bool
21324 pack_deducible_p (tree parm, tree fn)
21325 {
21326   tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
21327   for (; t; t = TREE_CHAIN (t))
21328     {
21329       tree type = TREE_VALUE (t);
21330       tree packs;
21331       if (!PACK_EXPANSION_P (type))
21332         continue;
21333       for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
21334            packs; packs = TREE_CHAIN (packs))
21335         if (template_args_equal (TREE_VALUE (packs), parm))
21336           {
21337             /* The template parameter pack is used in a function parameter
21338                pack.  If this is the end of the parameter list, the
21339                template parameter pack is deducible.  */
21340             if (TREE_CHAIN (t) == void_list_node)
21341               return true;
21342             else
21343               /* Otherwise, not.  Well, it could be deduced from
21344                  a non-pack parameter, but doing so would end up with
21345                  a deduction mismatch, so don't bother.  */
21346               return false;
21347           }
21348     }
21349   /* The template parameter pack isn't used in any function parameter
21350      packs, but it might be used deeper, e.g. tuple<Args...>.  */
21351   return true;
21352 }
21353
21354 /* Subroutine of fn_type_unification: check non-dependent parms for
21355    convertibility.  */
21356
21357 static int
21358 check_non_deducible_conversions (tree parms, const tree *args, unsigned nargs,
21359                                  tree fn, unification_kind_t strict, int flags,
21360                                  struct conversion **convs, bool explain_p)
21361 {
21362   /* Non-constructor methods need to leave a conversion for 'this', which
21363      isn't included in nargs here.  */
21364   unsigned offset = (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
21365                      && !DECL_CONSTRUCTOR_P (fn));
21366
21367   for (unsigned ia = 0;
21368        parms && parms != void_list_node && ia < nargs; )
21369     {
21370       tree parm = TREE_VALUE (parms);
21371
21372       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
21373           && (!TREE_CHAIN (parms)
21374               || TREE_CHAIN (parms) == void_list_node))
21375         /* For a function parameter pack that occurs at the end of the
21376            parameter-declaration-list, the type A of each remaining
21377            argument of the call is compared with the type P of the
21378            declarator-id of the function parameter pack.  */
21379         break;
21380
21381       parms = TREE_CHAIN (parms);
21382
21383       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
21384         /* For a function parameter pack that does not occur at the
21385            end of the parameter-declaration-list, the type of the
21386            parameter pack is a non-deduced context.  */
21387         continue;
21388
21389       if (!uses_template_parms (parm))
21390         {
21391           tree arg = args[ia];
21392           conversion **conv_p = convs ? &convs[ia+offset] : NULL;
21393           int lflags = conv_flags (ia, nargs, fn, arg, flags);
21394
21395           if (check_non_deducible_conversion (parm, arg, strict, lflags,
21396                                               conv_p, explain_p))
21397             return 1;
21398         }
21399
21400       ++ia;
21401     }
21402
21403   return 0;
21404 }
21405
21406 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
21407    NARGS elements of the arguments that are being used when calling
21408    it.  TARGS is a vector into which the deduced template arguments
21409    are placed.
21410
21411    Returns either a FUNCTION_DECL for the matching specialization of FN or
21412    NULL_TREE if no suitable specialization can be found.  If EXPLAIN_P is
21413    true, diagnostics will be printed to explain why it failed.
21414
21415    If FN is a conversion operator, or we are trying to produce a specific
21416    specialization, RETURN_TYPE is the return type desired.
21417
21418    The EXPLICIT_TARGS are explicit template arguments provided via a
21419    template-id.
21420
21421    The parameter STRICT is one of:
21422
21423    DEDUCE_CALL:
21424      We are deducing arguments for a function call, as in
21425      [temp.deduct.call].  If RETURN_TYPE is non-null, we are
21426      deducing arguments for a call to the result of a conversion
21427      function template, as in [over.call.object].
21428
21429    DEDUCE_CONV:
21430      We are deducing arguments for a conversion function, as in
21431      [temp.deduct.conv].
21432
21433    DEDUCE_EXACT:
21434      We are deducing arguments when doing an explicit instantiation
21435      as in [temp.explicit], when determining an explicit specialization
21436      as in [temp.expl.spec], or when taking the address of a function
21437      template, as in [temp.deduct.funcaddr].  */
21438
21439 tree
21440 fn_type_unification (tree fn,
21441                      tree explicit_targs,
21442                      tree targs,
21443                      const tree *args,
21444                      unsigned int nargs,
21445                      tree return_type,
21446                      unification_kind_t strict,
21447                      int flags,
21448                      struct conversion **convs,
21449                      bool explain_p,
21450                      bool decltype_p)
21451 {
21452   tree parms;
21453   tree fntype;
21454   tree decl = NULL_TREE;
21455   tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
21456   bool ok;
21457   static int deduction_depth;
21458   /* type_unification_real will pass back any access checks from default
21459      template argument substitution.  */
21460   vec<deferred_access_check, va_gc> *checks = NULL;
21461   /* We don't have all the template args yet.  */
21462   bool incomplete = true;
21463
21464   tree orig_fn = fn;
21465   if (flag_new_inheriting_ctors)
21466     fn = strip_inheriting_ctors (fn);
21467
21468   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
21469   tree r = error_mark_node;
21470
21471   tree full_targs = targs;
21472   if (TMPL_ARGS_DEPTH (targs)
21473       < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (fn)))
21474     full_targs = (add_outermost_template_args
21475                   (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (fn)),
21476                    targs));
21477
21478   if (decltype_p)
21479     complain |= tf_decltype;
21480
21481   /* In C++0x, it's possible to have a function template whose type depends
21482      on itself recursively.  This is most obvious with decltype, but can also
21483      occur with enumeration scope (c++/48969).  So we need to catch infinite
21484      recursion and reject the substitution at deduction time; this function
21485      will return error_mark_node for any repeated substitution.
21486
21487      This also catches excessive recursion such as when f<N> depends on
21488      f<N-1> across all integers, and returns error_mark_node for all the
21489      substitutions back up to the initial one.
21490
21491      This is, of course, not reentrant.  */
21492   if (excessive_deduction_depth)
21493     return error_mark_node;
21494   ++deduction_depth;
21495
21496   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
21497
21498   fntype = TREE_TYPE (fn);
21499   if (explicit_targs)
21500     {
21501       /* [temp.deduct]
21502
21503          The specified template arguments must match the template
21504          parameters in kind (i.e., type, nontype, template), and there
21505          must not be more arguments than there are parameters;
21506          otherwise type deduction fails.
21507
21508          Nontype arguments must match the types of the corresponding
21509          nontype template parameters, or must be convertible to the
21510          types of the corresponding nontype parameters as specified in
21511          _temp.arg.nontype_, otherwise type deduction fails.
21512
21513          All references in the function type of the function template
21514          to the corresponding template parameters are replaced by the
21515          specified template argument values.  If a substitution in a
21516          template parameter or in the function type of the function
21517          template results in an invalid type, type deduction fails.  */
21518       int i, len = TREE_VEC_LENGTH (tparms);
21519       location_t loc = input_location;
21520       incomplete = false;
21521
21522       if (explicit_targs == error_mark_node)
21523         goto fail;
21524
21525       if (TMPL_ARGS_DEPTH (explicit_targs)
21526           < TMPL_ARGS_DEPTH (full_targs))
21527         explicit_targs = add_outermost_template_args (full_targs,
21528                                                       explicit_targs);
21529
21530       /* Adjust any explicit template arguments before entering the
21531          substitution context.  */
21532       explicit_targs
21533         = (coerce_template_parms (tparms, explicit_targs, fn,
21534                                   complain|tf_partial,
21535                                   /*require_all_args=*/false,
21536                                   /*use_default_args=*/false));
21537       if (explicit_targs == error_mark_node)
21538         goto fail;
21539
21540       /* Substitute the explicit args into the function type.  This is
21541          necessary so that, for instance, explicitly declared function
21542          arguments can match null pointed constants.  If we were given
21543          an incomplete set of explicit args, we must not do semantic
21544          processing during substitution as we could create partial
21545          instantiations.  */
21546       for (i = 0; i < len; i++)
21547         {
21548           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
21549           bool parameter_pack = false;
21550           tree targ = TREE_VEC_ELT (explicit_targs, i);
21551
21552           /* Dig out the actual parm.  */
21553           if (TREE_CODE (parm) == TYPE_DECL
21554               || TREE_CODE (parm) == TEMPLATE_DECL)
21555             {
21556               parm = TREE_TYPE (parm);
21557               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
21558             }
21559           else if (TREE_CODE (parm) == PARM_DECL)
21560             {
21561               parm = DECL_INITIAL (parm);
21562               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
21563             }
21564
21565           if (targ == NULL_TREE)
21566             /* No explicit argument for this template parameter.  */
21567             incomplete = true;
21568           else if (parameter_pack && pack_deducible_p (parm, fn))
21569             {
21570               /* Mark the argument pack as "incomplete". We could
21571                  still deduce more arguments during unification.
21572                  We remove this mark in type_unification_real.  */
21573               ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
21574               ARGUMENT_PACK_EXPLICIT_ARGS (targ)
21575                 = ARGUMENT_PACK_ARGS (targ);
21576
21577               /* We have some incomplete argument packs.  */
21578               incomplete = true;
21579             }
21580         }
21581
21582       if (incomplete)
21583         {
21584           if (!push_tinst_level (fn, explicit_targs))
21585             {
21586               excessive_deduction_depth = true;
21587               goto fail;
21588             }
21589           ++processing_template_decl;
21590           input_location = DECL_SOURCE_LOCATION (fn);
21591           /* Ignore any access checks; we'll see them again in
21592              instantiate_template and they might have the wrong
21593              access path at this point.  */
21594           push_deferring_access_checks (dk_deferred);
21595           tsubst_flags_t ecomplain = complain | tf_partial | tf_fndecl_type;
21596           fntype = tsubst (TREE_TYPE (fn), explicit_targs, ecomplain, NULL_TREE);
21597           pop_deferring_access_checks ();
21598           input_location = loc;
21599           --processing_template_decl;
21600           pop_tinst_level ();
21601
21602           if (fntype == error_mark_node)
21603             goto fail;
21604         }
21605
21606       /* Place the explicitly specified arguments in TARGS.  */
21607       explicit_targs = INNERMOST_TEMPLATE_ARGS (explicit_targs);
21608       for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
21609         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
21610       if (!incomplete && CHECKING_P
21611           && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
21612         SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
21613           (targs, NUM_TMPL_ARGS (explicit_targs));
21614     }
21615
21616   if (return_type && strict != DEDUCE_CALL)
21617     {
21618       tree *new_args = XALLOCAVEC (tree, nargs + 1);
21619       new_args[0] = return_type;
21620       memcpy (new_args + 1, args, nargs * sizeof (tree));
21621       args = new_args;
21622       ++nargs;
21623     }
21624
21625   if (!incomplete)
21626     goto deduced;
21627
21628   /* Never do unification on the 'this' parameter.  */
21629   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
21630
21631   if (return_type && strict == DEDUCE_CALL)
21632     {
21633       /* We're deducing for a call to the result of a template conversion
21634          function.  The parms we really want are in return_type.  */
21635       if (INDIRECT_TYPE_P (return_type))
21636         return_type = TREE_TYPE (return_type);
21637       parms = TYPE_ARG_TYPES (return_type);
21638     }
21639   else if (return_type)
21640     {
21641       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
21642     }
21643
21644   /* We allow incomplete unification without an error message here
21645      because the standard doesn't seem to explicitly prohibit it.  Our
21646      callers must be ready to deal with unification failures in any
21647      event.  */
21648
21649   /* If we aren't explaining yet, push tinst context so we can see where
21650      any errors (e.g. from class instantiations triggered by instantiation
21651      of default template arguments) come from.  If we are explaining, this
21652      context is redundant.  */
21653   if (!explain_p && !push_tinst_level (fn, targs))
21654     {
21655       excessive_deduction_depth = true;
21656       goto fail;
21657     }
21658
21659   ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
21660                                full_targs, parms, args, nargs, /*subr=*/0,
21661                                strict, &checks, explain_p);
21662   if (!explain_p)
21663     pop_tinst_level ();
21664   if (!ok)
21665     goto fail;
21666
21667   /* Now that we have bindings for all of the template arguments,
21668      ensure that the arguments deduced for the template template
21669      parameters have compatible template parameter lists.  We cannot
21670      check this property before we have deduced all template
21671      arguments, because the template parameter types of a template
21672      template parameter might depend on prior template parameters
21673      deduced after the template template parameter.  The following
21674      ill-formed example illustrates this issue:
21675
21676        template<typename T, template<T> class C> void f(C<5>, T);
21677
21678        template<int N> struct X {};
21679
21680        void g() {
21681          f(X<5>(), 5l); // error: template argument deduction fails
21682        }
21683
21684      The template parameter list of 'C' depends on the template type
21685      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
21686      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
21687      time that we deduce 'C'.  */
21688   if (!template_template_parm_bindings_ok_p
21689            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
21690     {
21691       unify_inconsistent_template_template_parameters (explain_p);
21692       goto fail;
21693     }
21694
21695  deduced:
21696
21697   /* CWG2369: Check satisfaction before non-deducible conversions.  */
21698   if (!constraints_satisfied_p (fn, targs))
21699     {
21700       if (explain_p)
21701         diagnose_constraints (DECL_SOURCE_LOCATION (fn), fn, targs);
21702       goto fail;
21703     }
21704
21705   /* DR 1391: All parameters have args, now check non-dependent parms for
21706      convertibility.  We don't do this if all args were explicitly specified,
21707      as the standard says that we substitute explicit args immediately.  */
21708   if (incomplete
21709       && check_non_deducible_conversions (parms, args, nargs, fn, strict, flags,
21710                                           convs, explain_p))
21711     goto fail;
21712
21713   /* All is well so far.  Now, check:
21714
21715      [temp.deduct]
21716
21717      When all template arguments have been deduced, all uses of
21718      template parameters in nondeduced contexts are replaced with
21719      the corresponding deduced argument values.  If the
21720      substitution results in an invalid type, as described above,
21721      type deduction fails.  */
21722   if (!push_tinst_level (fn, targs))
21723     {
21724       excessive_deduction_depth = true;
21725       goto fail;
21726     }
21727
21728   /* Also collect access checks from the instantiation.  */
21729   reopen_deferring_access_checks (checks);
21730
21731   decl = instantiate_template (fn, targs, complain);
21732
21733   checks = get_deferred_access_checks ();
21734   pop_deferring_access_checks ();
21735
21736   pop_tinst_level ();
21737
21738   if (decl == error_mark_node)
21739     goto fail;
21740
21741   /* Now perform any access checks encountered during substitution.  */
21742   push_access_scope (decl);
21743   ok = perform_access_checks (checks, complain);
21744   pop_access_scope (decl);
21745   if (!ok)
21746     goto fail;
21747
21748   /* If we're looking for an exact match, check that what we got
21749      is indeed an exact match.  It might not be if some template
21750      parameters are used in non-deduced contexts.  But don't check
21751      for an exact match if we have dependent template arguments;
21752      in that case we're doing partial ordering, and we already know
21753      that we have two candidates that will provide the actual type.  */
21754   if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
21755     {
21756       tree substed = TREE_TYPE (decl);
21757       unsigned int i;
21758
21759       tree sarg
21760         = skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
21761       if (return_type)
21762         sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
21763       for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
21764         if (!same_type_p (args[i], TREE_VALUE (sarg)))
21765           {
21766             unify_type_mismatch (explain_p, args[i],
21767                                  TREE_VALUE (sarg));
21768             goto fail;
21769           }
21770     }
21771
21772   /* After doing deduction with the inherited constructor, actually return an
21773      instantiation of the inheriting constructor.  */
21774   if (orig_fn != fn)
21775     decl = instantiate_template (orig_fn, targs, complain);
21776
21777   r = decl;
21778
21779  fail:
21780   --deduction_depth;
21781   if (excessive_deduction_depth)
21782     {
21783       if (deduction_depth == 0)
21784         /* Reset once we're all the way out.  */
21785         excessive_deduction_depth = false;
21786     }
21787
21788   return r;
21789 }
21790
21791 /* Adjust types before performing type deduction, as described in
21792    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
21793    sections are symmetric.  PARM is the type of a function parameter
21794    or the return type of the conversion function.  ARG is the type of
21795    the argument passed to the call, or the type of the value
21796    initialized with the result of the conversion function.
21797    ARG_EXPR is the original argument expression, which may be null.  */
21798
21799 static int
21800 maybe_adjust_types_for_deduction (unification_kind_t strict,
21801                                   tree* parm,
21802                                   tree* arg,
21803                                   tree arg_expr)
21804 {
21805   int result = 0;
21806
21807   switch (strict)
21808     {
21809     case DEDUCE_CALL:
21810       break;
21811
21812     case DEDUCE_CONV:
21813       /* Swap PARM and ARG throughout the remainder of this
21814          function; the handling is precisely symmetric since PARM
21815          will initialize ARG rather than vice versa.  */
21816       std::swap (parm, arg);
21817       break;
21818
21819     case DEDUCE_EXACT:
21820       /* Core issue #873: Do the DR606 thing (see below) for these cases,
21821          too, but here handle it by stripping the reference from PARM
21822          rather than by adding it to ARG.  */
21823       if (TYPE_REF_P (*parm)
21824           && TYPE_REF_IS_RVALUE (*parm)
21825           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
21826           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
21827           && TYPE_REF_P (*arg)
21828           && !TYPE_REF_IS_RVALUE (*arg))
21829         *parm = TREE_TYPE (*parm);
21830       /* Nothing else to do in this case.  */
21831       return 0;
21832
21833     default:
21834       gcc_unreachable ();
21835     }
21836
21837   if (!TYPE_REF_P (*parm))
21838     {
21839       /* [temp.deduct.call]
21840
21841          If P is not a reference type:
21842
21843          --If A is an array type, the pointer type produced by the
21844          array-to-pointer standard conversion (_conv.array_) is
21845          used in place of A for type deduction; otherwise,
21846
21847          --If A is a function type, the pointer type produced by
21848          the function-to-pointer standard conversion
21849          (_conv.func_) is used in place of A for type deduction;
21850          otherwise,
21851
21852          --If A is a cv-qualified type, the top level
21853          cv-qualifiers of A's type are ignored for type
21854          deduction.  */
21855       if (TREE_CODE (*arg) == ARRAY_TYPE)
21856         *arg = build_pointer_type (TREE_TYPE (*arg));
21857       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
21858         *arg = build_pointer_type (*arg);
21859       else
21860         *arg = TYPE_MAIN_VARIANT (*arg);
21861     }
21862
21863   /* [14.8.2.1/3 temp.deduct.call], "A forwarding reference is an rvalue
21864      reference to a cv-unqualified template parameter that does not represent a
21865      template parameter of a class template (during class template argument
21866      deduction (13.3.1.8)). If P is a forwarding reference and the argument is
21867      an lvalue, the type "lvalue reference to A" is used in place of A for type
21868      deduction. */
21869   if (TYPE_REF_P (*parm)
21870       && TYPE_REF_IS_RVALUE (*parm)
21871       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
21872       && !TEMPLATE_TYPE_PARM_FOR_CLASS (TREE_TYPE (*parm))
21873       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
21874       && (arg_expr ? lvalue_p (arg_expr)
21875           /* try_one_overload doesn't provide an arg_expr, but
21876              functions are always lvalues.  */
21877           : TREE_CODE (*arg) == FUNCTION_TYPE))
21878     *arg = build_reference_type (*arg);
21879
21880   /* [temp.deduct.call]
21881
21882      If P is a cv-qualified type, the top level cv-qualifiers
21883      of P's type are ignored for type deduction.  If P is a
21884      reference type, the type referred to by P is used for
21885      type deduction.  */
21886   *parm = TYPE_MAIN_VARIANT (*parm);
21887   if (TYPE_REF_P (*parm))
21888     {
21889       *parm = TREE_TYPE (*parm);
21890       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
21891     }
21892
21893   /* DR 322. For conversion deduction, remove a reference type on parm
21894      too (which has been swapped into ARG).  */
21895   if (strict == DEDUCE_CONV && TYPE_REF_P (*arg))
21896     *arg = TREE_TYPE (*arg);
21897
21898   return result;
21899 }
21900
21901 /* Subroutine of fn_type_unification.  PARM is a function parameter of a
21902    template which doesn't contain any deducible template parameters; check if
21903    ARG is a suitable match for it.  STRICT, FLAGS and EXPLAIN_P are as in
21904    unify_one_argument.  */
21905
21906 static int
21907 check_non_deducible_conversion (tree parm, tree arg, int strict,
21908                                 int flags, struct conversion **conv_p,
21909                                 bool explain_p)
21910 {
21911   tree type;
21912
21913   if (!TYPE_P (arg))
21914     type = TREE_TYPE (arg);
21915   else
21916     type = arg;
21917
21918   if (same_type_p (parm, type))
21919     return unify_success (explain_p);
21920
21921   tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
21922   if (strict == DEDUCE_CONV)
21923     {
21924       if (can_convert_arg (type, parm, NULL_TREE, flags, complain))
21925         return unify_success (explain_p);
21926     }
21927   else if (strict != DEDUCE_EXACT)
21928     {
21929       bool ok = false;
21930       tree conv_arg = TYPE_P (arg) ? NULL_TREE : arg;
21931       if (conv_p)
21932         /* Avoid recalculating this in add_function_candidate.  */
21933         ok = (*conv_p
21934               = good_conversion (parm, type, conv_arg, flags, complain));
21935       else
21936         ok = can_convert_arg (parm, type, conv_arg, flags, complain);
21937       if (ok)
21938         return unify_success (explain_p);
21939     }
21940
21941   if (strict == DEDUCE_EXACT)
21942     return unify_type_mismatch (explain_p, parm, arg);
21943   else
21944     return unify_arg_conversion (explain_p, parm, type, arg);
21945 }
21946
21947 static bool uses_deducible_template_parms (tree type);
21948
21949 /* Returns true iff the expression EXPR is one from which a template
21950    argument can be deduced.  In other words, if it's an undecorated
21951    use of a template non-type parameter.  */
21952
21953 static bool
21954 deducible_expression (tree expr)
21955 {
21956   /* Strip implicit conversions and implicit INDIRECT_REFs.  */
21957   while (CONVERT_EXPR_P (expr)
21958          || TREE_CODE (expr) == VIEW_CONVERT_EXPR
21959          || REFERENCE_REF_P (expr))
21960     expr = TREE_OPERAND (expr, 0);
21961   return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
21962 }
21963
21964 /* Returns true iff the array domain DOMAIN uses a template parameter in a
21965    deducible way; that is, if it has a max value of <PARM> - 1.  */
21966
21967 static bool
21968 deducible_array_bound (tree domain)
21969 {
21970   if (domain == NULL_TREE)
21971     return false;
21972
21973   tree max = TYPE_MAX_VALUE (domain);
21974   if (TREE_CODE (max) != MINUS_EXPR)
21975     return false;
21976
21977   return deducible_expression (TREE_OPERAND (max, 0));
21978 }
21979
21980 /* Returns true iff the template arguments ARGS use a template parameter
21981    in a deducible way.  */
21982
21983 static bool
21984 deducible_template_args (tree args)
21985 {
21986   for (int i = 0; i < TREE_VEC_LENGTH (args); ++i)
21987     {
21988       bool deducible;
21989       tree elt = TREE_VEC_ELT (args, i);
21990       if (ARGUMENT_PACK_P (elt))
21991         deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
21992       else
21993         {
21994           if (PACK_EXPANSION_P (elt))
21995             elt = PACK_EXPANSION_PATTERN (elt);
21996           if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
21997             deducible = true;
21998           else if (TYPE_P (elt))
21999             deducible = uses_deducible_template_parms (elt);
22000           else
22001             deducible = deducible_expression (elt);
22002         }
22003       if (deducible)
22004         return true;
22005     }
22006   return false;
22007 }
22008
22009 /* Returns true iff TYPE contains any deducible references to template
22010    parameters, as per 14.8.2.5.  */
22011
22012 static bool
22013 uses_deducible_template_parms (tree type)
22014 {
22015   if (PACK_EXPANSION_P (type))
22016     type = PACK_EXPANSION_PATTERN (type);
22017
22018   /* T
22019      cv-list T
22020      TT<T>
22021      TT<i>
22022      TT<> */
22023   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
22024       || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
22025     return true;
22026
22027   /* T*
22028      T&
22029      T&&  */
22030   if (INDIRECT_TYPE_P (type))
22031     return uses_deducible_template_parms (TREE_TYPE (type));
22032
22033   /* T[integer-constant ]
22034      type [i]  */
22035   if (TREE_CODE (type) == ARRAY_TYPE)
22036     return (uses_deducible_template_parms (TREE_TYPE (type))
22037             || deducible_array_bound (TYPE_DOMAIN (type)));
22038
22039   /* T type ::*
22040      type T::*
22041      T T::*
22042      T (type ::*)()
22043      type (T::*)()
22044      type (type ::*)(T)
22045      type (T::*)(T)
22046      T (type ::*)(T)
22047      T (T::*)()
22048      T (T::*)(T) */
22049   if (TYPE_PTRMEM_P (type))
22050     return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
22051             || (uses_deducible_template_parms
22052                 (TYPE_PTRMEM_POINTED_TO_TYPE (type))));
22053
22054   /* template-name <T> (where template-name refers to a class template)
22055      template-name <i> (where template-name refers to a class template) */
22056   if (CLASS_TYPE_P (type)
22057       && CLASSTYPE_TEMPLATE_INFO (type)
22058       && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
22059     return deducible_template_args (INNERMOST_TEMPLATE_ARGS
22060                                     (CLASSTYPE_TI_ARGS (type)));
22061
22062   /* type (T)
22063      T()
22064      T(T)  */
22065   if (FUNC_OR_METHOD_TYPE_P (type))
22066     {
22067       if (uses_deducible_template_parms (TREE_TYPE (type)))
22068         return true;
22069       tree parm = TYPE_ARG_TYPES (type);
22070       if (TREE_CODE (type) == METHOD_TYPE)
22071         parm = TREE_CHAIN (parm);
22072       for (; parm; parm = TREE_CHAIN (parm))
22073         if (uses_deducible_template_parms (TREE_VALUE (parm)))
22074           return true;
22075     }
22076
22077   return false;
22078 }
22079
22080 /* Subroutine of type_unification_real and unify_pack_expansion to
22081    handle unification of a single P/A pair.  Parameters are as
22082    for those functions.  */
22083
22084 static int
22085 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
22086                     int subr, unification_kind_t strict,
22087                     bool explain_p)
22088 {
22089   tree arg_expr = NULL_TREE;
22090   int arg_strict;
22091
22092   if (arg == error_mark_node || parm == error_mark_node)
22093     return unify_invalid (explain_p);
22094   if (arg == unknown_type_node)
22095     /* We can't deduce anything from this, but we might get all the
22096        template args from other function args.  */
22097     return unify_success (explain_p);
22098
22099   /* Implicit conversions (Clause 4) will be performed on a function
22100      argument to convert it to the type of the corresponding function
22101      parameter if the parameter type contains no template-parameters that
22102      participate in template argument deduction.  */
22103   if (strict != DEDUCE_EXACT
22104       && TYPE_P (parm) && !uses_deducible_template_parms (parm))
22105     /* For function parameters with no deducible template parameters,
22106        just return.  We'll check non-dependent conversions later.  */
22107     return unify_success (explain_p);
22108
22109   switch (strict)
22110     {
22111     case DEDUCE_CALL:
22112       arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
22113                     | UNIFY_ALLOW_MORE_CV_QUAL
22114                     | UNIFY_ALLOW_DERIVED);
22115       break;
22116
22117     case DEDUCE_CONV:
22118       arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
22119       break;
22120
22121     case DEDUCE_EXACT:
22122       arg_strict = UNIFY_ALLOW_NONE;
22123       break;
22124
22125     default:
22126       gcc_unreachable ();
22127     }
22128
22129   /* We only do these transformations if this is the top-level
22130      parameter_type_list in a call or declaration matching; in other
22131      situations (nested function declarators, template argument lists) we
22132      won't be comparing a type to an expression, and we don't do any type
22133      adjustments.  */
22134   if (!subr)
22135     {
22136       if (!TYPE_P (arg))
22137         {
22138           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
22139           if (type_unknown_p (arg))
22140             {
22141               /* [temp.deduct.type] A template-argument can be
22142                  deduced from a pointer to function or pointer
22143                  to member function argument if the set of
22144                  overloaded functions does not contain function
22145                  templates and at most one of a set of
22146                  overloaded functions provides a unique
22147                  match.  */
22148               resolve_overloaded_unification (tparms, targs, parm,
22149                                               arg, strict,
22150                                               arg_strict, explain_p);
22151               /* If a unique match was not found, this is a
22152                  non-deduced context, so we still succeed. */
22153               return unify_success (explain_p);
22154             }
22155
22156           arg_expr = arg;
22157           arg = unlowered_expr_type (arg);
22158           if (arg == error_mark_node)
22159             return unify_invalid (explain_p);
22160         }
22161
22162       arg_strict |=
22163         maybe_adjust_types_for_deduction (strict, &parm, &arg, arg_expr);
22164     }
22165   else
22166     if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
22167         != (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
22168       return unify_template_argument_mismatch (explain_p, parm, arg);
22169
22170   /* For deduction from an init-list we need the actual list.  */
22171   if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
22172     arg = arg_expr;
22173   return unify (tparms, targs, parm, arg, arg_strict, explain_p);
22174 }
22175
22176 /* for_each_template_parm callback that always returns 0.  */
22177
22178 static int
22179 zero_r (tree, void *)
22180 {
22181   return 0;
22182 }
22183
22184 /* for_each_template_parm any_fn callback to handle deduction of a template
22185    type argument from the type of an array bound.  */
22186
22187 static int
22188 array_deduction_r (tree t, void *data)
22189 {
22190   tree_pair_p d = (tree_pair_p)data;
22191   tree &tparms = d->purpose;
22192   tree &targs = d->value;
22193
22194   if (TREE_CODE (t) == ARRAY_TYPE)
22195     if (tree dom = TYPE_DOMAIN (t))
22196       if (tree max = TYPE_MAX_VALUE (dom))
22197         {
22198           if (TREE_CODE (max) == MINUS_EXPR)
22199             max = TREE_OPERAND (max, 0);
22200           if (TREE_CODE (max) == TEMPLATE_PARM_INDEX)
22201             unify (tparms, targs, TREE_TYPE (max), size_type_node,
22202                    UNIFY_ALLOW_NONE, /*explain*/false);
22203         }
22204
22205   /* Keep walking.  */
22206   return 0;
22207 }
22208
22209 /* Try to deduce any not-yet-deduced template type arguments from the type of
22210    an array bound.  This is handled separately from unify because 14.8.2.5 says
22211    "The type of a type parameter is only deduced from an array bound if it is
22212    not otherwise deduced."  */
22213
22214 static void
22215 try_array_deduction (tree tparms, tree targs, tree parm)
22216 {
22217   tree_pair_s data = { tparms, targs };
22218   hash_set<tree> visited;
22219   for_each_template_parm (parm, zero_r, &data, &visited,
22220                           /*nondeduced*/false, array_deduction_r);
22221 }
22222
22223 /* Most parms like fn_type_unification.
22224
22225    If SUBR is 1, we're being called recursively (to unify the
22226    arguments of a function or method parameter of a function
22227    template).
22228
22229    CHECKS is a pointer to a vector of access checks encountered while
22230    substituting default template arguments.  */
22231
22232 static int
22233 type_unification_real (tree tparms,
22234                        tree full_targs,
22235                        tree xparms,
22236                        const tree *xargs,
22237                        unsigned int xnargs,
22238                        int subr,
22239                        unification_kind_t strict,
22240                        vec<deferred_access_check, va_gc> **checks,
22241                        bool explain_p)
22242 {
22243   tree parm, arg;
22244   int i;
22245   int ntparms = TREE_VEC_LENGTH (tparms);
22246   int saw_undeduced = 0;
22247   tree parms;
22248   const tree *args;
22249   unsigned int nargs;
22250   unsigned int ia;
22251
22252   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
22253   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
22254   gcc_assert (ntparms > 0);
22255
22256   tree targs = INNERMOST_TEMPLATE_ARGS (full_targs);
22257
22258   /* Reset the number of non-defaulted template arguments contained
22259      in TARGS.  */
22260   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
22261
22262  again:
22263   parms = xparms;
22264   args = xargs;
22265   nargs = xnargs;
22266
22267   ia = 0;
22268   while (parms && parms != void_list_node
22269          && ia < nargs)
22270     {
22271       parm = TREE_VALUE (parms);
22272
22273       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
22274           && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
22275         /* For a function parameter pack that occurs at the end of the
22276            parameter-declaration-list, the type A of each remaining
22277            argument of the call is compared with the type P of the
22278            declarator-id of the function parameter pack.  */
22279         break;
22280
22281       parms = TREE_CHAIN (parms);
22282
22283       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
22284         /* For a function parameter pack that does not occur at the
22285            end of the parameter-declaration-list, the type of the
22286            parameter pack is a non-deduced context.  */
22287         continue;
22288
22289       arg = args[ia];
22290       ++ia;
22291
22292       if (unify_one_argument (tparms, full_targs, parm, arg, subr, strict,
22293                               explain_p))
22294         return 1;
22295     }
22296
22297   if (parms
22298       && parms != void_list_node
22299       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
22300     {
22301       /* Unify the remaining arguments with the pack expansion type.  */
22302       tree argvec;
22303       tree parmvec = make_tree_vec (1);
22304
22305       /* Allocate a TREE_VEC and copy in all of the arguments */
22306       argvec = make_tree_vec (nargs - ia);
22307       for (i = 0; ia < nargs; ++ia, ++i)
22308         TREE_VEC_ELT (argvec, i) = args[ia];
22309
22310       /* Copy the parameter into parmvec.  */
22311       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
22312       if (unify_pack_expansion (tparms, full_targs, parmvec, argvec, strict,
22313                                 /*subr=*/subr, explain_p))
22314         return 1;
22315
22316       /* Advance to the end of the list of parameters.  */
22317       parms = TREE_CHAIN (parms);
22318     }
22319
22320   /* Fail if we've reached the end of the parm list, and more args
22321      are present, and the parm list isn't variadic.  */
22322   if (ia < nargs && parms == void_list_node)
22323     return unify_too_many_arguments (explain_p, nargs, ia);
22324   /* Fail if parms are left and they don't have default values and
22325      they aren't all deduced as empty packs (c++/57397).  This is
22326      consistent with sufficient_parms_p.  */
22327   if (parms && parms != void_list_node
22328       && TREE_PURPOSE (parms) == NULL_TREE)
22329     {
22330       unsigned int count = nargs;
22331       tree p = parms;
22332       bool type_pack_p;
22333       do
22334         {
22335           type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
22336           if (!type_pack_p)
22337             count++;
22338           p = TREE_CHAIN (p);
22339         }
22340       while (p && p != void_list_node);
22341       if (count != nargs)
22342         return unify_too_few_arguments (explain_p, ia, count,
22343                                         type_pack_p);
22344     }
22345
22346   if (!subr)
22347     {
22348       tsubst_flags_t complain = (explain_p
22349                                  ? tf_warning_or_error
22350                                  : tf_none);
22351       bool tried_array_deduction = (cxx_dialect < cxx17);
22352
22353       for (i = 0; i < ntparms; i++)
22354         {
22355           tree targ = TREE_VEC_ELT (targs, i);
22356           tree tparm = TREE_VEC_ELT (tparms, i);
22357
22358           /* Clear the "incomplete" flags on all argument packs now so that
22359              substituting them into later default arguments works.  */
22360           if (targ && ARGUMENT_PACK_P (targ))
22361             {
22362               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
22363               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
22364             }
22365
22366           if (targ || tparm == error_mark_node)
22367             continue;
22368           tparm = TREE_VALUE (tparm);
22369
22370           if (TREE_CODE (tparm) == TYPE_DECL
22371               && !tried_array_deduction)
22372             {
22373               try_array_deduction (tparms, targs, xparms);
22374               tried_array_deduction = true;
22375               if (TREE_VEC_ELT (targs, i))
22376                 continue;
22377             }
22378
22379           /* If this is an undeduced nontype parameter that depends on
22380              a type parameter, try another pass; its type may have been
22381              deduced from a later argument than the one from which
22382              this parameter can be deduced.  */
22383           if (TREE_CODE (tparm) == PARM_DECL
22384               && uses_template_parms (TREE_TYPE (tparm))
22385               && saw_undeduced < 2)
22386             {
22387               saw_undeduced = 1;
22388               continue;
22389             }
22390
22391           /* Core issue #226 (C++0x) [temp.deduct]:
22392
22393              If a template argument has not been deduced, its
22394              default template argument, if any, is used.
22395
22396              When we are in C++98 mode, TREE_PURPOSE will either
22397              be NULL_TREE or ERROR_MARK_NODE, so we do not need
22398              to explicitly check cxx_dialect here.  */
22399           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
22400             /* OK, there is a default argument.  Wait until after the
22401                conversion check to do substitution.  */
22402             continue;
22403
22404           /* If the type parameter is a parameter pack, then it will
22405              be deduced to an empty parameter pack.  */
22406           if (template_parameter_pack_p (tparm))
22407             {
22408               tree arg;
22409
22410               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
22411                 {
22412                   arg = make_node (NONTYPE_ARGUMENT_PACK);
22413                   TREE_CONSTANT (arg) = 1;
22414                 }
22415               else
22416                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
22417
22418               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
22419
22420               TREE_VEC_ELT (targs, i) = arg;
22421               continue;
22422             }
22423
22424           return unify_parameter_deduction_failure (explain_p, tparm);
22425         }
22426
22427       /* Now substitute into the default template arguments.  */
22428       for (i = 0; i < ntparms; i++)
22429         {
22430           tree targ = TREE_VEC_ELT (targs, i);
22431           tree tparm = TREE_VEC_ELT (tparms, i);
22432
22433           if (targ || tparm == error_mark_node)
22434             continue;
22435           tree parm = TREE_VALUE (tparm);
22436           tree arg = TREE_PURPOSE (tparm);
22437           reopen_deferring_access_checks (*checks);
22438           location_t save_loc = input_location;
22439           if (DECL_P (parm))
22440             input_location = DECL_SOURCE_LOCATION (parm);
22441
22442           if (saw_undeduced == 1
22443               && TREE_CODE (parm) == PARM_DECL
22444               && uses_template_parms (TREE_TYPE (parm)))
22445             {
22446               /* The type of this non-type parameter depends on undeduced
22447                  parameters.  Don't try to use its default argument yet,
22448                  since we might deduce an argument for it on the next pass,
22449                  but do check whether the arguments we already have cause
22450                  substitution failure, so that that happens before we try
22451                  later default arguments (78489).  */
22452               ++processing_template_decl;
22453               tree type = tsubst (TREE_TYPE (parm), full_targs, complain,
22454                                   NULL_TREE);
22455               --processing_template_decl;
22456               if (type == error_mark_node)
22457                 arg = error_mark_node;
22458               else
22459                 arg = NULL_TREE;
22460             }
22461           else
22462             {
22463               /* Even if the call is happening in template context, getting
22464                  here means it's non-dependent, and a default argument is
22465                  considered a separate definition under [temp.decls], so we can
22466                  do this substitution without processing_template_decl.  This
22467                  is important if the default argument contains something that
22468                  might be instantiation-dependent like access (87480).  */
22469               processing_template_decl_sentinel s;
22470               tree substed = NULL_TREE;
22471               if (saw_undeduced == 1)
22472                 {
22473                   /* First instatiate in template context, in case we still
22474                      depend on undeduced template parameters.  */
22475                   ++processing_template_decl;
22476                   substed = tsubst_template_arg (arg, full_targs, complain,
22477                                                  NULL_TREE);
22478                   --processing_template_decl;
22479                   if (substed != error_mark_node
22480                       && !uses_template_parms (substed))
22481                     /* We replaced all the tparms, substitute again out of
22482                        template context.  */
22483                     substed = NULL_TREE;
22484                 }
22485               if (!substed)
22486                 substed = tsubst_template_arg (arg, full_targs, complain,
22487                                                NULL_TREE);
22488
22489               if (!uses_template_parms (substed))
22490                 arg = convert_template_argument (parm, substed, full_targs,
22491                                                  complain, i, NULL_TREE);
22492               else if (saw_undeduced == 1)
22493                 arg = NULL_TREE;
22494               else
22495                 arg = error_mark_node;
22496             }
22497
22498           input_location = save_loc;
22499           *checks = get_deferred_access_checks ();
22500           pop_deferring_access_checks ();
22501
22502           if (arg == error_mark_node)
22503             return 1;
22504           else if (arg)
22505             {
22506               TREE_VEC_ELT (targs, i) = arg;
22507               /* The position of the first default template argument,
22508                  is also the number of non-defaulted arguments in TARGS.
22509                  Record that.  */
22510               if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
22511                 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
22512             }
22513         }
22514
22515       if (saw_undeduced++ == 1)
22516         goto again;
22517     }
22518
22519   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
22520     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
22521
22522   return unify_success (explain_p);
22523 }
22524
22525 /* Subroutine of type_unification_real.  Args are like the variables
22526    at the call site.  ARG is an overloaded function (or template-id);
22527    we try deducing template args from each of the overloads, and if
22528    only one succeeds, we go with that.  Modifies TARGS and returns
22529    true on success.  */
22530
22531 static bool
22532 resolve_overloaded_unification (tree tparms,
22533                                 tree targs,
22534                                 tree parm,
22535                                 tree arg,
22536                                 unification_kind_t strict,
22537                                 int sub_strict,
22538                                 bool explain_p)
22539 {
22540   tree tempargs = copy_node (targs);
22541   int good = 0;
22542   tree goodfn = NULL_TREE;
22543   bool addr_p;
22544
22545   if (TREE_CODE (arg) == ADDR_EXPR)
22546     {
22547       arg = TREE_OPERAND (arg, 0);
22548       addr_p = true;
22549     }
22550   else
22551     addr_p = false;
22552
22553   if (TREE_CODE (arg) == COMPONENT_REF)
22554     /* Handle `&x' where `x' is some static or non-static member
22555        function name.  */
22556     arg = TREE_OPERAND (arg, 1);
22557
22558   if (TREE_CODE (arg) == OFFSET_REF)
22559     arg = TREE_OPERAND (arg, 1);
22560
22561   /* Strip baselink information.  */
22562   if (BASELINK_P (arg))
22563     arg = BASELINK_FUNCTIONS (arg);
22564
22565   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
22566     {
22567       /* If we got some explicit template args, we need to plug them into
22568          the affected templates before we try to unify, in case the
22569          explicit args will completely resolve the templates in question.  */
22570
22571       int ok = 0;
22572       tree expl_subargs = TREE_OPERAND (arg, 1);
22573       arg = TREE_OPERAND (arg, 0);
22574
22575       for (lkp_iterator iter (arg); iter; ++iter)
22576         {
22577           tree fn = *iter;
22578           tree subargs, elem;
22579
22580           if (TREE_CODE (fn) != TEMPLATE_DECL)
22581             continue;
22582
22583           subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
22584                                            expl_subargs, NULL_TREE, tf_none,
22585                                            /*require_all_args=*/true,
22586                                            /*use_default_args=*/true);
22587           if (subargs != error_mark_node
22588               && !any_dependent_template_arguments_p (subargs))
22589             {
22590               fn = instantiate_template (fn, subargs, tf_none);
22591               if (!constraints_satisfied_p (fn))
22592                 continue;
22593               if (undeduced_auto_decl (fn))
22594                 {
22595                   /* Instantiate the function to deduce its return type.  */
22596                   ++function_depth;
22597                   instantiate_decl (fn, /*defer*/false, /*class*/false);
22598                   --function_depth;
22599                 }
22600
22601               if (flag_noexcept_type)
22602                 maybe_instantiate_noexcept (fn, tf_none);
22603
22604               elem = TREE_TYPE (fn);
22605               if (try_one_overload (tparms, targs, tempargs, parm,
22606                                     elem, strict, sub_strict, addr_p, explain_p)
22607                   && (!goodfn || !same_type_p (goodfn, elem)))
22608                 {
22609                   goodfn = elem;
22610                   ++good;
22611                 }
22612             }
22613           else if (subargs)
22614             ++ok;
22615         }
22616       /* If no templates (or more than one) are fully resolved by the
22617          explicit arguments, this template-id is a non-deduced context; it
22618          could still be OK if we deduce all template arguments for the
22619          enclosing call through other arguments.  */
22620       if (good != 1)
22621         good = ok;
22622     }
22623   else if (!OVL_P (arg))
22624     /* If ARG is, for example, "(0, &f)" then its type will be unknown
22625        -- but the deduction does not succeed because the expression is
22626        not just the function on its own.  */
22627     return false;
22628   else
22629     for (lkp_iterator iter (arg); iter; ++iter)
22630       {
22631         tree fn = *iter;
22632         if (try_one_overload (tparms, targs, tempargs, parm, TREE_TYPE (fn),
22633                               strict, sub_strict, addr_p, explain_p)
22634             && (!goodfn || !decls_match (goodfn, fn)))
22635           {
22636             goodfn = fn;
22637             ++good;
22638           }
22639       }
22640
22641   /* [temp.deduct.type] A template-argument can be deduced from a pointer
22642      to function or pointer to member function argument if the set of
22643      overloaded functions does not contain function templates and at most
22644      one of a set of overloaded functions provides a unique match.
22645
22646      So if we found multiple possibilities, we return success but don't
22647      deduce anything.  */
22648
22649   if (good == 1)
22650     {
22651       int i = TREE_VEC_LENGTH (targs);
22652       for (; i--; )
22653         if (TREE_VEC_ELT (tempargs, i))
22654           {
22655             tree old = TREE_VEC_ELT (targs, i);
22656             tree new_ = TREE_VEC_ELT (tempargs, i);
22657             if (new_ && old && ARGUMENT_PACK_P (old)
22658                 && ARGUMENT_PACK_EXPLICIT_ARGS (old))
22659               /* Don't forget explicit template arguments in a pack.  */
22660               ARGUMENT_PACK_EXPLICIT_ARGS (new_)
22661                 = ARGUMENT_PACK_EXPLICIT_ARGS (old);
22662             TREE_VEC_ELT (targs, i) = new_;
22663           }
22664     }
22665   if (good)
22666     return true;
22667
22668   return false;
22669 }
22670
22671 /* Core DR 115: In contexts where deduction is done and fails, or in
22672    contexts where deduction is not done, if a template argument list is
22673    specified and it, along with any default template arguments, identifies
22674    a single function template specialization, then the template-id is an
22675    lvalue for the function template specialization.  */
22676
22677 tree
22678 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
22679 {
22680   tree expr, offset, baselink;
22681   bool addr;
22682
22683   if (!type_unknown_p (orig_expr))
22684     return orig_expr;
22685
22686   expr = orig_expr;
22687   addr = false;
22688   offset = NULL_TREE;
22689   baselink = NULL_TREE;
22690
22691   if (TREE_CODE (expr) == ADDR_EXPR)
22692     {
22693       expr = TREE_OPERAND (expr, 0);
22694       addr = true;
22695     }
22696   if (TREE_CODE (expr) == OFFSET_REF)
22697     {
22698       offset = expr;
22699       expr = TREE_OPERAND (expr, 1);
22700     }
22701   if (BASELINK_P (expr))
22702     {
22703       baselink = expr;
22704       expr = BASELINK_FUNCTIONS (expr);
22705     }
22706
22707   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
22708     {
22709       int good = 0;
22710       tree goodfn = NULL_TREE;
22711
22712       /* If we got some explicit template args, we need to plug them into
22713          the affected templates before we try to unify, in case the
22714          explicit args will completely resolve the templates in question.  */
22715
22716       tree expl_subargs = TREE_OPERAND (expr, 1);
22717       tree arg = TREE_OPERAND (expr, 0);
22718       tree badfn = NULL_TREE;
22719       tree badargs = NULL_TREE;
22720
22721       for (lkp_iterator iter (arg); iter; ++iter)
22722         {
22723           tree fn = *iter;
22724           tree subargs, elem;
22725
22726           if (TREE_CODE (fn) != TEMPLATE_DECL)
22727             continue;
22728
22729           subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
22730                                            expl_subargs, NULL_TREE, tf_none,
22731                                            /*require_all_args=*/true,
22732                                            /*use_default_args=*/true);
22733           if (subargs != error_mark_node
22734               && !any_dependent_template_arguments_p (subargs))
22735             {
22736               elem = instantiate_template (fn, subargs, tf_none);
22737               if (elem == error_mark_node)
22738                 {
22739                   badfn = fn;
22740                   badargs = subargs;
22741                 }
22742               else if (elem && (!goodfn || !decls_match (goodfn, elem))
22743                        && constraints_satisfied_p (elem))
22744                 {
22745                   goodfn = elem;
22746                   ++good;
22747                 }
22748             }
22749         }
22750       if (good == 1)
22751         {
22752           mark_used (goodfn);
22753           expr = goodfn;
22754           if (baselink)
22755             expr = build_baselink (BASELINK_BINFO (baselink),
22756                                    BASELINK_ACCESS_BINFO (baselink),
22757                                    expr, BASELINK_OPTYPE (baselink));
22758           if (offset)
22759             {
22760               tree base
22761                 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
22762               expr = build_offset_ref (base, expr, addr, complain);
22763             }
22764           if (addr)
22765             expr = cp_build_addr_expr (expr, complain);
22766           return expr;
22767         }
22768       else if (good == 0 && badargs && (complain & tf_error))
22769         /* There were no good options and at least one bad one, so let the
22770            user know what the problem is.  */
22771         instantiate_template (badfn, badargs, complain);
22772     }
22773   return orig_expr;
22774 }
22775
22776 /* As above, but error out if the expression remains overloaded.  */
22777
22778 tree
22779 resolve_nondeduced_context_or_error (tree exp, tsubst_flags_t complain)
22780 {
22781   exp = resolve_nondeduced_context (exp, complain);
22782   if (type_unknown_p (exp))
22783     {
22784       if (complain & tf_error)
22785         cxx_incomplete_type_error (exp, TREE_TYPE (exp));
22786       return error_mark_node;
22787     }
22788   return exp;
22789 }
22790
22791 /* Subroutine of resolve_overloaded_unification; does deduction for a single
22792    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
22793    different overloads deduce different arguments for a given parm.
22794    ADDR_P is true if the expression for which deduction is being
22795    performed was of the form "& fn" rather than simply "fn".
22796
22797    Returns 1 on success.  */
22798
22799 static int
22800 try_one_overload (tree tparms,
22801                   tree orig_targs,
22802                   tree targs,
22803                   tree parm,
22804                   tree arg,
22805                   unification_kind_t strict,
22806                   int sub_strict,
22807                   bool addr_p,
22808                   bool explain_p)
22809 {
22810   int nargs;
22811   tree tempargs;
22812   int i;
22813
22814   if (arg == error_mark_node)
22815     return 0;
22816
22817   /* [temp.deduct.type] A template-argument can be deduced from a pointer
22818      to function or pointer to member function argument if the set of
22819      overloaded functions does not contain function templates and at most
22820      one of a set of overloaded functions provides a unique match.
22821
22822      So if this is a template, just return success.  */
22823
22824   if (uses_template_parms (arg))
22825     return 1;
22826
22827   if (TREE_CODE (arg) == METHOD_TYPE)
22828     arg = build_ptrmemfunc_type (build_pointer_type (arg));
22829   else if (addr_p)
22830     arg = build_pointer_type (arg);
22831
22832   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
22833
22834   /* We don't copy orig_targs for this because if we have already deduced
22835      some template args from previous args, unify would complain when we
22836      try to deduce a template parameter for the same argument, even though
22837      there isn't really a conflict.  */
22838   nargs = TREE_VEC_LENGTH (targs);
22839   tempargs = make_tree_vec (nargs);
22840
22841   if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
22842     return 0;
22843
22844   /* First make sure we didn't deduce anything that conflicts with
22845      explicitly specified args.  */
22846   for (i = nargs; i--; )
22847     {
22848       tree elt = TREE_VEC_ELT (tempargs, i);
22849       tree oldelt = TREE_VEC_ELT (orig_targs, i);
22850
22851       if (!elt)
22852         /*NOP*/;
22853       else if (uses_template_parms (elt))
22854         /* Since we're unifying against ourselves, we will fill in
22855            template args used in the function parm list with our own
22856            template parms.  Discard them.  */
22857         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
22858       else if (oldelt && ARGUMENT_PACK_P (oldelt))
22859         {
22860           /* Check that the argument at each index of the deduced argument pack
22861              is equivalent to the corresponding explicitly specified argument.
22862              We may have deduced more arguments than were explicitly specified,
22863              and that's OK.  */
22864
22865           /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
22866              that's wrong if we deduce the same argument pack from multiple
22867              function arguments: it's only incomplete the first time.  */
22868
22869           tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
22870           tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
22871
22872           if (TREE_VEC_LENGTH (deduced_pack)
22873               < TREE_VEC_LENGTH (explicit_pack))
22874             return 0;
22875
22876           for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
22877             if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
22878                                       TREE_VEC_ELT (deduced_pack, j)))
22879               return 0;
22880         }
22881       else if (oldelt && !template_args_equal (oldelt, elt))
22882         return 0;
22883     }
22884
22885   for (i = nargs; i--; )
22886     {
22887       tree elt = TREE_VEC_ELT (tempargs, i);
22888
22889       if (elt)
22890         TREE_VEC_ELT (targs, i) = elt;
22891     }
22892
22893   return 1;
22894 }
22895
22896 /* PARM is a template class (perhaps with unbound template
22897    parameters).  ARG is a fully instantiated type.  If ARG can be
22898    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
22899    TARGS are as for unify.  */
22900
22901 static tree
22902 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
22903                        bool explain_p)
22904 {
22905   tree copy_of_targs;
22906
22907   if (!CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
22908     return NULL_TREE;
22909   else if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
22910     /* Matches anything.  */;
22911   else if (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
22912            != most_general_template (CLASSTYPE_TI_TEMPLATE (parm)))
22913     return NULL_TREE;
22914
22915   /* We need to make a new template argument vector for the call to
22916      unify.  If we used TARGS, we'd clutter it up with the result of
22917      the attempted unification, even if this class didn't work out.
22918      We also don't want to commit ourselves to all the unifications
22919      we've already done, since unification is supposed to be done on
22920      an argument-by-argument basis.  In other words, consider the
22921      following pathological case:
22922
22923        template <int I, int J, int K>
22924        struct S {};
22925
22926        template <int I, int J>
22927        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
22928
22929        template <int I, int J, int K>
22930        void f(S<I, J, K>, S<I, I, I>);
22931
22932        void g() {
22933          S<0, 0, 0> s0;
22934          S<0, 1, 2> s2;
22935
22936          f(s0, s2);
22937        }
22938
22939      Now, by the time we consider the unification involving `s2', we
22940      already know that we must have `f<0, 0, 0>'.  But, even though
22941      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
22942      because there are two ways to unify base classes of S<0, 1, 2>
22943      with S<I, I, I>.  If we kept the already deduced knowledge, we
22944      would reject the possibility I=1.  */
22945   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
22946
22947   if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
22948     {
22949       if (unify_bound_ttp_args (tparms, copy_of_targs, parm, arg, explain_p))
22950         return NULL_TREE;
22951       return arg;
22952     }
22953
22954   /* If unification failed, we're done.  */
22955   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
22956              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
22957     return NULL_TREE;
22958
22959   return arg;
22960 }
22961
22962 /* Given a template type PARM and a class type ARG, find the unique
22963    base type in ARG that is an instance of PARM.  We do not examine
22964    ARG itself; only its base-classes.  If there is not exactly one
22965    appropriate base class, return NULL_TREE.  PARM may be the type of
22966    a partial specialization, as well as a plain template type.  Used
22967    by unify.  */
22968
22969 static enum template_base_result
22970 get_template_base (tree tparms, tree targs, tree parm, tree arg,
22971                    bool explain_p, tree *result)
22972 {
22973   tree rval = NULL_TREE;
22974   tree binfo;
22975
22976   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
22977
22978   binfo = TYPE_BINFO (complete_type (arg));
22979   if (!binfo)
22980     {
22981       /* The type could not be completed.  */
22982       *result = NULL_TREE;
22983       return tbr_incomplete_type;
22984     }
22985
22986   /* Walk in inheritance graph order.  The search order is not
22987      important, and this avoids multiple walks of virtual bases.  */
22988   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
22989     {
22990       tree r = try_class_unification (tparms, targs, parm,
22991                                       BINFO_TYPE (binfo), explain_p);
22992
22993       if (r)
22994         {
22995           /* If there is more than one satisfactory baseclass, then:
22996
22997                [temp.deduct.call]
22998
22999               If they yield more than one possible deduced A, the type
23000               deduction fails.
23001
23002              applies.  */
23003           if (rval && !same_type_p (r, rval))
23004             {
23005               /* [temp.deduct.call]/4.3: If there is a class C that is a
23006                  (direct or indirect) base class of D and derived (directly or
23007                  indirectly) from a class B and that would be a valid deduced
23008                  A, the deduced A cannot be B or pointer to B, respectively. */
23009               if (DERIVED_FROM_P (r, rval))
23010                 /* Ignore r.  */
23011                 continue;
23012               else if (DERIVED_FROM_P (rval, r))
23013                 /* Ignore rval.  */;
23014               else
23015                 {
23016                   *result = NULL_TREE;
23017                   return tbr_ambiguous_baseclass;
23018                 }
23019             }
23020
23021           rval = r;
23022         }
23023     }
23024
23025   *result = rval;
23026   return tbr_success;
23027 }
23028
23029 /* Returns the level of DECL, which declares a template parameter.  */
23030
23031 static int
23032 template_decl_level (tree decl)
23033 {
23034   switch (TREE_CODE (decl))
23035     {
23036     case TYPE_DECL:
23037     case TEMPLATE_DECL:
23038       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
23039
23040     case PARM_DECL:
23041       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
23042
23043     default:
23044       gcc_unreachable ();
23045     }
23046   return 0;
23047 }
23048
23049 /* Decide whether ARG can be unified with PARM, considering only the
23050    cv-qualifiers of each type, given STRICT as documented for unify.
23051    Returns nonzero iff the unification is OK on that basis.  */
23052
23053 static int
23054 check_cv_quals_for_unify (int strict, tree arg, tree parm)
23055 {
23056   int arg_quals = cp_type_quals (arg);
23057   int parm_quals = cp_type_quals (parm);
23058
23059   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
23060       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
23061     {
23062       /*  Although a CVR qualifier is ignored when being applied to a
23063           substituted template parameter ([8.3.2]/1 for example), that
23064           does not allow us to unify "const T" with "int&" because both
23065           types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
23066           It is ok when we're allowing additional CV qualifiers
23067           at the outer level [14.8.2.1]/3,1st bullet.  */
23068       if ((TYPE_REF_P (arg)
23069            || FUNC_OR_METHOD_TYPE_P (arg))
23070           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
23071         return 0;
23072
23073       if ((!INDIRECT_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
23074           && (parm_quals & TYPE_QUAL_RESTRICT))
23075         return 0;
23076     }
23077
23078   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
23079       && (arg_quals & parm_quals) != parm_quals)
23080     return 0;
23081
23082   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
23083       && (parm_quals & arg_quals) != arg_quals)
23084     return 0;
23085
23086   return 1;
23087 }
23088
23089 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
23090 void
23091 template_parm_level_and_index (tree parm, int* level, int* index)
23092 {
23093   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
23094       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
23095       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23096     {
23097       *index = TEMPLATE_TYPE_IDX (parm);
23098       *level = TEMPLATE_TYPE_LEVEL (parm);
23099     }
23100   else
23101     {
23102       *index = TEMPLATE_PARM_IDX (parm);
23103       *level = TEMPLATE_PARM_LEVEL (parm);
23104     }
23105 }
23106
23107 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)                    \
23108   do {                                                                  \
23109     if (unify (TP, TA, P, A, S, EP))                                    \
23110       return 1;                                                         \
23111   } while (0)
23112
23113 /* Unifies the remaining arguments in PACKED_ARGS with the pack
23114    expansion at the end of PACKED_PARMS. Returns 0 if the type
23115    deduction succeeds, 1 otherwise. STRICT is the same as in
23116    fn_type_unification. CALL_ARGS_P is true iff PACKED_ARGS is actually a
23117    function call argument list. We'll need to adjust the arguments to make them
23118    types. SUBR tells us if this is from a recursive call to
23119    type_unification_real, or for comparing two template argument
23120    lists. */
23121
23122 static int
23123 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
23124                       tree packed_args, unification_kind_t strict,
23125                       bool subr, bool explain_p)
23126 {
23127   tree parm
23128     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
23129   tree pattern = PACK_EXPANSION_PATTERN (parm);
23130   tree pack, packs = NULL_TREE;
23131   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
23132
23133   /* Add in any args remembered from an earlier partial instantiation.  */
23134   targs = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (parm), targs);
23135   int levels = TMPL_ARGS_DEPTH (targs);
23136
23137   packed_args = expand_template_argument_pack (packed_args);
23138
23139   int len = TREE_VEC_LENGTH (packed_args);
23140
23141   /* Determine the parameter packs we will be deducing from the
23142      pattern, and record their current deductions.  */
23143   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
23144        pack; pack = TREE_CHAIN (pack))
23145     {
23146       tree parm_pack = TREE_VALUE (pack);
23147       int idx, level;
23148
23149       /* Only template parameter packs can be deduced, not e.g. function
23150          parameter packs or __bases or __integer_pack.  */
23151       if (!TEMPLATE_PARM_P (parm_pack))
23152         continue;
23153
23154       /* Determine the index and level of this parameter pack.  */
23155       template_parm_level_and_index (parm_pack, &level, &idx);
23156       if (level < levels)
23157         continue;
23158
23159       /* Keep track of the parameter packs and their corresponding
23160          argument packs.  */
23161       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
23162       TREE_TYPE (packs) = make_tree_vec (len - start);
23163     }
23164
23165   /* Loop through all of the arguments that have not yet been
23166      unified and unify each with the pattern.  */
23167   for (i = start; i < len; i++)
23168     {
23169       tree parm;
23170       bool any_explicit = false;
23171       tree arg = TREE_VEC_ELT (packed_args, i);
23172
23173       /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
23174          or the element of its argument pack at the current index if
23175          this argument was explicitly specified.  */
23176       for (pack = packs; pack; pack = TREE_CHAIN (pack))
23177         {
23178           int idx, level;
23179           tree arg, pargs;
23180           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
23181
23182           arg = NULL_TREE;
23183           if (TREE_VALUE (pack)
23184               && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
23185               && (i - start < TREE_VEC_LENGTH (pargs)))
23186             {
23187               any_explicit = true;
23188               arg = TREE_VEC_ELT (pargs, i - start);
23189             }
23190           TMPL_ARG (targs, level, idx) = arg;
23191         }
23192
23193       /* If we had explicit template arguments, substitute them into the
23194          pattern before deduction.  */
23195       if (any_explicit)
23196         {
23197           /* Some arguments might still be unspecified or dependent.  */
23198           bool dependent;
23199           ++processing_template_decl;
23200           dependent = any_dependent_template_arguments_p (targs);
23201           if (!dependent)
23202             --processing_template_decl;
23203           parm = tsubst (pattern, targs,
23204                          explain_p ? tf_warning_or_error : tf_none,
23205                          NULL_TREE);
23206           if (dependent)
23207             --processing_template_decl;
23208           if (parm == error_mark_node)
23209             return 1;
23210         }
23211       else
23212         parm = pattern;
23213
23214       /* Unify the pattern with the current argument.  */
23215       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
23216                               explain_p))
23217         return 1;
23218
23219       /* For each parameter pack, collect the deduced value.  */
23220       for (pack = packs; pack; pack = TREE_CHAIN (pack))
23221         {
23222           int idx, level;
23223           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
23224
23225           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
23226             TMPL_ARG (targs, level, idx);
23227         }
23228     }
23229
23230   /* Verify that the results of unification with the parameter packs
23231      produce results consistent with what we've seen before, and make
23232      the deduced argument packs available.  */
23233   for (pack = packs; pack; pack = TREE_CHAIN (pack))
23234     {
23235       tree old_pack = TREE_VALUE (pack);
23236       tree new_args = TREE_TYPE (pack);
23237       int i, len = TREE_VEC_LENGTH (new_args);
23238       int idx, level;
23239       bool nondeduced_p = false;
23240
23241       /* By default keep the original deduced argument pack.
23242          If necessary, more specific code is going to update the
23243          resulting deduced argument later down in this function.  */
23244       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
23245       TMPL_ARG (targs, level, idx) = old_pack;
23246
23247       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
23248          actually deduce anything.  */
23249       for (i = 0; i < len && !nondeduced_p; ++i)
23250         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
23251           nondeduced_p = true;
23252       if (nondeduced_p)
23253         continue;
23254
23255       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
23256         {
23257           /* If we had fewer function args than explicit template args,
23258              just use the explicits.  */
23259           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
23260           int explicit_len = TREE_VEC_LENGTH (explicit_args);
23261           if (len < explicit_len)
23262             new_args = explicit_args;
23263         }
23264
23265       if (!old_pack)
23266         {
23267           tree result;
23268           /* Build the deduced *_ARGUMENT_PACK.  */
23269           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
23270             {
23271               result = make_node (NONTYPE_ARGUMENT_PACK);
23272               TREE_CONSTANT (result) = 1;
23273             }
23274           else
23275             result = cxx_make_type (TYPE_ARGUMENT_PACK);
23276
23277           SET_ARGUMENT_PACK_ARGS (result, new_args);
23278
23279           /* Note the deduced argument packs for this parameter
23280              pack.  */
23281           TMPL_ARG (targs, level, idx) = result;
23282         }
23283       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
23284                && (ARGUMENT_PACK_ARGS (old_pack) 
23285                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
23286         {
23287           /* We only had the explicitly-provided arguments before, but
23288              now we have a complete set of arguments.  */
23289           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
23290
23291           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
23292           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
23293           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
23294         }
23295       else
23296         {
23297           tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
23298           tree old_args = ARGUMENT_PACK_ARGS (old_pack);
23299           temp_override<int> ovl (TREE_VEC_LENGTH (old_args));
23300           /* During template argument deduction for the aggregate deduction
23301              candidate, the number of elements in a trailing parameter pack
23302              is only deduced from the number of remaining function
23303              arguments if it is not otherwise deduced.  */
23304           if (cxx_dialect >= cxx20
23305               && TREE_VEC_LENGTH (new_args) < TREE_VEC_LENGTH (old_args)
23306               && builtin_guide_p (TPARMS_PRIMARY_TEMPLATE (tparms)))
23307             TREE_VEC_LENGTH (old_args) = TREE_VEC_LENGTH (new_args);
23308           if (!comp_template_args (old_args, new_args,
23309                                    &bad_old_arg, &bad_new_arg))
23310             /* Inconsistent unification of this parameter pack.  */
23311             return unify_parameter_pack_inconsistent (explain_p,
23312                                                       bad_old_arg,
23313                                                       bad_new_arg);
23314         }
23315     }
23316
23317   return unify_success (explain_p);
23318 }
23319
23320 /* Handle unification of the domain of an array.  PARM_DOM and ARG_DOM are
23321    INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs.  The other
23322    parameters and return value are as for unify.  */
23323
23324 static int
23325 unify_array_domain (tree tparms, tree targs,
23326                     tree parm_dom, tree arg_dom,
23327                     bool explain_p)
23328 {
23329   tree parm_max;
23330   tree arg_max;
23331   bool parm_cst;
23332   bool arg_cst;
23333
23334   /* Our representation of array types uses "N - 1" as the
23335      TYPE_MAX_VALUE for an array with "N" elements, if "N" is
23336      not an integer constant.  We cannot unify arbitrarily
23337      complex expressions, so we eliminate the MINUS_EXPRs
23338      here.  */
23339   parm_max = TYPE_MAX_VALUE (parm_dom);
23340   parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
23341   if (!parm_cst)
23342     {
23343       gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
23344       parm_max = TREE_OPERAND (parm_max, 0);
23345     }
23346   arg_max = TYPE_MAX_VALUE (arg_dom);
23347   arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
23348   if (!arg_cst)
23349     {
23350       /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
23351          trying to unify the type of a variable with the type
23352          of a template parameter.  For example:
23353
23354            template <unsigned int N>
23355            void f (char (&) [N]);
23356            int g();
23357            void h(int i) {
23358              char a[g(i)];
23359              f(a);
23360            }
23361
23362          Here, the type of the ARG will be "int [g(i)]", and
23363          may be a SAVE_EXPR, etc.  */
23364       if (TREE_CODE (arg_max) != MINUS_EXPR)
23365         return unify_vla_arg (explain_p, arg_dom);
23366       arg_max = TREE_OPERAND (arg_max, 0);
23367     }
23368
23369   /* If only one of the bounds used a MINUS_EXPR, compensate
23370      by adding one to the other bound.  */
23371   if (parm_cst && !arg_cst)
23372     parm_max = fold_build2_loc (input_location, PLUS_EXPR,
23373                                 integer_type_node,
23374                                 parm_max,
23375                                 integer_one_node);
23376   else if (arg_cst && !parm_cst)
23377     arg_max = fold_build2_loc (input_location, PLUS_EXPR,
23378                                integer_type_node,
23379                                arg_max,
23380                                integer_one_node);
23381
23382   return unify (tparms, targs, parm_max, arg_max,
23383                 UNIFY_ALLOW_INTEGER, explain_p);
23384 }
23385
23386 /* Returns whether T, a P or A in unify, is a type, template or expression.  */
23387
23388 enum pa_kind_t { pa_type, pa_tmpl, pa_expr };
23389
23390 static pa_kind_t
23391 pa_kind (tree t)
23392 {
23393   if (PACK_EXPANSION_P (t))
23394     t = PACK_EXPANSION_PATTERN (t);
23395   if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
23396       || TREE_CODE (t) == UNBOUND_CLASS_TEMPLATE
23397       || DECL_TYPE_TEMPLATE_P (t))
23398     return pa_tmpl;
23399   else if (TYPE_P (t))
23400     return pa_type;
23401   else
23402     return pa_expr;
23403 }
23404
23405 /* Deduce the value of template parameters.  TPARMS is the (innermost)
23406    set of template parameters to a template.  TARGS is the bindings
23407    for those template parameters, as determined thus far; TARGS may
23408    include template arguments for outer levels of template parameters
23409    as well.  PARM is a parameter to a template function, or a
23410    subcomponent of that parameter; ARG is the corresponding argument.
23411    This function attempts to match PARM with ARG in a manner
23412    consistent with the existing assignments in TARGS.  If more values
23413    are deduced, then TARGS is updated.
23414
23415    Returns 0 if the type deduction succeeds, 1 otherwise.  The
23416    parameter STRICT is a bitwise or of the following flags:
23417
23418      UNIFY_ALLOW_NONE:
23419        Require an exact match between PARM and ARG.
23420      UNIFY_ALLOW_MORE_CV_QUAL:
23421        Allow the deduced ARG to be more cv-qualified (by qualification
23422        conversion) than ARG.
23423      UNIFY_ALLOW_LESS_CV_QUAL:
23424        Allow the deduced ARG to be less cv-qualified than ARG.
23425      UNIFY_ALLOW_DERIVED:
23426        Allow the deduced ARG to be a template base class of ARG,
23427        or a pointer to a template base class of the type pointed to by
23428        ARG.
23429      UNIFY_ALLOW_INTEGER:
23430        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
23431        case for more information.
23432      UNIFY_ALLOW_OUTER_LEVEL:
23433        This is the outermost level of a deduction. Used to determine validity
23434        of qualification conversions. A valid qualification conversion must
23435        have const qualified pointers leading up to the inner type which
23436        requires additional CV quals, except at the outer level, where const
23437        is not required [conv.qual]. It would be normal to set this flag in
23438        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
23439      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
23440        This is the outermost level of a deduction, and PARM can be more CV
23441        qualified at this point.
23442      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
23443        This is the outermost level of a deduction, and PARM can be less CV
23444        qualified at this point.  */
23445
23446 static int
23447 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
23448        bool explain_p)
23449 {
23450   int idx;
23451   tree targ;
23452   tree tparm;
23453   int strict_in = strict;
23454   tsubst_flags_t complain = (explain_p
23455                              ? tf_warning_or_error
23456                              : tf_none);
23457
23458   /* I don't think this will do the right thing with respect to types.
23459      But the only case I've seen it in so far has been array bounds, where
23460      signedness is the only information lost, and I think that will be
23461      okay.  VIEW_CONVERT_EXPR can appear with class NTTP, thanks to
23462      finish_id_expression_1, and are also OK.  */
23463   while (CONVERT_EXPR_P (parm) || TREE_CODE (parm) == VIEW_CONVERT_EXPR)
23464     parm = TREE_OPERAND (parm, 0);
23465
23466   if (arg == error_mark_node)
23467     return unify_invalid (explain_p);
23468   if (arg == unknown_type_node
23469       || arg == init_list_type_node)
23470     /* We can't deduce anything from this, but we might get all the
23471        template args from other function args.  */
23472     return unify_success (explain_p);
23473
23474   if (parm == any_targ_node || arg == any_targ_node)
23475     return unify_success (explain_p);
23476
23477   /* If PARM uses template parameters, then we can't bail out here,
23478      even if ARG == PARM, since we won't record unifications for the
23479      template parameters.  We might need them if we're trying to
23480      figure out which of two things is more specialized.  */
23481   if (arg == parm && !uses_template_parms (parm))
23482     return unify_success (explain_p);
23483
23484   /* Handle init lists early, so the rest of the function can assume
23485      we're dealing with a type. */
23486   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
23487     {
23488       tree elt, elttype;
23489       unsigned i;
23490       tree orig_parm = parm;
23491
23492       if (!is_std_init_list (parm)
23493           && TREE_CODE (parm) != ARRAY_TYPE)
23494         /* We can only deduce from an initializer list argument if the
23495            parameter is std::initializer_list or an array; otherwise this
23496            is a non-deduced context. */
23497         return unify_success (explain_p);
23498
23499       if (TREE_CODE (parm) == ARRAY_TYPE)
23500         elttype = TREE_TYPE (parm);
23501       else
23502         {
23503           elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
23504           /* Deduction is defined in terms of a single type, so just punt
23505              on the (bizarre) std::initializer_list<T...>.  */
23506           if (PACK_EXPANSION_P (elttype))
23507             return unify_success (explain_p);
23508         }
23509
23510       if (strict != DEDUCE_EXACT
23511           && TYPE_P (elttype)
23512           && !uses_deducible_template_parms (elttype))
23513         /* If ELTTYPE has no deducible template parms, skip deduction from
23514            the list elements.  */;
23515       else
23516         FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
23517           {
23518             int elt_strict = strict;
23519
23520             if (elt == error_mark_node)
23521               return unify_invalid (explain_p);
23522
23523             if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
23524               {
23525                 tree type = TREE_TYPE (elt);
23526                 if (type == error_mark_node)
23527                   return unify_invalid (explain_p);
23528                 /* It should only be possible to get here for a call.  */
23529                 gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
23530                 elt_strict |= maybe_adjust_types_for_deduction
23531                   (DEDUCE_CALL, &elttype, &type, elt);
23532                 elt = type;
23533               }
23534
23535           RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
23536                                    explain_p);
23537         }
23538
23539       if (TREE_CODE (parm) == ARRAY_TYPE
23540           && deducible_array_bound (TYPE_DOMAIN (parm)))
23541         {
23542           /* Also deduce from the length of the initializer list.  */
23543           tree max = size_int (CONSTRUCTOR_NELTS (arg));
23544           tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
23545           if (idx == error_mark_node)
23546             return unify_invalid (explain_p);
23547           return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
23548                                      idx, explain_p);
23549         }
23550
23551       /* If the std::initializer_list<T> deduction worked, replace the
23552          deduced A with std::initializer_list<A>.  */
23553       if (orig_parm != parm)
23554         {
23555           idx = TEMPLATE_TYPE_IDX (orig_parm);
23556           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
23557           targ = listify (targ);
23558           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
23559         }
23560       return unify_success (explain_p);
23561     }
23562
23563   /* If parm and arg aren't the same kind of thing (template, type, or
23564      expression), fail early.  */
23565   if (pa_kind (parm) != pa_kind (arg))
23566     return unify_invalid (explain_p);
23567
23568   /* Immediately reject some pairs that won't unify because of
23569      cv-qualification mismatches.  */
23570   if (TREE_CODE (arg) == TREE_CODE (parm)
23571       && TYPE_P (arg)
23572       /* It is the elements of the array which hold the cv quals of an array
23573          type, and the elements might be template type parms. We'll check
23574          when we recurse.  */
23575       && TREE_CODE (arg) != ARRAY_TYPE
23576       /* We check the cv-qualifiers when unifying with template type
23577          parameters below.  We want to allow ARG `const T' to unify with
23578          PARM `T' for example, when computing which of two templates
23579          is more specialized, for example.  */
23580       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
23581       && !check_cv_quals_for_unify (strict_in, arg, parm))
23582     return unify_cv_qual_mismatch (explain_p, parm, arg);
23583
23584   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
23585       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
23586     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
23587   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
23588   strict &= ~UNIFY_ALLOW_DERIVED;
23589   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
23590   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
23591
23592   switch (TREE_CODE (parm))
23593     {
23594     case TYPENAME_TYPE:
23595     case SCOPE_REF:
23596     case UNBOUND_CLASS_TEMPLATE:
23597       /* In a type which contains a nested-name-specifier, template
23598          argument values cannot be deduced for template parameters used
23599          within the nested-name-specifier.  */
23600       return unify_success (explain_p);
23601
23602     case TEMPLATE_TYPE_PARM:
23603     case TEMPLATE_TEMPLATE_PARM:
23604     case BOUND_TEMPLATE_TEMPLATE_PARM:
23605       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
23606       if (error_operand_p (tparm))
23607         return unify_invalid (explain_p);
23608
23609       if (TEMPLATE_TYPE_LEVEL (parm)
23610           != template_decl_level (tparm))
23611         /* The PARM is not one we're trying to unify.  Just check
23612            to see if it matches ARG.  */
23613         {
23614           if (TREE_CODE (arg) == TREE_CODE (parm)
23615               && (is_auto (parm) ? is_auto (arg)
23616                   : same_type_p (parm, arg)))
23617             return unify_success (explain_p);
23618           else
23619             return unify_type_mismatch (explain_p, parm, arg);
23620         }
23621       idx = TEMPLATE_TYPE_IDX (parm);
23622       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
23623       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
23624       if (error_operand_p (tparm))
23625         return unify_invalid (explain_p);
23626
23627       /* Check for mixed types and values.  */
23628       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
23629            && TREE_CODE (tparm) != TYPE_DECL)
23630           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
23631               && TREE_CODE (tparm) != TEMPLATE_DECL))
23632         gcc_unreachable ();
23633
23634       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23635         {
23636           if ((strict_in & UNIFY_ALLOW_DERIVED)
23637               && CLASS_TYPE_P (arg))
23638             {
23639               /* First try to match ARG directly.  */
23640               tree t = try_class_unification (tparms, targs, parm, arg,
23641                                               explain_p);
23642               if (!t)
23643                 {
23644                   /* Otherwise, look for a suitable base of ARG, as below.  */
23645                   enum template_base_result r;
23646                   r = get_template_base (tparms, targs, parm, arg,
23647                                          explain_p, &t);
23648                   if (!t)
23649                     return unify_no_common_base (explain_p, r, parm, arg);
23650                   arg = t;
23651                 }
23652             }
23653           /* ARG must be constructed from a template class or a template
23654              template parameter.  */
23655           else if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
23656                    && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
23657             return unify_template_deduction_failure (explain_p, parm, arg);
23658
23659           /* Deduce arguments T, i from TT<T> or TT<i>.  */
23660           if (unify_bound_ttp_args (tparms, targs, parm, arg, explain_p))
23661             return 1;
23662
23663           arg = TYPE_TI_TEMPLATE (arg);
23664
23665           /* Fall through to deduce template name.  */
23666         }
23667
23668       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
23669           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23670         {
23671           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
23672
23673           /* Simple cases: Value already set, does match or doesn't.  */
23674           if (targ != NULL_TREE && template_args_equal (targ, arg))
23675             return unify_success (explain_p);
23676           else if (targ)
23677             return unify_inconsistency (explain_p, parm, targ, arg);
23678         }
23679       else
23680         {
23681           /* If PARM is `const T' and ARG is only `int', we don't have
23682              a match unless we are allowing additional qualification.
23683              If ARG is `const int' and PARM is just `T' that's OK;
23684              that binds `const int' to `T'.  */
23685           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
23686                                          arg, parm))
23687             return unify_cv_qual_mismatch (explain_p, parm, arg);
23688
23689           /* Consider the case where ARG is `const volatile int' and
23690              PARM is `const T'.  Then, T should be `volatile int'.  */
23691           arg = cp_build_qualified_type_real
23692             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
23693           if (arg == error_mark_node)
23694             return unify_invalid (explain_p);
23695
23696           /* Simple cases: Value already set, does match or doesn't.  */
23697           if (targ != NULL_TREE && same_type_p (targ, arg))
23698             return unify_success (explain_p);
23699           else if (targ)
23700             return unify_inconsistency (explain_p, parm, targ, arg);
23701
23702           /* Make sure that ARG is not a variable-sized array.  (Note
23703              that were talking about variable-sized arrays (like
23704              `int[n]'), rather than arrays of unknown size (like
23705              `int[]').)  We'll get very confused by such a type since
23706              the bound of the array is not constant, and therefore
23707              not mangleable.  Besides, such types are not allowed in
23708              ISO C++, so we can do as we please here.  We do allow
23709              them for 'auto' deduction, since that isn't ABI-exposed.  */
23710           if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
23711             return unify_vla_arg (explain_p, arg);
23712
23713           /* Strip typedefs as in convert_template_argument.  */
23714           arg = canonicalize_type_argument (arg, tf_none);
23715         }
23716
23717       /* If ARG is a parameter pack or an expansion, we cannot unify
23718          against it unless PARM is also a parameter pack.  */
23719       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
23720           && !template_parameter_pack_p (parm))
23721         return unify_parameter_pack_mismatch (explain_p, parm, arg);
23722
23723       /* If the argument deduction results is a METHOD_TYPE,
23724          then there is a problem.
23725          METHOD_TYPE doesn't map to any real C++ type the result of
23726          the deduction cannot be of that type.  */
23727       if (TREE_CODE (arg) == METHOD_TYPE)
23728         return unify_method_type_error (explain_p, arg);
23729
23730       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
23731       return unify_success (explain_p);
23732
23733     case TEMPLATE_PARM_INDEX:
23734       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
23735       if (error_operand_p (tparm))
23736         return unify_invalid (explain_p);
23737
23738       if (TEMPLATE_PARM_LEVEL (parm)
23739           != template_decl_level (tparm))
23740         {
23741           /* The PARM is not one we're trying to unify.  Just check
23742              to see if it matches ARG.  */
23743           int result = !(TREE_CODE (arg) == TREE_CODE (parm)
23744                          && cp_tree_equal (parm, arg));
23745           if (result)
23746             unify_expression_unequal (explain_p, parm, arg);
23747           return result;
23748         }
23749
23750       idx = TEMPLATE_PARM_IDX (parm);
23751       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
23752
23753       if (targ)
23754         {
23755           if ((strict & UNIFY_ALLOW_INTEGER)
23756               && TREE_TYPE (targ) && TREE_TYPE (arg)
23757               && CP_INTEGRAL_TYPE_P (TREE_TYPE (targ)))
23758             /* We're deducing from an array bound, the type doesn't matter.  */
23759             arg = fold_convert (TREE_TYPE (targ), arg);
23760           int x = !cp_tree_equal (targ, arg);
23761           if (x)
23762             unify_inconsistency (explain_p, parm, targ, arg);
23763           return x;
23764         }
23765
23766       /* [temp.deduct.type] If, in the declaration of a function template
23767          with a non-type template-parameter, the non-type
23768          template-parameter is used in an expression in the function
23769          parameter-list and, if the corresponding template-argument is
23770          deduced, the template-argument type shall match the type of the
23771          template-parameter exactly, except that a template-argument
23772          deduced from an array bound may be of any integral type.
23773          The non-type parameter might use already deduced type parameters.  */
23774       tparm = TREE_TYPE (parm);
23775       if (TEMPLATE_PARM_LEVEL (parm) > TMPL_ARGS_DEPTH (targs))
23776         /* We don't have enough levels of args to do any substitution.  This
23777            can happen in the context of -fnew-ttp-matching.  */;
23778       else
23779         {
23780           ++processing_template_decl;
23781           tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
23782           --processing_template_decl;
23783
23784           if (tree a = type_uses_auto (tparm))
23785             {
23786               tparm = do_auto_deduction (tparm, arg, a,
23787                                          complain, adc_unify, targs);
23788               if (tparm == error_mark_node)
23789                 return 1;
23790             }
23791         }
23792
23793       if (!TREE_TYPE (arg))
23794         /* Template-parameter dependent expression.  Just accept it for now.
23795            It will later be processed in convert_template_argument.  */
23796         ;
23797       else if (same_type_ignoring_top_level_qualifiers_p
23798                (non_reference (TREE_TYPE (arg)),
23799                 non_reference (tparm)))
23800         /* OK.  Ignore top-level quals here because a class-type template
23801            parameter object is const.  */;
23802       else if ((strict & UNIFY_ALLOW_INTEGER)
23803                && CP_INTEGRAL_TYPE_P (tparm))
23804         /* Convert the ARG to the type of PARM; the deduced non-type
23805            template argument must exactly match the types of the
23806            corresponding parameter.  */
23807         arg = fold (build_nop (tparm, arg));
23808       else if (uses_template_parms (tparm))
23809         {
23810           /* We haven't deduced the type of this parameter yet.  */
23811           if (cxx_dialect >= cxx17
23812               /* We deduce from array bounds in try_array_deduction.  */
23813               && !(strict & UNIFY_ALLOW_INTEGER)
23814               && TEMPLATE_PARM_LEVEL (parm) <= TMPL_ARGS_DEPTH (targs))
23815             {
23816               /* Deduce it from the non-type argument.  */
23817               tree atype = TREE_TYPE (arg);
23818               RECUR_AND_CHECK_FAILURE (tparms, targs,
23819                                        tparm, atype,
23820                                        UNIFY_ALLOW_NONE, explain_p);
23821               /* Now check whether the type of this parameter is still
23822                  dependent, and give up if so.  */
23823               ++processing_template_decl;
23824               tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
23825               --processing_template_decl;
23826               if (uses_template_parms (tparm))
23827                 return unify_success (explain_p);
23828             }
23829           else
23830             /* Try again later.  */
23831             return unify_success (explain_p);
23832         }
23833       else
23834         return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
23835
23836       /* If ARG is a parameter pack or an expansion, we cannot unify
23837          against it unless PARM is also a parameter pack.  */
23838       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
23839           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
23840         return unify_parameter_pack_mismatch (explain_p, parm, arg);
23841
23842       {
23843         bool removed_attr = false;
23844         arg = strip_typedefs_expr (arg, &removed_attr);
23845       }
23846       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
23847       return unify_success (explain_p);
23848
23849     case PTRMEM_CST:
23850      {
23851         /* A pointer-to-member constant can be unified only with
23852          another constant.  */
23853       if (TREE_CODE (arg) != PTRMEM_CST)
23854         return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
23855
23856       /* Just unify the class member. It would be useless (and possibly
23857          wrong, depending on the strict flags) to unify also
23858          PTRMEM_CST_CLASS, because we want to be sure that both parm and
23859          arg refer to the same variable, even if through different
23860          classes. For instance:
23861
23862          struct A { int x; };
23863          struct B : A { };
23864
23865          Unification of &A::x and &B::x must succeed.  */
23866       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
23867                     PTRMEM_CST_MEMBER (arg), strict, explain_p);
23868      }
23869
23870     case POINTER_TYPE:
23871       {
23872         if (!TYPE_PTR_P (arg))
23873           return unify_type_mismatch (explain_p, parm, arg);
23874
23875         /* [temp.deduct.call]
23876
23877            A can be another pointer or pointer to member type that can
23878            be converted to the deduced A via a qualification
23879            conversion (_conv.qual_).
23880
23881            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
23882            This will allow for additional cv-qualification of the
23883            pointed-to types if appropriate.  */
23884
23885         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
23886           /* The derived-to-base conversion only persists through one
23887              level of pointers.  */
23888           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
23889
23890         return unify (tparms, targs, TREE_TYPE (parm),
23891                       TREE_TYPE (arg), strict, explain_p);
23892       }
23893
23894     case REFERENCE_TYPE:
23895       if (!TYPE_REF_P (arg))
23896         return unify_type_mismatch (explain_p, parm, arg);
23897       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
23898                     strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
23899
23900     case ARRAY_TYPE:
23901       if (TREE_CODE (arg) != ARRAY_TYPE)
23902         return unify_type_mismatch (explain_p, parm, arg);
23903       if ((TYPE_DOMAIN (parm) == NULL_TREE)
23904           != (TYPE_DOMAIN (arg) == NULL_TREE))
23905         return unify_type_mismatch (explain_p, parm, arg);
23906       RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
23907                                strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
23908       if (TYPE_DOMAIN (parm) != NULL_TREE)
23909         return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
23910                                    TYPE_DOMAIN (arg), explain_p);
23911       return unify_success (explain_p);
23912
23913     case REAL_TYPE:
23914     case COMPLEX_TYPE:
23915     case VECTOR_TYPE:
23916     case INTEGER_TYPE:
23917     case BOOLEAN_TYPE:
23918     case ENUMERAL_TYPE:
23919     case VOID_TYPE:
23920     case OPAQUE_TYPE:
23921     case NULLPTR_TYPE:
23922       if (TREE_CODE (arg) != TREE_CODE (parm))
23923         return unify_type_mismatch (explain_p, parm, arg);
23924
23925       /* We have already checked cv-qualification at the top of the
23926          function.  */
23927       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
23928         return unify_type_mismatch (explain_p, parm, arg);
23929
23930       /* As far as unification is concerned, this wins.  Later checks
23931          will invalidate it if necessary.  */
23932       return unify_success (explain_p);
23933
23934       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
23935       /* Type INTEGER_CST can come from ordinary constant template args.  */
23936     case INTEGER_CST:
23937       while (CONVERT_EXPR_P (arg))
23938         arg = TREE_OPERAND (arg, 0);
23939
23940       if (TREE_CODE (arg) != INTEGER_CST)
23941         return unify_template_argument_mismatch (explain_p, parm, arg);
23942       return (tree_int_cst_equal (parm, arg)
23943               ? unify_success (explain_p)
23944               : unify_template_argument_mismatch (explain_p, parm, arg));
23945
23946     case TREE_VEC:
23947       {
23948         int i, len, argslen;
23949         int parm_variadic_p = 0;
23950
23951         if (TREE_CODE (arg) != TREE_VEC)
23952           return unify_template_argument_mismatch (explain_p, parm, arg);
23953
23954         len = TREE_VEC_LENGTH (parm);
23955         argslen = TREE_VEC_LENGTH (arg);
23956
23957         /* Check for pack expansions in the parameters.  */
23958         for (i = 0; i < len; ++i)
23959           {
23960             if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
23961               {
23962                 if (i == len - 1)
23963                   /* We can unify against something with a trailing
23964                      parameter pack.  */
23965                   parm_variadic_p = 1;
23966                 else
23967                   /* [temp.deduct.type]/9: If the template argument list of
23968                      P contains a pack expansion that is not the last
23969                      template argument, the entire template argument list
23970                      is a non-deduced context.  */
23971                   return unify_success (explain_p);
23972               }
23973           }
23974
23975         /* If we don't have enough arguments to satisfy the parameters
23976            (not counting the pack expression at the end), or we have
23977            too many arguments for a parameter list that doesn't end in
23978            a pack expression, we can't unify.  */
23979         if (parm_variadic_p
23980             ? argslen < len - parm_variadic_p
23981             : argslen != len)
23982           return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
23983
23984         /* Unify all of the parameters that precede the (optional)
23985            pack expression.  */
23986         for (i = 0; i < len - parm_variadic_p; ++i)
23987           {
23988             RECUR_AND_CHECK_FAILURE (tparms, targs,
23989                                      TREE_VEC_ELT (parm, i),
23990                                      TREE_VEC_ELT (arg, i),
23991                                      UNIFY_ALLOW_NONE, explain_p);
23992           }
23993         if (parm_variadic_p)
23994           return unify_pack_expansion (tparms, targs, parm, arg,
23995                                        DEDUCE_EXACT,
23996                                        /*subr=*/true, explain_p);
23997         return unify_success (explain_p);
23998       }
23999
24000     case RECORD_TYPE:
24001     case UNION_TYPE:
24002       if (TREE_CODE (arg) != TREE_CODE (parm))
24003         return unify_type_mismatch (explain_p, parm, arg);
24004
24005       if (TYPE_PTRMEMFUNC_P (parm))
24006         {
24007           if (!TYPE_PTRMEMFUNC_P (arg))
24008             return unify_type_mismatch (explain_p, parm, arg);
24009
24010           return unify (tparms, targs,
24011                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
24012                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
24013                         strict, explain_p);
24014         }
24015       else if (TYPE_PTRMEMFUNC_P (arg))
24016         return unify_type_mismatch (explain_p, parm, arg);
24017
24018       if (CLASSTYPE_TEMPLATE_INFO (parm))
24019         {
24020           tree t = NULL_TREE;
24021
24022           if (strict_in & UNIFY_ALLOW_DERIVED)
24023             {
24024               /* First, we try to unify the PARM and ARG directly.  */
24025               t = try_class_unification (tparms, targs,
24026                                          parm, arg, explain_p);
24027
24028               if (!t)
24029                 {
24030                   /* Fallback to the special case allowed in
24031                      [temp.deduct.call]:
24032
24033                        If P is a class, and P has the form
24034                        template-id, then A can be a derived class of
24035                        the deduced A.  Likewise, if P is a pointer to
24036                        a class of the form template-id, A can be a
24037                        pointer to a derived class pointed to by the
24038                        deduced A.  */
24039                   enum template_base_result r;
24040                   r = get_template_base (tparms, targs, parm, arg,
24041                                          explain_p, &t);
24042
24043                   if (!t)
24044                     {
24045                       /* Don't give the derived diagnostic if we're
24046                          already dealing with the same template.  */
24047                       bool same_template
24048                         = (CLASSTYPE_TEMPLATE_INFO (arg)
24049                            && (CLASSTYPE_TI_TEMPLATE (parm)
24050                                == CLASSTYPE_TI_TEMPLATE (arg)));
24051                       return unify_no_common_base (explain_p && !same_template,
24052                                                    r, parm, arg);
24053                     }
24054                 }
24055             }
24056           else if (CLASSTYPE_TEMPLATE_INFO (arg)
24057                    && (CLASSTYPE_TI_TEMPLATE (parm)
24058                        == CLASSTYPE_TI_TEMPLATE (arg)))
24059             /* Perhaps PARM is something like S<U> and ARG is S<int>.
24060                Then, we should unify `int' and `U'.  */
24061             t = arg;
24062           else
24063             /* There's no chance of unification succeeding.  */
24064             return unify_type_mismatch (explain_p, parm, arg);
24065
24066           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
24067                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
24068         }
24069       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
24070         return unify_type_mismatch (explain_p, parm, arg);
24071       return unify_success (explain_p);
24072
24073     case METHOD_TYPE:
24074     case FUNCTION_TYPE:
24075       {
24076         unsigned int nargs;
24077         tree *args;
24078         tree a;
24079         unsigned int i;
24080
24081         if (TREE_CODE (arg) != TREE_CODE (parm))
24082           return unify_type_mismatch (explain_p, parm, arg);
24083
24084         /* CV qualifications for methods can never be deduced, they must
24085            match exactly.  We need to check them explicitly here,
24086            because type_unification_real treats them as any other
24087            cv-qualified parameter.  */
24088         if (TREE_CODE (parm) == METHOD_TYPE
24089             && (!check_cv_quals_for_unify
24090                 (UNIFY_ALLOW_NONE,
24091                  class_of_this_parm (arg),
24092                  class_of_this_parm (parm))))
24093           return unify_cv_qual_mismatch (explain_p, parm, arg);
24094         if (TREE_CODE (arg) == FUNCTION_TYPE
24095             && type_memfn_quals (parm) != type_memfn_quals (arg))
24096           return unify_cv_qual_mismatch (explain_p, parm, arg);
24097         if (type_memfn_rqual (parm) != type_memfn_rqual (arg))
24098           return unify_type_mismatch (explain_p, parm, arg);
24099
24100         RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
24101                                  TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
24102
24103         nargs = list_length (TYPE_ARG_TYPES (arg));
24104         args = XALLOCAVEC (tree, nargs);
24105         for (a = TYPE_ARG_TYPES (arg), i = 0;
24106              a != NULL_TREE && a != void_list_node;
24107              a = TREE_CHAIN (a), ++i)
24108           args[i] = TREE_VALUE (a);
24109         nargs = i;
24110
24111         if (type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
24112                                    args, nargs, 1, DEDUCE_EXACT,
24113                                    NULL, explain_p))
24114           return 1;
24115
24116         if (flag_noexcept_type)
24117           {
24118             tree pspec = TYPE_RAISES_EXCEPTIONS (parm);
24119             tree aspec = canonical_eh_spec (TYPE_RAISES_EXCEPTIONS (arg));
24120             if (pspec == NULL_TREE) pspec = noexcept_false_spec;
24121             if (aspec == NULL_TREE) aspec = noexcept_false_spec;
24122             if (TREE_PURPOSE (pspec) && TREE_PURPOSE (aspec)
24123                 && uses_template_parms (TREE_PURPOSE (pspec)))
24124               RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_PURPOSE (pspec),
24125                                        TREE_PURPOSE (aspec),
24126                                        UNIFY_ALLOW_NONE, explain_p);
24127             else if (nothrow_spec_p (pspec) && !nothrow_spec_p (aspec))
24128               return unify_type_mismatch (explain_p, parm, arg);
24129           }
24130
24131         return 0;
24132       }
24133
24134     case OFFSET_TYPE:
24135       /* Unify a pointer to member with a pointer to member function, which
24136          deduces the type of the member as a function type. */
24137       if (TYPE_PTRMEMFUNC_P (arg))
24138         {
24139           /* Check top-level cv qualifiers */
24140           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
24141             return unify_cv_qual_mismatch (explain_p, parm, arg);
24142
24143           RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
24144                                    TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
24145                                    UNIFY_ALLOW_NONE, explain_p);
24146
24147           /* Determine the type of the function we are unifying against. */
24148           tree fntype = static_fn_type (arg);
24149
24150           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
24151         }
24152
24153       if (TREE_CODE (arg) != OFFSET_TYPE)
24154         return unify_type_mismatch (explain_p, parm, arg);
24155       RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
24156                                TYPE_OFFSET_BASETYPE (arg),
24157                                UNIFY_ALLOW_NONE, explain_p);
24158       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24159                     strict, explain_p);
24160
24161     case CONST_DECL:
24162       if (DECL_TEMPLATE_PARM_P (parm))
24163         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
24164       if (arg != scalar_constant_value (parm))
24165         return unify_template_argument_mismatch (explain_p, parm, arg);
24166       return unify_success (explain_p);
24167
24168     case FIELD_DECL:
24169     case TEMPLATE_DECL:
24170       /* Matched cases are handled by the ARG == PARM test above.  */
24171       return unify_template_argument_mismatch (explain_p, parm, arg);
24172
24173     case VAR_DECL:
24174       /* We might get a variable as a non-type template argument in parm if the
24175          corresponding parameter is type-dependent.  Make any necessary
24176          adjustments based on whether arg is a reference.  */
24177       if (CONSTANT_CLASS_P (arg))
24178         parm = fold_non_dependent_expr (parm, complain);
24179       else if (REFERENCE_REF_P (arg))
24180         {
24181           tree sub = TREE_OPERAND (arg, 0);
24182           STRIP_NOPS (sub);
24183           if (TREE_CODE (sub) == ADDR_EXPR)
24184             arg = TREE_OPERAND (sub, 0);
24185         }
24186       /* Now use the normal expression code to check whether they match.  */
24187       goto expr;
24188
24189     case TYPE_ARGUMENT_PACK:
24190     case NONTYPE_ARGUMENT_PACK:
24191       return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
24192                     ARGUMENT_PACK_ARGS (arg), strict, explain_p);
24193
24194     case TYPEOF_TYPE:
24195     case DECLTYPE_TYPE:
24196     case UNDERLYING_TYPE:
24197       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
24198          or UNDERLYING_TYPE nodes.  */
24199       return unify_success (explain_p);
24200
24201     case ERROR_MARK:
24202       /* Unification fails if we hit an error node.  */
24203       return unify_invalid (explain_p);
24204
24205     case INDIRECT_REF:
24206       if (REFERENCE_REF_P (parm))
24207         {
24208           bool pexp = PACK_EXPANSION_P (arg);
24209           if (pexp)
24210             arg = PACK_EXPANSION_PATTERN (arg);
24211           if (REFERENCE_REF_P (arg))
24212             arg = TREE_OPERAND (arg, 0);
24213           if (pexp)
24214             arg = make_pack_expansion (arg, complain);
24215           return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
24216                         strict, explain_p);
24217         }
24218       /* FALLTHRU */
24219
24220     default:
24221       /* An unresolved overload is a nondeduced context.  */
24222       if (is_overloaded_fn (parm) || type_unknown_p (parm))
24223         return unify_success (explain_p);
24224       gcc_assert (EXPR_P (parm)
24225                   || COMPOUND_LITERAL_P (parm)
24226                   || TREE_CODE (parm) == TRAIT_EXPR);
24227     expr:
24228       /* We must be looking at an expression.  This can happen with
24229          something like:
24230
24231            template <int I>
24232            void foo(S<I>, S<I + 2>);
24233
24234          or
24235
24236            template<typename T>
24237            void foo(A<T, T{}>);
24238
24239          This is a "non-deduced context":
24240
24241            [deduct.type]
24242
24243            The non-deduced contexts are:
24244
24245            --A non-type template argument or an array bound in which
24246              a subexpression references a template parameter.
24247
24248          In these cases, we assume deduction succeeded, but don't
24249          actually infer any unifications.  */
24250
24251       if (!uses_template_parms (parm)
24252           && !template_args_equal (parm, arg))
24253         return unify_expression_unequal (explain_p, parm, arg);
24254       else
24255         return unify_success (explain_p);
24256     }
24257 }
24258 #undef RECUR_AND_CHECK_FAILURE
24259 \f
24260 /* Note that DECL can be defined in this translation unit, if
24261    required.  */
24262
24263 static void
24264 mark_definable (tree decl)
24265 {
24266   tree clone;
24267   DECL_NOT_REALLY_EXTERN (decl) = 1;
24268   FOR_EACH_CLONE (clone, decl)
24269     DECL_NOT_REALLY_EXTERN (clone) = 1;
24270 }
24271
24272 /* Called if RESULT is explicitly instantiated, or is a member of an
24273    explicitly instantiated class.  */
24274
24275 void
24276 mark_decl_instantiated (tree result, int extern_p)
24277 {
24278   SET_DECL_EXPLICIT_INSTANTIATION (result);
24279
24280   /* If this entity has already been written out, it's too late to
24281      make any modifications.  */
24282   if (TREE_ASM_WRITTEN (result))
24283     return;
24284
24285   /* consteval functions are never emitted.  */
24286   if (TREE_CODE (result) == FUNCTION_DECL
24287       && DECL_IMMEDIATE_FUNCTION_P (result))
24288     return;
24289
24290   /* For anonymous namespace we don't need to do anything.  */
24291   if (decl_anon_ns_mem_p (result))
24292     {
24293       gcc_assert (!TREE_PUBLIC (result));
24294       return;
24295     }
24296
24297   if (TREE_CODE (result) != FUNCTION_DECL)
24298     /* The TREE_PUBLIC flag for function declarations will have been
24299        set correctly by tsubst.  */
24300     TREE_PUBLIC (result) = 1;
24301
24302   /* This might have been set by an earlier implicit instantiation.  */
24303   DECL_COMDAT (result) = 0;
24304
24305   if (extern_p)
24306     {
24307       DECL_EXTERNAL (result) = 1;
24308       DECL_NOT_REALLY_EXTERN (result) = 0;
24309     }
24310   else
24311     {
24312       mark_definable (result);
24313       mark_needed (result);
24314       /* Always make artificials weak.  */
24315       if (DECL_ARTIFICIAL (result) && flag_weak)
24316         comdat_linkage (result);
24317       /* For WIN32 we also want to put explicit instantiations in
24318          linkonce sections.  */
24319       else if (TREE_PUBLIC (result))
24320         maybe_make_one_only (result);
24321       if (TREE_CODE (result) == FUNCTION_DECL
24322           && DECL_TEMPLATE_INSTANTIATED (result))
24323         /* If the function has already been instantiated, clear DECL_EXTERNAL,
24324            since start_preparsed_function wouldn't have if we had an earlier
24325            extern explicit instantiation.  */
24326         DECL_EXTERNAL (result) = 0;
24327     }
24328
24329   /* If EXTERN_P, then this function will not be emitted -- unless
24330      followed by an explicit instantiation, at which point its linkage
24331      will be adjusted.  If !EXTERN_P, then this function will be
24332      emitted here.  In neither circumstance do we want
24333      import_export_decl to adjust the linkage.  */
24334   DECL_INTERFACE_KNOWN (result) = 1;
24335 }
24336
24337 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
24338    important template arguments.  If any are missing, we check whether
24339    they're important by using error_mark_node for substituting into any
24340    args that were used for partial ordering (the ones between ARGS and END)
24341    and seeing if it bubbles up.  */
24342
24343 static bool
24344 check_undeduced_parms (tree targs, tree args, tree end)
24345 {
24346   bool found = false;
24347   int i;
24348   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
24349     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
24350       {
24351         found = true;
24352         TREE_VEC_ELT (targs, i) = error_mark_node;
24353       }
24354   if (found)
24355     {
24356       tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
24357       if (substed == error_mark_node)
24358         return true;
24359     }
24360   return false;
24361 }
24362
24363 /* Given two function templates PAT1 and PAT2, return:
24364
24365    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
24366    -1 if PAT2 is more specialized than PAT1.
24367    0 if neither is more specialized.
24368
24369    LEN indicates the number of parameters we should consider
24370    (defaulted parameters should not be considered).
24371
24372    The 1998 std underspecified function template partial ordering, and
24373    DR214 addresses the issue.  We take pairs of arguments, one from
24374    each of the templates, and deduce them against each other.  One of
24375    the templates will be more specialized if all the *other*
24376    template's arguments deduce against its arguments and at least one
24377    of its arguments *does* *not* deduce against the other template's
24378    corresponding argument.  Deduction is done as for class templates.
24379    The arguments used in deduction have reference and top level cv
24380    qualifiers removed.  Iff both arguments were originally reference
24381    types *and* deduction succeeds in both directions, an lvalue reference
24382    wins against an rvalue reference and otherwise the template
24383    with the more cv-qualified argument wins for that pairing (if
24384    neither is more cv-qualified, they both are equal).  Unlike regular
24385    deduction, after all the arguments have been deduced in this way,
24386    we do *not* verify the deduced template argument values can be
24387    substituted into non-deduced contexts.
24388
24389    The logic can be a bit confusing here, because we look at deduce1 and
24390    targs1 to see if pat2 is at least as specialized, and vice versa; if we
24391    can find template arguments for pat1 to make arg1 look like arg2, that
24392    means that arg2 is at least as specialized as arg1.  */
24393
24394 int
24395 more_specialized_fn (tree pat1, tree pat2, int len)
24396 {
24397   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
24398   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
24399   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
24400   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
24401   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
24402   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
24403   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
24404   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
24405   tree origs1, origs2;
24406   bool lose1 = false;
24407   bool lose2 = false;
24408
24409   /* Remove the this parameter from non-static member functions.  If
24410      one is a non-static member function and the other is not a static
24411      member function, remove the first parameter from that function
24412      also.  This situation occurs for operator functions where we
24413      locate both a member function (with this pointer) and non-member
24414      operator (with explicit first operand).  */
24415   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
24416     {
24417       len--; /* LEN is the number of significant arguments for DECL1 */
24418       args1 = TREE_CHAIN (args1);
24419       if (!DECL_STATIC_FUNCTION_P (decl2))
24420         args2 = TREE_CHAIN (args2);
24421     }
24422   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
24423     {
24424       args2 = TREE_CHAIN (args2);
24425       if (!DECL_STATIC_FUNCTION_P (decl1))
24426         {
24427           len--;
24428           args1 = TREE_CHAIN (args1);
24429         }
24430     }
24431
24432   /* If only one is a conversion operator, they are unordered.  */
24433   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
24434     return 0;
24435
24436   /* Consider the return type for a conversion function */
24437   if (DECL_CONV_FN_P (decl1))
24438     {
24439       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
24440       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
24441       len++;
24442     }
24443
24444   processing_template_decl++;
24445
24446   origs1 = args1;
24447   origs2 = args2;
24448
24449   while (len--
24450          /* Stop when an ellipsis is seen.  */
24451          && args1 != NULL_TREE && args2 != NULL_TREE)
24452     {
24453       tree arg1 = TREE_VALUE (args1);
24454       tree arg2 = TREE_VALUE (args2);
24455       int deduce1, deduce2;
24456       int quals1 = -1;
24457       int quals2 = -1;
24458       int ref1 = 0;
24459       int ref2 = 0;
24460
24461       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
24462           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
24463         {
24464           /* When both arguments are pack expansions, we need only
24465              unify the patterns themselves.  */
24466           arg1 = PACK_EXPANSION_PATTERN (arg1);
24467           arg2 = PACK_EXPANSION_PATTERN (arg2);
24468
24469           /* This is the last comparison we need to do.  */
24470           len = 0;
24471         }
24472
24473       if (TYPE_REF_P (arg1))
24474         {
24475           ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
24476           arg1 = TREE_TYPE (arg1);
24477           quals1 = cp_type_quals (arg1);
24478         }
24479
24480       if (TYPE_REF_P (arg2))
24481         {
24482           ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
24483           arg2 = TREE_TYPE (arg2);
24484           quals2 = cp_type_quals (arg2);
24485         }
24486
24487       arg1 = TYPE_MAIN_VARIANT (arg1);
24488       arg2 = TYPE_MAIN_VARIANT (arg2);
24489
24490       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
24491         {
24492           int i, len2 = remaining_arguments (args2);
24493           tree parmvec = make_tree_vec (1);
24494           tree argvec = make_tree_vec (len2);
24495           tree ta = args2;
24496
24497           /* Setup the parameter vector, which contains only ARG1.  */
24498           TREE_VEC_ELT (parmvec, 0) = arg1;
24499
24500           /* Setup the argument vector, which contains the remaining
24501              arguments.  */
24502           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
24503             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
24504
24505           deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
24506                                            argvec, DEDUCE_EXACT,
24507                                            /*subr=*/true, /*explain_p=*/false)
24508                      == 0);
24509
24510           /* We cannot deduce in the other direction, because ARG1 is
24511              a pack expansion but ARG2 is not.  */
24512           deduce2 = 0;
24513         }
24514       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
24515         {
24516           int i, len1 = remaining_arguments (args1);
24517           tree parmvec = make_tree_vec (1);
24518           tree argvec = make_tree_vec (len1);
24519           tree ta = args1;
24520
24521           /* Setup the parameter vector, which contains only ARG1.  */
24522           TREE_VEC_ELT (parmvec, 0) = arg2;
24523
24524           /* Setup the argument vector, which contains the remaining
24525              arguments.  */
24526           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
24527             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
24528
24529           deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
24530                                            argvec, DEDUCE_EXACT,
24531                                            /*subr=*/true, /*explain_p=*/false)
24532                      == 0);
24533
24534           /* We cannot deduce in the other direction, because ARG2 is
24535              a pack expansion but ARG1 is not.*/
24536           deduce1 = 0;
24537         }
24538
24539       else
24540         {
24541           /* The normal case, where neither argument is a pack
24542              expansion.  */
24543           deduce1 = (unify (tparms1, targs1, arg1, arg2,
24544                             UNIFY_ALLOW_NONE, /*explain_p=*/false)
24545                      == 0);
24546           deduce2 = (unify (tparms2, targs2, arg2, arg1,
24547                             UNIFY_ALLOW_NONE, /*explain_p=*/false)
24548                      == 0);
24549         }
24550
24551       /* If we couldn't deduce arguments for tparms1 to make arg1 match
24552          arg2, then arg2 is not as specialized as arg1.  */
24553       if (!deduce1)
24554         lose2 = true;
24555       if (!deduce2)
24556         lose1 = true;
24557
24558       /* "If, for a given type, deduction succeeds in both directions
24559          (i.e., the types are identical after the transformations above)
24560          and both P and A were reference types (before being replaced with
24561          the type referred to above):
24562          - if the type from the argument template was an lvalue reference and
24563          the type from the parameter template was not, the argument type is
24564          considered to be more specialized than the other; otherwise,
24565          - if the type from the argument template is more cv-qualified
24566          than the type from the parameter template (as described above),
24567          the argument type is considered to be more specialized than the other;
24568          otherwise,
24569          - neither type is more specialized than the other."  */
24570
24571       if (deduce1 && deduce2)
24572         {
24573           if (ref1 && ref2 && ref1 != ref2)
24574             {
24575               if (ref1 > ref2)
24576                 lose1 = true;
24577               else
24578                 lose2 = true;
24579             }
24580           else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
24581             {
24582               if ((quals1 & quals2) == quals2)
24583                 lose2 = true;
24584               if ((quals1 & quals2) == quals1)
24585                 lose1 = true;
24586             }
24587         }
24588
24589       if (lose1 && lose2)
24590         /* We've failed to deduce something in either direction.
24591            These must be unordered.  */
24592         break;
24593
24594       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
24595           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
24596         /* We have already processed all of the arguments in our
24597            handing of the pack expansion type.  */
24598         len = 0;
24599
24600       args1 = TREE_CHAIN (args1);
24601       args2 = TREE_CHAIN (args2);
24602     }
24603
24604   /* "In most cases, all template parameters must have values in order for
24605      deduction to succeed, but for partial ordering purposes a template
24606      parameter may remain without a value provided it is not used in the
24607      types being used for partial ordering."
24608
24609      Thus, if we are missing any of the targs1 we need to substitute into
24610      origs1, then pat2 is not as specialized as pat1.  This can happen when
24611      there is a nondeduced context.  */
24612   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
24613     lose2 = true;
24614   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
24615     lose1 = true;
24616
24617   processing_template_decl--;
24618
24619   /* If both deductions succeed, the partial ordering selects the more
24620      constrained template.  */
24621   /* P2113: If the corresponding template-parameters of the
24622      template-parameter-lists are not equivalent ([temp.over.link]) or if
24623      the function parameters that positionally correspond between the two
24624      templates are not of the same type, neither template is more
24625      specialized than the other.  */
24626   if (!lose1 && !lose2
24627       && comp_template_parms (DECL_TEMPLATE_PARMS (pat1),
24628                               DECL_TEMPLATE_PARMS (pat2))
24629       && compparms (origs1, origs2))
24630     {
24631       int winner = more_constrained (decl1, decl2);
24632       if (winner > 0)
24633         lose2 = true;
24634       else if (winner < 0)
24635         lose1 = true;
24636     }
24637
24638   /* All things being equal, if the next argument is a pack expansion
24639      for one function but not for the other, prefer the
24640      non-variadic function.  FIXME this is bogus; see c++/41958.  */
24641   if (lose1 == lose2
24642       && args1 && TREE_VALUE (args1)
24643       && args2 && TREE_VALUE (args2))
24644     {
24645       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
24646       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
24647     }
24648
24649   if (lose1 == lose2)
24650     return 0;
24651   else if (!lose1)
24652     return 1;
24653   else
24654     return -1;
24655 }
24656
24657 /* Determine which of two partial specializations of TMPL is more
24658    specialized.
24659
24660    PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
24661    to the first partial specialization.  The TREE_PURPOSE is the
24662    innermost set of template parameters for the partial
24663    specialization.  PAT2 is similar, but for the second template.
24664
24665    Return 1 if the first partial specialization is more specialized;
24666    -1 if the second is more specialized; 0 if neither is more
24667    specialized.
24668
24669    See [temp.class.order] for information about determining which of
24670    two templates is more specialized.  */
24671
24672 static int
24673 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
24674 {
24675   tree targs;
24676   int winner = 0;
24677   bool any_deductions = false;
24678
24679   tree tmpl1 = TREE_VALUE (pat1);
24680   tree tmpl2 = TREE_VALUE (pat2);
24681   tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
24682   tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
24683
24684   /* Just like what happens for functions, if we are ordering between
24685      different template specializations, we may encounter dependent
24686      types in the arguments, and we need our dependency check functions
24687      to behave correctly.  */
24688   ++processing_template_decl;
24689   targs = get_partial_spec_bindings (tmpl, tmpl1, specargs2);
24690   if (targs)
24691     {
24692       --winner;
24693       any_deductions = true;
24694     }
24695
24696   targs = get_partial_spec_bindings (tmpl, tmpl2, specargs1);
24697   if (targs)
24698     {
24699       ++winner;
24700       any_deductions = true;
24701     }
24702   --processing_template_decl;
24703
24704   /* If both deductions succeed, the partial ordering selects the more
24705      constrained template.  */
24706   if (!winner && any_deductions)
24707     winner = more_constrained (tmpl1, tmpl2);
24708
24709   /* In the case of a tie where at least one of the templates
24710      has a parameter pack at the end, the template with the most
24711      non-packed parameters wins.  */
24712   if (winner == 0
24713       && any_deductions
24714       && (template_args_variadic_p (TREE_PURPOSE (pat1))
24715           || template_args_variadic_p (TREE_PURPOSE (pat2))))
24716     {
24717       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
24718       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
24719       int len1 = TREE_VEC_LENGTH (args1);
24720       int len2 = TREE_VEC_LENGTH (args2);
24721
24722       /* We don't count the pack expansion at the end.  */
24723       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
24724         --len1;
24725       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
24726         --len2;
24727
24728       if (len1 > len2)
24729         return 1;
24730       else if (len1 < len2)
24731         return -1;
24732     }
24733
24734   return winner;
24735 }
24736
24737 /* Return the template arguments that will produce the function signature
24738    DECL from the function template FN, with the explicit template
24739    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
24740    also match.  Return NULL_TREE if no satisfactory arguments could be
24741    found.  */
24742
24743 static tree
24744 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
24745 {
24746   int ntparms = DECL_NTPARMS (fn);
24747   tree targs = make_tree_vec (ntparms);
24748   tree decl_type = TREE_TYPE (decl);
24749   tree decl_arg_types;
24750   tree *args;
24751   unsigned int nargs, ix;
24752   tree arg;
24753
24754   gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
24755
24756   /* Never do unification on the 'this' parameter.  */
24757   decl_arg_types = skip_artificial_parms_for (decl,
24758                                               TYPE_ARG_TYPES (decl_type));
24759
24760   nargs = list_length (decl_arg_types);
24761   args = XALLOCAVEC (tree, nargs);
24762   for (arg = decl_arg_types, ix = 0;
24763        arg != NULL_TREE && arg != void_list_node;
24764        arg = TREE_CHAIN (arg), ++ix)
24765     args[ix] = TREE_VALUE (arg);
24766
24767   if (fn_type_unification (fn, explicit_args, targs,
24768                            args, ix,
24769                            (check_rettype || DECL_CONV_FN_P (fn)
24770                             ? TREE_TYPE (decl_type) : NULL_TREE),
24771                            DEDUCE_EXACT, LOOKUP_NORMAL, NULL,
24772                            /*explain_p=*/false,
24773                            /*decltype*/false)
24774       == error_mark_node)
24775     return NULL_TREE;
24776
24777   return targs;
24778 }
24779
24780 /* Return the innermost template arguments that, when applied to a partial
24781    specialization SPEC_TMPL of TMPL, yield the ARGS.
24782
24783    For example, suppose we have:
24784
24785      template <class T, class U> struct S {};
24786      template <class T> struct S<T*, int> {};
24787
24788    Then, suppose we want to get `S<double*, int>'.  SPEC_TMPL will be the
24789    partial specialization and the ARGS will be {double*, int}.  The resulting
24790    vector will be {double}, indicating that `T' is bound to `double'.  */
24791
24792 static tree
24793 get_partial_spec_bindings (tree tmpl, tree spec_tmpl, tree args)
24794 {
24795   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
24796   tree spec_args
24797     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (spec_tmpl)));
24798   int i, ntparms = TREE_VEC_LENGTH (tparms);
24799   tree deduced_args;
24800   tree innermost_deduced_args;
24801
24802   innermost_deduced_args = make_tree_vec (ntparms);
24803   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
24804     {
24805       deduced_args = copy_node (args);
24806       SET_TMPL_ARGS_LEVEL (deduced_args,
24807                            TMPL_ARGS_DEPTH (deduced_args),
24808                            innermost_deduced_args);
24809     }
24810   else
24811     deduced_args = innermost_deduced_args;
24812
24813   bool tried_array_deduction = (cxx_dialect < cxx17);
24814  again:
24815   if (unify (tparms, deduced_args,
24816              INNERMOST_TEMPLATE_ARGS (spec_args),
24817              INNERMOST_TEMPLATE_ARGS (args),
24818              UNIFY_ALLOW_NONE, /*explain_p=*/false))
24819     return NULL_TREE;
24820
24821   for (i =  0; i < ntparms; ++i)
24822     if (! TREE_VEC_ELT (innermost_deduced_args, i))
24823       {
24824         if (!tried_array_deduction)
24825           {
24826             try_array_deduction (tparms, innermost_deduced_args,
24827                                  INNERMOST_TEMPLATE_ARGS (spec_args));
24828             tried_array_deduction = true;
24829             if (TREE_VEC_ELT (innermost_deduced_args, i))
24830               goto again;
24831           }
24832         return NULL_TREE;
24833       }
24834
24835   if (!push_tinst_level (spec_tmpl, deduced_args))
24836     {
24837       excessive_deduction_depth = true;
24838       return NULL_TREE;
24839     }
24840
24841   /* Verify that nondeduced template arguments agree with the type
24842      obtained from argument deduction.
24843
24844      For example:
24845
24846        struct A { typedef int X; };
24847        template <class T, class U> struct C {};
24848        template <class T> struct C<T, typename T::X> {};
24849
24850      Then with the instantiation `C<A, int>', we can deduce that
24851      `T' is `A' but unify () does not check whether `typename T::X'
24852      is `int'.  */
24853   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
24854
24855   if (spec_args != error_mark_node)
24856     spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
24857                                        INNERMOST_TEMPLATE_ARGS (spec_args),
24858                                        tmpl, tf_none, false, false);
24859
24860   pop_tinst_level ();
24861
24862   if (spec_args == error_mark_node
24863       /* We only need to check the innermost arguments; the other
24864          arguments will always agree.  */
24865       || !comp_template_args_porder (INNERMOST_TEMPLATE_ARGS (spec_args),
24866                                      INNERMOST_TEMPLATE_ARGS (args)))
24867     return NULL_TREE;
24868
24869   /* Now that we have bindings for all of the template arguments,
24870      ensure that the arguments deduced for the template template
24871      parameters have compatible template parameter lists.  See the use
24872      of template_template_parm_bindings_ok_p in fn_type_unification
24873      for more information.  */
24874   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
24875     return NULL_TREE;
24876
24877   return deduced_args;
24878 }
24879
24880 // Compare two function templates T1 and T2 by deducing bindings
24881 // from one against the other. If both deductions succeed, compare
24882 // constraints to see which is more constrained.
24883 static int
24884 more_specialized_inst (tree t1, tree t2)
24885 {
24886   int fate = 0;
24887   int count = 0;
24888
24889   if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
24890     {
24891       --fate;
24892       ++count;
24893     }
24894
24895   if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
24896     {
24897       ++fate;
24898       ++count;
24899     }
24900
24901   // If both deductions succeed, then one may be more constrained.
24902   if (count == 2 && fate == 0)
24903     fate = more_constrained (t1, t2);
24904
24905   return fate;
24906 }
24907
24908 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
24909    Return the TREE_LIST node with the most specialized template, if
24910    any.  If there is no most specialized template, the error_mark_node
24911    is returned.
24912
24913    Note that this function does not look at, or modify, the
24914    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
24915    returned is one of the elements of INSTANTIATIONS, callers may
24916    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
24917    and retrieve it from the value returned.  */
24918
24919 tree
24920 most_specialized_instantiation (tree templates)
24921 {
24922   tree fn, champ;
24923
24924   ++processing_template_decl;
24925
24926   champ = templates;
24927   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
24928     {
24929       gcc_assert (TREE_VALUE (champ) != TREE_VALUE (fn));
24930       int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
24931       if (fate == -1)
24932         champ = fn;
24933       else if (!fate)
24934         {
24935           /* Equally specialized, move to next function.  If there
24936              is no next function, nothing's most specialized.  */
24937           fn = TREE_CHAIN (fn);
24938           champ = fn;
24939           if (!fn)
24940             break;
24941         }
24942     }
24943
24944   if (champ)
24945     /* Now verify that champ is better than everything earlier in the
24946        instantiation list.  */
24947     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
24948       if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
24949       {
24950         champ = NULL_TREE;
24951         break;
24952       }
24953     }
24954
24955   processing_template_decl--;
24956
24957   if (!champ)
24958     return error_mark_node;
24959
24960   return champ;
24961 }
24962
24963 /* If DECL is a specialization of some template, return the most
24964    general such template.  Otherwise, returns NULL_TREE.
24965
24966    For example, given:
24967
24968      template <class T> struct S { template <class U> void f(U); };
24969
24970    if TMPL is `template <class U> void S<int>::f(U)' this will return
24971    the full template.  This function will not trace past partial
24972    specializations, however.  For example, given in addition:
24973
24974      template <class T> struct S<T*> { template <class U> void f(U); };
24975
24976    if TMPL is `template <class U> void S<int*>::f(U)' this will return
24977    `template <class T> template <class U> S<T*>::f(U)'.  */
24978
24979 tree
24980 most_general_template (tree decl)
24981 {
24982   if (TREE_CODE (decl) != TEMPLATE_DECL)
24983     {
24984       if (tree tinfo = get_template_info (decl))
24985         decl = TI_TEMPLATE (tinfo);
24986       /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
24987          template friend, or a FIELD_DECL for a capture pack.  */
24988       if (TREE_CODE (decl) != TEMPLATE_DECL)
24989         return NULL_TREE;
24990     }
24991
24992   /* Look for more and more general templates.  */
24993   while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
24994     {
24995       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
24996          (See cp-tree.h for details.)  */
24997       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
24998         break;
24999
25000       if (CLASS_TYPE_P (TREE_TYPE (decl))
25001           && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
25002           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
25003         break;
25004
25005       /* Stop if we run into an explicitly specialized class template.  */
25006       if (!DECL_NAMESPACE_SCOPE_P (decl)
25007           && DECL_CONTEXT (decl)
25008           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
25009         break;
25010
25011       decl = DECL_TI_TEMPLATE (decl);
25012     }
25013
25014   return decl;
25015 }
25016
25017 /* Return the most specialized of the template partial specializations
25018    which can produce TARGET, a specialization of some class or variable
25019    template.  The value returned is actually a TREE_LIST; the TREE_VALUE is
25020    a TEMPLATE_DECL node corresponding to the partial specialization, while
25021    the TREE_PURPOSE is the set of template arguments that must be
25022    substituted into the template pattern in order to generate TARGET.
25023
25024    If the choice of partial specialization is ambiguous, a diagnostic
25025    is issued, and the error_mark_node is returned.  If there are no
25026    partial specializations matching TARGET, then NULL_TREE is
25027    returned, indicating that the primary template should be used.  */
25028
25029 tree
25030 most_specialized_partial_spec (tree target, tsubst_flags_t complain)
25031 {
25032   tree list = NULL_TREE;
25033   tree t;
25034   tree champ;
25035   int fate;
25036   bool ambiguous_p;
25037   tree outer_args = NULL_TREE;
25038   tree tmpl, args;
25039
25040   if (TYPE_P (target))
25041     {
25042       tree tinfo = CLASSTYPE_TEMPLATE_INFO (target);
25043       tmpl = TI_TEMPLATE (tinfo);
25044       args = TI_ARGS (tinfo);
25045     }
25046   else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
25047     {
25048       tmpl = TREE_OPERAND (target, 0);
25049       args = TREE_OPERAND (target, 1);
25050     }
25051   else if (VAR_P (target))
25052     {
25053       tree tinfo = DECL_TEMPLATE_INFO (target);
25054       tmpl = TI_TEMPLATE (tinfo);
25055       args = TI_ARGS (tinfo);
25056     }
25057   else
25058     gcc_unreachable ();
25059
25060   tree main_tmpl = most_general_template (tmpl);
25061
25062   /* For determining which partial specialization to use, only the
25063      innermost args are interesting.  */
25064   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
25065     {
25066       outer_args = strip_innermost_template_args (args, 1);
25067       args = INNERMOST_TEMPLATE_ARGS (args);
25068     }
25069
25070   /* The caller hasn't called push_to_top_level yet, but we need
25071      get_partial_spec_bindings to be done in non-template context so that we'll
25072      fully resolve everything.  */
25073   processing_template_decl_sentinel ptds;
25074
25075   for (t = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl); t; t = TREE_CHAIN (t))
25076     {
25077       const tree ospec_tmpl = TREE_VALUE (t);
25078
25079       tree spec_tmpl;
25080       if (outer_args)
25081         {
25082           /* Substitute in the template args from the enclosing class.  */
25083           ++processing_template_decl;
25084           spec_tmpl = tsubst (ospec_tmpl, outer_args, tf_none, NULL_TREE);
25085           --processing_template_decl;
25086           if (spec_tmpl == error_mark_node)
25087             return error_mark_node;
25088         }
25089       else
25090         spec_tmpl = ospec_tmpl;
25091
25092       tree spec_args = get_partial_spec_bindings (tmpl, spec_tmpl, args);
25093       if (spec_args)
25094         {
25095           if (outer_args)
25096             spec_args = add_to_template_args (outer_args, spec_args);
25097
25098           /* Keep the candidate only if the constraints are satisfied,
25099              or if we're not compiling with concepts.  */
25100           if (!flag_concepts
25101               || constraints_satisfied_p (ospec_tmpl, spec_args))
25102             {
25103               list = tree_cons (spec_args, ospec_tmpl, list);
25104               TREE_TYPE (list) = TREE_TYPE (t);
25105             }
25106         }
25107     }
25108
25109   if (! list)
25110     return NULL_TREE;
25111
25112   ambiguous_p = false;
25113   t = list;
25114   champ = t;
25115   t = TREE_CHAIN (t);
25116   for (; t; t = TREE_CHAIN (t))
25117     {
25118       fate = more_specialized_partial_spec (tmpl, champ, t);
25119       if (fate == 1)
25120         ;
25121       else
25122         {
25123           if (fate == 0)
25124             {
25125               t = TREE_CHAIN (t);
25126               if (! t)
25127                 {
25128                   ambiguous_p = true;
25129                   break;
25130                 }
25131             }
25132           champ = t;
25133         }
25134     }
25135
25136   if (!ambiguous_p)
25137     for (t = list; t && t != champ; t = TREE_CHAIN (t))
25138       {
25139         fate = more_specialized_partial_spec (tmpl, champ, t);
25140         if (fate != 1)
25141           {
25142             ambiguous_p = true;
25143             break;
25144           }
25145       }
25146
25147   if (ambiguous_p)
25148     {
25149       const char *str;
25150       char *spaces = NULL;
25151       if (!(complain & tf_error))
25152         return error_mark_node;
25153       if (TYPE_P (target))
25154         error ("ambiguous template instantiation for %q#T", target);
25155       else
25156         error ("ambiguous template instantiation for %q#D", target);
25157       str = ngettext ("candidate is:", "candidates are:", list_length (list));
25158       for (t = list; t; t = TREE_CHAIN (t))
25159         {
25160           tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
25161           inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
25162                   "%s %#qS", spaces ? spaces : str, subst);
25163           spaces = spaces ? spaces : get_spaces (str);
25164         }
25165       free (spaces);
25166       return error_mark_node;
25167     }
25168
25169   return champ;
25170 }
25171
25172 /* Explicitly instantiate DECL.  */
25173
25174 void
25175 do_decl_instantiation (tree decl, tree storage)
25176 {
25177   tree result = NULL_TREE;
25178   int extern_p = 0;
25179
25180   if (!decl || decl == error_mark_node)
25181     /* An error occurred, for which grokdeclarator has already issued
25182        an appropriate message.  */
25183     return;
25184   else if (! DECL_LANG_SPECIFIC (decl))
25185     {
25186       error ("explicit instantiation of non-template %q#D", decl);
25187       return;
25188     }
25189   else if (DECL_DECLARED_CONCEPT_P (decl))
25190     {
25191       if (VAR_P (decl))
25192         error ("explicit instantiation of variable concept %q#D", decl);
25193       else
25194         error ("explicit instantiation of function concept %q#D", decl);
25195       return;
25196     }
25197
25198   bool var_templ = (DECL_TEMPLATE_INFO (decl)
25199                     && variable_template_p (DECL_TI_TEMPLATE (decl)));
25200
25201   if (VAR_P (decl) && !var_templ)
25202     {
25203       /* There is an asymmetry here in the way VAR_DECLs and
25204          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
25205          the latter, the DECL we get back will be marked as a
25206          template instantiation, and the appropriate
25207          DECL_TEMPLATE_INFO will be set up.  This does not happen for
25208          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
25209          should handle VAR_DECLs as it currently handles
25210          FUNCTION_DECLs.  */
25211       if (!DECL_CLASS_SCOPE_P (decl))
25212         {
25213           error ("%qD is not a static data member of a class template", decl);
25214           return;
25215         }
25216       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
25217       if (!result || !VAR_P (result))
25218         {
25219           error ("no matching template for %qD found", decl);
25220           return;
25221         }
25222       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
25223         {
25224           error ("type %qT for explicit instantiation %qD does not match "
25225                  "declared type %qT", TREE_TYPE (result), decl,
25226                  TREE_TYPE (decl));
25227           return;
25228         }
25229     }
25230   else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
25231     {
25232       error ("explicit instantiation of %q#D", decl);
25233       return;
25234     }
25235   else
25236     result = decl;
25237
25238   /* Check for various error cases.  Note that if the explicit
25239      instantiation is valid the RESULT will currently be marked as an
25240      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
25241      until we get here.  */
25242
25243   if (DECL_TEMPLATE_SPECIALIZATION (result))
25244     {
25245       /* DR 259 [temp.spec].
25246
25247          Both an explicit instantiation and a declaration of an explicit
25248          specialization shall not appear in a program unless the explicit
25249          instantiation follows a declaration of the explicit specialization.
25250
25251          For a given set of template parameters, if an explicit
25252          instantiation of a template appears after a declaration of an
25253          explicit specialization for that template, the explicit
25254          instantiation has no effect.  */
25255       return;
25256     }
25257   else if (DECL_EXPLICIT_INSTANTIATION (result))
25258     {
25259       /* [temp.spec]
25260
25261          No program shall explicitly instantiate any template more
25262          than once.
25263
25264          We check DECL_NOT_REALLY_EXTERN so as not to complain when
25265          the first instantiation was `extern' and the second is not,
25266          and EXTERN_P for the opposite case.  */
25267       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
25268         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
25269       /* If an "extern" explicit instantiation follows an ordinary
25270          explicit instantiation, the template is instantiated.  */
25271       if (extern_p)
25272         return;
25273     }
25274   else if (!DECL_IMPLICIT_INSTANTIATION (result))
25275     {
25276       error ("no matching template for %qD found", result);
25277       return;
25278     }
25279   else if (!DECL_TEMPLATE_INFO (result))
25280     {
25281       permerror (input_location, "explicit instantiation of non-template %q#D", result);
25282       return;
25283     }
25284
25285   if (storage == NULL_TREE)
25286     ;
25287   else if (storage == ridpointers[(int) RID_EXTERN])
25288     {
25289       if (cxx_dialect == cxx98)
25290         pedwarn (input_location, OPT_Wpedantic,
25291                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
25292                  "instantiations");
25293       extern_p = 1;
25294     }
25295   else
25296     error ("storage class %qD applied to template instantiation", storage);
25297
25298   check_explicit_instantiation_namespace (result);
25299   mark_decl_instantiated (result, extern_p);
25300   if (! extern_p)
25301     instantiate_decl (result, /*defer_ok=*/true,
25302                       /*expl_inst_class_mem_p=*/false);
25303 }
25304
25305 static void
25306 mark_class_instantiated (tree t, int extern_p)
25307 {
25308   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
25309   SET_CLASSTYPE_INTERFACE_KNOWN (t);
25310   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
25311   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
25312   if (! extern_p)
25313     {
25314       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
25315       rest_of_type_compilation (t, 1);
25316     }
25317 }
25318
25319 /* Perform an explicit instantiation of template class T.  STORAGE, if
25320    non-null, is the RID for extern, inline or static.  COMPLAIN is
25321    nonzero if this is called from the parser, zero if called recursively,
25322    since the standard is unclear (as detailed below).  */
25323
25324 void
25325 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
25326 {
25327   if (!(CLASS_TYPE_P (t) && CLASSTYPE_TEMPLATE_INFO (t)))
25328     {
25329       if (tree ti = TYPE_TEMPLATE_INFO (t))
25330         error ("explicit instantiation of non-class template %qD",
25331                TI_TEMPLATE (ti));
25332       else
25333         error ("explicit instantiation of non-template type %qT", t);
25334       return;
25335     }
25336
25337   complete_type (t);
25338
25339   if (!COMPLETE_TYPE_P (t))
25340     {
25341       if (complain & tf_error)
25342         error ("explicit instantiation of %q#T before definition of template",
25343                t);
25344       return;
25345     }
25346
25347   /* At most one of these will be true.  */
25348   bool extern_p = false;
25349   bool nomem_p = false;
25350   bool static_p = false;
25351
25352   if (storage != NULL_TREE)
25353     {
25354       if (storage == ridpointers[(int) RID_EXTERN])
25355         {
25356           if (cxx_dialect == cxx98)
25357             pedwarn (input_location, OPT_Wpedantic,
25358                      "ISO C++ 1998 forbids the use of %<extern%> on "
25359                      "explicit instantiations");
25360         }
25361       else
25362         pedwarn (input_location, OPT_Wpedantic,
25363                  "ISO C++ forbids the use of %qE"
25364                  " on explicit instantiations", storage);
25365
25366       if (storage == ridpointers[(int) RID_INLINE])
25367         nomem_p = true;
25368       else if (storage == ridpointers[(int) RID_EXTERN])
25369         extern_p = true;
25370       else if (storage == ridpointers[(int) RID_STATIC])
25371         static_p = true;
25372       else
25373         error ("storage class %qD applied to template instantiation",
25374                storage);
25375     }
25376
25377   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
25378     /* DR 259 [temp.spec].
25379
25380        Both an explicit instantiation and a declaration of an explicit
25381        specialization shall not appear in a program unless the
25382        explicit instantiation follows a declaration of the explicit
25383        specialization.
25384
25385        For a given set of template parameters, if an explicit
25386        instantiation of a template appears after a declaration of an
25387        explicit specialization for that template, the explicit
25388        instantiation has no effect.  */
25389     return;
25390
25391   if (CLASSTYPE_EXPLICIT_INSTANTIATION (t) && !CLASSTYPE_INTERFACE_ONLY (t))
25392     {
25393       /* We've already instantiated the template.  */
25394
25395       /* [temp.spec]
25396
25397          No program shall explicitly instantiate any template more
25398          than once.
25399
25400          If EXTERN_P then this is ok.  */
25401       if (!extern_p && (complain & tf_error))
25402         permerror (input_location,
25403                    "duplicate explicit instantiation of %q#T", t);
25404
25405       return;
25406     }
25407
25408   check_explicit_instantiation_namespace (TYPE_NAME (t));
25409   mark_class_instantiated (t, extern_p);
25410
25411   if (nomem_p)
25412     return;
25413
25414   /* In contrast to implicit instantiation, where only the
25415      declarations, and not the definitions, of members are
25416      instantiated, we have here:
25417
25418          [temp.explicit]
25419
25420          An explicit instantiation that names a class template
25421          specialization is also an explicit instantiation of the same
25422          kind (declaration or definition) of each of its members (not
25423          including members inherited from base classes and members
25424          that are templates) that has not been previously explicitly
25425          specialized in the translation unit containing the explicit
25426          instantiation, provided that the associated constraints, if
25427          any, of that member are satisfied by the template arguments
25428          of the explicit instantiation.  */
25429   for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
25430     if ((VAR_P (fld)
25431          || (TREE_CODE (fld) == FUNCTION_DECL
25432              && !static_p
25433              && user_provided_p (fld)))
25434         && DECL_TEMPLATE_INSTANTIATION (fld)
25435         && constraints_satisfied_p (fld))
25436       {
25437         mark_decl_instantiated (fld, extern_p);
25438         if (! extern_p)
25439           instantiate_decl (fld, /*defer_ok=*/true,
25440                             /*expl_inst_class_mem_p=*/true);
25441       }
25442     else if (DECL_IMPLICIT_TYPEDEF_P (fld))
25443       {
25444         tree type = TREE_TYPE (fld);
25445
25446         if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
25447             && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
25448           do_type_instantiation (type, storage, 0);
25449       }
25450 }
25451
25452 /* Given a function DECL, which is a specialization of TMPL, modify
25453    DECL to be a re-instantiation of TMPL with the same template
25454    arguments.  TMPL should be the template into which tsubst'ing
25455    should occur for DECL, not the most general template.
25456
25457    One reason for doing this is a scenario like this:
25458
25459      template <class T>
25460      void f(const T&, int i);
25461
25462      void g() { f(3, 7); }
25463
25464      template <class T>
25465      void f(const T& t, const int i) { }
25466
25467    Note that when the template is first instantiated, with
25468    instantiate_template, the resulting DECL will have no name for the
25469    first parameter, and the wrong type for the second.  So, when we go
25470    to instantiate the DECL, we regenerate it.  */
25471
25472 static void
25473 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
25474 {
25475   /* The arguments used to instantiate DECL, from the most general
25476      template.  */
25477   tree code_pattern;
25478
25479   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
25480
25481   /* Make sure that we can see identifiers, and compute access
25482      correctly.  */
25483   push_access_scope (decl);
25484
25485   if (TREE_CODE (decl) == FUNCTION_DECL)
25486     {
25487       tree specs;
25488       int args_depth;
25489       int parms_depth;
25490
25491       args_depth = TMPL_ARGS_DEPTH (args);
25492       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
25493       if (args_depth > parms_depth)
25494         args = get_innermost_template_args (args, parms_depth);
25495
25496       /* Instantiate a dynamic exception-specification.  noexcept will be
25497          handled below.  */
25498       if (tree raises = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (code_pattern)))
25499         if (TREE_VALUE (raises))
25500           {
25501             specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
25502                                                     args, tf_error, NULL_TREE,
25503                                                     /*defer_ok*/false);
25504             if (specs && specs != error_mark_node)
25505               TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
25506                                                           specs);
25507           }
25508
25509       /* Merge parameter declarations.  */
25510       if (tree pattern_parm
25511           = skip_artificial_parms_for (code_pattern,
25512                                        DECL_ARGUMENTS (code_pattern)))
25513         {
25514           tree *p = &DECL_ARGUMENTS (decl);
25515           for (int skip = num_artificial_parms_for (decl); skip; --skip)
25516             p = &DECL_CHAIN (*p);
25517           *p = tsubst_decl (pattern_parm, args, tf_error);
25518           for (tree t = *p; t; t = DECL_CHAIN (t))
25519             DECL_CONTEXT (t) = decl;
25520         }
25521
25522       /* Merge additional specifiers from the CODE_PATTERN.  */
25523       if (DECL_DECLARED_INLINE_P (code_pattern)
25524           && !DECL_DECLARED_INLINE_P (decl))
25525         DECL_DECLARED_INLINE_P (decl) = 1;
25526
25527       maybe_instantiate_noexcept (decl, tf_error);
25528     }
25529   else if (VAR_P (decl))
25530     {
25531       start_lambda_scope (decl);
25532       DECL_INITIAL (decl) =
25533         tsubst_init (DECL_INITIAL (code_pattern), decl, args,
25534                      tf_error, DECL_TI_TEMPLATE (decl));
25535       finish_lambda_scope ();
25536       if (VAR_HAD_UNKNOWN_BOUND (decl))
25537         TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
25538                                    tf_error, DECL_TI_TEMPLATE (decl));
25539     }
25540   else
25541     gcc_unreachable ();
25542
25543   pop_access_scope (decl);
25544 }
25545
25546 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
25547    substituted to get DECL.  */
25548
25549 tree
25550 template_for_substitution (tree decl)
25551 {
25552   tree tmpl = DECL_TI_TEMPLATE (decl);
25553
25554   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
25555      for the instantiation.  This is not always the most general
25556      template.  Consider, for example:
25557
25558         template <class T>
25559         struct S { template <class U> void f();
25560                    template <> void f<int>(); };
25561
25562      and an instantiation of S<double>::f<int>.  We want TD to be the
25563      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
25564   while (/* An instantiation cannot have a definition, so we need a
25565             more general template.  */
25566          DECL_TEMPLATE_INSTANTIATION (tmpl)
25567            /* We must also deal with friend templates.  Given:
25568
25569                 template <class T> struct S {
25570                   template <class U> friend void f() {};
25571                 };
25572
25573               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
25574               so far as the language is concerned, but that's still
25575               where we get the pattern for the instantiation from.  On
25576               other hand, if the definition comes outside the class, say:
25577
25578                 template <class T> struct S {
25579                   template <class U> friend void f();
25580                 };
25581                 template <class U> friend void f() {}
25582
25583               we don't need to look any further.  That's what the check for
25584               DECL_INITIAL is for.  */
25585           || (TREE_CODE (decl) == FUNCTION_DECL
25586               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
25587               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
25588     {
25589       /* The present template, TD, should not be a definition.  If it
25590          were a definition, we should be using it!  Note that we
25591          cannot restructure the loop to just keep going until we find
25592          a template with a definition, since that might go too far if
25593          a specialization was declared, but not defined.  */
25594
25595       /* Fetch the more general template.  */
25596       tmpl = DECL_TI_TEMPLATE (tmpl);
25597     }
25598
25599   return tmpl;
25600 }
25601
25602 /* Returns true if we need to instantiate this template instance even if we
25603    know we aren't going to emit it.  */
25604
25605 bool
25606 always_instantiate_p (tree decl)
25607 {
25608   /* We always instantiate inline functions so that we can inline them.  An
25609      explicit instantiation declaration prohibits implicit instantiation of
25610      non-inline functions.  With high levels of optimization, we would
25611      normally inline non-inline functions -- but we're not allowed to do
25612      that for "extern template" functions.  Therefore, we check
25613      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
25614   return ((TREE_CODE (decl) == FUNCTION_DECL
25615            && (DECL_DECLARED_INLINE_P (decl)
25616                || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
25617           /* And we need to instantiate static data members so that
25618              their initializers are available in integral constant
25619              expressions.  */
25620           || (VAR_P (decl)
25621               && decl_maybe_constant_var_p (decl)));
25622 }
25623
25624 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
25625    instantiate it now, modifying TREE_TYPE (fn).  Returns false on
25626    error, true otherwise.  */
25627
25628 bool
25629 maybe_instantiate_noexcept (tree fn, tsubst_flags_t complain)
25630 {
25631   if (fn == error_mark_node)
25632     return false;
25633
25634   /* Don't instantiate a noexcept-specification from template context.  */
25635   if (processing_template_decl
25636       && (!flag_noexcept_type || type_dependent_expression_p (fn)))
25637     return true;
25638
25639   if (DECL_MAYBE_DELETED (fn))
25640     {
25641       if (fn == current_function_decl)
25642         /* We're in start_preparsed_function, keep going.  */
25643         return true;
25644
25645       ++function_depth;
25646       synthesize_method (fn);
25647       --function_depth;
25648       return !DECL_MAYBE_DELETED (fn);
25649     }
25650
25651   tree fntype = TREE_TYPE (fn);
25652   tree spec = TYPE_RAISES_EXCEPTIONS (fntype);
25653
25654   if (!spec || !TREE_PURPOSE (spec))
25655     return true;
25656
25657   tree noex = TREE_PURPOSE (spec);
25658   if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
25659       && TREE_CODE (noex) != DEFERRED_PARSE)
25660     return true;
25661
25662   tree orig_fn = NULL_TREE;
25663   /* For a member friend template we can get a TEMPLATE_DECL.  Let's use
25664      its FUNCTION_DECL for the rest of this function -- push_access_scope
25665      doesn't accept TEMPLATE_DECLs.  */
25666   if (DECL_FUNCTION_TEMPLATE_P (fn))
25667     {
25668       orig_fn = fn;
25669       fn = DECL_TEMPLATE_RESULT (fn);
25670     }
25671
25672   if (DECL_CLONED_FUNCTION_P (fn))
25673     {
25674       tree prime = DECL_CLONED_FUNCTION (fn);
25675       if (!maybe_instantiate_noexcept (prime, complain))
25676         return false;
25677       spec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (prime));
25678     }
25679   else if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
25680     {
25681       static hash_set<tree>* fns = new hash_set<tree>;
25682       bool added = false;
25683       if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
25684         {
25685           spec = get_defaulted_eh_spec (fn, complain);
25686           if (spec == error_mark_node)
25687             /* This might have failed because of an unparsed DMI, so
25688                let's try again later.  */
25689             return false;
25690         }
25691       else if (!(added = !fns->add (fn)))
25692         {
25693           /* If hash_set::add returns true, the element was already there.  */
25694           location_t loc = cp_expr_loc_or_loc (DEFERRED_NOEXCEPT_PATTERN (noex),
25695                                             DECL_SOURCE_LOCATION (fn));
25696           error_at (loc,
25697                     "exception specification of %qD depends on itself",
25698                     fn);
25699           spec = noexcept_false_spec;
25700         }
25701       else if (push_tinst_level (fn))
25702         {
25703           push_to_top_level ();
25704           push_access_scope (fn);
25705           push_deferring_access_checks (dk_no_deferred);
25706           input_location = DECL_SOURCE_LOCATION (fn);
25707
25708           if (!DECL_LOCAL_DECL_P (fn))
25709             {
25710               /* If needed, set current_class_ptr for the benefit of
25711                  tsubst_copy/PARM_DECL.  The exception pattern will
25712                  refer to the parm of the template, not the
25713                  instantiation.  */
25714               tree tdecl = DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (fn));
25715               if (DECL_NONSTATIC_MEMBER_FUNCTION_P (tdecl))
25716                 {
25717                   tree this_parm = DECL_ARGUMENTS (tdecl);
25718                   current_class_ptr = NULL_TREE;
25719                   current_class_ref = cp_build_fold_indirect_ref (this_parm);
25720                   current_class_ptr = this_parm;
25721                 }
25722             }
25723
25724           /* If this function is represented by a TEMPLATE_DECL, then
25725              the deferred noexcept-specification might still contain
25726              dependent types, even after substitution.  And we need the
25727              dependency check functions to work in build_noexcept_spec.  */
25728           if (orig_fn)
25729             ++processing_template_decl;
25730
25731           /* Do deferred instantiation of the noexcept-specifier.  */
25732           noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
25733                                         DEFERRED_NOEXCEPT_ARGS (noex),
25734                                         tf_warning_or_error, fn,
25735                                         /*function_p=*/false,
25736                                         /*i_c_e_p=*/true);
25737
25738           /* Build up the noexcept-specification.  */
25739           spec = build_noexcept_spec (noex, tf_warning_or_error);
25740
25741           if (orig_fn)
25742             --processing_template_decl;
25743
25744           pop_deferring_access_checks ();
25745           pop_access_scope (fn);
25746           pop_tinst_level ();
25747           pop_from_top_level ();
25748         }
25749       else
25750         spec = noexcept_false_spec;
25751
25752       if (added)
25753         fns->remove (fn);
25754     }
25755
25756   if (spec == error_mark_node)
25757     {
25758       /* This failed with a hard error, so let's go with false.  */
25759       gcc_assert (seen_error ());
25760       spec = noexcept_false_spec;
25761     }
25762
25763   TREE_TYPE (fn) = build_exception_variant (fntype, spec);
25764   if (orig_fn)
25765     TREE_TYPE (orig_fn) = TREE_TYPE (fn);
25766
25767   return true;
25768 }
25769
25770 /* We're starting to process the function INST, an instantiation of PATTERN;
25771    add their parameters to local_specializations.  */
25772
25773 static void
25774 register_parameter_specializations (tree pattern, tree inst)
25775 {
25776   tree tmpl_parm = DECL_ARGUMENTS (pattern);
25777   tree spec_parm = DECL_ARGUMENTS (inst);
25778   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (inst))
25779     {
25780       register_local_specialization (spec_parm, tmpl_parm);
25781       spec_parm = skip_artificial_parms_for (inst, spec_parm);
25782       tmpl_parm = skip_artificial_parms_for (pattern, tmpl_parm);
25783     }
25784   for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
25785     {
25786       if (!DECL_PACK_P (tmpl_parm))
25787         {
25788           register_local_specialization (spec_parm, tmpl_parm);
25789           spec_parm = DECL_CHAIN (spec_parm);
25790         }
25791       else
25792         {
25793           /* Register the (value) argument pack as a specialization of
25794              TMPL_PARM, then move on.  */
25795           tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
25796           register_local_specialization (argpack, tmpl_parm);
25797         }
25798     }
25799   gcc_assert (!spec_parm);
25800 }
25801
25802 /* Instantiate the body of D using PATTERN with ARGS.  We have
25803    already determined PATTERN is the correct template to use.
25804    NESTED_P is true if this is a nested function, in which case
25805    PATTERN will be a FUNCTION_DECL not a TEMPLATE_DECL.  */
25806
25807 static void
25808 instantiate_body (tree pattern, tree args, tree d, bool nested_p)
25809 {
25810   tree td = NULL_TREE;
25811   tree code_pattern = pattern;
25812
25813   if (!nested_p)
25814     {
25815       td = pattern;
25816       code_pattern = DECL_TEMPLATE_RESULT (td);
25817     }
25818   else
25819     /* Only OMP reductions are nested.  */
25820     gcc_checking_assert (DECL_OMP_DECLARE_REDUCTION_P (code_pattern));
25821
25822   vec<tree> omp_privatization_save;
25823   if (current_function_decl)
25824     save_omp_privatization_clauses (omp_privatization_save);
25825
25826   bool push_to_top
25827     = !(current_function_decl
25828         && !LAMBDA_FUNCTION_P (d)
25829         && decl_function_context (d) == current_function_decl);
25830
25831   if (push_to_top)
25832     push_to_top_level ();
25833   else
25834     {
25835       gcc_assert (!processing_template_decl);
25836       push_function_context ();
25837       cp_unevaluated_operand = 0;
25838       c_inhibit_evaluation_warnings = 0;
25839     }
25840
25841   if (VAR_P (d))
25842     {
25843       /* The variable might be a lambda's extra scope, and that
25844          lambda's visibility depends on D's.  */
25845       maybe_commonize_var (d);
25846       determine_visibility (d);
25847     }
25848
25849   /* Mark D as instantiated so that recursive calls to
25850      instantiate_decl do not try to instantiate it again.  */
25851   DECL_TEMPLATE_INSTANTIATED (d) = 1;
25852
25853   if (td)
25854     /* Regenerate the declaration in case the template has been modified
25855        by a subsequent redeclaration.  */
25856     regenerate_decl_from_template (d, td, args);
25857
25858   /* We already set the file and line above.  Reset them now in case
25859      they changed as a result of calling regenerate_decl_from_template.  */
25860   input_location = DECL_SOURCE_LOCATION (d);
25861
25862   if (VAR_P (d))
25863     {
25864       /* Clear out DECL_RTL; whatever was there before may not be right
25865          since we've reset the type of the declaration.  */
25866       SET_DECL_RTL (d, NULL);
25867       DECL_IN_AGGR_P (d) = 0;
25868
25869       /* The initializer is placed in DECL_INITIAL by
25870          regenerate_decl_from_template so we don't need to
25871          push/pop_access_scope again here.  Pull it out so that
25872          cp_finish_decl can process it.  */
25873       bool const_init = false;
25874       tree init = DECL_INITIAL (d);
25875       DECL_INITIAL (d) = NULL_TREE;
25876       DECL_INITIALIZED_P (d) = 0;
25877
25878       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
25879          initializer.  That function will defer actual emission until
25880          we have a chance to determine linkage.  */
25881       DECL_EXTERNAL (d) = 0;
25882
25883       /* Enter the scope of D so that access-checking works correctly.  */
25884       bool enter_context = DECL_CLASS_SCOPE_P (d);
25885       if (enter_context)
25886         push_nested_class (DECL_CONTEXT (d));
25887
25888       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
25889       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
25890
25891       if (enter_context)
25892         pop_nested_class ();
25893     }
25894   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
25895     synthesize_method (d);
25896   else if (TREE_CODE (d) == FUNCTION_DECL)
25897     {
25898       /* Set up the list of local specializations.  */
25899       local_specialization_stack lss (push_to_top ? lss_blank : lss_copy);
25900       tree block = NULL_TREE;
25901
25902       /* Set up context.  */
25903       if (nested_p)
25904         block = push_stmt_list ();
25905       else
25906         {
25907           start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
25908
25909           perform_instantiation_time_access_checks (code_pattern, args);
25910         }
25911
25912       /* Create substitution entries for the parameters.  */
25913       register_parameter_specializations (code_pattern, d);
25914
25915       /* Substitute into the body of the function.  */
25916       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
25917         tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
25918                         tf_warning_or_error, d);
25919       else
25920         {
25921           tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
25922                        tf_warning_or_error, DECL_TI_TEMPLATE (d),
25923                        /*integral_constant_expression_p=*/false);
25924
25925           /* Set the current input_location to the end of the function
25926              so that finish_function knows where we are.  */
25927           input_location
25928             = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
25929
25930           /* Remember if we saw an infinite loop in the template.  */
25931           current_function_infinite_loop
25932             = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
25933         }
25934
25935       /* Finish the function.  */
25936       if (nested_p)
25937         DECL_SAVED_TREE (d) = pop_stmt_list (block);
25938       else
25939         {
25940           d = finish_function (/*inline_p=*/false);
25941           expand_or_defer_fn (d);
25942         }
25943
25944       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
25945         cp_check_omp_declare_reduction (d);
25946     }
25947
25948   /* We're not deferring instantiation any more.  */
25949   if (!nested_p)
25950     TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
25951
25952   if (push_to_top)
25953     pop_from_top_level ();
25954   else
25955     pop_function_context ();
25956
25957   if (current_function_decl)
25958     restore_omp_privatization_clauses (omp_privatization_save);
25959 }
25960
25961 /* Produce the definition of D, a _DECL generated from a template.  If
25962    DEFER_OK is true, then we don't have to actually do the
25963    instantiation now; we just have to do it sometime.  Normally it is
25964    an error if this is an explicit instantiation but D is undefined.
25965    EXPL_INST_CLASS_MEM_P is true iff D is a member of an explicitly
25966    instantiated class template.  */
25967
25968 tree
25969 instantiate_decl (tree d, bool defer_ok, bool expl_inst_class_mem_p)
25970 {
25971   tree tmpl = DECL_TI_TEMPLATE (d);
25972   tree gen_args;
25973   tree args;
25974   tree td;
25975   tree code_pattern;
25976   tree spec;
25977   tree gen_tmpl;
25978   bool pattern_defined;
25979   location_t saved_loc = input_location;
25980   int saved_unevaluated_operand = cp_unevaluated_operand;
25981   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
25982   bool external_p;
25983   bool deleted_p;
25984
25985   /* This function should only be used to instantiate templates for
25986      functions and static member variables.  */
25987   gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
25988
25989   /* A concept is never instantiated. */
25990   gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
25991
25992   gcc_checking_assert (!DECL_FUNCTION_SCOPE_P (d));
25993
25994   if (modules_p ())
25995     /* We may have a pending instantiation of D itself.  */
25996     lazy_load_pendings (d);
25997
25998   /* Variables are never deferred; if instantiation is required, they
25999      are instantiated right away.  That allows for better code in the
26000      case that an expression refers to the value of the variable --
26001      if the variable has a constant value the referring expression can
26002      take advantage of that fact.  */
26003   if (VAR_P (d))
26004     defer_ok = false;
26005
26006   /* Don't instantiate cloned functions.  Instead, instantiate the
26007      functions they cloned.  */
26008   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
26009     d = DECL_CLONED_FUNCTION (d);
26010
26011   if (DECL_TEMPLATE_INSTANTIATED (d)
26012       || TREE_TYPE (d) == error_mark_node
26013       || (TREE_CODE (d) == FUNCTION_DECL
26014           && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
26015       || DECL_TEMPLATE_SPECIALIZATION (d))
26016     /* D has already been instantiated or explicitly specialized, so
26017        there's nothing for us to do here.
26018
26019        It might seem reasonable to check whether or not D is an explicit
26020        instantiation, and, if so, stop here.  But when an explicit
26021        instantiation is deferred until the end of the compilation,
26022        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
26023        the instantiation.  */
26024     return d;
26025
26026   /* Check to see whether we know that this template will be
26027      instantiated in some other file, as with "extern template"
26028      extension.  */
26029   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
26030
26031   /* In general, we do not instantiate such templates.  */
26032   if (external_p && !always_instantiate_p (d))
26033     return d;
26034
26035   gen_tmpl = most_general_template (tmpl);
26036   gen_args = DECL_TI_ARGS (d);
26037
26038   /* We should already have the extra args.  */
26039   gcc_checking_assert (tmpl == gen_tmpl
26040                        || (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
26041                            == TMPL_ARGS_DEPTH (gen_args)));
26042   /* And what's in the hash table should match D.  */
26043   gcc_checking_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0))
26044                        == d
26045                        || spec == NULL_TREE);
26046
26047   /* This needs to happen before any tsubsting.  */
26048   if (! push_tinst_level (d))
26049     return d;
26050
26051   timevar_push (TV_TEMPLATE_INST);
26052
26053   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
26054      for the instantiation.  */
26055   td = template_for_substitution (d);
26056   args = gen_args;
26057
26058   if (VAR_P (d))
26059     {
26060       /* Look up an explicit specialization, if any.  */
26061       tree tid = lookup_template_variable (gen_tmpl, gen_args);
26062       tree elt = most_specialized_partial_spec (tid, tf_warning_or_error);
26063       if (elt && elt != error_mark_node)
26064         {
26065           td = TREE_VALUE (elt);
26066           args = TREE_PURPOSE (elt);
26067         }
26068     }
26069
26070   code_pattern = DECL_TEMPLATE_RESULT (td);
26071
26072   /* We should never be trying to instantiate a member of a class
26073      template or partial specialization.  */
26074   gcc_assert (d != code_pattern);
26075
26076   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
26077       || DECL_TEMPLATE_SPECIALIZATION (td))
26078     /* In the case of a friend template whose definition is provided
26079        outside the class, we may have too many arguments.  Drop the
26080        ones we don't need.  The same is true for specializations.  */
26081     args = get_innermost_template_args
26082       (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
26083
26084   if (TREE_CODE (d) == FUNCTION_DECL)
26085     {
26086       deleted_p = DECL_DELETED_FN (code_pattern);
26087       pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
26088                           && DECL_INITIAL (code_pattern) != error_mark_node)
26089                          || DECL_DEFAULTED_FN (code_pattern)
26090                          || deleted_p);
26091     }
26092   else
26093     {
26094       deleted_p = false;
26095       if (DECL_CLASS_SCOPE_P (code_pattern))
26096         pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
26097       else
26098         pattern_defined = ! DECL_EXTERNAL (code_pattern);
26099     }
26100
26101   /* We may be in the middle of deferred access check.  Disable it now.  */
26102   push_deferring_access_checks (dk_no_deferred);
26103
26104   /* Unless an explicit instantiation directive has already determined
26105      the linkage of D, remember that a definition is available for
26106      this entity.  */
26107   if (pattern_defined
26108       && !DECL_INTERFACE_KNOWN (d)
26109       && !DECL_NOT_REALLY_EXTERN (d))
26110     mark_definable (d);
26111
26112   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
26113   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
26114   input_location = DECL_SOURCE_LOCATION (d);
26115
26116   /* If D is a member of an explicitly instantiated class template,
26117      and no definition is available, treat it like an implicit
26118      instantiation.  */
26119   if (!pattern_defined && expl_inst_class_mem_p
26120       && DECL_EXPLICIT_INSTANTIATION (d))
26121     {
26122       /* Leave linkage flags alone on instantiations with anonymous
26123          visibility.  */
26124       if (TREE_PUBLIC (d))
26125         {
26126           DECL_NOT_REALLY_EXTERN (d) = 0;
26127           DECL_INTERFACE_KNOWN (d) = 0;
26128         }
26129       SET_DECL_IMPLICIT_INSTANTIATION (d);
26130     }
26131
26132   /* Defer all other templates, unless we have been explicitly
26133      forbidden from doing so.  */
26134   if (/* If there is no definition, we cannot instantiate the
26135          template.  */
26136       ! pattern_defined
26137       /* If it's OK to postpone instantiation, do so.  */
26138       || defer_ok
26139       /* If this is a static data member that will be defined
26140          elsewhere, we don't want to instantiate the entire data
26141          member, but we do want to instantiate the initializer so that
26142          we can substitute that elsewhere.  */
26143       || (external_p && VAR_P (d))
26144       /* Handle here a deleted function too, avoid generating
26145          its body (c++/61080).  */
26146       || deleted_p)
26147     {
26148       /* The definition of the static data member is now required so
26149          we must substitute the initializer.  */
26150       if (VAR_P (d)
26151           && !DECL_INITIAL (d)
26152           && DECL_INITIAL (code_pattern))
26153         {
26154           tree ns;
26155           tree init;
26156           bool const_init = false;
26157           bool enter_context = DECL_CLASS_SCOPE_P (d);
26158
26159           ns = decl_namespace_context (d);
26160           push_nested_namespace (ns);
26161           if (enter_context)
26162             push_nested_class (DECL_CONTEXT (d));
26163           init = tsubst_expr (DECL_INITIAL (code_pattern),
26164                               args,
26165                               tf_warning_or_error, NULL_TREE,
26166                               /*integral_constant_expression_p=*/false);
26167           /* If instantiating the initializer involved instantiating this
26168              again, don't call cp_finish_decl twice.  */
26169           if (!DECL_INITIAL (d))
26170             {
26171               /* Make sure the initializer is still constant, in case of
26172                  circular dependency (template/instantiate6.C). */
26173               const_init
26174                 = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
26175               cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
26176                               /*asmspec_tree=*/NULL_TREE,
26177                               LOOKUP_ONLYCONVERTING);
26178             }
26179           if (enter_context)
26180             pop_nested_class ();
26181           pop_nested_namespace (ns);
26182         }
26183
26184       /* We restore the source position here because it's used by
26185          add_pending_template.  */
26186       input_location = saved_loc;
26187
26188       if (at_eof && !pattern_defined
26189           && DECL_EXPLICIT_INSTANTIATION (d)
26190           && DECL_NOT_REALLY_EXTERN (d))
26191         /* [temp.explicit]
26192
26193            The definition of a non-exported function template, a
26194            non-exported member function template, or a non-exported
26195            member function or static data member of a class template
26196            shall be present in every translation unit in which it is
26197            explicitly instantiated.  */
26198         permerror (input_location,  "explicit instantiation of %qD "
26199                    "but no definition available", d);
26200
26201       /* If we're in unevaluated context, we just wanted to get the
26202          constant value; this isn't an odr use, so don't queue
26203          a full instantiation.  */
26204       if (!cp_unevaluated_operand
26205           /* ??? Historically, we have instantiated inline functions, even
26206              when marked as "extern template".  */
26207           && !(external_p && VAR_P (d)))
26208         add_pending_template (d);
26209     }
26210   else
26211     {
26212       set_instantiating_module (d);
26213       if (variable_template_p (gen_tmpl))
26214         note_variable_template_instantiation (d);
26215       instantiate_body (td, args, d, false);
26216     }
26217
26218   pop_deferring_access_checks ();
26219   timevar_pop (TV_TEMPLATE_INST);
26220   pop_tinst_level ();
26221   input_location = saved_loc;
26222   cp_unevaluated_operand = saved_unevaluated_operand;
26223   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
26224
26225   return d;
26226 }
26227
26228 /* Run through the list of templates that we wish we could
26229    instantiate, and instantiate any we can.  RETRIES is the
26230    number of times we retry pending template instantiation.  */
26231
26232 void
26233 instantiate_pending_templates (int retries)
26234 {
26235   int reconsider;
26236   location_t saved_loc = input_location;
26237
26238   /* Instantiating templates may trigger vtable generation.  This in turn
26239      may require further template instantiations.  We place a limit here
26240      to avoid infinite loop.  */
26241   if (pending_templates && retries >= max_tinst_depth)
26242     {
26243       tree decl = pending_templates->tinst->maybe_get_node ();
26244
26245       fatal_error (input_location,
26246                    "template instantiation depth exceeds maximum of %d"
26247                    " instantiating %q+D, possibly from virtual table generation"
26248                    " (use %<-ftemplate-depth=%> to increase the maximum)",
26249                    max_tinst_depth, decl);
26250       if (TREE_CODE (decl) == FUNCTION_DECL)
26251         /* Pretend that we defined it.  */
26252         DECL_INITIAL (decl) = error_mark_node;
26253       return;
26254     }
26255
26256   do
26257     {
26258       struct pending_template **t = &pending_templates;
26259       struct pending_template *last = NULL;
26260       reconsider = 0;
26261       while (*t)
26262         {
26263           tree instantiation = reopen_tinst_level ((*t)->tinst);
26264           bool complete = false;
26265
26266           if (TYPE_P (instantiation))
26267             {
26268               if (!COMPLETE_TYPE_P (instantiation))
26269                 {
26270                   instantiate_class_template (instantiation);
26271                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
26272                     for (tree fld = TYPE_FIELDS (instantiation);
26273                          fld; fld = TREE_CHAIN (fld))
26274                       if ((VAR_P (fld)
26275                            || (TREE_CODE (fld) == FUNCTION_DECL
26276                                && !DECL_ARTIFICIAL (fld)))
26277                           && DECL_TEMPLATE_INSTANTIATION (fld))
26278                         instantiate_decl (fld,
26279                                           /*defer_ok=*/false,
26280                                           /*expl_inst_class_mem_p=*/false);
26281
26282                   if (COMPLETE_TYPE_P (instantiation))
26283                     reconsider = 1;
26284                 }
26285
26286               complete = COMPLETE_TYPE_P (instantiation);
26287             }
26288           else
26289             {
26290               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
26291                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
26292                 {
26293                   instantiation
26294                     = instantiate_decl (instantiation,
26295                                         /*defer_ok=*/false,
26296                                         /*expl_inst_class_mem_p=*/false);
26297                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
26298                     reconsider = 1;
26299                 }
26300
26301               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
26302                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
26303             }
26304
26305           if (complete)
26306             {
26307               /* If INSTANTIATION has been instantiated, then we don't
26308                  need to consider it again in the future.  */
26309               struct pending_template *drop = *t;
26310               *t = (*t)->next;
26311               set_refcount_ptr (drop->tinst);
26312               pending_template_freelist ().free (drop);
26313             }
26314           else
26315             {
26316               last = *t;
26317               t = &(*t)->next;
26318             }
26319           tinst_depth = 0;
26320           set_refcount_ptr (current_tinst_level);
26321         }
26322       last_pending_template = last;
26323     }
26324   while (reconsider);
26325
26326   input_location = saved_loc;
26327 }
26328
26329 /* Substitute ARGVEC into T, which is a list of initializers for
26330    either base class or a non-static data member.  The TREE_PURPOSEs
26331    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
26332    instantiate_decl.  */
26333
26334 static tree
26335 tsubst_initializer_list (tree t, tree argvec)
26336 {
26337   tree inits = NULL_TREE;
26338   tree target_ctor = error_mark_node;
26339
26340   for (; t; t = TREE_CHAIN (t))
26341     {
26342       tree decl;
26343       tree init;
26344       tree expanded_bases = NULL_TREE;
26345       tree expanded_arguments = NULL_TREE;
26346       int i, len = 1;
26347
26348       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
26349         {
26350           tree expr;
26351           tree arg;
26352
26353           /* Expand the base class expansion type into separate base
26354              classes.  */
26355           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
26356                                                  tf_warning_or_error,
26357                                                  NULL_TREE);
26358           if (expanded_bases == error_mark_node)
26359             continue;
26360
26361           /* We'll be building separate TREE_LISTs of arguments for
26362              each base.  */
26363           len = TREE_VEC_LENGTH (expanded_bases);
26364           expanded_arguments = make_tree_vec (len);
26365           for (i = 0; i < len; i++)
26366             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
26367
26368           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
26369              expand each argument in the TREE_VALUE of t.  */
26370           expr = make_node (EXPR_PACK_EXPANSION);
26371           PACK_EXPANSION_LOCAL_P (expr) = true;
26372           PACK_EXPANSION_PARAMETER_PACKS (expr) =
26373             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
26374
26375           if (TREE_VALUE (t) == void_type_node)
26376             /* VOID_TYPE_NODE is used to indicate
26377                value-initialization.  */
26378             {
26379               for (i = 0; i < len; i++)
26380                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
26381             }
26382           else
26383             {
26384               /* Substitute parameter packs into each argument in the
26385                  TREE_LIST.  */
26386               in_base_initializer = 1;
26387               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
26388                 {
26389                   tree expanded_exprs;
26390
26391                   /* Expand the argument.  */
26392                   tree value;
26393                   if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
26394                     value = TREE_VALUE (arg);
26395                   else
26396                     {
26397                       value = expr;
26398                       SET_PACK_EXPANSION_PATTERN (value, TREE_VALUE (arg));
26399                     }
26400                   expanded_exprs
26401                     = tsubst_pack_expansion (value, argvec,
26402                                              tf_warning_or_error,
26403                                              NULL_TREE);
26404                   if (expanded_exprs == error_mark_node)
26405                     continue;
26406
26407                   /* Prepend each of the expanded expressions to the
26408                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
26409                   for (i = 0; i < len; i++)
26410                     if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
26411                       for (int j = 0; j < TREE_VEC_LENGTH (expanded_exprs); j++)
26412                         TREE_VEC_ELT (expanded_arguments, i)
26413                           = tree_cons (NULL_TREE,
26414                                        TREE_VEC_ELT (expanded_exprs, j),
26415                                        TREE_VEC_ELT (expanded_arguments, i));
26416                     else
26417                       TREE_VEC_ELT (expanded_arguments, i)
26418                         = tree_cons (NULL_TREE,
26419                                      TREE_VEC_ELT (expanded_exprs, i),
26420                                      TREE_VEC_ELT (expanded_arguments, i));
26421                 }
26422               in_base_initializer = 0;
26423
26424               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
26425                  since we built them backwards.  */
26426               for (i = 0; i < len; i++)
26427                 {
26428                   TREE_VEC_ELT (expanded_arguments, i) =
26429                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
26430                 }
26431             }
26432         }
26433
26434       for (i = 0; i < len; ++i)
26435         {
26436           if (expanded_bases)
26437             {
26438               decl = TREE_VEC_ELT (expanded_bases, i);
26439               decl = expand_member_init (decl);
26440               init = TREE_VEC_ELT (expanded_arguments, i);
26441             }
26442           else
26443             {
26444               tree tmp;
26445               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
26446                                   tf_warning_or_error, NULL_TREE);
26447
26448               decl = expand_member_init (decl);
26449               if (decl && !DECL_P (decl))
26450                 in_base_initializer = 1;
26451
26452               init = TREE_VALUE (t);
26453               tmp = init;
26454               if (init != void_type_node)
26455                 init = tsubst_expr (init, argvec,
26456                                     tf_warning_or_error, NULL_TREE,
26457                                     /*integral_constant_expression_p=*/false);
26458               if (init == NULL_TREE && tmp != NULL_TREE)
26459                 /* If we had an initializer but it instantiated to nothing,
26460                    value-initialize the object.  This will only occur when
26461                    the initializer was a pack expansion where the parameter
26462                    packs used in that expansion were of length zero.  */
26463                 init = void_type_node;
26464               in_base_initializer = 0;
26465             }
26466
26467           if (target_ctor != error_mark_node
26468               && init != error_mark_node)
26469             {
26470               error ("mem-initializer for %qD follows constructor delegation",
26471                      decl);
26472               return inits;
26473             }
26474           /* Look for a target constructor. */
26475           if (init != error_mark_node
26476               && decl && CLASS_TYPE_P (decl)
26477               && same_type_p (decl, current_class_type))
26478             {
26479               maybe_warn_cpp0x (CPP0X_DELEGATING_CTORS);
26480               if (inits)
26481                 {
26482                   error ("constructor delegation follows mem-initializer for %qD",
26483                          TREE_PURPOSE (inits));
26484                   continue;
26485                 }
26486               target_ctor = init;
26487             }
26488
26489           if (decl)
26490             {
26491               init = build_tree_list (decl, init);
26492               /* Carry over the dummy TREE_TYPE node containing the source
26493                  location.  */
26494               TREE_TYPE (init) = TREE_TYPE (t);
26495               TREE_CHAIN (init) = inits;
26496               inits = init;
26497             }
26498         }
26499     }
26500   return inits;
26501 }
26502
26503 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
26504
26505 static void
26506 set_current_access_from_decl (tree decl)
26507 {
26508   if (TREE_PRIVATE (decl))
26509     current_access_specifier = access_private_node;
26510   else if (TREE_PROTECTED (decl))
26511     current_access_specifier = access_protected_node;
26512   else
26513     current_access_specifier = access_public_node;
26514 }
26515
26516 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
26517    is the instantiation (which should have been created with
26518    start_enum) and ARGS are the template arguments to use.  */
26519
26520 static void
26521 tsubst_enum (tree tag, tree newtag, tree args)
26522 {
26523   tree e;
26524
26525   if (SCOPED_ENUM_P (newtag))
26526     begin_scope (sk_scoped_enum, newtag);
26527
26528   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
26529     {
26530       tree value;
26531       tree decl;
26532
26533       decl = TREE_VALUE (e);
26534       /* Note that in a template enum, the TREE_VALUE is the
26535          CONST_DECL, not the corresponding INTEGER_CST.  */
26536       value = tsubst_expr (DECL_INITIAL (decl),
26537                            args, tf_warning_or_error, NULL_TREE,
26538                            /*integral_constant_expression_p=*/true);
26539
26540       /* Give this enumeration constant the correct access.  */
26541       set_current_access_from_decl (decl);
26542
26543       /* Actually build the enumerator itself.  Here we're assuming that
26544          enumerators can't have dependent attributes.  */
26545       build_enumerator (DECL_NAME (decl), value, newtag,
26546                         DECL_ATTRIBUTES (decl), DECL_SOURCE_LOCATION (decl));
26547     }
26548
26549   if (SCOPED_ENUM_P (newtag))
26550     finish_scope ();
26551
26552   finish_enum_value_list (newtag);
26553   finish_enum (newtag);
26554
26555   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
26556     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
26557 }
26558
26559 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
26560    its type -- but without substituting the innermost set of template
26561    arguments.  So, innermost set of template parameters will appear in
26562    the type.  */
26563
26564 tree
26565 get_mostly_instantiated_function_type (tree decl)
26566 {
26567   /* For a function, DECL_TI_TEMPLATE is partially instantiated.  */
26568   return TREE_TYPE (DECL_TI_TEMPLATE (decl));
26569 }
26570
26571 /* Return truthvalue if we're processing a template different from
26572    the last one involved in diagnostics.  */
26573 bool
26574 problematic_instantiation_changed (void)
26575 {
26576   return current_tinst_level != last_error_tinst_level;
26577 }
26578
26579 /* Remember current template involved in diagnostics.  */
26580 void
26581 record_last_problematic_instantiation (void)
26582 {
26583   set_refcount_ptr (last_error_tinst_level, current_tinst_level);
26584 }
26585
26586 struct tinst_level *
26587 current_instantiation (void)
26588 {
26589   return current_tinst_level;
26590 }
26591
26592 /* Return TRUE if current_function_decl is being instantiated, false
26593    otherwise.  */
26594
26595 bool
26596 instantiating_current_function_p (void)
26597 {
26598   return (current_instantiation ()
26599           && (current_instantiation ()->maybe_get_node ()
26600               == current_function_decl));
26601 }
26602
26603 /* [temp.param] Check that template non-type parm TYPE is of an allowable
26604    type.  Return false for ok, true for disallowed.  Issue error and
26605    inform messages under control of COMPLAIN.  */
26606
26607 static bool
26608 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
26609 {
26610   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
26611     return false;
26612   else if (TYPE_PTR_P (type))
26613     return false;
26614   else if (TYPE_REF_P (type)
26615            && !TYPE_REF_IS_RVALUE (type))
26616     return false;
26617   else if (TYPE_PTRMEM_P (type))
26618     return false;
26619   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
26620     {
26621       if (CLASS_PLACEHOLDER_TEMPLATE (type) && cxx_dialect < cxx20)
26622         {
26623           if (complain & tf_error)
26624             error ("non-type template parameters of deduced class type only "
26625                    "available with %<-std=c++20%> or %<-std=gnu++20%>");
26626           return true;
26627         }
26628       return false;
26629     }
26630   else if (TREE_CODE (type) == TYPENAME_TYPE)
26631     return false;
26632   else if (TREE_CODE (type) == DECLTYPE_TYPE)
26633     return false;
26634   else if (TREE_CODE (type) == NULLPTR_TYPE)
26635     return false;
26636   /* A bound template template parm could later be instantiated to have a valid
26637      nontype parm type via an alias template.  */
26638   else if (cxx_dialect >= cxx11
26639            && TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
26640     return false;
26641   else if (VOID_TYPE_P (type))
26642     /* Fall through.  */;
26643   else if (cxx_dialect >= cxx20)
26644     {
26645       if (dependent_type_p (type))
26646         return false;
26647       if (!complete_type_or_maybe_complain (type, NULL_TREE, complain))
26648         return true;
26649       if (structural_type_p (type))
26650         return false;
26651       if (complain & tf_error)
26652         {
26653           auto_diagnostic_group d;
26654           error ("%qT is not a valid type for a template non-type "
26655                  "parameter because it is not structural", type);
26656           structural_type_p (type, true);
26657         }
26658       return true;
26659     }
26660   else if (CLASS_TYPE_P (type))
26661     {
26662       if (complain & tf_error)
26663         error ("non-type template parameters of class type only available "
26664                "with %<-std=c++20%> or %<-std=gnu++20%>");
26665       return true;
26666     }
26667
26668   if (complain & tf_error)
26669     {
26670       if (type == error_mark_node)
26671         inform (input_location, "invalid template non-type parameter");
26672       else
26673         error ("%q#T is not a valid type for a template non-type parameter",
26674                type);
26675     }
26676   return true;
26677 }
26678
26679 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
26680    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
26681
26682 static bool
26683 dependent_type_p_r (tree type)
26684 {
26685   tree scope;
26686
26687   /* [temp.dep.type]
26688
26689      A type is dependent if it is:
26690
26691      -- a template parameter. Template template parameters are types
26692         for us (since TYPE_P holds true for them) so we handle
26693         them here.  */
26694   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
26695       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
26696     return true;
26697   /* -- a qualified-id with a nested-name-specifier which contains a
26698         class-name that names a dependent type or whose unqualified-id
26699         names a dependent type.  */
26700   if (TREE_CODE (type) == TYPENAME_TYPE)
26701     return true;
26702
26703   /* An alias template specialization can be dependent even if the
26704      resulting type is not.  */
26705   if (dependent_alias_template_spec_p (type, nt_transparent))
26706     return true;
26707
26708   /* -- a cv-qualified type where the cv-unqualified type is
26709         dependent.
26710      No code is necessary for this bullet; the code below handles
26711      cv-qualified types, and we don't want to strip aliases with
26712      TYPE_MAIN_VARIANT because of DR 1558.  */
26713   /* -- a compound type constructed from any dependent type.  */
26714   if (TYPE_PTRMEM_P (type))
26715     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
26716             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
26717                                            (type)));
26718   else if (INDIRECT_TYPE_P (type))
26719     return dependent_type_p (TREE_TYPE (type));
26720   else if (FUNC_OR_METHOD_TYPE_P (type))
26721     {
26722       tree arg_type;
26723
26724       if (dependent_type_p (TREE_TYPE (type)))
26725         return true;
26726       for (arg_type = TYPE_ARG_TYPES (type);
26727            arg_type;
26728            arg_type = TREE_CHAIN (arg_type))
26729         if (dependent_type_p (TREE_VALUE (arg_type)))
26730           return true;
26731       if (cxx_dialect >= cxx17)
26732         /* A value-dependent noexcept-specifier makes the type dependent.  */
26733         if (tree spec = TYPE_RAISES_EXCEPTIONS (type))
26734           if (tree noex = TREE_PURPOSE (spec))
26735             /* Treat DEFERRED_NOEXCEPT as non-dependent, since it doesn't
26736                affect overload resolution and treating it as dependent breaks
26737                things.  Same for an unparsed noexcept expression.  */
26738             if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
26739                 && TREE_CODE (noex) != DEFERRED_PARSE
26740                 && value_dependent_expression_p (noex))
26741               return true;
26742       return false;
26743     }
26744   /* -- an array type constructed from any dependent type or whose
26745         size is specified by a constant expression that is
26746         value-dependent.
26747
26748         We checked for type- and value-dependence of the bounds in
26749         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
26750   if (TREE_CODE (type) == ARRAY_TYPE)
26751     {
26752       if (TYPE_DOMAIN (type)
26753           && dependent_type_p (TYPE_DOMAIN (type)))
26754         return true;
26755       return dependent_type_p (TREE_TYPE (type));
26756     }
26757
26758   /* -- a template-id in which either the template name is a template
26759      parameter ...  */
26760   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
26761     return true;
26762   /* ... or any of the template arguments is a dependent type or
26763         an expression that is type-dependent or value-dependent.  */
26764   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
26765            && (any_dependent_template_arguments_p
26766                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
26767     return true;
26768
26769   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
26770      dependent; if the argument of the `typeof' expression is not
26771      type-dependent, then it should already been have resolved.  */
26772   if (TREE_CODE (type) == TYPEOF_TYPE
26773       || TREE_CODE (type) == DECLTYPE_TYPE
26774       || TREE_CODE (type) == UNDERLYING_TYPE)
26775     return true;
26776
26777   /* A template argument pack is dependent if any of its packed
26778      arguments are.  */
26779   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
26780     {
26781       tree args = ARGUMENT_PACK_ARGS (type);
26782       int i, len = TREE_VEC_LENGTH (args);
26783       for (i = 0; i < len; ++i)
26784         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
26785           return true;
26786     }
26787
26788   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
26789      be template parameters.  */
26790   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
26791     return true;
26792
26793   if (any_dependent_type_attributes_p (TYPE_ATTRIBUTES (type)))
26794     return true;
26795
26796   /* The standard does not specifically mention types that are local
26797      to template functions or local classes, but they should be
26798      considered dependent too.  For example:
26799
26800        template <int I> void f() {
26801          enum E { a = I };
26802          S<sizeof (E)> s;
26803        }
26804
26805      The size of `E' cannot be known until the value of `I' has been
26806      determined.  Therefore, `E' must be considered dependent.  */
26807   scope = TYPE_CONTEXT (type);
26808   if (scope && TYPE_P (scope))
26809     return dependent_type_p (scope);
26810   /* Don't use type_dependent_expression_p here, as it can lead
26811      to infinite recursion trying to determine whether a lambda
26812      nested in a lambda is dependent (c++/47687).  */
26813   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
26814            && DECL_LANG_SPECIFIC (scope)
26815            && DECL_TEMPLATE_INFO (scope)
26816            && (any_dependent_template_arguments_p
26817                (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
26818     return true;
26819
26820   /* Other types are non-dependent.  */
26821   return false;
26822 }
26823
26824 /* Returns TRUE if TYPE is dependent, in the sense of
26825    [temp.dep.type].  Note that a NULL type is considered dependent.  */
26826
26827 bool
26828 dependent_type_p (tree type)
26829 {
26830   /* If there are no template parameters in scope, then there can't be
26831      any dependent types.  */
26832   if (!processing_template_decl)
26833     {
26834       /* If we are not processing a template, then nobody should be
26835          providing us with a dependent type.  */
26836       gcc_assert (type);
26837       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
26838       return false;
26839     }
26840
26841   /* If the type is NULL, we have not computed a type for the entity
26842      in question; in that case, the type is dependent.  */
26843   if (!type)
26844     return true;
26845
26846   /* Erroneous types can be considered non-dependent.  */
26847   if (type == error_mark_node)
26848     return false;
26849
26850   /* If we have not already computed the appropriate value for TYPE,
26851      do so now.  */
26852   if (!TYPE_DEPENDENT_P_VALID (type))
26853     {
26854       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
26855       TYPE_DEPENDENT_P_VALID (type) = 1;
26856     }
26857
26858   return TYPE_DEPENDENT_P (type);
26859 }
26860
26861 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
26862    lookup.  In other words, a dependent type that is not the current
26863    instantiation.  */
26864
26865 bool
26866 dependent_scope_p (tree scope)
26867 {
26868   return (scope && TYPE_P (scope) && dependent_type_p (scope)
26869           && !currently_open_class (scope));
26870 }
26871
26872 /* T is a SCOPE_REF.  Return whether it represents a non-static member of
26873    an unknown base of 'this' (and is therefore instantiation-dependent).  */
26874
26875 static bool
26876 unknown_base_ref_p (tree t)
26877 {
26878   if (!current_class_ptr)
26879     return false;
26880
26881   tree mem = TREE_OPERAND (t, 1);
26882   if (shared_member_p (mem))
26883     return false;
26884
26885   tree cur = current_nonlambda_class_type ();
26886   if (!any_dependent_bases_p (cur))
26887     return false;
26888
26889   tree ctx = TREE_OPERAND (t, 0);
26890   if (DERIVED_FROM_P (ctx, cur))
26891     return false;
26892
26893   return true;
26894 }
26895
26896 /* T is a SCOPE_REF; return whether we need to consider it
26897     instantiation-dependent so that we can check access at instantiation
26898     time even though we know which member it resolves to.  */
26899
26900 static bool
26901 instantiation_dependent_scope_ref_p (tree t)
26902 {
26903   if (DECL_P (TREE_OPERAND (t, 1))
26904       && CLASS_TYPE_P (TREE_OPERAND (t, 0))
26905       && !unknown_base_ref_p (t)
26906       && accessible_in_template_p (TREE_OPERAND (t, 0),
26907                                    TREE_OPERAND (t, 1)))
26908     return false;
26909   else
26910     return true;
26911 }
26912
26913 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
26914    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
26915    expression.  */
26916
26917 /* Note that this predicate is not appropriate for general expressions;
26918    only constant expressions (that satisfy potential_constant_expression)
26919    can be tested for value dependence.  */
26920
26921 bool
26922 value_dependent_expression_p (tree expression)
26923 {
26924   if (!processing_template_decl || expression == NULL_TREE)
26925     return false;
26926
26927   /* A type-dependent expression is also value-dependent.  */
26928   if (type_dependent_expression_p (expression))
26929     return true;
26930
26931   switch (TREE_CODE (expression))
26932     {
26933     case BASELINK:
26934       /* A dependent member function of the current instantiation.  */
26935       return dependent_type_p (BINFO_TYPE (BASELINK_BINFO (expression)));
26936
26937     case FUNCTION_DECL:
26938       /* A dependent member function of the current instantiation.  */
26939       if (DECL_CLASS_SCOPE_P (expression)
26940           && dependent_type_p (DECL_CONTEXT (expression)))
26941         return true;
26942       break;
26943
26944     case IDENTIFIER_NODE:
26945       /* A name that has not been looked up -- must be dependent.  */
26946       return true;
26947
26948     case TEMPLATE_PARM_INDEX:
26949       /* A non-type template parm.  */
26950       return true;
26951
26952     case CONST_DECL:
26953       /* A non-type template parm.  */
26954       if (DECL_TEMPLATE_PARM_P (expression))
26955         return true;
26956       return value_dependent_expression_p (DECL_INITIAL (expression));
26957
26958     case VAR_DECL:
26959        /* A constant with literal type and is initialized
26960           with an expression that is value-dependent.  */
26961       if (DECL_DEPENDENT_INIT_P (expression)
26962           /* FIXME cp_finish_decl doesn't fold reference initializers.  */
26963           || TYPE_REF_P (TREE_TYPE (expression)))
26964         return true;
26965       if (DECL_HAS_VALUE_EXPR_P (expression))
26966         {
26967           tree value_expr = DECL_VALUE_EXPR (expression);
26968           if (value_dependent_expression_p (value_expr)
26969               /* __PRETTY_FUNCTION__ inside a template function is dependent
26970                  on the name of the function.  */
26971               || (DECL_PRETTY_FUNCTION_P (expression)
26972                   /* It might be used in a template, but not a template
26973                      function, in which case its DECL_VALUE_EXPR will be
26974                      "top level".  */
26975                   && value_expr == error_mark_node))
26976             return true;
26977         }
26978       return false;
26979
26980     case DYNAMIC_CAST_EXPR:
26981     case STATIC_CAST_EXPR:
26982     case CONST_CAST_EXPR:
26983     case REINTERPRET_CAST_EXPR:
26984     case CAST_EXPR:
26985     case IMPLICIT_CONV_EXPR:
26986       /* These expressions are value-dependent if the type to which
26987          the cast occurs is dependent or the expression being casted
26988          is value-dependent.  */
26989       {
26990         tree type = TREE_TYPE (expression);
26991
26992         if (dependent_type_p (type))
26993           return true;
26994
26995         /* A functional cast has a list of operands.  */
26996         expression = TREE_OPERAND (expression, 0);
26997         if (!expression)
26998           {
26999             /* If there are no operands, it must be an expression such
27000                as "int()". This should not happen for aggregate types
27001                because it would form non-constant expressions.  */
27002             gcc_assert (cxx_dialect >= cxx11
27003                         || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
27004
27005             return false;
27006           }
27007
27008         if (TREE_CODE (expression) == TREE_LIST)
27009           return any_value_dependent_elements_p (expression);
27010
27011         return value_dependent_expression_p (expression);
27012       }
27013
27014     case SIZEOF_EXPR:
27015       if (SIZEOF_EXPR_TYPE_P (expression))
27016         return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
27017       /* FALLTHRU */
27018     case ALIGNOF_EXPR:
27019     case TYPEID_EXPR:
27020       /* A `sizeof' expression is value-dependent if the operand is
27021          type-dependent or is a pack expansion.  */
27022       expression = TREE_OPERAND (expression, 0);
27023       if (PACK_EXPANSION_P (expression))
27024         return true;
27025       else if (TYPE_P (expression))
27026         return dependent_type_p (expression);
27027       return instantiation_dependent_uneval_expression_p (expression);
27028
27029     case AT_ENCODE_EXPR:
27030       /* An 'encode' expression is value-dependent if the operand is
27031          type-dependent.  */
27032       expression = TREE_OPERAND (expression, 0);
27033       return dependent_type_p (expression);
27034
27035     case NOEXCEPT_EXPR:
27036       expression = TREE_OPERAND (expression, 0);
27037       return instantiation_dependent_uneval_expression_p (expression);
27038
27039     case SCOPE_REF:
27040       /* All instantiation-dependent expressions should also be considered
27041          value-dependent.  */
27042       return instantiation_dependent_scope_ref_p (expression);
27043
27044     case COMPONENT_REF:
27045       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
27046               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
27047
27048     case NONTYPE_ARGUMENT_PACK:
27049       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
27050          is value-dependent.  */
27051       {
27052         tree values = ARGUMENT_PACK_ARGS (expression);
27053         int i, len = TREE_VEC_LENGTH (values);
27054
27055         for (i = 0; i < len; ++i)
27056           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
27057             return true;
27058
27059         return false;
27060       }
27061
27062     case TRAIT_EXPR:
27063       {
27064         tree type2 = TRAIT_EXPR_TYPE2 (expression);
27065
27066         if (dependent_type_p (TRAIT_EXPR_TYPE1 (expression)))
27067           return true;
27068
27069         if (!type2)
27070           return false;
27071
27072         if (TREE_CODE (type2) != TREE_LIST)
27073           return dependent_type_p (type2);
27074
27075         for (; type2; type2 = TREE_CHAIN (type2))
27076           if (dependent_type_p (TREE_VALUE (type2)))
27077             return true;
27078
27079         return false;
27080       }
27081
27082     case MODOP_EXPR:
27083       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
27084               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
27085
27086     case ARRAY_REF:
27087       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
27088               || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
27089
27090     case ADDR_EXPR:
27091       {
27092         tree op = TREE_OPERAND (expression, 0);
27093         return (value_dependent_expression_p (op)
27094                 || has_value_dependent_address (op));
27095       }
27096
27097     case REQUIRES_EXPR:
27098       /* Treat all requires-expressions as value-dependent so
27099          we don't try to fold them.  */
27100       return true;
27101
27102     case TYPE_REQ:
27103       return dependent_type_p (TREE_OPERAND (expression, 0));
27104
27105     case CALL_EXPR:
27106       {
27107         if (value_dependent_expression_p (CALL_EXPR_FN (expression)))
27108           return true;
27109         tree fn = get_callee_fndecl (expression);
27110         int i, nargs;
27111         nargs = call_expr_nargs (expression);
27112         for (i = 0; i < nargs; ++i)
27113           {
27114             tree op = CALL_EXPR_ARG (expression, i);
27115             /* In a call to a constexpr member function, look through the
27116                implicit ADDR_EXPR on the object argument so that it doesn't
27117                cause the call to be considered value-dependent.  We also
27118                look through it in potential_constant_expression.  */
27119             if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
27120                 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
27121                 && TREE_CODE (op) == ADDR_EXPR)
27122               op = TREE_OPERAND (op, 0);
27123             if (value_dependent_expression_p (op))
27124               return true;
27125           }
27126         return false;
27127       }
27128
27129     case TEMPLATE_ID_EXPR:
27130       return concept_definition_p (TREE_OPERAND (expression, 0));
27131
27132     case CONSTRUCTOR:
27133       {
27134         unsigned ix;
27135         tree val;
27136         if (dependent_type_p (TREE_TYPE (expression)))
27137           return true;
27138         FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
27139           if (value_dependent_expression_p (val))
27140             return true;
27141         return false;
27142       }
27143
27144     case STMT_EXPR:
27145       /* Treat a GNU statement expression as dependent to avoid crashing
27146          under instantiate_non_dependent_expr; it can't be constant.  */
27147       return true;
27148
27149     default:
27150       /* A constant expression is value-dependent if any subexpression is
27151          value-dependent.  */
27152       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
27153         {
27154         case tcc_reference:
27155         case tcc_unary:
27156         case tcc_comparison:
27157         case tcc_binary:
27158         case tcc_expression:
27159         case tcc_vl_exp:
27160           {
27161             int i, len = cp_tree_operand_length (expression);
27162
27163             for (i = 0; i < len; i++)
27164               {
27165                 tree t = TREE_OPERAND (expression, i);
27166
27167                 /* In some cases, some of the operands may be missing.
27168                    (For example, in the case of PREDECREMENT_EXPR, the
27169                    amount to increment by may be missing.)  That doesn't
27170                    make the expression dependent.  */
27171                 if (t && value_dependent_expression_p (t))
27172                   return true;
27173               }
27174           }
27175           break;
27176         default:
27177           break;
27178         }
27179       break;
27180     }
27181
27182   /* The expression is not value-dependent.  */
27183   return false;
27184 }
27185
27186 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
27187    [temp.dep.expr].  Note that an expression with no type is
27188    considered dependent.  Other parts of the compiler arrange for an
27189    expression with type-dependent subexpressions to have no type, so
27190    this function doesn't have to be fully recursive.  */
27191
27192 bool
27193 type_dependent_expression_p (tree expression)
27194 {
27195   if (!processing_template_decl)
27196     return false;
27197
27198   if (expression == NULL_TREE || expression == error_mark_node)
27199     return false;
27200
27201   STRIP_ANY_LOCATION_WRAPPER (expression);
27202
27203   /* An unresolved name is always dependent.  */
27204   if (identifier_p (expression)
27205       || TREE_CODE (expression) == USING_DECL
27206       || TREE_CODE (expression) == WILDCARD_DECL)
27207     return true;
27208
27209   /* A lambda-expression in template context is dependent.  dependent_type_p is
27210      true for a lambda in the scope of a class or function template, but that
27211      doesn't cover all template contexts, like a default template argument.  */
27212   if (TREE_CODE (expression) == LAMBDA_EXPR)
27213     return true;
27214
27215   /* A fold expression is type-dependent. */
27216   if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
27217       || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
27218       || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
27219       || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
27220     return true;
27221
27222   /* Some expression forms are never type-dependent.  */
27223   if (TREE_CODE (expression) == SIZEOF_EXPR
27224       || TREE_CODE (expression) == ALIGNOF_EXPR
27225       || TREE_CODE (expression) == AT_ENCODE_EXPR
27226       || TREE_CODE (expression) == NOEXCEPT_EXPR
27227       || TREE_CODE (expression) == TRAIT_EXPR
27228       || TREE_CODE (expression) == TYPEID_EXPR
27229       || TREE_CODE (expression) == DELETE_EXPR
27230       || TREE_CODE (expression) == VEC_DELETE_EXPR
27231       || TREE_CODE (expression) == THROW_EXPR
27232       || TREE_CODE (expression) == REQUIRES_EXPR)
27233     return false;
27234
27235   /* The types of these expressions depends only on the type to which
27236      the cast occurs.  */
27237   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
27238       || TREE_CODE (expression) == STATIC_CAST_EXPR
27239       || TREE_CODE (expression) == CONST_CAST_EXPR
27240       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
27241       || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
27242       || TREE_CODE (expression) == CAST_EXPR)
27243     return dependent_type_p (TREE_TYPE (expression));
27244
27245   /* The types of these expressions depends only on the type created
27246      by the expression.  */
27247   if (TREE_CODE (expression) == NEW_EXPR
27248       || TREE_CODE (expression) == VEC_NEW_EXPR)
27249     {
27250       /* For NEW_EXPR tree nodes created inside a template, either
27251          the object type itself or a TREE_LIST may appear as the
27252          operand 1.  */
27253       tree type = TREE_OPERAND (expression, 1);
27254       if (TREE_CODE (type) == TREE_LIST)
27255         /* This is an array type.  We need to check array dimensions
27256            as well.  */
27257         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
27258                || value_dependent_expression_p
27259                     (TREE_OPERAND (TREE_VALUE (type), 1));
27260       /* Array type whose dimension has to be deduced.  */
27261       else if (TREE_CODE (type) == ARRAY_TYPE
27262                && TREE_OPERAND (expression, 2) == NULL_TREE)
27263         return true;
27264       else
27265         return dependent_type_p (type);
27266     }
27267
27268   if (TREE_CODE (expression) == SCOPE_REF)
27269     {
27270       tree scope = TREE_OPERAND (expression, 0);
27271       tree name = TREE_OPERAND (expression, 1);
27272
27273       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
27274          contains an identifier associated by name lookup with one or more
27275          declarations declared with a dependent type, or...a
27276          nested-name-specifier or qualified-id that names a member of an
27277          unknown specialization.  */
27278       return (type_dependent_expression_p (name)
27279               || dependent_scope_p (scope));
27280     }
27281
27282   if (TREE_CODE (expression) == TEMPLATE_DECL
27283       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
27284     return uses_outer_template_parms (expression);
27285
27286   if (TREE_CODE (expression) == STMT_EXPR)
27287     expression = stmt_expr_value_expr (expression);
27288
27289   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
27290     {
27291       tree elt;
27292       unsigned i;
27293
27294       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
27295         {
27296           if (type_dependent_expression_p (elt))
27297             return true;
27298         }
27299       return false;
27300     }
27301
27302   /* A static data member of the current instantiation with incomplete
27303      array type is type-dependent, as the definition and specializations
27304      can have different bounds.  */
27305   if (VAR_P (expression)
27306       && DECL_CLASS_SCOPE_P (expression)
27307       && dependent_type_p (DECL_CONTEXT (expression))
27308       && VAR_HAD_UNKNOWN_BOUND (expression))
27309     return true;
27310
27311   /* An array of unknown bound depending on a variadic parameter, eg:
27312
27313      template<typename... Args>
27314        void foo (Args... args)
27315        {
27316          int arr[] = { args... };
27317        }
27318
27319      template<int... vals>
27320        void bar ()
27321        {
27322          int arr[] = { vals... };
27323        }
27324
27325      If the array has no length and has an initializer, it must be that
27326      we couldn't determine its length in cp_complete_array_type because
27327      it is dependent.  */
27328   if (VAR_P (expression)
27329       && TREE_TYPE (expression) != NULL_TREE
27330       && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
27331       && !TYPE_DOMAIN (TREE_TYPE (expression))
27332       && DECL_INITIAL (expression))
27333    return true;
27334
27335   /* A function or variable template-id is type-dependent if it has any
27336      dependent template arguments.  */
27337   if (VAR_OR_FUNCTION_DECL_P (expression)
27338       && DECL_LANG_SPECIFIC (expression)
27339       && DECL_TEMPLATE_INFO (expression))
27340     {
27341       /* Consider the innermost template arguments, since those are the ones
27342          that come from the template-id; the template arguments for the
27343          enclosing class do not make it type-dependent unless they are used in
27344          the type of the decl.  */
27345       if (instantiates_primary_template_p (expression)
27346           && (any_dependent_template_arguments_p
27347               (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
27348         return true;
27349     }
27350
27351   /* Otherwise, if the function decl isn't from a dependent scope, it can't be
27352      type-dependent.  Checking this is important for functions with auto return
27353      type, which looks like a dependent type.  */
27354   if (TREE_CODE (expression) == FUNCTION_DECL
27355       && !(DECL_CLASS_SCOPE_P (expression)
27356            && dependent_type_p (DECL_CONTEXT (expression)))
27357       && !(DECL_LANG_SPECIFIC (expression)
27358            && DECL_UNIQUE_FRIEND_P (expression)
27359            && (!DECL_FRIEND_CONTEXT (expression)
27360                || dependent_type_p (DECL_FRIEND_CONTEXT (expression))))
27361       && !DECL_LOCAL_DECL_P (expression))
27362     {
27363       gcc_assert (!dependent_type_p (TREE_TYPE (expression))
27364                   || undeduced_auto_decl (expression));
27365       return false;
27366     }
27367
27368   /* Always dependent, on the number of arguments if nothing else.  */
27369   if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
27370     return true;
27371
27372   if (TREE_TYPE (expression) == unknown_type_node)
27373     {
27374       if (TREE_CODE (expression) == ADDR_EXPR)
27375         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
27376       if (TREE_CODE (expression) == COMPONENT_REF
27377           || TREE_CODE (expression) == OFFSET_REF)
27378         {
27379           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
27380             return true;
27381           expression = TREE_OPERAND (expression, 1);
27382           if (identifier_p (expression))
27383             return false;
27384         }
27385       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
27386       if (TREE_CODE (expression) == SCOPE_REF)
27387         return false;
27388
27389       /* CO_AWAIT/YIELD_EXPR with unknown type is always dependent.  */
27390       if (TREE_CODE (expression) == CO_AWAIT_EXPR
27391           || TREE_CODE (expression) == CO_YIELD_EXPR)
27392         return true;
27393
27394       if (BASELINK_P (expression))
27395         {
27396           if (BASELINK_OPTYPE (expression)
27397               && dependent_type_p (BASELINK_OPTYPE (expression)))
27398             return true;
27399           expression = BASELINK_FUNCTIONS (expression);
27400         }
27401
27402       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
27403         {
27404           if (any_dependent_template_arguments_p
27405               (TREE_OPERAND (expression, 1)))
27406             return true;
27407           expression = TREE_OPERAND (expression, 0);
27408           if (identifier_p (expression))
27409             return true;
27410         }
27411
27412       gcc_assert (OVL_P (expression));
27413
27414       for (lkp_iterator iter (expression); iter; ++iter)
27415         if (type_dependent_expression_p (*iter))
27416           return true;
27417
27418       return false;
27419     }
27420
27421   /* The type of a non-type template parm declared with a placeholder type
27422      depends on the corresponding template argument, even though
27423      placeholders are not normally considered dependent.  */
27424   if (TREE_CODE (expression) == TEMPLATE_PARM_INDEX
27425       && is_auto (TREE_TYPE (expression)))
27426     return true;
27427
27428   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
27429
27430   /* Dependent type attributes might not have made it from the decl to
27431      the type yet.  */
27432   if (DECL_P (expression)
27433       && any_dependent_type_attributes_p (DECL_ATTRIBUTES (expression)))
27434     return true;
27435
27436   return (dependent_type_p (TREE_TYPE (expression)));
27437 }
27438
27439 /* [temp.dep.expr]/5: A class member access expression (5.2.5) is
27440    type-dependent if the expression refers to a member of the current
27441    instantiation and the type of the referenced member is dependent, or the
27442    class member access expression refers to a member of an unknown
27443    specialization.
27444
27445    This function returns true if the OBJECT in such a class member access
27446    expression is of an unknown specialization.  */
27447
27448 bool
27449 type_dependent_object_expression_p (tree object)
27450 {
27451   /* An IDENTIFIER_NODE can sometimes have a TREE_TYPE, but it's still
27452      dependent.  */
27453   if (TREE_CODE (object) == IDENTIFIER_NODE)
27454     return true;
27455   tree scope = TREE_TYPE (object);
27456   return (!scope || dependent_scope_p (scope));
27457 }
27458
27459 /* walk_tree callback function for instantiation_dependent_expression_p,
27460    below.  Returns non-zero if a dependent subexpression is found.  */
27461
27462 static tree
27463 instantiation_dependent_r (tree *tp, int *walk_subtrees,
27464                            void * /*data*/)
27465 {
27466   if (TYPE_P (*tp))
27467     {
27468       /* We don't have to worry about decltype currently because decltype
27469          of an instantiation-dependent expr is a dependent type.  This
27470          might change depending on the resolution of DR 1172.  */
27471       *walk_subtrees = false;
27472       return NULL_TREE;
27473     }
27474   enum tree_code code = TREE_CODE (*tp);
27475   switch (code)
27476     {
27477       /* Don't treat an argument list as dependent just because it has no
27478          TREE_TYPE.  */
27479     case TREE_LIST:
27480     case TREE_VEC:
27481     case NONTYPE_ARGUMENT_PACK:
27482       return NULL_TREE;
27483
27484     case TEMPLATE_PARM_INDEX:
27485       if (dependent_type_p (TREE_TYPE (*tp)))
27486         return *tp;
27487       if (TEMPLATE_PARM_PARAMETER_PACK (*tp))
27488         return *tp;
27489       /* We'll check value-dependence separately.  */
27490       return NULL_TREE;
27491
27492       /* Handle expressions with type operands.  */
27493     case SIZEOF_EXPR:
27494     case ALIGNOF_EXPR:
27495     case TYPEID_EXPR:
27496     case AT_ENCODE_EXPR:
27497       {
27498         tree op = TREE_OPERAND (*tp, 0);
27499         if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
27500           op = TREE_TYPE (op);
27501         if (TYPE_P (op))
27502           {
27503             if (dependent_type_p (op))
27504               return *tp;
27505             else
27506               {
27507                 *walk_subtrees = false;
27508                 return NULL_TREE;
27509               }
27510           }
27511         break;
27512       }
27513
27514     case COMPONENT_REF:
27515       if (identifier_p (TREE_OPERAND (*tp, 1)))
27516         /* In a template, finish_class_member_access_expr creates a
27517            COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
27518            type-dependent, so that we can check access control at
27519            instantiation time (PR 42277).  See also Core issue 1273.  */
27520         return *tp;
27521       break;
27522
27523     case SCOPE_REF:
27524       if (instantiation_dependent_scope_ref_p (*tp))
27525         return *tp;
27526       else
27527         break;
27528
27529       /* Treat statement-expressions as dependent.  */
27530     case BIND_EXPR:
27531       return *tp;
27532
27533       /* Treat requires-expressions as dependent. */
27534     case REQUIRES_EXPR:
27535       return *tp;
27536
27537     case CALL_EXPR:
27538       /* Treat concept checks as dependent. */
27539       if (concept_check_p (*tp))
27540         return *tp;
27541       break;
27542
27543     case TEMPLATE_ID_EXPR:
27544       /* Treat concept checks as dependent.  */
27545       if (concept_check_p (*tp))
27546         return *tp;
27547       break;
27548
27549     case CONSTRUCTOR:
27550       if (CONSTRUCTOR_IS_DEPENDENT (*tp))
27551         return *tp;
27552       break;
27553
27554     default:
27555       break;
27556     }
27557
27558   if (type_dependent_expression_p (*tp))
27559     return *tp;
27560   else
27561     return NULL_TREE;
27562 }
27563
27564 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
27565    sense defined by the ABI:
27566
27567    "An expression is instantiation-dependent if it is type-dependent
27568    or value-dependent, or it has a subexpression that is type-dependent
27569    or value-dependent."
27570
27571    Except don't actually check value-dependence for unevaluated expressions,
27572    because in sizeof(i) we don't care about the value of i.  Checking
27573    type-dependence will in turn check value-dependence of array bounds/template
27574    arguments as needed.  */
27575
27576 bool
27577 instantiation_dependent_uneval_expression_p (tree expression)
27578 {
27579   tree result;
27580
27581   if (!processing_template_decl)
27582     return false;
27583
27584   if (expression == error_mark_node)
27585     return false;
27586
27587   result = cp_walk_tree_without_duplicates (&expression,
27588                                             instantiation_dependent_r, NULL);
27589   return result != NULL_TREE;
27590 }
27591
27592 /* As above, but also check value-dependence of the expression as a whole.  */
27593
27594 bool
27595 instantiation_dependent_expression_p (tree expression)
27596 {
27597   return (instantiation_dependent_uneval_expression_p (expression)
27598           || (processing_template_decl
27599               && potential_constant_expression (expression)
27600               && value_dependent_expression_p (expression)));
27601 }
27602
27603 /* Like type_dependent_expression_p, but it also works while not processing
27604    a template definition, i.e. during substitution or mangling.  */
27605
27606 bool
27607 type_dependent_expression_p_push (tree expr)
27608 {
27609   bool b;
27610   ++processing_template_decl;
27611   b = type_dependent_expression_p (expr);
27612   --processing_template_decl;
27613   return b;
27614 }
27615
27616 /* Returns TRUE if ARGS contains a type-dependent expression.  */
27617
27618 bool
27619 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
27620 {
27621   unsigned int i;
27622   tree arg;
27623
27624   FOR_EACH_VEC_SAFE_ELT (args, i, arg)
27625     {
27626       if (type_dependent_expression_p (arg))
27627         return true;
27628     }
27629   return false;
27630 }
27631
27632 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
27633    expressions) contains any type-dependent expressions.  */
27634
27635 bool
27636 any_type_dependent_elements_p (const_tree list)
27637 {
27638   for (; list; list = TREE_CHAIN (list))
27639     if (type_dependent_expression_p (TREE_VALUE (list)))
27640       return true;
27641
27642   return false;
27643 }
27644
27645 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
27646    expressions) contains any value-dependent expressions.  */
27647
27648 bool
27649 any_value_dependent_elements_p (const_tree list)
27650 {
27651   for (; list; list = TREE_CHAIN (list))
27652     if (value_dependent_expression_p (TREE_VALUE (list)))
27653       return true;
27654
27655   return false;
27656 }
27657
27658 /* Returns TRUE if the ARG (a template argument) is dependent.  */
27659
27660 bool
27661 dependent_template_arg_p (tree arg)
27662 {
27663   if (!processing_template_decl)
27664     return false;
27665
27666   /* Assume a template argument that was wrongly written by the user
27667      is dependent. This is consistent with what
27668      any_dependent_template_arguments_p [that calls this function]
27669      does.  */
27670   if (!arg || arg == error_mark_node)
27671     return true;
27672
27673   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
27674     arg = argument_pack_select_arg (arg);
27675
27676   if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
27677     return true;
27678   if (TREE_CODE (arg) == TEMPLATE_DECL)
27679     {
27680       if (DECL_TEMPLATE_PARM_P (arg))
27681         return true;
27682       /* A member template of a dependent class is not necessarily
27683          type-dependent, but it is a dependent template argument because it
27684          will be a member of an unknown specialization to that template.  */
27685       tree scope = CP_DECL_CONTEXT (arg);
27686       return TYPE_P (scope) && dependent_type_p (scope);
27687     }
27688   else if (ARGUMENT_PACK_P (arg))
27689     {
27690       tree args = ARGUMENT_PACK_ARGS (arg);
27691       int i, len = TREE_VEC_LENGTH (args);
27692       for (i = 0; i < len; ++i)
27693         {
27694           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
27695             return true;
27696         }
27697
27698       return false;
27699     }
27700   else if (TYPE_P (arg))
27701     return dependent_type_p (arg);
27702   else
27703     return value_dependent_expression_p (arg);
27704 }
27705
27706 /* Returns true if ARGS (a collection of template arguments) contains
27707    any types that require structural equality testing.  */
27708
27709 bool
27710 any_template_arguments_need_structural_equality_p (tree args)
27711 {
27712   int i;
27713   int j;
27714
27715   if (!args)
27716     return false;
27717   if (args == error_mark_node)
27718     return true;
27719
27720   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
27721     {
27722       tree level = TMPL_ARGS_LEVEL (args, i + 1);
27723       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
27724         {
27725           tree arg = TREE_VEC_ELT (level, j);
27726           tree packed_args = NULL_TREE;
27727           int k, len = 1;
27728
27729           if (ARGUMENT_PACK_P (arg))
27730             {
27731               /* Look inside the argument pack.  */
27732               packed_args = ARGUMENT_PACK_ARGS (arg);
27733               len = TREE_VEC_LENGTH (packed_args);
27734             }
27735
27736           for (k = 0; k < len; ++k)
27737             {
27738               if (packed_args)
27739                 arg = TREE_VEC_ELT (packed_args, k);
27740
27741               if (error_operand_p (arg))
27742                 return true;
27743               else if (TREE_CODE (arg) == TEMPLATE_DECL)
27744                 continue;
27745               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
27746                 return true;
27747               else if (!TYPE_P (arg) && TREE_TYPE (arg)
27748                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
27749                 return true;
27750             }
27751         }
27752     }
27753
27754   return false;
27755 }
27756
27757 /* Returns true if ARGS (a collection of template arguments) contains
27758    any dependent arguments.  */
27759
27760 bool
27761 any_dependent_template_arguments_p (const_tree args)
27762 {
27763   int i;
27764   int j;
27765
27766   if (!args)
27767     return false;
27768   if (args == error_mark_node)
27769     return true;
27770
27771   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
27772     {
27773       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
27774       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
27775         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
27776           return true;
27777     }
27778
27779   return false;
27780 }
27781
27782 /* Returns true if ARGS contains any errors.  */
27783
27784 bool
27785 any_erroneous_template_args_p (const_tree args)
27786 {
27787   int i;
27788   int j;
27789
27790   if (args == error_mark_node)
27791     return true;
27792
27793   if (args && TREE_CODE (args) != TREE_VEC)
27794     {
27795       if (tree ti = get_template_info (args))
27796         args = TI_ARGS (ti);
27797       else
27798         args = NULL_TREE;
27799     }
27800
27801   if (!args)
27802     return false;
27803
27804   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
27805     {
27806       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
27807       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
27808         if (error_operand_p (TREE_VEC_ELT (level, j)))
27809           return true;
27810     }
27811
27812   return false;
27813 }
27814
27815 /* Returns TRUE if the template TMPL is type-dependent.  */
27816
27817 bool
27818 dependent_template_p (tree tmpl)
27819 {
27820   if (TREE_CODE (tmpl) == OVERLOAD)
27821     {
27822       for (lkp_iterator iter (tmpl); iter; ++iter)
27823         if (dependent_template_p (*iter))
27824           return true;
27825       return false;
27826     }
27827
27828   /* Template template parameters are dependent.  */
27829   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
27830       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
27831     return true;
27832   /* So are names that have not been looked up.  */
27833   if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
27834     return true;
27835   return false;
27836 }
27837
27838 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
27839
27840 bool
27841 dependent_template_id_p (tree tmpl, tree args)
27842 {
27843   return (dependent_template_p (tmpl)
27844           || any_dependent_template_arguments_p (args));
27845 }
27846
27847 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
27848    are dependent.  */
27849
27850 bool
27851 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
27852 {
27853   int i;
27854
27855   if (!processing_template_decl)
27856     return false;
27857
27858   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
27859     {
27860       tree decl = TREE_VEC_ELT (declv, i);
27861       tree init = TREE_VEC_ELT (initv, i);
27862       tree cond = TREE_VEC_ELT (condv, i);
27863       tree incr = TREE_VEC_ELT (incrv, i);
27864
27865       if (type_dependent_expression_p (decl)
27866           || TREE_CODE (decl) == SCOPE_REF)
27867         return true;
27868
27869       if (init && type_dependent_expression_p (init))
27870         return true;
27871
27872       if (cond == global_namespace)
27873         return true;
27874
27875       if (type_dependent_expression_p (cond))
27876         return true;
27877
27878       if (COMPARISON_CLASS_P (cond)
27879           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
27880               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
27881         return true;
27882
27883       if (TREE_CODE (incr) == MODOP_EXPR)
27884         {
27885           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
27886               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
27887             return true;
27888         }
27889       else if (type_dependent_expression_p (incr))
27890         return true;
27891       else if (TREE_CODE (incr) == MODIFY_EXPR)
27892         {
27893           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
27894             return true;
27895           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
27896             {
27897               tree t = TREE_OPERAND (incr, 1);
27898               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
27899                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
27900                 return true;
27901
27902               /* If this loop has a class iterator with != comparison
27903                  with increment other than i++/++i/i--/--i, make sure the
27904                  increment is constant.  */
27905               if (CLASS_TYPE_P (TREE_TYPE (decl))
27906                   && TREE_CODE (cond) == NE_EXPR)
27907                 {
27908                   if (TREE_OPERAND (t, 0) == decl)
27909                     t = TREE_OPERAND (t, 1);
27910                   else
27911                     t = TREE_OPERAND (t, 0);
27912                   if (TREE_CODE (t) != INTEGER_CST)
27913                     return true;
27914                 }
27915             }
27916         }
27917     }
27918
27919   return false;
27920 }
27921
27922 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
27923    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
27924    no such TYPE can be found.  Note that this function peers inside
27925    uninstantiated templates and therefore should be used only in
27926    extremely limited situations.  ONLY_CURRENT_P restricts this
27927    peering to the currently open classes hierarchy (which is required
27928    when comparing types).  */
27929
27930 tree
27931 resolve_typename_type (tree type, bool only_current_p)
27932 {
27933   tree scope;
27934   tree name;
27935   tree decl;
27936   int quals;
27937   tree pushed_scope;
27938   tree result;
27939
27940   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
27941
27942   scope = TYPE_CONTEXT (type);
27943   /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope.  */
27944   gcc_checking_assert (uses_template_parms (scope));
27945
27946   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
27947      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of a
27948      TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL
27949      representing the typedef. In that case TYPE_IDENTIFIER (type) is
27950      not the non-qualified identifier of the TYPENAME_TYPE anymore.
27951      So by getting the TYPE_IDENTIFIER of the _main declaration_ of
27952      the TYPENAME_TYPE instead, we avoid messing up with a possible
27953      typedef variant case.  */
27954   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
27955
27956   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
27957      it first before we can figure out what NAME refers to.  */
27958   if (TREE_CODE (scope) == TYPENAME_TYPE)
27959     {
27960       if (TYPENAME_IS_RESOLVING_P (scope))
27961         /* Given a class template A with a dependent base with nested type C,
27962            typedef typename A::C::C C will land us here, as trying to resolve
27963            the initial A::C leads to the local C typedef, which leads back to
27964            A::C::C.  So we break the recursion now.  */
27965         return type;
27966       else
27967         scope = resolve_typename_type (scope, only_current_p);
27968     }
27969   /* If we don't know what SCOPE refers to, then we cannot resolve the
27970      TYPENAME_TYPE.  */
27971   if (!CLASS_TYPE_P (scope))
27972     return type;
27973   /* If this is a typedef, we don't want to look inside (c++/11987).  */
27974   if (typedef_variant_p (type))
27975     return type;
27976   /* If SCOPE isn't the template itself, it will not have a valid
27977      TYPE_FIELDS list.  */
27978   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
27979     /* scope is either the template itself or a compatible instantiation
27980        like X<T>, so look up the name in the original template.  */
27981     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
27982   /* If scope has no fields, it can't be a current instantiation.  Check this
27983      before currently_open_class to avoid infinite recursion (71515).  */
27984   if (!TYPE_FIELDS (scope))
27985     return type;
27986   /* If the SCOPE is not the current instantiation, there's no reason
27987      to look inside it.  */
27988   if (only_current_p && !currently_open_class (scope))
27989     return type;
27990   /* Enter the SCOPE so that name lookup will be resolved as if we
27991      were in the class definition.  In particular, SCOPE will no
27992      longer be considered a dependent type.  */
27993   pushed_scope = push_scope (scope);
27994   /* Look up the declaration.  */
27995   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
27996                         tf_warning_or_error);
27997
27998   result = NULL_TREE;
27999
28000   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
28001      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
28002   tree fullname = TYPENAME_TYPE_FULLNAME (type);
28003   if (!decl)
28004     /*nop*/;
28005   else if (identifier_p (fullname)
28006            && TREE_CODE (decl) == TYPE_DECL)
28007     {
28008       result = TREE_TYPE (decl);
28009       if (result == error_mark_node)
28010         result = NULL_TREE;
28011     }
28012   else if (TREE_CODE (fullname) == TEMPLATE_ID_EXPR
28013            && DECL_CLASS_TEMPLATE_P (decl))
28014     {
28015       /* Obtain the template and the arguments.  */
28016       tree tmpl = TREE_OPERAND (fullname, 0);
28017       if (TREE_CODE (tmpl) == IDENTIFIER_NODE)
28018         {
28019           /* We get here with a plain identifier because a previous tentative
28020              parse of the nested-name-specifier as part of a ptr-operator saw
28021              ::template X<A>.  The use of ::template is necessary in a
28022              ptr-operator, but wrong in a declarator-id.
28023
28024              [temp.names]: In a qualified-id of a declarator-id, the keyword
28025              template shall not appear at the top level.  */
28026           pedwarn (cp_expr_loc_or_input_loc (fullname), OPT_Wpedantic,
28027                    "keyword %<template%> not allowed in declarator-id");
28028           tmpl = decl;
28029         }
28030       tree args = TREE_OPERAND (fullname, 1);
28031       /* Instantiate the template.  */
28032       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
28033                                       /*entering_scope=*/true,
28034                                       tf_error | tf_user);
28035       if (result == error_mark_node)
28036         result = NULL_TREE;
28037     }
28038
28039   /* Leave the SCOPE.  */
28040   if (pushed_scope)
28041     pop_scope (pushed_scope);
28042
28043   /* If we failed to resolve it, return the original typename.  */
28044   if (!result)
28045     return type;
28046
28047   /* If lookup found a typename type, resolve that too.  */
28048   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
28049     {
28050       /* Ill-formed programs can cause infinite recursion here, so we
28051          must catch that.  */
28052       TYPENAME_IS_RESOLVING_P (result) = 1;
28053       result = resolve_typename_type (result, only_current_p);
28054       TYPENAME_IS_RESOLVING_P (result) = 0;
28055     }
28056
28057   /* Qualify the resulting type.  */
28058   quals = cp_type_quals (type);
28059   if (quals)
28060     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
28061
28062   return result;
28063 }
28064
28065 /* EXPR is an expression which is not type-dependent.  Return a proxy
28066    for EXPR that can be used to compute the types of larger
28067    expressions containing EXPR.  */
28068
28069 tree
28070 build_non_dependent_expr (tree expr)
28071 {
28072   tree orig_expr = expr;
28073   tree inner_expr;
28074
28075   /* When checking, try to get a constant value for all non-dependent
28076      expressions in order to expose bugs in *_dependent_expression_p
28077      and constexpr.  This can affect code generation, see PR70704, so
28078      only do this for -fchecking=2.  */
28079   if (flag_checking > 1
28080       && cxx_dialect >= cxx11
28081       /* Don't do this during nsdmi parsing as it can lead to
28082          unexpected recursive instantiations.  */
28083       && !parsing_nsdmi ()
28084       /* Don't do this during concept processing either and for
28085          the same reason.  */
28086       && !processing_constraint_expression_p ())
28087     fold_non_dependent_expr (expr, tf_none);
28088
28089   STRIP_ANY_LOCATION_WRAPPER (expr);
28090
28091   /* Preserve OVERLOADs; the functions must be available to resolve
28092      types.  */
28093   inner_expr = expr;
28094   if (TREE_CODE (inner_expr) == STMT_EXPR)
28095     inner_expr = stmt_expr_value_expr (inner_expr);
28096   if (TREE_CODE (inner_expr) == ADDR_EXPR)
28097     inner_expr = TREE_OPERAND (inner_expr, 0);
28098   if (TREE_CODE (inner_expr) == COMPONENT_REF)
28099     inner_expr = TREE_OPERAND (inner_expr, 1);
28100   if (is_overloaded_fn (inner_expr)
28101       || TREE_CODE (inner_expr) == OFFSET_REF)
28102     return orig_expr;
28103   /* There is no need to return a proxy for a variable or enumerator.  */
28104   if (VAR_P (expr) || TREE_CODE (expr) == CONST_DECL)
28105     return orig_expr;
28106   /* Preserve string constants; conversions from string constants to
28107      "char *" are allowed, even though normally a "const char *"
28108      cannot be used to initialize a "char *".  */
28109   if (TREE_CODE (expr) == STRING_CST)
28110     return orig_expr;
28111   /* Preserve void and arithmetic constants, as an optimization -- there is no
28112      reason to create a new node.  */
28113   if (TREE_CODE (expr) == VOID_CST
28114       || TREE_CODE (expr) == INTEGER_CST
28115       || TREE_CODE (expr) == REAL_CST)
28116     return orig_expr;
28117   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
28118      There is at least one place where we want to know that a
28119      particular expression is a throw-expression: when checking a ?:
28120      expression, there are special rules if the second or third
28121      argument is a throw-expression.  */
28122   if (TREE_CODE (expr) == THROW_EXPR)
28123     return orig_expr;
28124
28125   /* Don't wrap an initializer list, we need to be able to look inside.  */
28126   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
28127     return orig_expr;
28128
28129   /* Don't wrap a dummy object, we need to be able to test for it.  */
28130   if (is_dummy_object (expr))
28131     return orig_expr;
28132
28133   if (TREE_CODE (expr) == COND_EXPR)
28134     return build3 (COND_EXPR,
28135                    TREE_TYPE (expr),
28136                    build_non_dependent_expr (TREE_OPERAND (expr, 0)),
28137                    (TREE_OPERAND (expr, 1)
28138                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
28139                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
28140                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
28141   if (TREE_CODE (expr) == COMPOUND_EXPR
28142       && !COMPOUND_EXPR_OVERLOADED (expr))
28143     return build2 (COMPOUND_EXPR,
28144                    TREE_TYPE (expr),
28145                    TREE_OPERAND (expr, 0),
28146                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
28147
28148   /* If the type is unknown, it can't really be non-dependent */
28149   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
28150
28151   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
28152   return build1_loc (EXPR_LOCATION (orig_expr), NON_DEPENDENT_EXPR,
28153                      TREE_TYPE (expr), expr);
28154 }
28155
28156 /* ARGS is a vector of expressions as arguments to a function call.
28157    Replace the arguments with equivalent non-dependent expressions.
28158    This modifies ARGS in place.  */
28159
28160 void
28161 make_args_non_dependent (vec<tree, va_gc> *args)
28162 {
28163   unsigned int ix;
28164   tree arg;
28165
28166   FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
28167     {
28168       tree newarg = build_non_dependent_expr (arg);
28169       if (newarg != arg)
28170         (*args)[ix] = newarg;
28171     }
28172 }
28173
28174 /* Returns a type which represents 'auto' or 'decltype(auto)'.  We use a
28175    TEMPLATE_TYPE_PARM with a level one deeper than the actual template
28176    parms.  If set_canonical is true, we set TYPE_CANONICAL on it.  */
28177
28178 static tree
28179 make_auto_1 (tree name, bool set_canonical)
28180 {
28181   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
28182   TYPE_NAME (au) = build_decl (input_location, TYPE_DECL, name, au);
28183   TYPE_STUB_DECL (au) = TYPE_NAME (au);
28184   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
28185     (0, processing_template_decl + 1, processing_template_decl + 1,
28186      TYPE_NAME (au), NULL_TREE);
28187   if (set_canonical)
28188     TYPE_CANONICAL (au) = canonical_type_parameter (au);
28189   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
28190   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
28191   if (name == decltype_auto_identifier)
28192     AUTO_IS_DECLTYPE (au) = true;
28193
28194   return au;
28195 }
28196
28197 tree
28198 make_decltype_auto (void)
28199 {
28200   return make_auto_1 (decltype_auto_identifier, true);
28201 }
28202
28203 tree
28204 make_auto (void)
28205 {
28206   return make_auto_1 (auto_identifier, true);
28207 }
28208
28209 /* Return a C++17 deduction placeholder for class template TMPL.  */
28210
28211 tree
28212 make_template_placeholder (tree tmpl)
28213 {
28214   tree t = make_auto_1 (auto_identifier, false);
28215   CLASS_PLACEHOLDER_TEMPLATE (t) = tmpl;
28216   /* Our canonical type depends on the placeholder.  */
28217   TYPE_CANONICAL (t) = canonical_type_parameter (t);
28218   return t;
28219 }
28220
28221 /* True iff T is a C++17 class template deduction placeholder.  */
28222
28223 bool
28224 template_placeholder_p (tree t)
28225 {
28226   return is_auto (t) && CLASS_PLACEHOLDER_TEMPLATE (t);
28227 }
28228
28229 /* Make a "constrained auto" type-specifier. This is an auto or
28230   decltype(auto) type with constraints that must be associated after
28231   deduction.  The constraint is formed from the given concept CON
28232   and its optional sequence of template arguments ARGS.
28233
28234   TYPE must be the result of make_auto_type or make_decltype_auto_type. */
28235
28236 static tree
28237 make_constrained_placeholder_type (tree type, tree con, tree args)
28238 {
28239   /* Build the constraint. */
28240   tree tmpl = DECL_TI_TEMPLATE (con);
28241   tree expr = tmpl;
28242   if (TREE_CODE (con) == FUNCTION_DECL)
28243     expr = ovl_make (tmpl);
28244   ++processing_template_decl;
28245   expr = build_concept_check (expr, type, args, tf_warning_or_error);
28246   --processing_template_decl;
28247
28248   PLACEHOLDER_TYPE_CONSTRAINTS_INFO (type)
28249     = build_tree_list (current_template_parms, expr);
28250
28251   /* Our canonical type depends on the constraint.  */
28252   TYPE_CANONICAL (type) = canonical_type_parameter (type);
28253
28254   /* Attach the constraint to the type declaration. */
28255   return TYPE_NAME (type);
28256 }
28257
28258 /* Make a "constrained auto" type-specifier.  */
28259
28260 tree
28261 make_constrained_auto (tree con, tree args)
28262 {
28263   tree type = make_auto_1 (auto_identifier, false);
28264   return make_constrained_placeholder_type (type, con, args);
28265 }
28266
28267 /* Make a "constrained decltype(auto)" type-specifier.  */
28268
28269 tree
28270 make_constrained_decltype_auto (tree con, tree args)
28271 {
28272   tree type = make_auto_1 (decltype_auto_identifier, false);
28273   return make_constrained_placeholder_type (type, con, args);
28274 }
28275
28276 /* Returns true if the placeholder type constraint T has any dependent
28277    (explicit) template arguments.  */
28278
28279 static bool
28280 placeholder_type_constraint_dependent_p (tree t)
28281 {
28282   tree id = unpack_concept_check (t);
28283   tree args = TREE_OPERAND (id, 1);
28284   tree first = TREE_VEC_ELT (args, 0);
28285   if (ARGUMENT_PACK_P (first))
28286     {
28287       args = expand_template_argument_pack (args);
28288       first = TREE_VEC_ELT (args, 0);
28289     }
28290   gcc_checking_assert (TREE_CODE (first) == WILDCARD_DECL
28291                        || is_auto (first));
28292   for (int i = 1; i < TREE_VEC_LENGTH (args); ++i)
28293     if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
28294       return true;
28295   return false;
28296 }
28297
28298 /* Build and return a concept definition. Like other templates, the
28299    CONCEPT_DECL node is wrapped by a TEMPLATE_DECL.  This returns the
28300    the TEMPLATE_DECL. */
28301
28302 tree
28303 finish_concept_definition (cp_expr id, tree init)
28304 {
28305   gcc_assert (identifier_p (id));
28306   gcc_assert (processing_template_decl);
28307
28308   location_t loc = id.get_location();
28309
28310   /* A concept-definition shall not have associated constraints.  */
28311   if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
28312     {
28313       error_at (loc, "a concept cannot be constrained");
28314       TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
28315     }
28316
28317   /* A concept-definition shall appear in namespace scope.  Templates
28318      aren't allowed in block scope, so we only need to check for class
28319      scope.  */
28320   if (TYPE_P (current_scope()) || !DECL_NAMESPACE_SCOPE_P (current_scope ()))
28321     {
28322       error_at (loc, "concept %qE not in namespace scope", *id);
28323       return error_mark_node;
28324     }
28325
28326   /* Initially build the concept declaration; its type is bool.  */
28327   tree decl = build_lang_decl_loc (loc, CONCEPT_DECL, *id, boolean_type_node);
28328   DECL_CONTEXT (decl) = current_scope ();
28329   DECL_INITIAL (decl) = init;
28330
28331   set_originating_module (decl, false);
28332
28333   /* Push the enclosing template.  */
28334   return push_template_decl (decl);
28335 }
28336
28337 /* Given type ARG, return std::initializer_list<ARG>.  */
28338
28339 static tree
28340 listify (tree arg)
28341 {
28342   tree std_init_list = get_namespace_binding (std_node, init_list_identifier);
28343
28344   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
28345     {
28346       gcc_rich_location richloc (input_location);
28347       maybe_add_include_fixit (&richloc, "<initializer_list>", false);
28348       error_at (&richloc,
28349                 "deducing from brace-enclosed initializer list"
28350                 " requires %<#include <initializer_list>%>");
28351
28352       return error_mark_node;
28353     }
28354   tree argvec = make_tree_vec (1);
28355   TREE_VEC_ELT (argvec, 0) = arg;
28356
28357   return lookup_template_class (std_init_list, argvec, NULL_TREE,
28358                                 NULL_TREE, 0, tf_warning_or_error);
28359 }
28360
28361 /* Replace auto in TYPE with std::initializer_list<auto>.  */
28362
28363 static tree
28364 listify_autos (tree type, tree auto_node)
28365 {
28366   tree init_auto = listify (strip_top_quals (auto_node));
28367   tree argvec = make_tree_vec (1);
28368   TREE_VEC_ELT (argvec, 0) = init_auto;
28369   if (processing_template_decl)
28370     argvec = add_to_template_args (current_template_args (), argvec);
28371   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
28372 }
28373
28374 /* Hash traits for hashing possibly constrained 'auto'
28375    TEMPLATE_TYPE_PARMs for use by do_auto_deduction.  */
28376
28377 struct auto_hash : default_hash_traits<tree>
28378 {
28379   static inline hashval_t hash (tree);
28380   static inline bool equal (tree, tree);
28381 };
28382
28383 /* Hash the 'auto' T.  */
28384
28385 inline hashval_t
28386 auto_hash::hash (tree t)
28387 {
28388   if (tree c = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (t)))
28389     /* Matching constrained-type-specifiers denote the same template
28390        parameter, so hash the constraint.  */
28391     return hash_placeholder_constraint (c);
28392   else
28393     /* But unconstrained autos are all separate, so just hash the pointer.  */
28394     return iterative_hash_object (t, 0);
28395 }
28396
28397 /* Compare two 'auto's.  */
28398
28399 inline bool
28400 auto_hash::equal (tree t1, tree t2)
28401 {
28402   if (t1 == t2)
28403     return true;
28404
28405   tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
28406   tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
28407
28408   /* Two unconstrained autos are distinct.  */
28409   if (!c1 || !c2)
28410     return false;
28411
28412   return equivalent_placeholder_constraints (c1, c2);
28413 }
28414
28415 /* for_each_template_parm callback for extract_autos: if t is a (possibly
28416    constrained) auto, add it to the vector.  */
28417
28418 static int
28419 extract_autos_r (tree t, void *data)
28420 {
28421   hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
28422   if (is_auto (t))
28423     {
28424       /* All the autos were built with index 0; fix that up now.  */
28425       tree *p = hash.find_slot (t, INSERT);
28426       unsigned idx;
28427       if (*p)
28428         /* If this is a repeated constrained-type-specifier, use the index we
28429            chose before.  */
28430         idx = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (*p));
28431       else
28432         {
28433           /* Otherwise this is new, so use the current count.  */
28434           *p = t;
28435           idx = hash.elements () - 1;
28436         }
28437       TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (t)) = idx;
28438     }
28439
28440   /* Always keep walking.  */
28441   return 0;
28442 }
28443
28444 /* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
28445    says they can appear anywhere in the type.  */
28446
28447 static tree
28448 extract_autos (tree type)
28449 {
28450   hash_set<tree> visited;
28451   hash_table<auto_hash> hash (2);
28452
28453   for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
28454
28455   tree tree_vec = make_tree_vec (hash.elements());
28456   for (hash_table<auto_hash>::iterator iter = hash.begin();
28457        iter != hash.end(); ++iter)
28458     {
28459       tree elt = *iter;
28460       unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
28461       TREE_VEC_ELT (tree_vec, i)
28462         = build_tree_list (NULL_TREE, TYPE_NAME (elt));
28463     }
28464
28465   return tree_vec;
28466 }
28467
28468 /* The stem for deduction guide names.  */
28469 const char *const dguide_base = "__dguide_";
28470
28471 /* Return the name for a deduction guide for class template TMPL.  */
28472
28473 tree
28474 dguide_name (tree tmpl)
28475 {
28476   tree type = (TYPE_P (tmpl) ? tmpl : TREE_TYPE (tmpl));
28477   tree tname = TYPE_IDENTIFIER (type);
28478   char *buf = (char *) alloca (1 + strlen (dguide_base)
28479                                + IDENTIFIER_LENGTH (tname));
28480   memcpy (buf, dguide_base, strlen (dguide_base));
28481   memcpy (buf + strlen (dguide_base), IDENTIFIER_POINTER (tname),
28482           IDENTIFIER_LENGTH (tname) + 1);
28483   tree dname = get_identifier (buf);
28484   TREE_TYPE (dname) = type;
28485   return dname;
28486 }
28487
28488 /* True if NAME is the name of a deduction guide.  */
28489
28490 bool
28491 dguide_name_p (tree name)
28492 {
28493   return (TREE_CODE (name) == IDENTIFIER_NODE
28494           && TREE_TYPE (name)
28495           && !strncmp (IDENTIFIER_POINTER (name), dguide_base,
28496                        strlen (dguide_base)));
28497 }
28498
28499 /* True if FN is a deduction guide.  */
28500
28501 bool
28502 deduction_guide_p (const_tree fn)
28503 {
28504   if (DECL_P (fn))
28505     if (tree name = DECL_NAME (fn))
28506       return dguide_name_p (name);
28507   return false;
28508 }
28509
28510 /* True if FN is the copy deduction guide, i.e. A(A)->A.  */
28511
28512 bool
28513 copy_guide_p (const_tree fn)
28514 {
28515   gcc_assert (deduction_guide_p (fn));
28516   if (!DECL_ARTIFICIAL (fn))
28517     return false;
28518   tree parms = FUNCTION_FIRST_USER_PARMTYPE (DECL_TI_TEMPLATE (fn));
28519   return (TREE_CHAIN (parms) == void_list_node
28520           && same_type_p (TREE_VALUE (parms), TREE_TYPE (DECL_NAME (fn))));
28521 }
28522
28523 /* True if FN is a guide generated from a constructor template.  */
28524
28525 bool
28526 template_guide_p (const_tree fn)
28527 {
28528   gcc_assert (deduction_guide_p (fn));
28529   if (!DECL_ARTIFICIAL (fn))
28530     return false;
28531   tree tmpl = DECL_TI_TEMPLATE (fn);
28532   if (tree org = DECL_ABSTRACT_ORIGIN (tmpl))
28533     return PRIMARY_TEMPLATE_P (org);
28534   return false;
28535 }
28536
28537 /* True if FN is an aggregate initialization guide or the copy deduction
28538    guide.  */
28539
28540 bool
28541 builtin_guide_p (const_tree fn)
28542 {
28543   if (!deduction_guide_p (fn))
28544     return false;
28545   if (!DECL_ARTIFICIAL (fn))
28546     /* Explicitly declared.  */
28547     return false;
28548   if (DECL_ABSTRACT_ORIGIN (fn))
28549     /* Derived from a constructor.  */
28550     return false;
28551   return true;
28552 }
28553
28554 /* OLDDECL is a _DECL for a template parameter.  Return a similar parameter at
28555    LEVEL:INDEX, using tsubst_args and complain for substitution into non-type
28556    template parameter types.  Note that the handling of template template
28557    parameters relies on current_template_parms being set appropriately for the
28558    new template.  */
28559
28560 static tree
28561 rewrite_template_parm (tree olddecl, unsigned index, unsigned level,
28562                        tree tsubst_args, tsubst_flags_t complain)
28563 {
28564   if (olddecl == error_mark_node)
28565     return error_mark_node;
28566
28567   tree oldidx = get_template_parm_index (olddecl);
28568
28569   tree newtype;
28570   if (TREE_CODE (olddecl) == TYPE_DECL
28571       || TREE_CODE (olddecl) == TEMPLATE_DECL)
28572     {
28573       tree oldtype = TREE_TYPE (olddecl);
28574       newtype = cxx_make_type (TREE_CODE (oldtype));
28575       TYPE_MAIN_VARIANT (newtype) = newtype;
28576       if (TREE_CODE (oldtype) == TEMPLATE_TYPE_PARM)
28577         TEMPLATE_TYPE_PARM_FOR_CLASS (newtype)
28578           = TEMPLATE_TYPE_PARM_FOR_CLASS (oldtype);
28579     }
28580   else
28581     {
28582       newtype = TREE_TYPE (olddecl);
28583       if (type_uses_auto (newtype))
28584         {
28585           // Substitute once to fix references to other template parameters.
28586           newtype = tsubst (newtype, tsubst_args,
28587                             complain|tf_partial, NULL_TREE);
28588           // Now substitute again to reduce the level of the auto.
28589           newtype = tsubst (newtype, current_template_args (),
28590                             complain, NULL_TREE);
28591         }
28592       else
28593         newtype = tsubst (newtype, tsubst_args,
28594                           complain, NULL_TREE);
28595     }
28596
28597   tree newdecl
28598     = build_decl (DECL_SOURCE_LOCATION (olddecl), TREE_CODE (olddecl),
28599                   DECL_NAME (olddecl), newtype);
28600   SET_DECL_TEMPLATE_PARM_P (newdecl);
28601
28602   tree newidx;
28603   if (TREE_CODE (olddecl) == TYPE_DECL
28604       || TREE_CODE (olddecl) == TEMPLATE_DECL)
28605     {
28606       newidx = TEMPLATE_TYPE_PARM_INDEX (newtype)
28607         = build_template_parm_index (index, level, level,
28608                                      newdecl, newtype);
28609       TEMPLATE_PARM_PARAMETER_PACK (newidx)
28610         = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
28611       TYPE_STUB_DECL (newtype) = TYPE_NAME (newtype) = newdecl;
28612       if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (olddecl)))
28613         SET_TYPE_STRUCTURAL_EQUALITY (newtype);
28614       else
28615         TYPE_CANONICAL (newtype) = canonical_type_parameter (newtype);
28616
28617       if (TREE_CODE (olddecl) == TEMPLATE_DECL)
28618         {
28619           DECL_TEMPLATE_RESULT (newdecl)
28620             = build_decl (DECL_SOURCE_LOCATION (olddecl), TYPE_DECL,
28621                           DECL_NAME (olddecl), newtype);
28622           DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (newdecl)) = true;
28623           // First create a copy (ttargs) of tsubst_args with an
28624           // additional level for the template template parameter's own
28625           // template parameters (ttparms).
28626           tree ttparms = (INNERMOST_TEMPLATE_PARMS
28627                           (DECL_TEMPLATE_PARMS (olddecl)));
28628           const int depth = TMPL_ARGS_DEPTH (tsubst_args);
28629           tree ttargs = make_tree_vec (depth + 1);
28630           for (int i = 0; i < depth; ++i)
28631             TREE_VEC_ELT (ttargs, i) = TREE_VEC_ELT (tsubst_args, i);
28632           TREE_VEC_ELT (ttargs, depth)
28633             = template_parms_level_to_args (ttparms);
28634           // Substitute ttargs into ttparms to fix references to
28635           // other template parameters.
28636           ttparms = tsubst_template_parms_level (ttparms, ttargs,
28637                                                  complain|tf_partial);
28638           // Now substitute again with args based on tparms, to reduce
28639           // the level of the ttparms.
28640           ttargs = current_template_args ();
28641           ttparms = tsubst_template_parms_level (ttparms, ttargs,
28642                                                  complain);
28643           // Finally, tack the adjusted parms onto tparms.
28644           ttparms = tree_cons (size_int (depth), ttparms,
28645                                current_template_parms);
28646           DECL_TEMPLATE_PARMS (newdecl) = ttparms;
28647         }
28648     }
28649   else
28650     {
28651       tree oldconst = TEMPLATE_PARM_DECL (oldidx);
28652       tree newconst
28653         = build_decl (DECL_SOURCE_LOCATION (oldconst),
28654                       TREE_CODE (oldconst),
28655                       DECL_NAME (oldconst), newtype);
28656       TREE_CONSTANT (newconst) = TREE_CONSTANT (newdecl)
28657         = TREE_READONLY (newconst) = TREE_READONLY (newdecl) = true;
28658       SET_DECL_TEMPLATE_PARM_P (newconst);
28659       newidx = build_template_parm_index (index, level, level,
28660                                           newconst, newtype);
28661       TEMPLATE_PARM_PARAMETER_PACK (newidx)
28662         = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
28663       DECL_INITIAL (newdecl) = DECL_INITIAL (newconst) = newidx;
28664     }
28665
28666   return newdecl;
28667 }
28668
28669 /* As rewrite_template_parm, but for the whole TREE_LIST representing a
28670    template parameter.  */
28671
28672 static tree
28673 rewrite_tparm_list (tree oldelt, unsigned index, unsigned level,
28674                     tree targs, unsigned targs_index, tsubst_flags_t complain)
28675 {
28676   tree olddecl = TREE_VALUE (oldelt);
28677   tree newdecl = rewrite_template_parm (olddecl, index, level,
28678                                         targs, complain);
28679   if (newdecl == error_mark_node)
28680     return error_mark_node;
28681   tree newdef = tsubst_template_arg (TREE_PURPOSE (oldelt),
28682                                      targs, complain, NULL_TREE);
28683   tree list = build_tree_list (newdef, newdecl);
28684   TEMPLATE_PARM_CONSTRAINTS (list)
28685     = tsubst_constraint_info (TEMPLATE_PARM_CONSTRAINTS (oldelt),
28686                               targs, complain, NULL_TREE);
28687   int depth = TMPL_ARGS_DEPTH (targs);
28688   TMPL_ARG (targs, depth, targs_index) = template_parm_to_arg (list);
28689   return list;
28690 }
28691
28692 /* Returns a C++17 class deduction guide template based on the constructor
28693    CTOR.  As a special case, CTOR can be a RECORD_TYPE for an implicit default
28694    guide, REFERENCE_TYPE for an implicit copy/move guide, or TREE_LIST for an
28695    aggregate initialization guide.  OUTER_ARGS are the template arguments
28696    for the enclosing scope of the class.  */
28697
28698 static tree
28699 build_deduction_guide (tree type, tree ctor, tree outer_args, tsubst_flags_t complain)
28700 {
28701   tree tparms, targs, fparms, fargs, ci;
28702   bool memtmpl = false;
28703   bool explicit_p;
28704   location_t loc;
28705   tree fn_tmpl = NULL_TREE;
28706
28707   if (outer_args)
28708     {
28709       ++processing_template_decl;
28710       type = tsubst (type, outer_args, complain, CLASSTYPE_TI_TEMPLATE (type));
28711       --processing_template_decl;
28712     }
28713
28714   if (!DECL_DECLARES_FUNCTION_P (ctor))
28715     {
28716       if (TYPE_P (ctor))
28717         {
28718           bool copy_p = TYPE_REF_P (ctor);
28719           if (copy_p)
28720             fparms = tree_cons (NULL_TREE, type, void_list_node);
28721           else
28722             fparms = void_list_node;
28723         }
28724       else if (TREE_CODE (ctor) == TREE_LIST)
28725         fparms = ctor;
28726       else
28727         gcc_unreachable ();
28728
28729       tree ctmpl = CLASSTYPE_TI_TEMPLATE (type);
28730       tparms = DECL_TEMPLATE_PARMS (ctmpl);
28731       targs = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
28732       ci = NULL_TREE;
28733       fargs = NULL_TREE;
28734       loc = DECL_SOURCE_LOCATION (ctmpl);
28735       explicit_p = false;
28736     }
28737   else
28738     {
28739       ++processing_template_decl;
28740       bool ok = true;
28741
28742       fn_tmpl
28743         = (TREE_CODE (ctor) == TEMPLATE_DECL ? ctor
28744            : DECL_TI_TEMPLATE (ctor));
28745       if (outer_args)
28746         fn_tmpl = tsubst (fn_tmpl, outer_args, complain, ctor);
28747       ctor = DECL_TEMPLATE_RESULT (fn_tmpl);
28748
28749       tparms = DECL_TEMPLATE_PARMS (fn_tmpl);
28750       /* If type is a member class template, DECL_TI_ARGS (ctor) will have
28751          fully specialized args for the enclosing class.  Strip those off, as
28752          the deduction guide won't have those template parameters.  */
28753       targs = get_innermost_template_args (DECL_TI_ARGS (ctor),
28754                                                 TMPL_PARMS_DEPTH (tparms));
28755       /* Discard the 'this' parameter.  */
28756       fparms = FUNCTION_ARG_CHAIN (ctor);
28757       fargs = TREE_CHAIN (DECL_ARGUMENTS (ctor));
28758       ci = get_constraints (ctor);
28759       loc = DECL_SOURCE_LOCATION (ctor);
28760       explicit_p = DECL_NONCONVERTING_P (ctor);
28761
28762       if (PRIMARY_TEMPLATE_P (fn_tmpl))
28763         {
28764           memtmpl = true;
28765
28766           /* For a member template constructor, we need to flatten the two
28767              template parameter lists into one, and then adjust the function
28768              signature accordingly.  This gets...complicated.  */
28769           tree save_parms = current_template_parms;
28770
28771           /* For a member template we should have two levels of parms/args, one
28772              for the class and one for the constructor.  We stripped
28773              specialized args for further enclosing classes above.  */
28774           const int depth = 2;
28775           gcc_assert (TMPL_ARGS_DEPTH (targs) == depth);
28776
28777           /* Template args for translating references to the two-level template
28778              parameters into references to the one-level template parameters we
28779              are creating.  */
28780           tree tsubst_args = copy_node (targs);
28781           TMPL_ARGS_LEVEL (tsubst_args, depth)
28782             = copy_node (TMPL_ARGS_LEVEL (tsubst_args, depth));
28783
28784           /* Template parms for the constructor template.  */
28785           tree ftparms = TREE_VALUE (tparms);
28786           unsigned flen = TREE_VEC_LENGTH (ftparms);
28787           /* Template parms for the class template.  */
28788           tparms = TREE_CHAIN (tparms);
28789           tree ctparms = TREE_VALUE (tparms);
28790           unsigned clen = TREE_VEC_LENGTH (ctparms);
28791           /* Template parms for the deduction guide start as a copy of the
28792              template parms for the class.  We set current_template_parms for
28793              lookup_template_class_1.  */
28794           current_template_parms = tparms = copy_node (tparms);
28795           tree new_vec = TREE_VALUE (tparms) = make_tree_vec (flen + clen);
28796           for (unsigned i = 0; i < clen; ++i)
28797             TREE_VEC_ELT (new_vec, i) = TREE_VEC_ELT (ctparms, i);
28798
28799           /* Now we need to rewrite the constructor parms to append them to the
28800              class parms.  */
28801           for (unsigned i = 0; i < flen; ++i)
28802             {
28803               unsigned index = i + clen;
28804               unsigned level = 1;
28805               tree oldelt = TREE_VEC_ELT (ftparms, i);
28806               tree newelt
28807                 = rewrite_tparm_list (oldelt, index, level,
28808                                       tsubst_args, i, complain);
28809               if (newelt == error_mark_node)
28810                 ok = false;
28811               TREE_VEC_ELT (new_vec, index) = newelt;
28812             }
28813
28814           /* Now we have a final set of template parms to substitute into the
28815              function signature.  */
28816           targs = template_parms_to_args (tparms);
28817           fparms = tsubst_arg_types (fparms, tsubst_args, NULL_TREE,
28818                                      complain, ctor);
28819           if (fparms == error_mark_node)
28820             ok = false;
28821           if (ci)
28822             {
28823               if (outer_args)
28824                 /* FIXME: We'd like to avoid substituting outer template
28825                    arguments into the constraint ahead of time, but the
28826                    construction of tsubst_args assumes that outer arguments
28827                    are already substituted in.  */
28828                 ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
28829               ci = tsubst_constraint_info (ci, tsubst_args, complain, ctor);
28830             }
28831
28832           /* Parms are to have DECL_CHAIN tsubsted, which would be skipped if
28833              cp_unevaluated_operand.  */
28834           cp_evaluated ev;
28835           fargs = tsubst (fargs, tsubst_args, complain, ctor);
28836           current_template_parms = save_parms;
28837         }
28838       else
28839         {
28840           /* Substitute in the same arguments to rewrite class members into
28841              references to members of an unknown specialization.  */
28842           cp_evaluated ev;
28843           fparms = tsubst_arg_types (fparms, targs, NULL_TREE, complain, ctor);
28844           fargs = tsubst (fargs, targs, complain, ctor);
28845           if (ci)
28846             {
28847               if (outer_args)
28848                 /* FIXME: As above.  */
28849                 ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
28850               ci = tsubst_constraint_info (ci, targs, complain, ctor);
28851             }
28852         }
28853
28854       --processing_template_decl;
28855       if (!ok)
28856         return error_mark_node;
28857     }
28858
28859   if (!memtmpl)
28860     {
28861       /* Copy the parms so we can set DECL_PRIMARY_TEMPLATE.  */
28862       tparms = copy_node (tparms);
28863       INNERMOST_TEMPLATE_PARMS (tparms)
28864         = copy_node (INNERMOST_TEMPLATE_PARMS (tparms));
28865     }
28866
28867   tree fntype = build_function_type (type, fparms);
28868   tree ded_fn = build_lang_decl_loc (loc,
28869                                      FUNCTION_DECL,
28870                                      dguide_name (type), fntype);
28871   DECL_ARGUMENTS (ded_fn) = fargs;
28872   DECL_ARTIFICIAL (ded_fn) = true;
28873   DECL_NONCONVERTING_P (ded_fn) = explicit_p;
28874   tree ded_tmpl = build_template_decl (ded_fn, tparms, /*member*/false);
28875   DECL_ARTIFICIAL (ded_tmpl) = true;
28876   DECL_TEMPLATE_INFO (ded_fn) = build_template_info (ded_tmpl, targs);
28877   DECL_PRIMARY_TEMPLATE (ded_tmpl) = ded_tmpl;
28878   if (DECL_P (ctor))
28879     DECL_ABSTRACT_ORIGIN (ded_tmpl) = fn_tmpl;
28880   if (ci)
28881     set_constraints (ded_tmpl, ci);
28882
28883   return ded_tmpl;
28884 }
28885
28886 /* Add to LIST the member types for the reshaped initializer CTOR.  */
28887
28888 static tree
28889 collect_ctor_idx_types (tree ctor, tree list, tree elt = NULL_TREE)
28890 {
28891   vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (ctor);
28892   tree idx, val; unsigned i;
28893   FOR_EACH_CONSTRUCTOR_ELT (v, i, idx, val)
28894     {
28895       tree ftype = elt ? elt : TREE_TYPE (idx);
28896       if (BRACE_ENCLOSED_INITIALIZER_P (val)
28897           && CONSTRUCTOR_NELTS (val)
28898           /* As in reshape_init_r, a non-aggregate or array-of-dependent-bound
28899              type gets a single initializer.  */
28900           && CP_AGGREGATE_TYPE_P (ftype)
28901           && !(TREE_CODE (ftype) == ARRAY_TYPE
28902                && uses_template_parms (TYPE_DOMAIN (ftype))))
28903         {
28904           tree subelt = NULL_TREE;
28905           if (TREE_CODE (ftype) == ARRAY_TYPE)
28906             subelt = TREE_TYPE (ftype);
28907           list = collect_ctor_idx_types (val, list, subelt);
28908           continue;
28909         }
28910       tree arg = NULL_TREE;
28911       if (i == v->length() - 1
28912           && PACK_EXPANSION_P (ftype))
28913         /* Give the trailing pack expansion parameter a default argument to
28914            match aggregate initialization behavior, even if we deduce the
28915            length of the pack separately to more than we have initializers. */
28916         arg = build_constructor (init_list_type_node, NULL);
28917       /* if ei is of array type and xi is a braced-init-list or string literal,
28918          Ti is an rvalue reference to the declared type of ei */
28919       STRIP_ANY_LOCATION_WRAPPER (val);
28920       if (TREE_CODE (ftype) == ARRAY_TYPE
28921           && (BRACE_ENCLOSED_INITIALIZER_P (val)
28922               || TREE_CODE (val) == STRING_CST))
28923         {
28924           if (TREE_CODE (val) == STRING_CST)
28925             ftype = cp_build_qualified_type
28926               (ftype, cp_type_quals (ftype) | TYPE_QUAL_CONST);
28927           ftype = (cp_build_reference_type
28928                    (ftype, BRACE_ENCLOSED_INITIALIZER_P (val)));
28929         }
28930       list = tree_cons (arg, ftype, list);
28931     }
28932
28933   return list;
28934 }
28935
28936 /* Return whether ETYPE is, or is derived from, a specialization of TMPL.  */
28937
28938 static bool
28939 is_spec_or_derived (tree etype, tree tmpl)
28940 {
28941   if (!etype || !CLASS_TYPE_P (etype))
28942     return false;
28943
28944   etype = cv_unqualified (etype);
28945   tree type = TREE_TYPE (tmpl);
28946   tree tparms = (INNERMOST_TEMPLATE_PARMS
28947                  (DECL_TEMPLATE_PARMS (tmpl)));
28948   tree targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
28949   int err = unify (tparms, targs, type, etype,
28950                    UNIFY_ALLOW_DERIVED, /*explain*/false);
28951   ggc_free (targs);
28952   return !err;
28953 }
28954
28955 /* Return a C++20 aggregate deduction candidate for TYPE initialized from
28956    INIT.  */
28957
28958 static tree
28959 maybe_aggr_guide (tree tmpl, tree init, vec<tree,va_gc> *args)
28960 {
28961   if (cxx_dialect < cxx20)
28962     return NULL_TREE;
28963
28964   if (init == NULL_TREE)
28965     return NULL_TREE;
28966
28967   /* We might be creating a guide for a class member template, e.g.,
28968
28969        template<typename U> struct A {
28970          template<typename T> struct B { T t; };
28971        };
28972
28973      At this point, A will have been instantiated.  Below, we need to
28974      use both A<U>::B<T> (TEMPLATE_TYPE) and A<int>::B<T> (TYPE) types.  */
28975   const bool member_template_p
28976     = (DECL_TEMPLATE_INFO (tmpl)
28977        && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (tmpl)));
28978   tree type = TREE_TYPE (tmpl);
28979   tree template_type = (member_template_p
28980                         ? TREE_TYPE (DECL_TI_TEMPLATE (tmpl))
28981                         : type);
28982   if (!CP_AGGREGATE_TYPE_P (template_type))
28983     return NULL_TREE;
28984
28985   /* No aggregate candidate for copy-initialization.  */
28986   if (args->length() == 1)
28987     {
28988       tree val = (*args)[0];
28989       if (is_spec_or_derived (TREE_TYPE (val), tmpl))
28990         return NULL_TREE;
28991     }
28992
28993   /* If we encounter a problem, we just won't add the candidate.  */
28994   tsubst_flags_t complain = tf_none;
28995
28996   tree parms = NULL_TREE;
28997   if (BRACE_ENCLOSED_INITIALIZER_P (init))
28998     {
28999       init = reshape_init (template_type, init, complain);
29000       if (init == error_mark_node)
29001         return NULL_TREE;
29002       parms = collect_ctor_idx_types (init, parms);
29003       /* If we're creating a deduction guide for a member class template,
29004          we've used the original template pattern type for the reshape_init
29005          above; this is done because we want PARMS to be a template parameter
29006          type, something that can be deduced when used as a function template
29007          parameter.  At this point the outer class template has already been
29008          partially instantiated (we deferred the deduction until the enclosing
29009          scope is non-dependent).  Therefore we have to partially instantiate
29010          PARMS, so that its template level is properly reduced and we don't get
29011          mismatches when deducing types using the guide with PARMS.  */
29012       if (member_template_p)
29013         parms = tsubst (parms, DECL_TI_ARGS (tmpl), complain, init);
29014     }
29015   else if (TREE_CODE (init) == TREE_LIST)
29016     {
29017       int len = list_length (init);
29018       for (tree field = TYPE_FIELDS (type);
29019            len;
29020            --len, field = DECL_CHAIN (field))
29021         {
29022           field = next_initializable_field (field);
29023           if (!field)
29024             return NULL_TREE;
29025           tree ftype = finish_decltype_type (field, true, complain);
29026           parms = tree_cons (NULL_TREE, ftype, parms);
29027         }
29028     }
29029   else
29030     /* Aggregate initialization doesn't apply to an initializer expression.  */
29031     return NULL_TREE;
29032
29033   if (parms)
29034     {
29035       tree last = parms;
29036       parms = nreverse (parms);
29037       TREE_CHAIN (last) = void_list_node;
29038       tree guide = build_deduction_guide (type, parms, NULL_TREE, complain);
29039       return guide;
29040     }
29041
29042   return NULL_TREE;
29043 }
29044
29045 /* UGUIDES are the deduction guides for the underlying template of alias
29046    template TMPL; adjust them to be deduction guides for TMPL.  */
29047
29048 static tree
29049 alias_ctad_tweaks (tree tmpl, tree uguides)
29050 {
29051   /* [over.match.class.deduct]: When resolving a placeholder for a deduced
29052      class type (9.2.8.2) where the template-name names an alias template A,
29053      the defining-type-id of A must be of the form
29054
29055      typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
29056
29057      as specified in 9.2.8.2. The guides of A are the set of functions or
29058      function templates formed as follows. For each function or function
29059      template f in the guides of the template named by the simple-template-id
29060      of the defining-type-id, the template arguments of the return type of f
29061      are deduced from the defining-type-id of A according to the process in
29062      13.10.2.5 with the exception that deduction does not fail if not all
29063      template arguments are deduced. Let g denote the result of substituting
29064      these deductions into f. If substitution succeeds, form a function or
29065      function template f' with the following properties and add it to the set
29066      of guides of A:
29067
29068      * The function type of f' is the function type of g.
29069
29070      * If f is a function template, f' is a function template whose template
29071      parameter list consists of all the template parameters of A (including
29072      their default template arguments) that appear in the above deductions or
29073      (recursively) in their default template arguments, followed by the
29074      template parameters of f that were not deduced (including their default
29075      template arguments), otherwise f' is not a function template.
29076
29077      * The associated constraints (13.5.2) are the conjunction of the
29078      associated constraints of g and a constraint that is satisfied if and only
29079      if the arguments of A are deducible (see below) from the return type.
29080
29081      * If f is a copy deduction candidate (12.4.1.8), then f' is considered to
29082      be so as well.
29083
29084      * If f was generated from a deduction-guide (12.4.1.8), then f' is
29085      considered to be so as well.
29086
29087      * The explicit-specifier of f' is the explicit-specifier of g (if
29088      any).  */
29089
29090   /* This implementation differs from the above in two significant ways:
29091
29092      1) We include all template parameters of A, not just some.
29093      2) The added constraint is same_type instead of deducible.
29094
29095      I believe that while it's probably possible to construct a testcase that
29096      behaves differently with this simplification, it should have the same
29097      effect for real uses.  Including all template parameters means that we
29098      deduce all parameters of A when resolving the call, so when we're in the
29099      constraint we don't need to deduce them again, we can just check whether
29100      the deduction produced the desired result.  */
29101
29102   tsubst_flags_t complain = tf_warning_or_error;
29103   tree atype = TREE_TYPE (tmpl);
29104   tree aguides = NULL_TREE;
29105   tree atparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
29106   unsigned natparms = TREE_VEC_LENGTH (atparms);
29107   tree utype = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
29108   for (ovl_iterator iter (uguides); iter; ++iter)
29109     {
29110       tree f = *iter;
29111       tree in_decl = f;
29112       location_t loc = DECL_SOURCE_LOCATION (f);
29113       tree ret = TREE_TYPE (TREE_TYPE (f));
29114       tree fprime = f;
29115       if (TREE_CODE (f) == TEMPLATE_DECL)
29116         {
29117           processing_template_decl_sentinel ptds (/*reset*/false);
29118           ++processing_template_decl;
29119
29120           /* Deduce template arguments for f from the type-id of A.  */
29121           tree ftparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (f));
29122           unsigned len = TREE_VEC_LENGTH (ftparms);
29123           tree targs = make_tree_vec (len);
29124           int err = unify (ftparms, targs, ret, utype, UNIFY_ALLOW_NONE, false);
29125           if (err)
29126             continue;
29127
29128           /* The number of parms for f' is the number of parms for A plus
29129              non-deduced parms of f.  */
29130           unsigned ndlen = 0;
29131           unsigned j;
29132           for (unsigned i = 0; i < len; ++i)
29133             if (TREE_VEC_ELT (targs, i) == NULL_TREE)
29134               ++ndlen;
29135           tree gtparms = make_tree_vec (natparms + ndlen);
29136
29137           /* First copy over the parms of A.  */
29138           for (j = 0; j < natparms; ++j)
29139             TREE_VEC_ELT (gtparms, j) = TREE_VEC_ELT (atparms, j);
29140           /* Now rewrite the non-deduced parms of f.  */
29141           for (unsigned i = 0; ndlen && i < len; ++i)
29142             if (TREE_VEC_ELT (targs, i) == NULL_TREE)
29143               {
29144                 --ndlen;
29145                 unsigned index = j++;
29146                 unsigned level = 1;
29147                 tree oldlist = TREE_VEC_ELT (ftparms, i);
29148                 tree list = rewrite_tparm_list (oldlist, index, level,
29149                                                 targs, i, complain);
29150                 TREE_VEC_ELT (gtparms, index) = list;
29151               }
29152           gtparms = build_tree_list (size_one_node, gtparms);
29153
29154           /* Substitute the deduced arguments plus the rewritten template
29155              parameters into f to get g.  This covers the type, copyness,
29156              guideness, and explicit-specifier.  */
29157           tree g = tsubst_decl (DECL_TEMPLATE_RESULT (f), targs, complain);
29158           if (g == error_mark_node)
29159             continue;
29160           DECL_USE_TEMPLATE (g) = 0;
29161           fprime = build_template_decl (g, gtparms, false);
29162           DECL_TEMPLATE_RESULT (fprime) = g;
29163           TREE_TYPE (fprime) = TREE_TYPE (g);
29164           tree gtargs = template_parms_to_args (gtparms);
29165           DECL_TEMPLATE_INFO (g) = build_template_info (fprime, gtargs);
29166           DECL_PRIMARY_TEMPLATE (fprime) = fprime;
29167
29168           /* Substitute the associated constraints.  */
29169           tree ci = get_constraints (f);
29170           if (ci)
29171             ci = tsubst_constraint_info (ci, targs, complain, in_decl);
29172           if (ci == error_mark_node)
29173             continue;
29174
29175           /* Add a constraint that the return type matches the instantiation of
29176              A with the same template arguments.  */
29177           ret = TREE_TYPE (TREE_TYPE (fprime));
29178           if (!same_type_p (atype, ret)
29179               /* FIXME this should mean they don't compare as equivalent.  */
29180               || dependent_alias_template_spec_p (atype, nt_opaque))
29181             {
29182               tree same = finish_trait_expr (loc, CPTK_IS_SAME_AS, atype, ret);
29183               ci = append_constraint (ci, same);
29184             }
29185
29186           if (ci)
29187             {
29188               remove_constraints (fprime);
29189               set_constraints (fprime, ci);
29190             }
29191         }
29192       else
29193         {
29194           /* For a non-template deduction guide, if the arguments of A aren't
29195              deducible from the return type, don't add the candidate.  */
29196           tree targs = make_tree_vec (natparms);
29197           int err = unify (atparms, targs, utype, ret, UNIFY_ALLOW_NONE, false);
29198           for (unsigned i = 0; !err && i < natparms; ++i)
29199             if (TREE_VEC_ELT (targs, i) == NULL_TREE)
29200               err = true;
29201           if (err)
29202             continue;
29203         }
29204
29205       aguides = lookup_add (fprime, aguides);
29206     }
29207
29208   return aguides;
29209 }
29210
29211 /* Return artificial deduction guides built from the constructors of class
29212    template TMPL.  */
29213
29214 static tree
29215 ctor_deduction_guides_for (tree tmpl, tsubst_flags_t complain)
29216 {
29217   tree type = TREE_TYPE (tmpl);
29218   tree outer_args = NULL_TREE;
29219   if (DECL_CLASS_SCOPE_P (tmpl)
29220       && CLASSTYPE_TEMPLATE_INSTANTIATION (DECL_CONTEXT (tmpl)))
29221     {
29222       outer_args = CLASSTYPE_TI_ARGS (DECL_CONTEXT (tmpl));
29223       type = TREE_TYPE (most_general_template (tmpl));
29224     }
29225
29226   tree cands = NULL_TREE;
29227
29228   for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (type)); iter; ++iter)
29229     {
29230       /* Skip inherited constructors.  */
29231       if (iter.using_p ())
29232         continue;
29233
29234       tree guide = build_deduction_guide (type, *iter, outer_args, complain);
29235       cands = lookup_add (guide, cands);
29236     }
29237
29238   /* Add implicit default constructor deduction guide.  */
29239   if (!TYPE_HAS_USER_CONSTRUCTOR (type))
29240     {
29241       tree guide = build_deduction_guide (type, type, outer_args,
29242                                           complain);
29243       cands = lookup_add (guide, cands);
29244     }
29245
29246   /* Add copy guide.  */
29247   {
29248     tree gtype = build_reference_type (type);
29249     tree guide = build_deduction_guide (type, gtype, outer_args,
29250                                         complain);
29251     cands = lookup_add (guide, cands);
29252   }
29253
29254   return cands;
29255 }
29256
29257 static GTY((deletable)) hash_map<tree, tree_pair_p> *dguide_cache;
29258
29259 /* Return the non-aggregate deduction guides for deducible template TMPL.  The
29260    aggregate candidate is added separately because it depends on the
29261    initializer.  Set ANY_DGUIDES_P if we find a non-implicit deduction
29262    guide.  */
29263
29264 static tree
29265 deduction_guides_for (tree tmpl, bool &any_dguides_p, tsubst_flags_t complain)
29266 {
29267   tree guides = NULL_TREE;
29268   if (DECL_ALIAS_TEMPLATE_P (tmpl))
29269     {
29270       tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
29271       tree tinfo = get_template_info (under);
29272       guides = deduction_guides_for (TI_TEMPLATE (tinfo), any_dguides_p,
29273                                      complain);
29274     }
29275   else
29276     {
29277       guides = lookup_qualified_name (CP_DECL_CONTEXT (tmpl),
29278                                       dguide_name (tmpl),
29279                                       LOOK_want::NORMAL, /*complain*/false);
29280       if (guides == error_mark_node)
29281         guides = NULL_TREE;
29282       else
29283         any_dguides_p = true;
29284     }
29285
29286   /* Cache the deduction guides for a template.  We also remember the result of
29287      lookup, and rebuild everything if it changes; should be very rare.  */
29288   tree_pair_p cache = NULL;
29289   if (tree_pair_p &r
29290       = hash_map_safe_get_or_insert<hm_ggc> (dguide_cache, tmpl))
29291     {
29292       cache = r;
29293       if (cache->purpose == guides)
29294         return cache->value;
29295     }
29296   else
29297     {
29298       r = cache = ggc_cleared_alloc<tree_pair_s> ();
29299       cache->purpose = guides;
29300     }
29301
29302   tree cands = NULL_TREE;
29303   if (DECL_ALIAS_TEMPLATE_P (tmpl))
29304     cands = alias_ctad_tweaks (tmpl, guides);
29305   else
29306     {
29307       cands = ctor_deduction_guides_for (tmpl, complain);
29308       for (ovl_iterator it (guides); it; ++it)
29309         cands = lookup_add (*it, cands);
29310     }
29311
29312   cache->value = cands;
29313   return cands;
29314 }
29315
29316 /* Return whether TMPL is a (class template argument-) deducible template.  */
29317
29318 bool
29319 ctad_template_p (tree tmpl)
29320 {
29321   /* A deducible template is either a class template or is an alias template
29322      whose defining-type-id is of the form
29323
29324       typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
29325
29326      where the nested-name-specifier (if any) is non-dependent and the
29327      template-name of the simple-template-id names a deducible template.  */
29328
29329   if (DECL_CLASS_TEMPLATE_P (tmpl)
29330       || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
29331     return true;
29332   if (!DECL_ALIAS_TEMPLATE_P (tmpl))
29333     return false;
29334   tree orig = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
29335   if (tree tinfo = get_template_info (orig))
29336     return ctad_template_p (TI_TEMPLATE (tinfo));
29337   return false;
29338 }
29339
29340 /* Deduce template arguments for the class template placeholder PTYPE for
29341    template TMPL based on the initializer INIT, and return the resulting
29342    type.  */
29343
29344 static tree
29345 do_class_deduction (tree ptype, tree tmpl, tree init,
29346                     int flags, tsubst_flags_t complain)
29347 {
29348   /* We should have handled this in the caller.  */
29349   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
29350     return ptype;
29351
29352   /* Wait until the enclosing scope is non-dependent.  */
29353   if (DECL_CLASS_SCOPE_P (tmpl)
29354       && dependent_type_p (DECL_CONTEXT (tmpl)))
29355     return ptype;
29356
29357   /* Initializing one placeholder from another.  */
29358   if (init
29359       && (TREE_CODE (init) == TEMPLATE_PARM_INDEX
29360           || (TREE_CODE (init) == EXPR_PACK_EXPANSION
29361               && (TREE_CODE (PACK_EXPANSION_PATTERN (init))
29362                   == TEMPLATE_PARM_INDEX)))
29363       && is_auto (TREE_TYPE (init))
29364       && CLASS_PLACEHOLDER_TEMPLATE (TREE_TYPE (init)) == tmpl)
29365     return cp_build_qualified_type (TREE_TYPE (init), cp_type_quals (ptype));
29366
29367   /* Look through alias templates that just rename another template.  */
29368   tmpl = get_underlying_template (tmpl);
29369   if (!ctad_template_p (tmpl))
29370     {
29371       if (complain & tf_error)
29372         error ("non-deducible template %qT used without template arguments", tmpl);
29373       return error_mark_node;
29374     }
29375   else if (cxx_dialect < cxx20 && DECL_ALIAS_TEMPLATE_P (tmpl))
29376     {
29377       if (complain & tf_error)
29378         error ("alias template deduction only available "
29379                "with %<-std=c++20%> or %<-std=gnu++20%>");
29380       return error_mark_node;
29381     }
29382
29383   /* Wait until the initializer is non-dependent.  */
29384   if (type_dependent_expression_p (init))
29385     return ptype;
29386
29387   tree type = TREE_TYPE (tmpl);
29388
29389   bool try_list_ctor = false;
29390   bool list_init_p = false;
29391
29392   releasing_vec rv_args = NULL;
29393   vec<tree,va_gc> *&args = *&rv_args;
29394   if (init == NULL_TREE)
29395     args = make_tree_vector ();
29396   else if (BRACE_ENCLOSED_INITIALIZER_P (init))
29397     {
29398       list_init_p = true;
29399       try_list_ctor = TYPE_HAS_LIST_CTOR (type);
29400       if (try_list_ctor && CONSTRUCTOR_NELTS (init) == 1)
29401         {
29402           /* As an exception, the first phase in 16.3.1.7 (considering the
29403              initializer list as a single argument) is omitted if the
29404              initializer list consists of a single expression of type cv U,
29405              where U is a specialization of C or a class derived from a
29406              specialization of C.  */
29407           tree elt = CONSTRUCTOR_ELT (init, 0)->value;
29408           if (is_spec_or_derived (TREE_TYPE (elt), tmpl))
29409             try_list_ctor = false;
29410         }
29411       if (try_list_ctor || is_std_init_list (type))
29412         args = make_tree_vector_single (init);
29413       else
29414         args = make_tree_vector_from_ctor (init);
29415     }
29416   else if (TREE_CODE (init) == TREE_LIST)
29417     args = make_tree_vector_from_list (init);
29418   else
29419     args = make_tree_vector_single (init);
29420
29421   /* Do this now to avoid problems with erroneous args later on.  */
29422   args = resolve_args (args, complain);
29423   if (args == NULL)
29424     return error_mark_node;
29425
29426   bool any_dguides_p = false;
29427   tree cands = deduction_guides_for (tmpl, any_dguides_p, complain);
29428   if (cands == error_mark_node)
29429     return error_mark_node;
29430
29431   /* Prune explicit deduction guides in copy-initialization context (but
29432      not copy-list-initialization).  */
29433   bool elided = false;
29434   if (!list_init_p && (flags & LOOKUP_ONLYCONVERTING))
29435     {
29436       for (lkp_iterator iter (cands); !elided && iter; ++iter)
29437         if (DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
29438           elided = true;
29439
29440       if (elided)
29441         {
29442           /* Found a nonconverting guide, prune the candidates.  */
29443           tree pruned = NULL_TREE;
29444           for (lkp_iterator iter (cands); iter; ++iter)
29445             if (!DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
29446               pruned = lookup_add (*iter, pruned);
29447
29448           cands = pruned;
29449         }
29450     }
29451
29452   if (!any_dguides_p)
29453     if (tree guide = maybe_aggr_guide (tmpl, init, args))
29454       cands = lookup_add (guide, cands);
29455
29456   tree call = error_mark_node;
29457
29458   /* If this is list-initialization and the class has a list constructor, first
29459      try deducing from the list as a single argument, as [over.match.list].  */
29460   tree list_cands = NULL_TREE;
29461   if (try_list_ctor && cands)
29462     for (lkp_iterator iter (cands); iter; ++iter)
29463       {
29464         tree dg = *iter;
29465         if (is_list_ctor (dg))
29466           list_cands = lookup_add (dg, list_cands);
29467       }
29468   if (list_cands)
29469     {
29470       ++cp_unevaluated_operand;
29471       call = build_new_function_call (list_cands, &args, tf_decltype);
29472       --cp_unevaluated_operand;
29473
29474       if (call == error_mark_node)
29475         {
29476           /* That didn't work, now try treating the list as a sequence of
29477              arguments.  */
29478           release_tree_vector (args);
29479           args = make_tree_vector_from_ctor (init);
29480         }
29481     }
29482
29483   if (elided && !cands)
29484     {
29485       error ("cannot deduce template arguments for copy-initialization"
29486              " of %qT, as it has no non-explicit deduction guides or "
29487              "user-declared constructors", type);
29488       return error_mark_node;
29489     }
29490   else if (!cands && call == error_mark_node)
29491     {
29492       error ("cannot deduce template arguments of %qT, as it has no viable "
29493              "deduction guides", type);
29494       return error_mark_node;
29495     }
29496
29497   if (call == error_mark_node)
29498     {
29499       ++cp_unevaluated_operand;
29500       call = build_new_function_call (cands, &args, tf_decltype);
29501       --cp_unevaluated_operand;
29502     }
29503
29504   if (call == error_mark_node)
29505     {
29506       if (complain & tf_warning_or_error)
29507         {
29508           error ("class template argument deduction failed:");
29509
29510           ++cp_unevaluated_operand;
29511           call = build_new_function_call (cands, &args,
29512                                           complain | tf_decltype);
29513           --cp_unevaluated_operand;
29514
29515           if (elided)
29516             inform (input_location, "explicit deduction guides not considered "
29517                     "for copy-initialization");
29518         }
29519       return error_mark_node;
29520     }
29521   /* [over.match.list]/1: In copy-list-initialization, if an explicit
29522      constructor is chosen, the initialization is ill-formed.  */
29523   else if (flags & LOOKUP_ONLYCONVERTING)
29524     {
29525       tree fndecl = cp_get_callee_fndecl_nofold (call);
29526       if (fndecl && DECL_NONCONVERTING_P (fndecl))
29527         {
29528           if (complain & tf_warning_or_error)
29529             {
29530               // TODO: Pass down location from cp_finish_decl.
29531               error ("class template argument deduction for %qT failed: "
29532                      "explicit deduction guide selected in "
29533                      "copy-list-initialization", type);
29534               inform (DECL_SOURCE_LOCATION (fndecl),
29535                       "explicit deduction guide declared here");
29536
29537             }
29538           return error_mark_node;
29539         }
29540     }
29541
29542   /* If CTAD succeeded but the type doesn't have any explicit deduction
29543      guides, this deduction might not be what the user intended.  */
29544   if (call != error_mark_node && !any_dguides_p)
29545     {
29546       tree fndecl = cp_get_callee_fndecl_nofold (call);
29547       if (fndecl != NULL_TREE
29548           && (!DECL_IN_SYSTEM_HEADER (fndecl)
29549               || global_dc->dc_warn_system_headers)
29550           && warning (OPT_Wctad_maybe_unsupported,
29551                       "%qT may not intend to support class template argument "
29552                       "deduction", type))
29553         inform (input_location, "add a deduction guide to suppress this "
29554                 "warning");
29555     }
29556
29557   return cp_build_qualified_type (TREE_TYPE (call), cp_type_quals (ptype));
29558 }
29559
29560 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
29561    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
29562    The CONTEXT determines the context in which auto deduction is performed
29563    and is used to control error diagnostics.  FLAGS are the LOOKUP_* flags.
29564
29565    OUTER_TARGS is used during template argument deduction (context == adc_unify)
29566    to properly substitute the result.  It's also used in the adc_unify and
29567    adc_requirement contexts to communicate the the necessary template arguments
29568    to satisfaction.  OUTER_TARGS is ignored in other contexts.
29569
29570    For partial-concept-ids, extra args may be appended to the list of deduced
29571    template arguments prior to determining constraint satisfaction.  */
29572
29573 tree
29574 do_auto_deduction (tree type, tree init, tree auto_node,
29575                    tsubst_flags_t complain, auto_deduction_context context,
29576                    tree outer_targs, int flags)
29577 {
29578   if (init == error_mark_node)
29579     return error_mark_node;
29580
29581   if (init && type_dependent_expression_p (init)
29582       && context != adc_unify)
29583     /* Defining a subset of type-dependent expressions that we can deduce
29584        from ahead of time isn't worth the trouble.  */
29585     return type;
29586
29587   /* Similarly, we can't deduce from another undeduced decl.  */
29588   if (init && undeduced_auto_decl (init))
29589     return type;
29590
29591   /* We may be doing a partial substitution, but we still want to replace
29592      auto_node.  */
29593   complain &= ~tf_partial;
29594
29595   if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
29596     /* C++17 class template argument deduction.  */
29597     return do_class_deduction (type, tmpl, init, flags, complain);
29598
29599   if (init == NULL_TREE || TREE_TYPE (init) == NULL_TREE)
29600     /* Nothing we can do with this, even in deduction context.  */
29601     return type;
29602
29603   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
29604      with either a new invented type template parameter U or, if the
29605      initializer is a braced-init-list (8.5.4), with
29606      std::initializer_list<U>.  */
29607   if (BRACE_ENCLOSED_INITIALIZER_P (init))
29608     {
29609       if (!DIRECT_LIST_INIT_P (init))
29610         type = listify_autos (type, auto_node);
29611       else if (CONSTRUCTOR_NELTS (init) == 1)
29612         init = CONSTRUCTOR_ELT (init, 0)->value;
29613       else
29614         {
29615           if (complain & tf_warning_or_error)
29616             {
29617               if (permerror (input_location, "direct-list-initialization of "
29618                              "%<auto%> requires exactly one element"))
29619                 inform (input_location,
29620                         "for deduction to %<std::initializer_list%>, use copy-"
29621                         "list-initialization (i.e. add %<=%> before the %<{%>)");
29622             }
29623           type = listify_autos (type, auto_node);
29624         }
29625     }
29626
29627   if (type == error_mark_node)
29628     return error_mark_node;
29629
29630   if (BRACE_ENCLOSED_INITIALIZER_P (init))
29631     {
29632       /* We don't recurse here because we can't deduce from a nested
29633          initializer_list.  */
29634       if (CONSTRUCTOR_ELTS (init))
29635         for (constructor_elt &elt : CONSTRUCTOR_ELTS (init))
29636           elt.value = resolve_nondeduced_context (elt.value, complain);
29637     }
29638   else
29639     init = resolve_nondeduced_context (init, complain);
29640
29641   tree targs;
29642   if (context == adc_decomp_type
29643       && auto_node == type
29644       && init != error_mark_node
29645       && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
29646     {
29647       /* [dcl.struct.bind]/1 - if decomposition declaration has no ref-qualifiers
29648          and initializer has array type, deduce cv-qualified array type.  */
29649       targs = make_tree_vec (1);
29650       TREE_VEC_ELT (targs, 0) = TREE_TYPE (init);
29651     }
29652   else if (AUTO_IS_DECLTYPE (auto_node))
29653     {
29654       tree stripped_init = tree_strip_any_location_wrapper (init);
29655       if (REFERENCE_REF_P (stripped_init))
29656         stripped_init = TREE_OPERAND (stripped_init, 0);
29657       bool id = (DECL_P (stripped_init)
29658                  || ((TREE_CODE (init) == COMPONENT_REF
29659                       || TREE_CODE (init) == SCOPE_REF)
29660                      && !REF_PARENTHESIZED_P (init)));
29661       tree deduced = finish_decltype_type (init, id, complain);
29662       deduced = canonicalize_type_argument (deduced, complain);
29663       if (deduced == error_mark_node)
29664         return error_mark_node;
29665       targs = make_tree_vec (1);
29666       TREE_VEC_ELT (targs, 0) = deduced;
29667       /* FIXME: These errors ought to be diagnosed at parse time. */
29668       if (type != auto_node)
29669         {
29670           if (complain & tf_error)
29671             error ("%qT as type rather than plain %<decltype(auto)%>", type);
29672           return error_mark_node;
29673         }
29674       else if (TYPE_QUALS (type) != TYPE_UNQUALIFIED)
29675         {
29676           if (complain & tf_error)
29677             error ("%<decltype(auto)%> cannot be cv-qualified");
29678           return error_mark_node;
29679         }
29680     }
29681   else
29682     {
29683       if (error_operand_p (init))
29684         return error_mark_node;
29685
29686       tree parms = build_tree_list (NULL_TREE, type);
29687       tree tparms;
29688
29689       if (flag_concepts)
29690         tparms = extract_autos (type);
29691       else
29692         {
29693           tparms = make_tree_vec (1);
29694           TREE_VEC_ELT (tparms, 0)
29695             = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
29696         }
29697
29698       targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
29699       int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
29700                                        DEDUCE_CALL,
29701                                        NULL, /*explain_p=*/false);
29702       if (val > 0)
29703         {
29704           if (processing_template_decl)
29705             /* Try again at instantiation time.  */
29706             return type;
29707           if (type && type != error_mark_node
29708               && (complain & tf_error))
29709             /* If type is error_mark_node a diagnostic must have been
29710                emitted by now.  Also, having a mention to '<type error>'
29711                in the diagnostic is not really useful to the user.  */
29712             {
29713               if (cfun
29714                   && FNDECL_USED_AUTO (current_function_decl)
29715                   && (auto_node
29716                       == DECL_SAVED_AUTO_RETURN_TYPE (current_function_decl))
29717                   && LAMBDA_FUNCTION_P (current_function_decl))
29718                 error ("unable to deduce lambda return type from %qE", init);
29719               else
29720                 error ("unable to deduce %qT from %qE", type, init);
29721               type_unification_real (tparms, targs, parms, &init, 1, 0,
29722                                      DEDUCE_CALL,
29723                                      NULL, /*explain_p=*/true);
29724             }
29725           return error_mark_node;
29726         }
29727     }
29728
29729   /* Check any placeholder constraints against the deduced type. */
29730   if (processing_template_decl && context == adc_unify)
29731     /* Constraints will be checked after deduction.  */;
29732   else if (tree constr = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (auto_node)))
29733     {
29734       if (processing_template_decl)
29735         {
29736           gcc_checking_assert (context == adc_variable_type
29737                                || context == adc_return_type
29738                                || context == adc_decomp_type);
29739           gcc_checking_assert (!type_dependent_expression_p (init));
29740           /* If the constraint is dependent, we need to wait until
29741              instantiation time to resolve the placeholder.  */
29742           if (placeholder_type_constraint_dependent_p (constr))
29743             return type;
29744         }
29745
29746       if ((context == adc_return_type
29747            || context == adc_variable_type
29748            || context == adc_decomp_type)
29749           && current_function_decl
29750           && DECL_TEMPLATE_INFO (current_function_decl))
29751         outer_targs = DECL_TI_ARGS (current_function_decl);
29752
29753       tree full_targs = add_to_template_args (outer_targs, targs);
29754
29755       /* HACK: Compensate for callers not always communicating all levels of
29756          outer template arguments by filling in the outermost missing levels
29757          with dummy levels before checking satisfaction.  We'll still crash
29758          if the constraint depends on a template argument belonging to one of
29759          these missing levels, but this hack otherwise allows us to handle a
29760          large subset of possible constraints (including all non-dependent
29761          constraints).  */
29762       if (int missing_levels = (TEMPLATE_TYPE_ORIG_LEVEL (auto_node)
29763                                 - TMPL_ARGS_DEPTH (full_targs)))
29764         {
29765           tree dummy_levels = make_tree_vec (missing_levels);
29766           for (int i = 0; i < missing_levels; ++i)
29767             TREE_VEC_ELT (dummy_levels, i) = make_tree_vec (0);
29768           full_targs = add_to_template_args (dummy_levels, full_targs);
29769         }
29770
29771       if (!constraints_satisfied_p (auto_node, full_targs))
29772         {
29773           if (complain & tf_warning_or_error)
29774             {
29775               auto_diagnostic_group d;
29776               switch (context)
29777                 {
29778                 case adc_unspecified:
29779                 case adc_unify:
29780                   error("placeholder constraints not satisfied");
29781                   break;
29782                 case adc_variable_type:
29783                 case adc_decomp_type:
29784                   error ("deduced initializer does not satisfy "
29785                          "placeholder constraints");
29786                   break;
29787                 case adc_return_type:
29788                   error ("deduced return type does not satisfy "
29789                          "placeholder constraints");
29790                   break;
29791                 case adc_requirement:
29792                   error ("deduced expression type does not satisfy "
29793                          "placeholder constraints");
29794                   break;
29795                 }
29796               diagnose_constraints (input_location, auto_node, full_targs);
29797             }
29798           return error_mark_node;
29799         }
29800     }
29801
29802   if (TEMPLATE_TYPE_LEVEL (auto_node) == 1)
29803     /* The outer template arguments are already substituted into type
29804        (but we still may have used them for constraint checking above).  */;
29805   else if (context == adc_unify)
29806     targs = add_to_template_args (outer_targs, targs);
29807   else if (processing_template_decl)
29808     targs = add_to_template_args (current_template_args (), targs);
29809   return tsubst (type, targs, complain, NULL_TREE);
29810 }
29811
29812 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
29813    result.  */
29814
29815 tree
29816 splice_late_return_type (tree type, tree late_return_type)
29817 {
29818   if (late_return_type)
29819     {
29820       gcc_assert (is_auto (type) || seen_error ());
29821       return late_return_type;
29822     }
29823
29824   if (tree auto_node = find_type_usage (type, is_auto))
29825     if (TEMPLATE_TYPE_LEVEL (auto_node) <= processing_template_decl)
29826       {
29827         /* In an abbreviated function template we didn't know we were dealing
29828            with a function template when we saw the auto return type, so rebuild
29829            the return type using an auto with the correct level.  */
29830         tree new_auto = make_auto_1 (TYPE_IDENTIFIER (auto_node), false);
29831         tree auto_vec = make_tree_vec (1);
29832         TREE_VEC_ELT (auto_vec, 0) = new_auto;
29833         tree targs = add_outermost_template_args (current_template_args (),
29834                                                   auto_vec);
29835         /* Also rebuild the constraint info in terms of the new auto.  */
29836         if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (auto_node))
29837           PLACEHOLDER_TYPE_CONSTRAINTS_INFO (new_auto)
29838             = build_tree_list (current_template_parms,
29839                                tsubst_constraint (TREE_VALUE (ci), targs,
29840                                                   tf_none, NULL_TREE));
29841         TYPE_CANONICAL (new_auto) = canonical_type_parameter (new_auto);
29842         return tsubst (type, targs, tf_none, NULL_TREE);
29843       }
29844   return type;
29845 }
29846
29847 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
29848    'decltype(auto)' or a deduced class template.  */
29849
29850 bool
29851 is_auto (const_tree type)
29852 {
29853   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
29854       && (TYPE_IDENTIFIER (type) == auto_identifier
29855           || TYPE_IDENTIFIER (type) == decltype_auto_identifier))
29856     return true;
29857   else
29858     return false;
29859 }
29860
29861 /* for_each_template_parm callback for type_uses_auto.  */
29862
29863 int
29864 is_auto_r (tree tp, void */*data*/)
29865 {
29866   return is_auto (tp);
29867 }
29868
29869 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
29870    a use of `auto'.  Returns NULL_TREE otherwise.  */
29871
29872 tree
29873 type_uses_auto (tree type)
29874 {
29875   if (type == NULL_TREE)
29876     return NULL_TREE;
29877   else if (flag_concepts)
29878     {
29879       /* The Concepts TS allows multiple autos in one type-specifier; just
29880          return the first one we find, do_auto_deduction will collect all of
29881          them.  */
29882       if (uses_template_parms (type))
29883         return for_each_template_parm (type, is_auto_r, /*data*/NULL,
29884                                        /*visited*/NULL, /*nondeduced*/false);
29885       else
29886         return NULL_TREE;
29887     }
29888   else
29889     return find_type_usage (type, is_auto);
29890 }
29891
29892 /* Report ill-formed occurrences of auto types in ARGUMENTS.  If
29893    concepts are enabled, auto is acceptable in template arguments, but
29894    only when TEMPL identifies a template class.  Return TRUE if any
29895    such errors were reported.  */
29896
29897 bool
29898 check_auto_in_tmpl_args (tree tmpl, tree args)
29899 {
29900   /* If there were previous errors, nevermind.  */
29901   if (!args || TREE_CODE (args) != TREE_VEC)
29902     return false;
29903
29904   /* If TMPL is an identifier, we're parsing and we can't tell yet
29905      whether TMPL is supposed to be a type, a function or a variable.
29906      We'll only be able to tell during template substitution, so we
29907      expect to be called again then.  If concepts are enabled and we
29908      know we have a type, we're ok.  */
29909   if (flag_concepts
29910       && (identifier_p (tmpl)
29911           || (DECL_P (tmpl)
29912               &&  (DECL_TYPE_TEMPLATE_P (tmpl)
29913                    || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)))))
29914     return false;
29915
29916   /* Quickly search for any occurrences of auto; usually there won't
29917      be any, and then we'll avoid allocating the vector.  */
29918   if (!type_uses_auto (args))
29919     return false;
29920
29921   bool errors = false;
29922
29923   tree vec = extract_autos (args);
29924   for (int i = 0; i < TREE_VEC_LENGTH (vec); i++)
29925     {
29926       tree xauto = TREE_VALUE (TREE_VEC_ELT (vec, i));
29927       error_at (DECL_SOURCE_LOCATION (xauto),
29928                 "invalid use of %qT in template argument", xauto);
29929       errors = true;
29930     }
29931
29932   return errors;
29933 }
29934
29935 /* Recursively walk over && expressions searching for EXPR. Return a reference
29936    to that expression.  */
29937
29938 static tree *find_template_requirement (tree *t, tree key)
29939 {
29940   if (*t == key)
29941     return t;
29942   if (TREE_CODE (*t) == TRUTH_ANDIF_EXPR)
29943     {
29944       if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 0), key))
29945         return p;
29946       if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 1), key))
29947         return p;
29948     }
29949   return 0;
29950 }
29951
29952 /* Convert the generic type parameters in PARM that match the types given in the
29953    range [START_IDX, END_IDX) from the current_template_parms into generic type
29954    packs.  */
29955
29956 tree
29957 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
29958 {
29959   tree current = current_template_parms;
29960   int depth = TMPL_PARMS_DEPTH (current);
29961   current = INNERMOST_TEMPLATE_PARMS (current);
29962   tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
29963
29964   for (int i = 0; i < start_idx; ++i)
29965     TREE_VEC_ELT (replacement, i)
29966       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
29967
29968   for (int i = start_idx; i < end_idx; ++i)
29969     {
29970       /* Create a distinct parameter pack type from the current parm and add it
29971          to the replacement args to tsubst below into the generic function
29972          parameter.  */
29973       tree node = TREE_VEC_ELT (current, i);
29974       tree o = TREE_TYPE (TREE_VALUE (node));
29975       tree t = copy_type (o);
29976       TEMPLATE_TYPE_PARM_INDEX (t)
29977         = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
29978                                       t, 0, 0, tf_none);
29979       TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
29980       TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
29981       TYPE_MAIN_VARIANT (t) = t;
29982       TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
29983       TYPE_CANONICAL (t) = canonical_type_parameter (t);
29984       TREE_VEC_ELT (replacement, i) = t;
29985
29986       /* Replace the current template parameter with new pack.  */
29987       TREE_VALUE (node) = TREE_CHAIN (t);
29988
29989       /* Surgically adjust the associated constraint of adjusted parameter
29990          and it's corresponding contribution to the current template
29991          requirements.  */
29992       if (tree constr = TEMPLATE_PARM_CONSTRAINTS (node))
29993         {
29994           tree id = unpack_concept_check (constr);
29995           TREE_VEC_ELT (TREE_OPERAND (id, 1), 0) = t;
29996           tree fold = finish_left_unary_fold_expr (constr, TRUTH_ANDIF_EXPR);
29997           TEMPLATE_PARM_CONSTRAINTS (node) = fold;
29998
29999           /* If there was a constraint, we also need to replace that in
30000              the template requirements, which we've already built.  */
30001           tree *reqs = &TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
30002           reqs = find_template_requirement (reqs, constr);
30003           *reqs = fold;
30004         }
30005     }
30006
30007   for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
30008     TREE_VEC_ELT (replacement, i)
30009       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
30010
30011   /* If there are more levels then build up the replacement with the outer
30012      template parms.  */
30013   if (depth > 1)
30014     replacement = add_to_template_args (template_parms_to_args
30015                                         (TREE_CHAIN (current_template_parms)),
30016                                         replacement);
30017
30018   return tsubst (parm, replacement, tf_none, NULL_TREE);
30019 }
30020
30021 /* __integer_pack(N) in a pack expansion expands to a sequence of numbers from
30022    0..N-1.  */
30023
30024 void
30025 declare_integer_pack (void)
30026 {
30027   tree ipfn = push_library_fn (get_identifier ("__integer_pack"),
30028                                build_function_type_list (integer_type_node,
30029                                                          integer_type_node,
30030                                                          NULL_TREE),
30031                                NULL_TREE, ECF_CONST);
30032   DECL_DECLARED_CONSTEXPR_P (ipfn) = true;
30033   set_decl_built_in_function (ipfn, BUILT_IN_FRONTEND,
30034                               CP_BUILT_IN_INTEGER_PACK);
30035 }
30036
30037 /* Walk the decl or type specialization table calling FN on each
30038    entry.  */
30039
30040 void
30041 walk_specializations (bool decls_p,
30042                       void (*fn) (bool decls_p, spec_entry *entry, void *data),
30043                       void *data)
30044 {
30045   spec_hash_table *table = decls_p ? decl_specializations
30046     : type_specializations;
30047   spec_hash_table::iterator end (table->end ());
30048   for (spec_hash_table::iterator iter (table->begin ()); iter != end; ++iter)
30049     fn (decls_p, *iter, data);
30050 }
30051
30052 /* Lookup the specialization of *ELT, in the decl or type
30053    specialization table.  Return the SPEC that's already there, or
30054    NULL if nothing.  */
30055
30056 tree
30057 match_mergeable_specialization (bool decl_p, spec_entry *elt)
30058 {
30059   hash_table<spec_hasher> *specializations
30060     = decl_p ? decl_specializations : type_specializations;
30061   hashval_t hash = spec_hasher::hash (elt);
30062   auto *slot = specializations->find_slot_with_hash (elt, hash, NO_INSERT);
30063
30064   if (slot)
30065     return (*slot)->spec;
30066
30067   return NULL_TREE;
30068 }
30069
30070 /* Return flags encoding whether SPEC is on the instantiation and/or
30071    specialization lists of TMPL.  */
30072
30073 unsigned
30074 get_mergeable_specialization_flags (tree tmpl, tree decl)
30075 {
30076   unsigned flags = 0;
30077
30078   for (tree inst = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
30079        inst; inst = TREE_CHAIN (inst))
30080     if (TREE_VALUE (inst) == decl)
30081       {
30082         flags |= 1;
30083         break;
30084       }
30085
30086   if (CLASS_TYPE_P (TREE_TYPE (decl))
30087       && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl))
30088       && CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)) == 2)
30089     /* Only need to search if DECL is a partial specialization.  */
30090     for (tree part = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
30091          part; part = TREE_CHAIN (part))
30092       if (TREE_VALUE (part) == decl)
30093         {
30094           flags |= 2;
30095           break;
30096         }
30097
30098   return flags;
30099 }
30100
30101 /* Add a new specialization described by SPEC.  DECL is the
30102    maybe-template decl and FLAGS is as returned from
30103    get_mergeable_specialization_flags.  */
30104
30105 void
30106 add_mergeable_specialization (bool decl_p, bool alias_p, spec_entry *elt,
30107                               tree decl, unsigned flags)
30108 {
30109   hashval_t hash = spec_hasher::hash (elt);
30110   if (decl_p)
30111     {
30112       auto *slot = decl_specializations->find_slot_with_hash (elt, hash, INSERT);
30113
30114       gcc_checking_assert (!*slot);
30115       auto entry = ggc_alloc<spec_entry> ();
30116       *entry = *elt;
30117       *slot = entry;
30118
30119       if (alias_p)
30120         {
30121           elt->spec = TREE_TYPE (elt->spec);
30122           gcc_checking_assert (elt->spec);
30123         }
30124     }
30125
30126   if (!decl_p || alias_p)
30127     {
30128       auto *slot = type_specializations->find_slot_with_hash (elt, hash, INSERT);
30129
30130       /* We don't distinguish different constrained partial type
30131          specializations, so there could be duplicates.  Everything else
30132          must be new.   */
30133       if (!(flags & 2 && *slot))
30134         {
30135           gcc_checking_assert (!*slot);
30136
30137           auto entry = ggc_alloc<spec_entry> ();
30138           *entry = *elt;
30139           *slot = entry;
30140         }
30141     }
30142
30143   if (flags & 1)
30144     DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl)
30145       = tree_cons (elt->args, decl, DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl));
30146
30147   if (flags & 2)
30148     {
30149       /* A partial specialization.  */
30150       tree cons = tree_cons (elt->args, decl,
30151                              DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl));
30152       TREE_TYPE (cons) = elt->spec;
30153       DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl) = cons;
30154     }
30155 }
30156
30157 /* Set up the hash tables for template instantiations.  */
30158
30159 void
30160 init_template_processing (void)
30161 {
30162   decl_specializations = hash_table<spec_hasher>::create_ggc (37);
30163   type_specializations = hash_table<spec_hasher>::create_ggc (37);
30164
30165   if (cxx_dialect >= cxx11)
30166     declare_integer_pack ();
30167 }
30168
30169 /* Print stats about the template hash tables for -fstats.  */
30170
30171 void
30172 print_template_statistics (void)
30173 {
30174   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
30175            "%f collisions\n", (long) decl_specializations->size (),
30176            (long) decl_specializations->elements (),
30177            decl_specializations->collisions ());
30178   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
30179            "%f collisions\n", (long) type_specializations->size (),
30180            (long) type_specializations->elements (),
30181            type_specializations->collisions ());
30182 }
30183
30184 #if CHECKING_P
30185
30186 namespace selftest {
30187
30188 /* Verify that build_non_dependent_expr () works, for various expressions,
30189    and that location wrappers don't affect the results.  */
30190
30191 static void
30192 test_build_non_dependent_expr ()
30193 {
30194   location_t loc = BUILTINS_LOCATION;
30195
30196   /* Verify constants, without and with location wrappers.  */
30197   tree int_cst = build_int_cst (integer_type_node, 42);
30198   ASSERT_EQ (int_cst, build_non_dependent_expr (int_cst));
30199
30200   tree wrapped_int_cst = maybe_wrap_with_location (int_cst, loc);
30201   ASSERT_TRUE (location_wrapper_p (wrapped_int_cst));
30202   ASSERT_EQ (wrapped_int_cst, build_non_dependent_expr (wrapped_int_cst));
30203
30204   tree string_lit = build_string (4, "foo");
30205   TREE_TYPE (string_lit) = char_array_type_node;
30206   string_lit = fix_string_type (string_lit);
30207   ASSERT_EQ (string_lit, build_non_dependent_expr (string_lit));
30208
30209   tree wrapped_string_lit = maybe_wrap_with_location (string_lit, loc);
30210   ASSERT_TRUE (location_wrapper_p (wrapped_string_lit));
30211   ASSERT_EQ (wrapped_string_lit,
30212              build_non_dependent_expr (wrapped_string_lit));
30213 }
30214
30215 /* Verify that type_dependent_expression_p () works correctly, even
30216    in the presence of location wrapper nodes.  */
30217
30218 static void
30219 test_type_dependent_expression_p ()
30220 {
30221   location_t loc = BUILTINS_LOCATION;
30222
30223   tree name = get_identifier ("foo");
30224
30225   /* If no templates are involved, nothing is type-dependent.  */
30226   gcc_assert (!processing_template_decl);
30227   ASSERT_FALSE (type_dependent_expression_p (name));
30228
30229   ++processing_template_decl;
30230
30231   /* Within a template, an unresolved name is always type-dependent.  */
30232   ASSERT_TRUE (type_dependent_expression_p (name));
30233
30234   /* Ensure it copes with NULL_TREE and errors.  */
30235   ASSERT_FALSE (type_dependent_expression_p (NULL_TREE));
30236   ASSERT_FALSE (type_dependent_expression_p (error_mark_node));
30237
30238   /* A USING_DECL in a template should be type-dependent, even if wrapped
30239      with a location wrapper (PR c++/83799).  */
30240   tree using_decl = build_lang_decl (USING_DECL, name, NULL_TREE);
30241   TREE_TYPE (using_decl) = integer_type_node;
30242   ASSERT_TRUE (type_dependent_expression_p (using_decl));
30243   tree wrapped_using_decl = maybe_wrap_with_location (using_decl, loc);
30244   ASSERT_TRUE (location_wrapper_p (wrapped_using_decl));
30245   ASSERT_TRUE (type_dependent_expression_p (wrapped_using_decl));
30246
30247   --processing_template_decl;
30248 }
30249
30250 /* Run all of the selftests within this file.  */
30251
30252 void
30253 cp_pt_c_tests ()
30254 {
30255   test_build_non_dependent_expr ();
30256   test_type_dependent_expression_p ();
30257 }
30258
30259 } // namespace selftest
30260
30261 #endif /* #if CHECKING_P */
30262
30263 #include "gt-cp-pt.h"