xref: /netbsd-src/external/gpl3/gcc/dist/gcc/cp/pt.cc (revision 0a3071956a3a9fdebdbf7f338cf2d439b45fc728)
1 /* Handle parameterized types (templates) for GNU -*- C++ -*-.
2    Copyright (C) 1992-2022 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.
local_specialization_stack(lss_policy policy)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 
~local_specialization_stack()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, unification_kind_t, int,
156 					   struct conversion **, bool);
157 static int maybe_adjust_types_for_deduction (tree, unification_kind_t,
158 					     tree*, tree*, 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 static void tsubst_each_template_parm_constraints (tree, tree, tsubst_flags_t);
188 tree most_specialized_partial_spec (tree, tsubst_flags_t);
189 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
190 static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
191 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
192 static bool check_specialization_scope (void);
193 static tree process_partial_specialization (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    for a class or alias template (needed by instantiate_decl).  */
229 
230 void
push_access_scope(tree t)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_IMPLICIT_TYPEDEF_P (t)
239 	   && CLASS_TYPE_P (TREE_TYPE (t)))
240     push_nested_class (TREE_TYPE (t));
241   else if (DECL_CLASS_SCOPE_P (t))
242     push_nested_class (DECL_CONTEXT (t));
243   else if (deduction_guide_p (t) && DECL_ARTIFICIAL (t))
244     /* An artificial deduction guide should have the same access as
245        the constructor.  */
246     push_nested_class (TREE_TYPE (TREE_TYPE (t)));
247   else
248     push_to_top_level ();
249 
250   if (TREE_CODE (t) == FUNCTION_DECL)
251     {
252       vec_safe_push (saved_access_scope, current_function_decl);
253       current_function_decl = t;
254     }
255 }
256 
257 /* Restore the scope set up by push_access_scope.  T is the node we
258    are processing.  */
259 
260 void
pop_access_scope(tree t)261 pop_access_scope (tree t)
262 {
263   if (TREE_CODE (t) == FUNCTION_DECL)
264     current_function_decl = saved_access_scope->pop();
265 
266   if (DECL_FRIEND_CONTEXT (t)
267       || (DECL_IMPLICIT_TYPEDEF_P (t)
268 	  && CLASS_TYPE_P (TREE_TYPE (t)))
269       || DECL_CLASS_SCOPE_P (t)
270       || (deduction_guide_p (t) && DECL_ARTIFICIAL (t)))
271     pop_nested_class ();
272   else
273     pop_from_top_level ();
274 }
275 
276 /* Do any processing required when DECL (a member template
277    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
278    to DECL, unless it is a specialization, in which case the DECL
279    itself is returned.  */
280 
281 tree
finish_member_template_decl(tree decl)282 finish_member_template_decl (tree decl)
283 {
284   if (decl == error_mark_node)
285     return error_mark_node;
286 
287   gcc_assert (DECL_P (decl));
288 
289   if (TREE_CODE (decl) == TYPE_DECL)
290     {
291       tree type;
292 
293       type = TREE_TYPE (decl);
294       if (type == error_mark_node)
295 	return error_mark_node;
296       if (MAYBE_CLASS_TYPE_P (type)
297 	  && CLASSTYPE_TEMPLATE_INFO (type)
298 	  && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
299 	{
300 	  tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
301 	  check_member_template (tmpl);
302 	  return tmpl;
303 	}
304       return NULL_TREE;
305     }
306   else if (TREE_CODE (decl) == FIELD_DECL)
307     error_at (DECL_SOURCE_LOCATION (decl),
308 	      "data member %qD cannot be a member template", decl);
309   else if (DECL_TEMPLATE_INFO (decl))
310     {
311       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
312 	{
313 	  check_member_template (DECL_TI_TEMPLATE (decl));
314 	  return DECL_TI_TEMPLATE (decl);
315 	}
316       else
317 	return decl;
318     }
319   else
320     error_at (DECL_SOURCE_LOCATION (decl),
321 	      "invalid member template declaration %qD", decl);
322 
323   return error_mark_node;
324 }
325 
326 /* Create a template info node.  */
327 
328 tree
build_template_info(tree template_decl,tree template_args)329 build_template_info (tree template_decl, tree template_args)
330 {
331   tree result = make_node (TEMPLATE_INFO);
332   TI_TEMPLATE (result) = template_decl;
333   TI_ARGS (result) = template_args;
334   return result;
335 }
336 
337 /* Return the template info node corresponding to T, whatever T is.  */
338 
339 tree
get_template_info(const_tree t)340 get_template_info (const_tree t)
341 {
342   tree tinfo = NULL_TREE;
343 
344   if (!t || t == error_mark_node)
345     return NULL;
346 
347   if (TREE_CODE (t) == NAMESPACE_DECL
348       || TREE_CODE (t) == PARM_DECL)
349     return NULL;
350 
351   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
352     tinfo = DECL_TEMPLATE_INFO (t);
353 
354   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
355     t = TREE_TYPE (t);
356 
357   if (OVERLOAD_TYPE_P (t))
358     tinfo = TYPE_TEMPLATE_INFO (t);
359   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
360     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
361 
362   return tinfo;
363 }
364 
365 /* Returns the template nesting level of the indicated class TYPE.
366 
367    For example, in:
368      template <class T>
369      struct A
370      {
371        template <class U>
372        struct B {};
373      };
374 
375    A<T>::B<U> has depth two, while A<T> has depth one.
376    Both A<T>::B<int> and A<int>::B<U> have depth one, if
377    they are instantiations, not specializations.
378 
379    This function is guaranteed to return 0 if passed NULL_TREE so
380    that, for example, `template_class_depth (current_class_type)' is
381    always safe.  */
382 
383 int
template_class_depth(tree type)384 template_class_depth (tree type)
385 {
386   int depth;
387 
388   for (depth = 0; type && TREE_CODE (type) != NAMESPACE_DECL; )
389     {
390       tree tinfo = get_template_info (type);
391 
392       if (tinfo
393 	  && TREE_CODE (TI_TEMPLATE (tinfo)) == TEMPLATE_DECL
394 	  && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
395 	  && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
396 	++depth;
397 
398       if (DECL_P (type))
399 	{
400 	  if (tree fctx = DECL_FRIEND_CONTEXT (type))
401 	    type = fctx;
402 	  else
403 	    type = CP_DECL_CONTEXT (type);
404 	}
405       else if (LAMBDA_TYPE_P (type) && LAMBDA_TYPE_EXTRA_SCOPE (type))
406 	type = LAMBDA_TYPE_EXTRA_SCOPE (type);
407       else
408 	type = CP_TYPE_CONTEXT (type);
409     }
410 
411   return depth;
412 }
413 
414 /* Return TRUE if NODE instantiates a template that has arguments of
415    its own, be it directly a primary template or indirectly through a
416    partial specializations.  */
417 static bool
instantiates_primary_template_p(tree node)418 instantiates_primary_template_p (tree node)
419 {
420   tree tinfo = get_template_info (node);
421   if (!tinfo)
422     return false;
423 
424   tree tmpl = TI_TEMPLATE (tinfo);
425   if (PRIMARY_TEMPLATE_P (tmpl))
426     return true;
427 
428   if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
429     return false;
430 
431   /* So now we know we have a specialization, but it could be a full
432      or a partial specialization.  To tell which, compare the depth of
433      its template arguments with those of its context.  */
434 
435   tree ctxt = DECL_CONTEXT (tmpl);
436   tree ctinfo = get_template_info (ctxt);
437   if (!ctinfo)
438     return true;
439 
440   return (TMPL_ARGS_DEPTH (TI_ARGS (tinfo))
441 	  > TMPL_ARGS_DEPTH (TI_ARGS (ctinfo)));
442 }
443 
444 /* Subroutine of maybe_begin_member_template_processing.
445    Returns true if processing DECL needs us to push template parms.  */
446 
447 static bool
inline_needs_template_parms(tree decl,bool nsdmi)448 inline_needs_template_parms (tree decl, bool nsdmi)
449 {
450   if (!decl || (!nsdmi && ! DECL_TEMPLATE_INFO (decl)))
451     return false;
452 
453   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
454 	  > (current_template_depth + DECL_TEMPLATE_SPECIALIZATION (decl)));
455 }
456 
457 /* Subroutine of maybe_begin_member_template_processing.
458    Push the template parms in PARMS, starting from LEVELS steps into the
459    chain, and ending at the beginning, since template parms are listed
460    innermost first.  */
461 
462 static void
push_inline_template_parms_recursive(tree parmlist,int levels)463 push_inline_template_parms_recursive (tree parmlist, int levels)
464 {
465   tree parms = TREE_VALUE (parmlist);
466   int i;
467 
468   if (levels > 1)
469     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
470 
471   ++processing_template_decl;
472   current_template_parms
473     = tree_cons (size_int (current_template_depth + 1),
474 		 parms, current_template_parms);
475   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
476 
477   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
478 	       NULL);
479   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
480     {
481       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
482 
483       if (error_operand_p (parm))
484 	continue;
485 
486       gcc_assert (DECL_P (parm));
487 
488       switch (TREE_CODE (parm))
489 	{
490 	case TYPE_DECL:
491 	case TEMPLATE_DECL:
492 	  pushdecl (parm);
493 	  break;
494 
495 	case PARM_DECL:
496 	  /* Push the CONST_DECL.  */
497 	  pushdecl (TEMPLATE_PARM_DECL (DECL_INITIAL (parm)));
498 	  break;
499 
500 	default:
501 	  gcc_unreachable ();
502 	}
503     }
504 }
505 
506 /* Restore the template parameter context for a member template, a
507    friend template defined in a class definition, or a non-template
508    member of template class.  */
509 
510 void
maybe_begin_member_template_processing(tree decl)511 maybe_begin_member_template_processing (tree decl)
512 {
513   tree parms;
514   int levels = 0;
515   bool nsdmi = TREE_CODE (decl) == FIELD_DECL;
516 
517   if (nsdmi)
518     {
519       tree ctx = DECL_CONTEXT (decl);
520       decl = (CLASSTYPE_TEMPLATE_INFO (ctx)
521 	      /* Disregard full specializations (c++/60999).  */
522 	      && uses_template_parms (ctx)
523 	      ? CLASSTYPE_TI_TEMPLATE (ctx) : NULL_TREE);
524     }
525 
526   if (inline_needs_template_parms (decl, nsdmi))
527     {
528       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
529       levels = TMPL_PARMS_DEPTH (parms) - current_template_depth;
530 
531       if (DECL_TEMPLATE_SPECIALIZATION (decl))
532 	{
533 	  --levels;
534 	  parms = TREE_CHAIN (parms);
535 	}
536 
537       push_inline_template_parms_recursive (parms, levels);
538     }
539 
540   /* Remember how many levels of template parameters we pushed so that
541      we can pop them later.  */
542   inline_parm_levels.safe_push (levels);
543 }
544 
545 /* Undo the effects of maybe_begin_member_template_processing.  */
546 
547 void
maybe_end_member_template_processing(void)548 maybe_end_member_template_processing (void)
549 {
550   int i;
551   int last;
552 
553   if (inline_parm_levels.length () == 0)
554     return;
555 
556   last = inline_parm_levels.pop ();
557   for (i = 0; i < last; ++i)
558     {
559       --processing_template_decl;
560       current_template_parms = TREE_CHAIN (current_template_parms);
561       poplevel (0, 0, 0);
562     }
563 }
564 
565 /* Return a new template argument vector which contains all of ARGS,
566    but has as its innermost set of arguments the EXTRA_ARGS.  */
567 
568 tree
add_to_template_args(tree args,tree extra_args)569 add_to_template_args (tree args, tree extra_args)
570 {
571   tree new_args;
572   int extra_depth;
573   int i;
574   int j;
575 
576   if (args == NULL_TREE || extra_args == error_mark_node)
577     return extra_args;
578 
579   extra_depth = TMPL_ARGS_DEPTH (extra_args);
580   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
581 
582   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
583     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
584 
585   for (j = 1; j <= extra_depth; ++j, ++i)
586     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
587 
588   return new_args;
589 }
590 
591 /* Like add_to_template_args, but only the outermost ARGS are added to
592    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
593    (EXTRA_ARGS) levels are added.  This function is used to combine
594    the template arguments from a partial instantiation with the
595    template arguments used to attain the full instantiation from the
596    partial instantiation.
597 
598    If ARGS is a TEMPLATE_DECL, use its parameters as args.  */
599 
600 tree
add_outermost_template_args(tree args,tree extra_args)601 add_outermost_template_args (tree args, tree extra_args)
602 {
603   tree new_args;
604 
605   if (!args)
606     return extra_args;
607   if (TREE_CODE (args) == TEMPLATE_DECL)
608     {
609       tree ti = get_template_info (DECL_TEMPLATE_RESULT (args));
610       args = TI_ARGS (ti);
611     }
612 
613   /* If there are more levels of EXTRA_ARGS than there are ARGS,
614      something very fishy is going on.  */
615   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
616 
617   /* If *all* the new arguments will be the EXTRA_ARGS, just return
618      them.  */
619   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
620     return extra_args;
621 
622   /* For the moment, we make ARGS look like it contains fewer levels.  */
623   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
624 
625   new_args = add_to_template_args (args, extra_args);
626 
627   /* Now, we restore ARGS to its full dimensions.  */
628   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
629 
630   return new_args;
631 }
632 
633 /* Return the N levels of innermost template arguments from the ARGS.  */
634 
635 tree
get_innermost_template_args(tree args,int n)636 get_innermost_template_args (tree args, int n)
637 {
638   tree new_args;
639   int extra_levels;
640   int i;
641 
642   gcc_assert (n >= 0);
643 
644   /* If N is 1, just return the innermost set of template arguments.  */
645   if (n == 1)
646     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
647 
648   /* If we're not removing anything, just return the arguments we were
649      given.  */
650   extra_levels = TMPL_ARGS_DEPTH (args) - n;
651   gcc_assert (extra_levels >= 0);
652   if (extra_levels == 0)
653     return args;
654 
655   /* Make a new set of arguments, not containing the outer arguments.  */
656   new_args = make_tree_vec (n);
657   for (i = 1; i <= n; ++i)
658     SET_TMPL_ARGS_LEVEL (new_args, i,
659 			 TMPL_ARGS_LEVEL (args, i + extra_levels));
660 
661   return new_args;
662 }
663 
664 /* The inverse of get_innermost_template_args: Return all but the innermost
665    EXTRA_LEVELS levels of template arguments from the ARGS.  */
666 
667 static tree
strip_innermost_template_args(tree args,int extra_levels)668 strip_innermost_template_args (tree args, int extra_levels)
669 {
670   tree new_args;
671   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
672   int i;
673 
674   gcc_assert (n >= 0);
675 
676   /* If N is 1, just return the outermost set of template arguments.  */
677   if (n == 1)
678     return TMPL_ARGS_LEVEL (args, 1);
679 
680   /* If we're not removing anything, just return the arguments we were
681      given.  */
682   gcc_assert (extra_levels >= 0);
683   if (extra_levels == 0)
684     return args;
685 
686   /* Make a new set of arguments, not containing the inner arguments.  */
687   new_args = make_tree_vec (n);
688   for (i = 1; i <= n; ++i)
689     SET_TMPL_ARGS_LEVEL (new_args, i,
690 			 TMPL_ARGS_LEVEL (args, i));
691 
692   return new_args;
693 }
694 
695 /* We've got a template header coming up; push to a new level for storing
696    the parms.  */
697 
698 void
begin_template_parm_list(void)699 begin_template_parm_list (void)
700 {
701   /* We use a non-tag-transparent scope here, which causes pushtag to
702      put tags in this scope, rather than in the enclosing class or
703      namespace scope.  This is the right thing, since we want
704      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
705      global template class, push_template_decl handles putting the
706      TEMPLATE_DECL into top-level scope.  For a nested template class,
707      e.g.:
708 
709        template <class T> struct S1 {
710 	 template <class T> struct S2 {};
711        };
712 
713      pushtag contains special code to insert the TEMPLATE_DECL for S2
714      at the right scope.  */
715   begin_scope (sk_template_parms, NULL);
716   ++processing_template_decl;
717   ++processing_template_parmlist;
718   note_template_header (0);
719 
720   /* Add a dummy parameter level while we process the parameter list.  */
721   current_template_parms
722     = tree_cons (size_int (current_template_depth + 1),
723 		 make_tree_vec (0),
724 		 current_template_parms);
725 }
726 
727 /* This routine is called when a specialization is declared.  If it is
728    invalid to declare a specialization here, an error is reported and
729    false is returned, otherwise this routine will return true.  */
730 
731 static bool
check_specialization_scope(void)732 check_specialization_scope (void)
733 {
734   tree scope = current_scope ();
735 
736   /* [temp.expl.spec]
737 
738      An explicit specialization shall be declared in the namespace of
739      which the template is a member, or, for member templates, in the
740      namespace of which the enclosing class or enclosing class
741      template is a member.  An explicit specialization of a member
742      function, member class or static data member of a class template
743      shall be declared in the namespace of which the class template
744      is a member.  */
745   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
746     {
747       error ("explicit specialization in non-namespace scope %qD", scope);
748       return false;
749     }
750 
751   /* [temp.expl.spec]
752 
753      In an explicit specialization declaration for a member of a class
754      template or a member template that appears in namespace scope,
755      the member template and some of its enclosing class templates may
756      remain unspecialized, except that the declaration shall not
757      explicitly specialize a class member template if its enclosing
758      class templates are not explicitly specialized as well.  */
759   if (current_template_parms)
760     {
761       error ("enclosing class templates are not explicitly specialized");
762       return false;
763     }
764 
765   return true;
766 }
767 
768 /* We've just seen template <>.  */
769 
770 bool
begin_specialization(void)771 begin_specialization (void)
772 {
773   begin_scope (sk_template_spec, NULL);
774   note_template_header (1);
775   return check_specialization_scope ();
776 }
777 
778 /* Called at then end of processing a declaration preceded by
779    template<>.  */
780 
781 void
end_specialization(void)782 end_specialization (void)
783 {
784   finish_scope ();
785   reset_specialization ();
786 }
787 
788 /* Any template <>'s that we have seen thus far are not referring to a
789    function specialization.  */
790 
791 void
reset_specialization(void)792 reset_specialization (void)
793 {
794   processing_specialization = 0;
795   template_header_count = 0;
796 }
797 
798 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
799    it was of the form template <>.  */
800 
801 static void
note_template_header(int specialization)802 note_template_header (int specialization)
803 {
804   processing_specialization = specialization;
805   template_header_count++;
806 }
807 
808 /* We're beginning an explicit instantiation.  */
809 
810 void
begin_explicit_instantiation(void)811 begin_explicit_instantiation (void)
812 {
813   gcc_assert (!processing_explicit_instantiation);
814   processing_explicit_instantiation = true;
815 }
816 
817 
818 void
end_explicit_instantiation(void)819 end_explicit_instantiation (void)
820 {
821   gcc_assert (processing_explicit_instantiation);
822   processing_explicit_instantiation = false;
823 }
824 
825 /* An explicit specialization or partial specialization of TMPL is being
826    declared.  Check that the namespace in which the specialization is
827    occurring is permissible.  Returns false iff it is invalid to
828    specialize TMPL in the current namespace.  */
829 
830 static bool
check_specialization_namespace(tree tmpl)831 check_specialization_namespace (tree tmpl)
832 {
833   tree tpl_ns = decl_namespace_context (tmpl);
834 
835   /* [tmpl.expl.spec]
836 
837      An explicit specialization shall be declared in a namespace enclosing the
838      specialized template. An explicit specialization whose declarator-id is
839      not qualified shall be declared in the nearest enclosing namespace of the
840      template, or, if the namespace is inline (7.3.1), any namespace from its
841      enclosing namespace set.  */
842   if (current_scope() != DECL_CONTEXT (tmpl)
843       && !at_namespace_scope_p ())
844     {
845       error ("specialization of %qD must appear at namespace scope", tmpl);
846       return false;
847     }
848 
849   if (is_nested_namespace (current_namespace, tpl_ns, cxx_dialect < cxx11))
850     /* Same or enclosing namespace.  */
851     return true;
852   else
853     {
854       auto_diagnostic_group d;
855       if (permerror (input_location,
856 		     "specialization of %qD in different namespace", tmpl))
857 	inform (DECL_SOURCE_LOCATION (tmpl),
858 		"  from definition of %q#D", tmpl);
859       return false;
860     }
861 }
862 
863 /* SPEC is an explicit instantiation.  Check that it is valid to
864    perform this explicit instantiation in the current namespace.  */
865 
866 static void
check_explicit_instantiation_namespace(tree spec)867 check_explicit_instantiation_namespace (tree spec)
868 {
869   tree ns;
870 
871   /* DR 275: An explicit instantiation shall appear in an enclosing
872      namespace of its template.  */
873   ns = decl_namespace_context (spec);
874   if (!is_nested_namespace (current_namespace, ns))
875     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
876 	       "(which does not enclose namespace %qD)",
877 	       spec, current_namespace, ns);
878 }
879 
880 /* Returns true if TYPE is a new partial specialization that needs to be
881    set up.  This may also modify TYPE to point to the correct (new or
882    existing) constrained partial specialization.  */
883 
884 static bool
maybe_new_partial_specialization(tree & type)885 maybe_new_partial_specialization (tree& type)
886 {
887   /* An implicit instantiation of an incomplete type implies
888      the definition of a new class template.
889 
890 	template<typename T>
891 	  struct S;
892 
893 	template<typename T>
894 	  struct S<T*>;
895 
896      Here, S<T*> is an implicit instantiation of S whose type
897      is incomplete.  */
898   if (CLASSTYPE_IMPLICIT_INSTANTIATION (type) && !COMPLETE_TYPE_P (type))
899     return true;
900 
901   /* It can also be the case that TYPE is a completed specialization.
902      Continuing the previous example, suppose we also declare:
903 
904 	template<typename T>
905 	  requires Integral<T>
906 	    struct S<T*>;
907 
908      Here, S<T*> refers to the specialization S<T*> defined
909      above. However, we need to differentiate definitions because
910      we intend to define a new partial specialization. In this case,
911      we rely on the fact that the constraints are different for
912      this declaration than that above.
913 
914      Note that we also get here for injected class names and
915      late-parsed template definitions. We must ensure that we
916      do not create new type declarations for those cases.  */
917   if (flag_concepts && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
918     {
919       tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
920       tree args = CLASSTYPE_TI_ARGS (type);
921 
922       /* If there are no template parameters, this cannot be a new
923 	 partial template specialization?  */
924       if (!current_template_parms)
925 	return false;
926 
927       /* The injected-class-name is not a new partial specialization.  */
928       if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
929 	return false;
930 
931       /* If the constraints are not the same as those of the primary
932 	 then, we can probably create a new specialization.  */
933       tree type_constr = current_template_constraints ();
934 
935       if (type == TREE_TYPE (tmpl))
936 	{
937 	  tree main_constr = get_constraints (tmpl);
938 	  if (equivalent_constraints (type_constr, main_constr))
939 	    return false;
940 	}
941 
942       /* Also, if there's a pre-existing specialization with matching
943 	 constraints, then this also isn't new.  */
944       tree specs = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
945       while (specs)
946         {
947           tree spec_tmpl = TREE_VALUE (specs);
948           tree spec_args = TREE_PURPOSE (specs);
949           tree spec_constr = get_constraints (spec_tmpl);
950           if (comp_template_args (args, spec_args)
951 	      && equivalent_constraints (type_constr, spec_constr))
952 	    {
953 	      type = TREE_TYPE (spec_tmpl);
954 	      return false;
955 	    }
956           specs = TREE_CHAIN (specs);
957         }
958 
959       /* Create a new type node (and corresponding type decl)
960 	 for the newly declared specialization.  */
961       tree t = make_class_type (TREE_CODE (type));
962       CLASSTYPE_DECLARED_CLASS (t) = CLASSTYPE_DECLARED_CLASS (type);
963       SET_TYPE_TEMPLATE_INFO (t, build_template_info (tmpl, args));
964 
965       /* We only need a separate type node for storing the definition of this
966 	 partial specialization; uses of S<T*> are unconstrained, so all are
967 	 equivalent.  So keep TYPE_CANONICAL the same.  */
968       TYPE_CANONICAL (t) = TYPE_CANONICAL (type);
969 
970       /* Build the corresponding type decl.  */
971       tree d = create_implicit_typedef (DECL_NAME (tmpl), t);
972       DECL_CONTEXT (d) = TYPE_CONTEXT (t);
973       DECL_SOURCE_LOCATION (d) = input_location;
974       TREE_PRIVATE (d) = (current_access_specifier == access_private_node);
975       TREE_PROTECTED (d) = (current_access_specifier == access_protected_node);
976 
977       set_instantiating_module (d);
978       DECL_MODULE_EXPORT_P (d) = DECL_MODULE_EXPORT_P (tmpl);
979 
980       type = t;
981       return true;
982     }
983 
984   return false;
985 }
986 
987 /* The TYPE is being declared.  If it is a template type, that means it
988    is a partial specialization.  Do appropriate error-checking.  */
989 
990 tree
maybe_process_partial_specialization(tree type)991 maybe_process_partial_specialization (tree type)
992 {
993   tree context;
994 
995   if (type == error_mark_node)
996     return error_mark_node;
997 
998   /* A lambda that appears in specialization context is not itself a
999      specialization.  */
1000   if (CLASS_TYPE_P (type) && CLASSTYPE_LAMBDA_EXPR (type))
1001     return type;
1002 
1003   /* An injected-class-name is not a specialization.  */
1004   if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
1005     return type;
1006 
1007   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
1008     {
1009       error ("name of class shadows template template parameter %qD",
1010 	     TYPE_NAME (type));
1011       return error_mark_node;
1012     }
1013 
1014   context = TYPE_CONTEXT (type);
1015 
1016   if (TYPE_ALIAS_P (type))
1017     {
1018       tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (type);
1019 
1020       if (tinfo && DECL_ALIAS_TEMPLATE_P (TI_TEMPLATE (tinfo)))
1021 	error ("specialization of alias template %qD",
1022 	       TI_TEMPLATE (tinfo));
1023       else
1024 	error ("explicit specialization of non-template %qT", type);
1025       return error_mark_node;
1026     }
1027   else if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
1028     {
1029       /* This is for ordinary explicit specialization and partial
1030 	 specialization of a template class such as:
1031 
1032 	   template <> class C<int>;
1033 
1034 	 or:
1035 
1036 	   template <class T> class C<T*>;
1037 
1038 	 Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
1039 
1040       if (maybe_new_partial_specialization (type))
1041 	{
1042 	  if (!check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type))
1043 	      && !at_namespace_scope_p ())
1044 	    return error_mark_node;
1045 	  SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1046 	  DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1047 	  if (processing_template_decl)
1048 	    {
1049 	      tree decl = push_template_decl (TYPE_MAIN_DECL (type));
1050 	      if (decl == error_mark_node)
1051 		return error_mark_node;
1052 	      return TREE_TYPE (decl);
1053 	    }
1054 	}
1055       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
1056 	error ("specialization of %qT after instantiation", type);
1057       else if (errorcount && !processing_specialization
1058 	        && CLASSTYPE_TEMPLATE_SPECIALIZATION (type)
1059 	       && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
1060 	/* Trying to define a specialization either without a template<> header
1061 	   or in an inappropriate place.  We've already given an error, so just
1062 	   bail now so we don't actually define the specialization.  */
1063 	return error_mark_node;
1064     }
1065   else if (CLASS_TYPE_P (type)
1066 	   && !CLASSTYPE_USE_TEMPLATE (type)
1067 	   && CLASSTYPE_TEMPLATE_INFO (type)
1068 	   && context && CLASS_TYPE_P (context)
1069 	   && CLASSTYPE_TEMPLATE_INFO (context))
1070     {
1071       /* This is for an explicit specialization of member class
1072 	 template according to [temp.expl.spec/18]:
1073 
1074 	   template <> template <class U> class C<int>::D;
1075 
1076 	 The context `C<int>' must be an implicit instantiation.
1077 	 Otherwise this is just a member class template declared
1078 	 earlier like:
1079 
1080 	   template <> class C<int> { template <class U> class D; };
1081 	   template <> template <class U> class C<int>::D;
1082 
1083 	 In the first case, `C<int>::D' is a specialization of `C<T>::D'
1084 	 while in the second case, `C<int>::D' is a primary template
1085 	 and `C<T>::D' may not exist.  */
1086 
1087       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
1088 	  && !COMPLETE_TYPE_P (type))
1089 	{
1090 	  tree t;
1091 	  tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
1092 
1093 	  if (current_namespace
1094 	      != decl_namespace_context (tmpl))
1095 	    {
1096 	      if (permerror (input_location,
1097 			     "specialization of %qD in different namespace",
1098 			     type))
1099 		inform (DECL_SOURCE_LOCATION (tmpl),
1100 			"from definition of %q#D", tmpl);
1101 	    }
1102 
1103 	  /* Check for invalid specialization after instantiation:
1104 
1105 	       template <> template <> class C<int>::D<int>;
1106 	       template <> template <class U> class C<int>::D;  */
1107 
1108 	  for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
1109 	       t; t = TREE_CHAIN (t))
1110 	    {
1111 	      tree inst = TREE_VALUE (t);
1112 	      if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst)
1113 		  || !COMPLETE_OR_OPEN_TYPE_P (inst))
1114 		{
1115 		  /* We already have a full specialization of this partial
1116 		     instantiation, or a full specialization has been
1117 		     looked up but not instantiated.  Reassign it to the
1118 		     new member specialization template.  */
1119 		  spec_entry elt;
1120 		  spec_entry *entry;
1121 
1122 		  elt.tmpl = most_general_template (tmpl);
1123 		  elt.args = CLASSTYPE_TI_ARGS (inst);
1124 		  elt.spec = inst;
1125 
1126 		  type_specializations->remove_elt (&elt);
1127 
1128 		  elt.tmpl = tmpl;
1129 		  CLASSTYPE_TI_ARGS (inst)
1130 		    = elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
1131 
1132 		  spec_entry **slot
1133 		    = type_specializations->find_slot (&elt, INSERT);
1134 		  entry = ggc_alloc<spec_entry> ();
1135 		  *entry = elt;
1136 		  *slot = entry;
1137 		}
1138 	      else
1139 		/* But if we've had an implicit instantiation, that's a
1140 		   problem ([temp.expl.spec]/6).  */
1141 		error ("specialization %qT after instantiation %qT",
1142 		       type, inst);
1143 	    }
1144 
1145 	  /* Mark TYPE as a specialization.  And as a result, we only
1146 	     have one level of template argument for the innermost
1147 	     class template.  */
1148 	  SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1149 	  DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1150 	  CLASSTYPE_TI_ARGS (type)
1151 	    = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
1152 	}
1153     }
1154   else if (processing_specialization)
1155     {
1156        /* Someday C++0x may allow for enum template specialization.  */
1157       if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
1158 	  && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
1159 	pedwarn (input_location, OPT_Wpedantic, "template specialization "
1160 		 "of %qD not allowed by ISO C++", type);
1161       else
1162 	{
1163 	  error ("explicit specialization of non-template %qT", type);
1164 	  return error_mark_node;
1165 	}
1166     }
1167 
1168   return type;
1169 }
1170 
1171 /* Returns nonzero if we can optimize the retrieval of specializations
1172    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
1173    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
1174 
1175 static inline bool
optimize_specialization_lookup_p(tree tmpl)1176 optimize_specialization_lookup_p (tree tmpl)
1177 {
1178   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
1179 	  && DECL_CLASS_SCOPE_P (tmpl)
1180 	  /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
1181 	     parameter.  */
1182 	  && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
1183 	  /* The optimized lookup depends on the fact that the
1184 	     template arguments for the member function template apply
1185 	     purely to the containing class, which is not true if the
1186 	     containing class is an explicit or partial
1187 	     specialization.  */
1188 	  && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
1189 	  && !DECL_MEMBER_TEMPLATE_P (tmpl)
1190 	  && !DECL_CONV_FN_P (tmpl)
1191 	  /* It is possible to have a template that is not a member
1192 	     template and is not a member of a template class:
1193 
1194 	     template <typename T>
1195 	     struct S { friend A::f(); };
1196 
1197 	     Here, the friend function is a template, but the context does
1198 	     not have template information.  The optimized lookup relies
1199 	     on having ARGS be the template arguments for both the class
1200 	     and the function template.  */
1201 	  && !DECL_UNIQUE_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
1202 }
1203 
1204 /* Make sure ARGS doesn't use any inappropriate typedefs; we should have
1205    gone through coerce_template_parms by now.  */
1206 
1207 static void
verify_unstripped_args_1(tree inner)1208 verify_unstripped_args_1 (tree inner)
1209 {
1210   for (int i = 0; i < TREE_VEC_LENGTH (inner); ++i)
1211     {
1212       tree arg = TREE_VEC_ELT (inner, i);
1213       if (TREE_CODE (arg) == TEMPLATE_DECL)
1214 	/* OK */;
1215       else if (TYPE_P (arg))
1216 	gcc_assert (strip_typedefs (arg, NULL) == arg);
1217       else if (ARGUMENT_PACK_P (arg))
1218 	verify_unstripped_args_1 (ARGUMENT_PACK_ARGS (arg));
1219       else if (strip_typedefs (TREE_TYPE (arg), NULL) != TREE_TYPE (arg))
1220 	/* Allow typedefs on the type of a non-type argument, since a
1221 	   parameter can have them.  */;
1222       else
1223 	gcc_assert (strip_typedefs_expr (arg, NULL) == arg);
1224     }
1225 }
1226 
1227 static void
verify_unstripped_args(tree args)1228 verify_unstripped_args (tree args)
1229 {
1230   ++processing_template_decl;
1231   if (!any_dependent_template_arguments_p (args))
1232     verify_unstripped_args_1 (INNERMOST_TEMPLATE_ARGS (args));
1233   --processing_template_decl;
1234 }
1235 
1236 /* Retrieve the specialization (in the sense of [temp.spec] - a
1237    specialization is either an instantiation or an explicit
1238    specialization) of TMPL for the given template ARGS.  If there is
1239    no such specialization, return NULL_TREE.  The ARGS are a vector of
1240    arguments, or a vector of vectors of arguments, in the case of
1241    templates with more than one level of parameters.
1242 
1243    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
1244    then we search for a partial specialization matching ARGS.  This
1245    parameter is ignored if TMPL is not a class template.
1246 
1247    We can also look up a FIELD_DECL, if it is a lambda capture pack; the
1248    result is a NONTYPE_ARGUMENT_PACK.  */
1249 
1250 static tree
retrieve_specialization(tree tmpl,tree args,hashval_t hash)1251 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1252 {
1253   if (tmpl == NULL_TREE)
1254     return NULL_TREE;
1255 
1256   if (args == error_mark_node)
1257     return NULL_TREE;
1258 
1259   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL
1260 	      || TREE_CODE (tmpl) == FIELD_DECL);
1261 
1262   /* There should be as many levels of arguments as there are
1263      levels of parameters.  */
1264   gcc_assert (TMPL_ARGS_DEPTH (args)
1265 	      == (TREE_CODE (tmpl) == TEMPLATE_DECL
1266 		  ? TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl))
1267 		  : template_class_depth (DECL_CONTEXT (tmpl))));
1268 
1269   if (flag_checking)
1270     verify_unstripped_args (args);
1271 
1272   /* Lambda functions in templates aren't instantiated normally, but through
1273      tsubst_lambda_expr.  */
1274   if (lambda_fn_in_template_p (tmpl))
1275     return NULL_TREE;
1276 
1277   if (optimize_specialization_lookup_p (tmpl))
1278     {
1279       /* The template arguments actually apply to the containing
1280 	 class.  Find the class specialization with those
1281 	 arguments.  */
1282       tree class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
1283       tree class_specialization
1284 	= retrieve_specialization (class_template, args, 0);
1285       if (!class_specialization)
1286 	return NULL_TREE;
1287 
1288       /* Find the instance of TMPL.  */
1289       tree fns = get_class_binding (class_specialization, DECL_NAME (tmpl));
1290       for (ovl_iterator iter (fns); iter; ++iter)
1291 	{
1292 	  tree fn = *iter;
1293 	  if (tree ti = get_template_info (fn))
1294 	    if (TI_TEMPLATE (ti) == tmpl
1295 		/* using-declarations can bring in a different
1296 		   instantiation of tmpl as a member of a different
1297 		   instantiation of tmpl's class.  We don't want those
1298 		   here.  */
1299 		&& DECL_CONTEXT (fn) == class_specialization)
1300 	      return fn;
1301 	}
1302       return NULL_TREE;
1303     }
1304   else
1305     {
1306       spec_entry *found;
1307       spec_entry elt;
1308       spec_hash_table *specializations;
1309 
1310       elt.tmpl = tmpl;
1311       elt.args = args;
1312       elt.spec = NULL_TREE;
1313 
1314       if (DECL_CLASS_TEMPLATE_P (tmpl))
1315 	specializations = type_specializations;
1316       else
1317 	specializations = decl_specializations;
1318 
1319       if (hash == 0)
1320 	hash = spec_hasher::hash (&elt);
1321       found = specializations->find_with_hash (&elt, hash);
1322       if (found)
1323 	return found->spec;
1324     }
1325 
1326   return NULL_TREE;
1327 }
1328 
1329 /* Like retrieve_specialization, but for local declarations.  */
1330 
1331 tree
retrieve_local_specialization(tree tmpl)1332 retrieve_local_specialization (tree tmpl)
1333 {
1334   if (local_specializations == NULL)
1335     return NULL_TREE;
1336 
1337   tree *slot = local_specializations->get (tmpl);
1338   return slot ? *slot : NULL_TREE;
1339 }
1340 
1341 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1342 
1343 int
is_specialization_of(tree decl,tree tmpl)1344 is_specialization_of (tree decl, tree tmpl)
1345 {
1346   tree t;
1347 
1348   if (TREE_CODE (decl) == FUNCTION_DECL)
1349     {
1350       for (t = decl;
1351 	   t != NULL_TREE;
1352 	   t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1353 	if (t == tmpl)
1354 	  return 1;
1355     }
1356   else
1357     {
1358       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1359 
1360       for (t = TREE_TYPE (decl);
1361 	   t != NULL_TREE;
1362 	   t = CLASSTYPE_USE_TEMPLATE (t)
1363 	     ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1364 	if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1365 	  return 1;
1366     }
1367 
1368   return 0;
1369 }
1370 
1371 /* Returns nonzero iff DECL is a specialization of friend declaration
1372    FRIEND_DECL according to [temp.friend].  */
1373 
1374 bool
is_specialization_of_friend(tree decl,tree friend_decl)1375 is_specialization_of_friend (tree decl, tree friend_decl)
1376 {
1377   bool need_template = true;
1378   int template_depth;
1379 
1380   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1381 	      || TREE_CODE (decl) == TYPE_DECL);
1382 
1383   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1384      of a template class, we want to check if DECL is a specialization
1385      if this.  */
1386   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1387       && DECL_TEMPLATE_INFO (friend_decl)
1388       && !DECL_USE_TEMPLATE (friend_decl))
1389     {
1390       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1391       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1392       need_template = false;
1393     }
1394   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1395 	   && !PRIMARY_TEMPLATE_P (friend_decl))
1396     need_template = false;
1397 
1398   /* There is nothing to do if this is not a template friend.  */
1399   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1400     return false;
1401 
1402   if (is_specialization_of (decl, friend_decl))
1403     return true;
1404 
1405   /* [temp.friend/6]
1406      A member of a class template may be declared to be a friend of a
1407      non-template class.  In this case, the corresponding member of
1408      every specialization of the class template is a friend of the
1409      class granting friendship.
1410 
1411      For example, given a template friend declaration
1412 
1413        template <class T> friend void A<T>::f();
1414 
1415      the member function below is considered a friend
1416 
1417        template <> struct A<int> {
1418 	 void f();
1419        };
1420 
1421      For this type of template friend, TEMPLATE_DEPTH below will be
1422      nonzero.  To determine if DECL is a friend of FRIEND, we first
1423      check if the enclosing class is a specialization of another.  */
1424 
1425   template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1426   if (template_depth
1427       && DECL_CLASS_SCOPE_P (decl)
1428       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1429 			       CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1430     {
1431       /* Next, we check the members themselves.  In order to handle
1432 	 a few tricky cases, such as when FRIEND_DECL's are
1433 
1434 	   template <class T> friend void A<T>::g(T t);
1435 	   template <class T> template <T t> friend void A<T>::h();
1436 
1437 	 and DECL's are
1438 
1439 	   void A<int>::g(int);
1440 	   template <int> void A<int>::h();
1441 
1442 	 we need to figure out ARGS, the template arguments from
1443 	 the context of DECL.  This is required for template substitution
1444 	 of `T' in the function parameter of `g' and template parameter
1445 	 of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1446 
1447       tree context = DECL_CONTEXT (decl);
1448       tree args = NULL_TREE;
1449       int current_depth = 0;
1450 
1451       while (current_depth < template_depth)
1452 	{
1453 	  if (CLASSTYPE_TEMPLATE_INFO (context))
1454 	    {
1455 	      if (current_depth == 0)
1456 		args = TYPE_TI_ARGS (context);
1457 	      else
1458 		args = add_to_template_args (TYPE_TI_ARGS (context), args);
1459 	      current_depth++;
1460 	    }
1461 	  context = TYPE_CONTEXT (context);
1462 	}
1463 
1464       if (TREE_CODE (decl) == FUNCTION_DECL)
1465 	{
1466 	  bool is_template;
1467 	  tree friend_type;
1468 	  tree decl_type;
1469 	  tree friend_args_type;
1470 	  tree decl_args_type;
1471 
1472 	  /* Make sure that both DECL and FRIEND_DECL are templates or
1473 	     non-templates.  */
1474 	  is_template = DECL_TEMPLATE_INFO (decl)
1475 			&& PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1476 	  if (need_template ^ is_template)
1477 	    return false;
1478 	  else if (is_template)
1479 	    {
1480 	      /* If both are templates, check template parameter list.  */
1481 	      tree friend_parms
1482 		= tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1483 					 args, tf_none);
1484 	      if (!comp_template_parms
1485 		     (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1486 		      friend_parms))
1487 		return false;
1488 
1489 	      decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1490 	    }
1491 	  else
1492 	    decl_type = TREE_TYPE (decl);
1493 
1494 	  friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1495 					      tf_none, NULL_TREE);
1496 	  if (friend_type == error_mark_node)
1497 	    return false;
1498 
1499 	  /* Check if return types match.  */
1500 	  if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1501 	    return false;
1502 
1503 	  /* Check if function parameter types match, ignoring the
1504 	     `this' parameter.  */
1505 	  friend_args_type = TYPE_ARG_TYPES (friend_type);
1506 	  decl_args_type = TYPE_ARG_TYPES (decl_type);
1507 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1508 	    friend_args_type = TREE_CHAIN (friend_args_type);
1509 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1510 	    decl_args_type = TREE_CHAIN (decl_args_type);
1511 
1512 	  return compparms (decl_args_type, friend_args_type);
1513 	}
1514       else
1515 	{
1516 	  /* DECL is a TYPE_DECL */
1517 	  bool is_template;
1518 	  tree decl_type = TREE_TYPE (decl);
1519 
1520 	  /* Make sure that both DECL and FRIEND_DECL are templates or
1521 	     non-templates.  */
1522 	  is_template
1523 	    = CLASSTYPE_TEMPLATE_INFO (decl_type)
1524 	      && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1525 
1526 	  if (need_template ^ is_template)
1527 	    return false;
1528 	  else if (is_template)
1529 	    {
1530 	      tree friend_parms;
1531 	      /* If both are templates, check the name of the two
1532 		 TEMPLATE_DECL's first because is_friend didn't.  */
1533 	      if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1534 		  != DECL_NAME (friend_decl))
1535 		return false;
1536 
1537 	      /* Now check template parameter list.  */
1538 	      friend_parms
1539 		= tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1540 					 args, tf_none);
1541 	      return comp_template_parms
1542 		(DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1543 		 friend_parms);
1544 	    }
1545 	  else
1546 	    return (DECL_NAME (decl)
1547 		    == DECL_NAME (friend_decl));
1548 	}
1549     }
1550   return false;
1551 }
1552 
1553 /* Register the specialization SPEC as a specialization of TMPL with
1554    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1555    is actually just a friend declaration.  ATTRLIST is the list of
1556    attributes that the specialization is declared with or NULL when
1557    it isn't.  Returns SPEC, or an equivalent prior declaration, if
1558    available.
1559 
1560    We also store instantiations of field packs in the hash table, even
1561    though they are not themselves templates, to make lookup easier.  */
1562 
1563 static tree
register_specialization(tree spec,tree tmpl,tree args,bool is_friend,hashval_t hash)1564 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1565 			 hashval_t hash)
1566 {
1567   tree fn;
1568   spec_entry **slot = NULL;
1569   spec_entry elt;
1570 
1571   gcc_assert ((TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec))
1572 	      || (TREE_CODE (tmpl) == FIELD_DECL
1573 		  && TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK));
1574 
1575   if (TREE_CODE (spec) == FUNCTION_DECL
1576       && uses_template_parms (DECL_TI_ARGS (spec)))
1577     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1578        register it; we want the corresponding TEMPLATE_DECL instead.
1579        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1580        the more obvious `uses_template_parms (spec)' to avoid problems
1581        with default function arguments.  In particular, given
1582        something like this:
1583 
1584 	  template <class T> void f(T t1, T t = T())
1585 
1586        the default argument expression is not substituted for in an
1587        instantiation unless and until it is actually needed.  */
1588     return spec;
1589 
1590   if (optimize_specialization_lookup_p (tmpl))
1591     /* We don't put these specializations in the hash table, but we might
1592        want to give an error about a mismatch.  */
1593     fn = retrieve_specialization (tmpl, args, 0);
1594   else
1595     {
1596       elt.tmpl = tmpl;
1597       elt.args = args;
1598       elt.spec = spec;
1599 
1600       if (hash == 0)
1601 	hash = spec_hasher::hash (&elt);
1602 
1603       slot = decl_specializations->find_slot_with_hash (&elt, hash, INSERT);
1604       if (*slot)
1605 	fn = (*slot)->spec;
1606       else
1607 	fn = NULL_TREE;
1608     }
1609 
1610   /* We can sometimes try to re-register a specialization that we've
1611      already got.  In particular, regenerate_decl_from_template calls
1612      duplicate_decls which will update the specialization list.  But,
1613      we'll still get called again here anyhow.  It's more convenient
1614      to simply allow this than to try to prevent it.  */
1615   if (fn == spec)
1616     return spec;
1617   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1618     {
1619       if (DECL_TEMPLATE_INSTANTIATION (fn))
1620 	{
1621 	  if (DECL_ODR_USED (fn)
1622 	      || DECL_EXPLICIT_INSTANTIATION (fn))
1623 	    {
1624 	      error ("specialization of %qD after instantiation",
1625 		     fn);
1626 	      return error_mark_node;
1627 	    }
1628 	  else
1629 	    {
1630 	      tree clone;
1631 	      /* This situation should occur only if the first
1632 		 specialization is an implicit instantiation, the
1633 		 second is an explicit specialization, and the
1634 		 implicit instantiation has not yet been used.  That
1635 		 situation can occur if we have implicitly
1636 		 instantiated a member function and then specialized
1637 		 it later.
1638 
1639 		 We can also wind up here if a friend declaration that
1640 		 looked like an instantiation turns out to be a
1641 		 specialization:
1642 
1643 		   template <class T> void foo(T);
1644 		   class S { friend void foo<>(int) };
1645 		   template <> void foo(int);
1646 
1647 		 We transform the existing DECL in place so that any
1648 		 pointers to it become pointers to the updated
1649 		 declaration.
1650 
1651 		 If there was a definition for the template, but not
1652 		 for the specialization, we want this to look as if
1653 		 there were no definition, and vice versa.  */
1654 	      DECL_INITIAL (fn) = NULL_TREE;
1655 	      duplicate_decls (spec, fn, /*hiding=*/is_friend);
1656 	      /* The call to duplicate_decls will have applied
1657 		 [temp.expl.spec]:
1658 
1659 		   An explicit specialization of a function template
1660 		   is inline only if it is explicitly declared to be,
1661 		   and independently of whether its function template
1662 		   is.
1663 
1664 		to the primary function; now copy the inline bits to
1665 		the various clones.  */
1666 	      FOR_EACH_CLONE (clone, fn)
1667 		{
1668 		  DECL_DECLARED_INLINE_P (clone)
1669 		    = DECL_DECLARED_INLINE_P (fn);
1670 		  DECL_SOURCE_LOCATION (clone)
1671 		    = DECL_SOURCE_LOCATION (fn);
1672 		  DECL_DELETED_FN (clone)
1673 		    = DECL_DELETED_FN (fn);
1674 		}
1675 	      check_specialization_namespace (tmpl);
1676 
1677 	      return fn;
1678 	    }
1679 	}
1680       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1681 	{
1682 	  tree dd = duplicate_decls (spec, fn, /*hiding=*/is_friend);
1683 	  if (dd == error_mark_node)
1684 	    /* We've already complained in duplicate_decls.  */
1685 	    return error_mark_node;
1686 
1687 	  if (dd == NULL_TREE && DECL_INITIAL (spec))
1688 	    /* Dup decl failed, but this is a new definition. Set the
1689 	       line number so any errors match this new
1690 	       definition.  */
1691 	    DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1692 
1693 	  return fn;
1694 	}
1695     }
1696   else if (fn)
1697     return duplicate_decls (spec, fn, /*hiding=*/is_friend);
1698 
1699   /* A specialization must be declared in the same namespace as the
1700      template it is specializing.  */
1701   if (DECL_P (spec) && DECL_TEMPLATE_SPECIALIZATION (spec)
1702       && !check_specialization_namespace (tmpl))
1703     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1704 
1705   if (slot != NULL /* !optimize_specialization_lookup_p (tmpl) */)
1706     {
1707       spec_entry *entry = ggc_alloc<spec_entry> ();
1708       gcc_assert (tmpl && args && spec);
1709       *entry = elt;
1710       *slot = entry;
1711       if ((TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1712 	   && PRIMARY_TEMPLATE_P (tmpl)
1713 	   && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1714 	  || variable_template_p (tmpl))
1715 	/* If TMPL is a forward declaration of a template function, keep a list
1716 	   of all specializations in case we need to reassign them to a friend
1717 	   template later in tsubst_friend_function.
1718 
1719 	   Also keep a list of all variable template instantiations so that
1720 	   process_partial_specialization can check whether a later partial
1721 	   specialization would have used it.  */
1722 	DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1723 	  = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1724     }
1725 
1726   return spec;
1727 }
1728 
1729 /* Restricts tree and type comparisons.  */
1730 int comparing_specializations;
1731 int comparing_dependent_aliases;
1732 
1733 /* Returns true iff two spec_entry nodes are equivalent.  */
1734 
1735 bool
equal(spec_entry * e1,spec_entry * e2)1736 spec_hasher::equal (spec_entry *e1, spec_entry *e2)
1737 {
1738   int equal;
1739 
1740   ++comparing_specializations;
1741   ++comparing_dependent_aliases;
1742   ++processing_template_decl;
1743   equal = (e1->tmpl == e2->tmpl
1744 	   && comp_template_args (e1->args, e2->args));
1745   if (equal && flag_concepts
1746       /* tmpl could be a FIELD_DECL for a capture pack.  */
1747       && TREE_CODE (e1->tmpl) == TEMPLATE_DECL
1748       && VAR_P (DECL_TEMPLATE_RESULT (e1->tmpl))
1749       && uses_template_parms (e1->args))
1750     {
1751       /* Partial specializations of a variable template can be distinguished by
1752 	 constraints.  */
1753       tree c1 = e1->spec ? get_constraints (e1->spec) : NULL_TREE;
1754       tree c2 = e2->spec ? get_constraints (e2->spec) : NULL_TREE;
1755       equal = equivalent_constraints (c1, c2);
1756     }
1757   --processing_template_decl;
1758   --comparing_dependent_aliases;
1759   --comparing_specializations;
1760 
1761   return equal;
1762 }
1763 
1764 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1765 
1766 static hashval_t
hash_tmpl_and_args(tree tmpl,tree args)1767 hash_tmpl_and_args (tree tmpl, tree args)
1768 {
1769   hashval_t val = iterative_hash_object (DECL_UID (tmpl), 0);
1770   return iterative_hash_template_arg (args, val);
1771 }
1772 
1773 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1774    ignoring SPEC.  */
1775 
1776 hashval_t
hash(spec_entry * e)1777 spec_hasher::hash (spec_entry *e)
1778 {
1779   return hash_tmpl_and_args (e->tmpl, e->args);
1780 }
1781 
1782 /* Recursively calculate a hash value for a template argument ARG, for use
1783    in the hash tables of template specializations.   We must be
1784    careful to (at least) skip the same entities template_args_equal
1785    does.  */
1786 
1787 hashval_t
iterative_hash_template_arg(tree arg,hashval_t val)1788 iterative_hash_template_arg (tree arg, hashval_t val)
1789 {
1790   if (arg == NULL_TREE)
1791     return iterative_hash_object (arg, val);
1792 
1793   if (!TYPE_P (arg))
1794     /* Strip nop-like things, but not the same as STRIP_NOPS.  */
1795     while (CONVERT_EXPR_P (arg)
1796 	   || TREE_CODE (arg) == NON_LVALUE_EXPR
1797 	   || class_nttp_const_wrapper_p (arg))
1798       arg = TREE_OPERAND (arg, 0);
1799 
1800   enum tree_code code = TREE_CODE (arg);
1801 
1802   val = iterative_hash_object (code, val);
1803 
1804   switch (code)
1805     {
1806     case ARGUMENT_PACK_SELECT:
1807       /* Getting here with an ARGUMENT_PACK_SELECT means we're probably
1808 	 preserving it in a hash table, which is bad because it will change
1809 	 meaning when gen_elem_of_pack_expansion_instantiation changes the
1810 	 ARGUMENT_PACK_SELECT_INDEX.  */
1811       gcc_unreachable ();
1812 
1813     case ERROR_MARK:
1814       return val;
1815 
1816     case IDENTIFIER_NODE:
1817       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1818 
1819     case TREE_VEC:
1820       for (int i = 0, len = TREE_VEC_LENGTH (arg); i < len; ++i)
1821 	val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1822       return val;
1823 
1824     case TYPE_PACK_EXPANSION:
1825     case EXPR_PACK_EXPANSION:
1826       val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1827       return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1828 
1829     case TYPE_ARGUMENT_PACK:
1830     case NONTYPE_ARGUMENT_PACK:
1831       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1832 
1833     case TREE_LIST:
1834       for (; arg; arg = TREE_CHAIN (arg))
1835 	val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1836       return val;
1837 
1838     case OVERLOAD:
1839       for (lkp_iterator iter (arg); iter; ++iter)
1840 	val = iterative_hash_template_arg (*iter, val);
1841       return val;
1842 
1843     case CONSTRUCTOR:
1844       {
1845 	iterative_hash_template_arg (TREE_TYPE (arg), val);
1846 	for (auto &e: CONSTRUCTOR_ELTS (arg))
1847 	  {
1848 	    val = iterative_hash_template_arg (e.index, val);
1849 	    val = iterative_hash_template_arg (e.value, val);
1850 	  }
1851 	return val;
1852       }
1853 
1854     case PARM_DECL:
1855       if (!DECL_ARTIFICIAL (arg))
1856 	{
1857 	  val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1858 	  val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1859 	}
1860       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1861 
1862     case TARGET_EXPR:
1863       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1864 
1865     case PTRMEM_CST:
1866       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1867       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1868 
1869     case TEMPLATE_PARM_INDEX:
1870       val = iterative_hash_template_arg
1871 	(TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1872       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1873       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1874 
1875     case TRAIT_EXPR:
1876       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1877       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1878       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1879 
1880     case BASELINK:
1881       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1882 					 val);
1883       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1884 					  val);
1885 
1886     case MODOP_EXPR:
1887       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1888       code = TREE_CODE (TREE_OPERAND (arg, 1));
1889       val = iterative_hash_object (code, val);
1890       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1891 
1892     case LAMBDA_EXPR:
1893       /* [temp.over.link] Two lambda-expressions are never considered
1894 	 equivalent.
1895 
1896          So just hash the closure type.  */
1897       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1898 
1899     case CAST_EXPR:
1900     case IMPLICIT_CONV_EXPR:
1901     case STATIC_CAST_EXPR:
1902     case REINTERPRET_CAST_EXPR:
1903     case CONST_CAST_EXPR:
1904     case DYNAMIC_CAST_EXPR:
1905     case NEW_EXPR:
1906       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1907       /* Now hash operands as usual.  */
1908       break;
1909 
1910     case CALL_EXPR:
1911       {
1912 	tree fn = CALL_EXPR_FN (arg);
1913 	if (tree name = call_expr_dependent_name (arg))
1914 	  {
1915 	    if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
1916 	      val = iterative_hash_template_arg (TREE_OPERAND (fn, 1), val);
1917 	    fn = name;
1918 	  }
1919 	val = iterative_hash_template_arg (fn, val);
1920 	call_expr_arg_iterator ai;
1921 	for (tree x = first_call_expr_arg (arg, &ai); x;
1922 	     x = next_call_expr_arg (&ai))
1923 	  val = iterative_hash_template_arg (x, val);
1924 	return val;
1925       }
1926 
1927     default:
1928       break;
1929     }
1930 
1931   char tclass = TREE_CODE_CLASS (code);
1932   switch (tclass)
1933     {
1934     case tcc_type:
1935       if (tree ats = alias_template_specialization_p (arg, nt_transparent))
1936 	{
1937 	  // We want an alias specialization that survived strip_typedefs
1938 	  // to hash differently from its TYPE_CANONICAL, to avoid hash
1939 	  // collisions that compare as different in template_args_equal.
1940 	  // These could be dependent specializations that strip_typedefs
1941 	  // left alone, or untouched specializations because
1942 	  // coerce_template_parms returns the unconverted template
1943 	  // arguments if it sees incomplete argument packs.
1944 	  tree ti = TYPE_ALIAS_TEMPLATE_INFO (ats);
1945 	  return hash_tmpl_and_args (TI_TEMPLATE (ti), TI_ARGS (ti));
1946 	}
1947 
1948       switch (TREE_CODE (arg))
1949 	{
1950 	case TEMPLATE_TEMPLATE_PARM:
1951 	  {
1952 	    tree tpi = TEMPLATE_TYPE_PARM_INDEX (arg);
1953 
1954 	    /* Do not recurse with TPI directly, as that is unbounded
1955 	       recursion.  */
1956 	    val = iterative_hash_object (TEMPLATE_PARM_LEVEL (tpi), val);
1957 	    val = iterative_hash_object (TEMPLATE_PARM_IDX (tpi), val);
1958 	  }
1959 	  break;
1960 
1961 	case  DECLTYPE_TYPE:
1962 	  val = iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1963 	  break;
1964 
1965 	default:
1966 	  if (tree canonical = TYPE_CANONICAL (arg))
1967 	    val = iterative_hash_object (TYPE_HASH (canonical), val);
1968 	  break;
1969 	}
1970 
1971       return val;
1972 
1973     case tcc_declaration:
1974     case tcc_constant:
1975       return iterative_hash_expr (arg, val);
1976 
1977     default:
1978       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1979       for (int i = 0, n = cp_tree_operand_length (arg); i < n; ++i)
1980 	val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1981       return val;
1982     }
1983 }
1984 
1985 /* Unregister the specialization SPEC as a specialization of TMPL.
1986    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1987    if the SPEC was listed as a specialization of TMPL.
1988 
1989    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1990 
1991 bool
reregister_specialization(tree spec,tree tinfo,tree new_spec)1992 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1993 {
1994   spec_entry *entry;
1995   spec_entry elt;
1996 
1997   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1998   elt.args = TI_ARGS (tinfo);
1999   elt.spec = NULL_TREE;
2000 
2001   entry = decl_specializations->find (&elt);
2002   if (entry != NULL)
2003     {
2004       gcc_assert (entry->spec == spec || entry->spec == new_spec);
2005       gcc_assert (new_spec != NULL_TREE);
2006       entry->spec = new_spec;
2007       return 1;
2008     }
2009 
2010   return 0;
2011 }
2012 
2013 /* Like register_specialization, but for local declarations.  We are
2014    registering SPEC, an instantiation of TMPL.  */
2015 
2016 void
register_local_specialization(tree spec,tree tmpl)2017 register_local_specialization (tree spec, tree tmpl)
2018 {
2019   gcc_assert (tmpl != spec);
2020   local_specializations->put (tmpl, spec);
2021 }
2022 
2023 /* TYPE is a class type.  Returns true if TYPE is an explicitly
2024    specialized class.  */
2025 
2026 bool
explicit_class_specialization_p(tree type)2027 explicit_class_specialization_p (tree type)
2028 {
2029   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
2030     return false;
2031   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
2032 }
2033 
2034 /* Print the list of functions at FNS, going through all the overloads
2035    for each element of the list.  Alternatively, FNS cannot be a
2036    TREE_LIST, in which case it will be printed together with all the
2037    overloads.
2038 
2039    MORE and *STR should respectively be FALSE and NULL when the function
2040    is called from the outside.  They are used internally on recursive
2041    calls.  print_candidates manages the two parameters and leaves NULL
2042    in *STR when it ends.  */
2043 
2044 static void
print_candidates_1(tree fns,char ** str,bool more=false)2045 print_candidates_1 (tree fns, char **str, bool more = false)
2046 {
2047   if (TREE_CODE (fns) == TREE_LIST)
2048     for (; fns; fns = TREE_CHAIN (fns))
2049       print_candidates_1 (TREE_VALUE (fns), str, more || TREE_CHAIN (fns));
2050   else
2051     for (lkp_iterator iter (fns); iter;)
2052       {
2053 	tree cand = *iter;
2054 	++iter;
2055 
2056 	const char *pfx = *str;
2057 	if (!pfx)
2058 	  {
2059 	    if (more || iter)
2060 	      pfx = _("candidates are:");
2061 	    else
2062 	      pfx = _("candidate is:");
2063 	    *str = get_spaces (pfx);
2064 	  }
2065 	inform (DECL_SOURCE_LOCATION (cand), "%s %#qD", pfx, cand);
2066       }
2067 }
2068 
2069 /* Print the list of candidate FNS in an error message.  FNS can also
2070    be a TREE_LIST of non-functions in the case of an ambiguous lookup.  */
2071 
2072 void
print_candidates(tree fns)2073 print_candidates (tree fns)
2074 {
2075   char *str = NULL;
2076   print_candidates_1 (fns, &str);
2077   free (str);
2078 }
2079 
2080 /* Get a (possibly) constrained template declaration for the
2081    purpose of ordering candidates.  */
2082 static tree
get_template_for_ordering(tree list)2083 get_template_for_ordering (tree list)
2084 {
2085   gcc_assert (TREE_CODE (list) == TREE_LIST);
2086   tree f = TREE_VALUE (list);
2087   if (tree ti = DECL_TEMPLATE_INFO (f))
2088     return TI_TEMPLATE (ti);
2089   return f;
2090 }
2091 
2092 /* Among candidates having the same signature, return the
2093    most constrained or NULL_TREE if there is no best candidate.
2094    If the signatures of candidates vary (e.g., template
2095    specialization vs. member function), then there can be no
2096    most constrained.
2097 
2098    Note that we don't compare constraints on the functions
2099    themselves, but rather those of their templates. */
2100 static tree
most_constrained_function(tree candidates)2101 most_constrained_function (tree candidates)
2102 {
2103   // Try to find the best candidate in a first pass.
2104   tree champ = candidates;
2105   for (tree c = TREE_CHAIN (champ); c; c = TREE_CHAIN (c))
2106     {
2107       int winner = more_constrained (get_template_for_ordering (champ),
2108                                      get_template_for_ordering (c));
2109       if (winner == -1)
2110         champ = c; // The candidate is more constrained
2111       else if (winner == 0)
2112         return NULL_TREE; // Neither is more constrained
2113     }
2114 
2115   // Verify that the champ is better than previous candidates.
2116   for (tree c = candidates; c != champ; c = TREE_CHAIN (c)) {
2117     if (!more_constrained (get_template_for_ordering (champ),
2118                            get_template_for_ordering (c)))
2119       return NULL_TREE;
2120   }
2121 
2122   return champ;
2123 }
2124 
2125 
2126 /* Returns the template (one of the functions given by TEMPLATE_ID)
2127    which can be specialized to match the indicated DECL with the
2128    explicit template args given in TEMPLATE_ID.  The DECL may be
2129    NULL_TREE if none is available.  In that case, the functions in
2130    TEMPLATE_ID are non-members.
2131 
2132    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
2133    specialization of a member template.
2134 
2135    The TEMPLATE_COUNT is the number of references to qualifying
2136    template classes that appeared in the name of the function. See
2137    check_explicit_specialization for a more accurate description.
2138 
2139    TSK indicates what kind of template declaration (if any) is being
2140    declared.  TSK_TEMPLATE indicates that the declaration given by
2141    DECL, though a FUNCTION_DECL, has template parameters, and is
2142    therefore a template function.
2143 
2144    The template args (those explicitly specified and those deduced)
2145    are output in a newly created vector *TARGS_OUT.
2146 
2147    If it is impossible to determine the result, an error message is
2148    issued.  The error_mark_node is returned to indicate failure.  */
2149 
2150 static tree
determine_specialization(tree template_id,tree decl,tree * targs_out,int need_member_template,int template_count,tmpl_spec_kind tsk)2151 determine_specialization (tree template_id,
2152 			  tree decl,
2153 			  tree* targs_out,
2154 			  int need_member_template,
2155 			  int template_count,
2156 			  tmpl_spec_kind tsk)
2157 {
2158   tree fns;
2159   tree targs;
2160   tree explicit_targs;
2161   tree candidates = NULL_TREE;
2162 
2163   /* A TREE_LIST of templates of which DECL may be a specialization.
2164      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
2165      corresponding TREE_PURPOSE is the set of template arguments that,
2166      when used to instantiate the template, would produce a function
2167      with the signature of DECL.  */
2168   tree templates = NULL_TREE;
2169   int header_count;
2170   cp_binding_level *b;
2171 
2172   *targs_out = NULL_TREE;
2173 
2174   if (template_id == error_mark_node || decl == error_mark_node)
2175     return error_mark_node;
2176 
2177   /* We shouldn't be specializing a member template of an
2178      unspecialized class template; we already gave an error in
2179      check_specialization_scope, now avoid crashing.  */
2180   if (!VAR_P (decl)
2181       && template_count && DECL_CLASS_SCOPE_P (decl)
2182       && template_class_depth (DECL_CONTEXT (decl)) > 0)
2183     {
2184       gcc_assert (errorcount);
2185       return error_mark_node;
2186     }
2187 
2188   fns = TREE_OPERAND (template_id, 0);
2189   explicit_targs = TREE_OPERAND (template_id, 1);
2190 
2191   if (fns == error_mark_node)
2192     return error_mark_node;
2193 
2194   /* Check for baselinks.  */
2195   if (BASELINK_P (fns))
2196     fns = BASELINK_FUNCTIONS (fns);
2197 
2198   if (TREE_CODE (decl) == FUNCTION_DECL && !is_overloaded_fn (fns))
2199     {
2200       error_at (DECL_SOURCE_LOCATION (decl),
2201 		"%qD is not a function template", fns);
2202       return error_mark_node;
2203     }
2204   else if (VAR_P (decl) && !variable_template_p (fns))
2205     {
2206       error ("%qD is not a variable template", fns);
2207       return error_mark_node;
2208     }
2209 
2210   /* Count the number of template headers specified for this
2211      specialization.  */
2212   header_count = 0;
2213   for (b = current_binding_level;
2214        b->kind == sk_template_parms;
2215        b = b->level_chain)
2216     ++header_count;
2217 
2218   tree orig_fns = fns;
2219   bool header_mismatch = false;
2220 
2221   if (variable_template_p (fns))
2222     {
2223       tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (fns));
2224       targs = coerce_template_parms (parms, explicit_targs, fns,
2225 				     tf_warning_or_error,
2226 				     /*req_all*/true, /*use_defarg*/true);
2227       if (targs != error_mark_node
2228 	  && constraints_satisfied_p (fns, targs))
2229         templates = tree_cons (targs, fns, templates);
2230     }
2231   else for (lkp_iterator iter (fns); iter; ++iter)
2232     {
2233       tree fn = *iter;
2234 
2235       if (TREE_CODE (fn) == TEMPLATE_DECL)
2236 	{
2237 	  tree decl_arg_types;
2238 	  tree fn_arg_types;
2239 
2240 	  /* In case of explicit specialization, we need to check if
2241 	     the number of template headers appearing in the specialization
2242 	     is correct. This is usually done in check_explicit_specialization,
2243 	     but the check done there cannot be exhaustive when specializing
2244 	     member functions. Consider the following code:
2245 
2246 	     template <> void A<int>::f(int);
2247 	     template <> template <> void A<int>::f(int);
2248 
2249 	     Assuming that A<int> is not itself an explicit specialization
2250 	     already, the first line specializes "f" which is a non-template
2251 	     member function, whilst the second line specializes "f" which
2252 	     is a template member function. So both lines are syntactically
2253 	     correct, and check_explicit_specialization does not reject
2254 	     them.
2255 
2256 	     Here, we can do better, as we are matching the specialization
2257 	     against the declarations. We count the number of template
2258 	     headers, and we check if they match TEMPLATE_COUNT + 1
2259 	     (TEMPLATE_COUNT is the number of qualifying template classes,
2260 	     plus there must be another header for the member template
2261 	     itself).
2262 
2263 	     Notice that if header_count is zero, this is not a
2264 	     specialization but rather a template instantiation, so there
2265 	     is no check we can perform here.  */
2266 	  if (header_count && header_count != template_count + 1)
2267 	    {
2268 	      header_mismatch = true;
2269 	      continue;
2270 	    }
2271 
2272 	  /* Check that the number of template arguments at the
2273 	     innermost level for DECL is the same as for FN.  */
2274 	  if (current_binding_level->kind == sk_template_parms
2275 	      && !current_binding_level->explicit_spec_p
2276 	      && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
2277 		  != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
2278 				      (current_template_parms))))
2279 	    continue;
2280 
2281 	  /* DECL might be a specialization of FN.  */
2282 	  decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2283 	  fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
2284 
2285 	  /* For a non-static member function, we need to make sure
2286 	     that the const qualification is the same.  Since
2287 	     get_bindings does not try to merge the "this" parameter,
2288 	     we must do the comparison explicitly.  */
2289 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
2290 	    {
2291 	      if (!same_type_p (TREE_VALUE (fn_arg_types),
2292 				TREE_VALUE (decl_arg_types)))
2293 		continue;
2294 
2295 	      /* And the ref-qualification.  */
2296 	      if (type_memfn_rqual (TREE_TYPE (decl))
2297 		  != type_memfn_rqual (TREE_TYPE (fn)))
2298 		continue;
2299 	    }
2300 
2301 	  /* Skip the "this" parameter and, for constructors of
2302 	     classes with virtual bases, the VTT parameter.  A
2303 	     full specialization of a constructor will have a VTT
2304 	     parameter, but a template never will.  */
2305 	  decl_arg_types
2306 	    = skip_artificial_parms_for (decl, decl_arg_types);
2307 	  fn_arg_types
2308 	    = skip_artificial_parms_for (fn, fn_arg_types);
2309 
2310 	  /* Function templates cannot be specializations; there are
2311 	     no partial specializations of functions.  Therefore, if
2312 	     the type of DECL does not match FN, there is no
2313 	     match.
2314 
2315              Note that it should never be the case that we have both
2316              candidates added here, and for regular member functions
2317              below. */
2318 	  if (tsk == tsk_template)
2319 	    {
2320 	      if (!comp_template_parms (DECL_TEMPLATE_PARMS (fn),
2321 					current_template_parms))
2322 		continue;
2323 	      if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2324 				TREE_TYPE (TREE_TYPE (fn))))
2325 		continue;
2326 	      if (!compparms (fn_arg_types, decl_arg_types))
2327 		continue;
2328 
2329 	      tree freq = get_constraints (fn);
2330 	      tree dreq = get_constraints (decl);
2331 	      if (!freq != !dreq)
2332 		continue;
2333 	      if (freq)
2334 		{
2335 		  /* C++20 CA104: Substitute directly into the
2336 		     constraint-expression.  */
2337 		  tree fargs = DECL_TI_ARGS (fn);
2338 		  tsubst_flags_t complain = tf_none;
2339 		  freq = tsubst_constraint_info (freq, fargs, complain, fn);
2340 		  if (!cp_tree_equal (freq, dreq))
2341 		    continue;
2342 		}
2343 
2344 	      candidates = tree_cons (NULL_TREE, fn, candidates);
2345 	      continue;
2346 	    }
2347 
2348 	  /* See whether this function might be a specialization of this
2349 	     template.  Suppress access control because we might be trying
2350 	     to make this specialization a friend, and we have already done
2351 	     access control for the declaration of the specialization.  */
2352 	  push_deferring_access_checks (dk_no_check);
2353 	  targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
2354 	  pop_deferring_access_checks ();
2355 
2356 	  if (!targs)
2357 	    /* We cannot deduce template arguments that when used to
2358 	       specialize TMPL will produce DECL.  */
2359 	    continue;
2360 
2361 	  if (uses_template_parms (targs))
2362 	    /* We deduced something involving 'auto', which isn't a valid
2363 	       template argument.  */
2364 	    continue;
2365 
2366 	  /* Save this template, and the arguments deduced.  */
2367 	  templates = tree_cons (targs, fn, templates);
2368 	}
2369       else if (need_member_template)
2370 	/* FN is an ordinary member function, and we need a
2371 	   specialization of a member template.  */
2372 	;
2373       else if (TREE_CODE (fn) != FUNCTION_DECL)
2374 	/* We can get IDENTIFIER_NODEs here in certain erroneous
2375 	   cases.  */
2376 	;
2377       else if (!DECL_FUNCTION_MEMBER_P (fn))
2378 	/* This is just an ordinary non-member function.  Nothing can
2379 	   be a specialization of that.  */
2380 	;
2381       else if (DECL_ARTIFICIAL (fn))
2382 	/* Cannot specialize functions that are created implicitly.  */
2383 	;
2384       else
2385 	{
2386 	  tree decl_arg_types;
2387 
2388 	  /* This is an ordinary member function.  However, since
2389 	     we're here, we can assume its enclosing class is a
2390 	     template class.  For example,
2391 
2392 	       template <typename T> struct S { void f(); };
2393 	       template <> void S<int>::f() {}
2394 
2395 	     Here, S<int>::f is a non-template, but S<int> is a
2396 	     template class.  If FN has the same type as DECL, we
2397 	     might be in business.  */
2398 
2399 	  if (!DECL_TEMPLATE_INFO (fn))
2400 	    /* Its enclosing class is an explicit specialization
2401 	       of a template class.  This is not a candidate.  */
2402 	    continue;
2403 
2404 	  if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2405 			    TREE_TYPE (TREE_TYPE (fn))))
2406 	    /* The return types differ.  */
2407 	    continue;
2408 
2409 	  /* Adjust the type of DECL in case FN is a static member.  */
2410 	  decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2411 	  if (DECL_STATIC_FUNCTION_P (fn)
2412 	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2413 	    decl_arg_types = TREE_CHAIN (decl_arg_types);
2414 
2415 	  if (!compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2416 			 decl_arg_types))
2417             continue;
2418 
2419 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2420 	      && (type_memfn_rqual (TREE_TYPE (decl))
2421 		  != type_memfn_rqual (TREE_TYPE (fn))))
2422 	    continue;
2423 
2424           // If the deduced arguments do not satisfy the constraints,
2425           // this is not a candidate.
2426           if (flag_concepts && !constraints_satisfied_p (fn))
2427             continue;
2428 
2429           // Add the candidate.
2430           candidates = tree_cons (NULL_TREE, fn, candidates);
2431 	}
2432     }
2433 
2434   if (templates && TREE_CHAIN (templates))
2435     {
2436       /* We have:
2437 
2438 	   [temp.expl.spec]
2439 
2440 	   It is possible for a specialization with a given function
2441 	   signature to be instantiated from more than one function
2442 	   template.  In such cases, explicit specification of the
2443 	   template arguments must be used to uniquely identify the
2444 	   function template specialization being specialized.
2445 
2446 	 Note that here, there's no suggestion that we're supposed to
2447 	 determine which of the candidate templates is most
2448 	 specialized.  However, we, also have:
2449 
2450 	   [temp.func.order]
2451 
2452 	   Partial ordering of overloaded function template
2453 	   declarations is used in the following contexts to select
2454 	   the function template to which a function template
2455 	   specialization refers:
2456 
2457 	   -- when an explicit specialization refers to a function
2458 	      template.
2459 
2460 	 So, we do use the partial ordering rules, at least for now.
2461 	 This extension can only serve to make invalid programs valid,
2462 	 so it's safe.  And, there is strong anecdotal evidence that
2463 	 the committee intended the partial ordering rules to apply;
2464 	 the EDG front end has that behavior, and John Spicer claims
2465 	 that the committee simply forgot to delete the wording in
2466 	 [temp.expl.spec].  */
2467       tree tmpl = most_specialized_instantiation (templates);
2468       if (tmpl != error_mark_node)
2469 	{
2470 	  templates = tmpl;
2471 	  TREE_CHAIN (templates) = NULL_TREE;
2472 	}
2473     }
2474 
2475   // Concepts allows multiple declarations of member functions
2476   // with the same signature. Like above, we need to rely on
2477   // on the partial ordering of those candidates to determine which
2478   // is the best.
2479   if (flag_concepts && candidates && TREE_CHAIN (candidates))
2480     {
2481       if (tree cand = most_constrained_function (candidates))
2482         {
2483           candidates = cand;
2484           TREE_CHAIN (cand) = NULL_TREE;
2485         }
2486     }
2487 
2488   if (templates == NULL_TREE && candidates == NULL_TREE)
2489     {
2490       error ("template-id %qD for %q+D does not match any template "
2491 	     "declaration", template_id, decl);
2492       if (header_mismatch)
2493 	inform (DECL_SOURCE_LOCATION (decl),
2494 		"saw %d %<template<>%>, need %d for "
2495 		"specializing a member function template",
2496 		header_count, template_count + 1);
2497       print_candidates (orig_fns);
2498       return error_mark_node;
2499     }
2500   else if ((templates && TREE_CHAIN (templates))
2501 	   || (candidates && TREE_CHAIN (candidates))
2502 	   || (templates && candidates))
2503     {
2504       error ("ambiguous template specialization %qD for %q+D",
2505 	     template_id, decl);
2506       candidates = chainon (candidates, templates);
2507       print_candidates (candidates);
2508       return error_mark_node;
2509     }
2510 
2511   /* We have one, and exactly one, match.  */
2512   if (candidates)
2513     {
2514       tree fn = TREE_VALUE (candidates);
2515       *targs_out = copy_node (DECL_TI_ARGS (fn));
2516 
2517       /* Propagate the candidate's constraints to the declaration.  */
2518       if (tsk != tsk_template)
2519 	set_constraints (decl, get_constraints (fn));
2520 
2521       /* DECL is a re-declaration or partial instantiation of a template
2522 	 function.  */
2523       if (TREE_CODE (fn) == TEMPLATE_DECL)
2524 	return fn;
2525       /* It was a specialization of an ordinary member function in a
2526 	 template class.  */
2527       return DECL_TI_TEMPLATE (fn);
2528     }
2529 
2530   /* It was a specialization of a template.  */
2531   tree tmpl = TREE_VALUE (templates);
2532   *targs_out = add_outermost_template_args (tmpl, TREE_PURPOSE (templates));
2533 
2534   /* Propagate the template's constraints to the declaration.  */
2535   if (tsk != tsk_template)
2536     set_constraints (decl, get_constraints (tmpl));
2537 
2538   return tmpl;
2539 }
2540 
2541 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2542    but with the default argument values filled in from those in the
2543    TMPL_TYPES.  */
2544 
2545 static tree
copy_default_args_to_explicit_spec_1(tree spec_types,tree tmpl_types)2546 copy_default_args_to_explicit_spec_1 (tree spec_types,
2547 				      tree tmpl_types)
2548 {
2549   tree new_spec_types;
2550 
2551   if (!spec_types)
2552     return NULL_TREE;
2553 
2554   if (spec_types == void_list_node)
2555     return void_list_node;
2556 
2557   /* Substitute into the rest of the list.  */
2558   new_spec_types =
2559     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2560 					  TREE_CHAIN (tmpl_types));
2561 
2562   /* Add the default argument for this parameter.  */
2563   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2564 			 TREE_VALUE (spec_types),
2565 			 new_spec_types);
2566 }
2567 
2568 /* DECL is an explicit specialization.  Replicate default arguments
2569    from the template it specializes.  (That way, code like:
2570 
2571      template <class T> void f(T = 3);
2572      template <> void f(double);
2573      void g () { f (); }
2574 
2575    works, as required.)  An alternative approach would be to look up
2576    the correct default arguments at the call-site, but this approach
2577    is consistent with how implicit instantiations are handled.  */
2578 
2579 static void
copy_default_args_to_explicit_spec(tree decl)2580 copy_default_args_to_explicit_spec (tree decl)
2581 {
2582   tree tmpl;
2583   tree spec_types;
2584   tree tmpl_types;
2585   tree new_spec_types;
2586   tree old_type;
2587   tree new_type;
2588   tree t;
2589   tree object_type = NULL_TREE;
2590   tree in_charge = NULL_TREE;
2591   tree vtt = NULL_TREE;
2592 
2593   /* See if there's anything we need to do.  */
2594   tmpl = DECL_TI_TEMPLATE (decl);
2595   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2596   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2597     if (TREE_PURPOSE (t))
2598       break;
2599   if (!t)
2600     return;
2601 
2602   old_type = TREE_TYPE (decl);
2603   spec_types = TYPE_ARG_TYPES (old_type);
2604 
2605   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2606     {
2607       /* Remove the this pointer, but remember the object's type for
2608 	 CV quals.  */
2609       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2610       spec_types = TREE_CHAIN (spec_types);
2611       tmpl_types = TREE_CHAIN (tmpl_types);
2612 
2613       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2614 	{
2615 	  /* DECL may contain more parameters than TMPL due to the extra
2616 	     in-charge parameter in constructors and destructors.  */
2617 	  in_charge = spec_types;
2618 	  spec_types = TREE_CHAIN (spec_types);
2619 	}
2620       if (DECL_HAS_VTT_PARM_P (decl))
2621 	{
2622 	  vtt = spec_types;
2623 	  spec_types = TREE_CHAIN (spec_types);
2624 	}
2625     }
2626 
2627   /* Compute the merged default arguments.  */
2628   new_spec_types =
2629     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2630 
2631   /* Compute the new FUNCTION_TYPE.  */
2632   if (object_type)
2633     {
2634       if (vtt)
2635 	new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2636 					 TREE_VALUE (vtt),
2637 					 new_spec_types);
2638 
2639       if (in_charge)
2640 	/* Put the in-charge parameter back.  */
2641 	new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2642 					 TREE_VALUE (in_charge),
2643 					 new_spec_types);
2644 
2645       new_type = build_method_type_directly (object_type,
2646 					     TREE_TYPE (old_type),
2647 					     new_spec_types);
2648     }
2649   else
2650     new_type = build_function_type (TREE_TYPE (old_type),
2651 				    new_spec_types);
2652   new_type = cp_build_type_attribute_variant (new_type,
2653 					      TYPE_ATTRIBUTES (old_type));
2654   new_type = cxx_copy_lang_qualifiers (new_type, old_type);
2655 
2656   TREE_TYPE (decl) = new_type;
2657 }
2658 
2659 /* Return the number of template headers we expect to see for a definition
2660    or specialization of CTYPE or one of its non-template members.  */
2661 
2662 int
num_template_headers_for_class(tree ctype)2663 num_template_headers_for_class (tree ctype)
2664 {
2665   int num_templates = 0;
2666 
2667   while (ctype && CLASS_TYPE_P (ctype))
2668     {
2669       /* You're supposed to have one `template <...>' for every
2670 	 template class, but you don't need one for a full
2671 	 specialization.  For example:
2672 
2673 	 template <class T> struct S{};
2674 	 template <> struct S<int> { void f(); };
2675 	 void S<int>::f () {}
2676 
2677 	 is correct; there shouldn't be a `template <>' for the
2678 	 definition of `S<int>::f'.  */
2679       if (!CLASSTYPE_TEMPLATE_INFO (ctype))
2680 	/* If CTYPE does not have template information of any
2681 	   kind,  then it is not a template, nor is it nested
2682 	   within a template.  */
2683 	break;
2684       if (explicit_class_specialization_p (ctype))
2685 	break;
2686       if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (ctype)))
2687 	++num_templates;
2688 
2689       ctype = TYPE_CONTEXT (ctype);
2690     }
2691 
2692   return num_templates;
2693 }
2694 
2695 /* Do a simple sanity check on the template headers that precede the
2696    variable declaration DECL.  */
2697 
2698 void
check_template_variable(tree decl)2699 check_template_variable (tree decl)
2700 {
2701   tree ctx = CP_DECL_CONTEXT (decl);
2702   int wanted = num_template_headers_for_class (ctx);
2703   if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
2704       && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
2705     {
2706       if (cxx_dialect < cxx14)
2707         pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wc__14_extensions,
2708 		 "variable templates only available with "
2709 		 "%<-std=c++14%> or %<-std=gnu++14%>");
2710 
2711       // Namespace-scope variable templates should have a template header.
2712       ++wanted;
2713     }
2714   if (template_header_count > wanted)
2715     {
2716       auto_diagnostic_group d;
2717       bool warned = pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2718 			     "too many template headers for %qD "
2719 	                     "(should be %d)",
2720 			     decl, wanted);
2721       if (warned && CLASS_TYPE_P (ctx)
2722 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (ctx))
2723 	inform (DECL_SOURCE_LOCATION (decl),
2724 		"members of an explicitly specialized class are defined "
2725 		"without a template header");
2726     }
2727 }
2728 
2729 /* An explicit specialization whose declarator-id or class-head-name is not
2730    qualified shall be declared in the nearest enclosing namespace of the
2731    template, or, if the namespace is inline (7.3.1), any namespace from its
2732    enclosing namespace set.
2733 
2734    If the name declared in the explicit instantiation is an unqualified name,
2735    the explicit instantiation shall appear in the namespace where its template
2736    is declared or, if that namespace is inline (7.3.1), any namespace from its
2737    enclosing namespace set.  */
2738 
2739 void
check_unqualified_spec_or_inst(tree t,location_t loc)2740 check_unqualified_spec_or_inst (tree t, location_t loc)
2741 {
2742   tree tmpl = most_general_template (t);
2743   if (DECL_NAMESPACE_SCOPE_P (tmpl)
2744       && !is_nested_namespace (current_namespace,
2745 			       CP_DECL_CONTEXT (tmpl), true))
2746     {
2747       if (processing_specialization)
2748 	permerror (loc, "explicit specialization of %qD outside its "
2749 		   "namespace must use a nested-name-specifier", tmpl);
2750       else if (processing_explicit_instantiation
2751 	       && cxx_dialect >= cxx11)
2752 	/* This was allowed in C++98, so only pedwarn.  */
2753 	pedwarn (loc, OPT_Wpedantic, "explicit instantiation of %qD "
2754 		 "outside its namespace must use a nested-name-"
2755 		 "specifier", tmpl);
2756     }
2757 }
2758 
2759 /* Warn for a template specialization SPEC that is missing some of a set
2760    of function or type attributes that the template TEMPL is declared with.
2761    ATTRLIST is a list of additional attributes that SPEC should be taken
2762    to ultimately be declared with.  */
2763 
2764 static void
warn_spec_missing_attributes(tree tmpl,tree spec,tree attrlist)2765 warn_spec_missing_attributes (tree tmpl, tree spec, tree attrlist)
2766 {
2767   if (DECL_FUNCTION_TEMPLATE_P (tmpl))
2768     tmpl = DECL_TEMPLATE_RESULT (tmpl);
2769 
2770   /* Avoid warning if the difference between the primary and
2771      the specialization is not in one of the attributes below.  */
2772   const char* const blacklist[] = {
2773     "alloc_align", "alloc_size", "assume_aligned", "format",
2774     "format_arg", "malloc", "nonnull", NULL
2775   };
2776 
2777   /* Put together a list of the black listed attributes that the primary
2778      template is declared with that the specialization is not, in case
2779      it's not apparent from the most recent declaration of the primary.  */
2780   pretty_printer str;
2781   unsigned nattrs = decls_mismatched_attributes (tmpl, spec, attrlist,
2782 						 blacklist, &str);
2783 
2784   if (!nattrs)
2785     return;
2786 
2787   auto_diagnostic_group d;
2788   if (warning_at (DECL_SOURCE_LOCATION (spec), OPT_Wmissing_attributes,
2789 		  "explicit specialization %q#D may be missing attributes",
2790 		  spec))
2791     inform (DECL_SOURCE_LOCATION (tmpl),
2792 	    nattrs > 1
2793 	    ? G_("missing primary template attributes %s")
2794 	    : G_("missing primary template attribute %s"),
2795 	    pp_formatted_text (&str));
2796 }
2797 
2798 /* Check to see if the function just declared, as indicated in
2799    DECLARATOR, and in DECL, is a specialization of a function
2800    template.  We may also discover that the declaration is an explicit
2801    instantiation at this point.
2802 
2803    Returns DECL, or an equivalent declaration that should be used
2804    instead if all goes well.  Issues an error message if something is
2805    amiss.  Returns error_mark_node if the error is not easily
2806    recoverable.
2807 
2808    FLAGS is a bitmask consisting of the following flags:
2809 
2810    2: The function has a definition.
2811    4: The function is a friend.
2812 
2813    The TEMPLATE_COUNT is the number of references to qualifying
2814    template classes that appeared in the name of the function.  For
2815    example, in
2816 
2817      template <class T> struct S { void f(); };
2818      void S<int>::f();
2819 
2820    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2821    classes are not counted in the TEMPLATE_COUNT, so that in
2822 
2823      template <class T> struct S {};
2824      template <> struct S<int> { void f(); }
2825      template <> void S<int>::f();
2826 
2827    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2828    invalid; there should be no template <>.)
2829 
2830    If the function is a specialization, it is marked as such via
2831    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2832    is set up correctly, and it is added to the list of specializations
2833    for that template.  */
2834 
2835 tree
check_explicit_specialization(tree declarator,tree decl,int template_count,int flags,tree attrlist)2836 check_explicit_specialization (tree declarator,
2837 			       tree decl,
2838 			       int template_count,
2839 			       int flags,
2840 			       tree attrlist)
2841 {
2842   int have_def = flags & 2;
2843   int is_friend = flags & 4;
2844   bool is_concept = flags & 8;
2845   int specialization = 0;
2846   int explicit_instantiation = 0;
2847   int member_specialization = 0;
2848   tree ctype = DECL_CLASS_CONTEXT (decl);
2849   tree dname = DECL_NAME (decl);
2850   tmpl_spec_kind tsk;
2851 
2852   if (is_friend)
2853     {
2854       if (!processing_specialization)
2855 	tsk = tsk_none;
2856       else
2857 	tsk = tsk_excessive_parms;
2858     }
2859   else
2860     tsk = current_tmpl_spec_kind (template_count);
2861 
2862   switch (tsk)
2863     {
2864     case tsk_none:
2865       if (processing_specialization && !VAR_P (decl))
2866 	{
2867 	  specialization = 1;
2868 	  SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2869 	}
2870       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR
2871 	       || (DECL_LANG_SPECIFIC (decl)
2872 		   && DECL_IMPLICIT_INSTANTIATION (decl)))
2873 	{
2874 	  if (is_friend)
2875 	    /* This could be something like:
2876 
2877 	       template <class T> void f(T);
2878 	       class S { friend void f<>(int); }  */
2879 	    specialization = 1;
2880 	  else
2881 	    {
2882 	      /* This case handles bogus declarations like template <>
2883 		 template <class T> void f<int>(); */
2884 
2885 	      error_at (cp_expr_loc_or_input_loc (declarator),
2886 			"template-id %qE in declaration of primary template",
2887 			declarator);
2888 	      return decl;
2889 	    }
2890 	}
2891       break;
2892 
2893     case tsk_invalid_member_spec:
2894       /* The error has already been reported in
2895 	 check_specialization_scope.  */
2896       return error_mark_node;
2897 
2898     case tsk_invalid_expl_inst:
2899       error ("template parameter list used in explicit instantiation");
2900 
2901       /* Fall through.  */
2902 
2903     case tsk_expl_inst:
2904       if (have_def)
2905 	error ("definition provided for explicit instantiation");
2906 
2907       explicit_instantiation = 1;
2908       break;
2909 
2910     case tsk_excessive_parms:
2911     case tsk_insufficient_parms:
2912       if (tsk == tsk_excessive_parms)
2913 	error ("too many template parameter lists in declaration of %qD",
2914 	       decl);
2915       else if (template_header_count)
2916 	error("too few template parameter lists in declaration of %qD", decl);
2917       else
2918 	error("explicit specialization of %qD must be introduced by "
2919 	      "%<template <>%>", decl);
2920 
2921       /* Fall through.  */
2922     case tsk_expl_spec:
2923       if (is_concept)
2924         error ("explicit specialization declared %<concept%>");
2925 
2926       if (VAR_P (decl) && TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2927 	/* In cases like template<> constexpr bool v = true;
2928 	   We'll give an error in check_template_variable.  */
2929 	break;
2930 
2931       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2932       if (ctype)
2933 	member_specialization = 1;
2934       else
2935 	specialization = 1;
2936       break;
2937 
2938     case tsk_template:
2939       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2940 	{
2941 	  /* This case handles bogus declarations like template <>
2942 	     template <class T> void f<int>(); */
2943 
2944 	  if (!uses_template_parms (TREE_OPERAND (declarator, 1)))
2945 	    error_at (cp_expr_loc_or_input_loc (declarator),
2946 		      "template-id %qE in declaration of primary template",
2947 		      declarator);
2948 	  else if (variable_template_p (TREE_OPERAND (declarator, 0)))
2949 	    {
2950 	      /* Partial specialization of variable template.  */
2951 	      SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2952 	      specialization = 1;
2953 	      goto ok;
2954 	    }
2955 	  else if (cxx_dialect < cxx14)
2956 	    error_at (cp_expr_loc_or_input_loc (declarator),
2957 		      "non-type partial specialization %qE "
2958 		      "is not allowed", declarator);
2959 	  else
2960 	    error_at (cp_expr_loc_or_input_loc (declarator),
2961 		      "non-class, non-variable partial specialization %qE "
2962 		      "is not allowed", declarator);
2963 	  return decl;
2964 	ok:;
2965 	}
2966 
2967       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2968 	/* This is a specialization of a member template, without
2969 	   specialization the containing class.  Something like:
2970 
2971 	     template <class T> struct S {
2972 	       template <class U> void f (U);
2973 	     };
2974 	     template <> template <class U> void S<int>::f(U) {}
2975 
2976 	   That's a specialization -- but of the entire template.  */
2977 	specialization = 1;
2978       break;
2979 
2980     default:
2981       gcc_unreachable ();
2982     }
2983 
2984   if ((specialization || member_specialization)
2985       /* This doesn't apply to variable templates.  */
2986       && FUNC_OR_METHOD_TYPE_P (TREE_TYPE (decl)))
2987     {
2988       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2989       for (; t; t = TREE_CHAIN (t))
2990 	if (TREE_PURPOSE (t))
2991 	  {
2992 	    permerror (input_location,
2993 		       "default argument specified in explicit specialization");
2994 	    break;
2995 	  }
2996     }
2997 
2998   if (specialization || member_specialization || explicit_instantiation)
2999     {
3000       tree tmpl = NULL_TREE;
3001       tree targs = NULL_TREE;
3002       bool was_template_id = (TREE_CODE (declarator) == TEMPLATE_ID_EXPR);
3003       bool found_hidden = false;
3004 
3005       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
3006       if (!was_template_id)
3007 	{
3008 	  tree fns;
3009 
3010 	  gcc_assert (identifier_p (declarator));
3011 	  if (ctype)
3012 	    fns = dname;
3013 	  else
3014 	    {
3015 	      /* If there is no class context, the explicit instantiation
3016 		 must be at namespace scope.  */
3017 	      gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
3018 
3019 	      /* Find the namespace binding, using the declaration
3020 		 context.  */
3021 	      fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
3022 					   LOOK_want::NORMAL, true);
3023 	      if (fns == error_mark_node)
3024 		{
3025 		  /* If lookup fails, look for a friend declaration so we can
3026 		     give a better diagnostic.  */
3027 		  fns = (lookup_qualified_name
3028 			 (CP_DECL_CONTEXT (decl), dname,
3029 			  LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND,
3030 			  /*complain*/true));
3031 		  found_hidden = true;
3032 		}
3033 
3034 	      if (fns == error_mark_node || !is_overloaded_fn (fns))
3035 		{
3036 		  error ("%qD is not a template function", dname);
3037 		  fns = error_mark_node;
3038 		}
3039 	    }
3040 
3041 	  declarator = lookup_template_function (fns, NULL_TREE);
3042 	}
3043 
3044       if (declarator == error_mark_node)
3045 	return error_mark_node;
3046 
3047       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
3048 	{
3049 	  if (!explicit_instantiation)
3050 	    /* A specialization in class scope.  This is invalid,
3051 	       but the error will already have been flagged by
3052 	       check_specialization_scope.  */
3053 	    return error_mark_node;
3054 	  else
3055 	    {
3056 	      /* It's not valid to write an explicit instantiation in
3057 		 class scope, e.g.:
3058 
3059 		   class C { template void f(); }
3060 
3061 		   This case is caught by the parser.  However, on
3062 		   something like:
3063 
3064 		   template class C { void f(); };
3065 
3066 		   (which is invalid) we can get here.  The error will be
3067 		   issued later.  */
3068 	      ;
3069 	    }
3070 
3071 	  return decl;
3072 	}
3073       else if (ctype != NULL_TREE
3074 	       && (identifier_p (TREE_OPERAND (declarator, 0))))
3075 	{
3076 	  // We'll match variable templates in start_decl.
3077 	  if (VAR_P (decl))
3078 	    return decl;
3079 
3080 	  /* Find the list of functions in ctype that have the same
3081 	     name as the declared function.  */
3082 	  tree name = TREE_OPERAND (declarator, 0);
3083 
3084 	  if (constructor_name_p (name, ctype))
3085 	    {
3086 	      if (DECL_CONSTRUCTOR_P (decl)
3087 		  ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
3088 		  : !CLASSTYPE_DESTRUCTOR (ctype))
3089 		{
3090 		  /* From [temp.expl.spec]:
3091 
3092 		     If such an explicit specialization for the member
3093 		     of a class template names an implicitly-declared
3094 		     special member function (clause _special_), the
3095 		     program is ill-formed.
3096 
3097 		     Similar language is found in [temp.explicit].  */
3098 		  error ("specialization of implicitly-declared special member function");
3099 		  return error_mark_node;
3100 		}
3101 
3102 	      name = DECL_NAME (decl);
3103 	    }
3104 
3105 	  /* For a type-conversion operator, We might be looking for
3106 	     `operator int' which will be a specialization of
3107 	     `operator T'.  Grab all the conversion operators, and
3108 	     then select from them.  */
3109 	  tree fns = get_class_binding (ctype, IDENTIFIER_CONV_OP_P (name)
3110 					? conv_op_identifier : name);
3111 
3112 	  if (fns == NULL_TREE)
3113 	    {
3114 	      error ("no member function %qD declared in %qT", name, ctype);
3115 	      return error_mark_node;
3116 	    }
3117 	  else
3118 	    TREE_OPERAND (declarator, 0) = fns;
3119 	}
3120 
3121       /* Figure out what exactly is being specialized at this point.
3122 	 Note that for an explicit instantiation, even one for a
3123 	 member function, we cannot tell a priori whether the
3124 	 instantiation is for a member template, or just a member
3125 	 function of a template class.  Even if a member template is
3126 	 being instantiated, the member template arguments may be
3127 	 elided if they can be deduced from the rest of the
3128 	 declaration.  */
3129       tmpl = determine_specialization (declarator, decl,
3130 				       &targs,
3131 				       member_specialization,
3132 				       template_count,
3133 				       tsk);
3134 
3135       if (!tmpl || tmpl == error_mark_node)
3136 	/* We couldn't figure out what this declaration was
3137 	   specializing.  */
3138 	return error_mark_node;
3139       else
3140 	{
3141 	  if (found_hidden && TREE_CODE (decl) == FUNCTION_DECL)
3142 	    {
3143 	      auto_diagnostic_group d;
3144 	      if (pedwarn (DECL_SOURCE_LOCATION (decl), 0,
3145 			   "friend declaration %qD is not visible to "
3146 			   "explicit specialization", tmpl))
3147 		inform (DECL_SOURCE_LOCATION (tmpl),
3148 			"friend declaration here");
3149 	    }
3150 
3151 	  if (!ctype && !is_friend
3152 	      && CP_DECL_CONTEXT (decl) == current_namespace)
3153 	    check_unqualified_spec_or_inst (tmpl, DECL_SOURCE_LOCATION (decl));
3154 
3155 	  tree gen_tmpl = most_general_template (tmpl);
3156 
3157 	  if (explicit_instantiation)
3158 	    {
3159 	      /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
3160 		 is done by do_decl_instantiation later.  */
3161 
3162 	      int arg_depth = TMPL_ARGS_DEPTH (targs);
3163 	      int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
3164 
3165 	      if (arg_depth > parm_depth)
3166 		{
3167 		  /* If TMPL is not the most general template (for
3168 		     example, if TMPL is a friend template that is
3169 		     injected into namespace scope), then there will
3170 		     be too many levels of TARGS.  Remove some of them
3171 		     here.  */
3172 		  int i;
3173 		  tree new_targs;
3174 
3175 		  new_targs = make_tree_vec (parm_depth);
3176 		  for (i = arg_depth - parm_depth; i < arg_depth; ++i)
3177 		    TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
3178 		      = TREE_VEC_ELT (targs, i);
3179 		  targs = new_targs;
3180 		}
3181 
3182 	      return instantiate_template (tmpl, targs, tf_error);
3183 	    }
3184 
3185 	  /* If we thought that the DECL was a member function, but it
3186 	     turns out to be specializing a static member function,
3187 	     make DECL a static member function as well.  */
3188 	  if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3189 	      && DECL_STATIC_FUNCTION_P (tmpl)
3190 	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
3191 	    revert_static_member_fn (decl);
3192 
3193 	  /* If this is a specialization of a member template of a
3194 	     template class, we want to return the TEMPLATE_DECL, not
3195 	     the specialization of it.  */
3196 	  if (tsk == tsk_template && !was_template_id)
3197 	    {
3198 	      tree result = DECL_TEMPLATE_RESULT (tmpl);
3199 	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3200 	      DECL_INITIAL (result) = NULL_TREE;
3201 	      if (have_def)
3202 		{
3203 		  tree parm;
3204 		  DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
3205 		  DECL_SOURCE_LOCATION (result)
3206 		    = DECL_SOURCE_LOCATION (decl);
3207 		  /* We want to use the argument list specified in the
3208 		     definition, not in the original declaration.  */
3209 		  DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
3210 		  for (parm = DECL_ARGUMENTS (result); parm;
3211 		       parm = DECL_CHAIN (parm))
3212 		    DECL_CONTEXT (parm) = result;
3213 		}
3214 	      return register_specialization (tmpl, gen_tmpl, targs,
3215 					      is_friend, 0);
3216 	    }
3217 
3218 	  /* Set up the DECL_TEMPLATE_INFO for DECL.  */
3219 	  DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
3220 
3221 	  if (was_template_id)
3222 	    TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl)) = true;
3223 
3224 	  /* Inherit default function arguments from the template
3225 	     DECL is specializing.  */
3226 	  if (DECL_FUNCTION_TEMPLATE_P (tmpl))
3227 	    copy_default_args_to_explicit_spec (decl);
3228 
3229 	  /* This specialization has the same protection as the
3230 	     template it specializes.  */
3231 	  TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
3232 	  TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
3233 
3234           /* 7.1.1-1 [dcl.stc]
3235 
3236              A storage-class-specifier shall not be specified in an
3237              explicit specialization...
3238 
3239              The parser rejects these, so unless action is taken here,
3240              explicit function specializations will always appear with
3241              global linkage.
3242 
3243              The action recommended by the C++ CWG in response to C++
3244              defect report 605 is to make the storage class and linkage
3245              of the explicit specialization match the templated function:
3246 
3247              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
3248            */
3249           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
3250             {
3251               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
3252               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
3253 
3254               /* A concept cannot be specialized.  */
3255               if (DECL_DECLARED_CONCEPT_P (tmpl_func))
3256                 {
3257                   error ("explicit specialization of function concept %qD",
3258                          gen_tmpl);
3259                   return error_mark_node;
3260                 }
3261 
3262               /* This specialization has the same linkage and visibility as
3263                  the function template it specializes.  */
3264               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
3265 	      if (! TREE_PUBLIC (decl))
3266 		{
3267 		  DECL_INTERFACE_KNOWN (decl) = 1;
3268 		  DECL_NOT_REALLY_EXTERN (decl) = 1;
3269 		}
3270               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
3271               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
3272                 {
3273                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
3274                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
3275                 }
3276             }
3277 
3278 	  /* If DECL is a friend declaration, declared using an
3279 	     unqualified name, the namespace associated with DECL may
3280 	     have been set incorrectly.  For example, in:
3281 
3282 	       template <typename T> void f(T);
3283 	       namespace N {
3284 		 struct S { friend void f<int>(int); }
3285 	       }
3286 
3287 	     we will have set the DECL_CONTEXT for the friend
3288 	     declaration to N, rather than to the global namespace.  */
3289 	  if (DECL_NAMESPACE_SCOPE_P (decl))
3290 	    DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
3291 
3292 	  if (is_friend && !have_def)
3293 	    /* This is not really a declaration of a specialization.
3294 	       It's just the name of an instantiation.  But, it's not
3295 	       a request for an instantiation, either.  */
3296 	    SET_DECL_IMPLICIT_INSTANTIATION (decl);
3297 	  else if (TREE_CODE (decl) == FUNCTION_DECL)
3298 	    /* A specialization is not necessarily COMDAT.  */
3299 	    DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
3300 				  && DECL_DECLARED_INLINE_P (decl));
3301 	  else if (VAR_P (decl))
3302 	    DECL_COMDAT (decl) = false;
3303 
3304 	  /* If this is a full specialization, register it so that we can find
3305 	     it again.  Partial specializations will be registered in
3306 	     process_partial_specialization.  */
3307 	  if (!processing_template_decl)
3308 	    {
3309 	      warn_spec_missing_attributes (gen_tmpl, decl, attrlist);
3310 
3311 	      decl = register_specialization (decl, gen_tmpl, targs,
3312 					      is_friend, 0);
3313 	    }
3314 
3315 
3316 	  /* A 'structor should already have clones.  */
3317 	  gcc_assert (decl == error_mark_node
3318 		      || variable_template_p (tmpl)
3319 		      || !(DECL_CONSTRUCTOR_P (decl)
3320 			   || DECL_DESTRUCTOR_P (decl))
3321 		      || DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
3322 	}
3323     }
3324 
3325   return decl;
3326 }
3327 
3328 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
3329    parameters.  These are represented in the same format used for
3330    DECL_TEMPLATE_PARMS.  */
3331 
3332 int
comp_template_parms(const_tree parms1,const_tree parms2)3333 comp_template_parms (const_tree parms1, const_tree parms2)
3334 {
3335   const_tree p1;
3336   const_tree p2;
3337 
3338   if (parms1 == parms2)
3339     return 1;
3340 
3341   for (p1 = parms1, p2 = parms2;
3342        p1 != NULL_TREE && p2 != NULL_TREE;
3343        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
3344     {
3345       tree t1 = TREE_VALUE (p1);
3346       tree t2 = TREE_VALUE (p2);
3347       int i;
3348 
3349       gcc_assert (TREE_CODE (t1) == TREE_VEC);
3350       gcc_assert (TREE_CODE (t2) == TREE_VEC);
3351 
3352       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
3353 	return 0;
3354 
3355       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
3356 	{
3357           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
3358           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
3359 
3360           /* If either of the template parameters are invalid, assume
3361              they match for the sake of error recovery. */
3362           if (error_operand_p (parm1) || error_operand_p (parm2))
3363             return 1;
3364 
3365 	  if (TREE_CODE (parm1) != TREE_CODE (parm2))
3366 	    return 0;
3367 
3368 	  if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
3369               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
3370                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
3371 	    continue;
3372 	  else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
3373 	    return 0;
3374 	}
3375     }
3376 
3377   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3378     /* One set of parameters has more parameters lists than the
3379        other.  */
3380     return 0;
3381 
3382   return 1;
3383 }
3384 
3385 /* Returns true if two template parameters are declared with
3386    equivalent constraints.  */
3387 
3388 static bool
template_parameter_constraints_equivalent_p(const_tree parm1,const_tree parm2)3389 template_parameter_constraints_equivalent_p (const_tree parm1, const_tree parm2)
3390 {
3391   tree req1 = TREE_TYPE (parm1);
3392   tree req2 = TREE_TYPE (parm2);
3393   if (!req1 != !req2)
3394     return false;
3395   if (req1)
3396     return cp_tree_equal (req1, req2);
3397   return true;
3398 }
3399 
3400 /* Returns true when two template parameters are equivalent.  */
3401 
3402 static bool
template_parameters_equivalent_p(const_tree parm1,const_tree parm2)3403 template_parameters_equivalent_p (const_tree parm1, const_tree parm2)
3404 {
3405   tree decl1 = TREE_VALUE (parm1);
3406   tree decl2 = TREE_VALUE (parm2);
3407 
3408   /* If either of the template parameters are invalid, assume
3409      they match for the sake of error recovery. */
3410   if (error_operand_p (decl1) || error_operand_p (decl2))
3411     return true;
3412 
3413   /* ... they declare parameters of the same kind.  */
3414   if (TREE_CODE (decl1) != TREE_CODE (decl2))
3415     return false;
3416 
3417   /* ... one parameter was introduced by a parameter declaration, then
3418      both are. This case arises as a result of eagerly rewriting declarations
3419      during parsing.  */
3420   if (DECL_VIRTUAL_P (decl1) != DECL_VIRTUAL_P (decl2))
3421     return false;
3422 
3423   /* ... if either declares a pack, they both do.  */
3424   if (template_parameter_pack_p (decl1) != template_parameter_pack_p (decl2))
3425     return false;
3426 
3427   if (TREE_CODE (decl1) == PARM_DECL)
3428     {
3429       /* ... if they declare non-type parameters, the types are equivalent.  */
3430       if (!same_type_p (TREE_TYPE (decl1), TREE_TYPE (decl2)))
3431 	return false;
3432     }
3433   else if (TREE_CODE (decl2) == TEMPLATE_DECL)
3434     {
3435       /* ... if they declare template template parameters, their template
3436 	 parameter lists are equivalent.  */
3437       if (!template_heads_equivalent_p (decl1, decl2))
3438 	return false;
3439     }
3440 
3441   /* ... if they are declared with a qualified-concept name, they both
3442      are, and those names are equivalent.  */
3443   return template_parameter_constraints_equivalent_p (parm1, parm2);
3444 }
3445 
3446 /* Returns true if two template parameters lists are equivalent.
3447    Two template parameter lists are equivalent if they have the
3448    same length and their corresponding parameters are equivalent.
3449 
3450    PARMS1 and PARMS2 are TREE_LISTs containing TREE_VECs: the
3451    data structure returned by DECL_TEMPLATE_PARMS.
3452 
3453    This is generally the same implementation as comp_template_parms
3454    except that it also the concept names and arguments used to
3455    introduce parameters.  */
3456 
3457 static bool
template_parameter_lists_equivalent_p(const_tree parms1,const_tree parms2)3458 template_parameter_lists_equivalent_p (const_tree parms1, const_tree parms2)
3459 {
3460   if (parms1 == parms2)
3461     return true;
3462 
3463   const_tree p1 = parms1;
3464   const_tree p2 = parms2;
3465   while (p1 != NULL_TREE && p2 != NULL_TREE)
3466     {
3467       tree list1 = TREE_VALUE (p1);
3468       tree list2 = TREE_VALUE (p2);
3469 
3470       if (TREE_VEC_LENGTH (list1) != TREE_VEC_LENGTH (list2))
3471 	return 0;
3472 
3473       for (int i = 0; i < TREE_VEC_LENGTH (list2); ++i)
3474 	{
3475 	  tree parm1 = TREE_VEC_ELT (list1, i);
3476 	  tree parm2 = TREE_VEC_ELT (list2, i);
3477 	  if (!template_parameters_equivalent_p (parm1, parm2))
3478 	    return false;
3479 	}
3480 
3481       p1 = TREE_CHAIN (p1);
3482       p2 = TREE_CHAIN (p2);
3483     }
3484 
3485   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3486     return false;
3487 
3488   return true;
3489 }
3490 
3491 /* Return true if the requires-clause of the template parameter lists are
3492    equivalent and false otherwise.  */
3493 static bool
template_requirements_equivalent_p(const_tree parms1,const_tree parms2)3494 template_requirements_equivalent_p (const_tree parms1, const_tree parms2)
3495 {
3496   tree req1 = TEMPLATE_PARMS_CONSTRAINTS (parms1);
3497   tree req2 = TEMPLATE_PARMS_CONSTRAINTS (parms2);
3498   if ((req1 != NULL_TREE) != (req2 != NULL_TREE))
3499     return false;
3500   if (!cp_tree_equal (req1, req2))
3501     return false;
3502   return true;
3503 }
3504 
3505 /* Returns true if two template heads are equivalent. 17.6.6.1p6:
3506    Two template heads are equivalent if their template parameter
3507    lists are equivalent and their requires clauses are equivalent.
3508 
3509    In pre-C++20, this is equivalent to calling comp_template_parms
3510    for the template parameters of TMPL1 and TMPL2.  */
3511 
3512 bool
template_heads_equivalent_p(const_tree tmpl1,const_tree tmpl2)3513 template_heads_equivalent_p (const_tree tmpl1, const_tree tmpl2)
3514 {
3515   tree parms1 = DECL_TEMPLATE_PARMS (tmpl1);
3516   tree parms2 = DECL_TEMPLATE_PARMS (tmpl2);
3517 
3518   /* Don't change the matching rules for pre-C++20.  */
3519   if (cxx_dialect < cxx20)
3520     return comp_template_parms (parms1, parms2);
3521 
3522   /* ... have the same number of template parameters, and their
3523      corresponding parameters are equivalent.  */
3524   if (!template_parameter_lists_equivalent_p (parms1, parms2))
3525     return false;
3526 
3527   /* ... if either has a requires-clause, they both do and their
3528      corresponding constraint-expressions are equivalent.  */
3529   return template_requirements_equivalent_p (parms1, parms2);
3530 }
3531 
3532 /* Determine whether PARM is a parameter pack.  */
3533 
3534 bool
template_parameter_pack_p(const_tree parm)3535 template_parameter_pack_p (const_tree parm)
3536 {
3537   /* Determine if we have a non-type template parameter pack.  */
3538   if (TREE_CODE (parm) == PARM_DECL)
3539     return (DECL_TEMPLATE_PARM_P (parm)
3540             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
3541   if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
3542     return TEMPLATE_PARM_PARAMETER_PACK (parm);
3543 
3544   /* If this is a list of template parameters, we could get a
3545      TYPE_DECL or a TEMPLATE_DECL.  */
3546   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
3547     parm = TREE_TYPE (parm);
3548 
3549   /* Otherwise it must be a type template parameter.  */
3550   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
3551 	   || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
3552 	  && TEMPLATE_TYPE_PARAMETER_PACK (parm));
3553 }
3554 
3555 /* Determine if T is a function parameter pack.  */
3556 
3557 bool
function_parameter_pack_p(const_tree t)3558 function_parameter_pack_p (const_tree t)
3559 {
3560   if (t && TREE_CODE (t) == PARM_DECL)
3561     return DECL_PACK_P (t);
3562   return false;
3563 }
3564 
3565 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
3566    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
3567 
3568 tree
get_function_template_decl(const_tree primary_func_tmpl_inst)3569 get_function_template_decl (const_tree primary_func_tmpl_inst)
3570 {
3571   if (! primary_func_tmpl_inst
3572       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
3573       || ! primary_template_specialization_p (primary_func_tmpl_inst))
3574     return NULL;
3575 
3576   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
3577 }
3578 
3579 /* Return true iff the function parameter PARAM_DECL was expanded
3580    from the function parameter pack PACK.  */
3581 
3582 bool
function_parameter_expanded_from_pack_p(tree param_decl,tree pack)3583 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
3584 {
3585   if (DECL_ARTIFICIAL (param_decl)
3586       || !function_parameter_pack_p (pack))
3587     return false;
3588 
3589   /* The parameter pack and its pack arguments have the same
3590      DECL_PARM_INDEX.  */
3591   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
3592 }
3593 
3594 /* Determine whether ARGS describes a variadic template args list,
3595    i.e., one that is terminated by a template argument pack.  */
3596 
3597 static bool
template_args_variadic_p(tree args)3598 template_args_variadic_p (tree args)
3599 {
3600   int nargs;
3601   tree last_parm;
3602 
3603   if (args == NULL_TREE)
3604     return false;
3605 
3606   args = INNERMOST_TEMPLATE_ARGS (args);
3607   nargs = TREE_VEC_LENGTH (args);
3608 
3609   if (nargs == 0)
3610     return false;
3611 
3612   last_parm = TREE_VEC_ELT (args, nargs - 1);
3613 
3614   return ARGUMENT_PACK_P (last_parm);
3615 }
3616 
3617 /* Generate a new name for the parameter pack name NAME (an
3618    IDENTIFIER_NODE) that incorporates its */
3619 
3620 static tree
make_ith_pack_parameter_name(tree name,int i)3621 make_ith_pack_parameter_name (tree name, int i)
3622 {
3623   /* Munge the name to include the parameter index.  */
3624 #define NUMBUF_LEN 128
3625   char numbuf[NUMBUF_LEN];
3626   char* newname;
3627   int newname_len;
3628 
3629   if (name == NULL_TREE)
3630     return name;
3631   snprintf (numbuf, NUMBUF_LEN, "%i", i);
3632   newname_len = IDENTIFIER_LENGTH (name)
3633 	        + strlen (numbuf) + 2;
3634   newname = (char*)alloca (newname_len);
3635   snprintf (newname, newname_len,
3636 	    "%s#%i", IDENTIFIER_POINTER (name), i);
3637   return get_identifier (newname);
3638 }
3639 
3640 /* Return true if T is a primary function, class or alias template
3641    specialization, not including the template pattern.  */
3642 
3643 bool
primary_template_specialization_p(const_tree t)3644 primary_template_specialization_p (const_tree t)
3645 {
3646   if (!t)
3647     return false;
3648 
3649   if (VAR_OR_FUNCTION_DECL_P (t))
3650     return (DECL_LANG_SPECIFIC (t)
3651 	    && DECL_USE_TEMPLATE (t)
3652 	    && DECL_TEMPLATE_INFO (t)
3653 	    && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t)));
3654   else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
3655     return (CLASSTYPE_TEMPLATE_INFO (t)
3656 	    && CLASSTYPE_USE_TEMPLATE (t)
3657 	    && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)));
3658   else if (alias_template_specialization_p (t, nt_transparent))
3659     return true;
3660   return false;
3661 }
3662 
3663 /* Return true if PARM is a template template parameter.  */
3664 
3665 bool
template_template_parameter_p(const_tree parm)3666 template_template_parameter_p (const_tree parm)
3667 {
3668   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
3669 }
3670 
3671 /* Return true iff PARM is a DECL representing a type template
3672    parameter.  */
3673 
3674 bool
template_type_parameter_p(const_tree parm)3675 template_type_parameter_p (const_tree parm)
3676 {
3677   return (parm
3678 	  && (TREE_CODE (parm) == TYPE_DECL
3679 	      || TREE_CODE (parm) == TEMPLATE_DECL)
3680 	  && DECL_TEMPLATE_PARM_P (parm));
3681 }
3682 
3683 /* Return the template parameters of T if T is a
3684    primary template instantiation, NULL otherwise.  */
3685 
3686 tree
get_primary_template_innermost_parameters(const_tree t)3687 get_primary_template_innermost_parameters (const_tree t)
3688 {
3689   tree parms = NULL, template_info = NULL;
3690 
3691   if ((template_info = get_template_info (t))
3692       && primary_template_specialization_p (t))
3693     parms = INNERMOST_TEMPLATE_PARMS
3694 	(DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
3695 
3696   return parms;
3697 }
3698 
3699 /* Returns the template arguments of T if T is a template instantiation,
3700    NULL otherwise.  */
3701 
3702 tree
get_template_innermost_arguments(const_tree t)3703 get_template_innermost_arguments (const_tree t)
3704 {
3705   tree args = NULL, template_info = NULL;
3706 
3707   if ((template_info = get_template_info (t))
3708       && TI_ARGS (template_info))
3709     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
3710 
3711   return args;
3712 }
3713 
3714 /* Return the argument pack elements of T if T is a template argument pack,
3715    NULL otherwise.  */
3716 
3717 tree
get_template_argument_pack_elems(const_tree t)3718 get_template_argument_pack_elems (const_tree t)
3719 {
3720   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
3721       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
3722     return NULL;
3723 
3724   return ARGUMENT_PACK_ARGS (t);
3725 }
3726 
3727 /* In an ARGUMENT_PACK_SELECT, the actual underlying argument that the
3728    ARGUMENT_PACK_SELECT represents. */
3729 
3730 static tree
argument_pack_select_arg(tree t)3731 argument_pack_select_arg (tree t)
3732 {
3733   tree args = ARGUMENT_PACK_ARGS (ARGUMENT_PACK_SELECT_FROM_PACK (t));
3734   tree arg = TREE_VEC_ELT (args, ARGUMENT_PACK_SELECT_INDEX (t));
3735 
3736   /* If the selected argument is an expansion E, that most likely means we were
3737      called from gen_elem_of_pack_expansion_instantiation during the
3738      substituting of an argument pack (of which the Ith element is a pack
3739      expansion, where I is ARGUMENT_PACK_SELECT_INDEX) into a pack expansion.
3740      In this case, the Ith element resulting from this substituting is going to
3741      be a pack expansion, which pattern is the pattern of E.  Let's return the
3742      pattern of E, and gen_elem_of_pack_expansion_instantiation will build the
3743      resulting pack expansion from it.  */
3744   if (PACK_EXPANSION_P (arg))
3745     {
3746       /* Make sure we aren't throwing away arg info.  */
3747       gcc_assert (!PACK_EXPANSION_EXTRA_ARGS (arg));
3748       arg = PACK_EXPANSION_PATTERN (arg);
3749     }
3750 
3751   return arg;
3752 }
3753 
3754 /* Return a modification of ARGS that's suitable for preserving inside a hash
3755    table.  In particular, this replaces each ARGUMENT_PACK_SELECT with its
3756    underlying argument.  ARGS is copied (upon modification) iff COW_P.  */
3757 
3758 static tree
preserve_args(tree args,bool cow_p=true)3759 preserve_args (tree args, bool cow_p = true)
3760 {
3761   if (!args)
3762     return NULL_TREE;
3763 
3764   for (int i = 0, len = TREE_VEC_LENGTH (args); i < len; ++i)
3765     {
3766       tree t = TREE_VEC_ELT (args, i);
3767       tree r;
3768       if (!t)
3769 	r = NULL_TREE;
3770       else if (TREE_CODE (t) == ARGUMENT_PACK_SELECT)
3771 	r = argument_pack_select_arg (t);
3772       else if (TREE_CODE (t) == TREE_VEC)
3773 	r = preserve_args (t, cow_p);
3774       else
3775 	r = t;
3776       if (r != t)
3777 	{
3778 	  if (cow_p)
3779 	    {
3780 	      args = copy_template_args (args);
3781 	      cow_p = false;
3782 	    }
3783 	  TREE_VEC_ELT (args, i) = r;
3784 	}
3785     }
3786 
3787   return args;
3788 }
3789 
3790 /* True iff FN is a function representing a built-in variadic parameter
3791    pack.  */
3792 
3793 bool
builtin_pack_fn_p(tree fn)3794 builtin_pack_fn_p (tree fn)
3795 {
3796   if (!fn
3797       || TREE_CODE (fn) != FUNCTION_DECL
3798       || !DECL_IS_UNDECLARED_BUILTIN (fn))
3799     return false;
3800 
3801   if (id_equal (DECL_NAME (fn), "__integer_pack"))
3802     return true;
3803 
3804   return false;
3805 }
3806 
3807 /* True iff CALL is a call to a function representing a built-in variadic
3808    parameter pack.  */
3809 
3810 static bool
builtin_pack_call_p(tree call)3811 builtin_pack_call_p (tree call)
3812 {
3813   if (TREE_CODE (call) != CALL_EXPR)
3814     return false;
3815   return builtin_pack_fn_p (CALL_EXPR_FN (call));
3816 }
3817 
3818 /* Return a TREE_VEC for the expansion of __integer_pack(HI).  */
3819 
3820 static tree
expand_integer_pack(tree call,tree args,tsubst_flags_t complain,tree in_decl)3821 expand_integer_pack (tree call, tree args, tsubst_flags_t complain,
3822 		     tree in_decl)
3823 {
3824   tree ohi = CALL_EXPR_ARG (call, 0);
3825   tree hi = tsubst_copy_and_build (ohi, args, complain, in_decl,
3826 				   false/*fn*/, true/*int_cst*/);
3827 
3828   if (instantiation_dependent_expression_p (hi))
3829     {
3830       if (hi != ohi)
3831 	{
3832 	  call = copy_node (call);
3833 	  CALL_EXPR_ARG (call, 0) = hi;
3834 	}
3835       tree ex = make_pack_expansion (call, complain);
3836       tree vec = make_tree_vec (1);
3837       TREE_VEC_ELT (vec, 0) = ex;
3838       return vec;
3839     }
3840   else
3841     {
3842       hi = instantiate_non_dependent_expr_sfinae (hi, complain);
3843       hi = cxx_constant_value (hi);
3844       int len = valid_constant_size_p (hi) ? tree_to_shwi (hi) : -1;
3845 
3846       /* Calculate the largest value of len that won't make the size of the vec
3847 	 overflow an int.  The compiler will exceed resource limits long before
3848 	 this, but it seems a decent place to diagnose.  */
3849       int max = ((INT_MAX - sizeof (tree_vec)) / sizeof (tree)) + 1;
3850 
3851       if (len < 0 || len > max)
3852 	{
3853 	  if ((complain & tf_error)
3854 	      && hi != error_mark_node)
3855 	    error ("argument to %<__integer_pack%> must be between 0 and %d",
3856 		   max);
3857 	  return error_mark_node;
3858 	}
3859 
3860       tree vec = make_tree_vec (len);
3861 
3862       for (int i = 0; i < len; ++i)
3863 	TREE_VEC_ELT (vec, i) = size_int (i);
3864 
3865       return vec;
3866     }
3867 }
3868 
3869 /* Return a TREE_VEC for the expansion of built-in template parameter pack
3870    CALL.  */
3871 
3872 static tree
expand_builtin_pack_call(tree call,tree args,tsubst_flags_t complain,tree in_decl)3873 expand_builtin_pack_call (tree call, tree args, tsubst_flags_t complain,
3874 			  tree in_decl)
3875 {
3876   if (!builtin_pack_call_p (call))
3877     return NULL_TREE;
3878 
3879   tree fn = CALL_EXPR_FN (call);
3880 
3881   if (id_equal (DECL_NAME (fn), "__integer_pack"))
3882     return expand_integer_pack (call, args, complain, in_decl);
3883 
3884   return NULL_TREE;
3885 }
3886 
3887 /* Return true if the tree T has the extra args mechanism for
3888    avoiding partial instantiation.  */
3889 
3890 static bool
has_extra_args_mechanism_p(const_tree t)3891 has_extra_args_mechanism_p (const_tree t)
3892 {
3893   return (PACK_EXPANSION_P (t) /* PACK_EXPANSION_EXTRA_ARGS  */
3894 	  || TREE_CODE (t) == REQUIRES_EXPR /* REQUIRES_EXPR_EXTRA_ARGS  */
3895 	  || (TREE_CODE (t) == IF_STMT
3896 	      && IF_STMT_CONSTEXPR_P (t))); /* IF_STMT_EXTRA_ARGS  */
3897 }
3898 
3899 /* Structure used to track the progress of find_parameter_packs_r.  */
3900 struct find_parameter_pack_data
3901 {
3902   /* TREE_LIST that will contain all of the parameter packs found by
3903      the traversal.  */
3904   tree* parameter_packs;
3905 
3906   /* Set of AST nodes that have been visited by the traversal.  */
3907   hash_set<tree> *visited;
3908 
3909   /* True iff we're making a type pack expansion.  */
3910   bool type_pack_expansion_p;
3911 
3912   /* True iff we found a subtree that has the extra args mechanism.  */
3913   bool found_extra_args_tree_p = false;
3914 };
3915 
3916 /* Identifies all of the argument packs that occur in a template
3917    argument and appends them to the TREE_LIST inside DATA, which is a
3918    find_parameter_pack_data structure. This is a subroutine of
3919    make_pack_expansion and uses_parameter_packs.  */
3920 static tree
find_parameter_packs_r(tree * tp,int * walk_subtrees,void * data)3921 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
3922 {
3923   tree t = *tp;
3924   struct find_parameter_pack_data* ppd =
3925     (struct find_parameter_pack_data*)data;
3926   bool parameter_pack_p = false;
3927 
3928 #define WALK_SUBTREE(NODE)				\
3929   cp_walk_tree (&(NODE), &find_parameter_packs_r,	\
3930 		ppd, ppd->visited)			\
3931 
3932   /* Don't look through typedefs; we are interested in whether a
3933      parameter pack is actually written in the expression/type we're
3934      looking at, not the target type.  */
3935   if (TYPE_P (t) && typedef_variant_p (t))
3936     {
3937       /* But do look at arguments for an alias template.  */
3938       if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
3939 	cp_walk_tree (&TI_ARGS (tinfo),
3940 		      &find_parameter_packs_r,
3941 		      ppd, ppd->visited);
3942       *walk_subtrees = 0;
3943       return NULL_TREE;
3944     }
3945 
3946   /* Identify whether this is a parameter pack or not.  */
3947   switch (TREE_CODE (t))
3948     {
3949     case TEMPLATE_PARM_INDEX:
3950       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3951         parameter_pack_p = true;
3952       break;
3953 
3954     case TEMPLATE_TYPE_PARM:
3955       t = TYPE_MAIN_VARIANT (t);
3956       /* FALLTHRU */
3957     case TEMPLATE_TEMPLATE_PARM:
3958       /* If the placeholder appears in the decl-specifier-seq of a function
3959 	 parameter pack (14.6.3), or the type-specifier-seq of a type-id that
3960 	 is a pack expansion, the invented template parameter is a template
3961 	 parameter pack.  */
3962       if (ppd->type_pack_expansion_p && is_auto (t))
3963 	TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
3964       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3965         parameter_pack_p = true;
3966       break;
3967 
3968     case FIELD_DECL:
3969     case PARM_DECL:
3970       if (DECL_PACK_P (t))
3971         {
3972           /* We don't want to walk into the type of a PARM_DECL,
3973              because we don't want to see the type parameter pack.  */
3974           *walk_subtrees = 0;
3975 	  parameter_pack_p = true;
3976         }
3977       break;
3978 
3979     case VAR_DECL:
3980       if (DECL_PACK_P (t))
3981         {
3982           /* We don't want to walk into the type of a variadic capture proxy,
3983              because we don't want to see the type parameter pack.  */
3984           *walk_subtrees = 0;
3985 	  parameter_pack_p = true;
3986         }
3987       else if (variable_template_specialization_p (t))
3988 	{
3989 	  cp_walk_tree (&DECL_TI_ARGS (t),
3990 			find_parameter_packs_r,
3991 			ppd, ppd->visited);
3992 	  *walk_subtrees = 0;
3993 	}
3994       break;
3995 
3996     case CALL_EXPR:
3997       if (builtin_pack_call_p (t))
3998 	parameter_pack_p = true;
3999       break;
4000 
4001     case BASES:
4002       parameter_pack_p = true;
4003       break;
4004     default:
4005       /* Not a parameter pack.  */
4006       break;
4007     }
4008 
4009   if (parameter_pack_p)
4010     {
4011       /* Add this parameter pack to the list.  */
4012       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
4013     }
4014 
4015   if (has_extra_args_mechanism_p (t) && !PACK_EXPANSION_P (t))
4016     ppd->found_extra_args_tree_p = true;
4017 
4018   if (TYPE_P (t))
4019     cp_walk_tree (&TYPE_CONTEXT (t),
4020 		  &find_parameter_packs_r, ppd, ppd->visited);
4021 
4022   /* This switch statement will return immediately if we don't find a
4023      parameter pack.  ??? Should some of these be in cp_walk_subtrees?  */
4024   switch (TREE_CODE (t))
4025     {
4026     case BOUND_TEMPLATE_TEMPLATE_PARM:
4027       /* Check the template itself.  */
4028       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)),
4029 		    &find_parameter_packs_r, ppd, ppd->visited);
4030       return NULL_TREE;
4031 
4032     case DECL_EXPR:
4033       {
4034 	tree decl = DECL_EXPR_DECL (t);
4035 	/* Ignore the declaration of a capture proxy for a parameter pack.  */
4036 	if (is_capture_proxy (decl))
4037 	  *walk_subtrees = 0;
4038 	if (is_typedef_decl (decl))
4039 	  /* Since we stop at typedefs above, we need to look through them at
4040 	     the point of the DECL_EXPR.  */
4041 	  cp_walk_tree (&DECL_ORIGINAL_TYPE (decl),
4042 			&find_parameter_packs_r, ppd, ppd->visited);
4043 	return NULL_TREE;
4044       }
4045 
4046     case TEMPLATE_DECL:
4047       if (!DECL_TEMPLATE_TEMPLATE_PARM_P (t))
4048 	return NULL_TREE;
4049       cp_walk_tree (&TREE_TYPE (t),
4050 		    &find_parameter_packs_r, ppd, ppd->visited);
4051       return NULL_TREE;
4052 
4053     case TYPE_PACK_EXPANSION:
4054     case EXPR_PACK_EXPANSION:
4055       *walk_subtrees = 0;
4056       return NULL_TREE;
4057 
4058     case INTEGER_TYPE:
4059       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r,
4060 		    ppd, ppd->visited);
4061       *walk_subtrees = 0;
4062       return NULL_TREE;
4063 
4064     case IDENTIFIER_NODE:
4065       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd,
4066 		    ppd->visited);
4067       *walk_subtrees = 0;
4068       return NULL_TREE;
4069 
4070     case LAMBDA_EXPR:
4071       {
4072 	/* Since we defer implicit capture, look in the parms and body.  */
4073 	tree fn = lambda_function (t);
4074 	cp_walk_tree (&TREE_TYPE (fn), &find_parameter_packs_r, ppd,
4075 		      ppd->visited);
4076 	cp_walk_tree (&DECL_SAVED_TREE (fn), &find_parameter_packs_r, ppd,
4077 		      ppd->visited);
4078 	return NULL_TREE;
4079       }
4080 
4081     case DECLTYPE_TYPE:
4082       {
4083 	/* When traversing a DECLTYPE_TYPE_EXPR, we need to set
4084 	   type_pack_expansion_p to false so that any placeholders
4085 	   within the expression don't get marked as parameter packs.  */
4086 	bool type_pack_expansion_p = ppd->type_pack_expansion_p;
4087 	ppd->type_pack_expansion_p = false;
4088 	cp_walk_tree (&DECLTYPE_TYPE_EXPR (t), &find_parameter_packs_r,
4089 		      ppd, ppd->visited);
4090 	ppd->type_pack_expansion_p = type_pack_expansion_p;
4091 	*walk_subtrees = 0;
4092 	return NULL_TREE;
4093       }
4094 
4095     case IF_STMT:
4096       cp_walk_tree (&IF_COND (t), &find_parameter_packs_r,
4097 		    ppd, ppd->visited);
4098       cp_walk_tree (&THEN_CLAUSE (t), &find_parameter_packs_r,
4099 		    ppd, ppd->visited);
4100       cp_walk_tree (&ELSE_CLAUSE (t), &find_parameter_packs_r,
4101 		    ppd, ppd->visited);
4102       /* Don't walk into IF_STMT_EXTRA_ARGS.  */
4103       *walk_subtrees = 0;
4104       return NULL_TREE;
4105 
4106     case TAG_DEFN:
4107       t = TREE_TYPE (t);
4108       if (CLASS_TYPE_P (t))
4109 	{
4110 	  /* Local class, need to look through the whole definition.
4111 	     TYPE_BINFO might be unset for a partial instantiation.  */
4112 	  if (TYPE_BINFO (t))
4113 	    for (tree bb : BINFO_BASE_BINFOS (TYPE_BINFO (t)))
4114 	      cp_walk_tree (&BINFO_TYPE (bb), &find_parameter_packs_r,
4115 			    ppd, ppd->visited);
4116 	}
4117       else
4118 	/* Enum, look at the values.  */
4119 	for (tree l = TYPE_VALUES (t); l; l = TREE_CHAIN (l))
4120 	  cp_walk_tree (&DECL_INITIAL (TREE_VALUE (l)),
4121 			&find_parameter_packs_r,
4122 			ppd, ppd->visited);
4123       return NULL_TREE;
4124 
4125     case FUNCTION_TYPE:
4126     case METHOD_TYPE:
4127       WALK_SUBTREE (TYPE_RAISES_EXCEPTIONS (t));
4128       break;
4129 
4130     default:
4131       return NULL_TREE;
4132     }
4133 
4134 #undef WALK_SUBTREE
4135 
4136   return NULL_TREE;
4137 }
4138 
4139 /* Determines if the expression or type T uses any parameter packs.  */
4140 tree
uses_parameter_packs(tree t)4141 uses_parameter_packs (tree t)
4142 {
4143   tree parameter_packs = NULL_TREE;
4144   struct find_parameter_pack_data ppd;
4145   ppd.parameter_packs = &parameter_packs;
4146   ppd.visited = new hash_set<tree>;
4147   ppd.type_pack_expansion_p = false;
4148   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4149   delete ppd.visited;
4150   return parameter_packs;
4151 }
4152 
4153 /* Turn ARG, which may be an expression, type, or a TREE_LIST
4154    representation a base-class initializer into a parameter pack
4155    expansion. If all goes well, the resulting node will be an
4156    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
4157    respectively.  */
4158 tree
make_pack_expansion(tree arg,tsubst_flags_t complain)4159 make_pack_expansion (tree arg, tsubst_flags_t complain)
4160 {
4161   tree result;
4162   tree parameter_packs = NULL_TREE;
4163   bool for_types = false;
4164   struct find_parameter_pack_data ppd;
4165 
4166   if (!arg || arg == error_mark_node)
4167     return arg;
4168 
4169   if (TREE_CODE (arg) == TREE_LIST && TREE_PURPOSE (arg))
4170     {
4171       /* A TREE_LIST with a non-null TREE_PURPOSE is for a base
4172          class initializer.  In this case, the TREE_PURPOSE will be a
4173          _TYPE node (representing the base class expansion we're
4174          initializing) and the TREE_VALUE will be a TREE_LIST
4175          containing the initialization arguments.
4176 
4177          The resulting expansion looks somewhat different from most
4178          expansions. Rather than returning just one _EXPANSION, we
4179          return a TREE_LIST whose TREE_PURPOSE is a
4180          TYPE_PACK_EXPANSION containing the bases that will be
4181          initialized.  The TREE_VALUE will be identical to the
4182          original TREE_VALUE, which is a list of arguments that will
4183          be passed to each base.  We do not introduce any new pack
4184          expansion nodes into the TREE_VALUE (although it is possible
4185          that some already exist), because the TREE_PURPOSE and
4186          TREE_VALUE all need to be expanded together with the same
4187          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
4188          resulting TREE_PURPOSE will mention the parameter packs in
4189          both the bases and the arguments to the bases.  */
4190       tree purpose;
4191       tree value;
4192       tree parameter_packs = NULL_TREE;
4193 
4194       /* Determine which parameter packs will be used by the base
4195          class expansion.  */
4196       ppd.visited = new hash_set<tree>;
4197       ppd.parameter_packs = &parameter_packs;
4198       ppd.type_pack_expansion_p = false;
4199       gcc_assert (TYPE_P (TREE_PURPOSE (arg)));
4200       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r,
4201                     &ppd, ppd.visited);
4202 
4203       if (parameter_packs == NULL_TREE)
4204         {
4205 	  if (complain & tf_error)
4206 	    error ("base initializer expansion %qT contains no parameter packs",
4207 		   arg);
4208           delete ppd.visited;
4209           return error_mark_node;
4210         }
4211 
4212       if (TREE_VALUE (arg) != void_type_node)
4213         {
4214           /* Collect the sets of parameter packs used in each of the
4215              initialization arguments.  */
4216           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
4217             {
4218               /* Determine which parameter packs will be expanded in this
4219                  argument.  */
4220               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r,
4221                             &ppd, ppd.visited);
4222             }
4223         }
4224 
4225       delete ppd.visited;
4226 
4227       /* Create the pack expansion type for the base type.  */
4228       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
4229       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
4230       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
4231       PACK_EXPANSION_LOCAL_P (purpose) = at_function_scope_p ();
4232 
4233       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4234 	 they will rarely be compared to anything.  */
4235       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
4236 
4237       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
4238     }
4239 
4240   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
4241     for_types = true;
4242 
4243   /* Build the PACK_EXPANSION_* node.  */
4244   result = for_types
4245      ? cxx_make_type (TYPE_PACK_EXPANSION)
4246      : make_node (EXPR_PACK_EXPANSION);
4247   SET_PACK_EXPANSION_PATTERN (result, arg);
4248   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
4249     {
4250       /* Propagate type and const-expression information.  */
4251       TREE_TYPE (result) = TREE_TYPE (arg);
4252       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
4253       /* Mark this read now, since the expansion might be length 0.  */
4254       mark_exp_read (arg);
4255     }
4256   else
4257     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4258        they will rarely be compared to anything.  */
4259     SET_TYPE_STRUCTURAL_EQUALITY (result);
4260 
4261   /* Determine which parameter packs will be expanded.  */
4262   ppd.parameter_packs = &parameter_packs;
4263   ppd.visited = new hash_set<tree>;
4264   ppd.type_pack_expansion_p = TYPE_P (arg);
4265   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
4266   delete ppd.visited;
4267 
4268   /* Make sure we found some parameter packs.  */
4269   if (parameter_packs == NULL_TREE)
4270     {
4271       if (complain & tf_error)
4272 	{
4273 	  if (TYPE_P (arg))
4274 	    error ("expansion pattern %qT contains no parameter packs", arg);
4275 	  else
4276 	    error ("expansion pattern %qE contains no parameter packs", arg);
4277 	}
4278       return error_mark_node;
4279     }
4280   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
4281 
4282   PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
4283   if (ppd.found_extra_args_tree_p)
4284     /* If the pattern of this pack expansion contains a subtree that has
4285        the extra args mechanism for avoiding partial instantiation, then
4286        force this pack expansion to also use extra args.  Otherwise
4287        partial instantiation of this pack expansion may not lower the
4288        level of some parameter packs within the pattern, which would
4289        confuse tsubst_pack_expansion later (PR101764).  */
4290     PACK_EXPANSION_FORCE_EXTRA_ARGS_P (result) = true;
4291 
4292   return result;
4293 }
4294 
4295 /* Checks T for any "bare" parameter packs, which have not yet been
4296    expanded, and issues an error if any are found. This operation can
4297    only be done on full expressions or types (e.g., an expression
4298    statement, "if" condition, etc.), because we could have expressions like:
4299 
4300      foo(f(g(h(args)))...)
4301 
4302    where "args" is a parameter pack. check_for_bare_parameter_packs
4303    should not be called for the subexpressions args, h(args),
4304    g(h(args)), or f(g(h(args))), because we would produce erroneous
4305    error messages.
4306 
4307    Returns TRUE and emits an error if there were bare parameter packs,
4308    returns FALSE otherwise.  */
4309 bool
check_for_bare_parameter_packs(tree t,location_t loc)4310 check_for_bare_parameter_packs (tree t, location_t loc /* = UNKNOWN_LOCATION */)
4311 {
4312   tree parameter_packs = NULL_TREE;
4313   struct find_parameter_pack_data ppd;
4314 
4315   if (!processing_template_decl || !t || t == error_mark_node)
4316     return false;
4317 
4318   if (TREE_CODE (t) == TYPE_DECL)
4319     t = TREE_TYPE (t);
4320 
4321   ppd.parameter_packs = &parameter_packs;
4322   ppd.visited = new hash_set<tree>;
4323   ppd.type_pack_expansion_p = false;
4324   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4325   delete ppd.visited;
4326 
4327   if (!parameter_packs)
4328     return false;
4329 
4330   if (loc == UNKNOWN_LOCATION)
4331     loc = cp_expr_loc_or_input_loc (t);
4332 
4333   /* It's OK for a lambda to have an unexpanded parameter pack from the
4334      containing context, but do complain about unexpanded capture packs.  */
4335   tree lam = current_lambda_expr ();
4336   if (lam)
4337     lam = TREE_TYPE (lam);
4338 
4339   if (lam && lam != current_class_type)
4340     {
4341       /* We're in a lambda, but it isn't the innermost class.
4342 	 This should work, but currently doesn't.  */
4343       sorry_at (loc, "unexpanded parameter pack in local class in lambda");
4344       return true;
4345     }
4346 
4347   if (lam && CLASSTYPE_TEMPLATE_INFO (lam))
4348     for (; parameter_packs;
4349 	 parameter_packs = TREE_CHAIN (parameter_packs))
4350       {
4351 	tree pack = TREE_VALUE (parameter_packs);
4352 	if (is_capture_proxy (pack)
4353 	    || (TREE_CODE (pack) == PARM_DECL
4354 		&& DECL_CONTEXT (DECL_CONTEXT (pack)) == lam))
4355 	  break;
4356       }
4357 
4358   if (parameter_packs)
4359     {
4360       error_at (loc, "parameter packs not expanded with %<...%>:");
4361       while (parameter_packs)
4362         {
4363           tree pack = TREE_VALUE (parameter_packs);
4364           tree name = NULL_TREE;
4365 
4366           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
4367               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
4368             name = TYPE_NAME (pack);
4369           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
4370             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
4371 	  else if (TREE_CODE (pack) == CALL_EXPR)
4372 	    name = DECL_NAME (CALL_EXPR_FN (pack));
4373           else
4374             name = DECL_NAME (pack);
4375 
4376 	  if (name)
4377 	    inform (loc, "        %qD", name);
4378 	  else
4379 	    inform (loc, "        %s", "<anonymous>");
4380 
4381           parameter_packs = TREE_CHAIN (parameter_packs);
4382         }
4383 
4384       return true;
4385     }
4386 
4387   return false;
4388 }
4389 
4390 /* Expand any parameter packs that occur in the template arguments in
4391    ARGS.  */
4392 tree
expand_template_argument_pack(tree args)4393 expand_template_argument_pack (tree args)
4394 {
4395   if (args == error_mark_node)
4396     return error_mark_node;
4397 
4398   tree result_args = NULL_TREE;
4399   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
4400   int num_result_args = -1;
4401   int non_default_args_count = -1;
4402 
4403   /* First, determine if we need to expand anything, and the number of
4404      slots we'll need.  */
4405   for (in_arg = 0; in_arg < nargs; ++in_arg)
4406     {
4407       tree arg = TREE_VEC_ELT (args, in_arg);
4408       if (arg == NULL_TREE)
4409 	return args;
4410       if (ARGUMENT_PACK_P (arg))
4411         {
4412           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
4413           if (num_result_args < 0)
4414             num_result_args = in_arg + num_packed;
4415           else
4416             num_result_args += num_packed;
4417         }
4418       else
4419         {
4420           if (num_result_args >= 0)
4421             num_result_args++;
4422         }
4423     }
4424 
4425   /* If no expansion is necessary, we're done.  */
4426   if (num_result_args < 0)
4427     return args;
4428 
4429   /* Expand arguments.  */
4430   result_args = make_tree_vec (num_result_args);
4431   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
4432     non_default_args_count =
4433       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
4434   for (in_arg = 0; in_arg < nargs; ++in_arg)
4435     {
4436       tree arg = TREE_VEC_ELT (args, in_arg);
4437       if (ARGUMENT_PACK_P (arg))
4438         {
4439           tree packed = ARGUMENT_PACK_ARGS (arg);
4440           int i, num_packed = TREE_VEC_LENGTH (packed);
4441           for (i = 0; i < num_packed; ++i, ++out_arg)
4442             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
4443 	  if (non_default_args_count > 0)
4444 	    non_default_args_count += num_packed - 1;
4445         }
4446       else
4447         {
4448           TREE_VEC_ELT (result_args, out_arg) = arg;
4449           ++out_arg;
4450         }
4451     }
4452   if (non_default_args_count >= 0)
4453     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
4454   return result_args;
4455 }
4456 
4457 /* Checks if DECL shadows a template parameter.
4458 
4459    [temp.local]: A template-parameter shall not be redeclared within its
4460    scope (including nested scopes).
4461 
4462    Emits an error and returns TRUE if the DECL shadows a parameter,
4463    returns FALSE otherwise.  */
4464 
4465 bool
check_template_shadow(tree decl)4466 check_template_shadow (tree decl)
4467 {
4468   tree olddecl;
4469 
4470   /* If we're not in a template, we can't possibly shadow a template
4471      parameter.  */
4472   if (!current_template_parms)
4473     return true;
4474 
4475   /* Figure out what we're shadowing.  */
4476   decl = OVL_FIRST (decl);
4477   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
4478 
4479   /* If there's no previous binding for this name, we're not shadowing
4480      anything, let alone a template parameter.  */
4481   if (!olddecl)
4482     return true;
4483 
4484   /* If we're not shadowing a template parameter, we're done.  Note
4485      that OLDDECL might be an OVERLOAD (or perhaps even an
4486      ERROR_MARK), so we can't just blithely assume it to be a _DECL
4487      node.  */
4488   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
4489     return true;
4490 
4491   /* We check for decl != olddecl to avoid bogus errors for using a
4492      name inside a class.  We check TPFI to avoid duplicate errors for
4493      inline member templates.  */
4494   if (decl == olddecl
4495       || (DECL_TEMPLATE_PARM_P (decl)
4496 	  && TEMPLATE_PARMS_FOR_INLINE (current_template_parms)))
4497     return true;
4498 
4499   /* Don't complain about the injected class name, as we've already
4500      complained about the class itself.  */
4501   if (DECL_SELF_REFERENCE_P (decl))
4502     return false;
4503 
4504   if (DECL_TEMPLATE_PARM_P (decl))
4505     error ("declaration of template parameter %q+D shadows "
4506 	   "template parameter", decl);
4507   else
4508     error ("declaration of %q+#D shadows template parameter", decl);
4509   inform (DECL_SOURCE_LOCATION (olddecl),
4510 	  "template parameter %qD declared here", olddecl);
4511   return false;
4512 }
4513 
4514 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
4515    ORIG_LEVEL, DECL, and TYPE.  */
4516 
4517 static tree
build_template_parm_index(int index,int level,int orig_level,tree decl,tree type)4518 build_template_parm_index (int index,
4519 			   int level,
4520 			   int orig_level,
4521 			   tree decl,
4522 			   tree type)
4523 {
4524   tree t = make_node (TEMPLATE_PARM_INDEX);
4525   TEMPLATE_PARM_IDX (t) = index;
4526   TEMPLATE_PARM_LEVEL (t) = level;
4527   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
4528   TEMPLATE_PARM_DECL (t) = decl;
4529   TREE_TYPE (t) = type;
4530   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
4531   TREE_READONLY (t) = TREE_READONLY (decl);
4532 
4533   return t;
4534 }
4535 
4536 /* Find the canonical type parameter for the given template type
4537    parameter.  Returns the canonical type parameter, which may be TYPE
4538    if no such parameter existed.  */
4539 
4540 tree
canonical_type_parameter(tree type)4541 canonical_type_parameter (tree type)
4542 {
4543   int idx = TEMPLATE_TYPE_IDX (type);
4544 
4545   gcc_assert (TREE_CODE (type) != TEMPLATE_TEMPLATE_PARM);
4546 
4547   if (vec_safe_length (canonical_template_parms) <= (unsigned) idx)
4548     vec_safe_grow_cleared (canonical_template_parms, idx + 1, true);
4549 
4550   for (tree list = (*canonical_template_parms)[idx];
4551        list; list = TREE_CHAIN (list))
4552     if (comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
4553       return TREE_VALUE (list);
4554 
4555   (*canonical_template_parms)[idx]
4556     = tree_cons (NULL_TREE, type, (*canonical_template_parms)[idx]);
4557   return type;
4558 }
4559 
4560 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
4561    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
4562    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
4563    new one is created.  */
4564 
4565 static tree
reduce_template_parm_level(tree index,tree type,int levels,tree args,tsubst_flags_t complain)4566 reduce_template_parm_level (tree index, tree type, int levels, tree args,
4567 			    tsubst_flags_t complain)
4568 {
4569   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
4570       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
4571 	  != TEMPLATE_PARM_LEVEL (index) - levels)
4572       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
4573     {
4574       tree orig_decl = TEMPLATE_PARM_DECL (index);
4575 
4576       tree decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
4577 			      TREE_CODE (orig_decl), DECL_NAME (orig_decl),
4578 			      type);
4579       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
4580       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
4581       DECL_VIRTUAL_P (decl) = DECL_VIRTUAL_P (orig_decl);
4582       DECL_ARTIFICIAL (decl) = 1;
4583       SET_DECL_TEMPLATE_PARM_P (decl);
4584 
4585       tree tpi = build_template_parm_index (TEMPLATE_PARM_IDX (index),
4586 					    TEMPLATE_PARM_LEVEL (index) - levels,
4587 					    TEMPLATE_PARM_ORIG_LEVEL (index),
4588 					    decl, type);
4589       TEMPLATE_PARM_DESCENDANTS (index) = tpi;
4590       TEMPLATE_PARM_PARAMETER_PACK (tpi)
4591 	= TEMPLATE_PARM_PARAMETER_PACK (index);
4592 
4593       /* Template template parameters need this.  */
4594       tree inner = decl;
4595       if (TREE_CODE (decl) == TEMPLATE_DECL)
4596 	{
4597 	  inner = build_decl (DECL_SOURCE_LOCATION (decl),
4598 			      TYPE_DECL, DECL_NAME (decl), type);
4599 	  DECL_TEMPLATE_RESULT (decl) = inner;
4600 	  DECL_ARTIFICIAL (inner) = true;
4601 	  DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
4602 	    (DECL_TEMPLATE_PARMS (orig_decl), args, complain);
4603 	}
4604 
4605       /* Attach the TPI to the decl.  */
4606       if (TREE_CODE (inner) == TYPE_DECL)
4607 	TEMPLATE_TYPE_PARM_INDEX (type) = tpi;
4608       else
4609 	DECL_INITIAL (decl) = tpi;
4610     }
4611 
4612   return TEMPLATE_PARM_DESCENDANTS (index);
4613 }
4614 
4615 /* Process information from new template parameter PARM and append it
4616    to the LIST being built.  This new parameter is a non-type
4617    parameter iff IS_NON_TYPE is true. This new parameter is a
4618    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
4619    is in PARM_LOC.  */
4620 
4621 tree
process_template_parm(tree list,location_t parm_loc,tree parm,bool is_non_type,bool is_parameter_pack)4622 process_template_parm (tree list, location_t parm_loc, tree parm,
4623 		       bool is_non_type, bool is_parameter_pack)
4624 {
4625   gcc_assert (TREE_CODE (parm) == TREE_LIST);
4626   tree prev = NULL_TREE;
4627   int idx = 0;
4628 
4629   if (list)
4630     {
4631       prev = tree_last (list);
4632 
4633       tree p = TREE_VALUE (prev);
4634       if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
4635 	idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
4636       else if (TREE_CODE (p) == PARM_DECL)
4637 	idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
4638 
4639       ++idx;
4640     }
4641 
4642   tree decl = NULL_TREE;
4643   tree defval = TREE_PURPOSE (parm);
4644   tree constr = TREE_TYPE (parm);
4645 
4646   if (is_non_type)
4647     {
4648       parm = TREE_VALUE (parm);
4649 
4650       SET_DECL_TEMPLATE_PARM_P (parm);
4651 
4652       if (TREE_TYPE (parm) != error_mark_node)
4653 	{
4654 	  /* [temp.param]
4655 
4656 	     The top-level cv-qualifiers on the template-parameter are
4657 	     ignored when determining its type.  */
4658 	  TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
4659 	  if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
4660 	    TREE_TYPE (parm) = error_mark_node;
4661 	  else if (uses_parameter_packs (TREE_TYPE (parm))
4662 		   && !is_parameter_pack
4663 		   /* If we're in a nested template parameter list, the template
4664 		      template parameter could be a parameter pack.  */
4665 		   && processing_template_parmlist == 1)
4666 	    {
4667 	      /* This template parameter is not a parameter pack, but it
4668 		 should be. Complain about "bare" parameter packs.  */
4669 	      check_for_bare_parameter_packs (TREE_TYPE (parm));
4670 
4671 	      /* Recover by calling this a parameter pack.  */
4672 	      is_parameter_pack = true;
4673 	    }
4674 	}
4675 
4676       /* A template parameter is not modifiable.  */
4677       TREE_CONSTANT (parm) = 1;
4678       TREE_READONLY (parm) = 1;
4679       decl = build_decl (parm_loc,
4680 			 CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
4681       TREE_CONSTANT (decl) = 1;
4682       TREE_READONLY (decl) = 1;
4683       DECL_INITIAL (parm) = DECL_INITIAL (decl)
4684 	= build_template_parm_index (idx, current_template_depth,
4685 				     current_template_depth,
4686 				     decl, TREE_TYPE (parm));
4687 
4688       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4689 	= is_parameter_pack;
4690     }
4691   else
4692     {
4693       tree t;
4694       parm = TREE_VALUE (TREE_VALUE (parm));
4695 
4696       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
4697 	{
4698 	  t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
4699 	  /* This is for distinguishing between real templates and template
4700 	     template parameters */
4701 	  TREE_TYPE (parm) = t;
4702 
4703 	  /* any_template_parm_r expects to be able to get the targs of a
4704 	     DECL_TEMPLATE_RESULT.  */
4705 	  tree result = DECL_TEMPLATE_RESULT (parm);
4706 	  TREE_TYPE (result) = t;
4707 	  tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (parm));
4708 	  tree tinfo = build_template_info (parm, args);
4709 	  retrofit_lang_decl (result);
4710 	  DECL_TEMPLATE_INFO (result) = tinfo;
4711 
4712 	  decl = parm;
4713 	}
4714       else
4715 	{
4716 	  t = cxx_make_type (TEMPLATE_TYPE_PARM);
4717 	  /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
4718 	  decl = build_decl (parm_loc,
4719 			     TYPE_DECL, parm, t);
4720 	}
4721 
4722       TYPE_NAME (t) = decl;
4723       TYPE_STUB_DECL (t) = decl;
4724       parm = decl;
4725       TEMPLATE_TYPE_PARM_INDEX (t)
4726 	= build_template_parm_index (idx, current_template_depth,
4727 				     current_template_depth,
4728 				     decl, TREE_TYPE (parm));
4729       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
4730       if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
4731 	SET_TYPE_STRUCTURAL_EQUALITY (t);
4732       else
4733 	TYPE_CANONICAL (t) = canonical_type_parameter (t);
4734     }
4735   DECL_ARTIFICIAL (decl) = 1;
4736   SET_DECL_TEMPLATE_PARM_P (decl);
4737 
4738   /* Build requirements for the type/template parameter.
4739      This must be done after SET_DECL_TEMPLATE_PARM_P or
4740      process_template_parm could fail. */
4741   tree reqs = finish_shorthand_constraint (parm, constr);
4742 
4743   decl = pushdecl (decl);
4744   if (!is_non_type)
4745     parm = decl;
4746 
4747   /* Build the parameter node linking the parameter declaration,
4748      its default argument (if any), and its constraints (if any). */
4749   parm = build_tree_list (defval, parm);
4750   TEMPLATE_PARM_CONSTRAINTS (parm) = reqs;
4751 
4752   if (prev)
4753     TREE_CHAIN (prev) = parm;
4754   else
4755     list = parm;
4756 
4757   return list;
4758 }
4759 
4760 /* The end of a template parameter list has been reached.  Process the
4761    tree list into a parameter vector, converting each parameter into a more
4762    useful form.	 Type parameters are saved as IDENTIFIER_NODEs, and others
4763    as PARM_DECLs.  */
4764 
4765 tree
end_template_parm_list(tree parms)4766 end_template_parm_list (tree parms)
4767 {
4768   tree saved_parmlist = make_tree_vec (list_length (parms));
4769 
4770   /* Pop the dummy parameter level and add the real one.  We do not
4771      morph the dummy parameter in place, as it might have been
4772      captured by a (nested) template-template-parm.  */
4773   current_template_parms = TREE_CHAIN (current_template_parms);
4774 
4775   current_template_parms
4776     = tree_cons (size_int (current_template_depth + 1),
4777 		 saved_parmlist, current_template_parms);
4778 
4779   for (unsigned ix = 0; parms; ix++)
4780     {
4781       tree parm = parms;
4782       parms = TREE_CHAIN (parms);
4783       TREE_CHAIN (parm) = NULL_TREE;
4784 
4785       TREE_VEC_ELT (saved_parmlist, ix) = parm;
4786     }
4787 
4788   --processing_template_parmlist;
4789 
4790   return saved_parmlist;
4791 }
4792 
4793 // Explicitly indicate the end of the template parameter list. We assume
4794 // that the current template parameters have been constructed and/or
4795 // managed explicitly, as when creating new template template parameters
4796 // from a shorthand constraint.
4797 void
end_template_parm_list()4798 end_template_parm_list ()
4799 {
4800   --processing_template_parmlist;
4801 }
4802 
4803 /* end_template_decl is called after a template declaration is seen.  */
4804 
4805 void
end_template_decl(void)4806 end_template_decl (void)
4807 {
4808   reset_specialization ();
4809 
4810   if (! processing_template_decl)
4811     return;
4812 
4813   /* This matches the pushlevel in begin_template_parm_list.  */
4814   finish_scope ();
4815 
4816   --processing_template_decl;
4817   current_template_parms = TREE_CHAIN (current_template_parms);
4818 }
4819 
4820 /* Takes a TEMPLATE_PARM_P or DECL_TEMPLATE_PARM_P node or a TREE_LIST
4821    thereof, and converts it into an argument suitable to be passed to
4822    the type substitution functions.  Note that if the TREE_LIST contains
4823    an error_mark node, the returned argument is error_mark_node.  */
4824 
4825 tree
template_parm_to_arg(tree t)4826 template_parm_to_arg (tree t)
4827 {
4828   if (!t)
4829     return NULL_TREE;
4830 
4831   if (TREE_CODE (t) == TREE_LIST)
4832     t = TREE_VALUE (t);
4833 
4834   if (error_operand_p (t))
4835     return error_mark_node;
4836 
4837   if (DECL_P (t) && DECL_TEMPLATE_PARM_P (t))
4838     {
4839       if (TREE_CODE (t) == TYPE_DECL
4840 	  || TREE_CODE (t) == TEMPLATE_DECL)
4841 	t = TREE_TYPE (t);
4842       else
4843 	t = DECL_INITIAL (t);
4844     }
4845 
4846   gcc_assert (TEMPLATE_PARM_P (t));
4847 
4848   if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
4849       || TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
4850     {
4851       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
4852 	{
4853 	  /* Turn this argument into a TYPE_ARGUMENT_PACK
4854 	     with a single element, which expands T.  */
4855 	  tree vec = make_tree_vec (1);
4856 	  if (CHECKING_P)
4857 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4858 
4859 	  TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4860 
4861 	  t = cxx_make_type (TYPE_ARGUMENT_PACK);
4862 	  SET_ARGUMENT_PACK_ARGS (t, vec);
4863 	}
4864     }
4865   else
4866     {
4867       if (TEMPLATE_PARM_PARAMETER_PACK (t))
4868 	{
4869 	  /* Turn this argument into a NONTYPE_ARGUMENT_PACK
4870 	     with a single element, which expands T.  */
4871 	  tree vec = make_tree_vec (1);
4872 	  if (CHECKING_P)
4873 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4874 
4875 	  t = convert_from_reference (t);
4876 	  TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4877 
4878 	  t  = make_node (NONTYPE_ARGUMENT_PACK);
4879 	  SET_ARGUMENT_PACK_ARGS (t, vec);
4880 	}
4881       else
4882 	t = convert_from_reference (t);
4883     }
4884   return t;
4885 }
4886 
4887 /* Given a single level of template parameters (a TREE_VEC), return it
4888    as a set of template arguments.  */
4889 
4890 tree
template_parms_level_to_args(tree parms)4891 template_parms_level_to_args (tree parms)
4892 {
4893   tree a = copy_node (parms);
4894   TREE_TYPE (a) = NULL_TREE;
4895   for (int i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4896     TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4897 
4898   if (CHECKING_P)
4899     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4900 
4901   return a;
4902 }
4903 
4904 /* Given a set of template parameters, return them as a set of template
4905    arguments.  The template parameters are represented as a TREE_VEC, in
4906    the form documented in cp-tree.h for template arguments.  */
4907 
4908 tree
template_parms_to_args(tree parms)4909 template_parms_to_args (tree parms)
4910 {
4911   tree header;
4912   tree args = NULL_TREE;
4913   int length = TMPL_PARMS_DEPTH (parms);
4914   int l = length;
4915 
4916   /* If there is only one level of template parameters, we do not
4917      create a TREE_VEC of TREE_VECs.  Instead, we return a single
4918      TREE_VEC containing the arguments.  */
4919   if (length > 1)
4920     args = make_tree_vec (length);
4921 
4922   for (header = parms; header; header = TREE_CHAIN (header))
4923     {
4924       tree a = template_parms_level_to_args (TREE_VALUE (header));
4925 
4926       if (length > 1)
4927 	TREE_VEC_ELT (args, --l) = a;
4928       else
4929 	args = a;
4930     }
4931 
4932   return args;
4933 }
4934 
4935 /* Within the declaration of a template, return the currently active
4936    template parameters as an argument TREE_VEC.  */
4937 
4938 static tree
current_template_args(void)4939 current_template_args (void)
4940 {
4941   return template_parms_to_args (current_template_parms);
4942 }
4943 
4944 /* Return the fully generic arguments for of TMPL, i.e. what
4945    current_template_args would be while parsing it.  */
4946 
4947 tree
generic_targs_for(tree tmpl)4948 generic_targs_for (tree tmpl)
4949 {
4950   if (tmpl == NULL_TREE)
4951     return NULL_TREE;
4952   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
4953       || DECL_TEMPLATE_SPECIALIZATION (tmpl))
4954     /* DECL_TEMPLATE_RESULT doesn't have the arguments we want.  For a template
4955        template parameter, it has no TEMPLATE_INFO; for a partial
4956        specialization, it has the arguments for the primary template, and we
4957        want the arguments for the partial specialization.  */;
4958   else if (tree result = DECL_TEMPLATE_RESULT (tmpl))
4959     if (tree ti = get_template_info (result))
4960       return TI_ARGS (ti);
4961   return template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl));
4962 }
4963 
4964 /* Return the template arguments corresponding to the template parameters of
4965    TMPL's enclosing scope.  When TMPL is a member of a partial specialization,
4966    this returns the arguments for the partial specialization as opposed to those
4967    for the primary template, which is the main difference between this function
4968    and simply using e.g. the TYPE_TI_ARGS of TMPL's DECL_CONTEXT.  */
4969 
4970 tree
outer_template_args(tree tmpl)4971 outer_template_args (tree tmpl)
4972 {
4973   tree ti = get_template_info (DECL_TEMPLATE_RESULT (tmpl));
4974   if (!ti)
4975     return NULL_TREE;
4976   tree args = TI_ARGS (ti);
4977   if (!PRIMARY_TEMPLATE_P (tmpl))
4978     return args;
4979   if (TMPL_ARGS_DEPTH (args) == 1)
4980     return NULL_TREE;
4981   args = copy_node (args);
4982   --TREE_VEC_LENGTH (args);
4983   return args;
4984 }
4985 
4986 /* Update the declared TYPE by doing any lookups which were thought to be
4987    dependent, but are not now that we know the SCOPE of the declarator.  */
4988 
4989 tree
maybe_update_decl_type(tree orig_type,tree scope)4990 maybe_update_decl_type (tree orig_type, tree scope)
4991 {
4992   tree type = orig_type;
4993 
4994   if (type == NULL_TREE)
4995     return type;
4996 
4997   if (TREE_CODE (orig_type) == TYPE_DECL)
4998     type = TREE_TYPE (type);
4999 
5000   if (scope && TYPE_P (scope) && dependent_type_p (scope)
5001       && dependent_type_p (type)
5002       /* Don't bother building up the args in this case.  */
5003       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
5004     {
5005       /* tsubst in the args corresponding to the template parameters,
5006 	 including auto if present.  Most things will be unchanged, but
5007 	 make_typename_type and tsubst_qualified_id will resolve
5008 	 TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
5009       tree args = current_template_args ();
5010       tree auto_node = type_uses_auto (type);
5011       tree pushed;
5012       if (auto_node)
5013 	{
5014 	  tree auto_vec = make_tree_vec (1);
5015 	  TREE_VEC_ELT (auto_vec, 0) = auto_node;
5016 	  args = add_to_template_args (args, auto_vec);
5017 	}
5018       pushed = push_scope (scope);
5019       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
5020       if (pushed)
5021 	pop_scope (scope);
5022     }
5023 
5024   if (type == error_mark_node)
5025     return orig_type;
5026 
5027   if (TREE_CODE (orig_type) == TYPE_DECL)
5028     {
5029       if (same_type_p (type, TREE_TYPE (orig_type)))
5030 	type = orig_type;
5031       else
5032 	type = TYPE_NAME (type);
5033     }
5034   return type;
5035 }
5036 
5037 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
5038    template PARMS and constraints, CONSTR.  If MEMBER_TEMPLATE_P is true,
5039    the new  template is a member template. */
5040 
5041 static tree
build_template_decl(tree decl,tree parms,bool member_template_p)5042 build_template_decl (tree decl, tree parms, bool member_template_p)
5043 {
5044   gcc_checking_assert (TREE_CODE (decl) != TEMPLATE_DECL);
5045 
5046   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
5047   SET_DECL_LANGUAGE (tmpl, DECL_LANGUAGE (decl));
5048   DECL_TEMPLATE_PARMS (tmpl) = parms;
5049   DECL_TEMPLATE_RESULT (tmpl) = decl;
5050   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
5051   TREE_TYPE (tmpl) = TREE_TYPE (decl);
5052   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
5053   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
5054 
5055   /* Propagate module information from the decl.  */
5056   DECL_MODULE_EXPORT_P (tmpl) = DECL_MODULE_EXPORT_P (decl);
5057 
5058   return tmpl;
5059 }
5060 
5061 struct template_parm_data
5062 {
5063   /* The level of the template parameters we are currently
5064      processing.  */
5065   int level;
5066 
5067   /* The index of the specialization argument we are currently
5068      processing.  */
5069   int current_arg;
5070 
5071   /* An array whose size is the number of template parameters.  The
5072      elements are nonzero if the parameter has been used in any one
5073      of the arguments processed so far.  */
5074   int* parms;
5075 
5076   /* An array whose size is the number of template arguments.  The
5077      elements are nonzero if the argument makes use of template
5078      parameters of this level.  */
5079   int* arg_uses_template_parms;
5080 };
5081 
5082 /* Subroutine of push_template_decl used to see if each template
5083    parameter in a partial specialization is used in the explicit
5084    argument list.  If T is of the LEVEL given in DATA (which is
5085    treated as a template_parm_data*), then DATA->PARMS is marked
5086    appropriately.  */
5087 
5088 static int
mark_template_parm(tree t,void * data)5089 mark_template_parm (tree t, void* data)
5090 {
5091   int level;
5092   int idx;
5093   struct template_parm_data* tpd = (struct template_parm_data*) data;
5094 
5095   template_parm_level_and_index (t, &level, &idx);
5096 
5097   if (level == tpd->level)
5098     {
5099       tpd->parms[idx] = 1;
5100       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
5101     }
5102 
5103   /* In C++17 the type of a non-type argument is a deduced context.  */
5104   if (cxx_dialect >= cxx17
5105       && TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5106     for_each_template_parm (TREE_TYPE (t),
5107 			    &mark_template_parm,
5108 			    data,
5109 			    NULL,
5110 			    /*include_nondeduced_p=*/false);
5111 
5112   /* Return zero so that for_each_template_parm will continue the
5113      traversal of the tree; we want to mark *every* template parm.  */
5114   return 0;
5115 }
5116 
5117 /* Process the partial specialization DECL.  */
5118 
5119 static tree
process_partial_specialization(tree decl)5120 process_partial_specialization (tree decl)
5121 {
5122   tree type = TREE_TYPE (decl);
5123   tree tinfo = get_template_info (decl);
5124   tree maintmpl = TI_TEMPLATE (tinfo);
5125   tree specargs = TI_ARGS (tinfo);
5126   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
5127   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
5128   tree inner_parms;
5129   tree inst;
5130   int nargs = TREE_VEC_LENGTH (inner_args);
5131   int ntparms;
5132   int  i;
5133   bool did_error_intro = false;
5134   struct template_parm_data tpd;
5135   struct template_parm_data tpd2;
5136 
5137   gcc_assert (current_template_parms);
5138 
5139   /* A concept cannot be specialized.  */
5140   if (flag_concepts && variable_concept_p (maintmpl))
5141     {
5142       error ("specialization of variable concept %q#D", maintmpl);
5143       return error_mark_node;
5144     }
5145 
5146   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
5147   ntparms = TREE_VEC_LENGTH (inner_parms);
5148 
5149   /* We check that each of the template parameters given in the
5150      partial specialization is used in the argument list to the
5151      specialization.  For example:
5152 
5153        template <class T> struct S;
5154        template <class T> struct S<T*>;
5155 
5156      The second declaration is OK because `T*' uses the template
5157      parameter T, whereas
5158 
5159        template <class T> struct S<int>;
5160 
5161      is no good.  Even trickier is:
5162 
5163        template <class T>
5164        struct S1
5165        {
5166 	  template <class U>
5167 	  struct S2;
5168 	  template <class U>
5169 	  struct S2<T>;
5170        };
5171 
5172      The S2<T> declaration is actually invalid; it is a
5173      full-specialization.  Of course,
5174 
5175 	  template <class U>
5176 	  struct S2<T (*)(U)>;
5177 
5178      or some such would have been OK.  */
5179   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
5180   tpd.parms = XALLOCAVEC (int, ntparms);
5181   memset (tpd.parms, 0, sizeof (int) * ntparms);
5182 
5183   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5184   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
5185   for (i = 0; i < nargs; ++i)
5186     {
5187       tpd.current_arg = i;
5188       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
5189 			      &mark_template_parm,
5190 			      &tpd,
5191 			      NULL,
5192 			      /*include_nondeduced_p=*/false);
5193     }
5194   for (i = 0; i < ntparms; ++i)
5195     if (tpd.parms[i] == 0)
5196       {
5197 	/* One of the template parms was not used in a deduced context in the
5198 	   specialization.  */
5199 	if (!did_error_intro)
5200 	  {
5201 	    error ("template parameters not deducible in "
5202 		   "partial specialization:");
5203 	    did_error_intro = true;
5204 	  }
5205 
5206 	inform (input_location, "        %qD",
5207 		TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
5208       }
5209 
5210   if (did_error_intro)
5211     return error_mark_node;
5212 
5213   /* [temp.class.spec]
5214 
5215      The argument list of the specialization shall not be identical to
5216      the implicit argument list of the primary template.  */
5217   tree main_args
5218     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
5219   if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args))
5220       && (!flag_concepts
5221 	  || !strictly_subsumes (current_template_constraints (), maintmpl)))
5222     {
5223       if (!flag_concepts)
5224         error ("partial specialization %q+D does not specialize "
5225 	       "any template arguments; to define the primary template, "
5226 	       "remove the template argument list", decl);
5227       else
5228         error ("partial specialization %q+D does not specialize any "
5229 	       "template arguments and is not more constrained than "
5230 	       "the primary template; to define the primary template, "
5231 	       "remove the template argument list", decl);
5232       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5233     }
5234 
5235   /* A partial specialization that replaces multiple parameters of the
5236      primary template with a pack expansion is less specialized for those
5237      parameters.  */
5238   if (nargs < DECL_NTPARMS (maintmpl))
5239     {
5240       error ("partial specialization is not more specialized than the "
5241 	     "primary template because it replaces multiple parameters "
5242 	     "with a pack expansion");
5243       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5244       /* Avoid crash in process_partial_specialization.  */
5245       return decl;
5246     }
5247 
5248   else if (nargs > DECL_NTPARMS (maintmpl))
5249     {
5250       error ("too many arguments for partial specialization %qT", type);
5251       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5252       /* Avoid crash below.  */
5253       return decl;
5254     }
5255 
5256   /* If we aren't in a dependent class, we can actually try deduction.  */
5257   else if (tpd.level == 1
5258 	   /* FIXME we should be able to handle a partial specialization of a
5259 	      partial instantiation, but currently we can't (c++/41727).  */
5260 	   && TMPL_ARGS_DEPTH (specargs) == 1
5261 	   && !get_partial_spec_bindings (maintmpl, maintmpl, specargs))
5262     {
5263       auto_diagnostic_group d;
5264       if (pedwarn (input_location, 0,
5265 		   "partial specialization %qD is not more specialized than",
5266 		   decl))
5267 	inform (DECL_SOURCE_LOCATION (maintmpl), "primary template %qD",
5268 		maintmpl);
5269     }
5270 
5271   /* [temp.spec.partial]
5272 
5273      The type of a template parameter corresponding to a specialized
5274      non-type argument shall not be dependent on a parameter of the
5275      specialization.
5276 
5277      Also, we verify that pack expansions only occur at the
5278      end of the argument list.  */
5279   tpd2.parms = 0;
5280   for (i = 0; i < nargs; ++i)
5281     {
5282       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
5283       tree arg = TREE_VEC_ELT (inner_args, i);
5284       tree packed_args = NULL_TREE;
5285       int j, len = 1;
5286 
5287       if (ARGUMENT_PACK_P (arg))
5288         {
5289           /* Extract the arguments from the argument pack. We'll be
5290              iterating over these in the following loop.  */
5291           packed_args = ARGUMENT_PACK_ARGS (arg);
5292           len = TREE_VEC_LENGTH (packed_args);
5293         }
5294 
5295       for (j = 0; j < len; j++)
5296         {
5297           if (packed_args)
5298             /* Get the Jth argument in the parameter pack.  */
5299             arg = TREE_VEC_ELT (packed_args, j);
5300 
5301           if (PACK_EXPANSION_P (arg))
5302             {
5303               /* Pack expansions must come at the end of the
5304                  argument list.  */
5305               if ((packed_args && j < len - 1)
5306                   || (!packed_args && i < nargs - 1))
5307                 {
5308                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5309                     error ("parameter pack argument %qE must be at the "
5310 			   "end of the template argument list", arg);
5311                   else
5312                     error ("parameter pack argument %qT must be at the "
5313 			   "end of the template argument list", arg);
5314                 }
5315             }
5316 
5317           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5318             /* We only care about the pattern.  */
5319             arg = PACK_EXPANSION_PATTERN (arg);
5320 
5321           if (/* These first two lines are the `non-type' bit.  */
5322               !TYPE_P (arg)
5323               && TREE_CODE (arg) != TEMPLATE_DECL
5324               /* This next two lines are the `argument expression is not just a
5325                  simple identifier' condition and also the `specialized
5326                  non-type argument' bit.  */
5327               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
5328 	      && !((REFERENCE_REF_P (arg)
5329 		    || TREE_CODE (arg) == VIEW_CONVERT_EXPR)
5330 		   && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
5331             {
5332 	      /* Look at the corresponding template parameter,
5333 		 marking which template parameters its type depends
5334 		 upon.  */
5335 	      tree type = TREE_TYPE (parm);
5336 
5337 	      if (!tpd2.parms)
5338 		{
5339 		  /* We haven't yet initialized TPD2.  Do so now.  */
5340 		  tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5341 		  /* The number of parameters here is the number in the
5342 		     main template, which, as checked in the assertion
5343 		     above, is NARGS.  */
5344 		  tpd2.parms = XALLOCAVEC (int, nargs);
5345 		  tpd2.level =
5346 		    TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
5347 		}
5348 
5349 	      /* Mark the template parameters.  But this time, we're
5350 		 looking for the template parameters of the main
5351 		 template, not in the specialization.  */
5352 	      tpd2.current_arg = i;
5353 	      tpd2.arg_uses_template_parms[i] = 0;
5354 	      memset (tpd2.parms, 0, sizeof (int) * nargs);
5355 	      for_each_template_parm (type,
5356 				      &mark_template_parm,
5357 				      &tpd2,
5358 				      NULL,
5359 				      /*include_nondeduced_p=*/false);
5360 
5361 	      if (tpd2.arg_uses_template_parms [i])
5362 		{
5363 		  /* The type depended on some template parameters.
5364 		     If they are fully specialized in the
5365 		     specialization, that's OK.  */
5366 		  int j;
5367 		  int count = 0;
5368 		  for (j = 0; j < nargs; ++j)
5369 		    if (tpd2.parms[j] != 0
5370 			&& tpd.arg_uses_template_parms [j])
5371 		      ++count;
5372 		  if (count != 0)
5373 		    error_n (input_location, count,
5374 			     "type %qT of template argument %qE depends "
5375 			     "on a template parameter",
5376 			     "type %qT of template argument %qE depends "
5377 			     "on template parameters",
5378 			     type,
5379 			     arg);
5380 		}
5381             }
5382         }
5383     }
5384 
5385   /* We should only get here once.  */
5386   if (TREE_CODE (decl) == TYPE_DECL)
5387     gcc_assert (!COMPLETE_TYPE_P (type));
5388 
5389   // Build the template decl.
5390   tree tmpl = build_template_decl (decl, current_template_parms,
5391 				   DECL_MEMBER_TEMPLATE_P (maintmpl));
5392   SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5393   DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
5394   DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
5395 
5396   /* Give template template parms a DECL_CONTEXT of the template
5397      for which they are a parameter.  */
5398   for (i = 0; i < ntparms; ++i)
5399     {
5400       tree parm = TREE_VALUE (TREE_VEC_ELT (inner_parms, i));
5401       if (TREE_CODE (parm) == TEMPLATE_DECL)
5402 	DECL_CONTEXT (parm) = tmpl;
5403     }
5404 
5405   if (VAR_P (decl))
5406     /* We didn't register this in check_explicit_specialization so we could
5407        wait until the constraints were set.  */
5408     decl = register_specialization (decl, maintmpl, specargs, false, 0);
5409   else
5410     associate_classtype_constraints (type);
5411 
5412   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
5413     = tree_cons (specargs, tmpl,
5414                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
5415   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
5416 
5417   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
5418        inst = TREE_CHAIN (inst))
5419     {
5420       tree instance = TREE_VALUE (inst);
5421       if (TYPE_P (instance)
5422 	  ? (COMPLETE_TYPE_P (instance)
5423 	     && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
5424 	  : DECL_TEMPLATE_INSTANTIATION (instance))
5425 	{
5426 	  tree spec = most_specialized_partial_spec (instance, tf_none);
5427 	  tree inst_decl = (DECL_P (instance)
5428 			    ? instance : TYPE_NAME (instance));
5429 	  if (!spec)
5430 	    /* OK */;
5431 	  else if (spec == error_mark_node)
5432 	    permerror (input_location,
5433 		       "declaration of %qD ambiguates earlier template "
5434 		       "instantiation for %qD", decl, inst_decl);
5435 	  else if (TREE_VALUE (spec) == tmpl)
5436 	    permerror (input_location,
5437 		       "partial specialization of %qD after instantiation "
5438 		       "of %qD", decl, inst_decl);
5439 	}
5440     }
5441 
5442   return decl;
5443 }
5444 
5445 /* PARM is a template parameter of some form; return the corresponding
5446    TEMPLATE_PARM_INDEX.  */
5447 
5448 static tree
get_template_parm_index(tree parm)5449 get_template_parm_index (tree parm)
5450 {
5451   if (TREE_CODE (parm) == PARM_DECL
5452       || TREE_CODE (parm) == CONST_DECL)
5453     parm = DECL_INITIAL (parm);
5454   else if (TREE_CODE (parm) == TYPE_DECL
5455 	   || TREE_CODE (parm) == TEMPLATE_DECL)
5456     parm = TREE_TYPE (parm);
5457   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
5458       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM
5459       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
5460     parm = TEMPLATE_TYPE_PARM_INDEX (parm);
5461   gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
5462   return parm;
5463 }
5464 
5465 /* Subroutine of fixed_parameter_pack_p below.  Look for any template
5466    parameter packs used by the template parameter PARM.  */
5467 
5468 static void
fixed_parameter_pack_p_1(tree parm,struct find_parameter_pack_data * ppd)5469 fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
5470 {
5471   /* A type parm can't refer to another parm.  */
5472   if (TREE_CODE (parm) == TYPE_DECL || parm == error_mark_node)
5473     return;
5474   else if (TREE_CODE (parm) == PARM_DECL)
5475     {
5476       cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
5477 		    ppd, ppd->visited);
5478       return;
5479     }
5480 
5481   gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
5482 
5483   tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
5484   for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
5485     {
5486       tree p = TREE_VALUE (TREE_VEC_ELT (vec, i));
5487       if (template_parameter_pack_p (p))
5488 	/* Any packs in the type are expanded by this parameter.  */;
5489       else
5490 	fixed_parameter_pack_p_1 (p, ppd);
5491     }
5492 }
5493 
5494 /* PARM is a template parameter pack.  Return any parameter packs used in
5495    its type or the type of any of its template parameters.  If there are
5496    any such packs, it will be instantiated into a fixed template parameter
5497    list by partial instantiation rather than be fully deduced.  */
5498 
5499 tree
fixed_parameter_pack_p(tree parm)5500 fixed_parameter_pack_p (tree parm)
5501 {
5502   /* This can only be true in a member template.  */
5503   if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
5504     return NULL_TREE;
5505   /* This can only be true for a parameter pack.  */
5506   if (!template_parameter_pack_p (parm))
5507     return NULL_TREE;
5508   /* A type parm can't refer to another parm.  */
5509   if (TREE_CODE (parm) == TYPE_DECL)
5510     return NULL_TREE;
5511 
5512   tree parameter_packs = NULL_TREE;
5513   struct find_parameter_pack_data ppd;
5514   ppd.parameter_packs = &parameter_packs;
5515   ppd.visited = new hash_set<tree>;
5516   ppd.type_pack_expansion_p = false;
5517 
5518   fixed_parameter_pack_p_1 (parm, &ppd);
5519 
5520   delete ppd.visited;
5521   return parameter_packs;
5522 }
5523 
5524 /* Check that a template declaration's use of default arguments and
5525    parameter packs is not invalid.  Here, PARMS are the template
5526    parameters.  IS_PRIMARY is true if DECL is the thing declared by
5527    a primary template.  IS_PARTIAL is true if DECL is a partial
5528    specialization.
5529 
5530    IS_FRIEND_DECL is nonzero if DECL is either a non-defining friend
5531    function template declaration or a friend class template
5532    declaration.  In the function case, 1 indicates a declaration, 2
5533    indicates a redeclaration.  When IS_FRIEND_DECL=2, no errors are
5534    emitted for extraneous default arguments.
5535 
5536    Returns TRUE if there were no errors found, FALSE otherwise. */
5537 
5538 bool
check_default_tmpl_args(tree decl,tree parms,bool is_primary,bool is_partial,int is_friend_decl)5539 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
5540                          bool is_partial, int is_friend_decl)
5541 {
5542   const char *msg;
5543   int last_level_to_check;
5544   tree parm_level;
5545   bool no_errors = true;
5546 
5547   /* [temp.param]
5548 
5549      A default template-argument shall not be specified in a
5550      function template declaration or a function template definition, nor
5551      in the template-parameter-list of the definition of a member of a
5552      class template.  */
5553 
5554   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
5555       || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_DECL_P (decl)))
5556     /* You can't have a function template declaration in a local
5557        scope, nor you can you define a member of a class template in a
5558        local scope.  */
5559     return true;
5560 
5561   if ((TREE_CODE (decl) == TYPE_DECL
5562        && TREE_TYPE (decl)
5563        && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5564       || (TREE_CODE (decl) == FUNCTION_DECL
5565 	  && LAMBDA_FUNCTION_P (decl)))
5566     /* A lambda doesn't have an explicit declaration; don't complain
5567        about the parms of the enclosing class.  */
5568     return true;
5569 
5570   if (current_class_type
5571       && !TYPE_BEING_DEFINED (current_class_type)
5572       && DECL_LANG_SPECIFIC (decl)
5573       && DECL_DECLARES_FUNCTION_P (decl)
5574       /* If this is either a friend defined in the scope of the class
5575 	 or a member function.  */
5576       && (DECL_FUNCTION_MEMBER_P (decl)
5577 	  ? same_type_p (DECL_CONTEXT (decl), current_class_type)
5578 	  : DECL_FRIEND_CONTEXT (decl)
5579 	  ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
5580 	  : false)
5581       /* And, if it was a member function, it really was defined in
5582 	 the scope of the class.  */
5583       && (!DECL_FUNCTION_MEMBER_P (decl)
5584 	  || DECL_INITIALIZED_IN_CLASS_P (decl)))
5585     /* We already checked these parameters when the template was
5586        declared, so there's no need to do it again now.  This function
5587        was defined in class scope, but we're processing its body now
5588        that the class is complete.  */
5589     return true;
5590 
5591   /* Core issue 226 (C++0x only): the following only applies to class
5592      templates.  */
5593   if (is_primary
5594       && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
5595     {
5596       /* [temp.param]
5597 
5598          If a template-parameter has a default template-argument, all
5599          subsequent template-parameters shall have a default
5600          template-argument supplied.  */
5601       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
5602         {
5603           tree inner_parms = TREE_VALUE (parm_level);
5604           int ntparms = TREE_VEC_LENGTH (inner_parms);
5605           int seen_def_arg_p = 0;
5606           int i;
5607 
5608           for (i = 0; i < ntparms; ++i)
5609             {
5610               tree parm = TREE_VEC_ELT (inner_parms, i);
5611 
5612               if (parm == error_mark_node)
5613                 continue;
5614 
5615               if (TREE_PURPOSE (parm))
5616                 seen_def_arg_p = 1;
5617               else if (seen_def_arg_p
5618 		       && !template_parameter_pack_p (TREE_VALUE (parm)))
5619                 {
5620                   error ("no default argument for %qD", TREE_VALUE (parm));
5621                   /* For better subsequent error-recovery, we indicate that
5622                      there should have been a default argument.  */
5623                   TREE_PURPOSE (parm) = error_mark_node;
5624                   no_errors = false;
5625                 }
5626 	      else if (!is_partial
5627 		       && !is_friend_decl
5628 		       /* Don't complain about an enclosing partial
5629 			  specialization.  */
5630 		       && parm_level == parms
5631 		       && (TREE_CODE (decl) == TYPE_DECL || VAR_P (decl))
5632 		       && i < ntparms - 1
5633 		       && template_parameter_pack_p (TREE_VALUE (parm))
5634 		       /* A fixed parameter pack will be partially
5635 			  instantiated into a fixed length list.  */
5636 		       && !fixed_parameter_pack_p (TREE_VALUE (parm)))
5637 		{
5638 		  /* A primary class template, primary variable template
5639 		     (DR 2032), or alias template can only have one
5640 		     parameter pack, at the end of the template
5641 		     parameter list.  */
5642 
5643 		  error ("parameter pack %q+D must be at the end of the"
5644 			 " template parameter list", TREE_VALUE (parm));
5645 
5646 		  TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
5647 		    = error_mark_node;
5648 		  no_errors = false;
5649 		}
5650             }
5651         }
5652     }
5653 
5654   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
5655       || is_partial
5656       || !is_primary
5657       || is_friend_decl)
5658     /* For an ordinary class template, default template arguments are
5659        allowed at the innermost level, e.g.:
5660 	 template <class T = int>
5661 	 struct S {};
5662        but, in a partial specialization, they're not allowed even
5663        there, as we have in [temp.class.spec]:
5664 
5665 	 The template parameter list of a specialization shall not
5666 	 contain default template argument values.
5667 
5668        So, for a partial specialization, or for a function template
5669        (in C++98/C++03), we look at all of them.  */
5670     ;
5671   else
5672     /* But, for a primary class template that is not a partial
5673        specialization we look at all template parameters except the
5674        innermost ones.  */
5675     parms = TREE_CHAIN (parms);
5676 
5677   /* Figure out what error message to issue.  */
5678   if (is_friend_decl == 2)
5679     msg = G_("default template arguments may not be used in function template "
5680 	     "friend re-declaration");
5681   else if (is_friend_decl)
5682     msg = G_("default template arguments may not be used in template "
5683 	     "friend declarations");
5684   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
5685     msg = G_("default template arguments may not be used in function templates "
5686 	     "without %<-std=c++11%> or %<-std=gnu++11%>");
5687   else if (is_partial)
5688     msg = G_("default template arguments may not be used in "
5689 	     "partial specializations");
5690   else if (current_class_type && CLASSTYPE_IS_TEMPLATE (current_class_type))
5691     msg = G_("default argument for template parameter for class enclosing %qD");
5692   else
5693     /* Per [temp.param]/9, "A default template-argument shall not be
5694        specified in the template-parameter-lists of the definition of
5695        a member of a class template that appears outside of the member's
5696        class.", thus if we aren't handling a member of a class template
5697        there is no need to examine the parameters.  */
5698     return true;
5699 
5700   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
5701     /* If we're inside a class definition, there's no need to
5702        examine the parameters to the class itself.  On the one
5703        hand, they will be checked when the class is defined, and,
5704        on the other, default arguments are valid in things like:
5705 	 template <class T = double>
5706 	 struct S { template <class U> void f(U); };
5707        Here the default argument for `S' has no bearing on the
5708        declaration of `f'.  */
5709     last_level_to_check = template_class_depth (current_class_type) + 1;
5710   else
5711     /* Check everything.  */
5712     last_level_to_check = 0;
5713 
5714   for (parm_level = parms;
5715        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
5716        parm_level = TREE_CHAIN (parm_level))
5717     {
5718       tree inner_parms = TREE_VALUE (parm_level);
5719       int i;
5720       int ntparms;
5721 
5722       ntparms = TREE_VEC_LENGTH (inner_parms);
5723       for (i = 0; i < ntparms; ++i)
5724         {
5725           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
5726             continue;
5727 
5728 	  if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
5729 	    {
5730 	      if (msg)
5731 	        {
5732                   no_errors = false;
5733                   if (is_friend_decl == 2)
5734                     return no_errors;
5735 
5736 		  error (msg, decl);
5737 		  msg = 0;
5738 	        }
5739 
5740 	      /* Clear out the default argument so that we are not
5741 	         confused later.  */
5742 	      TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
5743 	    }
5744         }
5745 
5746       /* At this point, if we're still interested in issuing messages,
5747 	 they must apply to classes surrounding the object declared.  */
5748       if (msg)
5749 	msg = G_("default argument for template parameter for class "
5750 		 "enclosing %qD");
5751     }
5752 
5753   return no_errors;
5754 }
5755 
5756 /* Worker for push_template_decl_real, called via
5757    for_each_template_parm.  DATA is really an int, indicating the
5758    level of the parameters we are interested in.  If T is a template
5759    parameter of that level, return nonzero.  */
5760 
5761 static int
template_parm_this_level_p(tree t,void * data)5762 template_parm_this_level_p (tree t, void* data)
5763 {
5764   int this_level = *(int *)data;
5765   int level;
5766 
5767   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5768     level = TEMPLATE_PARM_LEVEL (t);
5769   else
5770     level = TEMPLATE_TYPE_LEVEL (t);
5771   return level == this_level;
5772 }
5773 
5774 /* Worker for uses_outer_template_parms, called via for_each_template_parm.
5775    DATA is really an int, indicating the innermost outer level of parameters.
5776    If T is a template parameter of that level or further out, return
5777    nonzero.  */
5778 
5779 static int
template_parm_outer_level(tree t,void * data)5780 template_parm_outer_level (tree t, void *data)
5781 {
5782   int this_level = *(int *)data;
5783   int level;
5784 
5785   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5786     level = TEMPLATE_PARM_LEVEL (t);
5787   else
5788     level = TEMPLATE_TYPE_LEVEL (t);
5789   return level <= this_level;
5790 }
5791 
5792 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
5793    parameters given by current_template_args, or reuses a
5794    previously existing one, if appropriate.  Returns the DECL, or an
5795    equivalent one, if it is replaced via a call to duplicate_decls.
5796 
5797    If IS_FRIEND is true, DECL is a friend declaration.  */
5798 
5799 tree
push_template_decl(tree decl,bool is_friend)5800 push_template_decl (tree decl, bool is_friend)
5801 {
5802   if (decl == error_mark_node || !current_template_parms)
5803     return error_mark_node;
5804 
5805   /* See if this is a partial specialization.  */
5806   bool is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
5807 		      && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
5808 		      && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
5809 		     || (VAR_P (decl)
5810 			 && DECL_LANG_SPECIFIC (decl)
5811 			 && DECL_TEMPLATE_SPECIALIZATION (decl)
5812 			 && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
5813 
5814   /* No surprising friend functions.  */
5815   gcc_checking_assert (is_friend
5816 		       || !(TREE_CODE (decl) == FUNCTION_DECL
5817 			    && DECL_UNIQUE_FRIEND_P (decl)));
5818 
5819   tree ctx;
5820   if (is_friend)
5821     /* For a friend, we want the context of the friend, not
5822        the type of which it is a friend.  */
5823     ctx = CP_DECL_CONTEXT (decl);
5824   else if (CP_DECL_CONTEXT (decl)
5825 	   && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
5826     /* In the case of a virtual function, we want the class in which
5827        it is defined.  */
5828     ctx = CP_DECL_CONTEXT (decl);
5829   else
5830     /* Otherwise, if we're currently defining some class, the DECL
5831        is assumed to be a member of the class.  */
5832     ctx = current_scope ();
5833 
5834   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
5835     ctx = NULL_TREE;
5836 
5837   if (!DECL_CONTEXT (decl))
5838     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5839 
5840   /* See if this is a primary template.  */
5841   bool is_primary = false;
5842   if (is_friend && ctx
5843       && uses_template_parms_level (ctx, current_template_depth))
5844     /* A friend template that specifies a class context, i.e.
5845          template <typename T> friend void A<T>::f();
5846        is not primary.  */
5847     ;
5848   else if (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5849     /* Lambdas are not primary.  */
5850     ;
5851   else
5852     is_primary = template_parm_scope_p ();
5853 
5854   /* True if the template is a member template, in the sense of
5855      [temp.mem].  */
5856   bool member_template_p = false;
5857 
5858   if (is_primary)
5859     {
5860       warning (OPT_Wtemplates, "template %qD declared", decl);
5861 
5862       if (DECL_CLASS_SCOPE_P (decl))
5863 	member_template_p = true;
5864 
5865       if (TREE_CODE (decl) == TYPE_DECL
5866 	  && IDENTIFIER_ANON_P (DECL_NAME (decl)))
5867 	{
5868 	  error ("template class without a name");
5869 	  return error_mark_node;
5870 	}
5871       else if (TREE_CODE (decl) == FUNCTION_DECL)
5872 	{
5873 	  if (member_template_p)
5874 	    {
5875 	      if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
5876 		error ("member template %qD may not have virt-specifiers", decl);
5877 	    }
5878 	  if (DECL_DESTRUCTOR_P (decl))
5879 	    {
5880 	      /* [temp.mem]
5881 
5882 		 A destructor shall not be a member template.  */
5883 	      error_at (DECL_SOURCE_LOCATION (decl),
5884 			"destructor %qD declared as member template", decl);
5885 	      return error_mark_node;
5886 	    }
5887 	  if (IDENTIFIER_NEWDEL_OP_P (DECL_NAME (decl))
5888 	      && (!prototype_p (TREE_TYPE (decl))
5889 		  || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
5890 		  || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5891 		  || (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5892 		      == void_list_node)))
5893 	    {
5894 	      /* [basic.stc.dynamic.allocation]
5895 
5896 		 An allocation function can be a function
5897 		 template. ... Template allocation functions shall
5898 		 have two or more parameters.  */
5899 	      error ("invalid template declaration of %qD", decl);
5900 	      return error_mark_node;
5901 	    }
5902 	}
5903       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5904 	       && CLASS_TYPE_P (TREE_TYPE (decl)))
5905 	/* Class template.  */;
5906       else if (TREE_CODE (decl) == TYPE_DECL
5907 	       && TYPE_DECL_ALIAS_P (decl))
5908 	/* alias-declaration */
5909 	gcc_assert (!DECL_ARTIFICIAL (decl));
5910       else if (VAR_P (decl))
5911 	/* C++14 variable template. */;
5912       else if (TREE_CODE (decl) == CONCEPT_DECL)
5913 	/* C++20 concept definitions.  */;
5914       else
5915 	{
5916 	  error ("template declaration of %q#D", decl);
5917 	  return error_mark_node;
5918 	}
5919     }
5920 
5921   bool local_p = (!DECL_IMPLICIT_TYPEDEF_P (decl)
5922 		  && ((ctx && TREE_CODE (ctx) == FUNCTION_DECL)
5923 		      || (VAR_OR_FUNCTION_DECL_P (decl)
5924 			  && DECL_LOCAL_DECL_P (decl))));
5925 
5926   /* Check to see that the rules regarding the use of default
5927      arguments are not being violated.  We check args for a friend
5928      functions when we know whether it's a definition, introducing
5929      declaration or re-declaration.  */
5930   if (!local_p && (!is_friend || TREE_CODE (decl) != FUNCTION_DECL))
5931     check_default_tmpl_args (decl, current_template_parms,
5932 			     is_primary, is_partial, is_friend);
5933 
5934   /* Ensure that there are no parameter packs in the type of this
5935      declaration that have not been expanded.  */
5936   if (TREE_CODE (decl) == FUNCTION_DECL)
5937     {
5938       /* Check each of the arguments individually to see if there are
5939          any bare parameter packs.  */
5940       tree type = TREE_TYPE (decl);
5941       tree arg = DECL_ARGUMENTS (decl);
5942       tree argtype = TYPE_ARG_TYPES (type);
5943 
5944       while (arg && argtype)
5945         {
5946           if (!DECL_PACK_P (arg)
5947               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
5948             {
5949             /* This is a PARM_DECL that contains unexpanded parameter
5950                packs. We have already complained about this in the
5951                check_for_bare_parameter_packs call, so just replace
5952                these types with ERROR_MARK_NODE.  */
5953               TREE_TYPE (arg) = error_mark_node;
5954               TREE_VALUE (argtype) = error_mark_node;
5955             }
5956 
5957           arg = DECL_CHAIN (arg);
5958           argtype = TREE_CHAIN (argtype);
5959         }
5960 
5961       /* Check for bare parameter packs in the return type and the
5962          exception specifiers.  */
5963       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
5964 	/* Errors were already issued, set return type to int
5965 	   as the frontend doesn't expect error_mark_node as
5966 	   the return type.  */
5967 	TREE_TYPE (type) = integer_type_node;
5968       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
5969 	TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
5970     }
5971   else
5972     {
5973       if (check_for_bare_parameter_packs (is_typedef_decl (decl)
5974 					  ? DECL_ORIGINAL_TYPE (decl)
5975 					  : TREE_TYPE (decl)))
5976 	{
5977 	  TREE_TYPE (decl) = error_mark_node;
5978 	  return error_mark_node;
5979 	}
5980 
5981       if (is_partial && VAR_P (decl)
5982 	  && check_for_bare_parameter_packs (DECL_TI_ARGS (decl)))
5983 	return error_mark_node;
5984     }
5985 
5986   if (is_partial)
5987     return process_partial_specialization (decl);
5988 
5989   tree args = current_template_args ();
5990   tree tmpl = NULL_TREE;
5991   bool new_template_p = false;
5992   if (local_p)
5993     {
5994       /* Does not get a template head.  */
5995       tmpl = NULL_TREE;
5996       gcc_checking_assert (!is_primary);
5997     }
5998   else if (!ctx
5999 	   || TREE_CODE (ctx) == FUNCTION_DECL
6000 	   || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
6001 	   || (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
6002 	   || (is_friend && !(DECL_LANG_SPECIFIC (decl)
6003 			      && DECL_TEMPLATE_INFO (decl))))
6004     {
6005       if (DECL_LANG_SPECIFIC (decl)
6006 	  && DECL_TEMPLATE_INFO (decl)
6007 	  && DECL_TI_TEMPLATE (decl))
6008 	tmpl = DECL_TI_TEMPLATE (decl);
6009       /* If DECL is a TYPE_DECL for a class-template, then there won't
6010 	 be DECL_LANG_SPECIFIC.  The information equivalent to
6011 	 DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
6012       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
6013 	       && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
6014 	       && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
6015 	{
6016 	  /* Since a template declaration already existed for this
6017 	     class-type, we must be redeclaring it here.  Make sure
6018 	     that the redeclaration is valid.  */
6019 	  redeclare_class_template (TREE_TYPE (decl),
6020 				    current_template_parms,
6021 				    current_template_constraints ());
6022 	  /* We don't need to create a new TEMPLATE_DECL; just use the
6023 	     one we already had.  */
6024 	  tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
6025 	}
6026       else
6027 	{
6028 	  tmpl = build_template_decl (decl, current_template_parms,
6029 				      member_template_p);
6030 	  new_template_p = true;
6031 
6032 	  if (DECL_LANG_SPECIFIC (decl)
6033 	      && DECL_TEMPLATE_SPECIALIZATION (decl))
6034 	    {
6035 	      /* A specialization of a member template of a template
6036 		 class.  */
6037 	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
6038 	      DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
6039 	      DECL_TEMPLATE_INFO (decl) = NULL_TREE;
6040 	    }
6041 	}
6042     }
6043   else
6044     {
6045       tree a, t, current, parms;
6046       int i;
6047       tree tinfo = get_template_info (decl);
6048 
6049       if (!tinfo)
6050 	{
6051 	  error ("template definition of non-template %q#D", decl);
6052 	  return error_mark_node;
6053 	}
6054 
6055       tmpl = TI_TEMPLATE (tinfo);
6056 
6057       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
6058 	  && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
6059 	  && DECL_TEMPLATE_SPECIALIZATION (decl)
6060 	  && DECL_MEMBER_TEMPLATE_P (tmpl))
6061 	{
6062 	  /* The declaration is a specialization of a member
6063 	     template, declared outside the class.  Therefore, the
6064 	     innermost template arguments will be NULL, so we
6065 	     replace them with the arguments determined by the
6066 	     earlier call to check_explicit_specialization.  */
6067 	  args = DECL_TI_ARGS (decl);
6068 
6069 	  tree new_tmpl
6070 	    = build_template_decl (decl, current_template_parms,
6071 				   member_template_p);
6072 	  DECL_TI_TEMPLATE (decl) = new_tmpl;
6073 	  SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
6074 	  DECL_TEMPLATE_INFO (new_tmpl)
6075 	    = build_template_info (tmpl, args);
6076 
6077 	  register_specialization (new_tmpl,
6078 				   most_general_template (tmpl),
6079 				   args,
6080 				   is_friend, 0);
6081 	  return decl;
6082 	}
6083 
6084       /* Make sure the template headers we got make sense.  */
6085 
6086       parms = DECL_TEMPLATE_PARMS (tmpl);
6087       i = TMPL_PARMS_DEPTH (parms);
6088       if (TMPL_ARGS_DEPTH (args) != i)
6089 	{
6090 	  error ("expected %d levels of template parms for %q#D, got %d",
6091 		 i, decl, TMPL_ARGS_DEPTH (args));
6092 	  DECL_INTERFACE_KNOWN (decl) = 1;
6093 	  return error_mark_node;
6094 	}
6095       else
6096 	for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
6097 	  {
6098 	    a = TMPL_ARGS_LEVEL (args, i);
6099 	    t = INNERMOST_TEMPLATE_PARMS (parms);
6100 
6101 	    if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
6102 	      {
6103 		if (current == decl)
6104 		  error ("got %d template parameters for %q#D",
6105 			 TREE_VEC_LENGTH (a), decl);
6106 		else
6107 		  error ("got %d template parameters for %q#T",
6108 			 TREE_VEC_LENGTH (a), current);
6109 		error ("  but %d required", TREE_VEC_LENGTH (t));
6110 		/* Avoid crash in import_export_decl.  */
6111 		DECL_INTERFACE_KNOWN (decl) = 1;
6112 		return error_mark_node;
6113 	      }
6114 
6115 	    if (current == decl)
6116 	      current = ctx;
6117 	    else if (current == NULL_TREE)
6118 	      /* Can happen in erroneous input.  */
6119 	      break;
6120 	    else
6121 	      current = get_containing_scope (current);
6122 	  }
6123 
6124       /* Check that the parms are used in the appropriate qualifying scopes
6125 	 in the declarator.  */
6126       if (!comp_template_args
6127 	  (TI_ARGS (tinfo),
6128 	   TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
6129 	{
6130 	  error ("template arguments to %qD do not match original "
6131 		 "template %qD", decl, DECL_TEMPLATE_RESULT (tmpl));
6132 	  if (!uses_template_parms (TI_ARGS (tinfo)))
6133 	    inform (input_location, "use %<template<>%> for"
6134 		    " an explicit specialization");
6135 	  /* Avoid crash in import_export_decl.  */
6136 	  DECL_INTERFACE_KNOWN (decl) = 1;
6137 	  return error_mark_node;
6138 	}
6139     }
6140 
6141   gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
6142 
6143   if (new_template_p)
6144     {
6145       /* Push template declarations for global functions and types.
6146 	 Note that we do not try to push a global template friend
6147 	 declared in a template class; such a thing may well depend on
6148 	 the template parameters of the class and we'll push it when
6149 	 instantiating the befriending class.  */
6150       if (!ctx
6151 	  && !(is_friend && template_class_depth (current_class_type) > 0))
6152 	{
6153 	  tree pushed = pushdecl_namespace_level (tmpl, /*hiding=*/is_friend);
6154 	  if (pushed == error_mark_node)
6155 	    return error_mark_node;
6156 
6157 	  /* pushdecl may have found an existing template.  */
6158 	  if (pushed != tmpl)
6159 	    {
6160 	      decl = DECL_TEMPLATE_RESULT (pushed);
6161 	      tmpl = NULL_TREE;
6162 	    }
6163 	}
6164       else if (is_friend)
6165 	{
6166 	  /* Record this decl as belonging to the current class.  It's
6167 	     not chained onto anything else.  */
6168 	  DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (tmpl) = true;
6169 	  gcc_checking_assert (!DECL_CHAIN (tmpl));
6170 	  DECL_CHAIN (tmpl) = current_scope ();
6171 	}
6172     }
6173   else if (tmpl)
6174     /* The type may have been completed, or (erroneously) changed.  */
6175     TREE_TYPE (tmpl) = TREE_TYPE (decl);
6176 
6177   if (tmpl)
6178     {
6179       if (is_primary)
6180 	{
6181 	  tree parms = DECL_TEMPLATE_PARMS (tmpl);
6182 
6183 	  DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6184 
6185 	  /* Give template template parms a DECL_CONTEXT of the template
6186 	     for which they are a parameter.  */
6187 	  parms = INNERMOST_TEMPLATE_PARMS (parms);
6188 	  for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
6189 	    {
6190 	      tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6191 	      if (TREE_CODE (parm) == TEMPLATE_DECL)
6192 		DECL_CONTEXT (parm) = tmpl;
6193 	    }
6194 
6195 	  if (TREE_CODE (decl) == TYPE_DECL
6196 	      && TYPE_DECL_ALIAS_P (decl))
6197 	    {
6198 	      if (tree constr
6199 		  = TEMPLATE_PARMS_CONSTRAINTS (DECL_TEMPLATE_PARMS (tmpl)))
6200 		{
6201 		  /* ??? Why don't we do this here for all templates?  */
6202 		  constr = build_constraints (constr, NULL_TREE);
6203 		  set_constraints (decl, constr);
6204 		}
6205 	      if (complex_alias_template_p (tmpl))
6206 		TEMPLATE_DECL_COMPLEX_ALIAS_P (tmpl) = true;
6207 	    }
6208 	}
6209 
6210       /* The DECL_TI_ARGS of DECL contains full set of arguments
6211 	 referring wback to its most general template.  If TMPL is a
6212 	 specialization, ARGS may only have the innermost set of
6213 	 arguments.  Add the missing argument levels if necessary.  */
6214       if (DECL_TEMPLATE_INFO (tmpl))
6215 	args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
6216 
6217       tree info = build_template_info (tmpl, args);
6218 
6219       if (DECL_IMPLICIT_TYPEDEF_P (decl))
6220 	SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
6221       else
6222 	{
6223 	  retrofit_lang_decl (decl);
6224 	  DECL_TEMPLATE_INFO (decl) = info;
6225 	}
6226     }
6227 
6228   if (flag_implicit_templates
6229       && !is_friend
6230       && TREE_PUBLIC (decl)
6231       && VAR_OR_FUNCTION_DECL_P (decl))
6232     /* Set DECL_COMDAT on template instantiations; if we force
6233        them to be emitted by explicit instantiation,
6234        mark_needed will tell cgraph to do the right thing.  */
6235     DECL_COMDAT (decl) = true;
6236 
6237   gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
6238 
6239   return decl;
6240 }
6241 
6242 /* FN is an inheriting constructor that inherits from the constructor
6243    template INHERITED; turn FN into a constructor template with a matching
6244    template header.  */
6245 
6246 tree
add_inherited_template_parms(tree fn,tree inherited)6247 add_inherited_template_parms (tree fn, tree inherited)
6248 {
6249   tree inner_parms
6250     = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
6251   inner_parms = copy_node (inner_parms);
6252   tree parms
6253     = tree_cons (size_int (current_template_depth + 1),
6254 		 inner_parms, current_template_parms);
6255   tree tmpl = build_template_decl (fn, parms, /*member*/true);
6256   tree args = template_parms_to_args (parms);
6257   DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
6258   DECL_ARTIFICIAL (tmpl) = true;
6259   DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6260   return tmpl;
6261 }
6262 
6263 /* Called when a class template TYPE is redeclared with the indicated
6264    template PARMS, e.g.:
6265 
6266      template <class T> struct S;
6267      template <class T> struct S {};  */
6268 
6269 bool
redeclare_class_template(tree type,tree parms,tree cons)6270 redeclare_class_template (tree type, tree parms, tree cons)
6271 {
6272   tree tmpl;
6273   tree tmpl_parms;
6274   int i;
6275 
6276   if (!TYPE_TEMPLATE_INFO (type))
6277     {
6278       error ("%qT is not a template type", type);
6279       return false;
6280     }
6281 
6282   tmpl = TYPE_TI_TEMPLATE (type);
6283   if (!PRIMARY_TEMPLATE_P (tmpl))
6284     /* The type is nested in some template class.  Nothing to worry
6285        about here; there are no new template parameters for the nested
6286        type.  */
6287     return true;
6288 
6289   if (!parms)
6290     {
6291       error ("template specifiers not specified in declaration of %qD",
6292 	     tmpl);
6293       return false;
6294     }
6295 
6296   parms = INNERMOST_TEMPLATE_PARMS (parms);
6297   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
6298 
6299   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
6300     {
6301       error_n (input_location, TREE_VEC_LENGTH (parms),
6302                "redeclared with %d template parameter",
6303                "redeclared with %d template parameters",
6304                TREE_VEC_LENGTH (parms));
6305       inform_n (DECL_SOURCE_LOCATION (tmpl), TREE_VEC_LENGTH (tmpl_parms),
6306                 "previous declaration %qD used %d template parameter",
6307                 "previous declaration %qD used %d template parameters",
6308                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
6309       return false;
6310     }
6311 
6312   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
6313     {
6314       tree tmpl_parm;
6315       tree parm;
6316 
6317       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
6318           || TREE_VEC_ELT (parms, i) == error_mark_node)
6319         continue;
6320 
6321       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
6322       if (error_operand_p (tmpl_parm))
6323 	return false;
6324 
6325       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6326 
6327       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
6328 	 TEMPLATE_DECL.  */
6329       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
6330 	  || (TREE_CODE (tmpl_parm) != TYPE_DECL
6331 	      && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
6332 	  || (TREE_CODE (tmpl_parm) != PARM_DECL
6333 	      && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
6334 		  != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
6335 	  || (TREE_CODE (tmpl_parm) == PARM_DECL
6336 	      && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
6337 		  != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
6338 	{
6339 	  auto_diagnostic_group d;
6340 	  error ("template parameter %q+#D", tmpl_parm);
6341 	  if (DECL_P (parm))
6342 	    inform (DECL_SOURCE_LOCATION (parm), "redeclared here as %q#D", parm);
6343 	  else
6344 	    inform (input_location, "redeclared here");
6345 	  return false;
6346 	}
6347 
6348       /* The parameters can be declared to introduce different
6349 	 constraints.  */
6350       tree p1 = TREE_VEC_ELT (tmpl_parms, i);
6351       tree p2 = TREE_VEC_ELT (parms, i);
6352       if (!template_parameter_constraints_equivalent_p (p1, p2))
6353 	{
6354 	  auto_diagnostic_group d;
6355 	  error ("declaration of template parameter %q+#D with different "
6356 		 "constraints", parm);
6357 	  inform (DECL_SOURCE_LOCATION (tmpl_parm),
6358 		  "original declaration appeared here");
6359 	  return false;
6360 	}
6361 
6362       /* Give each template template parm in this redeclaration a
6363 	 DECL_CONTEXT of the template for which they are a parameter.  */
6364       if (TREE_CODE (parm) == TEMPLATE_DECL)
6365 	{
6366 	  gcc_assert (DECL_CONTEXT (parm) == NULL_TREE);
6367 	  DECL_CONTEXT (parm) = tmpl;
6368 	}
6369     }
6370 
6371   if (!merge_default_template_args (parms, tmpl_parms, /*class_p=*/true))
6372     return false;
6373 
6374   tree ci = get_constraints (tmpl);
6375   tree req1 = ci ? CI_TEMPLATE_REQS (ci) : NULL_TREE;
6376   tree req2 = cons ? CI_TEMPLATE_REQS (cons) : NULL_TREE;
6377 
6378   /* Two classes with different constraints declare different entities.  */
6379   if (!cp_tree_equal (req1, req2))
6380     {
6381       auto_diagnostic_group d;
6382       error_at (input_location, "redeclaration %q#D with different "
6383                                 "constraints", tmpl);
6384       inform (DECL_SOURCE_LOCATION (tmpl),
6385               "original declaration appeared here");
6386       return false;
6387     }
6388 
6389     return true;
6390 }
6391 
6392 /* The actual substitution part of instantiate_non_dependent_expr_sfinae,
6393    to be used when the caller has already checked
6394     !instantiation_dependent_uneval_expression_p (expr)
6395    and cleared processing_template_decl.  */
6396 
6397 tree
instantiate_non_dependent_expr_internal(tree expr,tsubst_flags_t complain)6398 instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
6399 {
6400   return tsubst_copy_and_build (expr,
6401 				/*args=*/NULL_TREE,
6402 				complain,
6403 				/*in_decl=*/NULL_TREE,
6404 				/*function_p=*/false,
6405 				/*integral_constant_expression_p=*/true);
6406 }
6407 
6408 /* Instantiate the non-dependent expression EXPR.  */
6409 
6410 tree
instantiate_non_dependent_expr_sfinae(tree expr,tsubst_flags_t complain)6411 instantiate_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
6412 {
6413   if (expr == NULL_TREE)
6414     return NULL_TREE;
6415 
6416   if (processing_template_decl)
6417     {
6418       /* The caller should have checked this already.  */
6419       gcc_checking_assert (!instantiation_dependent_uneval_expression_p (expr));
6420       processing_template_decl_sentinel s;
6421       expr = instantiate_non_dependent_expr_internal (expr, complain);
6422     }
6423   return expr;
6424 }
6425 
6426 tree
instantiate_non_dependent_expr(tree expr)6427 instantiate_non_dependent_expr (tree expr)
6428 {
6429   return instantiate_non_dependent_expr_sfinae (expr, tf_error);
6430 }
6431 
6432 /* Like instantiate_non_dependent_expr, but return NULL_TREE if the
6433    expression is dependent or non-constant.  */
6434 
6435 tree
instantiate_non_dependent_or_null(tree expr)6436 instantiate_non_dependent_or_null (tree expr)
6437 {
6438   if (expr == NULL_TREE)
6439     return NULL_TREE;
6440   if (processing_template_decl)
6441     {
6442       if (!is_nondependent_constant_expression (expr))
6443 	expr = NULL_TREE;
6444       else
6445 	{
6446 	  processing_template_decl_sentinel s;
6447 	  expr = instantiate_non_dependent_expr_internal (expr, tf_error);
6448 	}
6449     }
6450   return expr;
6451 }
6452 
6453 /* True iff T is a specialization of a variable template.  */
6454 
6455 bool
variable_template_specialization_p(tree t)6456 variable_template_specialization_p (tree t)
6457 {
6458   if (!VAR_P (t) || !DECL_LANG_SPECIFIC (t) || !DECL_TEMPLATE_INFO (t))
6459     return false;
6460   tree tmpl = DECL_TI_TEMPLATE (t);
6461   return variable_template_p (tmpl);
6462 }
6463 
6464 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
6465    template declaration, or a TYPE_DECL for an alias declaration.  */
6466 
6467 bool
alias_type_or_template_p(tree t)6468 alias_type_or_template_p (tree t)
6469 {
6470   if (t == NULL_TREE)
6471     return false;
6472   return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
6473 	  || (TYPE_P (t)
6474 	      && TYPE_NAME (t)
6475 	      && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
6476 	  || DECL_ALIAS_TEMPLATE_P (t));
6477 }
6478 
6479 /* If T is a specialization of an alias template, return it; otherwise return
6480    NULL_TREE.  If TRANSPARENT_TYPEDEFS is true, look through other aliases.  */
6481 
6482 tree
alias_template_specialization_p(const_tree t,bool transparent_typedefs)6483 alias_template_specialization_p (const_tree t,
6484 				 bool transparent_typedefs)
6485 {
6486   if (!TYPE_P (t))
6487     return NULL_TREE;
6488 
6489   /* It's an alias template specialization if it's an alias and its
6490      TYPE_NAME is a specialization of a primary template.  */
6491   if (typedef_variant_p (t))
6492     {
6493       if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
6494 	if (PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo)))
6495 	  return CONST_CAST_TREE (t);
6496       if (transparent_typedefs)
6497 	return alias_template_specialization_p (DECL_ORIGINAL_TYPE
6498 						(TYPE_NAME (t)),
6499 						transparent_typedefs);
6500     }
6501 
6502   return NULL_TREE;
6503 }
6504 
6505 /* Data structure for complex_alias_template_*.  */
6506 
6507 struct uses_all_template_parms_data
6508 {
6509   int level;
6510   bool *seen;
6511 };
6512 
6513 /* walk_tree callback for complex_alias_template_p.  */
6514 
6515 static tree
complex_alias_template_r(tree * tp,int * walk_subtrees,void * data_)6516 complex_alias_template_r (tree *tp, int *walk_subtrees, void *data_)
6517 {
6518   tree t = *tp;
6519   auto &data = *(struct uses_all_template_parms_data*)data_;
6520 
6521   switch (TREE_CODE (t))
6522     {
6523     case TEMPLATE_TYPE_PARM:
6524     case TEMPLATE_PARM_INDEX:
6525     case TEMPLATE_TEMPLATE_PARM:
6526     case BOUND_TEMPLATE_TEMPLATE_PARM:
6527       {
6528 	tree idx = get_template_parm_index (t);
6529 	if (TEMPLATE_PARM_LEVEL (idx) == data.level)
6530 	  data.seen[TEMPLATE_PARM_IDX (idx)] = true;
6531       }
6532 
6533     default:;
6534     }
6535 
6536   if (!PACK_EXPANSION_P (t))
6537     return 0;
6538 
6539   /* An alias template with a pack expansion that expands a pack from the
6540      enclosing class needs to be considered complex, to avoid confusion with
6541      the same pack being used as an argument to the alias's own template
6542      parameter (91966).  */
6543   for (tree pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
6544        pack = TREE_CHAIN (pack))
6545     {
6546       tree parm_pack = TREE_VALUE (pack);
6547       if (!TEMPLATE_PARM_P (parm_pack))
6548 	continue;
6549       int idx, level;
6550       template_parm_level_and_index (parm_pack, &level, &idx);
6551       if (level < data.level)
6552 	return t;
6553 
6554       /* Consider the expanded packs to be used outside the expansion...  */
6555       data.seen[idx] = true;
6556     }
6557 
6558   /* ...but don't walk into the pattern.  Consider PR104008:
6559 
6560      template <typename T, typename... Ts>
6561      using IsOneOf = disjunction<is_same<T, Ts>...>;
6562 
6563      where IsOneOf seemingly uses all of its template parameters in its
6564      expansion (and does not expand a pack from the enclosing class), so the
6565      alias was not marked as complex.  However, if it is used like
6566      "IsOneOf<T>", the empty pack for Ts means that T no longer appears in the
6567      expansion.  So only Ts is considered used by the pack expansion.  */
6568   *walk_subtrees = false;
6569 
6570   return 0;
6571 }
6572 
6573 /* An alias template is complex from a SFINAE perspective if a template-id
6574    using that alias can be ill-formed when the expansion is not, as with
6575    the void_t template.
6576 
6577    Returns 1 if always complex, 0 if not complex, -1 if complex iff any of the
6578    template arguments are empty packs.  */
6579 
6580 static bool
complex_alias_template_p(const_tree tmpl)6581 complex_alias_template_p (const_tree tmpl)
6582 {
6583   /* A renaming alias isn't complex.  */
6584   if (get_underlying_template (CONST_CAST_TREE (tmpl)) != tmpl)
6585     return false;
6586 
6587   /* Any other constrained alias is complex.  */
6588   if (get_constraints (tmpl))
6589     return true;
6590 
6591   struct uses_all_template_parms_data data;
6592   tree pat = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6593   tree parms = DECL_TEMPLATE_PARMS (tmpl);
6594   data.level = TMPL_PARMS_DEPTH (parms);
6595   int len = TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS (parms));
6596   data.seen = XALLOCAVEC (bool, len);
6597   for (int i = 0; i < len; ++i)
6598     data.seen[i] = false;
6599 
6600   if (cp_walk_tree_without_duplicates (&pat, complex_alias_template_r, &data))
6601     return true;
6602   for (int i = 0; i < len; ++i)
6603     if (!data.seen[i])
6604       return true;
6605   return false;
6606 }
6607 
6608 /* If T is a specialization of a complex alias template with dependent
6609    template-arguments, return it; otherwise return NULL_TREE.  If T is a
6610    typedef to such a specialization, return the specialization.  */
6611 
6612 tree
dependent_alias_template_spec_p(const_tree t,bool transparent_typedefs)6613 dependent_alias_template_spec_p (const_tree t, bool transparent_typedefs)
6614 {
6615   if (t == error_mark_node)
6616     return NULL_TREE;
6617   gcc_assert (TYPE_P (t));
6618 
6619   if (!typedef_variant_p (t))
6620     return NULL_TREE;
6621 
6622   tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t);
6623   if (tinfo
6624       && TEMPLATE_DECL_COMPLEX_ALIAS_P (TI_TEMPLATE (tinfo))
6625       && (any_dependent_template_arguments_p
6626 	  (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)))))
6627     return CONST_CAST_TREE (t);
6628 
6629   if (transparent_typedefs)
6630     {
6631       tree utype = DECL_ORIGINAL_TYPE (TYPE_NAME (t));
6632       return dependent_alias_template_spec_p (utype, transparent_typedefs);
6633     }
6634 
6635   return NULL_TREE;
6636 }
6637 
6638 /* Return the number of innermost template parameters in TMPL.  */
6639 
6640 static int
num_innermost_template_parms(const_tree tmpl)6641 num_innermost_template_parms (const_tree tmpl)
6642 {
6643   tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6644   return TREE_VEC_LENGTH (parms);
6645 }
6646 
6647 /* Return either TMPL or another template that it is equivalent to under DR
6648    1286: An alias that just changes the name of a template is equivalent to
6649    the other template.  */
6650 
6651 static tree
get_underlying_template(tree tmpl)6652 get_underlying_template (tree tmpl)
6653 {
6654   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
6655   while (DECL_ALIAS_TEMPLATE_P (tmpl))
6656     {
6657       /* Determine if the alias is equivalent to an underlying template.  */
6658       tree orig_type = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6659       /* The underlying type may have been ill-formed. Don't proceed.  */
6660       if (!orig_type)
6661 	break;
6662       tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (orig_type);
6663       if (!tinfo)
6664 	break;
6665 
6666       tree underlying = TI_TEMPLATE (tinfo);
6667       if (!PRIMARY_TEMPLATE_P (underlying)
6668 	  || (num_innermost_template_parms (tmpl)
6669 	      != num_innermost_template_parms (underlying)))
6670 	break;
6671 
6672       /* Does the alias add cv-quals?  */
6673       if (TYPE_QUALS (TREE_TYPE (underlying)) != TYPE_QUALS (TREE_TYPE (tmpl)))
6674 	break;
6675 
6676       tree alias_args = INNERMOST_TEMPLATE_ARGS (generic_targs_for (tmpl));
6677       if (!comp_template_args (TI_ARGS (tinfo), alias_args))
6678 	break;
6679 
6680       /* Are any default template arguments equivalent?  */
6681       tree aparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6682       tree uparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (underlying));
6683       const int nparms = TREE_VEC_LENGTH (aparms);
6684       for (int i = 0; i < nparms; ++i)
6685 	{
6686 	  tree adefarg = TREE_PURPOSE (TREE_VEC_ELT (aparms, i));
6687 	  tree udefarg = TREE_PURPOSE (TREE_VEC_ELT (uparms, i));
6688 	  if (!template_args_equal (adefarg, udefarg))
6689 	    goto top_break;
6690 	}
6691 
6692       /* If TMPL adds or changes any constraints, it isn't equivalent.  I think
6693 	 it's appropriate to treat a less-constrained alias as equivalent.  */
6694       if (!at_least_as_constrained (underlying, tmpl))
6695 	break;
6696 
6697       /* Alias is equivalent.  Strip it and repeat.  */
6698       tmpl = underlying;
6699     }
6700   top_break:;
6701 
6702   return tmpl;
6703 }
6704 
6705 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
6706    must be a reference-to-function or a pointer-to-function type, as specified
6707    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
6708    and check that the resulting function has external linkage.  */
6709 
6710 static tree
convert_nontype_argument_function(tree type,tree expr,tsubst_flags_t complain)6711 convert_nontype_argument_function (tree type, tree expr,
6712 				   tsubst_flags_t complain)
6713 {
6714   tree fns = expr;
6715   tree fn, fn_no_ptr;
6716   linkage_kind linkage;
6717 
6718   fn = instantiate_type (type, fns, tf_none);
6719   if (fn == error_mark_node)
6720     return error_mark_node;
6721 
6722   if (value_dependent_expression_p (fn))
6723     goto accept;
6724 
6725   fn_no_ptr = fn;
6726   if (REFERENCE_REF_P (fn_no_ptr))
6727     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6728   fn_no_ptr = strip_fnptr_conv (fn_no_ptr);
6729   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
6730     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6731   if (BASELINK_P (fn_no_ptr))
6732     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
6733 
6734   /* [temp.arg.nontype]/1
6735 
6736      A template-argument for a non-type, non-template template-parameter
6737      shall be one of:
6738      [...]
6739      -- the address of an object or function with external [C++11: or
6740         internal] linkage.  */
6741 
6742   STRIP_ANY_LOCATION_WRAPPER (fn_no_ptr);
6743   if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
6744     {
6745       if (complain & tf_error)
6746 	{
6747 	  location_t loc = cp_expr_loc_or_input_loc (expr);
6748 	  error_at (loc, "%qE is not a valid template argument for type %qT",
6749 		    expr, type);
6750 	  if (TYPE_PTR_P (type))
6751 	    inform (loc, "it must be the address of a function "
6752 		    "with external linkage");
6753 	  else
6754 	    inform (loc, "it must be the name of a function with "
6755 		    "external linkage");
6756 	}
6757       return NULL_TREE;
6758     }
6759 
6760   linkage = decl_linkage (fn_no_ptr);
6761   if (cxx_dialect >= cxx11 ? linkage == lk_none : linkage != lk_external)
6762     {
6763       if (complain & tf_error)
6764 	{
6765 	  location_t loc = cp_expr_loc_or_input_loc (expr);
6766 	  if (cxx_dialect >= cxx11)
6767 	    error_at (loc, "%qE is not a valid template argument for type "
6768 		      "%qT because %qD has no linkage",
6769 		      expr, type, fn_no_ptr);
6770 	  else
6771 	    error_at (loc, "%qE is not a valid template argument for type "
6772 		      "%qT because %qD does not have external linkage",
6773 		      expr, type, fn_no_ptr);
6774 	}
6775       return NULL_TREE;
6776     }
6777 
6778  accept:
6779   if (TYPE_REF_P (type))
6780     {
6781       if (REFERENCE_REF_P (fn))
6782 	fn = TREE_OPERAND (fn, 0);
6783       else
6784 	fn = build_address (fn);
6785     }
6786   if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (fn)))
6787     fn = build_nop (type, fn);
6788 
6789   return fn;
6790 }
6791 
6792 /* Subroutine of convert_nontype_argument.
6793    Check if EXPR of type TYPE is a valid pointer-to-member constant.
6794    Emit an error otherwise.  */
6795 
6796 static bool
check_valid_ptrmem_cst_expr(tree type,tree expr,tsubst_flags_t complain)6797 check_valid_ptrmem_cst_expr (tree type, tree expr,
6798 			     tsubst_flags_t complain)
6799 {
6800   tree orig_expr = expr;
6801   STRIP_NOPS (expr);
6802   if (null_ptr_cst_p (expr))
6803     return true;
6804   if (TREE_CODE (expr) == PTRMEM_CST
6805       && same_type_p (TYPE_PTRMEM_CLASS_TYPE (type),
6806 		      PTRMEM_CST_CLASS (expr)))
6807     return true;
6808   if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
6809     return true;
6810   if (processing_template_decl
6811       && TREE_CODE (expr) == ADDR_EXPR
6812       && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
6813     return true;
6814   if (complain & tf_error)
6815     {
6816       location_t loc = cp_expr_loc_or_input_loc (orig_expr);
6817       error_at (loc, "%qE is not a valid template argument for type %qT",
6818 		orig_expr, type);
6819       if (TREE_CODE (expr) != PTRMEM_CST)
6820 	inform (loc, "it must be a pointer-to-member of the form %<&X::Y%>");
6821       else
6822 	inform (loc, "because it is a member of %qT", PTRMEM_CST_CLASS (expr));
6823     }
6824   return false;
6825 }
6826 
6827 /* Returns TRUE iff the address of OP is value-dependent.
6828 
6829    14.6.2.4 [temp.dep.temp]:
6830    A non-integral non-type template-argument is dependent if its type is
6831    dependent or it has either of the following forms
6832      qualified-id
6833      & qualified-id
6834    and contains a nested-name-specifier which specifies a class-name that
6835    names a dependent type.
6836 
6837    We generalize this to just say that the address of a member of a
6838    dependent class is value-dependent; the above doesn't cover the
6839    address of a static data member named with an unqualified-id.  */
6840 
6841 static bool
has_value_dependent_address(tree op)6842 has_value_dependent_address (tree op)
6843 {
6844   STRIP_ANY_LOCATION_WRAPPER (op);
6845 
6846   /* We could use get_inner_reference here, but there's no need;
6847      this is only relevant for template non-type arguments, which
6848      can only be expressed as &id-expression.  */
6849   if (DECL_P (op))
6850     {
6851       tree ctx = CP_DECL_CONTEXT (op);
6852 
6853       if (TYPE_P (ctx) && dependent_type_p (ctx))
6854 	return true;
6855 
6856       if (VAR_P (op)
6857 	  && TREE_STATIC (op)
6858 	  && TREE_CODE (ctx) == FUNCTION_DECL
6859 	  && type_dependent_expression_p (ctx))
6860 	return true;
6861     }
6862 
6863   return false;
6864 }
6865 
6866 /* The next set of functions are used for providing helpful explanatory
6867    diagnostics for failed overload resolution.  Their messages should be
6868    indented by two spaces for consistency with the messages in
6869    call.cc  */
6870 
6871 static int
unify_success(bool)6872 unify_success (bool /*explain_p*/)
6873 {
6874   return 0;
6875 }
6876 
6877 /* Other failure functions should call this one, to provide a single function
6878    for setting a breakpoint on.  */
6879 
6880 static int
unify_invalid(bool)6881 unify_invalid (bool /*explain_p*/)
6882 {
6883   return 1;
6884 }
6885 
6886 static int
unify_parameter_deduction_failure(bool explain_p,tree parm)6887 unify_parameter_deduction_failure (bool explain_p, tree parm)
6888 {
6889   if (explain_p)
6890     inform (input_location,
6891 	    "  couldn%'t deduce template parameter %qD", parm);
6892   return unify_invalid (explain_p);
6893 }
6894 
6895 static int
unify_cv_qual_mismatch(bool explain_p,tree parm,tree arg)6896 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
6897 {
6898   if (explain_p)
6899     inform (input_location,
6900 	    "  types %qT and %qT have incompatible cv-qualifiers",
6901 	    parm, arg);
6902   return unify_invalid (explain_p);
6903 }
6904 
6905 static int
unify_type_mismatch(bool explain_p,tree parm,tree arg)6906 unify_type_mismatch (bool explain_p, tree parm, tree arg)
6907 {
6908   if (explain_p)
6909     inform (input_location, "  mismatched types %qT and %qT", parm, arg);
6910   return unify_invalid (explain_p);
6911 }
6912 
6913 static int
unify_parameter_pack_mismatch(bool explain_p,tree parm,tree arg)6914 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
6915 {
6916   if (explain_p)
6917     inform (input_location,
6918 	    "  template parameter %qD is not a parameter pack, but "
6919 	    "argument %qD is",
6920 	    parm, arg);
6921   return unify_invalid (explain_p);
6922 }
6923 
6924 static int
unify_ptrmem_cst_mismatch(bool explain_p,tree parm,tree arg)6925 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
6926 {
6927   if (explain_p)
6928     inform (input_location,
6929 	    "  template argument %qE does not match "
6930 	    "pointer-to-member constant %qE",
6931 	    arg, parm);
6932   return unify_invalid (explain_p);
6933 }
6934 
6935 static int
unify_expression_unequal(bool explain_p,tree parm,tree arg)6936 unify_expression_unequal (bool explain_p, tree parm, tree arg)
6937 {
6938   if (explain_p)
6939     inform (input_location, "  %qE is not equivalent to %qE", parm, arg);
6940   return unify_invalid (explain_p);
6941 }
6942 
6943 static int
unify_parameter_pack_inconsistent(bool explain_p,tree old_arg,tree new_arg)6944 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
6945 {
6946   if (explain_p)
6947     inform (input_location,
6948 	    "  inconsistent parameter pack deduction with %qT and %qT",
6949 	    old_arg, new_arg);
6950   return unify_invalid (explain_p);
6951 }
6952 
6953 static int
unify_inconsistency(bool explain_p,tree parm,tree first,tree second)6954 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
6955 {
6956   if (explain_p)
6957     {
6958       if (TYPE_P (parm))
6959 	inform (input_location,
6960 		"  deduced conflicting types for parameter %qT (%qT and %qT)",
6961 		parm, first, second);
6962       else
6963 	inform (input_location,
6964 		"  deduced conflicting values for non-type parameter "
6965 		"%qE (%qE and %qE)", parm, first, second);
6966     }
6967   return unify_invalid (explain_p);
6968 }
6969 
6970 static int
unify_vla_arg(bool explain_p,tree arg)6971 unify_vla_arg (bool explain_p, tree arg)
6972 {
6973   if (explain_p)
6974     inform (input_location,
6975 	    "  variable-sized array type %qT is not "
6976 	    "a valid template argument",
6977 	    arg);
6978   return unify_invalid (explain_p);
6979 }
6980 
6981 static int
unify_method_type_error(bool explain_p,tree arg)6982 unify_method_type_error (bool explain_p, tree arg)
6983 {
6984   if (explain_p)
6985     inform (input_location,
6986 	    "  member function type %qT is not a valid template argument",
6987 	    arg);
6988   return unify_invalid (explain_p);
6989 }
6990 
6991 static int
unify_arity(bool explain_p,int have,int wanted,bool least_p=false)6992 unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
6993 {
6994   if (explain_p)
6995     {
6996       if (least_p)
6997 	inform_n (input_location, wanted,
6998 		  "  candidate expects at least %d argument, %d provided",
6999 		  "  candidate expects at least %d arguments, %d provided",
7000 		  wanted, have);
7001       else
7002 	inform_n (input_location, wanted,
7003 		  "  candidate expects %d argument, %d provided",
7004 		  "  candidate expects %d arguments, %d provided",
7005 		  wanted, have);
7006     }
7007   return unify_invalid (explain_p);
7008 }
7009 
7010 static int
unify_too_many_arguments(bool explain_p,int have,int wanted)7011 unify_too_many_arguments (bool explain_p, int have, int wanted)
7012 {
7013   return unify_arity (explain_p, have, wanted);
7014 }
7015 
7016 static int
unify_too_few_arguments(bool explain_p,int have,int wanted,bool least_p=false)7017 unify_too_few_arguments (bool explain_p, int have, int wanted,
7018 			 bool least_p = false)
7019 {
7020   return unify_arity (explain_p, have, wanted, least_p);
7021 }
7022 
7023 static int
unify_arg_conversion(bool explain_p,tree to_type,tree from_type,tree arg)7024 unify_arg_conversion (bool explain_p, tree to_type,
7025 		      tree from_type, tree arg)
7026 {
7027   if (explain_p)
7028     inform (cp_expr_loc_or_input_loc (arg),
7029 	    "  cannot convert %qE (type %qT) to type %qT",
7030 	    arg, from_type, to_type);
7031   return unify_invalid (explain_p);
7032 }
7033 
7034 static int
unify_no_common_base(bool explain_p,enum template_base_result r,tree parm,tree arg)7035 unify_no_common_base (bool explain_p, enum template_base_result r,
7036 		      tree parm, tree arg)
7037 {
7038   if (explain_p)
7039     switch (r)
7040       {
7041       case tbr_ambiguous_baseclass:
7042 	inform (input_location, "  %qT is an ambiguous base class of %qT",
7043 		parm, arg);
7044 	break;
7045       default:
7046 	inform (input_location, "  %qT is not derived from %qT", arg, parm);
7047 	break;
7048       }
7049   return unify_invalid (explain_p);
7050 }
7051 
7052 static int
unify_inconsistent_template_template_parameters(bool explain_p)7053 unify_inconsistent_template_template_parameters (bool explain_p)
7054 {
7055   if (explain_p)
7056     inform (input_location,
7057 	    "  template parameters of a template template argument are "
7058 	    "inconsistent with other deduced template arguments");
7059   return unify_invalid (explain_p);
7060 }
7061 
7062 static int
unify_template_deduction_failure(bool explain_p,tree parm,tree arg)7063 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
7064 {
7065   if (explain_p)
7066     inform (input_location,
7067 	    "  cannot deduce a template for %qT from non-template type %qT",
7068 	    parm, arg);
7069   return unify_invalid (explain_p);
7070 }
7071 
7072 static int
unify_template_argument_mismatch(bool explain_p,tree parm,tree arg)7073 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
7074 {
7075   if (explain_p)
7076     inform (input_location,
7077 	    "  template argument %qE does not match %qE", arg, parm);
7078   return unify_invalid (explain_p);
7079 }
7080 
7081 /* True if T is a C++20 template parameter object to store the argument for a
7082    template parameter of class type.  */
7083 
7084 bool
template_parm_object_p(const_tree t)7085 template_parm_object_p (const_tree t)
7086 {
7087   return (TREE_CODE (t) == VAR_DECL && DECL_ARTIFICIAL (t) && DECL_NAME (t)
7088 	  && startswith (IDENTIFIER_POINTER (DECL_NAME (t)), "_ZTA"));
7089 }
7090 
7091 /* Subroutine of convert_nontype_argument, to check whether EXPR, as an
7092    argument for TYPE, points to an unsuitable object.
7093 
7094    Also adjust the type of the index in C++20 array subobject references.  */
7095 
7096 static bool
invalid_tparm_referent_p(tree type,tree expr,tsubst_flags_t complain)7097 invalid_tparm_referent_p (tree type, tree expr, tsubst_flags_t complain)
7098 {
7099   switch (TREE_CODE (expr))
7100     {
7101     CASE_CONVERT:
7102       return invalid_tparm_referent_p (type, TREE_OPERAND (expr, 0),
7103 				       complain);
7104 
7105     case TARGET_EXPR:
7106       return invalid_tparm_referent_p (type, TARGET_EXPR_INITIAL (expr),
7107 				       complain);
7108 
7109     case CONSTRUCTOR:
7110       {
7111 	for (auto &e: CONSTRUCTOR_ELTS (expr))
7112 	  if (invalid_tparm_referent_p (TREE_TYPE (e.value), e.value, complain))
7113 	    return true;
7114       }
7115       break;
7116 
7117     case ADDR_EXPR:
7118       {
7119 	tree decl = TREE_OPERAND (expr, 0);
7120 
7121 	if (cxx_dialect >= cxx20)
7122 	  while (TREE_CODE (decl) == COMPONENT_REF
7123 		 || TREE_CODE (decl) == ARRAY_REF)
7124 	    {
7125 	      tree &op = TREE_OPERAND (decl, 1);
7126 	      if (TREE_CODE (decl) == ARRAY_REF
7127 		  && TREE_CODE (op) == INTEGER_CST)
7128 		/* Canonicalize array offsets to ptrdiff_t; how they were
7129 		   written doesn't matter for subobject identity.  */
7130 		op = fold_convert (ptrdiff_type_node, op);
7131 	      decl = TREE_OPERAND (decl, 0);
7132 	    }
7133 
7134 	if (!VAR_P (decl))
7135 	  {
7136 	    if (complain & tf_error)
7137 	      error_at (cp_expr_loc_or_input_loc (expr),
7138 			"%qE is not a valid template argument of type %qT "
7139 			"because %qE is not a variable", expr, type, decl);
7140 	    return true;
7141 	  }
7142 	else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
7143 	  {
7144 	    if (complain & tf_error)
7145 	      error_at (cp_expr_loc_or_input_loc (expr),
7146 			"%qE is not a valid template argument of type %qT "
7147 			"in C++98 because %qD does not have external linkage",
7148 			expr, type, decl);
7149 	    return true;
7150 	  }
7151 	else if ((cxx_dialect >= cxx11 && cxx_dialect < cxx17)
7152 		 && decl_linkage (decl) == lk_none)
7153 	  {
7154 	    if (complain & tf_error)
7155 	      error_at (cp_expr_loc_or_input_loc (expr),
7156 			"%qE is not a valid template argument of type %qT "
7157 			"because %qD has no linkage", expr, type, decl);
7158 	    return true;
7159 	  }
7160 	/* C++17: For a non-type template-parameter of reference or pointer
7161 	   type, the value of the constant expression shall not refer to (or
7162 	   for a pointer type, shall not be the address of):
7163 	   * a subobject (4.5),
7164 	   * a temporary object (15.2),
7165 	   * a string literal (5.13.5),
7166 	   * the result of a typeid expression (8.2.8), or
7167 	   * a predefined __func__ variable (11.4.1).  */
7168 	else if (DECL_ARTIFICIAL (decl))
7169 	  {
7170 	    if (complain & tf_error)
7171 	      error ("the address of %qD is not a valid template argument",
7172 		     decl);
7173 	    return true;
7174 	  }
7175 	else if (cxx_dialect < cxx20
7176 		 && !(same_type_ignoring_top_level_qualifiers_p
7177 		      (strip_array_types (TREE_TYPE (type)),
7178 		       strip_array_types (TREE_TYPE (decl)))))
7179 	  {
7180 	    if (complain & tf_error)
7181 	      error ("the address of the %qT subobject of %qD is not a "
7182 		     "valid template argument", TREE_TYPE (type), decl);
7183 	    return true;
7184 	  }
7185 	else if (!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
7186 	  {
7187 	    if (complain & tf_error)
7188 	      error ("the address of %qD is not a valid template argument "
7189 		     "because it does not have static storage duration",
7190 		     decl);
7191 	    return true;
7192 	  }
7193       }
7194       break;
7195 
7196     default:
7197       if (!INDIRECT_TYPE_P (type))
7198 	/* We're only concerned about pointers and references here.  */;
7199       else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7200 	/* Null pointer values are OK in C++11.  */;
7201       else
7202 	{
7203 	  if (VAR_P (expr))
7204 	    {
7205 	      if (complain & tf_error)
7206 		error ("%qD is not a valid template argument "
7207 		       "because %qD is a variable, not the address of "
7208 		       "a variable", expr, expr);
7209 	      return true;
7210 	    }
7211 	  else
7212 	    {
7213 	      if (complain & tf_error)
7214 		error ("%qE is not a valid template argument for %qT "
7215 		       "because it is not the address of a variable",
7216 		       expr, type);
7217 	      return true;
7218 	    }
7219 	}
7220     }
7221   return false;
7222 
7223 }
7224 
7225 /* The template arguments corresponding to template parameter objects of types
7226    that contain pointers to members.  */
7227 
7228 static GTY(()) hash_map<tree, tree> *tparm_obj_values;
7229 
7230 /* Return a VAR_DECL for the C++20 template parameter object corresponding to
7231    template argument EXPR.  */
7232 
7233 static tree
get_template_parm_object(tree expr,tsubst_flags_t complain)7234 get_template_parm_object (tree expr, tsubst_flags_t complain)
7235 {
7236   if (TREE_CODE (expr) == TARGET_EXPR)
7237     expr = TARGET_EXPR_INITIAL (expr);
7238 
7239   if (!TREE_CONSTANT (expr))
7240     {
7241       if ((complain & tf_error)
7242 	  && require_rvalue_constant_expression (expr))
7243 	cxx_constant_value (expr);
7244       return error_mark_node;
7245     }
7246   if (invalid_tparm_referent_p (TREE_TYPE (expr), expr, complain))
7247     return error_mark_node;
7248 
7249   /* This is no longer a compound literal.  */
7250   gcc_assert (!TREE_HAS_CONSTRUCTOR (expr));
7251 
7252   tree name = mangle_template_parm_object (expr);
7253   tree decl = get_global_binding (name);
7254   if (decl)
7255     return decl;
7256 
7257   tree type = cp_build_qualified_type (TREE_TYPE (expr), TYPE_QUAL_CONST);
7258   decl = create_temporary_var (type);
7259   DECL_CONTEXT (decl) = NULL_TREE;
7260   TREE_STATIC (decl) = true;
7261   DECL_DECLARED_CONSTEXPR_P (decl) = true;
7262   TREE_READONLY (decl) = true;
7263   DECL_NAME (decl) = name;
7264   SET_DECL_ASSEMBLER_NAME (decl, name);
7265   comdat_linkage (decl);
7266 
7267   if (!zero_init_p (type))
7268     {
7269       /* If EXPR contains any PTRMEM_CST, they will get clobbered by
7270 	 lower_var_init before we're done mangling.  So store the original
7271 	 value elsewhere.  */
7272       tree copy = unshare_constructor (expr);
7273       hash_map_safe_put<hm_ggc> (tparm_obj_values, decl, copy);
7274     }
7275 
7276   pushdecl_top_level_and_finish (decl, expr);
7277 
7278   return decl;
7279 }
7280 
7281 /* Return the actual template argument corresponding to template parameter
7282    object VAR.  */
7283 
7284 tree
tparm_object_argument(tree var)7285 tparm_object_argument (tree var)
7286 {
7287   if (zero_init_p (TREE_TYPE (var)))
7288     return DECL_INITIAL (var);
7289   return *(tparm_obj_values->get (var));
7290 }
7291 
7292 /* Attempt to convert the non-type template parameter EXPR to the
7293    indicated TYPE.  If the conversion is successful, return the
7294    converted value.  If the conversion is unsuccessful, return
7295    NULL_TREE if we issued an error message, or error_mark_node if we
7296    did not.  We issue error messages for out-and-out bad template
7297    parameters, but not simply because the conversion failed, since we
7298    might be just trying to do argument deduction.  Both TYPE and EXPR
7299    must be non-dependent.
7300 
7301    The conversion follows the special rules described in
7302    [temp.arg.nontype], and it is much more strict than an implicit
7303    conversion.
7304 
7305    This function is called twice for each template argument (see
7306    lookup_template_class for a more accurate description of this
7307    problem). This means that we need to handle expressions which
7308    are not valid in a C++ source, but can be created from the
7309    first call (for instance, casts to perform conversions). These
7310    hacks can go away after we fix the double coercion problem.  */
7311 
7312 static tree
convert_nontype_argument(tree type,tree expr,tsubst_flags_t complain)7313 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
7314 {
7315   tree expr_type;
7316   location_t loc = cp_expr_loc_or_input_loc (expr);
7317 
7318   /* Detect immediately string literals as invalid non-type argument.
7319      This special-case is not needed for correctness (we would easily
7320      catch this later), but only to provide better diagnostic for this
7321      common user mistake. As suggested by DR 100, we do not mention
7322      linkage issues in the diagnostic as this is not the point.  */
7323   if (TREE_CODE (expr) == STRING_CST && !CLASS_TYPE_P (type))
7324     {
7325       if (complain & tf_error)
7326 	error ("%qE is not a valid template argument for type %qT "
7327 	       "because string literals can never be used in this context",
7328 	       expr, type);
7329       return NULL_TREE;
7330     }
7331 
7332   /* Add the ADDR_EXPR now for the benefit of
7333      value_dependent_expression_p.  */
7334   if (TYPE_PTROBV_P (type)
7335       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
7336     {
7337       expr = decay_conversion (expr, complain);
7338       if (expr == error_mark_node)
7339 	return error_mark_node;
7340     }
7341 
7342   /* If we are in a template, EXPR may be non-dependent, but still
7343      have a syntactic, rather than semantic, form.  For example, EXPR
7344      might be a SCOPE_REF, rather than the VAR_DECL to which the
7345      SCOPE_REF refers.  Preserving the qualifying scope is necessary
7346      so that access checking can be performed when the template is
7347      instantiated -- but here we need the resolved form so that we can
7348      convert the argument.  */
7349   bool non_dep = false;
7350   if (TYPE_REF_OBJ_P (type)
7351       && has_value_dependent_address (expr))
7352     /* If we want the address and it's value-dependent, don't fold.  */;
7353   else if (processing_template_decl
7354 	   && is_nondependent_constant_expression (expr))
7355     non_dep = true;
7356   if (error_operand_p (expr))
7357     return error_mark_node;
7358   expr_type = TREE_TYPE (expr);
7359 
7360   /* If the argument is non-dependent, perform any conversions in
7361      non-dependent context as well.  */
7362   processing_template_decl_sentinel s (non_dep);
7363   if (non_dep)
7364     expr = instantiate_non_dependent_expr_internal (expr, complain);
7365 
7366   bool val_dep_p = value_dependent_expression_p (expr);
7367   if (val_dep_p)
7368     expr = canonicalize_expr_argument (expr, complain);
7369   else
7370     STRIP_ANY_LOCATION_WRAPPER (expr);
7371 
7372   /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
7373      to a non-type argument of "nullptr".  */
7374   if (NULLPTR_TYPE_P (expr_type) && TYPE_PTR_OR_PTRMEM_P (type))
7375     expr = fold_simple (convert (type, expr));
7376 
7377   /* In C++11, integral or enumeration non-type template arguments can be
7378      arbitrary constant expressions.  Pointer and pointer to
7379      member arguments can be general constant expressions that evaluate
7380      to a null value, but otherwise still need to be of a specific form.  */
7381   if (cxx_dialect >= cxx11)
7382     {
7383       if (TREE_CODE (expr) == PTRMEM_CST && TYPE_PTRMEM_P (type))
7384 	/* A PTRMEM_CST is already constant, and a valid template
7385 	   argument for a parameter of pointer to member type, we just want
7386 	   to leave it in that form rather than lower it to a
7387 	   CONSTRUCTOR.  */;
7388       else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7389 	       || cxx_dialect >= cxx17)
7390 	{
7391 	  /* C++17: A template-argument for a non-type template-parameter shall
7392 	     be a converted constant expression (8.20) of the type of the
7393 	     template-parameter.  */
7394 	  expr = build_converted_constant_expr (type, expr, complain);
7395 	  if (expr == error_mark_node)
7396 	    /* Make sure we return NULL_TREE only if we have really issued
7397 	       an error, as described above.  */
7398 	    return (complain & tf_error) ? NULL_TREE : error_mark_node;
7399 	  else if (TREE_CODE (expr) == IMPLICIT_CONV_EXPR)
7400 	    {
7401 	      IMPLICIT_CONV_EXPR_NONTYPE_ARG (expr) = true;
7402 	      return expr;
7403 	    }
7404 	  expr = maybe_constant_value (expr, NULL_TREE,
7405 				       /*manifestly_const_eval=*/true);
7406 	  expr = convert_from_reference (expr);
7407 	  /* EXPR may have become value-dependent.  */
7408 	  val_dep_p = value_dependent_expression_p (expr);
7409 	}
7410       else if (TYPE_PTR_OR_PTRMEM_P (type))
7411 	{
7412 	  tree folded = maybe_constant_value (expr, NULL_TREE,
7413 					      /*manifestly_const_eval=*/true);
7414 	  if (TYPE_PTR_P (type) ? integer_zerop (folded)
7415 	      : null_member_pointer_value_p (folded))
7416 	    expr = folded;
7417 	}
7418     }
7419 
7420   if (TYPE_REF_P (type))
7421     expr = mark_lvalue_use (expr);
7422   else
7423     expr = mark_rvalue_use (expr);
7424 
7425   /* HACK: Due to double coercion, we can get a
7426      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
7427      which is the tree that we built on the first call (see
7428      below when coercing to reference to object or to reference to
7429      function). We just strip everything and get to the arg.
7430      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
7431      for examples.  */
7432   if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
7433     {
7434       /* Check this before we strip *& to avoid redundancy.  */
7435       if (!mark_single_function (expr, complain))
7436 	return error_mark_node;
7437 
7438       tree probe_type, probe = expr;
7439       if (REFERENCE_REF_P (probe))
7440 	probe = TREE_OPERAND (probe, 0);
7441       probe_type = TREE_TYPE (probe);
7442       if (TREE_CODE (probe) == NOP_EXPR)
7443 	{
7444 	  /* ??? Maybe we could use convert_from_reference here, but we
7445 	     would need to relax its constraints because the NOP_EXPR
7446 	     could actually change the type to something more cv-qualified,
7447 	     and this is not folded by convert_from_reference.  */
7448 	  tree addr = TREE_OPERAND (probe, 0);
7449 	  if (TYPE_REF_P (probe_type)
7450 	      && TREE_CODE (addr) == ADDR_EXPR
7451 	      && TYPE_PTR_P (TREE_TYPE (addr))
7452 	      && (same_type_ignoring_top_level_qualifiers_p
7453 		  (TREE_TYPE (probe_type),
7454 		   TREE_TYPE (TREE_TYPE (addr)))))
7455 	    {
7456 	      expr = TREE_OPERAND (addr, 0);
7457 	      expr_type = TREE_TYPE (probe_type);
7458 	    }
7459 	}
7460     }
7461 
7462   /* [temp.arg.nontype]/5, bullet 1
7463 
7464      For a non-type template-parameter of integral or enumeration type,
7465      integral promotions (_conv.prom_) and integral conversions
7466      (_conv.integral_) are applied.  */
7467   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7468       || TREE_CODE (type) == REAL_TYPE)
7469     {
7470       if (cxx_dialect < cxx11)
7471 	{
7472 	  tree t = build_converted_constant_expr (type, expr, complain);
7473 	  t = maybe_constant_value (t);
7474 	  if (t != error_mark_node)
7475 	    expr = t;
7476 	}
7477 
7478       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
7479 	return error_mark_node;
7480 
7481       /* Notice that there are constant expressions like '4 % 0' which
7482 	 do not fold into integer constants.  */
7483       if (!CONSTANT_CLASS_P (expr) && !val_dep_p)
7484 	{
7485 	  if (complain & tf_error)
7486 	    {
7487 	      int errs = errorcount, warns = warningcount + werrorcount;
7488 	      if (!require_potential_constant_expression (expr))
7489 		expr = error_mark_node;
7490 	      else
7491 		expr = cxx_constant_value (expr);
7492 	      if (errorcount > errs || warningcount + werrorcount > warns)
7493 		inform (loc, "in template argument for type %qT", type);
7494 	      if (expr == error_mark_node)
7495 		return NULL_TREE;
7496 	      /* else cxx_constant_value complained but gave us
7497 		 a real constant, so go ahead.  */
7498 	      if (!CONSTANT_CLASS_P (expr))
7499 		{
7500 		  /* Some assemble time constant expressions like
7501 		     (intptr_t)&&lab1 - (intptr_t)&&lab2 or
7502 		     4 + (intptr_t)&&var satisfy reduced_constant_expression_p
7503 		     as we can emit them into .rodata initializers of
7504 		     variables, yet they can't fold into an INTEGER_CST at
7505 		     compile time.  Refuse them here.  */
7506 		  gcc_checking_assert (reduced_constant_expression_p (expr));
7507 		  error_at (loc, "template argument %qE for type %qT not "
7508 				 "a compile-time constant", expr, type);
7509 		  return NULL_TREE;
7510 		}
7511 	    }
7512 	  else
7513 	    return NULL_TREE;
7514 	}
7515 
7516       /* Avoid typedef problems.  */
7517       if (TREE_TYPE (expr) != type)
7518 	expr = fold_convert (type, expr);
7519     }
7520   /* [temp.arg.nontype]/5, bullet 2
7521 
7522      For a non-type template-parameter of type pointer to object,
7523      qualification conversions (_conv.qual_) and the array-to-pointer
7524      conversion (_conv.array_) are applied.  */
7525   else if (TYPE_PTROBV_P (type))
7526     {
7527       tree decayed = expr;
7528 
7529       /* Look through any NOP_EXPRs around an ADDR_EXPR, whether they come from
7530 	 decay_conversion or an explicit cast.  If it's a problematic cast,
7531 	 we'll complain about it below.  */
7532       if (TREE_CODE (expr) == NOP_EXPR)
7533 	{
7534 	  tree probe = expr;
7535 	  STRIP_NOPS (probe);
7536 	  if (TREE_CODE (probe) == ADDR_EXPR
7537 	      && TYPE_PTR_P (TREE_TYPE (probe)))
7538 	    {
7539 	      expr = probe;
7540 	      expr_type = TREE_TYPE (expr);
7541 	    }
7542 	}
7543 
7544       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
7545 
7546 	 A template-argument for a non-type, non-template template-parameter
7547 	 shall be one of: [...]
7548 
7549 	 -- the name of a non-type template-parameter;
7550 	 -- the address of an object or function with external linkage, [...]
7551 	    expressed as "& id-expression" where the & is optional if the name
7552 	    refers to a function or array, or if the corresponding
7553 	    template-parameter is a reference.
7554 
7555 	Here, we do not care about functions, as they are invalid anyway
7556 	for a parameter of type pointer-to-object.  */
7557 
7558       if (val_dep_p)
7559 	/* Non-type template parameters are OK.  */
7560 	;
7561       else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7562 	/* Null pointer values are OK in C++11.  */;
7563       else if (TREE_CODE (expr) != ADDR_EXPR
7564 	       && !INDIRECT_TYPE_P (expr_type))
7565 	/* Other values, like integer constants, might be valid
7566 	   non-type arguments of some other type.  */
7567 	return error_mark_node;
7568       else if (invalid_tparm_referent_p (type, expr, complain))
7569 	return NULL_TREE;
7570 
7571       expr = decayed;
7572 
7573       expr = perform_qualification_conversions (type, expr);
7574       if (expr == error_mark_node)
7575 	return error_mark_node;
7576     }
7577   /* [temp.arg.nontype]/5, bullet 3
7578 
7579      For a non-type template-parameter of type reference to object, no
7580      conversions apply. The type referred to by the reference may be more
7581      cv-qualified than the (otherwise identical) type of the
7582      template-argument. The template-parameter is bound directly to the
7583      template-argument, which must be an lvalue.  */
7584   else if (TYPE_REF_OBJ_P (type))
7585     {
7586       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
7587 						      expr_type))
7588 	return error_mark_node;
7589 
7590       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
7591 	{
7592 	  if (complain & tf_error)
7593 	    error ("%qE is not a valid template argument for type %qT "
7594 		   "because of conflicts in cv-qualification", expr, type);
7595 	  return NULL_TREE;
7596 	}
7597 
7598       if (!lvalue_p (expr))
7599 	{
7600 	  if (complain & tf_error)
7601 	    error ("%qE is not a valid template argument for type %qT "
7602 		   "because it is not an lvalue", expr, type);
7603 	  return NULL_TREE;
7604 	}
7605 
7606       /* [temp.arg.nontype]/1
7607 
7608 	 A template-argument for a non-type, non-template template-parameter
7609 	 shall be one of: [...]
7610 
7611 	 -- the address of an object or function with external linkage.  */
7612       if (INDIRECT_REF_P (expr)
7613 	  && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
7614 	{
7615 	  expr = TREE_OPERAND (expr, 0);
7616 	  if (DECL_P (expr))
7617 	    {
7618 	      if (complain & tf_error)
7619 		error ("%q#D is not a valid template argument for type %qT "
7620 		       "because a reference variable does not have a constant "
7621 		       "address", expr, type);
7622 	      return NULL_TREE;
7623 	    }
7624 	}
7625 
7626       if (TYPE_REF_OBJ_P (TREE_TYPE (expr)) && val_dep_p)
7627 	/* OK, dependent reference.  We don't want to ask whether a DECL is
7628 	   itself value-dependent, since what we want here is its address.  */;
7629       else
7630 	{
7631 	  expr = build_address (expr);
7632 
7633 	  if (invalid_tparm_referent_p (type, expr, complain))
7634 	    return NULL_TREE;
7635 	}
7636 
7637       if (!same_type_p (type, TREE_TYPE (expr)))
7638 	expr = build_nop (type, expr);
7639     }
7640   /* [temp.arg.nontype]/5, bullet 4
7641 
7642      For a non-type template-parameter of type pointer to function, only
7643      the function-to-pointer conversion (_conv.func_) is applied. If the
7644      template-argument represents a set of overloaded functions (or a
7645      pointer to such), the matching function is selected from the set
7646      (_over.over_).  */
7647   else if (TYPE_PTRFN_P (type))
7648     {
7649       /* If the argument is a template-id, we might not have enough
7650 	 context information to decay the pointer.  */
7651       if (!type_unknown_p (expr_type))
7652 	{
7653 	  expr = decay_conversion (expr, complain);
7654 	  if (expr == error_mark_node)
7655 	    return error_mark_node;
7656 	}
7657 
7658       if (cxx_dialect >= cxx11 && integer_zerop (expr))
7659 	/* Null pointer values are OK in C++11.  */
7660 	return perform_qualification_conversions (type, expr);
7661 
7662       expr = convert_nontype_argument_function (type, expr, complain);
7663       if (!expr || expr == error_mark_node)
7664 	return expr;
7665     }
7666   /* [temp.arg.nontype]/5, bullet 5
7667 
7668      For a non-type template-parameter of type reference to function, no
7669      conversions apply. If the template-argument represents a set of
7670      overloaded functions, the matching function is selected from the set
7671      (_over.over_).  */
7672   else if (TYPE_REFFN_P (type))
7673     {
7674       if (TREE_CODE (expr) == ADDR_EXPR)
7675 	{
7676 	  if (complain & tf_error)
7677 	    {
7678 	      error ("%qE is not a valid template argument for type %qT "
7679 		     "because it is a pointer", expr, type);
7680 	      inform (input_location, "try using %qE instead",
7681 		      TREE_OPERAND (expr, 0));
7682 	    }
7683 	  return NULL_TREE;
7684 	}
7685 
7686       expr = convert_nontype_argument_function (type, expr, complain);
7687       if (!expr || expr == error_mark_node)
7688 	return expr;
7689     }
7690   /* [temp.arg.nontype]/5, bullet 6
7691 
7692      For a non-type template-parameter of type pointer to member function,
7693      no conversions apply. If the template-argument represents a set of
7694      overloaded member functions, the matching member function is selected
7695      from the set (_over.over_).  */
7696   else if (TYPE_PTRMEMFUNC_P (type))
7697     {
7698       expr = instantiate_type (type, expr, tf_none);
7699       if (expr == error_mark_node)
7700 	return error_mark_node;
7701 
7702       /* [temp.arg.nontype] bullet 1 says the pointer to member
7703          expression must be a pointer-to-member constant.  */
7704       if (!val_dep_p
7705 	  && !check_valid_ptrmem_cst_expr (type, expr, complain))
7706 	return NULL_TREE;
7707 
7708       /* Repeated conversion can't deal with a conversion that turns PTRMEM_CST
7709 	 into a CONSTRUCTOR, so build up a new PTRMEM_CST instead.  */
7710       if (fnptr_conv_p (type, TREE_TYPE (expr)))
7711 	expr = make_ptrmem_cst (type, PTRMEM_CST_MEMBER (expr));
7712     }
7713   /* [temp.arg.nontype]/5, bullet 7
7714 
7715      For a non-type template-parameter of type pointer to data member,
7716      qualification conversions (_conv.qual_) are applied.  */
7717   else if (TYPE_PTRDATAMEM_P (type))
7718     {
7719       /* [temp.arg.nontype] bullet 1 says the pointer to member
7720          expression must be a pointer-to-member constant.  */
7721       if (!val_dep_p
7722 	  && !check_valid_ptrmem_cst_expr (type, expr, complain))
7723 	return NULL_TREE;
7724 
7725       expr = perform_qualification_conversions (type, expr);
7726       if (expr == error_mark_node)
7727 	return expr;
7728     }
7729   else if (NULLPTR_TYPE_P (type))
7730     {
7731       if (!NULLPTR_TYPE_P (TREE_TYPE (expr)))
7732 	{
7733 	  if (complain & tf_error)
7734 	    error ("%qE is not a valid template argument for type %qT "
7735 		   "because it is of type %qT", expr, type, TREE_TYPE (expr));
7736 	  return NULL_TREE;
7737 	}
7738       return expr;
7739     }
7740   else if (CLASS_TYPE_P (type))
7741     {
7742       /* Replace the argument with a reference to the corresponding template
7743 	 parameter object.  */
7744       if (!val_dep_p)
7745 	expr = get_template_parm_object (expr, complain);
7746       if (expr == error_mark_node)
7747 	return NULL_TREE;
7748     }
7749   /* A template non-type parameter must be one of the above.  */
7750   else
7751     gcc_unreachable ();
7752 
7753   /* Sanity check: did we actually convert the argument to the
7754      right type?  */
7755   gcc_assert (same_type_ignoring_top_level_qualifiers_p
7756 	      (type, TREE_TYPE (expr)));
7757   return convert_from_reference (expr);
7758 }
7759 
7760 /* Subroutine of coerce_template_template_parms, which returns 1 if
7761    PARM_PARM and ARG_PARM match using the rule for the template
7762    parameters of template template parameters. Both PARM and ARG are
7763    template parameters; the rest of the arguments are the same as for
7764    coerce_template_template_parms.
7765  */
7766 static int
coerce_template_template_parm(tree parm,tree arg,tsubst_flags_t complain,tree in_decl,tree outer_args)7767 coerce_template_template_parm (tree parm,
7768                               tree arg,
7769                               tsubst_flags_t complain,
7770                               tree in_decl,
7771                               tree outer_args)
7772 {
7773   if (arg == NULL_TREE || error_operand_p (arg)
7774       || parm == NULL_TREE || error_operand_p (parm))
7775     return 0;
7776 
7777   if (TREE_CODE (arg) != TREE_CODE (parm))
7778     return 0;
7779 
7780   switch (TREE_CODE (parm))
7781     {
7782     case TEMPLATE_DECL:
7783       /* We encounter instantiations of templates like
7784 	 template <template <template <class> class> class TT>
7785 	 class C;  */
7786       {
7787 	tree parmparm = DECL_TEMPLATE_PARMS (parm);
7788 	tree argparm = DECL_TEMPLATE_PARMS (arg);
7789 
7790 	if (!coerce_template_template_parms
7791 	    (parmparm, argparm, complain, in_decl, outer_args))
7792 	  return 0;
7793       }
7794       /* Fall through.  */
7795 
7796     case TYPE_DECL:
7797       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
7798 	  && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7799 	/* Argument is a parameter pack but parameter is not.  */
7800 	return 0;
7801       break;
7802 
7803     case PARM_DECL:
7804       /* The tsubst call is used to handle cases such as
7805 
7806            template <int> class C {};
7807 	   template <class T, template <T> class TT> class D {};
7808 	   D<int, C> d;
7809 
7810 	 i.e. the parameter list of TT depends on earlier parameters.  */
7811       if (!uses_template_parms (TREE_TYPE (arg)))
7812 	{
7813 	  tree t = tsubst (TREE_TYPE (parm), outer_args, complain, in_decl);
7814 	  if (!uses_template_parms (t)
7815 	      && !same_type_p (t, TREE_TYPE (arg)))
7816 	    return 0;
7817 	}
7818 
7819       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
7820 	  && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7821 	/* Argument is a parameter pack but parameter is not.  */
7822 	return 0;
7823 
7824       break;
7825 
7826     default:
7827       gcc_unreachable ();
7828     }
7829 
7830   return 1;
7831 }
7832 
7833 /* Coerce template argument list ARGLIST for use with template
7834    template-parameter TEMPL.  */
7835 
7836 static tree
coerce_template_args_for_ttp(tree templ,tree arglist,tsubst_flags_t complain)7837 coerce_template_args_for_ttp (tree templ, tree arglist,
7838 			      tsubst_flags_t complain)
7839 {
7840   /* Consider an example where a template template parameter declared as
7841 
7842      template <class T, class U = std::allocator<T> > class TT
7843 
7844      The template parameter level of T and U are one level larger than
7845      of TT.  To proper process the default argument of U, say when an
7846      instantiation `TT<int>' is seen, we need to build the full
7847      arguments containing {int} as the innermost level.  Outer levels,
7848      available when not appearing as default template argument, can be
7849      obtained from the arguments of the enclosing template.
7850 
7851      Suppose that TT is later substituted with std::vector.  The above
7852      instantiation is `TT<int, std::allocator<T> >' with TT at
7853      level 1, and T at level 2, while the template arguments at level 1
7854      becomes {std::vector} and the inner level 2 is {int}.  */
7855 
7856   tree outer = DECL_CONTEXT (templ);
7857   if (outer)
7858     outer = generic_targs_for (outer);
7859   else if (current_template_parms)
7860     {
7861       /* This is an argument of the current template, so we haven't set
7862 	 DECL_CONTEXT yet.  */
7863       tree relevant_template_parms;
7864 
7865       /* Parameter levels that are greater than the level of the given
7866 	 template template parm are irrelevant.  */
7867       relevant_template_parms = current_template_parms;
7868       while (TMPL_PARMS_DEPTH (relevant_template_parms)
7869 	     != TEMPLATE_TYPE_LEVEL (TREE_TYPE (templ)))
7870 	relevant_template_parms = TREE_CHAIN (relevant_template_parms);
7871 
7872       outer = template_parms_to_args (relevant_template_parms);
7873     }
7874 
7875   if (outer)
7876     arglist = add_to_template_args (outer, arglist);
7877 
7878   tree parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7879   return coerce_template_parms (parmlist, arglist, templ,
7880 				complain,
7881 				/*require_all_args=*/true,
7882 				/*use_default_args=*/true);
7883 }
7884 
7885 /* A cache of template template parameters with match-all default
7886    arguments.  */
7887 static GTY((deletable)) hash_map<tree,tree> *defaulted_ttp_cache;
7888 
7889 /* T is a bound template template-parameter.  Copy its arguments into default
7890    arguments of the template template-parameter's template parameters.  */
7891 
7892 static tree
add_defaults_to_ttp(tree otmpl)7893 add_defaults_to_ttp (tree otmpl)
7894 {
7895   if (tree *c = hash_map_safe_get (defaulted_ttp_cache, otmpl))
7896     return *c;
7897 
7898   tree ntmpl = copy_node (otmpl);
7899 
7900   tree ntype = copy_node (TREE_TYPE (otmpl));
7901   TYPE_STUB_DECL (ntype) = TYPE_NAME (ntype) = ntmpl;
7902   TYPE_MAIN_VARIANT (ntype) = ntype;
7903   TYPE_POINTER_TO (ntype) = TYPE_REFERENCE_TO (ntype) = NULL_TREE;
7904   TYPE_NAME (ntype) = ntmpl;
7905   SET_TYPE_STRUCTURAL_EQUALITY (ntype);
7906 
7907   tree idx = TEMPLATE_TYPE_PARM_INDEX (ntype)
7908     = copy_node (TEMPLATE_TYPE_PARM_INDEX (ntype));
7909   TEMPLATE_PARM_DECL (idx) = ntmpl;
7910   TREE_TYPE (ntmpl) = TREE_TYPE (idx) = ntype;
7911 
7912   tree oparms = DECL_TEMPLATE_PARMS (otmpl);
7913   tree parms = DECL_TEMPLATE_PARMS (ntmpl) = copy_node (oparms);
7914   TREE_CHAIN (parms) = TREE_CHAIN (oparms);
7915   tree vec = TREE_VALUE (parms) = copy_node (TREE_VALUE (parms));
7916   for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
7917     {
7918       tree o = TREE_VEC_ELT (vec, i);
7919       if (!template_parameter_pack_p (TREE_VALUE (o)))
7920 	{
7921 	  tree n = TREE_VEC_ELT (vec, i) = copy_node (o);
7922 	  TREE_PURPOSE (n) = any_targ_node;
7923 	}
7924     }
7925 
7926   hash_map_safe_put<hm_ggc> (defaulted_ttp_cache, otmpl, ntmpl);
7927   return ntmpl;
7928 }
7929 
7930 /* ARG is a bound potential template template-argument, and PARGS is a list
7931    of arguments for the corresponding template template-parameter.  Adjust
7932    PARGS as appropriate for application to ARG's template, and if ARG is a
7933    BOUND_TEMPLATE_TEMPLATE_PARM, possibly adjust it to add default template
7934    arguments to the template template parameter.  */
7935 
7936 static tree
coerce_ttp_args_for_tta(tree & arg,tree pargs,tsubst_flags_t complain)7937 coerce_ttp_args_for_tta (tree& arg, tree pargs, tsubst_flags_t complain)
7938 {
7939   ++processing_template_decl;
7940   tree arg_tmpl = TYPE_TI_TEMPLATE (arg);
7941   if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
7942     {
7943       /* When comparing two template template-parameters in partial ordering,
7944 	 rewrite the one currently being used as an argument to have default
7945 	 arguments for all parameters.  */
7946       arg_tmpl = add_defaults_to_ttp (arg_tmpl);
7947       pargs = coerce_template_args_for_ttp (arg_tmpl, pargs, complain);
7948       if (pargs != error_mark_node)
7949 	arg = bind_template_template_parm (TREE_TYPE (arg_tmpl),
7950 					   TYPE_TI_ARGS (arg));
7951     }
7952   else
7953     {
7954       tree aparms
7955 	= INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (arg_tmpl));
7956       pargs = coerce_template_parms (aparms, pargs, arg_tmpl, complain,
7957 				       /*require_all*/true,
7958 				       /*use_default*/true);
7959     }
7960   --processing_template_decl;
7961   return pargs;
7962 }
7963 
7964 /* Subroutine of unify for the case when PARM is a
7965    BOUND_TEMPLATE_TEMPLATE_PARM.  */
7966 
7967 static int
unify_bound_ttp_args(tree tparms,tree targs,tree parm,tree & arg,bool explain_p)7968 unify_bound_ttp_args (tree tparms, tree targs, tree parm, tree& arg,
7969 		      bool explain_p)
7970 {
7971   tree parmvec = TYPE_TI_ARGS (parm);
7972   tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
7973 
7974   /* The template template parm might be variadic and the argument
7975      not, so flatten both argument lists.  */
7976   parmvec = expand_template_argument_pack (parmvec);
7977   argvec = expand_template_argument_pack (argvec);
7978 
7979   if (flag_new_ttp)
7980     {
7981       /* In keeping with P0522R0, adjust P's template arguments
7982 	 to apply to A's template; then flatten it again.  */
7983       tree nparmvec = coerce_ttp_args_for_tta (arg, parmvec, tf_none);
7984       nparmvec = expand_template_argument_pack (nparmvec);
7985 
7986       if (unify (tparms, targs, nparmvec, argvec,
7987 		 UNIFY_ALLOW_NONE, explain_p))
7988 	return 1;
7989 
7990       /* If the P0522 adjustment eliminated a pack expansion, deduce
7991 	 empty packs.  */
7992       if (flag_new_ttp
7993 	  && TREE_VEC_LENGTH (nparmvec) < TREE_VEC_LENGTH (parmvec)
7994 	  && unify_pack_expansion (tparms, targs, parmvec, argvec,
7995 				   DEDUCE_EXACT, /*sub*/true, explain_p))
7996 	return 1;
7997     }
7998   else
7999     {
8000       /* Deduce arguments T, i from TT<T> or TT<i>.
8001 	 We check each element of PARMVEC and ARGVEC individually
8002 	 rather than the whole TREE_VEC since they can have
8003 	 different number of elements, which is allowed under N2555.  */
8004 
8005       int len = TREE_VEC_LENGTH (parmvec);
8006 
8007       /* Check if the parameters end in a pack, making them
8008 	 variadic.  */
8009       int parm_variadic_p = 0;
8010       if (len > 0
8011 	  && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
8012 	parm_variadic_p = 1;
8013 
8014       for (int i = 0; i < len - parm_variadic_p; ++i)
8015 	/* If the template argument list of P contains a pack
8016 	   expansion that is not the last template argument, the
8017 	   entire template argument list is a non-deduced
8018 	   context.  */
8019 	if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
8020 	  return unify_success (explain_p);
8021 
8022       if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
8023 	return unify_too_few_arguments (explain_p,
8024 					TREE_VEC_LENGTH (argvec), len);
8025 
8026       for (int i = 0; i < len - parm_variadic_p; ++i)
8027 	if (unify (tparms, targs,
8028 		   TREE_VEC_ELT (parmvec, i),
8029 		   TREE_VEC_ELT (argvec, i),
8030 		   UNIFY_ALLOW_NONE, explain_p))
8031 	  return 1;
8032 
8033       if (parm_variadic_p
8034 	  && unify_pack_expansion (tparms, targs,
8035 				   parmvec, argvec,
8036 				   DEDUCE_EXACT,
8037 				   /*subr=*/true, explain_p))
8038 	return 1;
8039     }
8040 
8041   return 0;
8042 }
8043 
8044 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
8045    template template parameters.  Both PARM_PARMS and ARG_PARMS are
8046    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
8047    or PARM_DECL.
8048 
8049    Consider the example:
8050      template <class T> class A;
8051      template<template <class U> class TT> class B;
8052 
8053    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
8054    the parameters to A, and OUTER_ARGS contains A.  */
8055 
8056 static int
coerce_template_template_parms(tree parm_parms_full,tree arg_parms_full,tsubst_flags_t complain,tree in_decl,tree outer_args)8057 coerce_template_template_parms (tree parm_parms_full,
8058 				tree arg_parms_full,
8059 				tsubst_flags_t complain,
8060 				tree in_decl,
8061 				tree outer_args)
8062 {
8063   int nparms, nargs, i;
8064   tree parm, arg;
8065   int variadic_p = 0;
8066 
8067   tree parm_parms = INNERMOST_TEMPLATE_PARMS (parm_parms_full);
8068   tree arg_parms = INNERMOST_TEMPLATE_PARMS (arg_parms_full);
8069 
8070   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
8071   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
8072 
8073   nparms = TREE_VEC_LENGTH (parm_parms);
8074   nargs = TREE_VEC_LENGTH (arg_parms);
8075 
8076   if (flag_new_ttp)
8077     {
8078       /* P0522R0: A template template-parameter P is at least as specialized as
8079 	 a template template-argument A if, given the following rewrite to two
8080 	 function templates, the function template corresponding to P is at
8081 	 least as specialized as the function template corresponding to A
8082 	 according to the partial ordering rules for function templates
8083 	 ([temp.func.order]). Given an invented class template X with the
8084 	 template parameter list of A (including default arguments):
8085 
8086 	 * Each of the two function templates has the same template parameters,
8087 	 respectively, as P or A.
8088 
8089 	 * Each function template has a single function parameter whose type is
8090 	 a specialization of X with template arguments corresponding to the
8091 	 template parameters from the respective function template where, for
8092 	 each template parameter PP in the template parameter list of the
8093 	 function template, a corresponding template argument AA is formed. If
8094 	 PP declares a parameter pack, then AA is the pack expansion
8095 	 PP... ([temp.variadic]); otherwise, AA is the id-expression PP.
8096 
8097 	 If the rewrite produces an invalid type, then P is not at least as
8098 	 specialized as A.  */
8099 
8100       /* So coerce P's args to apply to A's parms, and then deduce between A's
8101 	 args and the converted args.  If that succeeds, A is at least as
8102 	 specialized as P, so they match.*/
8103       processing_template_decl_sentinel ptds (/*reset*/false);
8104       ++processing_template_decl;
8105 
8106       tree pargs = template_parms_level_to_args (parm_parms);
8107 
8108       /* PARM, and thus the context in which we are passing ARG to it, may be
8109 	 at a deeper level than ARG; when trying to coerce to ARG_PARMS, we
8110 	 want to provide the right number of levels, so we reduce the number of
8111 	 levels in OUTER_ARGS before prepending them.  This is most important
8112 	 when ARG is a namespace-scope template, as in alias-decl-ttp2.C.
8113 
8114 	 ARG might also be deeper than PARM (ttp23).  In that case, we include
8115 	 all of OUTER_ARGS.  The missing levels seem potentially problematic,
8116 	 but I can't come up with a testcase that breaks.  */
8117       if (int arg_outer_levs = TMPL_PARMS_DEPTH (arg_parms_full) - 1)
8118 	{
8119 	  auto x = make_temp_override (TREE_VEC_LENGTH (outer_args));
8120 	  if (TMPL_ARGS_DEPTH (outer_args) > arg_outer_levs)
8121 	    TREE_VEC_LENGTH (outer_args) = arg_outer_levs;
8122 	  pargs = add_to_template_args (outer_args, pargs);
8123 	}
8124 
8125       pargs = coerce_template_parms (arg_parms, pargs, NULL_TREE, tf_none,
8126 				     /*require_all*/true, /*use_default*/true);
8127       if (pargs != error_mark_node)
8128 	{
8129 	  tree targs = make_tree_vec (nargs);
8130 	  tree aargs = template_parms_level_to_args (arg_parms);
8131 	  if (!unify (arg_parms, targs, aargs, pargs, UNIFY_ALLOW_NONE,
8132 		      /*explain*/false))
8133 	    return 1;
8134 	}
8135     }
8136 
8137   /* Determine whether we have a parameter pack at the end of the
8138      template template parameter's template parameter list.  */
8139   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
8140     {
8141       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
8142 
8143       if (error_operand_p (parm))
8144 	return 0;
8145 
8146       switch (TREE_CODE (parm))
8147         {
8148         case TEMPLATE_DECL:
8149         case TYPE_DECL:
8150           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
8151             variadic_p = 1;
8152           break;
8153 
8154         case PARM_DECL:
8155           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
8156             variadic_p = 1;
8157           break;
8158 
8159         default:
8160           gcc_unreachable ();
8161         }
8162     }
8163 
8164   if (nargs != nparms
8165       && !(variadic_p && nargs >= nparms - 1))
8166     return 0;
8167 
8168   /* Check all of the template parameters except the parameter pack at
8169      the end (if any).  */
8170   for (i = 0; i < nparms - variadic_p; ++i)
8171     {
8172       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
8173           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
8174         continue;
8175 
8176       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
8177       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
8178 
8179       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
8180                                           outer_args))
8181 	return 0;
8182 
8183     }
8184 
8185   if (variadic_p)
8186     {
8187       /* Check each of the template parameters in the template
8188 	 argument against the template parameter pack at the end of
8189 	 the template template parameter.  */
8190       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
8191 	return 0;
8192 
8193       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
8194 
8195       for (; i < nargs; ++i)
8196         {
8197           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
8198             continue;
8199 
8200           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
8201 
8202           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
8203                                               outer_args))
8204             return 0;
8205         }
8206     }
8207 
8208   return 1;
8209 }
8210 
8211 /* Verifies that the deduced template arguments (in TARGS) for the
8212    template template parameters (in TPARMS) represent valid bindings,
8213    by comparing the template parameter list of each template argument
8214    to the template parameter list of its corresponding template
8215    template parameter, in accordance with DR150. This
8216    routine can only be called after all template arguments have been
8217    deduced. It will return TRUE if all of the template template
8218    parameter bindings are okay, FALSE otherwise.  */
8219 bool
template_template_parm_bindings_ok_p(tree tparms,tree targs)8220 template_template_parm_bindings_ok_p (tree tparms, tree targs)
8221 {
8222   int i, ntparms = TREE_VEC_LENGTH (tparms);
8223   bool ret = true;
8224 
8225   /* We're dealing with template parms in this process.  */
8226   ++processing_template_decl;
8227 
8228   targs = INNERMOST_TEMPLATE_ARGS (targs);
8229 
8230   for (i = 0; i < ntparms; ++i)
8231     {
8232       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
8233       tree targ = TREE_VEC_ELT (targs, i);
8234 
8235       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
8236 	{
8237 	  tree packed_args = NULL_TREE;
8238 	  int idx, len = 1;
8239 
8240 	  if (ARGUMENT_PACK_P (targ))
8241 	    {
8242 	      /* Look inside the argument pack.  */
8243 	      packed_args = ARGUMENT_PACK_ARGS (targ);
8244 	      len = TREE_VEC_LENGTH (packed_args);
8245 	    }
8246 
8247 	  for (idx = 0; idx < len; ++idx)
8248 	    {
8249 	      tree targ_parms = NULL_TREE;
8250 
8251 	      if (packed_args)
8252 		/* Extract the next argument from the argument
8253 		   pack.  */
8254 		targ = TREE_VEC_ELT (packed_args, idx);
8255 
8256 	      if (PACK_EXPANSION_P (targ))
8257 		/* Look at the pattern of the pack expansion.  */
8258 		targ = PACK_EXPANSION_PATTERN (targ);
8259 
8260 	      /* Extract the template parameters from the template
8261 		 argument.  */
8262 	      if (TREE_CODE (targ) == TEMPLATE_DECL)
8263 		targ_parms = DECL_TEMPLATE_PARMS (targ);
8264 	      else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
8265 		targ_parms = DECL_TEMPLATE_PARMS (TYPE_NAME (targ));
8266 
8267 	      /* Verify that we can coerce the template template
8268 		 parameters from the template argument to the template
8269 		 parameter.  This requires an exact match.  */
8270 	      if (targ_parms
8271 		  && !coerce_template_template_parms
8272 		       (DECL_TEMPLATE_PARMS (tparm),
8273 			targ_parms,
8274 			tf_none,
8275 			tparm,
8276 			targs))
8277 		{
8278 		  ret = false;
8279 		  goto out;
8280 		}
8281 	    }
8282 	}
8283     }
8284 
8285  out:
8286 
8287   --processing_template_decl;
8288   return ret;
8289 }
8290 
8291 /* Since type attributes aren't mangled, we need to strip them from
8292    template type arguments.  */
8293 
8294 tree
canonicalize_type_argument(tree arg,tsubst_flags_t complain)8295 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
8296 {
8297   if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
8298     return arg;
8299   bool removed_attributes = false;
8300   tree canon = strip_typedefs (arg, &removed_attributes);
8301   if (removed_attributes
8302       && (complain & tf_warning))
8303     warning (OPT_Wignored_attributes,
8304 	     "ignoring attributes on template argument %qT", arg);
8305   return canon;
8306 }
8307 
8308 /* And from inside dependent non-type arguments like sizeof(Type).  */
8309 
8310 static tree
canonicalize_expr_argument(tree arg,tsubst_flags_t complain)8311 canonicalize_expr_argument (tree arg, tsubst_flags_t complain)
8312 {
8313   if (!arg || arg == error_mark_node)
8314     return arg;
8315   bool removed_attributes = false;
8316   tree canon = strip_typedefs_expr (arg, &removed_attributes);
8317   if (removed_attributes
8318       && (complain & tf_warning))
8319     warning (OPT_Wignored_attributes,
8320 	     "ignoring attributes in template argument %qE", arg);
8321   return canon;
8322 }
8323 
8324 /* A template declaration can be substituted for a constrained
8325    template template parameter only when the argument is no more
8326    constrained than the parameter.  */
8327 
8328 static bool
is_compatible_template_arg(tree parm,tree arg,tree args)8329 is_compatible_template_arg (tree parm, tree arg, tree args)
8330 {
8331   tree parm_cons = get_constraints (parm);
8332 
8333   /* For now, allow constrained template template arguments
8334      and unconstrained template template parameters.  */
8335   if (parm_cons == NULL_TREE)
8336     return true;
8337 
8338   /* If the template parameter is constrained, we need to rewrite its
8339      constraints in terms of the ARG's template parameters. This ensures
8340      that all of the template parameter types will have the same depth.
8341 
8342      Note that this is only valid when coerce_template_template_parm is
8343      true for the innermost template parameters of PARM and ARG. In other
8344      words, because coercion is successful, this conversion will be valid.  */
8345   tree new_args = NULL_TREE;
8346   if (parm_cons)
8347     {
8348       tree aparms = DECL_INNERMOST_TEMPLATE_PARMS (arg);
8349       new_args = template_parms_level_to_args (aparms);
8350       new_args = add_to_template_args (args, new_args);
8351       ++processing_template_decl;
8352       parm_cons = tsubst_constraint_info (parm_cons, new_args,
8353 					  tf_none, NULL_TREE);
8354       --processing_template_decl;
8355       if (parm_cons == error_mark_node)
8356         return false;
8357     }
8358 
8359   return weakly_subsumes (parm_cons, arg);
8360 }
8361 
8362 // Convert a placeholder argument into a binding to the original
8363 // parameter. The original parameter is saved as the TREE_TYPE of
8364 // ARG.
8365 static inline tree
convert_wildcard_argument(tree parm,tree arg)8366 convert_wildcard_argument (tree parm, tree arg)
8367 {
8368   TREE_TYPE (arg) = parm;
8369   return arg;
8370 }
8371 
8372 /* We can't fully resolve ARG given as a non-type template argument to TYPE,
8373    because one of them is dependent.  But we need to represent the
8374    conversion for the benefit of cp_tree_equal.  */
8375 
8376 static tree
maybe_convert_nontype_argument(tree type,tree arg)8377 maybe_convert_nontype_argument (tree type, tree arg)
8378 {
8379   /* Auto parms get no conversion.  */
8380   if (type_uses_auto (type))
8381     return arg;
8382   /* We don't need or want to add this conversion now if we're going to use the
8383      argument for deduction.  */
8384   if (value_dependent_expression_p (arg))
8385     return arg;
8386 
8387   type = cv_unqualified (type);
8388   tree argtype = TREE_TYPE (arg);
8389   if (same_type_p (type, argtype))
8390     return arg;
8391 
8392   arg = build1 (IMPLICIT_CONV_EXPR, type, arg);
8393   IMPLICIT_CONV_EXPR_NONTYPE_ARG (arg) = true;
8394   return arg;
8395 }
8396 
8397 /* Convert the indicated template ARG as necessary to match the
8398    indicated template PARM.  Returns the converted ARG, or
8399    error_mark_node if the conversion was unsuccessful.  Error and
8400    warning messages are issued under control of COMPLAIN.  This
8401    conversion is for the Ith parameter in the parameter list.  ARGS is
8402    the full set of template arguments deduced so far.  */
8403 
8404 static tree
convert_template_argument(tree parm,tree arg,tree args,tsubst_flags_t complain,int i,tree in_decl)8405 convert_template_argument (tree parm,
8406 			   tree arg,
8407 			   tree args,
8408 			   tsubst_flags_t complain,
8409 			   int i,
8410 			   tree in_decl)
8411 {
8412   tree orig_arg;
8413   tree val;
8414   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
8415 
8416   if (parm == error_mark_node || error_operand_p (arg))
8417     return error_mark_node;
8418 
8419   /* Trivially convert placeholders. */
8420   if (TREE_CODE (arg) == WILDCARD_DECL)
8421     return convert_wildcard_argument (parm, arg);
8422 
8423   if (arg == any_targ_node)
8424     return arg;
8425 
8426   if (TREE_CODE (arg) == TREE_LIST
8427       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
8428     {
8429       /* The template argument was the name of some
8430 	 member function.  That's usually
8431 	 invalid, but static members are OK.  In any
8432 	 case, grab the underlying fields/functions
8433 	 and issue an error later if required.  */
8434       TREE_TYPE (arg) = unknown_type_node;
8435     }
8436 
8437   orig_arg = arg;
8438 
8439   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
8440   requires_type = (TREE_CODE (parm) == TYPE_DECL
8441 		   || requires_tmpl_type);
8442 
8443   /* When determining whether an argument pack expansion is a template,
8444      look at the pattern.  */
8445   if (PACK_EXPANSION_P (arg))
8446     arg = PACK_EXPANSION_PATTERN (arg);
8447 
8448   /* Deal with an injected-class-name used as a template template arg.  */
8449   if (requires_tmpl_type && CLASS_TYPE_P (arg))
8450     {
8451       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
8452       if (TREE_CODE (t) == TEMPLATE_DECL)
8453 	{
8454 	  if (cxx_dialect >= cxx11)
8455 	    /* OK under DR 1004.  */;
8456 	  else if (complain & tf_warning_or_error)
8457 	    pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
8458 		     " used as template template argument", TYPE_NAME (arg));
8459 	  else if (flag_pedantic_errors)
8460 	    t = arg;
8461 
8462 	  arg = t;
8463 	}
8464     }
8465 
8466   is_tmpl_type =
8467     ((TREE_CODE (arg) == TEMPLATE_DECL
8468       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
8469      || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
8470      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8471      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
8472 
8473   if (is_tmpl_type
8474       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8475 	  || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
8476     arg = TYPE_STUB_DECL (arg);
8477 
8478   is_type = TYPE_P (arg) || is_tmpl_type;
8479 
8480   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
8481       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
8482     {
8483       if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
8484 	{
8485 	  if (complain & tf_error)
8486 	    error ("invalid use of destructor %qE as a type", orig_arg);
8487 	  return error_mark_node;
8488 	}
8489 
8490       permerror (input_location,
8491 		 "to refer to a type member of a template parameter, "
8492 		 "use %<typename %E%>", orig_arg);
8493 
8494       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
8495 				     TREE_OPERAND (arg, 1),
8496 				     typename_type,
8497 				     complain);
8498       arg = orig_arg;
8499       is_type = 1;
8500     }
8501   if (is_type != requires_type)
8502     {
8503       if (in_decl)
8504 	{
8505 	  if (complain & tf_error)
8506 	    {
8507 	      error ("type/value mismatch at argument %d in template "
8508 		     "parameter list for %qD",
8509 		     i + 1, in_decl);
8510 	      if (is_type)
8511 		{
8512 		  /* The template argument is a type, but we're expecting
8513 		     an expression.  */
8514 		  inform (input_location,
8515 			  "  expected a constant of type %qT, got %qT",
8516 			  TREE_TYPE (parm),
8517 			  (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
8518 		  /* [temp.arg]/2: "In a template-argument, an ambiguity
8519 		     between a type-id and an expression is resolved to a
8520 		     type-id, regardless of the form of the corresponding
8521 		     template-parameter."  So give the user a clue.  */
8522 		  if (TREE_CODE (arg) == FUNCTION_TYPE)
8523 		    inform (input_location, "  ambiguous template argument "
8524 			    "for non-type template parameter is treated as "
8525 			    "function type");
8526 		}
8527 	      else if (requires_tmpl_type)
8528 		inform (input_location,
8529 			"  expected a class template, got %qE", orig_arg);
8530 	      else
8531 		inform (input_location,
8532 			"  expected a type, got %qE", orig_arg);
8533 	    }
8534 	}
8535       return error_mark_node;
8536     }
8537   if (is_tmpl_type ^ requires_tmpl_type)
8538     {
8539       if (in_decl && (complain & tf_error))
8540 	{
8541 	  error ("type/value mismatch at argument %d in template "
8542 		 "parameter list for %qD",
8543 		 i + 1, in_decl);
8544 	  if (is_tmpl_type)
8545 	    inform (input_location,
8546 		    "  expected a type, got %qT", DECL_NAME (arg));
8547 	  else
8548 	    inform (input_location,
8549 		    "  expected a class template, got %qT", orig_arg);
8550 	}
8551       return error_mark_node;
8552     }
8553 
8554   if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
8555     /* We already did the appropriate conversion when packing args.  */
8556     val = orig_arg;
8557   else if (is_type)
8558     {
8559       if (requires_tmpl_type)
8560 	{
8561 	  if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
8562 	    /* The number of argument required is not known yet.
8563 	       Just accept it for now.  */
8564 	    val = orig_arg;
8565 	  else
8566 	    {
8567 	      tree parmparm = DECL_TEMPLATE_PARMS (parm);
8568 	      tree argparm;
8569 
8570 	      /* Strip alias templates that are equivalent to another
8571 		 template.  */
8572 	      arg = get_underlying_template (arg);
8573 	      argparm = DECL_TEMPLATE_PARMS (arg);
8574 
8575 	      if (coerce_template_template_parms (parmparm, argparm,
8576 						  complain, in_decl,
8577 						  args))
8578 		{
8579 		  val = arg;
8580 
8581 		  /* TEMPLATE_TEMPLATE_PARM node is preferred over
8582 		     TEMPLATE_DECL.  */
8583 		  if (val != error_mark_node)
8584                     {
8585                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
8586                         val = TREE_TYPE (val);
8587 		      if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
8588 			val = make_pack_expansion (val, complain);
8589                     }
8590 		}
8591 	      else
8592 		{
8593 		  if (in_decl && (complain & tf_error))
8594 		    {
8595 		      error ("type/value mismatch at argument %d in "
8596 			     "template parameter list for %qD",
8597 			     i + 1, in_decl);
8598 		      inform (input_location,
8599 			      "  expected a template of type %qD, got %qT",
8600 			      parm, orig_arg);
8601 		    }
8602 
8603 		  val = error_mark_node;
8604 		}
8605 
8606               // Check that the constraints are compatible before allowing the
8607               // substitution.
8608               if (val != error_mark_node)
8609 		if (!is_compatible_template_arg (parm, arg, args))
8610                   {
8611 		    if (in_decl && (complain & tf_error))
8612                       {
8613                         error ("constraint mismatch at argument %d in "
8614                                "template parameter list for %qD",
8615                                i + 1, in_decl);
8616                         inform (input_location, "  expected %qD but got %qD",
8617                                 parm, arg);
8618                       }
8619 		    val = error_mark_node;
8620                   }
8621 	    }
8622 	}
8623       else
8624 	val = orig_arg;
8625       /* We only form one instance of each template specialization.
8626 	 Therefore, if we use a non-canonical variant (i.e., a
8627 	 typedef), any future messages referring to the type will use
8628 	 the typedef, which is confusing if those future uses do not
8629 	 themselves also use the typedef.  */
8630       if (TYPE_P (val))
8631 	val = canonicalize_type_argument (val, complain);
8632     }
8633   else
8634     {
8635       tree t = TREE_TYPE (parm);
8636 
8637       if (TEMPLATE_PARM_LEVEL (get_template_parm_index (parm))
8638 	  > TMPL_ARGS_DEPTH (args))
8639 	/* We don't have enough levels of args to do any substitution.  This
8640 	   can happen in the context of -fnew-ttp-matching.  */;
8641       else if (tree a = type_uses_auto (t))
8642 	{
8643 	  t = do_auto_deduction (t, arg, a, complain, adc_unify, args,
8644 				 LOOKUP_IMPLICIT, /*tmpl=*/in_decl);
8645 	  if (t == error_mark_node)
8646 	    return error_mark_node;
8647 	}
8648       else
8649 	t = tsubst (t, args, complain, in_decl);
8650 
8651       /* Perform array-to-pointer and function-to-pointer conversion
8652 	 as per [temp.param]/10.  */
8653       t = type_decays_to (t);
8654 
8655       if (invalid_nontype_parm_type_p (t, complain))
8656 	return error_mark_node;
8657 
8658       /* Drop top-level cv-qualifiers on the substituted/deduced type of
8659 	 this non-type template parameter, as per [temp.param]/6.  */
8660       t = cv_unqualified (t);
8661 
8662       if (t != TREE_TYPE (parm))
8663 	t = canonicalize_type_argument (t, complain);
8664 
8665       if (!type_dependent_expression_p (orig_arg)
8666 	  && !uses_template_parms (t))
8667 	/* We used to call digest_init here.  However, digest_init
8668 	   will report errors, which we don't want when complain
8669 	   is zero.  More importantly, digest_init will try too
8670 	   hard to convert things: for example, `0' should not be
8671 	   converted to pointer type at this point according to
8672 	   the standard.  Accepting this is not merely an
8673 	   extension, since deciding whether or not these
8674 	   conversions can occur is part of determining which
8675 	   function template to call, or whether a given explicit
8676 	   argument specification is valid.  */
8677 	val = convert_nontype_argument (t, orig_arg, complain);
8678       else
8679 	{
8680 	  val = canonicalize_expr_argument (orig_arg, complain);
8681 	  val = maybe_convert_nontype_argument (t, val);
8682 	}
8683 
8684 
8685       if (val == NULL_TREE)
8686 	val = error_mark_node;
8687       else if (val == error_mark_node && (complain & tf_error))
8688 	error_at (cp_expr_loc_or_input_loc (orig_arg),
8689 		  "could not convert template argument %qE from %qT to %qT",
8690 		  orig_arg, TREE_TYPE (orig_arg), t);
8691 
8692       if (INDIRECT_REF_P (val))
8693         {
8694           /* Reject template arguments that are references to built-in
8695              functions with no library fallbacks.  */
8696           const_tree inner = TREE_OPERAND (val, 0);
8697 	  const_tree innertype = TREE_TYPE (inner);
8698 	  if (innertype
8699 	      && TYPE_REF_P (innertype)
8700 	      && TREE_CODE (TREE_TYPE (innertype)) == FUNCTION_TYPE
8701 	      && TREE_OPERAND_LENGTH (inner) > 0
8702               && reject_gcc_builtin (TREE_OPERAND (inner, 0)))
8703               return error_mark_node;
8704         }
8705 
8706       if (TREE_CODE (val) == SCOPE_REF)
8707 	{
8708 	  /* Strip typedefs from the SCOPE_REF.  */
8709 	  tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
8710 	  tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
8711 						   complain);
8712 	  val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
8713 				      QUALIFIED_NAME_IS_TEMPLATE (val));
8714 	}
8715     }
8716 
8717   return val;
8718 }
8719 
8720 /* Coerces the remaining template arguments in INNER_ARGS (from
8721    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
8722    Returns the coerced argument pack. PARM_IDX is the position of this
8723    parameter in the template parameter list. ARGS is the original
8724    template argument list.  */
8725 static tree
coerce_template_parameter_pack(tree parms,int parm_idx,tree args,tree inner_args,int arg_idx,tree new_args,int * lost,tree in_decl,tsubst_flags_t complain)8726 coerce_template_parameter_pack (tree parms,
8727                                 int parm_idx,
8728                                 tree args,
8729                                 tree inner_args,
8730                                 int arg_idx,
8731                                 tree new_args,
8732                                 int* lost,
8733                                 tree in_decl,
8734                                 tsubst_flags_t complain)
8735 {
8736   tree parm = TREE_VEC_ELT (parms, parm_idx);
8737   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8738   tree packed_args;
8739   tree argument_pack;
8740   tree packed_parms = NULL_TREE;
8741 
8742   if (arg_idx > nargs)
8743     arg_idx = nargs;
8744 
8745   if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
8746     {
8747       /* When the template parameter is a non-type template parameter pack
8748          or template template parameter pack whose type or template
8749          parameters use parameter packs, we know exactly how many arguments
8750          we are looking for.  Build a vector of the instantiated decls for
8751          these template parameters in PACKED_PARMS.  */
8752       /* We can't use make_pack_expansion here because it would interpret a
8753 	 _DECL as a use rather than a declaration.  */
8754       tree decl = TREE_VALUE (parm);
8755       tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
8756       SET_PACK_EXPANSION_PATTERN (exp, decl);
8757       PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
8758       SET_TYPE_STRUCTURAL_EQUALITY (exp);
8759 
8760       TREE_VEC_LENGTH (args)--;
8761       packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
8762       TREE_VEC_LENGTH (args)++;
8763 
8764       if (packed_parms == error_mark_node)
8765         return error_mark_node;
8766 
8767       /* If we're doing a partial instantiation of a member template,
8768          verify that all of the types used for the non-type
8769          template parameter pack are, in fact, valid for non-type
8770          template parameters.  */
8771       if (arg_idx < nargs
8772           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
8773         {
8774           int j, len = TREE_VEC_LENGTH (packed_parms);
8775           for (j = 0; j < len; ++j)
8776             {
8777               tree t = TREE_VEC_ELT (packed_parms, j);
8778               if (TREE_CODE (t) == PARM_DECL
8779 		  && invalid_nontype_parm_type_p (TREE_TYPE (t), complain))
8780                 return error_mark_node;
8781             }
8782 	  /* We don't know how many args we have yet, just
8783 	     use the unconverted ones for now.  */
8784 	  return NULL_TREE;
8785         }
8786 
8787       packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
8788     }
8789   /* Check if we have a placeholder pack, which indicates we're
8790      in the context of a introduction list.  In that case we want
8791      to match this pack to the single placeholder.  */
8792   else if (arg_idx < nargs
8793            && TREE_CODE (TREE_VEC_ELT (inner_args, arg_idx)) == WILDCARD_DECL
8794            && WILDCARD_PACK_P (TREE_VEC_ELT (inner_args, arg_idx)))
8795     {
8796       nargs = arg_idx + 1;
8797       packed_args = make_tree_vec (1);
8798     }
8799   else
8800     packed_args = make_tree_vec (nargs - arg_idx);
8801 
8802   /* Convert the remaining arguments, which will be a part of the
8803      parameter pack "parm".  */
8804   int first_pack_arg = arg_idx;
8805   for (; arg_idx < nargs; ++arg_idx)
8806     {
8807       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
8808       tree actual_parm = TREE_VALUE (parm);
8809       int pack_idx = arg_idx - first_pack_arg;
8810 
8811       if (packed_parms)
8812         {
8813 	  /* Once we've packed as many args as we have types, stop.  */
8814 	  if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
8815 	    break;
8816 	  else if (PACK_EXPANSION_P (arg))
8817 	    /* We don't know how many args we have yet, just
8818 	       use the unconverted ones for now.  */
8819 	    return NULL_TREE;
8820 	  else
8821 	    actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
8822         }
8823 
8824       if (arg == error_mark_node)
8825 	{
8826 	  if (complain & tf_error)
8827 	    error ("template argument %d is invalid", arg_idx + 1);
8828 	}
8829       else
8830 	arg = convert_template_argument (actual_parm,
8831 					 arg, new_args, complain, parm_idx,
8832 					 in_decl);
8833       if (arg == error_mark_node)
8834         (*lost)++;
8835       TREE_VEC_ELT (packed_args, pack_idx) = arg;
8836     }
8837 
8838   if (arg_idx - first_pack_arg < TREE_VEC_LENGTH (packed_args)
8839       && TREE_VEC_LENGTH (packed_args) > 0)
8840     {
8841       if (complain & tf_error)
8842 	error ("wrong number of template arguments (%d, should be %d)",
8843 	       arg_idx - first_pack_arg, TREE_VEC_LENGTH (packed_args));
8844       return error_mark_node;
8845     }
8846 
8847   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
8848       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
8849     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
8850   else
8851     {
8852       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
8853       TREE_CONSTANT (argument_pack) = 1;
8854     }
8855 
8856   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
8857   if (CHECKING_P)
8858     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
8859 					 TREE_VEC_LENGTH (packed_args));
8860   return argument_pack;
8861 }
8862 
8863 /* Returns the number of pack expansions in the template argument vector
8864    ARGS.  */
8865 
8866 static int
pack_expansion_args_count(tree args)8867 pack_expansion_args_count (tree args)
8868 {
8869   int i;
8870   int count = 0;
8871   if (args)
8872     for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
8873       {
8874 	tree elt = TREE_VEC_ELT (args, i);
8875 	if (elt && PACK_EXPANSION_P (elt))
8876 	  ++count;
8877       }
8878   return count;
8879 }
8880 
8881 /* Convert all template arguments to their appropriate types, and
8882    return a vector containing the innermost resulting template
8883    arguments.  If any error occurs, return error_mark_node. Error and
8884    warning messages are issued under control of COMPLAIN.
8885 
8886    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
8887    for arguments not specified in ARGS.  Otherwise, if
8888    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
8889    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
8890    USE_DEFAULT_ARGS is false, then all arguments must be specified in
8891    ARGS.  */
8892 
8893 static tree
coerce_template_parms(tree parms,tree args,tree in_decl,tsubst_flags_t complain,bool require_all_args,bool use_default_args)8894 coerce_template_parms (tree parms,
8895 		       tree args,
8896 		       tree in_decl,
8897 		       tsubst_flags_t complain,
8898 		       bool require_all_args,
8899 		       bool use_default_args)
8900 {
8901   int nparms, nargs, parm_idx, arg_idx, lost = 0;
8902   tree orig_inner_args;
8903   tree inner_args;
8904   tree new_args;
8905   tree new_inner_args;
8906 
8907   /* When used as a boolean value, indicates whether this is a
8908      variadic template parameter list. Since it's an int, we can also
8909      subtract it from nparms to get the number of non-variadic
8910      parameters.  */
8911   int variadic_p = 0;
8912   int variadic_args_p = 0;
8913   int post_variadic_parms = 0;
8914 
8915   /* Adjustment to nparms for fixed parameter packs.  */
8916   int fixed_pack_adjust = 0;
8917   int fixed_packs = 0;
8918   int missing = 0;
8919 
8920   /* Likewise for parameters with default arguments.  */
8921   int default_p = 0;
8922 
8923   if (args == error_mark_node)
8924     return error_mark_node;
8925 
8926   nparms = TREE_VEC_LENGTH (parms);
8927 
8928   /* Determine if there are any parameter packs or default arguments.  */
8929   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
8930     {
8931       tree parm = TREE_VEC_ELT (parms, parm_idx);
8932       if (variadic_p)
8933 	++post_variadic_parms;
8934       if (template_parameter_pack_p (TREE_VALUE (parm)))
8935 	++variadic_p;
8936       if (TREE_PURPOSE (parm))
8937 	++default_p;
8938     }
8939 
8940   inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
8941   /* If there are no parameters that follow a parameter pack, we need to
8942      expand any argument packs so that we can deduce a parameter pack from
8943      some non-packed args followed by an argument pack, as in variadic85.C.
8944      If there are such parameters, we need to leave argument packs intact
8945      so the arguments are assigned properly.  This can happen when dealing
8946      with a nested class inside a partial specialization of a class
8947      template, as in variadic92.C, or when deducing a template parameter pack
8948      from a sub-declarator, as in variadic114.C.  */
8949   if (!post_variadic_parms)
8950     inner_args = expand_template_argument_pack (inner_args);
8951 
8952   /* Count any pack expansion args.  */
8953   variadic_args_p = pack_expansion_args_count (inner_args);
8954 
8955   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8956   if ((nargs - variadic_args_p > nparms && !variadic_p)
8957       || (nargs < nparms - variadic_p
8958 	  && require_all_args
8959 	  && !variadic_args_p
8960 	  && (!use_default_args
8961 	      || (TREE_VEC_ELT (parms, nargs) != error_mark_node
8962                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
8963     {
8964     bad_nargs:
8965       if (complain & tf_error)
8966 	{
8967           if (variadic_p || default_p)
8968             {
8969               nparms -= variadic_p + default_p;
8970 	      error ("wrong number of template arguments "
8971 		     "(%d, should be at least %d)", nargs, nparms);
8972             }
8973 	  else
8974 	     error ("wrong number of template arguments "
8975 		    "(%d, should be %d)", nargs, nparms);
8976 
8977 	  if (in_decl)
8978 	    inform (DECL_SOURCE_LOCATION (in_decl),
8979 		    "provided for %qD", in_decl);
8980 	}
8981 
8982       return error_mark_node;
8983     }
8984   /* We can't pass a pack expansion to a non-pack parameter of an alias
8985      template (DR 1430).  */
8986   else if (in_decl
8987 	   && (DECL_ALIAS_TEMPLATE_P (in_decl)
8988 	       || concept_definition_p (in_decl))
8989 	   && variadic_args_p
8990 	   && nargs - variadic_args_p < nparms - variadic_p)
8991     {
8992       if (complain & tf_error)
8993 	{
8994 	  for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
8995 	    {
8996 	      tree arg = TREE_VEC_ELT (inner_args, i);
8997 	      tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
8998 
8999 	      if (PACK_EXPANSION_P (arg)
9000 		  && !template_parameter_pack_p (parm))
9001 		{
9002 		  if (DECL_ALIAS_TEMPLATE_P (in_decl))
9003 		    error_at (location_of (arg),
9004 			      "pack expansion argument for non-pack parameter "
9005 			      "%qD of alias template %qD", parm, in_decl);
9006 		  else
9007 		    error_at (location_of (arg),
9008 			      "pack expansion argument for non-pack parameter "
9009 			      "%qD of concept %qD", parm, in_decl);
9010 		  inform (DECL_SOURCE_LOCATION (parm), "declared here");
9011 		  goto found;
9012 		}
9013 	    }
9014 	  gcc_unreachable ();
9015 	found:;
9016 	}
9017       return error_mark_node;
9018     }
9019 
9020   /* We need to evaluate the template arguments, even though this
9021      template-id may be nested within a "sizeof".  */
9022   cp_evaluated ev;
9023 
9024   new_inner_args = make_tree_vec (nparms);
9025   new_args = add_outermost_template_args (args, new_inner_args);
9026   int pack_adjust = 0;
9027   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
9028     {
9029       tree arg;
9030       tree parm;
9031 
9032       /* Get the Ith template parameter.  */
9033       parm = TREE_VEC_ELT (parms, parm_idx);
9034 
9035       if (parm == error_mark_node)
9036 	{
9037 	  TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
9038 	  continue;
9039 	}
9040 
9041       /* Calculate the next argument.  */
9042       if (arg_idx < nargs)
9043 	arg = TREE_VEC_ELT (inner_args, arg_idx);
9044       else
9045 	arg = NULL_TREE;
9046 
9047       if (template_parameter_pack_p (TREE_VALUE (parm))
9048 	  && (arg || require_all_args || !(complain & tf_partial))
9049 	  && !(arg && ARGUMENT_PACK_P (arg)))
9050         {
9051 	  /* Some arguments will be placed in the
9052 	     template parameter pack PARM.  */
9053 	  arg = coerce_template_parameter_pack (parms, parm_idx, args,
9054 						inner_args, arg_idx,
9055 						new_args, &lost,
9056 						in_decl, complain);
9057 
9058 	  if (arg == NULL_TREE)
9059 	    {
9060 	      /* We don't know how many args we have yet, just use the
9061 		 unconverted (and still packed) ones for now.  */
9062 	      new_inner_args = orig_inner_args;
9063 	      arg_idx = nargs;
9064 	      break;
9065 	    }
9066 
9067           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
9068 
9069           /* Store this argument.  */
9070           if (arg == error_mark_node)
9071 	    {
9072 	      lost++;
9073 	      /* We are done with all of the arguments.  */
9074 	      arg_idx = nargs;
9075 	      break;
9076 	    }
9077 	  else
9078 	    {
9079 	      pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
9080 	      arg_idx += pack_adjust;
9081 	      if (fixed_parameter_pack_p (TREE_VALUE (parm)))
9082 		{
9083 		  ++fixed_packs;
9084 		  fixed_pack_adjust += pack_adjust;
9085 		}
9086 	    }
9087 
9088           continue;
9089         }
9090       else if (arg)
9091 	{
9092           if (PACK_EXPANSION_P (arg))
9093             {
9094 	      /* "If every valid specialization of a variadic template
9095 		 requires an empty template parameter pack, the template is
9096 		 ill-formed, no diagnostic required."  So check that the
9097 		 pattern works with this parameter.  */
9098 	      tree pattern = PACK_EXPANSION_PATTERN (arg);
9099 	      tree conv = convert_template_argument (TREE_VALUE (parm),
9100 						     pattern, new_args,
9101 						     complain, parm_idx,
9102 						     in_decl);
9103 	      if (conv == error_mark_node)
9104 		{
9105 		  if (complain & tf_error)
9106 		    inform (input_location, "so any instantiation with a "
9107 			    "non-empty parameter pack would be ill-formed");
9108 		  ++lost;
9109 		}
9110 	      else if (TYPE_P (conv) && !TYPE_P (pattern))
9111 		/* Recover from missing typename.  */
9112 		TREE_VEC_ELT (inner_args, arg_idx)
9113 		  = make_pack_expansion (conv, complain);
9114 
9115               /* We don't know how many args we have yet, just
9116                  use the unconverted ones for now.  */
9117               new_inner_args = inner_args;
9118 	      arg_idx = nargs;
9119               break;
9120             }
9121         }
9122       else if (require_all_args)
9123 	{
9124 	  /* There must be a default arg in this case.  */
9125 	  arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
9126 				     complain, in_decl);
9127 	  /* The position of the first default template argument,
9128 	     is also the number of non-defaulted arguments in NEW_INNER_ARGS.
9129 	     Record that.  */
9130 	  if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
9131 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
9132 						 arg_idx - pack_adjust);
9133 	}
9134       else
9135 	break;
9136 
9137       if (arg == error_mark_node)
9138 	{
9139 	  if (complain & tf_error)
9140 	    error ("template argument %d is invalid", arg_idx + 1);
9141 	}
9142       else if (!arg)
9143 	{
9144 	  /* This can occur if there was an error in the template
9145 	     parameter list itself (which we would already have
9146 	     reported) that we are trying to recover from, e.g., a class
9147 	     template with a parameter list such as
9148 	     template<typename..., typename> (cpp0x/variadic150.C).  */
9149 	  ++lost;
9150 
9151 	  /* This can also happen with a fixed parameter pack (71834).  */
9152 	  if (arg_idx >= nargs)
9153 	    ++missing;
9154 	}
9155       else
9156 	arg = convert_template_argument (TREE_VALUE (parm),
9157 					 arg, new_args, complain,
9158                                          parm_idx, in_decl);
9159 
9160       if (arg == error_mark_node)
9161 	lost++;
9162 
9163       TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
9164     }
9165 
9166   if (missing || arg_idx < nargs - variadic_args_p)
9167     {
9168       /* If we had fixed parameter packs, we didn't know how many arguments we
9169 	 actually needed earlier; now we do.  */
9170       nparms += fixed_pack_adjust;
9171       variadic_p -= fixed_packs;
9172       goto bad_nargs;
9173     }
9174 
9175   if (arg_idx < nargs)
9176     {
9177       /* We had some pack expansion arguments that will only work if the packs
9178 	 are empty, but wait until instantiation time to complain.
9179 	 See variadic-ttp3.C.  */
9180 
9181       /* Except that we can't provide empty packs to alias templates or
9182          concepts when there are no corresponding parameters. Basically,
9183          we can get here with this:
9184 
9185              template<typename T> concept C = true;
9186 
9187              template<typename... Args>
9188 	       requires C<Args...>
9189              void f();
9190 
9191          When parsing C<Args...>, we try to form a concept check of
9192          C<?, Args...>. Without the extra check for substituting an empty
9193          pack past the last parameter, we can accept the check as valid.
9194 
9195          FIXME: This may be valid for alias templates (but I doubt it).
9196 
9197          FIXME: The error could be better also.   */
9198       if (in_decl && concept_definition_p (in_decl))
9199 	{
9200 	  if (complain & tf_error)
9201 	    error_at (location_of (TREE_VEC_ELT (args, arg_idx)),
9202 		      "too many arguments");
9203 	  return error_mark_node;
9204 	}
9205 
9206       int len = nparms + (nargs - arg_idx);
9207       tree args = make_tree_vec (len);
9208       int i = 0;
9209       for (; i < nparms; ++i)
9210 	TREE_VEC_ELT (args, i) = TREE_VEC_ELT (new_inner_args, i);
9211       for (; i < len; ++i, ++arg_idx)
9212 	TREE_VEC_ELT (args, i) = TREE_VEC_ELT (inner_args,
9213 					       arg_idx - pack_adjust);
9214       new_inner_args = args;
9215     }
9216 
9217   if (lost)
9218     {
9219       gcc_assert (!(complain & tf_error) || seen_error ());
9220       return error_mark_node;
9221     }
9222 
9223   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
9224     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
9225 					 TREE_VEC_LENGTH (new_inner_args));
9226 
9227   return new_inner_args;
9228 }
9229 
9230 /* Convert all template arguments to their appropriate types, and
9231    return a vector containing the innermost resulting template
9232    arguments.  If any error occurs, return error_mark_node. Error and
9233    warning messages are not issued.
9234 
9235    Note that no function argument deduction is performed, and default
9236    arguments are used to fill in unspecified arguments. */
9237 tree
coerce_template_parms(tree parms,tree args,tree in_decl)9238 coerce_template_parms (tree parms, tree args, tree in_decl)
9239 {
9240   return coerce_template_parms (parms, args, in_decl, tf_none, true, true);
9241 }
9242 
9243 /* Convert all template arguments to their appropriate type, and
9244    instantiate default arguments as needed. This returns a vector
9245    containing the innermost resulting template arguments, or
9246    error_mark_node if unsuccessful.  */
9247 tree
coerce_template_parms(tree parms,tree args,tree in_decl,tsubst_flags_t complain)9248 coerce_template_parms (tree parms, tree args, tree in_decl,
9249                        tsubst_flags_t complain)
9250 {
9251   return coerce_template_parms (parms, args, in_decl, complain, true, true);
9252 }
9253 
9254 /* Like coerce_template_parms.  If PARMS represents all template
9255    parameters levels, this function returns a vector of vectors
9256    representing all the resulting argument levels.  Note that in this
9257    case, only the innermost arguments are coerced because the
9258    outermost ones are supposed to have been coerced already.
9259 
9260    Otherwise, if PARMS represents only (the innermost) vector of
9261    parameters, this function returns a vector containing just the
9262    innermost resulting arguments.  */
9263 
9264 static tree
coerce_innermost_template_parms(tree parms,tree args,tree in_decl,tsubst_flags_t complain,bool require_all_args,bool use_default_args)9265 coerce_innermost_template_parms (tree parms,
9266 				  tree args,
9267 				  tree in_decl,
9268 				  tsubst_flags_t complain,
9269 				  bool require_all_args,
9270 				  bool use_default_args)
9271 {
9272   int parms_depth = TMPL_PARMS_DEPTH (parms);
9273   int args_depth = TMPL_ARGS_DEPTH (args);
9274   tree coerced_args;
9275 
9276   if (parms_depth > 1)
9277     {
9278       coerced_args = make_tree_vec (parms_depth);
9279       tree level;
9280       int cur_depth;
9281 
9282       for (level = parms, cur_depth = parms_depth;
9283 	   parms_depth > 0 && level != NULL_TREE;
9284 	   level = TREE_CHAIN (level), --cur_depth)
9285 	{
9286 	  tree l;
9287 	  if (cur_depth == args_depth)
9288 	    l = coerce_template_parms (TREE_VALUE (level),
9289 				       args, in_decl, complain,
9290 				       require_all_args,
9291 				       use_default_args);
9292 	  else
9293 	    l = TMPL_ARGS_LEVEL (args, cur_depth);
9294 
9295 	  if (l == error_mark_node)
9296 	    return error_mark_node;
9297 
9298 	  SET_TMPL_ARGS_LEVEL (coerced_args, cur_depth, l);
9299 	}
9300     }
9301   else
9302     coerced_args = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parms),
9303 					  args, in_decl, complain,
9304 					  require_all_args,
9305 					  use_default_args);
9306   return coerced_args;
9307 }
9308 
9309 /* Returns true if T is a wrapper to make a C++20 template parameter
9310    object const.  */
9311 
9312 static bool
class_nttp_const_wrapper_p(tree t)9313 class_nttp_const_wrapper_p (tree t)
9314 {
9315   if (cxx_dialect < cxx20)
9316     return false;
9317   return (TREE_CODE (t) == VIEW_CONVERT_EXPR
9318 	  && CP_TYPE_CONST_P (TREE_TYPE (t))
9319 	  && TREE_CODE (TREE_OPERAND (t, 0)) == TEMPLATE_PARM_INDEX);
9320 }
9321 
9322 /* Returns 1 if template args OT and NT are equivalent.  */
9323 
9324 int
template_args_equal(tree ot,tree nt,bool partial_order)9325 template_args_equal (tree ot, tree nt, bool partial_order /* = false */)
9326 {
9327   if (nt == ot)
9328     return 1;
9329   if (nt == NULL_TREE || ot == NULL_TREE)
9330     return false;
9331   if (nt == any_targ_node || ot == any_targ_node)
9332     return true;
9333 
9334   if (class_nttp_const_wrapper_p (nt))
9335     nt = TREE_OPERAND (nt, 0);
9336   if (class_nttp_const_wrapper_p (ot))
9337     ot = TREE_OPERAND (ot, 0);
9338 
9339   /* DR 1558: Don't treat an alias template specialization with dependent
9340      arguments as equivalent to its underlying type when used as a template
9341      argument; we need them to be distinct so that we substitute into the
9342      specialization arguments at instantiation time.  And aliases can't be
9343      equivalent without being ==, so we don't need to look any deeper.
9344 
9345      During partial ordering, however, we need to treat them normally so we can
9346      order uses of the same alias with different cv-qualification (79960).  */
9347   auto cso = make_temp_override (comparing_dependent_aliases);
9348   if (!partial_order)
9349     ++comparing_dependent_aliases;
9350 
9351   if (TREE_CODE (nt) == TREE_VEC || TREE_CODE (ot) == TREE_VEC)
9352     /* For member templates */
9353     return TREE_CODE (ot) == TREE_CODE (nt) && comp_template_args (ot, nt);
9354   else if (PACK_EXPANSION_P (ot) || PACK_EXPANSION_P (nt))
9355     return (PACK_EXPANSION_P (ot) && PACK_EXPANSION_P (nt)
9356 	    && template_args_equal (PACK_EXPANSION_PATTERN (ot),
9357 				    PACK_EXPANSION_PATTERN (nt))
9358 	    && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
9359 				    PACK_EXPANSION_EXTRA_ARGS (nt)));
9360   else if (ARGUMENT_PACK_P (ot) || ARGUMENT_PACK_P (nt))
9361     return cp_tree_equal (ot, nt);
9362   else if (TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
9363     gcc_unreachable ();
9364   else if (TYPE_P (nt) || TYPE_P (ot))
9365     {
9366       if (!(TYPE_P (nt) && TYPE_P (ot)))
9367 	return false;
9368       return same_type_p (ot, nt);
9369     }
9370   else
9371     {
9372       /* Try to treat a template non-type argument that has been converted
9373 	 to the parameter type as equivalent to one that hasn't yet.  */
9374       for (enum tree_code code1 = TREE_CODE (ot);
9375 	   CONVERT_EXPR_CODE_P (code1)
9376 	     || code1 == NON_LVALUE_EXPR;
9377 	   code1 = TREE_CODE (ot))
9378 	ot = TREE_OPERAND (ot, 0);
9379 
9380       for (enum tree_code code2 = TREE_CODE (nt);
9381 	   CONVERT_EXPR_CODE_P (code2)
9382 	     || code2 == NON_LVALUE_EXPR;
9383 	   code2 = TREE_CODE (nt))
9384 	nt = TREE_OPERAND (nt, 0);
9385 
9386       return cp_tree_equal (ot, nt);
9387     }
9388 }
9389 
9390 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
9391    template arguments.  Returns 0 otherwise, and updates OLDARG_PTR and
9392    NEWARG_PTR with the offending arguments if they are non-NULL.  */
9393 
9394 int
comp_template_args(tree oldargs,tree newargs,tree * oldarg_ptr,tree * newarg_ptr,bool partial_order)9395 comp_template_args (tree oldargs, tree newargs,
9396 		    tree *oldarg_ptr, tree *newarg_ptr,
9397 		    bool partial_order)
9398 {
9399   int i;
9400 
9401   if (oldargs == newargs)
9402     return 1;
9403 
9404   if (!oldargs || !newargs)
9405     return 0;
9406 
9407   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
9408     return 0;
9409 
9410   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
9411     {
9412       tree nt = TREE_VEC_ELT (newargs, i);
9413       tree ot = TREE_VEC_ELT (oldargs, i);
9414 
9415       if (! template_args_equal (ot, nt, partial_order))
9416 	{
9417 	  if (oldarg_ptr != NULL)
9418 	    *oldarg_ptr = ot;
9419 	  if (newarg_ptr != NULL)
9420 	    *newarg_ptr = nt;
9421 	  return 0;
9422 	}
9423     }
9424   return 1;
9425 }
9426 
9427 inline bool
comp_template_args_porder(tree oargs,tree nargs)9428 comp_template_args_porder (tree oargs, tree nargs)
9429 {
9430   return comp_template_args (oargs, nargs, NULL, NULL, true);
9431 }
9432 
9433 /* Implement a freelist interface for objects of type T.
9434 
9435    Head is a separate object, rather than a regular member, so that we
9436    can define it as a GTY deletable pointer, which is highly
9437    desirable.  A data member could be declared that way, but then the
9438    containing object would implicitly get GTY((user)), which would
9439    prevent us from instantiating freelists as global objects.
9440    Although this way we can create freelist global objects, they're
9441    such thin wrappers that instantiating temporaries at every use
9442    loses nothing and saves permanent storage for the freelist object.
9443 
9444    Member functions next, anew, poison and reinit have default
9445    implementations that work for most of the types we're interested
9446    in, but if they don't work for some type, they should be explicitly
9447    specialized.  See the comments before them for requirements, and
9448    the example specializations for the tree_list_freelist.  */
9449 template <typename T>
9450 class freelist
9451 {
9452   /* Return the next object in a chain.  We could just do type
9453      punning, but if we access the object with its underlying type, we
9454      avoid strict-aliasing trouble.  This needs only work between
9455      poison and reinit.  */
next(T * obj)9456   static T *&next (T *obj) { return obj->next; }
9457 
9458   /* Return a newly allocated, uninitialized or minimally-initialized
9459      object of type T.  Any initialization performed by anew should
9460      either remain across the life of the object and the execution of
9461      poison, or be redone by reinit.  */
anew()9462   static T *anew () { return ggc_alloc<T> (); }
9463 
9464   /* Optionally scribble all over the bits holding the object, so that
9465      they become (mostly?) uninitialized memory.  This is called while
9466      preparing to make the object part of the free list.  */
poison(T * obj)9467   static void poison (T *obj) {
9468     T *p ATTRIBUTE_UNUSED = obj;
9469     T **q ATTRIBUTE_UNUSED = &next (obj);
9470 
9471 #ifdef ENABLE_GC_CHECKING
9472     /* Poison the data, to indicate the data is garbage.  */
9473     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, sizeof (*p)));
9474     memset (p, 0xa5, sizeof (*p));
9475 #endif
9476     /* Let valgrind know the object is free.  */
9477     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, sizeof (*p)));
9478 
9479     /* Let valgrind know the next portion of the object is available,
9480        but uninitialized.  */
9481     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9482   }
9483 
9484   /* Bring an object that underwent at least one lifecycle after anew
9485      and before the most recent free and poison, back to a usable
9486      state, reinitializing whatever is needed for it to be
9487      functionally equivalent to an object just allocated and returned
9488      by anew.  This may poison or clear the next field, used by
9489      freelist housekeeping after poison was called.  */
reinit(T * obj)9490   static void reinit (T *obj) {
9491     T **q ATTRIBUTE_UNUSED = &next (obj);
9492 
9493 #ifdef ENABLE_GC_CHECKING
9494     memset (q, 0xa5, sizeof (*q));
9495 #endif
9496     /* Let valgrind know the entire object is available, but
9497        uninitialized.  */
9498     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (*obj)));
9499   }
9500 
9501   /* Reference a GTY-deletable pointer that points to the first object
9502      in the free list proper.  */
9503   T *&head;
9504 public:
9505   /* Construct a freelist object chaining objects off of HEAD.  */
freelist(T * & head)9506   freelist (T *&head) : head(head) {}
9507 
9508   /* Add OBJ to the free object list.  The former head becomes OBJ's
9509      successor.  */
free(T * obj)9510   void free (T *obj)
9511   {
9512     poison (obj);
9513     next (obj) = head;
9514     head = obj;
9515   }
9516 
9517   /* Take an object from the free list, if one is available, or
9518      allocate a new one.  Objects taken from the free list should be
9519      regarded as filled with garbage, except for bits that are
9520      configured to be preserved across free and alloc.  */
alloc()9521   T *alloc ()
9522   {
9523     if (head)
9524       {
9525 	T *obj = head;
9526 	head = next (head);
9527 	reinit (obj);
9528 	return obj;
9529       }
9530     else
9531       return anew ();
9532   }
9533 };
9534 
9535 /* Explicitly specialize the interfaces for freelist<tree_node>: we
9536    want to allocate a TREE_LIST using the usual interface, and ensure
9537    TREE_CHAIN remains functional.  Alas, we have to duplicate a bit of
9538    build_tree_list logic in reinit, so this could go out of sync.  */
9539 template <>
9540 inline tree &
next(tree obj)9541 freelist<tree_node>::next (tree obj)
9542 {
9543   return TREE_CHAIN (obj);
9544 }
9545 template <>
9546 inline tree
anew()9547 freelist<tree_node>::anew ()
9548 {
9549   return build_tree_list (NULL, NULL);
9550 }
9551 template <>
9552 inline void
poison(tree obj ATTRIBUTE_UNUSED)9553 freelist<tree_node>::poison (tree obj ATTRIBUTE_UNUSED)
9554 {
9555   int size ATTRIBUTE_UNUSED = sizeof (tree_list);
9556   tree p ATTRIBUTE_UNUSED = obj;
9557   tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9558   tree *q ATTRIBUTE_UNUSED = &next (obj);
9559 
9560 #ifdef ENABLE_GC_CHECKING
9561   gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9562 
9563   /* Poison the data, to indicate the data is garbage.  */
9564   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, size));
9565   memset (p, 0xa5, size);
9566 #endif
9567   /* Let valgrind know the object is free.  */
9568   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, size));
9569   /* But we still want to use the TREE_CODE and TREE_CHAIN parts.  */
9570   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9571   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9572 
9573 #ifdef ENABLE_GC_CHECKING
9574   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (b, sizeof (*b)));
9575   /* Keep TREE_CHAIN functional.  */
9576   TREE_SET_CODE (obj, TREE_LIST);
9577 #else
9578   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9579 #endif
9580 }
9581 template <>
9582 inline void
reinit(tree obj ATTRIBUTE_UNUSED)9583 freelist<tree_node>::reinit (tree obj ATTRIBUTE_UNUSED)
9584 {
9585   tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9586 
9587 #ifdef ENABLE_GC_CHECKING
9588   gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9589   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9590   memset (obj, 0, sizeof (tree_list));
9591 #endif
9592 
9593   /* Let valgrind know the entire object is available, but
9594      uninitialized.  */
9595   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9596 
9597 #ifdef ENABLE_GC_CHECKING
9598   TREE_SET_CODE (obj, TREE_LIST);
9599 #else
9600   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9601 #endif
9602 }
9603 
9604 /* Point to the first object in the TREE_LIST freelist.  */
9605 static GTY((deletable)) tree tree_list_freelist_head;
9606 /* Return the/an actual TREE_LIST freelist.  */
9607 static inline freelist<tree_node>
tree_list_freelist()9608 tree_list_freelist ()
9609 {
9610   return tree_list_freelist_head;
9611 }
9612 
9613 /* Point to the first object in the tinst_level freelist.  */
9614 static GTY((deletable)) tinst_level *tinst_level_freelist_head;
9615 /* Return the/an actual tinst_level freelist.  */
9616 static inline freelist<tinst_level>
tinst_level_freelist()9617 tinst_level_freelist ()
9618 {
9619   return tinst_level_freelist_head;
9620 }
9621 
9622 /* Point to the first object in the pending_template freelist.  */
9623 static GTY((deletable)) pending_template *pending_template_freelist_head;
9624 /* Return the/an actual pending_template freelist.  */
9625 static inline freelist<pending_template>
pending_template_freelist()9626 pending_template_freelist ()
9627 {
9628   return pending_template_freelist_head;
9629 }
9630 
9631 /* Build the TREE_LIST object out of a split list, store it
9632    permanently, and return it.  */
9633 tree
to_list()9634 tinst_level::to_list ()
9635 {
9636   gcc_assert (split_list_p ());
9637   tree ret = tree_list_freelist ().alloc ();
9638   TREE_PURPOSE (ret) = tldcl;
9639   TREE_VALUE (ret) = targs;
9640   tldcl = ret;
9641   targs = NULL;
9642   gcc_assert (tree_list_p ());
9643   return ret;
9644 }
9645 
9646 const unsigned short tinst_level::refcount_infinity;
9647 
9648 /* Increment OBJ's refcount unless it is already infinite.  */
9649 static tinst_level *
inc_refcount_use(tinst_level * obj)9650 inc_refcount_use (tinst_level *obj)
9651 {
9652   if (obj && obj->refcount != tinst_level::refcount_infinity)
9653     ++obj->refcount;
9654   return obj;
9655 }
9656 
9657 /* Release storage for OBJ and node, if it's a TREE_LIST.  */
9658 void
free(tinst_level * obj)9659 tinst_level::free (tinst_level *obj)
9660 {
9661   if (obj->tree_list_p ())
9662     tree_list_freelist ().free (obj->get_node ());
9663   tinst_level_freelist ().free (obj);
9664 }
9665 
9666 /* Decrement OBJ's refcount if not infinite.  If it reaches zero, release
9667    OBJ's DECL and OBJ, and start over with the tinst_level object that
9668    used to be referenced by OBJ's NEXT.  */
9669 static void
dec_refcount_use(tinst_level * obj)9670 dec_refcount_use (tinst_level *obj)
9671 {
9672   while (obj
9673 	 && obj->refcount != tinst_level::refcount_infinity
9674 	 && !--obj->refcount)
9675     {
9676       tinst_level *next = obj->next;
9677       tinst_level::free (obj);
9678       obj = next;
9679     }
9680 }
9681 
9682 /* Modify PTR so that it points to OBJ, adjusting the refcounts of OBJ
9683    and of the former PTR.  Omitting the second argument is equivalent
9684    to passing (T*)NULL; this is allowed because passing the
9685    zero-valued integral constant NULL confuses type deduction and/or
9686    overload resolution.  */
9687 template <typename T>
9688 static void
set_refcount_ptr(T * & ptr,T * obj=NULL)9689 set_refcount_ptr (T *& ptr, T *obj = NULL)
9690 {
9691   T *save = ptr;
9692   ptr = inc_refcount_use (obj);
9693   dec_refcount_use (save);
9694 }
9695 
9696 static void
add_pending_template(tree d)9697 add_pending_template (tree d)
9698 {
9699   tree ti = (TYPE_P (d)
9700 	     ? CLASSTYPE_TEMPLATE_INFO (d)
9701 	     : DECL_TEMPLATE_INFO (d));
9702   struct pending_template *pt;
9703   int level;
9704 
9705   if (TI_PENDING_TEMPLATE_FLAG (ti))
9706     return;
9707 
9708   /* We are called both from instantiate_decl, where we've already had a
9709      tinst_level pushed, and instantiate_template, where we haven't.
9710      Compensate.  */
9711   gcc_assert (TREE_CODE (d) != TREE_LIST);
9712   level = !current_tinst_level
9713     || current_tinst_level->maybe_get_node () != d;
9714 
9715   if (level)
9716     push_tinst_level (d);
9717 
9718   pt = pending_template_freelist ().alloc ();
9719   pt->next = NULL;
9720   pt->tinst = NULL;
9721   set_refcount_ptr (pt->tinst, current_tinst_level);
9722   if (last_pending_template)
9723     last_pending_template->next = pt;
9724   else
9725     pending_templates = pt;
9726 
9727   last_pending_template = pt;
9728 
9729   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
9730 
9731   if (level)
9732     pop_tinst_level ();
9733 }
9734 
9735 
9736 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
9737    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
9738    documentation for TEMPLATE_ID_EXPR.  */
9739 
9740 tree
lookup_template_function(tree fns,tree arglist)9741 lookup_template_function (tree fns, tree arglist)
9742 {
9743   if (fns == error_mark_node || arglist == error_mark_node)
9744     return error_mark_node;
9745 
9746   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
9747 
9748   if (!is_overloaded_fn (fns) && !identifier_p (fns))
9749     {
9750       error ("%q#D is not a function template", fns);
9751       return error_mark_node;
9752     }
9753 
9754   if (BASELINK_P (fns))
9755     {
9756       fns = copy_node (fns);
9757       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
9758 					 unknown_type_node,
9759 					 BASELINK_FUNCTIONS (fns),
9760 					 arglist);
9761       return fns;
9762     }
9763 
9764   return build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, arglist);
9765 }
9766 
9767 /* Within the scope of a template class S<T>, the name S gets bound
9768    (in build_self_reference) to a TYPE_DECL for the class, not a
9769    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
9770    or one of its enclosing classes, and that type is a template,
9771    return the associated TEMPLATE_DECL.  Otherwise, the original
9772    DECL is returned.
9773 
9774    Also handle the case when DECL is a TREE_LIST of ambiguous
9775    injected-class-names from different bases.  */
9776 
9777 tree
maybe_get_template_decl_from_type_decl(tree decl)9778 maybe_get_template_decl_from_type_decl (tree decl)
9779 {
9780   if (decl == NULL_TREE)
9781     return decl;
9782 
9783   /* DR 176: A lookup that finds an injected-class-name (10.2
9784      [class.member.lookup]) can result in an ambiguity in certain cases
9785      (for example, if it is found in more than one base class). If all of
9786      the injected-class-names that are found refer to specializations of
9787      the same class template, and if the name is followed by a
9788      template-argument-list, the reference refers to the class template
9789      itself and not a specialization thereof, and is not ambiguous.  */
9790   if (TREE_CODE (decl) == TREE_LIST)
9791     {
9792       tree t, tmpl = NULL_TREE;
9793       for (t = decl; t; t = TREE_CHAIN (t))
9794 	{
9795 	  tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
9796 	  if (!tmpl)
9797 	    tmpl = elt;
9798 	  else if (tmpl != elt)
9799 	    break;
9800 	}
9801       if (tmpl && t == NULL_TREE)
9802 	return tmpl;
9803       else
9804 	return decl;
9805     }
9806 
9807   return (decl != NULL_TREE
9808 	  && DECL_SELF_REFERENCE_P (decl)
9809 	  && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
9810     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
9811 }
9812 
9813 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
9814    parameters, find the desired type.
9815 
9816    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
9817 
9818    IN_DECL, if non-NULL, is the template declaration we are trying to
9819    instantiate.
9820 
9821    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
9822    the class we are looking up.
9823 
9824    Issue error and warning messages under control of COMPLAIN.
9825 
9826    If the template class is really a local class in a template
9827    function, then the FUNCTION_CONTEXT is the function in which it is
9828    being instantiated.
9829 
9830    ??? Note that this function is currently called *twice* for each
9831    template-id: the first time from the parser, while creating the
9832    incomplete type (finish_template_type), and the second type during the
9833    real instantiation (instantiate_template_class). This is surely something
9834    that we want to avoid. It also causes some problems with argument
9835    coercion (see convert_nontype_argument for more information on this).  */
9836 
9837 static tree
lookup_template_class_1(tree d1,tree arglist,tree in_decl,tree context,int entering_scope,tsubst_flags_t complain)9838 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
9839 			 int entering_scope, tsubst_flags_t complain)
9840 {
9841   tree templ = NULL_TREE, parmlist;
9842   tree t;
9843   spec_entry **slot;
9844   spec_entry *entry;
9845   spec_entry elt;
9846   hashval_t hash;
9847 
9848   if (identifier_p (d1))
9849     {
9850       tree value = innermost_non_namespace_value (d1);
9851       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
9852 	templ = value;
9853       else
9854 	{
9855 	  if (context)
9856 	    push_decl_namespace (context);
9857 	  templ = lookup_name (d1);
9858 	  templ = maybe_get_template_decl_from_type_decl (templ);
9859 	  if (context)
9860 	    pop_decl_namespace ();
9861 	}
9862       if (templ)
9863 	context = DECL_CONTEXT (templ);
9864     }
9865   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
9866     {
9867       tree type = TREE_TYPE (d1);
9868 
9869       /* If we are declaring a constructor, say A<T>::A<T>, we will get
9870 	 an implicit typename for the second A.  Deal with it.  */
9871       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
9872 	type = TREE_TYPE (type);
9873 
9874       if (CLASSTYPE_TEMPLATE_INFO (type))
9875 	{
9876 	  templ = CLASSTYPE_TI_TEMPLATE (type);
9877 	  d1 = DECL_NAME (templ);
9878 	}
9879     }
9880   else if (TREE_CODE (d1) == ENUMERAL_TYPE
9881 	   || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
9882     {
9883       templ = TYPE_TI_TEMPLATE (d1);
9884       d1 = DECL_NAME (templ);
9885     }
9886   else if (DECL_TYPE_TEMPLATE_P (d1))
9887     {
9888       templ = d1;
9889       d1 = DECL_NAME (templ);
9890       context = DECL_CONTEXT (templ);
9891     }
9892   else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
9893     {
9894       templ = d1;
9895       d1 = DECL_NAME (templ);
9896     }
9897 
9898   /* Issue an error message if we didn't find a template.  */
9899   if (! templ)
9900     {
9901       if (complain & tf_error)
9902 	error ("%qT is not a template", d1);
9903       return error_mark_node;
9904     }
9905 
9906   if (TREE_CODE (templ) != TEMPLATE_DECL
9907 	 /* Make sure it's a user visible template, if it was named by
9908 	    the user.  */
9909       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
9910 	  && !PRIMARY_TEMPLATE_P (templ)))
9911     {
9912       if (complain & tf_error)
9913 	{
9914 	  error ("non-template type %qT used as a template", d1);
9915 	  if (in_decl)
9916 	    error ("for template declaration %q+D", in_decl);
9917 	}
9918       return error_mark_node;
9919     }
9920 
9921   complain &= ~tf_user;
9922 
9923   /* An alias that just changes the name of a template is equivalent to the
9924      other template, so if any of the arguments are pack expansions, strip
9925      the alias to avoid problems with a pack expansion passed to a non-pack
9926      alias template parameter (DR 1430).  */
9927   if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
9928     templ = get_underlying_template (templ);
9929 
9930   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
9931     {
9932       tree parm;
9933       tree arglist2 = coerce_template_args_for_ttp (templ, arglist, complain);
9934       if (arglist2 == error_mark_node
9935 	  || (!uses_template_parms (arglist2)
9936 	      && check_instantiated_args (templ, arglist2, complain)))
9937 	return error_mark_node;
9938 
9939       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
9940       return parm;
9941     }
9942   else
9943     {
9944       tree template_type = TREE_TYPE (templ);
9945       tree gen_tmpl;
9946       tree type_decl;
9947       tree found = NULL_TREE;
9948       int arg_depth;
9949       int parm_depth;
9950       int is_dependent_type;
9951       int use_partial_inst_tmpl = false;
9952 
9953       if (template_type == error_mark_node)
9954 	/* An error occurred while building the template TEMPL, and a
9955 	   diagnostic has most certainly been emitted for that
9956 	   already.  Let's propagate that error.  */
9957 	return error_mark_node;
9958 
9959       gen_tmpl = most_general_template (templ);
9960       if (modules_p ())
9961 	lazy_load_pendings (gen_tmpl);
9962 
9963       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
9964       parm_depth = TMPL_PARMS_DEPTH (parmlist);
9965       arg_depth = TMPL_ARGS_DEPTH (arglist);
9966 
9967       if (arg_depth == 1 && parm_depth > 1)
9968 	{
9969 	  /* We've been given an incomplete set of template arguments.
9970 	     For example, given:
9971 
9972 	       template <class T> struct S1 {
9973 		 template <class U> struct S2 {};
9974 		 template <class U> struct S2<U*> {};
9975 		};
9976 
9977 	     we will be called with an ARGLIST of `U*', but the
9978 	     TEMPLATE will be `template <class T> template
9979 	     <class U> struct S1<T>::S2'.  We must fill in the missing
9980 	     arguments.  */
9981 	  tree ti = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (templ));
9982 	  arglist = add_outermost_template_args (TI_ARGS (ti), arglist);
9983 	  arg_depth = TMPL_ARGS_DEPTH (arglist);
9984 	}
9985 
9986       /* Now we should have enough arguments.  */
9987       gcc_assert (parm_depth == arg_depth);
9988 
9989       /* From here on, we're only interested in the most general
9990 	 template.  */
9991 
9992       /* Shortcut looking up the current class scope again.  */
9993       if (current_class_type)
9994 	if (tree ti = CLASSTYPE_TEMPLATE_INFO (current_class_type))
9995 	  if (gen_tmpl == most_general_template (TI_TEMPLATE (ti))
9996 	      && comp_template_args (arglist, TI_ARGS (ti)))
9997 	    return current_class_type;
9998 
9999       /* Calculate the BOUND_ARGS.  These will be the args that are
10000 	 actually tsubst'd into the definition to create the
10001 	 instantiation.  */
10002       arglist = coerce_innermost_template_parms (parmlist, arglist, gen_tmpl,
10003 						 complain,
10004 						 /*require_all_args=*/true,
10005 						 /*use_default_args=*/true);
10006 
10007       if (arglist == error_mark_node)
10008 	/* We were unable to bind the arguments.  */
10009 	return error_mark_node;
10010 
10011       /* In the scope of a template class, explicit references to the
10012 	 template class refer to the type of the template, not any
10013 	 instantiation of it.  For example, in:
10014 
10015 	   template <class T> class C { void f(C<T>); }
10016 
10017 	 the `C<T>' is just the same as `C'.  Outside of the
10018 	 class, however, such a reference is an instantiation.  */
10019       if (entering_scope
10020 	  || !PRIMARY_TEMPLATE_P (gen_tmpl)
10021 	  || currently_open_class (template_type))
10022 	{
10023 	  tree tinfo = TYPE_TEMPLATE_INFO (template_type);
10024 
10025 	  if (tinfo && comp_template_args (TI_ARGS (tinfo), arglist))
10026 	    return template_type;
10027 	}
10028 
10029       /* If we already have this specialization, return it.  */
10030       elt.tmpl = gen_tmpl;
10031       elt.args = arglist;
10032       elt.spec = NULL_TREE;
10033       hash = spec_hasher::hash (&elt);
10034       entry = type_specializations->find_with_hash (&elt, hash);
10035 
10036       if (entry)
10037 	return entry->spec;
10038 
10039       /* If the template's constraints are not satisfied,
10040          then we cannot form a valid type.
10041 
10042          Note that the check is deferred until after the hash
10043          lookup. This prevents redundant checks on previously
10044          instantiated specializations. */
10045       if (flag_concepts
10046 	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl)
10047 	  && !constraints_satisfied_p (gen_tmpl, arglist))
10048         {
10049           if (complain & tf_error)
10050             {
10051 	      auto_diagnostic_group d;
10052               error ("template constraint failure for %qD", gen_tmpl);
10053               diagnose_constraints (input_location, gen_tmpl, arglist);
10054             }
10055           return error_mark_node;
10056         }
10057 
10058       is_dependent_type = uses_template_parms (arglist);
10059 
10060       /* If the deduced arguments are invalid, then the binding
10061 	 failed.  */
10062       if (!is_dependent_type
10063 	  && check_instantiated_args (gen_tmpl,
10064 				      INNERMOST_TEMPLATE_ARGS (arglist),
10065 				      complain))
10066 	return error_mark_node;
10067 
10068       if (!is_dependent_type
10069 	  && !PRIMARY_TEMPLATE_P (gen_tmpl)
10070 	  && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
10071 	  && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
10072 	/* This occurs when the user has tried to define a tagged type
10073 	   in a scope that forbids it.  We emitted an error during the
10074 	   parse.  We didn't complete the bail out then, so here we
10075 	   are.  */
10076 	return error_mark_node;
10077 
10078       context = DECL_CONTEXT (gen_tmpl);
10079       if (context && TYPE_P (context))
10080 	{
10081 	  context = tsubst_aggr_type (context, arglist, complain, in_decl, true);
10082 	  context = complete_type (context);
10083 	}
10084       else
10085 	context = tsubst (context, arglist, complain, in_decl);
10086 
10087       if (context == error_mark_node)
10088 	return error_mark_node;
10089 
10090       if (!context)
10091 	context = global_namespace;
10092 
10093       /* Create the type.  */
10094       if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10095 	{
10096 	  /* The user referred to a specialization of an alias
10097 	    template represented by GEN_TMPL.
10098 
10099 	    [temp.alias]/2 says:
10100 
10101 	        When a template-id refers to the specialization of an
10102 		alias template, it is equivalent to the associated
10103 		type obtained by substitution of its
10104 		template-arguments for the template-parameters in the
10105 		type-id of the alias template.  */
10106 
10107 	  t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
10108 	  /* Note that the call above (by indirectly calling
10109 	     register_specialization in tsubst_decl) registers the
10110 	     TYPE_DECL representing the specialization of the alias
10111 	     template.  So next time someone substitutes ARGLIST for
10112 	     the template parms into the alias template (GEN_TMPL),
10113 	     she'll get that TYPE_DECL back.  */
10114 
10115 	  if (t == error_mark_node)
10116 	    return t;
10117 	}
10118       else if (TREE_CODE (template_type) == ENUMERAL_TYPE)
10119 	{
10120 	  if (!is_dependent_type)
10121 	    {
10122 	      set_current_access_from_decl (TYPE_NAME (template_type));
10123 	      t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
10124 			      tsubst (ENUM_UNDERLYING_TYPE (template_type),
10125 				      arglist, complain, in_decl),
10126 			      tsubst_attributes (TYPE_ATTRIBUTES (template_type),
10127 						 arglist, complain, in_decl),
10128 			      SCOPED_ENUM_P (template_type), NULL);
10129 
10130 	      if (t == error_mark_node)
10131 		return t;
10132 	    }
10133 	  else
10134             {
10135               /* We don't want to call start_enum for this type, since
10136                  the values for the enumeration constants may involve
10137                  template parameters.  And, no one should be interested
10138                  in the enumeration constants for such a type.  */
10139               t = cxx_make_type (ENUMERAL_TYPE);
10140               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
10141             }
10142           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
10143 	  ENUM_FIXED_UNDERLYING_TYPE_P (t)
10144 	    = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
10145 	}
10146       else if (CLASS_TYPE_P (template_type))
10147 	{
10148 	  /* Lambda closures are regenerated in tsubst_lambda_expr, not
10149 	     instantiated here.  */
10150 	  gcc_assert (!LAMBDA_TYPE_P (template_type));
10151 
10152 	  t = make_class_type (TREE_CODE (template_type));
10153 	  CLASSTYPE_DECLARED_CLASS (t)
10154 	    = CLASSTYPE_DECLARED_CLASS (template_type);
10155 	  SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
10156 
10157 	  /* A local class.  Make sure the decl gets registered properly.  */
10158 	  if (context == current_function_decl)
10159 	    if (pushtag (DECL_NAME (gen_tmpl), t)
10160 		== error_mark_node)
10161 	      return error_mark_node;
10162 
10163 	  if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
10164 	    /* This instantiation is another name for the primary
10165 	       template type. Set the TYPE_CANONICAL field
10166 	       appropriately. */
10167 	    TYPE_CANONICAL (t) = template_type;
10168 	  else if (any_template_arguments_need_structural_equality_p (arglist))
10169 	    /* Some of the template arguments require structural
10170 	       equality testing, so this template class requires
10171 	       structural equality testing. */
10172 	    SET_TYPE_STRUCTURAL_EQUALITY (t);
10173 	}
10174       else
10175 	gcc_unreachable ();
10176 
10177       /* If we called start_enum or pushtag above, this information
10178 	 will already be set up.  */
10179       type_decl = TYPE_NAME (t);
10180       if (!type_decl)
10181 	{
10182 	  TYPE_CONTEXT (t) = FROB_CONTEXT (context);
10183 
10184 	  type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
10185 	  DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
10186 	  DECL_SOURCE_LOCATION (type_decl)
10187 	    = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
10188 	}
10189 
10190       set_instantiating_module (type_decl);
10191       /* Although GEN_TMPL is the TEMPLATE_DECL, it has the same value
10192 	 of export flag.  We want to propagate this because it might
10193 	 be a friend declaration that pushes a new hidden binding.  */
10194       DECL_MODULE_EXPORT_P (type_decl) = DECL_MODULE_EXPORT_P (gen_tmpl);
10195 
10196       if (CLASS_TYPE_P (template_type))
10197 	{
10198 	  TREE_PRIVATE (type_decl)
10199 	    = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
10200 	  TREE_PROTECTED (type_decl)
10201 	    = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
10202 	  if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
10203 	    {
10204 	      DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
10205 	      DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
10206 	    }
10207 	}
10208 
10209       if (OVERLOAD_TYPE_P (t)
10210 	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10211 	{
10212 	  static const char *tags[] = {"abi_tag", "may_alias"};
10213 
10214 	  for (unsigned ix = 0; ix != 2; ix++)
10215 	    {
10216 	      tree attributes
10217 		= lookup_attribute (tags[ix], TYPE_ATTRIBUTES (template_type));
10218 
10219 	      if (attributes)
10220 		TYPE_ATTRIBUTES (t)
10221 		  = tree_cons (TREE_PURPOSE (attributes),
10222 			       TREE_VALUE (attributes),
10223 			       TYPE_ATTRIBUTES (t));
10224 	    }
10225 	}
10226 
10227       /* Let's consider the explicit specialization of a member
10228          of a class template specialization that is implicitly instantiated,
10229 	 e.g.:
10230 	     template<class T>
10231 	     struct S
10232 	     {
10233 	       template<class U> struct M {}; //#0
10234 	     };
10235 
10236 	     template<>
10237 	     template<>
10238 	     struct S<int>::M<char> //#1
10239 	     {
10240 	       int i;
10241 	     };
10242 	[temp.expl.spec]/4 says this is valid.
10243 
10244 	In this case, when we write:
10245 	S<int>::M<char> m;
10246 
10247 	M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
10248 	the one of #0.
10249 
10250 	When we encounter #1, we want to store the partial instantiation
10251 	of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
10252 
10253 	For all cases other than this "explicit specialization of member of a
10254 	class template", we just want to store the most general template into
10255 	the CLASSTYPE_TI_TEMPLATE of M.
10256 
10257 	This case of "explicit specialization of member of a class template"
10258 	only happens when:
10259 	1/ the enclosing class is an instantiation of, and therefore not
10260 	the same as, the context of the most general template, and
10261 	2/ we aren't looking at the partial instantiation itself, i.e.
10262 	the innermost arguments are not the same as the innermost parms of
10263 	the most general template.
10264 
10265 	So it's only when 1/ and 2/ happens that we want to use the partial
10266 	instantiation of the member template in lieu of its most general
10267 	template.  */
10268 
10269       if (PRIMARY_TEMPLATE_P (gen_tmpl)
10270 	  && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
10271 	  /* the enclosing class must be an instantiation...  */
10272 	  && CLASS_TYPE_P (context)
10273 	  && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
10274 	{
10275 	  TREE_VEC_LENGTH (arglist)--;
10276 	  ++processing_template_decl;
10277 	  tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (gen_tmpl));
10278 	  tree partial_inst_args =
10279 	    tsubst (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)),
10280 		    arglist, complain, NULL_TREE);
10281 	  --processing_template_decl;
10282 	  TREE_VEC_LENGTH (arglist)++;
10283 	  if (partial_inst_args == error_mark_node)
10284 	    return error_mark_node;
10285 	  use_partial_inst_tmpl =
10286 	    /*...and we must not be looking at the partial instantiation
10287 	     itself. */
10288 	    !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
10289 				 partial_inst_args);
10290 	}
10291 
10292       if (!use_partial_inst_tmpl)
10293 	/* This case is easy; there are no member templates involved.  */
10294 	found = gen_tmpl;
10295       else
10296 	{
10297 	  /* This is a full instantiation of a member template.  Find
10298 	     the partial instantiation of which this is an instance.  */
10299 
10300 	  /* Temporarily reduce by one the number of levels in the ARGLIST
10301 	     so as to avoid comparing the last set of arguments.  */
10302 	  TREE_VEC_LENGTH (arglist)--;
10303 	  /* We don't use COMPLAIN in the following call because this isn't
10304 	     the immediate context of deduction.  For instance, tf_partial
10305 	     could be set here as we might be at the beginning of template
10306 	     argument deduction when any explicitly specified template
10307 	     arguments are substituted into the function type.  tf_partial
10308 	     could lead into trouble because we wouldn't find the partial
10309 	     instantiation that might have been created outside tf_partial
10310 	     context, because the levels of template parameters wouldn't
10311 	     match, because in a tf_partial context, tsubst doesn't reduce
10312 	     TEMPLATE_PARM_LEVEL.  */
10313 	  found = tsubst (gen_tmpl, arglist, tf_none, NULL_TREE);
10314 	  TREE_VEC_LENGTH (arglist)++;
10315 	  /* FOUND is either a proper class type, or an alias
10316 	     template specialization.  In the later case, it's a
10317 	     TYPE_DECL, resulting from the substituting of arguments
10318 	     for parameters in the TYPE_DECL of the alias template
10319 	     done earlier.  So be careful while getting the template
10320 	     of FOUND.  */
10321 	  found = (TREE_CODE (found) == TEMPLATE_DECL
10322 		   ? found
10323 		   : (TREE_CODE (found) == TYPE_DECL
10324 		      ? DECL_TI_TEMPLATE (found)
10325 		      : CLASSTYPE_TI_TEMPLATE (found)));
10326 
10327 	  if (DECL_CLASS_TEMPLATE_P (found)
10328 	      && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (found)))
10329 	    {
10330 	      /* If this partial instantiation is specialized, we want to
10331 		 use it for hash table lookup.  */
10332 	      elt.tmpl = found;
10333 	      elt.args = arglist = INNERMOST_TEMPLATE_ARGS (arglist);
10334 	      hash = spec_hasher::hash (&elt);
10335 	    }
10336 	}
10337 
10338       /* Build template info for the new specialization.  */
10339       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
10340 
10341       elt.spec = t;
10342       slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
10343       gcc_checking_assert (*slot == NULL);
10344       entry = ggc_alloc<spec_entry> ();
10345       *entry = elt;
10346       *slot = entry;
10347 
10348       /* Note this use of the partial instantiation so we can check it
10349 	 later in maybe_process_partial_specialization.  */
10350       DECL_TEMPLATE_INSTANTIATIONS (found)
10351 	= tree_cons (arglist, t,
10352 		     DECL_TEMPLATE_INSTANTIATIONS (found));
10353 
10354       if (TREE_CODE (template_type) == ENUMERAL_TYPE
10355 	  && !uses_template_parms (current_nonlambda_scope ())
10356 	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10357 	/* Now that the type has been registered on the instantiations
10358 	   list, we set up the enumerators.  Because the enumeration
10359 	   constants may involve the enumeration type itself, we make
10360 	   sure to register the type first, and then create the
10361 	   constants.  That way, doing tsubst_expr for the enumeration
10362 	   constants won't result in recursive calls here; we'll find
10363 	   the instantiation and exit above.  */
10364 	tsubst_enum (template_type, t, arglist);
10365 
10366       if (CLASS_TYPE_P (template_type) && is_dependent_type)
10367 	/* If the type makes use of template parameters, the
10368 	   code that generates debugging information will crash.  */
10369 	DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
10370 
10371       /* Possibly limit visibility based on template args.  */
10372       TREE_PUBLIC (type_decl) = 1;
10373       determine_visibility (type_decl);
10374 
10375       inherit_targ_abi_tags (t);
10376 
10377       return t;
10378     }
10379 }
10380 
10381 /* Wrapper for lookup_template_class_1.  */
10382 
10383 tree
lookup_template_class(tree d1,tree arglist,tree in_decl,tree context,int entering_scope,tsubst_flags_t complain)10384 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
10385                        int entering_scope, tsubst_flags_t complain)
10386 {
10387   tree ret;
10388   timevar_push (TV_TEMPLATE_INST);
10389   ret = lookup_template_class_1 (d1, arglist, in_decl, context,
10390                                  entering_scope, complain);
10391   timevar_pop (TV_TEMPLATE_INST);
10392   return ret;
10393 }
10394 
10395 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST.  */
10396 
10397 tree
lookup_template_variable(tree templ,tree arglist)10398 lookup_template_variable (tree templ, tree arglist)
10399 {
10400   if (flag_concepts && variable_concept_p (templ))
10401     return build_concept_check (templ, arglist, tf_none);
10402 
10403   /* The type of the expression is NULL_TREE since the template-id could refer
10404      to an explicit or partial specialization. */
10405   return build2 (TEMPLATE_ID_EXPR, NULL_TREE, templ, arglist);
10406 }
10407 
10408 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR for use. */
10409 
10410 tree
finish_template_variable(tree var,tsubst_flags_t complain)10411 finish_template_variable (tree var, tsubst_flags_t complain)
10412 {
10413   tree templ = TREE_OPERAND (var, 0);
10414   tree arglist = TREE_OPERAND (var, 1);
10415 
10416   tree parms = DECL_TEMPLATE_PARMS (templ);
10417   arglist = coerce_innermost_template_parms (parms, arglist, templ, complain,
10418 					     /*req_all*/true,
10419 					     /*use_default*/true);
10420   if (arglist == error_mark_node)
10421     return error_mark_node;
10422 
10423   if (flag_concepts && !constraints_satisfied_p (templ, arglist))
10424     {
10425       if (complain & tf_error)
10426 	{
10427 	  auto_diagnostic_group d;
10428 	  error ("use of invalid variable template %qE", var);
10429 	  diagnose_constraints (location_of (var), templ, arglist);
10430 	}
10431       return error_mark_node;
10432     }
10433 
10434   return instantiate_template (templ, arglist, complain);
10435 }
10436 
10437 /* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
10438    TARGS template args, and instantiate it if it's not dependent.  */
10439 
10440 tree
lookup_and_finish_template_variable(tree templ,tree targs,tsubst_flags_t complain)10441 lookup_and_finish_template_variable (tree templ, tree targs,
10442 				     tsubst_flags_t complain)
10443 {
10444   templ = lookup_template_variable (templ, targs);
10445   if (!any_dependent_template_arguments_p (targs))
10446     {
10447       /* We may be called while doing a partial substitution, but the
10448 	 type of the variable template may be auto, in which case we
10449 	 will call do_auto_deduction in mark_used (which clears tf_partial)
10450 	 and the auto must be properly reduced at that time for the
10451 	 deduction to work.  */
10452       complain &= ~tf_partial;
10453       templ = finish_template_variable (templ, complain);
10454       mark_used (templ);
10455     }
10456 
10457   return convert_from_reference (templ);
10458 }
10459 
10460 /* If the set of template parameters PARMS contains a template parameter
10461    at the given LEVEL and INDEX, then return this parameter.  Otherwise
10462    return NULL_TREE.  */
10463 
10464 static tree
corresponding_template_parameter(tree parms,int level,int index)10465 corresponding_template_parameter (tree parms, int level, int index)
10466 {
10467   while (TMPL_PARMS_DEPTH (parms) > level)
10468     parms = TREE_CHAIN (parms);
10469 
10470   if (TMPL_PARMS_DEPTH (parms) != level
10471       || TREE_VEC_LENGTH (TREE_VALUE (parms)) <= index)
10472     return NULL_TREE;
10473 
10474   tree t = TREE_VALUE (TREE_VEC_ELT (TREE_VALUE (parms), index));
10475   /* As in template_parm_to_arg.  */
10476   if (TREE_CODE (t) == TYPE_DECL || TREE_CODE (t) == TEMPLATE_DECL)
10477     t = TREE_TYPE (t);
10478   else
10479     t = DECL_INITIAL (t);
10480 
10481   gcc_assert (TEMPLATE_PARM_P (t));
10482   return t;
10483 }
10484 
10485 /* Return the template parameter from PARMS that positionally corresponds
10486    to the template parameter PARM, or else return NULL_TREE.  */
10487 
10488 static tree
corresponding_template_parameter(tree parms,tree parm)10489 corresponding_template_parameter (tree parms, tree parm)
10490 {
10491   int level, index;
10492   template_parm_level_and_index (parm, &level, &index);
10493   return corresponding_template_parameter (parms, level, index);
10494 }
10495 
10496 
10497 struct pair_fn_data
10498 {
10499   tree_fn_t fn;
10500   tree_fn_t any_fn;
10501   void *data;
10502   /* True when we should also visit template parameters that occur in
10503      non-deduced contexts.  */
10504   bool include_nondeduced_p;
10505   hash_set<tree> *visited;
10506 };
10507 
10508 /* Called from for_each_template_parm via walk_tree.  */
10509 
10510 static tree
for_each_template_parm_r(tree * tp,int * walk_subtrees,void * d)10511 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
10512 {
10513   tree t = *tp;
10514   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
10515   tree_fn_t fn = pfd->fn;
10516   void *data = pfd->data;
10517   tree result = NULL_TREE;
10518 
10519 #define WALK_SUBTREE(NODE)						\
10520   do									\
10521     {									\
10522       result = for_each_template_parm (NODE, fn, data, pfd->visited,	\
10523 				       pfd->include_nondeduced_p,	\
10524 				       pfd->any_fn);			\
10525       if (result) goto out;						\
10526     }									\
10527   while (0)
10528 
10529   if (pfd->any_fn && (*pfd->any_fn)(t, data))
10530     return t;
10531 
10532   if (TYPE_P (t)
10533       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
10534     WALK_SUBTREE (TYPE_CONTEXT (t));
10535 
10536   switch (TREE_CODE (t))
10537     {
10538     case RECORD_TYPE:
10539       if (TYPE_PTRMEMFUNC_P (t))
10540 	break;
10541       /* Fall through.  */
10542 
10543     case UNION_TYPE:
10544     case ENUMERAL_TYPE:
10545       if (!TYPE_TEMPLATE_INFO (t))
10546 	*walk_subtrees = 0;
10547       else
10548 	WALK_SUBTREE (TYPE_TI_ARGS (t));
10549       break;
10550 
10551     case INTEGER_TYPE:
10552       WALK_SUBTREE (TYPE_MIN_VALUE (t));
10553       WALK_SUBTREE (TYPE_MAX_VALUE (t));
10554       break;
10555 
10556     case METHOD_TYPE:
10557       /* Since we're not going to walk subtrees, we have to do this
10558 	 explicitly here.  */
10559       WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
10560       /* Fall through.  */
10561 
10562     case FUNCTION_TYPE:
10563       /* Check the return type.  */
10564       WALK_SUBTREE (TREE_TYPE (t));
10565 
10566       /* Check the parameter types.  Since default arguments are not
10567 	 instantiated until they are needed, the TYPE_ARG_TYPES may
10568 	 contain expressions that involve template parameters.  But,
10569 	 no-one should be looking at them yet.  And, once they're
10570 	 instantiated, they don't contain template parameters, so
10571 	 there's no point in looking at them then, either.  */
10572       {
10573 	tree parm;
10574 
10575 	for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
10576 	  WALK_SUBTREE (TREE_VALUE (parm));
10577 
10578 	/* Since we've already handled the TYPE_ARG_TYPES, we don't
10579 	   want walk_tree walking into them itself.  */
10580 	*walk_subtrees = 0;
10581       }
10582 
10583       if (flag_noexcept_type)
10584 	{
10585 	  tree spec = TYPE_RAISES_EXCEPTIONS (t);
10586 	  if (spec)
10587 	    WALK_SUBTREE (TREE_PURPOSE (spec));
10588 	}
10589       break;
10590 
10591     case TYPEOF_TYPE:
10592     case DECLTYPE_TYPE:
10593     case UNDERLYING_TYPE:
10594       if (pfd->include_nondeduced_p
10595 	  && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
10596 				     pfd->visited,
10597 				     pfd->include_nondeduced_p,
10598 				     pfd->any_fn))
10599 	return error_mark_node;
10600       *walk_subtrees = false;
10601       break;
10602 
10603     case FUNCTION_DECL:
10604     case VAR_DECL:
10605       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10606 	WALK_SUBTREE (DECL_TI_ARGS (t));
10607       /* Fall through.  */
10608 
10609     case PARM_DECL:
10610     case CONST_DECL:
10611       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t))
10612 	WALK_SUBTREE (DECL_INITIAL (t));
10613       if (DECL_CONTEXT (t)
10614 	  && pfd->include_nondeduced_p)
10615 	WALK_SUBTREE (DECL_CONTEXT (t));
10616       break;
10617 
10618     case BOUND_TEMPLATE_TEMPLATE_PARM:
10619       /* Record template parameters such as `T' inside `TT<T>'.  */
10620       WALK_SUBTREE (TYPE_TI_ARGS (t));
10621       /* Fall through.  */
10622 
10623     case TEMPLATE_TEMPLATE_PARM:
10624     case TEMPLATE_TYPE_PARM:
10625     case TEMPLATE_PARM_INDEX:
10626       if (fn && (*fn)(t, data))
10627 	return t;
10628       else if (!fn)
10629 	return t;
10630       break;
10631 
10632     case TEMPLATE_DECL:
10633       /* A template template parameter is encountered.  */
10634       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10635 	WALK_SUBTREE (TREE_TYPE (t));
10636 
10637       /* Already substituted template template parameter */
10638       *walk_subtrees = 0;
10639       break;
10640 
10641     case TYPENAME_TYPE:
10642       /* A template-id in a TYPENAME_TYPE might be a deduced context after
10643 	 partial instantiation.  */
10644       WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
10645       *walk_subtrees = 0;
10646       break;
10647 
10648     case INDIRECT_REF:
10649     case COMPONENT_REF:
10650       /* If there's no type, then this thing must be some expression
10651 	 involving template parameters.  */
10652       if (!fn && !TREE_TYPE (t))
10653 	return error_mark_node;
10654       break;
10655 
10656     case CONSTRUCTOR:
10657     case TRAIT_EXPR:
10658     case PLUS_EXPR:
10659     case MULT_EXPR:
10660     case SCOPE_REF:
10661       /* These are non-deduced contexts.  */
10662       if (!pfd->include_nondeduced_p)
10663 	*walk_subtrees = 0;
10664       break;
10665 
10666     case MODOP_EXPR:
10667     case CAST_EXPR:
10668     case IMPLICIT_CONV_EXPR:
10669     case REINTERPRET_CAST_EXPR:
10670     case CONST_CAST_EXPR:
10671     case STATIC_CAST_EXPR:
10672     case DYNAMIC_CAST_EXPR:
10673     case ARROW_EXPR:
10674     case DOTSTAR_EXPR:
10675     case TYPEID_EXPR:
10676     case PSEUDO_DTOR_EXPR:
10677       if (!fn)
10678 	return error_mark_node;
10679       break;
10680 
10681     default:
10682       break;
10683     }
10684 
10685   #undef WALK_SUBTREE
10686 
10687   /* We didn't find any template parameters we liked.  */
10688  out:
10689   return result;
10690 }
10691 
10692 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
10693    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
10694    call FN with the parameter and the DATA.
10695    If FN returns nonzero, the iteration is terminated, and
10696    for_each_template_parm returns 1.  Otherwise, the iteration
10697    continues.  If FN never returns a nonzero value, the value
10698    returned by for_each_template_parm is 0.  If FN is NULL, it is
10699    considered to be the function which always returns 1.
10700 
10701    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
10702    parameters that occur in non-deduced contexts.  When false, only
10703    visits those template parameters that can be deduced.  */
10704 
10705 static tree
for_each_template_parm(tree t,tree_fn_t fn,void * data,hash_set<tree> * visited,bool include_nondeduced_p,tree_fn_t any_fn)10706 for_each_template_parm (tree t, tree_fn_t fn, void* data,
10707 			hash_set<tree> *visited,
10708 			bool include_nondeduced_p,
10709 			tree_fn_t any_fn)
10710 {
10711   struct pair_fn_data pfd;
10712   tree result;
10713 
10714   /* Set up.  */
10715   pfd.fn = fn;
10716   pfd.any_fn = any_fn;
10717   pfd.data = data;
10718   pfd.include_nondeduced_p = include_nondeduced_p;
10719 
10720   /* Walk the tree.  (Conceptually, we would like to walk without
10721      duplicates, but for_each_template_parm_r recursively calls
10722      for_each_template_parm, so we would need to reorganize a fair
10723      bit to use walk_tree_without_duplicates, so we keep our own
10724      visited list.)  */
10725   if (visited)
10726     pfd.visited = visited;
10727   else
10728     pfd.visited = new hash_set<tree>;
10729   result = cp_walk_tree (&t,
10730 		         for_each_template_parm_r,
10731 		         &pfd,
10732 		         pfd.visited);
10733 
10734   /* Clean up.  */
10735   if (!visited)
10736     {
10737       delete pfd.visited;
10738       pfd.visited = 0;
10739     }
10740 
10741   return result;
10742 }
10743 
10744 struct find_template_parameter_info
10745 {
find_template_parameter_infofind_template_parameter_info10746   explicit find_template_parameter_info (tree ctx_parms)
10747     : parm_list (NULL_TREE),
10748       ctx_parms (ctx_parms),
10749       max_depth (TMPL_PARMS_DEPTH (ctx_parms))
10750   {}
10751 
10752   hash_set<tree> visited;
10753   hash_set<tree> parms;
10754   tree parm_list;
10755   tree ctx_parms;
10756   int max_depth;
10757 };
10758 
10759 /* Appends the declaration of T to the list in DATA.  */
10760 
10761 static int
keep_template_parm(tree t,void * data)10762 keep_template_parm (tree t, void* data)
10763 {
10764   find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10765 
10766   /* Template parameters declared within the expression are not part of
10767      the parameter mapping. For example, in this concept:
10768 
10769        template<typename T>
10770        concept C = requires { <expr> } -> same_as<int>;
10771 
10772      the return specifier same_as<int> declares a new decltype parameter
10773      that must not be part of the parameter mapping. The same is true
10774      for generic lambda parameters, lambda template parameters, etc.  */
10775   int level;
10776   int index;
10777   template_parm_level_and_index (t, &level, &index);
10778   if (level == 0 || level > ftpi->max_depth)
10779     return 0;
10780 
10781   if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10782     /* We want the underlying TEMPLATE_TEMPLATE_PARM, not the
10783        BOUND_TEMPLATE_TEMPLATE_PARM itself.  */
10784     t = TREE_TYPE (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (t));
10785 
10786   /* This template parameter might be an argument to a cached dependent
10787      specalization that was formed earlier inside some other template, in
10788      which case the parameter is not among the ones that are in-scope.
10789      Look in CTX_PARMS to find the corresponding in-scope template
10790      parameter, and use it instead.  */
10791   if (tree in_scope = corresponding_template_parameter (ftpi->ctx_parms, t))
10792     t = in_scope;
10793 
10794   /* Arguments like const T yield parameters like const T. This means that
10795      a template-id like X<T, const T> would yield two distinct parameters:
10796      T and const T. Adjust types to their unqualified versions.  */
10797   if (TYPE_P (t))
10798     t = TYPE_MAIN_VARIANT (t);
10799   if (!ftpi->parms.add (t))
10800     ftpi->parm_list = tree_cons (NULL_TREE, t, ftpi->parm_list);
10801 
10802   /* Verify the parameter we found has a valid index.  */
10803   if (flag_checking)
10804     {
10805       tree parms = ftpi->ctx_parms;
10806       while (TMPL_PARMS_DEPTH (parms) > level)
10807 	parms = TREE_CHAIN (parms);
10808       if (int len = TREE_VEC_LENGTH (TREE_VALUE (parms)))
10809 	gcc_assert (index < len);
10810     }
10811 
10812   return 0;
10813 }
10814 
10815 /* Ensure that we recursively examine certain terms that are not normally
10816    visited in for_each_template_parm_r.  */
10817 
10818 static int
any_template_parm_r(tree t,void * data)10819 any_template_parm_r (tree t, void *data)
10820 {
10821   find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10822 
10823 #define WALK_SUBTREE(NODE)						\
10824   do									\
10825     {									\
10826       for_each_template_parm (NODE, keep_template_parm, data,		\
10827 			      &ftpi->visited, true,			\
10828 			      any_template_parm_r);			\
10829     }									\
10830   while (0)
10831 
10832   /* A mention of a member alias/typedef is a use of all of its template
10833      arguments, including those from the enclosing class, so we don't use
10834      alias_template_specialization_p here.  */
10835   if (TYPE_P (t) && typedef_variant_p (t))
10836     if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
10837       WALK_SUBTREE (TI_ARGS (tinfo));
10838 
10839   switch (TREE_CODE (t))
10840     {
10841     case TEMPLATE_TYPE_PARM:
10842       /* Type constraints of a placeholder type may contain parameters.  */
10843       if (is_auto (t))
10844 	if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
10845 	  WALK_SUBTREE (constr);
10846       break;
10847 
10848     case TEMPLATE_ID_EXPR:
10849       /* Search through references to variable templates.  */
10850       WALK_SUBTREE (TREE_OPERAND (t, 0));
10851       WALK_SUBTREE (TREE_OPERAND (t, 1));
10852       break;
10853 
10854     case TEMPLATE_PARM_INDEX:
10855     case PARM_DECL:
10856       /* A parameter or constraint variable may also depend on a template
10857 	 parameter without explicitly naming it.  */
10858       WALK_SUBTREE (TREE_TYPE (t));
10859       break;
10860 
10861     case TEMPLATE_DECL:
10862       /* If T is a member template that shares template parameters with
10863 	 ctx_parms, we need to mark all those parameters for mapping.
10864 	 To that end, it should suffice to just walk the DECL_CONTEXT of
10865 	 the template (assuming the template is not overly general).  */
10866       WALK_SUBTREE (DECL_CONTEXT (t));
10867       break;
10868 
10869     case LAMBDA_EXPR:
10870       {
10871 	/* Look in the parms and body.  */
10872 	tree fn = lambda_function (t);
10873 	WALK_SUBTREE (TREE_TYPE (fn));
10874 	WALK_SUBTREE (DECL_SAVED_TREE (fn));
10875       }
10876       break;
10877 
10878     case IDENTIFIER_NODE:
10879       if (IDENTIFIER_CONV_OP_P (t))
10880 	/* The conversion-type-id of a conversion operator may be dependent.  */
10881 	WALK_SUBTREE (TREE_TYPE (t));
10882       break;
10883 
10884     case CONVERT_EXPR:
10885       if (is_dummy_object (t))
10886 	WALK_SUBTREE (TREE_TYPE (t));
10887       break;
10888 
10889     default:
10890       break;
10891     }
10892 
10893   /* Keep walking.  */
10894   return 0;
10895 }
10896 
10897 /* Returns a list of unique template parameters found within T, where CTX_PARMS
10898    are the template parameters in scope.  */
10899 
10900 tree
find_template_parameters(tree t,tree ctx_parms)10901 find_template_parameters (tree t, tree ctx_parms)
10902 {
10903   if (!ctx_parms)
10904     return NULL_TREE;
10905 
10906   find_template_parameter_info ftpi (ctx_parms);
10907   for_each_template_parm (t, keep_template_parm, &ftpi, &ftpi.visited,
10908 			  /*include_nondeduced*/true, any_template_parm_r);
10909   return ftpi.parm_list;
10910 }
10911 
10912 /* Returns true if T depends on any template parameter.  */
10913 
10914 int
uses_template_parms(tree t)10915 uses_template_parms (tree t)
10916 {
10917   if (t == NULL_TREE)
10918     return false;
10919 
10920   bool dependent_p;
10921   int saved_processing_template_decl;
10922 
10923   saved_processing_template_decl = processing_template_decl;
10924   if (!saved_processing_template_decl)
10925     processing_template_decl = 1;
10926   if (TYPE_P (t))
10927     dependent_p = dependent_type_p (t);
10928   else if (TREE_CODE (t) == TREE_VEC)
10929     dependent_p = any_dependent_template_arguments_p (t);
10930   else if (TREE_CODE (t) == TREE_LIST)
10931     dependent_p = (uses_template_parms (TREE_VALUE (t))
10932 		   || uses_template_parms (TREE_CHAIN (t)));
10933   else if (TREE_CODE (t) == TYPE_DECL)
10934     dependent_p = dependent_type_p (TREE_TYPE (t));
10935   else if (t == error_mark_node || TREE_CODE (t) == NAMESPACE_DECL)
10936     dependent_p = false;
10937   else
10938     dependent_p = instantiation_dependent_expression_p (t);
10939 
10940   processing_template_decl = saved_processing_template_decl;
10941 
10942   return dependent_p;
10943 }
10944 
10945 /* Returns true iff we're processing an incompletely instantiated function
10946    template.  Useful instead of processing_template_decl because the latter
10947    is set to 0 during instantiate_non_dependent_expr.  */
10948 
10949 bool
in_template_function(void)10950 in_template_function (void)
10951 {
10952   /* Inspect the less volatile cfun->decl instead of current_function_decl;
10953      the latter might get set for e.g. access checking during satisfaction.  */
10954   tree fn = cfun ? cfun->decl : NULL_TREE;
10955   bool ret;
10956   ++processing_template_decl;
10957   ret = (fn && DECL_LANG_SPECIFIC (fn)
10958 	 && DECL_TEMPLATE_INFO (fn)
10959 	 && any_dependent_template_arguments_p (DECL_TI_ARGS (fn)));
10960   --processing_template_decl;
10961   return ret;
10962 }
10963 
10964 /* Returns true if T depends on any template parameter with level LEVEL.  */
10965 
10966 bool
uses_template_parms_level(tree t,int level)10967 uses_template_parms_level (tree t, int level)
10968 {
10969   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
10970 				 /*include_nondeduced_p=*/true);
10971 }
10972 
10973 /* Returns true if the signature of DECL depends on any template parameter from
10974    its enclosing class.  */
10975 
10976 static bool
uses_outer_template_parms(tree decl)10977 uses_outer_template_parms (tree decl)
10978 {
10979   int depth = template_class_depth (CP_DECL_CONTEXT (decl));
10980   if (depth == 0)
10981     return false;
10982   if (for_each_template_parm (TREE_TYPE (decl), template_parm_outer_level,
10983 			      &depth, NULL, /*include_nondeduced_p=*/true))
10984     return true;
10985   if (PRIMARY_TEMPLATE_P (decl)
10986       || DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
10987     {
10988       tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (decl));
10989       for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
10990 	{
10991 	  tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
10992 	  tree defarg = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
10993 	  if (TREE_CODE (parm) == PARM_DECL
10994 	      && for_each_template_parm (TREE_TYPE (parm),
10995 					 template_parm_outer_level,
10996 					 &depth, NULL, /*nondeduced*/true))
10997 	    return true;
10998 	  if (TREE_CODE (parm) == TEMPLATE_DECL
10999 	      && uses_outer_template_parms (parm))
11000 	    return true;
11001 	  if (defarg
11002 	      && for_each_template_parm (defarg, template_parm_outer_level,
11003 					 &depth, NULL, /*nondeduced*/true))
11004 	    return true;
11005 	}
11006     }
11007   if (uses_outer_template_parms_in_constraints (decl))
11008     return true;
11009   return false;
11010 }
11011 
11012 /* Returns true if the constraints of DECL depend on any template parameters
11013    from its enclosing scope.  */
11014 
11015 bool
uses_outer_template_parms_in_constraints(tree decl)11016 uses_outer_template_parms_in_constraints (tree decl)
11017 {
11018   tree ci = get_constraints (decl);
11019   if (ci)
11020     ci = CI_ASSOCIATED_CONSTRAINTS (ci);
11021   if (!ci)
11022     return false;
11023   int depth = template_class_depth (CP_DECL_CONTEXT (decl));
11024   if (depth == 0)
11025     return false;
11026   return for_each_template_parm (ci, template_parm_outer_level,
11027 				 &depth, NULL, /*nondeduced*/true);
11028 }
11029 
11030 /* Returns TRUE iff INST is an instantiation we don't need to do in an
11031    ill-formed translation unit, i.e. a variable or function that isn't
11032    usable in a constant expression.  */
11033 
11034 static inline bool
neglectable_inst_p(tree d)11035 neglectable_inst_p (tree d)
11036 {
11037   return (d && DECL_P (d)
11038 	  && !undeduced_auto_decl (d)
11039 	  && !(TREE_CODE (d) == FUNCTION_DECL
11040 	       ? FNDECL_MANIFESTLY_CONST_EVALUATED (d)
11041 	       : decl_maybe_constant_var_p (d)));
11042 }
11043 
11044 /* Returns TRUE iff we should refuse to instantiate DECL because it's
11045    neglectable and instantiated from within an erroneous instantiation.  */
11046 
11047 static bool
limit_bad_template_recursion(tree decl)11048 limit_bad_template_recursion (tree decl)
11049 {
11050   struct tinst_level *lev = current_tinst_level;
11051   int errs = errorcount + sorrycount;
11052   if (errs == 0 || !neglectable_inst_p (decl))
11053     return false;
11054 
11055   /* Avoid instantiating members of an ill-formed class.  */
11056   bool refuse
11057     = (DECL_CLASS_SCOPE_P (decl)
11058        && CLASSTYPE_ERRONEOUS (DECL_CONTEXT (decl)));
11059 
11060   if (!refuse)
11061     {
11062       for (; lev; lev = lev->next)
11063 	if (neglectable_inst_p (lev->maybe_get_node ()))
11064 	  break;
11065       refuse = (lev && errs > lev->errors);
11066     }
11067 
11068   if (refuse)
11069     {
11070       /* Don't warn about it not being defined.  */
11071       suppress_warning (decl, OPT_Wunused);
11072       tree clone;
11073       FOR_EACH_CLONE (clone, decl)
11074 	suppress_warning (clone, OPT_Wunused);
11075     }
11076   return refuse;
11077 }
11078 
11079 static int tinst_depth;
11080 extern int max_tinst_depth;
11081 int depth_reached;
11082 
11083 static GTY(()) struct tinst_level *last_error_tinst_level;
11084 
11085 /* We're starting to instantiate D; record the template instantiation context
11086    at LOC for diagnostics and to restore it later.  */
11087 
11088 bool
push_tinst_level_loc(tree tldcl,tree targs,location_t loc)11089 push_tinst_level_loc (tree tldcl, tree targs, location_t loc)
11090 {
11091   struct tinst_level *new_level;
11092 
11093   if (tinst_depth >= max_tinst_depth)
11094     {
11095       /* Tell error.cc not to try to instantiate any templates.  */
11096       at_eof = 2;
11097       fatal_error (input_location,
11098 		   "template instantiation depth exceeds maximum of %d"
11099 		   " (use %<-ftemplate-depth=%> to increase the maximum)",
11100                    max_tinst_depth);
11101       return false;
11102     }
11103 
11104   /* If the current instantiation caused problems, don't let it instantiate
11105      anything else.  Do allow deduction substitution and decls usable in
11106      constant expressions.  */
11107   if (!targs && limit_bad_template_recursion (tldcl))
11108     {
11109       /* Avoid no_linkage_errors and unused function (and all other)
11110 	 warnings for this decl.  */
11111       suppress_warning (tldcl);
11112       return false;
11113     }
11114 
11115   /* When not -quiet, dump template instantiations other than functions, since
11116      announce_function will take care of those.  */
11117   if (!quiet_flag && !targs
11118       && TREE_CODE (tldcl) != TREE_LIST
11119       && TREE_CODE (tldcl) != FUNCTION_DECL)
11120     fprintf (stderr, " %s", decl_as_string (tldcl, TFF_DECL_SPECIFIERS));
11121 
11122   new_level = tinst_level_freelist ().alloc ();
11123   new_level->tldcl = tldcl;
11124   new_level->targs = targs;
11125   new_level->locus = loc;
11126   new_level->errors = errorcount + sorrycount;
11127   new_level->next = NULL;
11128   new_level->refcount = 0;
11129   new_level->path = new_level->visible = nullptr;
11130   set_refcount_ptr (new_level->next, current_tinst_level);
11131   set_refcount_ptr (current_tinst_level, new_level);
11132 
11133   ++tinst_depth;
11134   if (GATHER_STATISTICS && (tinst_depth > depth_reached))
11135     depth_reached = tinst_depth;
11136 
11137   return true;
11138 }
11139 
11140 /* We're starting substitution of TMPL<ARGS>; record the template
11141    substitution context for diagnostics and to restore it later.  */
11142 
11143 bool
push_tinst_level(tree tmpl,tree args)11144 push_tinst_level (tree tmpl, tree args)
11145 {
11146   return push_tinst_level_loc (tmpl, args, input_location);
11147 }
11148 
11149 /* We're starting to instantiate D; record INPUT_LOCATION and the
11150    template instantiation context for diagnostics and to restore it
11151    later.  */
11152 
11153 bool
push_tinst_level(tree d)11154 push_tinst_level (tree d)
11155 {
11156   return push_tinst_level_loc (d, input_location);
11157 }
11158 
11159 /* Likewise, but record LOC as the program location.  */
11160 
11161 bool
push_tinst_level_loc(tree d,location_t loc)11162 push_tinst_level_loc (tree d, location_t loc)
11163 {
11164   gcc_assert (TREE_CODE (d) != TREE_LIST);
11165   return push_tinst_level_loc (d, NULL, loc);
11166 }
11167 
11168 /* We're done instantiating this template; return to the instantiation
11169    context.  */
11170 
11171 void
pop_tinst_level(void)11172 pop_tinst_level (void)
11173 {
11174   /* Restore the filename and line number stashed away when we started
11175      this instantiation.  */
11176   input_location = current_tinst_level->locus;
11177   set_refcount_ptr (current_tinst_level, current_tinst_level->next);
11178   --tinst_depth;
11179 }
11180 
11181 /* We're instantiating a deferred template; restore the template
11182    instantiation context in which the instantiation was requested, which
11183    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
11184 
11185 static tree
reopen_tinst_level(struct tinst_level * level)11186 reopen_tinst_level (struct tinst_level *level)
11187 {
11188   struct tinst_level *t;
11189 
11190   tinst_depth = 0;
11191   for (t = level; t; t = t->next)
11192     ++tinst_depth;
11193 
11194   set_refcount_ptr (current_tinst_level, level);
11195   pop_tinst_level ();
11196   if (current_tinst_level)
11197     current_tinst_level->errors = errorcount+sorrycount;
11198   return level->maybe_get_node ();
11199 }
11200 
11201 /* Returns the TINST_LEVEL which gives the original instantiation
11202    context.  */
11203 
11204 struct tinst_level *
outermost_tinst_level(void)11205 outermost_tinst_level (void)
11206 {
11207   struct tinst_level *level = current_tinst_level;
11208   if (level)
11209     while (level->next)
11210       level = level->next;
11211   return level;
11212 }
11213 
11214 /* True iff T is a friend function declaration that is not itself a template
11215    and is not defined in a class template.  */
11216 
11217 bool
non_templated_friend_p(tree t)11218 non_templated_friend_p (tree t)
11219 {
11220   if (t && TREE_CODE (t) == FUNCTION_DECL
11221       && DECL_UNIQUE_FRIEND_P (t))
11222     {
11223       tree ti = DECL_TEMPLATE_INFO (t);
11224       if (!ti)
11225 	return true;
11226       /* DECL_FRIEND_CONTEXT is set for a friend defined in class.  */
11227       if (DECL_FRIEND_CONTEXT (t))
11228 	return false;
11229       /* Non-templated friends in a class template are still represented with a
11230 	 TEMPLATE_DECL; check that its primary template is the befriending
11231 	 class.  Note that DECL_PRIMARY_TEMPLATE is null for
11232 	 template <class T> friend A<T>::f(); */
11233       tree tmpl = TI_TEMPLATE (ti);
11234       tree primary = DECL_PRIMARY_TEMPLATE (tmpl);
11235       return (primary && primary != tmpl);
11236     }
11237   else
11238     return false;
11239 }
11240 
11241 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
11242    vector of template arguments, as for tsubst.
11243 
11244    Returns an appropriate tsubst'd friend declaration.  */
11245 
11246 static tree
tsubst_friend_function(tree decl,tree args)11247 tsubst_friend_function (tree decl, tree args)
11248 {
11249   tree new_friend;
11250 
11251   if (TREE_CODE (decl) == FUNCTION_DECL
11252       && DECL_TEMPLATE_INSTANTIATION (decl)
11253       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
11254     /* This was a friend declared with an explicit template
11255        argument list, e.g.:
11256 
11257        friend void f<>(T);
11258 
11259        to indicate that f was a template instantiation, not a new
11260        function declaration.  Now, we have to figure out what
11261        instantiation of what template.  */
11262     {
11263       tree template_id, arglist, fns;
11264       tree new_args;
11265       tree tmpl;
11266       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
11267 
11268       /* Friend functions are looked up in the containing namespace scope.
11269 	 We must enter that scope, to avoid finding member functions of the
11270 	 current class with same name.  */
11271       push_nested_namespace (ns);
11272       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
11273 			 tf_warning_or_error, NULL_TREE,
11274 			 /*integral_constant_expression_p=*/false);
11275       pop_nested_namespace (ns);
11276       arglist = tsubst (DECL_TI_ARGS (decl), args,
11277 			tf_warning_or_error, NULL_TREE);
11278       template_id = lookup_template_function (fns, arglist);
11279 
11280       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11281       tmpl = determine_specialization (template_id, new_friend,
11282 				       &new_args,
11283 				       /*need_member_template=*/0,
11284 				       TREE_VEC_LENGTH (args),
11285 				       tsk_none);
11286       return instantiate_template (tmpl, new_args, tf_error);
11287     }
11288 
11289   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11290   if (new_friend == error_mark_node)
11291     return error_mark_node;
11292 
11293   /* The NEW_FRIEND will look like an instantiation, to the
11294      compiler, but is not an instantiation from the point of view of
11295      the language.  For example, we might have had:
11296 
11297      template <class T> struct S {
11298        template <class U> friend void f(T, U);
11299      };
11300 
11301      Then, in S<int>, template <class U> void f(int, U) is not an
11302      instantiation of anything.  */
11303 
11304   DECL_USE_TEMPLATE (new_friend) = 0;
11305   if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11306     {
11307       DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (new_friend) = false;
11308       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
11309       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
11310 	= DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
11311 
11312       /* Substitute TEMPLATE_PARMS_CONSTRAINTS so that parameter levels will
11313 	 match in decls_match.  */
11314       tree parms = DECL_TEMPLATE_PARMS (new_friend);
11315       tree treqs = TEMPLATE_PARMS_CONSTRAINTS (parms);
11316       treqs = maybe_substitute_reqs_for (treqs, new_friend);
11317       if (treqs != TEMPLATE_PARMS_CONSTRAINTS (parms))
11318 	{
11319 	  TEMPLATE_PARMS_CONSTRAINTS (parms) = treqs;
11320 	  /* As well as each TEMPLATE_PARM_CONSTRAINTS.  */
11321 	  tsubst_each_template_parm_constraints (parms, args,
11322 						 tf_warning_or_error);
11323 	}
11324     }
11325 
11326   /* The mangled name for the NEW_FRIEND is incorrect.  The function
11327      is not a template instantiation and should not be mangled like
11328      one.  Therefore, we forget the mangling here; we'll recompute it
11329      later if we need it.  */
11330   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
11331     {
11332       SET_DECL_RTL (new_friend, NULL);
11333       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
11334     }
11335 
11336   if (DECL_NAMESPACE_SCOPE_P (new_friend))
11337     {
11338       tree old_decl;
11339       tree ns;
11340 
11341       /* We must save some information from NEW_FRIEND before calling
11342 	 duplicate decls since that function will free NEW_FRIEND if
11343 	 possible.  */
11344       tree new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
11345       tree new_friend_result_template_info = NULL_TREE;
11346       bool new_friend_is_defn =
11347 	(new_friend_template_info
11348 	 && (DECL_INITIAL (DECL_TEMPLATE_RESULT
11349 			   (template_for_substitution (new_friend)))
11350 	     != NULL_TREE));
11351       tree not_tmpl = new_friend;
11352 
11353       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11354 	{
11355 	  /* This declaration is a `primary' template.  */
11356 	  DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
11357 
11358 	  not_tmpl = DECL_TEMPLATE_RESULT (new_friend);
11359 	  new_friend_result_template_info = DECL_TEMPLATE_INFO (not_tmpl);
11360 	}
11361 
11362       /* Inside pushdecl_namespace_level, we will push into the
11363 	 current namespace. However, the friend function should go
11364 	 into the namespace of the template.  */
11365       ns = decl_namespace_context (new_friend);
11366       push_nested_namespace (ns);
11367       old_decl = pushdecl_namespace_level (new_friend, /*hiding=*/true);
11368       pop_nested_namespace (ns);
11369 
11370       if (old_decl == error_mark_node)
11371 	return error_mark_node;
11372 
11373       if (old_decl != new_friend)
11374 	{
11375 	  /* This new friend declaration matched an existing
11376 	     declaration.  For example, given:
11377 
11378 	       template <class T> void f(T);
11379 	       template <class U> class C {
11380 		 template <class T> friend void f(T) {}
11381 	       };
11382 
11383 	     the friend declaration actually provides the definition
11384 	     of `f', once C has been instantiated for some type.  So,
11385 	     old_decl will be the out-of-class template declaration,
11386 	     while new_friend is the in-class definition.
11387 
11388 	     But, if `f' was called before this point, the
11389 	     instantiation of `f' will have DECL_TI_ARGS corresponding
11390 	     to `T' but not to `U', references to which might appear
11391 	     in the definition of `f'.  Previously, the most general
11392 	     template for an instantiation of `f' was the out-of-class
11393 	     version; now it is the in-class version.  Therefore, we
11394 	     run through all specialization of `f', adding to their
11395 	     DECL_TI_ARGS appropriately.  In particular, they need a
11396 	     new set of outer arguments, corresponding to the
11397 	     arguments for this class instantiation.
11398 
11399 	     The same situation can arise with something like this:
11400 
11401 	       friend void f(int);
11402 	       template <class T> class C {
11403 		 friend void f(T) {}
11404 	       };
11405 
11406 	     when `C<int>' is instantiated.  Now, `f(int)' is defined
11407 	     in the class.  */
11408 
11409 	  if (!new_friend_is_defn)
11410 	    /* On the other hand, if the in-class declaration does
11411 	       *not* provide a definition, then we don't want to alter
11412 	       existing definitions.  We can just leave everything
11413 	       alone.  */
11414 	    ;
11415 	  else
11416 	    {
11417 	      tree new_template = TI_TEMPLATE (new_friend_template_info);
11418 	      tree new_args = TI_ARGS (new_friend_template_info);
11419 
11420 	      /* Overwrite whatever template info was there before, if
11421 		 any, with the new template information pertaining to
11422 		 the declaration.  */
11423 	      DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
11424 
11425 	      if (TREE_CODE (old_decl) != TEMPLATE_DECL)
11426 		{
11427 		  /* We should have called reregister_specialization in
11428 		     duplicate_decls.  */
11429 		  gcc_assert (retrieve_specialization (new_template,
11430 						       new_args, 0)
11431 			      == old_decl);
11432 
11433 		  /* Instantiate it if the global has already been used.  */
11434 		  if (DECL_ODR_USED (old_decl))
11435 		    instantiate_decl (old_decl, /*defer_ok=*/true,
11436 				      /*expl_inst_class_mem_p=*/false);
11437 		}
11438 	      else
11439 		{
11440 		  tree t;
11441 
11442 		  /* Indicate that the old function template is a partial
11443 		     instantiation.  */
11444 		  DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
11445 		    = new_friend_result_template_info;
11446 
11447 		  gcc_assert (new_template
11448 			      == most_general_template (new_template));
11449 		  gcc_assert (new_template != old_decl);
11450 
11451 		  /* Reassign any specializations already in the hash table
11452 		     to the new more general template, and add the
11453 		     additional template args.  */
11454 		  for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
11455 		       t != NULL_TREE;
11456 		       t = TREE_CHAIN (t))
11457 		    {
11458 		      tree spec = TREE_VALUE (t);
11459 		      spec_entry elt;
11460 
11461 		      elt.tmpl = old_decl;
11462 		      elt.args = DECL_TI_ARGS (spec);
11463 		      elt.spec = NULL_TREE;
11464 
11465 		      decl_specializations->remove_elt (&elt);
11466 
11467 		      DECL_TI_ARGS (spec)
11468 			= add_outermost_template_args (new_args,
11469 						       DECL_TI_ARGS (spec));
11470 
11471 		      register_specialization
11472 			(spec, new_template, DECL_TI_ARGS (spec), true, 0);
11473 
11474 		    }
11475 		  DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
11476 		}
11477 	    }
11478 
11479 	  /* The information from NEW_FRIEND has been merged into OLD_DECL
11480 	     by duplicate_decls.  */
11481 	  new_friend = old_decl;
11482 	}
11483     }
11484   else
11485     {
11486       tree context = DECL_CONTEXT (new_friend);
11487       bool dependent_p;
11488 
11489       /* In the code
11490 	   template <class T> class C {
11491 	     template <class U> friend void C1<U>::f (); // case 1
11492 	     friend void C2<T>::f ();			 // case 2
11493 	   };
11494 	 we only need to make sure CONTEXT is a complete type for
11495 	 case 2.  To distinguish between the two cases, we note that
11496 	 CONTEXT of case 1 remains dependent type after tsubst while
11497 	 this isn't true for case 2.  */
11498       ++processing_template_decl;
11499       dependent_p = dependent_type_p (context);
11500       --processing_template_decl;
11501 
11502       if (!dependent_p
11503 	  && !complete_type_or_else (context, NULL_TREE))
11504 	return error_mark_node;
11505 
11506       if (COMPLETE_TYPE_P (context))
11507 	{
11508 	  tree fn = new_friend;
11509 	  /* do_friend adds the TEMPLATE_DECL for any member friend
11510 	     template even if it isn't a member template, i.e.
11511 	       template <class T> friend A<T>::f();
11512 	     Look through it in that case.  */
11513 	  if (TREE_CODE (fn) == TEMPLATE_DECL
11514 	      && !PRIMARY_TEMPLATE_P (fn))
11515 	    fn = DECL_TEMPLATE_RESULT (fn);
11516 	  /* Check to see that the declaration is really present, and,
11517 	     possibly obtain an improved declaration.  */
11518 	  fn = check_classfn (context, fn, NULL_TREE);
11519 
11520 	  if (fn)
11521 	    new_friend = fn;
11522 	}
11523     }
11524 
11525   return new_friend;
11526 }
11527 
11528 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
11529    template arguments, as for tsubst.
11530 
11531    Returns an appropriate tsubst'd friend type or error_mark_node on
11532    failure.  */
11533 
11534 static tree
tsubst_friend_class(tree friend_tmpl,tree args)11535 tsubst_friend_class (tree friend_tmpl, tree args)
11536 {
11537   tree tmpl;
11538 
11539   if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
11540     {
11541       tmpl = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
11542       return TREE_TYPE (tmpl);
11543     }
11544 
11545   tree context = CP_DECL_CONTEXT (friend_tmpl);
11546   if (TREE_CODE (context) == NAMESPACE_DECL)
11547     push_nested_namespace (context);
11548   else
11549     {
11550       context = tsubst (context, args, tf_error, NULL_TREE);
11551       push_nested_class (context);
11552     }
11553 
11554   tmpl = lookup_name (DECL_NAME (friend_tmpl), LOOK_where::CLASS_NAMESPACE,
11555 		      LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND);
11556 
11557   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
11558     {
11559       /* The friend template has already been declared.  Just
11560 	 check to see that the declarations match, and install any new
11561 	 default parameters.  We must tsubst the default parameters,
11562 	 of course.  We only need the innermost template parameters
11563 	 because that is all that redeclare_class_template will look
11564 	 at.  */
11565       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
11566 	  > TMPL_ARGS_DEPTH (args))
11567 	{
11568 	  tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
11569 					      args, tf_warning_or_error);
11570 	  tsubst_each_template_parm_constraints (parms, args,
11571 						 tf_warning_or_error);
11572           location_t saved_input_location = input_location;
11573           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
11574           tree cons = get_constraints (tmpl);
11575           redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
11576           input_location = saved_input_location;
11577 	}
11578     }
11579   else
11580     {
11581       /* The friend template has not already been declared.  In this
11582 	 case, the instantiation of the template class will cause the
11583 	 injection of this template into the namespace scope.  */
11584       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
11585 
11586       if (tmpl != error_mark_node)
11587 	{
11588 	  /* The new TMPL is not an instantiation of anything, so we
11589 	     forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE
11590 	     for the new type because that is supposed to be the
11591 	     corresponding template decl, i.e., TMPL.  */
11592 	  DECL_USE_TEMPLATE (tmpl) = 0;
11593 	  DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
11594 	  CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
11595 	  CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
11596 	    = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
11597 
11598 	  /* Substitute into and set the constraints on the new declaration.  */
11599 	  if (tree ci = get_constraints (friend_tmpl))
11600 	    {
11601 	      ++processing_template_decl;
11602 	      ci = tsubst_constraint_info (ci, args, tf_warning_or_error,
11603 					   DECL_FRIEND_CONTEXT (friend_tmpl));
11604 	      --processing_template_decl;
11605 	      set_constraints (tmpl, ci);
11606 	      tsubst_each_template_parm_constraints (DECL_TEMPLATE_PARMS (tmpl),
11607 						     args, tf_warning_or_error);
11608 	    }
11609 
11610 	  /* Inject this template into the enclosing namspace scope.  */
11611 	  tmpl = pushdecl_namespace_level (tmpl, /*hiding=*/true);
11612 	}
11613     }
11614 
11615   if (TREE_CODE (context) == NAMESPACE_DECL)
11616     pop_nested_namespace (context);
11617   else
11618     pop_nested_class ();
11619 
11620   return TREE_TYPE (tmpl);
11621 }
11622 
11623 /* Returns zero if TYPE cannot be completed later due to circularity.
11624    Otherwise returns one.  */
11625 
11626 static int
can_complete_type_without_circularity(tree type)11627 can_complete_type_without_circularity (tree type)
11628 {
11629   if (type == NULL_TREE || type == error_mark_node)
11630     return 0;
11631   else if (COMPLETE_TYPE_P (type))
11632     return 1;
11633   else if (TREE_CODE (type) == ARRAY_TYPE)
11634     return can_complete_type_without_circularity (TREE_TYPE (type));
11635   else if (CLASS_TYPE_P (type)
11636 	   && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
11637     return 0;
11638   else
11639     return 1;
11640 }
11641 
11642 static tree tsubst_omp_clauses (tree, enum c_omp_region_type, tree,
11643 				tsubst_flags_t, tree);
11644 
11645 /* Instantiate a single dependent attribute T (a TREE_LIST), and return either
11646    T or a new TREE_LIST, possibly a chain in the case of a pack expansion.  */
11647 
11648 static tree
tsubst_attribute(tree t,tree * decl_p,tree args,tsubst_flags_t complain,tree in_decl)11649 tsubst_attribute (tree t, tree *decl_p, tree args,
11650 		  tsubst_flags_t complain, tree in_decl)
11651 {
11652   gcc_assert (ATTR_IS_DEPENDENT (t));
11653 
11654   tree val = TREE_VALUE (t);
11655   if (val == NULL_TREE)
11656     /* Nothing to do.  */;
11657   else if ((flag_openmp || flag_openmp_simd)
11658 	   && is_attribute_p ("omp declare simd",
11659 			      get_attribute_name (t)))
11660     {
11661       tree clauses = TREE_VALUE (val);
11662       clauses = tsubst_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD, args,
11663 				    complain, in_decl);
11664       c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11665       clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11666       tree parms = DECL_ARGUMENTS (*decl_p);
11667       clauses
11668 	= c_omp_declare_simd_clauses_to_numbers (parms, clauses);
11669       if (clauses)
11670 	val = build_tree_list (NULL_TREE, clauses);
11671       else
11672 	val = NULL_TREE;
11673     }
11674   else if (flag_openmp
11675 	   && is_attribute_p ("omp declare variant base",
11676 			      get_attribute_name (t)))
11677     {
11678       ++cp_unevaluated_operand;
11679       tree varid
11680 	= tsubst_expr (TREE_PURPOSE (val), args, complain,
11681 		       in_decl, /*integral_constant_expression_p=*/false);
11682       --cp_unevaluated_operand;
11683       tree chain = TREE_CHAIN (val);
11684       location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
11685       tree ctx = copy_list (TREE_VALUE (val));
11686       tree simd = get_identifier ("simd");
11687       tree score = get_identifier (" score");
11688       tree condition = get_identifier ("condition");
11689       for (tree t1 = ctx; t1; t1 = TREE_CHAIN (t1))
11690 	{
11691 	  const char *set = IDENTIFIER_POINTER (TREE_PURPOSE (t1));
11692 	  TREE_VALUE (t1) = copy_list (TREE_VALUE (t1));
11693 	  for (tree t2 = TREE_VALUE (t1); t2; t2 = TREE_CHAIN (t2))
11694 	    {
11695 	      if (TREE_PURPOSE (t2) == simd && set[0] == 'c')
11696 		{
11697 		  tree clauses = TREE_VALUE (t2);
11698 		  clauses = tsubst_omp_clauses (clauses,
11699 						C_ORT_OMP_DECLARE_SIMD, args,
11700 						complain, in_decl);
11701 		  c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11702 		  clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11703 		  TREE_VALUE (t2) = clauses;
11704 		}
11705 	      else
11706 		{
11707 		  TREE_VALUE (t2) = copy_list (TREE_VALUE (t2));
11708 		  for (tree t3 = TREE_VALUE (t2); t3; t3 = TREE_CHAIN (t3))
11709 		    if (TREE_VALUE (t3))
11710 		      {
11711 			bool allow_string
11712 			  = ((TREE_PURPOSE (t2) != condition || set[0] != 'u')
11713 			     && TREE_PURPOSE (t3) != score);
11714 			tree v = TREE_VALUE (t3);
11715 			if (TREE_CODE (v) == STRING_CST && allow_string)
11716 			  continue;
11717 			v = tsubst_expr (v, args, complain, in_decl, true);
11718 			v = fold_non_dependent_expr (v);
11719 			if (!INTEGRAL_TYPE_P (TREE_TYPE (v))
11720 			    || (TREE_PURPOSE (t3) == score
11721 				? TREE_CODE (v) != INTEGER_CST
11722 				: !tree_fits_shwi_p (v)))
11723 			  {
11724 			    location_t loc
11725 			      = cp_expr_loc_or_loc (TREE_VALUE (t3),
11726 						    match_loc);
11727 			    if (TREE_PURPOSE (t3) == score)
11728 			      error_at (loc, "score argument must be "
11729 					     "constant integer expression");
11730 			    else if (allow_string)
11731 			      error_at (loc, "property must be constant "
11732 					     "integer expression or string "
11733 					     "literal");
11734 			    else
11735 			      error_at (loc, "property must be constant "
11736 					     "integer expression");
11737 			    return NULL_TREE;
11738 			  }
11739 			else if (TREE_PURPOSE (t3) == score
11740 				 && tree_int_cst_sgn (v) < 0)
11741 			  {
11742 			    location_t loc
11743 			      = cp_expr_loc_or_loc (TREE_VALUE (t3),
11744 						    match_loc);
11745 			    error_at (loc, "score argument must be "
11746 					   "non-negative");
11747 			    return NULL_TREE;
11748 			  }
11749 			TREE_VALUE (t3) = v;
11750 		      }
11751 		}
11752 	    }
11753 	}
11754       val = tree_cons (varid, ctx, chain);
11755     }
11756   /* If the first attribute argument is an identifier, don't
11757      pass it through tsubst.  Attributes like mode, format,
11758      cleanup and several target specific attributes expect it
11759      unmodified.  */
11760   else if (attribute_takes_identifier_p (get_attribute_name (t)))
11761     {
11762       tree chain
11763 	= tsubst_expr (TREE_CHAIN (val), args, complain, in_decl,
11764 		       /*integral_constant_expression_p=*/false);
11765       if (chain != TREE_CHAIN (val))
11766 	val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
11767     }
11768   else if (PACK_EXPANSION_P (val))
11769     {
11770       /* An attribute pack expansion.  */
11771       tree purp = TREE_PURPOSE (t);
11772       tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
11773       if (pack == error_mark_node)
11774 	return error_mark_node;
11775       int len = TREE_VEC_LENGTH (pack);
11776       tree list = NULL_TREE;
11777       tree *q = &list;
11778       for (int i = 0; i < len; ++i)
11779 	{
11780 	  tree elt = TREE_VEC_ELT (pack, i);
11781 	  *q = build_tree_list (purp, elt);
11782 	  q = &TREE_CHAIN (*q);
11783 	}
11784       return list;
11785     }
11786   else
11787     val = tsubst_expr (val, args, complain, in_decl,
11788 		       /*integral_constant_expression_p=*/false);
11789 
11790   if (val == error_mark_node)
11791     return error_mark_node;
11792   if (val != TREE_VALUE (t))
11793     return build_tree_list (TREE_PURPOSE (t), val);
11794   return t;
11795 }
11796 
11797 /* Instantiate any dependent attributes in ATTRIBUTES, returning either it
11798    unchanged or a new TREE_LIST chain.  */
11799 
11800 static tree
tsubst_attributes(tree attributes,tree args,tsubst_flags_t complain,tree in_decl)11801 tsubst_attributes (tree attributes, tree args,
11802 		   tsubst_flags_t complain, tree in_decl)
11803 {
11804   tree last_dep = NULL_TREE;
11805 
11806   for (tree t = attributes; t; t = TREE_CHAIN (t))
11807     if (ATTR_IS_DEPENDENT (t))
11808       {
11809 	last_dep = t;
11810 	attributes = copy_list (attributes);
11811 	break;
11812       }
11813 
11814   if (last_dep)
11815     for (tree *p = &attributes; *p; )
11816       {
11817 	tree t = *p;
11818 	if (ATTR_IS_DEPENDENT (t))
11819 	  {
11820 	    tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
11821 	    if (subst != t)
11822 	      {
11823 		*p = subst;
11824 		while (*p)
11825 		  p = &TREE_CHAIN (*p);
11826 		*p = TREE_CHAIN (t);
11827 		continue;
11828 	      }
11829 	  }
11830 	p = &TREE_CHAIN (*p);
11831       }
11832 
11833   return attributes;
11834 }
11835 
11836 /* Apply any attributes which had to be deferred until instantiation
11837    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
11838    ARGS, COMPLAIN, IN_DECL are as tsubst.  Returns true normally,
11839    false on error.  */
11840 
11841 static bool
apply_late_template_attributes(tree * decl_p,tree attributes,int attr_flags,tree args,tsubst_flags_t complain,tree in_decl)11842 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
11843 				tree args, tsubst_flags_t complain, tree in_decl)
11844 {
11845   tree t;
11846   tree *p;
11847 
11848   if (attributes == NULL_TREE)
11849     return true;
11850 
11851   if (DECL_P (*decl_p))
11852     {
11853       if (TREE_TYPE (*decl_p) == error_mark_node)
11854 	return false;
11855       p = &DECL_ATTRIBUTES (*decl_p);
11856       /* DECL_ATTRIBUTES comes from copy_node in tsubst_decl, and is identical
11857          to our attributes parameter.  */
11858       gcc_assert (*p == attributes);
11859     }
11860   else
11861     {
11862       p = &TYPE_ATTRIBUTES (*decl_p);
11863       /* TYPE_ATTRIBUTES was set up (with abi_tag and may_alias) in
11864 	 lookup_template_class_1, and should be preserved.  */
11865       gcc_assert (*p != attributes);
11866       while (*p)
11867 	p = &TREE_CHAIN (*p);
11868     }
11869 
11870   /* save_template_attributes puts the dependent attributes at the beginning of
11871      the list; find the non-dependent ones.  */
11872   for (t = attributes; t; t = TREE_CHAIN (t))
11873     if (!ATTR_IS_DEPENDENT (t))
11874       break;
11875   tree nondep = t;
11876 
11877   /* Apply any non-dependent attributes.  */
11878   *p = nondep;
11879 
11880   if (nondep == attributes)
11881     return true;
11882 
11883   /* And then any dependent ones.  */
11884   tree late_attrs = NULL_TREE;
11885   tree *q = &late_attrs;
11886   for (t = attributes; t != nondep; t = TREE_CHAIN (t))
11887     {
11888       *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
11889       if (*q == error_mark_node)
11890 	return false;
11891       if (*q == t)
11892 	{
11893 	  *q = copy_node (t);
11894 	  TREE_CHAIN (*q) = NULL_TREE;
11895 	}
11896       while (*q)
11897 	q = &TREE_CHAIN (*q);
11898     }
11899 
11900   /* cplus_decl_attributes can add some attributes implicitly.  For templates,
11901      those attributes should have been added already when those templates were
11902      parsed, and shouldn't be added based on from which context they are
11903      first time instantiated.  */
11904   auto o1 = make_temp_override (current_optimize_pragma, NULL_TREE);
11905   auto o2 = make_temp_override (optimization_current_node,
11906 				optimization_default_node);
11907   auto o3 = make_temp_override (current_target_pragma, NULL_TREE);
11908   auto o4 = make_temp_override (scope_chain->omp_declare_target_attribute,
11909 				NULL);
11910 
11911   cplus_decl_attributes (decl_p, late_attrs, attr_flags);
11912 
11913   return true;
11914 }
11915 
11916 /* The template TMPL is being instantiated with the template arguments TARGS.
11917    Perform the access checks that we deferred when parsing the template.  */
11918 
11919 static void
perform_instantiation_time_access_checks(tree tmpl,tree targs)11920 perform_instantiation_time_access_checks (tree tmpl, tree targs)
11921 {
11922   unsigned i;
11923   deferred_access_check *chk;
11924 
11925   if (!CLASS_TYPE_P (tmpl) && TREE_CODE (tmpl) != FUNCTION_DECL)
11926     return;
11927 
11928   if (vec<deferred_access_check, va_gc> *access_checks
11929       = TI_DEFERRED_ACCESS_CHECKS (get_template_info (tmpl)))
11930     FOR_EACH_VEC_ELT (*access_checks, i, chk)
11931       {
11932 	tree decl = chk->decl;
11933 	tree diag_decl = chk->diag_decl;
11934 	tree type_scope = TREE_TYPE (chk->binfo);
11935 
11936 	if (uses_template_parms (type_scope))
11937 	  type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
11938 
11939 	/* Make access check error messages point to the location
11940 	   of the use of the typedef.  */
11941 	iloc_sentinel ils (chk->loc);
11942 	perform_or_defer_access_check (TYPE_BINFO (type_scope),
11943 				       decl, diag_decl, tf_warning_or_error);
11944       }
11945 }
11946 
11947 static tree
instantiate_class_template_1(tree type)11948 instantiate_class_template_1 (tree type)
11949 {
11950   tree templ, args, pattern, t, member;
11951   tree typedecl;
11952   tree pbinfo;
11953   tree base_list;
11954   unsigned int saved_maximum_field_alignment;
11955   tree fn_context;
11956 
11957   if (type == error_mark_node)
11958     return error_mark_node;
11959 
11960   if (COMPLETE_OR_OPEN_TYPE_P (type)
11961       || uses_template_parms (type))
11962     return type;
11963 
11964   /* Figure out which template is being instantiated.  */
11965   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
11966   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
11967 
11968   /* Mark the type as in the process of being defined.  */
11969   TYPE_BEING_DEFINED (type) = 1;
11970 
11971   /* We may be in the middle of deferred access check.  Disable
11972      it now.  */
11973   deferring_access_check_sentinel acs (dk_no_deferred);
11974 
11975   /* Determine what specialization of the original template to
11976      instantiate.  */
11977   t = most_specialized_partial_spec (type, tf_warning_or_error);
11978   if (t == error_mark_node)
11979     return error_mark_node;
11980   else if (t)
11981     {
11982       /* This TYPE is actually an instantiation of a partial
11983 	 specialization.  We replace the innermost set of ARGS with
11984 	 the arguments appropriate for substitution.  For example,
11985 	 given:
11986 
11987 	   template <class T> struct S {};
11988 	   template <class T> struct S<T*> {};
11989 
11990 	 and supposing that we are instantiating S<int*>, ARGS will
11991 	 presently be {int*} -- but we need {int}.  */
11992       pattern = TREE_TYPE (t);
11993       args = TREE_PURPOSE (t);
11994     }
11995   else
11996     {
11997       pattern = TREE_TYPE (templ);
11998       args = CLASSTYPE_TI_ARGS (type);
11999     }
12000 
12001   /* If the template we're instantiating is incomplete, then clearly
12002      there's nothing we can do.  */
12003   if (!COMPLETE_TYPE_P (pattern))
12004     {
12005       /* We can try again later.  */
12006       TYPE_BEING_DEFINED (type) = 0;
12007       return type;
12008     }
12009 
12010   /* If we've recursively instantiated too many templates, stop.  */
12011   if (! push_tinst_level (type))
12012     return type;
12013 
12014   int saved_unevaluated_operand = cp_unevaluated_operand;
12015   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
12016 
12017   fn_context = decl_function_context (TYPE_MAIN_DECL (type));
12018   /* Also avoid push_to_top_level for a lambda in an NSDMI.  */
12019   if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
12020     fn_context = error_mark_node;
12021   if (!fn_context)
12022     push_to_top_level ();
12023   else
12024     {
12025       cp_unevaluated_operand = 0;
12026       c_inhibit_evaluation_warnings = 0;
12027     }
12028   /* Use #pragma pack from the template context.  */
12029   saved_maximum_field_alignment = maximum_field_alignment;
12030   maximum_field_alignment = TYPE_PRECISION (pattern);
12031 
12032   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
12033 
12034   /* Set the input location to the most specialized template definition.
12035      This is needed if tsubsting causes an error.  */
12036   typedecl = TYPE_MAIN_DECL (pattern);
12037   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
12038     DECL_SOURCE_LOCATION (typedecl);
12039 
12040   set_instantiating_module (TYPE_NAME (type));
12041 
12042   TYPE_PACKED (type) = TYPE_PACKED (pattern);
12043   SET_TYPE_ALIGN (type, TYPE_ALIGN (pattern));
12044   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
12045   CLASSTYPE_NON_AGGREGATE (type) = CLASSTYPE_NON_AGGREGATE (pattern);
12046   if (ANON_AGGR_TYPE_P (pattern))
12047     SET_ANON_AGGR_TYPE_P (type);
12048   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
12049     {
12050       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
12051       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
12052       /* Adjust visibility for template arguments.  */
12053       determine_visibility (TYPE_MAIN_DECL (type));
12054     }
12055   if (CLASS_TYPE_P (type))
12056     CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
12057 
12058   pbinfo = TYPE_BINFO (pattern);
12059 
12060   /* We should never instantiate a nested class before its enclosing
12061      class; we need to look up the nested class by name before we can
12062      instantiate it, and that lookup should instantiate the enclosing
12063      class.  */
12064   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
12065 	      || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
12066 
12067   base_list = NULL_TREE;
12068   /* Defer access checking while we substitute into the types named in
12069      the base-clause.  */
12070   push_deferring_access_checks (dk_deferred);
12071   if (BINFO_N_BASE_BINFOS (pbinfo))
12072     {
12073       tree pbase_binfo;
12074       int i;
12075 
12076       /* Substitute into each of the bases to determine the actual
12077 	 basetypes.  */
12078       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
12079 	{
12080 	  tree base;
12081 	  tree access = BINFO_BASE_ACCESS (pbinfo, i);
12082           tree expanded_bases = NULL_TREE;
12083           int idx, len = 1;
12084 
12085           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
12086             {
12087               expanded_bases =
12088 		tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
12089 				       args, tf_error, NULL_TREE);
12090               if (expanded_bases == error_mark_node)
12091                 continue;
12092 
12093               len = TREE_VEC_LENGTH (expanded_bases);
12094             }
12095 
12096           for (idx = 0; idx < len; idx++)
12097             {
12098               if (expanded_bases)
12099                 /* Extract the already-expanded base class.  */
12100                 base = TREE_VEC_ELT (expanded_bases, idx);
12101               else
12102                 /* Substitute to figure out the base class.  */
12103                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
12104                                NULL_TREE);
12105 
12106               if (base == error_mark_node)
12107                 continue;
12108 
12109               base_list = tree_cons (access, base, base_list);
12110               if (BINFO_VIRTUAL_P (pbase_binfo))
12111                 TREE_TYPE (base_list) = integer_type_node;
12112             }
12113 	}
12114 
12115       /* The list is now in reverse order; correct that.  */
12116       base_list = nreverse (base_list);
12117     }
12118   /* Now call xref_basetypes to set up all the base-class
12119      information.  */
12120   xref_basetypes (type, base_list);
12121 
12122   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
12123 				  (int) ATTR_FLAG_TYPE_IN_PLACE,
12124 				  args, tf_error, NULL_TREE);
12125   fixup_attribute_variants (type);
12126 
12127   /* Now that our base classes are set up, enter the scope of the
12128      class, so that name lookups into base classes, etc. will work
12129      correctly.  This is precisely analogous to what we do in
12130      begin_class_definition when defining an ordinary non-template
12131      class, except we also need to push the enclosing classes.  */
12132   push_nested_class (type);
12133 
12134   /* Now check accessibility of the types named in its base-clause,
12135      relative to the scope of the class.  */
12136   pop_to_parent_deferring_access_checks ();
12137 
12138   /* A vector to hold members marked with attribute used. */
12139   auto_vec<tree> used;
12140 
12141   /* Now members are processed in the order of declaration.  */
12142   for (member = CLASSTYPE_DECL_LIST (pattern);
12143        member; member = TREE_CHAIN (member))
12144     {
12145       tree t = TREE_VALUE (member);
12146 
12147       if (TREE_PURPOSE (member))
12148 	{
12149 	  if (TYPE_P (t))
12150 	    {
12151 	      if (LAMBDA_TYPE_P (t))
12152 		/* A closure type for a lambda in an NSDMI or default argument.
12153 		   Ignore it; it will be regenerated when needed.  */
12154 		continue;
12155 
12156 	      bool class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
12157 				       && TYPE_LANG_SPECIFIC (t)
12158 				       && CLASSTYPE_IS_TEMPLATE (t));
12159 
12160 	      /* If the member is a class template, then -- even after
12161 		 substitution -- there may be dependent types in the
12162 		 template argument list for the class.  We increment
12163 		 PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
12164 		 that function will assume that no types are dependent
12165 		 when outside of a template.  */
12166 	      if (class_template_p)
12167 		++processing_template_decl;
12168 	      tree newtag = tsubst (t, args, tf_error, NULL_TREE);
12169 	      if (class_template_p)
12170 		--processing_template_decl;
12171 	      if (newtag == error_mark_node)
12172 		continue;
12173 
12174 	      if (TREE_CODE (newtag) != ENUMERAL_TYPE)
12175 		{
12176 		  tree name = TYPE_IDENTIFIER (t);
12177 
12178 		  if (class_template_p)
12179 		    /* Unfortunately, lookup_template_class sets
12180 		       CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
12181 		       instantiation (i.e., for the type of a member
12182 		       template class nested within a template class.)
12183 		       This behavior is required for
12184 		       maybe_process_partial_specialization to work
12185 		       correctly, but is not accurate in this case;
12186 		       the TAG is not an instantiation of anything.
12187 		       (The corresponding TEMPLATE_DECL is an
12188 		       instantiation, but the TYPE is not.) */
12189 		    CLASSTYPE_USE_TEMPLATE (newtag) = 0;
12190 
12191 		  /* Now, install the tag.  We don't use pushtag
12192 		     because that does too much work -- creating an
12193 		     implicit typedef, which we've already done.  */
12194 		  set_identifier_type_value (name, TYPE_NAME (newtag));
12195 		  maybe_add_class_template_decl_list (type, newtag, false);
12196 		  TREE_PUBLIC (TYPE_NAME (newtag)) = true;
12197 		  determine_visibility (TYPE_NAME (newtag));
12198 		}
12199 	    }
12200 	  else if (DECL_DECLARES_FUNCTION_P (t))
12201 	    {
12202 	      tree r;
12203 
12204 	      if (TREE_CODE (t) == TEMPLATE_DECL)
12205 		++processing_template_decl;
12206 	      r = tsubst (t, args, tf_error, NULL_TREE);
12207 	      if (TREE_CODE (t) == TEMPLATE_DECL)
12208 		--processing_template_decl;
12209 	      set_current_access_from_decl (r);
12210 	      finish_member_declaration (r);
12211 	      /* Instantiate members marked with attribute used.  */
12212 	      if (r != error_mark_node && DECL_PRESERVE_P (r))
12213 		used.safe_push (r);
12214 	      if (TREE_CODE (r) == FUNCTION_DECL
12215 		  && DECL_OMP_DECLARE_REDUCTION_P (r))
12216 		cp_check_omp_declare_reduction (r);
12217 	    }
12218 	  else if ((DECL_CLASS_TEMPLATE_P (t) || DECL_IMPLICIT_TYPEDEF_P (t))
12219 		   && LAMBDA_TYPE_P (TREE_TYPE (t)))
12220 	    /* A closure type for a lambda in an NSDMI or default argument.
12221 	       Ignore it; it will be regenerated when needed.  */;
12222 	  else
12223 	    {
12224 	      /* Build new TYPE_FIELDS.  */
12225               if (TREE_CODE (t) == STATIC_ASSERT)
12226 		tsubst_expr (t, args, tf_warning_or_error, NULL_TREE,
12227 			     /*integral_constant_expression_p=*/true);
12228 	      else if (TREE_CODE (t) != CONST_DECL)
12229 		{
12230 		  tree r;
12231 		  tree vec = NULL_TREE;
12232 		  int len = 1;
12233 
12234 		  gcc_checking_assert (TREE_CODE (t) != CONST_DECL);
12235 		  /* The file and line for this declaration, to
12236 		     assist in error message reporting.  Since we
12237 		     called push_tinst_level above, we don't need to
12238 		     restore these.  */
12239 		  input_location = DECL_SOURCE_LOCATION (t);
12240 
12241 		  if (TREE_CODE (t) == TEMPLATE_DECL)
12242 		    ++processing_template_decl;
12243 		  r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
12244 		  if (TREE_CODE (t) == TEMPLATE_DECL)
12245 		    --processing_template_decl;
12246 
12247 		  if (TREE_CODE (r) == TREE_VEC)
12248 		    {
12249 		      /* A capture pack became multiple fields.  */
12250 		      vec = r;
12251 		      len = TREE_VEC_LENGTH (vec);
12252 		    }
12253 
12254 		  for (int i = 0; i < len; ++i)
12255 		    {
12256 		      if (vec)
12257 			r = TREE_VEC_ELT (vec, i);
12258 		      if (VAR_P (r))
12259 			{
12260 			  /* In [temp.inst]:
12261 
12262 			     [t]he initialization (and any associated
12263 			     side-effects) of a static data member does
12264 			     not occur unless the static data member is
12265 			     itself used in a way that requires the
12266 			     definition of the static data member to
12267 			     exist.
12268 
12269 			     Therefore, we do not substitute into the
12270 			     initialized for the static data member here.  */
12271 			  finish_static_data_member_decl
12272 			    (r,
12273 			     /*init=*/NULL_TREE,
12274 			     /*init_const_expr_p=*/false,
12275 			     /*asmspec_tree=*/NULL_TREE,
12276 			     /*flags=*/0);
12277 			  /* Instantiate members marked with attribute used. */
12278 			  if (r != error_mark_node && DECL_PRESERVE_P (r))
12279 			    used.safe_push (r);
12280 			}
12281 		      else if (TREE_CODE (r) == FIELD_DECL)
12282 			{
12283 			  /* Determine whether R has a valid type and can be
12284 			     completed later.  If R is invalid, then its type
12285 			     is replaced by error_mark_node.  */
12286 			  tree rtype = TREE_TYPE (r);
12287 			  if (can_complete_type_without_circularity (rtype))
12288 			    complete_type (rtype);
12289 
12290 			  if (!complete_or_array_type_p (rtype))
12291 			    {
12292 			      /* If R's type couldn't be completed and
12293 				 it isn't a flexible array member (whose
12294 				 type is incomplete by definition) give
12295 				 an error.  */
12296 			      cxx_incomplete_type_error (r, rtype);
12297 			      TREE_TYPE (r) = error_mark_node;
12298 			    }
12299 			  else if (TREE_CODE (rtype) == ARRAY_TYPE
12300 				   && TYPE_DOMAIN (rtype) == NULL_TREE
12301 				   && (TREE_CODE (type) == UNION_TYPE
12302 				       || TREE_CODE (type) == QUAL_UNION_TYPE))
12303 			    {
12304 			      error ("flexible array member %qD in union", r);
12305 			      TREE_TYPE (r) = error_mark_node;
12306 			    }
12307 			  else if (!verify_type_context (input_location,
12308 							 TCTX_FIELD, rtype))
12309 			    TREE_TYPE (r) = error_mark_node;
12310 			}
12311 
12312 		      /* If it is a TYPE_DECL for a class-scoped
12313 			 ENUMERAL_TYPE, such a thing will already have
12314 			 been added to the field list by tsubst_enum
12315 			 in finish_member_declaration case above.  */
12316 		      if (!(TREE_CODE (r) == TYPE_DECL
12317 			    && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
12318 			    && DECL_ARTIFICIAL (r)))
12319 			{
12320 			  set_current_access_from_decl (r);
12321 			  finish_member_declaration (r);
12322 			}
12323 		    }
12324 		}
12325 	    }
12326 	}
12327       else
12328 	{
12329 	  if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
12330 	      || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
12331 	    {
12332 	      /* Build new CLASSTYPE_FRIEND_CLASSES.  */
12333 
12334 	      tree friend_type = t;
12335 	      if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12336 		{
12337 		  /* template <class T> friend class C;  */
12338 		  friend_type = tsubst_friend_class (friend_type, args);
12339 		}
12340 	      else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
12341 		{
12342 		  /* template <class T> friend class C::D;  */
12343 		  friend_type = tsubst (friend_type, args,
12344 					tf_warning_or_error, NULL_TREE);
12345 		  if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12346 		    friend_type = TREE_TYPE (friend_type);
12347 		}
12348 	      else if (TREE_CODE (friend_type) == TYPENAME_TYPE
12349 		       || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
12350 		{
12351 		  /* This could be either
12352 
12353 		       friend class T::C;
12354 
12355 		     when dependent_type_p is false or
12356 
12357 		       template <class U> friend class T::C;
12358 
12359 		     otherwise.  */
12360 		  /* Bump processing_template_decl in case this is something like
12361 		     template <class T> friend struct A<T>::B.  */
12362 		  ++processing_template_decl;
12363 		  friend_type = tsubst (friend_type, args,
12364 					tf_warning_or_error, NULL_TREE);
12365 		  --processing_template_decl;
12366 		}
12367 	      else if (uses_template_parms (friend_type))
12368 		/* friend class C<T>;  */
12369 		friend_type = tsubst (friend_type, args,
12370 				      tf_warning_or_error, NULL_TREE);
12371 
12372 	      /* Otherwise it's
12373 
12374 		   friend class C;
12375 
12376 		 where C is already declared or
12377 
12378 		   friend class C<int>;
12379 
12380 		 We don't have to do anything in these cases.  */
12381 
12382 	      if (friend_type != error_mark_node)
12383 		make_friend_class (type, friend_type, /*complain=*/false);
12384 	    }
12385 	  else
12386 	    {
12387 	      /* Build new DECL_FRIENDLIST.  */
12388 	      tree r;
12389 
12390 	      /* The file and line for this declaration, to
12391 		 assist in error message reporting.  Since we
12392 		 called push_tinst_level above, we don't need to
12393 		 restore these.  */
12394 	      input_location = DECL_SOURCE_LOCATION (t);
12395 
12396 	      if (TREE_CODE (t) == TEMPLATE_DECL)
12397 		{
12398 		  ++processing_template_decl;
12399 		  push_deferring_access_checks (dk_no_check);
12400 		}
12401 
12402 	      r = tsubst_friend_function (t, args);
12403 	      add_friend (type, r, /*complain=*/false);
12404 	      if (TREE_CODE (t) == TEMPLATE_DECL)
12405 		{
12406 		  pop_deferring_access_checks ();
12407 		  --processing_template_decl;
12408 		}
12409 	    }
12410 	}
12411     }
12412 
12413   if (fn_context)
12414     {
12415       /* Restore these before substituting into the lambda capture
12416 	 initializers.  */
12417       cp_unevaluated_operand = saved_unevaluated_operand;
12418       c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
12419     }
12420 
12421   /* Set the file and line number information to whatever is given for
12422      the class itself.  This puts error messages involving generated
12423      implicit functions at a predictable point, and the same point
12424      that would be used for non-template classes.  */
12425   input_location = DECL_SOURCE_LOCATION (typedecl);
12426 
12427   unreverse_member_declarations (type);
12428   finish_struct_1 (type);
12429   TYPE_BEING_DEFINED (type) = 0;
12430 
12431   /* Remember if instantiating this class ran into errors, so we can avoid
12432      instantiating member functions in limit_bad_template_recursion.  We set
12433      this flag even if the problem was in another instantiation triggered by
12434      this one, as that will likely also cause trouble for member functions.  */
12435   if (errorcount + sorrycount > current_tinst_level->errors)
12436     CLASSTYPE_ERRONEOUS (type) = true;
12437 
12438   /* We don't instantiate default arguments for member functions.  14.7.1:
12439 
12440      The implicit instantiation of a class template specialization causes
12441      the implicit instantiation of the declarations, but not of the
12442      definitions or default arguments, of the class member functions,
12443      member classes, static data members and member templates....  */
12444 
12445   perform_instantiation_time_access_checks (pattern, args);
12446   perform_deferred_access_checks (tf_warning_or_error);
12447 
12448   /* Now that we've gone through all the members, instantiate those
12449      marked with attribute used.  We must do this in the context of
12450      the class -- not the context we pushed from, as that might be
12451      inside a template and change the behaviour of mark_used.  */
12452   for (tree x : used)
12453     mark_used (x);
12454 
12455   pop_nested_class ();
12456   maximum_field_alignment = saved_maximum_field_alignment;
12457   if (!fn_context)
12458     pop_from_top_level ();
12459   pop_tinst_level ();
12460 
12461   /* The vtable for a template class can be emitted in any translation
12462      unit in which the class is instantiated.  When there is no key
12463      method, however, finish_struct_1 will already have added TYPE to
12464      the keyed_classes.  */
12465   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
12466     vec_safe_push (keyed_classes, type);
12467 
12468   return type;
12469 }
12470 
12471 /* Wrapper for instantiate_class_template_1.  */
12472 
12473 tree
instantiate_class_template(tree type)12474 instantiate_class_template (tree type)
12475 {
12476   tree ret;
12477   timevar_push (TV_TEMPLATE_INST);
12478   ret = instantiate_class_template_1 (type);
12479   timevar_pop (TV_TEMPLATE_INST);
12480   return ret;
12481 }
12482 
12483 tree
tsubst_template_arg(tree t,tree args,tsubst_flags_t complain,tree in_decl)12484 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12485 {
12486   tree r;
12487 
12488   if (!t)
12489     r = t;
12490   else if (TYPE_P (t))
12491     r = tsubst (t, args, complain, in_decl);
12492   else
12493     {
12494       if (!(complain & tf_warning))
12495 	++c_inhibit_evaluation_warnings;
12496       r = tsubst_expr (t, args, complain, in_decl,
12497 		       /*integral_constant_expression_p=*/true);
12498       if (!(complain & tf_warning))
12499 	--c_inhibit_evaluation_warnings;
12500     }
12501 
12502   return r;
12503 }
12504 
12505 /* Given a function parameter pack TMPL_PARM and some function parameters
12506    instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
12507    and set *SPEC_P to point at the next point in the list.  */
12508 
12509 tree
extract_fnparm_pack(tree tmpl_parm,tree * spec_p)12510 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
12511 {
12512   /* Collect all of the extra "packed" parameters into an
12513      argument pack.  */
12514   tree argpack;
12515   tree spec_parm = *spec_p;
12516   int len;
12517 
12518   for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
12519     if (tmpl_parm
12520 	&& !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
12521       break;
12522 
12523   spec_parm = *spec_p;
12524   if (len == 1 && DECL_PACK_P (spec_parm))
12525     {
12526       /* The instantiation is still a parameter pack; don't wrap it in a
12527 	 NONTYPE_ARGUMENT_PACK.  */
12528       argpack = spec_parm;
12529       spec_parm = DECL_CHAIN (spec_parm);
12530     }
12531   else
12532     {
12533       /* Fill in PARMVEC with all of the parameters.  */
12534       tree parmvec = make_tree_vec (len);
12535       argpack = make_node (NONTYPE_ARGUMENT_PACK);
12536       for (int i = 0; i < len; i++)
12537 	{
12538 	  tree elt = spec_parm;
12539 	  if (DECL_PACK_P (elt))
12540 	    elt = make_pack_expansion (elt);
12541 	  TREE_VEC_ELT (parmvec, i) = elt;
12542 	  spec_parm = DECL_CHAIN (spec_parm);
12543 	}
12544 
12545       /* Build the argument packs.  */
12546       SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
12547     }
12548   *spec_p = spec_parm;
12549 
12550   return argpack;
12551 }
12552 
12553 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
12554    NONTYPE_ARGUMENT_PACK.  */
12555 
12556 static tree
make_fnparm_pack(tree spec_parm)12557 make_fnparm_pack (tree spec_parm)
12558 {
12559   return extract_fnparm_pack (NULL_TREE, &spec_parm);
12560 }
12561 
12562 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
12563    pack expansion with no extra args, 2 if it has extra args, or 0
12564    if it is not a pack expansion.  */
12565 
12566 static int
argument_pack_element_is_expansion_p(tree arg_pack,int i)12567 argument_pack_element_is_expansion_p (tree arg_pack, int i)
12568 {
12569   if (TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12570     /* We're being called before this happens in tsubst_pack_expansion.  */
12571     arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12572   tree vec = ARGUMENT_PACK_ARGS (arg_pack);
12573   if (i >= TREE_VEC_LENGTH (vec))
12574     return 0;
12575   tree elt = TREE_VEC_ELT (vec, i);
12576   if (DECL_P (elt))
12577     /* A decl pack is itself an expansion.  */
12578     elt = TREE_TYPE (elt);
12579   if (!PACK_EXPANSION_P (elt))
12580     return 0;
12581   if (PACK_EXPANSION_EXTRA_ARGS (elt))
12582     return 2;
12583   return 1;
12584 }
12585 
12586 
12587 /* Creates and return an ARGUMENT_PACK_SELECT tree node.  */
12588 
12589 static tree
make_argument_pack_select(tree arg_pack,unsigned index)12590 make_argument_pack_select (tree arg_pack, unsigned index)
12591 {
12592   tree aps = make_node (ARGUMENT_PACK_SELECT);
12593 
12594   ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
12595   ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12596 
12597   return aps;
12598 }
12599 
12600 /*  This is a subroutine of tsubst_pack_expansion.
12601 
12602     It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
12603     mechanism to store the (non complete list of) arguments of the
12604     substitution and return a non substituted pack expansion, in order
12605     to wait for when we have enough arguments to really perform the
12606     substitution.  */
12607 
12608 static bool
use_pack_expansion_extra_args_p(tree t,tree parm_packs,int arg_pack_len,bool has_empty_arg)12609 use_pack_expansion_extra_args_p (tree t,
12610 				 tree parm_packs,
12611 				 int arg_pack_len,
12612 				 bool has_empty_arg)
12613 {
12614   if (has_empty_arg
12615       && PACK_EXPANSION_FORCE_EXTRA_ARGS_P (t))
12616     return true;
12617 
12618   /* If one pack has an expansion and another pack has a normal
12619      argument or if one pack has an empty argument and an another
12620      one hasn't then tsubst_pack_expansion cannot perform the
12621      substitution and need to fall back on the
12622      PACK_EXPANSION_EXTRA mechanism.  */
12623   if (parm_packs == NULL_TREE)
12624     return false;
12625   else if (has_empty_arg)
12626     {
12627       /* If all the actual packs are pack expansions, we can still
12628 	 subsitute directly.  */
12629       for (tree p = parm_packs; p; p = TREE_CHAIN (p))
12630 	{
12631 	  tree a = TREE_VALUE (p);
12632 	  if (TREE_CODE (a) == ARGUMENT_PACK_SELECT)
12633 	    a = ARGUMENT_PACK_SELECT_FROM_PACK (a);
12634 	  a = ARGUMENT_PACK_ARGS (a);
12635 	  if (TREE_VEC_LENGTH (a) == 1)
12636 	    a = TREE_VEC_ELT (a, 0);
12637 	  if (PACK_EXPANSION_P (a))
12638 	    continue;
12639 	  return true;
12640 	}
12641       return false;
12642     }
12643 
12644   for (int i = 0 ; i < arg_pack_len; ++i)
12645     {
12646       bool has_expansion_arg = false;
12647       bool has_non_expansion_arg = false;
12648       for (tree parm_pack = parm_packs;
12649 	   parm_pack;
12650 	   parm_pack = TREE_CHAIN (parm_pack))
12651 	{
12652 	  tree arg = TREE_VALUE (parm_pack);
12653 
12654 	  int exp = argument_pack_element_is_expansion_p (arg, i);
12655 	  if (exp == 2)
12656 	    /* We can't substitute a pack expansion with extra args into
12657 	       our pattern.  */
12658 	    return true;
12659 	  else if (exp)
12660 	    has_expansion_arg = true;
12661 	  else
12662 	    has_non_expansion_arg = true;
12663 	}
12664 
12665       if (has_expansion_arg && has_non_expansion_arg)
12666 	{
12667 	  gcc_checking_assert (false);
12668 	  return true;
12669 	}
12670     }
12671   return false;
12672 }
12673 
12674 /* [temp.variadic]/6 says that:
12675 
12676        The instantiation of a pack expansion [...]
12677        produces a list E1,E2, ..., En, where N is the number of elements
12678        in the pack expansion parameters.
12679 
12680    This subroutine of tsubst_pack_expansion produces one of these Ei.
12681 
12682    PATTERN is the pattern of the pack expansion.  PARM_PACKS is a
12683    TREE_LIST in which each TREE_PURPOSE is a parameter pack of
12684    PATTERN, and each TREE_VALUE is its corresponding argument pack.
12685    INDEX is the index 'i' of the element Ei to produce.  ARGS,
12686    COMPLAIN, and IN_DECL are the same parameters as for the
12687    tsubst_pack_expansion function.
12688 
12689    The function returns the resulting Ei upon successful completion,
12690    or error_mark_node.
12691 
12692    Note that this function possibly modifies the ARGS parameter, so
12693    it's the responsibility of the caller to restore it.  */
12694 
12695 static tree
gen_elem_of_pack_expansion_instantiation(tree pattern,tree parm_packs,unsigned index,tree args,tsubst_flags_t complain,tree in_decl)12696 gen_elem_of_pack_expansion_instantiation (tree pattern,
12697 					  tree parm_packs,
12698 					  unsigned index,
12699 					  tree args /* This parm gets
12700 						       modified.  */,
12701 					  tsubst_flags_t complain,
12702 					  tree in_decl)
12703 {
12704   tree t;
12705   bool ith_elem_is_expansion = false;
12706 
12707   /* For each parameter pack, change the substitution of the parameter
12708      pack to the ith argument in its argument pack, then expand the
12709      pattern.  */
12710   for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
12711     {
12712       tree parm = TREE_PURPOSE (pack);
12713       tree arg_pack = TREE_VALUE (pack);
12714       tree aps;			/* instance of ARGUMENT_PACK_SELECT.  */
12715 
12716       ith_elem_is_expansion |=
12717 	argument_pack_element_is_expansion_p (arg_pack, index);
12718 
12719       /* Select the Ith argument from the pack.  */
12720       if (TREE_CODE (parm) == PARM_DECL
12721 	  || VAR_P (parm)
12722 	  || TREE_CODE (parm) == FIELD_DECL)
12723 	{
12724 	  if (index == 0)
12725 	    {
12726 	      aps = make_argument_pack_select (arg_pack, index);
12727 	      if (!mark_used (parm, complain) && !(complain & tf_error))
12728 		return error_mark_node;
12729 	      register_local_specialization (aps, parm);
12730 	    }
12731 	  else
12732 	    aps = retrieve_local_specialization (parm);
12733 	}
12734       else
12735 	{
12736 	  int idx, level;
12737 	  template_parm_level_and_index (parm, &level, &idx);
12738 
12739 	  if (index == 0)
12740 	    {
12741 	      aps = make_argument_pack_select (arg_pack, index);
12742 	      /* Update the corresponding argument.  */
12743 	      TMPL_ARG (args, level, idx) = aps;
12744 	    }
12745 	  else
12746 	    /* Re-use the ARGUMENT_PACK_SELECT.  */
12747 	    aps = TMPL_ARG (args, level, idx);
12748 	}
12749       ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12750     }
12751 
12752   /* Substitute into the PATTERN with the (possibly altered)
12753      arguments.  */
12754   if (pattern == in_decl)
12755     /* Expanding a fixed parameter pack from
12756        coerce_template_parameter_pack.  */
12757     t = tsubst_decl (pattern, args, complain);
12758   else if (pattern == error_mark_node)
12759     t = error_mark_node;
12760   else if (!TYPE_P (pattern))
12761     t = tsubst_expr (pattern, args, complain, in_decl,
12762 		     /*integral_constant_expression_p=*/false);
12763   else
12764     {
12765       t = tsubst (pattern, args, complain, in_decl);
12766       if (is_auto (t) && !ith_elem_is_expansion)
12767 	/* When expanding the fake auto... pack expansion from add_capture, we
12768 	   need to mark that the expansion is no longer a pack.  */
12769 	TEMPLATE_TYPE_PARAMETER_PACK (t) = false;
12770     }
12771 
12772   /*  If the Ith argument pack element is a pack expansion, then
12773       the Ith element resulting from the substituting is going to
12774       be a pack expansion as well.  */
12775   if (ith_elem_is_expansion)
12776     t = make_pack_expansion (t, complain);
12777 
12778   return t;
12779 }
12780 
12781 /* When the unexpanded parameter pack in a fold expression expands to an empty
12782    sequence, the value of the expression is as follows; the program is
12783    ill-formed if the operator is not listed in this table.
12784 
12785    &&	true
12786    ||	false
12787    ,	void()  */
12788 
12789 tree
expand_empty_fold(tree t,tsubst_flags_t complain)12790 expand_empty_fold (tree t, tsubst_flags_t complain)
12791 {
12792   tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
12793   if (!FOLD_EXPR_MODIFY_P (t))
12794     switch (code)
12795       {
12796       case TRUTH_ANDIF_EXPR:
12797 	return boolean_true_node;
12798       case TRUTH_ORIF_EXPR:
12799 	return boolean_false_node;
12800       case COMPOUND_EXPR:
12801 	return void_node;
12802       default:
12803 	break;
12804       }
12805 
12806   if (complain & tf_error)
12807     error_at (location_of (t),
12808 	      "fold of empty expansion over %O", code);
12809   return error_mark_node;
12810 }
12811 
12812 /* Given a fold-expression T and a current LEFT and RIGHT operand,
12813    form an expression that combines the two terms using the
12814    operator of T. */
12815 
12816 static tree
fold_expression(tree t,tree left,tree right,tsubst_flags_t complain)12817 fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
12818 {
12819   tree_code code = FOLD_EXPR_OP (t);
12820 
12821   tree lookups = templated_operator_saved_lookups (t);
12822 
12823   // Handle compound assignment operators.
12824   if (FOLD_EXPR_MODIFY_P (t))
12825     return build_x_modify_expr (input_location, left, code, right,
12826 				lookups, complain);
12827 
12828   warning_sentinel s(warn_parentheses);
12829   switch (code)
12830     {
12831     case COMPOUND_EXPR:
12832       return build_x_compound_expr (input_location, left, right,
12833 				    lookups, complain);
12834     default:
12835       return build_x_binary_op (input_location, code,
12836                                 left, TREE_CODE (left),
12837                                 right, TREE_CODE (right),
12838 				lookups, /*overload=*/NULL,
12839                                 complain);
12840     }
12841 }
12842 
12843 /* Substitute ARGS into the pack of a fold expression T. */
12844 
12845 static inline tree
tsubst_fold_expr_pack(tree t,tree args,tsubst_flags_t complain,tree in_decl)12846 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12847 {
12848   return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
12849 }
12850 
12851 /* Substitute ARGS into the pack of a fold expression T. */
12852 
12853 static inline tree
tsubst_fold_expr_init(tree t,tree args,tsubst_flags_t complain,tree in_decl)12854 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12855 {
12856   return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl, false);
12857 }
12858 
12859 /* Expand a PACK of arguments into a grouped as left fold.
12860    Given a pack containing elements A0, A1, ..., An and an
12861    operator @, this builds the expression:
12862 
12863       ((A0 @ A1) @ A2) ... @ An
12864 
12865    Note that PACK must not be empty.
12866 
12867    The operator is defined by the original fold expression T. */
12868 
12869 static tree
expand_left_fold(tree t,tree pack,tsubst_flags_t complain)12870 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
12871 {
12872   tree left = TREE_VEC_ELT (pack, 0);
12873   for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
12874     {
12875       tree right = TREE_VEC_ELT (pack, i);
12876       left = fold_expression (t, left, right, complain);
12877     }
12878   return left;
12879 }
12880 
12881 /* Substitute into a unary left fold expression. */
12882 
12883 static tree
tsubst_unary_left_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)12884 tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
12885                         tree in_decl)
12886 {
12887   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12888   if (pack == error_mark_node)
12889     return error_mark_node;
12890   if (PACK_EXPANSION_P (pack))
12891     {
12892       tree r = copy_node (t);
12893       FOLD_EXPR_PACK (r) = pack;
12894       return r;
12895     }
12896   if (TREE_VEC_LENGTH (pack) == 0)
12897     return expand_empty_fold (t, complain);
12898   else
12899     return expand_left_fold (t, pack, complain);
12900 }
12901 
12902 /* Substitute into a binary left fold expression.
12903 
12904    Do ths by building a single (non-empty) vector of argumnts and
12905    building the expression from those elements. */
12906 
12907 static tree
tsubst_binary_left_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)12908 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
12909                          tree in_decl)
12910 {
12911   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12912   if (pack == error_mark_node)
12913     return error_mark_node;
12914   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
12915   if (init == error_mark_node)
12916     return error_mark_node;
12917 
12918   if (PACK_EXPANSION_P (pack))
12919     {
12920       tree r = copy_node (t);
12921       FOLD_EXPR_PACK (r) = pack;
12922       FOLD_EXPR_INIT (r) = init;
12923       return r;
12924     }
12925 
12926   tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
12927   TREE_VEC_ELT (vec, 0) = init;
12928   for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
12929     TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
12930 
12931   return expand_left_fold (t, vec, complain);
12932 }
12933 
12934 /* Expand a PACK of arguments into a grouped as right fold.
12935    Given a pack containing elementns A0, A1, ..., and an
12936    operator @, this builds the expression:
12937 
12938       A0@ ... (An-2 @ (An-1 @ An))
12939 
12940    Note that PACK must not be empty.
12941 
12942    The operator is defined by the original fold expression T. */
12943 
12944 tree
expand_right_fold(tree t,tree pack,tsubst_flags_t complain)12945 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
12946 {
12947   // Build the expression.
12948   int n = TREE_VEC_LENGTH (pack);
12949   tree right = TREE_VEC_ELT (pack, n - 1);
12950   for (--n; n != 0; --n)
12951     {
12952       tree left = TREE_VEC_ELT (pack, n - 1);
12953       right = fold_expression (t, left, right, complain);
12954     }
12955   return right;
12956 }
12957 
12958 /* Substitute into a unary right fold expression. */
12959 
12960 static tree
tsubst_unary_right_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)12961 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
12962                          tree in_decl)
12963 {
12964   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12965   if (pack == error_mark_node)
12966     return error_mark_node;
12967   if (PACK_EXPANSION_P (pack))
12968     {
12969       tree r = copy_node (t);
12970       FOLD_EXPR_PACK (r) = pack;
12971       return r;
12972     }
12973   if (TREE_VEC_LENGTH (pack) == 0)
12974     return expand_empty_fold (t, complain);
12975   else
12976     return expand_right_fold (t, pack, complain);
12977 }
12978 
12979 /* Substitute into a binary right fold expression.
12980 
12981    Do ths by building a single (non-empty) vector of arguments and
12982    building the expression from those elements. */
12983 
12984 static tree
tsubst_binary_right_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)12985 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
12986                          tree in_decl)
12987 {
12988   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12989   if (pack == error_mark_node)
12990     return error_mark_node;
12991   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
12992   if (init == error_mark_node)
12993     return error_mark_node;
12994 
12995   if (PACK_EXPANSION_P (pack))
12996     {
12997       tree r = copy_node (t);
12998       FOLD_EXPR_PACK (r) = pack;
12999       FOLD_EXPR_INIT (r) = init;
13000       return r;
13001     }
13002 
13003   int n = TREE_VEC_LENGTH (pack);
13004   tree vec = make_tree_vec (n + 1);
13005   for (int i = 0; i < n; ++i)
13006     TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
13007   TREE_VEC_ELT (vec, n) = init;
13008 
13009   return expand_right_fold (t, vec, complain);
13010 }
13011 
13012 /* Walk through the pattern of a pack expansion, adding everything in
13013    local_specializations to a list.  */
13014 
13015 class el_data
13016 {
13017 public:
13018   /* Set of variables declared within the pattern.  */
13019   hash_set<tree> internal;
13020   /* Set of AST nodes that have been visited by the traversal.  */
13021   hash_set<tree> visited;
13022   /* List of local_specializations used within the pattern.  */
13023   tree extra;
13024   tsubst_flags_t complain;
13025   /* True iff we don't want to walk into unevaluated contexts.  */
13026   bool skip_unevaluated_operands = false;
13027   /* The unevaluated contexts that we avoided walking.  */
13028   auto_vec<tree> skipped_trees;
13029 
el_data(tsubst_flags_t c)13030   el_data (tsubst_flags_t c)
13031     : extra (NULL_TREE), complain (c) {}
13032 };
13033 static tree
extract_locals_r(tree * tp,int * walk_subtrees,void * data_)13034 extract_locals_r (tree *tp, int *walk_subtrees, void *data_)
13035 {
13036   el_data &data = *reinterpret_cast<el_data*>(data_);
13037   tree *extra = &data.extra;
13038   tsubst_flags_t complain = data.complain;
13039 
13040   if (data.skip_unevaluated_operands
13041       && unevaluated_p (TREE_CODE (*tp)))
13042     {
13043       data.skipped_trees.safe_push (*tp);
13044       *walk_subtrees = 0;
13045       return NULL_TREE;
13046     }
13047 
13048   if (TYPE_P (*tp) && typedef_variant_p (*tp))
13049     /* Remember local typedefs (85214).  */
13050     tp = &TYPE_NAME (*tp);
13051 
13052   if (TREE_CODE (*tp) == DECL_EXPR)
13053     {
13054       tree decl = DECL_EXPR_DECL (*tp);
13055       data.internal.add (decl);
13056       if (VAR_P (decl)
13057 	  && DECL_DECOMPOSITION_P (decl)
13058 	  && TREE_TYPE (decl) != error_mark_node)
13059 	{
13060 	  gcc_assert (DECL_NAME (decl) == NULL_TREE);
13061 	  for (tree decl2 = DECL_CHAIN (decl);
13062 	       decl2
13063 	       && VAR_P (decl2)
13064 	       && DECL_DECOMPOSITION_P (decl2)
13065 	       && DECL_NAME (decl2)
13066 	       && TREE_TYPE (decl2) != error_mark_node;
13067 	       decl2 = DECL_CHAIN (decl2))
13068 	    {
13069 	      gcc_assert (DECL_DECOMP_BASE (decl2) == decl);
13070 	      data.internal.add (decl2);
13071 	    }
13072 	}
13073     }
13074   else if (TREE_CODE (*tp) == LAMBDA_EXPR)
13075     {
13076       /* Since we defer implicit capture, look in the parms and body.  */
13077       tree fn = lambda_function (*tp);
13078       cp_walk_tree (&TREE_TYPE (fn), &extract_locals_r, &data,
13079 		    &data.visited);
13080       cp_walk_tree (&DECL_SAVED_TREE (fn), &extract_locals_r, &data,
13081 		    &data.visited);
13082     }
13083   else if (tree spec = retrieve_local_specialization (*tp))
13084     {
13085       if (data.internal.contains (*tp))
13086 	/* Don't mess with variables declared within the pattern.  */
13087 	return NULL_TREE;
13088       if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
13089 	{
13090 	  /* Maybe pull out the PARM_DECL for a partial instantiation.  */
13091 	  tree args = ARGUMENT_PACK_ARGS (spec);
13092 	  if (TREE_VEC_LENGTH (args) == 1)
13093 	    {
13094 	      tree elt = TREE_VEC_ELT (args, 0);
13095 	      if (PACK_EXPANSION_P (elt))
13096 		elt = PACK_EXPANSION_PATTERN (elt);
13097 	      if (DECL_PACK_P (elt))
13098 		spec = elt;
13099 	    }
13100 	  if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
13101 	    {
13102 	      /* Handle lambda capture here, since we aren't doing any
13103 		 substitution now, and so tsubst_copy won't call
13104 		 process_outer_var_ref.  */
13105 	      tree args = ARGUMENT_PACK_ARGS (spec);
13106 	      int len = TREE_VEC_LENGTH (args);
13107 	      for (int i = 0; i < len; ++i)
13108 		{
13109 		  tree arg = TREE_VEC_ELT (args, i);
13110 		  tree carg = arg;
13111 		  if (outer_automatic_var_p (arg))
13112 		    carg = process_outer_var_ref (arg, complain);
13113 		  if (carg != arg)
13114 		    {
13115 		      /* Make a new NONTYPE_ARGUMENT_PACK of the capture
13116 			 proxies.  */
13117 		      if (i == 0)
13118 			{
13119 			  spec = copy_node (spec);
13120 			  args = copy_node (args);
13121 			  SET_ARGUMENT_PACK_ARGS (spec, args);
13122 			  register_local_specialization (spec, *tp);
13123 			}
13124 		      TREE_VEC_ELT (args, i) = carg;
13125 		    }
13126 		}
13127 	    }
13128 	}
13129       if (outer_automatic_var_p (spec))
13130 	spec = process_outer_var_ref (spec, complain);
13131       *extra = tree_cons (*tp, spec, *extra);
13132     }
13133   return NULL_TREE;
13134 }
13135 static tree
extract_local_specs(tree pattern,tsubst_flags_t complain)13136 extract_local_specs (tree pattern, tsubst_flags_t complain)
13137 {
13138   el_data data (complain);
13139   /* Walk the pattern twice, ignoring unevaluated operands the first time
13140      around, so that if a local specialization appears in both an evaluated
13141      and unevaluated context we prefer to process it in the evaluated context
13142      (since e.g. process_outer_var_ref is a no-op inside an unevaluated
13143      context).  */
13144   data.skip_unevaluated_operands = true;
13145   cp_walk_tree (&pattern, extract_locals_r, &data, &data.visited);
13146   /* Now walk the unevaluated contexts we skipped the first time around.  */
13147   data.skip_unevaluated_operands = false;
13148   for (tree t : data.skipped_trees)
13149     {
13150       data.visited.remove (t);
13151       cp_walk_tree (&t, extract_locals_r, &data, &data.visited);
13152     }
13153   return data.extra;
13154 }
13155 
13156 /* Extract any uses of local_specializations from PATTERN and add them to ARGS
13157    for use in PACK_EXPANSION_EXTRA_ARGS.  */
13158 
13159 tree
build_extra_args(tree pattern,tree args,tsubst_flags_t complain)13160 build_extra_args (tree pattern, tree args, tsubst_flags_t complain)
13161 {
13162   /* Make a copy of the extra arguments so that they won't get changed
13163      out from under us.  */
13164   tree extra = preserve_args (copy_template_args (args), /*cow_p=*/false);
13165   if (local_specializations)
13166     if (tree locals = extract_local_specs (pattern, complain))
13167       extra = tree_cons (NULL_TREE, extra, locals);
13168   return extra;
13169 }
13170 
13171 /* Apply any local specializations from PACK_EXPANSION_EXTRA_ARGS and add the
13172    normal template args to ARGS.  */
13173 
13174 tree
add_extra_args(tree extra,tree args,tsubst_flags_t complain,tree in_decl)13175 add_extra_args (tree extra, tree args, tsubst_flags_t complain, tree in_decl)
13176 {
13177   if (extra && TREE_CODE (extra) == TREE_LIST)
13178     {
13179       for (tree elt = TREE_CHAIN (extra); elt; elt = TREE_CHAIN (elt))
13180 	{
13181 	  /* The partial instantiation involved local declarations collected in
13182 	     extract_local_specs; map from the general template to our local
13183 	     context.  */
13184 	  tree gen = TREE_PURPOSE (elt);
13185 	  tree inst = TREE_VALUE (elt);
13186 	  if (DECL_P (inst))
13187 	    if (tree local = retrieve_local_specialization (inst))
13188 	      inst = local;
13189 	  /* else inst is already a full instantiation of the pack.  */
13190 	  register_local_specialization (inst, gen);
13191 	}
13192       gcc_assert (!TREE_PURPOSE (extra));
13193       extra = TREE_VALUE (extra);
13194     }
13195   if (uses_template_parms (extra))
13196     {
13197       /* This can happen after dependent substitution into a
13198 	 requires-expr or a lambda that uses constexpr if.  */
13199       extra = tsubst_template_args (extra, args, complain, in_decl);
13200       args = add_outermost_template_args (args, extra);
13201     }
13202   else
13203     args = add_to_template_args (extra, args);
13204   return args;
13205 }
13206 
13207 /* Substitute ARGS into T, which is an pack expansion
13208    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
13209    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
13210    (if only a partial substitution could be performed) or
13211    ERROR_MARK_NODE if there was an error.  */
13212 tree
tsubst_pack_expansion(tree t,tree args,tsubst_flags_t complain,tree in_decl)13213 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
13214 		       tree in_decl)
13215 {
13216   tree pattern;
13217   tree pack, packs = NULL_TREE;
13218   bool unsubstituted_packs = false;
13219   int i, len = -1;
13220   tree result;
13221   bool need_local_specializations = false;
13222   int levels;
13223 
13224   gcc_assert (PACK_EXPANSION_P (t));
13225   pattern = PACK_EXPANSION_PATTERN (t);
13226 
13227   /* Add in any args remembered from an earlier partial instantiation.  */
13228   args = add_extra_args (PACK_EXPANSION_EXTRA_ARGS (t), args, complain, in_decl);
13229 
13230   levels = TMPL_ARGS_DEPTH (args);
13231 
13232   /* Determine the argument packs that will instantiate the parameter
13233      packs used in the expansion expression. While we're at it,
13234      compute the number of arguments to be expanded and make sure it
13235      is consistent.  */
13236   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
13237        pack = TREE_CHAIN (pack))
13238     {
13239       tree parm_pack = TREE_VALUE (pack);
13240       tree arg_pack = NULL_TREE;
13241       tree orig_arg = NULL_TREE;
13242       int level = 0;
13243 
13244       if (TREE_CODE (parm_pack) == BASES)
13245 	{
13246 	  gcc_assert (parm_pack == pattern);
13247 	  if (BASES_DIRECT (parm_pack))
13248 	    return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
13249 							args, complain,
13250 							in_decl, false),
13251 					   complain);
13252 	  else
13253 	    return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
13254 						 args, complain, in_decl,
13255 						 false), complain);
13256 	}
13257       else if (builtin_pack_call_p (parm_pack))
13258 	{
13259 	  if (parm_pack != pattern)
13260 	    {
13261 	      if (complain & tf_error)
13262 		sorry ("%qE is not the entire pattern of the pack expansion",
13263 		       parm_pack);
13264 	      return error_mark_node;
13265 	    }
13266 	  return expand_builtin_pack_call (parm_pack, args,
13267 					   complain, in_decl);
13268 	}
13269       else if (TREE_CODE (parm_pack) == PARM_DECL)
13270 	{
13271 	  /* We know we have correct local_specializations if this
13272 	     expansion is at function scope, or if we're dealing with a
13273 	     local parameter in a requires expression; for the latter,
13274 	     tsubst_requires_expr set it up appropriately.  */
13275 	  if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
13276 	    arg_pack = retrieve_local_specialization (parm_pack);
13277 	  else
13278 	    /* We can't rely on local_specializations for a parameter
13279 	       name used later in a function declaration (such as in a
13280 	       late-specified return type).  Even if it exists, it might
13281 	       have the wrong value for a recursive call.  */
13282 	    need_local_specializations = true;
13283 
13284 	  if (!arg_pack)
13285 	    {
13286 	      /* This parameter pack was used in an unevaluated context.  Just
13287 		 make a dummy decl, since it's only used for its type.  */
13288 	      ++cp_unevaluated_operand;
13289 	      arg_pack = tsubst_decl (parm_pack, args, complain);
13290 	      --cp_unevaluated_operand;
13291 	      if (arg_pack && DECL_PACK_P (arg_pack))
13292 		/* Partial instantiation of the parm_pack, we can't build
13293 		   up an argument pack yet.  */
13294 		arg_pack = NULL_TREE;
13295 	      else
13296 		arg_pack = make_fnparm_pack (arg_pack);
13297 	    }
13298 	  else if (DECL_PACK_P (arg_pack))
13299 	    /* This argument pack isn't fully instantiated yet.  */
13300 	    arg_pack = NULL_TREE;
13301 	}
13302       else if (is_capture_proxy (parm_pack))
13303 	{
13304 	  arg_pack = retrieve_local_specialization (parm_pack);
13305 	  if (DECL_PACK_P (arg_pack))
13306 	    arg_pack = NULL_TREE;
13307 	}
13308       else
13309         {
13310 	  int idx;
13311           template_parm_level_and_index (parm_pack, &level, &idx);
13312           if (level <= levels)
13313             arg_pack = TMPL_ARG (args, level, idx);
13314 
13315 	  if (arg_pack && TREE_CODE (arg_pack) == TEMPLATE_TYPE_PARM
13316 	      && TEMPLATE_TYPE_PARAMETER_PACK (arg_pack))
13317 	    arg_pack = NULL_TREE;
13318         }
13319 
13320       orig_arg = arg_pack;
13321       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
13322 	arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
13323 
13324       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
13325 	/* This can only happen if we forget to expand an argument
13326 	   pack somewhere else. Just return an error, silently.  */
13327 	{
13328 	  result = make_tree_vec (1);
13329 	  TREE_VEC_ELT (result, 0) = error_mark_node;
13330 	  return result;
13331 	}
13332 
13333       if (arg_pack)
13334         {
13335           int my_len =
13336             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
13337 
13338 	  /* Don't bother trying to do a partial substitution with
13339 	     incomplete packs; we'll try again after deduction.  */
13340           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
13341             return t;
13342 
13343           if (len < 0)
13344 	    len = my_len;
13345 	  else if (len != my_len)
13346             {
13347 	      if (!(complain & tf_error))
13348 		/* Fail quietly.  */;
13349               else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
13350                 error ("mismatched argument pack lengths while expanding %qT",
13351                        pattern);
13352               else
13353                 error ("mismatched argument pack lengths while expanding %qE",
13354                        pattern);
13355               return error_mark_node;
13356             }
13357 
13358           /* Keep track of the parameter packs and their corresponding
13359              argument packs.  */
13360           packs = tree_cons (parm_pack, arg_pack, packs);
13361           TREE_TYPE (packs) = orig_arg;
13362         }
13363       else
13364 	{
13365 	  /* We can't substitute for this parameter pack.  We use a flag as
13366 	     well as the missing_level counter because function parameter
13367 	     packs don't have a level.  */
13368 	  gcc_assert (processing_template_decl || is_auto (parm_pack));
13369 	  unsubstituted_packs = true;
13370 	}
13371     }
13372 
13373   /* If the expansion is just T..., return the matching argument pack, unless
13374      we need to call convert_from_reference on all the elements.  This is an
13375      important optimization; see c++/68422.  */
13376   if (!unsubstituted_packs
13377       && TREE_PURPOSE (packs) == pattern)
13378     {
13379       tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
13380 
13381       /* If the argument pack is a single pack expansion, pull it out.  */
13382       if (TREE_VEC_LENGTH (args) == 1
13383 	  && pack_expansion_args_count (args))
13384 	return TREE_VEC_ELT (args, 0);
13385 
13386       /* Types need no adjustment, nor does sizeof..., and if we still have
13387 	 some pack expansion args we won't do anything yet.  */
13388       if (TREE_CODE (t) == TYPE_PACK_EXPANSION
13389 	  || PACK_EXPANSION_SIZEOF_P (t)
13390 	  || pack_expansion_args_count (args))
13391 	return args;
13392       /* Also optimize expression pack expansions if we can tell that the
13393 	 elements won't have reference type.  */
13394       tree type = TREE_TYPE (pattern);
13395       if (type && !TYPE_REF_P (type)
13396 	  && !PACK_EXPANSION_P (type)
13397 	  && !WILDCARD_TYPE_P (type))
13398 	return args;
13399       /* Otherwise use the normal path so we get convert_from_reference.  */
13400     }
13401 
13402   /* We cannot expand this expansion expression, because we don't have
13403      all of the argument packs we need.  */
13404   if (use_pack_expansion_extra_args_p (t, packs, len, unsubstituted_packs))
13405     {
13406       /* We got some full packs, but we can't substitute them in until we
13407 	 have values for all the packs.  So remember these until then.  */
13408 
13409       t = make_pack_expansion (pattern, complain);
13410       PACK_EXPANSION_EXTRA_ARGS (t)
13411 	= build_extra_args (pattern, args, complain);
13412       return t;
13413     }
13414 
13415   /* If NEED_LOCAL_SPECIALIZATIONS then we're in a late-specified return
13416      type, so create our own local specializations map; the current map is
13417      either NULL or (in the case of recursive unification) might have
13418      bindings that we don't want to use or alter.  */
13419   local_specialization_stack lss (need_local_specializations
13420 				  ? lss_blank : lss_nop);
13421 
13422   if (unsubstituted_packs)
13423     {
13424       /* There were no real arguments, we're just replacing a parameter
13425 	 pack with another version of itself. Substitute into the
13426 	 pattern and return a PACK_EXPANSION_*. The caller will need to
13427 	 deal with that.  */
13428       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
13429 	result = tsubst_expr (pattern, args, complain, in_decl,
13430 			 /*integral_constant_expression_p=*/false);
13431       else
13432 	result = tsubst (pattern, args, complain, in_decl);
13433       result = make_pack_expansion (result, complain);
13434       PACK_EXPANSION_LOCAL_P (result) = PACK_EXPANSION_LOCAL_P (t);
13435       PACK_EXPANSION_SIZEOF_P (result) = PACK_EXPANSION_SIZEOF_P (t);
13436       if (PACK_EXPANSION_AUTO_P (t))
13437 	{
13438 	  /* This is a fake auto... pack expansion created in add_capture with
13439 	     _PACKS that don't appear in the pattern.  Copy one over.  */
13440 	  packs = PACK_EXPANSION_PARAMETER_PACKS (t);
13441 	  pack = retrieve_local_specialization (TREE_VALUE (packs));
13442 	  gcc_checking_assert (DECL_PACK_P (pack));
13443 	  PACK_EXPANSION_PARAMETER_PACKS (result)
13444 	    = build_tree_list (NULL_TREE, pack);
13445 	  PACK_EXPANSION_AUTO_P (result) = true;
13446 	}
13447       return result;
13448     }
13449 
13450   gcc_assert (len >= 0);
13451 
13452   /* For each argument in each argument pack, substitute into the
13453      pattern.  */
13454   result = make_tree_vec (len);
13455   tree elem_args = copy_template_args (args);
13456   for (i = 0; i < len; ++i)
13457     {
13458       t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
13459 						    i,
13460 						    elem_args, complain,
13461 						    in_decl);
13462       TREE_VEC_ELT (result, i) = t;
13463       if (t == error_mark_node)
13464 	{
13465 	  result = error_mark_node;
13466 	  break;
13467 	}
13468     }
13469 
13470   /* Update ARGS to restore the substitution from parameter packs to
13471      their argument packs.  */
13472   for (pack = packs; pack; pack = TREE_CHAIN (pack))
13473     {
13474       tree parm = TREE_PURPOSE (pack);
13475 
13476       if (TREE_CODE (parm) == PARM_DECL
13477 	  || VAR_P (parm)
13478 	  || TREE_CODE (parm) == FIELD_DECL)
13479         register_local_specialization (TREE_TYPE (pack), parm);
13480       else
13481         {
13482           int idx, level;
13483 
13484 	  if (TREE_VALUE (pack) == NULL_TREE)
13485 	    continue;
13486 
13487           template_parm_level_and_index (parm, &level, &idx);
13488 
13489           /* Update the corresponding argument.  */
13490           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
13491             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
13492               TREE_TYPE (pack);
13493           else
13494             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
13495         }
13496     }
13497 
13498   /* If the dependent pack arguments were such that we end up with only a
13499      single pack expansion again, there's no need to keep it in a TREE_VEC.  */
13500   if (len == 1 && TREE_CODE (result) == TREE_VEC
13501       && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
13502     return TREE_VEC_ELT (result, 0);
13503 
13504   return result;
13505 }
13506 
13507 /* Make an argument pack out of the TREE_VEC VEC.  */
13508 
13509 static tree
make_argument_pack(tree vec)13510 make_argument_pack (tree vec)
13511 {
13512   tree pack;
13513 
13514   if (TYPE_P (TREE_VEC_ELT (vec, 0)))
13515     pack = cxx_make_type (TYPE_ARGUMENT_PACK);
13516   else
13517     {
13518       pack = make_node (NONTYPE_ARGUMENT_PACK);
13519       TREE_CONSTANT (pack) = 1;
13520     }
13521   SET_ARGUMENT_PACK_ARGS (pack, vec);
13522   return pack;
13523 }
13524 
13525 /* Return an exact copy of template args T that can be modified
13526    independently.  */
13527 
13528 static tree
copy_template_args(tree t)13529 copy_template_args (tree t)
13530 {
13531   if (t == error_mark_node)
13532     return t;
13533 
13534   int len = TREE_VEC_LENGTH (t);
13535   tree new_vec = make_tree_vec (len);
13536 
13537   for (int i = 0; i < len; ++i)
13538     {
13539       tree elt = TREE_VEC_ELT (t, i);
13540       if (elt && TREE_CODE (elt) == TREE_VEC)
13541 	elt = copy_template_args (elt);
13542       TREE_VEC_ELT (new_vec, i) = elt;
13543     }
13544 
13545   NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
13546     = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13547 
13548   return new_vec;
13549 }
13550 
13551 /* Substitute ARGS into the *_ARGUMENT_PACK orig_arg.  */
13552 
13553 tree
tsubst_argument_pack(tree orig_arg,tree args,tsubst_flags_t complain,tree in_decl)13554 tsubst_argument_pack (tree orig_arg, tree args, tsubst_flags_t complain,
13555 		      tree in_decl)
13556 {
13557   /* Substitute into each of the arguments.  */
13558   tree pack_args = tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
13559 					 args, complain, in_decl);
13560   tree new_arg = error_mark_node;
13561   if (pack_args != error_mark_node)
13562     {
13563       if (TYPE_P (orig_arg))
13564 	{
13565 	  new_arg = cxx_make_type (TREE_CODE (orig_arg));
13566 	  SET_TYPE_STRUCTURAL_EQUALITY (new_arg);
13567 	}
13568       else
13569 	{
13570 	  new_arg = make_node (TREE_CODE (orig_arg));
13571 	  TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
13572 	}
13573 
13574       SET_ARGUMENT_PACK_ARGS (new_arg, pack_args);
13575     }
13576 
13577   return new_arg;
13578 }
13579 
13580 /* Substitute ARGS into the vector or list of template arguments T.  */
13581 
13582 tree
tsubst_template_args(tree t,tree args,tsubst_flags_t complain,tree in_decl)13583 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
13584 {
13585   tree orig_t = t;
13586   int len, need_new = 0, i, expanded_len_adjust = 0, out;
13587   tree *elts;
13588 
13589   if (t == error_mark_node)
13590     return error_mark_node;
13591 
13592   len = TREE_VEC_LENGTH (t);
13593   elts = XALLOCAVEC (tree, len);
13594 
13595   for (i = 0; i < len; i++)
13596     {
13597       tree orig_arg = TREE_VEC_ELT (t, i);
13598       tree new_arg;
13599 
13600       if (!orig_arg)
13601 	new_arg = NULL_TREE;
13602       else if (TREE_CODE (orig_arg) == TREE_VEC)
13603 	new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
13604       else if (PACK_EXPANSION_P (orig_arg))
13605         {
13606           /* Substitute into an expansion expression.  */
13607           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
13608 
13609           if (TREE_CODE (new_arg) == TREE_VEC)
13610             /* Add to the expanded length adjustment the number of
13611                expanded arguments. We subtract one from this
13612                measurement, because the argument pack expression
13613                itself is already counted as 1 in
13614                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
13615                the argument pack is empty.  */
13616             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
13617         }
13618       else if (ARGUMENT_PACK_P (orig_arg))
13619 	new_arg = tsubst_argument_pack (orig_arg, args, complain, in_decl);
13620       else
13621 	new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
13622 
13623       if (new_arg == error_mark_node)
13624 	return error_mark_node;
13625 
13626       elts[i] = new_arg;
13627       if (new_arg != orig_arg)
13628 	need_new = 1;
13629     }
13630 
13631   if (!need_new)
13632     return t;
13633 
13634   /* Make space for the expanded arguments coming from template
13635      argument packs.  */
13636   t = make_tree_vec (len + expanded_len_adjust);
13637   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
13638      arguments for a member template.
13639      In that case each TREE_VEC in ORIG_T represents a level of template
13640      arguments, and ORIG_T won't carry any non defaulted argument count.
13641      It will rather be the nested TREE_VECs that will carry one.
13642      In other words, ORIG_T carries a non defaulted argument count only
13643      if it doesn't contain any nested TREE_VEC.  */
13644   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
13645     {
13646       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
13647       count += expanded_len_adjust;
13648       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
13649     }
13650   for (i = 0, out = 0; i < len; i++)
13651     {
13652       tree orig_arg = TREE_VEC_ELT (orig_t, i);
13653       if (orig_arg
13654 	  && (PACK_EXPANSION_P (orig_arg) || ARGUMENT_PACK_P (orig_arg))
13655           && TREE_CODE (elts[i]) == TREE_VEC)
13656         {
13657           int idx;
13658 
13659           /* Now expand the template argument pack "in place".  */
13660           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
13661             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
13662         }
13663       else
13664         {
13665           TREE_VEC_ELT (t, out) = elts[i];
13666           out++;
13667         }
13668     }
13669 
13670   return t;
13671 }
13672 
13673 /* Substitute ARGS into one level PARMS of template parameters.  */
13674 
13675 static tree
tsubst_template_parms_level(tree parms,tree args,tsubst_flags_t complain)13676 tsubst_template_parms_level (tree parms, tree args, tsubst_flags_t complain)
13677 {
13678   if (parms == error_mark_node)
13679     return error_mark_node;
13680 
13681   tree new_vec = make_tree_vec (TREE_VEC_LENGTH (parms));
13682 
13683   for (int i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
13684     {
13685       tree tuple = TREE_VEC_ELT (parms, i);
13686 
13687       if (tuple == error_mark_node)
13688 	continue;
13689 
13690       TREE_VEC_ELT (new_vec, i) =
13691 	tsubst_template_parm (tuple, args, complain);
13692     }
13693 
13694   return new_vec;
13695 }
13696 
13697 /* Return the result of substituting ARGS into the template parameters
13698    given by PARMS.  If there are m levels of ARGS and m + n levels of
13699    PARMS, then the result will contain n levels of PARMS.  For
13700    example, if PARMS is `template <class T> template <class U>
13701    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
13702    result will be `template <int*, double, class V>'.  */
13703 
13704 static tree
tsubst_template_parms(tree parms,tree args,tsubst_flags_t complain)13705 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
13706 {
13707   tree r = NULL_TREE;
13708   tree* new_parms;
13709 
13710   /* When substituting into a template, we must set
13711      PROCESSING_TEMPLATE_DECL as the template parameters may be
13712      dependent if they are based on one-another, and the dependency
13713      predicates are short-circuit outside of templates.  */
13714   ++processing_template_decl;
13715 
13716   for (new_parms = &r;
13717        parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
13718        new_parms = &(TREE_CHAIN (*new_parms)),
13719 	 parms = TREE_CHAIN (parms))
13720     {
13721       tree new_vec = tsubst_template_parms_level (TREE_VALUE (parms),
13722 						  args, complain);
13723       *new_parms =
13724 	tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
13725 			     - TMPL_ARGS_DEPTH (args)),
13726 		   new_vec, NULL_TREE);
13727       TEMPLATE_PARMS_CONSTRAINTS (*new_parms)
13728 	= TEMPLATE_PARMS_CONSTRAINTS (parms);
13729     }
13730 
13731   --processing_template_decl;
13732 
13733   return r;
13734 }
13735 
13736 /* Return the result of substituting ARGS into one template parameter
13737    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
13738    parameter and which TREE_PURPOSE is the default argument of the
13739    template parameter.  */
13740 
13741 static tree
tsubst_template_parm(tree t,tree args,tsubst_flags_t complain)13742 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
13743 {
13744   tree default_value, parm_decl;
13745 
13746   if (args == NULL_TREE
13747       || t == NULL_TREE
13748       || t == error_mark_node)
13749     return t;
13750 
13751   gcc_assert (TREE_CODE (t) == TREE_LIST);
13752 
13753   default_value = TREE_PURPOSE (t);
13754   parm_decl = TREE_VALUE (t);
13755 
13756   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
13757   if (TREE_CODE (parm_decl) == PARM_DECL
13758       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
13759     parm_decl = error_mark_node;
13760   default_value = tsubst_template_arg (default_value, args,
13761 				       complain, NULL_TREE);
13762 
13763   tree r = build_tree_list (default_value, parm_decl);
13764   TEMPLATE_PARM_CONSTRAINTS (r) = TEMPLATE_PARM_CONSTRAINTS (t);
13765   return r;
13766 }
13767 
13768 /* Substitute in-place the TEMPLATE_PARM_CONSTRAINTS of each template
13769    parameter in PARMS for sake of declaration matching.  */
13770 
13771 static void
tsubst_each_template_parm_constraints(tree parms,tree args,tsubst_flags_t complain)13772 tsubst_each_template_parm_constraints (tree parms, tree args,
13773 				       tsubst_flags_t complain)
13774 {
13775   ++processing_template_decl;
13776   for (; parms; parms = TREE_CHAIN (parms))
13777     {
13778       tree level = TREE_VALUE (parms);
13779       for (int i = 0; i < TREE_VEC_LENGTH (level); ++i)
13780 	{
13781 	  tree parm = TREE_VEC_ELT (level, i);
13782 	  TEMPLATE_PARM_CONSTRAINTS (parm)
13783 	    = tsubst_constraint (TEMPLATE_PARM_CONSTRAINTS (parm), args,
13784 				 complain, NULL_TREE);
13785 	}
13786     }
13787   --processing_template_decl;
13788 }
13789 
13790 /* Substitute the ARGS into the indicated aggregate (or enumeration)
13791    type T.  If T is not an aggregate or enumeration type, it is
13792    handled as if by tsubst.  IN_DECL is as for tsubst.  If
13793    ENTERING_SCOPE is nonzero, T is the context for a template which
13794    we are presently tsubst'ing.  Return the substituted value.  */
13795 
13796 static tree
tsubst_aggr_type(tree t,tree args,tsubst_flags_t complain,tree in_decl,int entering_scope)13797 tsubst_aggr_type (tree t,
13798 		  tree args,
13799 		  tsubst_flags_t complain,
13800 		  tree in_decl,
13801 		  int entering_scope)
13802 {
13803   if (t == NULL_TREE)
13804     return NULL_TREE;
13805 
13806   /* If T is an alias template specialization, we want to substitute that
13807      rather than strip it, especially if it's dependent_alias_template_spec_p.
13808      It should be OK not to handle entering_scope in this case, since
13809      DECL_CONTEXT will never be an alias template specialization.  We only get
13810      here with an alias when tsubst calls us for TYPENAME_TYPE.  */
13811   if (alias_template_specialization_p (t, nt_transparent))
13812     return tsubst (t, args, complain, in_decl);
13813 
13814   switch (TREE_CODE (t))
13815     {
13816     case RECORD_TYPE:
13817       if (TYPE_PTRMEMFUNC_P (t))
13818 	return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
13819 
13820       /* Fall through.  */
13821     case ENUMERAL_TYPE:
13822     case UNION_TYPE:
13823       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
13824 	{
13825 	  tree argvec;
13826 	  tree context;
13827 	  tree r;
13828 
13829 	  /* In "sizeof(X<I>)" we need to evaluate "I".  */
13830 	  cp_evaluated ev;
13831 
13832 	  /* First, determine the context for the type we are looking
13833 	     up.  */
13834 	  context = TYPE_CONTEXT (t);
13835 	  if (context && TYPE_P (context))
13836 	    {
13837 	      context = tsubst_aggr_type (context, args, complain,
13838 					  in_decl, /*entering_scope=*/1);
13839 	      /* If context is a nested class inside a class template,
13840 	         it may still need to be instantiated (c++/33959).  */
13841 	      context = complete_type (context);
13842 	    }
13843 
13844 	  /* Then, figure out what arguments are appropriate for the
13845 	     type we are trying to find.  For example, given:
13846 
13847 	       template <class T> struct S;
13848 	       template <class T, class U> void f(T, U) { S<U> su; }
13849 
13850 	     and supposing that we are instantiating f<int, double>,
13851 	     then our ARGS will be {int, double}, but, when looking up
13852 	     S we only want {double}.  */
13853 	  argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
13854 					 complain, in_decl);
13855 	  if (argvec == error_mark_node)
13856 	    r = error_mark_node;
13857 	  else if (!entering_scope && (complain & tf_dguide)
13858 		   && dependent_scope_p (context))
13859 	    {
13860 	      /* See maybe_dependent_member_ref.  */
13861 	      tree name = TYPE_IDENTIFIER (t);
13862 	      tree fullname = name;
13863 	      if (instantiates_primary_template_p (t))
13864 		fullname = build_nt (TEMPLATE_ID_EXPR, name,
13865 				     INNERMOST_TEMPLATE_ARGS (argvec));
13866 	      return build_typename_type (context, name, fullname,
13867 					  typename_type);
13868 	    }
13869 	  else
13870 	    {
13871 	      r = lookup_template_class (t, argvec, in_decl, context,
13872 					 entering_scope, complain);
13873 	      r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
13874 	    }
13875 
13876 	  return r;
13877 	}
13878       else
13879 	/* This is not a template type, so there's nothing to do.  */
13880 	return t;
13881 
13882     default:
13883       return tsubst (t, args, complain, in_decl);
13884     }
13885 }
13886 
13887 /* Map from a FUNCTION_DECL to a vec of default argument instantiations,
13888    indexed in reverse order of the parameters.  */
13889 
13890 static GTY((cache)) hash_table<tree_vec_map_cache_hasher> *defarg_inst;
13891 
13892 /* Return a reference to the vec* of defarg insts for FN.  */
13893 
13894 static vec<tree,va_gc> *&
defarg_insts_for(tree fn)13895 defarg_insts_for (tree fn)
13896 {
13897   if (!defarg_inst)
13898     defarg_inst = hash_table<tree_vec_map_cache_hasher>::create_ggc (13);
13899   tree_vec_map in = { { fn }, nullptr };
13900   tree_vec_map **slot
13901     = defarg_inst->find_slot_with_hash (&in, DECL_UID (fn), INSERT);
13902   if (!*slot)
13903     {
13904       *slot = ggc_alloc<tree_vec_map> ();
13905       **slot = in;
13906     }
13907   return (*slot)->to;
13908 }
13909 
13910 /* Substitute into the default argument ARG (a default argument for
13911    FN), which has the indicated TYPE.  */
13912 
13913 tree
tsubst_default_argument(tree fn,int parmnum,tree type,tree arg,tsubst_flags_t complain)13914 tsubst_default_argument (tree fn, int parmnum, tree type, tree arg,
13915 			 tsubst_flags_t complain)
13916 {
13917   int errs = errorcount + sorrycount;
13918 
13919   /* This can happen in invalid code.  */
13920   if (TREE_CODE (arg) == DEFERRED_PARSE)
13921     return arg;
13922 
13923   /* Shortcut {}.  */
13924   if (BRACE_ENCLOSED_INITIALIZER_P (arg)
13925       && CONSTRUCTOR_NELTS (arg) == 0)
13926     return arg;
13927 
13928   tree parm = FUNCTION_FIRST_USER_PARM (fn);
13929   parm = chain_index (parmnum, parm);
13930   tree parmtype = TREE_TYPE (parm);
13931   if (DECL_BY_REFERENCE (parm))
13932     parmtype = TREE_TYPE (parmtype);
13933   if (parmtype == error_mark_node)
13934     return error_mark_node;
13935 
13936   gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, parmtype));
13937 
13938   /* Remember the location of the pointer to the vec rather than the location
13939      of the particular element, in case the vec grows in tsubst_expr.  */
13940   vec<tree,va_gc> *&defs = defarg_insts_for (fn);
13941   /* Index in reverse order to avoid allocating space for initial parameters
13942      that don't have default arguments.  */
13943   unsigned ridx = list_length (parm);
13944   if (vec_safe_length (defs) < ridx)
13945     vec_safe_grow_cleared (defs, ridx);
13946   else if (tree inst = (*defs)[ridx - 1])
13947     return inst;
13948 
13949   /* This default argument came from a template.  Instantiate the
13950      default argument here, not in tsubst.  In the case of
13951      something like:
13952 
13953        template <class T>
13954        struct S {
13955 	 static T t();
13956 	 void f(T = t());
13957        };
13958 
13959      we must be careful to do name lookup in the scope of S<T>,
13960      rather than in the current class.  */
13961   push_to_top_level ();
13962   push_access_scope (fn);
13963   push_deferring_access_checks (dk_no_deferred);
13964   start_lambda_scope (parm);
13965 
13966   /* The default argument expression may cause implicitly defined
13967      member functions to be synthesized, which will result in garbage
13968      collection.  We must treat this situation as if we were within
13969      the body of function so as to avoid collecting live data on the
13970      stack.  */
13971   ++function_depth;
13972   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
13973 		     complain, NULL_TREE,
13974 		     /*integral_constant_expression_p=*/false);
13975   --function_depth;
13976 
13977   finish_lambda_scope ();
13978 
13979   /* Make sure the default argument is reasonable.  */
13980   arg = check_default_argument (type, arg, complain);
13981 
13982   if (errorcount+sorrycount > errs
13983       && (complain & tf_warning_or_error))
13984     inform (input_location,
13985 	    "  when instantiating default argument for call to %qD", fn);
13986 
13987   pop_deferring_access_checks ();
13988   pop_access_scope (fn);
13989   pop_from_top_level ();
13990 
13991   if (arg != error_mark_node && !cp_unevaluated_operand)
13992     (*defs)[ridx - 1] = arg;
13993 
13994   return arg;
13995 }
13996 
13997 /* Substitute into all the default arguments for FN.  */
13998 
13999 static void
tsubst_default_arguments(tree fn,tsubst_flags_t complain)14000 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
14001 {
14002   tree arg;
14003   tree tmpl_args;
14004 
14005   tmpl_args = DECL_TI_ARGS (fn);
14006 
14007   /* If this function is not yet instantiated, we certainly don't need
14008      its default arguments.  */
14009   if (uses_template_parms (tmpl_args))
14010     return;
14011   /* Don't do this again for clones.  */
14012   if (DECL_CLONED_FUNCTION_P (fn))
14013     return;
14014 
14015   int i = 0;
14016   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
14017        arg;
14018        arg = TREE_CHAIN (arg), ++i)
14019     if (TREE_PURPOSE (arg))
14020       TREE_PURPOSE (arg) = tsubst_default_argument (fn, i,
14021 						    TREE_VALUE (arg),
14022 						    TREE_PURPOSE (arg),
14023 						    complain);
14024 }
14025 
14026 /* Hash table mapping a FUNCTION_DECL to its dependent explicit-specifier.  */
14027 static GTY((cache)) decl_tree_cache_map *explicit_specifier_map;
14028 
14029 /* Store a pair to EXPLICIT_SPECIFIER_MAP.  */
14030 
14031 void
store_explicit_specifier(tree v,tree t)14032 store_explicit_specifier (tree v, tree t)
14033 {
14034   if (!explicit_specifier_map)
14035     explicit_specifier_map = decl_tree_cache_map::create_ggc (37);
14036   DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (v) = true;
14037   explicit_specifier_map->put (v, t);
14038 }
14039 
14040 /* Lookup an element in EXPLICIT_SPECIFIER_MAP.  */
14041 
14042 tree
lookup_explicit_specifier(tree v)14043 lookup_explicit_specifier (tree v)
14044 {
14045   return *explicit_specifier_map->get (v);
14046 }
14047 
14048 /* Given T, a FUNCTION_TYPE or METHOD_TYPE, construct and return a corresponding
14049    FUNCTION_TYPE or METHOD_TYPE whose return type is RETURN_TYPE, argument types
14050    are ARG_TYPES, and exception specification is RAISES, and otherwise is
14051    identical to T.  */
14052 
14053 static tree
rebuild_function_or_method_type(tree t,tree return_type,tree arg_types,tree raises,tsubst_flags_t complain)14054 rebuild_function_or_method_type (tree t, tree return_type, tree arg_types,
14055 				 tree raises, tsubst_flags_t complain)
14056 {
14057   gcc_assert (FUNC_OR_METHOD_TYPE_P (t));
14058 
14059   tree new_type;
14060   if (TREE_CODE (t) == FUNCTION_TYPE)
14061     {
14062       new_type = build_function_type (return_type, arg_types);
14063       new_type = apply_memfn_quals (new_type, type_memfn_quals (t));
14064     }
14065   else
14066     {
14067       tree r = TREE_TYPE (TREE_VALUE (arg_types));
14068       /* Don't pick up extra function qualifiers from the basetype.  */
14069       r = cp_build_qualified_type_real (r, type_memfn_quals (t), complain);
14070       if (! MAYBE_CLASS_TYPE_P (r))
14071 	{
14072 	  /* [temp.deduct]
14073 
14074 	     Type deduction may fail for any of the following
14075 	     reasons:
14076 
14077 	     -- Attempting to create "pointer to member of T" when T
14078 	     is not a class type.  */
14079 	  if (complain & tf_error)
14080 	    error ("creating pointer to member function of non-class type %qT",
14081 		   r);
14082 	  return error_mark_node;
14083 	}
14084 
14085       new_type = build_method_type_directly (r, return_type,
14086 					     TREE_CHAIN (arg_types));
14087     }
14088   new_type = cp_build_type_attribute_variant (new_type, TYPE_ATTRIBUTES (t));
14089 
14090   cp_ref_qualifier rqual = type_memfn_rqual (t);
14091   bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
14092   return build_cp_fntype_variant (new_type, rqual, raises, late_return_type_p);
14093 }
14094 
14095 /* Check if the function type of DECL, a FUNCTION_DECL, agrees with the type of
14096    each of its formal parameters.  If there is a disagreement then rebuild
14097    DECL's function type according to its formal parameter types, as part of a
14098    resolution for Core issues 1001/1322.  */
14099 
14100 static void
maybe_rebuild_function_decl_type(tree decl)14101 maybe_rebuild_function_decl_type (tree decl)
14102 {
14103   bool function_type_needs_rebuilding = false;
14104   if (tree parm_list = FUNCTION_FIRST_USER_PARM (decl))
14105     {
14106       tree parm_type_list = FUNCTION_FIRST_USER_PARMTYPE (decl);
14107       while (parm_type_list && parm_type_list != void_list_node)
14108 	{
14109 	  tree parm_type = TREE_VALUE (parm_type_list);
14110 	  tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
14111 	  if (!same_type_p (parm_type, formal_parm_type_unqual))
14112 	    {
14113 	      function_type_needs_rebuilding = true;
14114 	      break;
14115 	    }
14116 
14117 	  parm_list = DECL_CHAIN (parm_list);
14118 	  parm_type_list = TREE_CHAIN (parm_type_list);
14119 	}
14120     }
14121 
14122   if (!function_type_needs_rebuilding)
14123     return;
14124 
14125   const tree fntype = TREE_TYPE (decl);
14126   tree parm_list = DECL_ARGUMENTS (decl);
14127   tree old_parm_type_list = TYPE_ARG_TYPES (fntype);
14128   tree new_parm_type_list = NULL_TREE;
14129   tree *q = &new_parm_type_list;
14130   for (int skip = num_artificial_parms_for (decl); skip > 0; skip--)
14131     {
14132       *q = copy_node (old_parm_type_list);
14133       parm_list = DECL_CHAIN (parm_list);
14134       old_parm_type_list = TREE_CHAIN (old_parm_type_list);
14135       q = &TREE_CHAIN (*q);
14136     }
14137   while (old_parm_type_list && old_parm_type_list != void_list_node)
14138     {
14139       *q = copy_node (old_parm_type_list);
14140       tree *new_parm_type = &TREE_VALUE (*q);
14141       tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
14142       if (!same_type_p (*new_parm_type, formal_parm_type_unqual))
14143 	*new_parm_type = formal_parm_type_unqual;
14144 
14145       parm_list = DECL_CHAIN (parm_list);
14146       old_parm_type_list = TREE_CHAIN (old_parm_type_list);
14147       q = &TREE_CHAIN (*q);
14148     }
14149   if (old_parm_type_list == void_list_node)
14150     *q = void_list_node;
14151 
14152   TREE_TYPE (decl)
14153     = rebuild_function_or_method_type (fntype,
14154 				       TREE_TYPE (fntype), new_parm_type_list,
14155 				       TYPE_RAISES_EXCEPTIONS (fntype), tf_none);
14156 }
14157 
14158 /* Subroutine of tsubst_decl for the case when T is a FUNCTION_DECL.  */
14159 
14160 static tree
tsubst_function_decl(tree t,tree args,tsubst_flags_t complain,tree lambda_fntype)14161 tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
14162 		      tree lambda_fntype)
14163 {
14164   tree gen_tmpl = NULL_TREE, argvec = NULL_TREE;
14165   hashval_t hash = 0;
14166   tree in_decl = t;
14167 
14168   /* Nobody should be tsubst'ing into non-template functions.  */
14169   gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE
14170 	      || DECL_LOCAL_DECL_P (t));
14171 
14172   if (DECL_LOCAL_DECL_P (t))
14173     {
14174       if (tree spec = retrieve_local_specialization (t))
14175 	return spec;
14176     }
14177   else if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
14178     {
14179       /* If T is not dependent, just return it.  */
14180       if (!uses_template_parms (DECL_TI_ARGS (t))
14181 	  && !LAMBDA_FUNCTION_P (t))
14182 	return t;
14183 
14184       /* A non-templated friend doesn't get DECL_TEMPLATE_INFO.  */
14185       if (non_templated_friend_p (t))
14186 	goto friend_case;
14187 
14188       /* Calculate the most general template of which R is a
14189 	 specialization.  */
14190       gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
14191 
14192       /* We're substituting a lambda function under tsubst_lambda_expr but not
14193 	 directly from it; find the matching function we're already inside.
14194 	 But don't do this if T is a generic lambda with a single level of
14195 	 template parms, as in that case we're doing a normal instantiation. */
14196       if (LAMBDA_FUNCTION_P (t) && !lambda_fntype
14197 	  && (!generic_lambda_fn_p (t)
14198 	      || TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)) > 1))
14199 	return enclosing_instantiation_of (t);
14200 
14201       /* Calculate the complete set of arguments used to
14202 	 specialize R.  */
14203       argvec = tsubst_template_args (DECL_TI_ARGS
14204 				     (DECL_TEMPLATE_RESULT
14205 				      (DECL_TI_TEMPLATE (t))),
14206 				     args, complain, in_decl);
14207       if (argvec == error_mark_node)
14208 	return error_mark_node;
14209 
14210       /* Check to see if we already have this specialization.  */
14211       if (!lambda_fntype)
14212 	{
14213 	  hash = hash_tmpl_and_args (gen_tmpl, argvec);
14214 	  if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
14215 	    /* The spec for these args might be a partial instantiation of the
14216 	       template, but here what we want is the FUNCTION_DECL.  */
14217 	    return STRIP_TEMPLATE (spec);
14218 	}
14219     }
14220   else
14221     {
14222       /* This special case arises when we have something like this:
14223 
14224 	 template <class T> struct S {
14225 	   friend void f<int>(int, double);
14226 	 };
14227 
14228 	 Here, the DECL_TI_TEMPLATE for the friend declaration
14229 	 will be an IDENTIFIER_NODE.  We are being called from
14230 	 tsubst_friend_function, and we want only to create a
14231 	 new decl (R) with appropriate types so that we can call
14232 	 determine_specialization.  */
14233     friend_case:
14234       gen_tmpl = NULL_TREE;
14235       argvec = NULL_TREE;
14236     }
14237 
14238   tree closure = (lambda_fntype ? TYPE_METHOD_BASETYPE (lambda_fntype)
14239 		  : NULL_TREE);
14240   tree ctx = closure ? closure : DECL_CONTEXT (t);
14241   bool member = ctx && TYPE_P (ctx);
14242 
14243   if (member && !closure)
14244     ctx = tsubst_aggr_type (ctx, args,
14245 			    complain, t, /*entering_scope=*/1);
14246 
14247   tree type = (lambda_fntype ? lambda_fntype
14248 	       : tsubst (TREE_TYPE (t), args,
14249 			 complain | tf_fndecl_type, in_decl));
14250   if (type == error_mark_node)
14251     return error_mark_node;
14252 
14253   /* If we hit excessive deduction depth, the type is bogus even if
14254      it isn't error_mark_node, so don't build a decl.  */
14255   if (excessive_deduction_depth)
14256     return error_mark_node;
14257 
14258   /* We do NOT check for matching decls pushed separately at this
14259      point, as they may not represent instantiations of this
14260      template, and in any case are considered separate under the
14261      discrete model.  */
14262   tree r = copy_decl (t);
14263   DECL_USE_TEMPLATE (r) = 0;
14264   TREE_TYPE (r) = type;
14265   /* Clear out the mangled name and RTL for the instantiation.  */
14266   SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
14267   SET_DECL_RTL (r, NULL);
14268   /* Leave DECL_INITIAL set on deleted instantiations.  */
14269   if (!DECL_DELETED_FN (r))
14270     DECL_INITIAL (r) = NULL_TREE;
14271   DECL_CONTEXT (r) = ctx;
14272   set_instantiating_module (r);
14273 
14274   /* Handle explicit(dependent-expr).  */
14275   if (DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (t))
14276     {
14277       tree spec = lookup_explicit_specifier (t);
14278       spec = tsubst_copy_and_build (spec, args, complain, in_decl,
14279 				    /*function_p=*/false,
14280 				    /*i_c_e_p=*/true);
14281       spec = build_explicit_specifier (spec, complain);
14282       if (instantiation_dependent_expression_p (spec))
14283 	store_explicit_specifier (r, spec);
14284       else
14285 	{
14286 	  DECL_NONCONVERTING_P (r) = (spec == boolean_true_node);
14287 	  DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (r) = false;
14288 	}
14289     }
14290 
14291   /* OpenMP UDRs have the only argument a reference to the declared
14292      type.  We want to diagnose if the declared type is a reference,
14293      which is invalid, but as references to references are usually
14294      quietly merged, diagnose it here.  */
14295   if (DECL_OMP_DECLARE_REDUCTION_P (t))
14296     {
14297       tree argtype
14298 	= TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
14299       argtype = tsubst (argtype, args, complain, in_decl);
14300       if (TYPE_REF_P (argtype))
14301 	error_at (DECL_SOURCE_LOCATION (t),
14302 		  "reference type %qT in "
14303 		  "%<#pragma omp declare reduction%>", argtype);
14304       if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
14305 	DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
14306 					  argtype);
14307     }
14308 
14309   if (member && DECL_CONV_FN_P (r))
14310     /* Type-conversion operator.  Reconstruct the name, in
14311        case it's the name of one of the template's parameters.  */
14312     DECL_NAME (r) = make_conv_op_name (TREE_TYPE (type));
14313 
14314   tree parms = DECL_ARGUMENTS (t);
14315   if (closure)
14316     parms = DECL_CHAIN (parms);
14317   parms = tsubst (parms, args, complain, t);
14318   for (tree parm = parms; parm; parm = DECL_CHAIN (parm))
14319     DECL_CONTEXT (parm) = r;
14320   if (closure)
14321     {
14322       tree tparm = build_this_parm (r, closure, type_memfn_quals (type));
14323       DECL_NAME (tparm) = closure_identifier;
14324       DECL_CHAIN (tparm) = parms;
14325       parms = tparm;
14326     }
14327   DECL_ARGUMENTS (r) = parms;
14328   DECL_RESULT (r) = NULL_TREE;
14329 
14330   maybe_rebuild_function_decl_type (r);
14331 
14332   TREE_STATIC (r) = 0;
14333   TREE_PUBLIC (r) = TREE_PUBLIC (t);
14334   DECL_EXTERNAL (r) = 1;
14335   /* If this is an instantiation of a function with internal
14336      linkage, we already know what object file linkage will be
14337      assigned to the instantiation.  */
14338   DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
14339   DECL_DEFER_OUTPUT (r) = 0;
14340   DECL_CHAIN (r) = NULL_TREE;
14341   DECL_PENDING_INLINE_INFO (r) = 0;
14342   DECL_PENDING_INLINE_P (r) = 0;
14343   DECL_SAVED_TREE (r) = NULL_TREE;
14344   DECL_STRUCT_FUNCTION (r) = NULL;
14345   TREE_USED (r) = 0;
14346   /* We'll re-clone as appropriate in instantiate_template.  */
14347   DECL_CLONED_FUNCTION (r) = NULL_TREE;
14348 
14349   /* If we aren't complaining now, return on error before we register
14350      the specialization so that we'll complain eventually.  */
14351   if ((complain & tf_error) == 0
14352       && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14353       && !grok_op_properties (r, /*complain=*/false))
14354     return error_mark_node;
14355 
14356   /* Associate the constraints directly with the instantiation. We
14357      don't substitute through the constraints; that's only done when
14358      they are checked.  */
14359   if (tree ci = get_constraints (t))
14360     set_constraints (r, ci);
14361 
14362   if (DECL_FRIEND_CONTEXT (t))
14363     SET_DECL_FRIEND_CONTEXT (r,
14364 			     tsubst (DECL_FRIEND_CONTEXT (t),
14365 				     args, complain, in_decl));
14366 
14367   if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14368 				       args, complain, in_decl))
14369     return error_mark_node;
14370 
14371   /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
14372      this in the special friend case mentioned above where
14373      GEN_TMPL is NULL.  */
14374   if (gen_tmpl && !closure)
14375     {
14376       DECL_TEMPLATE_INFO (r)
14377 	= build_template_info (gen_tmpl, argvec);
14378       SET_DECL_IMPLICIT_INSTANTIATION (r);
14379 
14380       tree new_r
14381 	= register_specialization (r, gen_tmpl, argvec, false, hash);
14382       if (new_r != r)
14383 	/* We instantiated this while substituting into
14384 	   the type earlier (template/friend54.C).  */
14385 	return new_r;
14386 
14387       /* We're not supposed to instantiate default arguments
14388 	 until they are called, for a template.  But, for a
14389 	 declaration like:
14390 
14391 	 template <class T> void f ()
14392 	 { extern void g(int i = T()); }
14393 
14394 	 we should do the substitution when the template is
14395 	 instantiated.  We handle the member function case in
14396 	 instantiate_class_template since the default arguments
14397 	 might refer to other members of the class.  */
14398       if (!member
14399 	  && !PRIMARY_TEMPLATE_P (gen_tmpl)
14400 	  && !uses_template_parms (argvec))
14401 	tsubst_default_arguments (r, complain);
14402     }
14403   else if (DECL_LOCAL_DECL_P (r))
14404     {
14405       if (!cp_unevaluated_operand)
14406 	register_local_specialization (r, t);
14407     }
14408   else
14409     DECL_TEMPLATE_INFO (r) = NULL_TREE;
14410 
14411   /* Copy the list of befriending classes.  */
14412   for (tree *friends = &DECL_BEFRIENDING_CLASSES (r);
14413        *friends;
14414        friends = &TREE_CHAIN (*friends))
14415     {
14416       *friends = copy_node (*friends);
14417       TREE_VALUE (*friends)
14418 	= tsubst (TREE_VALUE (*friends), args, complain, in_decl);
14419     }
14420 
14421   if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
14422     {
14423       maybe_retrofit_in_chrg (r);
14424       if (DECL_CONSTRUCTOR_P (r) && !grok_ctor_properties (ctx, r))
14425 	return error_mark_node;
14426       /* If this is an instantiation of a member template, clone it.
14427 	 If it isn't, that'll be handled by
14428 	 clone_constructors_and_destructors.  */
14429       if (gen_tmpl && PRIMARY_TEMPLATE_P (gen_tmpl))
14430 	clone_cdtor (r, /*update_methods=*/false);
14431     }
14432   else if ((complain & tf_error) != 0
14433 	   && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14434 	   && !grok_op_properties (r, /*complain=*/true))
14435     return error_mark_node;
14436 
14437   /* Possibly limit visibility based on template args.  */
14438   DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
14439   if (DECL_VISIBILITY_SPECIFIED (t))
14440     {
14441       DECL_VISIBILITY_SPECIFIED (r) = 0;
14442       DECL_ATTRIBUTES (r)
14443 	= remove_attribute ("visibility", DECL_ATTRIBUTES (r));
14444     }
14445   determine_visibility (r);
14446   if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
14447       && COMPLETE_TYPE_P (DECL_CONTEXT (r))
14448       && !processing_template_decl)
14449     defaulted_late_check (r);
14450 
14451   if (flag_openmp)
14452     if (tree attr = lookup_attribute ("omp declare variant base",
14453 				      DECL_ATTRIBUTES (r)))
14454       omp_declare_variant_finalize (r, attr);
14455 
14456   return r;
14457 }
14458 
14459 /* Subroutine of tsubst_decl for the case when T is a TEMPLATE_DECL.  */
14460 
14461 static tree
tsubst_template_decl(tree t,tree args,tsubst_flags_t complain,tree lambda_fntype)14462 tsubst_template_decl (tree t, tree args, tsubst_flags_t complain,
14463 		      tree lambda_fntype)
14464 {
14465   /* We can get here when processing a member function template,
14466      member class template, or template template parameter.  */
14467   tree decl = DECL_TEMPLATE_RESULT (t);
14468   tree in_decl = t;
14469   tree spec;
14470   tree tmpl_args;
14471   tree full_args;
14472   tree r;
14473   hashval_t hash = 0;
14474 
14475   if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
14476     {
14477       /* Template template parameter is treated here.  */
14478       tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14479       if (new_type == error_mark_node)
14480 	r = error_mark_node;
14481       /* If we get a real template back, return it.  This can happen in
14482 	 the context of most_specialized_partial_spec.  */
14483       else if (TREE_CODE (new_type) == TEMPLATE_DECL)
14484 	r = new_type;
14485       else
14486 	/* The new TEMPLATE_DECL was built in
14487 	   reduce_template_parm_level.  */
14488 	r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
14489       return r;
14490     }
14491 
14492   if (!lambda_fntype)
14493     {
14494       /* We might already have an instance of this template.
14495 	 The ARGS are for the surrounding class type, so the
14496 	 full args contain the tsubst'd args for the context,
14497 	 plus the innermost args from the template decl.  */
14498       tmpl_args = DECL_CLASS_TEMPLATE_P (t)
14499 	? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
14500 	: DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
14501       /* Because this is a template, the arguments will still be
14502 	 dependent, even after substitution.  If
14503 	 PROCESSING_TEMPLATE_DECL is not set, the dependency
14504 	 predicates will short-circuit.  */
14505       ++processing_template_decl;
14506       full_args = tsubst_template_args (tmpl_args, args,
14507 					complain, in_decl);
14508       --processing_template_decl;
14509       if (full_args == error_mark_node)
14510 	return error_mark_node;
14511 
14512       /* If this is a default template template argument,
14513 	 tsubst might not have changed anything.  */
14514       if (full_args == tmpl_args)
14515 	return t;
14516 
14517       hash = hash_tmpl_and_args (t, full_args);
14518       spec = retrieve_specialization (t, full_args, hash);
14519       if (spec != NULL_TREE)
14520 	{
14521 	  if (TYPE_P (spec))
14522 	    /* Type partial instantiations are stored as the type by
14523 	       lookup_template_class_1, not here as the template.  */
14524 	    spec = CLASSTYPE_TI_TEMPLATE (spec);
14525 	  return spec;
14526 	}
14527     }
14528 
14529   /* Make a new template decl.  It will be similar to the
14530      original, but will record the current template arguments.
14531      We also create a new function declaration, which is just
14532      like the old one, but points to this new template, rather
14533      than the old one.  */
14534   r = copy_decl (t);
14535   gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
14536   DECL_CHAIN (r) = NULL_TREE;
14537 
14538   // Build new template info linking to the original template decl.
14539   if (!lambda_fntype)
14540     {
14541       DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
14542       SET_DECL_IMPLICIT_INSTANTIATION (r);
14543     }
14544   else
14545     DECL_TEMPLATE_INFO (r) = NULL_TREE;
14546 
14547   /* The template parameters for this new template are all the
14548      template parameters for the old template, except the
14549      outermost level of parameters.  */
14550   auto tparm_guard = make_temp_override (current_template_parms);
14551   DECL_TEMPLATE_PARMS (r)
14552     = current_template_parms
14553     = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
14554 			     complain);
14555 
14556   bool class_p = false;
14557   tree inner = decl;
14558   ++processing_template_decl;
14559   if (TREE_CODE (inner) == FUNCTION_DECL)
14560     inner = tsubst_function_decl (inner, args, complain, lambda_fntype);
14561   else
14562     {
14563       if (TREE_CODE (inner) == TYPE_DECL && !TYPE_DECL_ALIAS_P (inner))
14564 	{
14565 	  class_p = true;
14566 	  inner = TREE_TYPE (inner);
14567 	}
14568       if (class_p)
14569 	inner = tsubst_aggr_type (inner, args, complain,
14570 				  in_decl, /*entering*/1);
14571       else
14572 	inner = tsubst (inner, args, complain, in_decl);
14573     }
14574   --processing_template_decl;
14575   if (inner == error_mark_node)
14576     return error_mark_node;
14577 
14578   if (class_p)
14579     {
14580       /* For a partial specialization, we need to keep pointing to
14581 	 the primary template.  */
14582       if (!DECL_TEMPLATE_SPECIALIZATION (t))
14583 	CLASSTYPE_TI_TEMPLATE (inner) = r;
14584 
14585       DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (inner);
14586       inner = TYPE_MAIN_DECL (inner);
14587     }
14588   else if (lambda_fntype)
14589     {
14590       tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (r));
14591       DECL_TEMPLATE_INFO (inner) = build_template_info (r, args);
14592     }
14593   else
14594     {
14595       DECL_TI_TEMPLATE (inner) = r;
14596       DECL_TI_ARGS (r) = DECL_TI_ARGS (inner);
14597     }
14598 
14599   DECL_TEMPLATE_RESULT (r) = inner;
14600   TREE_TYPE (r) = TREE_TYPE (inner);
14601   DECL_CONTEXT (r) = DECL_CONTEXT (inner);
14602 
14603   if (modules_p ())
14604     {
14605       /* Propagate module information from the decl.  */
14606       DECL_MODULE_EXPORT_P (r) = DECL_MODULE_EXPORT_P (inner);
14607       if (DECL_LANG_SPECIFIC (inner))
14608 	/* If this is a constrained template, the above tsubst of
14609 	   inner can find the unconstrained template, which may have
14610 	   come from an import.  This is ok, because we don't
14611 	   register this instantiation (see below).  */
14612 	gcc_checking_assert (!DECL_MODULE_IMPORT_P (inner)
14613 			     || (TEMPLATE_PARMS_CONSTRAINTS
14614 				 (DECL_TEMPLATE_PARMS (t))));
14615     }
14616 
14617   DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
14618   DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
14619 
14620   if (PRIMARY_TEMPLATE_P (t))
14621     DECL_PRIMARY_TEMPLATE (r) = r;
14622 
14623   if (TREE_CODE (decl) == FUNCTION_DECL && !lambda_fntype)
14624     /* Record this non-type partial instantiation.  */
14625     register_specialization (r, t,
14626 			     DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
14627 			     false, hash);
14628 
14629   return r;
14630 }
14631 
14632 /* True if FN is the op() for a lambda in an uninstantiated template.  */
14633 
14634 bool
lambda_fn_in_template_p(tree fn)14635 lambda_fn_in_template_p (tree fn)
14636 {
14637   if (!fn || !LAMBDA_FUNCTION_P (fn))
14638     return false;
14639   tree closure = DECL_CONTEXT (fn);
14640   return CLASSTYPE_TEMPLATE_INFO (closure) != NULL_TREE;
14641 }
14642 
14643 /* True if FN is the substitution (via tsubst_lambda_expr) of a function for
14644    which the above is true.  */
14645 
14646 bool
regenerated_lambda_fn_p(tree fn)14647 regenerated_lambda_fn_p (tree fn)
14648 {
14649   if (!fn || !LAMBDA_FUNCTION_P (fn))
14650     return false;
14651   tree closure = DECL_CONTEXT (fn);
14652   tree lam = CLASSTYPE_LAMBDA_EXPR (closure);
14653   return LAMBDA_EXPR_REGEN_INFO (lam) != NULL_TREE;
14654 }
14655 
14656 /* Return the LAMBDA_EXPR from which T was ultimately regenerated.
14657    If T is not a regenerated LAMBDA_EXPR, return T.  */
14658 
14659 tree
most_general_lambda(tree t)14660 most_general_lambda (tree t)
14661 {
14662   while (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
14663     t = TI_TEMPLATE (ti);
14664   return t;
14665 }
14666 
14667 /* Return the set of template arguments used to regenerate the lambda T
14668    from its most general lambda.  */
14669 
14670 tree
lambda_regenerating_args(tree t)14671 lambda_regenerating_args (tree t)
14672 {
14673   if (LAMBDA_FUNCTION_P (t))
14674     t = CLASSTYPE_LAMBDA_EXPR (DECL_CONTEXT (t));
14675   gcc_assert (TREE_CODE (t) == LAMBDA_EXPR);
14676   if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
14677     return TI_ARGS (ti);
14678   else
14679     return NULL_TREE;
14680 }
14681 
14682 /* We're instantiating a variable from template function TCTX.  Return the
14683    corresponding current enclosing scope.  We can match them up using
14684    DECL_SOURCE_LOCATION because lambdas only ever have one source location, and
14685    the DECL_SOURCE_LOCATION for a function instantiation is updated to match
14686    the template definition in regenerate_decl_from_template.  */
14687 
14688 static tree
enclosing_instantiation_of(tree tctx)14689 enclosing_instantiation_of (tree tctx)
14690 {
14691   tree fn = current_function_decl;
14692 
14693   /* We shouldn't ever need to do this for other artificial functions.  */
14694   gcc_assert (!DECL_ARTIFICIAL (tctx) || LAMBDA_FUNCTION_P (tctx));
14695 
14696   for (; fn; fn = decl_function_context (fn))
14697     if (DECL_SOURCE_LOCATION (fn) == DECL_SOURCE_LOCATION (tctx))
14698       return fn;
14699   gcc_unreachable ();
14700 }
14701 
14702 /* Substitute the ARGS into the T, which is a _DECL.  Return the
14703    result of the substitution.  Issue error and warning messages under
14704    control of COMPLAIN.  */
14705 
14706 static tree
tsubst_decl(tree t,tree args,tsubst_flags_t complain)14707 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
14708 {
14709 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
14710   location_t saved_loc;
14711   tree r = NULL_TREE;
14712   tree in_decl = t;
14713   hashval_t hash = 0;
14714 
14715   /* Set the filename and linenumber to improve error-reporting.  */
14716   saved_loc = input_location;
14717   input_location = DECL_SOURCE_LOCATION (t);
14718 
14719   switch (TREE_CODE (t))
14720     {
14721     case TEMPLATE_DECL:
14722       r = tsubst_template_decl (t, args, complain, /*lambda*/NULL_TREE);
14723       break;
14724 
14725     case FUNCTION_DECL:
14726       r = tsubst_function_decl (t, args, complain, /*lambda*/NULL_TREE);
14727       break;
14728 
14729     case PARM_DECL:
14730       {
14731 	tree type = NULL_TREE;
14732         int i, len = 1;
14733         tree expanded_types = NULL_TREE;
14734         tree prev_r = NULL_TREE;
14735         tree first_r = NULL_TREE;
14736 
14737         if (DECL_PACK_P (t))
14738           {
14739             /* If there is a local specialization that isn't a
14740                parameter pack, it means that we're doing a "simple"
14741                substitution from inside tsubst_pack_expansion. Just
14742                return the local specialization (which will be a single
14743                parm).  */
14744             tree spec = retrieve_local_specialization (t);
14745             if (spec
14746                 && TREE_CODE (spec) == PARM_DECL
14747                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
14748               RETURN (spec);
14749 
14750             /* Expand the TYPE_PACK_EXPANSION that provides the types for
14751                the parameters in this function parameter pack.  */
14752             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
14753 						    complain, in_decl);
14754             if (TREE_CODE (expanded_types) == TREE_VEC)
14755               {
14756                 len = TREE_VEC_LENGTH (expanded_types);
14757 
14758                 /* Zero-length parameter packs are boring. Just substitute
14759                    into the chain.  */
14760 		if (len == 0 && !cp_unevaluated_operand)
14761                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
14762 				  TREE_CHAIN (t)));
14763               }
14764             else
14765               {
14766                 /* All we did was update the type. Make a note of that.  */
14767                 type = expanded_types;
14768                 expanded_types = NULL_TREE;
14769               }
14770           }
14771 
14772         /* Loop through all of the parameters we'll build. When T is
14773            a function parameter pack, LEN is the number of expanded
14774            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
14775         r = NULL_TREE;
14776         for (i = 0; i < len; ++i)
14777           {
14778             prev_r = r;
14779             r = copy_node (t);
14780             if (DECL_TEMPLATE_PARM_P (t))
14781               SET_DECL_TEMPLATE_PARM_P (r);
14782 
14783             if (expanded_types)
14784               /* We're on the Ith parameter of the function parameter
14785                  pack.  */
14786               {
14787                 /* Get the Ith type.  */
14788                 type = TREE_VEC_ELT (expanded_types, i);
14789 
14790 		/* Rename the parameter to include the index.  */
14791 		DECL_NAME (r)
14792 		  = make_ith_pack_parameter_name (DECL_NAME (r), i);
14793               }
14794             else if (!type)
14795               /* We're dealing with a normal parameter.  */
14796               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14797 
14798             type = type_decays_to (type);
14799             TREE_TYPE (r) = type;
14800             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14801 
14802             if (DECL_INITIAL (r))
14803               {
14804                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
14805                   DECL_INITIAL (r) = TREE_TYPE (r);
14806                 else
14807                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
14808                                              complain, in_decl);
14809               }
14810 
14811             DECL_CONTEXT (r) = NULL_TREE;
14812 
14813             if (!DECL_TEMPLATE_PARM_P (r))
14814               DECL_ARG_TYPE (r) = type_passed_as (type);
14815 
14816 	    if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14817 						 args, complain, in_decl))
14818 	      return error_mark_node;
14819 
14820             /* Keep track of the first new parameter we
14821                generate. That's what will be returned to the
14822                caller.  */
14823             if (!first_r)
14824               first_r = r;
14825 
14826             /* Build a proper chain of parameters when substituting
14827                into a function parameter pack.  */
14828             if (prev_r)
14829               DECL_CHAIN (prev_r) = r;
14830           }
14831 
14832 	/* If cp_unevaluated_operand is set, we're just looking for a
14833 	   single dummy parameter, so don't keep going.  */
14834 	if (DECL_CHAIN (t) && !cp_unevaluated_operand)
14835 	  DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
14836 				   complain, DECL_CHAIN (t));
14837 
14838         /* FIRST_R contains the start of the chain we've built.  */
14839         r = first_r;
14840       }
14841       break;
14842 
14843     case FIELD_DECL:
14844       {
14845 	tree type = NULL_TREE;
14846 	tree vec = NULL_TREE;
14847 	tree expanded_types = NULL_TREE;
14848 	int len = 1;
14849 
14850 	if (PACK_EXPANSION_P (TREE_TYPE (t)))
14851 	  {
14852 	    /* This field is a lambda capture pack.  Return a TREE_VEC of
14853 	       the expanded fields to instantiate_class_template_1.  */
14854             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
14855 						    complain, in_decl);
14856             if (TREE_CODE (expanded_types) == TREE_VEC)
14857               {
14858                 len = TREE_VEC_LENGTH (expanded_types);
14859 		vec = make_tree_vec (len);
14860               }
14861             else
14862               {
14863                 /* All we did was update the type. Make a note of that.  */
14864                 type = expanded_types;
14865                 expanded_types = NULL_TREE;
14866               }
14867 	  }
14868 
14869 	for (int i = 0; i < len; ++i)
14870 	  {
14871 	    r = copy_decl (t);
14872 	    if (expanded_types)
14873 	      {
14874 		type = TREE_VEC_ELT (expanded_types, i);
14875 		DECL_NAME (r)
14876 		  = make_ith_pack_parameter_name (DECL_NAME (r), i);
14877 	      }
14878             else if (!type)
14879               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14880 
14881 	    if (type == error_mark_node)
14882 	      RETURN (error_mark_node);
14883 	    TREE_TYPE (r) = type;
14884 	    cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14885 
14886 	    if (DECL_C_BIT_FIELD (r))
14887 	      /* For bit-fields, DECL_BIT_FIELD_REPRESENTATIVE gives the
14888 		 number of bits.  */
14889 	      DECL_BIT_FIELD_REPRESENTATIVE (r)
14890 		= tsubst_expr (DECL_BIT_FIELD_REPRESENTATIVE (t), args,
14891 			       complain, in_decl,
14892 			       /*integral_constant_expression_p=*/true);
14893 	    if (DECL_INITIAL (t))
14894 	      {
14895 		/* Set up DECL_TEMPLATE_INFO so that we can get at the
14896 		   NSDMI in perform_member_init.  Still set DECL_INITIAL
14897 		   so that we know there is one.  */
14898 		DECL_INITIAL (r) = void_node;
14899 		gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
14900 		retrofit_lang_decl (r);
14901 		DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
14902 	      }
14903 	    /* We don't have to set DECL_CONTEXT here; it is set by
14904 	       finish_member_declaration.  */
14905 	    DECL_CHAIN (r) = NULL_TREE;
14906 
14907 	    if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14908 						 args, complain, in_decl))
14909 	      return error_mark_node;
14910 
14911 	    if (vec)
14912 	      TREE_VEC_ELT (vec, i) = r;
14913 	  }
14914 
14915 	if (vec)
14916 	  r = vec;
14917       }
14918       break;
14919 
14920     case USING_DECL:
14921       /* We reach here only for member using decls.  We also need to check
14922 	 uses_template_parms because DECL_DEPENDENT_P is not set for a
14923 	 using-declaration that designates a member of the current
14924 	 instantiation (c++/53549).  */
14925       if (DECL_DEPENDENT_P (t)
14926 	  || uses_template_parms (USING_DECL_SCOPE (t)))
14927 	{
14928 	  tree scope = USING_DECL_SCOPE (t);
14929 	  tree name = tsubst_copy (DECL_NAME (t), args, complain, in_decl);
14930 	  if (PACK_EXPANSION_P (scope))
14931 	    {
14932 	      tree vec = tsubst_pack_expansion (scope, args, complain, in_decl);
14933 	      int len = TREE_VEC_LENGTH (vec);
14934 	      r = make_tree_vec (len);
14935 	      for (int i = 0; i < len; ++i)
14936 		{
14937 		  tree escope = TREE_VEC_ELT (vec, i);
14938 		  tree elt = do_class_using_decl (escope, name);
14939 		  if (!elt)
14940 		    {
14941 		      r = error_mark_node;
14942 		      break;
14943 		    }
14944 		  else
14945 		    {
14946 		      TREE_PROTECTED (elt) = TREE_PROTECTED (t);
14947 		      TREE_PRIVATE (elt) = TREE_PRIVATE (t);
14948 		    }
14949 		  TREE_VEC_ELT (r, i) = elt;
14950 		}
14951 	    }
14952 	  else
14953 	    {
14954 	      tree inst_scope = tsubst_copy (USING_DECL_SCOPE (t), args,
14955 					     complain, in_decl);
14956 	      r = do_class_using_decl (inst_scope, name);
14957 	      if (!r)
14958 		r = error_mark_node;
14959 	      else
14960 		{
14961 		  TREE_PROTECTED (r) = TREE_PROTECTED (t);
14962 		  TREE_PRIVATE (r) = TREE_PRIVATE (t);
14963 		}
14964 	    }
14965 	}
14966       else
14967 	{
14968 	  r = copy_node (t);
14969 	  DECL_CHAIN (r) = NULL_TREE;
14970 	}
14971       break;
14972 
14973     case TYPE_DECL:
14974     case VAR_DECL:
14975       {
14976 	tree argvec = NULL_TREE;
14977 	tree gen_tmpl = NULL_TREE;
14978 	tree tmpl = NULL_TREE;
14979 	tree type = NULL_TREE;
14980 
14981 	if (TREE_TYPE (t) == error_mark_node)
14982 	  RETURN (error_mark_node);
14983 
14984 	if (TREE_CODE (t) == TYPE_DECL
14985 	    && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
14986 	  {
14987 	    /* If this is the canonical decl, we don't have to
14988 	       mess with instantiations, and often we can't (for
14989 	       typename, template type parms and such).  Note that
14990 	       TYPE_NAME is not correct for the above test if
14991 	       we've copied the type for a typedef.  */
14992 	    type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14993 	    if (type == error_mark_node)
14994 	      RETURN (error_mark_node);
14995 	    r = TYPE_NAME (type);
14996 	    break;
14997 	  }
14998 
14999 	/* Check to see if we already have the specialization we
15000 	   need.  */
15001 	tree spec = NULL_TREE;
15002 	bool local_p = false;
15003 	tree ctx = DECL_CONTEXT (t);
15004 	if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t))
15005 	    && (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t)))
15006 	  {
15007 	    local_p = false;
15008 	    if (DECL_CLASS_SCOPE_P (t))
15009 	      {
15010 		ctx = tsubst_aggr_type (ctx, args,
15011 					complain,
15012 					in_decl, /*entering_scope=*/1);
15013 		/* If CTX is unchanged, then T is in fact the
15014 		   specialization we want.  That situation occurs when
15015 		   referencing a static data member within in its own
15016 		   class.  We can use pointer equality, rather than
15017 		   same_type_p, because DECL_CONTEXT is always
15018 		   canonical...  */
15019 		if (ctx == DECL_CONTEXT (t)
15020 		    /* ... unless T is a member template; in which
15021 		       case our caller can be willing to create a
15022 		       specialization of that template represented
15023 		       by T.  */
15024 		    && !(DECL_TI_TEMPLATE (t)
15025 			 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
15026 		  spec = t;
15027 	      }
15028 
15029 	    if (!spec)
15030 	      {
15031 		tmpl = DECL_TI_TEMPLATE (t);
15032 		gen_tmpl = most_general_template (tmpl);
15033 		argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
15034 		if (argvec != error_mark_node)
15035 		  argvec = (coerce_innermost_template_parms
15036 			    (DECL_TEMPLATE_PARMS (gen_tmpl),
15037 			     argvec, tmpl, complain,
15038 			     /*all*/true, /*defarg*/true));
15039 		if (argvec == error_mark_node)
15040 		  RETURN (error_mark_node);
15041 		hash = hash_tmpl_and_args (gen_tmpl, argvec);
15042 		spec = retrieve_specialization (gen_tmpl, argvec, hash);
15043 	      }
15044 	  }
15045 	else
15046 	  {
15047 	    if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t)))
15048 	      /* Subsequent calls to pushdecl will fill this in.  */
15049 	      ctx = NULL_TREE;
15050 	    /* A local variable.  */
15051 	    local_p = true;
15052 	    /* Unless this is a reference to a static variable from an
15053 	       enclosing function, in which case we need to fill it in now.  */
15054 	    if (TREE_STATIC (t))
15055 	      {
15056 		tree fn = enclosing_instantiation_of (DECL_CONTEXT (t));
15057 		if (fn != current_function_decl)
15058 		  ctx = fn;
15059 	      }
15060 	    spec = retrieve_local_specialization (t);
15061 	  }
15062 	/* If we already have the specialization we need, there is
15063 	   nothing more to do.  */
15064 	if (spec)
15065 	  {
15066 	    r = spec;
15067 	    break;
15068 	  }
15069 
15070 	/* Create a new node for the specialization we need.  */
15071 	if (type == NULL_TREE)
15072 	  {
15073 	    if (is_typedef_decl (t))
15074 	      type = DECL_ORIGINAL_TYPE (t);
15075 	    else
15076 	      type = TREE_TYPE (t);
15077 	    if (VAR_P (t)
15078 		&& VAR_HAD_UNKNOWN_BOUND (t)
15079 		&& type != error_mark_node)
15080 	      type = strip_array_domain (type);
15081 	    tsubst_flags_t tcomplain = complain;
15082 	    if (VAR_P (t))
15083 	      tcomplain |= tf_tst_ok;
15084 	    type = tsubst (type, args, tcomplain, in_decl);
15085 	    /* Substituting the type might have recursively instantiated this
15086 	       same alias (c++/86171).  */
15087 	    if (gen_tmpl && DECL_ALIAS_TEMPLATE_P (gen_tmpl)
15088 		&& (spec = retrieve_specialization (gen_tmpl, argvec, hash)))
15089 	      {
15090 		r = spec;
15091 		break;
15092 	      }
15093 	  }
15094 	r = copy_decl (t);
15095 	if (VAR_P (r))
15096 	  {
15097 	    DECL_INITIALIZED_P (r) = 0;
15098 	    DECL_TEMPLATE_INSTANTIATED (r) = 0;
15099 	    if (type == error_mark_node)
15100 	      RETURN (error_mark_node);
15101 	    if (TREE_CODE (type) == FUNCTION_TYPE)
15102 	      {
15103 		/* It may seem that this case cannot occur, since:
15104 
15105 		   typedef void f();
15106 		   void g() { f x; }
15107 
15108 		   declares a function, not a variable.  However:
15109 
15110 		   typedef void f();
15111 		   template <typename T> void g() { T t; }
15112 		   template void g<f>();
15113 
15114 		   is an attempt to declare a variable with function
15115 		   type.  */
15116 		error ("variable %qD has function type",
15117 		       /* R is not yet sufficiently initialized, so we
15118 			  just use its name.  */
15119 		       DECL_NAME (r));
15120 		RETURN (error_mark_node);
15121 	      }
15122 	    type = complete_type (type);
15123 	    /* Wait until cp_finish_decl to set this again, to handle
15124 	       circular dependency (template/instantiate6.C). */
15125 	    DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
15126 	    type = check_var_type (DECL_NAME (r), type,
15127 				   DECL_SOURCE_LOCATION (r));
15128 	    if (DECL_HAS_VALUE_EXPR_P (t))
15129 	      {
15130 		tree ve = DECL_VALUE_EXPR (t);
15131 		/* If the DECL_VALUE_EXPR is converted to the declared type,
15132 		   preserve the identity so that gimplify_type_sizes works.  */
15133 		bool nop = (TREE_CODE (ve) == NOP_EXPR);
15134 		if (nop)
15135 		  ve = TREE_OPERAND (ve, 0);
15136 		ve = tsubst_expr (ve, args, complain, in_decl,
15137 				  /*constant_expression_p=*/false);
15138 		if (REFERENCE_REF_P (ve))
15139 		  {
15140 		    gcc_assert (TYPE_REF_P (type));
15141 		    ve = TREE_OPERAND (ve, 0);
15142 		  }
15143 		if (nop)
15144 		  ve = build_nop (type, ve);
15145 		else if (DECL_LANG_SPECIFIC (t)
15146 			 && DECL_OMP_PRIVATIZED_MEMBER (t)
15147 			 && TREE_CODE (ve) == COMPONENT_REF
15148 			 && TREE_CODE (TREE_OPERAND (ve, 1)) == FIELD_DECL
15149 			 && DECL_BIT_FIELD_TYPE (TREE_OPERAND (ve, 1)) == type)
15150 		  type = TREE_TYPE (ve);
15151 		else
15152 		  gcc_checking_assert (TYPE_MAIN_VARIANT (TREE_TYPE (ve))
15153 				       == TYPE_MAIN_VARIANT (type));
15154 		SET_DECL_VALUE_EXPR (r, ve);
15155 	      }
15156 	    if (CP_DECL_THREAD_LOCAL_P (r)
15157 		&& !processing_template_decl)
15158 	      set_decl_tls_model (r, decl_default_tls_model (r));
15159 	  }
15160 	else if (DECL_SELF_REFERENCE_P (t))
15161 	  SET_DECL_SELF_REFERENCE_P (r);
15162 	TREE_TYPE (r) = type;
15163 	cp_apply_type_quals_to_decl (cp_type_quals (type), r);
15164 	DECL_CONTEXT (r) = ctx;
15165 	/* Clear out the mangled name and RTL for the instantiation.  */
15166 	SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
15167 	if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
15168 	  SET_DECL_RTL (r, NULL);
15169 	set_instantiating_module (r);
15170 
15171 	/* The initializer must not be expanded until it is required;
15172 	   see [temp.inst].  */
15173 	DECL_INITIAL (r) = NULL_TREE;
15174 	DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
15175 	if (VAR_P (r))
15176 	  {
15177 	    if (DECL_LANG_SPECIFIC (r))
15178 	      SET_DECL_DEPENDENT_INIT_P (r, false);
15179 
15180 	    SET_DECL_MODE (r, VOIDmode);
15181 
15182 	    /* Possibly limit visibility based on template args.  */
15183 	    DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
15184 	    if (DECL_VISIBILITY_SPECIFIED (t))
15185 	      {
15186 		DECL_VISIBILITY_SPECIFIED (r) = 0;
15187 		DECL_ATTRIBUTES (r)
15188 		  = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
15189 	      }
15190 	    determine_visibility (r);
15191 	  }
15192 
15193 	if (!local_p)
15194 	  {
15195 	    /* A static data member declaration is always marked
15196 	       external when it is declared in-class, even if an
15197 	       initializer is present.  We mimic the non-template
15198 	       processing here.  */
15199 	    DECL_EXTERNAL (r) = 1;
15200 	    if (DECL_NAMESPACE_SCOPE_P (t))
15201 	      DECL_NOT_REALLY_EXTERN (r) = 1;
15202 
15203 	    DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
15204 	    SET_DECL_IMPLICIT_INSTANTIATION (r);
15205 	    if (!error_operand_p (r) || (complain & tf_error))
15206 	      register_specialization (r, gen_tmpl, argvec, false, hash);
15207 	  }
15208 	else
15209 	  {
15210 	    if (DECL_LANG_SPECIFIC (r))
15211 	      DECL_TEMPLATE_INFO (r) = NULL_TREE;
15212 	    if (!cp_unevaluated_operand)
15213 	      register_local_specialization (r, t);
15214 	  }
15215 
15216 	DECL_CHAIN (r) = NULL_TREE;
15217 
15218 	if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
15219 					     /*flags=*/0,
15220 					     args, complain, in_decl))
15221 	  return error_mark_node;
15222 
15223 	/* Preserve a typedef that names a type.  */
15224 	if (is_typedef_decl (r) && type != error_mark_node)
15225 	  {
15226 	    DECL_ORIGINAL_TYPE (r) = NULL_TREE;
15227 	    set_underlying_type (r);
15228 
15229 	    /* common_handle_aligned_attribute doesn't apply the alignment
15230 	       to DECL_ORIGINAL_TYPE.  */
15231 	    if (TYPE_USER_ALIGN (TREE_TYPE (t)))
15232 	      TREE_TYPE (r) = build_aligned_type (TREE_TYPE (r),
15233 						  TYPE_ALIGN (TREE_TYPE (t)));
15234 	  }
15235 
15236 	layout_decl (r, 0);
15237       }
15238       break;
15239 
15240     default:
15241       gcc_unreachable ();
15242     }
15243 #undef RETURN
15244 
15245  out:
15246   /* Restore the file and line information.  */
15247   input_location = saved_loc;
15248 
15249   return r;
15250 }
15251 
15252 /* Substitute into the complete parameter type list PARMS.  */
15253 
15254 tree
tsubst_function_parms(tree parms,tree args,tsubst_flags_t complain,tree in_decl)15255 tsubst_function_parms (tree parms,
15256 		       tree args,
15257 		       tsubst_flags_t complain,
15258 		       tree in_decl)
15259 {
15260   return tsubst_arg_types (parms, args, NULL_TREE, complain, in_decl);
15261 }
15262 
15263 /* Substitute into the ARG_TYPES of a function type.
15264    If END is a TREE_CHAIN, leave it and any following types
15265    un-substituted.  */
15266 
15267 static tree
tsubst_arg_types(tree arg_types,tree args,tree end,tsubst_flags_t complain,tree in_decl)15268 tsubst_arg_types (tree arg_types,
15269 		  tree args,
15270 		  tree end,
15271 		  tsubst_flags_t complain,
15272 		  tree in_decl)
15273 {
15274   tree type = NULL_TREE;
15275   int len = 1;
15276   tree expanded_args = NULL_TREE;
15277 
15278   if (!arg_types || arg_types == void_list_node || arg_types == end)
15279     return arg_types;
15280 
15281   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
15282     {
15283       /* For a pack expansion, perform substitution on the
15284          entire expression. Later on, we'll handle the arguments
15285          one-by-one.  */
15286       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
15287                                             args, complain, in_decl);
15288 
15289       if (TREE_CODE (expanded_args) == TREE_VEC)
15290         /* So that we'll spin through the parameters, one by one.  */
15291 	len = TREE_VEC_LENGTH (expanded_args);
15292       else
15293         {
15294           /* We only partially substituted into the parameter
15295              pack. Our type is TYPE_PACK_EXPANSION.  */
15296           type = expanded_args;
15297           expanded_args = NULL_TREE;
15298         }
15299     }
15300   else
15301     type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
15302 
15303   /* Check if a substituted type is erroneous before substituting into
15304      the rest of the chain.  */
15305   for (int i = 0; i < len; i++)
15306     {
15307       if (expanded_args)
15308 	type = TREE_VEC_ELT (expanded_args, i);
15309 
15310       if (type == error_mark_node)
15311 	return error_mark_node;
15312       if (VOID_TYPE_P (type))
15313 	{
15314 	  if (complain & tf_error)
15315 	    {
15316 	      error ("invalid parameter type %qT", type);
15317 	      if (in_decl)
15318 		error ("in declaration %q+D", in_decl);
15319 	    }
15320 	  return error_mark_node;
15321 	}
15322     }
15323 
15324   /* We do not substitute into default arguments here.  The standard
15325      mandates that they be instantiated only when needed, which is
15326      done in build_over_call.  */
15327   tree default_arg = TREE_PURPOSE (arg_types);
15328 
15329   /* Except that we do substitute default arguments under tsubst_lambda_expr,
15330      since the new op() won't have any associated template arguments for us
15331      to refer to later.  */
15332   if (lambda_fn_in_template_p (in_decl)
15333       || (in_decl && TREE_CODE (in_decl) == FUNCTION_DECL
15334 	  && DECL_LOCAL_DECL_P (in_decl)))
15335     default_arg = tsubst_copy_and_build (default_arg, args, complain, in_decl,
15336 					 false/*fn*/, false/*constexpr*/);
15337 
15338   tree remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
15339 					       args, end, complain, in_decl);
15340   if (remaining_arg_types == error_mark_node)
15341     return error_mark_node;
15342 
15343   for (int i = len-1; i >= 0; i--)
15344     {
15345       if (expanded_args)
15346 	type = TREE_VEC_ELT (expanded_args, i);
15347 
15348       /* Do array-to-pointer, function-to-pointer conversion, and ignore
15349 	 top-level qualifiers as required.  */
15350       type = cv_unqualified (type_decays_to (type));
15351 
15352       if (default_arg && TREE_CODE (default_arg) == DEFERRED_PARSE)
15353 	{
15354 	  /* We've instantiated a template before its default arguments
15355 	     have been parsed.  This can happen for a nested template
15356 	     class, and is not an error unless we require the default
15357 	     argument in a call of this function.  */
15358 	  remaining_arg_types
15359 	    = tree_cons (default_arg, type, remaining_arg_types);
15360 	  vec_safe_push (DEFPARSE_INSTANTIATIONS (default_arg),
15361 			 remaining_arg_types);
15362 	}
15363       else
15364 	remaining_arg_types
15365 	  = hash_tree_cons (default_arg, type, remaining_arg_types);
15366     }
15367 
15368   return remaining_arg_types;
15369 }
15370 
15371 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
15372    *not* handle the exception-specification for FNTYPE, because the
15373    initial substitution of explicitly provided template parameters
15374    during argument deduction forbids substitution into the
15375    exception-specification:
15376 
15377      [temp.deduct]
15378 
15379      All references in the function type of the function template to  the
15380      corresponding template parameters are replaced by the specified tem-
15381      plate argument values.  If a substitution in a template parameter or
15382      in  the function type of the function template results in an invalid
15383      type, type deduction fails.  [Note: The equivalent  substitution  in
15384      exception specifications is done only when the function is instanti-
15385      ated, at which point a program is  ill-formed  if  the  substitution
15386      results in an invalid type.]  */
15387 
15388 static tree
tsubst_function_type(tree t,tree args,tsubst_flags_t complain,tree in_decl)15389 tsubst_function_type (tree t,
15390 		      tree args,
15391 		      tsubst_flags_t complain,
15392 		      tree in_decl)
15393 {
15394   tree return_type;
15395   tree arg_types = NULL_TREE;
15396 
15397   /* The TYPE_CONTEXT is not used for function/method types.  */
15398   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
15399 
15400   /* DR 1227: Mixing immediate and non-immediate contexts in deduction
15401      failure.  */
15402   bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
15403 
15404   if (late_return_type_p)
15405     {
15406       /* Substitute the argument types.  */
15407       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15408 				    complain, in_decl);
15409       if (arg_types == error_mark_node)
15410 	return error_mark_node;
15411 
15412       tree save_ccp = current_class_ptr;
15413       tree save_ccr = current_class_ref;
15414       tree this_type = (TREE_CODE (t) == METHOD_TYPE
15415 			? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
15416       bool do_inject = this_type && CLASS_TYPE_P (this_type);
15417       if (do_inject)
15418 	{
15419 	  /* DR 1207: 'this' is in scope in the trailing return type.  */
15420 	  inject_this_parameter (this_type, cp_type_quals (this_type));
15421 	}
15422 
15423       /* Substitute the return type.  */
15424       return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15425 
15426       if (do_inject)
15427 	{
15428 	  current_class_ptr = save_ccp;
15429 	  current_class_ref = save_ccr;
15430 	}
15431     }
15432   else
15433     /* Substitute the return type.  */
15434     return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15435 
15436   if (return_type == error_mark_node)
15437     return error_mark_node;
15438   /* DR 486 clarifies that creation of a function type with an
15439      invalid return type is a deduction failure.  */
15440   if (TREE_CODE (return_type) == ARRAY_TYPE
15441       || TREE_CODE (return_type) == FUNCTION_TYPE)
15442     {
15443       if (complain & tf_error)
15444 	{
15445 	  if (TREE_CODE (return_type) == ARRAY_TYPE)
15446 	    error ("function returning an array");
15447 	  else
15448 	    error ("function returning a function");
15449 	}
15450       return error_mark_node;
15451     }
15452 
15453   if (!late_return_type_p)
15454     {
15455       /* Substitute the argument types.  */
15456       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15457 				    complain, in_decl);
15458       if (arg_types == error_mark_node)
15459 	return error_mark_node;
15460     }
15461 
15462   /* Construct a new type node and return it.  */
15463   return rebuild_function_or_method_type (t, return_type, arg_types,
15464 					  /*raises=*/NULL_TREE, complain);
15465 }
15466 
15467 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
15468    ARGS into that specification, and return the substituted
15469    specification.  If there is no specification, return NULL_TREE.  */
15470 
15471 static tree
tsubst_exception_specification(tree fntype,tree args,tsubst_flags_t complain,tree in_decl,bool defer_ok)15472 tsubst_exception_specification (tree fntype,
15473 				tree args,
15474 				tsubst_flags_t complain,
15475 				tree in_decl,
15476 				bool defer_ok)
15477 {
15478   tree specs;
15479   tree new_specs;
15480 
15481   specs = TYPE_RAISES_EXCEPTIONS (fntype);
15482   new_specs = NULL_TREE;
15483   if (specs && TREE_PURPOSE (specs))
15484     {
15485       /* A noexcept-specifier.  */
15486       tree expr = TREE_PURPOSE (specs);
15487       if (TREE_CODE (expr) == INTEGER_CST)
15488 	new_specs = expr;
15489       else if (defer_ok)
15490 	{
15491 	  /* Defer instantiation of noexcept-specifiers to avoid
15492 	     excessive instantiations (c++/49107).  */
15493 	  new_specs = make_node (DEFERRED_NOEXCEPT);
15494 	  if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15495 	    {
15496 	      /* We already partially instantiated this member template,
15497 		 so combine the new args with the old.  */
15498 	      DEFERRED_NOEXCEPT_PATTERN (new_specs)
15499 		= DEFERRED_NOEXCEPT_PATTERN (expr);
15500 	      DEFERRED_NOEXCEPT_ARGS (new_specs)
15501 		= add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
15502 	    }
15503 	  else
15504 	    {
15505 	      DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
15506 	      DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
15507 	    }
15508 	}
15509       else
15510 	{
15511 	  if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15512 	    {
15513 	      args = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr),
15514 					   args);
15515 	      expr = DEFERRED_NOEXCEPT_PATTERN (expr);
15516 	    }
15517 	  new_specs = tsubst_copy_and_build
15518 	    (expr, args, complain, in_decl, /*function_p=*/false,
15519 	     /*integral_constant_expression_p=*/true);
15520 	}
15521       new_specs = build_noexcept_spec (new_specs, complain);
15522       /* We've instantiated a template before a noexcept-specifier
15523 	 contained therein has been parsed.  This can happen for
15524 	 a nested template class:
15525 
15526 	  struct S {
15527 	    template<typename> struct B { B() noexcept(...); };
15528 	    struct A : B<int> { ... use B() ... };
15529 	  };
15530 
15531 	 where completing B<int> will trigger instantiating the
15532 	 noexcept, even though we only parse it at the end of S.  */
15533       if (UNPARSED_NOEXCEPT_SPEC_P (specs))
15534 	{
15535 	  gcc_checking_assert (defer_ok);
15536 	  vec_safe_push (DEFPARSE_INSTANTIATIONS (expr), new_specs);
15537 	}
15538     }
15539   else if (specs)
15540     {
15541       if (! TREE_VALUE (specs))
15542 	new_specs = specs;
15543       else
15544 	while (specs)
15545 	  {
15546 	    tree spec;
15547             int i, len = 1;
15548             tree expanded_specs = NULL_TREE;
15549 
15550             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
15551               {
15552                 /* Expand the pack expansion type.  */
15553                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
15554                                                        args, complain,
15555                                                        in_decl);
15556 
15557 		if (expanded_specs == error_mark_node)
15558 		  return error_mark_node;
15559 		else if (TREE_CODE (expanded_specs) == TREE_VEC)
15560 		  len = TREE_VEC_LENGTH (expanded_specs);
15561 		else
15562 		  {
15563 		    /* We're substituting into a member template, so
15564 		       we got a TYPE_PACK_EXPANSION back.  Add that
15565 		       expansion and move on.  */
15566 		    gcc_assert (TREE_CODE (expanded_specs)
15567 				== TYPE_PACK_EXPANSION);
15568 		    new_specs = add_exception_specifier (new_specs,
15569 							 expanded_specs,
15570 							 complain);
15571 		    specs = TREE_CHAIN (specs);
15572 		    continue;
15573 		  }
15574               }
15575 
15576             for (i = 0; i < len; ++i)
15577               {
15578                 if (expanded_specs)
15579                   spec = TREE_VEC_ELT (expanded_specs, i);
15580                 else
15581                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
15582                 if (spec == error_mark_node)
15583                   return spec;
15584                 new_specs = add_exception_specifier (new_specs, spec,
15585                                                      complain);
15586               }
15587 
15588             specs = TREE_CHAIN (specs);
15589 	  }
15590     }
15591   return new_specs;
15592 }
15593 
15594 /* Substitute through a TREE_LIST of types or expressions, handling pack
15595    expansions.  */
15596 
15597 tree
tsubst_tree_list(tree t,tree args,tsubst_flags_t complain,tree in_decl)15598 tsubst_tree_list (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15599 {
15600   if (t == void_list_node)
15601     return t;
15602 
15603   tree purpose = TREE_PURPOSE (t);
15604   tree purposevec = NULL_TREE;
15605   if (!purpose)
15606     ;
15607   else if (PACK_EXPANSION_P (purpose))
15608     {
15609       purpose = tsubst_pack_expansion (purpose, args, complain, in_decl);
15610       if (TREE_CODE (purpose) == TREE_VEC)
15611 	purposevec = purpose;
15612     }
15613   else if (TYPE_P (purpose))
15614     purpose = tsubst (purpose, args, complain, in_decl);
15615   else
15616     purpose = tsubst_copy_and_build (purpose, args, complain, in_decl);
15617   if (purpose == error_mark_node || purposevec == error_mark_node)
15618     return error_mark_node;
15619 
15620   tree value = TREE_VALUE (t);
15621   tree valuevec = NULL_TREE;
15622   if (!value)
15623     ;
15624   else if (PACK_EXPANSION_P (value))
15625     {
15626       value = tsubst_pack_expansion (value, args, complain, in_decl);
15627       if (TREE_CODE (value) == TREE_VEC)
15628 	valuevec = value;
15629     }
15630   else if (TYPE_P (value))
15631     value = tsubst (value, args, complain, in_decl);
15632   else
15633     value = tsubst_copy_and_build (value, args, complain, in_decl);
15634   if (value == error_mark_node || valuevec == error_mark_node)
15635     return error_mark_node;
15636 
15637   tree chain = TREE_CHAIN (t);
15638   if (!chain)
15639     ;
15640   else if (TREE_CODE (chain) == TREE_LIST)
15641     chain = tsubst_tree_list (chain, args, complain, in_decl);
15642   else if (TYPE_P (chain))
15643     chain = tsubst (chain, args, complain, in_decl);
15644   else
15645     chain = tsubst_copy_and_build (chain, args, complain, in_decl);
15646   if (chain == error_mark_node)
15647     return error_mark_node;
15648 
15649   if (purpose == TREE_PURPOSE (t)
15650       && value == TREE_VALUE (t)
15651       && chain == TREE_CHAIN (t))
15652     return t;
15653 
15654   int len;
15655   /* Determine the number of arguments.  */
15656   if (purposevec)
15657     {
15658       len = TREE_VEC_LENGTH (purposevec);
15659       gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
15660     }
15661   else if (valuevec)
15662     len = TREE_VEC_LENGTH (valuevec);
15663   else
15664     len = 1;
15665 
15666   for (int i = len; i-- > 0; )
15667     {
15668       if (purposevec)
15669 	purpose = TREE_VEC_ELT (purposevec, i);
15670       if (valuevec)
15671 	value = TREE_VEC_ELT (valuevec, i);
15672 
15673       if (value && TYPE_P (value))
15674 	chain = hash_tree_cons (purpose, value, chain);
15675       else
15676 	chain = tree_cons (purpose, value, chain);
15677     }
15678 
15679   return chain;
15680 }
15681 
15682 /* Take the tree structure T and replace template parameters used
15683    therein with the argument vector ARGS.  IN_DECL is an associated
15684    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
15685    Issue error and warning messages under control of COMPLAIN.  Note
15686    that we must be relatively non-tolerant of extensions here, in
15687    order to preserve conformance; if we allow substitutions that
15688    should not be allowed, we may allow argument deductions that should
15689    not succeed, and therefore report ambiguous overload situations
15690    where there are none.  In theory, we could allow the substitution,
15691    but indicate that it should have failed, and allow our caller to
15692    make sure that the right thing happens, but we don't try to do this
15693    yet.
15694 
15695    This function is used for dealing with types, decls and the like;
15696    for expressions, use tsubst_expr or tsubst_copy.  */
15697 
15698 tree
tsubst(tree t,tree args,tsubst_flags_t complain,tree in_decl)15699 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15700 {
15701   enum tree_code code;
15702   tree type, r = NULL_TREE;
15703 
15704   if (t == NULL_TREE || t == error_mark_node
15705       || t == integer_type_node
15706       || t == void_type_node
15707       || t == char_type_node
15708       || t == unknown_type_node
15709       || TREE_CODE (t) == NAMESPACE_DECL
15710       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
15711     return t;
15712 
15713   if (DECL_P (t))
15714     return tsubst_decl (t, args, complain);
15715 
15716   if (args == NULL_TREE)
15717     return t;
15718 
15719   code = TREE_CODE (t);
15720 
15721   gcc_assert (code != IDENTIFIER_NODE);
15722   type = TREE_TYPE (t);
15723 
15724   gcc_assert (type != unknown_type_node);
15725 
15726   /* Reuse typedefs.  We need to do this to handle dependent attributes,
15727      such as attribute aligned.  */
15728   if (TYPE_P (t)
15729       && typedef_variant_p (t))
15730     {
15731       tree decl = TYPE_NAME (t);
15732 
15733       if (alias_template_specialization_p (t, nt_opaque))
15734 	{
15735 	  /* DECL represents an alias template and we want to
15736 	     instantiate it.  */
15737 	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15738 	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15739 	  r = instantiate_alias_template (tmpl, gen_args, complain);
15740 	}
15741       else if (DECL_CLASS_SCOPE_P (decl)
15742 	       && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
15743 	       && uses_template_parms (DECL_CONTEXT (decl)))
15744 	{
15745 	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15746 	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15747 	  r = retrieve_specialization (tmpl, gen_args, 0);
15748 	}
15749       else if (DECL_FUNCTION_SCOPE_P (decl)
15750 	       && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
15751 	       && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
15752 	r = retrieve_local_specialization (decl);
15753       else
15754 	/* The typedef is from a non-template context.  */
15755 	return t;
15756 
15757       if (r)
15758 	{
15759 	  r = TREE_TYPE (r);
15760 	  r = cp_build_qualified_type_real
15761 	    (r, cp_type_quals (t) | cp_type_quals (r),
15762 	     complain | tf_ignore_bad_quals);
15763 	  return r;
15764 	}
15765       else
15766 	{
15767 	  /* We don't have an instantiation yet, so drop the typedef.  */
15768 	  int quals = cp_type_quals (t);
15769 	  t = DECL_ORIGINAL_TYPE (decl);
15770 	  t = cp_build_qualified_type_real (t, quals,
15771 					    complain | tf_ignore_bad_quals);
15772 	}
15773     }
15774 
15775   bool fndecl_type = (complain & tf_fndecl_type);
15776   complain &= ~tf_fndecl_type;
15777 
15778   bool tst_ok = (complain & tf_tst_ok);
15779   complain &= ~tf_tst_ok;
15780 
15781   if (type
15782       && code != TYPENAME_TYPE
15783       && code != TEMPLATE_TYPE_PARM
15784       && code != TEMPLATE_PARM_INDEX
15785       && code != IDENTIFIER_NODE
15786       && code != FUNCTION_TYPE
15787       && code != METHOD_TYPE)
15788     type = tsubst (type, args, complain, in_decl);
15789   if (type == error_mark_node)
15790     return error_mark_node;
15791 
15792   switch (code)
15793     {
15794     case RECORD_TYPE:
15795     case UNION_TYPE:
15796     case ENUMERAL_TYPE:
15797       return tsubst_aggr_type (t, args, complain, in_decl,
15798 			       /*entering_scope=*/0);
15799 
15800     case ERROR_MARK:
15801     case IDENTIFIER_NODE:
15802     case VOID_TYPE:
15803     case OPAQUE_TYPE:
15804     case REAL_TYPE:
15805     case COMPLEX_TYPE:
15806     case VECTOR_TYPE:
15807     case BOOLEAN_TYPE:
15808     case NULLPTR_TYPE:
15809     case LANG_TYPE:
15810       return t;
15811 
15812     case INTEGER_TYPE:
15813       if (t == integer_type_node)
15814 	return t;
15815 
15816       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
15817           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
15818         return t;
15819 
15820       {
15821 	tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
15822 
15823 	max = tsubst_expr (omax, args, complain, in_decl,
15824 			   /*integral_constant_expression_p=*/false);
15825 
15826 	/* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
15827 	   needed.  */
15828 	if (TREE_CODE (max) == NOP_EXPR
15829 	    && TREE_SIDE_EFFECTS (omax)
15830 	    && !TREE_TYPE (max))
15831 	  TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
15832 
15833 	/* If we're in a partial instantiation, preserve the magic NOP_EXPR
15834 	   with TREE_SIDE_EFFECTS that indicates this is not an integral
15835 	   constant expression.  */
15836 	if (processing_template_decl
15837 	    && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
15838 	  {
15839 	    gcc_assert (TREE_CODE (max) == NOP_EXPR);
15840 	    TREE_SIDE_EFFECTS (max) = 1;
15841 	  }
15842 
15843 	return compute_array_index_type (NULL_TREE, max, complain);
15844       }
15845 
15846     case TEMPLATE_TYPE_PARM:
15847       if (template_placeholder_p (t))
15848 	{
15849 	  tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (t);
15850 	  tmpl = tsubst_copy (tmpl, args, complain, in_decl);
15851 	  if (TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
15852 	    tmpl = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (tmpl);
15853 
15854 	  if (tmpl != CLASS_PLACEHOLDER_TEMPLATE (t))
15855 	    return make_template_placeholder (tmpl);
15856 	  else
15857 	    return t;
15858 	}
15859       /* Fall through.  */
15860     case TEMPLATE_TEMPLATE_PARM:
15861     case BOUND_TEMPLATE_TEMPLATE_PARM:
15862     case TEMPLATE_PARM_INDEX:
15863       {
15864 	int idx;
15865 	int level;
15866 	int levels;
15867 	tree arg = NULL_TREE;
15868 
15869 	r = NULL_TREE;
15870 
15871 	gcc_assert (TREE_VEC_LENGTH (args) > 0);
15872 	template_parm_level_and_index (t, &level, &idx);
15873 
15874 	levels = TMPL_ARGS_DEPTH (args);
15875 	if (level <= levels
15876 	    && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
15877 	  {
15878 	    arg = TMPL_ARG (args, level, idx);
15879 
15880 	    /* See through ARGUMENT_PACK_SELECT arguments. */
15881 	    if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
15882 	      arg = argument_pack_select_arg (arg);
15883 	  }
15884 
15885 	if (arg == error_mark_node)
15886 	  return error_mark_node;
15887 	else if (arg != NULL_TREE)
15888 	  {
15889 	    if (ARGUMENT_PACK_P (arg))
15890 	      /* If ARG is an argument pack, we don't actually want to
15891 		 perform a substitution here, because substitutions
15892 		 for argument packs are only done
15893 		 element-by-element. We can get to this point when
15894 		 substituting the type of a non-type template
15895 		 parameter pack, when that type actually contains
15896 		 template parameter packs from an outer template, e.g.,
15897 
15898 	         template<typename... Types> struct A {
15899 		   template<Types... Values> struct B { };
15900                  };  */
15901 	      return t;
15902 
15903 	    if (code == TEMPLATE_TYPE_PARM)
15904 	      {
15905 		int quals;
15906 
15907 		/* When building concept checks for the purpose of
15908 		   deducing placeholders, we can end up with wildcards
15909 		   where types are expected. Adjust this to the deduced
15910 		   value.  */
15911 		if (TREE_CODE (arg) == WILDCARD_DECL)
15912 		  arg = TREE_TYPE (TREE_TYPE (arg));
15913 
15914 		gcc_assert (TYPE_P (arg));
15915 
15916 		quals = cp_type_quals (arg) | cp_type_quals (t);
15917 
15918 		return cp_build_qualified_type_real
15919 		  (arg, quals, complain | tf_ignore_bad_quals);
15920 	      }
15921 	    else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
15922 	      {
15923 		/* We are processing a type constructed from a
15924 		   template template parameter.  */
15925 		tree argvec = tsubst (TYPE_TI_ARGS (t),
15926 				      args, complain, in_decl);
15927 		if (argvec == error_mark_node)
15928 		  return error_mark_node;
15929 
15930 		gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
15931 			    || TREE_CODE (arg) == TEMPLATE_DECL
15932 			    || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
15933 
15934 		if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
15935 		  /* Consider this code:
15936 
15937 			template <template <class> class Template>
15938 			struct Internal {
15939 			template <class Arg> using Bind = Template<Arg>;
15940 			};
15941 
15942 			template <template <class> class Template, class Arg>
15943 			using Instantiate = Template<Arg>; //#0
15944 
15945 			template <template <class> class Template,
15946                                   class Argument>
15947 			using Bind =
15948 			  Instantiate<Internal<Template>::template Bind,
15949 				      Argument>; //#1
15950 
15951 		     When #1 is parsed, the
15952 		     BOUND_TEMPLATE_TEMPLATE_PARM representing the
15953 		     parameter `Template' in #0 matches the
15954 		     UNBOUND_CLASS_TEMPLATE representing the argument
15955 		     `Internal<Template>::template Bind'; We then want
15956 		     to assemble the type `Bind<Argument>' that can't
15957 		     be fully created right now, because
15958 		     `Internal<Template>' not being complete, the Bind
15959 		     template cannot be looked up in that context.  So
15960 		     we need to "store" `Bind<Argument>' for later
15961 		     when the context of Bind becomes complete.  Let's
15962 		     store that in a TYPENAME_TYPE.  */
15963 		  return make_typename_type (TYPE_CONTEXT (arg),
15964 					     build_nt (TEMPLATE_ID_EXPR,
15965 						       TYPE_IDENTIFIER (arg),
15966 						       argvec),
15967 					     typename_type,
15968 					     complain);
15969 
15970 		/* We can get a TEMPLATE_TEMPLATE_PARM here when we
15971 		   are resolving nested-types in the signature of a
15972 		   member function templates.  Otherwise ARG is a
15973 		   TEMPLATE_DECL and is the real template to be
15974 		   instantiated.  */
15975 		if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
15976 		  arg = TYPE_NAME (arg);
15977 
15978 		r = lookup_template_class (arg,
15979 					   argvec, in_decl,
15980 					   DECL_CONTEXT (arg),
15981 					    /*entering_scope=*/0,
15982 					   complain);
15983 		return cp_build_qualified_type_real
15984 		  (r, cp_type_quals (t) | cp_type_quals (r), complain);
15985 	      }
15986 	    else if (code == TEMPLATE_TEMPLATE_PARM)
15987 	      return arg;
15988 	    else
15989 	      /* TEMPLATE_PARM_INDEX.  */
15990 	      return convert_from_reference (unshare_expr (arg));
15991 	  }
15992 
15993 	if (level == 1)
15994 	  /* This can happen during the attempted tsubst'ing in
15995 	     unify.  This means that we don't yet have any information
15996 	     about the template parameter in question.  */
15997 	  return t;
15998 
15999 	/* Early in template argument deduction substitution, we don't
16000 	   want to reduce the level of 'auto', or it will be confused
16001 	   with a normal template parm in subsequent deduction.
16002 	   Similarly, don't reduce the level of template parameters to
16003 	   avoid mismatches when deducing their types.  */
16004 	if (complain & tf_partial)
16005 	  return t;
16006 
16007 	/* If we get here, we must have been looking at a parm for a
16008 	   more deeply nested template.  Make a new version of this
16009 	   template parameter, but with a lower level.  */
16010 	switch (code)
16011 	  {
16012 	  case TEMPLATE_TYPE_PARM:
16013 	  case TEMPLATE_TEMPLATE_PARM:
16014 	  case BOUND_TEMPLATE_TEMPLATE_PARM:
16015 	    if (cp_type_quals (t))
16016 	      {
16017 		r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
16018 		r = cp_build_qualified_type_real
16019 		  (r, cp_type_quals (t),
16020 		   complain | (code == TEMPLATE_TYPE_PARM
16021 			       ? tf_ignore_bad_quals : 0));
16022 	      }
16023 	    else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
16024 		     && PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t)
16025 		     && (r = (TEMPLATE_PARM_DESCENDANTS
16026 			      (TEMPLATE_TYPE_PARM_INDEX (t))))
16027 		     && (r = TREE_TYPE (r))
16028 		     && !PLACEHOLDER_TYPE_CONSTRAINTS_INFO (r))
16029 	      /* Break infinite recursion when substituting the constraints
16030 		 of a constrained placeholder.  */;
16031 	    else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
16032 		     && !PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t)
16033 		     && (arg = TEMPLATE_TYPE_PARM_INDEX (t),
16034 			 r = TEMPLATE_PARM_DESCENDANTS (arg))
16035 		     && (TEMPLATE_PARM_LEVEL (r)
16036 			 == TEMPLATE_PARM_LEVEL (arg) - levels))
16037 		/* Cache the simple case of lowering a type parameter.  */
16038 	      r = TREE_TYPE (r);
16039 	    else
16040 	      {
16041 		r = copy_type (t);
16042 		TEMPLATE_TYPE_PARM_INDEX (r)
16043 		  = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
16044 						r, levels, args, complain);
16045 		TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
16046 		TYPE_MAIN_VARIANT (r) = r;
16047 		TYPE_POINTER_TO (r) = NULL_TREE;
16048 		TYPE_REFERENCE_TO (r) = NULL_TREE;
16049 
16050                 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
16051 		  if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t))
16052 		    /* Propagate constraints on placeholders since they are
16053 		       only instantiated during satisfaction.  */
16054 		    PLACEHOLDER_TYPE_CONSTRAINTS_INFO (r) = ci;
16055 
16056 		if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
16057 		  /* We have reduced the level of the template
16058 		     template parameter, but not the levels of its
16059 		     template parameters, so canonical_type_parameter
16060 		     will not be able to find the canonical template
16061 		     template parameter for this level. Thus, we
16062 		     require structural equality checking to compare
16063 		     TEMPLATE_TEMPLATE_PARMs. */
16064 		  SET_TYPE_STRUCTURAL_EQUALITY (r);
16065 		else if (TYPE_STRUCTURAL_EQUALITY_P (t))
16066 		  SET_TYPE_STRUCTURAL_EQUALITY (r);
16067 		else
16068 		  TYPE_CANONICAL (r) = canonical_type_parameter (r);
16069 
16070 		if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
16071 		  {
16072 		    tree tinfo = TYPE_TEMPLATE_INFO (t);
16073 		    /* We might need to substitute into the types of non-type
16074 		       template parameters.  */
16075 		    tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
16076 					complain, in_decl);
16077 		    if (tmpl == error_mark_node)
16078 		      return error_mark_node;
16079 		    tree argvec = tsubst (TI_ARGS (tinfo), args,
16080 					  complain, in_decl);
16081 		    if (argvec == error_mark_node)
16082 		      return error_mark_node;
16083 
16084 		    TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
16085 		      = build_template_info (tmpl, argvec);
16086 		  }
16087 	      }
16088 	    break;
16089 
16090 	  case TEMPLATE_PARM_INDEX:
16091 	    /* OK, now substitute the type of the non-type parameter.  We
16092 	       couldn't do it earlier because it might be an auto parameter,
16093 	       and we wouldn't need to if we had an argument.  */
16094 	    type = tsubst (type, args, complain, in_decl);
16095 	    if (type == error_mark_node)
16096 	      return error_mark_node;
16097 	    r = reduce_template_parm_level (t, type, levels, args, complain);
16098 	    break;
16099 
16100 	  default:
16101 	    gcc_unreachable ();
16102 	  }
16103 
16104 	return r;
16105       }
16106 
16107     case TREE_LIST:
16108       return tsubst_tree_list (t, args, complain, in_decl);
16109 
16110     case TREE_BINFO:
16111       /* We should never be tsubsting a binfo.  */
16112       gcc_unreachable ();
16113 
16114     case TREE_VEC:
16115       /* A vector of template arguments.  */
16116       gcc_assert (!type);
16117       return tsubst_template_args (t, args, complain, in_decl);
16118 
16119     case POINTER_TYPE:
16120     case REFERENCE_TYPE:
16121       {
16122 	if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
16123 	  return t;
16124 
16125 	/* [temp.deduct]
16126 
16127 	   Type deduction may fail for any of the following
16128 	   reasons:
16129 
16130 	   -- Attempting to create a pointer to reference type.
16131 	   -- Attempting to create a reference to a reference type or
16132 	      a reference to void.
16133 
16134 	  Core issue 106 says that creating a reference to a reference
16135 	  during instantiation is no longer a cause for failure. We
16136 	  only enforce this check in strict C++98 mode.  */
16137 	if ((TYPE_REF_P (type)
16138 	     && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
16139 	    || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
16140 	  {
16141 	    static location_t last_loc;
16142 
16143 	    /* We keep track of the last time we issued this error
16144 	       message to avoid spewing a ton of messages during a
16145 	       single bad template instantiation.  */
16146 	    if (complain & tf_error
16147 		&& last_loc != input_location)
16148 	      {
16149 		if (VOID_TYPE_P (type))
16150 		  error ("forming reference to void");
16151                else if (code == POINTER_TYPE)
16152                  error ("forming pointer to reference type %qT", type);
16153                else
16154 		  error ("forming reference to reference type %qT", type);
16155 		last_loc = input_location;
16156 	      }
16157 
16158 	    return error_mark_node;
16159 	  }
16160 	else if (TREE_CODE (type) == FUNCTION_TYPE
16161 		 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
16162 		     || type_memfn_rqual (type) != REF_QUAL_NONE))
16163 	  {
16164 	    if (complain & tf_error)
16165 	      {
16166 		if (code == POINTER_TYPE)
16167 		  error ("forming pointer to qualified function type %qT",
16168 			 type);
16169 		else
16170 		  error ("forming reference to qualified function type %qT",
16171 			 type);
16172 	      }
16173 	    return error_mark_node;
16174 	  }
16175 	else if (code == POINTER_TYPE)
16176 	  {
16177 	    r = build_pointer_type (type);
16178 	    if (TREE_CODE (type) == METHOD_TYPE)
16179 	      r = build_ptrmemfunc_type (r);
16180 	  }
16181 	else if (TYPE_REF_P (type))
16182 	  /* In C++0x, during template argument substitution, when there is an
16183 	     attempt to create a reference to a reference type, reference
16184 	     collapsing is applied as described in [14.3.1/4 temp.arg.type]:
16185 
16186 	     "If a template-argument for a template-parameter T names a type
16187 	     that is a reference to a type A, an attempt to create the type
16188 	     'lvalue reference to cv T' creates the type 'lvalue reference to
16189 	     A,' while an attempt to create the type type rvalue reference to
16190 	     cv T' creates the type T"
16191 	  */
16192 	  r = cp_build_reference_type
16193 	      (TREE_TYPE (type),
16194 	       TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
16195 	else
16196 	  r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
16197 	r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
16198 
16199 	if (r != error_mark_node)
16200 	  /* Will this ever be needed for TYPE_..._TO values?  */
16201 	  layout_type (r);
16202 
16203 	return r;
16204       }
16205     case OFFSET_TYPE:
16206       {
16207 	r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
16208 	if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
16209 	  {
16210 	    /* [temp.deduct]
16211 
16212 	       Type deduction may fail for any of the following
16213 	       reasons:
16214 
16215 	       -- Attempting to create "pointer to member of T" when T
16216 		  is not a class type.  */
16217 	    if (complain & tf_error)
16218 	      error ("creating pointer to member of non-class type %qT", r);
16219 	    return error_mark_node;
16220 	  }
16221 	if (TYPE_REF_P (type))
16222 	  {
16223 	    if (complain & tf_error)
16224 	      error ("creating pointer to member reference type %qT", type);
16225 	    return error_mark_node;
16226 	  }
16227 	if (VOID_TYPE_P (type))
16228 	  {
16229 	    if (complain & tf_error)
16230 	      error ("creating pointer to member of type void");
16231 	    return error_mark_node;
16232 	  }
16233 	gcc_assert (TREE_CODE (type) != METHOD_TYPE);
16234 	if (TREE_CODE (type) == FUNCTION_TYPE)
16235 	  {
16236 	    /* The type of the implicit object parameter gets its
16237 	       cv-qualifiers from the FUNCTION_TYPE. */
16238 	    tree memptr;
16239 	    tree method_type
16240 	      = build_memfn_type (type, r, type_memfn_quals (type),
16241 				  type_memfn_rqual (type));
16242 	    memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
16243 	    return cp_build_qualified_type_real (memptr, cp_type_quals (t),
16244 						 complain);
16245 	  }
16246 	else
16247 	  return cp_build_qualified_type_real (build_ptrmem_type (r, type),
16248 					       cp_type_quals (t),
16249 					       complain);
16250       }
16251     case FUNCTION_TYPE:
16252     case METHOD_TYPE:
16253       {
16254 	tree fntype;
16255 	tree specs;
16256 	fntype = tsubst_function_type (t, args, complain, in_decl);
16257 	if (fntype == error_mark_node)
16258 	  return error_mark_node;
16259 
16260 	/* Substitute the exception specification.  */
16261 	specs = tsubst_exception_specification (t, args, complain, in_decl,
16262 						/*defer_ok*/fndecl_type);
16263 	if (specs == error_mark_node)
16264 	  return error_mark_node;
16265 	if (specs)
16266 	  fntype = build_exception_variant (fntype, specs);
16267 	return fntype;
16268       }
16269     case ARRAY_TYPE:
16270       {
16271 	tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
16272 	if (domain == error_mark_node)
16273 	  return error_mark_node;
16274 
16275 	/* As an optimization, we avoid regenerating the array type if
16276 	   it will obviously be the same as T.  */
16277 	if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
16278 	  return t;
16279 
16280 	/* These checks should match the ones in create_array_type_for_decl.
16281 
16282 	   [temp.deduct]
16283 
16284 	   The deduction may fail for any of the following reasons:
16285 
16286 	   -- Attempting to create an array with an element type that
16287 	      is void, a function type, or a reference type, or [DR337]
16288 	      an abstract class type.  */
16289 	if (VOID_TYPE_P (type)
16290 	    || TREE_CODE (type) == FUNCTION_TYPE
16291 	    || (TREE_CODE (type) == ARRAY_TYPE
16292 		&& TYPE_DOMAIN (type) == NULL_TREE)
16293 	    || TYPE_REF_P (type))
16294 	  {
16295 	    if (complain & tf_error)
16296 	      error ("creating array of %qT", type);
16297 	    return error_mark_node;
16298 	  }
16299 
16300 	if (!verify_type_context (input_location, TCTX_ARRAY_ELEMENT, type,
16301 				  !(complain & tf_error)))
16302 	  return error_mark_node;
16303 
16304 	r = build_cplus_array_type (type, domain);
16305 
16306 	if (!valid_array_size_p (input_location, r, in_decl,
16307 				 (complain & tf_error)))
16308 	  return error_mark_node;
16309 
16310 	if (TYPE_USER_ALIGN (t))
16311 	  {
16312 	    SET_TYPE_ALIGN (r, TYPE_ALIGN (t));
16313 	    TYPE_USER_ALIGN (r) = 1;
16314 	  }
16315 
16316 	return r;
16317       }
16318 
16319     case TYPENAME_TYPE:
16320       {
16321 	tree ctx = TYPE_CONTEXT (t);
16322 	if (TREE_CODE (ctx) == TYPE_PACK_EXPANSION)
16323 	  {
16324 	    ctx = tsubst_pack_expansion (ctx, args, complain, in_decl);
16325 	    if (ctx == error_mark_node
16326 		|| TREE_VEC_LENGTH (ctx) > 1)
16327 	      return error_mark_node;
16328 	    if (TREE_VEC_LENGTH (ctx) == 0)
16329 	      {
16330 		if (complain & tf_error)
16331 		  error ("%qD is instantiated for an empty pack",
16332 			 TYPENAME_TYPE_FULLNAME (t));
16333 		return error_mark_node;
16334 	      }
16335 	    ctx = TREE_VEC_ELT (ctx, 0);
16336 	  }
16337 	else
16338 	  ctx = tsubst_aggr_type (ctx, args, complain, in_decl,
16339 				  /*entering_scope=*/1);
16340 	if (ctx == error_mark_node)
16341 	  return error_mark_node;
16342 
16343 	tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
16344 			      complain, in_decl);
16345 	if (f == error_mark_node)
16346 	  return error_mark_node;
16347 
16348 	if (!MAYBE_CLASS_TYPE_P (ctx))
16349 	  {
16350 	    if (complain & tf_error)
16351 	      error ("%qT is not a class, struct, or union type", ctx);
16352 	    return error_mark_node;
16353 	  }
16354 	else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
16355 	  {
16356 	    /* Normally, make_typename_type does not require that the CTX
16357 	       have complete type in order to allow things like:
16358 
16359 		 template <class T> struct S { typename S<T>::X Y; };
16360 
16361 	       But, such constructs have already been resolved by this
16362 	       point, so here CTX really should have complete type, unless
16363 	       it's a partial instantiation.  */
16364 	    if (!complete_type_or_maybe_complain (ctx, NULL_TREE, complain))
16365 	      return error_mark_node;
16366 	  }
16367 
16368 	tsubst_flags_t tcomplain = complain | tf_keep_type_decl;
16369 	if (tst_ok)
16370 	  tcomplain |= tf_tst_ok;
16371 	f = make_typename_type (ctx, f, typename_type, tcomplain);
16372 	if (f == error_mark_node)
16373 	  return f;
16374 	if (TREE_CODE (f) == TYPE_DECL)
16375 	  {
16376 	    complain |= tf_ignore_bad_quals;
16377 	    f = TREE_TYPE (f);
16378 	  }
16379 
16380 	if (TREE_CODE (f) != TYPENAME_TYPE)
16381 	  {
16382 	    if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
16383 	      {
16384 		if (complain & tf_error)
16385 		  error ("%qT resolves to %qT, which is not an enumeration type",
16386 			 t, f);
16387 		else
16388 		  return error_mark_node;
16389 	      }
16390 	    else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
16391 	      {
16392 		if (complain & tf_error)
16393 		  error ("%qT resolves to %qT, which is not a class type",
16394 			 t, f);
16395 		else
16396 		  return error_mark_node;
16397 	      }
16398 	  }
16399 
16400 	return cp_build_qualified_type_real
16401 	  (f, cp_type_quals (f) | cp_type_quals (t), complain);
16402       }
16403 
16404     case UNBOUND_CLASS_TEMPLATE:
16405       {
16406 	tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
16407 				     in_decl, /*entering_scope=*/1);
16408 	tree name = TYPE_IDENTIFIER (t);
16409 	tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
16410 
16411 	if (ctx == error_mark_node || name == error_mark_node)
16412 	  return error_mark_node;
16413 
16414 	if (parm_list)
16415 	  parm_list = tsubst_template_parms (parm_list, args, complain);
16416 	return make_unbound_class_template (ctx, name, parm_list, complain);
16417       }
16418 
16419     case TYPEOF_TYPE:
16420       {
16421 	tree type;
16422 
16423 	++cp_unevaluated_operand;
16424 	++c_inhibit_evaluation_warnings;
16425 
16426 	type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
16427 			    complain, in_decl,
16428 			    /*integral_constant_expression_p=*/false);
16429 
16430 	--cp_unevaluated_operand;
16431 	--c_inhibit_evaluation_warnings;
16432 
16433 	type = finish_typeof (type);
16434 	return cp_build_qualified_type_real (type,
16435 					     cp_type_quals (t)
16436 					     | cp_type_quals (type),
16437 					     complain);
16438       }
16439 
16440     case DECLTYPE_TYPE:
16441       {
16442 	tree type;
16443 
16444 	++cp_unevaluated_operand;
16445 	++c_inhibit_evaluation_warnings;
16446 
16447 	type = tsubst_copy_and_build (DECLTYPE_TYPE_EXPR (t), args,
16448 				      complain|tf_decltype, in_decl,
16449 				      /*function_p*/false,
16450 				      /*integral_constant_expression*/false);
16451 
16452 	--cp_unevaluated_operand;
16453 	--c_inhibit_evaluation_warnings;
16454 
16455 	if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
16456 	  type = lambda_capture_field_type (type,
16457 					    false /*explicit_init*/,
16458 					    DECLTYPE_FOR_REF_CAPTURE (t));
16459 	else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
16460 	  type = lambda_proxy_type (type);
16461 	else
16462 	  {
16463 	    bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
16464 	    if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
16465 		&& EXPR_P (type))
16466 	      /* In a template ~id could be either a complement expression
16467 		 or an unqualified-id naming a destructor; if instantiating
16468 		 it produces an expression, it's not an id-expression or
16469 		 member access.  */
16470 	      id = false;
16471 	    type = finish_decltype_type (type, id, complain);
16472 	  }
16473 	return cp_build_qualified_type_real (type,
16474 					     cp_type_quals (t)
16475 					     | cp_type_quals (type),
16476 					     complain | tf_ignore_bad_quals);
16477       }
16478 
16479     case UNDERLYING_TYPE:
16480       {
16481 	tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
16482 			    complain, in_decl);
16483 	return finish_underlying_type (type);
16484       }
16485 
16486     case TYPE_ARGUMENT_PACK:
16487     case NONTYPE_ARGUMENT_PACK:
16488       return tsubst_argument_pack (t, args, complain, in_decl);
16489 
16490     case VOID_CST:
16491     case INTEGER_CST:
16492     case REAL_CST:
16493     case STRING_CST:
16494     case PLUS_EXPR:
16495     case MINUS_EXPR:
16496     case NEGATE_EXPR:
16497     case NOP_EXPR:
16498     case INDIRECT_REF:
16499     case ADDR_EXPR:
16500     case CALL_EXPR:
16501     case ARRAY_REF:
16502     case SCOPE_REF:
16503       /* We should use one of the expression tsubsts for these codes.  */
16504       gcc_unreachable ();
16505 
16506     default:
16507       sorry ("use of %qs in template", get_tree_code_name (code));
16508       return error_mark_node;
16509     }
16510 }
16511 
16512 /* OLDFNS is a lookup set of member functions from some class template, and
16513    NEWFNS is a lookup set of member functions from NEWTYPE, a specialization
16514    of that class template.  Return the subset of NEWFNS which are
16515    specializations of a function from OLDFNS.  */
16516 
16517 static tree
filter_memfn_lookup(tree oldfns,tree newfns,tree newtype)16518 filter_memfn_lookup (tree oldfns, tree newfns, tree newtype)
16519 {
16520   /* Record all member functions from the old lookup set OLDFNS into
16521      VISIBLE_SET.  */
16522   hash_set<tree> visible_set;
16523   bool seen_dep_using = false;
16524   for (tree fn : lkp_range (oldfns))
16525     {
16526       if (TREE_CODE (fn) == USING_DECL)
16527 	{
16528 	  /* Imprecisely handle dependent using-decl by keeping all members
16529 	     in the new lookup set that are defined in a base class, i.e.
16530 	     members that could plausibly have been introduced by this
16531 	     dependent using-decl.
16532 	     FIXME: Track which members are introduced by a dependent
16533 	     using-decl precisely, perhaps by performing another lookup
16534 	     from the substituted USING_DECL_SCOPE.  */
16535 	  gcc_checking_assert (DECL_DEPENDENT_P (fn));
16536 	  seen_dep_using = true;
16537 	}
16538       else
16539 	visible_set.add (fn);
16540     }
16541 
16542   /* Returns true iff (a less specialized version of) FN appeared in
16543      the old lookup set OLDFNS.  */
16544   auto visible_p = [newtype, seen_dep_using, &visible_set] (tree fn) {
16545     if (DECL_CONTEXT (fn) != newtype)
16546       /* FN is a member function from a base class, introduced via a
16547 	 using-decl; if it might have been introduced by a dependent
16548 	 using-decl then just conservatively keep it, otherwise look
16549 	 in the old lookup set for FN exactly.  */
16550       return seen_dep_using || visible_set.contains (fn);
16551     else if (TREE_CODE (fn) == TEMPLATE_DECL)
16552       /* FN is a member function template from the current class;
16553 	 look in the old lookup set for the TEMPLATE_DECL from which
16554 	 it was specialized.  */
16555       return visible_set.contains (DECL_TI_TEMPLATE (fn));
16556     else
16557       /* FN is a non-template member function from the current class;
16558 	 look in the old lookup set for the FUNCTION_DECL from which
16559 	 it was specialized.  */
16560       return visible_set.contains (DECL_TEMPLATE_RESULT
16561 				   (DECL_TI_TEMPLATE (fn)));
16562   };
16563 
16564   bool lookup_changed_p = false;
16565   for (tree fn : lkp_range (newfns))
16566     if (!visible_p (fn))
16567       {
16568 	lookup_changed_p = true;
16569 	break;
16570       }
16571   if (!lookup_changed_p)
16572     return newfns;
16573 
16574   /* Filter out from NEWFNS the member functions that weren't
16575      previously visible according to OLDFNS.  */
16576   tree filtered_fns = NULL_TREE;
16577   unsigned filtered_size = 0;
16578   for (tree fn : lkp_range (newfns))
16579     if (visible_p (fn))
16580       {
16581 	filtered_fns = lookup_add (fn, filtered_fns);
16582 	filtered_size++;
16583       }
16584   gcc_checking_assert (seen_dep_using
16585 		       ? filtered_size >= visible_set.elements ()
16586 		       : filtered_size == visible_set.elements ());
16587 
16588   return filtered_fns;
16589 }
16590 
16591 /* tsubst a BASELINK.  OBJECT_TYPE, if non-NULL, is the type of the
16592    expression on the left-hand side of the "." or "->" operator.  We
16593    only do the lookup if we had a dependent BASELINK.  Otherwise we
16594    adjust it onto the instantiated heirarchy.  */
16595 
16596 static tree
tsubst_baselink(tree baselink,tree object_type,tree args,tsubst_flags_t complain,tree in_decl)16597 tsubst_baselink (tree baselink, tree object_type,
16598 		 tree args, tsubst_flags_t complain, tree in_decl)
16599 {
16600   bool qualified_p = BASELINK_QUALIFIED_P (baselink);
16601   tree qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
16602   qualifying_scope = tsubst (qualifying_scope, args, complain, in_decl);
16603 
16604   tree optype = BASELINK_OPTYPE (baselink);
16605   optype = tsubst (optype, args, complain, in_decl);
16606 
16607   tree template_args = NULL_TREE;
16608   bool template_id_p = false;
16609   tree fns = BASELINK_FUNCTIONS (baselink);
16610   if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
16611     {
16612       template_id_p = true;
16613       template_args = TREE_OPERAND (fns, 1);
16614       fns = TREE_OPERAND (fns, 0);
16615       if (template_args)
16616 	template_args = tsubst_template_args (template_args, args,
16617 					      complain, in_decl);
16618     }
16619 
16620   tree binfo_type = BINFO_TYPE (BASELINK_BINFO (baselink));
16621   binfo_type = tsubst (binfo_type, args, complain, in_decl);
16622   bool dependent_p = (binfo_type != BINFO_TYPE (BASELINK_BINFO (baselink))
16623 		      || optype != BASELINK_OPTYPE (baselink));
16624 
16625   if (dependent_p)
16626     {
16627       tree name = OVL_NAME (fns);
16628       if (IDENTIFIER_CONV_OP_P (name))
16629 	name = make_conv_op_name (optype);
16630 
16631       /* See maybe_dependent_member_ref.  */
16632       if ((complain & tf_dguide) && dependent_scope_p (qualifying_scope))
16633 	{
16634 	  if (template_id_p)
16635 	    name = build2 (TEMPLATE_ID_EXPR, unknown_type_node, name,
16636 			   template_args);
16637 	  return build_qualified_name (NULL_TREE, qualifying_scope, name,
16638 				       /* ::template */false);
16639 	}
16640 
16641       if (name == complete_dtor_identifier)
16642 	/* Treat as-if non-dependent below.  */
16643 	dependent_p = false;
16644 
16645       bool maybe_incomplete = BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (baselink);
16646       baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1,
16647 				  complain);
16648       if (maybe_incomplete)
16649 	{
16650 	  /* Filter out from the new lookup set those functions which didn't
16651 	     appear in the original lookup set (in a less specialized form).
16652 	     This is needed to preserve the consistency of member lookup
16653 	     performed in an incomplete-class context, within which
16654 	     later-declared members ought to remain invisible.  */
16655 	  BASELINK_FUNCTIONS (baselink)
16656 	    = filter_memfn_lookup (fns, BASELINK_FUNCTIONS (baselink),
16657 				   binfo_type);
16658 	  BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (baselink) = true;
16659 	}
16660 
16661       if (!baselink)
16662 	{
16663 	  if ((complain & tf_error)
16664 	      && constructor_name_p (name, qualifying_scope))
16665 	    error ("cannot call constructor %<%T::%D%> directly",
16666 		   qualifying_scope, name);
16667 	  return error_mark_node;
16668 	}
16669 
16670       fns = BASELINK_FUNCTIONS (baselink);
16671     }
16672   else
16673     {
16674       /* We're going to overwrite pieces below, make a duplicate.  */
16675       baselink = copy_node (baselink);
16676 
16677       if (qualifying_scope != BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink)))
16678 	{
16679 	  /* The decl we found was from non-dependent scope, but we still need
16680 	     to update the binfos for the instantiated qualifying_scope.  */
16681 	  BASELINK_ACCESS_BINFO (baselink) = TYPE_BINFO (qualifying_scope);
16682 	  BASELINK_BINFO (baselink) = lookup_base (qualifying_scope, binfo_type,
16683 						   ba_unique, nullptr, complain);
16684 	}
16685     }
16686 
16687   /* If lookup found a single function, mark it as used at this point.
16688      (If lookup found multiple functions the one selected later by
16689      overload resolution will be marked as used at that point.)  */
16690   if (!template_id_p && !really_overloaded_fn (fns))
16691     {
16692       tree fn = OVL_FIRST (fns);
16693       bool ok = mark_used (fn, complain);
16694       if (!ok && !(complain & tf_error))
16695 	return error_mark_node;
16696       if (ok && BASELINK_P (baselink))
16697 	/* We might have instantiated an auto function.  */
16698 	TREE_TYPE (baselink) = TREE_TYPE (fn);
16699     }
16700 
16701   if (BASELINK_P (baselink))
16702     {
16703       /* Add back the template arguments, if present.  */
16704       if (template_id_p)
16705 	BASELINK_FUNCTIONS (baselink)
16706 	  = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, template_args);
16707 
16708       /* Update the conversion operator type.  */
16709       BASELINK_OPTYPE (baselink) = optype;
16710     }
16711 
16712   if (!object_type)
16713     object_type = current_class_type;
16714 
16715   if (qualified_p || !dependent_p)
16716     {
16717       baselink = adjust_result_of_qualified_name_lookup (baselink,
16718 							 qualifying_scope,
16719 							 object_type);
16720       if (!qualified_p)
16721 	/* We need to call adjust_result_of_qualified_name_lookup in case the
16722 	   destructor names a base class, but we unset BASELINK_QUALIFIED_P
16723 	   so that we still get virtual function binding.  */
16724 	BASELINK_QUALIFIED_P (baselink) = false;
16725     }
16726 
16727   return baselink;
16728 }
16729 
16730 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
16731    true if the qualified-id will be a postfix-expression in-and-of
16732    itself; false if more of the postfix-expression follows the
16733    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
16734    of "&".  */
16735 
16736 static tree
tsubst_qualified_id(tree qualified_id,tree args,tsubst_flags_t complain,tree in_decl,bool done,bool address_p)16737 tsubst_qualified_id (tree qualified_id, tree args,
16738 		     tsubst_flags_t complain, tree in_decl,
16739 		     bool done, bool address_p)
16740 {
16741   tree expr;
16742   tree scope;
16743   tree name;
16744   bool is_template;
16745   tree template_args;
16746   location_t loc = EXPR_LOCATION (qualified_id);
16747 
16748   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
16749 
16750   /* Figure out what name to look up.  */
16751   name = TREE_OPERAND (qualified_id, 1);
16752   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
16753     {
16754       is_template = true;
16755       template_args = TREE_OPERAND (name, 1);
16756       if (template_args)
16757 	template_args = tsubst_template_args (template_args, args,
16758 					      complain, in_decl);
16759       if (template_args == error_mark_node)
16760 	return error_mark_node;
16761       name = TREE_OPERAND (name, 0);
16762     }
16763   else
16764     {
16765       is_template = false;
16766       template_args = NULL_TREE;
16767     }
16768 
16769   /* Substitute into the qualifying scope.  When there are no ARGS, we
16770      are just trying to simplify a non-dependent expression.  In that
16771      case the qualifying scope may be dependent, and, in any case,
16772      substituting will not help.  */
16773   scope = TREE_OPERAND (qualified_id, 0);
16774   if (args)
16775     {
16776       scope = tsubst (scope, args, complain, in_decl);
16777       expr = tsubst_copy (name, args, complain, in_decl);
16778     }
16779   else
16780     expr = name;
16781 
16782   if (dependent_scope_p (scope))
16783     {
16784       if (TREE_CODE (expr) == SCOPE_REF)
16785 	/* We built one in tsubst_baselink.  */
16786 	gcc_checking_assert (same_type_p (scope, TREE_OPERAND (expr, 0)));
16787       else
16788 	{
16789 	  if (is_template)
16790 	    expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr,
16791 				     template_args);
16792 	  expr = build_qualified_name (NULL_TREE, scope, expr,
16793 				       QUALIFIED_NAME_IS_TEMPLATE
16794 				       (qualified_id));
16795 	}
16796       REF_PARENTHESIZED_P (expr) = REF_PARENTHESIZED_P (qualified_id);
16797       return expr;
16798     }
16799 
16800   if (!BASELINK_P (name) && !DECL_P (expr))
16801     {
16802       if (TREE_CODE (expr) == BIT_NOT_EXPR)
16803 	{
16804 	  /* A BIT_NOT_EXPR is used to represent a destructor.  */
16805 	  if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
16806 	    {
16807 	      error ("qualifying type %qT does not match destructor name ~%qT",
16808 		     scope, TREE_OPERAND (expr, 0));
16809 	      expr = error_mark_node;
16810 	    }
16811 	  else
16812 	    expr = lookup_qualified_name (scope, complete_dtor_identifier,
16813 					  LOOK_want::NORMAL, false);
16814 	}
16815       else
16816 	expr = lookup_qualified_name (scope, expr, LOOK_want::NORMAL, false);
16817       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
16818 		     ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
16819 	{
16820 	  if (complain & tf_error)
16821 	    {
16822 	      error ("dependent-name %qE is parsed as a non-type, but "
16823 		     "instantiation yields a type", qualified_id);
16824 	      inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
16825 	    }
16826 	  return error_mark_node;
16827 	}
16828     }
16829 
16830   if (DECL_P (expr))
16831     {
16832       if (!check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
16833 						scope, complain))
16834 	return error_mark_node;
16835       /* Remember that there was a reference to this entity.  */
16836       if (!mark_used (expr, complain) && !(complain & tf_error))
16837 	return error_mark_node;
16838     }
16839 
16840   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
16841     {
16842       if (complain & tf_error)
16843 	qualified_name_lookup_error (scope,
16844 				     TREE_OPERAND (qualified_id, 1),
16845 				     expr, input_location);
16846       return error_mark_node;
16847     }
16848 
16849   if (is_template)
16850     {
16851       /* We may be repeating a check already done during parsing, but
16852 	 if it was well-formed and passed then, it will pass again
16853 	 now, and if it didn't, we wouldn't have got here.  The case
16854 	 we want to catch is when we couldn't tell then, and can now,
16855 	 namely when templ prior to substitution was an
16856 	 identifier.  */
16857       if (flag_concepts && check_auto_in_tmpl_args (expr, template_args))
16858 	return error_mark_node;
16859 
16860       if (variable_template_p (expr))
16861 	expr = lookup_and_finish_template_variable (expr, template_args,
16862 						    complain);
16863       else
16864 	expr = lookup_template_function (expr, template_args);
16865     }
16866 
16867   if (expr == error_mark_node && complain & tf_error)
16868     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
16869 				 expr, input_location);
16870   else if (TYPE_P (scope))
16871     {
16872       expr = (adjust_result_of_qualified_name_lookup
16873 	      (expr, scope, current_nonlambda_class_type ()));
16874       expr = (finish_qualified_id_expr
16875 	      (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
16876 	       QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
16877 	       /*template_arg_p=*/false, complain));
16878     }
16879 
16880   /* Expressions do not generally have reference type.  */
16881   if (TREE_CODE (expr) != SCOPE_REF
16882       /* However, if we're about to form a pointer-to-member, we just
16883 	 want the referenced member referenced.  */
16884       && TREE_CODE (expr) != OFFSET_REF)
16885     expr = convert_from_reference (expr);
16886 
16887   if (REF_PARENTHESIZED_P (qualified_id))
16888     expr = force_paren_expr (expr);
16889 
16890   expr = maybe_wrap_with_location (expr, loc);
16891 
16892   return expr;
16893 }
16894 
16895 /* tsubst the initializer for a VAR_DECL.  INIT is the unsubstituted
16896    initializer, DECL is the substituted VAR_DECL.  Other arguments are as
16897    for tsubst.  */
16898 
16899 static tree
tsubst_init(tree init,tree decl,tree args,tsubst_flags_t complain,tree in_decl)16900 tsubst_init (tree init, tree decl, tree args,
16901 	     tsubst_flags_t complain, tree in_decl)
16902 {
16903   if (!init)
16904     return NULL_TREE;
16905 
16906   init = tsubst_expr (init, args, complain, in_decl, false);
16907 
16908   tree type = TREE_TYPE (decl);
16909 
16910   if (!init && type != error_mark_node)
16911     {
16912       if (tree auto_node = type_uses_auto (type))
16913 	{
16914 	  if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
16915 	    {
16916 	      if (complain & tf_error)
16917 		error ("initializer for %q#D expands to an empty list "
16918 		       "of expressions", decl);
16919 	      return error_mark_node;
16920 	    }
16921 	}
16922       else if (!dependent_type_p (type))
16923 	{
16924 	  /* If we had an initializer but it
16925 	     instantiated to nothing,
16926 	     value-initialize the object.  This will
16927 	     only occur when the initializer was a
16928 	     pack expansion where the parameter packs
16929 	     used in that expansion were of length
16930 	     zero.  */
16931 	  init = build_value_init (type, complain);
16932 	  if (TREE_CODE (init) == AGGR_INIT_EXPR)
16933 	    init = get_target_expr_sfinae (init, complain);
16934 	  if (TREE_CODE (init) == TARGET_EXPR)
16935 	    TARGET_EXPR_DIRECT_INIT_P (init) = true;
16936 	}
16937     }
16938 
16939   return init;
16940 }
16941 
16942 /* If T is a reference to a dependent member of the current instantiation C and
16943    we are trying to refer to that member in a partial instantiation of C,
16944    return a SCOPE_REF; otherwise, return NULL_TREE.
16945 
16946    This can happen when forming a C++17 deduction guide, as in PR96199.  */
16947 
16948 static tree
maybe_dependent_member_ref(tree t,tree args,tsubst_flags_t complain,tree in_decl)16949 maybe_dependent_member_ref (tree t, tree args, tsubst_flags_t complain,
16950 			    tree in_decl)
16951 {
16952   if (!(complain & tf_dguide))
16953     return NULL_TREE;
16954 
16955   tree ctx = context_for_name_lookup (t);
16956   if (!CLASS_TYPE_P (ctx))
16957     return NULL_TREE;
16958 
16959   ctx = tsubst (ctx, args, complain, in_decl);
16960   if (dependent_scope_p (ctx))
16961     return build_qualified_name (NULL_TREE, ctx, DECL_NAME (t),
16962 				 /*template_p=*/false);
16963 
16964   return NULL_TREE;
16965 }
16966 
16967 /* Like tsubst, but deals with expressions.  This function just replaces
16968    template parms; to finish processing the resultant expression, use
16969    tsubst_copy_and_build or tsubst_expr.  */
16970 
16971 static tree
tsubst_copy(tree t,tree args,tsubst_flags_t complain,tree in_decl)16972 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
16973 {
16974   enum tree_code code;
16975   tree r;
16976 
16977   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
16978     return t;
16979 
16980   code = TREE_CODE (t);
16981 
16982   switch (code)
16983     {
16984     case PARM_DECL:
16985       r = retrieve_local_specialization (t);
16986 
16987       if (r == NULL_TREE)
16988 	{
16989 	  /* We get here for a use of 'this' in an NSDMI.  */
16990 	  if (DECL_NAME (t) == this_identifier && current_class_ptr)
16991 	    return current_class_ptr;
16992 
16993 	  /* This can happen for a parameter name used later in a function
16994 	     declaration (such as in a late-specified return type).  Just
16995 	     make a dummy decl, since it's only used for its type.  */
16996 	  gcc_assert (cp_unevaluated_operand != 0);
16997 	  r = tsubst_decl (t, args, complain);
16998 	  /* Give it the template pattern as its context; its true context
16999 	     hasn't been instantiated yet and this is good enough for
17000 	     mangling.  */
17001 	  DECL_CONTEXT (r) = DECL_CONTEXT (t);
17002 	}
17003 
17004       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
17005 	r = argument_pack_select_arg (r);
17006       if (!mark_used (r, complain) && !(complain & tf_error))
17007 	return error_mark_node;
17008       return r;
17009 
17010     case CONST_DECL:
17011       {
17012 	tree enum_type;
17013 	tree v;
17014 
17015 	if (DECL_TEMPLATE_PARM_P (t))
17016 	  return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
17017 	if (!uses_template_parms (DECL_CONTEXT (t)))
17018 	  return t;
17019 
17020 	if (tree ref = maybe_dependent_member_ref (t, args, complain, in_decl))
17021 	  return ref;
17022 
17023 	/* Unfortunately, we cannot just call lookup_name here.
17024 	   Consider:
17025 
17026 	     template <int I> int f() {
17027 	     enum E { a = I };
17028 	     struct S { void g() { E e = a; } };
17029 	     };
17030 
17031 	   When we instantiate f<7>::S::g(), say, lookup_name is not
17032 	   clever enough to find f<7>::a.  */
17033 	enum_type
17034 	  = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
17035 			      /*entering_scope=*/0);
17036 
17037 	for (v = TYPE_VALUES (enum_type);
17038 	     v != NULL_TREE;
17039 	     v = TREE_CHAIN (v))
17040 	  if (TREE_PURPOSE (v) == DECL_NAME (t))
17041 	    return TREE_VALUE (v);
17042 
17043 	  /* We didn't find the name.  That should never happen; if
17044 	     name-lookup found it during preliminary parsing, we
17045 	     should find it again here during instantiation.  */
17046 	gcc_unreachable ();
17047       }
17048       return t;
17049 
17050     case FIELD_DECL:
17051       if (DECL_CONTEXT (t))
17052 	{
17053 	  tree ctx;
17054 
17055 	  ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
17056 				  /*entering_scope=*/1);
17057 	  if (ctx != DECL_CONTEXT (t))
17058 	    {
17059 	      tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
17060 	      if (!r)
17061 		{
17062 		  if (complain & tf_error)
17063 		    error ("using invalid field %qD", t);
17064 		  return error_mark_node;
17065 		}
17066 	      return r;
17067 	    }
17068 	}
17069 
17070       return t;
17071 
17072     case VAR_DECL:
17073       if (tree ref = maybe_dependent_member_ref (t, args, complain, in_decl))
17074 	return ref;
17075       gcc_fallthrough();
17076     case FUNCTION_DECL:
17077       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
17078 	r = tsubst (t, args, complain, in_decl);
17079       else if (DECL_LOCAL_DECL_P (t))
17080 	{
17081 	  /* Local specialization will usually have been created when
17082 	     we instantiated the DECL_EXPR_DECL. */
17083 	  r = retrieve_local_specialization (t);
17084 	  if (!r)
17085 	    {
17086 	      /* We're in a generic lambda referencing a local extern
17087 		 from an outer block-scope of a non-template.  */
17088 	      gcc_checking_assert (LAMBDA_FUNCTION_P (current_function_decl));
17089 	      r = t;
17090 	    }
17091 	}
17092       else if (local_variable_p (t)
17093 	       && uses_template_parms (DECL_CONTEXT (t)))
17094 	{
17095 	  r = retrieve_local_specialization (t);
17096 	  if (r == NULL_TREE)
17097 	    {
17098 	      /* First try name lookup to find the instantiation.  */
17099 	      r = lookup_name (DECL_NAME (t));
17100 	      if (r)
17101 		{
17102 		  if (!VAR_P (r))
17103 		    {
17104 		      /* During error-recovery we may find a non-variable,
17105 			 even an OVERLOAD: just bail out and avoid ICEs and
17106 			 duplicate diagnostics (c++/62207).  */
17107 		      gcc_assert (seen_error ());
17108 		      return error_mark_node;
17109 		    }
17110 		  if (!is_capture_proxy (r))
17111 		    {
17112 		      /* Make sure the one we found is the one we want.  */
17113 		      tree ctx = enclosing_instantiation_of (DECL_CONTEXT (t));
17114 		      if (ctx != DECL_CONTEXT (r))
17115 			r = NULL_TREE;
17116 		    }
17117 		}
17118 
17119 	      if (r)
17120 		/* OK */;
17121 	      else
17122 		{
17123 		  /* This can happen for a variable used in a
17124 		     late-specified return type of a local lambda, or for a
17125 		     local static or constant.  Building a new VAR_DECL
17126 		     should be OK in all those cases.  */
17127 		  r = tsubst_decl (t, args, complain);
17128 		  if (local_specializations)
17129 		    /* Avoid infinite recursion (79640).  */
17130 		    register_local_specialization (r, t);
17131 		  if (decl_maybe_constant_var_p (r))
17132 		    {
17133 		      /* We can't call cp_finish_decl, so handle the
17134 			 initializer by hand.  */
17135 		      tree init = tsubst_init (DECL_INITIAL (t), r, args,
17136 					       complain, in_decl);
17137 		      if (!processing_template_decl)
17138 			init = maybe_constant_init (init);
17139 		      if (processing_template_decl
17140 			  ? potential_constant_expression (init)
17141 			  : reduced_constant_expression_p (init))
17142 			DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
17143 			  = TREE_CONSTANT (r) = true;
17144 		      DECL_INITIAL (r) = init;
17145 		      if (tree auto_node = type_uses_auto (TREE_TYPE (r)))
17146 			TREE_TYPE (r)
17147 			  = do_auto_deduction (TREE_TYPE (r), init, auto_node,
17148 					       complain, adc_variable_type);
17149 		    }
17150 		  gcc_assert (cp_unevaluated_operand || TREE_STATIC (r)
17151 			      || decl_constant_var_p (r)
17152 			      || seen_error ());
17153 		  if (!processing_template_decl
17154 		      && !TREE_STATIC (r))
17155 		    r = process_outer_var_ref (r, complain);
17156 		}
17157 	      /* Remember this for subsequent uses.  */
17158 	      if (local_specializations)
17159 		register_local_specialization (r, t);
17160 	    }
17161 	  if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
17162 	    r = argument_pack_select_arg (r);
17163 	}
17164       else
17165 	r = t;
17166       if (!mark_used (r, complain))
17167 	return error_mark_node;
17168       return r;
17169 
17170     case NAMESPACE_DECL:
17171       return t;
17172 
17173     case OVERLOAD:
17174       return t;
17175 
17176     case BASELINK:
17177       return tsubst_baselink (t, current_nonlambda_class_type (),
17178 			      args, complain, in_decl);
17179 
17180     case TEMPLATE_DECL:
17181       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
17182 	return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
17183 		       args, complain, in_decl);
17184       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
17185 	return tsubst (t, args, complain, in_decl);
17186       else if (DECL_CLASS_SCOPE_P (t)
17187 	       && uses_template_parms (DECL_CONTEXT (t)))
17188 	{
17189 	  /* Template template argument like the following example need
17190 	     special treatment:
17191 
17192 	       template <template <class> class TT> struct C {};
17193 	       template <class T> struct D {
17194 		 template <class U> struct E {};
17195 		 C<E> c;				// #1
17196 	       };
17197 	       D<int> d;				// #2
17198 
17199 	     We are processing the template argument `E' in #1 for
17200 	     the template instantiation #2.  Originally, `E' is a
17201 	     TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
17202 	     have to substitute this with one having context `D<int>'.  */
17203 
17204 	  tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
17205 	  if ((complain & tf_dguide) && dependent_scope_p (context))
17206 	    {
17207 	      /* When rewriting a constructor into a deduction guide, a
17208 		 non-dependent name can become dependent, so memtmpl<args>
17209 		 becomes context::template memtmpl<args>.  */
17210 	      if (DECL_TYPE_TEMPLATE_P (t))
17211 		return make_unbound_class_template (context, DECL_NAME (t),
17212 						    NULL_TREE, complain);
17213 	      tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17214 	      return build_qualified_name (type, context, DECL_NAME (t),
17215 					   /*template*/true);
17216 	    }
17217 	  return lookup_field (context, DECL_NAME(t), 0, false);
17218 	}
17219       else
17220 	/* Ordinary template template argument.  */
17221 	return t;
17222 
17223     case NON_LVALUE_EXPR:
17224     case VIEW_CONVERT_EXPR:
17225 	{
17226 	  /* Handle location wrappers by substituting the wrapped node
17227 	     first, *then* reusing the resulting type.  Doing the type
17228 	     first ensures that we handle template parameters and
17229 	     parameter pack expansions.  */
17230 	  if (location_wrapper_p (t))
17231 	    {
17232 	      tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args,
17233 				      complain, in_decl);
17234 	      return maybe_wrap_with_location (op0, EXPR_LOCATION (t));
17235 	    }
17236 	  tree op = TREE_OPERAND (t, 0);
17237 	  if (code == VIEW_CONVERT_EXPR
17238 	      && TREE_CODE (op) == TEMPLATE_PARM_INDEX)
17239 	    {
17240 	      /* Wrapper to make a C++20 template parameter object const.  */
17241 	      op = tsubst_copy (op, args, complain, in_decl);
17242 	      if (!CP_TYPE_CONST_P (TREE_TYPE (op)))
17243 		{
17244 		  /* The template argument is not const, presumably because
17245 		     it is still dependent, and so not the const template parm
17246 		     object.  */
17247 		  tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17248 		  gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
17249 				       (type, TREE_TYPE (op)));
17250 		  if (TREE_CODE (op) == CONSTRUCTOR
17251 		      || TREE_CODE (op) == IMPLICIT_CONV_EXPR)
17252 		    {
17253 		      /* Don't add a wrapper to these.  */
17254 		      op = copy_node (op);
17255 		      TREE_TYPE (op) = type;
17256 		    }
17257 		  else
17258 		    /* Do add a wrapper otherwise (in particular, if op is
17259 		       another TEMPLATE_PARM_INDEX).  */
17260 		    op = build1 (code, type, op);
17261 		}
17262 	      return op;
17263 	    }
17264 	  /* force_paren_expr can also create a VIEW_CONVERT_EXPR.  */
17265 	  else if (code == VIEW_CONVERT_EXPR && REF_PARENTHESIZED_P (t))
17266 	    {
17267 	      op = tsubst_copy (op, args, complain, in_decl);
17268 	      op = build1 (code, TREE_TYPE (op), op);
17269 	      REF_PARENTHESIZED_P (op) = true;
17270 	      return op;
17271 	    }
17272 	  /* We shouldn't see any other uses of these in templates.  */
17273 	  gcc_unreachable ();
17274 	}
17275 
17276     case CAST_EXPR:
17277     case REINTERPRET_CAST_EXPR:
17278     case CONST_CAST_EXPR:
17279     case STATIC_CAST_EXPR:
17280     case DYNAMIC_CAST_EXPR:
17281     case IMPLICIT_CONV_EXPR:
17282     case CONVERT_EXPR:
17283     case NOP_EXPR:
17284       {
17285 	tsubst_flags_t tcomplain = complain;
17286 	if (code == CAST_EXPR)
17287 	  tcomplain |= tf_tst_ok;
17288 	tree type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
17289 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17290 	return build1 (code, type, op0);
17291       }
17292 
17293     case BIT_CAST_EXPR:
17294       {
17295 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17296 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17297 	r = build_min (BIT_CAST_EXPR, type, op0);
17298 	SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
17299 	return r;
17300       }
17301 
17302     case SIZEOF_EXPR:
17303       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
17304 	  || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
17305         {
17306           tree expanded, op = TREE_OPERAND (t, 0);
17307 	  int len = 0;
17308 
17309 	  if (SIZEOF_EXPR_TYPE_P (t))
17310 	    op = TREE_TYPE (op);
17311 
17312 	  ++cp_unevaluated_operand;
17313 	  ++c_inhibit_evaluation_warnings;
17314 	  /* We only want to compute the number of arguments.  */
17315 	  if (PACK_EXPANSION_P (op))
17316 	    expanded = tsubst_pack_expansion (op, args, complain, in_decl);
17317 	  else
17318 	    expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
17319 					     args, complain, in_decl);
17320 	  --cp_unevaluated_operand;
17321 	  --c_inhibit_evaluation_warnings;
17322 
17323 	  if (TREE_CODE (expanded) == TREE_VEC)
17324 	    {
17325 	      len = TREE_VEC_LENGTH (expanded);
17326 	      /* Set TREE_USED for the benefit of -Wunused.  */
17327 	      for (int i = 0; i < len; i++)
17328 		if (DECL_P (TREE_VEC_ELT (expanded, i)))
17329 		  TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
17330 	    }
17331 
17332 	  if (expanded == error_mark_node)
17333 	    return error_mark_node;
17334 	  else if (PACK_EXPANSION_P (expanded)
17335 		   || (TREE_CODE (expanded) == TREE_VEC
17336 		       && pack_expansion_args_count (expanded)))
17337 
17338 	    {
17339 	      if (PACK_EXPANSION_P (expanded))
17340 		/* OK.  */;
17341 	      else if (TREE_VEC_LENGTH (expanded) == 1)
17342 		expanded = TREE_VEC_ELT (expanded, 0);
17343 	      else
17344 		expanded = make_argument_pack (expanded);
17345 
17346 	      if (TYPE_P (expanded))
17347 		return cxx_sizeof_or_alignof_type (input_location,
17348 						   expanded, SIZEOF_EXPR,
17349 						   false,
17350 						   complain & tf_error);
17351 	      else
17352 		return cxx_sizeof_or_alignof_expr (input_location,
17353 						   expanded, SIZEOF_EXPR,
17354 						   false,
17355                                                    complain & tf_error);
17356 	    }
17357 	  else
17358 	    return build_int_cst (size_type_node, len);
17359         }
17360       if (SIZEOF_EXPR_TYPE_P (t))
17361 	{
17362 	  r = tsubst (TREE_TYPE (TREE_OPERAND (t, 0)),
17363 		      args, complain, in_decl);
17364 	  r = build1 (NOP_EXPR, r, error_mark_node);
17365 	  r = build1 (SIZEOF_EXPR,
17366 		      tsubst (TREE_TYPE (t), args, complain, in_decl), r);
17367 	  SIZEOF_EXPR_TYPE_P (r) = 1;
17368 	  return r;
17369 	}
17370       /* Fall through */
17371 
17372     case INDIRECT_REF:
17373     case NEGATE_EXPR:
17374     case TRUTH_NOT_EXPR:
17375     case BIT_NOT_EXPR:
17376     case ADDR_EXPR:
17377     case UNARY_PLUS_EXPR:      /* Unary + */
17378     case ALIGNOF_EXPR:
17379     case AT_ENCODE_EXPR:
17380     case ARROW_EXPR:
17381     case THROW_EXPR:
17382     case TYPEID_EXPR:
17383     case REALPART_EXPR:
17384     case IMAGPART_EXPR:
17385     case PAREN_EXPR:
17386       {
17387 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17388 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17389 	r = build1_loc (EXPR_LOCATION (t), code, type, op0);
17390 	if (code == ALIGNOF_EXPR)
17391 	  ALIGNOF_EXPR_STD_P (r) = ALIGNOF_EXPR_STD_P (t);
17392 	/* For addresses of immediate functions ensure we have EXPR_LOCATION
17393 	   set for possible later diagnostics.  */
17394 	if (code == ADDR_EXPR
17395 	    && EXPR_LOCATION (r) == UNKNOWN_LOCATION
17396 	    && TREE_CODE (op0) == FUNCTION_DECL
17397 	    && DECL_IMMEDIATE_FUNCTION_P (op0))
17398 	  SET_EXPR_LOCATION (r, input_location);
17399 	return r;
17400       }
17401 
17402     case COMPONENT_REF:
17403       {
17404 	tree object;
17405 	tree name;
17406 
17407 	object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17408 	name = TREE_OPERAND (t, 1);
17409 	if (TREE_CODE (name) == BIT_NOT_EXPR)
17410 	  {
17411 	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
17412 				complain, in_decl);
17413 	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
17414 	  }
17415 	else if (TREE_CODE (name) == SCOPE_REF
17416 		 && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
17417 	  {
17418 	    tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
17419 				     complain, in_decl);
17420 	    name = TREE_OPERAND (name, 1);
17421 	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
17422 				complain, in_decl);
17423 	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
17424 	    name = build_qualified_name (/*type=*/NULL_TREE,
17425 					 base, name,
17426 					 /*template_p=*/false);
17427 	  }
17428 	else if (BASELINK_P (name))
17429 	  name = tsubst_baselink (name,
17430 				  non_reference (TREE_TYPE (object)),
17431 				  args, complain,
17432 				  in_decl);
17433 	else
17434 	  name = tsubst_copy (name, args, complain, in_decl);
17435 	return build_nt (COMPONENT_REF, object, name, NULL_TREE);
17436       }
17437 
17438     case PLUS_EXPR:
17439     case MINUS_EXPR:
17440     case MULT_EXPR:
17441     case TRUNC_DIV_EXPR:
17442     case CEIL_DIV_EXPR:
17443     case FLOOR_DIV_EXPR:
17444     case ROUND_DIV_EXPR:
17445     case EXACT_DIV_EXPR:
17446     case BIT_AND_EXPR:
17447     case BIT_IOR_EXPR:
17448     case BIT_XOR_EXPR:
17449     case TRUNC_MOD_EXPR:
17450     case FLOOR_MOD_EXPR:
17451     case TRUTH_ANDIF_EXPR:
17452     case TRUTH_ORIF_EXPR:
17453     case TRUTH_AND_EXPR:
17454     case TRUTH_OR_EXPR:
17455     case RSHIFT_EXPR:
17456     case LSHIFT_EXPR:
17457     case EQ_EXPR:
17458     case NE_EXPR:
17459     case MAX_EXPR:
17460     case MIN_EXPR:
17461     case LE_EXPR:
17462     case GE_EXPR:
17463     case LT_EXPR:
17464     case GT_EXPR:
17465     case COMPOUND_EXPR:
17466     case DOTSTAR_EXPR:
17467     case MEMBER_REF:
17468     case PREDECREMENT_EXPR:
17469     case PREINCREMENT_EXPR:
17470     case POSTDECREMENT_EXPR:
17471     case POSTINCREMENT_EXPR:
17472       {
17473 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17474 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17475 	return build_nt (code, op0, op1);
17476       }
17477 
17478     case SCOPE_REF:
17479       {
17480 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17481 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17482 	return build_qualified_name (/*type=*/NULL_TREE, op0, op1,
17483 				     QUALIFIED_NAME_IS_TEMPLATE (t));
17484       }
17485 
17486     case ARRAY_REF:
17487       {
17488 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17489 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17490 	return build_nt (ARRAY_REF, op0, op1, NULL_TREE, NULL_TREE);
17491       }
17492 
17493     case CALL_EXPR:
17494       {
17495 	int n = VL_EXP_OPERAND_LENGTH (t);
17496 	tree result = build_vl_exp (CALL_EXPR, n);
17497 	int i;
17498 	for (i = 0; i < n; i++)
17499 	  TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
17500 					     complain, in_decl);
17501 	return result;
17502       }
17503 
17504     case COND_EXPR:
17505     case MODOP_EXPR:
17506     case PSEUDO_DTOR_EXPR:
17507     case VEC_PERM_EXPR:
17508       {
17509 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17510 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17511 	tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
17512 	r = build_nt (code, op0, op1, op2);
17513 	copy_warning (r, t);
17514 	return r;
17515       }
17516 
17517     case NEW_EXPR:
17518       {
17519 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17520 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17521 	tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
17522 	r = build_nt (code, op0, op1, op2);
17523 	NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
17524 	return r;
17525       }
17526 
17527     case DELETE_EXPR:
17528       {
17529 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17530 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17531 	r = build_nt (code, op0, op1);
17532 	DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
17533 	DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
17534 	return r;
17535       }
17536 
17537     case TEMPLATE_ID_EXPR:
17538       {
17539 	/* Substituted template arguments */
17540 	tree tmpl = TREE_OPERAND (t, 0);
17541 	tree targs = TREE_OPERAND (t, 1);
17542 
17543 	tmpl = tsubst_copy (tmpl, args, complain, in_decl);
17544 	if (targs)
17545 	  targs = tsubst_template_args (targs, args, complain, in_decl);
17546 
17547 	if (variable_template_p (tmpl))
17548 	  return lookup_template_variable (tmpl, targs);
17549 	else
17550 	  return lookup_template_function (tmpl, targs);
17551       }
17552 
17553     case TREE_LIST:
17554       {
17555 	tree purpose, value, chain;
17556 
17557 	if (t == void_list_node)
17558 	  return t;
17559 
17560 	purpose = TREE_PURPOSE (t);
17561 	if (purpose)
17562 	  purpose = tsubst_copy (purpose, args, complain, in_decl);
17563 	value = TREE_VALUE (t);
17564 	if (value)
17565 	  value = tsubst_copy (value, args, complain, in_decl);
17566 	chain = TREE_CHAIN (t);
17567 	if (chain && chain != void_type_node)
17568 	  chain = tsubst_copy (chain, args, complain, in_decl);
17569 	if (purpose == TREE_PURPOSE (t)
17570 	    && value == TREE_VALUE (t)
17571 	    && chain == TREE_CHAIN (t))
17572 	  return t;
17573 	return tree_cons (purpose, value, chain);
17574       }
17575 
17576     case RECORD_TYPE:
17577     case UNION_TYPE:
17578     case ENUMERAL_TYPE:
17579     case INTEGER_TYPE:
17580     case TEMPLATE_TYPE_PARM:
17581     case TEMPLATE_TEMPLATE_PARM:
17582     case BOUND_TEMPLATE_TEMPLATE_PARM:
17583     case TEMPLATE_PARM_INDEX:
17584     case POINTER_TYPE:
17585     case REFERENCE_TYPE:
17586     case OFFSET_TYPE:
17587     case FUNCTION_TYPE:
17588     case METHOD_TYPE:
17589     case ARRAY_TYPE:
17590     case TYPENAME_TYPE:
17591     case UNBOUND_CLASS_TEMPLATE:
17592     case TYPEOF_TYPE:
17593     case DECLTYPE_TYPE:
17594     case TYPE_DECL:
17595       return tsubst (t, args, complain, in_decl);
17596 
17597     case USING_DECL:
17598       t = DECL_NAME (t);
17599       /* Fall through.  */
17600     case IDENTIFIER_NODE:
17601       if (IDENTIFIER_CONV_OP_P (t))
17602 	{
17603 	  tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17604 	  return make_conv_op_name (new_type);
17605 	}
17606       else
17607 	return t;
17608 
17609     case CONSTRUCTOR:
17610       /* This is handled by tsubst_copy_and_build.  */
17611       gcc_unreachable ();
17612 
17613     case VA_ARG_EXPR:
17614       {
17615 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17616 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17617 	return build_x_va_arg (EXPR_LOCATION (t), op0, type);
17618       }
17619 
17620     case CLEANUP_POINT_EXPR:
17621       /* We shouldn't have built any of these during initial template
17622 	 generation.  Instead, they should be built during instantiation
17623 	 in response to the saved STMT_IS_FULL_EXPR_P setting.  */
17624       gcc_unreachable ();
17625 
17626     case OFFSET_REF:
17627       {
17628 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17629 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17630 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17631 	r = build2 (code, type, op0, op1);
17632 	PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
17633 	if (!mark_used (TREE_OPERAND (r, 1), complain)
17634 	    && !(complain & tf_error))
17635 	  return error_mark_node;
17636 	return r;
17637       }
17638 
17639     case EXPR_PACK_EXPANSION:
17640       error ("invalid use of pack expansion expression");
17641       return error_mark_node;
17642 
17643     case NONTYPE_ARGUMENT_PACK:
17644       error ("use %<...%> to expand argument pack");
17645       return error_mark_node;
17646 
17647     case VOID_CST:
17648       gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
17649       return t;
17650 
17651     case INTEGER_CST:
17652     case REAL_CST:
17653     case COMPLEX_CST:
17654     case VECTOR_CST:
17655       {
17656 	/* Instantiate any typedefs in the type.  */
17657 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17658 	r = fold_convert (type, t);
17659 	gcc_assert (TREE_CODE (r) == code);
17660 	return r;
17661       }
17662 
17663     case STRING_CST:
17664       {
17665 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17666 	r = t;
17667 	if (type != TREE_TYPE (t))
17668 	  {
17669 	    r = copy_node (t);
17670 	    TREE_TYPE (r) = type;
17671 	  }
17672 	return r;
17673       }
17674 
17675     case PTRMEM_CST:
17676       /* These can sometimes show up in a partial instantiation, but never
17677 	 involve template parms.  */
17678       gcc_assert (!uses_template_parms (t));
17679       return t;
17680 
17681     case UNARY_LEFT_FOLD_EXPR:
17682       return tsubst_unary_left_fold (t, args, complain, in_decl);
17683     case UNARY_RIGHT_FOLD_EXPR:
17684       return tsubst_unary_right_fold (t, args, complain, in_decl);
17685     case BINARY_LEFT_FOLD_EXPR:
17686       return tsubst_binary_left_fold (t, args, complain, in_decl);
17687     case BINARY_RIGHT_FOLD_EXPR:
17688       return tsubst_binary_right_fold (t, args, complain, in_decl);
17689     case PREDICT_EXPR:
17690       return t;
17691 
17692     case DEBUG_BEGIN_STMT:
17693       /* ??? There's no point in copying it for now, but maybe some
17694 	 day it will contain more information, such as a pointer back
17695 	 to the containing function, inlined copy or so.  */
17696       return t;
17697 
17698     case CO_AWAIT_EXPR:
17699       return tsubst_expr (t, args, complain, in_decl,
17700 			  /*integral_constant_expression_p=*/false);
17701       break;
17702 
17703     default:
17704       /* We shouldn't get here, but keep going if !flag_checking.  */
17705       if (flag_checking)
17706 	gcc_unreachable ();
17707       return t;
17708     }
17709 }
17710 
17711 /* Helper function for tsubst_omp_clauses, used for instantiation of
17712    OMP_CLAUSE_DECL of clauses.  */
17713 
17714 static tree
tsubst_omp_clause_decl(tree decl,tree args,tsubst_flags_t complain,tree in_decl,tree * iterator_cache)17715 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
17716 			tree in_decl, tree *iterator_cache)
17717 {
17718   if (decl == NULL_TREE)
17719     return NULL_TREE;
17720 
17721   /* Handle OpenMP iterators.  */
17722   if (TREE_CODE (decl) == TREE_LIST
17723       && TREE_PURPOSE (decl)
17724       && TREE_CODE (TREE_PURPOSE (decl)) == TREE_VEC)
17725     {
17726       tree ret;
17727       if (iterator_cache[0] == TREE_PURPOSE (decl))
17728 	ret = iterator_cache[1];
17729       else
17730 	{
17731 	  tree *tp = &ret;
17732 	  begin_scope (sk_omp, NULL);
17733 	  for (tree it = TREE_PURPOSE (decl); it; it = TREE_CHAIN (it))
17734 	    {
17735 	      *tp = copy_node (it);
17736 	      TREE_VEC_ELT (*tp, 0)
17737 		= tsubst_decl (TREE_VEC_ELT (it, 0), args, complain);
17738 	      DECL_CONTEXT (TREE_VEC_ELT (*tp, 0)) = current_function_decl;
17739 	      pushdecl (TREE_VEC_ELT (*tp, 0));
17740 	      TREE_VEC_ELT (*tp, 1)
17741 		= tsubst_expr (TREE_VEC_ELT (it, 1), args, complain, in_decl,
17742 			       /*integral_constant_expression_p=*/false);
17743 	      TREE_VEC_ELT (*tp, 2)
17744 		= tsubst_expr (TREE_VEC_ELT (it, 2), args, complain, in_decl,
17745 			       /*integral_constant_expression_p=*/false);
17746 	      TREE_VEC_ELT (*tp, 3)
17747 		= tsubst_expr (TREE_VEC_ELT (it, 3), args, complain, in_decl,
17748 			       /*integral_constant_expression_p=*/false);
17749 	      TREE_CHAIN (*tp) = NULL_TREE;
17750 	      tp = &TREE_CHAIN (*tp);
17751 	    }
17752 	  TREE_VEC_ELT (ret, 5) = poplevel (1, 1, 0);
17753 	  iterator_cache[0] = TREE_PURPOSE (decl);
17754 	  iterator_cache[1] = ret;
17755 	}
17756       return build_tree_list (ret, tsubst_omp_clause_decl (TREE_VALUE (decl),
17757 							   args, complain,
17758 							   in_decl, NULL));
17759     }
17760 
17761   /* Handle an OpenMP array section represented as a TREE_LIST (or
17762      OMP_CLAUSE_DEPEND_KIND).  An OMP_CLAUSE_DEPEND (with a depend
17763      kind of OMP_CLAUSE_DEPEND_SINK) can also be represented as a
17764      TREE_LIST.  We can handle it exactly the same as an array section
17765      (purpose, value, and a chain), even though the nomenclature
17766      (low_bound, length, etc) is different.  */
17767   if (TREE_CODE (decl) == TREE_LIST)
17768     {
17769       tree low_bound
17770 	= tsubst_expr (TREE_PURPOSE (decl), args, complain, in_decl,
17771 		       /*integral_constant_expression_p=*/false);
17772       tree length = tsubst_expr (TREE_VALUE (decl), args, complain, in_decl,
17773 				 /*integral_constant_expression_p=*/false);
17774       tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
17775 					   in_decl, NULL);
17776       if (TREE_PURPOSE (decl) == low_bound
17777 	  && TREE_VALUE (decl) == length
17778 	  && TREE_CHAIN (decl) == chain)
17779 	return decl;
17780       tree ret = tree_cons (low_bound, length, chain);
17781       OMP_CLAUSE_DEPEND_SINK_NEGATIVE (ret)
17782 	= OMP_CLAUSE_DEPEND_SINK_NEGATIVE (decl);
17783       return ret;
17784     }
17785   tree ret = tsubst_expr (decl, args, complain, in_decl,
17786 			  /*integral_constant_expression_p=*/false);
17787   /* Undo convert_from_reference tsubst_expr could have called.  */
17788   if (decl
17789       && REFERENCE_REF_P (ret)
17790       && !REFERENCE_REF_P (decl))
17791     ret = TREE_OPERAND (ret, 0);
17792   return ret;
17793 }
17794 
17795 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
17796 
17797 static tree
tsubst_omp_clauses(tree clauses,enum c_omp_region_type ort,tree args,tsubst_flags_t complain,tree in_decl)17798 tsubst_omp_clauses (tree clauses, enum c_omp_region_type ort,
17799 		    tree args, tsubst_flags_t complain, tree in_decl)
17800 {
17801   tree new_clauses = NULL_TREE, nc, oc;
17802   tree linear_no_step = NULL_TREE;
17803   tree iterator_cache[2] = { NULL_TREE, NULL_TREE };
17804 
17805   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
17806     {
17807       nc = copy_node (oc);
17808       OMP_CLAUSE_CHAIN (nc) = new_clauses;
17809       new_clauses = nc;
17810 
17811       switch (OMP_CLAUSE_CODE (nc))
17812 	{
17813 	case OMP_CLAUSE_LASTPRIVATE:
17814 	  if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
17815 	    {
17816 	      OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
17817 	      tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
17818 			   in_decl, /*integral_constant_expression_p=*/false);
17819 	      OMP_CLAUSE_LASTPRIVATE_STMT (nc)
17820 		= pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
17821 	    }
17822 	  /* FALLTHRU */
17823 	case OMP_CLAUSE_PRIVATE:
17824 	case OMP_CLAUSE_SHARED:
17825 	case OMP_CLAUSE_FIRSTPRIVATE:
17826 	case OMP_CLAUSE_COPYIN:
17827 	case OMP_CLAUSE_COPYPRIVATE:
17828 	case OMP_CLAUSE_UNIFORM:
17829 	case OMP_CLAUSE_DEPEND:
17830 	case OMP_CLAUSE_AFFINITY:
17831 	case OMP_CLAUSE_FROM:
17832 	case OMP_CLAUSE_TO:
17833 	case OMP_CLAUSE_MAP:
17834 	case OMP_CLAUSE__CACHE_:
17835 	case OMP_CLAUSE_NONTEMPORAL:
17836 	case OMP_CLAUSE_USE_DEVICE_PTR:
17837 	case OMP_CLAUSE_USE_DEVICE_ADDR:
17838 	case OMP_CLAUSE_IS_DEVICE_PTR:
17839 	case OMP_CLAUSE_INCLUSIVE:
17840 	case OMP_CLAUSE_EXCLUSIVE:
17841 	  OMP_CLAUSE_DECL (nc)
17842 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17843 				      in_decl, iterator_cache);
17844 	  break;
17845 	case OMP_CLAUSE_NUM_TEAMS:
17846 	  if (OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (oc))
17847 	    OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (nc)
17848 	      = tsubst_expr (OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (oc), args,
17849 			     complain, in_decl,
17850 			     /*integral_constant_expression_p=*/false);
17851 	  /* FALLTHRU */
17852 	case OMP_CLAUSE_TILE:
17853 	case OMP_CLAUSE_IF:
17854 	case OMP_CLAUSE_NUM_THREADS:
17855 	case OMP_CLAUSE_SCHEDULE:
17856 	case OMP_CLAUSE_COLLAPSE:
17857 	case OMP_CLAUSE_FINAL:
17858 	case OMP_CLAUSE_DEVICE:
17859 	case OMP_CLAUSE_DIST_SCHEDULE:
17860 	case OMP_CLAUSE_THREAD_LIMIT:
17861 	case OMP_CLAUSE_SAFELEN:
17862 	case OMP_CLAUSE_SIMDLEN:
17863 	case OMP_CLAUSE_NUM_TASKS:
17864 	case OMP_CLAUSE_GRAINSIZE:
17865 	case OMP_CLAUSE_PRIORITY:
17866 	case OMP_CLAUSE_ORDERED:
17867 	case OMP_CLAUSE_HINT:
17868 	case OMP_CLAUSE_FILTER:
17869 	case OMP_CLAUSE_NUM_GANGS:
17870 	case OMP_CLAUSE_NUM_WORKERS:
17871 	case OMP_CLAUSE_VECTOR_LENGTH:
17872 	case OMP_CLAUSE_WORKER:
17873 	case OMP_CLAUSE_VECTOR:
17874 	case OMP_CLAUSE_ASYNC:
17875 	case OMP_CLAUSE_WAIT:
17876 	case OMP_CLAUSE_DETACH:
17877 	  OMP_CLAUSE_OPERAND (nc, 0)
17878 	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain,
17879 			   in_decl, /*integral_constant_expression_p=*/false);
17880 	  break;
17881 	case OMP_CLAUSE_REDUCTION:
17882 	case OMP_CLAUSE_IN_REDUCTION:
17883 	case OMP_CLAUSE_TASK_REDUCTION:
17884 	  if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
17885 	    {
17886 	      tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
17887 	      if (TREE_CODE (placeholder) == SCOPE_REF)
17888 		{
17889 		  tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
17890 				       complain, in_decl);
17891 		  OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
17892 		    = build_qualified_name (NULL_TREE, scope,
17893 					    TREE_OPERAND (placeholder, 1),
17894 					    false);
17895 		}
17896 	      else
17897 		gcc_assert (identifier_p (placeholder));
17898 	    }
17899 	  OMP_CLAUSE_DECL (nc)
17900 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17901 				      in_decl, NULL);
17902 	  break;
17903 	case OMP_CLAUSE_GANG:
17904 	case OMP_CLAUSE_ALIGNED:
17905 	  OMP_CLAUSE_DECL (nc)
17906 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17907 				      in_decl, NULL);
17908 	  OMP_CLAUSE_OPERAND (nc, 1)
17909 	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain,
17910 			   in_decl, /*integral_constant_expression_p=*/false);
17911 	  break;
17912 	case OMP_CLAUSE_ALLOCATE:
17913 	  OMP_CLAUSE_DECL (nc)
17914 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17915 				      in_decl, NULL);
17916 	  OMP_CLAUSE_OPERAND (nc, 1)
17917 	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain,
17918 			   in_decl, /*integral_constant_expression_p=*/false);
17919 	  OMP_CLAUSE_OPERAND (nc, 2)
17920 	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 2), args, complain,
17921 			   in_decl, /*integral_constant_expression_p=*/false);
17922 	  break;
17923 	case OMP_CLAUSE_LINEAR:
17924 	  OMP_CLAUSE_DECL (nc)
17925 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17926 				      in_decl, NULL);
17927 	  if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
17928 	    {
17929 	      gcc_assert (!linear_no_step);
17930 	      linear_no_step = nc;
17931 	    }
17932 	  else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
17933 	    OMP_CLAUSE_LINEAR_STEP (nc)
17934 	      = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
17935 					complain, in_decl, NULL);
17936 	  else
17937 	    OMP_CLAUSE_LINEAR_STEP (nc)
17938 	      = tsubst_expr (OMP_CLAUSE_LINEAR_STEP (oc), args, complain,
17939 			     in_decl,
17940 			     /*integral_constant_expression_p=*/false);
17941 	  break;
17942 	case OMP_CLAUSE_NOWAIT:
17943 	case OMP_CLAUSE_DEFAULT:
17944 	case OMP_CLAUSE_UNTIED:
17945 	case OMP_CLAUSE_MERGEABLE:
17946 	case OMP_CLAUSE_INBRANCH:
17947 	case OMP_CLAUSE_NOTINBRANCH:
17948 	case OMP_CLAUSE_PROC_BIND:
17949 	case OMP_CLAUSE_FOR:
17950 	case OMP_CLAUSE_PARALLEL:
17951 	case OMP_CLAUSE_SECTIONS:
17952 	case OMP_CLAUSE_TASKGROUP:
17953 	case OMP_CLAUSE_NOGROUP:
17954 	case OMP_CLAUSE_THREADS:
17955 	case OMP_CLAUSE_SIMD:
17956 	case OMP_CLAUSE_DEFAULTMAP:
17957 	case OMP_CLAUSE_ORDER:
17958 	case OMP_CLAUSE_BIND:
17959 	case OMP_CLAUSE_INDEPENDENT:
17960 	case OMP_CLAUSE_AUTO:
17961 	case OMP_CLAUSE_SEQ:
17962 	case OMP_CLAUSE_IF_PRESENT:
17963 	case OMP_CLAUSE_FINALIZE:
17964 	case OMP_CLAUSE_NOHOST:
17965 	  break;
17966 	default:
17967 	  gcc_unreachable ();
17968 	}
17969       if ((ort & C_ORT_OMP_DECLARE_SIMD) == C_ORT_OMP)
17970 	switch (OMP_CLAUSE_CODE (nc))
17971 	  {
17972 	  case OMP_CLAUSE_SHARED:
17973 	  case OMP_CLAUSE_PRIVATE:
17974 	  case OMP_CLAUSE_FIRSTPRIVATE:
17975 	  case OMP_CLAUSE_LASTPRIVATE:
17976 	  case OMP_CLAUSE_COPYPRIVATE:
17977 	  case OMP_CLAUSE_LINEAR:
17978 	  case OMP_CLAUSE_REDUCTION:
17979 	  case OMP_CLAUSE_IN_REDUCTION:
17980 	  case OMP_CLAUSE_TASK_REDUCTION:
17981 	  case OMP_CLAUSE_USE_DEVICE_PTR:
17982 	  case OMP_CLAUSE_USE_DEVICE_ADDR:
17983 	  case OMP_CLAUSE_IS_DEVICE_PTR:
17984 	  case OMP_CLAUSE_INCLUSIVE:
17985 	  case OMP_CLAUSE_EXCLUSIVE:
17986 	  case OMP_CLAUSE_ALLOCATE:
17987 	    /* tsubst_expr on SCOPE_REF results in returning
17988 	       finish_non_static_data_member result.  Undo that here.  */
17989 	    if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
17990 		&& (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
17991 		    == IDENTIFIER_NODE))
17992 	      {
17993 		tree t = OMP_CLAUSE_DECL (nc);
17994 		tree v = t;
17995 		while (v)
17996 		  switch (TREE_CODE (v))
17997 		    {
17998 		    case COMPONENT_REF:
17999 		    case MEM_REF:
18000 		    case INDIRECT_REF:
18001 		    CASE_CONVERT:
18002 		    case POINTER_PLUS_EXPR:
18003 		      v = TREE_OPERAND (v, 0);
18004 		      continue;
18005 		    case PARM_DECL:
18006 		      if (DECL_CONTEXT (v) == current_function_decl
18007 			  && DECL_ARTIFICIAL (v)
18008 			  && DECL_NAME (v) == this_identifier)
18009 			OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
18010 		      /* FALLTHRU */
18011 		    default:
18012 		      v = NULL_TREE;
18013 		      break;
18014 		    }
18015 	      }
18016 	    else if (VAR_P (OMP_CLAUSE_DECL (oc))
18017 		     && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
18018 		     && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
18019 		     && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
18020 		     && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
18021 	      {
18022 		tree decl = OMP_CLAUSE_DECL (nc);
18023 		if (VAR_P (decl))
18024 		  {
18025 		    retrofit_lang_decl (decl);
18026 		    DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
18027 		  }
18028 	      }
18029 	    break;
18030 	  default:
18031 	    break;
18032 	  }
18033     }
18034 
18035   new_clauses = nreverse (new_clauses);
18036   if (ort != C_ORT_OMP_DECLARE_SIMD)
18037     {
18038       new_clauses = finish_omp_clauses (new_clauses, ort);
18039       if (linear_no_step)
18040 	for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
18041 	  if (nc == linear_no_step)
18042 	    {
18043 	      OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
18044 	      break;
18045 	    }
18046     }
18047   return new_clauses;
18048 }
18049 
18050 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
18051 
18052 static tree
tsubst_copy_asm_operands(tree t,tree args,tsubst_flags_t complain,tree in_decl)18053 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
18054 			  tree in_decl)
18055 {
18056 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
18057 
18058   tree purpose, value, chain;
18059 
18060   if (t == NULL)
18061     return t;
18062 
18063   if (TREE_CODE (t) != TREE_LIST)
18064     return tsubst_copy_and_build (t, args, complain, in_decl,
18065 				  /*function_p=*/false,
18066 				  /*integral_constant_expression_p=*/false);
18067 
18068   if (t == void_list_node)
18069     return t;
18070 
18071   purpose = TREE_PURPOSE (t);
18072   if (purpose)
18073     purpose = RECUR (purpose);
18074   value = TREE_VALUE (t);
18075   if (value)
18076     {
18077       if (TREE_CODE (value) != LABEL_DECL)
18078 	value = RECUR (value);
18079       else
18080 	{
18081 	  value = lookup_label (DECL_NAME (value));
18082 	  gcc_assert (TREE_CODE (value) == LABEL_DECL);
18083 	  TREE_USED (value) = 1;
18084 	}
18085     }
18086   chain = TREE_CHAIN (t);
18087   if (chain && chain != void_type_node)
18088     chain = RECUR (chain);
18089   return tree_cons (purpose, value, chain);
18090 #undef RECUR
18091 }
18092 
18093 /* Used to temporarily communicate the list of #pragma omp parallel
18094    clauses to #pragma omp for instantiation if they are combined
18095    together.  */
18096 
18097 static tree *omp_parallel_combined_clauses;
18098 
18099 static tree tsubst_decomp_names (tree, tree, tree, tsubst_flags_t, tree,
18100 				 tree *, unsigned int *);
18101 
18102 /* Substitute one OMP_FOR iterator.  */
18103 
18104 static bool
tsubst_omp_for_iterator(tree t,int i,tree declv,tree & orig_declv,tree initv,tree condv,tree incrv,tree * clauses,tree args,tsubst_flags_t complain,tree in_decl,bool integral_constant_expression_p)18105 tsubst_omp_for_iterator (tree t, int i, tree declv, tree &orig_declv,
18106 			 tree initv, tree condv, tree incrv, tree *clauses,
18107 			 tree args, tsubst_flags_t complain, tree in_decl,
18108 			 bool integral_constant_expression_p)
18109 {
18110 #define RECUR(NODE)				\
18111   tsubst_expr ((NODE), args, complain, in_decl,	\
18112 	       integral_constant_expression_p)
18113   tree decl, init, cond = NULL_TREE, incr = NULL_TREE;
18114   bool ret = false;
18115 
18116   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
18117   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
18118 
18119   decl = TREE_OPERAND (init, 0);
18120   init = TREE_OPERAND (init, 1);
18121   tree decl_expr = NULL_TREE;
18122   bool range_for = TREE_VEC_ELT (OMP_FOR_COND (t), i) == global_namespace;
18123   if (range_for)
18124     {
18125       bool decomp = false;
18126       if (decl != error_mark_node && DECL_HAS_VALUE_EXPR_P (decl))
18127 	{
18128 	  tree v = DECL_VALUE_EXPR (decl);
18129 	  if (TREE_CODE (v) == ARRAY_REF
18130 	      && VAR_P (TREE_OPERAND (v, 0))
18131 	      && DECL_DECOMPOSITION_P (TREE_OPERAND (v, 0)))
18132 	    {
18133 	      tree decomp_first = NULL_TREE;
18134 	      unsigned decomp_cnt = 0;
18135 	      tree d = tsubst_decl (TREE_OPERAND (v, 0), args, complain);
18136 	      maybe_push_decl (d);
18137 	      d = tsubst_decomp_names (d, TREE_OPERAND (v, 0), args, complain,
18138 				       in_decl, &decomp_first, &decomp_cnt);
18139 	      decomp = true;
18140 	      if (d == error_mark_node)
18141 		decl = error_mark_node;
18142 	      else
18143 		for (unsigned int i = 0; i < decomp_cnt; i++)
18144 		  {
18145 		    if (!DECL_HAS_VALUE_EXPR_P (decomp_first))
18146 		      {
18147 			tree v = build_nt (ARRAY_REF, d,
18148 					   size_int (decomp_cnt - i - 1),
18149 					   NULL_TREE, NULL_TREE);
18150 			SET_DECL_VALUE_EXPR (decomp_first, v);
18151 			DECL_HAS_VALUE_EXPR_P (decomp_first) = 1;
18152 		      }
18153 		    fit_decomposition_lang_decl (decomp_first, d);
18154 		    decomp_first = DECL_CHAIN (decomp_first);
18155 		  }
18156 	    }
18157 	}
18158       decl = tsubst_decl (decl, args, complain);
18159       if (!decomp)
18160 	maybe_push_decl (decl);
18161     }
18162   else if (init && TREE_CODE (init) == DECL_EXPR)
18163     {
18164       /* We need to jump through some hoops to handle declarations in the
18165 	 init-statement, since we might need to handle auto deduction,
18166 	 but we need to keep control of initialization.  */
18167       decl_expr = init;
18168       init = DECL_INITIAL (DECL_EXPR_DECL (init));
18169       decl = tsubst_decl (decl, args, complain);
18170     }
18171   else
18172     {
18173       if (TREE_CODE (decl) == SCOPE_REF)
18174 	{
18175 	  decl = RECUR (decl);
18176 	  if (TREE_CODE (decl) == COMPONENT_REF)
18177 	    {
18178 	      tree v = decl;
18179 	      while (v)
18180 		switch (TREE_CODE (v))
18181 		  {
18182 		  case COMPONENT_REF:
18183 		  case MEM_REF:
18184 		  case INDIRECT_REF:
18185 		  CASE_CONVERT:
18186 		  case POINTER_PLUS_EXPR:
18187 		    v = TREE_OPERAND (v, 0);
18188 		    continue;
18189 		  case PARM_DECL:
18190 		    if (DECL_CONTEXT (v) == current_function_decl
18191 			&& DECL_ARTIFICIAL (v)
18192 			&& DECL_NAME (v) == this_identifier)
18193 		      {
18194 			decl = TREE_OPERAND (decl, 1);
18195 			decl = omp_privatize_field (decl, false);
18196 		      }
18197 		    /* FALLTHRU */
18198 		  default:
18199 		    v = NULL_TREE;
18200 		    break;
18201 		  }
18202 	    }
18203 	}
18204       else
18205 	decl = RECUR (decl);
18206     }
18207   if (init && TREE_CODE (init) == TREE_VEC)
18208     {
18209       init = copy_node (init);
18210       TREE_VEC_ELT (init, 0)
18211 	= tsubst_decl (TREE_VEC_ELT (init, 0), args, complain);
18212       TREE_VEC_ELT (init, 1) = RECUR (TREE_VEC_ELT (init, 1));
18213       TREE_VEC_ELT (init, 2) = RECUR (TREE_VEC_ELT (init, 2));
18214     }
18215   else
18216     init = RECUR (init);
18217 
18218   if (orig_declv && OMP_FOR_ORIG_DECLS (t))
18219     {
18220       tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
18221       if (TREE_CODE (o) == TREE_LIST)
18222 	TREE_VEC_ELT (orig_declv, i)
18223 	  = tree_cons (RECUR (TREE_PURPOSE (o)),
18224 		       RECUR (TREE_VALUE (o)),
18225 		       NULL_TREE);
18226       else
18227 	TREE_VEC_ELT (orig_declv, i) = RECUR (o);
18228     }
18229 
18230   if (range_for)
18231     {
18232       tree this_pre_body = NULL_TREE;
18233       tree orig_init = NULL_TREE;
18234       tree orig_decl = NULL_TREE;
18235       cp_convert_omp_range_for (this_pre_body, NULL, decl, orig_decl, init,
18236 				orig_init, cond, incr);
18237       if (orig_decl)
18238 	{
18239 	  if (orig_declv == NULL_TREE)
18240 	    orig_declv = copy_node (declv);
18241 	  TREE_VEC_ELT (orig_declv, i) = orig_decl;
18242 	  ret = true;
18243 	}
18244       else if (orig_declv)
18245 	TREE_VEC_ELT (orig_declv, i) = decl;
18246     }
18247 
18248   tree auto_node = type_uses_auto (TREE_TYPE (decl));
18249   if (!range_for && auto_node && init)
18250     TREE_TYPE (decl)
18251       = do_auto_deduction (TREE_TYPE (decl), init, auto_node, complain);
18252 
18253   gcc_assert (!type_dependent_expression_p (decl));
18254 
18255   if (!CLASS_TYPE_P (TREE_TYPE (decl)) || range_for)
18256     {
18257       if (decl_expr)
18258 	{
18259 	  /* Declare the variable, but don't let that initialize it.  */
18260 	  tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
18261 	  DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
18262 	  RECUR (decl_expr);
18263 	  DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
18264 	}
18265 
18266       if (!range_for)
18267 	{
18268 	  cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
18269 	  if (COMPARISON_CLASS_P (cond)
18270 	      && TREE_CODE (TREE_OPERAND (cond, 1)) == TREE_VEC)
18271 	    {
18272 	      tree lhs = RECUR (TREE_OPERAND (cond, 0));
18273 	      tree rhs = copy_node (TREE_OPERAND (cond, 1));
18274 	      TREE_VEC_ELT (rhs, 0)
18275 		= tsubst_decl (TREE_VEC_ELT (rhs, 0), args, complain);
18276 	      TREE_VEC_ELT (rhs, 1) = RECUR (TREE_VEC_ELT (rhs, 1));
18277 	      TREE_VEC_ELT (rhs, 2) = RECUR (TREE_VEC_ELT (rhs, 2));
18278 	      cond = build2 (TREE_CODE (cond), TREE_TYPE (cond),
18279 			     lhs, rhs);
18280 	    }
18281 	  else
18282 	    cond = RECUR (cond);
18283 	  incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
18284 	  if (TREE_CODE (incr) == MODIFY_EXPR)
18285 	    {
18286 	      tree lhs = RECUR (TREE_OPERAND (incr, 0));
18287 	      tree rhs = RECUR (TREE_OPERAND (incr, 1));
18288 	      incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
18289 					  NOP_EXPR, rhs, NULL_TREE, complain);
18290 	    }
18291 	  else
18292 	    incr = RECUR (incr);
18293 	  if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
18294 	    TREE_VEC_ELT (orig_declv, i) = decl;
18295 	}
18296       TREE_VEC_ELT (declv, i) = decl;
18297       TREE_VEC_ELT (initv, i) = init;
18298       TREE_VEC_ELT (condv, i) = cond;
18299       TREE_VEC_ELT (incrv, i) = incr;
18300       return ret;
18301     }
18302 
18303   if (decl_expr)
18304     {
18305       /* Declare and initialize the variable.  */
18306       RECUR (decl_expr);
18307       init = NULL_TREE;
18308     }
18309   else if (init)
18310     {
18311       tree *pc;
18312       int j;
18313       for (j = ((omp_parallel_combined_clauses == NULL
18314 		|| TREE_CODE (t) == OMP_LOOP) ? 1 : 0); j < 2; j++)
18315 	{
18316 	  for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
18317 	    {
18318 	      if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
18319 		  && OMP_CLAUSE_DECL (*pc) == decl)
18320 		break;
18321 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
18322 		       && OMP_CLAUSE_DECL (*pc) == decl)
18323 		{
18324 		  if (j)
18325 		    break;
18326 		  /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES.  */
18327 		  tree c = *pc;
18328 		  *pc = OMP_CLAUSE_CHAIN (c);
18329 		  OMP_CLAUSE_CHAIN (c) = *clauses;
18330 		  *clauses = c;
18331 		}
18332 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
18333 		       && OMP_CLAUSE_DECL (*pc) == decl)
18334 		{
18335 		  error ("iteration variable %qD should not be firstprivate",
18336 			 decl);
18337 		  *pc = OMP_CLAUSE_CHAIN (*pc);
18338 		}
18339 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
18340 		       && OMP_CLAUSE_DECL (*pc) == decl)
18341 		{
18342 		  error ("iteration variable %qD should not be reduction",
18343 			 decl);
18344 		  *pc = OMP_CLAUSE_CHAIN (*pc);
18345 		}
18346 	      else
18347 		pc = &OMP_CLAUSE_CHAIN (*pc);
18348 	    }
18349 	  if (*pc)
18350 	    break;
18351 	}
18352       if (*pc == NULL_TREE)
18353 	{
18354 	  tree c = build_omp_clause (input_location,
18355 				     TREE_CODE (t) == OMP_LOOP
18356 				     ? OMP_CLAUSE_LASTPRIVATE
18357 				     : OMP_CLAUSE_PRIVATE);
18358 	  OMP_CLAUSE_DECL (c) = decl;
18359 	  c = finish_omp_clauses (c, C_ORT_OMP);
18360 	  if (c)
18361 	    {
18362 	      OMP_CLAUSE_CHAIN (c) = *clauses;
18363 	      *clauses = c;
18364 	    }
18365 	}
18366     }
18367   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
18368   if (COMPARISON_CLASS_P (cond))
18369     {
18370       tree op0 = RECUR (TREE_OPERAND (cond, 0));
18371       tree op1 = RECUR (TREE_OPERAND (cond, 1));
18372       cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
18373     }
18374   else
18375     cond = RECUR (cond);
18376   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
18377   switch (TREE_CODE (incr))
18378     {
18379     case PREINCREMENT_EXPR:
18380     case PREDECREMENT_EXPR:
18381     case POSTINCREMENT_EXPR:
18382     case POSTDECREMENT_EXPR:
18383       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
18384 		     RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
18385       break;
18386     case MODIFY_EXPR:
18387       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
18388 	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
18389 	{
18390 	  tree rhs = TREE_OPERAND (incr, 1);
18391 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
18392 	  tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
18393 	  tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
18394 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18395 			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
18396 				 rhs0, rhs1));
18397 	}
18398       else
18399 	incr = RECUR (incr);
18400       break;
18401     case MODOP_EXPR:
18402       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
18403 	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
18404 	{
18405 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
18406 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18407 			 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
18408 				 TREE_TYPE (decl), lhs,
18409 				 RECUR (TREE_OPERAND (incr, 2))));
18410 	}
18411       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
18412 	       && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
18413 		   || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
18414 	{
18415 	  tree rhs = TREE_OPERAND (incr, 2);
18416 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
18417 	  tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
18418 	  tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
18419 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18420 			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
18421 				 rhs0, rhs1));
18422 	}
18423       else
18424 	incr = RECUR (incr);
18425       break;
18426     default:
18427       incr = RECUR (incr);
18428       break;
18429     }
18430 
18431   if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
18432     TREE_VEC_ELT (orig_declv, i) = decl;
18433   TREE_VEC_ELT (declv, i) = decl;
18434   TREE_VEC_ELT (initv, i) = init;
18435   TREE_VEC_ELT (condv, i) = cond;
18436   TREE_VEC_ELT (incrv, i) = incr;
18437   return false;
18438 #undef RECUR
18439 }
18440 
18441 /* Helper function of tsubst_expr, find OMP_TEAMS inside
18442    of OMP_TARGET's body.  */
18443 
18444 static tree
tsubst_find_omp_teams(tree * tp,int * walk_subtrees,void *)18445 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
18446 {
18447   *walk_subtrees = 0;
18448   switch (TREE_CODE (*tp))
18449     {
18450     case OMP_TEAMS:
18451       return *tp;
18452     case BIND_EXPR:
18453     case STATEMENT_LIST:
18454       *walk_subtrees = 1;
18455       break;
18456     default:
18457       break;
18458     }
18459   return NULL_TREE;
18460 }
18461 
18462 /* Helper function for tsubst_expr.  For decomposition declaration
18463    artificial base DECL, which is tsubsted PATTERN_DECL, tsubst
18464    also the corresponding decls representing the identifiers
18465    of the decomposition declaration.  Return DECL if successful
18466    or error_mark_node otherwise, set *FIRST to the first decl
18467    in the list chained through DECL_CHAIN and *CNT to the number
18468    of such decls.  */
18469 
18470 static tree
tsubst_decomp_names(tree decl,tree pattern_decl,tree args,tsubst_flags_t complain,tree in_decl,tree * first,unsigned int * cnt)18471 tsubst_decomp_names (tree decl, tree pattern_decl, tree args,
18472 		     tsubst_flags_t complain, tree in_decl, tree *first,
18473 		     unsigned int *cnt)
18474 {
18475   tree decl2, decl3, prev = decl;
18476   *cnt = 0;
18477   gcc_assert (DECL_NAME (decl) == NULL_TREE);
18478   for (decl2 = DECL_CHAIN (pattern_decl);
18479        decl2
18480        && VAR_P (decl2)
18481        && DECL_DECOMPOSITION_P (decl2)
18482        && DECL_NAME (decl2);
18483        decl2 = DECL_CHAIN (decl2))
18484     {
18485       if (TREE_TYPE (decl2) == error_mark_node && *cnt == 0)
18486 	{
18487 	  gcc_assert (errorcount);
18488 	  return error_mark_node;
18489 	}
18490       (*cnt)++;
18491       gcc_assert (DECL_DECOMP_BASE (decl2) == pattern_decl);
18492       gcc_assert (DECL_HAS_VALUE_EXPR_P (decl2));
18493       tree v = DECL_VALUE_EXPR (decl2);
18494       DECL_HAS_VALUE_EXPR_P (decl2) = 0;
18495       SET_DECL_VALUE_EXPR (decl2, NULL_TREE);
18496       decl3 = tsubst (decl2, args, complain, in_decl);
18497       SET_DECL_VALUE_EXPR (decl2, v);
18498       DECL_HAS_VALUE_EXPR_P (decl2) = 1;
18499       if (VAR_P (decl3))
18500 	DECL_TEMPLATE_INSTANTIATED (decl3) = 1;
18501       else
18502 	{
18503 	  gcc_assert (errorcount);
18504 	  decl = error_mark_node;
18505 	  continue;
18506 	}
18507       maybe_push_decl (decl3);
18508       if (error_operand_p (decl3))
18509 	decl = error_mark_node;
18510       else if (decl != error_mark_node
18511 	       && DECL_CHAIN (decl3) != prev
18512 	       && decl != prev)
18513 	{
18514 	  gcc_assert (errorcount);
18515 	  decl = error_mark_node;
18516 	}
18517       else
18518 	prev = decl3;
18519     }
18520   *first = prev;
18521   return decl;
18522 }
18523 
18524 /* Return the proper local_specialization for init-capture pack DECL.  */
18525 
18526 static tree
lookup_init_capture_pack(tree decl)18527 lookup_init_capture_pack (tree decl)
18528 {
18529   /* We handle normal pack captures by forwarding to the specialization of the
18530      captured parameter.  We can't do that for pack init-captures; we need them
18531      to have their own local_specialization.  We created the individual
18532      VAR_DECLs (if any) under build_capture_proxy, and we need to collect them
18533      when we process the DECL_EXPR for the pack init-capture in the template.
18534      So, how do we find them?  We don't know the capture proxy pack when
18535      building the individual resulting proxies, and we don't know the
18536      individual proxies when instantiating the pack.  What we have in common is
18537      the FIELD_DECL.
18538 
18539      So...when we instantiate the FIELD_DECL, we stick the result in
18540      local_specializations.  Then at the DECL_EXPR we look up that result, see
18541      how many elements it has, synthesize the names, and look them up.  */
18542 
18543   tree cname = DECL_NAME (decl);
18544   tree val = DECL_VALUE_EXPR (decl);
18545   tree field = TREE_OPERAND (val, 1);
18546   gcc_assert (TREE_CODE (field) == FIELD_DECL);
18547   tree fpack = retrieve_local_specialization (field);
18548   if (fpack == error_mark_node)
18549     return error_mark_node;
18550 
18551   int len = 1;
18552   tree vec = NULL_TREE;
18553   tree r = NULL_TREE;
18554   if (TREE_CODE (fpack) == TREE_VEC)
18555     {
18556       len = TREE_VEC_LENGTH (fpack);
18557       vec = make_tree_vec (len);
18558       r = make_node (NONTYPE_ARGUMENT_PACK);
18559       SET_ARGUMENT_PACK_ARGS (r, vec);
18560     }
18561   for (int i = 0; i < len; ++i)
18562     {
18563       tree ename = vec ? make_ith_pack_parameter_name (cname, i) : cname;
18564       tree elt = lookup_name (ename);
18565       if (vec)
18566 	TREE_VEC_ELT (vec, i) = elt;
18567       else
18568 	r = elt;
18569     }
18570   return r;
18571 }
18572 
18573 /* Like tsubst_copy for expressions, etc. but also does semantic
18574    processing.  */
18575 
18576 tree
tsubst_expr(tree t,tree args,tsubst_flags_t complain,tree in_decl,bool integral_constant_expression_p)18577 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
18578 	     bool integral_constant_expression_p)
18579 {
18580 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
18581 #define RECUR(NODE)				\
18582   tsubst_expr ((NODE), args, complain, in_decl,	\
18583 	       integral_constant_expression_p)
18584 
18585   tree stmt, tmp;
18586   tree r;
18587   location_t loc;
18588 
18589   if (t == NULL_TREE || t == error_mark_node)
18590     return t;
18591 
18592   loc = input_location;
18593   if (location_t eloc = cp_expr_location (t))
18594     input_location = eloc;
18595   if (STATEMENT_CODE_P (TREE_CODE (t)))
18596     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
18597 
18598   switch (TREE_CODE (t))
18599     {
18600     case STATEMENT_LIST:
18601       {
18602 	for (tree stmt : tsi_range (t))
18603 	  RECUR (stmt);
18604 	break;
18605       }
18606 
18607     case CTOR_INITIALIZER:
18608       finish_mem_initializers (tsubst_initializer_list
18609 			       (TREE_OPERAND (t, 0), args));
18610       break;
18611 
18612     case RETURN_EXPR:
18613       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
18614       break;
18615 
18616     case CO_RETURN_EXPR:
18617       finish_co_return_stmt (input_location, RECUR (TREE_OPERAND (t, 0)));
18618       break;
18619 
18620     case CO_YIELD_EXPR:
18621       stmt = finish_co_yield_expr (input_location,
18622 				   RECUR (TREE_OPERAND (t, 0)));
18623       RETURN (stmt);
18624 
18625     case CO_AWAIT_EXPR:
18626       stmt = finish_co_await_expr (input_location,
18627 				   RECUR (TREE_OPERAND (t, 0)));
18628       RETURN (stmt);
18629 
18630     case EXPR_STMT:
18631       tmp = RECUR (EXPR_STMT_EXPR (t));
18632       if (EXPR_STMT_STMT_EXPR_RESULT (t))
18633 	finish_stmt_expr_expr (tmp, cur_stmt_expr);
18634       else
18635 	finish_expr_stmt (tmp);
18636       break;
18637 
18638     case USING_STMT:
18639       finish_using_directive (USING_STMT_NAMESPACE (t), /*attribs=*/NULL_TREE);
18640       break;
18641 
18642     case DECL_EXPR:
18643       {
18644 	tree decl, pattern_decl;
18645 	tree init;
18646 
18647 	pattern_decl = decl = DECL_EXPR_DECL (t);
18648 	if (TREE_CODE (decl) == LABEL_DECL)
18649 	  finish_label_decl (DECL_NAME (decl));
18650 	else if (TREE_CODE (decl) == USING_DECL)
18651 	  {
18652 	    tree scope = USING_DECL_SCOPE (decl);
18653 	    if (DECL_DEPENDENT_P (decl))
18654 	      {
18655 		scope = tsubst (scope, args, complain, in_decl);
18656 		if (!MAYBE_CLASS_TYPE_P (scope)
18657 		    && TREE_CODE (scope) != ENUMERAL_TYPE)
18658 		  {
18659 		    if (complain & tf_error)
18660 		      error_at (DECL_SOURCE_LOCATION (decl), "%qT is not a "
18661 				"class, namespace, or enumeration", scope);
18662 		    return error_mark_node;
18663 		  }
18664 		finish_nonmember_using_decl (scope, DECL_NAME (decl));
18665 	      }
18666 	    else
18667 	      {
18668 		/* This is a non-dependent using-decl, and we'll have
18669 		   used the names it found during template parsing.  We do
18670 		   not want to do the lookup again, because we might not
18671 		   find the things we found then.  */
18672 		gcc_checking_assert (scope == tsubst (scope, args,
18673 						      complain, in_decl));
18674 		/* We still need to push the bindings so that we can look up
18675 		   this name later.  */
18676 		push_using_decl_bindings (DECL_NAME (decl),
18677 					  USING_DECL_DECLS (decl));
18678 	      }
18679 	  }
18680 	else if (is_capture_proxy (decl)
18681 		 && !DECL_TEMPLATE_INSTANTIATION (current_function_decl))
18682 	  {
18683 	    /* We're in tsubst_lambda_expr, we've already inserted a new
18684 	       capture proxy, so look it up and register it.  */
18685 	    tree inst;
18686 	    if (!DECL_PACK_P (decl))
18687 	      {
18688 		inst = lookup_name (DECL_NAME (decl), LOOK_where::BLOCK,
18689 				    LOOK_want::HIDDEN_LAMBDA);
18690 		gcc_assert (inst != decl && is_capture_proxy (inst));
18691 	      }
18692 	    else if (is_normal_capture_proxy (decl))
18693 	      {
18694 		inst = (retrieve_local_specialization
18695 			(DECL_CAPTURED_VARIABLE (decl)));
18696 		gcc_assert (TREE_CODE (inst) == NONTYPE_ARGUMENT_PACK
18697 			    || DECL_PACK_P (inst));
18698 	      }
18699 	    else
18700 	      inst = lookup_init_capture_pack (decl);
18701 
18702 	    register_local_specialization (inst, decl);
18703 	    break;
18704 	  }
18705 	else if (DECL_PRETTY_FUNCTION_P (decl))
18706 	  decl = make_fname_decl (DECL_SOURCE_LOCATION (decl),
18707 				  DECL_NAME (decl),
18708 				  true/*DECL_PRETTY_FUNCTION_P (decl)*/);
18709 	else if (DECL_IMPLICIT_TYPEDEF_P (decl)
18710 		 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
18711 	  /* Don't copy the old closure; we'll create a new one in
18712 	     tsubst_lambda_expr.  */
18713 	  break;
18714 	else
18715 	  {
18716 	    init = DECL_INITIAL (decl);
18717 	    decl = tsubst (decl, args, complain, in_decl);
18718 	    if (decl != error_mark_node)
18719 	      {
18720 		/* By marking the declaration as instantiated, we avoid
18721 		   trying to instantiate it.  Since instantiate_decl can't
18722 		   handle local variables, and since we've already done
18723 		   all that needs to be done, that's the right thing to
18724 		   do.  */
18725 		if (VAR_P (decl))
18726 		  DECL_TEMPLATE_INSTANTIATED (decl) = 1;
18727 		if (VAR_P (decl) && !DECL_NAME (decl)
18728 		    && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
18729 		  /* Anonymous aggregates are a special case.  */
18730 		  finish_anon_union (decl);
18731 		else if (is_capture_proxy (DECL_EXPR_DECL (t)))
18732 		  {
18733 		    DECL_CONTEXT (decl) = current_function_decl;
18734 		    if (DECL_NAME (decl) == this_identifier)
18735 		      {
18736 			tree lam = DECL_CONTEXT (current_function_decl);
18737 			lam = CLASSTYPE_LAMBDA_EXPR (lam);
18738 			LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
18739 		      }
18740 		    insert_capture_proxy (decl);
18741 		  }
18742 		else if (DECL_IMPLICIT_TYPEDEF_P (t))
18743 		  /* We already did a pushtag.  */;
18744 		else if (VAR_OR_FUNCTION_DECL_P (decl)
18745 			 && DECL_LOCAL_DECL_P (decl))
18746 		  {
18747 		    if (TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL)
18748 		      DECL_CONTEXT (decl) = NULL_TREE;
18749 		    decl = pushdecl (decl);
18750 		    if (TREE_CODE (decl) == FUNCTION_DECL
18751 			&& DECL_OMP_DECLARE_REDUCTION_P (decl)
18752 			&& cp_check_omp_declare_reduction (decl))
18753 		      instantiate_body (pattern_decl, args, decl, true);
18754 		  }
18755 		else
18756 		  {
18757 		    bool const_init = false;
18758 		    unsigned int cnt = 0;
18759 		    tree first = NULL_TREE, ndecl = error_mark_node;
18760 		    tree asmspec_tree = NULL_TREE;
18761 		    maybe_push_decl (decl);
18762 
18763 		    if (VAR_P (decl)
18764 			&& DECL_LANG_SPECIFIC (decl)
18765 			&& DECL_OMP_PRIVATIZED_MEMBER (decl))
18766 		      break;
18767 
18768 		    if (VAR_P (decl)
18769 			&& DECL_DECOMPOSITION_P (decl)
18770 			&& TREE_TYPE (pattern_decl) != error_mark_node)
18771 		      ndecl = tsubst_decomp_names (decl, pattern_decl, args,
18772 						   complain, in_decl, &first,
18773 						   &cnt);
18774 
18775 		    init = tsubst_init (init, decl, args, complain, in_decl);
18776 
18777 		    if (VAR_P (decl))
18778 		      const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
18779 				    (pattern_decl));
18780 
18781 		    if (ndecl != error_mark_node)
18782 		      cp_maybe_mangle_decomp (ndecl, first, cnt);
18783 
18784 		    /* In a non-template function, VLA type declarations are
18785 		       handled in grokdeclarator; for templates, handle them
18786 		       now.  */
18787 		    predeclare_vla (decl);
18788 
18789 		    if (VAR_P (decl) && DECL_HARD_REGISTER (pattern_decl))
18790 		      {
18791 			tree id = DECL_ASSEMBLER_NAME (pattern_decl);
18792 			const char *asmspec = IDENTIFIER_POINTER (id);
18793 			gcc_assert (asmspec[0] == '*');
18794 			asmspec_tree
18795 			  = build_string (IDENTIFIER_LENGTH (id) - 1,
18796 					  asmspec + 1);
18797 			TREE_TYPE (asmspec_tree) = char_array_type_node;
18798 		      }
18799 
18800 		    cp_finish_decl (decl, init, const_init, asmspec_tree, 0);
18801 
18802 		    if (ndecl != error_mark_node)
18803 		      cp_finish_decomp (ndecl, first, cnt);
18804 		  }
18805 	      }
18806 	  }
18807 
18808 	break;
18809       }
18810 
18811     case FOR_STMT:
18812       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
18813       RECUR (FOR_INIT_STMT (t));
18814       finish_init_stmt (stmt);
18815       tmp = RECUR (FOR_COND (t));
18816       finish_for_cond (tmp, stmt, false, 0);
18817       tmp = RECUR (FOR_EXPR (t));
18818       finish_for_expr (tmp, stmt);
18819       {
18820 	bool prev = note_iteration_stmt_body_start ();
18821 	RECUR (FOR_BODY (t));
18822 	note_iteration_stmt_body_end (prev);
18823       }
18824       finish_for_stmt (stmt);
18825       break;
18826 
18827     case RANGE_FOR_STMT:
18828       {
18829 	/* Construct another range_for, if this is not a final
18830 	   substitution (for inside a generic lambda of a
18831 	   template).  Otherwise convert to a regular for.  */
18832         tree decl, expr;
18833         stmt = (processing_template_decl
18834 		? begin_range_for_stmt (NULL_TREE, NULL_TREE)
18835 		: begin_for_stmt (NULL_TREE, NULL_TREE));
18836 	RECUR (RANGE_FOR_INIT_STMT (t));
18837         decl = RANGE_FOR_DECL (t);
18838         decl = tsubst (decl, args, complain, in_decl);
18839         maybe_push_decl (decl);
18840         expr = RECUR (RANGE_FOR_EXPR (t));
18841 
18842 	tree decomp_first = NULL_TREE;
18843 	unsigned decomp_cnt = 0;
18844 	if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
18845 	  decl = tsubst_decomp_names (decl, RANGE_FOR_DECL (t), args,
18846 				      complain, in_decl,
18847 				      &decomp_first, &decomp_cnt);
18848 
18849 	if (processing_template_decl)
18850 	  {
18851 	    RANGE_FOR_IVDEP (stmt) = RANGE_FOR_IVDEP (t);
18852 	    RANGE_FOR_UNROLL (stmt) = RANGE_FOR_UNROLL (t);
18853 	    finish_range_for_decl (stmt, decl, expr);
18854 	    if (decomp_first && decl != error_mark_node)
18855 	      cp_finish_decomp (decl, decomp_first, decomp_cnt);
18856 	  }
18857 	else
18858 	  {
18859 	    unsigned short unroll = (RANGE_FOR_UNROLL (t)
18860 				     ? tree_to_uhwi (RANGE_FOR_UNROLL (t)) : 0);
18861 	    stmt = cp_convert_range_for (stmt, decl, expr,
18862 					 decomp_first, decomp_cnt,
18863 					 RANGE_FOR_IVDEP (t), unroll);
18864 	  }
18865 
18866 	bool prev = note_iteration_stmt_body_start ();
18867         RECUR (RANGE_FOR_BODY (t));
18868 	note_iteration_stmt_body_end (prev);
18869         finish_for_stmt (stmt);
18870       }
18871       break;
18872 
18873     case WHILE_STMT:
18874       stmt = begin_while_stmt ();
18875       tmp = RECUR (WHILE_COND (t));
18876       finish_while_stmt_cond (tmp, stmt, false, 0);
18877       {
18878 	bool prev = note_iteration_stmt_body_start ();
18879 	RECUR (WHILE_BODY (t));
18880 	note_iteration_stmt_body_end (prev);
18881       }
18882       finish_while_stmt (stmt);
18883       break;
18884 
18885     case DO_STMT:
18886       stmt = begin_do_stmt ();
18887       {
18888 	bool prev = note_iteration_stmt_body_start ();
18889 	RECUR (DO_BODY (t));
18890 	note_iteration_stmt_body_end (prev);
18891       }
18892       finish_do_body (stmt);
18893       tmp = RECUR (DO_COND (t));
18894       finish_do_stmt (tmp, stmt, false, 0);
18895       break;
18896 
18897     case IF_STMT:
18898       stmt = begin_if_stmt ();
18899       IF_STMT_CONSTEXPR_P (stmt) = IF_STMT_CONSTEXPR_P (t);
18900       IF_STMT_CONSTEVAL_P (stmt) = IF_STMT_CONSTEVAL_P (t);
18901       if (IF_STMT_CONSTEXPR_P (t))
18902 	args = add_extra_args (IF_STMT_EXTRA_ARGS (t), args, complain, in_decl);
18903       tmp = RECUR (IF_COND (t));
18904       tmp = finish_if_stmt_cond (tmp, stmt);
18905       if (IF_STMT_CONSTEXPR_P (t)
18906 	  && instantiation_dependent_expression_p (tmp))
18907 	{
18908 	  /* We're partially instantiating a generic lambda, but the condition
18909 	     of the constexpr if is still dependent.  Don't substitute into the
18910 	     branches now, just remember the template arguments.  */
18911 	  do_poplevel (IF_SCOPE (stmt));
18912 	  IF_COND (stmt) = IF_COND (t);
18913 	  THEN_CLAUSE (stmt) = THEN_CLAUSE (t);
18914 	  ELSE_CLAUSE (stmt) = ELSE_CLAUSE (t);
18915 	  IF_STMT_EXTRA_ARGS (stmt) = build_extra_args (t, args, complain);
18916 	  add_stmt (stmt);
18917 	  break;
18918 	}
18919       if (IF_STMT_CONSTEXPR_P (t) && integer_zerop (tmp))
18920 	/* Don't instantiate the THEN_CLAUSE. */;
18921       else if (IF_STMT_CONSTEVAL_P (t))
18922 	{
18923 	  bool save_in_consteval_if_p = in_consteval_if_p;
18924 	  in_consteval_if_p = true;
18925 	  RECUR (THEN_CLAUSE (t));
18926 	  in_consteval_if_p = save_in_consteval_if_p;
18927 	}
18928       else
18929 	{
18930 	  tree folded = fold_non_dependent_expr (tmp, complain);
18931 	  bool inhibit = integer_zerop (folded);
18932 	  if (inhibit)
18933 	    ++c_inhibit_evaluation_warnings;
18934 	  RECUR (THEN_CLAUSE (t));
18935 	  if (inhibit)
18936 	    --c_inhibit_evaluation_warnings;
18937 	}
18938       finish_then_clause (stmt);
18939 
18940       if (IF_STMT_CONSTEXPR_P (t) && integer_nonzerop (tmp))
18941 	/* Don't instantiate the ELSE_CLAUSE. */;
18942       else if (ELSE_CLAUSE (t))
18943 	{
18944 	  tree folded = fold_non_dependent_expr (tmp, complain);
18945 	  bool inhibit = integer_nonzerop (folded);
18946 	  begin_else_clause (stmt);
18947 	  if (inhibit)
18948 	    ++c_inhibit_evaluation_warnings;
18949 	  RECUR (ELSE_CLAUSE (t));
18950 	  if (inhibit)
18951 	    --c_inhibit_evaluation_warnings;
18952 	  finish_else_clause (stmt);
18953 	}
18954 
18955       finish_if_stmt (stmt);
18956       break;
18957 
18958     case BIND_EXPR:
18959       if (BIND_EXPR_BODY_BLOCK (t))
18960 	stmt = begin_function_body ();
18961       else
18962 	stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
18963 				    ? BCS_TRY_BLOCK : 0);
18964 
18965       RECUR (BIND_EXPR_BODY (t));
18966 
18967       if (BIND_EXPR_BODY_BLOCK (t))
18968 	finish_function_body (stmt);
18969       else
18970 	finish_compound_stmt (stmt);
18971       break;
18972 
18973     case BREAK_STMT:
18974       finish_break_stmt ();
18975       break;
18976 
18977     case CONTINUE_STMT:
18978       finish_continue_stmt ();
18979       break;
18980 
18981     case SWITCH_STMT:
18982       stmt = begin_switch_stmt ();
18983       tmp = RECUR (SWITCH_STMT_COND (t));
18984       finish_switch_cond (tmp, stmt);
18985       RECUR (SWITCH_STMT_BODY (t));
18986       finish_switch_stmt (stmt);
18987       break;
18988 
18989     case CASE_LABEL_EXPR:
18990       {
18991 	tree decl = CASE_LABEL (t);
18992 	tree low = RECUR (CASE_LOW (t));
18993 	tree high = RECUR (CASE_HIGH (t));
18994 	tree l = finish_case_label (EXPR_LOCATION (t), low, high);
18995 	if (l && TREE_CODE (l) == CASE_LABEL_EXPR)
18996 	  {
18997 	    tree label = CASE_LABEL (l);
18998 	    FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
18999 	    if (DECL_ATTRIBUTES (decl) != NULL_TREE)
19000 	      cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
19001 	  }
19002       }
19003       break;
19004 
19005     case LABEL_EXPR:
19006       {
19007 	tree decl = LABEL_EXPR_LABEL (t);
19008 	tree label;
19009 
19010 	label = finish_label_stmt (DECL_NAME (decl));
19011 	if (TREE_CODE (label) == LABEL_DECL)
19012 	  FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
19013 	if (DECL_ATTRIBUTES (decl) != NULL_TREE)
19014 	  cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
19015       }
19016       break;
19017 
19018     case GOTO_EXPR:
19019       tmp = GOTO_DESTINATION (t);
19020       if (TREE_CODE (tmp) != LABEL_DECL)
19021 	/* Computed goto's must be tsubst'd into.  On the other hand,
19022 	   non-computed gotos must not be; the identifier in question
19023 	   will have no binding.  */
19024 	tmp = RECUR (tmp);
19025       else
19026 	tmp = DECL_NAME (tmp);
19027       finish_goto_stmt (tmp);
19028       break;
19029 
19030     case ASM_EXPR:
19031       {
19032 	tree string = RECUR (ASM_STRING (t));
19033 	tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
19034 						 complain, in_decl);
19035 	tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
19036 						complain, in_decl);
19037 	tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
19038 	 					  complain, in_decl);
19039 	tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
19040 						complain, in_decl);
19041 	tmp = finish_asm_stmt (EXPR_LOCATION (t), ASM_VOLATILE_P (t), string,
19042 			       outputs, inputs, clobbers, labels,
19043 			       ASM_INLINE_P (t));
19044 	tree asm_expr = tmp;
19045 	if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
19046 	  asm_expr = TREE_OPERAND (asm_expr, 0);
19047 	ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
19048       }
19049       break;
19050 
19051     case TRY_BLOCK:
19052       if (CLEANUP_P (t))
19053 	{
19054 	  stmt = begin_try_block ();
19055 	  RECUR (TRY_STMTS (t));
19056 	  finish_cleanup_try_block (stmt);
19057 	  finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
19058 	}
19059       else
19060 	{
19061 	  tree compound_stmt = NULL_TREE;
19062 
19063 	  if (FN_TRY_BLOCK_P (t))
19064 	    stmt = begin_function_try_block (&compound_stmt);
19065 	  else
19066 	    stmt = begin_try_block ();
19067 
19068 	  RECUR (TRY_STMTS (t));
19069 
19070 	  if (FN_TRY_BLOCK_P (t))
19071 	    finish_function_try_block (stmt);
19072 	  else
19073 	    finish_try_block (stmt);
19074 
19075 	  RECUR (TRY_HANDLERS (t));
19076 	  if (FN_TRY_BLOCK_P (t))
19077 	    finish_function_handler_sequence (stmt, compound_stmt);
19078 	  else
19079 	    finish_handler_sequence (stmt);
19080 	}
19081       break;
19082 
19083     case HANDLER:
19084       {
19085 	tree decl = HANDLER_PARMS (t);
19086 
19087 	if (decl)
19088 	  {
19089 	    decl = tsubst (decl, args, complain, in_decl);
19090 	    /* Prevent instantiate_decl from trying to instantiate
19091 	       this variable.  We've already done all that needs to be
19092 	       done.  */
19093 	    if (decl != error_mark_node)
19094 	      DECL_TEMPLATE_INSTANTIATED (decl) = 1;
19095 	  }
19096 	stmt = begin_handler ();
19097 	finish_handler_parms (decl, stmt);
19098 	RECUR (HANDLER_BODY (t));
19099 	finish_handler (stmt);
19100       }
19101       break;
19102 
19103     case TAG_DEFN:
19104       tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
19105       if (dependent_type_p (tmp))
19106 	/* This is a partial instantiation, try again when full.  */
19107 	add_stmt (build_min (TAG_DEFN, tmp));
19108       else if (CLASS_TYPE_P (tmp))
19109 	{
19110 	  /* Local classes are not independent templates; they are
19111 	     instantiated along with their containing function.  And this
19112 	     way we don't have to deal with pushing out of one local class
19113 	     to instantiate a member of another local class.  */
19114 	  /* Closures are handled by the LAMBDA_EXPR.  */
19115 	  gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
19116 	  complete_type (tmp);
19117 	  tree save_ccp = current_class_ptr;
19118 	  tree save_ccr = current_class_ref;
19119 	  for (tree fld = TYPE_FIELDS (tmp); fld; fld = DECL_CHAIN (fld))
19120 	    if ((VAR_P (fld)
19121 		 || (TREE_CODE (fld) == FUNCTION_DECL
19122 		     && !DECL_ARTIFICIAL (fld)))
19123 		&& DECL_TEMPLATE_INSTANTIATION (fld))
19124 	      instantiate_decl (fld, /*defer_ok=*/false,
19125 				/*expl_inst_class=*/false);
19126 	    else if (TREE_CODE (fld) == FIELD_DECL)
19127 	      maybe_instantiate_nsdmi_init (fld, tf_warning_or_error);
19128 	  current_class_ptr = save_ccp;
19129 	  current_class_ref = save_ccr;
19130 	}
19131       break;
19132 
19133     case STATIC_ASSERT:
19134       {
19135 	tree condition;
19136 
19137 	++c_inhibit_evaluation_warnings;
19138 	condition =
19139 	  tsubst_expr (STATIC_ASSERT_CONDITION (t),
19140                        args,
19141                        complain, in_decl,
19142                        /*integral_constant_expression_p=*/true);
19143 	--c_inhibit_evaluation_warnings;
19144 
19145         finish_static_assert (condition,
19146                               STATIC_ASSERT_MESSAGE (t),
19147                               STATIC_ASSERT_SOURCE_LOCATION (t),
19148 			      /*member_p=*/false, /*show_expr_p=*/true);
19149       }
19150       break;
19151 
19152     case OACC_KERNELS:
19153     case OACC_PARALLEL:
19154     case OACC_SERIAL:
19155       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_ACC, args, complain,
19156 				in_decl);
19157       stmt = begin_omp_parallel ();
19158       RECUR (OMP_BODY (t));
19159       finish_omp_construct (TREE_CODE (t), stmt, tmp);
19160       break;
19161 
19162     case OMP_PARALLEL:
19163       r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
19164       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), C_ORT_OMP, args,
19165 				complain, in_decl);
19166       if (OMP_PARALLEL_COMBINED (t))
19167 	omp_parallel_combined_clauses = &tmp;
19168       stmt = begin_omp_parallel ();
19169       RECUR (OMP_PARALLEL_BODY (t));
19170       gcc_assert (omp_parallel_combined_clauses == NULL);
19171       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
19172 	= OMP_PARALLEL_COMBINED (t);
19173       pop_omp_privatization_clauses (r);
19174       break;
19175 
19176     case OMP_TASK:
19177       if (OMP_TASK_BODY (t) == NULL_TREE)
19178 	{
19179 	  tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
19180 				    complain, in_decl);
19181 	  t = copy_node (t);
19182 	  OMP_TASK_CLAUSES (t) = tmp;
19183 	  add_stmt (t);
19184 	  break;
19185 	}
19186       r = push_omp_privatization_clauses (false);
19187       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
19188 				complain, in_decl);
19189       stmt = begin_omp_task ();
19190       RECUR (OMP_TASK_BODY (t));
19191       finish_omp_task (tmp, stmt);
19192       pop_omp_privatization_clauses (r);
19193       break;
19194 
19195     case OMP_FOR:
19196     case OMP_LOOP:
19197     case OMP_SIMD:
19198     case OMP_DISTRIBUTE:
19199     case OMP_TASKLOOP:
19200     case OACC_LOOP:
19201       {
19202 	tree clauses, body, pre_body;
19203 	tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
19204 	tree orig_declv = NULL_TREE;
19205 	tree incrv = NULL_TREE;
19206 	enum c_omp_region_type ort = C_ORT_OMP;
19207 	bool any_range_for = false;
19208 	int i;
19209 
19210 	if (TREE_CODE (t) == OACC_LOOP)
19211 	  ort = C_ORT_ACC;
19212 
19213 	r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
19214 	clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), ort, args, complain,
19215 				      in_decl);
19216 	if (OMP_FOR_INIT (t) != NULL_TREE)
19217 	  {
19218 	    declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19219 	    if (OMP_FOR_ORIG_DECLS (t))
19220 	      orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19221 	    initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19222 	    condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19223 	    incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19224 	  }
19225 
19226 	keep_next_level (true);
19227 	stmt = begin_omp_structured_block ();
19228 
19229 	pre_body = push_stmt_list ();
19230 	RECUR (OMP_FOR_PRE_BODY (t));
19231 	pre_body = pop_stmt_list (pre_body);
19232 
19233 	if (OMP_FOR_INIT (t) != NULL_TREE)
19234 	  for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
19235 	    any_range_for
19236 	      |= tsubst_omp_for_iterator (t, i, declv, orig_declv, initv,
19237 					  condv, incrv, &clauses, args,
19238 					  complain, in_decl,
19239 					  integral_constant_expression_p);
19240 	omp_parallel_combined_clauses = NULL;
19241 
19242 	if (any_range_for)
19243 	  {
19244 	    gcc_assert (orig_declv);
19245 	    body = begin_omp_structured_block ();
19246 	    for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
19247 	      if (TREE_VEC_ELT (orig_declv, i) != TREE_VEC_ELT (declv, i)
19248 		  && TREE_CODE (TREE_VEC_ELT (orig_declv, i)) == TREE_LIST
19249 		  && TREE_CHAIN (TREE_VEC_ELT (orig_declv, i)))
19250 		cp_finish_omp_range_for (TREE_VEC_ELT (orig_declv, i),
19251 					 TREE_VEC_ELT (declv, i));
19252 	  }
19253 	else
19254 	  body = push_stmt_list ();
19255 	RECUR (OMP_FOR_BODY (t));
19256 	if (any_range_for)
19257 	  body = finish_omp_structured_block (body);
19258 	else
19259 	  body = pop_stmt_list (body);
19260 
19261 	if (OMP_FOR_INIT (t) != NULL_TREE)
19262 	  t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
19263 			      orig_declv, initv, condv, incrv, body, pre_body,
19264 			      NULL, clauses);
19265 	else
19266 	  {
19267 	    t = make_node (TREE_CODE (t));
19268 	    TREE_TYPE (t) = void_type_node;
19269 	    OMP_FOR_BODY (t) = body;
19270 	    OMP_FOR_PRE_BODY (t) = pre_body;
19271 	    OMP_FOR_CLAUSES (t) = clauses;
19272 	    SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
19273 	    add_stmt (t);
19274 	  }
19275 
19276 	add_stmt (finish_omp_for_block (finish_omp_structured_block (stmt),
19277 					t));
19278 	pop_omp_privatization_clauses (r);
19279       }
19280       break;
19281 
19282     case OMP_SECTIONS:
19283     case OMP_MASKED:
19284       omp_parallel_combined_clauses = NULL;
19285       /* FALLTHRU */
19286     case OMP_SINGLE:
19287     case OMP_SCOPE:
19288     case OMP_TEAMS:
19289     case OMP_CRITICAL:
19290     case OMP_TASKGROUP:
19291     case OMP_SCAN:
19292       r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
19293 					  && OMP_TEAMS_COMBINED (t));
19294       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_OMP, args, complain,
19295 				in_decl);
19296       if (TREE_CODE (t) == OMP_TEAMS)
19297 	{
19298 	  keep_next_level (true);
19299 	  stmt = begin_omp_structured_block ();
19300 	  RECUR (OMP_BODY (t));
19301 	  stmt = finish_omp_structured_block (stmt);
19302 	}
19303       else
19304 	{
19305 	  stmt = push_stmt_list ();
19306 	  RECUR (OMP_BODY (t));
19307 	  stmt = pop_stmt_list (stmt);
19308 	}
19309 
19310       if (TREE_CODE (t) == OMP_CRITICAL
19311 	  && tmp != NULL_TREE
19312 	  && integer_nonzerop (OMP_CLAUSE_HINT_EXPR (tmp)))
19313 	{
19314 	  error_at (OMP_CLAUSE_LOCATION (tmp),
19315 		    "%<#pragma omp critical%> with %<hint%> clause requires "
19316 		    "a name, except when %<omp_sync_hint_none%> is used");
19317 	  RETURN (error_mark_node);
19318 	}
19319       t = copy_node (t);
19320       OMP_BODY (t) = stmt;
19321       OMP_CLAUSES (t) = tmp;
19322       add_stmt (t);
19323       pop_omp_privatization_clauses (r);
19324       break;
19325 
19326     case OMP_DEPOBJ:
19327       r = RECUR (OMP_DEPOBJ_DEPOBJ (t));
19328       if (OMP_DEPOBJ_CLAUSES (t) && OMP_DEPOBJ_CLAUSES (t) != error_mark_node)
19329 	{
19330 	  enum omp_clause_depend_kind kind = OMP_CLAUSE_DEPEND_SOURCE;
19331 	  if (TREE_CODE (OMP_DEPOBJ_CLAUSES (t)) == OMP_CLAUSE)
19332 	    {
19333 	      tmp = tsubst_omp_clauses (OMP_DEPOBJ_CLAUSES (t), C_ORT_OMP,
19334 					args, complain, in_decl);
19335 	      if (tmp == NULL_TREE)
19336 		tmp = error_mark_node;
19337 	    }
19338 	  else
19339 	    {
19340 	      kind = (enum omp_clause_depend_kind)
19341 		     tree_to_uhwi (OMP_DEPOBJ_CLAUSES (t));
19342 	      tmp = NULL_TREE;
19343 	    }
19344 	  finish_omp_depobj (EXPR_LOCATION (t), r, kind, tmp);
19345 	}
19346       else
19347 	finish_omp_depobj (EXPR_LOCATION (t), r,
19348 			   OMP_CLAUSE_DEPEND_SOURCE,
19349 			   OMP_DEPOBJ_CLAUSES (t));
19350       break;
19351 
19352     case OACC_DATA:
19353     case OMP_TARGET_DATA:
19354     case OMP_TARGET:
19355       tmp = tsubst_omp_clauses (OMP_CLAUSES (t),
19356 				TREE_CODE (t) == OACC_DATA
19357 				? C_ORT_ACC
19358 				: TREE_CODE (t) == OMP_TARGET
19359 				? C_ORT_OMP_TARGET : C_ORT_OMP,
19360 				args, complain, in_decl);
19361       keep_next_level (true);
19362       stmt = begin_omp_structured_block ();
19363 
19364       RECUR (OMP_BODY (t));
19365       stmt = finish_omp_structured_block (stmt);
19366 
19367       t = copy_node (t);
19368       OMP_BODY (t) = stmt;
19369       OMP_CLAUSES (t) = tmp;
19370 
19371       if (TREE_CODE (t) == OMP_TARGET)
19372 	finish_omp_target_clauses (EXPR_LOCATION (t), OMP_BODY (t),
19373 				   &OMP_CLAUSES (t));
19374 
19375       if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
19376 	{
19377 	  tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
19378 	  if (teams)
19379 	    /* For combined target teams, ensure the num_teams and
19380 	       thread_limit clause expressions are evaluated on the host,
19381 	       before entering the target construct.  */
19382 	    for (tree c = OMP_TEAMS_CLAUSES (teams);
19383 		 c; c = OMP_CLAUSE_CHAIN (c))
19384 	      if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
19385 		  || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
19386 		for (int i = 0;
19387 		     i <= (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS); ++i)
19388 		  if (OMP_CLAUSE_OPERAND (c, i)
19389 		      && TREE_CODE (OMP_CLAUSE_OPERAND (c, i)) != INTEGER_CST)
19390 		    {
19391 		      tree expr = OMP_CLAUSE_OPERAND (c, i);
19392 		      expr = force_target_expr (TREE_TYPE (expr), expr,
19393 						tf_none);
19394 		      if (expr == error_mark_node)
19395 			continue;
19396 		      tmp = TARGET_EXPR_SLOT (expr);
19397 		      add_stmt (expr);
19398 		      OMP_CLAUSE_OPERAND (c, i) = expr;
19399 		      tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
19400 						  OMP_CLAUSE_FIRSTPRIVATE);
19401 		      OMP_CLAUSE_DECL (tc) = tmp;
19402 		      OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
19403 		      OMP_TARGET_CLAUSES (t) = tc;
19404 		    }
19405 	}
19406       add_stmt (t);
19407       break;
19408 
19409     case OACC_DECLARE:
19410       t = copy_node (t);
19411       tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), C_ORT_ACC, args,
19412 				complain, in_decl);
19413       OACC_DECLARE_CLAUSES (t) = tmp;
19414       add_stmt (t);
19415       break;
19416 
19417     case OMP_TARGET_UPDATE:
19418     case OMP_TARGET_ENTER_DATA:
19419     case OMP_TARGET_EXIT_DATA:
19420       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_OMP, args,
19421 				complain, in_decl);
19422       t = copy_node (t);
19423       OMP_STANDALONE_CLAUSES (t) = tmp;
19424       add_stmt (t);
19425       break;
19426 
19427     case OACC_CACHE:
19428     case OACC_ENTER_DATA:
19429     case OACC_EXIT_DATA:
19430     case OACC_UPDATE:
19431       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_ACC, args,
19432 				complain, in_decl);
19433       t = copy_node (t);
19434       OMP_STANDALONE_CLAUSES (t) = tmp;
19435       add_stmt (t);
19436       break;
19437 
19438     case OMP_ORDERED:
19439       tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), C_ORT_OMP, args,
19440 				complain, in_decl);
19441       stmt = push_stmt_list ();
19442       RECUR (OMP_BODY (t));
19443       stmt = pop_stmt_list (stmt);
19444 
19445       t = copy_node (t);
19446       OMP_BODY (t) = stmt;
19447       OMP_ORDERED_CLAUSES (t) = tmp;
19448       add_stmt (t);
19449       break;
19450 
19451     case OMP_MASTER:
19452       omp_parallel_combined_clauses = NULL;
19453       /* FALLTHRU */
19454     case OMP_SECTION:
19455       stmt = push_stmt_list ();
19456       RECUR (OMP_BODY (t));
19457       stmt = pop_stmt_list (stmt);
19458 
19459       t = copy_node (t);
19460       OMP_BODY (t) = stmt;
19461       add_stmt (t);
19462       break;
19463 
19464     case OMP_ATOMIC:
19465       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
19466       tmp = NULL_TREE;
19467       if (TREE_CODE (TREE_OPERAND (t, 0)) == OMP_CLAUSE)
19468 	tmp = tsubst_omp_clauses (TREE_OPERAND (t, 0), C_ORT_OMP, args,
19469 				  complain, in_decl);
19470       if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
19471 	{
19472 	  tree op1 = TREE_OPERAND (t, 1);
19473 	  tree rhs1 = NULL_TREE;
19474 	  tree r = NULL_TREE;
19475 	  tree lhs, rhs;
19476 	  if (TREE_CODE (op1) == COMPOUND_EXPR)
19477 	    {
19478 	      rhs1 = RECUR (TREE_OPERAND (op1, 0));
19479 	      op1 = TREE_OPERAND (op1, 1);
19480 	    }
19481 	  if (TREE_CODE (op1) == COND_EXPR)
19482 	    {
19483 	      gcc_assert (rhs1 == NULL_TREE);
19484 	      tree c = TREE_OPERAND (op1, 0);
19485 	      if (TREE_CODE (c) == MODIFY_EXPR)
19486 		{
19487 		  r = RECUR (TREE_OPERAND (c, 0));
19488 		  c = TREE_OPERAND (c, 1);
19489 		}
19490 	      gcc_assert (TREE_CODE (c) == EQ_EXPR);
19491 	      rhs = RECUR (TREE_OPERAND (c, 1));
19492 	      lhs = RECUR (TREE_OPERAND (op1, 2));
19493 	      rhs1 = RECUR (TREE_OPERAND (op1, 1));
19494 	    }
19495 	  else
19496 	    {
19497 	      lhs = RECUR (TREE_OPERAND (op1, 0));
19498 	      rhs = RECUR (TREE_OPERAND (op1, 1));
19499 	    }
19500 	  finish_omp_atomic (EXPR_LOCATION (t), OMP_ATOMIC, TREE_CODE (op1),
19501 			     lhs, rhs, NULL_TREE, NULL_TREE, rhs1, r,
19502 			     tmp, OMP_ATOMIC_MEMORY_ORDER (t),
19503 			     OMP_ATOMIC_WEAK (t));
19504 	}
19505       else
19506 	{
19507 	  tree op1 = TREE_OPERAND (t, 1);
19508 	  tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
19509 	  tree rhs1 = NULL_TREE, r = NULL_TREE;
19510 	  enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
19511 	  enum tree_code opcode = NOP_EXPR;
19512 	  if (code == OMP_ATOMIC_READ)
19513 	    {
19514 	      v = RECUR (TREE_OPERAND (op1, 0));
19515 	      lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19516 	    }
19517 	  else if (code == OMP_ATOMIC_CAPTURE_OLD
19518 		   || code == OMP_ATOMIC_CAPTURE_NEW)
19519 	    {
19520 	      tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
19521 	      v = RECUR (TREE_OPERAND (op1, 0));
19522 	      lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19523 	      if (TREE_CODE (op11) == COMPOUND_EXPR)
19524 		{
19525 		  rhs1 = RECUR (TREE_OPERAND (op11, 0));
19526 		  op11 = TREE_OPERAND (op11, 1);
19527 		}
19528 	      if (TREE_CODE (op11) == COND_EXPR)
19529 		{
19530 		  gcc_assert (rhs1 == NULL_TREE);
19531 		  tree c = TREE_OPERAND (op11, 0);
19532 		  if (TREE_CODE (c) == MODIFY_EXPR)
19533 		    {
19534 		      r = RECUR (TREE_OPERAND (c, 0));
19535 		      c = TREE_OPERAND (c, 1);
19536 		    }
19537 		  gcc_assert (TREE_CODE (c) == EQ_EXPR);
19538 		  rhs = RECUR (TREE_OPERAND (c, 1));
19539 		  lhs = RECUR (TREE_OPERAND (op11, 2));
19540 		  rhs1 = RECUR (TREE_OPERAND (op11, 1));
19541 		}
19542 	      else
19543 		{
19544 		  lhs = RECUR (TREE_OPERAND (op11, 0));
19545 		  rhs = RECUR (TREE_OPERAND (op11, 1));
19546 		}
19547 	      opcode = TREE_CODE (op11);
19548 	      if (opcode == MODIFY_EXPR)
19549 		opcode = NOP_EXPR;
19550 	    }
19551 	  else
19552 	    {
19553 	      code = OMP_ATOMIC;
19554 	      lhs = RECUR (TREE_OPERAND (op1, 0));
19555 	      rhs = RECUR (TREE_OPERAND (op1, 1));
19556 	    }
19557 	  finish_omp_atomic (EXPR_LOCATION (t), code, opcode, lhs, rhs, v,
19558 			     lhs1, rhs1, r, tmp,
19559 			     OMP_ATOMIC_MEMORY_ORDER (t), OMP_ATOMIC_WEAK (t));
19560 	}
19561       break;
19562 
19563     case TRANSACTION_EXPR:
19564       {
19565 	int flags = 0;
19566 	flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
19567 	flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
19568 
19569         if (TRANSACTION_EXPR_IS_STMT (t))
19570           {
19571 	    tree body = TRANSACTION_EXPR_BODY (t);
19572 	    tree noex = NULL_TREE;
19573 	    if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
19574 	      {
19575 		noex = MUST_NOT_THROW_COND (body);
19576 		if (noex == NULL_TREE)
19577 		  noex = boolean_true_node;
19578 		body = TREE_OPERAND (body, 0);
19579 	      }
19580             stmt = begin_transaction_stmt (input_location, NULL, flags);
19581             RECUR (body);
19582             finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
19583           }
19584         else
19585           {
19586             stmt = build_transaction_expr (EXPR_LOCATION (t),
19587 					   RECUR (TRANSACTION_EXPR_BODY (t)),
19588 					   flags, NULL_TREE);
19589             RETURN (stmt);
19590           }
19591       }
19592       break;
19593 
19594     case MUST_NOT_THROW_EXPR:
19595       {
19596 	tree op0 = RECUR (TREE_OPERAND (t, 0));
19597 	tree cond = RECUR (MUST_NOT_THROW_COND (t));
19598 	RETURN (build_must_not_throw_expr (op0, cond));
19599       }
19600 
19601     case EXPR_PACK_EXPANSION:
19602       error ("invalid use of pack expansion expression");
19603       RETURN (error_mark_node);
19604 
19605     case NONTYPE_ARGUMENT_PACK:
19606       error ("use %<...%> to expand argument pack");
19607       RETURN (error_mark_node);
19608 
19609     case COMPOUND_EXPR:
19610       tmp = RECUR (TREE_OPERAND (t, 0));
19611       if (tmp == NULL_TREE)
19612 	/* If the first operand was a statement, we're done with it.  */
19613 	RETURN (RECUR (TREE_OPERAND (t, 1)));
19614       RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
19615 				    RECUR (TREE_OPERAND (t, 1)),
19616 				    templated_operator_saved_lookups (t),
19617 				    complain));
19618 
19619     case PREDICT_EXPR:
19620       RETURN (add_stmt (copy_node (t)));
19621 
19622     default:
19623       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
19624 
19625       RETURN (tsubst_copy_and_build (t, args, complain, in_decl,
19626 				    /*function_p=*/false,
19627 				    integral_constant_expression_p));
19628     }
19629 
19630   RETURN (NULL_TREE);
19631  out:
19632   input_location = loc;
19633   return r;
19634 #undef RECUR
19635 #undef RETURN
19636 }
19637 
19638 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
19639    function.  For description of the body see comment above
19640    cp_parser_omp_declare_reduction_exprs.  */
19641 
19642 static void
tsubst_omp_udr(tree t,tree args,tsubst_flags_t complain,tree in_decl)19643 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19644 {
19645   if (t == NULL_TREE || t == error_mark_node)
19646     return;
19647 
19648   gcc_assert (TREE_CODE (t) == STATEMENT_LIST && current_function_decl);
19649 
19650   tree_stmt_iterator tsi;
19651   int i;
19652   tree stmts[7];
19653   memset (stmts, 0, sizeof stmts);
19654   for (i = 0, tsi = tsi_start (t);
19655        i < 7 && !tsi_end_p (tsi);
19656        i++, tsi_next (&tsi))
19657     stmts[i] = tsi_stmt (tsi);
19658   gcc_assert (tsi_end_p (tsi));
19659 
19660   if (i >= 3)
19661     {
19662       gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
19663 		  && TREE_CODE (stmts[1]) == DECL_EXPR);
19664       tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
19665 			     args, complain, in_decl);
19666       tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
19667 			    args, complain, in_decl);
19668       /* tsubsting a local var_decl leaves DECL_CONTEXT null, as we
19669 	 expect to be pushing it.  */
19670       DECL_CONTEXT (omp_out) = current_function_decl;
19671       DECL_CONTEXT (omp_in) = current_function_decl;
19672       keep_next_level (true);
19673       tree block = begin_omp_structured_block ();
19674       tsubst_expr (stmts[2], args, complain, in_decl, false);
19675       block = finish_omp_structured_block (block);
19676       block = maybe_cleanup_point_expr_void (block);
19677       add_decl_expr (omp_out);
19678       copy_warning (omp_out, DECL_EXPR_DECL (stmts[0]));
19679       add_decl_expr (omp_in);
19680       finish_expr_stmt (block);
19681     }
19682   if (i >= 6)
19683     {
19684       gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
19685 		  && TREE_CODE (stmts[4]) == DECL_EXPR);
19686       tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
19687 			      args, complain, in_decl);
19688       tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
19689 			      args, complain, in_decl);
19690       DECL_CONTEXT (omp_priv) = current_function_decl;
19691       DECL_CONTEXT (omp_orig) = current_function_decl;
19692       keep_next_level (true);
19693       tree block = begin_omp_structured_block ();
19694       tsubst_expr (stmts[5], args, complain, in_decl, false);
19695       block = finish_omp_structured_block (block);
19696       block = maybe_cleanup_point_expr_void (block);
19697       cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
19698       add_decl_expr (omp_priv);
19699       add_decl_expr (omp_orig);
19700       finish_expr_stmt (block);
19701       if (i == 7)
19702 	add_decl_expr (omp_orig);
19703     }
19704 }
19705 
19706 /* T is a postfix-expression that is not being used in a function
19707    call.  Return the substituted version of T.  */
19708 
19709 static tree
tsubst_non_call_postfix_expression(tree t,tree args,tsubst_flags_t complain,tree in_decl)19710 tsubst_non_call_postfix_expression (tree t, tree args,
19711 				    tsubst_flags_t complain,
19712 				    tree in_decl)
19713 {
19714   if (TREE_CODE (t) == SCOPE_REF)
19715     t = tsubst_qualified_id (t, args, complain, in_decl,
19716 			     /*done=*/false, /*address_p=*/false);
19717   else
19718     t = tsubst_copy_and_build (t, args, complain, in_decl,
19719 			       /*function_p=*/false,
19720 			       /*integral_constant_expression_p=*/false);
19721 
19722   return t;
19723 }
19724 
19725 /* Subroutine of tsubst_lambda_expr: add the FIELD/INIT capture pair to the
19726    LAMBDA_EXPR_CAPTURE_LIST passed in LIST.  Do deduction for a previously
19727    dependent init-capture.  EXPLICIT_P is true if the original list had
19728    explicit captures.  */
19729 
19730 static void
prepend_one_capture(tree field,tree init,tree & list,bool explicit_p,tsubst_flags_t complain)19731 prepend_one_capture (tree field, tree init, tree &list, bool explicit_p,
19732 		     tsubst_flags_t complain)
19733 {
19734   if (tree auto_node = type_uses_auto (TREE_TYPE (field)))
19735     {
19736       tree type = NULL_TREE;
19737       if (!init)
19738 	{
19739 	  if (complain & tf_error)
19740 	    error ("empty initializer in lambda init-capture");
19741 	  init = error_mark_node;
19742 	}
19743       else if (TREE_CODE (init) == TREE_LIST)
19744 	init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19745       if (!type)
19746 	type = do_auto_deduction (TREE_TYPE (field), init, auto_node, complain);
19747       TREE_TYPE (field) = type;
19748       cp_apply_type_quals_to_decl (cp_type_quals (type), field);
19749     }
19750   list = tree_cons (field, init, list);
19751   LAMBDA_CAPTURE_EXPLICIT_P (list) = explicit_p;
19752 }
19753 
19754 /* T is a LAMBDA_EXPR.  Generate a new LAMBDA_EXPR for the current
19755    instantiation context.  Instantiating a pack expansion containing a lambda
19756    might result in multiple lambdas all based on the same lambda in the
19757    template.  */
19758 
19759 tree
tsubst_lambda_expr(tree t,tree args,tsubst_flags_t complain,tree in_decl)19760 tsubst_lambda_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19761 {
19762   tree oldfn = lambda_function (t);
19763   in_decl = oldfn;
19764 
19765   tree r = build_lambda_expr ();
19766 
19767   LAMBDA_EXPR_LOCATION (r)
19768     = LAMBDA_EXPR_LOCATION (t);
19769   LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
19770     = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
19771   LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
19772   if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
19773     LAMBDA_EXPR_REGEN_INFO (r)
19774       = build_template_info (t, add_to_template_args (TI_ARGS (ti),
19775 						      preserve_args (args)));
19776   else
19777     LAMBDA_EXPR_REGEN_INFO (r)
19778       = build_template_info (t, preserve_args (args));
19779 
19780   gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
19781 	      && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
19782 
19783   vec<tree,va_gc>* field_packs = NULL;
19784 
19785   for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t); cap;
19786        cap = TREE_CHAIN (cap))
19787     {
19788       tree ofield = TREE_PURPOSE (cap);
19789       tree init = TREE_VALUE (cap);
19790       if (PACK_EXPANSION_P (init))
19791 	init = tsubst_pack_expansion (init, args, complain, in_decl);
19792       else
19793 	init = tsubst_copy_and_build (init, args, complain, in_decl,
19794 				      /*fn*/false, /*constexpr*/false);
19795 
19796       if (init == error_mark_node)
19797 	return error_mark_node;
19798 
19799       if (init && TREE_CODE (init) == TREE_LIST)
19800 	init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19801 
19802       if (!processing_template_decl
19803 	  && init && TREE_CODE (init) != TREE_VEC
19804 	  && variably_modified_type_p (TREE_TYPE (init), NULL_TREE))
19805 	{
19806 	  /* For a VLA, simply tsubsting the field type won't work, we need to
19807 	     go through add_capture again.  XXX do we want to do this for all
19808 	     captures?  */
19809 	  tree name = (get_identifier
19810 		       (IDENTIFIER_POINTER (DECL_NAME (ofield)) + 2));
19811 	  tree ftype = TREE_TYPE (ofield);
19812 	  bool by_ref = (TYPE_REF_P (ftype)
19813 			 || (TREE_CODE (ftype) == DECLTYPE_TYPE
19814 			     && DECLTYPE_FOR_REF_CAPTURE (ftype)));
19815 	  add_capture (r, name, init, by_ref, !DECL_NORMAL_CAPTURE_P (ofield));
19816 	  continue;
19817 	}
19818 
19819       if (PACK_EXPANSION_P (ofield))
19820 	ofield = PACK_EXPANSION_PATTERN (ofield);
19821       tree field = tsubst_decl (ofield, args, complain);
19822 
19823       if (DECL_PACK_P (ofield) && !DECL_NORMAL_CAPTURE_P (ofield))
19824 	{
19825 	  /* Remember these for when we've pushed local_specializations.  */
19826 	  vec_safe_push (field_packs, ofield);
19827 	  vec_safe_push (field_packs, field);
19828 	}
19829 
19830       if (field == error_mark_node)
19831 	return error_mark_node;
19832 
19833       if (TREE_CODE (field) == TREE_VEC)
19834 	{
19835 	  int len = TREE_VEC_LENGTH (field);
19836 	  gcc_assert (TREE_CODE (init) == TREE_VEC
19837 		      && TREE_VEC_LENGTH (init) == len);
19838 	  for (int i = 0; i < len; ++i)
19839 	    prepend_one_capture (TREE_VEC_ELT (field, i),
19840 				 TREE_VEC_ELT (init, i),
19841 				 LAMBDA_EXPR_CAPTURE_LIST (r),
19842 				 LAMBDA_CAPTURE_EXPLICIT_P (cap),
19843 				 complain);
19844 	}
19845       else
19846 	{
19847 	  prepend_one_capture (field, init, LAMBDA_EXPR_CAPTURE_LIST (r),
19848 			       LAMBDA_CAPTURE_EXPLICIT_P (cap), complain);
19849 
19850 	  if (id_equal (DECL_NAME (field), "__this"))
19851 	    LAMBDA_EXPR_THIS_CAPTURE (r) = field;
19852 	}
19853     }
19854 
19855   tree type = begin_lambda_type (r);
19856   if (type == error_mark_node)
19857     return error_mark_node;
19858 
19859   if (LAMBDA_EXPR_EXTRA_SCOPE (t) == NULL_TREE)
19860     {
19861       /* A lambda in a default argument outside a class gets no
19862 	 LAMBDA_EXPR_EXTRA_SCOPE, as specified by the ABI.  But
19863 	 tsubst_default_argument calls start_lambda_scope, so we need to
19864 	 specifically ignore it here, and use the global scope.  */
19865       record_null_lambda_scope (r);
19866 
19867       /* If we're pushed into another scope (PR105652), fix it.  */
19868       if (TYPE_NAMESPACE_SCOPE_P (TREE_TYPE (t)))
19869 	TYPE_CONTEXT (type) = DECL_CONTEXT (TYPE_NAME (type))
19870 	  = TYPE_CONTEXT (TREE_TYPE (t));
19871     }
19872   else
19873     record_lambda_scope (r);
19874 
19875   /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
19876   determine_visibility (TYPE_NAME (type));
19877 
19878   register_capture_members (LAMBDA_EXPR_CAPTURE_LIST (r));
19879 
19880   tree oldtmpl = (generic_lambda_fn_p (oldfn)
19881 		  ? DECL_TI_TEMPLATE (oldfn)
19882 		  : NULL_TREE);
19883 
19884   tree fntype = static_fn_type (oldfn);
19885   if (oldtmpl)
19886     ++processing_template_decl;
19887   fntype = tsubst (fntype, args, complain, in_decl);
19888   if (oldtmpl)
19889     --processing_template_decl;
19890 
19891   if (fntype == error_mark_node)
19892     r = error_mark_node;
19893   else
19894     {
19895       /* The body of a lambda-expression is not a subexpression of the
19896 	 enclosing expression.  Parms are to have DECL_CHAIN tsubsted,
19897 	 which would be skipped if cp_unevaluated_operand.  */
19898       cp_evaluated ev;
19899 
19900       /* Fix the type of 'this'.  */
19901       fntype = build_memfn_type (fntype, type,
19902 				 type_memfn_quals (fntype),
19903 				 type_memfn_rqual (fntype));
19904       tree fn, tmpl;
19905       if (oldtmpl)
19906 	{
19907 	  tmpl = tsubst_template_decl (oldtmpl, args, complain, fntype);
19908 	  if (tmpl == error_mark_node)
19909 	    {
19910 	      r = error_mark_node;
19911 	      goto out;
19912 	    }
19913 	  fn = DECL_TEMPLATE_RESULT (tmpl);
19914 	  finish_member_declaration (tmpl);
19915 	}
19916       else
19917 	{
19918 	  tmpl = NULL_TREE;
19919 	  fn = tsubst_function_decl (oldfn, args, complain, fntype);
19920 	  if (fn == error_mark_node)
19921 	    {
19922 	      r = error_mark_node;
19923 	      goto out;
19924 	    }
19925 	  finish_member_declaration (fn);
19926 	}
19927 
19928       /* Let finish_function set this.  */
19929       DECL_DECLARED_CONSTEXPR_P (fn) = false;
19930 
19931       bool nested = cfun;
19932       if (nested)
19933 	push_function_context ();
19934       else
19935 	/* Still increment function_depth so that we don't GC in the
19936 	   middle of an expression.  */
19937 	++function_depth;
19938 
19939       local_specialization_stack s (lss_copy);
19940 
19941       bool save_in_consteval_if_p = in_consteval_if_p;
19942       in_consteval_if_p = false;
19943 
19944       tree body = start_lambda_function (fn, r);
19945 
19946       /* Now record them for lookup_init_capture_pack.  */
19947       int fplen = vec_safe_length (field_packs);
19948       for (int i = 0; i < fplen; )
19949 	{
19950 	  tree pack = (*field_packs)[i++];
19951 	  tree inst = (*field_packs)[i++];
19952 	  register_local_specialization (inst, pack);
19953 	}
19954       release_tree_vector (field_packs);
19955 
19956       register_parameter_specializations (oldfn, fn);
19957 
19958       if (oldtmpl)
19959 	{
19960 	  /* We might not partially instantiate some parts of the function, so
19961 	     copy these flags from the original template.  */
19962 	  language_function *ol = DECL_STRUCT_FUNCTION (oldfn)->language;
19963 	  current_function_returns_value = ol->returns_value;
19964 	  current_function_returns_null = ol->returns_null;
19965 	  current_function_returns_abnormally = ol->returns_abnormally;
19966 	  current_function_infinite_loop = ol->infinite_loop;
19967 	}
19968 
19969       /* [temp.deduct] A lambda-expression appearing in a function type or a
19970 	 template parameter is not considered part of the immediate context for
19971 	 the purposes of template argument deduction. */
19972       complain = tf_warning_or_error;
19973 
19974       tree saved = DECL_SAVED_TREE (oldfn);
19975       if (TREE_CODE (saved) == BIND_EXPR && BIND_EXPR_BODY_BLOCK (saved))
19976 	/* We already have a body block from start_lambda_function, we don't
19977 	   need another to confuse NRV (91217).  */
19978 	saved = BIND_EXPR_BODY (saved);
19979 
19980       tsubst_expr (saved, args, complain, r, /*constexpr*/false);
19981 
19982       finish_lambda_function (body);
19983 
19984       in_consteval_if_p = save_in_consteval_if_p;
19985 
19986       if (nested)
19987 	pop_function_context ();
19988       else
19989 	--function_depth;
19990 
19991       /* The capture list was built up in reverse order; fix that now.  */
19992       LAMBDA_EXPR_CAPTURE_LIST (r)
19993 	= nreverse (LAMBDA_EXPR_CAPTURE_LIST (r));
19994 
19995       LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
19996 
19997       maybe_add_lambda_conv_op (type);
19998     }
19999 
20000 out:
20001   finish_struct (type, /*attr*/NULL_TREE);
20002 
20003   insert_pending_capture_proxies ();
20004 
20005   return r;
20006 }
20007 
20008 /* Subroutine of maybe_fold_fn_template_args.  */
20009 
20010 static bool
fold_targs_r(tree targs,tsubst_flags_t complain)20011 fold_targs_r (tree targs, tsubst_flags_t complain)
20012 {
20013   int len = TREE_VEC_LENGTH (targs);
20014   for (int i = 0; i < len; ++i)
20015     {
20016       tree &elt = TREE_VEC_ELT (targs, i);
20017       if (!elt || TYPE_P (elt)
20018 	  || TREE_CODE (elt) == TEMPLATE_DECL)
20019 	continue;
20020       if (TREE_CODE (elt) == NONTYPE_ARGUMENT_PACK)
20021 	{
20022 	  if (!fold_targs_r (ARGUMENT_PACK_ARGS (elt), complain))
20023 	    return false;
20024 	}
20025       else if (/* We can only safely preevaluate scalar prvalues.  */
20026 	       SCALAR_TYPE_P (TREE_TYPE (elt))
20027 	       && !glvalue_p (elt)
20028 	       && !TREE_CONSTANT (elt))
20029 	{
20030 	  elt = cxx_constant_value_sfinae (elt, NULL_TREE, complain);
20031 	  if (elt == error_mark_node)
20032 	    return false;
20033 	}
20034     }
20035 
20036   return true;
20037 }
20038 
20039 /* Try to do constant evaluation of any explicit template arguments in FN
20040    before overload resolution, to get any errors only once.  Return true iff
20041    we didn't have any problems folding.  */
20042 
20043 static bool
maybe_fold_fn_template_args(tree fn,tsubst_flags_t complain)20044 maybe_fold_fn_template_args (tree fn, tsubst_flags_t complain)
20045 {
20046   if (processing_template_decl || fn == NULL_TREE)
20047     return true;
20048   if (fn == error_mark_node)
20049     return false;
20050   if (TREE_CODE (fn) == OFFSET_REF
20051       || TREE_CODE (fn) == COMPONENT_REF)
20052     fn = TREE_OPERAND (fn, 1);
20053   if (BASELINK_P (fn))
20054     fn = BASELINK_FUNCTIONS (fn);
20055   if (TREE_CODE (fn) != TEMPLATE_ID_EXPR)
20056     return true;
20057   tree targs = TREE_OPERAND (fn, 1);
20058   if (targs == NULL_TREE)
20059     return true;
20060   if (targs == error_mark_node)
20061     return false;
20062   return fold_targs_r (targs, complain);
20063 }
20064 
20065 /* Helper function for tsubst_copy_and_build CALL_EXPR and ARRAY_REF
20066    handling.  */
20067 
20068 static void
tsubst_copy_and_build_call_args(tree t,tree args,tsubst_flags_t complain,tree in_decl,bool integral_constant_expression_p,releasing_vec & call_args)20069 tsubst_copy_and_build_call_args (tree t, tree args, tsubst_flags_t complain,
20070 				 tree in_decl,
20071 				 bool integral_constant_expression_p,
20072 				 releasing_vec &call_args)
20073 {
20074   unsigned int nargs = call_expr_nargs (t);
20075   for (unsigned int i = 0; i < nargs; ++i)
20076     {
20077       tree arg = CALL_EXPR_ARG (t, i);
20078 
20079       if (!PACK_EXPANSION_P (arg))
20080 	vec_safe_push (call_args,
20081 		       tsubst_copy_and_build (arg, args, complain, in_decl,
20082 					      /*function_p=*/false,
20083 					      integral_constant_expression_p));
20084       else
20085 	{
20086 	  /* Expand the pack expansion and push each entry onto CALL_ARGS.  */
20087 	  arg = tsubst_pack_expansion (arg, args, complain, in_decl);
20088 	  if (TREE_CODE (arg) == TREE_VEC)
20089 	    {
20090 	      unsigned int len, j;
20091 
20092 	      len = TREE_VEC_LENGTH (arg);
20093 	      for (j = 0; j < len; ++j)
20094 		{
20095 		  tree value = TREE_VEC_ELT (arg, j);
20096 		  if (value != NULL_TREE)
20097 		    value = convert_from_reference (value);
20098 		  vec_safe_push (call_args, value);
20099 		}
20100 	    }
20101 	  else
20102 	    /* A partial substitution.  Add one entry.  */
20103 	    vec_safe_push (call_args, arg);
20104 	}
20105     }
20106 }
20107 
20108 /* Like tsubst but deals with expressions and performs semantic
20109    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)" or
20110    "F<TARGS> (ARGS)".  */
20111 
20112 tree
tsubst_copy_and_build(tree t,tree args,tsubst_flags_t complain,tree in_decl,bool function_p,bool integral_constant_expression_p)20113 tsubst_copy_and_build (tree t,
20114 		       tree args,
20115 		       tsubst_flags_t complain,
20116 		       tree in_decl,
20117 		       bool function_p,
20118 		       bool integral_constant_expression_p)
20119 {
20120 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
20121 #define RECUR(NODE)						\
20122   tsubst_copy_and_build (NODE, args, complain, in_decl, 	\
20123 			 /*function_p=*/false,			\
20124 			 integral_constant_expression_p)
20125 
20126   tree retval, op1;
20127   location_t save_loc;
20128 
20129   if (t == NULL_TREE || t == error_mark_node)
20130     return t;
20131 
20132   save_loc = input_location;
20133   if (location_t eloc = cp_expr_location (t))
20134     input_location = eloc;
20135 
20136   /* N3276 decltype magic only applies to calls at the top level or on the
20137      right side of a comma.  */
20138   tsubst_flags_t decltype_flag = (complain & tf_decltype);
20139   complain &= ~tf_decltype;
20140 
20141   switch (TREE_CODE (t))
20142     {
20143     case USING_DECL:
20144       t = DECL_NAME (t);
20145       /* Fall through.  */
20146     case IDENTIFIER_NODE:
20147       {
20148 	tree decl;
20149 	cp_id_kind idk;
20150 	bool non_integral_constant_expression_p;
20151 	const char *error_msg;
20152 
20153 	if (IDENTIFIER_CONV_OP_P (t))
20154 	  {
20155 	    tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20156 	    t = make_conv_op_name (new_type);
20157 	  }
20158 
20159 	/* Look up the name.  */
20160 	decl = lookup_name (t);
20161 
20162 	/* By convention, expressions use ERROR_MARK_NODE to indicate
20163 	   failure, not NULL_TREE.  */
20164 	if (decl == NULL_TREE)
20165 	  decl = error_mark_node;
20166 
20167 	decl = finish_id_expression (t, decl, NULL_TREE,
20168 				     &idk,
20169 				     integral_constant_expression_p,
20170           /*allow_non_integral_constant_expression_p=*/(cxx_dialect >= cxx11),
20171 				     &non_integral_constant_expression_p,
20172 				     /*template_p=*/false,
20173 				     /*done=*/true,
20174 				     /*address_p=*/false,
20175 				     /*template_arg_p=*/false,
20176 				     &error_msg,
20177 				     input_location);
20178 	if (error_msg)
20179 	  error (error_msg);
20180 	if (!function_p && identifier_p (decl))
20181 	  {
20182 	    if (complain & tf_error)
20183 	      unqualified_name_lookup_error (decl);
20184 	    decl = error_mark_node;
20185 	  }
20186 	RETURN (decl);
20187       }
20188 
20189     case TEMPLATE_ID_EXPR:
20190       {
20191 	tree object;
20192 	tree templ = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
20193 					    complain, in_decl,
20194 					    function_p,
20195 					    integral_constant_expression_p);
20196 	tree targs = TREE_OPERAND (t, 1);
20197 
20198 	if (targs)
20199 	  targs = tsubst_template_args (targs, args, complain, in_decl);
20200 	if (targs == error_mark_node)
20201 	  RETURN (error_mark_node);
20202 
20203 	if (TREE_CODE (templ) == SCOPE_REF)
20204 	  {
20205 	    tree name = TREE_OPERAND (templ, 1);
20206 	    tree tid = lookup_template_function (name, targs);
20207 	    TREE_OPERAND (templ, 1) = tid;
20208 	    RETURN (templ);
20209 	  }
20210 
20211 	if (concept_definition_p (templ))
20212 	  {
20213 	    tree check = build_concept_check (templ, targs, complain);
20214 	    if (check == error_mark_node)
20215 	      RETURN (error_mark_node);
20216 
20217 	    tree id = unpack_concept_check (check);
20218 
20219 	    /* If we built a function concept check, return the underlying
20220 	       template-id. So we can evaluate it as a function call.  */
20221 	    if (function_concept_p (TREE_OPERAND (id, 0)))
20222 	      RETURN (id);
20223 
20224 	    RETURN (check);
20225 	  }
20226 
20227 	if (variable_template_p (templ))
20228 	  {
20229 	    tree r = lookup_and_finish_template_variable (templ, targs,
20230 							  complain);
20231 	    r = maybe_wrap_with_location (r, EXPR_LOCATION (t));
20232 	    RETURN (r);
20233 	  }
20234 
20235 	if (TREE_CODE (templ) == COMPONENT_REF)
20236 	  {
20237 	    object = TREE_OPERAND (templ, 0);
20238 	    templ = TREE_OPERAND (templ, 1);
20239 	  }
20240 	else
20241 	  object = NULL_TREE;
20242 
20243 	tree tid = lookup_template_function (templ, targs);
20244 
20245 	if (object)
20246 	  RETURN (build3 (COMPONENT_REF, TREE_TYPE (tid),
20247 			 object, tid, NULL_TREE));
20248 	else if (identifier_p (templ))
20249 	  {
20250 	    /* C++20 P0846: we can encounter an IDENTIFIER_NODE here when
20251 	       name lookup found nothing when parsing the template name.  */
20252 	    gcc_assert (cxx_dialect >= cxx20 || seen_error ());
20253 	    RETURN (tid);
20254 	  }
20255 	else
20256 	  RETURN (baselink_for_fns (tid));
20257       }
20258 
20259     case INDIRECT_REF:
20260       {
20261 	tree r = RECUR (TREE_OPERAND (t, 0));
20262 
20263 	if (REFERENCE_REF_P (t))
20264 	  {
20265 	    /* A type conversion to reference type will be enclosed in
20266 	       such an indirect ref, but the substitution of the cast
20267 	       will have also added such an indirect ref.  */
20268 	    r = convert_from_reference (r);
20269 	  }
20270 	else
20271 	  r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
20272 				    templated_operator_saved_lookups (t),
20273 				    complain|decltype_flag);
20274 
20275 	if (REF_PARENTHESIZED_P (t))
20276 	  r = force_paren_expr (r);
20277 
20278 	RETURN (r);
20279       }
20280 
20281     case NOP_EXPR:
20282       {
20283 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20284 	tree op0 = RECUR (TREE_OPERAND (t, 0));
20285 	RETURN (build_nop (type, op0));
20286       }
20287 
20288     case IMPLICIT_CONV_EXPR:
20289       {
20290 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20291 	tree expr = RECUR (TREE_OPERAND (t, 0));
20292 	if (dependent_type_p (type) || type_dependent_expression_p (expr))
20293 	  {
20294 	    retval = copy_node (t);
20295 	    TREE_TYPE (retval) = type;
20296 	    TREE_OPERAND (retval, 0) = expr;
20297 	    RETURN (retval);
20298 	  }
20299 	if (IMPLICIT_CONV_EXPR_NONTYPE_ARG (t))
20300 	  /* We'll pass this to convert_nontype_argument again, we don't need
20301 	     to actually perform any conversion here.  */
20302 	  RETURN (expr);
20303 	int flags = LOOKUP_IMPLICIT;
20304 	if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
20305 	  flags = LOOKUP_NORMAL;
20306 	if (IMPLICIT_CONV_EXPR_BRACED_INIT (t))
20307 	  flags |= LOOKUP_NO_NARROWING;
20308 	RETURN (perform_implicit_conversion_flags (type, expr, complain,
20309 						  flags));
20310       }
20311 
20312     case CONVERT_EXPR:
20313       {
20314 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20315 	tree op0 = RECUR (TREE_OPERAND (t, 0));
20316 	if (op0 == error_mark_node)
20317 	  RETURN (error_mark_node);
20318 	RETURN (build1 (CONVERT_EXPR, type, op0));
20319       }
20320 
20321     case CAST_EXPR:
20322     case REINTERPRET_CAST_EXPR:
20323     case CONST_CAST_EXPR:
20324     case DYNAMIC_CAST_EXPR:
20325     case STATIC_CAST_EXPR:
20326       {
20327 	tree type;
20328 	tree op, r = NULL_TREE;
20329 
20330 	tsubst_flags_t tcomplain = complain;
20331 	if (TREE_CODE (t) == CAST_EXPR)
20332 	  tcomplain |= tf_tst_ok;
20333 	type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
20334 	if (integral_constant_expression_p
20335 	    && !cast_valid_in_integral_constant_expression_p (type))
20336 	  {
20337             if (complain & tf_error)
20338               error ("a cast to a type other than an integral or "
20339                      "enumeration type cannot appear in a constant-expression");
20340 	    RETURN (error_mark_node);
20341 	  }
20342 
20343 	op = RECUR (TREE_OPERAND (t, 0));
20344 
20345 	warning_sentinel s(warn_useless_cast);
20346 	warning_sentinel s2(warn_ignored_qualifiers);
20347 	warning_sentinel s3(warn_int_in_bool_context);
20348 	switch (TREE_CODE (t))
20349 	  {
20350 	  case CAST_EXPR:
20351 	    r = build_functional_cast (input_location, type, op, complain);
20352 	    break;
20353 	  case REINTERPRET_CAST_EXPR:
20354 	    r = build_reinterpret_cast (input_location, type, op, complain);
20355 	    break;
20356 	  case CONST_CAST_EXPR:
20357 	    r = build_const_cast (input_location, type, op, complain);
20358 	    break;
20359 	  case DYNAMIC_CAST_EXPR:
20360 	    r = build_dynamic_cast (input_location, type, op, complain);
20361 	    break;
20362 	  case STATIC_CAST_EXPR:
20363 	    r = build_static_cast (input_location, type, op, complain);
20364 	    if (IMPLICIT_RVALUE_P (t))
20365 	      set_implicit_rvalue_p (r);
20366 	    break;
20367 	  default:
20368 	    gcc_unreachable ();
20369 	  }
20370 
20371 	RETURN (r);
20372       }
20373 
20374     case BIT_CAST_EXPR:
20375       {
20376 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20377 	tree op0 = RECUR (TREE_OPERAND (t, 0));
20378 	RETURN (cp_build_bit_cast (EXPR_LOCATION (t), type, op0, complain));
20379       }
20380 
20381     case POSTDECREMENT_EXPR:
20382     case POSTINCREMENT_EXPR:
20383       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20384 						args, complain, in_decl);
20385       RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
20386 				templated_operator_saved_lookups (t),
20387 				complain|decltype_flag));
20388 
20389     case PREDECREMENT_EXPR:
20390     case PREINCREMENT_EXPR:
20391     case NEGATE_EXPR:
20392     case BIT_NOT_EXPR:
20393     case ABS_EXPR:
20394     case TRUTH_NOT_EXPR:
20395     case UNARY_PLUS_EXPR:  /* Unary + */
20396     case REALPART_EXPR:
20397     case IMAGPART_EXPR:
20398       RETURN (build_x_unary_op (input_location, TREE_CODE (t),
20399 				RECUR (TREE_OPERAND (t, 0)),
20400 				templated_operator_saved_lookups (t),
20401 				complain|decltype_flag));
20402 
20403     case FIX_TRUNC_EXPR:
20404       /* convert_like should have created an IMPLICIT_CONV_EXPR.  */
20405       gcc_unreachable ();
20406 
20407     case ADDR_EXPR:
20408       op1 = TREE_OPERAND (t, 0);
20409       if (TREE_CODE (op1) == LABEL_DECL)
20410 	RETURN (finish_label_address_expr (DECL_NAME (op1),
20411 					  EXPR_LOCATION (op1)));
20412       if (TREE_CODE (op1) == SCOPE_REF)
20413 	op1 = tsubst_qualified_id (op1, args, complain, in_decl,
20414 				   /*done=*/true, /*address_p=*/true);
20415       else
20416 	op1 = tsubst_non_call_postfix_expression (op1, args, complain,
20417 						  in_decl);
20418       RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
20419 				templated_operator_saved_lookups (t),
20420 				complain|decltype_flag));
20421 
20422     case PLUS_EXPR:
20423     case MINUS_EXPR:
20424     case MULT_EXPR:
20425     case TRUNC_DIV_EXPR:
20426     case CEIL_DIV_EXPR:
20427     case FLOOR_DIV_EXPR:
20428     case ROUND_DIV_EXPR:
20429     case EXACT_DIV_EXPR:
20430     case BIT_AND_EXPR:
20431     case BIT_IOR_EXPR:
20432     case BIT_XOR_EXPR:
20433     case TRUNC_MOD_EXPR:
20434     case FLOOR_MOD_EXPR:
20435     case TRUTH_ANDIF_EXPR:
20436     case TRUTH_ORIF_EXPR:
20437     case TRUTH_AND_EXPR:
20438     case TRUTH_OR_EXPR:
20439     case RSHIFT_EXPR:
20440     case LSHIFT_EXPR:
20441     case EQ_EXPR:
20442     case NE_EXPR:
20443     case MAX_EXPR:
20444     case MIN_EXPR:
20445     case LE_EXPR:
20446     case GE_EXPR:
20447     case LT_EXPR:
20448     case GT_EXPR:
20449     case SPACESHIP_EXPR:
20450     case MEMBER_REF:
20451     case DOTSTAR_EXPR:
20452       {
20453 	/* If either OP0 or OP1 was value- or type-dependent, suppress
20454 	   warnings that depend on the range of the types involved.  */
20455 	tree op0 = TREE_OPERAND (t, 0);
20456 	tree op1 = TREE_OPERAND (t, 1);
20457 	auto dep_p = [](tree t) {
20458 	  ++processing_template_decl;
20459 	  bool r = (potential_constant_expression (t)
20460 		    ? value_dependent_expression_p (t)
20461 		    : type_dependent_expression_p (t));
20462 	  --processing_template_decl;
20463 	  return r;
20464 	};
20465 	const bool was_dep = dep_p (op0) || dep_p (op1);
20466 	op0 = RECUR (op0);
20467 	op1 = RECUR (op1);
20468 
20469 	warning_sentinel s1(warn_type_limits, was_dep);
20470 	warning_sentinel s2(warn_div_by_zero, was_dep);
20471 	warning_sentinel s3(warn_logical_op, was_dep);
20472 	warning_sentinel s4(warn_tautological_compare, was_dep);
20473 	warning_sentinel s5(warn_address, was_dep);
20474 
20475 	tree r = build_x_binary_op
20476 	  (input_location, TREE_CODE (t),
20477 	   op0,
20478 	   (warning_suppressed_p (TREE_OPERAND (t, 0))
20479 	    ? ERROR_MARK
20480 	    : TREE_CODE (TREE_OPERAND (t, 0))),
20481 	   op1,
20482 	   (warning_suppressed_p (TREE_OPERAND (t, 1))
20483 	    ? ERROR_MARK
20484 	    : TREE_CODE (TREE_OPERAND (t, 1))),
20485 	   templated_operator_saved_lookups (t),
20486 	   /*overload=*/NULL,
20487 	   complain|decltype_flag);
20488 	if (EXPR_P (r))
20489 	  copy_warning (r, t);
20490 
20491 	RETURN (r);
20492       }
20493 
20494     case POINTER_PLUS_EXPR:
20495       {
20496 	tree op0 = RECUR (TREE_OPERAND (t, 0));
20497 	if (op0 == error_mark_node)
20498 	  RETURN (error_mark_node);
20499 	tree op1 = RECUR (TREE_OPERAND (t, 1));
20500 	if (op1 == error_mark_node)
20501 	  RETURN (error_mark_node);
20502 	RETURN (fold_build_pointer_plus (op0, op1));
20503       }
20504 
20505     case SCOPE_REF:
20506       RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
20507 				  /*address_p=*/false));
20508 
20509     case BASELINK:
20510       RETURN (tsubst_baselink (t, current_nonlambda_class_type (),
20511 			       args, complain, in_decl));
20512 
20513     case ARRAY_REF:
20514       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20515 						args, complain, in_decl);
20516       if (TREE_CODE (TREE_OPERAND (t, 1)) == CALL_EXPR
20517 	  && (CALL_EXPR_FN (TREE_OPERAND (t, 1))
20518 	      == ovl_op_identifier (ARRAY_REF)))
20519 	{
20520 	  tree c = TREE_OPERAND (t, 1);
20521 	  releasing_vec index_exp_list;
20522 	  tsubst_copy_and_build_call_args (c, args, complain, in_decl,
20523 					   integral_constant_expression_p,
20524 					   index_exp_list);
20525 
20526 	  tree r;
20527 	  if (vec_safe_length (index_exp_list) == 1
20528 	      && !PACK_EXPANSION_P (index_exp_list[0]))
20529 	    r = grok_array_decl (EXPR_LOCATION (t), op1,
20530 				 index_exp_list[0], NULL,
20531 				 complain | decltype_flag);
20532 	  else
20533 	    r = grok_array_decl (EXPR_LOCATION (t), op1,
20534 				 NULL_TREE, &index_exp_list,
20535 				 complain | decltype_flag);
20536 	  RETURN (r);
20537 	}
20538       RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
20539 				 RECUR (TREE_OPERAND (t, 1)),
20540 				 complain|decltype_flag));
20541 
20542     case SIZEOF_EXPR:
20543       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
20544 	  || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
20545 	RETURN (tsubst_copy (t, args, complain, in_decl));
20546       /* Fall through */
20547 
20548     case ALIGNOF_EXPR:
20549       {
20550 	tree r;
20551 
20552 	op1 = TREE_OPERAND (t, 0);
20553 	if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
20554 	  op1 = TREE_TYPE (op1);
20555 	bool std_alignof = (TREE_CODE (t) == ALIGNOF_EXPR
20556 			    && ALIGNOF_EXPR_STD_P (t));
20557         if (!args)
20558 	  {
20559 	    /* When there are no ARGS, we are trying to evaluate a
20560 	       non-dependent expression from the parser.  Trying to do
20561 	       the substitutions may not work.  */
20562 	    if (!TYPE_P (op1))
20563 	      op1 = TREE_TYPE (op1);
20564 	  }
20565 	else
20566 	  {
20567 	    ++cp_unevaluated_operand;
20568 	    ++c_inhibit_evaluation_warnings;
20569 	    if (TYPE_P (op1))
20570 	      op1 = tsubst (op1, args, complain, in_decl);
20571 	    else
20572 	      op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
20573 					   /*function_p=*/false,
20574 					   /*integral_constant_expression_p=*/
20575 					   false);
20576 	    --cp_unevaluated_operand;
20577 	    --c_inhibit_evaluation_warnings;
20578 	  }
20579         if (TYPE_P (op1))
20580 	  r = cxx_sizeof_or_alignof_type (input_location,
20581 					  op1, TREE_CODE (t), std_alignof,
20582 					  complain & tf_error);
20583 	else
20584 	  r = cxx_sizeof_or_alignof_expr (input_location,
20585 					  op1, TREE_CODE (t), std_alignof,
20586 					  complain & tf_error);
20587 	if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
20588 	  {
20589 	    if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
20590 	      {
20591 		if (!processing_template_decl && TYPE_P (op1))
20592 		  {
20593 		    r = build_min (SIZEOF_EXPR, size_type_node,
20594 				   build1 (NOP_EXPR, op1, error_mark_node));
20595 		    SIZEOF_EXPR_TYPE_P (r) = 1;
20596 		  }
20597 		else
20598 		  r = build_min (SIZEOF_EXPR, size_type_node, op1);
20599 		TREE_SIDE_EFFECTS (r) = 0;
20600 		TREE_READONLY (r) = 1;
20601 	      }
20602 	    SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
20603 	  }
20604 	RETURN (r);
20605       }
20606 
20607     case AT_ENCODE_EXPR:
20608       {
20609 	op1 = TREE_OPERAND (t, 0);
20610 	++cp_unevaluated_operand;
20611 	++c_inhibit_evaluation_warnings;
20612 	op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
20613 				     /*function_p=*/false,
20614 				     /*integral_constant_expression_p=*/false);
20615 	--cp_unevaluated_operand;
20616 	--c_inhibit_evaluation_warnings;
20617 	RETURN (objc_build_encode_expr (op1));
20618       }
20619 
20620     case NOEXCEPT_EXPR:
20621       op1 = TREE_OPERAND (t, 0);
20622       ++cp_unevaluated_operand;
20623       ++c_inhibit_evaluation_warnings;
20624       ++cp_noexcept_operand;
20625       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
20626 				   /*function_p=*/false,
20627 				   /*integral_constant_expression_p=*/false);
20628       --cp_unevaluated_operand;
20629       --c_inhibit_evaluation_warnings;
20630       --cp_noexcept_operand;
20631       RETURN (finish_noexcept_expr (op1, complain));
20632 
20633     case MODOP_EXPR:
20634       {
20635 	warning_sentinel s(warn_div_by_zero);
20636 	tree lhs = RECUR (TREE_OPERAND (t, 0));
20637 	tree rhs = RECUR (TREE_OPERAND (t, 2));
20638 
20639 	tree r = build_x_modify_expr
20640 	  (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
20641 	   templated_operator_saved_lookups (t),
20642 	   complain|decltype_flag);
20643 	/* TREE_NO_WARNING must be set if either the expression was
20644 	   parenthesized or it uses an operator such as >>= rather
20645 	   than plain assignment.  In the former case, it was already
20646 	   set and must be copied.  In the latter case,
20647 	   build_x_modify_expr sets it and it must not be reset
20648 	   here.  */
20649 	if (warning_suppressed_p (t, OPT_Wparentheses))
20650 	  suppress_warning (r, OPT_Wparentheses);
20651 
20652 	RETURN (r);
20653       }
20654 
20655     case ARROW_EXPR:
20656       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20657 						args, complain, in_decl);
20658       /* Remember that there was a reference to this entity.  */
20659       if (DECL_P (op1)
20660 	  && !mark_used (op1, complain) && !(complain & tf_error))
20661 	RETURN (error_mark_node);
20662       RETURN (build_x_arrow (input_location, op1, complain));
20663 
20664     case NEW_EXPR:
20665       {
20666 	tree placement = RECUR (TREE_OPERAND (t, 0));
20667 	tree init = RECUR (TREE_OPERAND (t, 3));
20668 	vec<tree, va_gc> *placement_vec;
20669 	vec<tree, va_gc> *init_vec;
20670 	tree ret;
20671 	location_t loc = EXPR_LOCATION (t);
20672 
20673 	if (placement == NULL_TREE)
20674 	  placement_vec = NULL;
20675 	else if (placement == error_mark_node)
20676 	  RETURN (error_mark_node);
20677 	else
20678 	  {
20679 	    placement_vec = make_tree_vector ();
20680 	    for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
20681 	      vec_safe_push (placement_vec, TREE_VALUE (placement));
20682 	  }
20683 
20684 	/* If there was an initializer in the original tree, but it
20685 	   instantiated to an empty list, then we should pass a
20686 	   non-NULL empty vector to tell build_new that it was an
20687 	   empty initializer() rather than no initializer.  This can
20688 	   only happen when the initializer is a pack expansion whose
20689 	   parameter packs are of length zero.  */
20690 	if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
20691 	  init_vec = NULL;
20692 	else if (init == error_mark_node)
20693 	  RETURN (error_mark_node);
20694 	else
20695 	  {
20696 	    init_vec = make_tree_vector ();
20697 	    if (init == void_node)
20698 	      gcc_assert (init_vec != NULL);
20699 	    else
20700 	      {
20701 		for (; init != NULL_TREE; init = TREE_CHAIN (init))
20702 		  vec_safe_push (init_vec, TREE_VALUE (init));
20703 	      }
20704 	  }
20705 
20706 	/* Avoid passing an enclosing decl to valid_array_size_p.  */
20707 	in_decl = NULL_TREE;
20708 
20709 	tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
20710 	tree op2 = RECUR (TREE_OPERAND (t, 2));
20711 	ret = build_new (loc, &placement_vec, op1, op2,
20712 			 &init_vec, NEW_EXPR_USE_GLOBAL (t),
20713 			 complain);
20714 
20715 	if (placement_vec != NULL)
20716 	  release_tree_vector (placement_vec);
20717 	if (init_vec != NULL)
20718 	  release_tree_vector (init_vec);
20719 
20720 	RETURN (ret);
20721       }
20722 
20723     case DELETE_EXPR:
20724       {
20725 	tree op0 = RECUR (TREE_OPERAND (t, 0));
20726 	tree op1 = RECUR (TREE_OPERAND (t, 1));
20727 	RETURN (delete_sanity (input_location, op0, op1,
20728 			       DELETE_EXPR_USE_VEC (t),
20729 			       DELETE_EXPR_USE_GLOBAL (t),
20730 			       complain));
20731       }
20732 
20733     case COMPOUND_EXPR:
20734       {
20735 	tree op0 = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
20736 					  complain & ~tf_decltype, in_decl,
20737 					  /*function_p=*/false,
20738 					  integral_constant_expression_p);
20739 	RETURN (build_x_compound_expr (EXPR_LOCATION (t),
20740 				       op0,
20741 				       RECUR (TREE_OPERAND (t, 1)),
20742 				       templated_operator_saved_lookups (t),
20743 				       complain|decltype_flag));
20744       }
20745 
20746     case CALL_EXPR:
20747       {
20748 	tree function;
20749 	unsigned int nargs;
20750 	bool qualified_p;
20751 	bool koenig_p;
20752 	tree ret;
20753 
20754 	function = CALL_EXPR_FN (t);
20755 	/* Internal function with no arguments.  */
20756 	if (function == NULL_TREE && call_expr_nargs (t) == 0)
20757 	  RETURN (t);
20758 
20759 	/* When we parsed the expression, we determined whether or
20760 	   not Koenig lookup should be performed.  */
20761 	koenig_p = KOENIG_LOOKUP_P (t);
20762 	if (function == NULL_TREE)
20763 	  {
20764 	    koenig_p = false;
20765 	    qualified_p = false;
20766 	  }
20767 	else if (TREE_CODE (function) == SCOPE_REF)
20768 	  {
20769 	    qualified_p = true;
20770 	    function = tsubst_qualified_id (function, args, complain, in_decl,
20771 					    /*done=*/false,
20772 					    /*address_p=*/false);
20773 	  }
20774 	else if (koenig_p
20775 		 && (identifier_p (function)
20776 		     || (TREE_CODE (function) == TEMPLATE_ID_EXPR
20777 			 && identifier_p (TREE_OPERAND (function, 0)))))
20778 	  {
20779 	    /* Do nothing; calling tsubst_copy_and_build on an identifier
20780 	       would incorrectly perform unqualified lookup again.
20781 
20782 	       Note that we can also have an IDENTIFIER_NODE if the earlier
20783 	       unqualified lookup found a member function; in that case
20784 	       koenig_p will be false and we do want to do the lookup
20785 	       again to find the instantiated member function.
20786 
20787 	       FIXME but doing that causes c++/15272, so we need to stop
20788 	       using IDENTIFIER_NODE in that situation.  */
20789 	    qualified_p = false;
20790 
20791 	    if (TREE_CODE (function) == TEMPLATE_ID_EXPR)
20792 	      /* Use tsubst_copy to substitute through the template arguments
20793 		 of the template-id without performing unqualified lookup of
20794 		 the template name.  */
20795 	      function = tsubst_copy (function, args, complain, in_decl);
20796 	  }
20797 	else
20798 	  {
20799 	    if (TREE_CODE (function) == COMPONENT_REF)
20800 	      {
20801 		tree op = TREE_OPERAND (function, 1);
20802 
20803 		qualified_p = (TREE_CODE (op) == SCOPE_REF
20804 			       || (BASELINK_P (op)
20805 				   && BASELINK_QUALIFIED_P (op)));
20806 	      }
20807 	    else
20808 	      qualified_p = false;
20809 
20810 	    if (TREE_CODE (function) == ADDR_EXPR
20811 		&& TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
20812 	      /* Avoid error about taking the address of a constructor.  */
20813 	      function = TREE_OPERAND (function, 0);
20814 
20815 	    tsubst_flags_t subcomplain = complain;
20816 	    if (koenig_p && TREE_CODE (function) == FUNCTION_DECL)
20817 	      /* When KOENIG_P, we don't want to mark_used the callee before
20818 		 augmenting the overload set via ADL, so during this initial
20819 		 substitution we disable mark_used by setting tf_conv (68942).  */
20820 	      subcomplain |= tf_conv;
20821 	    function = tsubst_copy_and_build (function, args, subcomplain,
20822 					      in_decl,
20823 					      !qualified_p,
20824 					      integral_constant_expression_p);
20825 
20826 	    if (BASELINK_P (function))
20827 	      qualified_p = true;
20828 	  }
20829 
20830 	nargs = call_expr_nargs (t);
20831 	releasing_vec call_args;
20832 	tsubst_copy_and_build_call_args (t, args, complain, in_decl,
20833 					 integral_constant_expression_p,
20834 					 call_args);
20835 
20836 	/* Stripped-down processing for a call in a thunk.  Specifically, in
20837 	   the thunk template for a generic lambda.  */
20838 	if (call_from_lambda_thunk_p (t))
20839 	  {
20840 	    /* Now that we've expanded any packs, the number of call args
20841 	       might be different.  */
20842 	    unsigned int cargs = call_args->length ();
20843 	    tree thisarg = NULL_TREE;
20844 	    if (TREE_CODE (function) == COMPONENT_REF)
20845 	      {
20846 		thisarg = TREE_OPERAND (function, 0);
20847 		if (TREE_CODE (thisarg) == INDIRECT_REF)
20848 		  thisarg = TREE_OPERAND (thisarg, 0);
20849 		function = TREE_OPERAND (function, 1);
20850 		if (TREE_CODE (function) == BASELINK)
20851 		  function = BASELINK_FUNCTIONS (function);
20852 	      }
20853 	    /* We aren't going to do normal overload resolution, so force the
20854 	       template-id to resolve.  */
20855 	    function = resolve_nondeduced_context (function, complain);
20856 	    for (unsigned i = 0; i < cargs; ++i)
20857 	      {
20858 		/* In a thunk, pass through args directly, without any
20859 		   conversions.  */
20860 		tree arg = (*call_args)[i];
20861 		while (TREE_CODE (arg) != PARM_DECL)
20862 		  arg = TREE_OPERAND (arg, 0);
20863 		(*call_args)[i] = arg;
20864 	      }
20865 	    if (thisarg)
20866 	      {
20867 		/* If there are no other args, just push 'this'.  */
20868 		if (cargs == 0)
20869 		  vec_safe_push (call_args, thisarg);
20870 		else
20871 		  {
20872 		    /* Otherwise, shift the other args over to make room.  */
20873 		    tree last = (*call_args)[cargs - 1];
20874 		    vec_safe_push (call_args, last);
20875 		    for (int i = cargs - 1; i > 0; --i)
20876 		      (*call_args)[i] = (*call_args)[i - 1];
20877 		    (*call_args)[0] = thisarg;
20878 		  }
20879 	      }
20880 	    ret = build_call_a (function, call_args->length (),
20881 				call_args->address ());
20882 	    /* The thunk location is not interesting.  */
20883 	    SET_EXPR_LOCATION (ret, UNKNOWN_LOCATION);
20884 	    CALL_FROM_THUNK_P (ret) = true;
20885 	    if (CLASS_TYPE_P (TREE_TYPE (ret)))
20886 	      CALL_EXPR_RETURN_SLOT_OPT (ret) = true;
20887 
20888 	    RETURN (ret);
20889 	  }
20890 
20891 	/* We do not perform argument-dependent lookup if normal
20892 	   lookup finds a non-function, in accordance with the
20893 	   resolution of DR 218.  */
20894 	if (koenig_p
20895 	    && ((is_overloaded_fn (function)
20896 		 /* If lookup found a member function, the Koenig lookup is
20897 		    not appropriate, even if an unqualified-name was used
20898 		    to denote the function.  */
20899 		 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
20900 		|| identifier_p (function)
20901 		/* C++20 P0846: Lookup found nothing.  */
20902 		|| (TREE_CODE (function) == TEMPLATE_ID_EXPR
20903 		    && identifier_p (TREE_OPERAND (function, 0))))
20904 	    /* Only do this when substitution turns a dependent call
20905 	       into a non-dependent call.  */
20906 	    && type_dependent_expression_p_push (t)
20907 	    && !any_type_dependent_arguments_p (call_args))
20908 	  function = perform_koenig_lookup (function, call_args, tf_none);
20909 
20910 	if (function != NULL_TREE
20911 	    && (identifier_p (function)
20912 		|| (TREE_CODE (function) == TEMPLATE_ID_EXPR
20913 		    && identifier_p (TREE_OPERAND (function, 0))
20914 		    && !any_dependent_template_arguments_p (TREE_OPERAND
20915 							    (function, 1))))
20916 	    && !any_type_dependent_arguments_p (call_args))
20917 	  {
20918 	    bool template_id_p = (TREE_CODE (function) == TEMPLATE_ID_EXPR);
20919 	    if (template_id_p)
20920 	      function = TREE_OPERAND (function, 0);
20921 	    if (koenig_p && (complain & tf_warning_or_error))
20922 	      {
20923 		/* For backwards compatibility and good diagnostics, try
20924 		   the unqualified lookup again if we aren't in SFINAE
20925 		   context.  */
20926 		tree unq = (tsubst_copy_and_build
20927 			    (function, args, complain, in_decl, true,
20928 			     integral_constant_expression_p));
20929 		if (unq == error_mark_node)
20930 		  RETURN (error_mark_node);
20931 
20932 		if (unq != function)
20933 		  {
20934 		    char const *const msg
20935 		      = G_("%qD was not declared in this scope, "
20936 			   "and no declarations were found by "
20937 			   "argument-dependent lookup at the point "
20938 			   "of instantiation");
20939 
20940 		    bool in_lambda = (current_class_type
20941 				      && LAMBDA_TYPE_P (current_class_type));
20942 		    /* In a lambda fn, we have to be careful to not
20943 		       introduce new this captures.  Legacy code can't
20944 		       be using lambdas anyway, so it's ok to be
20945 		       stricter.  Be strict with C++20 template-id ADL too.  */
20946 		    bool strict = in_lambda || template_id_p;
20947 		    bool diag = true;
20948 		    if (strict)
20949 		      error_at (cp_expr_loc_or_input_loc (t),
20950 				msg, function);
20951 		    else
20952 		      diag = permerror (cp_expr_loc_or_input_loc (t),
20953 					msg, function);
20954 		    if (diag)
20955 		      {
20956 			tree fn = unq;
20957 
20958 			if (INDIRECT_REF_P (fn))
20959 			  fn = TREE_OPERAND (fn, 0);
20960 			if (is_overloaded_fn (fn))
20961 			  fn = get_first_fn (fn);
20962 
20963 			if (!DECL_P (fn))
20964 			  /* Can't say anything more.  */;
20965 			else if (DECL_CLASS_SCOPE_P (fn))
20966 			  {
20967 			    location_t loc = cp_expr_loc_or_input_loc (t);
20968 			    inform (loc,
20969 				    "declarations in dependent base %qT are "
20970 				    "not found by unqualified lookup",
20971 				    DECL_CLASS_CONTEXT (fn));
20972 			    if (current_class_ptr)
20973 			      inform (loc,
20974 				      "use %<this->%D%> instead", function);
20975 			    else
20976 			      inform (loc,
20977 				      "use %<%T::%D%> instead",
20978 				      current_class_name, function);
20979 			  }
20980 			else
20981 			  inform (DECL_SOURCE_LOCATION (fn),
20982 				  "%qD declared here, later in the "
20983 				  "translation unit", fn);
20984 			if (strict)
20985 			  RETURN (error_mark_node);
20986 		      }
20987 
20988 		    function = unq;
20989 		  }
20990 	      }
20991 	    if (identifier_p (function))
20992 	      {
20993 		if (complain & tf_error)
20994 		  unqualified_name_lookup_error (function);
20995 		RETURN (error_mark_node);
20996 	      }
20997 	  }
20998 
20999 	/* Remember that there was a reference to this entity.  */
21000 	if (function != NULL_TREE)
21001 	  {
21002 	    tree inner = function;
21003 	    if (TREE_CODE (inner) == ADDR_EXPR
21004 		&& TREE_CODE (TREE_OPERAND (inner, 0)) == FUNCTION_DECL)
21005 	      /* We should already have called mark_used when taking the
21006 		 address of this function, but do so again anyway to make
21007 		 sure it's odr-used: at worst this is a no-op, but if we
21008 		 obtained this FUNCTION_DECL as part of ahead-of-time overload
21009 		 resolution then that call to mark_used wouldn't have marked it
21010 		 odr-used yet (53164).  */
21011 	      inner = TREE_OPERAND (inner, 0);
21012 	    if (DECL_P (inner)
21013 		&& !mark_used (inner, complain) && !(complain & tf_error))
21014 	      RETURN (error_mark_node);
21015 	  }
21016 
21017 	if (!maybe_fold_fn_template_args (function, complain))
21018 	  return error_mark_node;
21019 
21020 	/* Put back tf_decltype for the actual call.  */
21021 	complain |= decltype_flag;
21022 
21023 	if (function == NULL_TREE)
21024 	  switch (CALL_EXPR_IFN (t))
21025 	    {
21026 	    case IFN_LAUNDER:
21027 	      gcc_assert (nargs == 1);
21028 	      if (vec_safe_length (call_args) != 1)
21029 		{
21030 		  error_at (cp_expr_loc_or_input_loc (t),
21031 			    "wrong number of arguments to "
21032 			    "%<__builtin_launder%>");
21033 		  ret = error_mark_node;
21034 		}
21035 	      else
21036 		ret = finish_builtin_launder (cp_expr_loc_or_input_loc (t),
21037 					      (*call_args)[0], complain);
21038 	      break;
21039 
21040 	    case IFN_VEC_CONVERT:
21041 	      gcc_assert (nargs == 1);
21042 	      if (vec_safe_length (call_args) != 1)
21043 		{
21044 		  error_at (cp_expr_loc_or_input_loc (t),
21045 			    "wrong number of arguments to "
21046 			    "%<__builtin_convertvector%>");
21047 		  ret = error_mark_node;
21048 		  break;
21049 		}
21050 	      ret = cp_build_vec_convert ((*call_args)[0], input_location,
21051 					  tsubst (TREE_TYPE (t), args,
21052 						  complain, in_decl),
21053 					  complain);
21054 	      if (TREE_CODE (ret) == VIEW_CONVERT_EXPR)
21055 		RETURN (ret);
21056 	      break;
21057 
21058 	    case IFN_SHUFFLEVECTOR:
21059 	      {
21060 		ret = build_x_shufflevector (input_location, call_args,
21061 					     complain);
21062 		if (ret != error_mark_node)
21063 		  RETURN (ret);
21064 		break;
21065 	      }
21066 
21067 	    default:
21068 	      /* Unsupported internal function with arguments.  */
21069 	      gcc_unreachable ();
21070 	    }
21071 	else if (TREE_CODE (function) == OFFSET_REF
21072 		 || TREE_CODE (function) == DOTSTAR_EXPR
21073 		 || TREE_CODE (function) == MEMBER_REF)
21074 	  ret = build_offset_ref_call_from_tree (function, &call_args,
21075 						 complain);
21076 	else if (TREE_CODE (function) == COMPONENT_REF)
21077 	  {
21078 	    tree instance = TREE_OPERAND (function, 0);
21079 	    tree fn = TREE_OPERAND (function, 1);
21080 
21081 	    if (processing_template_decl
21082 		&& (type_dependent_expression_p (instance)
21083 		    || (!BASELINK_P (fn)
21084 			&& TREE_CODE (fn) != FIELD_DECL)
21085 		    || type_dependent_expression_p (fn)
21086 		    || any_type_dependent_arguments_p (call_args)))
21087 	      ret = build_min_nt_call_vec (function, call_args);
21088 	    else if (!BASELINK_P (fn))
21089 	      ret = finish_call_expr (function, &call_args,
21090 				       /*disallow_virtual=*/false,
21091 				       /*koenig_p=*/false,
21092 				       complain);
21093 	    else
21094 	      ret = (build_new_method_call
21095 		      (instance, fn,
21096 		       &call_args, NULL_TREE,
21097 		       qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
21098 		       /*fn_p=*/NULL,
21099 		       complain));
21100 	  }
21101 	else if (concept_check_p (function))
21102 	  {
21103 	    /* FUNCTION is a template-id referring to a concept definition.  */
21104 	    tree id = unpack_concept_check (function);
21105 	    tree tmpl = TREE_OPERAND (id, 0);
21106 	    tree args = TREE_OPERAND (id, 1);
21107 
21108 	    /* Calls to standard and variable concepts should have been
21109 	       previously diagnosed.  */
21110 	    gcc_assert (function_concept_p (tmpl));
21111 
21112 	    /* Ensure the result is wrapped as a call expression.  */
21113 	    ret = build_concept_check (tmpl, args, tf_warning_or_error);
21114 	  }
21115 	else
21116 	  ret = finish_call_expr (function, &call_args,
21117 				  /*disallow_virtual=*/qualified_p,
21118 				  koenig_p,
21119 				  complain);
21120 
21121 	if (ret != error_mark_node)
21122 	  {
21123 	    bool op = CALL_EXPR_OPERATOR_SYNTAX (t);
21124 	    bool ord = CALL_EXPR_ORDERED_ARGS (t);
21125 	    bool rev = CALL_EXPR_REVERSE_ARGS (t);
21126 	    if (op || ord || rev)
21127 	      if (tree call = extract_call_expr (ret))
21128 		{
21129 		  CALL_EXPR_OPERATOR_SYNTAX (call) = op;
21130 		  CALL_EXPR_ORDERED_ARGS (call) = ord;
21131 		  CALL_EXPR_REVERSE_ARGS (call) = rev;
21132 		}
21133 	  }
21134 
21135 	RETURN (ret);
21136       }
21137 
21138     case COND_EXPR:
21139       {
21140 	tree cond = RECUR (TREE_OPERAND (t, 0));
21141 	cond = mark_rvalue_use (cond);
21142 	tree folded_cond = fold_non_dependent_expr (cond, complain);
21143 	tree exp1, exp2;
21144 
21145 	if (TREE_CODE (folded_cond) == INTEGER_CST)
21146 	  {
21147 	    if (integer_zerop (folded_cond))
21148 	      {
21149 		++c_inhibit_evaluation_warnings;
21150 		exp1 = RECUR (TREE_OPERAND (t, 1));
21151 		--c_inhibit_evaluation_warnings;
21152 		exp2 = RECUR (TREE_OPERAND (t, 2));
21153 	      }
21154 	    else
21155 	      {
21156 		exp1 = RECUR (TREE_OPERAND (t, 1));
21157 		++c_inhibit_evaluation_warnings;
21158 		exp2 = RECUR (TREE_OPERAND (t, 2));
21159 		--c_inhibit_evaluation_warnings;
21160 	      }
21161 	    cond = folded_cond;
21162 	  }
21163 	else
21164 	  {
21165 	    exp1 = RECUR (TREE_OPERAND (t, 1));
21166 	    exp2 = RECUR (TREE_OPERAND (t, 2));
21167 	  }
21168 
21169 	warning_sentinel s(warn_duplicated_branches);
21170 	RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
21171 					 cond, exp1, exp2, complain));
21172       }
21173 
21174     case PSEUDO_DTOR_EXPR:
21175       {
21176 	tree op0 = RECUR (TREE_OPERAND (t, 0));
21177 	tree op1 = RECUR (TREE_OPERAND (t, 1));
21178 	tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
21179 	RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
21180 					       input_location));
21181       }
21182 
21183     case TREE_LIST:
21184       RETURN (tsubst_tree_list (t, args, complain, in_decl));
21185 
21186     case COMPONENT_REF:
21187       {
21188 	tree object;
21189 	tree object_type;
21190 	tree member;
21191 	tree r;
21192 
21193 	object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
21194 						     args, complain, in_decl);
21195 	/* Remember that there was a reference to this entity.  */
21196 	if (DECL_P (object)
21197 	    && !mark_used (object, complain) && !(complain & tf_error))
21198 	  RETURN (error_mark_node);
21199 	object_type = TREE_TYPE (object);
21200 
21201 	member = TREE_OPERAND (t, 1);
21202 	if (BASELINK_P (member))
21203 	  member = tsubst_baselink (member,
21204 				    non_reference (TREE_TYPE (object)),
21205 				    args, complain, in_decl);
21206 	else
21207 	  member = tsubst_copy (member, args, complain, in_decl);
21208 	if (member == error_mark_node)
21209 	  RETURN (error_mark_node);
21210 
21211 	if (object_type && TYPE_PTRMEMFUNC_P (object_type)
21212 	    && TREE_CODE (member) == FIELD_DECL)
21213 	  {
21214 	    r = build_ptrmemfunc_access_expr (object, DECL_NAME (member));
21215 	    RETURN (r);
21216 	  }
21217 	else if (TREE_CODE (member) == FIELD_DECL)
21218 	  {
21219 	    r = finish_non_static_data_member (member, object, NULL_TREE);
21220 	    if (TREE_CODE (r) == COMPONENT_REF)
21221 	      REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
21222 	    RETURN (r);
21223 	  }
21224 	else if (type_dependent_expression_p (object))
21225 	  /* We can't do much here.  */;
21226 	else if (!CLASS_TYPE_P (object_type))
21227 	  {
21228 	    if (scalarish_type_p (object_type))
21229 	      {
21230 		tree s = NULL_TREE;
21231 		tree dtor = member;
21232 
21233 		if (TREE_CODE (dtor) == SCOPE_REF)
21234 		  {
21235 		    s = TREE_OPERAND (dtor, 0);
21236 		    dtor = TREE_OPERAND (dtor, 1);
21237 		  }
21238 		if (TREE_CODE (dtor) == BIT_NOT_EXPR)
21239 		  {
21240 		    dtor = TREE_OPERAND (dtor, 0);
21241 		    if (TYPE_P (dtor))
21242 		      RETURN (finish_pseudo_destructor_expr
21243 			      (object, s, dtor, input_location));
21244 		  }
21245 	      }
21246 	  }
21247 	else if (TREE_CODE (member) == SCOPE_REF
21248 		 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
21249 	  {
21250 	    /* Lookup the template functions now that we know what the
21251 	       scope is.  */
21252 	    tree scope = TREE_OPERAND (member, 0);
21253 	    tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
21254 	    tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
21255 	    member = lookup_qualified_name (scope, tmpl, LOOK_want::NORMAL,
21256 					    /*complain=*/false);
21257 	    if (BASELINK_P (member))
21258 	      {
21259 		BASELINK_FUNCTIONS (member)
21260 		  = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
21261 			      args);
21262 		member = (adjust_result_of_qualified_name_lookup
21263 			  (member, BINFO_TYPE (BASELINK_BINFO (member)),
21264 			   object_type));
21265 	      }
21266 	    else
21267 	      {
21268 		qualified_name_lookup_error (scope, tmpl, member,
21269 					     input_location);
21270 		RETURN (error_mark_node);
21271 	      }
21272 	  }
21273 	else if (TREE_CODE (member) == SCOPE_REF
21274 		 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
21275 		 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
21276 	  {
21277 	    if (complain & tf_error)
21278 	      {
21279 		if (TYPE_P (TREE_OPERAND (member, 0)))
21280 		  error ("%qT is not a class or namespace",
21281 			 TREE_OPERAND (member, 0));
21282 		else
21283 		  error ("%qD is not a class or namespace",
21284 			 TREE_OPERAND (member, 0));
21285 	      }
21286 	    RETURN (error_mark_node);
21287 	  }
21288 
21289 	r = finish_class_member_access_expr (object, member,
21290 					     /*template_p=*/false,
21291 					     complain);
21292 	if (TREE_CODE (r) == COMPONENT_REF)
21293 	  REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
21294 	RETURN (r);
21295       }
21296 
21297     case THROW_EXPR:
21298       RETURN (build_throw
21299        (input_location, RECUR (TREE_OPERAND (t, 0))));
21300 
21301     case CONSTRUCTOR:
21302       {
21303 	vec<constructor_elt, va_gc> *n;
21304 	constructor_elt *ce;
21305 	unsigned HOST_WIDE_INT idx;
21306 	bool process_index_p;
21307         int newlen;
21308         bool need_copy_p = false;
21309 	tree r;
21310 
21311 	tsubst_flags_t tcomplain = complain;
21312 	if (COMPOUND_LITERAL_P (t))
21313 	  tcomplain |= tf_tst_ok;
21314 	tree type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
21315 	if (type == error_mark_node)
21316 	  RETURN (error_mark_node);
21317 
21318 	/* We do not want to process the index of aggregate
21319 	   initializers as they are identifier nodes which will be
21320 	   looked up by digest_init.  */
21321 	process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
21322 
21323 	if (null_member_pointer_value_p (t))
21324 	  {
21325 	    gcc_assert (same_type_p (type, TREE_TYPE (t)));
21326 	    RETURN (t);
21327 	  }
21328 
21329 	n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
21330         newlen = vec_safe_length (n);
21331 	FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
21332 	  {
21333 	    if (ce->index && process_index_p
21334 		/* An identifier index is looked up in the type
21335 		   being initialized, not the current scope.  */
21336 		&& TREE_CODE (ce->index) != IDENTIFIER_NODE)
21337 	      ce->index = RECUR (ce->index);
21338 
21339             if (PACK_EXPANSION_P (ce->value))
21340               {
21341                 /* Substitute into the pack expansion.  */
21342                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
21343                                                   in_decl);
21344 
21345 		if (ce->value == error_mark_node
21346 		    || PACK_EXPANSION_P (ce->value))
21347 		  ;
21348 		else if (TREE_VEC_LENGTH (ce->value) == 1)
21349                   /* Just move the argument into place.  */
21350                   ce->value = TREE_VEC_ELT (ce->value, 0);
21351                 else
21352                   {
21353                     /* Update the length of the final CONSTRUCTOR
21354                        arguments vector, and note that we will need to
21355                        copy.*/
21356                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
21357                     need_copy_p = true;
21358                   }
21359               }
21360             else
21361               ce->value = RECUR (ce->value);
21362 	  }
21363 
21364         if (need_copy_p)
21365           {
21366             vec<constructor_elt, va_gc> *old_n = n;
21367 
21368             vec_alloc (n, newlen);
21369             FOR_EACH_VEC_ELT (*old_n, idx, ce)
21370               {
21371                 if (TREE_CODE (ce->value) == TREE_VEC)
21372                   {
21373                     int i, len = TREE_VEC_LENGTH (ce->value);
21374                     for (i = 0; i < len; ++i)
21375                       CONSTRUCTOR_APPEND_ELT (n, 0,
21376                                               TREE_VEC_ELT (ce->value, i));
21377                   }
21378                 else
21379                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
21380               }
21381           }
21382 
21383 	r = build_constructor (init_list_type_node, n);
21384 	CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
21385 	CONSTRUCTOR_IS_DESIGNATED_INIT (r)
21386 	  = CONSTRUCTOR_IS_DESIGNATED_INIT (t);
21387 
21388 	if (TREE_HAS_CONSTRUCTOR (t))
21389 	  {
21390 	    fcl_t cl = fcl_functional;
21391 	    if (CONSTRUCTOR_C99_COMPOUND_LITERAL (t))
21392 	      cl = fcl_c99;
21393 	    RETURN (finish_compound_literal (type, r, complain, cl));
21394 	  }
21395 
21396 	TREE_TYPE (r) = type;
21397 	RETURN (r);
21398       }
21399 
21400     case TYPEID_EXPR:
21401       {
21402 	tree operand_0 = TREE_OPERAND (t, 0);
21403 	if (TYPE_P (operand_0))
21404 	  {
21405 	    operand_0 = tsubst (operand_0, args, complain, in_decl);
21406 	    RETURN (get_typeid (operand_0, complain));
21407 	  }
21408 	else
21409 	  {
21410 	    operand_0 = RECUR (operand_0);
21411 	    RETURN (build_typeid (operand_0, complain));
21412 	  }
21413       }
21414 
21415     case VAR_DECL:
21416       if (!args)
21417 	RETURN (t);
21418       /* Fall through */
21419 
21420     case PARM_DECL:
21421       {
21422 	tree r = tsubst_copy (t, args, complain, in_decl);
21423 	/* ??? We're doing a subset of finish_id_expression here.  */
21424 	if (tree wrap = maybe_get_tls_wrapper_call (r))
21425 	  /* Replace an evaluated use of the thread_local variable with
21426 	     a call to its wrapper.  */
21427 	  r = wrap;
21428 	else if (outer_automatic_var_p (r))
21429 	  r = process_outer_var_ref (r, complain);
21430 
21431 	if (!TYPE_REF_P (TREE_TYPE (t)))
21432 	  /* If the original type was a reference, we'll be wrapped in
21433 	     the appropriate INDIRECT_REF.  */
21434 	  r = convert_from_reference (r);
21435 	RETURN (r);
21436       }
21437 
21438     case VA_ARG_EXPR:
21439       {
21440 	tree op0 = RECUR (TREE_OPERAND (t, 0));
21441 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21442 	RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
21443       }
21444 
21445     case OFFSETOF_EXPR:
21446       {
21447 	tree object_ptr
21448 	  = tsubst_copy_and_build (TREE_OPERAND (t, 1), args, complain,
21449 				   in_decl, /*function_p=*/false,
21450 				   /*integral_constant_expression_p=*/false);
21451 	RETURN (finish_offsetof (object_ptr,
21452 				 RECUR (TREE_OPERAND (t, 0)),
21453 				 EXPR_LOCATION (t)));
21454       }
21455 
21456     case ADDRESSOF_EXPR:
21457       RETURN (cp_build_addressof (EXPR_LOCATION (t),
21458 				  RECUR (TREE_OPERAND (t, 0)), complain));
21459 
21460     case TRAIT_EXPR:
21461       {
21462 	tree type1 = tsubst (TRAIT_EXPR_TYPE1 (t), args,
21463 			     complain, in_decl);
21464 	tree type2 = tsubst (TRAIT_EXPR_TYPE2 (t), args,
21465 			     complain, in_decl);
21466 	RETURN (finish_trait_expr (TRAIT_EXPR_LOCATION (t),
21467 				   TRAIT_EXPR_KIND (t), type1, type2));
21468       }
21469 
21470     case STMT_EXPR:
21471       {
21472 	tree old_stmt_expr = cur_stmt_expr;
21473 	tree stmt_expr = begin_stmt_expr ();
21474 
21475 	cur_stmt_expr = stmt_expr;
21476 	tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
21477 		     integral_constant_expression_p);
21478 	stmt_expr = finish_stmt_expr (stmt_expr, false);
21479 	cur_stmt_expr = old_stmt_expr;
21480 
21481 	/* If the resulting list of expression statement is empty,
21482 	   fold it further into void_node.  */
21483 	if (empty_expr_stmt_p (stmt_expr))
21484 	  stmt_expr = void_node;
21485 
21486 	RETURN (stmt_expr);
21487       }
21488 
21489     case LAMBDA_EXPR:
21490       {
21491 	if (complain & tf_partial)
21492 	  {
21493 	    /* We don't have a full set of template arguments yet; don't touch
21494 	       the lambda at all.  */
21495 	    gcc_assert (processing_template_decl);
21496 	    return t;
21497 	  }
21498 	tree r = tsubst_lambda_expr (t, args, complain, in_decl);
21499 
21500 	RETURN (build_lambda_object (r));
21501       }
21502 
21503     case TRANSACTION_EXPR:
21504       RETURN (tsubst_expr(t, args, complain, in_decl,
21505 	     integral_constant_expression_p));
21506 
21507     case PAREN_EXPR:
21508       if (REF_PARENTHESIZED_P (t))
21509 	RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
21510       else
21511 	/* Recreate the PAREN_EXPR from __builtin_assoc_barrier.  */
21512 	{
21513 	  tree op0 = RECUR (TREE_OPERAND (t, 0));
21514 	  RETURN (build1_loc (input_location, PAREN_EXPR,
21515 			      TREE_TYPE (op0), op0));
21516 	}
21517 
21518     case VEC_PERM_EXPR:
21519       {
21520 	tree op0 = RECUR (TREE_OPERAND (t, 0));
21521 	tree op1 = RECUR (TREE_OPERAND (t, 1));
21522 	tree op2 = RECUR (TREE_OPERAND (t, 2));
21523 	RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
21524 				       complain));
21525       }
21526 
21527     case REQUIRES_EXPR:
21528       {
21529 	tree r = tsubst_requires_expr (t, args, tf_none, in_decl);
21530 	RETURN (r);
21531       }
21532 
21533     case RANGE_EXPR:
21534       /* No need to substitute further, a RANGE_EXPR will always be built
21535 	 with constant operands.  */
21536       RETURN (t);
21537 
21538     case ANNOTATE_EXPR:
21539       op1 = RECUR (TREE_OPERAND (t, 0));
21540       RETURN (build3_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
21541 			  TREE_TYPE (op1), op1,
21542 			  RECUR (TREE_OPERAND (t, 1)),
21543 			  RECUR (TREE_OPERAND (t, 2))));
21544 
21545     case NON_LVALUE_EXPR:
21546     case VIEW_CONVERT_EXPR:
21547       if (location_wrapper_p (t))
21548 	/* We need to do this here as well as in tsubst_copy so we get the
21549 	   other tsubst_copy_and_build semantics for a PARM_DECL operand.  */
21550 	RETURN (maybe_wrap_with_location (RECUR (TREE_OPERAND (t, 0)),
21551 					  EXPR_LOCATION (t)));
21552       /* fallthrough.  */
21553 
21554     default:
21555       /* Handle Objective-C++ constructs, if appropriate.  */
21556       {
21557 	tree subst
21558 	  = objcp_tsubst_copy_and_build (t, args, complain,
21559 					 in_decl, /*function_p=*/false);
21560 	if (subst)
21561 	  RETURN (subst);
21562       }
21563       RETURN (tsubst_copy (t, args, complain, in_decl));
21564     }
21565 
21566 #undef RECUR
21567 #undef RETURN
21568  out:
21569   input_location = save_loc;
21570   return retval;
21571 }
21572 
21573 /* Verify that the instantiated ARGS are valid. For type arguments,
21574    make sure that the type's linkage is ok. For non-type arguments,
21575    make sure they are constants if they are integral or enumerations.
21576    Emit an error under control of COMPLAIN, and return TRUE on error.  */
21577 
21578 static bool
check_instantiated_arg(tree tmpl,tree t,tsubst_flags_t complain)21579 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
21580 {
21581   if (dependent_template_arg_p (t))
21582     return false;
21583   if (ARGUMENT_PACK_P (t))
21584     {
21585       tree vec = ARGUMENT_PACK_ARGS (t);
21586       int len = TREE_VEC_LENGTH (vec);
21587       bool result = false;
21588       int i;
21589 
21590       for (i = 0; i < len; ++i)
21591 	if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
21592 	  result = true;
21593       return result;
21594     }
21595   else if (TYPE_P (t))
21596     {
21597       /* [basic.link]: A name with no linkage (notably, the name
21598 	 of a class or enumeration declared in a local scope)
21599 	 shall not be used to declare an entity with linkage.
21600 	 This implies that names with no linkage cannot be used as
21601 	 template arguments
21602 
21603 	 DR 757 relaxes this restriction for C++0x.  */
21604       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
21605 		 : no_linkage_check (t, /*relaxed_p=*/false));
21606 
21607       if (nt)
21608 	{
21609 	  /* DR 488 makes use of a type with no linkage cause
21610 	     type deduction to fail.  */
21611 	  if (complain & tf_error)
21612 	    {
21613 	      if (TYPE_UNNAMED_P (nt))
21614 		error ("%qT is/uses unnamed type", t);
21615 	      else
21616 		error ("template argument for %qD uses local type %qT",
21617 		       tmpl, t);
21618 	    }
21619 	  return true;
21620 	}
21621       /* In order to avoid all sorts of complications, we do not
21622 	 allow variably-modified types as template arguments.  */
21623       else if (variably_modified_type_p (t, NULL_TREE))
21624 	{
21625 	  if (complain & tf_error)
21626 	    error ("%qT is a variably modified type", t);
21627 	  return true;
21628 	}
21629     }
21630   /* Class template and alias template arguments should be OK.  */
21631   else if (DECL_TYPE_TEMPLATE_P (t))
21632     ;
21633   /* A non-type argument of integral or enumerated type must be a
21634      constant.  */
21635   else if (TREE_TYPE (t)
21636 	   && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
21637 	   && !REFERENCE_REF_P (t)
21638 	   && !TREE_CONSTANT (t))
21639     {
21640       if (complain & tf_error)
21641 	error ("integral expression %qE is not constant", t);
21642       return true;
21643     }
21644   return false;
21645 }
21646 
21647 static bool
check_instantiated_args(tree tmpl,tree args,tsubst_flags_t complain)21648 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
21649 {
21650   int ix, len = DECL_NTPARMS (tmpl);
21651   bool result = false;
21652 
21653   for (ix = 0; ix != len; ix++)
21654     {
21655       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
21656 	result = true;
21657     }
21658   if (result && (complain & tf_error))
21659     error ("  trying to instantiate %qD", tmpl);
21660   return result;
21661 }
21662 
21663 /* We're out of SFINAE context now, so generate diagnostics for the access
21664    errors we saw earlier when instantiating D from TMPL and ARGS.  */
21665 
21666 static void
recheck_decl_substitution(tree d,tree tmpl,tree args)21667 recheck_decl_substitution (tree d, tree tmpl, tree args)
21668 {
21669   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
21670   tree type = TREE_TYPE (pattern);
21671   location_t loc = input_location;
21672 
21673   push_access_scope (d);
21674   push_deferring_access_checks (dk_no_deferred);
21675   input_location = DECL_SOURCE_LOCATION (pattern);
21676   tsubst (type, args, tf_warning_or_error, d);
21677   input_location = loc;
21678   pop_deferring_access_checks ();
21679   pop_access_scope (d);
21680 }
21681 
21682 /* Instantiate the indicated variable, function, or alias template TMPL with
21683    the template arguments in TARG_PTR.  */
21684 
21685 static tree
instantiate_template_1(tree tmpl,tree orig_args,tsubst_flags_t complain)21686 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
21687 {
21688   tree targ_ptr = orig_args;
21689   tree fndecl;
21690   tree gen_tmpl;
21691   tree spec;
21692   bool access_ok = true;
21693 
21694   if (tmpl == error_mark_node)
21695     return error_mark_node;
21696 
21697   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
21698 
21699   if (modules_p ())
21700     lazy_load_pendings (tmpl);
21701 
21702   /* If this function is a clone, handle it specially.  */
21703   if (DECL_CLONED_FUNCTION_P (tmpl))
21704     {
21705       tree spec;
21706       tree clone;
21707 
21708       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
21709 	 DECL_CLONED_FUNCTION.  */
21710       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
21711 				   targ_ptr, complain);
21712       if (spec == error_mark_node)
21713 	return error_mark_node;
21714 
21715       /* Look for the clone.  */
21716       FOR_EACH_CLONE (clone, spec)
21717 	if (DECL_NAME (clone) == DECL_NAME (tmpl))
21718 	  return clone;
21719       /* We should always have found the clone by now.  */
21720       gcc_unreachable ();
21721       return NULL_TREE;
21722     }
21723 
21724   if (targ_ptr == error_mark_node)
21725     return error_mark_node;
21726 
21727   /* Check to see if we already have this specialization.  */
21728   gen_tmpl = most_general_template (tmpl);
21729   if (TMPL_ARGS_DEPTH (targ_ptr)
21730       < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)))
21731     /* targ_ptr only has the innermost template args, so add the outer ones
21732        from tmpl, which could be either a partial instantiation or gen_tmpl (in
21733        the case of a non-dependent call within a template definition).  */
21734     targ_ptr = (add_outermost_template_args
21735 		(DECL_TI_ARGS (DECL_TEMPLATE_RESULT (tmpl)),
21736 		 targ_ptr));
21737 
21738   /* It would be nice to avoid hashing here and then again in tsubst_decl,
21739      but it doesn't seem to be on the hot path.  */
21740   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
21741 
21742   gcc_checking_assert (tmpl == gen_tmpl
21743 		       || ((fndecl
21744 			    = retrieve_specialization (tmpl, orig_args, 0))
21745 			   == spec)
21746 		       || fndecl == NULL_TREE);
21747 
21748   if (spec != NULL_TREE)
21749     {
21750       if (FNDECL_HAS_ACCESS_ERRORS (spec))
21751 	{
21752 	  if (complain & tf_error)
21753 	    recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
21754 	  return error_mark_node;
21755 	}
21756       return spec;
21757     }
21758 
21759   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
21760 			       complain))
21761     return error_mark_node;
21762 
21763   /* We are building a FUNCTION_DECL, during which the access of its
21764      parameters and return types have to be checked.  However this
21765      FUNCTION_DECL which is the desired context for access checking
21766      is not built yet.  We solve this chicken-and-egg problem by
21767      deferring all checks until we have the FUNCTION_DECL.  */
21768   push_deferring_access_checks (dk_deferred);
21769 
21770   /* Instantiation of the function happens in the context of the function
21771      template, not the context of the overload resolution we're doing.  */
21772   push_to_top_level ();
21773   /* If there are dependent arguments, e.g. because we're doing partial
21774      ordering, make sure processing_template_decl stays set.  */
21775   if (uses_template_parms (targ_ptr))
21776     ++processing_template_decl;
21777   if (DECL_CLASS_SCOPE_P (gen_tmpl))
21778     {
21779       tree ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
21780 				   complain, gen_tmpl, true);
21781       push_nested_class (ctx);
21782     }
21783 
21784   tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
21785 
21786   fndecl = NULL_TREE;
21787   if (VAR_P (pattern))
21788     {
21789       /* We need to determine if we're using a partial or explicit
21790 	 specialization now, because the type of the variable could be
21791 	 different.  */
21792       tree tid = lookup_template_variable (tmpl, targ_ptr);
21793       tree elt = most_specialized_partial_spec (tid, complain);
21794       if (elt == error_mark_node)
21795 	pattern = error_mark_node;
21796       else if (elt)
21797 	{
21798 	  tree partial_tmpl = TREE_VALUE (elt);
21799 	  tree partial_args = TREE_PURPOSE (elt);
21800 	  tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
21801 	  fndecl = tsubst (partial_pat, partial_args, complain, gen_tmpl);
21802 	}
21803     }
21804 
21805   /* Substitute template parameters to obtain the specialization.  */
21806   if (fndecl == NULL_TREE)
21807     fndecl = tsubst (pattern, targ_ptr, complain, gen_tmpl);
21808   if (DECL_CLASS_SCOPE_P (gen_tmpl))
21809     pop_nested_class ();
21810   pop_from_top_level ();
21811 
21812   if (fndecl == error_mark_node)
21813     {
21814       pop_deferring_access_checks ();
21815       return error_mark_node;
21816     }
21817 
21818   /* The DECL_TI_TEMPLATE should always be the immediate parent
21819      template, not the most general template.  */
21820   DECL_TI_TEMPLATE (fndecl) = tmpl;
21821   DECL_TI_ARGS (fndecl) = targ_ptr;
21822 
21823   set_instantiating_module (fndecl);
21824 
21825   /* Now we know the specialization, compute access previously
21826      deferred.  Do no access control for inheriting constructors,
21827      as we already checked access for the inherited constructor.  */
21828   if (!(flag_new_inheriting_ctors
21829 	&& DECL_INHERITED_CTOR (fndecl)))
21830     {
21831       push_access_scope (fndecl);
21832       if (!perform_deferred_access_checks (complain))
21833 	access_ok = false;
21834       pop_access_scope (fndecl);
21835     }
21836   pop_deferring_access_checks ();
21837 
21838   /* If we've just instantiated the main entry point for a function,
21839      instantiate all the alternate entry points as well.  We do this
21840      by cloning the instantiation of the main entry point, not by
21841      instantiating the template clones.  */
21842   if (tree chain = DECL_CHAIN (gen_tmpl))
21843     if (DECL_P (chain) && DECL_CLONED_FUNCTION_P (chain))
21844       clone_cdtor (fndecl, /*update_methods=*/false);
21845 
21846   if (!access_ok)
21847     {
21848       if (!(complain & tf_error))
21849 	{
21850 	  /* Remember to reinstantiate when we're out of SFINAE so the user
21851 	     can see the errors.  */
21852 	  FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
21853 	}
21854       return error_mark_node;
21855     }
21856   return fndecl;
21857 }
21858 
21859 /* Wrapper for instantiate_template_1.  */
21860 
21861 tree
instantiate_template(tree tmpl,tree orig_args,tsubst_flags_t complain)21862 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
21863 {
21864   tree ret;
21865   timevar_push (TV_TEMPLATE_INST);
21866   ret = instantiate_template_1 (tmpl, orig_args,  complain);
21867   timevar_pop (TV_TEMPLATE_INST);
21868   return ret;
21869 }
21870 
21871 /* Instantiate the alias template TMPL with ARGS.  Also push a template
21872    instantiation level, which instantiate_template doesn't do because
21873    functions and variables have sufficient context established by the
21874    callers.  */
21875 
21876 static tree
instantiate_alias_template(tree tmpl,tree args,tsubst_flags_t complain)21877 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
21878 {
21879   if (tmpl == error_mark_node || args == error_mark_node)
21880     return error_mark_node;
21881 
21882   /* See maybe_dependent_member_ref.  */
21883   if (complain & tf_dguide)
21884     {
21885       tree ctx = tsubst_aggr_type (DECL_CONTEXT (tmpl), args, complain,
21886 				   tmpl, true);
21887       if (dependent_scope_p (ctx))
21888 	{
21889 	  tree name = DECL_NAME (tmpl);
21890 	  tree fullname = build_nt (TEMPLATE_ID_EXPR, name,
21891 				    INNERMOST_TEMPLATE_ARGS (args));
21892 	  tree tname = build_typename_type (ctx, name, fullname, typename_type);
21893 	  return TYPE_NAME (tname);
21894 	}
21895     }
21896 
21897   args =
21898     coerce_innermost_template_parms (DECL_TEMPLATE_PARMS (tmpl),
21899 				     args, tmpl, complain,
21900 				     /*require_all_args=*/true,
21901 				     /*use_default_args=*/true);
21902 
21903   /* FIXME check for satisfaction in check_instantiated_args.  */
21904   if (flag_concepts
21905       && !any_dependent_template_arguments_p (args)
21906       && !constraints_satisfied_p (tmpl, args))
21907     {
21908       if (complain & tf_error)
21909 	{
21910 	  auto_diagnostic_group d;
21911 	  error ("template constraint failure for %qD", tmpl);
21912 	  diagnose_constraints (input_location, tmpl, args);
21913 	}
21914       return error_mark_node;
21915     }
21916 
21917   if (!push_tinst_level (tmpl, args))
21918     return error_mark_node;
21919   tree r = instantiate_template (tmpl, args, complain);
21920   pop_tinst_level ();
21921 
21922   if (tree d = dependent_alias_template_spec_p (TREE_TYPE (r), nt_opaque))
21923     {
21924       /* An alias template specialization can be dependent
21925 	 even if its underlying type is not.  */
21926       TYPE_DEPENDENT_P (d) = true;
21927       TYPE_DEPENDENT_P_VALID (d) = true;
21928       /* Sometimes a dependent alias spec is equivalent to its expansion,
21929 	 sometimes not.  So always use structural_comptypes.  */
21930       SET_TYPE_STRUCTURAL_EQUALITY (d);
21931     }
21932 
21933   return r;
21934 }
21935 
21936 /* PARM is a template parameter pack for FN.  Returns true iff
21937    PARM is used in a deducible way in the argument list of FN.  */
21938 
21939 static bool
pack_deducible_p(tree parm,tree fn)21940 pack_deducible_p (tree parm, tree fn)
21941 {
21942   tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
21943   for (; t; t = TREE_CHAIN (t))
21944     {
21945       tree type = TREE_VALUE (t);
21946       tree packs;
21947       if (!PACK_EXPANSION_P (type))
21948 	continue;
21949       for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
21950 	   packs; packs = TREE_CHAIN (packs))
21951 	if (template_args_equal (TREE_VALUE (packs), parm))
21952 	  {
21953 	    /* The template parameter pack is used in a function parameter
21954 	       pack.  If this is the end of the parameter list, the
21955 	       template parameter pack is deducible.  */
21956 	    if (TREE_CHAIN (t) == void_list_node)
21957 	      return true;
21958 	    else
21959 	      /* Otherwise, not.  Well, it could be deduced from
21960 		 a non-pack parameter, but doing so would end up with
21961 		 a deduction mismatch, so don't bother.  */
21962 	      return false;
21963 	  }
21964     }
21965   /* The template parameter pack isn't used in any function parameter
21966      packs, but it might be used deeper, e.g. tuple<Args...>.  */
21967   return true;
21968 }
21969 
21970 /* Subroutine of fn_type_unification: check non-dependent parms for
21971    convertibility.  */
21972 
21973 static int
check_non_deducible_conversions(tree parms,const tree * args,unsigned nargs,tree fn,unification_kind_t strict,int flags,struct conversion ** convs,bool explain_p)21974 check_non_deducible_conversions (tree parms, const tree *args, unsigned nargs,
21975 				 tree fn, unification_kind_t strict, int flags,
21976 				 struct conversion **convs, bool explain_p)
21977 {
21978   /* Non-constructor methods need to leave a conversion for 'this', which
21979      isn't included in nargs here.  */
21980   unsigned offset = (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
21981 		     && !DECL_CONSTRUCTOR_P (fn));
21982 
21983   for (unsigned ia = 0;
21984        parms && parms != void_list_node && ia < nargs; )
21985     {
21986       tree parm = TREE_VALUE (parms);
21987 
21988       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
21989 	  && (!TREE_CHAIN (parms)
21990 	      || TREE_CHAIN (parms) == void_list_node))
21991 	/* For a function parameter pack that occurs at the end of the
21992 	   parameter-declaration-list, the type A of each remaining
21993 	   argument of the call is compared with the type P of the
21994 	   declarator-id of the function parameter pack.  */
21995 	break;
21996 
21997       parms = TREE_CHAIN (parms);
21998 
21999       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
22000 	/* For a function parameter pack that does not occur at the
22001 	   end of the parameter-declaration-list, the type of the
22002 	   parameter pack is a non-deduced context.  */
22003 	continue;
22004 
22005       if (!uses_template_parms (parm))
22006 	{
22007 	  tree arg = args[ia];
22008 	  conversion **conv_p = convs ? &convs[ia+offset] : NULL;
22009 	  int lflags = conv_flags (ia, nargs, fn, arg, flags);
22010 
22011 	  if (check_non_deducible_conversion (parm, arg, strict, lflags,
22012 					      conv_p, explain_p))
22013 	    return 1;
22014 	}
22015 
22016       ++ia;
22017     }
22018 
22019   return 0;
22020 }
22021 
22022 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
22023    NARGS elements of the arguments that are being used when calling
22024    it.  TARGS is a vector into which the deduced template arguments
22025    are placed.
22026 
22027    Returns either a FUNCTION_DECL for the matching specialization of FN or
22028    NULL_TREE if no suitable specialization can be found.  If EXPLAIN_P is
22029    true, diagnostics will be printed to explain why it failed.
22030 
22031    If FN is a conversion operator, or we are trying to produce a specific
22032    specialization, RETURN_TYPE is the return type desired.
22033 
22034    The EXPLICIT_TARGS are explicit template arguments provided via a
22035    template-id.
22036 
22037    The parameter STRICT is one of:
22038 
22039    DEDUCE_CALL:
22040      We are deducing arguments for a function call, as in
22041      [temp.deduct.call].  If RETURN_TYPE is non-null, we are
22042      deducing arguments for a call to the result of a conversion
22043      function template, as in [over.call.object].
22044 
22045    DEDUCE_CONV:
22046      We are deducing arguments for a conversion function, as in
22047      [temp.deduct.conv].
22048 
22049    DEDUCE_EXACT:
22050      We are deducing arguments when doing an explicit instantiation
22051      as in [temp.explicit], when determining an explicit specialization
22052      as in [temp.expl.spec], or when taking the address of a function
22053      template, as in [temp.deduct.funcaddr].  */
22054 
22055 tree
fn_type_unification(tree fn,tree explicit_targs,tree targs,const tree * args,unsigned int nargs,tree return_type,unification_kind_t strict,int flags,struct conversion ** convs,bool explain_p,bool decltype_p)22056 fn_type_unification (tree fn,
22057 		     tree explicit_targs,
22058 		     tree targs,
22059 		     const tree *args,
22060 		     unsigned int nargs,
22061 		     tree return_type,
22062 		     unification_kind_t strict,
22063 		     int flags,
22064 		     struct conversion **convs,
22065 		     bool explain_p,
22066 		     bool decltype_p)
22067 {
22068   tree parms;
22069   tree fntype;
22070   tree decl = NULL_TREE;
22071   tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
22072   bool ok;
22073   static int deduction_depth;
22074   /* type_unification_real will pass back any access checks from default
22075      template argument substitution.  */
22076   vec<deferred_access_check, va_gc> *checks = NULL;
22077   /* We don't have all the template args yet.  */
22078   bool incomplete = true;
22079 
22080   tree orig_fn = fn;
22081   if (flag_new_inheriting_ctors)
22082     fn = strip_inheriting_ctors (fn);
22083 
22084   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
22085   tree r = error_mark_node;
22086 
22087   tree full_targs = targs;
22088   if (TMPL_ARGS_DEPTH (targs)
22089       < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (fn)))
22090     full_targs = (add_outermost_template_args
22091 		  (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (fn)),
22092 		   targs));
22093 
22094   if (decltype_p)
22095     complain |= tf_decltype;
22096 
22097   /* In C++0x, it's possible to have a function template whose type depends
22098      on itself recursively.  This is most obvious with decltype, but can also
22099      occur with enumeration scope (c++/48969).  So we need to catch infinite
22100      recursion and reject the substitution at deduction time; this function
22101      will return error_mark_node for any repeated substitution.
22102 
22103      This also catches excessive recursion such as when f<N> depends on
22104      f<N-1> across all integers, and returns error_mark_node for all the
22105      substitutions back up to the initial one.
22106 
22107      This is, of course, not reentrant.  */
22108   if (excessive_deduction_depth)
22109     return error_mark_node;
22110   ++deduction_depth;
22111 
22112   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
22113 
22114   fntype = TREE_TYPE (fn);
22115   if (explicit_targs)
22116     {
22117       /* [temp.deduct]
22118 
22119 	 The specified template arguments must match the template
22120 	 parameters in kind (i.e., type, nontype, template), and there
22121 	 must not be more arguments than there are parameters;
22122 	 otherwise type deduction fails.
22123 
22124 	 Nontype arguments must match the types of the corresponding
22125 	 nontype template parameters, or must be convertible to the
22126 	 types of the corresponding nontype parameters as specified in
22127 	 _temp.arg.nontype_, otherwise type deduction fails.
22128 
22129 	 All references in the function type of the function template
22130 	 to the corresponding template parameters are replaced by the
22131 	 specified template argument values.  If a substitution in a
22132 	 template parameter or in the function type of the function
22133 	 template results in an invalid type, type deduction fails.  */
22134       int i, len = TREE_VEC_LENGTH (tparms);
22135       location_t loc = input_location;
22136       incomplete = false;
22137 
22138       if (explicit_targs == error_mark_node)
22139 	goto fail;
22140 
22141       if (TMPL_ARGS_DEPTH (explicit_targs)
22142 	  < TMPL_ARGS_DEPTH (full_targs))
22143 	explicit_targs = add_outermost_template_args (full_targs,
22144 						      explicit_targs);
22145 
22146       /* Adjust any explicit template arguments before entering the
22147 	 substitution context.  */
22148       explicit_targs
22149 	= (coerce_template_parms (tparms, explicit_targs, fn,
22150 				  complain|tf_partial,
22151 				  /*require_all_args=*/false,
22152 				  /*use_default_args=*/false));
22153       if (explicit_targs == error_mark_node)
22154 	goto fail;
22155 
22156       /* Substitute the explicit args into the function type.  This is
22157 	 necessary so that, for instance, explicitly declared function
22158 	 arguments can match null pointed constants.  If we were given
22159 	 an incomplete set of explicit args, we must not do semantic
22160 	 processing during substitution as we could create partial
22161 	 instantiations.  */
22162       for (i = 0; i < len; i++)
22163         {
22164           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
22165           bool parameter_pack = false;
22166 	  tree targ = TREE_VEC_ELT (explicit_targs, i);
22167 
22168           /* Dig out the actual parm.  */
22169           if (TREE_CODE (parm) == TYPE_DECL
22170               || TREE_CODE (parm) == TEMPLATE_DECL)
22171             {
22172               parm = TREE_TYPE (parm);
22173               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
22174             }
22175           else if (TREE_CODE (parm) == PARM_DECL)
22176             {
22177               parm = DECL_INITIAL (parm);
22178               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
22179             }
22180 
22181 	  if (targ == NULL_TREE)
22182 	    /* No explicit argument for this template parameter.  */
22183 	    incomplete = true;
22184 	  else if (parameter_pack && pack_deducible_p (parm, fn))
22185             {
22186               /* Mark the argument pack as "incomplete". We could
22187                  still deduce more arguments during unification.
22188 	         We remove this mark in type_unification_real.  */
22189 	      ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
22190 	      ARGUMENT_PACK_EXPLICIT_ARGS (targ)
22191 		= ARGUMENT_PACK_ARGS (targ);
22192 
22193               /* We have some incomplete argument packs.  */
22194               incomplete = true;
22195             }
22196         }
22197 
22198       if (incomplete)
22199 	{
22200 	  if (!push_tinst_level (fn, explicit_targs))
22201 	    {
22202 	      excessive_deduction_depth = true;
22203 	      goto fail;
22204 	    }
22205 	  ++processing_template_decl;
22206 	  input_location = DECL_SOURCE_LOCATION (fn);
22207 	  /* Ignore any access checks; we'll see them again in
22208 	     instantiate_template and they might have the wrong
22209 	     access path at this point.  */
22210 	  push_deferring_access_checks (dk_deferred);
22211 	  tsubst_flags_t ecomplain = complain | tf_partial | tf_fndecl_type;
22212 	  fntype = tsubst (TREE_TYPE (fn), explicit_targs, ecomplain, NULL_TREE);
22213 	  pop_deferring_access_checks ();
22214 	  input_location = loc;
22215 	  --processing_template_decl;
22216 	  pop_tinst_level ();
22217 
22218 	  if (fntype == error_mark_node)
22219 	    goto fail;
22220 	}
22221 
22222       /* Place the explicitly specified arguments in TARGS.  */
22223       explicit_targs = INNERMOST_TEMPLATE_ARGS (explicit_targs);
22224       for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
22225 	TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
22226       if (!incomplete && CHECKING_P
22227 	  && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
22228 	SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
22229 	  (targs, NUM_TMPL_ARGS (explicit_targs));
22230     }
22231 
22232   if (return_type && strict != DEDUCE_CALL)
22233     {
22234       tree *new_args = XALLOCAVEC (tree, nargs + 1);
22235       new_args[0] = return_type;
22236       memcpy (new_args + 1, args, nargs * sizeof (tree));
22237       args = new_args;
22238       ++nargs;
22239     }
22240 
22241   if (!incomplete)
22242     goto deduced;
22243 
22244   /* Never do unification on the 'this' parameter.  */
22245   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
22246 
22247   if (return_type && strict == DEDUCE_CALL)
22248     {
22249       /* We're deducing for a call to the result of a template conversion
22250          function.  The parms we really want are in return_type.  */
22251       if (INDIRECT_TYPE_P (return_type))
22252 	return_type = TREE_TYPE (return_type);
22253       parms = TYPE_ARG_TYPES (return_type);
22254     }
22255   else if (return_type)
22256     {
22257       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
22258     }
22259 
22260   /* We allow incomplete unification without an error message here
22261      because the standard doesn't seem to explicitly prohibit it.  Our
22262      callers must be ready to deal with unification failures in any
22263      event.  */
22264 
22265   /* If we aren't explaining yet, push tinst context so we can see where
22266      any errors (e.g. from class instantiations triggered by instantiation
22267      of default template arguments) come from.  If we are explaining, this
22268      context is redundant.  */
22269   if (!explain_p && !push_tinst_level (fn, targs))
22270     {
22271       excessive_deduction_depth = true;
22272       goto fail;
22273     }
22274 
22275   ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
22276 			       full_targs, parms, args, nargs, /*subr=*/0,
22277 			       strict, &checks, explain_p);
22278   if (!explain_p)
22279     pop_tinst_level ();
22280   if (!ok)
22281     goto fail;
22282 
22283   /* Now that we have bindings for all of the template arguments,
22284      ensure that the arguments deduced for the template template
22285      parameters have compatible template parameter lists.  We cannot
22286      check this property before we have deduced all template
22287      arguments, because the template parameter types of a template
22288      template parameter might depend on prior template parameters
22289      deduced after the template template parameter.  The following
22290      ill-formed example illustrates this issue:
22291 
22292        template<typename T, template<T> class C> void f(C<5>, T);
22293 
22294        template<int N> struct X {};
22295 
22296        void g() {
22297          f(X<5>(), 5l); // error: template argument deduction fails
22298        }
22299 
22300      The template parameter list of 'C' depends on the template type
22301      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
22302      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
22303      time that we deduce 'C'.  */
22304   if (!template_template_parm_bindings_ok_p
22305            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
22306     {
22307       unify_inconsistent_template_template_parameters (explain_p);
22308       goto fail;
22309     }
22310 
22311  deduced:
22312 
22313   /* CWG2369: Check satisfaction before non-deducible conversions.  */
22314   if (!constraints_satisfied_p (fn, targs))
22315     {
22316       if (explain_p)
22317 	diagnose_constraints (DECL_SOURCE_LOCATION (fn), fn, targs);
22318       goto fail;
22319     }
22320 
22321   /* DR 1391: All parameters have args, now check non-dependent parms for
22322      convertibility.  We don't do this if all args were explicitly specified,
22323      as the standard says that we substitute explicit args immediately.  */
22324   if (incomplete
22325       && check_non_deducible_conversions (parms, args, nargs, fn, strict, flags,
22326 					  convs, explain_p))
22327     goto fail;
22328 
22329   /* All is well so far.  Now, check:
22330 
22331      [temp.deduct]
22332 
22333      When all template arguments have been deduced, all uses of
22334      template parameters in nondeduced contexts are replaced with
22335      the corresponding deduced argument values.  If the
22336      substitution results in an invalid type, as described above,
22337      type deduction fails.  */
22338   if (!push_tinst_level (fn, targs))
22339     {
22340       excessive_deduction_depth = true;
22341       goto fail;
22342     }
22343 
22344   /* Also collect access checks from the instantiation.  */
22345   reopen_deferring_access_checks (checks);
22346 
22347   decl = instantiate_template (fn, targs, complain);
22348 
22349   checks = get_deferred_access_checks ();
22350   pop_deferring_access_checks ();
22351 
22352   pop_tinst_level ();
22353 
22354   if (decl == error_mark_node)
22355     goto fail;
22356 
22357   /* Now perform any access checks encountered during substitution.  */
22358   push_access_scope (decl);
22359   ok = perform_access_checks (checks, complain);
22360   pop_access_scope (decl);
22361   if (!ok)
22362     goto fail;
22363 
22364   /* If we're looking for an exact match, check that what we got
22365      is indeed an exact match.  It might not be if some template
22366      parameters are used in non-deduced contexts.  But don't check
22367      for an exact match if we have dependent template arguments;
22368      in that case we're doing partial ordering, and we already know
22369      that we have two candidates that will provide the actual type.  */
22370   if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
22371     {
22372       tree substed = TREE_TYPE (decl);
22373       unsigned int i;
22374 
22375       tree sarg
22376 	= skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
22377       if (return_type)
22378 	sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
22379       for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
22380 	if (!same_type_p (args[i], TREE_VALUE (sarg)))
22381 	  {
22382 	    unify_type_mismatch (explain_p, args[i],
22383 				 TREE_VALUE (sarg));
22384 	    goto fail;
22385 	  }
22386       if ((i < nargs || sarg)
22387 	  /* add_candidates uses DEDUCE_EXACT for x.operator foo(), but args
22388 	     doesn't contain the trailing void, and conv fns are always ().  */
22389 	  && !DECL_CONV_FN_P (decl))
22390 	{
22391 	  unsigned nsargs = i + list_length (sarg);
22392 	  unify_arity (explain_p, nargs, nsargs);
22393 	  goto fail;
22394 	}
22395     }
22396 
22397   /* After doing deduction with the inherited constructor, actually return an
22398      instantiation of the inheriting constructor.  */
22399   if (orig_fn != fn)
22400     decl = instantiate_template (orig_fn, targs, complain);
22401 
22402   r = decl;
22403 
22404  fail:
22405   --deduction_depth;
22406   if (excessive_deduction_depth)
22407     {
22408       if (deduction_depth == 0)
22409 	/* Reset once we're all the way out.  */
22410 	excessive_deduction_depth = false;
22411     }
22412 
22413   return r;
22414 }
22415 
22416 /* Returns true iff PARM is a forwarding reference in the context of
22417    template argument deduction for TMPL.  */
22418 
22419 static bool
forwarding_reference_p(tree parm,tree tmpl)22420 forwarding_reference_p (tree parm, tree tmpl)
22421 {
22422   /* [temp.deduct.call], "A forwarding reference is an rvalue reference to a
22423      cv-unqualified template parameter ..."  */
22424   if (TYPE_REF_P (parm)
22425       && TYPE_REF_IS_RVALUE (parm)
22426       && TREE_CODE (TREE_TYPE (parm)) == TEMPLATE_TYPE_PARM
22427       && cp_type_quals (TREE_TYPE (parm)) == TYPE_UNQUALIFIED)
22428     {
22429       parm = TREE_TYPE (parm);
22430       /* [temp.deduct.call], "... that does not represent a template parameter
22431 	 of a class template (during class template argument deduction)."  */
22432       if (tmpl
22433 	  && deduction_guide_p (tmpl)
22434 	  && DECL_ARTIFICIAL (tmpl))
22435 	{
22436 	  /* Since the template parameters of a synthesized guide consist of
22437 	     the template parameters of the class template followed by those of
22438 	     the constructor (if any), we can tell if PARM represents a template
22439 	     parameter of the class template by comparing its index with the
22440 	     arity of the class template.  */
22441 	  tree ctmpl = CLASSTYPE_TI_TEMPLATE (TREE_TYPE (TREE_TYPE (tmpl)));
22442 	  if (TEMPLATE_TYPE_IDX (parm)
22443 	      < TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (ctmpl)))
22444 	    return false;
22445 	}
22446       return true;
22447     }
22448   return false;
22449 }
22450 
22451 /* Adjust types before performing type deduction, as described in
22452    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
22453    sections are symmetric.  PARM is the type of a function parameter
22454    or the return type of the conversion function.  ARG is the type of
22455    the argument passed to the call, or the type of the value
22456    initialized with the result of the conversion function.
22457    ARG_EXPR is the original argument expression, which may be null.  */
22458 
22459 static int
maybe_adjust_types_for_deduction(tree tparms,unification_kind_t strict,tree * parm,tree * arg,tree arg_expr)22460 maybe_adjust_types_for_deduction (tree tparms,
22461 				  unification_kind_t strict,
22462 				  tree* parm,
22463 				  tree* arg,
22464 				  tree arg_expr)
22465 {
22466   int result = 0;
22467 
22468   switch (strict)
22469     {
22470     case DEDUCE_CALL:
22471       break;
22472 
22473     case DEDUCE_CONV:
22474       /* Swap PARM and ARG throughout the remainder of this
22475 	 function; the handling is precisely symmetric since PARM
22476 	 will initialize ARG rather than vice versa.  */
22477       std::swap (parm, arg);
22478       break;
22479 
22480     case DEDUCE_EXACT:
22481       /* Core issue #873: Do the DR606 thing (see below) for these cases,
22482 	 too, but here handle it by stripping the reference from PARM
22483 	 rather than by adding it to ARG.  */
22484       if (forwarding_reference_p (*parm, TPARMS_PRIMARY_TEMPLATE (tparms))
22485 	  && TYPE_REF_P (*arg)
22486 	  && !TYPE_REF_IS_RVALUE (*arg))
22487 	*parm = TREE_TYPE (*parm);
22488       /* Nothing else to do in this case.  */
22489       return 0;
22490 
22491     default:
22492       gcc_unreachable ();
22493     }
22494 
22495   if (!TYPE_REF_P (*parm))
22496     {
22497       /* [temp.deduct.call]
22498 
22499 	 If P is not a reference type:
22500 
22501 	 --If A is an array type, the pointer type produced by the
22502 	 array-to-pointer standard conversion (_conv.array_) is
22503 	 used in place of A for type deduction; otherwise,
22504 
22505 	 --If A is a function type, the pointer type produced by
22506 	 the function-to-pointer standard conversion
22507 	 (_conv.func_) is used in place of A for type deduction;
22508 	 otherwise,
22509 
22510 	 --If A is a cv-qualified type, the top level
22511 	 cv-qualifiers of A's type are ignored for type
22512 	 deduction.  */
22513       if (TREE_CODE (*arg) == ARRAY_TYPE)
22514 	*arg = build_pointer_type (TREE_TYPE (*arg));
22515       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
22516 	*arg = build_pointer_type (*arg);
22517       else
22518 	*arg = TYPE_MAIN_VARIANT (*arg);
22519     }
22520 
22521   /* [temp.deduct.call], "If P is a forwarding reference and the argument is
22522      an lvalue, the type 'lvalue reference to A' is used in place of A for
22523      type deduction."  */
22524   if (forwarding_reference_p (*parm, TPARMS_PRIMARY_TEMPLATE (tparms))
22525       && (arg_expr ? lvalue_p (arg_expr)
22526 	  /* try_one_overload doesn't provide an arg_expr, but
22527 	     functions are always lvalues.  */
22528 	  : TREE_CODE (*arg) == FUNCTION_TYPE))
22529     *arg = build_reference_type (*arg);
22530 
22531   /* [temp.deduct.call]
22532 
22533      If P is a cv-qualified type, the top level cv-qualifiers
22534      of P's type are ignored for type deduction.  If P is a
22535      reference type, the type referred to by P is used for
22536      type deduction.  */
22537   *parm = TYPE_MAIN_VARIANT (*parm);
22538   if (TYPE_REF_P (*parm))
22539     {
22540       *parm = TREE_TYPE (*parm);
22541       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
22542     }
22543 
22544   /* DR 322. For conversion deduction, remove a reference type on parm
22545      too (which has been swapped into ARG).  */
22546   if (strict == DEDUCE_CONV && TYPE_REF_P (*arg))
22547     *arg = TREE_TYPE (*arg);
22548 
22549   return result;
22550 }
22551 
22552 /* Subroutine of fn_type_unification.  PARM is a function parameter of a
22553    template which doesn't contain any deducible template parameters; check if
22554    ARG is a suitable match for it.  STRICT, FLAGS and EXPLAIN_P are as in
22555    unify_one_argument.  */
22556 
22557 static int
check_non_deducible_conversion(tree parm,tree arg,unification_kind_t strict,int flags,struct conversion ** conv_p,bool explain_p)22558 check_non_deducible_conversion (tree parm, tree arg, unification_kind_t strict,
22559 				int flags, struct conversion **conv_p,
22560 				bool explain_p)
22561 {
22562   tree type;
22563 
22564   if (!TYPE_P (arg))
22565     type = TREE_TYPE (arg);
22566   else
22567     type = arg;
22568 
22569   if (same_type_p (parm, type))
22570     return unify_success (explain_p);
22571 
22572   tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
22573   if (strict == DEDUCE_CONV)
22574     {
22575       if (can_convert_arg (type, parm, NULL_TREE, flags, complain))
22576 	return unify_success (explain_p);
22577     }
22578   else if (strict == DEDUCE_CALL)
22579     {
22580       bool ok = false;
22581       tree conv_arg = TYPE_P (arg) ? NULL_TREE : arg;
22582       if (conv_p)
22583 	/* Avoid recalculating this in add_function_candidate.  */
22584 	ok = (*conv_p
22585 	      = good_conversion (parm, type, conv_arg, flags, complain));
22586       else
22587 	ok = can_convert_arg (parm, type, conv_arg, flags, complain);
22588       if (ok)
22589 	return unify_success (explain_p);
22590     }
22591 
22592   if (strict == DEDUCE_EXACT)
22593     return unify_type_mismatch (explain_p, parm, arg);
22594   else
22595     return unify_arg_conversion (explain_p, parm, type, arg);
22596 }
22597 
22598 static bool uses_deducible_template_parms (tree type);
22599 
22600 /* Returns true iff the expression EXPR is one from which a template
22601    argument can be deduced.  In other words, if it's an undecorated
22602    use of a template non-type parameter.  */
22603 
22604 static bool
deducible_expression(tree expr)22605 deducible_expression (tree expr)
22606 {
22607   /* Strip implicit conversions and implicit INDIRECT_REFs.  */
22608   while (CONVERT_EXPR_P (expr)
22609 	 || TREE_CODE (expr) == VIEW_CONVERT_EXPR
22610 	 || REFERENCE_REF_P (expr))
22611     expr = TREE_OPERAND (expr, 0);
22612   return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
22613 }
22614 
22615 /* Returns true iff the array domain DOMAIN uses a template parameter in a
22616    deducible way; that is, if it has a max value of <PARM> - 1.  */
22617 
22618 static bool
deducible_array_bound(tree domain)22619 deducible_array_bound (tree domain)
22620 {
22621   if (domain == NULL_TREE)
22622     return false;
22623 
22624   tree max = TYPE_MAX_VALUE (domain);
22625   if (TREE_CODE (max) != MINUS_EXPR)
22626     return false;
22627 
22628   return deducible_expression (TREE_OPERAND (max, 0));
22629 }
22630 
22631 /* Returns true iff the template arguments ARGS use a template parameter
22632    in a deducible way.  */
22633 
22634 static bool
deducible_template_args(tree args)22635 deducible_template_args (tree args)
22636 {
22637   for (int i = 0; i < TREE_VEC_LENGTH (args); ++i)
22638     {
22639       bool deducible;
22640       tree elt = TREE_VEC_ELT (args, i);
22641       if (ARGUMENT_PACK_P (elt))
22642 	deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
22643       else
22644 	{
22645 	  if (PACK_EXPANSION_P (elt))
22646 	    elt = PACK_EXPANSION_PATTERN (elt);
22647 	  if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
22648 	    deducible = true;
22649 	  else if (TYPE_P (elt))
22650 	    deducible = uses_deducible_template_parms (elt);
22651 	  else
22652 	    deducible = deducible_expression (elt);
22653 	}
22654       if (deducible)
22655 	return true;
22656     }
22657   return false;
22658 }
22659 
22660 /* Returns true iff TYPE contains any deducible references to template
22661    parameters, as per 14.8.2.5.  */
22662 
22663 static bool
uses_deducible_template_parms(tree type)22664 uses_deducible_template_parms (tree type)
22665 {
22666   if (PACK_EXPANSION_P (type))
22667     type = PACK_EXPANSION_PATTERN (type);
22668 
22669   /* T
22670      cv-list T
22671      TT<T>
22672      TT<i>
22673      TT<> */
22674   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
22675       || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
22676     return true;
22677 
22678   /* T*
22679      T&
22680      T&&  */
22681   if (INDIRECT_TYPE_P (type))
22682     return uses_deducible_template_parms (TREE_TYPE (type));
22683 
22684   /* T[integer-constant ]
22685      type [i]  */
22686   if (TREE_CODE (type) == ARRAY_TYPE)
22687     return (uses_deducible_template_parms (TREE_TYPE (type))
22688 	    || deducible_array_bound (TYPE_DOMAIN (type)));
22689 
22690   /* T type ::*
22691      type T::*
22692      T T::*
22693      T (type ::*)()
22694      type (T::*)()
22695      type (type ::*)(T)
22696      type (T::*)(T)
22697      T (type ::*)(T)
22698      T (T::*)()
22699      T (T::*)(T) */
22700   if (TYPE_PTRMEM_P (type))
22701     return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
22702 	    || (uses_deducible_template_parms
22703 		(TYPE_PTRMEM_POINTED_TO_TYPE (type))));
22704 
22705   /* template-name <T> (where template-name refers to a class template)
22706      template-name <i> (where template-name refers to a class template) */
22707   if (CLASS_TYPE_P (type)
22708       && CLASSTYPE_TEMPLATE_INFO (type)
22709       && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
22710     return deducible_template_args (INNERMOST_TEMPLATE_ARGS
22711 				    (CLASSTYPE_TI_ARGS (type)));
22712 
22713   /* type (T)
22714      T()
22715      T(T)  */
22716   if (FUNC_OR_METHOD_TYPE_P (type))
22717     {
22718       if (uses_deducible_template_parms (TREE_TYPE (type)))
22719 	return true;
22720       tree parm = TYPE_ARG_TYPES (type);
22721       if (TREE_CODE (type) == METHOD_TYPE)
22722 	parm = TREE_CHAIN (parm);
22723       for (; parm; parm = TREE_CHAIN (parm))
22724 	if (uses_deducible_template_parms (TREE_VALUE (parm)))
22725 	  return true;
22726       if (flag_noexcept_type
22727 	  && TYPE_RAISES_EXCEPTIONS (type)
22728 	  && TREE_PURPOSE (TYPE_RAISES_EXCEPTIONS (type))
22729 	  && deducible_expression (TREE_PURPOSE (TYPE_RAISES_EXCEPTIONS (type))))
22730 	return true;
22731     }
22732 
22733   return false;
22734 }
22735 
22736 /* Subroutine of type_unification_real and unify_pack_expansion to
22737    handle unification of a single P/A pair.  Parameters are as
22738    for those functions.  */
22739 
22740 static int
unify_one_argument(tree tparms,tree targs,tree parm,tree arg,int subr,unification_kind_t strict,bool explain_p)22741 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
22742 		    int subr, unification_kind_t strict,
22743 		    bool explain_p)
22744 {
22745   tree arg_expr = NULL_TREE;
22746   int arg_strict;
22747 
22748   if (arg == error_mark_node || parm == error_mark_node)
22749     return unify_invalid (explain_p);
22750   if (arg == unknown_type_node)
22751     /* We can't deduce anything from this, but we might get all the
22752        template args from other function args.  */
22753     return unify_success (explain_p);
22754 
22755   /* Implicit conversions (Clause 4) will be performed on a function
22756      argument to convert it to the type of the corresponding function
22757      parameter if the parameter type contains no template-parameters that
22758      participate in template argument deduction.  */
22759   if (strict != DEDUCE_EXACT
22760       && TYPE_P (parm) && !uses_deducible_template_parms (parm))
22761     /* For function parameters with no deducible template parameters,
22762        just return.  We'll check non-dependent conversions later.  */
22763     return unify_success (explain_p);
22764 
22765   switch (strict)
22766     {
22767     case DEDUCE_CALL:
22768       arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
22769 		    | UNIFY_ALLOW_MORE_CV_QUAL
22770 		    | UNIFY_ALLOW_DERIVED);
22771       break;
22772 
22773     case DEDUCE_CONV:
22774       arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
22775       break;
22776 
22777     case DEDUCE_EXACT:
22778       arg_strict = UNIFY_ALLOW_NONE;
22779       break;
22780 
22781     default:
22782       gcc_unreachable ();
22783     }
22784 
22785   /* We only do these transformations if this is the top-level
22786      parameter_type_list in a call or declaration matching; in other
22787      situations (nested function declarators, template argument lists) we
22788      won't be comparing a type to an expression, and we don't do any type
22789      adjustments.  */
22790   if (!subr)
22791     {
22792       if (!TYPE_P (arg))
22793 	{
22794 	  gcc_assert (TREE_TYPE (arg) != NULL_TREE);
22795 	  if (type_unknown_p (arg))
22796 	    {
22797 	      /* [temp.deduct.type] A template-argument can be
22798 		 deduced from a pointer to function or pointer
22799 		 to member function argument if the set of
22800 		 overloaded functions does not contain function
22801 		 templates and at most one of a set of
22802 		 overloaded functions provides a unique
22803 		 match.  */
22804 	      resolve_overloaded_unification (tparms, targs, parm,
22805 					      arg, strict,
22806 					      arg_strict, explain_p);
22807 	      /* If a unique match was not found, this is a
22808 	         non-deduced context, so we still succeed. */
22809 	      return unify_success (explain_p);
22810 	    }
22811 
22812 	  arg_expr = arg;
22813 	  arg = unlowered_expr_type (arg);
22814 	  if (arg == error_mark_node)
22815 	    return unify_invalid (explain_p);
22816 	}
22817 
22818       arg_strict |= maybe_adjust_types_for_deduction (tparms, strict,
22819 						      &parm, &arg, arg_expr);
22820     }
22821   else
22822     if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
22823 	!= (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
22824       return unify_template_argument_mismatch (explain_p, parm, arg);
22825 
22826   /* For deduction from an init-list we need the actual list.  */
22827   if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
22828     arg = arg_expr;
22829   return unify (tparms, targs, parm, arg, arg_strict, explain_p);
22830 }
22831 
22832 /* for_each_template_parm callback that always returns 0.  */
22833 
22834 static int
zero_r(tree,void *)22835 zero_r (tree, void *)
22836 {
22837   return 0;
22838 }
22839 
22840 /* for_each_template_parm any_fn callback to handle deduction of a template
22841    type argument from the type of an array bound.  */
22842 
22843 static int
array_deduction_r(tree t,void * data)22844 array_deduction_r (tree t, void *data)
22845 {
22846   tree_pair_p d = (tree_pair_p)data;
22847   tree &tparms = d->purpose;
22848   tree &targs = d->value;
22849 
22850   if (TREE_CODE (t) == ARRAY_TYPE)
22851     if (tree dom = TYPE_DOMAIN (t))
22852       if (tree max = TYPE_MAX_VALUE (dom))
22853 	{
22854 	  if (TREE_CODE (max) == MINUS_EXPR)
22855 	    max = TREE_OPERAND (max, 0);
22856 	  if (TREE_CODE (max) == TEMPLATE_PARM_INDEX)
22857 	    unify (tparms, targs, TREE_TYPE (max), size_type_node,
22858 		   UNIFY_ALLOW_NONE, /*explain*/false);
22859 	}
22860 
22861   /* Keep walking.  */
22862   return 0;
22863 }
22864 
22865 /* Try to deduce any not-yet-deduced template type arguments from the type of
22866    an array bound.  This is handled separately from unify because 14.8.2.5 says
22867    "The type of a type parameter is only deduced from an array bound if it is
22868    not otherwise deduced."  */
22869 
22870 static void
try_array_deduction(tree tparms,tree targs,tree parm)22871 try_array_deduction (tree tparms, tree targs, tree parm)
22872 {
22873   tree_pair_s data = { tparms, targs };
22874   hash_set<tree> visited;
22875   for_each_template_parm (parm, zero_r, &data, &visited,
22876 			  /*nondeduced*/false, array_deduction_r);
22877 }
22878 
22879 /* Most parms like fn_type_unification.
22880 
22881    If SUBR is 1, we're being called recursively (to unify the
22882    arguments of a function or method parameter of a function
22883    template).
22884 
22885    CHECKS is a pointer to a vector of access checks encountered while
22886    substituting default template arguments.  */
22887 
22888 static int
type_unification_real(tree tparms,tree full_targs,tree xparms,const tree * xargs,unsigned int xnargs,int subr,unification_kind_t strict,vec<deferred_access_check,va_gc> ** checks,bool explain_p)22889 type_unification_real (tree tparms,
22890 		       tree full_targs,
22891 		       tree xparms,
22892 		       const tree *xargs,
22893 		       unsigned int xnargs,
22894 		       int subr,
22895 		       unification_kind_t strict,
22896 		       vec<deferred_access_check, va_gc> **checks,
22897 		       bool explain_p)
22898 {
22899   tree parm, arg;
22900   int i;
22901   int ntparms = TREE_VEC_LENGTH (tparms);
22902   int saw_undeduced = 0;
22903   tree parms;
22904   const tree *args;
22905   unsigned int nargs;
22906   unsigned int ia;
22907 
22908   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
22909   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
22910   gcc_assert (ntparms > 0);
22911 
22912   tree targs = INNERMOST_TEMPLATE_ARGS (full_targs);
22913 
22914   /* Reset the number of non-defaulted template arguments contained
22915      in TARGS.  */
22916   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
22917 
22918  again:
22919   parms = xparms;
22920   args = xargs;
22921   nargs = xnargs;
22922 
22923   /* Only fn_type_unification cares about terminal void.  */
22924   if (nargs && args[nargs-1] == void_type_node)
22925     --nargs;
22926 
22927   ia = 0;
22928   while (parms && parms != void_list_node
22929 	 && ia < nargs)
22930     {
22931       parm = TREE_VALUE (parms);
22932 
22933       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
22934 	  && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
22935 	/* For a function parameter pack that occurs at the end of the
22936 	   parameter-declaration-list, the type A of each remaining
22937 	   argument of the call is compared with the type P of the
22938 	   declarator-id of the function parameter pack.  */
22939 	break;
22940 
22941       parms = TREE_CHAIN (parms);
22942 
22943       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
22944 	/* For a function parameter pack that does not occur at the
22945 	   end of the parameter-declaration-list, the type of the
22946 	   parameter pack is a non-deduced context.  */
22947 	continue;
22948 
22949       arg = args[ia];
22950       ++ia;
22951 
22952       if (unify_one_argument (tparms, full_targs, parm, arg, subr, strict,
22953 			      explain_p))
22954 	return 1;
22955     }
22956 
22957   if (parms
22958       && parms != void_list_node
22959       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
22960     {
22961       /* Unify the remaining arguments with the pack expansion type.  */
22962       tree argvec;
22963       tree parmvec = make_tree_vec (1);
22964 
22965       /* Allocate a TREE_VEC and copy in all of the arguments */
22966       argvec = make_tree_vec (nargs - ia);
22967       for (i = 0; ia < nargs; ++ia, ++i)
22968 	TREE_VEC_ELT (argvec, i) = args[ia];
22969 
22970       /* Copy the parameter into parmvec.  */
22971       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
22972       if (unify_pack_expansion (tparms, full_targs, parmvec, argvec, strict,
22973                                 /*subr=*/subr, explain_p))
22974         return 1;
22975 
22976       /* Advance to the end of the list of parameters.  */
22977       parms = TREE_CHAIN (parms);
22978     }
22979 
22980   /* Fail if we've reached the end of the parm list, and more args
22981      are present, and the parm list isn't variadic.  */
22982   if (ia < nargs && parms == void_list_node)
22983     return unify_too_many_arguments (explain_p, nargs, ia);
22984   /* Fail if parms are left and they don't have default values and
22985      they aren't all deduced as empty packs (c++/57397).  This is
22986      consistent with sufficient_parms_p.  */
22987   if (parms && parms != void_list_node
22988       && TREE_PURPOSE (parms) == NULL_TREE)
22989     {
22990       unsigned int count = nargs;
22991       tree p = parms;
22992       bool type_pack_p;
22993       do
22994 	{
22995 	  type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
22996 	  if (!type_pack_p)
22997 	    count++;
22998 	  p = TREE_CHAIN (p);
22999 	}
23000       while (p && p != void_list_node);
23001       if (count != nargs)
23002 	return unify_too_few_arguments (explain_p, ia, count,
23003 					type_pack_p);
23004     }
23005 
23006   if (!subr)
23007     {
23008       tsubst_flags_t complain = (explain_p
23009 				 ? tf_warning_or_error
23010 				 : tf_none);
23011       bool tried_array_deduction = (cxx_dialect < cxx17);
23012 
23013       for (i = 0; i < ntparms; i++)
23014 	{
23015 	  tree targ = TREE_VEC_ELT (targs, i);
23016 	  tree tparm = TREE_VEC_ELT (tparms, i);
23017 
23018 	  /* Clear the "incomplete" flags on all argument packs now so that
23019 	     substituting them into later default arguments works.  */
23020 	  if (targ && ARGUMENT_PACK_P (targ))
23021             {
23022               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
23023               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
23024             }
23025 
23026 	  if (targ || tparm == error_mark_node)
23027 	    continue;
23028 	  tparm = TREE_VALUE (tparm);
23029 
23030 	  if (TREE_CODE (tparm) == TYPE_DECL
23031 	      && !tried_array_deduction)
23032 	    {
23033 	      try_array_deduction (tparms, targs, xparms);
23034 	      tried_array_deduction = true;
23035 	      if (TREE_VEC_ELT (targs, i))
23036 		continue;
23037 	    }
23038 
23039 	  /* If this is an undeduced nontype parameter that depends on
23040 	     a type parameter, try another pass; its type may have been
23041 	     deduced from a later argument than the one from which
23042 	     this parameter can be deduced.  */
23043 	  if (TREE_CODE (tparm) == PARM_DECL
23044 	      && uses_template_parms (TREE_TYPE (tparm))
23045 	      && saw_undeduced < 2)
23046 	    {
23047 	      saw_undeduced = 1;
23048 	      continue;
23049 	    }
23050 
23051 	  /* Core issue #226 (C++0x) [temp.deduct]:
23052 
23053 	     If a template argument has not been deduced, its
23054 	     default template argument, if any, is used.
23055 
23056 	     When we are in C++98 mode, TREE_PURPOSE will either
23057 	     be NULL_TREE or ERROR_MARK_NODE, so we do not need
23058 	     to explicitly check cxx_dialect here.  */
23059 	  if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
23060 	    /* OK, there is a default argument.  Wait until after the
23061 	       conversion check to do substitution.  */
23062 	    continue;
23063 
23064 	  /* If the type parameter is a parameter pack, then it will
23065 	     be deduced to an empty parameter pack.  */
23066 	  if (template_parameter_pack_p (tparm))
23067 	    {
23068 	      tree arg;
23069 
23070 	      if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
23071 		{
23072 		  arg = make_node (NONTYPE_ARGUMENT_PACK);
23073 		  TREE_CONSTANT (arg) = 1;
23074 		}
23075 	      else
23076 		arg = cxx_make_type (TYPE_ARGUMENT_PACK);
23077 
23078 	      SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
23079 
23080 	      TREE_VEC_ELT (targs, i) = arg;
23081 	      continue;
23082 	    }
23083 
23084 	  return unify_parameter_deduction_failure (explain_p, tparm);
23085 	}
23086 
23087       /* During partial ordering, we deduce dependent template args.  */
23088       bool any_dependent_targs = false;
23089 
23090       /* Now substitute into the default template arguments.  */
23091       for (i = 0; i < ntparms; i++)
23092 	{
23093 	  tree targ = TREE_VEC_ELT (targs, i);
23094 	  tree tparm = TREE_VEC_ELT (tparms, i);
23095 
23096 	  if (targ)
23097 	    {
23098 	      if (!any_dependent_targs && dependent_template_arg_p (targ))
23099 		any_dependent_targs = true;
23100 	      continue;
23101 	    }
23102 	  if (tparm == error_mark_node)
23103 	    continue;
23104 
23105 	  tree parm = TREE_VALUE (tparm);
23106 	  tree arg = TREE_PURPOSE (tparm);
23107 	  reopen_deferring_access_checks (*checks);
23108 	  location_t save_loc = input_location;
23109 	  if (DECL_P (parm))
23110 	    input_location = DECL_SOURCE_LOCATION (parm);
23111 
23112 	  if (saw_undeduced == 1
23113 	      && TREE_CODE (parm) == PARM_DECL
23114 	      && uses_template_parms (TREE_TYPE (parm)))
23115 	    {
23116 	      /* The type of this non-type parameter depends on undeduced
23117 		 parameters.  Don't try to use its default argument yet,
23118 		 since we might deduce an argument for it on the next pass,
23119 		 but do check whether the arguments we already have cause
23120 		 substitution failure, so that that happens before we try
23121 		 later default arguments (78489).  */
23122 	      ++processing_template_decl;
23123 	      tree type = tsubst (TREE_TYPE (parm), full_targs, complain,
23124 				  NULL_TREE);
23125 	      --processing_template_decl;
23126 	      if (type == error_mark_node)
23127 		arg = error_mark_node;
23128 	      else
23129 		arg = NULL_TREE;
23130 	    }
23131 	  else
23132 	    {
23133 	      /* Even if the call is happening in template context, getting
23134 		 here means it's non-dependent, and a default argument is
23135 		 considered a separate definition under [temp.decls], so we can
23136 		 do this substitution without processing_template_decl.  This
23137 		 is important if the default argument contains something that
23138 		 might be instantiation-dependent like access (87480).  */
23139 	      processing_template_decl_sentinel s (!any_dependent_targs);
23140 	      tree substed = NULL_TREE;
23141 	      if (saw_undeduced == 1 && !any_dependent_targs)
23142 		{
23143 		  /* First instatiate in template context, in case we still
23144 		     depend on undeduced template parameters.  */
23145 		  ++processing_template_decl;
23146 		  substed = tsubst_template_arg (arg, full_targs, complain,
23147 						 NULL_TREE);
23148 		  --processing_template_decl;
23149 		  if (substed != error_mark_node
23150 		      && !uses_template_parms (substed))
23151 		    /* We replaced all the tparms, substitute again out of
23152 		       template context.  */
23153 		    substed = NULL_TREE;
23154 		}
23155 	      if (!substed)
23156 		substed = tsubst_template_arg (arg, full_targs, complain,
23157 					       NULL_TREE);
23158 
23159 	      if (!uses_template_parms (substed))
23160 		arg = convert_template_argument (parm, substed, full_targs,
23161 						 complain, i, NULL_TREE);
23162 	      else if (saw_undeduced == 1)
23163 		arg = NULL_TREE;
23164 	      else if (!any_dependent_targs)
23165 		arg = error_mark_node;
23166 	    }
23167 
23168 	  input_location = save_loc;
23169 	  *checks = get_deferred_access_checks ();
23170 	  pop_deferring_access_checks ();
23171 
23172 	  if (arg == error_mark_node)
23173 	    return 1;
23174 	  else if (arg)
23175 	    {
23176 	      TREE_VEC_ELT (targs, i) = arg;
23177 	      /* The position of the first default template argument,
23178 		 is also the number of non-defaulted arguments in TARGS.
23179 		 Record that.  */
23180 	      if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
23181 		SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
23182 	    }
23183 	}
23184 
23185       if (saw_undeduced++ == 1)
23186 	goto again;
23187     }
23188 
23189   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
23190     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
23191 
23192   return unify_success (explain_p);
23193 }
23194 
23195 /* Subroutine of type_unification_real.  Args are like the variables
23196    at the call site.  ARG is an overloaded function (or template-id);
23197    we try deducing template args from each of the overloads, and if
23198    only one succeeds, we go with that.  Modifies TARGS and returns
23199    true on success.  */
23200 
23201 static bool
resolve_overloaded_unification(tree tparms,tree targs,tree parm,tree arg,unification_kind_t strict,int sub_strict,bool explain_p)23202 resolve_overloaded_unification (tree tparms,
23203 				tree targs,
23204 				tree parm,
23205 				tree arg,
23206 				unification_kind_t strict,
23207 				int sub_strict,
23208 			        bool explain_p)
23209 {
23210   tree tempargs = copy_node (targs);
23211   int good = 0;
23212   tree goodfn = NULL_TREE;
23213   bool addr_p;
23214 
23215   if (TREE_CODE (arg) == ADDR_EXPR)
23216     {
23217       arg = TREE_OPERAND (arg, 0);
23218       addr_p = true;
23219     }
23220   else
23221     addr_p = false;
23222 
23223   if (TREE_CODE (arg) == COMPONENT_REF)
23224     /* Handle `&x' where `x' is some static or non-static member
23225        function name.  */
23226     arg = TREE_OPERAND (arg, 1);
23227 
23228   if (TREE_CODE (arg) == OFFSET_REF)
23229     arg = TREE_OPERAND (arg, 1);
23230 
23231   /* Strip baselink information.  */
23232   if (BASELINK_P (arg))
23233     arg = BASELINK_FUNCTIONS (arg);
23234 
23235   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
23236     {
23237       /* If we got some explicit template args, we need to plug them into
23238 	 the affected templates before we try to unify, in case the
23239 	 explicit args will completely resolve the templates in question.  */
23240 
23241       int ok = 0;
23242       tree expl_subargs = TREE_OPERAND (arg, 1);
23243       arg = TREE_OPERAND (arg, 0);
23244 
23245       for (lkp_iterator iter (arg); iter; ++iter)
23246 	{
23247 	  tree fn = *iter;
23248 	  tree subargs, elem;
23249 
23250 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
23251 	    continue;
23252 
23253 	  subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
23254 					   expl_subargs, NULL_TREE, tf_none,
23255 					   /*require_all_args=*/true,
23256 					   /*use_default_args=*/true);
23257 	  if (subargs != error_mark_node
23258 	      && !any_dependent_template_arguments_p (subargs))
23259 	    {
23260 	      fn = instantiate_template (fn, subargs, tf_none);
23261 	      if (!constraints_satisfied_p (fn))
23262 		continue;
23263 	      if (undeduced_auto_decl (fn))
23264 		{
23265 		  /* Instantiate the function to deduce its return type.  */
23266 		  ++function_depth;
23267 		  instantiate_decl (fn, /*defer*/false, /*class*/false);
23268 		  --function_depth;
23269 		}
23270 
23271 	      if (flag_noexcept_type)
23272 		maybe_instantiate_noexcept (fn, tf_none);
23273 
23274 	      elem = TREE_TYPE (fn);
23275 	      if (try_one_overload (tparms, targs, tempargs, parm,
23276 				    elem, strict, sub_strict, addr_p, explain_p)
23277 		  && (!goodfn || !same_type_p (goodfn, elem)))
23278 		{
23279 		  goodfn = elem;
23280 		  ++good;
23281 		}
23282 	    }
23283 	  else if (subargs)
23284 	    ++ok;
23285 	}
23286       /* If no templates (or more than one) are fully resolved by the
23287 	 explicit arguments, this template-id is a non-deduced context; it
23288 	 could still be OK if we deduce all template arguments for the
23289 	 enclosing call through other arguments.  */
23290       if (good != 1)
23291 	good = ok;
23292     }
23293   else if (!OVL_P (arg))
23294     /* If ARG is, for example, "(0, &f)" then its type will be unknown
23295        -- but the deduction does not succeed because the expression is
23296        not just the function on its own.  */
23297     return false;
23298   else
23299     for (lkp_iterator iter (arg); iter; ++iter)
23300       {
23301 	tree fn = *iter;
23302 	if (try_one_overload (tparms, targs, tempargs, parm, TREE_TYPE (fn),
23303 			      strict, sub_strict, addr_p, explain_p)
23304 	    && (!goodfn || !decls_match (goodfn, fn)))
23305 	  {
23306 	    goodfn = fn;
23307 	    ++good;
23308 	  }
23309       }
23310 
23311   /* [temp.deduct.type] A template-argument can be deduced from a pointer
23312      to function or pointer to member function argument if the set of
23313      overloaded functions does not contain function templates and at most
23314      one of a set of overloaded functions provides a unique match.
23315 
23316      So if we found multiple possibilities, we return success but don't
23317      deduce anything.  */
23318 
23319   if (good == 1)
23320     {
23321       int i = TREE_VEC_LENGTH (targs);
23322       for (; i--; )
23323 	if (TREE_VEC_ELT (tempargs, i))
23324 	  {
23325 	    tree old = TREE_VEC_ELT (targs, i);
23326 	    tree new_ = TREE_VEC_ELT (tempargs, i);
23327 	    if (new_ && old && ARGUMENT_PACK_P (old)
23328 		&& ARGUMENT_PACK_EXPLICIT_ARGS (old))
23329 	      /* Don't forget explicit template arguments in a pack.  */
23330 	      ARGUMENT_PACK_EXPLICIT_ARGS (new_)
23331 		= ARGUMENT_PACK_EXPLICIT_ARGS (old);
23332 	    TREE_VEC_ELT (targs, i) = new_;
23333 	  }
23334     }
23335   if (good)
23336     return true;
23337 
23338   return false;
23339 }
23340 
23341 /* Core DR 115: In contexts where deduction is done and fails, or in
23342    contexts where deduction is not done, if a template argument list is
23343    specified and it, along with any default template arguments, identifies
23344    a single function template specialization, then the template-id is an
23345    lvalue for the function template specialization.  */
23346 
23347 tree
resolve_nondeduced_context(tree orig_expr,tsubst_flags_t complain)23348 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
23349 {
23350   tree expr, offset, baselink;
23351   bool addr;
23352 
23353   if (!type_unknown_p (orig_expr))
23354     return orig_expr;
23355 
23356   expr = orig_expr;
23357   addr = false;
23358   offset = NULL_TREE;
23359   baselink = NULL_TREE;
23360 
23361   if (TREE_CODE (expr) == ADDR_EXPR)
23362     {
23363       expr = TREE_OPERAND (expr, 0);
23364       addr = true;
23365     }
23366   if (TREE_CODE (expr) == OFFSET_REF)
23367     {
23368       offset = expr;
23369       expr = TREE_OPERAND (expr, 1);
23370     }
23371   if (BASELINK_P (expr))
23372     {
23373       baselink = expr;
23374       expr = BASELINK_FUNCTIONS (expr);
23375     }
23376 
23377   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
23378     {
23379       int good = 0;
23380       tree goodfn = NULL_TREE;
23381 
23382       /* If we got some explicit template args, we need to plug them into
23383 	 the affected templates before we try to unify, in case the
23384 	 explicit args will completely resolve the templates in question.  */
23385 
23386       tree expl_subargs = TREE_OPERAND (expr, 1);
23387       tree arg = TREE_OPERAND (expr, 0);
23388       tree badfn = NULL_TREE;
23389       tree badargs = NULL_TREE;
23390 
23391       for (lkp_iterator iter (arg); iter; ++iter)
23392 	{
23393 	  tree fn = *iter;
23394 	  tree subargs, elem;
23395 
23396 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
23397 	    continue;
23398 
23399 	  subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
23400 					   expl_subargs, NULL_TREE, tf_none,
23401 					   /*require_all_args=*/true,
23402 					   /*use_default_args=*/true);
23403 	  if (subargs != error_mark_node
23404 	      && !any_dependent_template_arguments_p (subargs))
23405 	    {
23406 	      elem = instantiate_template (fn, subargs, tf_none);
23407 	      if (elem == error_mark_node)
23408 		{
23409 		  badfn = fn;
23410 		  badargs = subargs;
23411 		}
23412 	      else if (elem && (!goodfn || !decls_match (goodfn, elem))
23413 		       && constraints_satisfied_p (elem))
23414 		{
23415 		  goodfn = elem;
23416 		  ++good;
23417 		}
23418 	    }
23419 	}
23420       if (good == 1)
23421 	{
23422 	  mark_used (goodfn);
23423 	  expr = goodfn;
23424 	  if (baselink)
23425 	    expr = build_baselink (BASELINK_BINFO (baselink),
23426 				   BASELINK_ACCESS_BINFO (baselink),
23427 				   expr, BASELINK_OPTYPE (baselink));
23428 	  if (offset)
23429 	    {
23430 	      tree base
23431 		= TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
23432 	      expr = build_offset_ref (base, expr, addr, complain);
23433 	    }
23434 	  if (addr)
23435 	    expr = cp_build_addr_expr (expr, complain);
23436 	  return expr;
23437 	}
23438       else if (good == 0 && badargs && (complain & tf_error))
23439 	/* There were no good options and at least one bad one, so let the
23440 	   user know what the problem is.  */
23441 	instantiate_template (badfn, badargs, complain);
23442     }
23443   return orig_expr;
23444 }
23445 
23446 /* As above, but error out if the expression remains overloaded.  */
23447 
23448 tree
resolve_nondeduced_context_or_error(tree exp,tsubst_flags_t complain)23449 resolve_nondeduced_context_or_error (tree exp, tsubst_flags_t complain)
23450 {
23451   exp = resolve_nondeduced_context (exp, complain);
23452   if (type_unknown_p (exp))
23453     {
23454       if (complain & tf_error)
23455 	cxx_incomplete_type_error (exp, TREE_TYPE (exp));
23456       return error_mark_node;
23457     }
23458   return exp;
23459 }
23460 
23461 /* Subroutine of resolve_overloaded_unification; does deduction for a single
23462    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
23463    different overloads deduce different arguments for a given parm.
23464    ADDR_P is true if the expression for which deduction is being
23465    performed was of the form "& fn" rather than simply "fn".
23466 
23467    Returns 1 on success.  */
23468 
23469 static int
try_one_overload(tree tparms,tree orig_targs,tree targs,tree parm,tree arg,unification_kind_t strict,int sub_strict,bool addr_p,bool explain_p)23470 try_one_overload (tree tparms,
23471 		  tree orig_targs,
23472 		  tree targs,
23473 		  tree parm,
23474 		  tree arg,
23475 		  unification_kind_t strict,
23476 		  int sub_strict,
23477 		  bool addr_p,
23478 		  bool explain_p)
23479 {
23480   int nargs;
23481   tree tempargs;
23482   int i;
23483 
23484   if (arg == error_mark_node)
23485     return 0;
23486 
23487   /* [temp.deduct.type] A template-argument can be deduced from a pointer
23488      to function or pointer to member function argument if the set of
23489      overloaded functions does not contain function templates and at most
23490      one of a set of overloaded functions provides a unique match.
23491 
23492      So if this is a template, just return success.  */
23493 
23494   if (uses_template_parms (arg))
23495     return 1;
23496 
23497   if (TREE_CODE (arg) == METHOD_TYPE)
23498     arg = build_ptrmemfunc_type (build_pointer_type (arg));
23499   else if (addr_p)
23500     arg = build_pointer_type (arg);
23501 
23502   sub_strict |= maybe_adjust_types_for_deduction (tparms, strict,
23503 						  &parm, &arg, NULL_TREE);
23504 
23505   /* We don't copy orig_targs for this because if we have already deduced
23506      some template args from previous args, unify would complain when we
23507      try to deduce a template parameter for the same argument, even though
23508      there isn't really a conflict.  */
23509   nargs = TREE_VEC_LENGTH (targs);
23510   tempargs = make_tree_vec (nargs);
23511 
23512   if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
23513     return 0;
23514 
23515   /* First make sure we didn't deduce anything that conflicts with
23516      explicitly specified args.  */
23517   for (i = nargs; i--; )
23518     {
23519       tree elt = TREE_VEC_ELT (tempargs, i);
23520       tree oldelt = TREE_VEC_ELT (orig_targs, i);
23521 
23522       if (!elt)
23523 	/*NOP*/;
23524       else if (uses_template_parms (elt))
23525 	/* Since we're unifying against ourselves, we will fill in
23526 	   template args used in the function parm list with our own
23527 	   template parms.  Discard them.  */
23528 	TREE_VEC_ELT (tempargs, i) = NULL_TREE;
23529       else if (oldelt && ARGUMENT_PACK_P (oldelt))
23530 	{
23531 	  /* Check that the argument at each index of the deduced argument pack
23532 	     is equivalent to the corresponding explicitly specified argument.
23533 	     We may have deduced more arguments than were explicitly specified,
23534 	     and that's OK.  */
23535 
23536 	  /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
23537 	     that's wrong if we deduce the same argument pack from multiple
23538 	     function arguments: it's only incomplete the first time.  */
23539 
23540 	  tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
23541 	  tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
23542 
23543 	  if (TREE_VEC_LENGTH (deduced_pack)
23544 	      < TREE_VEC_LENGTH (explicit_pack))
23545 	    return 0;
23546 
23547 	  for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
23548 	    if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
23549 				      TREE_VEC_ELT (deduced_pack, j)))
23550 	      return 0;
23551 	}
23552       else if (oldelt && !template_args_equal (oldelt, elt))
23553 	return 0;
23554     }
23555 
23556   for (i = nargs; i--; )
23557     {
23558       tree elt = TREE_VEC_ELT (tempargs, i);
23559 
23560       if (elt)
23561 	TREE_VEC_ELT (targs, i) = elt;
23562     }
23563 
23564   return 1;
23565 }
23566 
23567 /* PARM is a template class (perhaps with unbound template
23568    parameters).  ARG is a fully instantiated type.  If ARG can be
23569    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
23570    TARGS are as for unify.  */
23571 
23572 static tree
try_class_unification(tree tparms,tree targs,tree parm,tree arg,bool explain_p)23573 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
23574 		       bool explain_p)
23575 {
23576   tree copy_of_targs;
23577 
23578   if (!CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
23579     return NULL_TREE;
23580   else if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23581     /* Matches anything.  */;
23582   else if (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
23583 	   != most_general_template (CLASSTYPE_TI_TEMPLATE (parm)))
23584     return NULL_TREE;
23585 
23586   /* We need to make a new template argument vector for the call to
23587      unify.  If we used TARGS, we'd clutter it up with the result of
23588      the attempted unification, even if this class didn't work out.
23589      We also don't want to commit ourselves to all the unifications
23590      we've already done, since unification is supposed to be done on
23591      an argument-by-argument basis.  In other words, consider the
23592      following pathological case:
23593 
23594        template <int I, int J, int K>
23595        struct S {};
23596 
23597        template <int I, int J>
23598        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
23599 
23600        template <int I, int J, int K>
23601        void f(S<I, J, K>, S<I, I, I>);
23602 
23603        void g() {
23604 	 S<0, 0, 0> s0;
23605 	 S<0, 1, 2> s2;
23606 
23607 	 f(s0, s2);
23608        }
23609 
23610      Now, by the time we consider the unification involving `s2', we
23611      already know that we must have `f<0, 0, 0>'.  But, even though
23612      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
23613      because there are two ways to unify base classes of S<0, 1, 2>
23614      with S<I, I, I>.  If we kept the already deduced knowledge, we
23615      would reject the possibility I=1.  */
23616   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
23617 
23618   if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23619     {
23620       if (unify_bound_ttp_args (tparms, copy_of_targs, parm, arg, explain_p))
23621 	return NULL_TREE;
23622       return arg;
23623     }
23624 
23625   /* If unification failed, we're done.  */
23626   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
23627 	     CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
23628     return NULL_TREE;
23629 
23630   return arg;
23631 }
23632 
23633 /* Given a template type PARM and a class type ARG, find the unique
23634    base type in ARG that is an instance of PARM.  We do not examine
23635    ARG itself; only its base-classes.  If there is not exactly one
23636    appropriate base class, return NULL_TREE.  PARM may be the type of
23637    a partial specialization, as well as a plain template type.  Used
23638    by unify.  */
23639 
23640 static enum template_base_result
get_template_base(tree tparms,tree targs,tree parm,tree arg,bool explain_p,tree * result)23641 get_template_base (tree tparms, tree targs, tree parm, tree arg,
23642 		   bool explain_p, tree *result)
23643 {
23644   tree rval = NULL_TREE;
23645   tree binfo;
23646 
23647   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
23648 
23649   binfo = TYPE_BINFO (complete_type (arg));
23650   if (!binfo)
23651     {
23652       /* The type could not be completed.  */
23653       *result = NULL_TREE;
23654       return tbr_incomplete_type;
23655     }
23656 
23657   /* Walk in inheritance graph order.  The search order is not
23658      important, and this avoids multiple walks of virtual bases.  */
23659   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
23660     {
23661       tree r = try_class_unification (tparms, targs, parm,
23662 				      BINFO_TYPE (binfo), explain_p);
23663 
23664       if (r)
23665 	{
23666 	  /* If there is more than one satisfactory baseclass, then:
23667 
23668 	       [temp.deduct.call]
23669 
23670 	      If they yield more than one possible deduced A, the type
23671 	      deduction fails.
23672 
23673 	     applies.  */
23674 	  if (rval && !same_type_p (r, rval))
23675 	    {
23676 	      /* [temp.deduct.call]/4.3: If there is a class C that is a
23677 		 (direct or indirect) base class of D and derived (directly or
23678 		 indirectly) from a class B and that would be a valid deduced
23679 		 A, the deduced A cannot be B or pointer to B, respectively. */
23680 	      if (DERIVED_FROM_P (r, rval))
23681 		/* Ignore r.  */
23682 		continue;
23683 	      else if (DERIVED_FROM_P (rval, r))
23684 		/* Ignore rval.  */;
23685 	      else
23686 		{
23687 		  *result = NULL_TREE;
23688 		  return tbr_ambiguous_baseclass;
23689 		}
23690 	    }
23691 
23692 	  rval = r;
23693 	}
23694     }
23695 
23696   *result = rval;
23697   return tbr_success;
23698 }
23699 
23700 /* Returns the level of DECL, which declares a template parameter.  */
23701 
23702 static int
template_decl_level(tree decl)23703 template_decl_level (tree decl)
23704 {
23705   switch (TREE_CODE (decl))
23706     {
23707     case TYPE_DECL:
23708     case TEMPLATE_DECL:
23709       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
23710 
23711     case PARM_DECL:
23712       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
23713 
23714     default:
23715       gcc_unreachable ();
23716     }
23717   return 0;
23718 }
23719 
23720 /* Decide whether ARG can be unified with PARM, considering only the
23721    cv-qualifiers of each type, given STRICT as documented for unify.
23722    Returns nonzero iff the unification is OK on that basis.  */
23723 
23724 static int
check_cv_quals_for_unify(int strict,tree arg,tree parm)23725 check_cv_quals_for_unify (int strict, tree arg, tree parm)
23726 {
23727   int arg_quals = cp_type_quals (arg);
23728   int parm_quals = cp_type_quals (parm);
23729 
23730   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
23731       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
23732     {
23733       /*  Although a CVR qualifier is ignored when being applied to a
23734 	  substituted template parameter ([8.3.2]/1 for example), that
23735 	  does not allow us to unify "const T" with "int&" because both
23736 	  types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
23737 	  It is ok when we're allowing additional CV qualifiers
23738 	  at the outer level [14.8.2.1]/3,1st bullet.  */
23739       if ((TYPE_REF_P (arg)
23740 	   || FUNC_OR_METHOD_TYPE_P (arg))
23741 	  && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
23742 	return 0;
23743 
23744       if ((!INDIRECT_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
23745 	  && (parm_quals & TYPE_QUAL_RESTRICT))
23746 	return 0;
23747     }
23748 
23749   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
23750       && (arg_quals & parm_quals) != parm_quals)
23751     return 0;
23752 
23753   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
23754       && (parm_quals & arg_quals) != arg_quals)
23755     return 0;
23756 
23757   return 1;
23758 }
23759 
23760 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
23761 void
template_parm_level_and_index(tree parm,int * level,int * index)23762 template_parm_level_and_index (tree parm, int* level, int* index)
23763 {
23764   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
23765       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
23766       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23767     {
23768       *index = TEMPLATE_TYPE_IDX (parm);
23769       *level = TEMPLATE_TYPE_LEVEL (parm);
23770     }
23771   else
23772     {
23773       *index = TEMPLATE_PARM_IDX (parm);
23774       *level = TEMPLATE_PARM_LEVEL (parm);
23775     }
23776 }
23777 
23778 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)			\
23779   do {									\
23780     if (unify (TP, TA, P, A, S, EP))					\
23781       return 1;								\
23782   } while (0)
23783 
23784 /* Unifies the remaining arguments in PACKED_ARGS with the pack
23785    expansion at the end of PACKED_PARMS. Returns 0 if the type
23786    deduction succeeds, 1 otherwise. STRICT is the same as in
23787    fn_type_unification. CALL_ARGS_P is true iff PACKED_ARGS is actually a
23788    function call argument list. We'll need to adjust the arguments to make them
23789    types. SUBR tells us if this is from a recursive call to
23790    type_unification_real, or for comparing two template argument
23791    lists. */
23792 
23793 static int
unify_pack_expansion(tree tparms,tree targs,tree packed_parms,tree packed_args,unification_kind_t strict,bool subr,bool explain_p)23794 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
23795                       tree packed_args, unification_kind_t strict,
23796                       bool subr, bool explain_p)
23797 {
23798   tree parm
23799     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
23800   tree pattern = PACK_EXPANSION_PATTERN (parm);
23801   tree pack, packs = NULL_TREE;
23802   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
23803 
23804   /* Add in any args remembered from an earlier partial instantiation.  */
23805   targs = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (parm), targs);
23806   int levels = TMPL_ARGS_DEPTH (targs);
23807 
23808   packed_args = expand_template_argument_pack (packed_args);
23809 
23810   int len = TREE_VEC_LENGTH (packed_args);
23811 
23812   /* Determine the parameter packs we will be deducing from the
23813      pattern, and record their current deductions.  */
23814   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
23815        pack; pack = TREE_CHAIN (pack))
23816     {
23817       tree parm_pack = TREE_VALUE (pack);
23818       int idx, level;
23819 
23820       /* Only template parameter packs can be deduced, not e.g. function
23821 	 parameter packs or __bases or __integer_pack.  */
23822       if (!TEMPLATE_PARM_P (parm_pack))
23823 	continue;
23824 
23825       /* Determine the index and level of this parameter pack.  */
23826       template_parm_level_and_index (parm_pack, &level, &idx);
23827       if (level < levels)
23828 	continue;
23829 
23830       /* Keep track of the parameter packs and their corresponding
23831          argument packs.  */
23832       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
23833       TREE_TYPE (packs) = make_tree_vec (len - start);
23834     }
23835 
23836   /* Loop through all of the arguments that have not yet been
23837      unified and unify each with the pattern.  */
23838   for (i = start; i < len; i++)
23839     {
23840       tree parm;
23841       bool any_explicit = false;
23842       tree arg = TREE_VEC_ELT (packed_args, i);
23843 
23844       /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
23845 	 or the element of its argument pack at the current index if
23846 	 this argument was explicitly specified.  */
23847       for (pack = packs; pack; pack = TREE_CHAIN (pack))
23848         {
23849           int idx, level;
23850           tree arg, pargs;
23851           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
23852 
23853           arg = NULL_TREE;
23854           if (TREE_VALUE (pack)
23855               && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
23856               && (i - start < TREE_VEC_LENGTH (pargs)))
23857             {
23858               any_explicit = true;
23859               arg = TREE_VEC_ELT (pargs, i - start);
23860             }
23861           TMPL_ARG (targs, level, idx) = arg;
23862         }
23863 
23864       /* If we had explicit template arguments, substitute them into the
23865 	 pattern before deduction.  */
23866       if (any_explicit)
23867 	{
23868 	  /* Some arguments might still be unspecified or dependent.  */
23869 	  bool dependent;
23870 	  ++processing_template_decl;
23871 	  dependent = any_dependent_template_arguments_p (targs);
23872 	  if (!dependent)
23873 	    --processing_template_decl;
23874 	  parm = tsubst (pattern, targs,
23875 			 explain_p ? tf_warning_or_error : tf_none,
23876 			 NULL_TREE);
23877 	  if (dependent)
23878 	    --processing_template_decl;
23879 	  if (parm == error_mark_node)
23880 	    return 1;
23881 	}
23882       else
23883 	parm = pattern;
23884 
23885       /* Unify the pattern with the current argument.  */
23886       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
23887 			      explain_p))
23888 	return 1;
23889 
23890       /* For each parameter pack, collect the deduced value.  */
23891       for (pack = packs; pack; pack = TREE_CHAIN (pack))
23892         {
23893           int idx, level;
23894           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
23895 
23896           TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
23897             TMPL_ARG (targs, level, idx);
23898         }
23899     }
23900 
23901   /* Verify that the results of unification with the parameter packs
23902      produce results consistent with what we've seen before, and make
23903      the deduced argument packs available.  */
23904   for (pack = packs; pack; pack = TREE_CHAIN (pack))
23905     {
23906       tree old_pack = TREE_VALUE (pack);
23907       tree new_args = TREE_TYPE (pack);
23908       int i, len = TREE_VEC_LENGTH (new_args);
23909       int idx, level;
23910       bool nondeduced_p = false;
23911 
23912       /* By default keep the original deduced argument pack.
23913 	 If necessary, more specific code is going to update the
23914 	 resulting deduced argument later down in this function.  */
23915       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
23916       TMPL_ARG (targs, level, idx) = old_pack;
23917 
23918       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
23919 	 actually deduce anything.  */
23920       for (i = 0; i < len && !nondeduced_p; ++i)
23921 	if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
23922 	  nondeduced_p = true;
23923       if (nondeduced_p)
23924 	continue;
23925 
23926       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
23927         {
23928           /* If we had fewer function args than explicit template args,
23929              just use the explicits.  */
23930           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
23931           int explicit_len = TREE_VEC_LENGTH (explicit_args);
23932           if (len < explicit_len)
23933             new_args = explicit_args;
23934         }
23935 
23936       if (!old_pack)
23937         {
23938           tree result;
23939           /* Build the deduced *_ARGUMENT_PACK.  */
23940           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
23941             {
23942               result = make_node (NONTYPE_ARGUMENT_PACK);
23943               TREE_CONSTANT (result) = 1;
23944             }
23945           else
23946 	    result = cxx_make_type (TYPE_ARGUMENT_PACK);
23947 
23948           SET_ARGUMENT_PACK_ARGS (result, new_args);
23949 
23950           /* Note the deduced argument packs for this parameter
23951              pack.  */
23952           TMPL_ARG (targs, level, idx) = result;
23953         }
23954       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
23955                && (ARGUMENT_PACK_ARGS (old_pack)
23956                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
23957         {
23958           /* We only had the explicitly-provided arguments before, but
23959              now we have a complete set of arguments.  */
23960           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
23961 
23962           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
23963           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
23964           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
23965         }
23966       else
23967 	{
23968 	  tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
23969 	  tree old_args = ARGUMENT_PACK_ARGS (old_pack);
23970 	  temp_override<int> ovl (TREE_VEC_LENGTH (old_args));
23971 	  /* During template argument deduction for the aggregate deduction
23972 	     candidate, the number of elements in a trailing parameter pack
23973 	     is only deduced from the number of remaining function
23974 	     arguments if it is not otherwise deduced.  */
23975 	  if (cxx_dialect >= cxx20
23976 	      && TREE_VEC_LENGTH (new_args) < TREE_VEC_LENGTH (old_args)
23977 	      /* FIXME This isn't set properly for partial instantiations.  */
23978 	      && TPARMS_PRIMARY_TEMPLATE (tparms)
23979 	      && builtin_guide_p (TPARMS_PRIMARY_TEMPLATE (tparms)))
23980 	    TREE_VEC_LENGTH (old_args) = TREE_VEC_LENGTH (new_args);
23981 	  if (!comp_template_args (old_args, new_args,
23982 				   &bad_old_arg, &bad_new_arg))
23983 	    /* Inconsistent unification of this parameter pack.  */
23984 	    return unify_parameter_pack_inconsistent (explain_p,
23985 						      bad_old_arg,
23986 						      bad_new_arg);
23987 	}
23988     }
23989 
23990   return unify_success (explain_p);
23991 }
23992 
23993 /* Handle unification of the domain of an array.  PARM_DOM and ARG_DOM are
23994    INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs.  The other
23995    parameters and return value are as for unify.  */
23996 
23997 static int
unify_array_domain(tree tparms,tree targs,tree parm_dom,tree arg_dom,bool explain_p)23998 unify_array_domain (tree tparms, tree targs,
23999 		    tree parm_dom, tree arg_dom,
24000 		    bool explain_p)
24001 {
24002   tree parm_max;
24003   tree arg_max;
24004   bool parm_cst;
24005   bool arg_cst;
24006 
24007   /* Our representation of array types uses "N - 1" as the
24008      TYPE_MAX_VALUE for an array with "N" elements, if "N" is
24009      not an integer constant.  We cannot unify arbitrarily
24010      complex expressions, so we eliminate the MINUS_EXPRs
24011      here.  */
24012   parm_max = TYPE_MAX_VALUE (parm_dom);
24013   parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
24014   if (!parm_cst)
24015     {
24016       gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
24017       parm_max = TREE_OPERAND (parm_max, 0);
24018     }
24019   arg_max = TYPE_MAX_VALUE (arg_dom);
24020   arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
24021   if (!arg_cst)
24022     {
24023       /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
24024 	 trying to unify the type of a variable with the type
24025 	 of a template parameter.  For example:
24026 
24027 	   template <unsigned int N>
24028 	   void f (char (&) [N]);
24029 	   int g();
24030 	   void h(int i) {
24031 	     char a[g(i)];
24032 	     f(a);
24033 	   }
24034 
24035 	 Here, the type of the ARG will be "int [g(i)]", and
24036 	 may be a SAVE_EXPR, etc.  */
24037       if (TREE_CODE (arg_max) != MINUS_EXPR)
24038 	return unify_vla_arg (explain_p, arg_dom);
24039       arg_max = TREE_OPERAND (arg_max, 0);
24040     }
24041 
24042   /* If only one of the bounds used a MINUS_EXPR, compensate
24043      by adding one to the other bound.  */
24044   if (parm_cst && !arg_cst)
24045     parm_max = fold_build2_loc (input_location, PLUS_EXPR,
24046 				integer_type_node,
24047 				parm_max,
24048 				integer_one_node);
24049   else if (arg_cst && !parm_cst)
24050     arg_max = fold_build2_loc (input_location, PLUS_EXPR,
24051 			       integer_type_node,
24052 			       arg_max,
24053 			       integer_one_node);
24054 
24055   return unify (tparms, targs, parm_max, arg_max,
24056 		UNIFY_ALLOW_INTEGER, explain_p);
24057 }
24058 
24059 /* Returns whether T, a P or A in unify, is a type, template or expression.  */
24060 
24061 enum pa_kind_t { pa_type, pa_tmpl, pa_expr };
24062 
24063 static pa_kind_t
pa_kind(tree t)24064 pa_kind (tree t)
24065 {
24066   if (PACK_EXPANSION_P (t))
24067     t = PACK_EXPANSION_PATTERN (t);
24068   if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
24069       || TREE_CODE (t) == UNBOUND_CLASS_TEMPLATE
24070       || DECL_TYPE_TEMPLATE_P (t))
24071     return pa_tmpl;
24072   else if (TYPE_P (t))
24073     return pa_type;
24074   else
24075     return pa_expr;
24076 }
24077 
24078 /* Deduce the value of template parameters.  TPARMS is the (innermost)
24079    set of template parameters to a template.  TARGS is the bindings
24080    for those template parameters, as determined thus far; TARGS may
24081    include template arguments for outer levels of template parameters
24082    as well.  PARM is a parameter to a template function, or a
24083    subcomponent of that parameter; ARG is the corresponding argument.
24084    This function attempts to match PARM with ARG in a manner
24085    consistent with the existing assignments in TARGS.  If more values
24086    are deduced, then TARGS is updated.
24087 
24088    Returns 0 if the type deduction succeeds, 1 otherwise.  The
24089    parameter STRICT is a bitwise or of the following flags:
24090 
24091      UNIFY_ALLOW_NONE:
24092        Require an exact match between PARM and ARG.
24093      UNIFY_ALLOW_MORE_CV_QUAL:
24094        Allow the deduced ARG to be more cv-qualified (by qualification
24095        conversion) than ARG.
24096      UNIFY_ALLOW_LESS_CV_QUAL:
24097        Allow the deduced ARG to be less cv-qualified than ARG.
24098      UNIFY_ALLOW_DERIVED:
24099        Allow the deduced ARG to be a template base class of ARG,
24100        or a pointer to a template base class of the type pointed to by
24101        ARG.
24102      UNIFY_ALLOW_INTEGER:
24103        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
24104        case for more information.
24105      UNIFY_ALLOW_OUTER_LEVEL:
24106        This is the outermost level of a deduction. Used to determine validity
24107        of qualification conversions. A valid qualification conversion must
24108        have const qualified pointers leading up to the inner type which
24109        requires additional CV quals, except at the outer level, where const
24110        is not required [conv.qual]. It would be normal to set this flag in
24111        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
24112      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
24113        This is the outermost level of a deduction, and PARM can be more CV
24114        qualified at this point.
24115      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
24116        This is the outermost level of a deduction, and PARM can be less CV
24117        qualified at this point.  */
24118 
24119 static int
unify(tree tparms,tree targs,tree parm,tree arg,int strict,bool explain_p)24120 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
24121        bool explain_p)
24122 {
24123   int idx;
24124   tree targ;
24125   tree tparm;
24126   int strict_in = strict;
24127   tsubst_flags_t complain = (explain_p
24128 			     ? tf_warning_or_error
24129 			     : tf_none);
24130 
24131   /* I don't think this will do the right thing with respect to types.
24132      But the only case I've seen it in so far has been array bounds, where
24133      signedness is the only information lost, and I think that will be
24134      okay.  VIEW_CONVERT_EXPR can appear with class NTTP, thanks to
24135      finish_id_expression_1, and are also OK.  */
24136   while (CONVERT_EXPR_P (parm) || TREE_CODE (parm) == VIEW_CONVERT_EXPR)
24137     parm = TREE_OPERAND (parm, 0);
24138 
24139   if (arg == error_mark_node)
24140     return unify_invalid (explain_p);
24141   if (arg == unknown_type_node
24142       || arg == init_list_type_node)
24143     /* We can't deduce anything from this, but we might get all the
24144        template args from other function args.  */
24145     return unify_success (explain_p);
24146 
24147   if (parm == any_targ_node || arg == any_targ_node)
24148     return unify_success (explain_p);
24149 
24150   /* If PARM uses template parameters, then we can't bail out here,
24151      even if ARG == PARM, since we won't record unifications for the
24152      template parameters.  We might need them if we're trying to
24153      figure out which of two things is more specialized.  */
24154   if (arg == parm && !uses_template_parms (parm))
24155     return unify_success (explain_p);
24156 
24157   /* Handle init lists early, so the rest of the function can assume
24158      we're dealing with a type. */
24159   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
24160     {
24161       tree elttype;
24162       tree orig_parm = parm;
24163 
24164       if (!is_std_init_list (parm)
24165 	  && TREE_CODE (parm) != ARRAY_TYPE)
24166 	/* We can only deduce from an initializer list argument if the
24167 	   parameter is std::initializer_list or an array; otherwise this
24168 	   is a non-deduced context. */
24169 	return unify_success (explain_p);
24170 
24171       if (TREE_CODE (parm) == ARRAY_TYPE)
24172 	elttype = TREE_TYPE (parm);
24173       else
24174 	{
24175 	  elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
24176 	  /* Deduction is defined in terms of a single type, so just punt
24177 	     on the (bizarre) std::initializer_list<T...>.  */
24178 	  if (PACK_EXPANSION_P (elttype))
24179 	    return unify_success (explain_p);
24180 	}
24181 
24182       if (strict != DEDUCE_EXACT
24183 	  && TYPE_P (elttype)
24184 	  && !uses_deducible_template_parms (elttype))
24185 	/* If ELTTYPE has no deducible template parms, skip deduction from
24186 	   the list elements.  */;
24187       else
24188 	for (auto &e: CONSTRUCTOR_ELTS (arg))
24189 	  {
24190 	    tree elt = e.value;
24191 	    int elt_strict = strict;
24192 
24193 	    if (elt == error_mark_node)
24194 	      return unify_invalid (explain_p);
24195 
24196 	    if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
24197 	      {
24198 		tree type = TREE_TYPE (elt);
24199 		if (type == error_mark_node)
24200 		  return unify_invalid (explain_p);
24201 		/* It should only be possible to get here for a call.  */
24202 		gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
24203 		elt_strict |= maybe_adjust_types_for_deduction
24204 		  (tparms, DEDUCE_CALL, &elttype, &type, elt);
24205 		elt = type;
24206 	      }
24207 
24208 	  RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
24209 				   explain_p);
24210 	}
24211 
24212       if (TREE_CODE (parm) == ARRAY_TYPE
24213 	  && deducible_array_bound (TYPE_DOMAIN (parm)))
24214 	{
24215 	  /* Also deduce from the length of the initializer list.  */
24216 	  tree max = size_int (CONSTRUCTOR_NELTS (arg));
24217 	  tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
24218 	  if (idx == error_mark_node)
24219 	    return unify_invalid (explain_p);
24220 	  return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
24221 				     idx, explain_p);
24222 	}
24223 
24224       /* If the std::initializer_list<T> deduction worked, replace the
24225 	 deduced A with std::initializer_list<A>.  */
24226       if (orig_parm != parm)
24227 	{
24228 	  idx = TEMPLATE_TYPE_IDX (orig_parm);
24229 	  targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24230 	  targ = listify (targ);
24231 	  TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
24232 	}
24233       return unify_success (explain_p);
24234     }
24235 
24236   /* If parm and arg aren't the same kind of thing (template, type, or
24237      expression), fail early.  */
24238   if (pa_kind (parm) != pa_kind (arg))
24239     return unify_invalid (explain_p);
24240 
24241   /* Immediately reject some pairs that won't unify because of
24242      cv-qualification mismatches.  */
24243   if (TREE_CODE (arg) == TREE_CODE (parm)
24244       && TYPE_P (arg)
24245       /* It is the elements of the array which hold the cv quals of an array
24246 	 type, and the elements might be template type parms. We'll check
24247 	 when we recurse.  */
24248       && TREE_CODE (arg) != ARRAY_TYPE
24249       /* We check the cv-qualifiers when unifying with template type
24250 	 parameters below.  We want to allow ARG `const T' to unify with
24251 	 PARM `T' for example, when computing which of two templates
24252 	 is more specialized, for example.  */
24253       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
24254       && !check_cv_quals_for_unify (strict_in, arg, parm))
24255     return unify_cv_qual_mismatch (explain_p, parm, arg);
24256 
24257   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
24258       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
24259     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
24260   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
24261   strict &= ~UNIFY_ALLOW_DERIVED;
24262   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
24263   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
24264 
24265   switch (TREE_CODE (parm))
24266     {
24267     case TYPENAME_TYPE:
24268     case SCOPE_REF:
24269     case UNBOUND_CLASS_TEMPLATE:
24270       /* In a type which contains a nested-name-specifier, template
24271 	 argument values cannot be deduced for template parameters used
24272 	 within the nested-name-specifier.  */
24273       return unify_success (explain_p);
24274 
24275     case TEMPLATE_TYPE_PARM:
24276     case TEMPLATE_TEMPLATE_PARM:
24277     case BOUND_TEMPLATE_TEMPLATE_PARM:
24278       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
24279       if (error_operand_p (tparm))
24280 	return unify_invalid (explain_p);
24281 
24282       if (TEMPLATE_TYPE_LEVEL (parm)
24283 	  != template_decl_level (tparm))
24284 	/* The PARM is not one we're trying to unify.  Just check
24285 	   to see if it matches ARG.  */
24286 	{
24287 	  if (TREE_CODE (arg) == TREE_CODE (parm)
24288 	      && (is_auto (parm) ? is_auto (arg)
24289 		  : same_type_p (parm, arg)))
24290 	    return unify_success (explain_p);
24291 	  else
24292 	    return unify_type_mismatch (explain_p, parm, arg);
24293 	}
24294       idx = TEMPLATE_TYPE_IDX (parm);
24295       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24296       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
24297       if (error_operand_p (tparm))
24298 	return unify_invalid (explain_p);
24299 
24300       /* Check for mixed types and values.  */
24301       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
24302 	   && TREE_CODE (tparm) != TYPE_DECL)
24303 	  || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24304 	      && TREE_CODE (tparm) != TEMPLATE_DECL))
24305 	gcc_unreachable ();
24306 
24307       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24308 	{
24309 	  if ((strict_in & UNIFY_ALLOW_DERIVED)
24310 	      && CLASS_TYPE_P (arg))
24311 	    {
24312 	      /* First try to match ARG directly.  */
24313 	      tree t = try_class_unification (tparms, targs, parm, arg,
24314 					      explain_p);
24315 	      if (!t)
24316 		{
24317 		  /* Otherwise, look for a suitable base of ARG, as below.  */
24318 		  enum template_base_result r;
24319 		  r = get_template_base (tparms, targs, parm, arg,
24320 					 explain_p, &t);
24321 		  if (!t)
24322 		    return unify_no_common_base (explain_p, r, parm, arg);
24323 		  arg = t;
24324 		}
24325 	    }
24326 	  /* ARG must be constructed from a template class or a template
24327 	     template parameter.  */
24328 	  else if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
24329 		   && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
24330 	    return unify_template_deduction_failure (explain_p, parm, arg);
24331 
24332 	  /* Deduce arguments T, i from TT<T> or TT<i>.  */
24333 	  if (unify_bound_ttp_args (tparms, targs, parm, arg, explain_p))
24334 	    return 1;
24335 
24336 	  arg = TYPE_TI_TEMPLATE (arg);
24337 	  if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
24338 	    /* If the template is a template template parameter, use the
24339 	       TEMPLATE_TEMPLATE_PARM for matching.  */
24340 	    arg = TREE_TYPE (arg);
24341 
24342 	  /* Fall through to deduce template name.  */
24343 	}
24344 
24345       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24346 	  || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24347 	{
24348 	  /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
24349 
24350 	  /* Simple cases: Value already set, does match or doesn't.  */
24351 	  if (targ != NULL_TREE && template_args_equal (targ, arg))
24352 	    return unify_success (explain_p);
24353 	  else if (targ)
24354 	    return unify_inconsistency (explain_p, parm, targ, arg);
24355 	}
24356       else
24357 	{
24358 	  /* If PARM is `const T' and ARG is only `int', we don't have
24359 	     a match unless we are allowing additional qualification.
24360 	     If ARG is `const int' and PARM is just `T' that's OK;
24361 	     that binds `const int' to `T'.  */
24362 	  if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
24363 					 arg, parm))
24364 	    return unify_cv_qual_mismatch (explain_p, parm, arg);
24365 
24366 	  /* Consider the case where ARG is `const volatile int' and
24367 	     PARM is `const T'.  Then, T should be `volatile int'.  */
24368 	  arg = cp_build_qualified_type_real
24369 	    (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
24370 	  if (arg == error_mark_node)
24371 	    return unify_invalid (explain_p);
24372 
24373 	  /* Simple cases: Value already set, does match or doesn't.  */
24374 	  if (targ != NULL_TREE && same_type_p (targ, arg))
24375 	    return unify_success (explain_p);
24376 	  else if (targ)
24377 	    return unify_inconsistency (explain_p, parm, targ, arg);
24378 
24379 	  /* Make sure that ARG is not a variable-sized array.  (Note
24380 	     that were talking about variable-sized arrays (like
24381 	     `int[n]'), rather than arrays of unknown size (like
24382 	     `int[]').)  We'll get very confused by such a type since
24383 	     the bound of the array is not constant, and therefore
24384 	     not mangleable.  Besides, such types are not allowed in
24385 	     ISO C++, so we can do as we please here.  We do allow
24386 	     them for 'auto' deduction, since that isn't ABI-exposed.  */
24387 	  if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
24388 	    return unify_vla_arg (explain_p, arg);
24389 
24390 	  /* Strip typedefs as in convert_template_argument.  */
24391 	  arg = canonicalize_type_argument (arg, tf_none);
24392 	}
24393 
24394       /* If ARG is a parameter pack or an expansion, we cannot unify
24395 	 against it unless PARM is also a parameter pack.  */
24396       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
24397 	  && !template_parameter_pack_p (parm))
24398 	return unify_parameter_pack_mismatch (explain_p, parm, arg);
24399 
24400       /* If the argument deduction results is a METHOD_TYPE,
24401          then there is a problem.
24402          METHOD_TYPE doesn't map to any real C++ type the result of
24403 	 the deduction cannot be of that type.  */
24404       if (TREE_CODE (arg) == METHOD_TYPE)
24405 	return unify_method_type_error (explain_p, arg);
24406 
24407       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
24408       return unify_success (explain_p);
24409 
24410     case TEMPLATE_PARM_INDEX:
24411       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
24412       if (error_operand_p (tparm))
24413 	return unify_invalid (explain_p);
24414 
24415       if (TEMPLATE_PARM_LEVEL (parm)
24416 	  != template_decl_level (tparm))
24417 	{
24418 	  /* The PARM is not one we're trying to unify.  Just check
24419 	     to see if it matches ARG.  */
24420 	  int result = !(TREE_CODE (arg) == TREE_CODE (parm)
24421 			 && cp_tree_equal (parm, arg));
24422 	  if (result)
24423 	    unify_expression_unequal (explain_p, parm, arg);
24424 	  return result;
24425 	}
24426 
24427       idx = TEMPLATE_PARM_IDX (parm);
24428       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24429 
24430       if (targ)
24431 	{
24432 	  if ((strict & UNIFY_ALLOW_INTEGER)
24433 	      && TREE_TYPE (targ) && TREE_TYPE (arg)
24434 	      && CP_INTEGRAL_TYPE_P (TREE_TYPE (targ)))
24435 	    /* We're deducing from an array bound, the type doesn't matter.  */
24436 	    arg = fold_convert (TREE_TYPE (targ), arg);
24437 	  int x = !cp_tree_equal (targ, arg);
24438 	  if (x)
24439 	    unify_inconsistency (explain_p, parm, targ, arg);
24440 	  return x;
24441 	}
24442 
24443       /* [temp.deduct.type] If, in the declaration of a function template
24444 	 with a non-type template-parameter, the non-type
24445 	 template-parameter is used in an expression in the function
24446 	 parameter-list and, if the corresponding template-argument is
24447 	 deduced, the template-argument type shall match the type of the
24448 	 template-parameter exactly, except that a template-argument
24449 	 deduced from an array bound may be of any integral type.
24450 	 The non-type parameter might use already deduced type parameters.  */
24451       tparm = TREE_TYPE (parm);
24452       if (TEMPLATE_PARM_LEVEL (parm) > TMPL_ARGS_DEPTH (targs))
24453 	/* We don't have enough levels of args to do any substitution.  This
24454 	   can happen in the context of -fnew-ttp-matching.  */;
24455       else
24456 	{
24457 	  ++processing_template_decl;
24458 	  tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
24459 	  --processing_template_decl;
24460 
24461 	  if (tree a = type_uses_auto (tparm))
24462 	    {
24463 	      tparm = do_auto_deduction (tparm, arg, a,
24464 					 complain, adc_unify, targs,
24465 					 LOOKUP_NORMAL,
24466 					 TPARMS_PRIMARY_TEMPLATE (tparms));
24467 	      if (tparm == error_mark_node)
24468 		return 1;
24469 	    }
24470 	}
24471 
24472       if (!TREE_TYPE (arg)
24473 	  || TREE_CODE (TREE_TYPE (arg)) == DEPENDENT_OPERATOR_TYPE)
24474 	/* Template-parameter dependent expression.  Just accept it for now.
24475 	   It will later be processed in convert_template_argument.  */
24476 	;
24477       else if (same_type_ignoring_top_level_qualifiers_p
24478 	       (non_reference (TREE_TYPE (arg)),
24479 		non_reference (tparm)))
24480 	/* OK.  Ignore top-level quals here because a class-type template
24481 	   parameter object is const.  */;
24482       else if ((strict & UNIFY_ALLOW_INTEGER)
24483 	       && CP_INTEGRAL_TYPE_P (tparm))
24484 	/* Convert the ARG to the type of PARM; the deduced non-type
24485 	   template argument must exactly match the types of the
24486 	   corresponding parameter.  */
24487 	arg = fold (build_nop (tparm, arg));
24488       else if (uses_template_parms (tparm))
24489 	{
24490 	  /* We haven't deduced the type of this parameter yet.  */
24491 	  if (cxx_dialect >= cxx17
24492 	      /* We deduce from array bounds in try_array_deduction.  */
24493 	      && !(strict & UNIFY_ALLOW_INTEGER)
24494 	      && TEMPLATE_PARM_LEVEL (parm) <= TMPL_ARGS_DEPTH (targs))
24495 	    {
24496 	      /* Deduce it from the non-type argument.  As above, ignore
24497 		 top-level quals here too.  */
24498 	      tree atype = cv_unqualified (TREE_TYPE (arg));
24499 	      RECUR_AND_CHECK_FAILURE (tparms, targs,
24500 				       tparm, atype,
24501 				       UNIFY_ALLOW_NONE, explain_p);
24502 	      /* Now check whether the type of this parameter is still
24503 		 dependent, and give up if so.  */
24504 	      ++processing_template_decl;
24505 	      tparm = tsubst (TREE_TYPE (parm), targs, tf_none, NULL_TREE);
24506 	      --processing_template_decl;
24507 	      if (uses_template_parms (tparm))
24508 		return unify_success (explain_p);
24509 	    }
24510 	  else
24511 	    /* Try again later.  */
24512 	    return unify_success (explain_p);
24513 	}
24514       else
24515 	return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
24516 
24517       /* If ARG is a parameter pack or an expansion, we cannot unify
24518 	 against it unless PARM is also a parameter pack.  */
24519       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
24520 	  && !TEMPLATE_PARM_PARAMETER_PACK (parm))
24521 	return unify_parameter_pack_mismatch (explain_p, parm, arg);
24522 
24523       {
24524 	bool removed_attr = false;
24525 	arg = strip_typedefs_expr (arg, &removed_attr);
24526       }
24527       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
24528       return unify_success (explain_p);
24529 
24530     case PTRMEM_CST:
24531      {
24532 	/* A pointer-to-member constant can be unified only with
24533 	 another constant.  */
24534       if (TREE_CODE (arg) != PTRMEM_CST)
24535 	return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
24536 
24537       /* Just unify the class member. It would be useless (and possibly
24538 	 wrong, depending on the strict flags) to unify also
24539 	 PTRMEM_CST_CLASS, because we want to be sure that both parm and
24540 	 arg refer to the same variable, even if through different
24541 	 classes. For instance:
24542 
24543 	 struct A { int x; };
24544 	 struct B : A { };
24545 
24546 	 Unification of &A::x and &B::x must succeed.  */
24547       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
24548 		    PTRMEM_CST_MEMBER (arg), strict, explain_p);
24549      }
24550 
24551     case POINTER_TYPE:
24552       {
24553 	if (!TYPE_PTR_P (arg))
24554 	  return unify_type_mismatch (explain_p, parm, arg);
24555 
24556 	/* [temp.deduct.call]
24557 
24558 	   A can be another pointer or pointer to member type that can
24559 	   be converted to the deduced A via a qualification
24560 	   conversion (_conv.qual_).
24561 
24562 	   We pass down STRICT here rather than UNIFY_ALLOW_NONE.
24563 	   This will allow for additional cv-qualification of the
24564 	   pointed-to types if appropriate.  */
24565 
24566 	if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
24567 	  /* The derived-to-base conversion only persists through one
24568 	     level of pointers.  */
24569 	  strict |= (strict_in & UNIFY_ALLOW_DERIVED);
24570 
24571 	return unify (tparms, targs, TREE_TYPE (parm),
24572 		      TREE_TYPE (arg), strict, explain_p);
24573       }
24574 
24575     case REFERENCE_TYPE:
24576       if (!TYPE_REF_P (arg))
24577 	return unify_type_mismatch (explain_p, parm, arg);
24578       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24579 		    strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
24580 
24581     case ARRAY_TYPE:
24582       if (TREE_CODE (arg) != ARRAY_TYPE)
24583 	return unify_type_mismatch (explain_p, parm, arg);
24584       if ((TYPE_DOMAIN (parm) == NULL_TREE)
24585 	  != (TYPE_DOMAIN (arg) == NULL_TREE))
24586 	return unify_type_mismatch (explain_p, parm, arg);
24587       RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24588 			       strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
24589       if (TYPE_DOMAIN (parm) != NULL_TREE)
24590 	return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
24591 				   TYPE_DOMAIN (arg), explain_p);
24592       return unify_success (explain_p);
24593 
24594     case REAL_TYPE:
24595     case COMPLEX_TYPE:
24596     case VECTOR_TYPE:
24597     case INTEGER_TYPE:
24598     case BOOLEAN_TYPE:
24599     case ENUMERAL_TYPE:
24600     case VOID_TYPE:
24601     case OPAQUE_TYPE:
24602     case NULLPTR_TYPE:
24603       if (TREE_CODE (arg) != TREE_CODE (parm))
24604 	return unify_type_mismatch (explain_p, parm, arg);
24605 
24606       /* We have already checked cv-qualification at the top of the
24607 	 function.  */
24608       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
24609 	return unify_type_mismatch (explain_p, parm, arg);
24610 
24611       /* As far as unification is concerned, this wins.	 Later checks
24612 	 will invalidate it if necessary.  */
24613       return unify_success (explain_p);
24614 
24615       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
24616       /* Type INTEGER_CST can come from ordinary constant template args.  */
24617     case INTEGER_CST:
24618       while (CONVERT_EXPR_P (arg))
24619 	arg = TREE_OPERAND (arg, 0);
24620 
24621       if (TREE_CODE (arg) != INTEGER_CST)
24622 	return unify_template_argument_mismatch (explain_p, parm, arg);
24623       return (tree_int_cst_equal (parm, arg)
24624 	      ? unify_success (explain_p)
24625 	      : unify_template_argument_mismatch (explain_p, parm, arg));
24626 
24627     case TREE_VEC:
24628       {
24629 	int i, len, argslen;
24630 	int parm_variadic_p = 0;
24631 
24632 	if (TREE_CODE (arg) != TREE_VEC)
24633 	  return unify_template_argument_mismatch (explain_p, parm, arg);
24634 
24635 	len = TREE_VEC_LENGTH (parm);
24636 	argslen = TREE_VEC_LENGTH (arg);
24637 
24638 	/* Check for pack expansions in the parameters.  */
24639 	for (i = 0; i < len; ++i)
24640 	  {
24641 	    if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
24642 	      {
24643 		if (i == len - 1)
24644 		  /* We can unify against something with a trailing
24645 		     parameter pack.  */
24646 		  parm_variadic_p = 1;
24647 		else
24648 		  /* [temp.deduct.type]/9: If the template argument list of
24649 		     P contains a pack expansion that is not the last
24650 		     template argument, the entire template argument list
24651 		     is a non-deduced context.  */
24652 		  return unify_success (explain_p);
24653 	      }
24654 	  }
24655 
24656         /* If we don't have enough arguments to satisfy the parameters
24657            (not counting the pack expression at the end), or we have
24658            too many arguments for a parameter list that doesn't end in
24659            a pack expression, we can't unify.  */
24660 	if (parm_variadic_p
24661 	    ? argslen < len - parm_variadic_p
24662 	    : argslen != len)
24663 	  return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
24664 
24665 	/* Unify all of the parameters that precede the (optional)
24666 	   pack expression.  */
24667 	for (i = 0; i < len - parm_variadic_p; ++i)
24668 	  {
24669 	    RECUR_AND_CHECK_FAILURE (tparms, targs,
24670 				     TREE_VEC_ELT (parm, i),
24671 				     TREE_VEC_ELT (arg, i),
24672 				     UNIFY_ALLOW_NONE, explain_p);
24673 	  }
24674 	if (parm_variadic_p)
24675 	  return unify_pack_expansion (tparms, targs, parm, arg,
24676 				       DEDUCE_EXACT,
24677 				       /*subr=*/true, explain_p);
24678 	return unify_success (explain_p);
24679       }
24680 
24681     case RECORD_TYPE:
24682     case UNION_TYPE:
24683       if (TREE_CODE (arg) != TREE_CODE (parm))
24684 	return unify_type_mismatch (explain_p, parm, arg);
24685 
24686       if (TYPE_PTRMEMFUNC_P (parm))
24687 	{
24688 	  if (!TYPE_PTRMEMFUNC_P (arg))
24689 	    return unify_type_mismatch (explain_p, parm, arg);
24690 
24691 	  return unify (tparms, targs,
24692 			TYPE_PTRMEMFUNC_FN_TYPE (parm),
24693 			TYPE_PTRMEMFUNC_FN_TYPE (arg),
24694 			strict, explain_p);
24695 	}
24696       else if (TYPE_PTRMEMFUNC_P (arg))
24697 	return unify_type_mismatch (explain_p, parm, arg);
24698 
24699       if (CLASSTYPE_TEMPLATE_INFO (parm))
24700 	{
24701 	  tree t = NULL_TREE;
24702 
24703 	  if (strict_in & UNIFY_ALLOW_DERIVED)
24704 	    {
24705 	      /* First, we try to unify the PARM and ARG directly.  */
24706 	      t = try_class_unification (tparms, targs,
24707 					 parm, arg, explain_p);
24708 
24709 	      if (!t)
24710 		{
24711 		  /* Fallback to the special case allowed in
24712 		     [temp.deduct.call]:
24713 
24714 		       If P is a class, and P has the form
24715 		       template-id, then A can be a derived class of
24716 		       the deduced A.  Likewise, if P is a pointer to
24717 		       a class of the form template-id, A can be a
24718 		       pointer to a derived class pointed to by the
24719 		       deduced A.  */
24720 		  enum template_base_result r;
24721 		  r = get_template_base (tparms, targs, parm, arg,
24722 					 explain_p, &t);
24723 
24724 		  if (!t)
24725 		    {
24726 		      /* Don't give the derived diagnostic if we're
24727 			 already dealing with the same template.  */
24728 		      bool same_template
24729 			= (CLASSTYPE_TEMPLATE_INFO (arg)
24730 			   && (CLASSTYPE_TI_TEMPLATE (parm)
24731 			       == CLASSTYPE_TI_TEMPLATE (arg)));
24732 		      return unify_no_common_base (explain_p && !same_template,
24733 						   r, parm, arg);
24734 		    }
24735 		}
24736 	    }
24737 	  else if (CLASSTYPE_TEMPLATE_INFO (arg)
24738 		   && (CLASSTYPE_TI_TEMPLATE (parm)
24739 		       == CLASSTYPE_TI_TEMPLATE (arg)))
24740 	    /* Perhaps PARM is something like S<U> and ARG is S<int>.
24741 	       Then, we should unify `int' and `U'.  */
24742 	    t = arg;
24743 	  else
24744 	    /* There's no chance of unification succeeding.  */
24745 	    return unify_type_mismatch (explain_p, parm, arg);
24746 
24747 	  return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
24748 			CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
24749 	}
24750       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
24751 	return unify_type_mismatch (explain_p, parm, arg);
24752       return unify_success (explain_p);
24753 
24754     case METHOD_TYPE:
24755     case FUNCTION_TYPE:
24756       {
24757 	unsigned int nargs;
24758 	tree *args;
24759 	tree a;
24760 	unsigned int i;
24761 
24762 	if (TREE_CODE (arg) != TREE_CODE (parm))
24763 	  return unify_type_mismatch (explain_p, parm, arg);
24764 
24765 	/* CV qualifications for methods can never be deduced, they must
24766 	   match exactly.  We need to check them explicitly here,
24767 	   because type_unification_real treats them as any other
24768 	   cv-qualified parameter.  */
24769 	if (TREE_CODE (parm) == METHOD_TYPE
24770 	    && (!check_cv_quals_for_unify
24771 		(UNIFY_ALLOW_NONE,
24772 		 class_of_this_parm (arg),
24773 		 class_of_this_parm (parm))))
24774 	  return unify_cv_qual_mismatch (explain_p, parm, arg);
24775 	if (TREE_CODE (arg) == FUNCTION_TYPE
24776 	    && type_memfn_quals (parm) != type_memfn_quals (arg))
24777 	  return unify_cv_qual_mismatch (explain_p, parm, arg);
24778 	if (type_memfn_rqual (parm) != type_memfn_rqual (arg))
24779 	  return unify_type_mismatch (explain_p, parm, arg);
24780 
24781 	RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
24782 				 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
24783 
24784 	nargs = list_length (TYPE_ARG_TYPES (arg));
24785 	args = XALLOCAVEC (tree, nargs);
24786 	for (a = TYPE_ARG_TYPES (arg), i = 0;
24787 	     a != NULL_TREE && a != void_list_node;
24788 	     a = TREE_CHAIN (a), ++i)
24789 	  args[i] = TREE_VALUE (a);
24790 	nargs = i;
24791 
24792 	if (type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
24793 				   args, nargs, 1, DEDUCE_EXACT,
24794 				   NULL, explain_p))
24795 	  return 1;
24796 
24797 	if (flag_noexcept_type)
24798 	  {
24799 	    tree pspec = TYPE_RAISES_EXCEPTIONS (parm);
24800 	    tree aspec = canonical_eh_spec (TYPE_RAISES_EXCEPTIONS (arg));
24801 	    if (pspec == NULL_TREE) pspec = noexcept_false_spec;
24802 	    if (aspec == NULL_TREE) aspec = noexcept_false_spec;
24803 	    if (TREE_PURPOSE (pspec) && TREE_PURPOSE (aspec)
24804 		&& uses_template_parms (TREE_PURPOSE (pspec)))
24805 	      RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_PURPOSE (pspec),
24806 				       TREE_PURPOSE (aspec),
24807 				       UNIFY_ALLOW_NONE, explain_p);
24808 	    else if (nothrow_spec_p (pspec) && !nothrow_spec_p (aspec))
24809 	      return unify_type_mismatch (explain_p, parm, arg);
24810 	  }
24811 
24812 	return 0;
24813       }
24814 
24815     case OFFSET_TYPE:
24816       /* Unify a pointer to member with a pointer to member function, which
24817 	 deduces the type of the member as a function type. */
24818       if (TYPE_PTRMEMFUNC_P (arg))
24819 	{
24820 	  /* Check top-level cv qualifiers */
24821 	  if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
24822 	    return unify_cv_qual_mismatch (explain_p, parm, arg);
24823 
24824 	  RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
24825 				   TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
24826 				   UNIFY_ALLOW_NONE, explain_p);
24827 
24828 	  /* Determine the type of the function we are unifying against. */
24829 	  tree fntype = static_fn_type (arg);
24830 
24831 	  return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
24832 	}
24833 
24834       if (TREE_CODE (arg) != OFFSET_TYPE)
24835 	return unify_type_mismatch (explain_p, parm, arg);
24836       RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
24837 			       TYPE_OFFSET_BASETYPE (arg),
24838 			       UNIFY_ALLOW_NONE, explain_p);
24839       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24840 		    strict, explain_p);
24841 
24842     case CONST_DECL:
24843       if (DECL_TEMPLATE_PARM_P (parm))
24844 	return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
24845       if (arg != scalar_constant_value (parm))
24846 	return unify_template_argument_mismatch (explain_p, parm, arg);
24847       return unify_success (explain_p);
24848 
24849     case FIELD_DECL:
24850     case TEMPLATE_DECL:
24851       /* Matched cases are handled by the ARG == PARM test above.  */
24852       return unify_template_argument_mismatch (explain_p, parm, arg);
24853 
24854     case VAR_DECL:
24855       /* We might get a variable as a non-type template argument in parm if the
24856 	 corresponding parameter is type-dependent.  Make any necessary
24857 	 adjustments based on whether arg is a reference.  */
24858       if (CONSTANT_CLASS_P (arg))
24859 	parm = fold_non_dependent_expr (parm, complain);
24860       else if (REFERENCE_REF_P (arg))
24861 	{
24862 	  tree sub = TREE_OPERAND (arg, 0);
24863 	  STRIP_NOPS (sub);
24864 	  if (TREE_CODE (sub) == ADDR_EXPR)
24865 	    arg = TREE_OPERAND (sub, 0);
24866 	}
24867       /* Now use the normal expression code to check whether they match.  */
24868       goto expr;
24869 
24870     case TYPE_ARGUMENT_PACK:
24871     case NONTYPE_ARGUMENT_PACK:
24872       return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
24873 		    ARGUMENT_PACK_ARGS (arg), strict, explain_p);
24874 
24875     case TYPEOF_TYPE:
24876     case DECLTYPE_TYPE:
24877     case UNDERLYING_TYPE:
24878       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
24879 	 or UNDERLYING_TYPE nodes.  */
24880       return unify_success (explain_p);
24881 
24882     case ERROR_MARK:
24883       /* Unification fails if we hit an error node.  */
24884       return unify_invalid (explain_p);
24885 
24886     case INDIRECT_REF:
24887       if (REFERENCE_REF_P (parm))
24888 	{
24889 	  bool pexp = PACK_EXPANSION_P (arg);
24890 	  if (pexp)
24891 	    arg = PACK_EXPANSION_PATTERN (arg);
24892 	  if (REFERENCE_REF_P (arg))
24893 	    arg = TREE_OPERAND (arg, 0);
24894 	  if (pexp)
24895 	    arg = make_pack_expansion (arg, complain);
24896 	  return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
24897 			strict, explain_p);
24898 	}
24899       /* FALLTHRU */
24900 
24901     default:
24902       /* An unresolved overload is a nondeduced context.  */
24903       if (is_overloaded_fn (parm) || type_unknown_p (parm))
24904 	return unify_success (explain_p);
24905       gcc_assert (EXPR_P (parm)
24906 		  || TREE_CODE (parm) == CONSTRUCTOR
24907 		  || TREE_CODE (parm) == TRAIT_EXPR);
24908     expr:
24909       /* We must be looking at an expression.  This can happen with
24910 	 something like:
24911 
24912 	   template <int I>
24913 	   void foo(S<I>, S<I + 2>);
24914 
24915 	 or
24916 
24917 	   template<typename T>
24918 	   void foo(A<T, T{}>);
24919 
24920 	 This is a "non-deduced context":
24921 
24922 	   [deduct.type]
24923 
24924 	   The non-deduced contexts are:
24925 
24926 	   --A non-type template argument or an array bound in which
24927 	     a subexpression references a template parameter.
24928 
24929 	 In these cases, we assume deduction succeeded, but don't
24930 	 actually infer any unifications.  */
24931 
24932       if (!uses_template_parms (parm)
24933 	  && !template_args_equal (parm, arg))
24934 	return unify_expression_unequal (explain_p, parm, arg);
24935       else
24936 	return unify_success (explain_p);
24937     }
24938 }
24939 #undef RECUR_AND_CHECK_FAILURE
24940 
24941 /* Note that DECL can be defined in this translation unit, if
24942    required.  */
24943 
24944 static void
mark_definable(tree decl)24945 mark_definable (tree decl)
24946 {
24947   tree clone;
24948   DECL_NOT_REALLY_EXTERN (decl) = 1;
24949   FOR_EACH_CLONE (clone, decl)
24950     DECL_NOT_REALLY_EXTERN (clone) = 1;
24951 }
24952 
24953 /* Called if RESULT is explicitly instantiated, or is a member of an
24954    explicitly instantiated class.  */
24955 
24956 void
mark_decl_instantiated(tree result,int extern_p)24957 mark_decl_instantiated (tree result, int extern_p)
24958 {
24959   SET_DECL_EXPLICIT_INSTANTIATION (result);
24960 
24961   /* If this entity has already been written out, it's too late to
24962      make any modifications.  */
24963   if (TREE_ASM_WRITTEN (result))
24964     return;
24965 
24966   /* consteval functions are never emitted.  */
24967   if (TREE_CODE (result) == FUNCTION_DECL
24968       && DECL_IMMEDIATE_FUNCTION_P (result))
24969     return;
24970 
24971   /* For anonymous namespace we don't need to do anything.  */
24972   if (decl_anon_ns_mem_p (result))
24973     {
24974       gcc_assert (!TREE_PUBLIC (result));
24975       return;
24976     }
24977 
24978   if (TREE_CODE (result) != FUNCTION_DECL)
24979     /* The TREE_PUBLIC flag for function declarations will have been
24980        set correctly by tsubst.  */
24981     TREE_PUBLIC (result) = 1;
24982 
24983   if (extern_p)
24984     {
24985       DECL_EXTERNAL (result) = 1;
24986       DECL_NOT_REALLY_EXTERN (result) = 0;
24987     }
24988   else
24989     {
24990       mark_definable (result);
24991       mark_needed (result);
24992       /* Always make artificials weak.  */
24993       if (DECL_ARTIFICIAL (result) && flag_weak)
24994 	comdat_linkage (result);
24995       /* For WIN32 we also want to put explicit instantiations in
24996 	 linkonce sections.  */
24997       else if (TREE_PUBLIC (result))
24998 	maybe_make_one_only (result);
24999       if (TREE_CODE (result) == FUNCTION_DECL
25000 	  && DECL_TEMPLATE_INSTANTIATED (result))
25001 	/* If the function has already been instantiated, clear DECL_EXTERNAL,
25002 	   since start_preparsed_function wouldn't have if we had an earlier
25003 	   extern explicit instantiation.  */
25004 	DECL_EXTERNAL (result) = 0;
25005     }
25006 
25007   /* If EXTERN_P, then this function will not be emitted -- unless
25008      followed by an explicit instantiation, at which point its linkage
25009      will be adjusted.  If !EXTERN_P, then this function will be
25010      emitted here.  In neither circumstance do we want
25011      import_export_decl to adjust the linkage.  */
25012   DECL_INTERFACE_KNOWN (result) = 1;
25013 }
25014 
25015 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
25016    important template arguments.  If any are missing, we check whether
25017    they're important by using error_mark_node for substituting into any
25018    args that were used for partial ordering (the ones between ARGS and END)
25019    and seeing if it bubbles up.  */
25020 
25021 static bool
check_undeduced_parms(tree targs,tree args,tree end)25022 check_undeduced_parms (tree targs, tree args, tree end)
25023 {
25024   bool found = false;
25025   int i;
25026   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
25027     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
25028       {
25029 	found = true;
25030 	TREE_VEC_ELT (targs, i) = error_mark_node;
25031       }
25032   if (found)
25033     {
25034       tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
25035       if (substed == error_mark_node)
25036 	return true;
25037     }
25038   return false;
25039 }
25040 
25041 /* Given two function templates PAT1 and PAT2, return:
25042 
25043    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
25044    -1 if PAT2 is more specialized than PAT1.
25045    0 if neither is more specialized.
25046 
25047    LEN indicates the number of parameters we should consider
25048    (defaulted parameters should not be considered).
25049 
25050    The 1998 std underspecified function template partial ordering, and
25051    DR214 addresses the issue.  We take pairs of arguments, one from
25052    each of the templates, and deduce them against each other.  One of
25053    the templates will be more specialized if all the *other*
25054    template's arguments deduce against its arguments and at least one
25055    of its arguments *does* *not* deduce against the other template's
25056    corresponding argument.  Deduction is done as for class templates.
25057    The arguments used in deduction have reference and top level cv
25058    qualifiers removed.  Iff both arguments were originally reference
25059    types *and* deduction succeeds in both directions, an lvalue reference
25060    wins against an rvalue reference and otherwise the template
25061    with the more cv-qualified argument wins for that pairing (if
25062    neither is more cv-qualified, they both are equal).  Unlike regular
25063    deduction, after all the arguments have been deduced in this way,
25064    we do *not* verify the deduced template argument values can be
25065    substituted into non-deduced contexts.
25066 
25067    The logic can be a bit confusing here, because we look at deduce1 and
25068    targs1 to see if pat2 is at least as specialized, and vice versa; if we
25069    can find template arguments for pat1 to make arg1 look like arg2, that
25070    means that arg2 is at least as specialized as arg1.  */
25071 
25072 int
more_specialized_fn(tree pat1,tree pat2,int len)25073 more_specialized_fn (tree pat1, tree pat2, int len)
25074 {
25075   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
25076   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
25077   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
25078   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
25079   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
25080   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
25081   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
25082   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
25083   tree origs1, origs2;
25084   bool lose1 = false;
25085   bool lose2 = false;
25086 
25087   /* Remove the this parameter from non-static member functions.  If
25088      one is a non-static member function and the other is not a static
25089      member function, remove the first parameter from that function
25090      also.  This situation occurs for operator functions where we
25091      locate both a member function (with this pointer) and non-member
25092      operator (with explicit first operand).  */
25093   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
25094     {
25095       len--; /* LEN is the number of significant arguments for DECL1 */
25096       args1 = TREE_CHAIN (args1);
25097       if (!DECL_STATIC_FUNCTION_P (decl2))
25098 	args2 = TREE_CHAIN (args2);
25099     }
25100   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
25101     {
25102       args2 = TREE_CHAIN (args2);
25103       if (!DECL_STATIC_FUNCTION_P (decl1))
25104 	{
25105 	  len--;
25106 	  args1 = TREE_CHAIN (args1);
25107 	}
25108     }
25109 
25110   /* If only one is a conversion operator, they are unordered.  */
25111   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
25112     return 0;
25113 
25114   /* Consider the return type for a conversion function */
25115   if (DECL_CONV_FN_P (decl1))
25116     {
25117       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
25118       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
25119       len++;
25120     }
25121 
25122   processing_template_decl++;
25123 
25124   origs1 = args1;
25125   origs2 = args2;
25126 
25127   while (len--
25128 	 /* Stop when an ellipsis is seen.  */
25129 	 && args1 != NULL_TREE && args2 != NULL_TREE)
25130     {
25131       tree arg1 = TREE_VALUE (args1);
25132       tree arg2 = TREE_VALUE (args2);
25133       int deduce1, deduce2;
25134       int quals1 = -1;
25135       int quals2 = -1;
25136       int ref1 = 0;
25137       int ref2 = 0;
25138 
25139       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
25140           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25141         {
25142           /* When both arguments are pack expansions, we need only
25143              unify the patterns themselves.  */
25144           arg1 = PACK_EXPANSION_PATTERN (arg1);
25145           arg2 = PACK_EXPANSION_PATTERN (arg2);
25146 
25147           /* This is the last comparison we need to do.  */
25148           len = 0;
25149         }
25150 
25151       if (TYPE_REF_P (arg1))
25152 	{
25153 	  ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
25154 	  arg1 = TREE_TYPE (arg1);
25155 	  quals1 = cp_type_quals (arg1);
25156 	}
25157 
25158       if (TYPE_REF_P (arg2))
25159 	{
25160 	  ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
25161 	  arg2 = TREE_TYPE (arg2);
25162 	  quals2 = cp_type_quals (arg2);
25163 	}
25164 
25165       arg1 = TYPE_MAIN_VARIANT (arg1);
25166       arg2 = TYPE_MAIN_VARIANT (arg2);
25167 
25168       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
25169         {
25170           int i, len2 = remaining_arguments (args2);
25171           tree parmvec = make_tree_vec (1);
25172           tree argvec = make_tree_vec (len2);
25173           tree ta = args2;
25174 
25175           /* Setup the parameter vector, which contains only ARG1.  */
25176           TREE_VEC_ELT (parmvec, 0) = arg1;
25177 
25178           /* Setup the argument vector, which contains the remaining
25179              arguments.  */
25180           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
25181             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
25182 
25183           deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
25184 					   argvec, DEDUCE_EXACT,
25185 					   /*subr=*/true, /*explain_p=*/false)
25186 		     == 0);
25187 
25188           /* We cannot deduce in the other direction, because ARG1 is
25189              a pack expansion but ARG2 is not.  */
25190           deduce2 = 0;
25191         }
25192       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25193         {
25194           int i, len1 = remaining_arguments (args1);
25195           tree parmvec = make_tree_vec (1);
25196           tree argvec = make_tree_vec (len1);
25197           tree ta = args1;
25198 
25199           /* Setup the parameter vector, which contains only ARG1.  */
25200           TREE_VEC_ELT (parmvec, 0) = arg2;
25201 
25202           /* Setup the argument vector, which contains the remaining
25203              arguments.  */
25204           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
25205             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
25206 
25207           deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
25208 					   argvec, DEDUCE_EXACT,
25209 					   /*subr=*/true, /*explain_p=*/false)
25210 		     == 0);
25211 
25212           /* We cannot deduce in the other direction, because ARG2 is
25213              a pack expansion but ARG1 is not.*/
25214           deduce1 = 0;
25215         }
25216 
25217       else
25218         {
25219           /* The normal case, where neither argument is a pack
25220              expansion.  */
25221           deduce1 = (unify (tparms1, targs1, arg1, arg2,
25222 			    UNIFY_ALLOW_NONE, /*explain_p=*/false)
25223 		     == 0);
25224           deduce2 = (unify (tparms2, targs2, arg2, arg1,
25225 			    UNIFY_ALLOW_NONE, /*explain_p=*/false)
25226 		     == 0);
25227         }
25228 
25229       /* If we couldn't deduce arguments for tparms1 to make arg1 match
25230 	 arg2, then arg2 is not as specialized as arg1.  */
25231       if (!deduce1)
25232 	lose2 = true;
25233       if (!deduce2)
25234 	lose1 = true;
25235 
25236       /* "If, for a given type, deduction succeeds in both directions
25237 	 (i.e., the types are identical after the transformations above)
25238 	 and both P and A were reference types (before being replaced with
25239 	 the type referred to above):
25240 	 - if the type from the argument template was an lvalue reference and
25241 	 the type from the parameter template was not, the argument type is
25242 	 considered to be more specialized than the other; otherwise,
25243 	 - if the type from the argument template is more cv-qualified
25244 	 than the type from the parameter template (as described above),
25245 	 the argument type is considered to be more specialized than the other;
25246 	 otherwise,
25247 	 - neither type is more specialized than the other."  */
25248 
25249       if (deduce1 && deduce2)
25250 	{
25251 	  if (ref1 && ref2 && ref1 != ref2)
25252 	    {
25253 	      if (ref1 > ref2)
25254 		lose1 = true;
25255 	      else
25256 		lose2 = true;
25257 	    }
25258 	  else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
25259 	    {
25260 	      if ((quals1 & quals2) == quals2)
25261 		lose2 = true;
25262 	      if ((quals1 & quals2) == quals1)
25263 		lose1 = true;
25264 	    }
25265 	}
25266 
25267       if (lose1 && lose2)
25268 	/* We've failed to deduce something in either direction.
25269 	   These must be unordered.  */
25270 	break;
25271 
25272       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
25273           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25274         /* We have already processed all of the arguments in our
25275            handing of the pack expansion type.  */
25276         len = 0;
25277 
25278       args1 = TREE_CHAIN (args1);
25279       args2 = TREE_CHAIN (args2);
25280     }
25281 
25282   /* "In most cases, all template parameters must have values in order for
25283      deduction to succeed, but for partial ordering purposes a template
25284      parameter may remain without a value provided it is not used in the
25285      types being used for partial ordering."
25286 
25287      Thus, if we are missing any of the targs1 we need to substitute into
25288      origs1, then pat2 is not as specialized as pat1.  This can happen when
25289      there is a nondeduced context.  */
25290   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
25291     lose2 = true;
25292   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
25293     lose1 = true;
25294 
25295   processing_template_decl--;
25296 
25297   /* If both deductions succeed, the partial ordering selects the more
25298      constrained template.  */
25299   /* P2113: If the corresponding template-parameters of the
25300      template-parameter-lists are not equivalent ([temp.over.link]) or if
25301      the function parameters that positionally correspond between the two
25302      templates are not of the same type, neither template is more
25303      specialized than the other.  */
25304   if (!lose1 && !lose2
25305       && comp_template_parms (DECL_TEMPLATE_PARMS (pat1),
25306 			      DECL_TEMPLATE_PARMS (pat2))
25307       && compparms (origs1, origs2))
25308     {
25309       int winner = more_constrained (decl1, decl2);
25310       if (winner > 0)
25311 	lose2 = true;
25312       else if (winner < 0)
25313 	lose1 = true;
25314     }
25315 
25316   /* All things being equal, if the next argument is a pack expansion
25317      for one function but not for the other, prefer the
25318      non-variadic function.  FIXME this is bogus; see c++/41958.  */
25319   if (lose1 == lose2
25320       && args1 && TREE_VALUE (args1)
25321       && args2 && TREE_VALUE (args2))
25322     {
25323       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
25324       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
25325     }
25326 
25327   if (lose1 == lose2)
25328     return 0;
25329   else if (!lose1)
25330     return 1;
25331   else
25332     return -1;
25333 }
25334 
25335 /* Determine which of two partial specializations of TMPL is more
25336    specialized.
25337 
25338    PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
25339    to the first partial specialization.  The TREE_PURPOSE is the
25340    innermost set of template parameters for the partial
25341    specialization.  PAT2 is similar, but for the second template.
25342 
25343    Return 1 if the first partial specialization is more specialized;
25344    -1 if the second is more specialized; 0 if neither is more
25345    specialized.
25346 
25347    See [temp.class.order] for information about determining which of
25348    two templates is more specialized.  */
25349 
25350 static int
more_specialized_partial_spec(tree tmpl,tree pat1,tree pat2)25351 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
25352 {
25353   tree targs;
25354   int winner = 0;
25355   bool any_deductions = false;
25356 
25357   tree tmpl1 = TREE_VALUE (pat1);
25358   tree tmpl2 = TREE_VALUE (pat2);
25359   tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
25360   tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
25361 
25362   /* Just like what happens for functions, if we are ordering between
25363      different template specializations, we may encounter dependent
25364      types in the arguments, and we need our dependency check functions
25365      to behave correctly.  */
25366   ++processing_template_decl;
25367   targs = get_partial_spec_bindings (tmpl, tmpl1, specargs2);
25368   if (targs)
25369     {
25370       --winner;
25371       any_deductions = true;
25372     }
25373 
25374   targs = get_partial_spec_bindings (tmpl, tmpl2, specargs1);
25375   if (targs)
25376     {
25377       ++winner;
25378       any_deductions = true;
25379     }
25380   --processing_template_decl;
25381 
25382   /* If both deductions succeed, the partial ordering selects the more
25383      constrained template.  */
25384   if (!winner && any_deductions)
25385     winner = more_constrained (tmpl1, tmpl2);
25386 
25387   /* In the case of a tie where at least one of the templates
25388      has a parameter pack at the end, the template with the most
25389      non-packed parameters wins.  */
25390   if (winner == 0
25391       && any_deductions
25392       && (template_args_variadic_p (TREE_PURPOSE (pat1))
25393           || template_args_variadic_p (TREE_PURPOSE (pat2))))
25394     {
25395       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
25396       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
25397       int len1 = TREE_VEC_LENGTH (args1);
25398       int len2 = TREE_VEC_LENGTH (args2);
25399 
25400       /* We don't count the pack expansion at the end.  */
25401       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
25402         --len1;
25403       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
25404         --len2;
25405 
25406       if (len1 > len2)
25407         return 1;
25408       else if (len1 < len2)
25409         return -1;
25410     }
25411 
25412   return winner;
25413 }
25414 
25415 /* Return the template arguments that will produce the function signature
25416    DECL from the function template FN, with the explicit template
25417    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
25418    also match.  Return NULL_TREE if no satisfactory arguments could be
25419    found.  */
25420 
25421 static tree
get_bindings(tree fn,tree decl,tree explicit_args,bool check_rettype)25422 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
25423 {
25424   int ntparms = DECL_NTPARMS (fn);
25425   tree targs = make_tree_vec (ntparms);
25426   tree decl_type = TREE_TYPE (decl);
25427   tree decl_arg_types;
25428   tree *args;
25429   unsigned int nargs, ix;
25430   tree arg;
25431 
25432   gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
25433 
25434   /* Never do unification on the 'this' parameter.  */
25435   decl_arg_types = skip_artificial_parms_for (decl,
25436 					      TYPE_ARG_TYPES (decl_type));
25437 
25438   nargs = list_length (decl_arg_types);
25439   args = XALLOCAVEC (tree, nargs);
25440   for (arg = decl_arg_types, ix = 0;
25441        arg != NULL_TREE;
25442        arg = TREE_CHAIN (arg), ++ix)
25443     args[ix] = TREE_VALUE (arg);
25444 
25445   if (fn_type_unification (fn, explicit_args, targs,
25446 			   args, ix,
25447 			   (check_rettype || DECL_CONV_FN_P (fn)
25448 			    ? TREE_TYPE (decl_type) : NULL_TREE),
25449 			   DEDUCE_EXACT, LOOKUP_NORMAL, NULL,
25450 			   /*explain_p=*/false,
25451 			   /*decltype*/false)
25452       == error_mark_node)
25453     return NULL_TREE;
25454 
25455   return targs;
25456 }
25457 
25458 /* Return the innermost template arguments that, when applied to a partial
25459    specialization SPEC_TMPL of TMPL, yield the ARGS.
25460 
25461    For example, suppose we have:
25462 
25463      template <class T, class U> struct S {};
25464      template <class T> struct S<T*, int> {};
25465 
25466    Then, suppose we want to get `S<double*, int>'.  SPEC_TMPL will be the
25467    partial specialization and the ARGS will be {double*, int}.  The resulting
25468    vector will be {double}, indicating that `T' is bound to `double'.  */
25469 
25470 static tree
get_partial_spec_bindings(tree tmpl,tree spec_tmpl,tree args)25471 get_partial_spec_bindings (tree tmpl, tree spec_tmpl, tree args)
25472 {
25473   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
25474   tree spec_args
25475     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (spec_tmpl)));
25476   int i, ntparms = TREE_VEC_LENGTH (tparms);
25477   tree deduced_args;
25478   tree innermost_deduced_args;
25479 
25480   innermost_deduced_args = make_tree_vec (ntparms);
25481   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
25482     {
25483       deduced_args = copy_node (args);
25484       SET_TMPL_ARGS_LEVEL (deduced_args,
25485 			   TMPL_ARGS_DEPTH (deduced_args),
25486 			   innermost_deduced_args);
25487     }
25488   else
25489     deduced_args = innermost_deduced_args;
25490 
25491   bool tried_array_deduction = (cxx_dialect < cxx17);
25492  again:
25493   if (unify (tparms, deduced_args,
25494 	     INNERMOST_TEMPLATE_ARGS (spec_args),
25495 	     INNERMOST_TEMPLATE_ARGS (args),
25496 	     UNIFY_ALLOW_NONE, /*explain_p=*/false))
25497     return NULL_TREE;
25498 
25499   for (i =  0; i < ntparms; ++i)
25500     if (! TREE_VEC_ELT (innermost_deduced_args, i))
25501       {
25502 	if (!tried_array_deduction)
25503 	  {
25504 	    try_array_deduction (tparms, innermost_deduced_args,
25505 				 INNERMOST_TEMPLATE_ARGS (spec_args));
25506 	    tried_array_deduction = true;
25507 	    if (TREE_VEC_ELT (innermost_deduced_args, i))
25508 	      goto again;
25509 	  }
25510 	return NULL_TREE;
25511       }
25512 
25513   if (!push_tinst_level (spec_tmpl, deduced_args))
25514     {
25515       excessive_deduction_depth = true;
25516       return NULL_TREE;
25517     }
25518 
25519   /* Verify that nondeduced template arguments agree with the type
25520      obtained from argument deduction.
25521 
25522      For example:
25523 
25524        struct A { typedef int X; };
25525        template <class T, class U> struct C {};
25526        template <class T> struct C<T, typename T::X> {};
25527 
25528      Then with the instantiation `C<A, int>', we can deduce that
25529      `T' is `A' but unify () does not check whether `typename T::X'
25530      is `int'.  */
25531   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
25532 
25533   if (spec_args != error_mark_node)
25534     spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
25535 				       INNERMOST_TEMPLATE_ARGS (spec_args),
25536 				       tmpl, tf_none, false, false);
25537 
25538   pop_tinst_level ();
25539 
25540   if (spec_args == error_mark_node
25541       /* We only need to check the innermost arguments; the other
25542 	 arguments will always agree.  */
25543       || !comp_template_args_porder (INNERMOST_TEMPLATE_ARGS (spec_args),
25544 				     INNERMOST_TEMPLATE_ARGS (args)))
25545     return NULL_TREE;
25546 
25547   /* Now that we have bindings for all of the template arguments,
25548      ensure that the arguments deduced for the template template
25549      parameters have compatible template parameter lists.  See the use
25550      of template_template_parm_bindings_ok_p in fn_type_unification
25551      for more information.  */
25552   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
25553     return NULL_TREE;
25554 
25555   return deduced_args;
25556 }
25557 
25558 // Compare two function templates T1 and T2 by deducing bindings
25559 // from one against the other. If both deductions succeed, compare
25560 // constraints to see which is more constrained.
25561 static int
more_specialized_inst(tree t1,tree t2)25562 more_specialized_inst (tree t1, tree t2)
25563 {
25564   int fate = 0;
25565   int count = 0;
25566 
25567   if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
25568     {
25569       --fate;
25570       ++count;
25571     }
25572 
25573   if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
25574     {
25575       ++fate;
25576       ++count;
25577     }
25578 
25579   // If both deductions succeed, then one may be more constrained.
25580   if (count == 2 && fate == 0)
25581     fate = more_constrained (t1, t2);
25582 
25583   return fate;
25584 }
25585 
25586 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
25587    Return the TREE_LIST node with the most specialized template, if
25588    any.  If there is no most specialized template, the error_mark_node
25589    is returned.
25590 
25591    Note that this function does not look at, or modify, the
25592    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
25593    returned is one of the elements of INSTANTIATIONS, callers may
25594    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
25595    and retrieve it from the value returned.  */
25596 
25597 tree
most_specialized_instantiation(tree templates)25598 most_specialized_instantiation (tree templates)
25599 {
25600   tree fn, champ;
25601 
25602   ++processing_template_decl;
25603 
25604   champ = templates;
25605   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
25606     {
25607       gcc_assert (TREE_VALUE (champ) != TREE_VALUE (fn));
25608       int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
25609       if (fate == -1)
25610 	champ = fn;
25611       else if (!fate)
25612 	{
25613 	  /* Equally specialized, move to next function.  If there
25614 	     is no next function, nothing's most specialized.  */
25615 	  fn = TREE_CHAIN (fn);
25616 	  champ = fn;
25617 	  if (!fn)
25618 	    break;
25619 	}
25620     }
25621 
25622   if (champ)
25623     /* Now verify that champ is better than everything earlier in the
25624        instantiation list.  */
25625     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
25626       if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
25627       {
25628         champ = NULL_TREE;
25629         break;
25630       }
25631     }
25632 
25633   processing_template_decl--;
25634 
25635   if (!champ)
25636     return error_mark_node;
25637 
25638   return champ;
25639 }
25640 
25641 /* If DECL is a specialization of some template, return the most
25642    general such template.  Otherwise, returns NULL_TREE.
25643 
25644    For example, given:
25645 
25646      template <class T> struct S { template <class U> void f(U); };
25647 
25648    if TMPL is `template <class U> void S<int>::f(U)' this will return
25649    the full template.  This function will not trace past partial
25650    specializations, however.  For example, given in addition:
25651 
25652      template <class T> struct S<T*> { template <class U> void f(U); };
25653 
25654    if TMPL is `template <class U> void S<int*>::f(U)' this will return
25655    `template <class T> template <class U> S<T*>::f(U)'.  */
25656 
25657 tree
most_general_template(tree decl)25658 most_general_template (tree decl)
25659 {
25660   if (TREE_CODE (decl) != TEMPLATE_DECL)
25661     {
25662       if (tree tinfo = get_template_info (decl))
25663 	decl = TI_TEMPLATE (tinfo);
25664       /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
25665 	 template friend, or a FIELD_DECL for a capture pack.  */
25666       if (TREE_CODE (decl) != TEMPLATE_DECL)
25667 	return NULL_TREE;
25668     }
25669 
25670   /* Look for more and more general templates.  */
25671   while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
25672     {
25673       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
25674 	 (See cp-tree.h for details.)  */
25675       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
25676 	break;
25677 
25678       if (CLASS_TYPE_P (TREE_TYPE (decl))
25679 	  && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
25680 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
25681 	break;
25682 
25683       /* Stop if we run into an explicitly specialized class template.  */
25684       if (!DECL_NAMESPACE_SCOPE_P (decl)
25685 	  && DECL_CONTEXT (decl)
25686 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
25687 	break;
25688 
25689       decl = DECL_TI_TEMPLATE (decl);
25690     }
25691 
25692   return decl;
25693 }
25694 
25695 /* Return the most specialized of the template partial specializations
25696    which can produce TARGET, a specialization of some class or variable
25697    template.  The value returned is actually a TREE_LIST; the TREE_VALUE is
25698    a TEMPLATE_DECL node corresponding to the partial specialization, while
25699    the TREE_PURPOSE is the set of template arguments that must be
25700    substituted into the template pattern in order to generate TARGET.
25701 
25702    If the choice of partial specialization is ambiguous, a diagnostic
25703    is issued, and the error_mark_node is returned.  If there are no
25704    partial specializations matching TARGET, then NULL_TREE is
25705    returned, indicating that the primary template should be used.  */
25706 
25707 tree
most_specialized_partial_spec(tree target,tsubst_flags_t complain)25708 most_specialized_partial_spec (tree target, tsubst_flags_t complain)
25709 {
25710   tree list = NULL_TREE;
25711   tree t;
25712   tree champ;
25713   int fate;
25714   bool ambiguous_p;
25715   tree outer_args = NULL_TREE;
25716   tree tmpl, args;
25717 
25718   tree decl;
25719   if (TYPE_P (target))
25720     {
25721       tree tinfo = CLASSTYPE_TEMPLATE_INFO (target);
25722       tmpl = TI_TEMPLATE (tinfo);
25723       args = TI_ARGS (tinfo);
25724       decl = TYPE_NAME (target);
25725     }
25726   else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
25727     {
25728       tmpl = TREE_OPERAND (target, 0);
25729       args = TREE_OPERAND (target, 1);
25730       decl = DECL_TEMPLATE_RESULT (tmpl);
25731     }
25732   else if (VAR_P (target))
25733     {
25734       tree tinfo = DECL_TEMPLATE_INFO (target);
25735       tmpl = TI_TEMPLATE (tinfo);
25736       args = TI_ARGS (tinfo);
25737       decl = target;
25738     }
25739   else
25740     gcc_unreachable ();
25741 
25742   push_access_scope_guard pas (decl);
25743   deferring_access_check_sentinel acs (dk_no_deferred);
25744 
25745   tree main_tmpl = most_general_template (tmpl);
25746 
25747   /* For determining which partial specialization to use, only the
25748      innermost args are interesting.  */
25749   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
25750     {
25751       outer_args = strip_innermost_template_args (args, 1);
25752       args = INNERMOST_TEMPLATE_ARGS (args);
25753     }
25754 
25755   /* The caller hasn't called push_to_top_level yet, but we need
25756      get_partial_spec_bindings to be done in non-template context so that we'll
25757      fully resolve everything.  */
25758   processing_template_decl_sentinel ptds;
25759 
25760   for (t = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl); t; t = TREE_CHAIN (t))
25761     {
25762       const tree ospec_tmpl = TREE_VALUE (t);
25763 
25764       tree spec_tmpl;
25765       if (outer_args)
25766 	{
25767 	  /* Substitute in the template args from the enclosing class.  */
25768 	  ++processing_template_decl;
25769 	  spec_tmpl = tsubst (ospec_tmpl, outer_args, tf_none, NULL_TREE);
25770 	  --processing_template_decl;
25771 	  if (spec_tmpl == error_mark_node)
25772 	    return error_mark_node;
25773 	}
25774       else
25775 	spec_tmpl = ospec_tmpl;
25776 
25777       tree spec_args = get_partial_spec_bindings (tmpl, spec_tmpl, args);
25778       if (spec_args)
25779 	{
25780 	  if (outer_args)
25781 	    spec_args = add_to_template_args (outer_args, spec_args);
25782 
25783           /* Keep the candidate only if the constraints are satisfied,
25784              or if we're not compiling with concepts.  */
25785           if (!flag_concepts
25786 	      || constraints_satisfied_p (ospec_tmpl, spec_args))
25787             {
25788 	      list = tree_cons (spec_args, ospec_tmpl, list);
25789               TREE_TYPE (list) = TREE_TYPE (t);
25790             }
25791 	}
25792     }
25793 
25794   if (! list)
25795     return NULL_TREE;
25796 
25797   ambiguous_p = false;
25798   t = list;
25799   champ = t;
25800   t = TREE_CHAIN (t);
25801   for (; t; t = TREE_CHAIN (t))
25802     {
25803       fate = more_specialized_partial_spec (tmpl, champ, t);
25804       if (fate == 1)
25805 	;
25806       else
25807 	{
25808 	  if (fate == 0)
25809 	    {
25810 	      t = TREE_CHAIN (t);
25811 	      if (! t)
25812 		{
25813 		  ambiguous_p = true;
25814 		  break;
25815 		}
25816 	    }
25817 	  champ = t;
25818 	}
25819     }
25820 
25821   if (!ambiguous_p)
25822     for (t = list; t && t != champ; t = TREE_CHAIN (t))
25823       {
25824 	fate = more_specialized_partial_spec (tmpl, champ, t);
25825 	if (fate != 1)
25826 	  {
25827 	    ambiguous_p = true;
25828 	    break;
25829 	  }
25830       }
25831 
25832   if (ambiguous_p)
25833     {
25834       const char *str;
25835       char *spaces = NULL;
25836       if (!(complain & tf_error))
25837 	return error_mark_node;
25838       if (TYPE_P (target))
25839 	error ("ambiguous template instantiation for %q#T", target);
25840       else
25841 	error ("ambiguous template instantiation for %q#D", target);
25842       str = ngettext ("candidate is:", "candidates are:", list_length (list));
25843       for (t = list; t; t = TREE_CHAIN (t))
25844         {
25845 	  tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
25846           inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
25847 		  "%s %#qS", spaces ? spaces : str, subst);
25848           spaces = spaces ? spaces : get_spaces (str);
25849         }
25850       free (spaces);
25851       return error_mark_node;
25852     }
25853 
25854   return champ;
25855 }
25856 
25857 /* Explicitly instantiate DECL.  */
25858 
25859 void
do_decl_instantiation(tree decl,tree storage)25860 do_decl_instantiation (tree decl, tree storage)
25861 {
25862   tree result = NULL_TREE;
25863   int extern_p = 0;
25864 
25865   if (!decl || decl == error_mark_node)
25866     /* An error occurred, for which grokdeclarator has already issued
25867        an appropriate message.  */
25868     return;
25869   else if (! DECL_LANG_SPECIFIC (decl))
25870     {
25871       error ("explicit instantiation of non-template %q#D", decl);
25872       return;
25873     }
25874   else if (DECL_DECLARED_CONCEPT_P (decl))
25875     {
25876       if (VAR_P (decl))
25877 	error ("explicit instantiation of variable concept %q#D", decl);
25878       else
25879 	error ("explicit instantiation of function concept %q#D", decl);
25880       return;
25881     }
25882 
25883   bool var_templ = (DECL_TEMPLATE_INFO (decl)
25884                     && variable_template_p (DECL_TI_TEMPLATE (decl)));
25885 
25886   if (VAR_P (decl) && !var_templ)
25887     {
25888       /* There is an asymmetry here in the way VAR_DECLs and
25889 	 FUNCTION_DECLs are handled by grokdeclarator.  In the case of
25890 	 the latter, the DECL we get back will be marked as a
25891 	 template instantiation, and the appropriate
25892 	 DECL_TEMPLATE_INFO will be set up.  This does not happen for
25893 	 VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
25894 	 should handle VAR_DECLs as it currently handles
25895 	 FUNCTION_DECLs.  */
25896       if (!DECL_CLASS_SCOPE_P (decl))
25897 	{
25898 	  error ("%qD is not a static data member of a class template", decl);
25899 	  return;
25900 	}
25901       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
25902       if (!result || !VAR_P (result))
25903 	{
25904 	  error ("no matching template for %qD found", decl);
25905 	  return;
25906 	}
25907       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
25908 	{
25909 	  error ("type %qT for explicit instantiation %qD does not match "
25910 		 "declared type %qT", TREE_TYPE (result), decl,
25911 		 TREE_TYPE (decl));
25912 	  return;
25913 	}
25914     }
25915   else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
25916     {
25917       error ("explicit instantiation of %q#D", decl);
25918       return;
25919     }
25920   else
25921     result = decl;
25922 
25923   /* Check for various error cases.  Note that if the explicit
25924      instantiation is valid the RESULT will currently be marked as an
25925      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
25926      until we get here.  */
25927 
25928   if (DECL_TEMPLATE_SPECIALIZATION (result))
25929     {
25930       /* DR 259 [temp.spec].
25931 
25932 	 Both an explicit instantiation and a declaration of an explicit
25933 	 specialization shall not appear in a program unless the explicit
25934 	 instantiation follows a declaration of the explicit specialization.
25935 
25936 	 For a given set of template parameters, if an explicit
25937 	 instantiation of a template appears after a declaration of an
25938 	 explicit specialization for that template, the explicit
25939 	 instantiation has no effect.  */
25940       return;
25941     }
25942   else if (DECL_EXPLICIT_INSTANTIATION (result))
25943     {
25944       /* [temp.spec]
25945 
25946 	 No program shall explicitly instantiate any template more
25947 	 than once.
25948 
25949 	 We check DECL_NOT_REALLY_EXTERN so as not to complain when
25950 	 the first instantiation was `extern' and the second is not,
25951 	 and EXTERN_P for the opposite case.  */
25952       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
25953 	permerror (input_location, "duplicate explicit instantiation of %q#D", result);
25954       /* If an "extern" explicit instantiation follows an ordinary
25955 	 explicit instantiation, the template is instantiated.  */
25956       if (extern_p)
25957 	return;
25958     }
25959   else if (!DECL_IMPLICIT_INSTANTIATION (result))
25960     {
25961       error ("no matching template for %qD found", result);
25962       return;
25963     }
25964   else if (!DECL_TEMPLATE_INFO (result))
25965     {
25966       permerror (input_location, "explicit instantiation of non-template %q#D", result);
25967       return;
25968     }
25969 
25970   if (storage == NULL_TREE)
25971     ;
25972   else if (storage == ridpointers[(int) RID_EXTERN])
25973     {
25974       if (cxx_dialect == cxx98)
25975 	pedwarn (input_location, OPT_Wpedantic,
25976 		 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
25977 		 "instantiations");
25978       extern_p = 1;
25979     }
25980   else
25981     error ("storage class %qD applied to template instantiation", storage);
25982 
25983   check_explicit_instantiation_namespace (result);
25984   mark_decl_instantiated (result, extern_p);
25985   if (! extern_p)
25986     instantiate_decl (result, /*defer_ok=*/true,
25987 		      /*expl_inst_class_mem_p=*/false);
25988 }
25989 
25990 static void
mark_class_instantiated(tree t,int extern_p)25991 mark_class_instantiated (tree t, int extern_p)
25992 {
25993   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
25994   SET_CLASSTYPE_INTERFACE_KNOWN (t);
25995   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
25996   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
25997   if (! extern_p)
25998     {
25999       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
26000       rest_of_type_compilation (t, 1);
26001     }
26002 }
26003 
26004 /* Perform an explicit instantiation of template class T.  STORAGE, if
26005    non-null, is the RID for extern, inline or static.  COMPLAIN is
26006    nonzero if this is called from the parser, zero if called recursively,
26007    since the standard is unclear (as detailed below).  */
26008 
26009 void
do_type_instantiation(tree t,tree storage,tsubst_flags_t complain)26010 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
26011 {
26012   if (!(CLASS_TYPE_P (t) && CLASSTYPE_TEMPLATE_INFO (t)))
26013     {
26014       if (tree ti = TYPE_TEMPLATE_INFO (t))
26015 	error ("explicit instantiation of non-class template %qD",
26016 	       TI_TEMPLATE (ti));
26017       else
26018 	error ("explicit instantiation of non-template type %qT", t);
26019       return;
26020     }
26021 
26022   complete_type (t);
26023 
26024   if (!COMPLETE_TYPE_P (t))
26025     {
26026       if (complain & tf_error)
26027 	error ("explicit instantiation of %q#T before definition of template",
26028 	       t);
26029       return;
26030     }
26031 
26032   /* At most one of these will be true.  */
26033   bool extern_p = false;
26034   bool nomem_p = false;
26035   bool static_p = false;
26036 
26037   if (storage != NULL_TREE)
26038     {
26039       if (storage == ridpointers[(int) RID_EXTERN])
26040 	{
26041 	  if (cxx_dialect == cxx98)
26042 	    pedwarn (input_location, OPT_Wpedantic,
26043 		     "ISO C++ 1998 forbids the use of %<extern%> on "
26044 		     "explicit instantiations");
26045 	}
26046       else
26047 	pedwarn (input_location, OPT_Wpedantic,
26048 		 "ISO C++ forbids the use of %qE"
26049 		 " on explicit instantiations", storage);
26050 
26051       if (storage == ridpointers[(int) RID_INLINE])
26052 	nomem_p = true;
26053       else if (storage == ridpointers[(int) RID_EXTERN])
26054 	extern_p = true;
26055       else if (storage == ridpointers[(int) RID_STATIC])
26056 	static_p = true;
26057       else
26058 	error ("storage class %qD applied to template instantiation",
26059 	       storage);
26060     }
26061 
26062   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
26063     /* DR 259 [temp.spec].
26064 
26065        Both an explicit instantiation and a declaration of an explicit
26066        specialization shall not appear in a program unless the
26067        explicit instantiation follows a declaration of the explicit
26068        specialization.
26069 
26070        For a given set of template parameters, if an explicit
26071        instantiation of a template appears after a declaration of an
26072        explicit specialization for that template, the explicit
26073        instantiation has no effect.  */
26074     return;
26075 
26076   if (CLASSTYPE_EXPLICIT_INSTANTIATION (t) && !CLASSTYPE_INTERFACE_ONLY (t))
26077     {
26078       /* We've already instantiated the template.  */
26079 
26080       /* [temp.spec]
26081 
26082 	 No program shall explicitly instantiate any template more
26083 	 than once.
26084 
26085 	 If EXTERN_P then this is ok.  */
26086       if (!extern_p && (complain & tf_error))
26087 	permerror (input_location,
26088 		   "duplicate explicit instantiation of %q#T", t);
26089 
26090       return;
26091     }
26092 
26093   check_explicit_instantiation_namespace (TYPE_NAME (t));
26094   mark_class_instantiated (t, extern_p);
26095 
26096   if (nomem_p)
26097     return;
26098 
26099   /* In contrast to implicit instantiation, where only the
26100      declarations, and not the definitions, of members are
26101      instantiated, we have here:
26102 
26103 	 [temp.explicit]
26104 
26105 	 An explicit instantiation that names a class template
26106 	 specialization is also an explicit instantiation of the same
26107 	 kind (declaration or definition) of each of its members (not
26108 	 including members inherited from base classes and members
26109 	 that are templates) that has not been previously explicitly
26110 	 specialized in the translation unit containing the explicit
26111 	 instantiation, provided that the associated constraints, if
26112 	 any, of that member are satisfied by the template arguments
26113 	 of the explicit instantiation.  */
26114   for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
26115     if ((VAR_P (fld)
26116 	 || (TREE_CODE (fld) == FUNCTION_DECL
26117 	     && !static_p
26118 	     && user_provided_p (fld)))
26119 	&& DECL_TEMPLATE_INSTANTIATION (fld)
26120 	&& constraints_satisfied_p (fld))
26121       {
26122 	mark_decl_instantiated (fld, extern_p);
26123 	if (! extern_p)
26124 	  instantiate_decl (fld, /*defer_ok=*/true,
26125 			    /*expl_inst_class_mem_p=*/true);
26126       }
26127     else if (DECL_IMPLICIT_TYPEDEF_P (fld))
26128       {
26129 	tree type = TREE_TYPE (fld);
26130 
26131 	if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
26132 	    && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
26133 	  do_type_instantiation (type, storage, 0);
26134       }
26135 }
26136 
26137 /* Given a function DECL, which is a specialization of TMPL, modify
26138    DECL to be a re-instantiation of TMPL with the same template
26139    arguments.  TMPL should be the template into which tsubst'ing
26140    should occur for DECL, not the most general template.
26141 
26142    One reason for doing this is a scenario like this:
26143 
26144      template <class T>
26145      void f(const T&, int i);
26146 
26147      void g() { f(3, 7); }
26148 
26149      template <class T>
26150      void f(const T& t, const int i) { }
26151 
26152    Note that when the template is first instantiated, with
26153    instantiate_template, the resulting DECL will have no name for the
26154    first parameter, and the wrong type for the second.  So, when we go
26155    to instantiate the DECL, we regenerate it.  */
26156 
26157 static void
regenerate_decl_from_template(tree decl,tree tmpl,tree args)26158 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
26159 {
26160   /* The arguments used to instantiate DECL, from the most general
26161      template.  */
26162   tree code_pattern;
26163 
26164   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
26165 
26166   /* Make sure that we can see identifiers, and compute access
26167      correctly.  */
26168   push_access_scope (decl);
26169 
26170   if (TREE_CODE (decl) == FUNCTION_DECL)
26171     {
26172       tree specs;
26173       int args_depth;
26174       int parms_depth;
26175 
26176       /* Use the source location of the definition.  */
26177       DECL_SOURCE_LOCATION (decl) = DECL_SOURCE_LOCATION (tmpl);
26178 
26179       args_depth = TMPL_ARGS_DEPTH (args);
26180       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
26181       if (args_depth > parms_depth)
26182 	args = get_innermost_template_args (args, parms_depth);
26183 
26184       /* Instantiate a dynamic exception-specification.  noexcept will be
26185 	 handled below.  */
26186       if (tree raises = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (code_pattern)))
26187 	if (TREE_VALUE (raises))
26188 	  {
26189 	    specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
26190 						    args, tf_error, NULL_TREE,
26191 						    /*defer_ok*/false);
26192 	    if (specs && specs != error_mark_node)
26193 	      TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
26194 							  specs);
26195 	  }
26196 
26197       /* Merge parameter declarations.  */
26198       if (tree pattern_parm
26199 	  = skip_artificial_parms_for (code_pattern,
26200 				       DECL_ARGUMENTS (code_pattern)))
26201 	{
26202 	  tree *p = &DECL_ARGUMENTS (decl);
26203 	  for (int skip = num_artificial_parms_for (decl); skip; --skip)
26204 	    p = &DECL_CHAIN (*p);
26205 	  *p = tsubst_decl (pattern_parm, args, tf_error);
26206 	  for (tree t = *p; t; t = DECL_CHAIN (t))
26207 	    DECL_CONTEXT (t) = decl;
26208 	}
26209 
26210       /* Merge additional specifiers from the CODE_PATTERN.  */
26211       if (DECL_DECLARED_INLINE_P (code_pattern)
26212 	  && !DECL_DECLARED_INLINE_P (decl))
26213 	DECL_DECLARED_INLINE_P (decl) = 1;
26214 
26215       maybe_instantiate_noexcept (decl, tf_error);
26216     }
26217   else if (VAR_P (decl))
26218     {
26219       start_lambda_scope (decl);
26220       DECL_INITIAL (decl) =
26221 	tsubst_init (DECL_INITIAL (code_pattern), decl, args,
26222 		     tf_error, DECL_TI_TEMPLATE (decl));
26223       finish_lambda_scope ();
26224       if (VAR_HAD_UNKNOWN_BOUND (decl))
26225 	TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
26226 				   tf_error, DECL_TI_TEMPLATE (decl));
26227     }
26228   else
26229     gcc_unreachable ();
26230 
26231   pop_access_scope (decl);
26232 }
26233 
26234 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
26235    substituted to get DECL.  */
26236 
26237 tree
template_for_substitution(tree decl)26238 template_for_substitution (tree decl)
26239 {
26240   tree tmpl = DECL_TI_TEMPLATE (decl);
26241 
26242   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
26243      for the instantiation.  This is not always the most general
26244      template.  Consider, for example:
26245 
26246 	template <class T>
26247 	struct S { template <class U> void f();
26248 		   template <> void f<int>(); };
26249 
26250      and an instantiation of S<double>::f<int>.  We want TD to be the
26251      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
26252   while (/* An instantiation cannot have a definition, so we need a
26253 	    more general template.  */
26254 	 DECL_TEMPLATE_INSTANTIATION (tmpl)
26255 	   /* We must also deal with friend templates.  Given:
26256 
26257 		template <class T> struct S {
26258 		  template <class U> friend void f() {};
26259 		};
26260 
26261 	      S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
26262 	      so far as the language is concerned, but that's still
26263 	      where we get the pattern for the instantiation from.  On
26264 	      other hand, if the definition comes outside the class, say:
26265 
26266 		template <class T> struct S {
26267 		  template <class U> friend void f();
26268 		};
26269 		template <class U> friend void f() {}
26270 
26271 	      we don't need to look any further.  That's what the check for
26272 	      DECL_INITIAL is for.  */
26273 	  || (TREE_CODE (decl) == FUNCTION_DECL
26274 	      && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
26275 	      && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
26276     {
26277       /* The present template, TD, should not be a definition.  If it
26278 	 were a definition, we should be using it!  Note that we
26279 	 cannot restructure the loop to just keep going until we find
26280 	 a template with a definition, since that might go too far if
26281 	 a specialization was declared, but not defined.  */
26282 
26283       /* Fetch the more general template.  */
26284       tmpl = DECL_TI_TEMPLATE (tmpl);
26285     }
26286 
26287   return tmpl;
26288 }
26289 
26290 /* Returns true if we need to instantiate this template instance even if we
26291    know we aren't going to emit it.  */
26292 
26293 bool
always_instantiate_p(tree decl)26294 always_instantiate_p (tree decl)
26295 {
26296   /* We always instantiate inline functions so that we can inline them.  An
26297      explicit instantiation declaration prohibits implicit instantiation of
26298      non-inline functions.  With high levels of optimization, we would
26299      normally inline non-inline functions -- but we're not allowed to do
26300      that for "extern template" functions.  Therefore, we check
26301      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
26302   return ((TREE_CODE (decl) == FUNCTION_DECL
26303 	   && (DECL_DECLARED_INLINE_P (decl)
26304 	       || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
26305 	  /* And we need to instantiate static data members so that
26306 	     their initializers are available in integral constant
26307 	     expressions.  */
26308 	  || (VAR_P (decl)
26309 	      && decl_maybe_constant_var_p (decl)));
26310 }
26311 
26312 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
26313    instantiate it now, modifying TREE_TYPE (fn).  Returns false on
26314    error, true otherwise.  */
26315 
26316 bool
maybe_instantiate_noexcept(tree fn,tsubst_flags_t complain)26317 maybe_instantiate_noexcept (tree fn, tsubst_flags_t complain)
26318 {
26319   if (fn == error_mark_node)
26320     return false;
26321 
26322   /* Don't instantiate a noexcept-specification from template context.  */
26323   if (processing_template_decl
26324       && (!flag_noexcept_type || type_dependent_expression_p (fn)))
26325     return true;
26326 
26327   tree fntype = TREE_TYPE (fn);
26328   tree spec = TYPE_RAISES_EXCEPTIONS (fntype);
26329 
26330   if ((!spec || UNEVALUATED_NOEXCEPT_SPEC_P (spec))
26331       && DECL_MAYBE_DELETED (fn))
26332     {
26333       if (fn == current_function_decl)
26334 	/* We're in start_preparsed_function, keep going.  */
26335 	return true;
26336 
26337       ++function_depth;
26338       maybe_synthesize_method (fn);
26339       --function_depth;
26340       return !DECL_DELETED_FN (fn);
26341     }
26342 
26343   if (!spec || !TREE_PURPOSE (spec))
26344     return true;
26345 
26346   tree noex = TREE_PURPOSE (spec);
26347   if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
26348       && TREE_CODE (noex) != DEFERRED_PARSE)
26349     return true;
26350 
26351   tree orig_fn = NULL_TREE;
26352   /* For a member friend template we can get a TEMPLATE_DECL.  Let's use
26353      its FUNCTION_DECL for the rest of this function -- push_access_scope
26354      doesn't accept TEMPLATE_DECLs.  */
26355   if (DECL_FUNCTION_TEMPLATE_P (fn))
26356     {
26357       orig_fn = fn;
26358       fn = DECL_TEMPLATE_RESULT (fn);
26359     }
26360 
26361   if (DECL_CLONED_FUNCTION_P (fn))
26362     {
26363       tree prime = DECL_CLONED_FUNCTION (fn);
26364       if (!maybe_instantiate_noexcept (prime, complain))
26365 	return false;
26366       spec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (prime));
26367     }
26368   else if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
26369     {
26370       static hash_set<tree>* fns = new hash_set<tree>;
26371       bool added = false;
26372       if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
26373 	{
26374 	  spec = get_defaulted_eh_spec (fn, complain);
26375 	  if (spec == error_mark_node)
26376 	    /* This might have failed because of an unparsed DMI, so
26377 	       let's try again later.  */
26378 	    return false;
26379 	}
26380       else if (!(added = !fns->add (fn)))
26381 	{
26382 	  /* If hash_set::add returns true, the element was already there.  */
26383 	  location_t loc = cp_expr_loc_or_loc (DEFERRED_NOEXCEPT_PATTERN (noex),
26384 					    DECL_SOURCE_LOCATION (fn));
26385 	  error_at (loc,
26386 		    "exception specification of %qD depends on itself",
26387 		    fn);
26388 	  spec = noexcept_false_spec;
26389 	}
26390       else if (push_tinst_level (fn))
26391 	{
26392 	  push_to_top_level ();
26393 	  push_access_scope (fn);
26394 	  push_deferring_access_checks (dk_no_deferred);
26395 	  input_location = DECL_SOURCE_LOCATION (fn);
26396 
26397 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
26398 	      && !DECL_LOCAL_DECL_P (fn))
26399 	    {
26400 	      /* If needed, set current_class_ptr for the benefit of
26401 		 tsubst_copy/PARM_DECL.  */
26402 	      tree this_parm = DECL_ARGUMENTS (fn);
26403 	      current_class_ptr = NULL_TREE;
26404 	      current_class_ref = cp_build_fold_indirect_ref (this_parm);
26405 	      current_class_ptr = this_parm;
26406 	    }
26407 
26408 	  /* If this function is represented by a TEMPLATE_DECL, then
26409 	     the deferred noexcept-specification might still contain
26410 	     dependent types, even after substitution.  And we need the
26411 	     dependency check functions to work in build_noexcept_spec.  */
26412 	  if (orig_fn)
26413 	    ++processing_template_decl;
26414 
26415 	  /* Do deferred instantiation of the noexcept-specifier.  */
26416 	  noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
26417 					DEFERRED_NOEXCEPT_ARGS (noex),
26418 					tf_warning_or_error, fn,
26419 					/*function_p=*/false,
26420 					/*i_c_e_p=*/true);
26421 
26422 	  /* Build up the noexcept-specification.  */
26423 	  spec = build_noexcept_spec (noex, tf_warning_or_error);
26424 
26425 	  if (orig_fn)
26426 	    --processing_template_decl;
26427 
26428 	  pop_deferring_access_checks ();
26429 	  pop_access_scope (fn);
26430 	  pop_tinst_level ();
26431 	  pop_from_top_level ();
26432 	}
26433       else
26434 	spec = noexcept_false_spec;
26435 
26436       if (added)
26437 	fns->remove (fn);
26438     }
26439 
26440   if (spec == error_mark_node)
26441     {
26442       /* This failed with a hard error, so let's go with false.  */
26443       gcc_assert (seen_error ());
26444       spec = noexcept_false_spec;
26445     }
26446 
26447   TREE_TYPE (fn) = build_exception_variant (fntype, spec);
26448   if (orig_fn)
26449     TREE_TYPE (orig_fn) = TREE_TYPE (fn);
26450 
26451   return true;
26452 }
26453 
26454 /* We're starting to process the function INST, an instantiation of PATTERN;
26455    add their parameters to local_specializations.  */
26456 
26457 static void
register_parameter_specializations(tree pattern,tree inst)26458 register_parameter_specializations (tree pattern, tree inst)
26459 {
26460   tree tmpl_parm = DECL_ARGUMENTS (pattern);
26461   tree spec_parm = DECL_ARGUMENTS (inst);
26462   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (inst))
26463     {
26464       register_local_specialization (spec_parm, tmpl_parm);
26465       spec_parm = skip_artificial_parms_for (inst, spec_parm);
26466       tmpl_parm = skip_artificial_parms_for (pattern, tmpl_parm);
26467     }
26468   for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
26469     {
26470       if (!DECL_PACK_P (tmpl_parm))
26471 	{
26472 	  register_local_specialization (spec_parm, tmpl_parm);
26473 	  spec_parm = DECL_CHAIN (spec_parm);
26474 	}
26475       else
26476 	{
26477 	  /* Register the (value) argument pack as a specialization of
26478 	     TMPL_PARM, then move on.  */
26479 	  tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
26480 	  register_local_specialization (argpack, tmpl_parm);
26481 	}
26482     }
26483   gcc_assert (!spec_parm);
26484 }
26485 
26486 /* Instantiate the body of D using PATTERN with ARGS.  We have
26487    already determined PATTERN is the correct template to use.
26488    NESTED_P is true if this is a nested function, in which case
26489    PATTERN will be a FUNCTION_DECL not a TEMPLATE_DECL.  */
26490 
26491 static void
instantiate_body(tree pattern,tree args,tree d,bool nested_p)26492 instantiate_body (tree pattern, tree args, tree d, bool nested_p)
26493 {
26494   tree td = NULL_TREE;
26495   tree code_pattern = pattern;
26496 
26497   if (!nested_p)
26498     {
26499       td = pattern;
26500       code_pattern = DECL_TEMPLATE_RESULT (td);
26501     }
26502   else
26503     /* Only OMP reductions are nested.  */
26504     gcc_checking_assert (DECL_OMP_DECLARE_REDUCTION_P (code_pattern));
26505 
26506   vec<tree> omp_privatization_save;
26507   if (current_function_decl)
26508     save_omp_privatization_clauses (omp_privatization_save);
26509 
26510   bool push_to_top = maybe_push_to_top_level (d);
26511 
26512   if (VAR_P (d))
26513     {
26514       /* The variable might be a lambda's extra scope, and that
26515 	 lambda's visibility depends on D's.  */
26516       maybe_commonize_var (d);
26517       determine_visibility (d);
26518     }
26519 
26520   /* Mark D as instantiated so that recursive calls to
26521      instantiate_decl do not try to instantiate it again.  */
26522   DECL_TEMPLATE_INSTANTIATED (d) = 1;
26523 
26524   if (td)
26525     /* Regenerate the declaration in case the template has been modified
26526        by a subsequent redeclaration.  */
26527     regenerate_decl_from_template (d, td, args);
26528 
26529   /* We already set the file and line above.  Reset them now in case
26530      they changed as a result of calling regenerate_decl_from_template.  */
26531   input_location = DECL_SOURCE_LOCATION (d);
26532 
26533   if (VAR_P (d))
26534     {
26535       /* Clear out DECL_RTL; whatever was there before may not be right
26536 	 since we've reset the type of the declaration.  */
26537       SET_DECL_RTL (d, NULL);
26538       DECL_IN_AGGR_P (d) = 0;
26539 
26540       /* The initializer is placed in DECL_INITIAL by
26541 	 regenerate_decl_from_template so we don't need to
26542 	 push/pop_access_scope again here.  Pull it out so that
26543 	 cp_finish_decl can process it.  */
26544       bool const_init = false;
26545       tree init = DECL_INITIAL (d);
26546       DECL_INITIAL (d) = NULL_TREE;
26547       DECL_INITIALIZED_P (d) = 0;
26548 
26549       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
26550 	 initializer.  That function will defer actual emission until
26551 	 we have a chance to determine linkage.  */
26552       DECL_EXTERNAL (d) = 0;
26553 
26554       /* Enter the scope of D so that access-checking works correctly.  */
26555       bool enter_context = DECL_CLASS_SCOPE_P (d);
26556       if (enter_context)
26557         push_nested_class (DECL_CONTEXT (d));
26558 
26559       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
26560       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
26561 
26562       if (enter_context)
26563         pop_nested_class ();
26564     }
26565   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
26566     synthesize_method (d);
26567   else if (TREE_CODE (d) == FUNCTION_DECL)
26568     {
26569       /* Set up the list of local specializations.  */
26570       local_specialization_stack lss (push_to_top ? lss_blank : lss_copy);
26571       tree block = NULL_TREE;
26572 
26573       /* Set up context.  */
26574       if (nested_p)
26575 	block = push_stmt_list ();
26576       else
26577 	{
26578 	  start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
26579 
26580 	  perform_instantiation_time_access_checks (code_pattern, args);
26581 	}
26582 
26583       /* Create substitution entries for the parameters.  */
26584       register_parameter_specializations (code_pattern, d);
26585 
26586       /* Substitute into the body of the function.  */
26587       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
26588 	tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
26589 			tf_warning_or_error, d);
26590       else
26591 	{
26592 	  tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
26593 		       tf_warning_or_error, DECL_TI_TEMPLATE (d),
26594 		       /*integral_constant_expression_p=*/false);
26595 
26596 	  /* Set the current input_location to the end of the function
26597 	     so that finish_function knows where we are.  */
26598 	  input_location
26599 	    = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
26600 
26601 	  /* Remember if we saw an infinite loop in the template.  */
26602 	  current_function_infinite_loop
26603 	    = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
26604 	}
26605 
26606       /* Finish the function.  */
26607       if (nested_p)
26608 	DECL_SAVED_TREE (d) = pop_stmt_list (block);
26609       else
26610 	{
26611 	  d = finish_function (/*inline_p=*/false);
26612 	  expand_or_defer_fn (d);
26613 	}
26614 
26615       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
26616 	cp_check_omp_declare_reduction (d);
26617     }
26618 
26619   /* We're not deferring instantiation any more.  */
26620   if (!nested_p)
26621     TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
26622 
26623   maybe_pop_from_top_level (push_to_top);
26624 
26625   if (current_function_decl)
26626     restore_omp_privatization_clauses (omp_privatization_save);
26627 }
26628 
26629 /* Produce the definition of D, a _DECL generated from a template.  If
26630    DEFER_OK is true, then we don't have to actually do the
26631    instantiation now; we just have to do it sometime.  Normally it is
26632    an error if this is an explicit instantiation but D is undefined.
26633    EXPL_INST_CLASS_MEM_P is true iff D is a member of an explicitly
26634    instantiated class template.  */
26635 
26636 tree
instantiate_decl(tree d,bool defer_ok,bool expl_inst_class_mem_p)26637 instantiate_decl (tree d, bool defer_ok, bool expl_inst_class_mem_p)
26638 {
26639   tree tmpl = DECL_TI_TEMPLATE (d);
26640   tree gen_args;
26641   tree args;
26642   tree td;
26643   tree code_pattern;
26644   tree spec;
26645   tree gen_tmpl;
26646   bool pattern_defined;
26647   location_t saved_loc = input_location;
26648   int saved_unevaluated_operand = cp_unevaluated_operand;
26649   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
26650   bool external_p;
26651   bool deleted_p;
26652 
26653   /* This function should only be used to instantiate templates for
26654      functions and static member variables.  */
26655   gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
26656 
26657   /* A concept is never instantiated. */
26658   gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
26659 
26660   gcc_checking_assert (!DECL_FUNCTION_SCOPE_P (d));
26661 
26662   if (modules_p ())
26663     /* We may have a pending instantiation of D itself.  */
26664     lazy_load_pendings (d);
26665 
26666   /* Variables are never deferred; if instantiation is required, they
26667      are instantiated right away.  That allows for better code in the
26668      case that an expression refers to the value of the variable --
26669      if the variable has a constant value the referring expression can
26670      take advantage of that fact.  */
26671   if (VAR_P (d))
26672     defer_ok = false;
26673 
26674   /* Don't instantiate cloned functions.  Instead, instantiate the
26675      functions they cloned.  */
26676   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
26677     d = DECL_CLONED_FUNCTION (d);
26678 
26679   if (DECL_TEMPLATE_INSTANTIATED (d)
26680       || TREE_TYPE (d) == error_mark_node
26681       || (TREE_CODE (d) == FUNCTION_DECL
26682 	  && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
26683       || DECL_TEMPLATE_SPECIALIZATION (d))
26684     /* D has already been instantiated or explicitly specialized, so
26685        there's nothing for us to do here.
26686 
26687        It might seem reasonable to check whether or not D is an explicit
26688        instantiation, and, if so, stop here.  But when an explicit
26689        instantiation is deferred until the end of the compilation,
26690        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
26691        the instantiation.  */
26692     return d;
26693 
26694   /* Check to see whether we know that this template will be
26695      instantiated in some other file, as with "extern template"
26696      extension.  */
26697   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
26698 
26699   /* In general, we do not instantiate such templates.  */
26700   if (external_p && !always_instantiate_p (d))
26701     return d;
26702 
26703   gen_tmpl = most_general_template (tmpl);
26704   gen_args = DECL_TI_ARGS (d);
26705 
26706   /* We should already have the extra args.  */
26707   gcc_checking_assert (tmpl == gen_tmpl
26708 		       || (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
26709 			   == TMPL_ARGS_DEPTH (gen_args)));
26710   /* And what's in the hash table should match D.  */
26711   gcc_checking_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0))
26712 		       == d
26713 		       || spec == NULL_TREE);
26714 
26715   /* This needs to happen before any tsubsting.  */
26716   if (! push_tinst_level (d))
26717     return d;
26718 
26719   timevar_push (TV_TEMPLATE_INST);
26720 
26721   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
26722      for the instantiation.  */
26723   td = template_for_substitution (d);
26724   args = gen_args;
26725 
26726   if (variable_template_specialization_p (d))
26727     {
26728       /* Look up an explicit specialization, if any.  */
26729       tree elt = most_specialized_partial_spec (d, tf_warning_or_error);
26730       if (elt && elt != error_mark_node)
26731 	{
26732 	  td = TREE_VALUE (elt);
26733 	  args = TREE_PURPOSE (elt);
26734 	}
26735     }
26736 
26737   code_pattern = DECL_TEMPLATE_RESULT (td);
26738 
26739   /* We should never be trying to instantiate a member of a class
26740      template or partial specialization.  */
26741   gcc_assert (d != code_pattern);
26742 
26743   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
26744       || DECL_TEMPLATE_SPECIALIZATION (td))
26745     /* In the case of a friend template whose definition is provided
26746        outside the class, we may have too many arguments.  Drop the
26747        ones we don't need.  The same is true for specializations.  */
26748     args = get_innermost_template_args
26749       (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
26750 
26751   if (TREE_CODE (d) == FUNCTION_DECL)
26752     {
26753       deleted_p = DECL_DELETED_FN (code_pattern);
26754       pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
26755 			  && DECL_INITIAL (code_pattern) != error_mark_node)
26756 			 || DECL_DEFAULTED_FN (code_pattern)
26757 			 || deleted_p);
26758     }
26759   else
26760     {
26761       deleted_p = false;
26762       if (DECL_CLASS_SCOPE_P (code_pattern))
26763 	pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
26764       else
26765 	pattern_defined = ! DECL_EXTERNAL (code_pattern);
26766     }
26767 
26768   /* We may be in the middle of deferred access check.  Disable it now.  */
26769   push_deferring_access_checks (dk_no_deferred);
26770 
26771   /* Unless an explicit instantiation directive has already determined
26772      the linkage of D, remember that a definition is available for
26773      this entity.  */
26774   if (pattern_defined
26775       && !DECL_INTERFACE_KNOWN (d)
26776       && !DECL_NOT_REALLY_EXTERN (d))
26777     mark_definable (d);
26778 
26779   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
26780   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
26781   input_location = DECL_SOURCE_LOCATION (d);
26782 
26783   /* If D is a member of an explicitly instantiated class template,
26784      and no definition is available, treat it like an implicit
26785      instantiation.  */
26786   if (!pattern_defined && expl_inst_class_mem_p
26787       && DECL_EXPLICIT_INSTANTIATION (d))
26788     {
26789       /* Leave linkage flags alone on instantiations with anonymous
26790 	 visibility.  */
26791       if (TREE_PUBLIC (d))
26792 	{
26793 	  DECL_NOT_REALLY_EXTERN (d) = 0;
26794 	  DECL_INTERFACE_KNOWN (d) = 0;
26795 	}
26796       SET_DECL_IMPLICIT_INSTANTIATION (d);
26797     }
26798 
26799   /* Defer all other templates, unless we have been explicitly
26800      forbidden from doing so.  */
26801   if (/* If there is no definition, we cannot instantiate the
26802 	 template.  */
26803       ! pattern_defined
26804       /* If it's OK to postpone instantiation, do so.  */
26805       || defer_ok
26806       /* If this is a static data member that will be defined
26807 	 elsewhere, we don't want to instantiate the entire data
26808 	 member, but we do want to instantiate the initializer so that
26809 	 we can substitute that elsewhere.  */
26810       || (external_p && VAR_P (d))
26811       /* Handle here a deleted function too, avoid generating
26812 	 its body (c++/61080).  */
26813       || deleted_p)
26814     {
26815       /* The definition of the static data member is now required so
26816 	 we must substitute the initializer.  */
26817       if (VAR_P (d)
26818 	  && !DECL_INITIAL (d)
26819 	  && DECL_INITIAL (code_pattern))
26820 	{
26821 	  tree ns;
26822 	  tree init;
26823 	  bool const_init = false;
26824 	  bool enter_context = DECL_CLASS_SCOPE_P (d);
26825 
26826 	  ns = decl_namespace_context (d);
26827 	  push_nested_namespace (ns);
26828 	  if (enter_context)
26829 	    push_nested_class (DECL_CONTEXT (d));
26830 	  init = tsubst_expr (DECL_INITIAL (code_pattern),
26831 			      args,
26832 			      tf_warning_or_error, NULL_TREE,
26833 			      /*integral_constant_expression_p=*/false);
26834 	  /* If instantiating the initializer involved instantiating this
26835 	     again, don't call cp_finish_decl twice.  */
26836 	  if (!DECL_INITIAL (d))
26837 	    {
26838 	      /* Make sure the initializer is still constant, in case of
26839 		 circular dependency (template/instantiate6.C). */
26840 	      const_init
26841 		= DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
26842 	      cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
26843 			      /*asmspec_tree=*/NULL_TREE, 0);
26844 	    }
26845 	  if (enter_context)
26846 	    pop_nested_class ();
26847 	  pop_nested_namespace (ns);
26848 	}
26849 
26850       /* We restore the source position here because it's used by
26851 	 add_pending_template.  */
26852       input_location = saved_loc;
26853 
26854       if (at_eof && !pattern_defined
26855 	  && DECL_EXPLICIT_INSTANTIATION (d)
26856 	  && DECL_NOT_REALLY_EXTERN (d))
26857 	/* [temp.explicit]
26858 
26859 	   The definition of a non-exported function template, a
26860 	   non-exported member function template, or a non-exported
26861 	   member function or static data member of a class template
26862 	   shall be present in every translation unit in which it is
26863 	   explicitly instantiated.  */
26864 	permerror (input_location,  "explicit instantiation of %qD "
26865 		   "but no definition available", d);
26866 
26867       /* If we're in unevaluated context, we just wanted to get the
26868 	 constant value; this isn't an odr use, so don't queue
26869 	 a full instantiation.  */
26870       if (!cp_unevaluated_operand
26871 	  /* ??? Historically, we have instantiated inline functions, even
26872 	     when marked as "extern template".  */
26873 	  && !(external_p && VAR_P (d)))
26874 	add_pending_template (d);
26875     }
26876   else
26877     {
26878       set_instantiating_module (d);
26879       if (variable_template_p (gen_tmpl))
26880 	note_variable_template_instantiation (d);
26881       instantiate_body (td, args, d, false);
26882     }
26883 
26884   pop_deferring_access_checks ();
26885   timevar_pop (TV_TEMPLATE_INST);
26886   pop_tinst_level ();
26887   input_location = saved_loc;
26888   cp_unevaluated_operand = saved_unevaluated_operand;
26889   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
26890 
26891   return d;
26892 }
26893 
26894 /* Run through the list of templates that we wish we could
26895    instantiate, and instantiate any we can.  RETRIES is the
26896    number of times we retry pending template instantiation.  */
26897 
26898 void
instantiate_pending_templates(int retries)26899 instantiate_pending_templates (int retries)
26900 {
26901   int reconsider;
26902   location_t saved_loc = input_location;
26903 
26904   /* Instantiating templates may trigger vtable generation.  This in turn
26905      may require further template instantiations.  We place a limit here
26906      to avoid infinite loop.  */
26907   if (pending_templates && retries >= max_tinst_depth)
26908     {
26909       tree decl = pending_templates->tinst->maybe_get_node ();
26910 
26911       fatal_error (input_location,
26912 		   "template instantiation depth exceeds maximum of %d"
26913 		   " instantiating %q+D, possibly from virtual table generation"
26914 		   " (use %<-ftemplate-depth=%> to increase the maximum)",
26915 		   max_tinst_depth, decl);
26916       if (TREE_CODE (decl) == FUNCTION_DECL)
26917 	/* Pretend that we defined it.  */
26918 	DECL_INITIAL (decl) = error_mark_node;
26919       return;
26920     }
26921 
26922   do
26923     {
26924       struct pending_template **t = &pending_templates;
26925       struct pending_template *last = NULL;
26926       reconsider = 0;
26927       while (*t)
26928 	{
26929 	  tree instantiation = reopen_tinst_level ((*t)->tinst);
26930 	  bool complete = false;
26931 
26932 	  if (TYPE_P (instantiation))
26933 	    {
26934 	      if (!COMPLETE_TYPE_P (instantiation))
26935 		{
26936 		  instantiate_class_template (instantiation);
26937 		  if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
26938 		    for (tree fld = TYPE_FIELDS (instantiation);
26939 			 fld; fld = TREE_CHAIN (fld))
26940 		      if ((VAR_P (fld)
26941 			   || (TREE_CODE (fld) == FUNCTION_DECL
26942 			       && !DECL_ARTIFICIAL (fld)))
26943 			  && DECL_TEMPLATE_INSTANTIATION (fld))
26944 			instantiate_decl (fld,
26945 					  /*defer_ok=*/false,
26946 					  /*expl_inst_class_mem_p=*/false);
26947 
26948 		  if (COMPLETE_TYPE_P (instantiation))
26949 		    reconsider = 1;
26950 		}
26951 
26952 	      complete = COMPLETE_TYPE_P (instantiation);
26953 	    }
26954 	  else
26955 	    {
26956 	      if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
26957 		  && !DECL_TEMPLATE_INSTANTIATED (instantiation))
26958 		{
26959 		  instantiation
26960 		    = instantiate_decl (instantiation,
26961 					/*defer_ok=*/false,
26962 					/*expl_inst_class_mem_p=*/false);
26963 		  if (DECL_TEMPLATE_INSTANTIATED (instantiation))
26964 		    reconsider = 1;
26965 		}
26966 
26967 	      complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
26968 			  || DECL_TEMPLATE_INSTANTIATED (instantiation));
26969 	    }
26970 
26971 	  if (complete)
26972 	    {
26973 	      /* If INSTANTIATION has been instantiated, then we don't
26974 		 need to consider it again in the future.  */
26975 	      struct pending_template *drop = *t;
26976 	      *t = (*t)->next;
26977 	      set_refcount_ptr (drop->tinst);
26978 	      pending_template_freelist ().free (drop);
26979 	    }
26980 	  else
26981 	    {
26982 	      last = *t;
26983 	      t = &(*t)->next;
26984 	    }
26985 	  tinst_depth = 0;
26986 	  set_refcount_ptr (current_tinst_level);
26987 	}
26988       last_pending_template = last;
26989     }
26990   while (reconsider);
26991 
26992   input_location = saved_loc;
26993 }
26994 
26995 /* Substitute ARGVEC into T, which is a list of initializers for
26996    either base class or a non-static data member.  The TREE_PURPOSEs
26997    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
26998    instantiate_decl.  */
26999 
27000 static tree
tsubst_initializer_list(tree t,tree argvec)27001 tsubst_initializer_list (tree t, tree argvec)
27002 {
27003   tree inits = NULL_TREE;
27004   tree target_ctor = error_mark_node;
27005 
27006   for (; t; t = TREE_CHAIN (t))
27007     {
27008       tree decl;
27009       tree init;
27010       tree expanded_bases = NULL_TREE;
27011       tree expanded_arguments = NULL_TREE;
27012       int i, len = 1;
27013 
27014       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
27015         {
27016           tree expr;
27017           tree arg;
27018 
27019           /* Expand the base class expansion type into separate base
27020              classes.  */
27021           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
27022                                                  tf_warning_or_error,
27023                                                  NULL_TREE);
27024           if (expanded_bases == error_mark_node)
27025             continue;
27026 
27027           /* We'll be building separate TREE_LISTs of arguments for
27028              each base.  */
27029           len = TREE_VEC_LENGTH (expanded_bases);
27030           expanded_arguments = make_tree_vec (len);
27031           for (i = 0; i < len; i++)
27032             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
27033 
27034           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
27035              expand each argument in the TREE_VALUE of t.  */
27036           expr = make_node (EXPR_PACK_EXPANSION);
27037 	  PACK_EXPANSION_LOCAL_P (expr) = true;
27038           PACK_EXPANSION_PARAMETER_PACKS (expr) =
27039             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
27040 
27041 	  if (TREE_VALUE (t) == void_type_node)
27042 	    /* VOID_TYPE_NODE is used to indicate
27043 	       value-initialization.  */
27044 	    {
27045 	      for (i = 0; i < len; i++)
27046 		TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
27047 	    }
27048 	  else
27049 	    {
27050 	      /* Substitute parameter packs into each argument in the
27051 		 TREE_LIST.  */
27052 	      in_base_initializer = 1;
27053 	      for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
27054 		{
27055 		  tree expanded_exprs;
27056 
27057 		  /* Expand the argument.  */
27058 		  tree value;
27059 		  if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
27060 		    value = TREE_VALUE (arg);
27061 		  else
27062 		    {
27063 		      value = expr;
27064 		      SET_PACK_EXPANSION_PATTERN (value, TREE_VALUE (arg));
27065 		    }
27066 		  expanded_exprs
27067 		    = tsubst_pack_expansion (value, argvec,
27068 					     tf_warning_or_error,
27069 					     NULL_TREE);
27070 		  if (expanded_exprs == error_mark_node)
27071 		    continue;
27072 
27073 		  /* Prepend each of the expanded expressions to the
27074 		     corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
27075 		  for (i = 0; i < len; i++)
27076 		    if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
27077 		      for (int j = 0; j < TREE_VEC_LENGTH (expanded_exprs); j++)
27078 			TREE_VEC_ELT (expanded_arguments, i)
27079 			  = tree_cons (NULL_TREE,
27080 				       TREE_VEC_ELT (expanded_exprs, j),
27081 				       TREE_VEC_ELT (expanded_arguments, i));
27082 		    else
27083 		      TREE_VEC_ELT (expanded_arguments, i)
27084 			= tree_cons (NULL_TREE,
27085 				     TREE_VEC_ELT (expanded_exprs, i),
27086 				     TREE_VEC_ELT (expanded_arguments, i));
27087 		}
27088 	      in_base_initializer = 0;
27089 
27090 	      /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
27091 		 since we built them backwards.  */
27092 	      for (i = 0; i < len; i++)
27093 		{
27094 		  TREE_VEC_ELT (expanded_arguments, i) =
27095 		    nreverse (TREE_VEC_ELT (expanded_arguments, i));
27096 		}
27097 	    }
27098         }
27099 
27100       for (i = 0; i < len; ++i)
27101         {
27102           if (expanded_bases)
27103             {
27104               decl = TREE_VEC_ELT (expanded_bases, i);
27105               decl = expand_member_init (decl);
27106               init = TREE_VEC_ELT (expanded_arguments, i);
27107             }
27108           else
27109             {
27110 	      tree tmp;
27111               decl = tsubst_copy (TREE_PURPOSE (t), argvec,
27112                                   tf_warning_or_error, NULL_TREE);
27113 
27114               decl = expand_member_init (decl);
27115               if (decl && !DECL_P (decl))
27116                 in_base_initializer = 1;
27117 
27118 	      init = TREE_VALUE (t);
27119 	      tmp = init;
27120 	      if (init != void_type_node)
27121 		init = tsubst_expr (init, argvec,
27122 				    tf_warning_or_error, NULL_TREE,
27123 				    /*integral_constant_expression_p=*/false);
27124 	      if (init == NULL_TREE && tmp != NULL_TREE)
27125 		/* If we had an initializer but it instantiated to nothing,
27126 		   value-initialize the object.  This will only occur when
27127 		   the initializer was a pack expansion where the parameter
27128 		   packs used in that expansion were of length zero.  */
27129 		init = void_type_node;
27130               in_base_initializer = 0;
27131             }
27132 
27133 	  if (target_ctor != error_mark_node
27134 	      && init != error_mark_node)
27135 	    {
27136 	      error ("mem-initializer for %qD follows constructor delegation",
27137 		     decl);
27138 	      return inits;
27139 	    }
27140 	  /* Look for a target constructor. */
27141 	  if (init != error_mark_node
27142 	      && decl && CLASS_TYPE_P (decl)
27143 	      && same_type_p (decl, current_class_type))
27144 	    {
27145 	      maybe_warn_cpp0x (CPP0X_DELEGATING_CTORS);
27146 	      if (inits)
27147 		{
27148 		  error ("constructor delegation follows mem-initializer for %qD",
27149 			 TREE_PURPOSE (inits));
27150 		  continue;
27151 		}
27152 	      target_ctor = init;
27153 	    }
27154 
27155           if (decl)
27156             {
27157               init = build_tree_list (decl, init);
27158 	      /* Carry over the dummy TREE_TYPE node containing the source
27159 		 location.  */
27160 	      TREE_TYPE (init) = TREE_TYPE (t);
27161               TREE_CHAIN (init) = inits;
27162               inits = init;
27163             }
27164         }
27165     }
27166   return inits;
27167 }
27168 
27169 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
27170    is the instantiation (which should have been created with
27171    start_enum) and ARGS are the template arguments to use.  */
27172 
27173 static void
tsubst_enum(tree tag,tree newtag,tree args)27174 tsubst_enum (tree tag, tree newtag, tree args)
27175 {
27176   tree e;
27177 
27178   if (SCOPED_ENUM_P (newtag))
27179     begin_scope (sk_scoped_enum, newtag);
27180 
27181   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
27182     {
27183       tree value;
27184       tree decl = TREE_VALUE (e);
27185 
27186       /* Note that in a template enum, the TREE_VALUE is the
27187 	 CONST_DECL, not the corresponding INTEGER_CST.  */
27188       value = tsubst_expr (DECL_INITIAL (decl),
27189 			   args, tf_warning_or_error, NULL_TREE,
27190 			   /*integral_constant_expression_p=*/true);
27191 
27192       /* Give this enumeration constant the correct access.  */
27193       set_current_access_from_decl (decl);
27194 
27195       /* Actually build the enumerator itself.  Here we're assuming that
27196 	 enumerators can't have dependent attributes.  */
27197       tree newdecl = build_enumerator (DECL_NAME (decl), value, newtag,
27198 				       DECL_ATTRIBUTES (decl),
27199 				       DECL_SOURCE_LOCATION (decl));
27200       /* Attribute deprecated without an argument isn't sticky: it'll
27201 	 melt into a tree flag, so we need to propagate the flag here,
27202 	 since we just created a new enumerator.  */
27203       TREE_DEPRECATED (newdecl) = TREE_DEPRECATED (decl);
27204       TREE_UNAVAILABLE (newdecl) = TREE_UNAVAILABLE (decl);
27205     }
27206 
27207   if (SCOPED_ENUM_P (newtag))
27208     finish_scope ();
27209 
27210   finish_enum_value_list (newtag);
27211   finish_enum (newtag);
27212 
27213   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
27214     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
27215   TREE_DEPRECATED (newtag) = TREE_DEPRECATED (tag);
27216   TREE_UNAVAILABLE (newtag) = TREE_UNAVAILABLE (tag);
27217 }
27218 
27219 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
27220    its type -- but without substituting the innermost set of template
27221    arguments.  So, innermost set of template parameters will appear in
27222    the type.  */
27223 
27224 tree
get_mostly_instantiated_function_type(tree decl)27225 get_mostly_instantiated_function_type (tree decl)
27226 {
27227   /* For a function, DECL_TI_TEMPLATE is partially instantiated.  */
27228   return TREE_TYPE (DECL_TI_TEMPLATE (decl));
27229 }
27230 
27231 /* Return truthvalue if we're processing a template different from
27232    the last one involved in diagnostics.  */
27233 bool
problematic_instantiation_changed(void)27234 problematic_instantiation_changed (void)
27235 {
27236   return current_tinst_level != last_error_tinst_level;
27237 }
27238 
27239 /* Remember current template involved in diagnostics.  */
27240 void
record_last_problematic_instantiation(void)27241 record_last_problematic_instantiation (void)
27242 {
27243   set_refcount_ptr (last_error_tinst_level, current_tinst_level);
27244 }
27245 
27246 struct tinst_level *
current_instantiation(void)27247 current_instantiation (void)
27248 {
27249   return current_tinst_level;
27250 }
27251 
27252 /* Return TRUE if current_function_decl is being instantiated, false
27253    otherwise.  */
27254 
27255 bool
instantiating_current_function_p(void)27256 instantiating_current_function_p (void)
27257 {
27258   return (current_instantiation ()
27259 	  && (current_instantiation ()->maybe_get_node ()
27260 	      == current_function_decl));
27261 }
27262 
27263 /* [temp.param] Check that template non-type parm TYPE is of an allowable
27264    type.  Return false for ok, true for disallowed.  Issue error and
27265    inform messages under control of COMPLAIN.  */
27266 
27267 static bool
invalid_nontype_parm_type_p(tree type,tsubst_flags_t complain)27268 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
27269 {
27270   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
27271     return false;
27272   else if (TYPE_PTR_P (type))
27273     return false;
27274   else if (TYPE_REF_P (type)
27275 	   && !TYPE_REF_IS_RVALUE (type))
27276     return false;
27277   else if (TYPE_PTRMEM_P (type))
27278     return false;
27279   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
27280     {
27281       if (CLASS_PLACEHOLDER_TEMPLATE (type) && cxx_dialect < cxx20)
27282 	{
27283 	  if (complain & tf_error)
27284 	    error ("non-type template parameters of deduced class type only "
27285 		   "available with %<-std=c++20%> or %<-std=gnu++20%>");
27286 	  return true;
27287 	}
27288       return false;
27289     }
27290   else if (TREE_CODE (type) == NULLPTR_TYPE)
27291     return false;
27292   else if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM
27293 	   && cxx_dialect < cxx11)
27294     /* Fall through; before C++11 alias templates, a bound ttp
27295        always instantiates into a class type.  */;
27296   else if (WILDCARD_TYPE_P (type))
27297     /* Any other wildcard type not already handled above is allowed.  */
27298     return false;
27299   else if (TREE_CODE (type) == COMPLEX_TYPE)
27300     /* Fall through.  */;
27301   else if (VOID_TYPE_P (type))
27302     /* Fall through.  */;
27303   else if (cxx_dialect >= cxx20)
27304     {
27305       if (dependent_type_p (type))
27306 	return false;
27307       if (!complete_type_or_maybe_complain (type, NULL_TREE, complain))
27308 	return true;
27309       if (structural_type_p (type))
27310 	return false;
27311       if (complain & tf_error)
27312 	{
27313 	  auto_diagnostic_group d;
27314 	  error ("%qT is not a valid type for a template non-type "
27315 		 "parameter because it is not structural", type);
27316 	  structural_type_p (type, true);
27317 	}
27318       return true;
27319     }
27320   else if (CLASS_TYPE_P (type))
27321     {
27322       if (complain & tf_error)
27323 	error ("non-type template parameters of class type only available "
27324 	       "with %<-std=c++20%> or %<-std=gnu++20%>");
27325       return true;
27326     }
27327 
27328   if (complain & tf_error)
27329     {
27330       if (type == error_mark_node)
27331 	inform (input_location, "invalid template non-type parameter");
27332       else
27333 	error ("%q#T is not a valid type for a template non-type parameter",
27334 	       type);
27335     }
27336   return true;
27337 }
27338 
27339 /* Returns true iff the noexcept-specifier for TYPE is value-dependent.  */
27340 
27341 static bool
value_dependent_noexcept_spec_p(tree type)27342 value_dependent_noexcept_spec_p (tree type)
27343 {
27344   if (tree spec = TYPE_RAISES_EXCEPTIONS (type))
27345     if (tree noex = TREE_PURPOSE (spec))
27346       /* Treat DEFERRED_NOEXCEPT as non-dependent, since it doesn't
27347 	 affect overload resolution and treating it as dependent breaks
27348 	 things.  Same for an unparsed noexcept expression.  */
27349       if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
27350 	  && TREE_CODE (noex) != DEFERRED_PARSE
27351 	  && value_dependent_expression_p (noex))
27352 	return true;
27353 
27354   return false;
27355 }
27356 
27357 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
27358    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
27359 
27360 static bool
dependent_type_p_r(tree type)27361 dependent_type_p_r (tree type)
27362 {
27363   tree scope;
27364 
27365   /* [temp.dep.type]
27366 
27367      A type is dependent if it is:
27368 
27369      -- a template parameter. Template template parameters are types
27370 	for us (since TYPE_P holds true for them) so we handle
27371 	them here.  */
27372   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
27373       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
27374     return true;
27375   /* -- a qualified-id with a nested-name-specifier which contains a
27376 	class-name that names a dependent type or whose unqualified-id
27377 	names a dependent type.  */
27378   if (TREE_CODE (type) == TYPENAME_TYPE)
27379     return true;
27380 
27381   /* An alias template specialization can be dependent even if the
27382      resulting type is not.  */
27383   if (dependent_alias_template_spec_p (type, nt_transparent))
27384     return true;
27385 
27386   /* -- a cv-qualified type where the cv-unqualified type is
27387 	dependent.
27388      No code is necessary for this bullet; the code below handles
27389      cv-qualified types, and we don't want to strip aliases with
27390      TYPE_MAIN_VARIANT because of DR 1558.  */
27391   /* -- a compound type constructed from any dependent type.  */
27392   if (TYPE_PTRMEM_P (type))
27393     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
27394 	    || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
27395 					   (type)));
27396   else if (INDIRECT_TYPE_P (type))
27397     return dependent_type_p (TREE_TYPE (type));
27398   else if (FUNC_OR_METHOD_TYPE_P (type))
27399     {
27400       tree arg_type;
27401 
27402       if (dependent_type_p (TREE_TYPE (type)))
27403 	return true;
27404       for (arg_type = TYPE_ARG_TYPES (type);
27405 	   arg_type;
27406 	   arg_type = TREE_CHAIN (arg_type))
27407 	if (dependent_type_p (TREE_VALUE (arg_type)))
27408 	  return true;
27409       if (cxx_dialect >= cxx17
27410 	  && value_dependent_noexcept_spec_p (type))
27411 	/* A value-dependent noexcept-specifier makes the type dependent.  */
27412 	return true;
27413       return false;
27414     }
27415   /* -- an array type constructed from any dependent type or whose
27416 	size is specified by a constant expression that is
27417 	value-dependent.
27418 
27419         We checked for type- and value-dependence of the bounds in
27420         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
27421   if (TREE_CODE (type) == ARRAY_TYPE)
27422     {
27423       if (TYPE_DOMAIN (type)
27424 	  && dependent_type_p (TYPE_DOMAIN (type)))
27425 	return true;
27426       return dependent_type_p (TREE_TYPE (type));
27427     }
27428 
27429   /* -- a template-id in which either the template name is a template
27430      parameter ...  */
27431   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
27432     return true;
27433   /* ... or any of the template arguments is a dependent type or
27434 	an expression that is type-dependent or value-dependent.  */
27435   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
27436 	   && (any_dependent_template_arguments_p
27437 	       (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
27438     return true;
27439 
27440   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
27441      dependent; if the argument of the `typeof' expression is not
27442      type-dependent, then it should already been have resolved.  */
27443   if (TREE_CODE (type) == TYPEOF_TYPE
27444       || TREE_CODE (type) == DECLTYPE_TYPE
27445       || TREE_CODE (type) == UNDERLYING_TYPE)
27446     return true;
27447 
27448   /* A template argument pack is dependent if any of its packed
27449      arguments are.  */
27450   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
27451     {
27452       tree args = ARGUMENT_PACK_ARGS (type);
27453       int i, len = TREE_VEC_LENGTH (args);
27454       for (i = 0; i < len; ++i)
27455         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
27456           return true;
27457     }
27458 
27459   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
27460      be template parameters.  */
27461   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
27462     return true;
27463 
27464   if (TREE_CODE (type) == DEPENDENT_OPERATOR_TYPE)
27465     return true;
27466 
27467   if (any_dependent_type_attributes_p (TYPE_ATTRIBUTES (type)))
27468     return true;
27469 
27470   /* The standard does not specifically mention types that are local
27471      to template functions or local classes, but they should be
27472      considered dependent too.  For example:
27473 
27474        template <int I> void f() {
27475 	 enum E { a = I };
27476 	 S<sizeof (E)> s;
27477        }
27478 
27479      The size of `E' cannot be known until the value of `I' has been
27480      determined.  Therefore, `E' must be considered dependent.  */
27481   scope = TYPE_CONTEXT (type);
27482   if (scope && TYPE_P (scope))
27483     return dependent_type_p (scope);
27484   /* Don't use type_dependent_expression_p here, as it can lead
27485      to infinite recursion trying to determine whether a lambda
27486      nested in a lambda is dependent (c++/47687).  */
27487   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
27488 	   && DECL_LANG_SPECIFIC (scope)
27489 	   && DECL_TEMPLATE_INFO (scope)
27490 	   && (any_dependent_template_arguments_p
27491 	       (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
27492     return true;
27493 
27494   /* Other types are non-dependent.  */
27495   return false;
27496 }
27497 
27498 /* Returns TRUE if TYPE is dependent, in the sense of
27499    [temp.dep.type].  Note that a NULL type is considered dependent.  */
27500 
27501 bool
dependent_type_p(tree type)27502 dependent_type_p (tree type)
27503 {
27504   /* If there are no template parameters in scope, then there can't be
27505      any dependent types.  */
27506   if (!processing_template_decl)
27507     {
27508       /* If we are not processing a template, then nobody should be
27509 	 providing us with a dependent type.  */
27510       gcc_assert (type);
27511       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
27512       return false;
27513     }
27514 
27515   /* If the type is NULL, we have not computed a type for the entity
27516      in question; in that case, the type is dependent.  */
27517   if (!type)
27518     return true;
27519 
27520   /* Erroneous types can be considered non-dependent.  */
27521   if (type == error_mark_node)
27522     return false;
27523 
27524   /* If we have not already computed the appropriate value for TYPE,
27525      do so now.  */
27526   if (!TYPE_DEPENDENT_P_VALID (type))
27527     {
27528       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
27529       TYPE_DEPENDENT_P_VALID (type) = 1;
27530     }
27531 
27532   return TYPE_DEPENDENT_P (type);
27533 }
27534 
27535 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
27536    lookup.  In other words, a dependent type that is not the current
27537    instantiation.  */
27538 
27539 bool
dependent_scope_p(tree scope)27540 dependent_scope_p (tree scope)
27541 {
27542   return (scope && TYPE_P (scope) && dependent_type_p (scope)
27543 	  && !currently_open_class (scope));
27544 }
27545 
27546 /* True if we might find more declarations in SCOPE during instantiation than
27547    we can when parsing the template.  */
27548 
27549 bool
dependentish_scope_p(tree scope)27550 dependentish_scope_p (tree scope)
27551 {
27552   return dependent_scope_p (scope) || any_dependent_bases_p (scope);
27553 }
27554 
27555 /* T is a SCOPE_REF.  Return whether it represents a non-static member of
27556    an unknown base of 'this' (and is therefore instantiation-dependent).  */
27557 
27558 static bool
unknown_base_ref_p(tree t)27559 unknown_base_ref_p (tree t)
27560 {
27561   if (!current_class_ptr)
27562     return false;
27563 
27564   tree mem = TREE_OPERAND (t, 1);
27565   if (shared_member_p (mem))
27566     return false;
27567 
27568   tree cur = current_nonlambda_class_type ();
27569   if (!any_dependent_bases_p (cur))
27570     return false;
27571 
27572   tree ctx = TREE_OPERAND (t, 0);
27573   if (DERIVED_FROM_P (ctx, cur))
27574     return false;
27575 
27576   return true;
27577 }
27578 
27579 /* T is a SCOPE_REF; return whether we need to consider it
27580     instantiation-dependent so that we can check access at instantiation
27581     time even though we know which member it resolves to.  */
27582 
27583 static bool
instantiation_dependent_scope_ref_p(tree t)27584 instantiation_dependent_scope_ref_p (tree t)
27585 {
27586   if (DECL_P (TREE_OPERAND (t, 1))
27587       && CLASS_TYPE_P (TREE_OPERAND (t, 0))
27588       && !dependent_scope_p (TREE_OPERAND (t, 0))
27589       && !unknown_base_ref_p (t)
27590       && accessible_in_template_p (TREE_OPERAND (t, 0),
27591 				   TREE_OPERAND (t, 1)))
27592     return false;
27593   else
27594     return true;
27595 }
27596 
27597 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
27598    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
27599    expression.  */
27600 
27601 /* Note that this predicate is not appropriate for general expressions;
27602    only constant expressions (that satisfy potential_constant_expression)
27603    can be tested for value dependence.  */
27604 
27605 bool
value_dependent_expression_p(tree expression)27606 value_dependent_expression_p (tree expression)
27607 {
27608   if (!processing_template_decl || expression == NULL_TREE)
27609     return false;
27610 
27611   /* A type-dependent expression is also value-dependent.  */
27612   if (type_dependent_expression_p (expression))
27613     return true;
27614 
27615   switch (TREE_CODE (expression))
27616     {
27617     case BASELINK:
27618       /* A dependent member function of the current instantiation.  */
27619       return dependent_type_p (BINFO_TYPE (BASELINK_BINFO (expression)));
27620 
27621     case FUNCTION_DECL:
27622       /* A dependent member function of the current instantiation.  */
27623       if (DECL_CLASS_SCOPE_P (expression)
27624 	  && dependent_type_p (DECL_CONTEXT (expression)))
27625 	return true;
27626       break;
27627 
27628     case IDENTIFIER_NODE:
27629       /* A name that has not been looked up -- must be dependent.  */
27630       return true;
27631 
27632     case TEMPLATE_PARM_INDEX:
27633       /* A non-type template parm.  */
27634       return true;
27635 
27636     case CONST_DECL:
27637       /* A non-type template parm.  */
27638       if (DECL_TEMPLATE_PARM_P (expression))
27639 	return true;
27640       return value_dependent_expression_p (DECL_INITIAL (expression));
27641 
27642     case VAR_DECL:
27643        /* A constant with literal type and is initialized
27644 	  with an expression that is value-dependent.  */
27645       if (DECL_DEPENDENT_INIT_P (expression))
27646 	return true;
27647       if (DECL_HAS_VALUE_EXPR_P (expression))
27648 	{
27649 	  tree value_expr = DECL_VALUE_EXPR (expression);
27650 	  if (value_dependent_expression_p (value_expr)
27651 	      /* __PRETTY_FUNCTION__ inside a template function is dependent
27652 		 on the name of the function.  */
27653 	      || (DECL_PRETTY_FUNCTION_P (expression)
27654 		  /* It might be used in a template, but not a template
27655 		     function, in which case its DECL_VALUE_EXPR will be
27656 		     "top level".  */
27657 		  && value_expr == error_mark_node))
27658 	    return true;
27659 	}
27660       else if (TYPE_REF_P (TREE_TYPE (expression)))
27661 	/* FIXME cp_finish_decl doesn't fold reference initializers.  */
27662 	return true;
27663       return false;
27664 
27665     case DYNAMIC_CAST_EXPR:
27666     case STATIC_CAST_EXPR:
27667     case CONST_CAST_EXPR:
27668     case REINTERPRET_CAST_EXPR:
27669     case CAST_EXPR:
27670     case IMPLICIT_CONV_EXPR:
27671       /* These expressions are value-dependent if the type to which
27672 	 the cast occurs is dependent or the expression being casted
27673 	 is value-dependent.  */
27674       {
27675 	tree type = TREE_TYPE (expression);
27676 
27677 	if (dependent_type_p (type))
27678 	  return true;
27679 
27680 	/* A functional cast has a list of operands.  */
27681 	expression = TREE_OPERAND (expression, 0);
27682 	if (!expression)
27683 	  {
27684 	    /* If there are no operands, it must be an expression such
27685 	       as "int()". This should not happen for aggregate types
27686 	       because it would form non-constant expressions.  */
27687 	    gcc_assert (cxx_dialect >= cxx11
27688 			|| INTEGRAL_OR_ENUMERATION_TYPE_P (type));
27689 
27690 	    return false;
27691 	  }
27692 
27693 	if (TREE_CODE (expression) == TREE_LIST)
27694 	  return any_value_dependent_elements_p (expression);
27695 
27696 	if (TREE_CODE (type) == REFERENCE_TYPE
27697 	    && has_value_dependent_address (expression))
27698 	  return true;
27699 
27700 	return value_dependent_expression_p (expression);
27701       }
27702 
27703     case SIZEOF_EXPR:
27704       if (SIZEOF_EXPR_TYPE_P (expression))
27705 	return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
27706       /* FALLTHRU */
27707     case ALIGNOF_EXPR:
27708     case TYPEID_EXPR:
27709       /* A `sizeof' expression is value-dependent if the operand is
27710 	 type-dependent or is a pack expansion.  */
27711       expression = TREE_OPERAND (expression, 0);
27712       if (PACK_EXPANSION_P (expression))
27713         return true;
27714       else if (TYPE_P (expression))
27715 	return dependent_type_p (expression);
27716       return instantiation_dependent_uneval_expression_p (expression);
27717 
27718     case AT_ENCODE_EXPR:
27719       /* An 'encode' expression is value-dependent if the operand is
27720 	 type-dependent.  */
27721       expression = TREE_OPERAND (expression, 0);
27722       return dependent_type_p (expression);
27723 
27724     case NOEXCEPT_EXPR:
27725       expression = TREE_OPERAND (expression, 0);
27726       return instantiation_dependent_uneval_expression_p (expression);
27727 
27728     case SCOPE_REF:
27729       /* All instantiation-dependent expressions should also be considered
27730 	 value-dependent.  */
27731       return instantiation_dependent_scope_ref_p (expression);
27732 
27733     case COMPONENT_REF:
27734       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
27735 	      || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
27736 
27737     case NONTYPE_ARGUMENT_PACK:
27738       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
27739          is value-dependent.  */
27740       {
27741         tree values = ARGUMENT_PACK_ARGS (expression);
27742         int i, len = TREE_VEC_LENGTH (values);
27743 
27744         for (i = 0; i < len; ++i)
27745           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
27746             return true;
27747 
27748         return false;
27749       }
27750 
27751     case TRAIT_EXPR:
27752       {
27753 	tree type2 = TRAIT_EXPR_TYPE2 (expression);
27754 
27755 	if (dependent_type_p (TRAIT_EXPR_TYPE1 (expression)))
27756 	  return true;
27757 
27758 	if (!type2)
27759 	  return false;
27760 
27761 	if (TREE_CODE (type2) != TREE_LIST)
27762 	  return dependent_type_p (type2);
27763 
27764 	for (; type2; type2 = TREE_CHAIN (type2))
27765 	  if (dependent_type_p (TREE_VALUE (type2)))
27766 	    return true;
27767 
27768 	return false;
27769       }
27770 
27771     case MODOP_EXPR:
27772       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
27773 	      || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
27774 
27775     case ARRAY_REF:
27776       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
27777 	      || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
27778 
27779     case ADDR_EXPR:
27780       {
27781 	tree op = TREE_OPERAND (expression, 0);
27782 	return (value_dependent_expression_p (op)
27783 		|| has_value_dependent_address (op));
27784       }
27785 
27786     case REQUIRES_EXPR:
27787       /* Treat all requires-expressions as value-dependent so
27788          we don't try to fold them.  */
27789       return true;
27790 
27791     case TYPE_REQ:
27792       return dependent_type_p (TREE_OPERAND (expression, 0));
27793 
27794     case CALL_EXPR:
27795       {
27796 	if (value_dependent_expression_p (CALL_EXPR_FN (expression)))
27797 	  return true;
27798 	tree fn = get_callee_fndecl (expression);
27799 	int i, nargs;
27800 	nargs = call_expr_nargs (expression);
27801 	for (i = 0; i < nargs; ++i)
27802 	  {
27803 	    tree op = CALL_EXPR_ARG (expression, i);
27804 	    /* In a call to a constexpr member function, look through the
27805 	       implicit ADDR_EXPR on the object argument so that it doesn't
27806 	       cause the call to be considered value-dependent.  We also
27807 	       look through it in potential_constant_expression.  */
27808 	    if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
27809 		&& DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
27810 		&& TREE_CODE (op) == ADDR_EXPR)
27811 	      op = TREE_OPERAND (op, 0);
27812 	    if (value_dependent_expression_p (op))
27813 	      return true;
27814 	  }
27815 	return false;
27816       }
27817 
27818     case TEMPLATE_ID_EXPR:
27819       return concept_definition_p (TREE_OPERAND (expression, 0))
27820 	&& any_dependent_template_arguments_p (TREE_OPERAND (expression, 1));
27821 
27822     case CONSTRUCTOR:
27823       {
27824 	unsigned ix;
27825 	tree val;
27826 	if (dependent_type_p (TREE_TYPE (expression)))
27827 	  return true;
27828 	FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
27829 	  if (value_dependent_expression_p (val))
27830 	    return true;
27831 	return false;
27832       }
27833 
27834     case STMT_EXPR:
27835       /* Treat a GNU statement expression as dependent to avoid crashing
27836 	 under instantiate_non_dependent_expr; it can't be constant.  */
27837       return true;
27838 
27839     default:
27840       /* A constant expression is value-dependent if any subexpression is
27841 	 value-dependent.  */
27842       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
27843 	{
27844 	case tcc_reference:
27845 	case tcc_unary:
27846 	case tcc_comparison:
27847 	case tcc_binary:
27848 	case tcc_expression:
27849 	case tcc_vl_exp:
27850 	  {
27851 	    int i, len = cp_tree_operand_length (expression);
27852 
27853 	    for (i = 0; i < len; i++)
27854 	      {
27855 		tree t = TREE_OPERAND (expression, i);
27856 
27857 		/* In some cases, some of the operands may be missing.
27858 		   (For example, in the case of PREDECREMENT_EXPR, the
27859 		   amount to increment by may be missing.)  That doesn't
27860 		   make the expression dependent.  */
27861 		if (t && value_dependent_expression_p (t))
27862 		  return true;
27863 	      }
27864 	  }
27865 	  break;
27866 	default:
27867 	  break;
27868 	}
27869       break;
27870     }
27871 
27872   /* The expression is not value-dependent.  */
27873   return false;
27874 }
27875 
27876 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
27877    [temp.dep.expr].  Note that an expression with no type is
27878    considered dependent.  Other parts of the compiler arrange for an
27879    expression with type-dependent subexpressions to have no type, so
27880    this function doesn't have to be fully recursive.  */
27881 
27882 bool
type_dependent_expression_p(tree expression)27883 type_dependent_expression_p (tree expression)
27884 {
27885   if (!processing_template_decl)
27886     return false;
27887 
27888   if (expression == NULL_TREE || expression == error_mark_node)
27889     return false;
27890 
27891   STRIP_ANY_LOCATION_WRAPPER (expression);
27892 
27893   /* An unresolved name is always dependent.  */
27894   if (identifier_p (expression)
27895       || TREE_CODE (expression) == USING_DECL
27896       || TREE_CODE (expression) == WILDCARD_DECL)
27897     return true;
27898 
27899   /* A lambda-expression in template context is dependent.  dependent_type_p is
27900      true for a lambda in the scope of a class or function template, but that
27901      doesn't cover all template contexts, like a default template argument.  */
27902   if (TREE_CODE (expression) == LAMBDA_EXPR)
27903     return true;
27904 
27905   /* A fold expression is type-dependent. */
27906   if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
27907       || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
27908       || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
27909       || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
27910     return true;
27911 
27912   /* Some expression forms are never type-dependent.  */
27913   if (TREE_CODE (expression) == SIZEOF_EXPR
27914       || TREE_CODE (expression) == ALIGNOF_EXPR
27915       || TREE_CODE (expression) == AT_ENCODE_EXPR
27916       || TREE_CODE (expression) == NOEXCEPT_EXPR
27917       || TREE_CODE (expression) == TRAIT_EXPR
27918       || TREE_CODE (expression) == TYPEID_EXPR
27919       || TREE_CODE (expression) == DELETE_EXPR
27920       || TREE_CODE (expression) == VEC_DELETE_EXPR
27921       || TREE_CODE (expression) == THROW_EXPR
27922       || TREE_CODE (expression) == REQUIRES_EXPR)
27923     return false;
27924 
27925   /* The types of these expressions depends only on the type to which
27926      the cast occurs.  */
27927   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
27928       || TREE_CODE (expression) == STATIC_CAST_EXPR
27929       || TREE_CODE (expression) == CONST_CAST_EXPR
27930       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
27931       || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
27932       || TREE_CODE (expression) == CAST_EXPR)
27933     return dependent_type_p (TREE_TYPE (expression));
27934 
27935   /* The types of these expressions depends only on the type created
27936      by the expression.  */
27937   if (TREE_CODE (expression) == NEW_EXPR
27938       || TREE_CODE (expression) == VEC_NEW_EXPR)
27939     {
27940       /* For NEW_EXPR tree nodes created inside a template, either
27941 	 the object type itself or a TREE_LIST may appear as the
27942 	 operand 1.  */
27943       tree type = TREE_OPERAND (expression, 1);
27944       if (TREE_CODE (type) == TREE_LIST)
27945 	/* This is an array type.  We need to check array dimensions
27946 	   as well.  */
27947 	return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
27948 	       || value_dependent_expression_p
27949 		    (TREE_OPERAND (TREE_VALUE (type), 1));
27950       /* Array type whose dimension has to be deduced.  */
27951       else if (TREE_CODE (type) == ARRAY_TYPE
27952 	       && TREE_OPERAND (expression, 2) == NULL_TREE)
27953 	return true;
27954       else
27955 	return dependent_type_p (type);
27956     }
27957 
27958   if (TREE_CODE (expression) == SCOPE_REF)
27959     {
27960       tree scope = TREE_OPERAND (expression, 0);
27961       tree name = TREE_OPERAND (expression, 1);
27962 
27963       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
27964 	 contains an identifier associated by name lookup with one or more
27965 	 declarations declared with a dependent type, or...a
27966 	 nested-name-specifier or qualified-id that names a member of an
27967 	 unknown specialization.  */
27968       return (type_dependent_expression_p (name)
27969 	      || dependent_scope_p (scope));
27970     }
27971 
27972   if (TREE_CODE (expression) == TEMPLATE_DECL
27973       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
27974     return uses_outer_template_parms (expression);
27975 
27976   if (TREE_CODE (expression) == STMT_EXPR)
27977     expression = stmt_expr_value_expr (expression);
27978 
27979   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
27980     {
27981       for (auto &elt : CONSTRUCTOR_ELTS (expression))
27982 	if (type_dependent_expression_p (elt.value))
27983 	  return true;
27984       return false;
27985     }
27986 
27987   /* A static data member of the current instantiation with incomplete
27988      array type is type-dependent, as the definition and specializations
27989      can have different bounds.  */
27990   if (VAR_P (expression)
27991       && DECL_CLASS_SCOPE_P (expression)
27992       && dependent_type_p (DECL_CONTEXT (expression))
27993       && VAR_HAD_UNKNOWN_BOUND (expression))
27994     return true;
27995 
27996   /* An array of unknown bound depending on a variadic parameter, eg:
27997 
27998      template<typename... Args>
27999        void foo (Args... args)
28000        {
28001          int arr[] = { args... };
28002        }
28003 
28004      template<int... vals>
28005        void bar ()
28006        {
28007          int arr[] = { vals... };
28008        }
28009 
28010      If the array has no length and has an initializer, it must be that
28011      we couldn't determine its length in cp_complete_array_type because
28012      it is dependent.  */
28013   if (((VAR_P (expression) && DECL_INITIAL (expression))
28014        || COMPOUND_LITERAL_P (expression))
28015       && TREE_TYPE (expression) != NULL_TREE
28016       && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
28017       && !TYPE_DOMAIN (TREE_TYPE (expression)))
28018    return true;
28019 
28020   /* Pull a FUNCTION_DECL out of a BASELINK if we can.  */
28021   if (BASELINK_P (expression))
28022     {
28023       if (BASELINK_OPTYPE (expression)
28024 	  && dependent_type_p (BASELINK_OPTYPE (expression)))
28025 	return true;
28026       expression = BASELINK_FUNCTIONS (expression);
28027     }
28028 
28029   /* A function or variable template-id is type-dependent if it has any
28030      dependent template arguments.  */
28031   if (VAR_OR_FUNCTION_DECL_P (expression)
28032       && DECL_LANG_SPECIFIC (expression)
28033       && DECL_TEMPLATE_INFO (expression))
28034     {
28035       /* Consider the innermost template arguments, since those are the ones
28036 	 that come from the template-id; the template arguments for the
28037 	 enclosing class do not make it type-dependent unless they are used in
28038 	 the type of the decl.  */
28039       if (instantiates_primary_template_p (expression)
28040 	  && (any_dependent_template_arguments_p
28041 	      (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
28042 	return true;
28043     }
28044 
28045   /* Otherwise, if the function decl isn't from a dependent scope, it can't be
28046      type-dependent.  Checking this is important for functions with auto return
28047      type, which looks like a dependent type.  */
28048   if (TREE_CODE (expression) == FUNCTION_DECL
28049       && !(DECL_CLASS_SCOPE_P (expression)
28050 	   && dependent_type_p (DECL_CONTEXT (expression)))
28051       && !(DECL_LANG_SPECIFIC (expression)
28052 	   && DECL_UNIQUE_FRIEND_P (expression)
28053 	   && (!DECL_FRIEND_CONTEXT (expression)
28054 	       || dependent_type_p (DECL_FRIEND_CONTEXT (expression))))
28055       && !DECL_LOCAL_DECL_P (expression))
28056     {
28057       gcc_assert (!dependent_type_p (TREE_TYPE (expression))
28058 		  || undeduced_auto_decl (expression));
28059       return false;
28060     }
28061 
28062   /* Otherwise, its constraints could still depend on outer template parameters
28063      from its (dependent) scope.  */
28064   if (TREE_CODE (expression) == FUNCTION_DECL
28065       /* As an optimization, check this cheaper sufficient condition first.
28066 	 (At this point we've established that we're looking at a member of
28067 	 a dependent class, so it makes sense to start treating say undeduced
28068 	 auto as dependent.)  */
28069       && !dependent_type_p (TREE_TYPE (expression))
28070       && uses_outer_template_parms_in_constraints (expression))
28071     return true;
28072 
28073   /* Always dependent, on the number of arguments if nothing else.  */
28074   if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
28075     return true;
28076 
28077   if (TREE_TYPE (expression) == unknown_type_node)
28078     {
28079       if (TREE_CODE (expression) == ADDR_EXPR)
28080 	return type_dependent_expression_p (TREE_OPERAND (expression, 0));
28081       if (TREE_CODE (expression) == COMPONENT_REF
28082 	  || TREE_CODE (expression) == OFFSET_REF)
28083 	{
28084 	  if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
28085 	    return true;
28086 	  expression = TREE_OPERAND (expression, 1);
28087 	  if (identifier_p (expression))
28088 	    return false;
28089 	}
28090       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
28091       if (TREE_CODE (expression) == SCOPE_REF)
28092 	return false;
28093 
28094       /* CO_AWAIT/YIELD_EXPR with unknown type is always dependent.  */
28095       if (TREE_CODE (expression) == CO_AWAIT_EXPR
28096 	  || TREE_CODE (expression) == CO_YIELD_EXPR)
28097 	return true;
28098 
28099       if (BASELINK_P (expression))
28100 	{
28101 	  if (BASELINK_OPTYPE (expression)
28102 	      && dependent_type_p (BASELINK_OPTYPE (expression)))
28103 	    return true;
28104 	  expression = BASELINK_FUNCTIONS (expression);
28105 	}
28106 
28107       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
28108 	{
28109 	  if (any_dependent_template_arguments_p
28110 	      (TREE_OPERAND (expression, 1)))
28111 	    return true;
28112 	  expression = TREE_OPERAND (expression, 0);
28113 	  if (identifier_p (expression))
28114 	    return true;
28115 	}
28116 
28117       gcc_assert (OVL_P (expression));
28118 
28119       for (lkp_iterator iter (expression); iter; ++iter)
28120 	if (type_dependent_expression_p (*iter))
28121 	  return true;
28122 
28123       return false;
28124     }
28125 
28126   /* The type of a non-type template parm declared with a placeholder type
28127      depends on the corresponding template argument, even though
28128      placeholders are not normally considered dependent.  */
28129   if (TREE_CODE (expression) == TEMPLATE_PARM_INDEX
28130       && is_auto (TREE_TYPE (expression)))
28131     return true;
28132 
28133   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
28134 
28135   /* Dependent type attributes might not have made it from the decl to
28136      the type yet.  */
28137   if (DECL_P (expression)
28138       && any_dependent_type_attributes_p (DECL_ATTRIBUTES (expression)))
28139     return true;
28140 
28141   return (dependent_type_p (TREE_TYPE (expression)));
28142 }
28143 
28144 /* [temp.dep.expr]/5: A class member access expression (5.2.5) is
28145    type-dependent if the expression refers to a member of the current
28146    instantiation and the type of the referenced member is dependent, or the
28147    class member access expression refers to a member of an unknown
28148    specialization.
28149 
28150    This function returns true if the OBJECT in such a class member access
28151    expression is of an unknown specialization.  */
28152 
28153 bool
type_dependent_object_expression_p(tree object)28154 type_dependent_object_expression_p (tree object)
28155 {
28156   /* An IDENTIFIER_NODE can sometimes have a TREE_TYPE, but it's still
28157      dependent.  */
28158   if (TREE_CODE (object) == IDENTIFIER_NODE)
28159     return true;
28160   tree scope = TREE_TYPE (object);
28161   return (!scope || dependent_scope_p (scope));
28162 }
28163 
28164 /* walk_tree callback function for instantiation_dependent_expression_p,
28165    below.  Returns non-zero if a dependent subexpression is found.  */
28166 
28167 static tree
instantiation_dependent_r(tree * tp,int * walk_subtrees,void *)28168 instantiation_dependent_r (tree *tp, int *walk_subtrees,
28169 			   void * /*data*/)
28170 {
28171   if (TYPE_P (*tp))
28172     {
28173       /* We don't have to worry about decltype currently because decltype
28174 	 of an instantiation-dependent expr is a dependent type.  This
28175 	 might change depending on the resolution of DR 1172.  */
28176       *walk_subtrees = false;
28177       return NULL_TREE;
28178     }
28179   enum tree_code code = TREE_CODE (*tp);
28180   switch (code)
28181     {
28182       /* Don't treat an argument list as dependent just because it has no
28183 	 TREE_TYPE.  */
28184     case TREE_LIST:
28185     case TREE_VEC:
28186     case NONTYPE_ARGUMENT_PACK:
28187       return NULL_TREE;
28188 
28189     case TEMPLATE_PARM_INDEX:
28190       if (dependent_type_p (TREE_TYPE (*tp)))
28191 	return *tp;
28192       if (TEMPLATE_PARM_PARAMETER_PACK (*tp))
28193 	return *tp;
28194       /* We'll check value-dependence separately.  */
28195       return NULL_TREE;
28196 
28197       /* Handle expressions with type operands.  */
28198     case SIZEOF_EXPR:
28199     case ALIGNOF_EXPR:
28200     case TYPEID_EXPR:
28201     case AT_ENCODE_EXPR:
28202       {
28203 	tree op = TREE_OPERAND (*tp, 0);
28204 	if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
28205 	  op = TREE_TYPE (op);
28206 	if (TYPE_P (op))
28207 	  {
28208 	    if (dependent_type_p (op))
28209 	      return *tp;
28210 	    else
28211 	      {
28212 		*walk_subtrees = false;
28213 		return NULL_TREE;
28214 	      }
28215 	  }
28216 	break;
28217       }
28218 
28219     case COMPONENT_REF:
28220       if (identifier_p (TREE_OPERAND (*tp, 1)))
28221 	/* In a template, finish_class_member_access_expr creates a
28222 	   COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
28223 	   type-dependent, so that we can check access control at
28224 	   instantiation time (PR 42277).  See also Core issue 1273.  */
28225 	return *tp;
28226       break;
28227 
28228     case SCOPE_REF:
28229       if (instantiation_dependent_scope_ref_p (*tp))
28230 	return *tp;
28231       else
28232 	break;
28233 
28234       /* Treat statement-expressions as dependent.  */
28235     case BIND_EXPR:
28236       return *tp;
28237 
28238       /* Treat requires-expressions as dependent. */
28239     case REQUIRES_EXPR:
28240       return *tp;
28241 
28242     case CONSTRUCTOR:
28243       if (CONSTRUCTOR_IS_DEPENDENT (*tp))
28244 	return *tp;
28245       break;
28246 
28247     case TEMPLATE_DECL:
28248     case FUNCTION_DECL:
28249       /* Before C++17, a noexcept-specifier isn't part of the function type
28250 	 so it doesn't affect type dependence, but we still want to consider it
28251 	 for instantiation dependence.  */
28252       if (cxx_dialect < cxx17
28253 	  && DECL_DECLARES_FUNCTION_P (*tp)
28254 	  && value_dependent_noexcept_spec_p (TREE_TYPE (*tp)))
28255 	return *tp;
28256       break;
28257 
28258     default:
28259       break;
28260     }
28261 
28262   if (type_dependent_expression_p (*tp))
28263     return *tp;
28264   else
28265     return NULL_TREE;
28266 }
28267 
28268 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
28269    sense defined by the ABI:
28270 
28271    "An expression is instantiation-dependent if it is type-dependent
28272    or value-dependent, or it has a subexpression that is type-dependent
28273    or value-dependent."
28274 
28275    Except don't actually check value-dependence for unevaluated expressions,
28276    because in sizeof(i) we don't care about the value of i.  Checking
28277    type-dependence will in turn check value-dependence of array bounds/template
28278    arguments as needed.  */
28279 
28280 bool
instantiation_dependent_uneval_expression_p(tree expression)28281 instantiation_dependent_uneval_expression_p (tree expression)
28282 {
28283   tree result;
28284 
28285   if (!processing_template_decl)
28286     return false;
28287 
28288   if (expression == error_mark_node)
28289     return false;
28290 
28291   result = cp_walk_tree_without_duplicates (&expression,
28292 					    instantiation_dependent_r, NULL);
28293   return result != NULL_TREE;
28294 }
28295 
28296 /* As above, but also check value-dependence of the expression as a whole.  */
28297 
28298 bool
instantiation_dependent_expression_p(tree expression)28299 instantiation_dependent_expression_p (tree expression)
28300 {
28301   return (instantiation_dependent_uneval_expression_p (expression)
28302 	  || (processing_template_decl
28303 	      && potential_constant_expression (expression)
28304 	      && value_dependent_expression_p (expression)));
28305 }
28306 
28307 /* Like type_dependent_expression_p, but it also works while not processing
28308    a template definition, i.e. during substitution or mangling.  */
28309 
28310 bool
type_dependent_expression_p_push(tree expr)28311 type_dependent_expression_p_push (tree expr)
28312 {
28313   bool b;
28314   ++processing_template_decl;
28315   b = type_dependent_expression_p (expr);
28316   --processing_template_decl;
28317   return b;
28318 }
28319 
28320 /* Returns TRUE if ARGS contains a type-dependent expression.  */
28321 
28322 bool
any_type_dependent_arguments_p(const vec<tree,va_gc> * args)28323 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
28324 {
28325   unsigned int i;
28326   tree arg;
28327 
28328   FOR_EACH_VEC_SAFE_ELT (args, i, arg)
28329     {
28330       if (type_dependent_expression_p (arg))
28331 	return true;
28332     }
28333   return false;
28334 }
28335 
28336 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
28337    expressions) contains any type-dependent expressions.  */
28338 
28339 bool
any_type_dependent_elements_p(const_tree list)28340 any_type_dependent_elements_p (const_tree list)
28341 {
28342   for (; list; list = TREE_CHAIN (list))
28343     if (type_dependent_expression_p (TREE_VALUE (list)))
28344       return true;
28345 
28346   return false;
28347 }
28348 
28349 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
28350    expressions) contains any value-dependent expressions.  */
28351 
28352 bool
any_value_dependent_elements_p(const_tree list)28353 any_value_dependent_elements_p (const_tree list)
28354 {
28355   for (; list; list = TREE_CHAIN (list))
28356     if (value_dependent_expression_p (TREE_VALUE (list)))
28357       return true;
28358 
28359   return false;
28360 }
28361 
28362 /* Returns TRUE if the ARG (a template argument) is dependent.  */
28363 
28364 bool
dependent_template_arg_p(tree arg)28365 dependent_template_arg_p (tree arg)
28366 {
28367   if (!processing_template_decl)
28368     return false;
28369 
28370   /* Assume a template argument that was wrongly written by the user
28371      is dependent. This is consistent with what
28372      any_dependent_template_arguments_p [that calls this function]
28373      does.  */
28374   if (!arg || arg == error_mark_node)
28375     return true;
28376 
28377   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
28378     arg = argument_pack_select_arg (arg);
28379 
28380   if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
28381     return true;
28382   if (TREE_CODE (arg) == TEMPLATE_DECL)
28383     {
28384       if (DECL_TEMPLATE_PARM_P (arg))
28385 	return true;
28386       /* A member template of a dependent class is not necessarily
28387 	 type-dependent, but it is a dependent template argument because it
28388 	 will be a member of an unknown specialization to that template.  */
28389       tree scope = CP_DECL_CONTEXT (arg);
28390       return TYPE_P (scope) && dependent_type_p (scope);
28391     }
28392   else if (ARGUMENT_PACK_P (arg))
28393     {
28394       tree args = ARGUMENT_PACK_ARGS (arg);
28395       int i, len = TREE_VEC_LENGTH (args);
28396       for (i = 0; i < len; ++i)
28397         {
28398           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
28399             return true;
28400         }
28401 
28402       return false;
28403     }
28404   else if (TYPE_P (arg))
28405     return dependent_type_p (arg);
28406   else
28407     return value_dependent_expression_p (arg);
28408 }
28409 
28410 /* Identify any expressions that use function parms.  */
28411 
28412 static tree
find_parm_usage_r(tree * tp,int * walk_subtrees,void *)28413 find_parm_usage_r (tree *tp, int *walk_subtrees, void*)
28414 {
28415   tree t = *tp;
28416   if (TREE_CODE (t) == PARM_DECL)
28417     {
28418       *walk_subtrees = 0;
28419       return t;
28420     }
28421   return NULL_TREE;
28422 }
28423 
28424 /* Returns true if ARGS (a collection of template arguments) contains
28425    any types that require structural equality testing.  */
28426 
28427 bool
any_template_arguments_need_structural_equality_p(tree args)28428 any_template_arguments_need_structural_equality_p (tree args)
28429 {
28430   int i;
28431   int j;
28432 
28433   if (!args)
28434     return false;
28435   if (args == error_mark_node)
28436     return true;
28437 
28438   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
28439     {
28440       tree level = TMPL_ARGS_LEVEL (args, i + 1);
28441       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
28442 	{
28443 	  tree arg = TREE_VEC_ELT (level, j);
28444 	  tree packed_args = NULL_TREE;
28445 	  int k, len = 1;
28446 
28447 	  if (ARGUMENT_PACK_P (arg))
28448 	    {
28449 	      /* Look inside the argument pack.  */
28450 	      packed_args = ARGUMENT_PACK_ARGS (arg);
28451 	      len = TREE_VEC_LENGTH (packed_args);
28452 	    }
28453 
28454 	  for (k = 0; k < len; ++k)
28455 	    {
28456 	      if (packed_args)
28457 		arg = TREE_VEC_ELT (packed_args, k);
28458 
28459 	      if (error_operand_p (arg))
28460 		return true;
28461 	      else if (TREE_CODE (arg) == TEMPLATE_DECL)
28462 		continue;
28463 	      else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
28464 		return true;
28465 	      else if (!TYPE_P (arg) && TREE_TYPE (arg)
28466 		       && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
28467 		return true;
28468 	      /* Checking current_function_decl because this structural
28469 		 comparison is only necessary for redeclaration.  */
28470 	      else if (!current_function_decl
28471 		       && dependent_template_arg_p (arg)
28472 		       && (cp_walk_tree_without_duplicates
28473 			   (&arg, find_parm_usage_r, NULL)))
28474 		return true;
28475 	    }
28476 	}
28477     }
28478 
28479   return false;
28480 }
28481 
28482 /* Returns true if ARGS (a collection of template arguments) contains
28483    any dependent arguments.  */
28484 
28485 bool
any_dependent_template_arguments_p(const_tree args)28486 any_dependent_template_arguments_p (const_tree args)
28487 {
28488   int i;
28489   int j;
28490 
28491   if (!args)
28492     return false;
28493   if (args == error_mark_node)
28494     return true;
28495 
28496   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
28497     {
28498       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
28499       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
28500 	if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
28501 	  return true;
28502     }
28503 
28504   return false;
28505 }
28506 
28507 /* Returns true if ARGS contains any errors.  */
28508 
28509 bool
any_erroneous_template_args_p(const_tree args)28510 any_erroneous_template_args_p (const_tree args)
28511 {
28512   int i;
28513   int j;
28514 
28515   if (args == error_mark_node)
28516     return true;
28517 
28518   if (args && TREE_CODE (args) != TREE_VEC)
28519     {
28520       if (tree ti = get_template_info (args))
28521 	args = TI_ARGS (ti);
28522       else
28523 	args = NULL_TREE;
28524     }
28525 
28526   if (!args)
28527     return false;
28528 
28529   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
28530     {
28531       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
28532       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
28533 	if (error_operand_p (TREE_VEC_ELT (level, j)))
28534 	  return true;
28535     }
28536 
28537   return false;
28538 }
28539 
28540 /* Returns TRUE if the template TMPL is type-dependent.  */
28541 
28542 bool
dependent_template_p(tree tmpl)28543 dependent_template_p (tree tmpl)
28544 {
28545   if (TREE_CODE (tmpl) == OVERLOAD)
28546     {
28547       for (lkp_iterator iter (tmpl); iter; ++iter)
28548 	if (dependent_template_p (*iter))
28549 	  return true;
28550       return false;
28551     }
28552 
28553   /* Template template parameters are dependent.  */
28554   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
28555       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
28556     return true;
28557   /* So are names that have not been looked up.  */
28558   if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
28559     return true;
28560   return false;
28561 }
28562 
28563 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
28564 
28565 bool
dependent_template_id_p(tree tmpl,tree args)28566 dependent_template_id_p (tree tmpl, tree args)
28567 {
28568   return (dependent_template_p (tmpl)
28569 	  || any_dependent_template_arguments_p (args));
28570 }
28571 
28572 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
28573    are dependent.  */
28574 
28575 bool
dependent_omp_for_p(tree declv,tree initv,tree condv,tree incrv)28576 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
28577 {
28578   int i;
28579 
28580   if (!processing_template_decl)
28581     return false;
28582 
28583   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
28584     {
28585       tree decl = TREE_VEC_ELT (declv, i);
28586       tree init = TREE_VEC_ELT (initv, i);
28587       tree cond = TREE_VEC_ELT (condv, i);
28588       tree incr = TREE_VEC_ELT (incrv, i);
28589 
28590       if (type_dependent_expression_p (decl)
28591 	  || TREE_CODE (decl) == SCOPE_REF)
28592 	return true;
28593 
28594       if (init && type_dependent_expression_p (init))
28595 	return true;
28596 
28597       if (cond == global_namespace)
28598 	return true;
28599 
28600       if (type_dependent_expression_p (cond))
28601 	return true;
28602 
28603       if (COMPARISON_CLASS_P (cond)
28604 	  && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
28605 	      || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
28606 	return true;
28607 
28608       if (TREE_CODE (incr) == MODOP_EXPR)
28609 	{
28610 	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
28611 	      || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
28612 	    return true;
28613 	}
28614       else if (type_dependent_expression_p (incr))
28615 	return true;
28616       else if (TREE_CODE (incr) == MODIFY_EXPR)
28617 	{
28618 	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
28619 	    return true;
28620 	  else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
28621 	    {
28622 	      tree t = TREE_OPERAND (incr, 1);
28623 	      if (type_dependent_expression_p (TREE_OPERAND (t, 0))
28624 		  || type_dependent_expression_p (TREE_OPERAND (t, 1)))
28625 		return true;
28626 
28627 	      /* If this loop has a class iterator with != comparison
28628 		 with increment other than i++/++i/i--/--i, make sure the
28629 		 increment is constant.  */
28630 	      if (CLASS_TYPE_P (TREE_TYPE (decl))
28631 		  && TREE_CODE (cond) == NE_EXPR)
28632 		{
28633 		  if (TREE_OPERAND (t, 0) == decl)
28634 		    t = TREE_OPERAND (t, 1);
28635 		  else
28636 		    t = TREE_OPERAND (t, 0);
28637 		  if (TREE_CODE (t) != INTEGER_CST)
28638 		    return true;
28639 		}
28640 	    }
28641 	}
28642     }
28643 
28644   return false;
28645 }
28646 
28647 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
28648    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
28649    no such TYPE can be found.  Note that this function peers inside
28650    uninstantiated templates and therefore should be used only in
28651    extremely limited situations.  ONLY_CURRENT_P restricts this
28652    peering to the currently open classes hierarchy (which is required
28653    when comparing types).  */
28654 
28655 tree
resolve_typename_type(tree type,bool only_current_p)28656 resolve_typename_type (tree type, bool only_current_p)
28657 {
28658   tree scope;
28659   tree name;
28660   tree decl;
28661   int quals;
28662   tree pushed_scope;
28663   tree result;
28664 
28665   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
28666 
28667   scope = TYPE_CONTEXT (type);
28668   /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope.  */
28669   gcc_checking_assert (uses_template_parms (scope));
28670 
28671   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
28672      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of a
28673      TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL
28674      representing the typedef. In that case TYPE_IDENTIFIER (type) is
28675      not the non-qualified identifier of the TYPENAME_TYPE anymore.
28676      So by getting the TYPE_IDENTIFIER of the _main declaration_ of
28677      the TYPENAME_TYPE instead, we avoid messing up with a possible
28678      typedef variant case.  */
28679   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
28680 
28681   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
28682      it first before we can figure out what NAME refers to.  */
28683   if (TREE_CODE (scope) == TYPENAME_TYPE)
28684     {
28685       if (TYPENAME_IS_RESOLVING_P (scope))
28686 	/* Given a class template A with a dependent base with nested type C,
28687 	   typedef typename A::C::C C will land us here, as trying to resolve
28688 	   the initial A::C leads to the local C typedef, which leads back to
28689 	   A::C::C.  So we break the recursion now.  */
28690 	return type;
28691       else
28692 	scope = resolve_typename_type (scope, only_current_p);
28693     }
28694   /* If we don't know what SCOPE refers to, then we cannot resolve the
28695      TYPENAME_TYPE.  */
28696   if (!CLASS_TYPE_P (scope))
28697     return type;
28698   /* If this is a typedef, we don't want to look inside (c++/11987).  */
28699   if (typedef_variant_p (type))
28700     return type;
28701   /* If SCOPE isn't the template itself, it will not have a valid
28702      TYPE_FIELDS list.  */
28703   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
28704     /* scope is either the template itself or a compatible instantiation
28705        like X<T>, so look up the name in the original template.  */
28706     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
28707   /* If scope has no fields, it can't be a current instantiation.  Check this
28708      before currently_open_class to avoid infinite recursion (71515).  */
28709   if (!TYPE_FIELDS (scope))
28710     return type;
28711   /* If the SCOPE is not the current instantiation, there's no reason
28712      to look inside it.  */
28713   if (only_current_p && !currently_open_class (scope))
28714     return type;
28715   /* Enter the SCOPE so that name lookup will be resolved as if we
28716      were in the class definition.  In particular, SCOPE will no
28717      longer be considered a dependent type.  */
28718   pushed_scope = push_scope (scope);
28719   /* Look up the declaration.  */
28720   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
28721 			tf_warning_or_error);
28722 
28723   result = NULL_TREE;
28724 
28725   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
28726      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
28727   tree fullname = TYPENAME_TYPE_FULLNAME (type);
28728   if (!decl)
28729     /*nop*/;
28730   else if (identifier_p (fullname)
28731 	   && TREE_CODE (decl) == TYPE_DECL)
28732     {
28733       result = TREE_TYPE (decl);
28734       if (result == error_mark_node)
28735 	result = NULL_TREE;
28736     }
28737   else if (TREE_CODE (fullname) == TEMPLATE_ID_EXPR
28738 	   && DECL_CLASS_TEMPLATE_P (decl))
28739     {
28740       /* Obtain the template and the arguments.  */
28741       tree tmpl = TREE_OPERAND (fullname, 0);
28742       if (TREE_CODE (tmpl) == IDENTIFIER_NODE)
28743 	{
28744 	  /* We get here with a plain identifier because a previous tentative
28745 	     parse of the nested-name-specifier as part of a ptr-operator saw
28746 	     ::template X<A>.  The use of ::template is necessary in a
28747 	     ptr-operator, but wrong in a declarator-id.
28748 
28749 	     [temp.names]: In a qualified-id of a declarator-id, the keyword
28750 	     template shall not appear at the top level.  */
28751 	  pedwarn (cp_expr_loc_or_input_loc (fullname), OPT_Wpedantic,
28752 		   "keyword %<template%> not allowed in declarator-id");
28753 	  tmpl = decl;
28754 	}
28755       tree args = TREE_OPERAND (fullname, 1);
28756       /* Instantiate the template.  */
28757       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
28758 				      /*entering_scope=*/true,
28759 				      tf_error | tf_user);
28760       if (result == error_mark_node)
28761 	result = NULL_TREE;
28762     }
28763 
28764   /* Leave the SCOPE.  */
28765   if (pushed_scope)
28766     pop_scope (pushed_scope);
28767 
28768   /* If we failed to resolve it, return the original typename.  */
28769   if (!result)
28770     return type;
28771 
28772   /* If lookup found a typename type, resolve that too.  */
28773   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
28774     {
28775       /* Ill-formed programs can cause infinite recursion here, so we
28776 	 must catch that.  */
28777       TYPENAME_IS_RESOLVING_P (result) = 1;
28778       result = resolve_typename_type (result, only_current_p);
28779       TYPENAME_IS_RESOLVING_P (result) = 0;
28780     }
28781 
28782   /* Qualify the resulting type.  */
28783   quals = cp_type_quals (type);
28784   if (quals)
28785     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
28786 
28787   return result;
28788 }
28789 
28790 /* EXPR is an expression which is not type-dependent.  Return a proxy
28791    for EXPR that can be used to compute the types of larger
28792    expressions containing EXPR.  */
28793 
28794 tree
build_non_dependent_expr(tree expr)28795 build_non_dependent_expr (tree expr)
28796 {
28797   tree orig_expr = expr;
28798   tree inner_expr;
28799 
28800   /* When checking, try to get a constant value for all non-dependent
28801      expressions in order to expose bugs in *_dependent_expression_p
28802      and constexpr.  This can affect code generation, see PR70704, so
28803      only do this for -fchecking=2.  */
28804   if (flag_checking > 1
28805       && cxx_dialect >= cxx11
28806       /* Don't do this during nsdmi parsing as it can lead to
28807 	 unexpected recursive instantiations.  */
28808       && !parsing_nsdmi ()
28809       /* Don't do this during concept processing either and for
28810          the same reason.  */
28811       && !processing_constraint_expression_p ())
28812     fold_non_dependent_expr (expr, tf_none);
28813 
28814   STRIP_ANY_LOCATION_WRAPPER (expr);
28815 
28816   /* Preserve OVERLOADs; the functions must be available to resolve
28817      types.  */
28818   inner_expr = expr;
28819   if (TREE_CODE (inner_expr) == STMT_EXPR)
28820     inner_expr = stmt_expr_value_expr (inner_expr);
28821   if (TREE_CODE (inner_expr) == ADDR_EXPR)
28822     inner_expr = TREE_OPERAND (inner_expr, 0);
28823   if (TREE_CODE (inner_expr) == COMPONENT_REF)
28824     inner_expr = TREE_OPERAND (inner_expr, 1);
28825   if (is_overloaded_fn (inner_expr)
28826       || TREE_CODE (inner_expr) == OFFSET_REF)
28827     return orig_expr;
28828   /* There is no need to return a proxy for a variable, parameter
28829      or enumerator.  */
28830   if (VAR_P (expr) || TREE_CODE (expr) == PARM_DECL
28831       || TREE_CODE (expr) == CONST_DECL)
28832     return orig_expr;
28833   /* Preserve string constants; conversions from string constants to
28834      "char *" are allowed, even though normally a "const char *"
28835      cannot be used to initialize a "char *".  */
28836   if (TREE_CODE (expr) == STRING_CST)
28837     return orig_expr;
28838   /* Preserve void and arithmetic constants, as an optimization -- there is no
28839      reason to create a new node.  */
28840   if (TREE_CODE (expr) == VOID_CST
28841       || TREE_CODE (expr) == INTEGER_CST
28842       || TREE_CODE (expr) == REAL_CST)
28843     return orig_expr;
28844   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
28845      There is at least one place where we want to know that a
28846      particular expression is a throw-expression: when checking a ?:
28847      expression, there are special rules if the second or third
28848      argument is a throw-expression.  */
28849   if (TREE_CODE (expr) == THROW_EXPR)
28850     return orig_expr;
28851 
28852   /* Don't wrap an initializer list, we need to be able to look inside.  */
28853   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
28854     return orig_expr;
28855 
28856   /* Don't wrap a dummy object, we need to be able to test for it.  */
28857   if (is_dummy_object (expr))
28858     return orig_expr;
28859 
28860   if (TREE_CODE (expr) == COND_EXPR)
28861     return build3 (COND_EXPR,
28862 		   TREE_TYPE (expr),
28863 		   build_non_dependent_expr (TREE_OPERAND (expr, 0)),
28864 		   (TREE_OPERAND (expr, 1)
28865 		    ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
28866 		    : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
28867 		   build_non_dependent_expr (TREE_OPERAND (expr, 2)));
28868   if (TREE_CODE (expr) == COMPOUND_EXPR)
28869     return build2 (COMPOUND_EXPR,
28870 		   TREE_TYPE (expr),
28871 		   TREE_OPERAND (expr, 0),
28872 		   build_non_dependent_expr (TREE_OPERAND (expr, 1)));
28873 
28874   /* If the type is unknown, it can't really be non-dependent */
28875   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
28876 
28877   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
28878   return build1_loc (EXPR_LOCATION (orig_expr), NON_DEPENDENT_EXPR,
28879 		     TREE_TYPE (expr), expr);
28880 }
28881 
28882 /* ARGS is a vector of expressions as arguments to a function call.
28883    Replace the arguments with equivalent non-dependent expressions.
28884    This modifies ARGS in place.  */
28885 
28886 void
make_args_non_dependent(vec<tree,va_gc> * args)28887 make_args_non_dependent (vec<tree, va_gc> *args)
28888 {
28889   unsigned int ix;
28890   tree arg;
28891 
28892   FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
28893     {
28894       tree newarg = build_non_dependent_expr (arg);
28895       if (newarg != arg)
28896 	(*args)[ix] = newarg;
28897     }
28898 }
28899 
28900 /* Returns a type which represents 'auto' or 'decltype(auto)'.  We use a
28901    TEMPLATE_TYPE_PARM with a level one deeper than the actual template parms,
28902    by default.  If set_canonical is true, we set TYPE_CANONICAL on it.  */
28903 
28904 static tree
make_auto_1(tree name,bool set_canonical,int level=-1)28905 make_auto_1 (tree name, bool set_canonical, int level = -1)
28906 {
28907   if (level == -1)
28908     level = current_template_depth + 1;
28909   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
28910   TYPE_NAME (au) = build_decl (input_location, TYPE_DECL, name, au);
28911   TYPE_STUB_DECL (au) = TYPE_NAME (au);
28912   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
28913     (0, level, level, TYPE_NAME (au), NULL_TREE);
28914   if (set_canonical)
28915     TYPE_CANONICAL (au) = canonical_type_parameter (au);
28916   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
28917   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
28918   if (name == decltype_auto_identifier)
28919     AUTO_IS_DECLTYPE (au) = true;
28920 
28921   return au;
28922 }
28923 
28924 tree
make_decltype_auto(void)28925 make_decltype_auto (void)
28926 {
28927   return make_auto_1 (decltype_auto_identifier, true);
28928 }
28929 
28930 tree
make_auto(void)28931 make_auto (void)
28932 {
28933   return make_auto_1 (auto_identifier, true);
28934 }
28935 
28936 /* Return a C++17 deduction placeholder for class template TMPL.
28937    There are represented as an 'auto' with the special level 0 and
28938    CLASS_PLACEHOLDER_TEMPLATE set.  */
28939 
28940 tree
make_template_placeholder(tree tmpl)28941 make_template_placeholder (tree tmpl)
28942 {
28943   tree t = make_auto_1 (auto_identifier, false, /*level=*/0);
28944   CLASS_PLACEHOLDER_TEMPLATE (t) = tmpl;
28945   /* Our canonical type depends on the placeholder.  */
28946   TYPE_CANONICAL (t) = canonical_type_parameter (t);
28947   return t;
28948 }
28949 
28950 /* True iff T is a C++17 class template deduction placeholder.  */
28951 
28952 bool
template_placeholder_p(tree t)28953 template_placeholder_p (tree t)
28954 {
28955   return is_auto (t) && CLASS_PLACEHOLDER_TEMPLATE (t);
28956 }
28957 
28958 /* Make a "constrained auto" type-specifier. This is an auto or
28959   decltype(auto) type with constraints that must be associated after
28960   deduction.  The constraint is formed from the given concept CON
28961   and its optional sequence of template arguments ARGS.
28962 
28963   TYPE must be the result of make_auto_type or make_decltype_auto_type. */
28964 
28965 static tree
make_constrained_placeholder_type(tree type,tree con,tree args)28966 make_constrained_placeholder_type (tree type, tree con, tree args)
28967 {
28968   /* Build the constraint. */
28969   tree tmpl = DECL_TI_TEMPLATE (con);
28970   tree expr = tmpl;
28971   if (TREE_CODE (con) == FUNCTION_DECL)
28972     expr = ovl_make (tmpl);
28973   ++processing_template_decl;
28974   expr = build_concept_check (expr, type, args, tf_warning_or_error);
28975   --processing_template_decl;
28976 
28977   PLACEHOLDER_TYPE_CONSTRAINTS_INFO (type)
28978     = build_tree_list (current_template_parms, expr);
28979 
28980   /* Our canonical type depends on the constraint.  */
28981   TYPE_CANONICAL (type) = canonical_type_parameter (type);
28982 
28983   /* Attach the constraint to the type declaration. */
28984   return TYPE_NAME (type);
28985 }
28986 
28987 /* Make a "constrained auto" type-specifier.  */
28988 
28989 tree
make_constrained_auto(tree con,tree args)28990 make_constrained_auto (tree con, tree args)
28991 {
28992   tree type = make_auto_1 (auto_identifier, false);
28993   return make_constrained_placeholder_type (type, con, args);
28994 }
28995 
28996 /* Make a "constrained decltype(auto)" type-specifier.  */
28997 
28998 tree
make_constrained_decltype_auto(tree con,tree args)28999 make_constrained_decltype_auto (tree con, tree args)
29000 {
29001   tree type = make_auto_1 (decltype_auto_identifier, false);
29002   return make_constrained_placeholder_type (type, con, args);
29003 }
29004 
29005 /* Returns true if the placeholder type constraint T has any dependent
29006    (explicit) template arguments.  */
29007 
29008 static bool
placeholder_type_constraint_dependent_p(tree t)29009 placeholder_type_constraint_dependent_p (tree t)
29010 {
29011   tree id = unpack_concept_check (t);
29012   tree args = TREE_OPERAND (id, 1);
29013   tree first = TREE_VEC_ELT (args, 0);
29014   if (ARGUMENT_PACK_P (first))
29015     {
29016       args = expand_template_argument_pack (args);
29017       first = TREE_VEC_ELT (args, 0);
29018     }
29019   gcc_checking_assert (TREE_CODE (first) == WILDCARD_DECL
29020 		       || is_auto (first));
29021   for (int i = 1; i < TREE_VEC_LENGTH (args); ++i)
29022     if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
29023       return true;
29024   return false;
29025 }
29026 
29027 /* Build and return a concept definition. Like other templates, the
29028    CONCEPT_DECL node is wrapped by a TEMPLATE_DECL.  This returns the
29029    the TEMPLATE_DECL. */
29030 
29031 tree
finish_concept_definition(cp_expr id,tree init)29032 finish_concept_definition (cp_expr id, tree init)
29033 {
29034   gcc_assert (identifier_p (id));
29035   gcc_assert (processing_template_decl);
29036 
29037   location_t loc = id.get_location();
29038 
29039   /* A concept-definition shall not have associated constraints.  */
29040   if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
29041     {
29042       error_at (loc, "a concept cannot be constrained");
29043       TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
29044     }
29045 
29046   /* A concept-definition shall appear in namespace scope.  Templates
29047      aren't allowed in block scope, so we only need to check for class
29048      scope.  */
29049   if (TYPE_P (current_scope()) || !DECL_NAMESPACE_SCOPE_P (current_scope ()))
29050     {
29051       error_at (loc, "concept %qE not in namespace scope", *id);
29052       return error_mark_node;
29053     }
29054 
29055   if (current_template_depth > 1)
29056     {
29057       error_at (loc, "concept %qE has multiple template parameter lists", *id);
29058       return error_mark_node;
29059     }
29060 
29061   /* Initially build the concept declaration; its type is bool.  */
29062   tree decl = build_lang_decl_loc (loc, CONCEPT_DECL, *id, boolean_type_node);
29063   DECL_CONTEXT (decl) = current_scope ();
29064   DECL_INITIAL (decl) = init;
29065 
29066   set_originating_module (decl, false);
29067 
29068   /* Push the enclosing template.  */
29069   return push_template_decl (decl);
29070 }
29071 
29072 /* Given type ARG, return std::initializer_list<ARG>.  */
29073 
29074 static tree
listify(tree arg)29075 listify (tree arg)
29076 {
29077   tree std_init_list = get_namespace_binding (std_node, init_list_identifier);
29078 
29079   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
29080     {
29081       gcc_rich_location richloc (input_location);
29082       maybe_add_include_fixit (&richloc, "<initializer_list>", false);
29083       error_at (&richloc,
29084 		"deducing from brace-enclosed initializer list"
29085 		" requires %<#include <initializer_list>%>");
29086 
29087       return error_mark_node;
29088     }
29089   tree argvec = make_tree_vec (1);
29090   TREE_VEC_ELT (argvec, 0) = arg;
29091 
29092   return lookup_template_class (std_init_list, argvec, NULL_TREE,
29093 				NULL_TREE, 0, tf_warning_or_error);
29094 }
29095 
29096 /* Replace auto in TYPE with std::initializer_list<auto>.  */
29097 
29098 static tree
listify_autos(tree type,tree auto_node)29099 listify_autos (tree type, tree auto_node)
29100 {
29101   tree init_auto = listify (strip_top_quals (auto_node));
29102   tree argvec = make_tree_vec (1);
29103   TREE_VEC_ELT (argvec, 0) = init_auto;
29104   if (processing_template_decl)
29105     argvec = add_to_template_args (current_template_args (), argvec);
29106   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
29107 }
29108 
29109 /* Hash traits for hashing possibly constrained 'auto'
29110    TEMPLATE_TYPE_PARMs for use by do_auto_deduction.  */
29111 
29112 struct auto_hash : default_hash_traits<tree>
29113 {
29114   static inline hashval_t hash (tree);
29115   static inline bool equal (tree, tree);
29116 };
29117 
29118 /* Hash the 'auto' T.  */
29119 
29120 inline hashval_t
hash(tree t)29121 auto_hash::hash (tree t)
29122 {
29123   if (tree c = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (t)))
29124     /* Matching constrained-type-specifiers denote the same template
29125        parameter, so hash the constraint.  */
29126     return hash_placeholder_constraint (c);
29127   else
29128     /* But unconstrained autos are all separate, so just hash the pointer.  */
29129     return iterative_hash_object (t, 0);
29130 }
29131 
29132 /* Compare two 'auto's.  */
29133 
29134 inline bool
equal(tree t1,tree t2)29135 auto_hash::equal (tree t1, tree t2)
29136 {
29137   if (t1 == t2)
29138     return true;
29139 
29140   tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
29141   tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
29142 
29143   /* Two unconstrained autos are distinct.  */
29144   if (!c1 || !c2)
29145     return false;
29146 
29147   return equivalent_placeholder_constraints (c1, c2);
29148 }
29149 
29150 /* for_each_template_parm callback for extract_autos: if t is a (possibly
29151    constrained) auto, add it to the vector.  */
29152 
29153 static int
extract_autos_r(tree t,void * data)29154 extract_autos_r (tree t, void *data)
29155 {
29156   hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
29157   if (is_auto (t) && !template_placeholder_p (t))
29158     {
29159       /* All the autos were built with index 0; fix that up now.  */
29160       tree *p = hash.find_slot (t, INSERT);
29161       unsigned idx;
29162       if (*p)
29163 	/* If this is a repeated constrained-type-specifier, use the index we
29164 	   chose before.  */
29165 	idx = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (*p));
29166       else
29167 	{
29168 	  /* Otherwise this is new, so use the current count.  */
29169 	  *p = t;
29170 	  idx = hash.elements () - 1;
29171 	}
29172       TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (t)) = idx;
29173     }
29174 
29175   /* Always keep walking.  */
29176   return 0;
29177 }
29178 
29179 /* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
29180    says they can appear anywhere in the type.  */
29181 
29182 static tree
extract_autos(tree type)29183 extract_autos (tree type)
29184 {
29185   hash_set<tree> visited;
29186   hash_table<auto_hash> hash (2);
29187 
29188   for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
29189 
29190   tree tree_vec = make_tree_vec (hash.elements());
29191   for (tree elt : hash)
29192     {
29193       unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
29194       TREE_VEC_ELT (tree_vec, i)
29195 	= build_tree_list (NULL_TREE, TYPE_NAME (elt));
29196     }
29197 
29198   return tree_vec;
29199 }
29200 
29201 /* The stem for deduction guide names.  */
29202 const char *const dguide_base = "__dguide_";
29203 
29204 /* Return the name for a deduction guide for class template TMPL.  */
29205 
29206 tree
dguide_name(tree tmpl)29207 dguide_name (tree tmpl)
29208 {
29209   tree type = (TYPE_P (tmpl) ? tmpl : TREE_TYPE (tmpl));
29210   tree tname = TYPE_IDENTIFIER (type);
29211   char *buf = (char *) alloca (1 + strlen (dguide_base)
29212 			       + IDENTIFIER_LENGTH (tname));
29213   memcpy (buf, dguide_base, strlen (dguide_base));
29214   memcpy (buf + strlen (dguide_base), IDENTIFIER_POINTER (tname),
29215 	  IDENTIFIER_LENGTH (tname) + 1);
29216   tree dname = get_identifier (buf);
29217   TREE_TYPE (dname) = type;
29218   return dname;
29219 }
29220 
29221 /* True if NAME is the name of a deduction guide.  */
29222 
29223 bool
dguide_name_p(tree name)29224 dguide_name_p (tree name)
29225 {
29226   return (TREE_CODE (name) == IDENTIFIER_NODE
29227 	  && TREE_TYPE (name)
29228 	  && startswith (IDENTIFIER_POINTER (name), dguide_base));
29229 }
29230 
29231 /* True if FN is a deduction guide.  */
29232 
29233 bool
deduction_guide_p(const_tree fn)29234 deduction_guide_p (const_tree fn)
29235 {
29236   if (DECL_P (fn))
29237     if (tree name = DECL_NAME (fn))
29238       return dguide_name_p (name);
29239   return false;
29240 }
29241 
29242 /* True if FN is the copy deduction guide, i.e. A(A)->A.  */
29243 
29244 bool
copy_guide_p(const_tree fn)29245 copy_guide_p (const_tree fn)
29246 {
29247   gcc_assert (deduction_guide_p (fn));
29248   if (!DECL_ARTIFICIAL (fn))
29249     return false;
29250   tree parms = FUNCTION_FIRST_USER_PARMTYPE (DECL_TI_TEMPLATE (fn));
29251   return (TREE_CHAIN (parms) == void_list_node
29252 	  && same_type_p (TREE_VALUE (parms), TREE_TYPE (DECL_NAME (fn))));
29253 }
29254 
29255 /* True if FN is a guide generated from a constructor template.  */
29256 
29257 bool
template_guide_p(const_tree fn)29258 template_guide_p (const_tree fn)
29259 {
29260   gcc_assert (deduction_guide_p (fn));
29261   if (!DECL_ARTIFICIAL (fn))
29262     return false;
29263   tree tmpl = DECL_TI_TEMPLATE (fn);
29264   if (tree org = DECL_ABSTRACT_ORIGIN (tmpl))
29265     return PRIMARY_TEMPLATE_P (org);
29266   return false;
29267 }
29268 
29269 /* True if FN is an aggregate initialization guide or the copy deduction
29270    guide.  */
29271 
29272 bool
builtin_guide_p(const_tree fn)29273 builtin_guide_p (const_tree fn)
29274 {
29275   if (!deduction_guide_p (fn))
29276     return false;
29277   if (!DECL_ARTIFICIAL (fn))
29278     /* Explicitly declared.  */
29279     return false;
29280   if (DECL_ABSTRACT_ORIGIN (fn))
29281     /* Derived from a constructor.  */
29282     return false;
29283   return true;
29284 }
29285 
29286 /* OLDDECL is a _DECL for a template parameter.  Return a similar parameter at
29287    LEVEL:INDEX, using tsubst_args and complain for substitution into non-type
29288    template parameter types.  Note that the handling of template template
29289    parameters relies on current_template_parms being set appropriately for the
29290    new template.  */
29291 
29292 static tree
rewrite_template_parm(tree olddecl,unsigned index,unsigned level,tree tsubst_args,tsubst_flags_t complain)29293 rewrite_template_parm (tree olddecl, unsigned index, unsigned level,
29294 		       tree tsubst_args, tsubst_flags_t complain)
29295 {
29296   if (olddecl == error_mark_node)
29297     return error_mark_node;
29298 
29299   tree oldidx = get_template_parm_index (olddecl);
29300 
29301   tree newtype;
29302   if (TREE_CODE (olddecl) == TYPE_DECL
29303       || TREE_CODE (olddecl) == TEMPLATE_DECL)
29304     {
29305       tree oldtype = TREE_TYPE (olddecl);
29306       newtype = cxx_make_type (TREE_CODE (oldtype));
29307       TYPE_MAIN_VARIANT (newtype) = newtype;
29308     }
29309   else
29310     {
29311       newtype = TREE_TYPE (olddecl);
29312       if (type_uses_auto (newtype))
29313 	{
29314 	  // Substitute once to fix references to other template parameters.
29315 	  newtype = tsubst (newtype, tsubst_args,
29316 			    complain|tf_partial, NULL_TREE);
29317 	  // Now substitute again to reduce the level of the auto.
29318 	  newtype = tsubst (newtype, current_template_args (),
29319 			    complain, NULL_TREE);
29320 	}
29321       else
29322 	newtype = tsubst (newtype, tsubst_args,
29323 			  complain, NULL_TREE);
29324     }
29325 
29326   tree newdecl
29327     = build_decl (DECL_SOURCE_LOCATION (olddecl), TREE_CODE (olddecl),
29328 		  DECL_NAME (olddecl), newtype);
29329   SET_DECL_TEMPLATE_PARM_P (newdecl);
29330 
29331   tree newidx;
29332   if (TREE_CODE (olddecl) == TYPE_DECL
29333       || TREE_CODE (olddecl) == TEMPLATE_DECL)
29334     {
29335       newidx = TEMPLATE_TYPE_PARM_INDEX (newtype)
29336 	= build_template_parm_index (index, level, level,
29337 				     newdecl, newtype);
29338       TEMPLATE_PARM_PARAMETER_PACK (newidx)
29339 	= TEMPLATE_PARM_PARAMETER_PACK (oldidx);
29340       TYPE_STUB_DECL (newtype) = TYPE_NAME (newtype) = newdecl;
29341       if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (olddecl)))
29342 	SET_TYPE_STRUCTURAL_EQUALITY (newtype);
29343       else
29344 	TYPE_CANONICAL (newtype) = canonical_type_parameter (newtype);
29345 
29346       if (TREE_CODE (olddecl) == TEMPLATE_DECL)
29347 	{
29348 	  DECL_TEMPLATE_RESULT (newdecl)
29349 	    = build_decl (DECL_SOURCE_LOCATION (olddecl), TYPE_DECL,
29350 			  DECL_NAME (olddecl), newtype);
29351 	  DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (newdecl)) = true;
29352 	  // First create a copy (ttargs) of tsubst_args with an
29353 	  // additional level for the template template parameter's own
29354 	  // template parameters (ttparms).
29355 	  tree ttparms = (INNERMOST_TEMPLATE_PARMS
29356 			  (DECL_TEMPLATE_PARMS (olddecl)));
29357 	  const int depth = TMPL_ARGS_DEPTH (tsubst_args);
29358 	  tree ttargs = make_tree_vec (depth + 1);
29359 	  for (int i = 0; i < depth; ++i)
29360 	    TREE_VEC_ELT (ttargs, i) = TMPL_ARGS_LEVEL (tsubst_args, i + 1);
29361 	  TREE_VEC_ELT (ttargs, depth)
29362 	    = template_parms_level_to_args (ttparms);
29363 	  // Substitute ttargs into ttparms to fix references to
29364 	  // other template parameters.
29365 	  ttparms = tsubst_template_parms_level (ttparms, ttargs,
29366 						 complain|tf_partial);
29367 	  // Now substitute again with args based on tparms, to reduce
29368 	  // the level of the ttparms.
29369 	  ttargs = current_template_args ();
29370 	  ttparms = tsubst_template_parms_level (ttparms, ttargs,
29371 						 complain);
29372 	  // Finally, tack the adjusted parms onto tparms.
29373 	  ttparms = tree_cons (size_int (level + 1), ttparms,
29374 			       copy_node (current_template_parms));
29375 	  // As with all template template parms, the parameter list captured
29376 	  // by this template template parm that corresponds to its own level
29377 	  // should be empty.  This avoids infinite recursion when structurally
29378 	  // comparing two such rewritten template template parms (PR102479).
29379 	  gcc_assert (!TREE_VEC_LENGTH
29380 		      (TREE_VALUE (TREE_CHAIN (DECL_TEMPLATE_PARMS (olddecl)))));
29381 	  gcc_assert (TMPL_PARMS_DEPTH (TREE_CHAIN (ttparms)) == level);
29382 	  TREE_VALUE (TREE_CHAIN (ttparms)) = make_tree_vec (0);
29383 	  // All done.
29384 	  DECL_TEMPLATE_PARMS (newdecl) = ttparms;
29385 	}
29386     }
29387   else
29388     {
29389       tree oldconst = TEMPLATE_PARM_DECL (oldidx);
29390       tree newconst
29391 	= build_decl (DECL_SOURCE_LOCATION (oldconst),
29392 		      TREE_CODE (oldconst),
29393 		      DECL_NAME (oldconst), newtype);
29394       TREE_CONSTANT (newconst) = TREE_CONSTANT (newdecl)
29395 	= TREE_READONLY (newconst) = TREE_READONLY (newdecl) = true;
29396       SET_DECL_TEMPLATE_PARM_P (newconst);
29397       newidx = build_template_parm_index (index, level, level,
29398 					  newconst, newtype);
29399       TEMPLATE_PARM_PARAMETER_PACK (newidx)
29400 	= TEMPLATE_PARM_PARAMETER_PACK (oldidx);
29401       DECL_INITIAL (newdecl) = DECL_INITIAL (newconst) = newidx;
29402     }
29403 
29404   return newdecl;
29405 }
29406 
29407 /* As rewrite_template_parm, but for the whole TREE_LIST representing a
29408    template parameter.  */
29409 
29410 static tree
rewrite_tparm_list(tree oldelt,unsigned index,unsigned level,tree targs,unsigned targs_index,tsubst_flags_t complain)29411 rewrite_tparm_list (tree oldelt, unsigned index, unsigned level,
29412 		    tree targs, unsigned targs_index, tsubst_flags_t complain)
29413 {
29414   tree olddecl = TREE_VALUE (oldelt);
29415   tree newdecl = rewrite_template_parm (olddecl, index, level,
29416 					targs, complain);
29417   if (newdecl == error_mark_node)
29418     return error_mark_node;
29419   tree newdef = tsubst_template_arg (TREE_PURPOSE (oldelt),
29420 				     targs, complain, NULL_TREE);
29421   tree list = build_tree_list (newdef, newdecl);
29422   TEMPLATE_PARM_CONSTRAINTS (list)
29423     = tsubst_constraint_info (TEMPLATE_PARM_CONSTRAINTS (oldelt),
29424 			      targs, complain, NULL_TREE);
29425   int depth = TMPL_ARGS_DEPTH (targs);
29426   TMPL_ARG (targs, depth, targs_index) = template_parm_to_arg (list);
29427   return list;
29428 }
29429 
29430 /* Returns a C++17 class deduction guide template based on the constructor
29431    CTOR.  As a special case, CTOR can be a RECORD_TYPE for an implicit default
29432    guide, REFERENCE_TYPE for an implicit copy/move guide, or TREE_LIST for an
29433    aggregate initialization guide.  OUTER_ARGS are the template arguments
29434    for the enclosing scope of the class.  */
29435 
29436 static tree
build_deduction_guide(tree type,tree ctor,tree outer_args,tsubst_flags_t complain)29437 build_deduction_guide (tree type, tree ctor, tree outer_args, tsubst_flags_t complain)
29438 {
29439   tree tparms, targs, fparms, fargs, ci;
29440   bool memtmpl = false;
29441   bool explicit_p;
29442   location_t loc;
29443   tree fn_tmpl = NULL_TREE;
29444 
29445   if (outer_args)
29446     {
29447       ++processing_template_decl;
29448       type = tsubst (type, outer_args, complain, CLASSTYPE_TI_TEMPLATE (type));
29449       --processing_template_decl;
29450     }
29451 
29452   if (!DECL_DECLARES_FUNCTION_P (ctor))
29453     {
29454       if (TYPE_P (ctor))
29455 	{
29456 	  bool copy_p = TYPE_REF_P (ctor);
29457 	  if (copy_p)
29458 	    fparms = tree_cons (NULL_TREE, type, void_list_node);
29459 	  else
29460 	    fparms = void_list_node;
29461 	}
29462       else if (TREE_CODE (ctor) == TREE_LIST)
29463 	fparms = ctor;
29464       else
29465 	gcc_unreachable ();
29466 
29467       tree ctmpl = CLASSTYPE_TI_TEMPLATE (type);
29468       tparms = DECL_TEMPLATE_PARMS (ctmpl);
29469       targs = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
29470       ci = NULL_TREE;
29471       fargs = NULL_TREE;
29472       loc = DECL_SOURCE_LOCATION (ctmpl);
29473       explicit_p = false;
29474     }
29475   else
29476     {
29477       ++processing_template_decl;
29478       bool ok = true;
29479 
29480       complain |= tf_dguide;
29481 
29482       fn_tmpl
29483 	= (TREE_CODE (ctor) == TEMPLATE_DECL ? ctor
29484 	   : DECL_TI_TEMPLATE (ctor));
29485       if (outer_args)
29486 	fn_tmpl = tsubst (fn_tmpl, outer_args, complain, ctor);
29487       ctor = DECL_TEMPLATE_RESULT (fn_tmpl);
29488 
29489       tparms = DECL_TEMPLATE_PARMS (fn_tmpl);
29490       /* If type is a member class template, DECL_TI_ARGS (ctor) will have
29491 	 fully specialized args for the enclosing class.  Strip those off, as
29492 	 the deduction guide won't have those template parameters.  */
29493       targs = get_innermost_template_args (DECL_TI_ARGS (ctor),
29494 						TMPL_PARMS_DEPTH (tparms));
29495       /* Discard the 'this' parameter.  */
29496       fparms = FUNCTION_ARG_CHAIN (ctor);
29497       fargs = TREE_CHAIN (DECL_ARGUMENTS (ctor));
29498       ci = get_constraints (ctor);
29499       loc = DECL_SOURCE_LOCATION (ctor);
29500       explicit_p = DECL_NONCONVERTING_P (ctor);
29501 
29502       if (PRIMARY_TEMPLATE_P (fn_tmpl))
29503 	{
29504 	  memtmpl = true;
29505 
29506 	  /* For a member template constructor, we need to flatten the two
29507 	     template parameter lists into one, and then adjust the function
29508 	     signature accordingly.  This gets...complicated.  */
29509 	  tree save_parms = current_template_parms;
29510 
29511 	  /* For a member template we should have two levels of parms/args, one
29512 	     for the class and one for the constructor.  We stripped
29513 	     specialized args for further enclosing classes above.  */
29514 	  const int depth = 2;
29515 	  gcc_assert (TMPL_ARGS_DEPTH (targs) == depth);
29516 
29517 	  /* Template args for translating references to the two-level template
29518 	     parameters into references to the one-level template parameters we
29519 	     are creating.  */
29520 	  tree tsubst_args = copy_node (targs);
29521 	  TMPL_ARGS_LEVEL (tsubst_args, depth)
29522 	    = copy_node (TMPL_ARGS_LEVEL (tsubst_args, depth));
29523 
29524 	  /* Template parms for the constructor template.  */
29525 	  tree ftparms = TREE_VALUE (tparms);
29526 	  unsigned flen = TREE_VEC_LENGTH (ftparms);
29527 	  /* Template parms for the class template.  */
29528 	  tparms = TREE_CHAIN (tparms);
29529 	  tree ctparms = TREE_VALUE (tparms);
29530 	  unsigned clen = TREE_VEC_LENGTH (ctparms);
29531 	  /* Template parms for the deduction guide start as a copy of the
29532 	     template parms for the class.  We set current_template_parms for
29533 	     lookup_template_class_1.  */
29534 	  current_template_parms = tparms = copy_node (tparms);
29535 	  tree new_vec = TREE_VALUE (tparms) = make_tree_vec (flen + clen);
29536 	  for (unsigned i = 0; i < clen; ++i)
29537 	    TREE_VEC_ELT (new_vec, i) = TREE_VEC_ELT (ctparms, i);
29538 
29539 	  /* Now we need to rewrite the constructor parms to append them to the
29540 	     class parms.  */
29541 	  for (unsigned i = 0; i < flen; ++i)
29542 	    {
29543 	      unsigned index = i + clen;
29544 	      unsigned level = 1;
29545 	      tree oldelt = TREE_VEC_ELT (ftparms, i);
29546 	      tree newelt
29547 		= rewrite_tparm_list (oldelt, index, level,
29548 				      tsubst_args, i, complain);
29549 	      if (newelt == error_mark_node)
29550 		ok = false;
29551 	      TREE_VEC_ELT (new_vec, index) = newelt;
29552 	    }
29553 
29554 	  /* Now we have a final set of template parms to substitute into the
29555 	     function signature.  */
29556 	  targs = template_parms_to_args (tparms);
29557 	  fparms = tsubst_arg_types (fparms, tsubst_args, NULL_TREE,
29558 				     complain, ctor);
29559 	  if (fparms == error_mark_node)
29560 	    ok = false;
29561 	  if (ci)
29562 	    {
29563 	      if (outer_args)
29564 		/* FIXME: We'd like to avoid substituting outer template
29565 		   arguments into the constraint ahead of time, but the
29566 		   construction of tsubst_args assumes that outer arguments
29567 		   are already substituted in.  */
29568 		ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
29569 	      ci = tsubst_constraint_info (ci, tsubst_args, complain, ctor);
29570 	    }
29571 
29572 	  /* Parms are to have DECL_CHAIN tsubsted, which would be skipped if
29573 	     cp_unevaluated_operand.  */
29574 	  cp_evaluated ev;
29575 	  fargs = tsubst (fargs, tsubst_args, complain, ctor);
29576 	  current_template_parms = save_parms;
29577 	}
29578       else
29579 	{
29580 	  /* Substitute in the same arguments to rewrite class members into
29581 	     references to members of an unknown specialization.  */
29582 	  cp_evaluated ev;
29583 	  fparms = tsubst_arg_types (fparms, targs, NULL_TREE, complain, ctor);
29584 	  fargs = tsubst (fargs, targs, complain, ctor);
29585 	  if (ci)
29586 	    {
29587 	      if (outer_args)
29588 		/* FIXME: As above.  */
29589 		ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
29590 	      ci = tsubst_constraint_info (ci, targs, complain, ctor);
29591 	    }
29592 	}
29593 
29594       --processing_template_decl;
29595       if (!ok)
29596 	return error_mark_node;
29597     }
29598 
29599   if (!memtmpl)
29600     {
29601       /* Copy the parms so we can set DECL_PRIMARY_TEMPLATE.  */
29602       tparms = copy_node (tparms);
29603       INNERMOST_TEMPLATE_PARMS (tparms)
29604 	= copy_node (INNERMOST_TEMPLATE_PARMS (tparms));
29605     }
29606 
29607   tree fntype = build_function_type (type, fparms);
29608   tree ded_fn = build_lang_decl_loc (loc,
29609 				     FUNCTION_DECL,
29610 				     dguide_name (type), fntype);
29611   DECL_ARGUMENTS (ded_fn) = fargs;
29612   DECL_ARTIFICIAL (ded_fn) = true;
29613   DECL_NONCONVERTING_P (ded_fn) = explicit_p;
29614   tree ded_tmpl = build_template_decl (ded_fn, tparms, /*member*/false);
29615   DECL_ARTIFICIAL (ded_tmpl) = true;
29616   DECL_TEMPLATE_INFO (ded_fn) = build_template_info (ded_tmpl, targs);
29617   DECL_PRIMARY_TEMPLATE (ded_tmpl) = ded_tmpl;
29618   if (DECL_P (ctor))
29619     DECL_ABSTRACT_ORIGIN (ded_tmpl) = fn_tmpl;
29620   if (ci)
29621     set_constraints (ded_tmpl, ci);
29622 
29623   return ded_tmpl;
29624 }
29625 
29626 /* Add to LIST the member types for the reshaped initializer CTOR.  */
29627 
29628 static tree
collect_ctor_idx_types(tree ctor,tree list,tree elt=NULL_TREE)29629 collect_ctor_idx_types (tree ctor, tree list, tree elt = NULL_TREE)
29630 {
29631   vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (ctor);
29632   tree idx, val; unsigned i;
29633   FOR_EACH_CONSTRUCTOR_ELT (v, i, idx, val)
29634     {
29635       tree ftype = elt ? elt : TREE_TYPE (idx);
29636       if (BRACE_ENCLOSED_INITIALIZER_P (val)
29637 	  && CONSTRUCTOR_BRACES_ELIDED_P (val))
29638 	{
29639 	  tree subelt = NULL_TREE;
29640 	  if (TREE_CODE (ftype) == ARRAY_TYPE)
29641 	    subelt = TREE_TYPE (ftype);
29642 	  list = collect_ctor_idx_types (val, list, subelt);
29643 	  continue;
29644 	}
29645       tree arg = NULL_TREE;
29646       if (i == v->length() - 1
29647 	  && PACK_EXPANSION_P (ftype))
29648 	/* Give the trailing pack expansion parameter a default argument to
29649 	   match aggregate initialization behavior, even if we deduce the
29650 	   length of the pack separately to more than we have initializers. */
29651 	arg = build_constructor (init_list_type_node, NULL);
29652       /* if ei is of array type and xi is a braced-init-list or string literal,
29653 	 Ti is an rvalue reference to the declared type of ei */
29654       STRIP_ANY_LOCATION_WRAPPER (val);
29655       if (TREE_CODE (ftype) == ARRAY_TYPE
29656 	  && (BRACE_ENCLOSED_INITIALIZER_P (val)
29657 	      || TREE_CODE (val) == STRING_CST))
29658 	{
29659 	  if (TREE_CODE (val) == STRING_CST)
29660 	    ftype = cp_build_qualified_type
29661 	      (ftype, cp_type_quals (ftype) | TYPE_QUAL_CONST);
29662 	  ftype = (cp_build_reference_type
29663 		   (ftype, BRACE_ENCLOSED_INITIALIZER_P (val)));
29664 	}
29665       list = tree_cons (arg, ftype, list);
29666     }
29667 
29668   return list;
29669 }
29670 
29671 /* Return whether ETYPE is, or is derived from, a specialization of TMPL.  */
29672 
29673 static bool
is_spec_or_derived(tree etype,tree tmpl)29674 is_spec_or_derived (tree etype, tree tmpl)
29675 {
29676   if (!etype || !CLASS_TYPE_P (etype))
29677     return false;
29678 
29679   etype = cv_unqualified (etype);
29680   tree type = TREE_TYPE (tmpl);
29681   tree tparms = (INNERMOST_TEMPLATE_PARMS
29682 		 (DECL_TEMPLATE_PARMS (tmpl)));
29683   tree targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
29684   int err = unify (tparms, targs, type, etype,
29685 		   UNIFY_ALLOW_DERIVED, /*explain*/false);
29686   ggc_free (targs);
29687   return !err;
29688 }
29689 
29690 static tree alias_ctad_tweaks (tree, tree);
29691 
29692 /* Return a C++20 aggregate deduction candidate for TYPE initialized from
29693    INIT.  */
29694 
29695 static tree
maybe_aggr_guide(tree tmpl,tree init,vec<tree,va_gc> * args)29696 maybe_aggr_guide (tree tmpl, tree init, vec<tree,va_gc> *args)
29697 {
29698   if (cxx_dialect < cxx20)
29699     return NULL_TREE;
29700 
29701   if (init == NULL_TREE)
29702     return NULL_TREE;
29703 
29704   if (DECL_ALIAS_TEMPLATE_P (tmpl))
29705     {
29706       tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
29707       tree tinfo = get_template_info (under);
29708       if (tree guide = maybe_aggr_guide (TI_TEMPLATE (tinfo), init, args))
29709 	return alias_ctad_tweaks (tmpl, guide);
29710       return NULL_TREE;
29711     }
29712 
29713   /* We might be creating a guide for a class member template, e.g.,
29714 
29715        template<typename U> struct A {
29716 	 template<typename T> struct B { T t; };
29717        };
29718 
29719      At this point, A will have been instantiated.  Below, we need to
29720      use both A<U>::B<T> (TEMPLATE_TYPE) and A<int>::B<T> (TYPE) types.  */
29721   const bool member_template_p
29722     = (DECL_TEMPLATE_INFO (tmpl)
29723        && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (tmpl)));
29724   tree type = TREE_TYPE (tmpl);
29725   tree template_type = (member_template_p
29726 			? TREE_TYPE (DECL_TI_TEMPLATE (tmpl))
29727 			: type);
29728   if (!CP_AGGREGATE_TYPE_P (template_type))
29729     return NULL_TREE;
29730 
29731   /* No aggregate candidate for copy-initialization.  */
29732   if (args->length() == 1)
29733     {
29734       tree val = (*args)[0];
29735       if (is_spec_or_derived (TREE_TYPE (val), tmpl))
29736 	return NULL_TREE;
29737     }
29738 
29739   /* If we encounter a problem, we just won't add the candidate.  */
29740   tsubst_flags_t complain = tf_none;
29741 
29742   tree parms = NULL_TREE;
29743   if (BRACE_ENCLOSED_INITIALIZER_P (init))
29744     {
29745       init = reshape_init (template_type, init, complain);
29746       if (init == error_mark_node)
29747 	return NULL_TREE;
29748       parms = collect_ctor_idx_types (init, parms);
29749       /* If we're creating a deduction guide for a member class template,
29750 	 we've used the original template pattern type for the reshape_init
29751 	 above; this is done because we want PARMS to be a template parameter
29752 	 type, something that can be deduced when used as a function template
29753 	 parameter.  At this point the outer class template has already been
29754 	 partially instantiated (we deferred the deduction until the enclosing
29755 	 scope is non-dependent).  Therefore we have to partially instantiate
29756 	 PARMS, so that its template level is properly reduced and we don't get
29757 	 mismatches when deducing types using the guide with PARMS.  */
29758       if (member_template_p)
29759 	{
29760 	  ++processing_template_decl;
29761 	  parms = tsubst (parms, DECL_TI_ARGS (tmpl), complain, init);
29762 	  --processing_template_decl;
29763 	}
29764     }
29765   else if (TREE_CODE (init) == TREE_LIST)
29766     {
29767       int len = list_length (init);
29768       for (tree field = TYPE_FIELDS (type);
29769 	   len;
29770 	   --len, field = DECL_CHAIN (field))
29771 	{
29772 	  field = next_initializable_field (field);
29773 	  if (!field)
29774 	    return NULL_TREE;
29775 	  tree ftype = finish_decltype_type (field, true, complain);
29776 	  parms = tree_cons (NULL_TREE, ftype, parms);
29777 	}
29778     }
29779   else
29780     /* Aggregate initialization doesn't apply to an initializer expression.  */
29781     return NULL_TREE;
29782 
29783   if (parms)
29784     {
29785       tree last = parms;
29786       parms = nreverse (parms);
29787       TREE_CHAIN (last) = void_list_node;
29788       tree guide = build_deduction_guide (type, parms, NULL_TREE, complain);
29789       return guide;
29790     }
29791 
29792   return NULL_TREE;
29793 }
29794 
29795 /* UGUIDES are the deduction guides for the underlying template of alias
29796    template TMPL; adjust them to be deduction guides for TMPL.  */
29797 
29798 static tree
alias_ctad_tweaks(tree tmpl,tree uguides)29799 alias_ctad_tweaks (tree tmpl, tree uguides)
29800 {
29801   /* [over.match.class.deduct]: When resolving a placeholder for a deduced
29802      class type (9.2.8.2) where the template-name names an alias template A,
29803      the defining-type-id of A must be of the form
29804 
29805      typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
29806 
29807      as specified in 9.2.8.2. The guides of A are the set of functions or
29808      function templates formed as follows. For each function or function
29809      template f in the guides of the template named by the simple-template-id
29810      of the defining-type-id, the template arguments of the return type of f
29811      are deduced from the defining-type-id of A according to the process in
29812      13.10.2.5 with the exception that deduction does not fail if not all
29813      template arguments are deduced. Let g denote the result of substituting
29814      these deductions into f. If substitution succeeds, form a function or
29815      function template f' with the following properties and add it to the set
29816      of guides of A:
29817 
29818      * The function type of f' is the function type of g.
29819 
29820      * If f is a function template, f' is a function template whose template
29821      parameter list consists of all the template parameters of A (including
29822      their default template arguments) that appear in the above deductions or
29823      (recursively) in their default template arguments, followed by the
29824      template parameters of f that were not deduced (including their default
29825      template arguments), otherwise f' is not a function template.
29826 
29827      * The associated constraints (13.5.2) are the conjunction of the
29828      associated constraints of g and a constraint that is satisfied if and only
29829      if the arguments of A are deducible (see below) from the return type.
29830 
29831      * If f is a copy deduction candidate (12.4.1.8), then f' is considered to
29832      be so as well.
29833 
29834      * If f was generated from a deduction-guide (12.4.1.8), then f' is
29835      considered to be so as well.
29836 
29837      * The explicit-specifier of f' is the explicit-specifier of g (if
29838      any).  */
29839 
29840   /* This implementation differs from the above in two significant ways:
29841 
29842      1) We include all template parameters of A, not just some.
29843      2) The added constraint is same_type instead of deducible.
29844 
29845      I believe that while it's probably possible to construct a testcase that
29846      behaves differently with this simplification, it should have the same
29847      effect for real uses.  Including all template parameters means that we
29848      deduce all parameters of A when resolving the call, so when we're in the
29849      constraint we don't need to deduce them again, we can just check whether
29850      the deduction produced the desired result.  */
29851 
29852   tsubst_flags_t complain = tf_warning_or_error;
29853   tree atype = TREE_TYPE (tmpl);
29854   tree aguides = NULL_TREE;
29855   tree atparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
29856   unsigned natparms = TREE_VEC_LENGTH (atparms);
29857   tree utype = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
29858   for (ovl_iterator iter (uguides); iter; ++iter)
29859     {
29860       tree f = *iter;
29861       tree in_decl = f;
29862       location_t loc = DECL_SOURCE_LOCATION (f);
29863       tree ret = TREE_TYPE (TREE_TYPE (f));
29864       tree fprime = f;
29865       if (TREE_CODE (f) == TEMPLATE_DECL)
29866 	{
29867 	  processing_template_decl_sentinel ptds (/*reset*/false);
29868 	  ++processing_template_decl;
29869 
29870 	  /* Deduce template arguments for f from the type-id of A.  */
29871 	  tree ftparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (f));
29872 	  unsigned len = TREE_VEC_LENGTH (ftparms);
29873 	  tree targs = make_tree_vec (len);
29874 	  int err = unify (ftparms, targs, ret, utype, UNIFY_ALLOW_NONE, false);
29875 	  if (err)
29876 	    continue;
29877 
29878 	  /* The number of parms for f' is the number of parms for A plus
29879 	     non-deduced parms of f.  */
29880 	  unsigned ndlen = 0;
29881 	  unsigned j;
29882 	  for (unsigned i = 0; i < len; ++i)
29883 	    if (TREE_VEC_ELT (targs, i) == NULL_TREE)
29884 	      ++ndlen;
29885 	  tree gtparms = make_tree_vec (natparms + ndlen);
29886 
29887 	  /* Set current_template_parms as in build_deduction_guide.  */
29888 	  auto ctp = make_temp_override (current_template_parms);
29889 	  current_template_parms = copy_node (DECL_TEMPLATE_PARMS (tmpl));
29890 	  TREE_VALUE (current_template_parms) = gtparms;
29891 
29892 	  /* First copy over the parms of A.  */
29893 	  for (j = 0; j < natparms; ++j)
29894 	    TREE_VEC_ELT (gtparms, j) = TREE_VEC_ELT (atparms, j);
29895 	  /* Now rewrite the non-deduced parms of f.  */
29896 	  for (unsigned i = 0; ndlen && i < len; ++i)
29897 	    if (TREE_VEC_ELT (targs, i) == NULL_TREE)
29898 	      {
29899 		--ndlen;
29900 		unsigned index = j++;
29901 		unsigned level = 1;
29902 		tree oldlist = TREE_VEC_ELT (ftparms, i);
29903 		tree list = rewrite_tparm_list (oldlist, index, level,
29904 						targs, i, complain);
29905 		TREE_VEC_ELT (gtparms, index) = list;
29906 	      }
29907 	  gtparms = build_tree_list (size_one_node, gtparms);
29908 
29909 	  /* Substitute the deduced arguments plus the rewritten template
29910 	     parameters into f to get g.  This covers the type, copyness,
29911 	     guideness, and explicit-specifier.  */
29912 	  tree g;
29913 	    {
29914 	      /* Parms are to have DECL_CHAIN tsubsted, which would be skipped
29915 		 if cp_unevaluated_operand.  */
29916 	      cp_evaluated ev;
29917 	      g = tsubst_decl (DECL_TEMPLATE_RESULT (f), targs, complain);
29918 	    }
29919 	  if (g == error_mark_node)
29920 	    continue;
29921 	  DECL_USE_TEMPLATE (g) = 0;
29922 	  fprime = build_template_decl (g, gtparms, false);
29923 	  DECL_TEMPLATE_RESULT (fprime) = g;
29924 	  TREE_TYPE (fprime) = TREE_TYPE (g);
29925 	  tree gtargs = template_parms_to_args (gtparms);
29926 	  DECL_TEMPLATE_INFO (g) = build_template_info (fprime, gtargs);
29927 	  DECL_PRIMARY_TEMPLATE (fprime) = fprime;
29928 
29929 	  /* Substitute the associated constraints.  */
29930 	  tree ci = get_constraints (f);
29931 	  if (ci)
29932 	    ci = tsubst_constraint_info (ci, targs, complain, in_decl);
29933 	  if (ci == error_mark_node)
29934 	    continue;
29935 
29936 	  /* Add a constraint that the return type matches the instantiation of
29937 	     A with the same template arguments.  */
29938 	  ret = TREE_TYPE (TREE_TYPE (fprime));
29939 	  if (!same_type_p (atype, ret)
29940 	      /* FIXME this should mean they don't compare as equivalent.  */
29941 	      || dependent_alias_template_spec_p (atype, nt_opaque))
29942 	    {
29943 	      tree same = finish_trait_expr (loc, CPTK_IS_SAME_AS, atype, ret);
29944 	      ci = append_constraint (ci, same);
29945 	    }
29946 
29947 	  if (ci)
29948 	    {
29949 	      remove_constraints (fprime);
29950 	      set_constraints (fprime, ci);
29951 	    }
29952 	}
29953       else
29954 	{
29955 	  /* For a non-template deduction guide, if the arguments of A aren't
29956 	     deducible from the return type, don't add the candidate.  */
29957 	  tree targs = make_tree_vec (natparms);
29958 	  int err = unify (atparms, targs, utype, ret, UNIFY_ALLOW_NONE, false);
29959 	  for (unsigned i = 0; !err && i < natparms; ++i)
29960 	    if (TREE_VEC_ELT (targs, i) == NULL_TREE)
29961 	      err = true;
29962 	  if (err)
29963 	    continue;
29964 	}
29965 
29966       aguides = lookup_add (fprime, aguides);
29967     }
29968 
29969   return aguides;
29970 }
29971 
29972 /* Return artificial deduction guides built from the constructors of class
29973    template TMPL.  */
29974 
29975 static tree
ctor_deduction_guides_for(tree tmpl,tsubst_flags_t complain)29976 ctor_deduction_guides_for (tree tmpl, tsubst_flags_t complain)
29977 {
29978   tree outer_args = outer_template_args (tmpl);
29979   tree type = TREE_TYPE (most_general_template (tmpl));
29980 
29981   tree cands = NULL_TREE;
29982 
29983   for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (type)); iter; ++iter)
29984     {
29985       /* Skip inherited constructors.  */
29986       if (iter.using_p ())
29987 	continue;
29988 
29989       tree guide = build_deduction_guide (type, *iter, outer_args, complain);
29990       cands = lookup_add (guide, cands);
29991     }
29992 
29993   /* Add implicit default constructor deduction guide.  */
29994   if (!TYPE_HAS_USER_CONSTRUCTOR (type))
29995     {
29996       tree guide = build_deduction_guide (type, type, outer_args,
29997 					  complain);
29998       cands = lookup_add (guide, cands);
29999     }
30000 
30001   /* Add copy guide.  */
30002   {
30003     tree gtype = build_reference_type (type);
30004     tree guide = build_deduction_guide (type, gtype, outer_args,
30005 					complain);
30006     cands = lookup_add (guide, cands);
30007   }
30008 
30009   return cands;
30010 }
30011 
30012 static GTY((deletable)) hash_map<tree, tree_pair_p> *dguide_cache;
30013 
30014 /* Return the non-aggregate deduction guides for deducible template TMPL.  The
30015    aggregate candidate is added separately because it depends on the
30016    initializer.  Set ANY_DGUIDES_P if we find a non-implicit deduction
30017    guide.  */
30018 
30019 static tree
deduction_guides_for(tree tmpl,bool & any_dguides_p,tsubst_flags_t complain)30020 deduction_guides_for (tree tmpl, bool &any_dguides_p, tsubst_flags_t complain)
30021 {
30022   tree guides = NULL_TREE;
30023   if (DECL_ALIAS_TEMPLATE_P (tmpl))
30024     {
30025       tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30026       tree tinfo = get_template_info (under);
30027       guides = deduction_guides_for (TI_TEMPLATE (tinfo), any_dguides_p,
30028 				     complain);
30029     }
30030   else
30031     {
30032       guides = lookup_qualified_name (CP_DECL_CONTEXT (tmpl),
30033 				      dguide_name (tmpl),
30034 				      LOOK_want::NORMAL, /*complain*/false);
30035       if (guides == error_mark_node)
30036 	guides = NULL_TREE;
30037       else
30038 	any_dguides_p = true;
30039     }
30040 
30041   /* Cache the deduction guides for a template.  We also remember the result of
30042      lookup, and rebuild everything if it changes; should be very rare.  */
30043   tree_pair_p cache = NULL;
30044   if (tree_pair_p &r
30045       = hash_map_safe_get_or_insert<hm_ggc> (dguide_cache, tmpl))
30046     {
30047       cache = r;
30048       if (cache->purpose == guides)
30049 	return cache->value;
30050     }
30051   else
30052     {
30053       r = cache = ggc_cleared_alloc<tree_pair_s> ();
30054       cache->purpose = guides;
30055     }
30056 
30057   tree cands = NULL_TREE;
30058   if (DECL_ALIAS_TEMPLATE_P (tmpl))
30059     cands = alias_ctad_tweaks (tmpl, guides);
30060   else
30061     {
30062       cands = ctor_deduction_guides_for (tmpl, complain);
30063       for (ovl_iterator it (guides); it; ++it)
30064 	cands = lookup_add (*it, cands);
30065     }
30066 
30067   cache->value = cands;
30068   return cands;
30069 }
30070 
30071 /* Return whether TMPL is a (class template argument-) deducible template.  */
30072 
30073 bool
ctad_template_p(tree tmpl)30074 ctad_template_p (tree tmpl)
30075 {
30076   /* A deducible template is either a class template or is an alias template
30077      whose defining-type-id is of the form
30078 
30079       typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
30080 
30081      where the nested-name-specifier (if any) is non-dependent and the
30082      template-name of the simple-template-id names a deducible template.  */
30083 
30084   if (DECL_CLASS_TEMPLATE_P (tmpl)
30085       || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
30086     return true;
30087   if (!DECL_ALIAS_TEMPLATE_P (tmpl))
30088     return false;
30089   tree orig = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30090   if (tree tinfo = get_template_info (orig))
30091     return ctad_template_p (TI_TEMPLATE (tinfo));
30092   return false;
30093 }
30094 
30095 /* Deduce template arguments for the class template placeholder PTYPE for
30096    template TMPL based on the initializer INIT, and return the resulting
30097    type.  */
30098 
30099 static tree
do_class_deduction(tree ptype,tree tmpl,tree init,int flags,tsubst_flags_t complain)30100 do_class_deduction (tree ptype, tree tmpl, tree init,
30101 		    int flags, tsubst_flags_t complain)
30102 {
30103   /* We should have handled this in the caller.  */
30104   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
30105     return ptype;
30106 
30107   /* If the class was erroneous, don't try to deduce, because that
30108      can generate a lot of diagnostic.  */
30109   if (TREE_TYPE (tmpl)
30110       && TYPE_LANG_SPECIFIC (TREE_TYPE (tmpl))
30111       && CLASSTYPE_ERRONEOUS (TREE_TYPE (tmpl)))
30112     return ptype;
30113 
30114   /* Wait until the enclosing scope is non-dependent.  */
30115   if (DECL_CLASS_SCOPE_P (tmpl)
30116       && dependent_type_p (DECL_CONTEXT (tmpl)))
30117     return ptype;
30118 
30119   /* Initializing one placeholder from another.  */
30120   if (init
30121       && (TREE_CODE (init) == TEMPLATE_PARM_INDEX
30122 	  || (TREE_CODE (init) == EXPR_PACK_EXPANSION
30123 	      && (TREE_CODE (PACK_EXPANSION_PATTERN (init))
30124 		  == TEMPLATE_PARM_INDEX)))
30125       && is_auto (TREE_TYPE (init))
30126       && CLASS_PLACEHOLDER_TEMPLATE (TREE_TYPE (init)) == tmpl)
30127     return cp_build_qualified_type (TREE_TYPE (init), cp_type_quals (ptype));
30128 
30129   if (!ctad_template_p (tmpl))
30130     {
30131       if (complain & tf_error)
30132 	error ("non-deducible template %qT used without template arguments", tmpl);
30133       return error_mark_node;
30134     }
30135   else if (cxx_dialect < cxx20 && DECL_ALIAS_TEMPLATE_P (tmpl))
30136     {
30137       if (complain & tf_error)
30138 	{
30139 	  /* Be permissive with equivalent alias templates.  */
30140 	  tree u = get_underlying_template (tmpl);
30141 	  diagnostic_t dk = (u == tmpl) ? DK_ERROR : DK_PEDWARN;
30142 	  bool complained
30143 	    = emit_diagnostic (dk, input_location, 0,
30144 			       "alias template deduction only available "
30145 			       "with %<-std=c++20%> or %<-std=gnu++20%>");
30146 	  if (u == tmpl)
30147 	    return error_mark_node;
30148 	  else if (complained)
30149 	    {
30150 	      inform (input_location, "use %qD directly instead", u);
30151 	      tmpl = u;
30152 	    }
30153 	}
30154       else
30155 	return error_mark_node;
30156     }
30157 
30158   /* Wait until the initializer is non-dependent.  */
30159   if (type_dependent_expression_p (init))
30160     return ptype;
30161 
30162   /* Don't bother with the alias rules for an equivalent template.  */
30163   tmpl = get_underlying_template (tmpl);
30164 
30165   tree type = TREE_TYPE (tmpl);
30166 
30167   bool try_list_ctor = false;
30168   bool list_init_p = false;
30169 
30170   releasing_vec rv_args = NULL;
30171   vec<tree,va_gc> *&args = *&rv_args;
30172   if (init == NULL_TREE)
30173     args = make_tree_vector ();
30174   else if (BRACE_ENCLOSED_INITIALIZER_P (init))
30175     {
30176       list_init_p = true;
30177       try_list_ctor = TYPE_HAS_LIST_CTOR (type);
30178       if (try_list_ctor && CONSTRUCTOR_NELTS (init) == 1
30179 	  && !CONSTRUCTOR_IS_DESIGNATED_INIT (init))
30180 	{
30181 	  /* As an exception, the first phase in 16.3.1.7 (considering the
30182 	     initializer list as a single argument) is omitted if the
30183 	     initializer list consists of a single expression of type cv U,
30184 	     where U is a specialization of C or a class derived from a
30185 	     specialization of C.  */
30186 	  tree elt = CONSTRUCTOR_ELT (init, 0)->value;
30187 	  if (is_spec_or_derived (TREE_TYPE (elt), tmpl))
30188 	    try_list_ctor = false;
30189 	}
30190       if (try_list_ctor || is_std_init_list (type))
30191 	args = make_tree_vector_single (init);
30192       else
30193 	args = make_tree_vector_from_ctor (init);
30194     }
30195   else if (TREE_CODE (init) == TREE_LIST)
30196     args = make_tree_vector_from_list (init);
30197   else
30198     args = make_tree_vector_single (init);
30199 
30200   /* Do this now to avoid problems with erroneous args later on.  */
30201   args = resolve_args (args, complain);
30202   if (args == NULL)
30203     return error_mark_node;
30204 
30205   bool any_dguides_p = false;
30206   tree cands = deduction_guides_for (tmpl, any_dguides_p, complain);
30207   if (cands == error_mark_node)
30208     return error_mark_node;
30209 
30210   /* Prune explicit deduction guides in copy-initialization context (but
30211      not copy-list-initialization).  */
30212   bool elided = false;
30213   if (!list_init_p && (flags & LOOKUP_ONLYCONVERTING))
30214     {
30215       for (lkp_iterator iter (cands); !elided && iter; ++iter)
30216 	if (DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
30217 	  elided = true;
30218 
30219       if (elided)
30220 	{
30221 	  /* Found a nonconverting guide, prune the candidates.  */
30222 	  tree pruned = NULL_TREE;
30223 	  for (lkp_iterator iter (cands); iter; ++iter)
30224 	    if (!DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
30225 	      pruned = lookup_add (*iter, pruned);
30226 
30227 	  cands = pruned;
30228 	}
30229     }
30230 
30231   if (!any_dguides_p)
30232     if (tree guide = maybe_aggr_guide (tmpl, init, args))
30233       cands = lookup_add (guide, cands);
30234 
30235   tree fndecl = error_mark_node;
30236 
30237   /* If this is list-initialization and the class has a list constructor, first
30238      try deducing from the list as a single argument, as [over.match.list].  */
30239   tree list_cands = NULL_TREE;
30240   if (try_list_ctor && cands)
30241     for (lkp_iterator iter (cands); iter; ++iter)
30242       {
30243 	tree dg = *iter;
30244 	if (is_list_ctor (dg))
30245 	  list_cands = lookup_add (dg, list_cands);
30246       }
30247   if (list_cands)
30248     {
30249       fndecl = perform_dguide_overload_resolution (list_cands, args, tf_none);
30250 
30251       if (fndecl == error_mark_node)
30252 	{
30253 	  /* That didn't work, now try treating the list as a sequence of
30254 	     arguments.  */
30255 	  release_tree_vector (args);
30256 	  args = make_tree_vector_from_ctor (init);
30257 	}
30258     }
30259 
30260   if (elided && !cands)
30261     {
30262       error ("cannot deduce template arguments for copy-initialization"
30263 	     " of %qT, as it has no non-explicit deduction guides or "
30264 	     "user-declared constructors", type);
30265       return error_mark_node;
30266     }
30267   else if (!cands && fndecl == error_mark_node)
30268     {
30269       error ("cannot deduce template arguments of %qT, as it has no viable "
30270 	     "deduction guides", type);
30271       return error_mark_node;
30272     }
30273 
30274   if (fndecl == error_mark_node)
30275     fndecl = perform_dguide_overload_resolution (cands, args, tf_none);
30276 
30277   if (fndecl == error_mark_node)
30278     {
30279       if (complain & tf_warning_or_error)
30280 	{
30281 	  error ("class template argument deduction failed:");
30282 	  perform_dguide_overload_resolution (cands, args, complain);
30283 	  if (elided)
30284 	    inform (input_location, "explicit deduction guides not considered "
30285 		    "for copy-initialization");
30286 	}
30287       return error_mark_node;
30288     }
30289   /* [over.match.list]/1: In copy-list-initialization, if an explicit
30290      constructor is chosen, the initialization is ill-formed.  */
30291   else if (flags & LOOKUP_ONLYCONVERTING)
30292     {
30293       if (DECL_NONCONVERTING_P (fndecl))
30294 	{
30295 	  if (complain & tf_warning_or_error)
30296 	    {
30297 	      // TODO: Pass down location from cp_finish_decl.
30298 	      error ("class template argument deduction for %qT failed: "
30299 		     "explicit deduction guide selected in "
30300 		     "copy-list-initialization", type);
30301 	      inform (DECL_SOURCE_LOCATION (fndecl),
30302 		      "explicit deduction guide declared here");
30303 
30304 	    }
30305 	  return error_mark_node;
30306 	}
30307     }
30308 
30309   /* If CTAD succeeded but the type doesn't have any explicit deduction
30310      guides, this deduction might not be what the user intended.  */
30311   if (fndecl != error_mark_node && !any_dguides_p && (complain & tf_warning))
30312     {
30313       if ((!DECL_IN_SYSTEM_HEADER (fndecl)
30314 	   || global_dc->dc_warn_system_headers)
30315 	  && warning (OPT_Wctad_maybe_unsupported,
30316 		      "%qT may not intend to support class template argument "
30317 		      "deduction", type))
30318 	inform (input_location, "add a deduction guide to suppress this "
30319 		"warning");
30320     }
30321 
30322   return cp_build_qualified_type (TREE_TYPE (TREE_TYPE (fndecl)),
30323 				  cp_type_quals (ptype));
30324 }
30325 
30326 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
30327    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
30328    The CONTEXT determines the context in which auto deduction is performed
30329    and is used to control error diagnostics.  FLAGS are the LOOKUP_* flags.
30330 
30331    OUTER_TARGS is used during template argument deduction (context == adc_unify)
30332    to properly substitute the result.  It's also used in the adc_unify and
30333    adc_requirement contexts to communicate the necessary template arguments
30334    to satisfaction.  OUTER_TARGS is ignored in other contexts.
30335 
30336    Additionally for adc_unify contexts TMPL is the template for which TYPE
30337    is a template parameter type.
30338 
30339    For partial-concept-ids, extra args from OUTER_TARGS, TMPL and the current
30340    scope may be appended to the list of deduced template arguments prior to
30341    determining constraint satisfaction as appropriate.  */
30342 
30343 tree
do_auto_deduction(tree type,tree init,tree auto_node,tsubst_flags_t complain,auto_deduction_context context,tree outer_targs,int flags,tree tmpl)30344 do_auto_deduction (tree type, tree init, tree auto_node,
30345 		   tsubst_flags_t complain /* = tf_warning_or_error */,
30346 		   auto_deduction_context context /* = adc_unspecified */,
30347 		   tree outer_targs /* = NULL_TREE */,
30348 		   int flags /* = LOOKUP_NORMAL */,
30349 		   tree tmpl /* = NULL_TREE */)
30350 {
30351   if (init == error_mark_node)
30352     return error_mark_node;
30353 
30354   if (init && type_dependent_expression_p (init)
30355       && context != adc_unify)
30356     /* Defining a subset of type-dependent expressions that we can deduce
30357        from ahead of time isn't worth the trouble.  */
30358     return type;
30359 
30360   /* Similarly, we can't deduce from another undeduced decl.  */
30361   if (init && undeduced_auto_decl (init))
30362     return type;
30363 
30364   /* We may be doing a partial substitution, but we still want to replace
30365      auto_node.  */
30366   complain &= ~tf_partial;
30367 
30368   if (tree ctmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
30369     /* C++17 class template argument deduction.  */
30370     return do_class_deduction (type, ctmpl, init, flags, complain);
30371 
30372   if (init == NULL_TREE || TREE_TYPE (init) == NULL_TREE)
30373     /* Nothing we can do with this, even in deduction context.  */
30374     return type;
30375 
30376   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
30377      with either a new invented type template parameter U or, if the
30378      initializer is a braced-init-list (8.5.4), with
30379      std::initializer_list<U>.  */
30380   if (BRACE_ENCLOSED_INITIALIZER_P (init))
30381     {
30382       if (!DIRECT_LIST_INIT_P (init))
30383 	type = listify_autos (type, auto_node);
30384       else if (CONSTRUCTOR_NELTS (init) == 1)
30385 	init = CONSTRUCTOR_ELT (init, 0)->value;
30386       else
30387 	{
30388           if (complain & tf_warning_or_error)
30389             {
30390 	      if (permerror (input_location, "direct-list-initialization of "
30391 			     "%<auto%> requires exactly one element"))
30392 	        inform (input_location,
30393 		        "for deduction to %<std::initializer_list%>, use copy-"
30394 		        "list-initialization (i.e. add %<=%> before the %<{%>)");
30395             }
30396 	  type = listify_autos (type, auto_node);
30397 	}
30398     }
30399 
30400   if (type == error_mark_node)
30401     return error_mark_node;
30402 
30403   if (BRACE_ENCLOSED_INITIALIZER_P (init))
30404     {
30405       /* We don't recurse here because we can't deduce from a nested
30406 	 initializer_list.  */
30407       if (CONSTRUCTOR_ELTS (init))
30408 	for (constructor_elt &elt : CONSTRUCTOR_ELTS (init))
30409 	  elt.value = resolve_nondeduced_context (elt.value, complain);
30410     }
30411   else
30412     init = resolve_nondeduced_context (init, complain);
30413 
30414   tree targs;
30415   if (context == adc_decomp_type
30416       && auto_node == type
30417       && init != error_mark_node
30418       && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
30419     {
30420       /* [dcl.struct.bind]/1 - if decomposition declaration has no ref-qualifiers
30421 	 and initializer has array type, deduce cv-qualified array type.  */
30422       targs = make_tree_vec (1);
30423       TREE_VEC_ELT (targs, 0) = TREE_TYPE (init);
30424     }
30425   else if (AUTO_IS_DECLTYPE (auto_node))
30426     {
30427       /* Figure out if INIT is an unparenthesized id-expression or an
30428 	 unparenthesized class member access.  */
30429       tree stripped_init = tree_strip_any_location_wrapper (init);
30430       /* We need to be able to tell '(r)' and 'r' apart (when it's of
30431 	 reference type).  Only the latter is an id-expression.  */
30432       if (REFERENCE_REF_P (stripped_init)
30433 	  && !REF_PARENTHESIZED_P (stripped_init))
30434 	stripped_init = TREE_OPERAND (stripped_init, 0);
30435       const bool id = (DECL_P (stripped_init)
30436 		       || ((TREE_CODE (stripped_init) == COMPONENT_REF
30437 			    || TREE_CODE (stripped_init) == SCOPE_REF)
30438 			   && !REF_PARENTHESIZED_P (stripped_init)));
30439       tree deduced = finish_decltype_type (init, id, complain);
30440       deduced = canonicalize_type_argument (deduced, complain);
30441       if (deduced == error_mark_node)
30442 	return error_mark_node;
30443       targs = make_tree_vec (1);
30444       TREE_VEC_ELT (targs, 0) = deduced;
30445     }
30446   else
30447     {
30448       if (error_operand_p (init))
30449 	return error_mark_node;
30450 
30451       tree parms = build_tree_list (NULL_TREE, type);
30452       tree tparms;
30453 
30454       if (flag_concepts_ts)
30455 	tparms = extract_autos (type);
30456       else
30457 	{
30458 	  tparms = make_tree_vec (1);
30459 	  TREE_VEC_ELT (tparms, 0)
30460 	    = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
30461 	}
30462 
30463       targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
30464       int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
30465 				       DEDUCE_CALL,
30466 				       NULL, /*explain_p=*/false);
30467       if (val > 0)
30468 	{
30469 	  if (processing_template_decl)
30470 	    /* Try again at instantiation time.  */
30471 	    return type;
30472 	  if (type && type != error_mark_node
30473 	      && (complain & tf_error))
30474 	    /* If type is error_mark_node a diagnostic must have been
30475 	       emitted by now.  Also, having a mention to '<type error>'
30476 	       in the diagnostic is not really useful to the user.  */
30477 	    {
30478 	      if (cfun
30479 		  && FNDECL_USED_AUTO (current_function_decl)
30480 		  && (auto_node
30481 		      == DECL_SAVED_AUTO_RETURN_TYPE (current_function_decl))
30482 		  && LAMBDA_FUNCTION_P (current_function_decl))
30483 		error ("unable to deduce lambda return type from %qE", init);
30484 	      else
30485 		error ("unable to deduce %qT from %qE", type, init);
30486 	      type_unification_real (tparms, targs, parms, &init, 1, 0,
30487 				     DEDUCE_CALL,
30488 				     NULL, /*explain_p=*/true);
30489 	    }
30490 	  return error_mark_node;
30491 	}
30492     }
30493 
30494   /* Check any placeholder constraints against the deduced type. */
30495   if (processing_template_decl && context == adc_unify)
30496     /* Constraints will be checked after deduction.  */;
30497   else if (tree constr = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (auto_node)))
30498     {
30499       if (processing_template_decl)
30500 	{
30501 	  gcc_checking_assert (context == adc_variable_type
30502 			       || context == adc_return_type
30503 			       || context == adc_decomp_type);
30504 	  gcc_checking_assert (!type_dependent_expression_p (init));
30505 	  /* If the constraint is dependent, we need to wait until
30506 	     instantiation time to resolve the placeholder.  */
30507 	  if (placeholder_type_constraint_dependent_p (constr))
30508 	    return type;
30509 	}
30510 
30511       if (context == adc_return_type
30512 	  || context == adc_variable_type
30513 	  || context == adc_decomp_type)
30514 	if (tree fn = current_function_decl)
30515 	  if (DECL_TEMPLATE_INFO (fn) || LAMBDA_FUNCTION_P (fn))
30516 	    {
30517 	      outer_targs = DECL_TEMPLATE_INFO (fn)
30518 		? DECL_TI_ARGS (fn) : NULL_TREE;
30519 	      if (LAMBDA_FUNCTION_P (fn))
30520 		{
30521 		  /* As in satisfy_declaration_constraints.  */
30522 		  tree regen_args = lambda_regenerating_args (fn);
30523 		  if (outer_targs)
30524 		    outer_targs = add_to_template_args (regen_args, outer_targs);
30525 		  else
30526 		    outer_targs = regen_args;
30527 		}
30528 	    }
30529 
30530       tree full_targs = outer_targs;
30531       if (context == adc_unify && tmpl)
30532 	full_targs = add_outermost_template_args (tmpl, full_targs);
30533       full_targs = add_to_template_args (full_targs, targs);
30534 
30535       /* HACK: Compensate for callers not always communicating all levels of
30536 	 outer template arguments by filling in the outermost missing levels
30537 	 with dummy levels before checking satisfaction.  We'll still crash
30538 	 if the constraint depends on a template argument belonging to one of
30539 	 these missing levels, but this hack otherwise allows us to handle a
30540 	 large subset of possible constraints (including all non-dependent
30541 	 constraints).  */
30542       if (int missing_levels = (TEMPLATE_TYPE_ORIG_LEVEL (auto_node)
30543 				- TMPL_ARGS_DEPTH (full_targs)))
30544 	{
30545 	  tree dummy_levels = make_tree_vec (missing_levels);
30546 	  for (int i = 0; i < missing_levels; ++i)
30547 	    TREE_VEC_ELT (dummy_levels, i) = make_tree_vec (0);
30548 	  full_targs = add_to_template_args (dummy_levels, full_targs);
30549 	}
30550 
30551       if (!constraints_satisfied_p (auto_node, full_targs))
30552 	{
30553 	  if (complain & tf_warning_or_error)
30554 	    {
30555 	      auto_diagnostic_group d;
30556 	      switch (context)
30557 		{
30558 		case adc_unspecified:
30559 		case adc_unify:
30560 		  error("placeholder constraints not satisfied");
30561 		  break;
30562 		case adc_variable_type:
30563 		case adc_decomp_type:
30564 		  error ("deduced initializer does not satisfy "
30565 			 "placeholder constraints");
30566 		  break;
30567 		case adc_return_type:
30568 		  error ("deduced return type does not satisfy "
30569 			 "placeholder constraints");
30570 		  break;
30571 		case adc_requirement:
30572 		  error ("deduced expression type does not satisfy "
30573 			 "placeholder constraints");
30574 		  break;
30575 		}
30576 	      diagnose_constraints (input_location, auto_node, full_targs);
30577 	    }
30578 	  return error_mark_node;
30579 	}
30580     }
30581 
30582   if (TEMPLATE_TYPE_LEVEL (auto_node) == 1)
30583     /* The outer template arguments are already substituted into type
30584        (but we still may have used them for constraint checking above).  */;
30585   else if (context == adc_unify)
30586     targs = add_to_template_args (outer_targs, targs);
30587   else if (processing_template_decl)
30588     targs = add_to_template_args (current_template_args (), targs);
30589   return tsubst (type, targs, complain, NULL_TREE);
30590 }
30591 
30592 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
30593    result.  */
30594 
30595 tree
splice_late_return_type(tree type,tree late_return_type)30596 splice_late_return_type (tree type, tree late_return_type)
30597 {
30598   if (late_return_type)
30599     {
30600       gcc_assert (is_auto (type) || seen_error ());
30601       return late_return_type;
30602     }
30603 
30604   if (tree auto_node = find_type_usage (type, is_auto))
30605     if (TEMPLATE_TYPE_LEVEL (auto_node) <= current_template_depth)
30606       {
30607 	/* In an abbreviated function template we didn't know we were dealing
30608 	   with a function template when we saw the auto return type, so rebuild
30609 	   the return type using an auto with the correct level.  */
30610 	tree new_auto = make_auto_1 (TYPE_IDENTIFIER (auto_node), false);
30611 	tree auto_vec = make_tree_vec (1);
30612 	TREE_VEC_ELT (auto_vec, 0) = new_auto;
30613 	tree targs = add_outermost_template_args (current_template_args (),
30614 						  auto_vec);
30615 	/* Also rebuild the constraint info in terms of the new auto.  */
30616 	if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (auto_node))
30617 	  PLACEHOLDER_TYPE_CONSTRAINTS_INFO (new_auto)
30618 	    = build_tree_list (current_template_parms,
30619 			       tsubst_constraint (TREE_VALUE (ci), targs,
30620 						  tf_none, NULL_TREE));
30621 	TYPE_CANONICAL (new_auto) = canonical_type_parameter (new_auto);
30622 	return tsubst (type, targs, tf_none, NULL_TREE);
30623       }
30624   return type;
30625 }
30626 
30627 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
30628    'decltype(auto)' or a deduced class template.  */
30629 
30630 bool
is_auto(const_tree type)30631 is_auto (const_tree type)
30632 {
30633   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
30634       && (TYPE_IDENTIFIER (type) == auto_identifier
30635 	  || TYPE_IDENTIFIER (type) == decltype_auto_identifier))
30636     return true;
30637   else
30638     return false;
30639 }
30640 
30641 /* for_each_template_parm callback for type_uses_auto.  */
30642 
30643 int
is_auto_r(tree tp,void *)30644 is_auto_r (tree tp, void */*data*/)
30645 {
30646   return is_auto (tp);
30647 }
30648 
30649 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
30650    a use of `auto'.  Returns NULL_TREE otherwise.  */
30651 
30652 tree
type_uses_auto(tree type)30653 type_uses_auto (tree type)
30654 {
30655   if (type == NULL_TREE)
30656     return NULL_TREE;
30657   else if (flag_concepts_ts)
30658     {
30659       /* The Concepts TS allows multiple autos in one type-specifier; just
30660 	 return the first one we find, do_auto_deduction will collect all of
30661 	 them.  */
30662       if (uses_template_parms (type))
30663 	return for_each_template_parm (type, is_auto_r, /*data*/NULL,
30664 				       /*visited*/NULL, /*nondeduced*/false);
30665       else
30666 	return NULL_TREE;
30667     }
30668   else
30669     return find_type_usage (type, is_auto);
30670 }
30671 
30672 /* Report ill-formed occurrences of auto types in ARGUMENTS.  If
30673    concepts are enabled, auto is acceptable in template arguments, but
30674    only when TEMPL identifies a template class.  Return TRUE if any
30675    such errors were reported.  */
30676 
30677 bool
check_auto_in_tmpl_args(tree tmpl,tree args)30678 check_auto_in_tmpl_args (tree tmpl, tree args)
30679 {
30680   if (!flag_concepts_ts)
30681     /* Only the concepts TS allows 'auto' as a type-id; it'd otherwise
30682        have already been rejected by the parser more generally.  */
30683     return false;
30684 
30685   /* If there were previous errors, nevermind.  */
30686   if (!args || TREE_CODE (args) != TREE_VEC)
30687     return false;
30688 
30689   /* If TMPL is an identifier, we're parsing and we can't tell yet
30690      whether TMPL is supposed to be a type, a function or a variable.
30691      We'll only be able to tell during template substitution, so we
30692      expect to be called again then.  If concepts are enabled and we
30693      know we have a type, we're ok.  */
30694   if (identifier_p (tmpl)
30695       || (DECL_P (tmpl)
30696 	  &&  (DECL_TYPE_TEMPLATE_P (tmpl)
30697 	       || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))))
30698     return false;
30699 
30700   /* Quickly search for any occurrences of auto; usually there won't
30701      be any, and then we'll avoid allocating the vector.  */
30702   if (!type_uses_auto (args))
30703     return false;
30704 
30705   bool errors = false;
30706 
30707   tree vec = extract_autos (args);
30708   for (int i = 0; i < TREE_VEC_LENGTH (vec); i++)
30709     {
30710       tree xauto = TREE_VALUE (TREE_VEC_ELT (vec, i));
30711       error_at (DECL_SOURCE_LOCATION (xauto),
30712 		"invalid use of %qT in template argument", xauto);
30713       errors = true;
30714     }
30715 
30716   return errors;
30717 }
30718 
30719 /* Recursively walk over && expressions searching for EXPR. Return a reference
30720    to that expression.  */
30721 
find_template_requirement(tree * t,tree key)30722 static tree *find_template_requirement (tree *t, tree key)
30723 {
30724   if (*t == key)
30725     return t;
30726   if (TREE_CODE (*t) == TRUTH_ANDIF_EXPR)
30727     {
30728       if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 0), key))
30729 	return p;
30730       if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 1), key))
30731 	return p;
30732     }
30733   return 0;
30734 }
30735 
30736 /* Convert the generic type parameters in PARM that match the types given in the
30737    range [START_IDX, END_IDX) from the current_template_parms into generic type
30738    packs.  */
30739 
30740 tree
convert_generic_types_to_packs(tree parm,int start_idx,int end_idx)30741 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
30742 {
30743   tree current = current_template_parms;
30744   int depth = TMPL_PARMS_DEPTH (current);
30745   current = INNERMOST_TEMPLATE_PARMS (current);
30746   tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
30747 
30748   for (int i = 0; i < start_idx; ++i)
30749     TREE_VEC_ELT (replacement, i)
30750       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
30751 
30752   for (int i = start_idx; i < end_idx; ++i)
30753     {
30754       /* Create a distinct parameter pack type from the current parm and add it
30755 	 to the replacement args to tsubst below into the generic function
30756 	 parameter.  */
30757       tree node = TREE_VEC_ELT (current, i);
30758       tree o = TREE_TYPE (TREE_VALUE (node));
30759       tree t = copy_type (o);
30760       TEMPLATE_TYPE_PARM_INDEX (t)
30761 	= reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
30762 				      t, 0, 0, tf_none);
30763       TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
30764       TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
30765       TYPE_MAIN_VARIANT (t) = t;
30766       TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
30767       TYPE_CANONICAL (t) = canonical_type_parameter (t);
30768       TREE_VEC_ELT (replacement, i) = t;
30769 
30770       /* Replace the current template parameter with new pack.  */
30771       TREE_VALUE (node) = TREE_CHAIN (t);
30772 
30773       /* Surgically adjust the associated constraint of adjusted parameter
30774          and it's corresponding contribution to the current template
30775          requirements.  */
30776       if (tree constr = TEMPLATE_PARM_CONSTRAINTS (node))
30777 	{
30778 	  tree id = unpack_concept_check (constr);
30779 	  TREE_VEC_ELT (TREE_OPERAND (id, 1), 0) = t;
30780 	  tree fold = finish_left_unary_fold_expr (constr, TRUTH_ANDIF_EXPR);
30781 	  TEMPLATE_PARM_CONSTRAINTS (node) = fold;
30782 
30783 	  /* If there was a constraint, we also need to replace that in
30784 	     the template requirements, which we've already built.  */
30785 	  tree *reqs = &TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
30786 	  reqs = find_template_requirement (reqs, constr);
30787 	  *reqs = fold;
30788 	}
30789     }
30790 
30791   for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
30792     TREE_VEC_ELT (replacement, i)
30793       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
30794 
30795   /* If there are more levels then build up the replacement with the outer
30796      template parms.  */
30797   if (depth > 1)
30798     replacement = add_to_template_args (template_parms_to_args
30799 					(TREE_CHAIN (current_template_parms)),
30800 					replacement);
30801 
30802   return tsubst (parm, replacement, tf_none, NULL_TREE);
30803 }
30804 
30805 /* __integer_pack(N) in a pack expansion expands to a sequence of numbers from
30806    0..N-1.  */
30807 
30808 void
declare_integer_pack(void)30809 declare_integer_pack (void)
30810 {
30811   tree ipfn = push_library_fn (get_identifier ("__integer_pack"),
30812 			       build_function_type_list (integer_type_node,
30813 							 integer_type_node,
30814 							 NULL_TREE),
30815 			       NULL_TREE, ECF_CONST);
30816   DECL_DECLARED_CONSTEXPR_P (ipfn) = true;
30817   set_decl_built_in_function (ipfn, BUILT_IN_FRONTEND,
30818 			      CP_BUILT_IN_INTEGER_PACK);
30819 }
30820 
30821 /* Walk the decl or type specialization table calling FN on each
30822    entry.  */
30823 
30824 void
walk_specializations(bool decls_p,void (* fn)(bool decls_p,spec_entry * entry,void * data),void * data)30825 walk_specializations (bool decls_p,
30826 		      void (*fn) (bool decls_p, spec_entry *entry, void *data),
30827 		      void *data)
30828 {
30829   spec_hash_table *table = decls_p ? decl_specializations
30830     : type_specializations;
30831   spec_hash_table::iterator end (table->end ());
30832   for (spec_hash_table::iterator iter (table->begin ()); iter != end; ++iter)
30833     fn (decls_p, *iter, data);
30834 }
30835 
30836 /* Lookup the specialization of *ELT, in the decl or type
30837    specialization table.  Return the SPEC that's already there, or
30838    NULL if nothing.  */
30839 
30840 tree
match_mergeable_specialization(bool decl_p,spec_entry * elt)30841 match_mergeable_specialization (bool decl_p, spec_entry *elt)
30842 {
30843   hash_table<spec_hasher> *specializations
30844     = decl_p ? decl_specializations : type_specializations;
30845   hashval_t hash = spec_hasher::hash (elt);
30846   auto *slot = specializations->find_slot_with_hash (elt, hash, NO_INSERT);
30847 
30848   if (slot)
30849     return (*slot)->spec;
30850 
30851   return NULL_TREE;
30852 }
30853 
30854 /* Return flags encoding whether SPEC is on the instantiation and/or
30855    specialization lists of TMPL.  */
30856 
30857 unsigned
get_mergeable_specialization_flags(tree tmpl,tree decl)30858 get_mergeable_specialization_flags (tree tmpl, tree decl)
30859 {
30860   unsigned flags = 0;
30861 
30862   for (tree inst = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
30863        inst; inst = TREE_CHAIN (inst))
30864     if (TREE_VALUE (inst) == decl)
30865       {
30866 	flags |= 1;
30867 	break;
30868       }
30869 
30870   if (CLASS_TYPE_P (TREE_TYPE (decl))
30871       && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl))
30872       && CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)) == 2)
30873     /* Only need to search if DECL is a partial specialization.  */
30874     for (tree part = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
30875 	 part; part = TREE_CHAIN (part))
30876       if (TREE_VALUE (part) == decl)
30877 	{
30878 	  flags |= 2;
30879 	  break;
30880 	}
30881 
30882   return flags;
30883 }
30884 
30885 /* Add a new specialization described by SPEC.  DECL is the
30886    maybe-template decl and FLAGS is as returned from
30887    get_mergeable_specialization_flags.  */
30888 
30889 void
add_mergeable_specialization(bool decl_p,bool alias_p,spec_entry * elt,tree decl,unsigned flags)30890 add_mergeable_specialization (bool decl_p, bool alias_p, spec_entry *elt,
30891 			      tree decl, unsigned flags)
30892 {
30893   hashval_t hash = spec_hasher::hash (elt);
30894   if (decl_p)
30895     {
30896       auto *slot = decl_specializations->find_slot_with_hash (elt, hash, INSERT);
30897 
30898       gcc_checking_assert (!*slot);
30899       auto entry = ggc_alloc<spec_entry> ();
30900       *entry = *elt;
30901       *slot = entry;
30902 
30903       if (alias_p)
30904 	{
30905 	  elt->spec = TREE_TYPE (elt->spec);
30906 	  gcc_checking_assert (elt->spec);
30907 	}
30908     }
30909 
30910   if (!decl_p || alias_p)
30911     {
30912       auto *slot = type_specializations->find_slot_with_hash (elt, hash, INSERT);
30913 
30914       /* We don't distinguish different constrained partial type
30915 	 specializations, so there could be duplicates.  Everything else
30916 	 must be new.   */
30917       if (!(flags & 2 && *slot))
30918 	{
30919 	  gcc_checking_assert (!*slot);
30920 
30921 	  auto entry = ggc_alloc<spec_entry> ();
30922 	  *entry = *elt;
30923 	  *slot = entry;
30924 	}
30925     }
30926 
30927   if (flags & 1)
30928     DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl)
30929       = tree_cons (elt->args, decl, DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl));
30930 
30931   if (flags & 2)
30932     {
30933       /* A partial specialization.  */
30934       tree cons = tree_cons (elt->args, decl,
30935 			     DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl));
30936       TREE_TYPE (cons) = elt->spec;
30937       DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl) = cons;
30938     }
30939 }
30940 
30941 /* Set up the hash tables for template instantiations.  */
30942 
30943 void
init_template_processing(void)30944 init_template_processing (void)
30945 {
30946   decl_specializations = hash_table<spec_hasher>::create_ggc (37);
30947   type_specializations = hash_table<spec_hasher>::create_ggc (37);
30948 
30949   if (cxx_dialect >= cxx11)
30950     declare_integer_pack ();
30951 }
30952 
30953 /* Print stats about the template hash tables for -fstats.  */
30954 
30955 void
print_template_statistics(void)30956 print_template_statistics (void)
30957 {
30958   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
30959 	   "%f collisions\n", (long) decl_specializations->size (),
30960 	   (long) decl_specializations->elements (),
30961 	   decl_specializations->collisions ());
30962   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
30963 	   "%f collisions\n", (long) type_specializations->size (),
30964 	   (long) type_specializations->elements (),
30965 	   type_specializations->collisions ());
30966 }
30967 
30968 #if CHECKING_P
30969 
30970 namespace selftest {
30971 
30972 /* Verify that build_non_dependent_expr () works, for various expressions,
30973    and that location wrappers don't affect the results.  */
30974 
30975 static void
test_build_non_dependent_expr()30976 test_build_non_dependent_expr ()
30977 {
30978   location_t loc = BUILTINS_LOCATION;
30979 
30980   /* Verify constants, without and with location wrappers.  */
30981   tree int_cst = build_int_cst (integer_type_node, 42);
30982   ASSERT_EQ (int_cst, build_non_dependent_expr (int_cst));
30983 
30984   tree wrapped_int_cst = maybe_wrap_with_location (int_cst, loc);
30985   ASSERT_TRUE (location_wrapper_p (wrapped_int_cst));
30986   ASSERT_EQ (wrapped_int_cst, build_non_dependent_expr (wrapped_int_cst));
30987 
30988   tree string_lit = build_string (4, "foo");
30989   TREE_TYPE (string_lit) = char_array_type_node;
30990   string_lit = fix_string_type (string_lit);
30991   ASSERT_EQ (string_lit, build_non_dependent_expr (string_lit));
30992 
30993   tree wrapped_string_lit = maybe_wrap_with_location (string_lit, loc);
30994   ASSERT_TRUE (location_wrapper_p (wrapped_string_lit));
30995   ASSERT_EQ (wrapped_string_lit,
30996 	     build_non_dependent_expr (wrapped_string_lit));
30997 }
30998 
30999 /* Verify that type_dependent_expression_p () works correctly, even
31000    in the presence of location wrapper nodes.  */
31001 
31002 static void
test_type_dependent_expression_p()31003 test_type_dependent_expression_p ()
31004 {
31005   location_t loc = BUILTINS_LOCATION;
31006 
31007   tree name = get_identifier ("foo");
31008 
31009   /* If no templates are involved, nothing is type-dependent.  */
31010   gcc_assert (!processing_template_decl);
31011   ASSERT_FALSE (type_dependent_expression_p (name));
31012 
31013   ++processing_template_decl;
31014 
31015   /* Within a template, an unresolved name is always type-dependent.  */
31016   ASSERT_TRUE (type_dependent_expression_p (name));
31017 
31018   /* Ensure it copes with NULL_TREE and errors.  */
31019   ASSERT_FALSE (type_dependent_expression_p (NULL_TREE));
31020   ASSERT_FALSE (type_dependent_expression_p (error_mark_node));
31021 
31022   /* A USING_DECL in a template should be type-dependent, even if wrapped
31023      with a location wrapper (PR c++/83799).  */
31024   tree using_decl = build_lang_decl (USING_DECL, name, NULL_TREE);
31025   TREE_TYPE (using_decl) = integer_type_node;
31026   ASSERT_TRUE (type_dependent_expression_p (using_decl));
31027   tree wrapped_using_decl = maybe_wrap_with_location (using_decl, loc);
31028   ASSERT_TRUE (location_wrapper_p (wrapped_using_decl));
31029   ASSERT_TRUE (type_dependent_expression_p (wrapped_using_decl));
31030 
31031   --processing_template_decl;
31032 }
31033 
31034 /* Run all of the selftests within this file.  */
31035 
31036 void
cp_pt_cc_tests()31037 cp_pt_cc_tests ()
31038 {
31039   test_build_non_dependent_expr ();
31040   test_type_dependent_expression_p ();
31041 }
31042 
31043 } // namespace selftest
31044 
31045 #endif /* #if CHECKING_P */
31046 
31047 #include "gt-cp-pt.h"
31048