1 /* Handle parameterized types (templates) for GNU -*- C++ -*-.
2    Copyright (C) 1992-2021 Free Software Foundation, Inc.
3    Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
4    Rewritten by Jason Merrill (jason@cygnus.com).
5 
6 This file is part of GCC.
7 
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
12 
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17 
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21 
22 /* Known bugs or deficiencies include:
23 
24      all methods must be provided in header files; can't use a source
25      file that contains only the method templates and "just win".
26 
27      Fixed by: C++20 modules.  */
28 
29 #include "config.h"
30 #include "system.h"
31 #include "coretypes.h"
32 #include "cp-tree.h"
33 #include "timevar.h"
34 #include "stringpool.h"
35 #include "varasm.h"
36 #include "attribs.h"
37 #include "stor-layout.h"
38 #include "intl.h"
39 #include "c-family/c-objc.h"
40 #include "cp-objcp-common.h"
41 #include "toplev.h"
42 #include "tree-iterator.h"
43 #include "type-utils.h"
44 #include "gimplify.h"
45 #include "gcc-rich-location.h"
46 #include "selftest.h"
47 #include "target.h"
48 
49 /* The type of functions taking a tree, and some additional data, and
50    returning an int.  */
51 typedef int (*tree_fn_t) (tree, void*);
52 
53 /* The PENDING_TEMPLATES is a list of templates whose instantiations
54    have been deferred, either because their definitions were not yet
55    available, or because we were putting off doing the work.  */
56 struct GTY ((chain_next ("%h.next"))) pending_template
57 {
58   struct pending_template *next;
59   struct tinst_level *tinst;
60 };
61 
62 static GTY(()) struct pending_template *pending_templates;
63 static GTY(()) struct pending_template *last_pending_template;
64 
65 int processing_template_parmlist;
66 static int template_header_count;
67 
68 static vec<int> inline_parm_levels;
69 
70 static GTY(()) struct tinst_level *current_tinst_level;
71 
72 static GTY(()) vec<tree, va_gc> *saved_access_scope;
73 
74 /* Live only within one (recursive) call to tsubst_expr.  We use
75    this to pass the statement expression node from the STMT_EXPR
76    to the EXPR_STMT that is its result.  */
77 static tree cur_stmt_expr;
78 
79 // -------------------------------------------------------------------------- //
80 // Local Specialization Stack
81 //
82 // Implementation of the RAII helper for creating new local
83 // specializations.
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, int, int,
156 					   struct conversion **, bool);
157 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
158 					     tree);
159 static int type_unification_real (tree, tree, tree, const tree *,
160 				  unsigned int, int, unification_kind_t,
161 				  vec<deferred_access_check, va_gc> **,
162 				  bool);
163 static void note_template_header (int);
164 static tree convert_nontype_argument_function (tree, tree, tsubst_flags_t);
165 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
166 static tree convert_template_argument (tree, tree, tree,
167 				       tsubst_flags_t, int, tree);
168 static tree for_each_template_parm (tree, tree_fn_t, void*,
169 				    hash_set<tree> *, bool, tree_fn_t = NULL);
170 static tree expand_template_argument_pack (tree);
171 static tree build_template_parm_index (int, int, int, tree, tree);
172 static bool inline_needs_template_parms (tree, bool);
173 static void push_inline_template_parms_recursive (tree, int);
174 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
175 static int mark_template_parm (tree, void *);
176 static int template_parm_this_level_p (tree, void *);
177 static tree tsubst_friend_function (tree, tree);
178 static tree tsubst_friend_class (tree, tree);
179 static int can_complete_type_without_circularity (tree);
180 static tree get_bindings (tree, tree, tree, bool);
181 static int template_decl_level (tree);
182 static int check_cv_quals_for_unify (int, tree, tree);
183 static int unify_pack_expansion (tree, tree, tree,
184 				 tree, unification_kind_t, bool, bool);
185 static tree copy_template_args (tree);
186 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
187 tree most_specialized_partial_spec (tree, tsubst_flags_t);
188 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
189 static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
190 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
191 static bool check_specialization_scope (void);
192 static tree process_partial_specialization (tree);
193 static enum template_base_result get_template_base (tree, tree, tree, tree,
194 						    bool , tree *);
195 static tree try_class_unification (tree, tree, tree, tree, bool);
196 static bool class_nttp_const_wrapper_p (tree t);
197 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
198 					   tree, tree);
199 static bool template_template_parm_bindings_ok_p (tree, tree);
200 static void tsubst_default_arguments (tree, tsubst_flags_t);
201 static tree for_each_template_parm_r (tree *, int *, void *);
202 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
203 static void copy_default_args_to_explicit_spec (tree);
204 static bool invalid_nontype_parm_type_p (tree, tsubst_flags_t);
205 static bool dependent_template_arg_p (tree);
206 static bool any_template_arguments_need_structural_equality_p (tree);
207 static bool dependent_type_p_r (tree);
208 static tree tsubst_copy	(tree, tree, tsubst_flags_t, tree);
209 static tree tsubst_decl (tree, tree, tsubst_flags_t);
210 static void perform_instantiation_time_access_checks (tree, tree);
211 static tree listify (tree);
212 static tree listify_autos (tree, tree);
213 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
214 static tree instantiate_alias_template (tree, tree, tsubst_flags_t);
215 static bool complex_alias_template_p (const_tree tmpl);
216 static tree get_underlying_template (tree);
217 static tree tsubst_attributes (tree, tree, tsubst_flags_t, tree);
218 static tree canonicalize_expr_argument (tree, tsubst_flags_t);
219 static tree make_argument_pack (tree);
220 static void register_parameter_specializations (tree, tree);
221 static tree enclosing_instantiation_of (tree tctx);
222 static void instantiate_body (tree pattern, tree args, tree d, bool nested);
223 
224 /* Make the current scope suitable for access checking when we are
225    processing T.  T can be FUNCTION_DECL for instantiated function
226    template, VAR_DECL for static member variable, or TYPE_DECL for
227    alias template (needed by instantiate_decl).  */
228 
229 void
push_access_scope(tree t)230 push_access_scope (tree t)
231 {
232   gcc_assert (VAR_OR_FUNCTION_DECL_P (t)
233 	      || TREE_CODE (t) == TYPE_DECL);
234 
235   if (DECL_FRIEND_CONTEXT (t))
236     push_nested_class (DECL_FRIEND_CONTEXT (t));
237   else if (DECL_CLASS_SCOPE_P (t))
238     push_nested_class (DECL_CONTEXT (t));
239   else
240     push_to_top_level ();
241 
242   if (TREE_CODE (t) == FUNCTION_DECL)
243     {
244       vec_safe_push (saved_access_scope, current_function_decl);
245       current_function_decl = t;
246     }
247 }
248 
249 /* Restore the scope set up by push_access_scope.  T is the node we
250    are processing.  */
251 
252 void
pop_access_scope(tree t)253 pop_access_scope (tree t)
254 {
255   if (TREE_CODE (t) == FUNCTION_DECL)
256     current_function_decl = saved_access_scope->pop();
257 
258   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
259     pop_nested_class ();
260   else
261     pop_from_top_level ();
262 }
263 
264 /* Do any processing required when DECL (a member template
265    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
266    to DECL, unless it is a specialization, in which case the DECL
267    itself is returned.  */
268 
269 tree
finish_member_template_decl(tree decl)270 finish_member_template_decl (tree decl)
271 {
272   if (decl == error_mark_node)
273     return error_mark_node;
274 
275   gcc_assert (DECL_P (decl));
276 
277   if (TREE_CODE (decl) == TYPE_DECL)
278     {
279       tree type;
280 
281       type = TREE_TYPE (decl);
282       if (type == error_mark_node)
283 	return error_mark_node;
284       if (MAYBE_CLASS_TYPE_P (type)
285 	  && CLASSTYPE_TEMPLATE_INFO (type)
286 	  && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
287 	{
288 	  tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
289 	  check_member_template (tmpl);
290 	  return tmpl;
291 	}
292       return NULL_TREE;
293     }
294   else if (TREE_CODE (decl) == FIELD_DECL)
295     error_at (DECL_SOURCE_LOCATION (decl),
296 	      "data member %qD cannot be a member template", decl);
297   else if (DECL_TEMPLATE_INFO (decl))
298     {
299       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
300 	{
301 	  check_member_template (DECL_TI_TEMPLATE (decl));
302 	  return DECL_TI_TEMPLATE (decl);
303 	}
304       else
305 	return decl;
306     }
307   else
308     error_at (DECL_SOURCE_LOCATION (decl),
309 	      "invalid member template declaration %qD", decl);
310 
311   return error_mark_node;
312 }
313 
314 /* Create a template info node.  */
315 
316 tree
build_template_info(tree template_decl,tree template_args)317 build_template_info (tree template_decl, tree template_args)
318 {
319   tree result = make_node (TEMPLATE_INFO);
320   TI_TEMPLATE (result) = template_decl;
321   TI_ARGS (result) = template_args;
322   return result;
323 }
324 
325 /* Return the template info node corresponding to T, whatever T is.  */
326 
327 tree
get_template_info(const_tree t)328 get_template_info (const_tree t)
329 {
330   tree tinfo = NULL_TREE;
331 
332   if (!t || t == error_mark_node)
333     return NULL;
334 
335   if (TREE_CODE (t) == NAMESPACE_DECL
336       || TREE_CODE (t) == PARM_DECL)
337     return NULL;
338 
339   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
340     tinfo = DECL_TEMPLATE_INFO (t);
341 
342   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
343     t = TREE_TYPE (t);
344 
345   if (OVERLOAD_TYPE_P (t))
346     tinfo = TYPE_TEMPLATE_INFO (t);
347   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
348     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
349 
350   return tinfo;
351 }
352 
353 /* Returns the template nesting level of the indicated class TYPE.
354 
355    For example, in:
356      template <class T>
357      struct A
358      {
359        template <class U>
360        struct B {};
361      };
362 
363    A<T>::B<U> has depth two, while A<T> has depth one.
364    Both A<T>::B<int> and A<int>::B<U> have depth one, if
365    they are instantiations, not specializations.
366 
367    This function is guaranteed to return 0 if passed NULL_TREE so
368    that, for example, `template_class_depth (current_class_type)' is
369    always safe.  */
370 
371 int
template_class_depth(tree type)372 template_class_depth (tree type)
373 {
374   int depth;
375 
376   for (depth = 0; type && TREE_CODE (type) != NAMESPACE_DECL; )
377     {
378       tree tinfo = get_template_info (type);
379 
380       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
381 	  && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
382 	++depth;
383 
384       if (DECL_P (type))
385 	{
386 	  if (tree fctx = DECL_FRIEND_CONTEXT (type))
387 	    type = fctx;
388 	  else
389 	    type = CP_DECL_CONTEXT (type);
390 	}
391       else if (LAMBDA_TYPE_P (type) && LAMBDA_TYPE_EXTRA_SCOPE (type))
392 	type = LAMBDA_TYPE_EXTRA_SCOPE (type);
393       else
394 	type = CP_TYPE_CONTEXT (type);
395     }
396 
397   return depth;
398 }
399 
400 /* Return TRUE if NODE instantiates a template that has arguments of
401    its own, be it directly a primary template or indirectly through a
402    partial specializations.  */
403 static bool
instantiates_primary_template_p(tree node)404 instantiates_primary_template_p (tree node)
405 {
406   tree tinfo = get_template_info (node);
407   if (!tinfo)
408     return false;
409 
410   tree tmpl = TI_TEMPLATE (tinfo);
411   if (PRIMARY_TEMPLATE_P (tmpl))
412     return true;
413 
414   if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
415     return false;
416 
417   /* So now we know we have a specialization, but it could be a full
418      or a partial specialization.  To tell which, compare the depth of
419      its template arguments with those of its context.  */
420 
421   tree ctxt = DECL_CONTEXT (tmpl);
422   tree ctinfo = get_template_info (ctxt);
423   if (!ctinfo)
424     return true;
425 
426   return (TMPL_ARGS_DEPTH (TI_ARGS (tinfo))
427 	  > TMPL_ARGS_DEPTH (TI_ARGS (ctinfo)));
428 }
429 
430 /* Subroutine of maybe_begin_member_template_processing.
431    Returns true if processing DECL needs us to push template parms.  */
432 
433 static bool
inline_needs_template_parms(tree decl,bool nsdmi)434 inline_needs_template_parms (tree decl, bool nsdmi)
435 {
436   if (!decl || (!nsdmi && ! DECL_TEMPLATE_INFO (decl)))
437     return false;
438 
439   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
440 	  > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
441 }
442 
443 /* Subroutine of maybe_begin_member_template_processing.
444    Push the template parms in PARMS, starting from LEVELS steps into the
445    chain, and ending at the beginning, since template parms are listed
446    innermost first.  */
447 
448 static void
push_inline_template_parms_recursive(tree parmlist,int levels)449 push_inline_template_parms_recursive (tree parmlist, int levels)
450 {
451   tree parms = TREE_VALUE (parmlist);
452   int i;
453 
454   if (levels > 1)
455     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
456 
457   ++processing_template_decl;
458   current_template_parms
459     = tree_cons (size_int (processing_template_decl),
460 		 parms, current_template_parms);
461   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
462 
463   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
464 	       NULL);
465   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
466     {
467       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
468 
469       if (error_operand_p (parm))
470 	continue;
471 
472       gcc_assert (DECL_P (parm));
473 
474       switch (TREE_CODE (parm))
475 	{
476 	case TYPE_DECL:
477 	case TEMPLATE_DECL:
478 	  pushdecl (parm);
479 	  break;
480 
481 	case PARM_DECL:
482 	  /* Push the CONST_DECL.  */
483 	  pushdecl (TEMPLATE_PARM_DECL (DECL_INITIAL (parm)));
484 	  break;
485 
486 	default:
487 	  gcc_unreachable ();
488 	}
489     }
490 }
491 
492 /* Restore the template parameter context for a member template, a
493    friend template defined in a class definition, or a non-template
494    member of template class.  */
495 
496 void
maybe_begin_member_template_processing(tree decl)497 maybe_begin_member_template_processing (tree decl)
498 {
499   tree parms;
500   int levels = 0;
501   bool nsdmi = TREE_CODE (decl) == FIELD_DECL;
502 
503   if (nsdmi)
504     {
505       tree ctx = DECL_CONTEXT (decl);
506       decl = (CLASSTYPE_TEMPLATE_INFO (ctx)
507 	      /* Disregard full specializations (c++/60999).  */
508 	      && uses_template_parms (ctx)
509 	      ? CLASSTYPE_TI_TEMPLATE (ctx) : NULL_TREE);
510     }
511 
512   if (inline_needs_template_parms (decl, nsdmi))
513     {
514       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
515       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
516 
517       if (DECL_TEMPLATE_SPECIALIZATION (decl))
518 	{
519 	  --levels;
520 	  parms = TREE_CHAIN (parms);
521 	}
522 
523       push_inline_template_parms_recursive (parms, levels);
524     }
525 
526   /* Remember how many levels of template parameters we pushed so that
527      we can pop them later.  */
528   inline_parm_levels.safe_push (levels);
529 }
530 
531 /* Undo the effects of maybe_begin_member_template_processing.  */
532 
533 void
maybe_end_member_template_processing(void)534 maybe_end_member_template_processing (void)
535 {
536   int i;
537   int last;
538 
539   if (inline_parm_levels.length () == 0)
540     return;
541 
542   last = inline_parm_levels.pop ();
543   for (i = 0; i < last; ++i)
544     {
545       --processing_template_decl;
546       current_template_parms = TREE_CHAIN (current_template_parms);
547       poplevel (0, 0, 0);
548     }
549 }
550 
551 /* Return a new template argument vector which contains all of ARGS,
552    but has as its innermost set of arguments the EXTRA_ARGS.  */
553 
554 tree
add_to_template_args(tree args,tree extra_args)555 add_to_template_args (tree args, tree extra_args)
556 {
557   tree new_args;
558   int extra_depth;
559   int i;
560   int j;
561 
562   if (args == NULL_TREE || extra_args == error_mark_node)
563     return extra_args;
564 
565   extra_depth = TMPL_ARGS_DEPTH (extra_args);
566   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
567 
568   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
569     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
570 
571   for (j = 1; j <= extra_depth; ++j, ++i)
572     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
573 
574   return new_args;
575 }
576 
577 /* Like add_to_template_args, but only the outermost ARGS are added to
578    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
579    (EXTRA_ARGS) levels are added.  This function is used to combine
580    the template arguments from a partial instantiation with the
581    template arguments used to attain the full instantiation from the
582    partial instantiation.
583 
584    If ARGS is a TEMPLATE_DECL, use its parameters as args.  */
585 
586 tree
add_outermost_template_args(tree args,tree extra_args)587 add_outermost_template_args (tree args, tree extra_args)
588 {
589   tree new_args;
590 
591   if (!args)
592     return extra_args;
593   if (TREE_CODE (args) == TEMPLATE_DECL)
594     {
595       tree ti = get_template_info (DECL_TEMPLATE_RESULT (args));
596       args = TI_ARGS (ti);
597     }
598 
599   /* If there are more levels of EXTRA_ARGS than there are ARGS,
600      something very fishy is going on.  */
601   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
602 
603   /* If *all* the new arguments will be the EXTRA_ARGS, just return
604      them.  */
605   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
606     return extra_args;
607 
608   /* For the moment, we make ARGS look like it contains fewer levels.  */
609   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
610 
611   new_args = add_to_template_args (args, extra_args);
612 
613   /* Now, we restore ARGS to its full dimensions.  */
614   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
615 
616   return new_args;
617 }
618 
619 /* Return the N levels of innermost template arguments from the ARGS.  */
620 
621 tree
get_innermost_template_args(tree args,int n)622 get_innermost_template_args (tree args, int n)
623 {
624   tree new_args;
625   int extra_levels;
626   int i;
627 
628   gcc_assert (n >= 0);
629 
630   /* If N is 1, just return the innermost set of template arguments.  */
631   if (n == 1)
632     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
633 
634   /* If we're not removing anything, just return the arguments we were
635      given.  */
636   extra_levels = TMPL_ARGS_DEPTH (args) - n;
637   gcc_assert (extra_levels >= 0);
638   if (extra_levels == 0)
639     return args;
640 
641   /* Make a new set of arguments, not containing the outer arguments.  */
642   new_args = make_tree_vec (n);
643   for (i = 1; i <= n; ++i)
644     SET_TMPL_ARGS_LEVEL (new_args, i,
645 			 TMPL_ARGS_LEVEL (args, i + extra_levels));
646 
647   return new_args;
648 }
649 
650 /* The inverse of get_innermost_template_args: Return all but the innermost
651    EXTRA_LEVELS levels of template arguments from the ARGS.  */
652 
653 static tree
strip_innermost_template_args(tree args,int extra_levels)654 strip_innermost_template_args (tree args, int extra_levels)
655 {
656   tree new_args;
657   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
658   int i;
659 
660   gcc_assert (n >= 0);
661 
662   /* If N is 1, just return the outermost set of template arguments.  */
663   if (n == 1)
664     return TMPL_ARGS_LEVEL (args, 1);
665 
666   /* If we're not removing anything, just return the arguments we were
667      given.  */
668   gcc_assert (extra_levels >= 0);
669   if (extra_levels == 0)
670     return args;
671 
672   /* Make a new set of arguments, not containing the inner arguments.  */
673   new_args = make_tree_vec (n);
674   for (i = 1; i <= n; ++i)
675     SET_TMPL_ARGS_LEVEL (new_args, i,
676 			 TMPL_ARGS_LEVEL (args, i));
677 
678   return new_args;
679 }
680 
681 /* We've got a template header coming up; push to a new level for storing
682    the parms.  */
683 
684 void
begin_template_parm_list(void)685 begin_template_parm_list (void)
686 {
687   /* We use a non-tag-transparent scope here, which causes pushtag to
688      put tags in this scope, rather than in the enclosing class or
689      namespace scope.  This is the right thing, since we want
690      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
691      global template class, push_template_decl handles putting the
692      TEMPLATE_DECL into top-level scope.  For a nested template class,
693      e.g.:
694 
695        template <class T> struct S1 {
696 	 template <class T> struct S2 {};
697        };
698 
699      pushtag contains special code to insert the TEMPLATE_DECL for S2
700      at the right scope.  */
701   begin_scope (sk_template_parms, NULL);
702   ++processing_template_decl;
703   ++processing_template_parmlist;
704   note_template_header (0);
705 
706   /* Add a dummy parameter level while we process the parameter list.  */
707   current_template_parms
708     = tree_cons (size_int (processing_template_decl),
709 		 make_tree_vec (0),
710 		 current_template_parms);
711 }
712 
713 /* This routine is called when a specialization is declared.  If it is
714    invalid to declare a specialization here, an error is reported and
715    false is returned, otherwise this routine will return true.  */
716 
717 static bool
check_specialization_scope(void)718 check_specialization_scope (void)
719 {
720   tree scope = current_scope ();
721 
722   /* [temp.expl.spec]
723 
724      An explicit specialization shall be declared in the namespace of
725      which the template is a member, or, for member templates, in the
726      namespace of which the enclosing class or enclosing class
727      template is a member.  An explicit specialization of a member
728      function, member class or static data member of a class template
729      shall be declared in the namespace of which the class template
730      is a member.  */
731   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
732     {
733       error ("explicit specialization in non-namespace scope %qD", scope);
734       return false;
735     }
736 
737   /* [temp.expl.spec]
738 
739      In an explicit specialization declaration for a member of a class
740      template or a member template that appears in namespace scope,
741      the member template and some of its enclosing class templates may
742      remain unspecialized, except that the declaration shall not
743      explicitly specialize a class member template if its enclosing
744      class templates are not explicitly specialized as well.  */
745   if (current_template_parms)
746     {
747       error ("enclosing class templates are not explicitly specialized");
748       return false;
749     }
750 
751   return true;
752 }
753 
754 /* We've just seen template <>.  */
755 
756 bool
begin_specialization(void)757 begin_specialization (void)
758 {
759   begin_scope (sk_template_spec, NULL);
760   note_template_header (1);
761   return check_specialization_scope ();
762 }
763 
764 /* Called at then end of processing a declaration preceded by
765    template<>.  */
766 
767 void
end_specialization(void)768 end_specialization (void)
769 {
770   finish_scope ();
771   reset_specialization ();
772 }
773 
774 /* Any template <>'s that we have seen thus far are not referring to a
775    function specialization.  */
776 
777 void
reset_specialization(void)778 reset_specialization (void)
779 {
780   processing_specialization = 0;
781   template_header_count = 0;
782 }
783 
784 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
785    it was of the form template <>.  */
786 
787 static void
note_template_header(int specialization)788 note_template_header (int specialization)
789 {
790   processing_specialization = specialization;
791   template_header_count++;
792 }
793 
794 /* We're beginning an explicit instantiation.  */
795 
796 void
begin_explicit_instantiation(void)797 begin_explicit_instantiation (void)
798 {
799   gcc_assert (!processing_explicit_instantiation);
800   processing_explicit_instantiation = true;
801 }
802 
803 
804 void
end_explicit_instantiation(void)805 end_explicit_instantiation (void)
806 {
807   gcc_assert (processing_explicit_instantiation);
808   processing_explicit_instantiation = false;
809 }
810 
811 /* An explicit specialization or partial specialization of TMPL is being
812    declared.  Check that the namespace in which the specialization is
813    occurring is permissible.  Returns false iff it is invalid to
814    specialize TMPL in the current namespace.  */
815 
816 static bool
check_specialization_namespace(tree tmpl)817 check_specialization_namespace (tree tmpl)
818 {
819   tree tpl_ns = decl_namespace_context (tmpl);
820 
821   /* [tmpl.expl.spec]
822 
823      An explicit specialization shall be declared in a namespace enclosing the
824      specialized template. An explicit specialization whose declarator-id is
825      not qualified shall be declared in the nearest enclosing namespace of the
826      template, or, if the namespace is inline (7.3.1), any namespace from its
827      enclosing namespace set.  */
828   if (current_scope() != DECL_CONTEXT (tmpl)
829       && !at_namespace_scope_p ())
830     {
831       error ("specialization of %qD must appear at namespace scope", tmpl);
832       return false;
833     }
834 
835   if (is_nested_namespace (current_namespace, tpl_ns, cxx_dialect < cxx11))
836     /* Same or enclosing namespace.  */
837     return true;
838   else
839     {
840       auto_diagnostic_group d;
841       if (permerror (input_location,
842 		     "specialization of %qD in different namespace", tmpl))
843 	inform (DECL_SOURCE_LOCATION (tmpl),
844 		"  from definition of %q#D", tmpl);
845       return false;
846     }
847 }
848 
849 /* SPEC is an explicit instantiation.  Check that it is valid to
850    perform this explicit instantiation in the current namespace.  */
851 
852 static void
check_explicit_instantiation_namespace(tree spec)853 check_explicit_instantiation_namespace (tree spec)
854 {
855   tree ns;
856 
857   /* DR 275: An explicit instantiation shall appear in an enclosing
858      namespace of its template.  */
859   ns = decl_namespace_context (spec);
860   if (!is_nested_namespace (current_namespace, ns))
861     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
862 	       "(which does not enclose namespace %qD)",
863 	       spec, current_namespace, ns);
864 }
865 
866 /* Returns the type of a template specialization only if that
867    specialization needs to be defined. Otherwise (e.g., if the type has
868    already been defined), the function returns NULL_TREE.  */
869 
870 static tree
maybe_new_partial_specialization(tree type)871 maybe_new_partial_specialization (tree type)
872 {
873   /* An implicit instantiation of an incomplete type implies
874      the definition of a new class template.
875 
876 	template<typename T>
877 	  struct S;
878 
879 	template<typename T>
880 	  struct S<T*>;
881 
882      Here, S<T*> is an implicit instantiation of S whose type
883      is incomplete.  */
884   if (CLASSTYPE_IMPLICIT_INSTANTIATION (type) && !COMPLETE_TYPE_P (type))
885     return type;
886 
887   /* It can also be the case that TYPE is a completed specialization.
888      Continuing the previous example, suppose we also declare:
889 
890 	template<typename T>
891 	  requires Integral<T>
892 	    struct S<T*>;
893 
894      Here, S<T*> refers to the specialization S<T*> defined
895      above. However, we need to differentiate definitions because
896      we intend to define a new partial specialization. In this case,
897      we rely on the fact that the constraints are different for
898      this declaration than that above.
899 
900      Note that we also get here for injected class names and
901      late-parsed template definitions. We must ensure that we
902      do not create new type declarations for those cases.  */
903   if (flag_concepts && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
904     {
905       tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
906       tree args = CLASSTYPE_TI_ARGS (type);
907 
908       /* If there are no template parameters, this cannot be a new
909 	 partial template specialization?  */
910       if (!current_template_parms)
911         return NULL_TREE;
912 
913       /* The injected-class-name is not a new partial specialization.  */
914       if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
915 	return NULL_TREE;
916 
917       /* If the constraints are not the same as those of the primary
918 	 then, we can probably create a new specialization.  */
919       tree type_constr = current_template_constraints ();
920 
921       if (type == TREE_TYPE (tmpl))
922 	{
923 	  tree main_constr = get_constraints (tmpl);
924 	  if (equivalent_constraints (type_constr, main_constr))
925 	    return NULL_TREE;
926 	}
927 
928       /* Also, if there's a pre-existing specialization with matching
929 	 constraints, then this also isn't new.  */
930       tree specs = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
931       while (specs)
932         {
933           tree spec_tmpl = TREE_VALUE (specs);
934           tree spec_args = TREE_PURPOSE (specs);
935           tree spec_constr = get_constraints (spec_tmpl);
936           if (comp_template_args (args, spec_args)
937 	      && equivalent_constraints (type_constr, spec_constr))
938             return NULL_TREE;
939           specs = TREE_CHAIN (specs);
940         }
941 
942       /* Create a new type node (and corresponding type decl)
943 	 for the newly declared specialization.  */
944       tree t = make_class_type (TREE_CODE (type));
945       CLASSTYPE_DECLARED_CLASS (t) = CLASSTYPE_DECLARED_CLASS (type);
946       SET_TYPE_TEMPLATE_INFO (t, build_template_info (tmpl, args));
947 
948       /* We only need a separate type node for storing the definition of this
949 	 partial specialization; uses of S<T*> are unconstrained, so all are
950 	 equivalent.  So keep TYPE_CANONICAL the same.  */
951       TYPE_CANONICAL (t) = TYPE_CANONICAL (type);
952 
953       /* Build the corresponding type decl.  */
954       tree d = create_implicit_typedef (DECL_NAME (tmpl), t);
955       DECL_CONTEXT (d) = TYPE_CONTEXT (t);
956       DECL_SOURCE_LOCATION (d) = input_location;
957       TREE_PRIVATE (d) = (current_access_specifier == access_private_node);
958       TREE_PROTECTED (d) = (current_access_specifier == access_protected_node);
959 
960       set_instantiating_module (d);
961       DECL_MODULE_EXPORT_P (d) = DECL_MODULE_EXPORT_P (tmpl);
962 
963       return t;
964     }
965 
966   return NULL_TREE;
967 }
968 
969 /* The TYPE is being declared.  If it is a template type, that means it
970    is a partial specialization.  Do appropriate error-checking.  */
971 
972 tree
maybe_process_partial_specialization(tree type)973 maybe_process_partial_specialization (tree type)
974 {
975   tree context;
976 
977   if (type == error_mark_node)
978     return error_mark_node;
979 
980   /* A lambda that appears in specialization context is not itself a
981      specialization.  */
982   if (CLASS_TYPE_P (type) && CLASSTYPE_LAMBDA_EXPR (type))
983     return type;
984 
985   /* An injected-class-name is not a specialization.  */
986   if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
987     return type;
988 
989   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
990     {
991       error ("name of class shadows template template parameter %qD",
992 	     TYPE_NAME (type));
993       return error_mark_node;
994     }
995 
996   context = TYPE_CONTEXT (type);
997 
998   if (TYPE_ALIAS_P (type))
999     {
1000       tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (type);
1001 
1002       if (tinfo && DECL_ALIAS_TEMPLATE_P (TI_TEMPLATE (tinfo)))
1003 	error ("specialization of alias template %qD",
1004 	       TI_TEMPLATE (tinfo));
1005       else
1006 	error ("explicit specialization of non-template %qT", type);
1007       return error_mark_node;
1008     }
1009   else if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
1010     {
1011       /* This is for ordinary explicit specialization and partial
1012 	 specialization of a template class such as:
1013 
1014 	   template <> class C<int>;
1015 
1016 	 or:
1017 
1018 	   template <class T> class C<T*>;
1019 
1020 	 Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
1021 
1022       if (tree t = maybe_new_partial_specialization (type))
1023 	{
1024 	  if (!check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (t))
1025 	      && !at_namespace_scope_p ())
1026 	    return error_mark_node;
1027 	  SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (t);
1028 	  DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (t)) = input_location;
1029 	  if (processing_template_decl)
1030 	    {
1031 	      tree decl = push_template_decl (TYPE_MAIN_DECL (t));
1032 	      if (decl == error_mark_node)
1033 		return error_mark_node;
1034 	      return TREE_TYPE (decl);
1035 	    }
1036 	}
1037       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
1038 	error ("specialization of %qT after instantiation", type);
1039       else if (errorcount && !processing_specialization
1040 	        && CLASSTYPE_TEMPLATE_SPECIALIZATION (type)
1041 	       && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
1042 	/* Trying to define a specialization either without a template<> header
1043 	   or in an inappropriate place.  We've already given an error, so just
1044 	   bail now so we don't actually define the specialization.  */
1045 	return error_mark_node;
1046     }
1047   else if (CLASS_TYPE_P (type)
1048 	   && !CLASSTYPE_USE_TEMPLATE (type)
1049 	   && CLASSTYPE_TEMPLATE_INFO (type)
1050 	   && context && CLASS_TYPE_P (context)
1051 	   && CLASSTYPE_TEMPLATE_INFO (context))
1052     {
1053       /* This is for an explicit specialization of member class
1054 	 template according to [temp.expl.spec/18]:
1055 
1056 	   template <> template <class U> class C<int>::D;
1057 
1058 	 The context `C<int>' must be an implicit instantiation.
1059 	 Otherwise this is just a member class template declared
1060 	 earlier like:
1061 
1062 	   template <> class C<int> { template <class U> class D; };
1063 	   template <> template <class U> class C<int>::D;
1064 
1065 	 In the first case, `C<int>::D' is a specialization of `C<T>::D'
1066 	 while in the second case, `C<int>::D' is a primary template
1067 	 and `C<T>::D' may not exist.  */
1068 
1069       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
1070 	  && !COMPLETE_TYPE_P (type))
1071 	{
1072 	  tree t;
1073 	  tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
1074 
1075 	  if (current_namespace
1076 	      != decl_namespace_context (tmpl))
1077 	    {
1078 	      if (permerror (input_location,
1079 			     "specialization of %qD in different namespace",
1080 			     type))
1081 		inform (DECL_SOURCE_LOCATION (tmpl),
1082 			"from definition of %q#D", tmpl);
1083 	    }
1084 
1085 	  /* Check for invalid specialization after instantiation:
1086 
1087 	       template <> template <> class C<int>::D<int>;
1088 	       template <> template <class U> class C<int>::D;  */
1089 
1090 	  for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
1091 	       t; t = TREE_CHAIN (t))
1092 	    {
1093 	      tree inst = TREE_VALUE (t);
1094 	      if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst)
1095 		  || !COMPLETE_OR_OPEN_TYPE_P (inst))
1096 		{
1097 		  /* We already have a full specialization of this partial
1098 		     instantiation, or a full specialization has been
1099 		     looked up but not instantiated.  Reassign it to the
1100 		     new member specialization template.  */
1101 		  spec_entry elt;
1102 		  spec_entry *entry;
1103 
1104 		  elt.tmpl = most_general_template (tmpl);
1105 		  elt.args = CLASSTYPE_TI_ARGS (inst);
1106 		  elt.spec = inst;
1107 
1108 		  type_specializations->remove_elt (&elt);
1109 
1110 		  elt.tmpl = tmpl;
1111 		  CLASSTYPE_TI_ARGS (inst)
1112 		    = elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
1113 
1114 		  spec_entry **slot
1115 		    = type_specializations->find_slot (&elt, INSERT);
1116 		  entry = ggc_alloc<spec_entry> ();
1117 		  *entry = elt;
1118 		  *slot = entry;
1119 		}
1120 	      else
1121 		/* But if we've had an implicit instantiation, that's a
1122 		   problem ([temp.expl.spec]/6).  */
1123 		error ("specialization %qT after instantiation %qT",
1124 		       type, inst);
1125 	    }
1126 
1127 	  /* Mark TYPE as a specialization.  And as a result, we only
1128 	     have one level of template argument for the innermost
1129 	     class template.  */
1130 	  SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1131 	  DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1132 	  CLASSTYPE_TI_ARGS (type)
1133 	    = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
1134 	}
1135     }
1136   else if (processing_specialization)
1137     {
1138        /* Someday C++0x may allow for enum template specialization.  */
1139       if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
1140 	  && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
1141 	pedwarn (input_location, OPT_Wpedantic, "template specialization "
1142 		 "of %qD not allowed by ISO C++", type);
1143       else
1144 	{
1145 	  error ("explicit specialization of non-template %qT", type);
1146 	  return error_mark_node;
1147 	}
1148     }
1149 
1150   return type;
1151 }
1152 
1153 /* Returns nonzero if we can optimize the retrieval of specializations
1154    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
1155    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
1156 
1157 static inline bool
optimize_specialization_lookup_p(tree tmpl)1158 optimize_specialization_lookup_p (tree tmpl)
1159 {
1160   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
1161 	  && DECL_CLASS_SCOPE_P (tmpl)
1162 	  /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
1163 	     parameter.  */
1164 	  && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
1165 	  /* The optimized lookup depends on the fact that the
1166 	     template arguments for the member function template apply
1167 	     purely to the containing class, which is not true if the
1168 	     containing class is an explicit or partial
1169 	     specialization.  */
1170 	  && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
1171 	  && !DECL_MEMBER_TEMPLATE_P (tmpl)
1172 	  && !DECL_CONV_FN_P (tmpl)
1173 	  /* It is possible to have a template that is not a member
1174 	     template and is not a member of a template class:
1175 
1176 	     template <typename T>
1177 	     struct S { friend A::f(); };
1178 
1179 	     Here, the friend function is a template, but the context does
1180 	     not have template information.  The optimized lookup relies
1181 	     on having ARGS be the template arguments for both the class
1182 	     and the function template.  */
1183 	  && !DECL_UNIQUE_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
1184 }
1185 
1186 /* Make sure ARGS doesn't use any inappropriate typedefs; we should have
1187    gone through coerce_template_parms by now.  */
1188 
1189 static void
verify_unstripped_args_1(tree inner)1190 verify_unstripped_args_1 (tree inner)
1191 {
1192   for (int i = 0; i < TREE_VEC_LENGTH (inner); ++i)
1193     {
1194       tree arg = TREE_VEC_ELT (inner, i);
1195       if (TREE_CODE (arg) == TEMPLATE_DECL)
1196 	/* OK */;
1197       else if (TYPE_P (arg))
1198 	gcc_assert (strip_typedefs (arg, NULL) == arg);
1199       else if (ARGUMENT_PACK_P (arg))
1200 	verify_unstripped_args_1 (ARGUMENT_PACK_ARGS (arg));
1201       else if (strip_typedefs (TREE_TYPE (arg), NULL) != TREE_TYPE (arg))
1202 	/* Allow typedefs on the type of a non-type argument, since a
1203 	   parameter can have them.  */;
1204       else
1205 	gcc_assert (strip_typedefs_expr (arg, NULL) == arg);
1206     }
1207 }
1208 
1209 static void
verify_unstripped_args(tree args)1210 verify_unstripped_args (tree args)
1211 {
1212   ++processing_template_decl;
1213   if (!any_dependent_template_arguments_p (args))
1214     verify_unstripped_args_1 (INNERMOST_TEMPLATE_ARGS (args));
1215   --processing_template_decl;
1216 }
1217 
1218 /* Retrieve the specialization (in the sense of [temp.spec] - a
1219    specialization is either an instantiation or an explicit
1220    specialization) of TMPL for the given template ARGS.  If there is
1221    no such specialization, return NULL_TREE.  The ARGS are a vector of
1222    arguments, or a vector of vectors of arguments, in the case of
1223    templates with more than one level of parameters.
1224 
1225    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
1226    then we search for a partial specialization matching ARGS.  This
1227    parameter is ignored if TMPL is not a class template.
1228 
1229    We can also look up a FIELD_DECL, if it is a lambda capture pack; the
1230    result is a NONTYPE_ARGUMENT_PACK.  */
1231 
1232 static tree
retrieve_specialization(tree tmpl,tree args,hashval_t hash)1233 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1234 {
1235   if (tmpl == NULL_TREE)
1236     return NULL_TREE;
1237 
1238   if (args == error_mark_node)
1239     return NULL_TREE;
1240 
1241   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL
1242 	      || TREE_CODE (tmpl) == FIELD_DECL);
1243 
1244   /* There should be as many levels of arguments as there are
1245      levels of parameters.  */
1246   gcc_assert (TMPL_ARGS_DEPTH (args)
1247 	      == (TREE_CODE (tmpl) == TEMPLATE_DECL
1248 		  ? TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl))
1249 		  : template_class_depth (DECL_CONTEXT (tmpl))));
1250 
1251   if (flag_checking)
1252     verify_unstripped_args (args);
1253 
1254   /* Lambda functions in templates aren't instantiated normally, but through
1255      tsubst_lambda_expr.  */
1256   if (lambda_fn_in_template_p (tmpl))
1257     return NULL_TREE;
1258 
1259   if (optimize_specialization_lookup_p (tmpl))
1260     {
1261       /* The template arguments actually apply to the containing
1262 	 class.  Find the class specialization with those
1263 	 arguments.  */
1264       tree class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
1265       tree class_specialization
1266 	= retrieve_specialization (class_template, args, 0);
1267       if (!class_specialization)
1268 	return NULL_TREE;
1269 
1270       /* Find the instance of TMPL.  */
1271       tree fns = get_class_binding (class_specialization, DECL_NAME (tmpl));
1272       for (ovl_iterator iter (fns); iter; ++iter)
1273 	{
1274 	  tree fn = *iter;
1275 	  if (tree ti = get_template_info (fn))
1276 	    if (TI_TEMPLATE (ti) == tmpl
1277 		/* using-declarations can bring in a different
1278 		   instantiation of tmpl as a member of a different
1279 		   instantiation of tmpl's class.  We don't want those
1280 		   here.  */
1281 		&& DECL_CONTEXT (fn) == class_specialization)
1282 	      return fn;
1283 	}
1284       return NULL_TREE;
1285     }
1286   else
1287     {
1288       spec_entry *found;
1289       spec_entry elt;
1290       spec_hash_table *specializations;
1291 
1292       elt.tmpl = tmpl;
1293       elt.args = args;
1294       elt.spec = NULL_TREE;
1295 
1296       if (DECL_CLASS_TEMPLATE_P (tmpl))
1297 	specializations = type_specializations;
1298       else
1299 	specializations = decl_specializations;
1300 
1301       if (hash == 0)
1302 	hash = spec_hasher::hash (&elt);
1303       found = specializations->find_with_hash (&elt, hash);
1304       if (found)
1305 	return found->spec;
1306     }
1307 
1308   return NULL_TREE;
1309 }
1310 
1311 /* Like retrieve_specialization, but for local declarations.  */
1312 
1313 tree
retrieve_local_specialization(tree tmpl)1314 retrieve_local_specialization (tree tmpl)
1315 {
1316   if (local_specializations == NULL)
1317     return NULL_TREE;
1318 
1319   tree *slot = local_specializations->get (tmpl);
1320   return slot ? *slot : NULL_TREE;
1321 }
1322 
1323 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1324 
1325 int
is_specialization_of(tree decl,tree tmpl)1326 is_specialization_of (tree decl, tree tmpl)
1327 {
1328   tree t;
1329 
1330   if (TREE_CODE (decl) == FUNCTION_DECL)
1331     {
1332       for (t = decl;
1333 	   t != NULL_TREE;
1334 	   t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1335 	if (t == tmpl)
1336 	  return 1;
1337     }
1338   else
1339     {
1340       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1341 
1342       for (t = TREE_TYPE (decl);
1343 	   t != NULL_TREE;
1344 	   t = CLASSTYPE_USE_TEMPLATE (t)
1345 	     ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1346 	if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1347 	  return 1;
1348     }
1349 
1350   return 0;
1351 }
1352 
1353 /* Returns nonzero iff DECL is a specialization of friend declaration
1354    FRIEND_DECL according to [temp.friend].  */
1355 
1356 bool
is_specialization_of_friend(tree decl,tree friend_decl)1357 is_specialization_of_friend (tree decl, tree friend_decl)
1358 {
1359   bool need_template = true;
1360   int template_depth;
1361 
1362   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1363 	      || TREE_CODE (decl) == TYPE_DECL);
1364 
1365   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1366      of a template class, we want to check if DECL is a specialization
1367      if this.  */
1368   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1369       && DECL_TEMPLATE_INFO (friend_decl)
1370       && !DECL_USE_TEMPLATE (friend_decl))
1371     {
1372       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1373       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1374       need_template = false;
1375     }
1376   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1377 	   && !PRIMARY_TEMPLATE_P (friend_decl))
1378     need_template = false;
1379 
1380   /* There is nothing to do if this is not a template friend.  */
1381   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1382     return false;
1383 
1384   if (is_specialization_of (decl, friend_decl))
1385     return true;
1386 
1387   /* [temp.friend/6]
1388      A member of a class template may be declared to be a friend of a
1389      non-template class.  In this case, the corresponding member of
1390      every specialization of the class template is a friend of the
1391      class granting friendship.
1392 
1393      For example, given a template friend declaration
1394 
1395        template <class T> friend void A<T>::f();
1396 
1397      the member function below is considered a friend
1398 
1399        template <> struct A<int> {
1400 	 void f();
1401        };
1402 
1403      For this type of template friend, TEMPLATE_DEPTH below will be
1404      nonzero.  To determine if DECL is a friend of FRIEND, we first
1405      check if the enclosing class is a specialization of another.  */
1406 
1407   template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1408   if (template_depth
1409       && DECL_CLASS_SCOPE_P (decl)
1410       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1411 			       CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1412     {
1413       /* Next, we check the members themselves.  In order to handle
1414 	 a few tricky cases, such as when FRIEND_DECL's are
1415 
1416 	   template <class T> friend void A<T>::g(T t);
1417 	   template <class T> template <T t> friend void A<T>::h();
1418 
1419 	 and DECL's are
1420 
1421 	   void A<int>::g(int);
1422 	   template <int> void A<int>::h();
1423 
1424 	 we need to figure out ARGS, the template arguments from
1425 	 the context of DECL.  This is required for template substitution
1426 	 of `T' in the function parameter of `g' and template parameter
1427 	 of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1428 
1429       tree context = DECL_CONTEXT (decl);
1430       tree args = NULL_TREE;
1431       int current_depth = 0;
1432 
1433       while (current_depth < template_depth)
1434 	{
1435 	  if (CLASSTYPE_TEMPLATE_INFO (context))
1436 	    {
1437 	      if (current_depth == 0)
1438 		args = TYPE_TI_ARGS (context);
1439 	      else
1440 		args = add_to_template_args (TYPE_TI_ARGS (context), args);
1441 	      current_depth++;
1442 	    }
1443 	  context = TYPE_CONTEXT (context);
1444 	}
1445 
1446       if (TREE_CODE (decl) == FUNCTION_DECL)
1447 	{
1448 	  bool is_template;
1449 	  tree friend_type;
1450 	  tree decl_type;
1451 	  tree friend_args_type;
1452 	  tree decl_args_type;
1453 
1454 	  /* Make sure that both DECL and FRIEND_DECL are templates or
1455 	     non-templates.  */
1456 	  is_template = DECL_TEMPLATE_INFO (decl)
1457 			&& PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1458 	  if (need_template ^ is_template)
1459 	    return false;
1460 	  else if (is_template)
1461 	    {
1462 	      /* If both are templates, check template parameter list.  */
1463 	      tree friend_parms
1464 		= tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1465 					 args, tf_none);
1466 	      if (!comp_template_parms
1467 		     (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1468 		      friend_parms))
1469 		return false;
1470 
1471 	      decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1472 	    }
1473 	  else
1474 	    decl_type = TREE_TYPE (decl);
1475 
1476 	  friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1477 					      tf_none, NULL_TREE);
1478 	  if (friend_type == error_mark_node)
1479 	    return false;
1480 
1481 	  /* Check if return types match.  */
1482 	  if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1483 	    return false;
1484 
1485 	  /* Check if function parameter types match, ignoring the
1486 	     `this' parameter.  */
1487 	  friend_args_type = TYPE_ARG_TYPES (friend_type);
1488 	  decl_args_type = TYPE_ARG_TYPES (decl_type);
1489 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1490 	    friend_args_type = TREE_CHAIN (friend_args_type);
1491 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1492 	    decl_args_type = TREE_CHAIN (decl_args_type);
1493 
1494 	  return compparms (decl_args_type, friend_args_type);
1495 	}
1496       else
1497 	{
1498 	  /* DECL is a TYPE_DECL */
1499 	  bool is_template;
1500 	  tree decl_type = TREE_TYPE (decl);
1501 
1502 	  /* Make sure that both DECL and FRIEND_DECL are templates or
1503 	     non-templates.  */
1504 	  is_template
1505 	    = CLASSTYPE_TEMPLATE_INFO (decl_type)
1506 	      && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1507 
1508 	  if (need_template ^ is_template)
1509 	    return false;
1510 	  else if (is_template)
1511 	    {
1512 	      tree friend_parms;
1513 	      /* If both are templates, check the name of the two
1514 		 TEMPLATE_DECL's first because is_friend didn't.  */
1515 	      if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1516 		  != DECL_NAME (friend_decl))
1517 		return false;
1518 
1519 	      /* Now check template parameter list.  */
1520 	      friend_parms
1521 		= tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1522 					 args, tf_none);
1523 	      return comp_template_parms
1524 		(DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1525 		 friend_parms);
1526 	    }
1527 	  else
1528 	    return (DECL_NAME (decl)
1529 		    == DECL_NAME (friend_decl));
1530 	}
1531     }
1532   return false;
1533 }
1534 
1535 /* Register the specialization SPEC as a specialization of TMPL with
1536    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1537    is actually just a friend declaration.  ATTRLIST is the list of
1538    attributes that the specialization is declared with or NULL when
1539    it isn't.  Returns SPEC, or an equivalent prior declaration, if
1540    available.
1541 
1542    We also store instantiations of field packs in the hash table, even
1543    though they are not themselves templates, to make lookup easier.  */
1544 
1545 static tree
register_specialization(tree spec,tree tmpl,tree args,bool is_friend,hashval_t hash)1546 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1547 			 hashval_t hash)
1548 {
1549   tree fn;
1550   spec_entry **slot = NULL;
1551   spec_entry elt;
1552 
1553   gcc_assert ((TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec))
1554 	      || (TREE_CODE (tmpl) == FIELD_DECL
1555 		  && TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK));
1556 
1557   if (TREE_CODE (spec) == FUNCTION_DECL
1558       && uses_template_parms (DECL_TI_ARGS (spec)))
1559     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1560        register it; we want the corresponding TEMPLATE_DECL instead.
1561        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1562        the more obvious `uses_template_parms (spec)' to avoid problems
1563        with default function arguments.  In particular, given
1564        something like this:
1565 
1566 	  template <class T> void f(T t1, T t = T())
1567 
1568        the default argument expression is not substituted for in an
1569        instantiation unless and until it is actually needed.  */
1570     return spec;
1571 
1572   if (optimize_specialization_lookup_p (tmpl))
1573     /* We don't put these specializations in the hash table, but we might
1574        want to give an error about a mismatch.  */
1575     fn = retrieve_specialization (tmpl, args, 0);
1576   else
1577     {
1578       elt.tmpl = tmpl;
1579       elt.args = args;
1580       elt.spec = spec;
1581 
1582       if (hash == 0)
1583 	hash = spec_hasher::hash (&elt);
1584 
1585       slot = decl_specializations->find_slot_with_hash (&elt, hash, INSERT);
1586       if (*slot)
1587 	fn = (*slot)->spec;
1588       else
1589 	fn = NULL_TREE;
1590     }
1591 
1592   /* We can sometimes try to re-register a specialization that we've
1593      already got.  In particular, regenerate_decl_from_template calls
1594      duplicate_decls which will update the specialization list.  But,
1595      we'll still get called again here anyhow.  It's more convenient
1596      to simply allow this than to try to prevent it.  */
1597   if (fn == spec)
1598     return spec;
1599   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1600     {
1601       if (DECL_TEMPLATE_INSTANTIATION (fn))
1602 	{
1603 	  if (DECL_ODR_USED (fn)
1604 	      || DECL_EXPLICIT_INSTANTIATION (fn))
1605 	    {
1606 	      error ("specialization of %qD after instantiation",
1607 		     fn);
1608 	      return error_mark_node;
1609 	    }
1610 	  else
1611 	    {
1612 	      tree clone;
1613 	      /* This situation should occur only if the first
1614 		 specialization is an implicit instantiation, the
1615 		 second is an explicit specialization, and the
1616 		 implicit instantiation has not yet been used.  That
1617 		 situation can occur if we have implicitly
1618 		 instantiated a member function and then specialized
1619 		 it later.
1620 
1621 		 We can also wind up here if a friend declaration that
1622 		 looked like an instantiation turns out to be a
1623 		 specialization:
1624 
1625 		   template <class T> void foo(T);
1626 		   class S { friend void foo<>(int) };
1627 		   template <> void foo(int);
1628 
1629 		 We transform the existing DECL in place so that any
1630 		 pointers to it become pointers to the updated
1631 		 declaration.
1632 
1633 		 If there was a definition for the template, but not
1634 		 for the specialization, we want this to look as if
1635 		 there were no definition, and vice versa.  */
1636 	      DECL_INITIAL (fn) = NULL_TREE;
1637 	      duplicate_decls (spec, fn, /*hiding=*/is_friend);
1638 	      /* The call to duplicate_decls will have applied
1639 		 [temp.expl.spec]:
1640 
1641 		   An explicit specialization of a function template
1642 		   is inline only if it is explicitly declared to be,
1643 		   and independently of whether its function template
1644 		   is.
1645 
1646 		to the primary function; now copy the inline bits to
1647 		the various clones.  */
1648 	      FOR_EACH_CLONE (clone, fn)
1649 		{
1650 		  DECL_DECLARED_INLINE_P (clone)
1651 		    = DECL_DECLARED_INLINE_P (fn);
1652 		  DECL_SOURCE_LOCATION (clone)
1653 		    = DECL_SOURCE_LOCATION (fn);
1654 		  DECL_DELETED_FN (clone)
1655 		    = DECL_DELETED_FN (fn);
1656 		}
1657 	      check_specialization_namespace (tmpl);
1658 
1659 	      return fn;
1660 	    }
1661 	}
1662       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1663 	{
1664 	  tree dd = duplicate_decls (spec, fn, /*hiding=*/is_friend);
1665 	  if (dd == error_mark_node)
1666 	    /* We've already complained in duplicate_decls.  */
1667 	    return error_mark_node;
1668 
1669 	  if (dd == NULL_TREE && DECL_INITIAL (spec))
1670 	    /* Dup decl failed, but this is a new definition. Set the
1671 	       line number so any errors match this new
1672 	       definition.  */
1673 	    DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1674 
1675 	  return fn;
1676 	}
1677     }
1678   else if (fn)
1679     return duplicate_decls (spec, fn, /*hiding=*/is_friend);
1680 
1681   /* A specialization must be declared in the same namespace as the
1682      template it is specializing.  */
1683   if (DECL_P (spec) && DECL_TEMPLATE_SPECIALIZATION (spec)
1684       && !check_specialization_namespace (tmpl))
1685     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1686 
1687   if (slot != NULL /* !optimize_specialization_lookup_p (tmpl) */)
1688     {
1689       spec_entry *entry = ggc_alloc<spec_entry> ();
1690       gcc_assert (tmpl && args && spec);
1691       *entry = elt;
1692       *slot = entry;
1693       if ((TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1694 	   && PRIMARY_TEMPLATE_P (tmpl)
1695 	   && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1696 	  || variable_template_p (tmpl))
1697 	/* If TMPL is a forward declaration of a template function, keep a list
1698 	   of all specializations in case we need to reassign them to a friend
1699 	   template later in tsubst_friend_function.
1700 
1701 	   Also keep a list of all variable template instantiations so that
1702 	   process_partial_specialization can check whether a later partial
1703 	   specialization would have used it.  */
1704 	DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1705 	  = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1706     }
1707 
1708   return spec;
1709 }
1710 
1711 /* Restricts tree and type comparisons.  */
1712 int comparing_specializations;
1713 int comparing_dependent_aliases;
1714 
1715 /* Returns true iff two spec_entry nodes are equivalent.  */
1716 
1717 bool
equal(spec_entry * e1,spec_entry * e2)1718 spec_hasher::equal (spec_entry *e1, spec_entry *e2)
1719 {
1720   int equal;
1721 
1722   ++comparing_specializations;
1723   ++comparing_dependent_aliases;
1724   ++processing_template_decl;
1725   equal = (e1->tmpl == e2->tmpl
1726 	   && comp_template_args (e1->args, e2->args));
1727   if (equal && flag_concepts
1728       /* tmpl could be a FIELD_DECL for a capture pack.  */
1729       && TREE_CODE (e1->tmpl) == TEMPLATE_DECL
1730       && VAR_P (DECL_TEMPLATE_RESULT (e1->tmpl))
1731       && uses_template_parms (e1->args))
1732     {
1733       /* Partial specializations of a variable template can be distinguished by
1734 	 constraints.  */
1735       tree c1 = e1->spec ? get_constraints (e1->spec) : NULL_TREE;
1736       tree c2 = e2->spec ? get_constraints (e2->spec) : NULL_TREE;
1737       equal = equivalent_constraints (c1, c2);
1738     }
1739   --processing_template_decl;
1740   --comparing_dependent_aliases;
1741   --comparing_specializations;
1742 
1743   return equal;
1744 }
1745 
1746 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1747 
1748 static hashval_t
hash_tmpl_and_args(tree tmpl,tree args)1749 hash_tmpl_and_args (tree tmpl, tree args)
1750 {
1751   hashval_t val = iterative_hash_object (DECL_UID (tmpl), 0);
1752   return iterative_hash_template_arg (args, val);
1753 }
1754 
1755 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1756    ignoring SPEC.  */
1757 
1758 hashval_t
hash(spec_entry * e)1759 spec_hasher::hash (spec_entry *e)
1760 {
1761   return hash_tmpl_and_args (e->tmpl, e->args);
1762 }
1763 
1764 /* Recursively calculate a hash value for a template argument ARG, for use
1765    in the hash tables of template specializations.   We must be
1766    careful to (at least) skip the same entities template_args_equal
1767    does.  */
1768 
1769 hashval_t
iterative_hash_template_arg(tree arg,hashval_t val)1770 iterative_hash_template_arg (tree arg, hashval_t val)
1771 {
1772   if (arg == NULL_TREE)
1773     return iterative_hash_object (arg, val);
1774 
1775   if (!TYPE_P (arg))
1776     /* Strip nop-like things, but not the same as STRIP_NOPS.  */
1777     while (CONVERT_EXPR_P (arg)
1778 	   || TREE_CODE (arg) == NON_LVALUE_EXPR
1779 	   || class_nttp_const_wrapper_p (arg))
1780       arg = TREE_OPERAND (arg, 0);
1781 
1782   enum tree_code code = TREE_CODE (arg);
1783 
1784   val = iterative_hash_object (code, val);
1785 
1786   switch (code)
1787     {
1788     case ARGUMENT_PACK_SELECT:
1789       gcc_unreachable ();
1790 
1791     case ERROR_MARK:
1792       return val;
1793 
1794     case IDENTIFIER_NODE:
1795       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1796 
1797     case TREE_VEC:
1798       for (int i = 0, len = TREE_VEC_LENGTH (arg); i < len; ++i)
1799 	val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1800       return val;
1801 
1802     case TYPE_PACK_EXPANSION:
1803     case EXPR_PACK_EXPANSION:
1804       val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1805       return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1806 
1807     case TYPE_ARGUMENT_PACK:
1808     case NONTYPE_ARGUMENT_PACK:
1809       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1810 
1811     case TREE_LIST:
1812       for (; arg; arg = TREE_CHAIN (arg))
1813 	val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1814       return val;
1815 
1816     case OVERLOAD:
1817       for (lkp_iterator iter (arg); iter; ++iter)
1818 	val = iterative_hash_template_arg (*iter, val);
1819       return val;
1820 
1821     case CONSTRUCTOR:
1822       {
1823 	tree field, value;
1824 	unsigned i;
1825 	iterative_hash_template_arg (TREE_TYPE (arg), val);
1826 	FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1827 	  {
1828 	    val = iterative_hash_template_arg (field, val);
1829 	    val = iterative_hash_template_arg (value, val);
1830 	  }
1831 	return val;
1832       }
1833 
1834     case PARM_DECL:
1835       if (!DECL_ARTIFICIAL (arg))
1836 	{
1837 	  val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1838 	  val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1839 	}
1840       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1841 
1842     case TARGET_EXPR:
1843       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1844 
1845     case PTRMEM_CST:
1846       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1847       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1848 
1849     case TEMPLATE_PARM_INDEX:
1850       val = iterative_hash_template_arg
1851 	(TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1852       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1853       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1854 
1855     case TRAIT_EXPR:
1856       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1857       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1858       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1859 
1860     case BASELINK:
1861       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1862 					 val);
1863       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1864 					  val);
1865 
1866     case MODOP_EXPR:
1867       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1868       code = TREE_CODE (TREE_OPERAND (arg, 1));
1869       val = iterative_hash_object (code, val);
1870       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1871 
1872     case LAMBDA_EXPR:
1873       /* [temp.over.link] Two lambda-expressions are never considered
1874 	 equivalent.
1875 
1876          So just hash the closure type.  */
1877       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1878 
1879     case CAST_EXPR:
1880     case IMPLICIT_CONV_EXPR:
1881     case STATIC_CAST_EXPR:
1882     case REINTERPRET_CAST_EXPR:
1883     case CONST_CAST_EXPR:
1884     case DYNAMIC_CAST_EXPR:
1885     case NEW_EXPR:
1886       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1887       /* Now hash operands as usual.  */
1888       break;
1889 
1890     case CALL_EXPR:
1891       {
1892 	tree fn = CALL_EXPR_FN (arg);
1893 	if (tree name = dependent_name (fn))
1894 	  {
1895 	    if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
1896 	      val = iterative_hash_template_arg (TREE_OPERAND (fn, 1), val);
1897 	    fn = name;
1898 	  }
1899 	val = iterative_hash_template_arg (fn, val);
1900 	call_expr_arg_iterator ai;
1901 	for (tree x = first_call_expr_arg (arg, &ai); x;
1902 	     x = next_call_expr_arg (&ai))
1903 	  val = iterative_hash_template_arg (x, val);
1904 	return val;
1905       }
1906 
1907     default:
1908       break;
1909     }
1910 
1911   char tclass = TREE_CODE_CLASS (code);
1912   switch (tclass)
1913     {
1914     case tcc_type:
1915       if (tree ats = alias_template_specialization_p (arg, nt_transparent))
1916 	{
1917 	  // We want an alias specialization that survived strip_typedefs
1918 	  // to hash differently from its TYPE_CANONICAL, to avoid hash
1919 	  // collisions that compare as different in template_args_equal.
1920 	  // These could be dependent specializations that strip_typedefs
1921 	  // left alone, or untouched specializations because
1922 	  // coerce_template_parms returns the unconverted template
1923 	  // arguments if it sees incomplete argument packs.
1924 	  tree ti = TYPE_ALIAS_TEMPLATE_INFO (ats);
1925 	  return hash_tmpl_and_args (TI_TEMPLATE (ti), TI_ARGS (ti));
1926 	}
1927 
1928       switch (TREE_CODE (arg))
1929 	{
1930 	case TEMPLATE_TEMPLATE_PARM:
1931 	  {
1932 	    tree tpi = TEMPLATE_TYPE_PARM_INDEX (arg);
1933 
1934 	    /* Do not recurse with TPI directly, as that is unbounded
1935 	       recursion.  */
1936 	    val = iterative_hash_object (TEMPLATE_PARM_LEVEL (tpi), val);
1937 	    val = iterative_hash_object (TEMPLATE_PARM_IDX (tpi), val);
1938 	  }
1939 	  break;
1940 
1941 	case  DECLTYPE_TYPE:
1942 	  val = iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1943 	  break;
1944 
1945 	default:
1946 	  if (tree canonical = TYPE_CANONICAL (arg))
1947 	    val = iterative_hash_object (TYPE_HASH (canonical), val);
1948 	  break;
1949 	}
1950 
1951       return val;
1952 
1953     case tcc_declaration:
1954     case tcc_constant:
1955       return iterative_hash_expr (arg, val);
1956 
1957     default:
1958       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1959       for (int i = 0, n = cp_tree_operand_length (arg); i < n; ++i)
1960 	val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1961       return val;
1962     }
1963 
1964   gcc_unreachable ();
1965   return 0;
1966 }
1967 
1968 /* Unregister the specialization SPEC as a specialization of TMPL.
1969    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1970    if the SPEC was listed as a specialization of TMPL.
1971 
1972    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1973 
1974 bool
reregister_specialization(tree spec,tree tinfo,tree new_spec)1975 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1976 {
1977   spec_entry *entry;
1978   spec_entry elt;
1979 
1980   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1981   elt.args = TI_ARGS (tinfo);
1982   elt.spec = NULL_TREE;
1983 
1984   entry = decl_specializations->find (&elt);
1985   if (entry != NULL)
1986     {
1987       gcc_assert (entry->spec == spec || entry->spec == new_spec);
1988       gcc_assert (new_spec != NULL_TREE);
1989       entry->spec = new_spec;
1990       return 1;
1991     }
1992 
1993   return 0;
1994 }
1995 
1996 /* Like register_specialization, but for local declarations.  We are
1997    registering SPEC, an instantiation of TMPL.  */
1998 
1999 void
register_local_specialization(tree spec,tree tmpl)2000 register_local_specialization (tree spec, tree tmpl)
2001 {
2002   gcc_assert (tmpl != spec);
2003   local_specializations->put (tmpl, spec);
2004 }
2005 
2006 /* TYPE is a class type.  Returns true if TYPE is an explicitly
2007    specialized class.  */
2008 
2009 bool
explicit_class_specialization_p(tree type)2010 explicit_class_specialization_p (tree type)
2011 {
2012   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
2013     return false;
2014   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
2015 }
2016 
2017 /* Print the list of functions at FNS, going through all the overloads
2018    for each element of the list.  Alternatively, FNS cannot be a
2019    TREE_LIST, in which case it will be printed together with all the
2020    overloads.
2021 
2022    MORE and *STR should respectively be FALSE and NULL when the function
2023    is called from the outside.  They are used internally on recursive
2024    calls.  print_candidates manages the two parameters and leaves NULL
2025    in *STR when it ends.  */
2026 
2027 static void
2028 print_candidates_1 (tree fns, char **str, bool more = false)
2029 {
2030   if (TREE_CODE (fns) == TREE_LIST)
2031     for (; fns; fns = TREE_CHAIN (fns))
2032       print_candidates_1 (TREE_VALUE (fns), str, more || TREE_CHAIN (fns));
2033   else
2034     for (lkp_iterator iter (fns); iter;)
2035       {
2036 	tree cand = *iter;
2037 	++iter;
2038 
2039 	const char *pfx = *str;
2040 	if (!pfx)
2041 	  {
2042 	    if (more || iter)
2043 	      pfx = _("candidates are:");
2044 	    else
2045 	      pfx = _("candidate is:");
2046 	    *str = get_spaces (pfx);
2047 	  }
2048 	inform (DECL_SOURCE_LOCATION (cand), "%s %#qD", pfx, cand);
2049       }
2050 }
2051 
2052 /* Print the list of candidate FNS in an error message.  FNS can also
2053    be a TREE_LIST of non-functions in the case of an ambiguous lookup.  */
2054 
2055 void
print_candidates(tree fns)2056 print_candidates (tree fns)
2057 {
2058   char *str = NULL;
2059   print_candidates_1 (fns, &str);
2060   free (str);
2061 }
2062 
2063 /* Get a (possibly) constrained template declaration for the
2064    purpose of ordering candidates.  */
2065 static tree
get_template_for_ordering(tree list)2066 get_template_for_ordering (tree list)
2067 {
2068   gcc_assert (TREE_CODE (list) == TREE_LIST);
2069   tree f = TREE_VALUE (list);
2070   if (tree ti = DECL_TEMPLATE_INFO (f))
2071     return TI_TEMPLATE (ti);
2072   return f;
2073 }
2074 
2075 /* Among candidates having the same signature, return the
2076    most constrained or NULL_TREE if there is no best candidate.
2077    If the signatures of candidates vary (e.g., template
2078    specialization vs. member function), then there can be no
2079    most constrained.
2080 
2081    Note that we don't compare constraints on the functions
2082    themselves, but rather those of their templates. */
2083 static tree
most_constrained_function(tree candidates)2084 most_constrained_function (tree candidates)
2085 {
2086   // Try to find the best candidate in a first pass.
2087   tree champ = candidates;
2088   for (tree c = TREE_CHAIN (champ); c; c = TREE_CHAIN (c))
2089     {
2090       int winner = more_constrained (get_template_for_ordering (champ),
2091                                      get_template_for_ordering (c));
2092       if (winner == -1)
2093         champ = c; // The candidate is more constrained
2094       else if (winner == 0)
2095         return NULL_TREE; // Neither is more constrained
2096     }
2097 
2098   // Verify that the champ is better than previous candidates.
2099   for (tree c = candidates; c != champ; c = TREE_CHAIN (c)) {
2100     if (!more_constrained (get_template_for_ordering (champ),
2101                            get_template_for_ordering (c)))
2102       return NULL_TREE;
2103   }
2104 
2105   return champ;
2106 }
2107 
2108 
2109 /* Returns the template (one of the functions given by TEMPLATE_ID)
2110    which can be specialized to match the indicated DECL with the
2111    explicit template args given in TEMPLATE_ID.  The DECL may be
2112    NULL_TREE if none is available.  In that case, the functions in
2113    TEMPLATE_ID are non-members.
2114 
2115    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
2116    specialization of a member template.
2117 
2118    The TEMPLATE_COUNT is the number of references to qualifying
2119    template classes that appeared in the name of the function. See
2120    check_explicit_specialization for a more accurate description.
2121 
2122    TSK indicates what kind of template declaration (if any) is being
2123    declared.  TSK_TEMPLATE indicates that the declaration given by
2124    DECL, though a FUNCTION_DECL, has template parameters, and is
2125    therefore a template function.
2126 
2127    The template args (those explicitly specified and those deduced)
2128    are output in a newly created vector *TARGS_OUT.
2129 
2130    If it is impossible to determine the result, an error message is
2131    issued.  The error_mark_node is returned to indicate failure.  */
2132 
2133 static tree
determine_specialization(tree template_id,tree decl,tree * targs_out,int need_member_template,int template_count,tmpl_spec_kind tsk)2134 determine_specialization (tree template_id,
2135 			  tree decl,
2136 			  tree* targs_out,
2137 			  int need_member_template,
2138 			  int template_count,
2139 			  tmpl_spec_kind tsk)
2140 {
2141   tree fns;
2142   tree targs;
2143   tree explicit_targs;
2144   tree candidates = NULL_TREE;
2145 
2146   /* A TREE_LIST of templates of which DECL may be a specialization.
2147      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
2148      corresponding TREE_PURPOSE is the set of template arguments that,
2149      when used to instantiate the template, would produce a function
2150      with the signature of DECL.  */
2151   tree templates = NULL_TREE;
2152   int header_count;
2153   cp_binding_level *b;
2154 
2155   *targs_out = NULL_TREE;
2156 
2157   if (template_id == error_mark_node || decl == error_mark_node)
2158     return error_mark_node;
2159 
2160   /* We shouldn't be specializing a member template of an
2161      unspecialized class template; we already gave an error in
2162      check_specialization_scope, now avoid crashing.  */
2163   if (!VAR_P (decl)
2164       && template_count && DECL_CLASS_SCOPE_P (decl)
2165       && template_class_depth (DECL_CONTEXT (decl)) > 0)
2166     {
2167       gcc_assert (errorcount);
2168       return error_mark_node;
2169     }
2170 
2171   fns = TREE_OPERAND (template_id, 0);
2172   explicit_targs = TREE_OPERAND (template_id, 1);
2173 
2174   if (fns == error_mark_node)
2175     return error_mark_node;
2176 
2177   /* Check for baselinks.  */
2178   if (BASELINK_P (fns))
2179     fns = BASELINK_FUNCTIONS (fns);
2180 
2181   if (TREE_CODE (decl) == FUNCTION_DECL && !is_overloaded_fn (fns))
2182     {
2183       error_at (DECL_SOURCE_LOCATION (decl),
2184 		"%qD is not a function template", fns);
2185       return error_mark_node;
2186     }
2187   else if (VAR_P (decl) && !variable_template_p (fns))
2188     {
2189       error ("%qD is not a variable template", fns);
2190       return error_mark_node;
2191     }
2192 
2193   /* Count the number of template headers specified for this
2194      specialization.  */
2195   header_count = 0;
2196   for (b = current_binding_level;
2197        b->kind == sk_template_parms;
2198        b = b->level_chain)
2199     ++header_count;
2200 
2201   tree orig_fns = fns;
2202   bool header_mismatch = false;
2203 
2204   if (variable_template_p (fns))
2205     {
2206       tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (fns));
2207       targs = coerce_template_parms (parms, explicit_targs, fns,
2208 				     tf_warning_or_error,
2209 				     /*req_all*/true, /*use_defarg*/true);
2210       if (targs != error_mark_node)
2211         templates = tree_cons (targs, fns, templates);
2212     }
2213   else for (lkp_iterator iter (fns); iter; ++iter)
2214     {
2215       tree fn = *iter;
2216 
2217       if (TREE_CODE (fn) == TEMPLATE_DECL)
2218 	{
2219 	  tree decl_arg_types;
2220 	  tree fn_arg_types;
2221 	  tree insttype;
2222 
2223 	  /* In case of explicit specialization, we need to check if
2224 	     the number of template headers appearing in the specialization
2225 	     is correct. This is usually done in check_explicit_specialization,
2226 	     but the check done there cannot be exhaustive when specializing
2227 	     member functions. Consider the following code:
2228 
2229 	     template <> void A<int>::f(int);
2230 	     template <> template <> void A<int>::f(int);
2231 
2232 	     Assuming that A<int> is not itself an explicit specialization
2233 	     already, the first line specializes "f" which is a non-template
2234 	     member function, whilst the second line specializes "f" which
2235 	     is a template member function. So both lines are syntactically
2236 	     correct, and check_explicit_specialization does not reject
2237 	     them.
2238 
2239 	     Here, we can do better, as we are matching the specialization
2240 	     against the declarations. We count the number of template
2241 	     headers, and we check if they match TEMPLATE_COUNT + 1
2242 	     (TEMPLATE_COUNT is the number of qualifying template classes,
2243 	     plus there must be another header for the member template
2244 	     itself).
2245 
2246 	     Notice that if header_count is zero, this is not a
2247 	     specialization but rather a template instantiation, so there
2248 	     is no check we can perform here.  */
2249 	  if (header_count && header_count != template_count + 1)
2250 	    {
2251 	      header_mismatch = true;
2252 	      continue;
2253 	    }
2254 
2255 	  /* Check that the number of template arguments at the
2256 	     innermost level for DECL is the same as for FN.  */
2257 	  if (current_binding_level->kind == sk_template_parms
2258 	      && !current_binding_level->explicit_spec_p
2259 	      && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
2260 		  != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
2261 				      (current_template_parms))))
2262 	    continue;
2263 
2264 	  /* DECL might be a specialization of FN.  */
2265 	  decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2266 	  fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
2267 
2268 	  /* For a non-static member function, we need to make sure
2269 	     that the const qualification is the same.  Since
2270 	     get_bindings does not try to merge the "this" parameter,
2271 	     we must do the comparison explicitly.  */
2272 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
2273 	    {
2274 	      if (!same_type_p (TREE_VALUE (fn_arg_types),
2275 				TREE_VALUE (decl_arg_types)))
2276 		continue;
2277 
2278 	      /* And the ref-qualification.  */
2279 	      if (type_memfn_rqual (TREE_TYPE (decl))
2280 		  != type_memfn_rqual (TREE_TYPE (fn)))
2281 		continue;
2282 	    }
2283 
2284 	  /* Skip the "this" parameter and, for constructors of
2285 	     classes with virtual bases, the VTT parameter.  A
2286 	     full specialization of a constructor will have a VTT
2287 	     parameter, but a template never will.  */
2288 	  decl_arg_types
2289 	    = skip_artificial_parms_for (decl, decl_arg_types);
2290 	  fn_arg_types
2291 	    = skip_artificial_parms_for (fn, fn_arg_types);
2292 
2293 	  /* Function templates cannot be specializations; there are
2294 	     no partial specializations of functions.  Therefore, if
2295 	     the type of DECL does not match FN, there is no
2296 	     match.
2297 
2298              Note that it should never be the case that we have both
2299              candidates added here, and for regular member functions
2300              below. */
2301 	  if (tsk == tsk_template)
2302 	    {
2303 	      if (!comp_template_parms (DECL_TEMPLATE_PARMS (fn),
2304 					current_template_parms))
2305 		continue;
2306 	      if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2307 				TREE_TYPE (TREE_TYPE (fn))))
2308 		continue;
2309 	      if (!compparms (fn_arg_types, decl_arg_types))
2310 		continue;
2311 
2312 	      tree freq = get_trailing_function_requirements (fn);
2313 	      tree dreq = get_trailing_function_requirements (decl);
2314 	      if (!freq != !dreq)
2315 		continue;
2316 	      if (freq)
2317 		{
2318 		  tree fargs = DECL_TI_ARGS (fn);
2319 		  tsubst_flags_t complain = tf_none;
2320 		  freq = tsubst_constraint (freq, fargs, complain, fn);
2321 		  if (!cp_tree_equal (freq, dreq))
2322 		    continue;
2323 		}
2324 
2325 	      candidates = tree_cons (NULL_TREE, fn, candidates);
2326 	      continue;
2327 	    }
2328 
2329 	  /* See whether this function might be a specialization of this
2330 	     template.  Suppress access control because we might be trying
2331 	     to make this specialization a friend, and we have already done
2332 	     access control for the declaration of the specialization.  */
2333 	  push_deferring_access_checks (dk_no_check);
2334 	  targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
2335 	  pop_deferring_access_checks ();
2336 
2337 	  if (!targs)
2338 	    /* We cannot deduce template arguments that when used to
2339 	       specialize TMPL will produce DECL.  */
2340 	    continue;
2341 
2342 	  if (uses_template_parms (targs))
2343 	    /* We deduced something involving 'auto', which isn't a valid
2344 	       template argument.  */
2345 	    continue;
2346 
2347           /* Remove, from the set of candidates, all those functions
2348              whose constraints are not satisfied. */
2349           if (flag_concepts && !constraints_satisfied_p (fn, targs))
2350             continue;
2351 
2352           // Then, try to form the new function type.
2353 	  insttype = tsubst (TREE_TYPE (fn), targs, tf_fndecl_type, NULL_TREE);
2354 	  if (insttype == error_mark_node)
2355 	    continue;
2356 	  fn_arg_types
2357 	    = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (insttype));
2358 	  if (!compparms (fn_arg_types, decl_arg_types))
2359 	    continue;
2360 
2361 	  /* Save this template, and the arguments deduced.  */
2362 	  templates = tree_cons (targs, fn, templates);
2363 	}
2364       else if (need_member_template)
2365 	/* FN is an ordinary member function, and we need a
2366 	   specialization of a member template.  */
2367 	;
2368       else if (TREE_CODE (fn) != FUNCTION_DECL)
2369 	/* We can get IDENTIFIER_NODEs here in certain erroneous
2370 	   cases.  */
2371 	;
2372       else if (!DECL_FUNCTION_MEMBER_P (fn))
2373 	/* This is just an ordinary non-member function.  Nothing can
2374 	   be a specialization of that.  */
2375 	;
2376       else if (DECL_ARTIFICIAL (fn))
2377 	/* Cannot specialize functions that are created implicitly.  */
2378 	;
2379       else
2380 	{
2381 	  tree decl_arg_types;
2382 
2383 	  /* This is an ordinary member function.  However, since
2384 	     we're here, we can assume its enclosing class is a
2385 	     template class.  For example,
2386 
2387 	       template <typename T> struct S { void f(); };
2388 	       template <> void S<int>::f() {}
2389 
2390 	     Here, S<int>::f is a non-template, but S<int> is a
2391 	     template class.  If FN has the same type as DECL, we
2392 	     might be in business.  */
2393 
2394 	  if (!DECL_TEMPLATE_INFO (fn))
2395 	    /* Its enclosing class is an explicit specialization
2396 	       of a template class.  This is not a candidate.  */
2397 	    continue;
2398 
2399 	  if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2400 			    TREE_TYPE (TREE_TYPE (fn))))
2401 	    /* The return types differ.  */
2402 	    continue;
2403 
2404 	  /* Adjust the type of DECL in case FN is a static member.  */
2405 	  decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2406 	  if (DECL_STATIC_FUNCTION_P (fn)
2407 	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2408 	    decl_arg_types = TREE_CHAIN (decl_arg_types);
2409 
2410 	  if (!compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2411 			 decl_arg_types))
2412             continue;
2413 
2414 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2415 	      && (type_memfn_rqual (TREE_TYPE (decl))
2416 		  != type_memfn_rqual (TREE_TYPE (fn))))
2417 	    continue;
2418 
2419           // If the deduced arguments do not satisfy the constraints,
2420           // this is not a candidate.
2421           if (flag_concepts && !constraints_satisfied_p (fn))
2422             continue;
2423 
2424           // Add the candidate.
2425           candidates = tree_cons (NULL_TREE, fn, candidates);
2426 	}
2427     }
2428 
2429   if (templates && TREE_CHAIN (templates))
2430     {
2431       /* We have:
2432 
2433 	   [temp.expl.spec]
2434 
2435 	   It is possible for a specialization with a given function
2436 	   signature to be instantiated from more than one function
2437 	   template.  In such cases, explicit specification of the
2438 	   template arguments must be used to uniquely identify the
2439 	   function template specialization being specialized.
2440 
2441 	 Note that here, there's no suggestion that we're supposed to
2442 	 determine which of the candidate templates is most
2443 	 specialized.  However, we, also have:
2444 
2445 	   [temp.func.order]
2446 
2447 	   Partial ordering of overloaded function template
2448 	   declarations is used in the following contexts to select
2449 	   the function template to which a function template
2450 	   specialization refers:
2451 
2452 	   -- when an explicit specialization refers to a function
2453 	      template.
2454 
2455 	 So, we do use the partial ordering rules, at least for now.
2456 	 This extension can only serve to make invalid programs valid,
2457 	 so it's safe.  And, there is strong anecdotal evidence that
2458 	 the committee intended the partial ordering rules to apply;
2459 	 the EDG front end has that behavior, and John Spicer claims
2460 	 that the committee simply forgot to delete the wording in
2461 	 [temp.expl.spec].  */
2462       tree tmpl = most_specialized_instantiation (templates);
2463       if (tmpl != error_mark_node)
2464 	{
2465 	  templates = tmpl;
2466 	  TREE_CHAIN (templates) = NULL_TREE;
2467 	}
2468     }
2469 
2470   // Concepts allows multiple declarations of member functions
2471   // with the same signature. Like above, we need to rely on
2472   // on the partial ordering of those candidates to determine which
2473   // is the best.
2474   if (flag_concepts && candidates && TREE_CHAIN (candidates))
2475     {
2476       if (tree cand = most_constrained_function (candidates))
2477         {
2478           candidates = cand;
2479           TREE_CHAIN (cand) = NULL_TREE;
2480         }
2481     }
2482 
2483   if (templates == NULL_TREE && candidates == NULL_TREE)
2484     {
2485       error ("template-id %qD for %q+D does not match any template "
2486 	     "declaration", template_id, decl);
2487       if (header_mismatch)
2488 	inform (DECL_SOURCE_LOCATION (decl),
2489 		"saw %d %<template<>%>, need %d for "
2490 		"specializing a member function template",
2491 		header_count, template_count + 1);
2492       print_candidates (orig_fns);
2493       return error_mark_node;
2494     }
2495   else if ((templates && TREE_CHAIN (templates))
2496 	   || (candidates && TREE_CHAIN (candidates))
2497 	   || (templates && candidates))
2498     {
2499       error ("ambiguous template specialization %qD for %q+D",
2500 	     template_id, decl);
2501       candidates = chainon (candidates, templates);
2502       print_candidates (candidates);
2503       return error_mark_node;
2504     }
2505 
2506   /* We have one, and exactly one, match.  */
2507   if (candidates)
2508     {
2509       tree fn = TREE_VALUE (candidates);
2510       *targs_out = copy_node (DECL_TI_ARGS (fn));
2511 
2512       /* Propagate the candidate's constraints to the declaration.  */
2513       if (tsk != tsk_template)
2514 	set_constraints (decl, get_constraints (fn));
2515 
2516       /* DECL is a re-declaration or partial instantiation of a template
2517 	 function.  */
2518       if (TREE_CODE (fn) == TEMPLATE_DECL)
2519 	return fn;
2520       /* It was a specialization of an ordinary member function in a
2521 	 template class.  */
2522       return DECL_TI_TEMPLATE (fn);
2523     }
2524 
2525   /* It was a specialization of a template.  */
2526   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2527   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2528     {
2529       *targs_out = copy_node (targs);
2530       SET_TMPL_ARGS_LEVEL (*targs_out,
2531 			   TMPL_ARGS_DEPTH (*targs_out),
2532 			   TREE_PURPOSE (templates));
2533     }
2534   else
2535     *targs_out = TREE_PURPOSE (templates);
2536   return TREE_VALUE (templates);
2537 }
2538 
2539 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2540    but with the default argument values filled in from those in the
2541    TMPL_TYPES.  */
2542 
2543 static tree
copy_default_args_to_explicit_spec_1(tree spec_types,tree tmpl_types)2544 copy_default_args_to_explicit_spec_1 (tree spec_types,
2545 				      tree tmpl_types)
2546 {
2547   tree new_spec_types;
2548 
2549   if (!spec_types)
2550     return NULL_TREE;
2551 
2552   if (spec_types == void_list_node)
2553     return void_list_node;
2554 
2555   /* Substitute into the rest of the list.  */
2556   new_spec_types =
2557     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2558 					  TREE_CHAIN (tmpl_types));
2559 
2560   /* Add the default argument for this parameter.  */
2561   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2562 			 TREE_VALUE (spec_types),
2563 			 new_spec_types);
2564 }
2565 
2566 /* DECL is an explicit specialization.  Replicate default arguments
2567    from the template it specializes.  (That way, code like:
2568 
2569      template <class T> void f(T = 3);
2570      template <> void f(double);
2571      void g () { f (); }
2572 
2573    works, as required.)  An alternative approach would be to look up
2574    the correct default arguments at the call-site, but this approach
2575    is consistent with how implicit instantiations are handled.  */
2576 
2577 static void
copy_default_args_to_explicit_spec(tree decl)2578 copy_default_args_to_explicit_spec (tree decl)
2579 {
2580   tree tmpl;
2581   tree spec_types;
2582   tree tmpl_types;
2583   tree new_spec_types;
2584   tree old_type;
2585   tree new_type;
2586   tree t;
2587   tree object_type = NULL_TREE;
2588   tree in_charge = NULL_TREE;
2589   tree vtt = NULL_TREE;
2590 
2591   /* See if there's anything we need to do.  */
2592   tmpl = DECL_TI_TEMPLATE (decl);
2593   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2594   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2595     if (TREE_PURPOSE (t))
2596       break;
2597   if (!t)
2598     return;
2599 
2600   old_type = TREE_TYPE (decl);
2601   spec_types = TYPE_ARG_TYPES (old_type);
2602 
2603   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2604     {
2605       /* Remove the this pointer, but remember the object's type for
2606 	 CV quals.  */
2607       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2608       spec_types = TREE_CHAIN (spec_types);
2609       tmpl_types = TREE_CHAIN (tmpl_types);
2610 
2611       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2612 	{
2613 	  /* DECL may contain more parameters than TMPL due to the extra
2614 	     in-charge parameter in constructors and destructors.  */
2615 	  in_charge = spec_types;
2616 	  spec_types = TREE_CHAIN (spec_types);
2617 	}
2618       if (DECL_HAS_VTT_PARM_P (decl))
2619 	{
2620 	  vtt = spec_types;
2621 	  spec_types = TREE_CHAIN (spec_types);
2622 	}
2623     }
2624 
2625   /* Compute the merged default arguments.  */
2626   new_spec_types =
2627     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2628 
2629   /* Compute the new FUNCTION_TYPE.  */
2630   if (object_type)
2631     {
2632       if (vtt)
2633 	new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2634 					 TREE_VALUE (vtt),
2635 					 new_spec_types);
2636 
2637       if (in_charge)
2638 	/* Put the in-charge parameter back.  */
2639 	new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2640 					 TREE_VALUE (in_charge),
2641 					 new_spec_types);
2642 
2643       new_type = build_method_type_directly (object_type,
2644 					     TREE_TYPE (old_type),
2645 					     new_spec_types);
2646     }
2647   else
2648     new_type = build_function_type (TREE_TYPE (old_type),
2649 				    new_spec_types);
2650   new_type = cp_build_type_attribute_variant (new_type,
2651 					      TYPE_ATTRIBUTES (old_type));
2652   new_type = cxx_copy_lang_qualifiers (new_type, old_type);
2653 
2654   TREE_TYPE (decl) = new_type;
2655 }
2656 
2657 /* Return the number of template headers we expect to see for a definition
2658    or specialization of CTYPE or one of its non-template members.  */
2659 
2660 int
num_template_headers_for_class(tree ctype)2661 num_template_headers_for_class (tree ctype)
2662 {
2663   int num_templates = 0;
2664 
2665   while (ctype && CLASS_TYPE_P (ctype))
2666     {
2667       /* You're supposed to have one `template <...>' for every
2668 	 template class, but you don't need one for a full
2669 	 specialization.  For example:
2670 
2671 	 template <class T> struct S{};
2672 	 template <> struct S<int> { void f(); };
2673 	 void S<int>::f () {}
2674 
2675 	 is correct; there shouldn't be a `template <>' for the
2676 	 definition of `S<int>::f'.  */
2677       if (!CLASSTYPE_TEMPLATE_INFO (ctype))
2678 	/* If CTYPE does not have template information of any
2679 	   kind,  then it is not a template, nor is it nested
2680 	   within a template.  */
2681 	break;
2682       if (explicit_class_specialization_p (ctype))
2683 	break;
2684       if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (ctype)))
2685 	++num_templates;
2686 
2687       ctype = TYPE_CONTEXT (ctype);
2688     }
2689 
2690   return num_templates;
2691 }
2692 
2693 /* Do a simple sanity check on the template headers that precede the
2694    variable declaration DECL.  */
2695 
2696 void
check_template_variable(tree decl)2697 check_template_variable (tree decl)
2698 {
2699   tree ctx = CP_DECL_CONTEXT (decl);
2700   int wanted = num_template_headers_for_class (ctx);
2701   if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
2702       && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
2703     {
2704       if (cxx_dialect < cxx14)
2705         pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2706 		 "variable templates only available with "
2707 		 "%<-std=c++14%> or %<-std=gnu++14%>");
2708 
2709       // Namespace-scope variable templates should have a template header.
2710       ++wanted;
2711     }
2712   if (template_header_count > wanted)
2713     {
2714       auto_diagnostic_group d;
2715       bool warned = pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2716 			     "too many template headers for %qD "
2717 	                     "(should be %d)",
2718 			     decl, wanted);
2719       if (warned && CLASS_TYPE_P (ctx)
2720 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (ctx))
2721 	inform (DECL_SOURCE_LOCATION (decl),
2722 		"members of an explicitly specialized class are defined "
2723 		"without a template header");
2724     }
2725 }
2726 
2727 /* An explicit specialization whose declarator-id or class-head-name is not
2728    qualified shall be declared in the nearest enclosing namespace of the
2729    template, or, if the namespace is inline (7.3.1), any namespace from its
2730    enclosing namespace set.
2731 
2732    If the name declared in the explicit instantiation is an unqualified name,
2733    the explicit instantiation shall appear in the namespace where its template
2734    is declared or, if that namespace is inline (7.3.1), any namespace from its
2735    enclosing namespace set.  */
2736 
2737 void
check_unqualified_spec_or_inst(tree t,location_t loc)2738 check_unqualified_spec_or_inst (tree t, location_t loc)
2739 {
2740   tree tmpl = most_general_template (t);
2741   if (DECL_NAMESPACE_SCOPE_P (tmpl)
2742       && !is_nested_namespace (current_namespace,
2743 			       CP_DECL_CONTEXT (tmpl), true))
2744     {
2745       if (processing_specialization)
2746 	permerror (loc, "explicit specialization of %qD outside its "
2747 		   "namespace must use a nested-name-specifier", tmpl);
2748       else if (processing_explicit_instantiation
2749 	       && cxx_dialect >= cxx11)
2750 	/* This was allowed in C++98, so only pedwarn.  */
2751 	pedwarn (loc, OPT_Wpedantic, "explicit instantiation of %qD "
2752 		 "outside its namespace must use a nested-name-"
2753 		 "specifier", tmpl);
2754     }
2755 }
2756 
2757 /* Warn for a template specialization SPEC that is missing some of a set
2758    of function or type attributes that the template TEMPL is declared with.
2759    ATTRLIST is a list of additional attributes that SPEC should be taken
2760    to ultimately be declared with.  */
2761 
2762 static void
warn_spec_missing_attributes(tree tmpl,tree spec,tree attrlist)2763 warn_spec_missing_attributes (tree tmpl, tree spec, tree attrlist)
2764 {
2765   if (DECL_FUNCTION_TEMPLATE_P (tmpl))
2766     tmpl = DECL_TEMPLATE_RESULT (tmpl);
2767 
2768   /* Avoid warning if the difference between the primary and
2769      the specialization is not in one of the attributes below.  */
2770   const char* const blacklist[] = {
2771     "alloc_align", "alloc_size", "assume_aligned", "format",
2772     "format_arg", "malloc", "nonnull", NULL
2773   };
2774 
2775   /* Put together a list of the black listed attributes that the primary
2776      template is declared with that the specialization is not, in case
2777      it's not apparent from the most recent declaration of the primary.  */
2778   pretty_printer str;
2779   unsigned nattrs = decls_mismatched_attributes (tmpl, spec, attrlist,
2780 						 blacklist, &str);
2781 
2782   if (!nattrs)
2783     return;
2784 
2785   auto_diagnostic_group d;
2786   if (warning_at (DECL_SOURCE_LOCATION (spec), OPT_Wmissing_attributes,
2787 		  "explicit specialization %q#D may be missing attributes",
2788 		  spec))
2789     inform (DECL_SOURCE_LOCATION (tmpl),
2790 	    nattrs > 1
2791 	    ? G_("missing primary template attributes %s")
2792 	    : G_("missing primary template attribute %s"),
2793 	    pp_formatted_text (&str));
2794 }
2795 
2796 /* Check to see if the function just declared, as indicated in
2797    DECLARATOR, and in DECL, is a specialization of a function
2798    template.  We may also discover that the declaration is an explicit
2799    instantiation at this point.
2800 
2801    Returns DECL, or an equivalent declaration that should be used
2802    instead if all goes well.  Issues an error message if something is
2803    amiss.  Returns error_mark_node if the error is not easily
2804    recoverable.
2805 
2806    FLAGS is a bitmask consisting of the following flags:
2807 
2808    2: The function has a definition.
2809    4: The function is a friend.
2810 
2811    The TEMPLATE_COUNT is the number of references to qualifying
2812    template classes that appeared in the name of the function.  For
2813    example, in
2814 
2815      template <class T> struct S { void f(); };
2816      void S<int>::f();
2817 
2818    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2819    classes are not counted in the TEMPLATE_COUNT, so that in
2820 
2821      template <class T> struct S {};
2822      template <> struct S<int> { void f(); }
2823      template <> void S<int>::f();
2824 
2825    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2826    invalid; there should be no template <>.)
2827 
2828    If the function is a specialization, it is marked as such via
2829    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2830    is set up correctly, and it is added to the list of specializations
2831    for that template.  */
2832 
2833 tree
check_explicit_specialization(tree declarator,tree decl,int template_count,int flags,tree attrlist)2834 check_explicit_specialization (tree declarator,
2835 			       tree decl,
2836 			       int template_count,
2837 			       int flags,
2838 			       tree attrlist)
2839 {
2840   int have_def = flags & 2;
2841   int is_friend = flags & 4;
2842   bool is_concept = flags & 8;
2843   int specialization = 0;
2844   int explicit_instantiation = 0;
2845   int member_specialization = 0;
2846   tree ctype = DECL_CLASS_CONTEXT (decl);
2847   tree dname = DECL_NAME (decl);
2848   tmpl_spec_kind tsk;
2849 
2850   if (is_friend)
2851     {
2852       if (!processing_specialization)
2853 	tsk = tsk_none;
2854       else
2855 	tsk = tsk_excessive_parms;
2856     }
2857   else
2858     tsk = current_tmpl_spec_kind (template_count);
2859 
2860   switch (tsk)
2861     {
2862     case tsk_none:
2863       if (processing_specialization && !VAR_P (decl))
2864 	{
2865 	  specialization = 1;
2866 	  SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2867 	}
2868       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2869 	{
2870 	  if (is_friend)
2871 	    /* This could be something like:
2872 
2873 	       template <class T> void f(T);
2874 	       class S { friend void f<>(int); }  */
2875 	    specialization = 1;
2876 	  else
2877 	    {
2878 	      /* This case handles bogus declarations like template <>
2879 		 template <class T> void f<int>(); */
2880 
2881 	      error_at (cp_expr_loc_or_input_loc (declarator),
2882 			"template-id %qE in declaration of primary template",
2883 			declarator);
2884 	      return decl;
2885 	    }
2886 	}
2887       break;
2888 
2889     case tsk_invalid_member_spec:
2890       /* The error has already been reported in
2891 	 check_specialization_scope.  */
2892       return error_mark_node;
2893 
2894     case tsk_invalid_expl_inst:
2895       error ("template parameter list used in explicit instantiation");
2896 
2897       /* Fall through.  */
2898 
2899     case tsk_expl_inst:
2900       if (have_def)
2901 	error ("definition provided for explicit instantiation");
2902 
2903       explicit_instantiation = 1;
2904       break;
2905 
2906     case tsk_excessive_parms:
2907     case tsk_insufficient_parms:
2908       if (tsk == tsk_excessive_parms)
2909 	error ("too many template parameter lists in declaration of %qD",
2910 	       decl);
2911       else if (template_header_count)
2912 	error("too few template parameter lists in declaration of %qD", decl);
2913       else
2914 	error("explicit specialization of %qD must be introduced by "
2915 	      "%<template <>%>", decl);
2916 
2917       /* Fall through.  */
2918     case tsk_expl_spec:
2919       if (is_concept)
2920         error ("explicit specialization declared %<concept%>");
2921 
2922       if (VAR_P (decl) && TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2923 	/* In cases like template<> constexpr bool v = true;
2924 	   We'll give an error in check_template_variable.  */
2925 	break;
2926 
2927       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2928       if (ctype)
2929 	member_specialization = 1;
2930       else
2931 	specialization = 1;
2932       break;
2933 
2934     case tsk_template:
2935       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2936 	{
2937 	  /* This case handles bogus declarations like template <>
2938 	     template <class T> void f<int>(); */
2939 
2940 	  if (!uses_template_parms (TREE_OPERAND (declarator, 1)))
2941 	    error_at (cp_expr_loc_or_input_loc (declarator),
2942 		      "template-id %qE in declaration of primary template",
2943 		      declarator);
2944 	  else if (variable_template_p (TREE_OPERAND (declarator, 0)))
2945 	    {
2946 	      /* Partial specialization of variable template.  */
2947 	      SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2948 	      specialization = 1;
2949 	      goto ok;
2950 	    }
2951 	  else if (cxx_dialect < cxx14)
2952 	    error_at (cp_expr_loc_or_input_loc (declarator),
2953 		      "non-type partial specialization %qE "
2954 		      "is not allowed", declarator);
2955 	  else
2956 	    error_at (cp_expr_loc_or_input_loc (declarator),
2957 		      "non-class, non-variable partial specialization %qE "
2958 		      "is not allowed", declarator);
2959 	  return decl;
2960 	ok:;
2961 	}
2962 
2963       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2964 	/* This is a specialization of a member template, without
2965 	   specialization the containing class.  Something like:
2966 
2967 	     template <class T> struct S {
2968 	       template <class U> void f (U);
2969 	     };
2970 	     template <> template <class U> void S<int>::f(U) {}
2971 
2972 	   That's a specialization -- but of the entire template.  */
2973 	specialization = 1;
2974       break;
2975 
2976     default:
2977       gcc_unreachable ();
2978     }
2979 
2980   if ((specialization || member_specialization)
2981       /* This doesn't apply to variable templates.  */
2982       && FUNC_OR_METHOD_TYPE_P (TREE_TYPE (decl)))
2983     {
2984       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2985       for (; t; t = TREE_CHAIN (t))
2986 	if (TREE_PURPOSE (t))
2987 	  {
2988 	    permerror (input_location,
2989 		       "default argument specified in explicit specialization");
2990 	    break;
2991 	  }
2992     }
2993 
2994   if (specialization || member_specialization || explicit_instantiation)
2995     {
2996       tree tmpl = NULL_TREE;
2997       tree targs = NULL_TREE;
2998       bool was_template_id = (TREE_CODE (declarator) == TEMPLATE_ID_EXPR);
2999       bool found_hidden = false;
3000 
3001       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
3002       if (!was_template_id)
3003 	{
3004 	  tree fns;
3005 
3006 	  gcc_assert (identifier_p (declarator));
3007 	  if (ctype)
3008 	    fns = dname;
3009 	  else
3010 	    {
3011 	      /* If there is no class context, the explicit instantiation
3012 		 must be at namespace scope.  */
3013 	      gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
3014 
3015 	      /* Find the namespace binding, using the declaration
3016 		 context.  */
3017 	      fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
3018 					   LOOK_want::NORMAL, true);
3019 	      if (fns == error_mark_node)
3020 		{
3021 		  /* If lookup fails, look for a friend declaration so we can
3022 		     give a better diagnostic.  */
3023 		  fns = (lookup_qualified_name
3024 			 (CP_DECL_CONTEXT (decl), dname,
3025 			  LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND,
3026 			  /*complain*/true));
3027 		  found_hidden = true;
3028 		}
3029 
3030 	      if (fns == error_mark_node || !is_overloaded_fn (fns))
3031 		{
3032 		  error ("%qD is not a template function", dname);
3033 		  fns = error_mark_node;
3034 		}
3035 	    }
3036 
3037 	  declarator = lookup_template_function (fns, NULL_TREE);
3038 	}
3039 
3040       if (declarator == error_mark_node)
3041 	return error_mark_node;
3042 
3043       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
3044 	{
3045 	  if (!explicit_instantiation)
3046 	    /* A specialization in class scope.  This is invalid,
3047 	       but the error will already have been flagged by
3048 	       check_specialization_scope.  */
3049 	    return error_mark_node;
3050 	  else
3051 	    {
3052 	      /* It's not valid to write an explicit instantiation in
3053 		 class scope, e.g.:
3054 
3055 		   class C { template void f(); }
3056 
3057 		   This case is caught by the parser.  However, on
3058 		   something like:
3059 
3060 		   template class C { void f(); };
3061 
3062 		   (which is invalid) we can get here.  The error will be
3063 		   issued later.  */
3064 	      ;
3065 	    }
3066 
3067 	  return decl;
3068 	}
3069       else if (ctype != NULL_TREE
3070 	       && (identifier_p (TREE_OPERAND (declarator, 0))))
3071 	{
3072 	  // We'll match variable templates in start_decl.
3073 	  if (VAR_P (decl))
3074 	    return decl;
3075 
3076 	  /* Find the list of functions in ctype that have the same
3077 	     name as the declared function.  */
3078 	  tree name = TREE_OPERAND (declarator, 0);
3079 
3080 	  if (constructor_name_p (name, ctype))
3081 	    {
3082 	      if (DECL_CONSTRUCTOR_P (decl)
3083 		  ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
3084 		  : !CLASSTYPE_DESTRUCTOR (ctype))
3085 		{
3086 		  /* From [temp.expl.spec]:
3087 
3088 		     If such an explicit specialization for the member
3089 		     of a class template names an implicitly-declared
3090 		     special member function (clause _special_), the
3091 		     program is ill-formed.
3092 
3093 		     Similar language is found in [temp.explicit].  */
3094 		  error ("specialization of implicitly-declared special member function");
3095 		  return error_mark_node;
3096 		}
3097 
3098 	      name = DECL_NAME (decl);
3099 	    }
3100 
3101 	  /* For a type-conversion operator, We might be looking for
3102 	     `operator int' which will be a specialization of
3103 	     `operator T'.  Grab all the conversion operators, and
3104 	     then select from them.  */
3105 	  tree fns = get_class_binding (ctype, IDENTIFIER_CONV_OP_P (name)
3106 					? conv_op_identifier : name);
3107 
3108 	  if (fns == NULL_TREE)
3109 	    {
3110 	      error ("no member function %qD declared in %qT", name, ctype);
3111 	      return error_mark_node;
3112 	    }
3113 	  else
3114 	    TREE_OPERAND (declarator, 0) = fns;
3115 	}
3116 
3117       /* Figure out what exactly is being specialized at this point.
3118 	 Note that for an explicit instantiation, even one for a
3119 	 member function, we cannot tell a priori whether the
3120 	 instantiation is for a member template, or just a member
3121 	 function of a template class.  Even if a member template is
3122 	 being instantiated, the member template arguments may be
3123 	 elided if they can be deduced from the rest of the
3124 	 declaration.  */
3125       tmpl = determine_specialization (declarator, decl,
3126 				       &targs,
3127 				       member_specialization,
3128 				       template_count,
3129 				       tsk);
3130 
3131       if (!tmpl || tmpl == error_mark_node)
3132 	/* We couldn't figure out what this declaration was
3133 	   specializing.  */
3134 	return error_mark_node;
3135       else
3136 	{
3137 	  if (found_hidden && TREE_CODE (decl) == FUNCTION_DECL)
3138 	    {
3139 	      auto_diagnostic_group d;
3140 	      if (pedwarn (DECL_SOURCE_LOCATION (decl), 0,
3141 			   "friend declaration %qD is not visible to "
3142 			   "explicit specialization", tmpl))
3143 		inform (DECL_SOURCE_LOCATION (tmpl),
3144 			"friend declaration here");
3145 	    }
3146 
3147 	  if (!ctype && !is_friend
3148 	      && CP_DECL_CONTEXT (decl) == current_namespace)
3149 	    check_unqualified_spec_or_inst (tmpl, DECL_SOURCE_LOCATION (decl));
3150 
3151 	  tree gen_tmpl = most_general_template (tmpl);
3152 
3153 	  if (explicit_instantiation)
3154 	    {
3155 	      /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
3156 		 is done by do_decl_instantiation later.  */
3157 
3158 	      int arg_depth = TMPL_ARGS_DEPTH (targs);
3159 	      int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
3160 
3161 	      if (arg_depth > parm_depth)
3162 		{
3163 		  /* If TMPL is not the most general template (for
3164 		     example, if TMPL is a friend template that is
3165 		     injected into namespace scope), then there will
3166 		     be too many levels of TARGS.  Remove some of them
3167 		     here.  */
3168 		  int i;
3169 		  tree new_targs;
3170 
3171 		  new_targs = make_tree_vec (parm_depth);
3172 		  for (i = arg_depth - parm_depth; i < arg_depth; ++i)
3173 		    TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
3174 		      = TREE_VEC_ELT (targs, i);
3175 		  targs = new_targs;
3176 		}
3177 
3178 	      return instantiate_template (tmpl, targs, tf_error);
3179 	    }
3180 
3181 	  /* If we thought that the DECL was a member function, but it
3182 	     turns out to be specializing a static member function,
3183 	     make DECL a static member function as well.  */
3184 	  if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3185 	      && DECL_STATIC_FUNCTION_P (tmpl)
3186 	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
3187 	    revert_static_member_fn (decl);
3188 
3189 	  /* If this is a specialization of a member template of a
3190 	     template class, we want to return the TEMPLATE_DECL, not
3191 	     the specialization of it.  */
3192 	  if (tsk == tsk_template && !was_template_id)
3193 	    {
3194 	      tree result = DECL_TEMPLATE_RESULT (tmpl);
3195 	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3196 	      DECL_INITIAL (result) = NULL_TREE;
3197 	      if (have_def)
3198 		{
3199 		  tree parm;
3200 		  DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
3201 		  DECL_SOURCE_LOCATION (result)
3202 		    = DECL_SOURCE_LOCATION (decl);
3203 		  /* We want to use the argument list specified in the
3204 		     definition, not in the original declaration.  */
3205 		  DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
3206 		  for (parm = DECL_ARGUMENTS (result); parm;
3207 		       parm = DECL_CHAIN (parm))
3208 		    DECL_CONTEXT (parm) = result;
3209 		}
3210 	      return register_specialization (tmpl, gen_tmpl, targs,
3211 					      is_friend, 0);
3212 	    }
3213 
3214 	  /* Set up the DECL_TEMPLATE_INFO for DECL.  */
3215 	  DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
3216 
3217 	  if (was_template_id)
3218 	    TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl)) = true;
3219 
3220 	  /* Inherit default function arguments from the template
3221 	     DECL is specializing.  */
3222 	  if (DECL_FUNCTION_TEMPLATE_P (tmpl))
3223 	    copy_default_args_to_explicit_spec (decl);
3224 
3225 	  /* This specialization has the same protection as the
3226 	     template it specializes.  */
3227 	  TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
3228 	  TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
3229 
3230           /* 7.1.1-1 [dcl.stc]
3231 
3232              A storage-class-specifier shall not be specified in an
3233              explicit specialization...
3234 
3235              The parser rejects these, so unless action is taken here,
3236              explicit function specializations will always appear with
3237              global linkage.
3238 
3239              The action recommended by the C++ CWG in response to C++
3240              defect report 605 is to make the storage class and linkage
3241              of the explicit specialization match the templated function:
3242 
3243              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
3244            */
3245           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
3246             {
3247               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
3248               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
3249 
3250               /* A concept cannot be specialized.  */
3251               if (DECL_DECLARED_CONCEPT_P (tmpl_func))
3252                 {
3253                   error ("explicit specialization of function concept %qD",
3254                          gen_tmpl);
3255                   return error_mark_node;
3256                 }
3257 
3258               /* This specialization has the same linkage and visibility as
3259                  the function template it specializes.  */
3260               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
3261 	      if (! TREE_PUBLIC (decl))
3262 		{
3263 		  DECL_INTERFACE_KNOWN (decl) = 1;
3264 		  DECL_NOT_REALLY_EXTERN (decl) = 1;
3265 		}
3266               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
3267               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
3268                 {
3269                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
3270                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
3271                 }
3272             }
3273 
3274 	  /* If DECL is a friend declaration, declared using an
3275 	     unqualified name, the namespace associated with DECL may
3276 	     have been set incorrectly.  For example, in:
3277 
3278 	       template <typename T> void f(T);
3279 	       namespace N {
3280 		 struct S { friend void f<int>(int); }
3281 	       }
3282 
3283 	     we will have set the DECL_CONTEXT for the friend
3284 	     declaration to N, rather than to the global namespace.  */
3285 	  if (DECL_NAMESPACE_SCOPE_P (decl))
3286 	    DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
3287 
3288 	  if (is_friend && !have_def)
3289 	    /* This is not really a declaration of a specialization.
3290 	       It's just the name of an instantiation.  But, it's not
3291 	       a request for an instantiation, either.  */
3292 	    SET_DECL_IMPLICIT_INSTANTIATION (decl);
3293 	  else if (TREE_CODE (decl) == FUNCTION_DECL)
3294 	    /* A specialization is not necessarily COMDAT.  */
3295 	    DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
3296 				  && DECL_DECLARED_INLINE_P (decl));
3297 	  else if (VAR_P (decl))
3298 	    DECL_COMDAT (decl) = false;
3299 
3300 	  /* If this is a full specialization, register it so that we can find
3301 	     it again.  Partial specializations will be registered in
3302 	     process_partial_specialization.  */
3303 	  if (!processing_template_decl)
3304 	    {
3305 	      warn_spec_missing_attributes (gen_tmpl, decl, attrlist);
3306 
3307 	      decl = register_specialization (decl, gen_tmpl, targs,
3308 					      is_friend, 0);
3309 	    }
3310 
3311 
3312 	  /* A 'structor should already have clones.  */
3313 	  gcc_assert (decl == error_mark_node
3314 		      || variable_template_p (tmpl)
3315 		      || !(DECL_CONSTRUCTOR_P (decl)
3316 			   || DECL_DESTRUCTOR_P (decl))
3317 		      || DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
3318 	}
3319     }
3320 
3321   return decl;
3322 }
3323 
3324 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
3325    parameters.  These are represented in the same format used for
3326    DECL_TEMPLATE_PARMS.  */
3327 
3328 int
comp_template_parms(const_tree parms1,const_tree parms2)3329 comp_template_parms (const_tree parms1, const_tree parms2)
3330 {
3331   const_tree p1;
3332   const_tree p2;
3333 
3334   if (parms1 == parms2)
3335     return 1;
3336 
3337   for (p1 = parms1, p2 = parms2;
3338        p1 != NULL_TREE && p2 != NULL_TREE;
3339        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
3340     {
3341       tree t1 = TREE_VALUE (p1);
3342       tree t2 = TREE_VALUE (p2);
3343       int i;
3344 
3345       gcc_assert (TREE_CODE (t1) == TREE_VEC);
3346       gcc_assert (TREE_CODE (t2) == TREE_VEC);
3347 
3348       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
3349 	return 0;
3350 
3351       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
3352 	{
3353           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
3354           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
3355 
3356           /* If either of the template parameters are invalid, assume
3357              they match for the sake of error recovery. */
3358           if (error_operand_p (parm1) || error_operand_p (parm2))
3359             return 1;
3360 
3361 	  if (TREE_CODE (parm1) != TREE_CODE (parm2))
3362 	    return 0;
3363 
3364 	  if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
3365               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
3366                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
3367 	    continue;
3368 	  else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
3369 	    return 0;
3370 	}
3371     }
3372 
3373   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3374     /* One set of parameters has more parameters lists than the
3375        other.  */
3376     return 0;
3377 
3378   return 1;
3379 }
3380 
3381 /* Returns true if two template parameters are declared with
3382    equivalent constraints.  */
3383 
3384 static bool
template_parameter_constraints_equivalent_p(const_tree parm1,const_tree parm2)3385 template_parameter_constraints_equivalent_p (const_tree parm1, const_tree parm2)
3386 {
3387   tree req1 = TREE_TYPE (parm1);
3388   tree req2 = TREE_TYPE (parm2);
3389   if (!req1 != !req2)
3390     return false;
3391   if (req1)
3392     return cp_tree_equal (req1, req2);
3393   return true;
3394 }
3395 
3396 /* Returns true when two template parameters are equivalent.  */
3397 
3398 static bool
template_parameters_equivalent_p(const_tree parm1,const_tree parm2)3399 template_parameters_equivalent_p (const_tree parm1, const_tree parm2)
3400 {
3401   tree decl1 = TREE_VALUE (parm1);
3402   tree decl2 = TREE_VALUE (parm2);
3403 
3404   /* If either of the template parameters are invalid, assume
3405      they match for the sake of error recovery. */
3406   if (error_operand_p (decl1) || error_operand_p (decl2))
3407     return true;
3408 
3409   /* ... they declare parameters of the same kind.  */
3410   if (TREE_CODE (decl1) != TREE_CODE (decl2))
3411     return false;
3412 
3413   /* ... one parameter was introduced by a parameter declaration, then
3414      both are. This case arises as a result of eagerly rewriting declarations
3415      during parsing.  */
3416   if (DECL_VIRTUAL_P (decl1) != DECL_VIRTUAL_P (decl2))
3417     return false;
3418 
3419   /* ... if either declares a pack, they both do.  */
3420   if (template_parameter_pack_p (decl1) != template_parameter_pack_p (decl2))
3421     return false;
3422 
3423   if (TREE_CODE (decl1) == PARM_DECL)
3424     {
3425       /* ... if they declare non-type parameters, the types are equivalent.  */
3426       if (!same_type_p (TREE_TYPE (decl1), TREE_TYPE (decl2)))
3427 	return false;
3428     }
3429   else if (TREE_CODE (decl2) == TEMPLATE_DECL)
3430     {
3431       /* ... if they declare template template parameters, their template
3432 	 parameter lists are equivalent.  */
3433       if (!template_heads_equivalent_p (decl1, decl2))
3434 	return false;
3435     }
3436 
3437   /* ... if they are declared with a qualified-concept name, they both
3438      are, and those names are equivalent.  */
3439   return template_parameter_constraints_equivalent_p (parm1, parm2);
3440 }
3441 
3442 /* Returns true if two template parameters lists are equivalent.
3443    Two template parameter lists are equivalent if they have the
3444    same length and their corresponding parameters are equivalent.
3445 
3446    PARMS1 and PARMS2 are TREE_LISTs containing TREE_VECs: the
3447    data structure returned by DECL_TEMPLATE_PARMS.
3448 
3449    This is generally the same implementation as comp_template_parms
3450    except that it also the concept names and arguments used to
3451    introduce parameters.  */
3452 
3453 static bool
template_parameter_lists_equivalent_p(const_tree parms1,const_tree parms2)3454 template_parameter_lists_equivalent_p (const_tree parms1, const_tree parms2)
3455 {
3456   if (parms1 == parms2)
3457     return true;
3458 
3459   const_tree p1 = parms1;
3460   const_tree p2 = parms2;
3461   while (p1 != NULL_TREE && p2 != NULL_TREE)
3462     {
3463       tree list1 = TREE_VALUE (p1);
3464       tree list2 = TREE_VALUE (p2);
3465 
3466       if (TREE_VEC_LENGTH (list1) != TREE_VEC_LENGTH (list2))
3467 	return 0;
3468 
3469       for (int i = 0; i < TREE_VEC_LENGTH (list2); ++i)
3470 	{
3471 	  tree parm1 = TREE_VEC_ELT (list1, i);
3472 	  tree parm2 = TREE_VEC_ELT (list2, i);
3473 	  if (!template_parameters_equivalent_p (parm1, parm2))
3474 	    return false;
3475 	}
3476 
3477       p1 = TREE_CHAIN (p1);
3478       p2 = TREE_CHAIN (p2);
3479     }
3480 
3481   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3482     return false;
3483 
3484   return true;
3485 }
3486 
3487 /* Return true if the requires-clause of the template parameter lists are
3488    equivalent and false otherwise.  */
3489 static bool
template_requirements_equivalent_p(const_tree parms1,const_tree parms2)3490 template_requirements_equivalent_p (const_tree parms1, const_tree parms2)
3491 {
3492   tree req1 = TEMPLATE_PARMS_CONSTRAINTS (parms1);
3493   tree req2 = TEMPLATE_PARMS_CONSTRAINTS (parms2);
3494   if ((req1 != NULL_TREE) != (req2 != NULL_TREE))
3495     return false;
3496   if (!cp_tree_equal (req1, req2))
3497     return false;
3498   return true;
3499 }
3500 
3501 /* Returns true if two template heads are equivalent. 17.6.6.1p6:
3502    Two template heads are equivalent if their template parameter
3503    lists are equivalent and their requires clauses are equivalent.
3504 
3505    In pre-C++20, this is equivalent to calling comp_template_parms
3506    for the template parameters of TMPL1 and TMPL2.  */
3507 
3508 bool
template_heads_equivalent_p(const_tree tmpl1,const_tree tmpl2)3509 template_heads_equivalent_p (const_tree tmpl1, const_tree tmpl2)
3510 {
3511   tree parms1 = DECL_TEMPLATE_PARMS (tmpl1);
3512   tree parms2 = DECL_TEMPLATE_PARMS (tmpl2);
3513 
3514   /* Don't change the matching rules for pre-C++20.  */
3515   if (cxx_dialect < cxx20)
3516     return comp_template_parms (parms1, parms2);
3517 
3518   /* ... have the same number of template parameters, and their
3519      corresponding parameters are equivalent.  */
3520   if (!template_parameter_lists_equivalent_p (parms1, parms2))
3521     return false;
3522 
3523   /* ... if either has a requires-clause, they both do and their
3524      corresponding constraint-expressions are equivalent.  */
3525   return template_requirements_equivalent_p (parms1, parms2);
3526 }
3527 
3528 /* Determine whether PARM is a parameter pack.  */
3529 
3530 bool
template_parameter_pack_p(const_tree parm)3531 template_parameter_pack_p (const_tree parm)
3532 {
3533   /* Determine if we have a non-type template parameter pack.  */
3534   if (TREE_CODE (parm) == PARM_DECL)
3535     return (DECL_TEMPLATE_PARM_P (parm)
3536             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
3537   if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
3538     return TEMPLATE_PARM_PARAMETER_PACK (parm);
3539 
3540   /* If this is a list of template parameters, we could get a
3541      TYPE_DECL or a TEMPLATE_DECL.  */
3542   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
3543     parm = TREE_TYPE (parm);
3544 
3545   /* Otherwise it must be a type template parameter.  */
3546   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
3547 	   || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
3548 	  && TEMPLATE_TYPE_PARAMETER_PACK (parm));
3549 }
3550 
3551 /* Determine if T is a function parameter pack.  */
3552 
3553 bool
function_parameter_pack_p(const_tree t)3554 function_parameter_pack_p (const_tree t)
3555 {
3556   if (t && TREE_CODE (t) == PARM_DECL)
3557     return DECL_PACK_P (t);
3558   return false;
3559 }
3560 
3561 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
3562    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
3563 
3564 tree
get_function_template_decl(const_tree primary_func_tmpl_inst)3565 get_function_template_decl (const_tree primary_func_tmpl_inst)
3566 {
3567   if (! primary_func_tmpl_inst
3568       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
3569       || ! primary_template_specialization_p (primary_func_tmpl_inst))
3570     return NULL;
3571 
3572   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
3573 }
3574 
3575 /* Return true iff the function parameter PARAM_DECL was expanded
3576    from the function parameter pack PACK.  */
3577 
3578 bool
function_parameter_expanded_from_pack_p(tree param_decl,tree pack)3579 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
3580 {
3581   if (DECL_ARTIFICIAL (param_decl)
3582       || !function_parameter_pack_p (pack))
3583     return false;
3584 
3585   /* The parameter pack and its pack arguments have the same
3586      DECL_PARM_INDEX.  */
3587   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
3588 }
3589 
3590 /* Determine whether ARGS describes a variadic template args list,
3591    i.e., one that is terminated by a template argument pack.  */
3592 
3593 static bool
template_args_variadic_p(tree args)3594 template_args_variadic_p (tree args)
3595 {
3596   int nargs;
3597   tree last_parm;
3598 
3599   if (args == NULL_TREE)
3600     return false;
3601 
3602   args = INNERMOST_TEMPLATE_ARGS (args);
3603   nargs = TREE_VEC_LENGTH (args);
3604 
3605   if (nargs == 0)
3606     return false;
3607 
3608   last_parm = TREE_VEC_ELT (args, nargs - 1);
3609 
3610   return ARGUMENT_PACK_P (last_parm);
3611 }
3612 
3613 /* Generate a new name for the parameter pack name NAME (an
3614    IDENTIFIER_NODE) that incorporates its */
3615 
3616 static tree
make_ith_pack_parameter_name(tree name,int i)3617 make_ith_pack_parameter_name (tree name, int i)
3618 {
3619   /* Munge the name to include the parameter index.  */
3620 #define NUMBUF_LEN 128
3621   char numbuf[NUMBUF_LEN];
3622   char* newname;
3623   int newname_len;
3624 
3625   if (name == NULL_TREE)
3626     return name;
3627   snprintf (numbuf, NUMBUF_LEN, "%i", i);
3628   newname_len = IDENTIFIER_LENGTH (name)
3629 	        + strlen (numbuf) + 2;
3630   newname = (char*)alloca (newname_len);
3631   snprintf (newname, newname_len,
3632 	    "%s#%i", IDENTIFIER_POINTER (name), i);
3633   return get_identifier (newname);
3634 }
3635 
3636 /* Return true if T is a primary function, class or alias template
3637    specialization, not including the template pattern.  */
3638 
3639 bool
primary_template_specialization_p(const_tree t)3640 primary_template_specialization_p (const_tree t)
3641 {
3642   if (!t)
3643     return false;
3644 
3645   if (VAR_OR_FUNCTION_DECL_P (t))
3646     return (DECL_LANG_SPECIFIC (t)
3647 	    && DECL_USE_TEMPLATE (t)
3648 	    && DECL_TEMPLATE_INFO (t)
3649 	    && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t)));
3650   else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
3651     return (CLASSTYPE_TEMPLATE_INFO (t)
3652 	    && CLASSTYPE_USE_TEMPLATE (t)
3653 	    && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)));
3654   else if (alias_template_specialization_p (t, nt_transparent))
3655     return true;
3656   return false;
3657 }
3658 
3659 /* Return true if PARM is a template template parameter.  */
3660 
3661 bool
template_template_parameter_p(const_tree parm)3662 template_template_parameter_p (const_tree parm)
3663 {
3664   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
3665 }
3666 
3667 /* Return true iff PARM is a DECL representing a type template
3668    parameter.  */
3669 
3670 bool
template_type_parameter_p(const_tree parm)3671 template_type_parameter_p (const_tree parm)
3672 {
3673   return (parm
3674 	  && (TREE_CODE (parm) == TYPE_DECL
3675 	      || TREE_CODE (parm) == TEMPLATE_DECL)
3676 	  && DECL_TEMPLATE_PARM_P (parm));
3677 }
3678 
3679 /* Return the template parameters of T if T is a
3680    primary template instantiation, NULL otherwise.  */
3681 
3682 tree
get_primary_template_innermost_parameters(const_tree t)3683 get_primary_template_innermost_parameters (const_tree t)
3684 {
3685   tree parms = NULL, template_info = NULL;
3686 
3687   if ((template_info = get_template_info (t))
3688       && primary_template_specialization_p (t))
3689     parms = INNERMOST_TEMPLATE_PARMS
3690 	(DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
3691 
3692   return parms;
3693 }
3694 
3695 /* Return the template parameters of the LEVELth level from the full list
3696    of template parameters PARMS.  */
3697 
3698 tree
get_template_parms_at_level(tree parms,int level)3699 get_template_parms_at_level (tree parms, int level)
3700 {
3701   tree p;
3702   if (!parms
3703       || TREE_CODE (parms) != TREE_LIST
3704       || level > TMPL_PARMS_DEPTH (parms))
3705     return NULL_TREE;
3706 
3707   for (p = parms; p; p = TREE_CHAIN (p))
3708     if (TMPL_PARMS_DEPTH (p) == level)
3709       return p;
3710 
3711   return NULL_TREE;
3712 }
3713 
3714 /* Returns the template arguments of T if T is a template instantiation,
3715    NULL otherwise.  */
3716 
3717 tree
get_template_innermost_arguments(const_tree t)3718 get_template_innermost_arguments (const_tree t)
3719 {
3720   tree args = NULL, template_info = NULL;
3721 
3722   if ((template_info = get_template_info (t))
3723       && TI_ARGS (template_info))
3724     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
3725 
3726   return args;
3727 }
3728 
3729 /* Return the argument pack elements of T if T is a template argument pack,
3730    NULL otherwise.  */
3731 
3732 tree
get_template_argument_pack_elems(const_tree t)3733 get_template_argument_pack_elems (const_tree t)
3734 {
3735   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
3736       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
3737     return NULL;
3738 
3739   return ARGUMENT_PACK_ARGS (t);
3740 }
3741 
3742 /* In an ARGUMENT_PACK_SELECT, the actual underlying argument that the
3743    ARGUMENT_PACK_SELECT represents. */
3744 
3745 static tree
argument_pack_select_arg(tree t)3746 argument_pack_select_arg (tree t)
3747 {
3748   tree args = ARGUMENT_PACK_ARGS (ARGUMENT_PACK_SELECT_FROM_PACK (t));
3749   tree arg = TREE_VEC_ELT (args, ARGUMENT_PACK_SELECT_INDEX (t));
3750 
3751   /* If the selected argument is an expansion E, that most likely means we were
3752      called from gen_elem_of_pack_expansion_instantiation during the
3753      substituting of an argument pack (of which the Ith element is a pack
3754      expansion, where I is ARGUMENT_PACK_SELECT_INDEX) into a pack expansion.
3755      In this case, the Ith element resulting from this substituting is going to
3756      be a pack expansion, which pattern is the pattern of E.  Let's return the
3757      pattern of E, and gen_elem_of_pack_expansion_instantiation will build the
3758      resulting pack expansion from it.  */
3759   if (PACK_EXPANSION_P (arg))
3760     {
3761       /* Make sure we aren't throwing away arg info.  */
3762       gcc_assert (!PACK_EXPANSION_EXTRA_ARGS (arg));
3763       arg = PACK_EXPANSION_PATTERN (arg);
3764     }
3765 
3766   return arg;
3767 }
3768 
3769 
3770 /* True iff FN is a function representing a built-in variadic parameter
3771    pack.  */
3772 
3773 bool
builtin_pack_fn_p(tree fn)3774 builtin_pack_fn_p (tree fn)
3775 {
3776   if (!fn
3777       || TREE_CODE (fn) != FUNCTION_DECL
3778       || !DECL_IS_UNDECLARED_BUILTIN (fn))
3779     return false;
3780 
3781   if (id_equal (DECL_NAME (fn), "__integer_pack"))
3782     return true;
3783 
3784   return false;
3785 }
3786 
3787 /* True iff CALL is a call to a function representing a built-in variadic
3788    parameter pack.  */
3789 
3790 static bool
builtin_pack_call_p(tree call)3791 builtin_pack_call_p (tree call)
3792 {
3793   if (TREE_CODE (call) != CALL_EXPR)
3794     return false;
3795   return builtin_pack_fn_p (CALL_EXPR_FN (call));
3796 }
3797 
3798 /* Return a TREE_VEC for the expansion of __integer_pack(HI).  */
3799 
3800 static tree
expand_integer_pack(tree call,tree args,tsubst_flags_t complain,tree in_decl)3801 expand_integer_pack (tree call, tree args, tsubst_flags_t complain,
3802 		     tree in_decl)
3803 {
3804   tree ohi = CALL_EXPR_ARG (call, 0);
3805   tree hi = tsubst_copy_and_build (ohi, args, complain, in_decl,
3806 				   false/*fn*/, true/*int_cst*/);
3807 
3808   if (value_dependent_expression_p (hi))
3809     {
3810       if (hi != ohi)
3811 	{
3812 	  call = copy_node (call);
3813 	  CALL_EXPR_ARG (call, 0) = hi;
3814 	}
3815       tree ex = make_pack_expansion (call, complain);
3816       tree vec = make_tree_vec (1);
3817       TREE_VEC_ELT (vec, 0) = ex;
3818       return vec;
3819     }
3820   else
3821     {
3822       hi = cxx_constant_value (hi);
3823       int len = valid_constant_size_p (hi) ? tree_to_shwi (hi) : -1;
3824 
3825       /* Calculate the largest value of len that won't make the size of the vec
3826 	 overflow an int.  The compiler will exceed resource limits long before
3827 	 this, but it seems a decent place to diagnose.  */
3828       int max = ((INT_MAX - sizeof (tree_vec)) / sizeof (tree)) + 1;
3829 
3830       if (len < 0 || len > max)
3831 	{
3832 	  if ((complain & tf_error)
3833 	      && hi != error_mark_node)
3834 	    error ("argument to %<__integer_pack%> must be between 0 and %d",
3835 		   max);
3836 	  return error_mark_node;
3837 	}
3838 
3839       tree vec = make_tree_vec (len);
3840 
3841       for (int i = 0; i < len; ++i)
3842 	TREE_VEC_ELT (vec, i) = size_int (i);
3843 
3844       return vec;
3845     }
3846 }
3847 
3848 /* Return a TREE_VEC for the expansion of built-in template parameter pack
3849    CALL.  */
3850 
3851 static tree
expand_builtin_pack_call(tree call,tree args,tsubst_flags_t complain,tree in_decl)3852 expand_builtin_pack_call (tree call, tree args, tsubst_flags_t complain,
3853 			  tree in_decl)
3854 {
3855   if (!builtin_pack_call_p (call))
3856     return NULL_TREE;
3857 
3858   tree fn = CALL_EXPR_FN (call);
3859 
3860   if (id_equal (DECL_NAME (fn), "__integer_pack"))
3861     return expand_integer_pack (call, args, complain, in_decl);
3862 
3863   return NULL_TREE;
3864 }
3865 
3866 /* Structure used to track the progress of find_parameter_packs_r.  */
3867 struct find_parameter_pack_data
3868 {
3869   /* TREE_LIST that will contain all of the parameter packs found by
3870      the traversal.  */
3871   tree* parameter_packs;
3872 
3873   /* Set of AST nodes that have been visited by the traversal.  */
3874   hash_set<tree> *visited;
3875 
3876   /* True iff we're making a type pack expansion.  */
3877   bool type_pack_expansion_p;
3878 };
3879 
3880 /* Identifies all of the argument packs that occur in a template
3881    argument and appends them to the TREE_LIST inside DATA, which is a
3882    find_parameter_pack_data structure. This is a subroutine of
3883    make_pack_expansion and uses_parameter_packs.  */
3884 static tree
find_parameter_packs_r(tree * tp,int * walk_subtrees,void * data)3885 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
3886 {
3887   tree t = *tp;
3888   struct find_parameter_pack_data* ppd =
3889     (struct find_parameter_pack_data*)data;
3890   bool parameter_pack_p = false;
3891 
3892 #define WALK_SUBTREE(NODE)				\
3893   cp_walk_tree (&(NODE), &find_parameter_packs_r,	\
3894 		ppd, ppd->visited)			\
3895 
3896   /* Don't look through typedefs; we are interested in whether a
3897      parameter pack is actually written in the expression/type we're
3898      looking at, not the target type.  */
3899   if (TYPE_P (t) && typedef_variant_p (t))
3900     {
3901       /* But do look at arguments for an alias template.  */
3902       if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
3903 	cp_walk_tree (&TI_ARGS (tinfo),
3904 		      &find_parameter_packs_r,
3905 		      ppd, ppd->visited);
3906       *walk_subtrees = 0;
3907       return NULL_TREE;
3908     }
3909 
3910   /* Identify whether this is a parameter pack or not.  */
3911   switch (TREE_CODE (t))
3912     {
3913     case TEMPLATE_PARM_INDEX:
3914       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3915         parameter_pack_p = true;
3916       break;
3917 
3918     case TEMPLATE_TYPE_PARM:
3919       t = TYPE_MAIN_VARIANT (t);
3920       /* FALLTHRU */
3921     case TEMPLATE_TEMPLATE_PARM:
3922       /* If the placeholder appears in the decl-specifier-seq of a function
3923 	 parameter pack (14.6.3), or the type-specifier-seq of a type-id that
3924 	 is a pack expansion, the invented template parameter is a template
3925 	 parameter pack.  */
3926       if (ppd->type_pack_expansion_p && is_auto (t))
3927 	TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
3928       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3929         parameter_pack_p = true;
3930       break;
3931 
3932     case FIELD_DECL:
3933     case PARM_DECL:
3934       if (DECL_PACK_P (t))
3935         {
3936           /* We don't want to walk into the type of a PARM_DECL,
3937              because we don't want to see the type parameter pack.  */
3938           *walk_subtrees = 0;
3939 	  parameter_pack_p = true;
3940         }
3941       break;
3942 
3943     case VAR_DECL:
3944       if (DECL_PACK_P (t))
3945         {
3946           /* We don't want to walk into the type of a variadic capture proxy,
3947              because we don't want to see the type parameter pack.  */
3948           *walk_subtrees = 0;
3949 	  parameter_pack_p = true;
3950         }
3951       else if (variable_template_specialization_p (t))
3952 	{
3953 	  cp_walk_tree (&DECL_TI_ARGS (t),
3954 			find_parameter_packs_r,
3955 			ppd, ppd->visited);
3956 	  *walk_subtrees = 0;
3957 	}
3958       break;
3959 
3960     case CALL_EXPR:
3961       if (builtin_pack_call_p (t))
3962 	parameter_pack_p = true;
3963       break;
3964 
3965     case BASES:
3966       parameter_pack_p = true;
3967       break;
3968     default:
3969       /* Not a parameter pack.  */
3970       break;
3971     }
3972 
3973   if (parameter_pack_p)
3974     {
3975       /* Add this parameter pack to the list.  */
3976       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
3977     }
3978 
3979   if (TYPE_P (t))
3980     cp_walk_tree (&TYPE_CONTEXT (t),
3981 		  &find_parameter_packs_r, ppd, ppd->visited);
3982 
3983   /* This switch statement will return immediately if we don't find a
3984      parameter pack.  ??? Should some of these be in cp_walk_subtrees?  */
3985   switch (TREE_CODE (t))
3986     {
3987     case BOUND_TEMPLATE_TEMPLATE_PARM:
3988       /* Check the template itself.  */
3989       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)),
3990 		    &find_parameter_packs_r, ppd, ppd->visited);
3991       return NULL_TREE;
3992 
3993     case DECL_EXPR:
3994       {
3995 	tree decl = DECL_EXPR_DECL (t);
3996 	/* Ignore the declaration of a capture proxy for a parameter pack.  */
3997 	if (is_capture_proxy (decl))
3998 	  *walk_subtrees = 0;
3999 	if (is_typedef_decl (decl))
4000 	  /* Since we stop at typedefs above, we need to look through them at
4001 	     the point of the DECL_EXPR.  */
4002 	  cp_walk_tree (&DECL_ORIGINAL_TYPE (decl),
4003 			&find_parameter_packs_r, ppd, ppd->visited);
4004 	return NULL_TREE;
4005       }
4006 
4007     case TEMPLATE_DECL:
4008       if (!DECL_TEMPLATE_TEMPLATE_PARM_P (t))
4009 	return NULL_TREE;
4010       cp_walk_tree (&TREE_TYPE (t),
4011 		    &find_parameter_packs_r, ppd, ppd->visited);
4012       return NULL_TREE;
4013 
4014     case TYPE_PACK_EXPANSION:
4015     case EXPR_PACK_EXPANSION:
4016       *walk_subtrees = 0;
4017       return NULL_TREE;
4018 
4019     case INTEGER_TYPE:
4020       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r,
4021 		    ppd, ppd->visited);
4022       *walk_subtrees = 0;
4023       return NULL_TREE;
4024 
4025     case IDENTIFIER_NODE:
4026       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd,
4027 		    ppd->visited);
4028       *walk_subtrees = 0;
4029       return NULL_TREE;
4030 
4031     case LAMBDA_EXPR:
4032       {
4033 	/* Since we defer implicit capture, look in the parms and body.  */
4034 	tree fn = lambda_function (t);
4035 	cp_walk_tree (&TREE_TYPE (fn), &find_parameter_packs_r, ppd,
4036 		      ppd->visited);
4037 	cp_walk_tree (&DECL_SAVED_TREE (fn), &find_parameter_packs_r, ppd,
4038 		      ppd->visited);
4039 	return NULL_TREE;
4040       }
4041 
4042     case DECLTYPE_TYPE:
4043       {
4044 	/* When traversing a DECLTYPE_TYPE_EXPR, we need to set
4045 	   type_pack_expansion_p to false so that any placeholders
4046 	   within the expression don't get marked as parameter packs.  */
4047 	bool type_pack_expansion_p = ppd->type_pack_expansion_p;
4048 	ppd->type_pack_expansion_p = false;
4049 	cp_walk_tree (&DECLTYPE_TYPE_EXPR (t), &find_parameter_packs_r,
4050 		      ppd, ppd->visited);
4051 	ppd->type_pack_expansion_p = type_pack_expansion_p;
4052 	*walk_subtrees = 0;
4053 	return NULL_TREE;
4054       }
4055 
4056     case IF_STMT:
4057       cp_walk_tree (&IF_COND (t), &find_parameter_packs_r,
4058 		    ppd, ppd->visited);
4059       cp_walk_tree (&THEN_CLAUSE (t), &find_parameter_packs_r,
4060 		    ppd, ppd->visited);
4061       cp_walk_tree (&ELSE_CLAUSE (t), &find_parameter_packs_r,
4062 		    ppd, ppd->visited);
4063       /* Don't walk into IF_STMT_EXTRA_ARGS.  */
4064       *walk_subtrees = 0;
4065       return NULL_TREE;
4066 
4067     case TAG_DEFN:
4068       /* Local class, need to look through the whole definition.  */
4069       t = TREE_TYPE (t);
4070       if (CLASS_TYPE_P (t))
4071 	for (tree bb : BINFO_BASE_BINFOS (TYPE_BINFO (t)))
4072 	  cp_walk_tree (&BINFO_TYPE (bb), &find_parameter_packs_r,
4073 			ppd, ppd->visited);
4074       return NULL_TREE;
4075 
4076     case FUNCTION_TYPE:
4077     case METHOD_TYPE:
4078       WALK_SUBTREE (TYPE_RAISES_EXCEPTIONS (t));
4079       break;
4080 
4081     default:
4082       return NULL_TREE;
4083     }
4084 
4085 #undef WALK_SUBTREE
4086 
4087   return NULL_TREE;
4088 }
4089 
4090 /* Determines if the expression or type T uses any parameter packs.  */
4091 tree
uses_parameter_packs(tree t)4092 uses_parameter_packs (tree t)
4093 {
4094   tree parameter_packs = NULL_TREE;
4095   struct find_parameter_pack_data ppd;
4096   ppd.parameter_packs = &parameter_packs;
4097   ppd.visited = new hash_set<tree>;
4098   ppd.type_pack_expansion_p = false;
4099   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4100   delete ppd.visited;
4101   return parameter_packs;
4102 }
4103 
4104 /* Turn ARG, which may be an expression, type, or a TREE_LIST
4105    representation a base-class initializer into a parameter pack
4106    expansion. If all goes well, the resulting node will be an
4107    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
4108    respectively.  */
4109 tree
make_pack_expansion(tree arg,tsubst_flags_t complain)4110 make_pack_expansion (tree arg, tsubst_flags_t complain)
4111 {
4112   tree result;
4113   tree parameter_packs = NULL_TREE;
4114   bool for_types = false;
4115   struct find_parameter_pack_data ppd;
4116 
4117   if (!arg || arg == error_mark_node)
4118     return arg;
4119 
4120   if (TREE_CODE (arg) == TREE_LIST && TREE_PURPOSE (arg))
4121     {
4122       /* A TREE_LIST with a non-null TREE_PURPOSE is for a base
4123          class initializer.  In this case, the TREE_PURPOSE will be a
4124          _TYPE node (representing the base class expansion we're
4125          initializing) and the TREE_VALUE will be a TREE_LIST
4126          containing the initialization arguments.
4127 
4128          The resulting expansion looks somewhat different from most
4129          expansions. Rather than returning just one _EXPANSION, we
4130          return a TREE_LIST whose TREE_PURPOSE is a
4131          TYPE_PACK_EXPANSION containing the bases that will be
4132          initialized.  The TREE_VALUE will be identical to the
4133          original TREE_VALUE, which is a list of arguments that will
4134          be passed to each base.  We do not introduce any new pack
4135          expansion nodes into the TREE_VALUE (although it is possible
4136          that some already exist), because the TREE_PURPOSE and
4137          TREE_VALUE all need to be expanded together with the same
4138          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
4139          resulting TREE_PURPOSE will mention the parameter packs in
4140          both the bases and the arguments to the bases.  */
4141       tree purpose;
4142       tree value;
4143       tree parameter_packs = NULL_TREE;
4144 
4145       /* Determine which parameter packs will be used by the base
4146          class expansion.  */
4147       ppd.visited = new hash_set<tree>;
4148       ppd.parameter_packs = &parameter_packs;
4149       ppd.type_pack_expansion_p = false;
4150       gcc_assert (TYPE_P (TREE_PURPOSE (arg)));
4151       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r,
4152                     &ppd, ppd.visited);
4153 
4154       if (parameter_packs == NULL_TREE)
4155         {
4156 	  if (complain & tf_error)
4157 	    error ("base initializer expansion %qT contains no parameter packs",
4158 		   arg);
4159           delete ppd.visited;
4160           return error_mark_node;
4161         }
4162 
4163       if (TREE_VALUE (arg) != void_type_node)
4164         {
4165           /* Collect the sets of parameter packs used in each of the
4166              initialization arguments.  */
4167           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
4168             {
4169               /* Determine which parameter packs will be expanded in this
4170                  argument.  */
4171               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r,
4172                             &ppd, ppd.visited);
4173             }
4174         }
4175 
4176       delete ppd.visited;
4177 
4178       /* Create the pack expansion type for the base type.  */
4179       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
4180       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
4181       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
4182       PACK_EXPANSION_LOCAL_P (purpose) = at_function_scope_p ();
4183 
4184       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4185 	 they will rarely be compared to anything.  */
4186       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
4187 
4188       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
4189     }
4190 
4191   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
4192     for_types = true;
4193 
4194   /* Build the PACK_EXPANSION_* node.  */
4195   result = for_types
4196      ? cxx_make_type (TYPE_PACK_EXPANSION)
4197      : make_node (EXPR_PACK_EXPANSION);
4198   SET_PACK_EXPANSION_PATTERN (result, arg);
4199   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
4200     {
4201       /* Propagate type and const-expression information.  */
4202       TREE_TYPE (result) = TREE_TYPE (arg);
4203       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
4204       /* Mark this read now, since the expansion might be length 0.  */
4205       mark_exp_read (arg);
4206     }
4207   else
4208     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4209        they will rarely be compared to anything.  */
4210     SET_TYPE_STRUCTURAL_EQUALITY (result);
4211 
4212   /* Determine which parameter packs will be expanded.  */
4213   ppd.parameter_packs = &parameter_packs;
4214   ppd.visited = new hash_set<tree>;
4215   ppd.type_pack_expansion_p = TYPE_P (arg);
4216   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
4217   delete ppd.visited;
4218 
4219   /* Make sure we found some parameter packs.  */
4220   if (parameter_packs == NULL_TREE)
4221     {
4222       if (complain & tf_error)
4223 	{
4224 	  if (TYPE_P (arg))
4225 	    error ("expansion pattern %qT contains no parameter packs", arg);
4226 	  else
4227 	    error ("expansion pattern %qE contains no parameter packs", arg);
4228 	}
4229       return error_mark_node;
4230     }
4231   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
4232 
4233   PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
4234 
4235   return result;
4236 }
4237 
4238 /* Checks T for any "bare" parameter packs, which have not yet been
4239    expanded, and issues an error if any are found. This operation can
4240    only be done on full expressions or types (e.g., an expression
4241    statement, "if" condition, etc.), because we could have expressions like:
4242 
4243      foo(f(g(h(args)))...)
4244 
4245    where "args" is a parameter pack. check_for_bare_parameter_packs
4246    should not be called for the subexpressions args, h(args),
4247    g(h(args)), or f(g(h(args))), because we would produce erroneous
4248    error messages.
4249 
4250    Returns TRUE and emits an error if there were bare parameter packs,
4251    returns FALSE otherwise.  */
4252 bool
check_for_bare_parameter_packs(tree t,location_t loc)4253 check_for_bare_parameter_packs (tree t, location_t loc /* = UNKNOWN_LOCATION */)
4254 {
4255   tree parameter_packs = NULL_TREE;
4256   struct find_parameter_pack_data ppd;
4257 
4258   if (!processing_template_decl || !t || t == error_mark_node)
4259     return false;
4260 
4261   if (TREE_CODE (t) == TYPE_DECL)
4262     t = TREE_TYPE (t);
4263 
4264   ppd.parameter_packs = &parameter_packs;
4265   ppd.visited = new hash_set<tree>;
4266   ppd.type_pack_expansion_p = false;
4267   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4268   delete ppd.visited;
4269 
4270   /* It's OK for a lambda to have an unexpanded parameter pack from the
4271      containing context, but do complain about unexpanded capture packs.  */
4272   if (current_class_type && LAMBDA_TYPE_P (current_class_type)
4273       && CLASSTYPE_TEMPLATE_INFO (current_class_type))
4274     for (; parameter_packs;
4275 	 parameter_packs = TREE_CHAIN (parameter_packs))
4276       {
4277 	tree pack = TREE_VALUE (parameter_packs);
4278 	if (is_capture_proxy (pack))
4279 	  break;
4280       }
4281 
4282   if (parameter_packs)
4283     {
4284       if (loc == UNKNOWN_LOCATION)
4285 	loc = cp_expr_loc_or_input_loc (t);
4286       error_at (loc, "parameter packs not expanded with %<...%>:");
4287       while (parameter_packs)
4288         {
4289           tree pack = TREE_VALUE (parameter_packs);
4290           tree name = NULL_TREE;
4291 
4292           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
4293               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
4294             name = TYPE_NAME (pack);
4295           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
4296             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
4297 	  else if (TREE_CODE (pack) == CALL_EXPR)
4298 	    name = DECL_NAME (CALL_EXPR_FN (pack));
4299           else
4300             name = DECL_NAME (pack);
4301 
4302 	  if (name)
4303 	    inform (loc, "        %qD", name);
4304 	  else
4305 	    inform (loc, "        %s", "<anonymous>");
4306 
4307           parameter_packs = TREE_CHAIN (parameter_packs);
4308         }
4309 
4310       return true;
4311     }
4312 
4313   return false;
4314 }
4315 
4316 /* Expand any parameter packs that occur in the template arguments in
4317    ARGS.  */
4318 tree
expand_template_argument_pack(tree args)4319 expand_template_argument_pack (tree args)
4320 {
4321   if (args == error_mark_node)
4322     return error_mark_node;
4323 
4324   tree result_args = NULL_TREE;
4325   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
4326   int num_result_args = -1;
4327   int non_default_args_count = -1;
4328 
4329   /* First, determine if we need to expand anything, and the number of
4330      slots we'll need.  */
4331   for (in_arg = 0; in_arg < nargs; ++in_arg)
4332     {
4333       tree arg = TREE_VEC_ELT (args, in_arg);
4334       if (arg == NULL_TREE)
4335 	return args;
4336       if (ARGUMENT_PACK_P (arg))
4337         {
4338           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
4339           if (num_result_args < 0)
4340             num_result_args = in_arg + num_packed;
4341           else
4342             num_result_args += num_packed;
4343         }
4344       else
4345         {
4346           if (num_result_args >= 0)
4347             num_result_args++;
4348         }
4349     }
4350 
4351   /* If no expansion is necessary, we're done.  */
4352   if (num_result_args < 0)
4353     return args;
4354 
4355   /* Expand arguments.  */
4356   result_args = make_tree_vec (num_result_args);
4357   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
4358     non_default_args_count =
4359       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
4360   for (in_arg = 0; in_arg < nargs; ++in_arg)
4361     {
4362       tree arg = TREE_VEC_ELT (args, in_arg);
4363       if (ARGUMENT_PACK_P (arg))
4364         {
4365           tree packed = ARGUMENT_PACK_ARGS (arg);
4366           int i, num_packed = TREE_VEC_LENGTH (packed);
4367           for (i = 0; i < num_packed; ++i, ++out_arg)
4368             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
4369 	  if (non_default_args_count > 0)
4370 	    non_default_args_count += num_packed - 1;
4371         }
4372       else
4373         {
4374           TREE_VEC_ELT (result_args, out_arg) = arg;
4375           ++out_arg;
4376         }
4377     }
4378   if (non_default_args_count >= 0)
4379     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
4380   return result_args;
4381 }
4382 
4383 /* Checks if DECL shadows a template parameter.
4384 
4385    [temp.local]: A template-parameter shall not be redeclared within its
4386    scope (including nested scopes).
4387 
4388    Emits an error and returns TRUE if the DECL shadows a parameter,
4389    returns FALSE otherwise.  */
4390 
4391 bool
check_template_shadow(tree decl)4392 check_template_shadow (tree decl)
4393 {
4394   tree olddecl;
4395 
4396   /* If we're not in a template, we can't possibly shadow a template
4397      parameter.  */
4398   if (!current_template_parms)
4399     return true;
4400 
4401   /* Figure out what we're shadowing.  */
4402   decl = OVL_FIRST (decl);
4403   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
4404 
4405   /* If there's no previous binding for this name, we're not shadowing
4406      anything, let alone a template parameter.  */
4407   if (!olddecl)
4408     return true;
4409 
4410   /* If we're not shadowing a template parameter, we're done.  Note
4411      that OLDDECL might be an OVERLOAD (or perhaps even an
4412      ERROR_MARK), so we can't just blithely assume it to be a _DECL
4413      node.  */
4414   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
4415     return true;
4416 
4417   /* We check for decl != olddecl to avoid bogus errors for using a
4418      name inside a class.  We check TPFI to avoid duplicate errors for
4419      inline member templates.  */
4420   if (decl == olddecl
4421       || (DECL_TEMPLATE_PARM_P (decl)
4422 	  && TEMPLATE_PARMS_FOR_INLINE (current_template_parms)))
4423     return true;
4424 
4425   /* Don't complain about the injected class name, as we've already
4426      complained about the class itself.  */
4427   if (DECL_SELF_REFERENCE_P (decl))
4428     return false;
4429 
4430   if (DECL_TEMPLATE_PARM_P (decl))
4431     error ("declaration of template parameter %q+D shadows "
4432 	   "template parameter", decl);
4433   else
4434     error ("declaration of %q+#D shadows template parameter", decl);
4435   inform (DECL_SOURCE_LOCATION (olddecl),
4436 	  "template parameter %qD declared here", olddecl);
4437   return false;
4438 }
4439 
4440 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
4441    ORIG_LEVEL, DECL, and TYPE.  */
4442 
4443 static tree
build_template_parm_index(int index,int level,int orig_level,tree decl,tree type)4444 build_template_parm_index (int index,
4445 			   int level,
4446 			   int orig_level,
4447 			   tree decl,
4448 			   tree type)
4449 {
4450   tree t = make_node (TEMPLATE_PARM_INDEX);
4451   TEMPLATE_PARM_IDX (t) = index;
4452   TEMPLATE_PARM_LEVEL (t) = level;
4453   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
4454   TEMPLATE_PARM_DECL (t) = decl;
4455   TREE_TYPE (t) = type;
4456   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
4457   TREE_READONLY (t) = TREE_READONLY (decl);
4458 
4459   return t;
4460 }
4461 
4462 /* Find the canonical type parameter for the given template type
4463    parameter.  Returns the canonical type parameter, which may be TYPE
4464    if no such parameter existed.  */
4465 
4466 tree
canonical_type_parameter(tree type)4467 canonical_type_parameter (tree type)
4468 {
4469   int idx = TEMPLATE_TYPE_IDX (type);
4470 
4471   gcc_assert (TREE_CODE (type) != TEMPLATE_TEMPLATE_PARM);
4472 
4473   if (vec_safe_length (canonical_template_parms) <= (unsigned) idx)
4474     vec_safe_grow_cleared (canonical_template_parms, idx + 1, true);
4475 
4476   for (tree list = (*canonical_template_parms)[idx];
4477        list; list = TREE_CHAIN (list))
4478     if (comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
4479       return TREE_VALUE (list);
4480 
4481   (*canonical_template_parms)[idx]
4482     = tree_cons (NULL_TREE, type, (*canonical_template_parms)[idx]);
4483   return type;
4484 }
4485 
4486 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
4487    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
4488    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
4489    new one is created.  */
4490 
4491 static tree
reduce_template_parm_level(tree index,tree type,int levels,tree args,tsubst_flags_t complain)4492 reduce_template_parm_level (tree index, tree type, int levels, tree args,
4493 			    tsubst_flags_t complain)
4494 {
4495   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
4496       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
4497 	  != TEMPLATE_PARM_LEVEL (index) - levels)
4498       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
4499     {
4500       tree orig_decl = TEMPLATE_PARM_DECL (index);
4501 
4502       tree decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
4503 			      TREE_CODE (orig_decl), DECL_NAME (orig_decl),
4504 			      type);
4505       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
4506       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
4507       DECL_VIRTUAL_P (decl) = DECL_VIRTUAL_P (orig_decl);
4508       DECL_ARTIFICIAL (decl) = 1;
4509       SET_DECL_TEMPLATE_PARM_P (decl);
4510 
4511       tree tpi = build_template_parm_index (TEMPLATE_PARM_IDX (index),
4512 					    TEMPLATE_PARM_LEVEL (index) - levels,
4513 					    TEMPLATE_PARM_ORIG_LEVEL (index),
4514 					    decl, type);
4515       TEMPLATE_PARM_DESCENDANTS (index) = tpi;
4516       TEMPLATE_PARM_PARAMETER_PACK (tpi)
4517 	= TEMPLATE_PARM_PARAMETER_PACK (index);
4518 
4519       /* Template template parameters need this.  */
4520       tree inner = decl;
4521       if (TREE_CODE (decl) == TEMPLATE_DECL)
4522 	{
4523 	  inner = build_decl (DECL_SOURCE_LOCATION (decl),
4524 			      TYPE_DECL, DECL_NAME (decl), type);
4525 	  DECL_TEMPLATE_RESULT (decl) = inner;
4526 	  DECL_ARTIFICIAL (inner) = true;
4527 	  DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
4528 	    (DECL_TEMPLATE_PARMS (orig_decl), args, complain);
4529 	}
4530 
4531       /* Attach the TPI to the decl.  */
4532       if (TREE_CODE (inner) == TYPE_DECL)
4533 	TEMPLATE_TYPE_PARM_INDEX (type) = tpi;
4534       else
4535 	DECL_INITIAL (decl) = tpi;
4536     }
4537 
4538   return TEMPLATE_PARM_DESCENDANTS (index);
4539 }
4540 
4541 /* Process information from new template parameter PARM and append it
4542    to the LIST being built.  This new parameter is a non-type
4543    parameter iff IS_NON_TYPE is true. This new parameter is a
4544    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
4545    is in PARM_LOC.  */
4546 
4547 tree
process_template_parm(tree list,location_t parm_loc,tree parm,bool is_non_type,bool is_parameter_pack)4548 process_template_parm (tree list, location_t parm_loc, tree parm,
4549 		       bool is_non_type, bool is_parameter_pack)
4550 {
4551   gcc_assert (TREE_CODE (parm) == TREE_LIST);
4552   tree prev = NULL_TREE;
4553   int idx = 0;
4554 
4555   if (list)
4556     {
4557       prev = tree_last (list);
4558 
4559       tree p = TREE_VALUE (prev);
4560       if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
4561 	idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
4562       else if (TREE_CODE (p) == PARM_DECL)
4563 	idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
4564 
4565       ++idx;
4566     }
4567 
4568   tree decl = NULL_TREE;
4569   tree defval = TREE_PURPOSE (parm);
4570   tree constr = TREE_TYPE (parm);
4571 
4572   if (is_non_type)
4573     {
4574       parm = TREE_VALUE (parm);
4575 
4576       SET_DECL_TEMPLATE_PARM_P (parm);
4577 
4578       if (TREE_TYPE (parm) != error_mark_node)
4579 	{
4580 	  /* [temp.param]
4581 
4582 	     The top-level cv-qualifiers on the template-parameter are
4583 	     ignored when determining its type.  */
4584 	  TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
4585 	  if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
4586 	    TREE_TYPE (parm) = error_mark_node;
4587 	  else if (uses_parameter_packs (TREE_TYPE (parm))
4588 		   && !is_parameter_pack
4589 		   /* If we're in a nested template parameter list, the template
4590 		      template parameter could be a parameter pack.  */
4591 		   && processing_template_parmlist == 1)
4592 	    {
4593 	      /* This template parameter is not a parameter pack, but it
4594 		 should be. Complain about "bare" parameter packs.  */
4595 	      check_for_bare_parameter_packs (TREE_TYPE (parm));
4596 
4597 	      /* Recover by calling this a parameter pack.  */
4598 	      is_parameter_pack = true;
4599 	    }
4600 	}
4601 
4602       /* A template parameter is not modifiable.  */
4603       TREE_CONSTANT (parm) = 1;
4604       TREE_READONLY (parm) = 1;
4605       decl = build_decl (parm_loc,
4606 			 CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
4607       TREE_CONSTANT (decl) = 1;
4608       TREE_READONLY (decl) = 1;
4609       DECL_INITIAL (parm) = DECL_INITIAL (decl)
4610 	= build_template_parm_index (idx, processing_template_decl,
4611 				     processing_template_decl,
4612 				     decl, TREE_TYPE (parm));
4613 
4614       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4615 	= is_parameter_pack;
4616     }
4617   else
4618     {
4619       tree t;
4620       parm = TREE_VALUE (TREE_VALUE (parm));
4621 
4622       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
4623 	{
4624 	  t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
4625 	  /* This is for distinguishing between real templates and template
4626 	     template parameters */
4627 	  TREE_TYPE (parm) = t;
4628 
4629 	  /* any_template_parm_r expects to be able to get the targs of a
4630 	     DECL_TEMPLATE_RESULT.  */
4631 	  tree result = DECL_TEMPLATE_RESULT (parm);
4632 	  TREE_TYPE (result) = t;
4633 	  tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (parm));
4634 	  tree tinfo = build_template_info (parm, args);
4635 	  retrofit_lang_decl (result);
4636 	  DECL_TEMPLATE_INFO (result) = tinfo;
4637 
4638 	  decl = parm;
4639 	}
4640       else
4641 	{
4642 	  t = cxx_make_type (TEMPLATE_TYPE_PARM);
4643 	  /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
4644 	  decl = build_decl (parm_loc,
4645 			     TYPE_DECL, parm, t);
4646 	}
4647 
4648       TYPE_NAME (t) = decl;
4649       TYPE_STUB_DECL (t) = decl;
4650       parm = decl;
4651       TEMPLATE_TYPE_PARM_INDEX (t)
4652 	= build_template_parm_index (idx, processing_template_decl,
4653 				     processing_template_decl,
4654 				     decl, TREE_TYPE (parm));
4655       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
4656       if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
4657 	SET_TYPE_STRUCTURAL_EQUALITY (t);
4658       else
4659 	TYPE_CANONICAL (t) = canonical_type_parameter (t);
4660     }
4661   DECL_ARTIFICIAL (decl) = 1;
4662   SET_DECL_TEMPLATE_PARM_P (decl);
4663 
4664   /* Build requirements for the type/template parameter.
4665      This must be done after SET_DECL_TEMPLATE_PARM_P or
4666      process_template_parm could fail. */
4667   tree reqs = finish_shorthand_constraint (parm, constr);
4668 
4669   decl = pushdecl (decl);
4670   if (!is_non_type)
4671     parm = decl;
4672 
4673   /* Build the parameter node linking the parameter declaration,
4674      its default argument (if any), and its constraints (if any). */
4675   parm = build_tree_list (defval, parm);
4676   TEMPLATE_PARM_CONSTRAINTS (parm) = reqs;
4677 
4678   if (prev)
4679     TREE_CHAIN (prev) = parm;
4680   else
4681     list = parm;
4682 
4683   return list;
4684 }
4685 
4686 /* The end of a template parameter list has been reached.  Process the
4687    tree list into a parameter vector, converting each parameter into a more
4688    useful form.	 Type parameters are saved as IDENTIFIER_NODEs, and others
4689    as PARM_DECLs.  */
4690 
4691 tree
end_template_parm_list(tree parms)4692 end_template_parm_list (tree parms)
4693 {
4694   tree saved_parmlist = make_tree_vec (list_length (parms));
4695 
4696   /* Pop the dummy parameter level and add the real one.  We do not
4697      morph the dummy parameter in place, as it might have been
4698      captured by a (nested) template-template-parm.  */
4699   current_template_parms = TREE_CHAIN (current_template_parms);
4700 
4701   current_template_parms
4702     = tree_cons (size_int (processing_template_decl),
4703 		 saved_parmlist, current_template_parms);
4704 
4705   for (unsigned ix = 0; parms; ix++)
4706     {
4707       tree parm = parms;
4708       parms = TREE_CHAIN (parms);
4709       TREE_CHAIN (parm) = NULL_TREE;
4710 
4711       TREE_VEC_ELT (saved_parmlist, ix) = parm;
4712     }
4713 
4714   --processing_template_parmlist;
4715 
4716   return saved_parmlist;
4717 }
4718 
4719 // Explicitly indicate the end of the template parameter list. We assume
4720 // that the current template parameters have been constructed and/or
4721 // managed explicitly, as when creating new template template parameters
4722 // from a shorthand constraint.
4723 void
end_template_parm_list()4724 end_template_parm_list ()
4725 {
4726   --processing_template_parmlist;
4727 }
4728 
4729 /* end_template_decl is called after a template declaration is seen.  */
4730 
4731 void
end_template_decl(void)4732 end_template_decl (void)
4733 {
4734   reset_specialization ();
4735 
4736   if (! processing_template_decl)
4737     return;
4738 
4739   /* This matches the pushlevel in begin_template_parm_list.  */
4740   finish_scope ();
4741 
4742   --processing_template_decl;
4743   current_template_parms = TREE_CHAIN (current_template_parms);
4744 }
4745 
4746 /* Takes a TEMPLATE_PARM_P or DECL_TEMPLATE_PARM_P node or a TREE_LIST
4747    thereof, and converts it into an argument suitable to be passed to
4748    the type substitution functions.  Note that if the TREE_LIST contains
4749    an error_mark node, the returned argument is error_mark_node.  */
4750 
4751 tree
template_parm_to_arg(tree t)4752 template_parm_to_arg (tree t)
4753 {
4754   if (!t)
4755     return NULL_TREE;
4756 
4757   if (TREE_CODE (t) == TREE_LIST)
4758     t = TREE_VALUE (t);
4759 
4760   if (error_operand_p (t))
4761     return error_mark_node;
4762 
4763   if (DECL_P (t) && DECL_TEMPLATE_PARM_P (t))
4764     {
4765       if (TREE_CODE (t) == TYPE_DECL
4766 	  || TREE_CODE (t) == TEMPLATE_DECL)
4767 	t = TREE_TYPE (t);
4768       else
4769 	t = DECL_INITIAL (t);
4770     }
4771 
4772   gcc_assert (TEMPLATE_PARM_P (t));
4773 
4774   if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
4775       || TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
4776     {
4777       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
4778 	{
4779 	  /* Turn this argument into a TYPE_ARGUMENT_PACK
4780 	     with a single element, which expands T.  */
4781 	  tree vec = make_tree_vec (1);
4782 	  if (CHECKING_P)
4783 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4784 
4785 	  TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4786 
4787 	  t = cxx_make_type (TYPE_ARGUMENT_PACK);
4788 	  SET_ARGUMENT_PACK_ARGS (t, vec);
4789 	}
4790     }
4791   else
4792     {
4793       if (TEMPLATE_PARM_PARAMETER_PACK (t))
4794 	{
4795 	  /* Turn this argument into a NONTYPE_ARGUMENT_PACK
4796 	     with a single element, which expands T.  */
4797 	  tree vec = make_tree_vec (1);
4798 	  if (CHECKING_P)
4799 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4800 
4801 	  t = convert_from_reference (t);
4802 	  TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4803 
4804 	  t  = make_node (NONTYPE_ARGUMENT_PACK);
4805 	  SET_ARGUMENT_PACK_ARGS (t, vec);
4806 	}
4807       else
4808 	t = convert_from_reference (t);
4809     }
4810   return t;
4811 }
4812 
4813 /* Given a single level of template parameters (a TREE_VEC), return it
4814    as a set of template arguments.  */
4815 
4816 tree
template_parms_level_to_args(tree parms)4817 template_parms_level_to_args (tree parms)
4818 {
4819   tree a = copy_node (parms);
4820   TREE_TYPE (a) = NULL_TREE;
4821   for (int i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4822     TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4823 
4824   if (CHECKING_P)
4825     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4826 
4827   return a;
4828 }
4829 
4830 /* Given a set of template parameters, return them as a set of template
4831    arguments.  The template parameters are represented as a TREE_VEC, in
4832    the form documented in cp-tree.h for template arguments.  */
4833 
4834 tree
template_parms_to_args(tree parms)4835 template_parms_to_args (tree parms)
4836 {
4837   tree header;
4838   tree args = NULL_TREE;
4839   int length = TMPL_PARMS_DEPTH (parms);
4840   int l = length;
4841 
4842   /* If there is only one level of template parameters, we do not
4843      create a TREE_VEC of TREE_VECs.  Instead, we return a single
4844      TREE_VEC containing the arguments.  */
4845   if (length > 1)
4846     args = make_tree_vec (length);
4847 
4848   for (header = parms; header; header = TREE_CHAIN (header))
4849     {
4850       tree a = template_parms_level_to_args (TREE_VALUE (header));
4851 
4852       if (length > 1)
4853 	TREE_VEC_ELT (args, --l) = a;
4854       else
4855 	args = a;
4856     }
4857 
4858   return args;
4859 }
4860 
4861 /* Within the declaration of a template, return the currently active
4862    template parameters as an argument TREE_VEC.  */
4863 
4864 static tree
current_template_args(void)4865 current_template_args (void)
4866 {
4867   return template_parms_to_args (current_template_parms);
4868 }
4869 
4870 /* Return the fully generic arguments for of TMPL, i.e. what
4871    current_template_args would be while parsing it.  */
4872 
4873 tree
generic_targs_for(tree tmpl)4874 generic_targs_for (tree tmpl)
4875 {
4876   if (tmpl == NULL_TREE)
4877     return NULL_TREE;
4878   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
4879       || DECL_TEMPLATE_SPECIALIZATION (tmpl))
4880     /* DECL_TEMPLATE_RESULT doesn't have the arguments we want.  For a template
4881        template parameter, it has no TEMPLATE_INFO; for a partial
4882        specialization, it has the arguments for the primary template, and we
4883        want the arguments for the partial specialization.  */;
4884   else if (tree result = DECL_TEMPLATE_RESULT (tmpl))
4885     if (tree ti = get_template_info (result))
4886       return TI_ARGS (ti);
4887   return template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl));
4888 }
4889 
4890 /* Update the declared TYPE by doing any lookups which were thought to be
4891    dependent, but are not now that we know the SCOPE of the declarator.  */
4892 
4893 tree
maybe_update_decl_type(tree orig_type,tree scope)4894 maybe_update_decl_type (tree orig_type, tree scope)
4895 {
4896   tree type = orig_type;
4897 
4898   if (type == NULL_TREE)
4899     return type;
4900 
4901   if (TREE_CODE (orig_type) == TYPE_DECL)
4902     type = TREE_TYPE (type);
4903 
4904   if (scope && TYPE_P (scope) && dependent_type_p (scope)
4905       && dependent_type_p (type)
4906       /* Don't bother building up the args in this case.  */
4907       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4908     {
4909       /* tsubst in the args corresponding to the template parameters,
4910 	 including auto if present.  Most things will be unchanged, but
4911 	 make_typename_type and tsubst_qualified_id will resolve
4912 	 TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
4913       tree args = current_template_args ();
4914       tree auto_node = type_uses_auto (type);
4915       tree pushed;
4916       if (auto_node)
4917 	{
4918 	  tree auto_vec = make_tree_vec (1);
4919 	  TREE_VEC_ELT (auto_vec, 0) = auto_node;
4920 	  args = add_to_template_args (args, auto_vec);
4921 	}
4922       pushed = push_scope (scope);
4923       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4924       if (pushed)
4925 	pop_scope (scope);
4926     }
4927 
4928   if (type == error_mark_node)
4929     return orig_type;
4930 
4931   if (TREE_CODE (orig_type) == TYPE_DECL)
4932     {
4933       if (same_type_p (type, TREE_TYPE (orig_type)))
4934 	type = orig_type;
4935       else
4936 	type = TYPE_NAME (type);
4937     }
4938   return type;
4939 }
4940 
4941 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4942    template PARMS and constraints, CONSTR.  If MEMBER_TEMPLATE_P is true,
4943    the new  template is a member template. */
4944 
4945 static tree
build_template_decl(tree decl,tree parms,bool member_template_p)4946 build_template_decl (tree decl, tree parms, bool member_template_p)
4947 {
4948   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4949   SET_DECL_LANGUAGE (tmpl, DECL_LANGUAGE (decl));
4950   DECL_TEMPLATE_PARMS (tmpl) = parms;
4951   DECL_TEMPLATE_RESULT (tmpl) = decl;
4952   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4953   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4954   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
4955   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4956 
4957   /* Propagate module information from the decl.  */
4958   DECL_MODULE_EXPORT_P (tmpl) = DECL_MODULE_EXPORT_P (decl);
4959 
4960   return tmpl;
4961 }
4962 
4963 struct template_parm_data
4964 {
4965   /* The level of the template parameters we are currently
4966      processing.  */
4967   int level;
4968 
4969   /* The index of the specialization argument we are currently
4970      processing.  */
4971   int current_arg;
4972 
4973   /* An array whose size is the number of template parameters.  The
4974      elements are nonzero if the parameter has been used in any one
4975      of the arguments processed so far.  */
4976   int* parms;
4977 
4978   /* An array whose size is the number of template arguments.  The
4979      elements are nonzero if the argument makes use of template
4980      parameters of this level.  */
4981   int* arg_uses_template_parms;
4982 };
4983 
4984 /* Subroutine of push_template_decl used to see if each template
4985    parameter in a partial specialization is used in the explicit
4986    argument list.  If T is of the LEVEL given in DATA (which is
4987    treated as a template_parm_data*), then DATA->PARMS is marked
4988    appropriately.  */
4989 
4990 static int
mark_template_parm(tree t,void * data)4991 mark_template_parm (tree t, void* data)
4992 {
4993   int level;
4994   int idx;
4995   struct template_parm_data* tpd = (struct template_parm_data*) data;
4996 
4997   template_parm_level_and_index (t, &level, &idx);
4998 
4999   if (level == tpd->level)
5000     {
5001       tpd->parms[idx] = 1;
5002       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
5003     }
5004 
5005   /* In C++17 the type of a non-type argument is a deduced context.  */
5006   if (cxx_dialect >= cxx17
5007       && TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5008     for_each_template_parm (TREE_TYPE (t),
5009 			    &mark_template_parm,
5010 			    data,
5011 			    NULL,
5012 			    /*include_nondeduced_p=*/false);
5013 
5014   /* Return zero so that for_each_template_parm will continue the
5015      traversal of the tree; we want to mark *every* template parm.  */
5016   return 0;
5017 }
5018 
5019 /* Process the partial specialization DECL.  */
5020 
5021 static tree
process_partial_specialization(tree decl)5022 process_partial_specialization (tree decl)
5023 {
5024   tree type = TREE_TYPE (decl);
5025   tree tinfo = get_template_info (decl);
5026   tree maintmpl = TI_TEMPLATE (tinfo);
5027   tree specargs = TI_ARGS (tinfo);
5028   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
5029   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
5030   tree inner_parms;
5031   tree inst;
5032   int nargs = TREE_VEC_LENGTH (inner_args);
5033   int ntparms;
5034   int  i;
5035   bool did_error_intro = false;
5036   struct template_parm_data tpd;
5037   struct template_parm_data tpd2;
5038 
5039   gcc_assert (current_template_parms);
5040 
5041   /* A concept cannot be specialized.  */
5042   if (flag_concepts && variable_concept_p (maintmpl))
5043     {
5044       error ("specialization of variable concept %q#D", maintmpl);
5045       return error_mark_node;
5046     }
5047 
5048   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
5049   ntparms = TREE_VEC_LENGTH (inner_parms);
5050 
5051   /* We check that each of the template parameters given in the
5052      partial specialization is used in the argument list to the
5053      specialization.  For example:
5054 
5055        template <class T> struct S;
5056        template <class T> struct S<T*>;
5057 
5058      The second declaration is OK because `T*' uses the template
5059      parameter T, whereas
5060 
5061        template <class T> struct S<int>;
5062 
5063      is no good.  Even trickier is:
5064 
5065        template <class T>
5066        struct S1
5067        {
5068 	  template <class U>
5069 	  struct S2;
5070 	  template <class U>
5071 	  struct S2<T>;
5072        };
5073 
5074      The S2<T> declaration is actually invalid; it is a
5075      full-specialization.  Of course,
5076 
5077 	  template <class U>
5078 	  struct S2<T (*)(U)>;
5079 
5080      or some such would have been OK.  */
5081   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
5082   tpd.parms = XALLOCAVEC (int, ntparms);
5083   memset (tpd.parms, 0, sizeof (int) * ntparms);
5084 
5085   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5086   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
5087   for (i = 0; i < nargs; ++i)
5088     {
5089       tpd.current_arg = i;
5090       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
5091 			      &mark_template_parm,
5092 			      &tpd,
5093 			      NULL,
5094 			      /*include_nondeduced_p=*/false);
5095     }
5096   for (i = 0; i < ntparms; ++i)
5097     if (tpd.parms[i] == 0)
5098       {
5099 	/* One of the template parms was not used in a deduced context in the
5100 	   specialization.  */
5101 	if (!did_error_intro)
5102 	  {
5103 	    error ("template parameters not deducible in "
5104 		   "partial specialization:");
5105 	    did_error_intro = true;
5106 	  }
5107 
5108 	inform (input_location, "        %qD",
5109 		TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
5110       }
5111 
5112   if (did_error_intro)
5113     return error_mark_node;
5114 
5115   /* [temp.class.spec]
5116 
5117      The argument list of the specialization shall not be identical to
5118      the implicit argument list of the primary template.  */
5119   tree main_args
5120     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
5121   if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args))
5122       && (!flag_concepts
5123 	  || !strictly_subsumes (current_template_constraints (), maintmpl)))
5124     {
5125       if (!flag_concepts)
5126         error ("partial specialization %q+D does not specialize "
5127 	       "any template arguments; to define the primary template, "
5128 	       "remove the template argument list", decl);
5129       else
5130         error ("partial specialization %q+D does not specialize any "
5131 	       "template arguments and is not more constrained than "
5132 	       "the primary template; to define the primary template, "
5133 	       "remove the template argument list", decl);
5134       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5135     }
5136 
5137   /* A partial specialization that replaces multiple parameters of the
5138      primary template with a pack expansion is less specialized for those
5139      parameters.  */
5140   if (nargs < DECL_NTPARMS (maintmpl))
5141     {
5142       error ("partial specialization is not more specialized than the "
5143 	     "primary template because it replaces multiple parameters "
5144 	     "with a pack expansion");
5145       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5146       /* Avoid crash in process_partial_specialization.  */
5147       return decl;
5148     }
5149 
5150   else if (nargs > DECL_NTPARMS (maintmpl))
5151     {
5152       error ("too many arguments for partial specialization %qT", type);
5153       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5154       /* Avoid crash below.  */
5155       return decl;
5156     }
5157 
5158   /* If we aren't in a dependent class, we can actually try deduction.  */
5159   else if (tpd.level == 1
5160 	   /* FIXME we should be able to handle a partial specialization of a
5161 	      partial instantiation, but currently we can't (c++/41727).  */
5162 	   && TMPL_ARGS_DEPTH (specargs) == 1
5163 	   && !get_partial_spec_bindings (maintmpl, maintmpl, specargs))
5164     {
5165       auto_diagnostic_group d;
5166       if (permerror (input_location, "partial specialization %qD is not "
5167 		     "more specialized than", decl))
5168 	inform (DECL_SOURCE_LOCATION (maintmpl), "primary template %qD",
5169 		maintmpl);
5170     }
5171 
5172   /* [temp.class.spec]
5173 
5174      A partially specialized non-type argument expression shall not
5175      involve template parameters of the partial specialization except
5176      when the argument expression is a simple identifier.
5177 
5178      The type of a template parameter corresponding to a specialized
5179      non-type argument shall not be dependent on a parameter of the
5180      specialization.
5181 
5182      Also, we verify that pack expansions only occur at the
5183      end of the argument list.  */
5184   tpd2.parms = 0;
5185   for (i = 0; i < nargs; ++i)
5186     {
5187       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
5188       tree arg = TREE_VEC_ELT (inner_args, i);
5189       tree packed_args = NULL_TREE;
5190       int j, len = 1;
5191 
5192       if (ARGUMENT_PACK_P (arg))
5193         {
5194           /* Extract the arguments from the argument pack. We'll be
5195              iterating over these in the following loop.  */
5196           packed_args = ARGUMENT_PACK_ARGS (arg);
5197           len = TREE_VEC_LENGTH (packed_args);
5198         }
5199 
5200       for (j = 0; j < len; j++)
5201         {
5202           if (packed_args)
5203             /* Get the Jth argument in the parameter pack.  */
5204             arg = TREE_VEC_ELT (packed_args, j);
5205 
5206           if (PACK_EXPANSION_P (arg))
5207             {
5208               /* Pack expansions must come at the end of the
5209                  argument list.  */
5210               if ((packed_args && j < len - 1)
5211                   || (!packed_args && i < nargs - 1))
5212                 {
5213                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5214                     error ("parameter pack argument %qE must be at the "
5215 			   "end of the template argument list", arg);
5216                   else
5217                     error ("parameter pack argument %qT must be at the "
5218 			   "end of the template argument list", arg);
5219                 }
5220             }
5221 
5222           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5223             /* We only care about the pattern.  */
5224             arg = PACK_EXPANSION_PATTERN (arg);
5225 
5226           if (/* These first two lines are the `non-type' bit.  */
5227               !TYPE_P (arg)
5228               && TREE_CODE (arg) != TEMPLATE_DECL
5229               /* This next two lines are the `argument expression is not just a
5230                  simple identifier' condition and also the `specialized
5231                  non-type argument' bit.  */
5232               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
5233 	      && !((REFERENCE_REF_P (arg)
5234 		    || TREE_CODE (arg) == VIEW_CONVERT_EXPR)
5235 		   && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
5236             {
5237               if ((!packed_args && tpd.arg_uses_template_parms[i])
5238                   || (packed_args && uses_template_parms (arg)))
5239 		error_at (cp_expr_loc_or_input_loc (arg),
5240 			  "template argument %qE involves template "
5241 			  "parameter(s)", arg);
5242               else
5243                 {
5244                   /* Look at the corresponding template parameter,
5245                      marking which template parameters its type depends
5246                      upon.  */
5247                   tree type = TREE_TYPE (parm);
5248 
5249                   if (!tpd2.parms)
5250                     {
5251                       /* We haven't yet initialized TPD2.  Do so now.  */
5252                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5253                       /* The number of parameters here is the number in the
5254                          main template, which, as checked in the assertion
5255                          above, is NARGS.  */
5256                       tpd2.parms = XALLOCAVEC (int, nargs);
5257                       tpd2.level =
5258                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
5259                     }
5260 
5261                   /* Mark the template parameters.  But this time, we're
5262                      looking for the template parameters of the main
5263                      template, not in the specialization.  */
5264                   tpd2.current_arg = i;
5265                   tpd2.arg_uses_template_parms[i] = 0;
5266                   memset (tpd2.parms, 0, sizeof (int) * nargs);
5267                   for_each_template_parm (type,
5268                                           &mark_template_parm,
5269                                           &tpd2,
5270                                           NULL,
5271 					  /*include_nondeduced_p=*/false);
5272 
5273                   if (tpd2.arg_uses_template_parms [i])
5274                     {
5275                       /* The type depended on some template parameters.
5276                          If they are fully specialized in the
5277                          specialization, that's OK.  */
5278                       int j;
5279                       int count = 0;
5280                       for (j = 0; j < nargs; ++j)
5281                         if (tpd2.parms[j] != 0
5282                             && tpd.arg_uses_template_parms [j])
5283                           ++count;
5284                       if (count != 0)
5285                         error_n (input_location, count,
5286                                  "type %qT of template argument %qE depends "
5287                                  "on a template parameter",
5288                                  "type %qT of template argument %qE depends "
5289                                  "on template parameters",
5290                                  type,
5291                                  arg);
5292                     }
5293                 }
5294             }
5295         }
5296     }
5297 
5298   /* We should only get here once.  */
5299   if (TREE_CODE (decl) == TYPE_DECL)
5300     gcc_assert (!COMPLETE_TYPE_P (type));
5301 
5302   // Build the template decl.
5303   tree tmpl = build_template_decl (decl, current_template_parms,
5304 				   DECL_MEMBER_TEMPLATE_P (maintmpl));
5305   SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5306   DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
5307   DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
5308 
5309   /* Give template template parms a DECL_CONTEXT of the template
5310      for which they are a parameter.  */
5311   for (i = 0; i < ntparms; ++i)
5312     {
5313       tree parm = TREE_VALUE (TREE_VEC_ELT (inner_parms, i));
5314       if (TREE_CODE (parm) == TEMPLATE_DECL)
5315 	DECL_CONTEXT (parm) = tmpl;
5316     }
5317 
5318   if (VAR_P (decl))
5319     /* We didn't register this in check_explicit_specialization so we could
5320        wait until the constraints were set.  */
5321     decl = register_specialization (decl, maintmpl, specargs, false, 0);
5322   else
5323     associate_classtype_constraints (type);
5324 
5325   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
5326     = tree_cons (specargs, tmpl,
5327                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
5328   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
5329 
5330   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
5331        inst = TREE_CHAIN (inst))
5332     {
5333       tree instance = TREE_VALUE (inst);
5334       if (TYPE_P (instance)
5335 	  ? (COMPLETE_TYPE_P (instance)
5336 	     && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
5337 	  : DECL_TEMPLATE_INSTANTIATION (instance))
5338 	{
5339 	  tree spec = most_specialized_partial_spec (instance, tf_none);
5340 	  tree inst_decl = (DECL_P (instance)
5341 			    ? instance : TYPE_NAME (instance));
5342 	  if (!spec)
5343 	    /* OK */;
5344 	  else if (spec == error_mark_node)
5345 	    permerror (input_location,
5346 		       "declaration of %qD ambiguates earlier template "
5347 		       "instantiation for %qD", decl, inst_decl);
5348 	  else if (TREE_VALUE (spec) == tmpl)
5349 	    permerror (input_location,
5350 		       "partial specialization of %qD after instantiation "
5351 		       "of %qD", decl, inst_decl);
5352 	}
5353     }
5354 
5355   return decl;
5356 }
5357 
5358 /* PARM is a template parameter of some form; return the corresponding
5359    TEMPLATE_PARM_INDEX.  */
5360 
5361 static tree
get_template_parm_index(tree parm)5362 get_template_parm_index (tree parm)
5363 {
5364   if (TREE_CODE (parm) == PARM_DECL
5365       || TREE_CODE (parm) == CONST_DECL)
5366     parm = DECL_INITIAL (parm);
5367   else if (TREE_CODE (parm) == TYPE_DECL
5368 	   || TREE_CODE (parm) == TEMPLATE_DECL)
5369     parm = TREE_TYPE (parm);
5370   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
5371       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM
5372       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
5373     parm = TEMPLATE_TYPE_PARM_INDEX (parm);
5374   gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
5375   return parm;
5376 }
5377 
5378 /* Subroutine of fixed_parameter_pack_p below.  Look for any template
5379    parameter packs used by the template parameter PARM.  */
5380 
5381 static void
fixed_parameter_pack_p_1(tree parm,struct find_parameter_pack_data * ppd)5382 fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
5383 {
5384   /* A type parm can't refer to another parm.  */
5385   if (TREE_CODE (parm) == TYPE_DECL || parm == error_mark_node)
5386     return;
5387   else if (TREE_CODE (parm) == PARM_DECL)
5388     {
5389       cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
5390 		    ppd, ppd->visited);
5391       return;
5392     }
5393 
5394   gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
5395 
5396   tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
5397   for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
5398     {
5399       tree p = TREE_VALUE (TREE_VEC_ELT (vec, i));
5400       if (template_parameter_pack_p (p))
5401 	/* Any packs in the type are expanded by this parameter.  */;
5402       else
5403 	fixed_parameter_pack_p_1 (p, ppd);
5404     }
5405 }
5406 
5407 /* PARM is a template parameter pack.  Return any parameter packs used in
5408    its type or the type of any of its template parameters.  If there are
5409    any such packs, it will be instantiated into a fixed template parameter
5410    list by partial instantiation rather than be fully deduced.  */
5411 
5412 tree
fixed_parameter_pack_p(tree parm)5413 fixed_parameter_pack_p (tree parm)
5414 {
5415   /* This can only be true in a member template.  */
5416   if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
5417     return NULL_TREE;
5418   /* This can only be true for a parameter pack.  */
5419   if (!template_parameter_pack_p (parm))
5420     return NULL_TREE;
5421   /* A type parm can't refer to another parm.  */
5422   if (TREE_CODE (parm) == TYPE_DECL)
5423     return NULL_TREE;
5424 
5425   tree parameter_packs = NULL_TREE;
5426   struct find_parameter_pack_data ppd;
5427   ppd.parameter_packs = &parameter_packs;
5428   ppd.visited = new hash_set<tree>;
5429   ppd.type_pack_expansion_p = false;
5430 
5431   fixed_parameter_pack_p_1 (parm, &ppd);
5432 
5433   delete ppd.visited;
5434   return parameter_packs;
5435 }
5436 
5437 /* Check that a template declaration's use of default arguments and
5438    parameter packs is not invalid.  Here, PARMS are the template
5439    parameters.  IS_PRIMARY is true if DECL is the thing declared by
5440    a primary template.  IS_PARTIAL is true if DECL is a partial
5441    specialization.
5442 
5443    IS_FRIEND_DECL is nonzero if DECL is either a non-defining friend
5444    function template declaration or a friend class template
5445    declaration.  In the function case, 1 indicates a declaration, 2
5446    indicates a redeclaration.  When IS_FRIEND_DECL=2, no errors are
5447    emitted for extraneous default arguments.
5448 
5449    Returns TRUE if there were no errors found, FALSE otherwise. */
5450 
5451 bool
check_default_tmpl_args(tree decl,tree parms,bool is_primary,bool is_partial,int is_friend_decl)5452 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
5453                          bool is_partial, int is_friend_decl)
5454 {
5455   const char *msg;
5456   int last_level_to_check;
5457   tree parm_level;
5458   bool no_errors = true;
5459 
5460   /* [temp.param]
5461 
5462      A default template-argument shall not be specified in a
5463      function template declaration or a function template definition, nor
5464      in the template-parameter-list of the definition of a member of a
5465      class template.  */
5466 
5467   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
5468       || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_DECL_P (decl)))
5469     /* You can't have a function template declaration in a local
5470        scope, nor you can you define a member of a class template in a
5471        local scope.  */
5472     return true;
5473 
5474   if ((TREE_CODE (decl) == TYPE_DECL
5475        && TREE_TYPE (decl)
5476        && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5477       || (TREE_CODE (decl) == FUNCTION_DECL
5478 	  && LAMBDA_FUNCTION_P (decl)))
5479     /* A lambda doesn't have an explicit declaration; don't complain
5480        about the parms of the enclosing class.  */
5481     return true;
5482 
5483   if (current_class_type
5484       && !TYPE_BEING_DEFINED (current_class_type)
5485       && DECL_LANG_SPECIFIC (decl)
5486       && DECL_DECLARES_FUNCTION_P (decl)
5487       /* If this is either a friend defined in the scope of the class
5488 	 or a member function.  */
5489       && (DECL_FUNCTION_MEMBER_P (decl)
5490 	  ? same_type_p (DECL_CONTEXT (decl), current_class_type)
5491 	  : DECL_FRIEND_CONTEXT (decl)
5492 	  ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
5493 	  : false)
5494       /* And, if it was a member function, it really was defined in
5495 	 the scope of the class.  */
5496       && (!DECL_FUNCTION_MEMBER_P (decl)
5497 	  || DECL_INITIALIZED_IN_CLASS_P (decl)))
5498     /* We already checked these parameters when the template was
5499        declared, so there's no need to do it again now.  This function
5500        was defined in class scope, but we're processing its body now
5501        that the class is complete.  */
5502     return true;
5503 
5504   /* Core issue 226 (C++0x only): the following only applies to class
5505      templates.  */
5506   if (is_primary
5507       && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
5508     {
5509       /* [temp.param]
5510 
5511          If a template-parameter has a default template-argument, all
5512          subsequent template-parameters shall have a default
5513          template-argument supplied.  */
5514       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
5515         {
5516           tree inner_parms = TREE_VALUE (parm_level);
5517           int ntparms = TREE_VEC_LENGTH (inner_parms);
5518           int seen_def_arg_p = 0;
5519           int i;
5520 
5521           for (i = 0; i < ntparms; ++i)
5522             {
5523               tree parm = TREE_VEC_ELT (inner_parms, i);
5524 
5525               if (parm == error_mark_node)
5526                 continue;
5527 
5528               if (TREE_PURPOSE (parm))
5529                 seen_def_arg_p = 1;
5530               else if (seen_def_arg_p
5531 		       && !template_parameter_pack_p (TREE_VALUE (parm)))
5532                 {
5533                   error ("no default argument for %qD", TREE_VALUE (parm));
5534                   /* For better subsequent error-recovery, we indicate that
5535                      there should have been a default argument.  */
5536                   TREE_PURPOSE (parm) = error_mark_node;
5537                   no_errors = false;
5538                 }
5539 	      else if (!is_partial
5540 		       && !is_friend_decl
5541 		       /* Don't complain about an enclosing partial
5542 			  specialization.  */
5543 		       && parm_level == parms
5544 		       && (TREE_CODE (decl) == TYPE_DECL || VAR_P (decl))
5545 		       && i < ntparms - 1
5546 		       && template_parameter_pack_p (TREE_VALUE (parm))
5547 		       /* A fixed parameter pack will be partially
5548 			  instantiated into a fixed length list.  */
5549 		       && !fixed_parameter_pack_p (TREE_VALUE (parm)))
5550 		{
5551 		  /* A primary class template, primary variable template
5552 		     (DR 2032), or alias template can only have one
5553 		     parameter pack, at the end of the template
5554 		     parameter list.  */
5555 
5556 		  error ("parameter pack %q+D must be at the end of the"
5557 			 " template parameter list", TREE_VALUE (parm));
5558 
5559 		  TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
5560 		    = error_mark_node;
5561 		  no_errors = false;
5562 		}
5563             }
5564         }
5565     }
5566 
5567   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
5568       || is_partial
5569       || !is_primary
5570       || is_friend_decl)
5571     /* For an ordinary class template, default template arguments are
5572        allowed at the innermost level, e.g.:
5573 	 template <class T = int>
5574 	 struct S {};
5575        but, in a partial specialization, they're not allowed even
5576        there, as we have in [temp.class.spec]:
5577 
5578 	 The template parameter list of a specialization shall not
5579 	 contain default template argument values.
5580 
5581        So, for a partial specialization, or for a function template
5582        (in C++98/C++03), we look at all of them.  */
5583     ;
5584   else
5585     /* But, for a primary class template that is not a partial
5586        specialization we look at all template parameters except the
5587        innermost ones.  */
5588     parms = TREE_CHAIN (parms);
5589 
5590   /* Figure out what error message to issue.  */
5591   if (is_friend_decl == 2)
5592     msg = G_("default template arguments may not be used in function template "
5593 	     "friend re-declaration");
5594   else if (is_friend_decl)
5595     msg = G_("default template arguments may not be used in template "
5596 	     "friend declarations");
5597   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
5598     msg = G_("default template arguments may not be used in function templates "
5599 	     "without %<-std=c++11%> or %<-std=gnu++11%>");
5600   else if (is_partial)
5601     msg = G_("default template arguments may not be used in "
5602 	     "partial specializations");
5603   else if (current_class_type && CLASSTYPE_IS_TEMPLATE (current_class_type))
5604     msg = G_("default argument for template parameter for class enclosing %qD");
5605   else
5606     /* Per [temp.param]/9, "A default template-argument shall not be
5607        specified in the template-parameter-lists of the definition of
5608        a member of a class template that appears outside of the member's
5609        class.", thus if we aren't handling a member of a class template
5610        there is no need to examine the parameters.  */
5611     return true;
5612 
5613   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
5614     /* If we're inside a class definition, there's no need to
5615        examine the parameters to the class itself.  On the one
5616        hand, they will be checked when the class is defined, and,
5617        on the other, default arguments are valid in things like:
5618 	 template <class T = double>
5619 	 struct S { template <class U> void f(U); };
5620        Here the default argument for `S' has no bearing on the
5621        declaration of `f'.  */
5622     last_level_to_check = template_class_depth (current_class_type) + 1;
5623   else
5624     /* Check everything.  */
5625     last_level_to_check = 0;
5626 
5627   for (parm_level = parms;
5628        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
5629        parm_level = TREE_CHAIN (parm_level))
5630     {
5631       tree inner_parms = TREE_VALUE (parm_level);
5632       int i;
5633       int ntparms;
5634 
5635       ntparms = TREE_VEC_LENGTH (inner_parms);
5636       for (i = 0; i < ntparms; ++i)
5637         {
5638           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
5639             continue;
5640 
5641 	  if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
5642 	    {
5643 	      if (msg)
5644 	        {
5645                   no_errors = false;
5646                   if (is_friend_decl == 2)
5647                     return no_errors;
5648 
5649 		  error (msg, decl);
5650 		  msg = 0;
5651 	        }
5652 
5653 	      /* Clear out the default argument so that we are not
5654 	         confused later.  */
5655 	      TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
5656 	    }
5657         }
5658 
5659       /* At this point, if we're still interested in issuing messages,
5660 	 they must apply to classes surrounding the object declared.  */
5661       if (msg)
5662 	msg = G_("default argument for template parameter for class "
5663 		 "enclosing %qD");
5664     }
5665 
5666   return no_errors;
5667 }
5668 
5669 /* Worker for push_template_decl_real, called via
5670    for_each_template_parm.  DATA is really an int, indicating the
5671    level of the parameters we are interested in.  If T is a template
5672    parameter of that level, return nonzero.  */
5673 
5674 static int
template_parm_this_level_p(tree t,void * data)5675 template_parm_this_level_p (tree t, void* data)
5676 {
5677   int this_level = *(int *)data;
5678   int level;
5679 
5680   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5681     level = TEMPLATE_PARM_LEVEL (t);
5682   else
5683     level = TEMPLATE_TYPE_LEVEL (t);
5684   return level == this_level;
5685 }
5686 
5687 /* Worker for uses_outer_template_parms, called via for_each_template_parm.
5688    DATA is really an int, indicating the innermost outer level of parameters.
5689    If T is a template parameter of that level or further out, return
5690    nonzero.  */
5691 
5692 static int
template_parm_outer_level(tree t,void * data)5693 template_parm_outer_level (tree t, void *data)
5694 {
5695   int this_level = *(int *)data;
5696   int level;
5697 
5698   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5699     level = TEMPLATE_PARM_LEVEL (t);
5700   else
5701     level = TEMPLATE_TYPE_LEVEL (t);
5702   return level <= this_level;
5703 }
5704 
5705 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
5706    parameters given by current_template_args, or reuses a
5707    previously existing one, if appropriate.  Returns the DECL, or an
5708    equivalent one, if it is replaced via a call to duplicate_decls.
5709 
5710    If IS_FRIEND is true, DECL is a friend declaration.  */
5711 
5712 tree
push_template_decl(tree decl,bool is_friend)5713 push_template_decl (tree decl, bool is_friend)
5714 {
5715   if (decl == error_mark_node || !current_template_parms)
5716     return error_mark_node;
5717 
5718   /* See if this is a partial specialization.  */
5719   bool is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
5720 		      && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
5721 		      && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
5722 		     || (VAR_P (decl)
5723 			 && DECL_LANG_SPECIFIC (decl)
5724 			 && DECL_TEMPLATE_SPECIALIZATION (decl)
5725 			 && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
5726 
5727   /* No surprising friend functions.  */
5728   gcc_checking_assert (is_friend
5729 		       || !(TREE_CODE (decl) == FUNCTION_DECL
5730 			    && DECL_UNIQUE_FRIEND_P (decl)));
5731 
5732   tree ctx;
5733   if (is_friend)
5734     /* For a friend, we want the context of the friend, not
5735        the type of which it is a friend.  */
5736     ctx = CP_DECL_CONTEXT (decl);
5737   else if (CP_DECL_CONTEXT (decl)
5738 	   && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
5739     /* In the case of a virtual function, we want the class in which
5740        it is defined.  */
5741     ctx = CP_DECL_CONTEXT (decl);
5742   else
5743     /* Otherwise, if we're currently defining some class, the DECL
5744        is assumed to be a member of the class.  */
5745     ctx = current_scope ();
5746 
5747   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
5748     ctx = NULL_TREE;
5749 
5750   if (!DECL_CONTEXT (decl))
5751     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5752 
5753   /* See if this is a primary template.  */
5754   bool is_primary = false;
5755   if (is_friend && ctx
5756       && uses_template_parms_level (ctx, processing_template_decl))
5757     /* A friend template that specifies a class context, i.e.
5758          template <typename T> friend void A<T>::f();
5759        is not primary.  */
5760     ;
5761   else if (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5762     /* Lambdas are not primary.  */
5763     ;
5764   else
5765     is_primary = template_parm_scope_p ();
5766 
5767   /* True if the template is a member template, in the sense of
5768      [temp.mem].  */
5769   bool member_template_p = false;
5770 
5771   if (is_primary)
5772     {
5773       warning (OPT_Wtemplates, "template %qD declared", decl);
5774 
5775       if (DECL_CLASS_SCOPE_P (decl))
5776 	member_template_p = true;
5777 
5778       if (TREE_CODE (decl) == TYPE_DECL
5779 	  && IDENTIFIER_ANON_P (DECL_NAME (decl)))
5780 	{
5781 	  error ("template class without a name");
5782 	  return error_mark_node;
5783 	}
5784       else if (TREE_CODE (decl) == FUNCTION_DECL)
5785 	{
5786 	  if (member_template_p)
5787 	    {
5788 	      if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
5789 		error ("member template %qD may not have virt-specifiers", decl);
5790 	    }
5791 	  if (DECL_DESTRUCTOR_P (decl))
5792 	    {
5793 	      /* [temp.mem]
5794 
5795 		 A destructor shall not be a member template.  */
5796 	      error_at (DECL_SOURCE_LOCATION (decl),
5797 			"destructor %qD declared as member template", decl);
5798 	      return error_mark_node;
5799 	    }
5800 	  if (IDENTIFIER_NEWDEL_OP_P (DECL_NAME (decl))
5801 	      && (!prototype_p (TREE_TYPE (decl))
5802 		  || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
5803 		  || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5804 		  || (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5805 		      == void_list_node)))
5806 	    {
5807 	      /* [basic.stc.dynamic.allocation]
5808 
5809 		 An allocation function can be a function
5810 		 template. ... Template allocation functions shall
5811 		 have two or more parameters.  */
5812 	      error ("invalid template declaration of %qD", decl);
5813 	      return error_mark_node;
5814 	    }
5815 	}
5816       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5817 	       && CLASS_TYPE_P (TREE_TYPE (decl)))
5818 	{
5819 	  /* Class template, set TEMPLATE_TYPE_PARM_FOR_CLASS.  */
5820 	  tree parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
5821 	  for (int i = 0; i < TREE_VEC_LENGTH (parms); ++i)
5822 	    {
5823 	      tree t = TREE_VALUE (TREE_VEC_ELT (parms, i));
5824 	      if (TREE_CODE (t) == TYPE_DECL)
5825 		t = TREE_TYPE (t);
5826 	      if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
5827 		TEMPLATE_TYPE_PARM_FOR_CLASS (t) = true;
5828 	    }
5829 	}
5830       else if (TREE_CODE (decl) == TYPE_DECL
5831 	       && TYPE_DECL_ALIAS_P (decl))
5832 	/* alias-declaration */
5833 	gcc_assert (!DECL_ARTIFICIAL (decl));
5834       else if (VAR_P (decl))
5835 	/* C++14 variable template. */;
5836       else if (TREE_CODE (decl) == CONCEPT_DECL)
5837 	/* C++20 concept definitions.  */;
5838       else
5839 	{
5840 	  error ("template declaration of %q#D", decl);
5841 	  return error_mark_node;
5842 	}
5843     }
5844 
5845   bool local_p = (!DECL_IMPLICIT_TYPEDEF_P (decl)
5846 		  && ((ctx && TREE_CODE (ctx) == FUNCTION_DECL)
5847 		      || (VAR_OR_FUNCTION_DECL_P (decl)
5848 			  && DECL_LOCAL_DECL_P (decl))));
5849 
5850   /* Check to see that the rules regarding the use of default
5851      arguments are not being violated.  We check args for a friend
5852      functions when we know whether it's a definition, introducing
5853      declaration or re-declaration.  */
5854   if (!local_p && (!is_friend || TREE_CODE (decl) != FUNCTION_DECL))
5855     check_default_tmpl_args (decl, current_template_parms,
5856 			     is_primary, is_partial, is_friend);
5857 
5858   /* Ensure that there are no parameter packs in the type of this
5859      declaration that have not been expanded.  */
5860   if (TREE_CODE (decl) == FUNCTION_DECL)
5861     {
5862       /* Check each of the arguments individually to see if there are
5863          any bare parameter packs.  */
5864       tree type = TREE_TYPE (decl);
5865       tree arg = DECL_ARGUMENTS (decl);
5866       tree argtype = TYPE_ARG_TYPES (type);
5867 
5868       while (arg && argtype)
5869         {
5870           if (!DECL_PACK_P (arg)
5871               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
5872             {
5873             /* This is a PARM_DECL that contains unexpanded parameter
5874                packs. We have already complained about this in the
5875                check_for_bare_parameter_packs call, so just replace
5876                these types with ERROR_MARK_NODE.  */
5877               TREE_TYPE (arg) = error_mark_node;
5878               TREE_VALUE (argtype) = error_mark_node;
5879             }
5880 
5881           arg = DECL_CHAIN (arg);
5882           argtype = TREE_CHAIN (argtype);
5883         }
5884 
5885       /* Check for bare parameter packs in the return type and the
5886          exception specifiers.  */
5887       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
5888 	/* Errors were already issued, set return type to int
5889 	   as the frontend doesn't expect error_mark_node as
5890 	   the return type.  */
5891 	TREE_TYPE (type) = integer_type_node;
5892       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
5893 	TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
5894     }
5895   else if (check_for_bare_parameter_packs (is_typedef_decl (decl)
5896 					   ? DECL_ORIGINAL_TYPE (decl)
5897 					   : TREE_TYPE (decl)))
5898     {
5899       TREE_TYPE (decl) = error_mark_node;
5900       return error_mark_node;
5901     }
5902 
5903   if (is_partial)
5904     return process_partial_specialization (decl);
5905 
5906   tree args = current_template_args ();
5907   tree tmpl = NULL_TREE;
5908   bool new_template_p = false;
5909   if (local_p)
5910     {
5911       /* Does not get a template head.  */
5912       tmpl = NULL_TREE;
5913       gcc_checking_assert (!is_primary);
5914     }
5915   else if (!ctx
5916 	   || TREE_CODE (ctx) == FUNCTION_DECL
5917 	   || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
5918 	   || (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5919 	   || (is_friend && !(DECL_LANG_SPECIFIC (decl)
5920 			      && DECL_TEMPLATE_INFO (decl))))
5921     {
5922       if (DECL_LANG_SPECIFIC (decl)
5923 	  && DECL_TEMPLATE_INFO (decl)
5924 	  && DECL_TI_TEMPLATE (decl))
5925 	tmpl = DECL_TI_TEMPLATE (decl);
5926       /* If DECL is a TYPE_DECL for a class-template, then there won't
5927 	 be DECL_LANG_SPECIFIC.  The information equivalent to
5928 	 DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
5929       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5930 	       && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
5931 	       && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
5932 	{
5933 	  /* Since a template declaration already existed for this
5934 	     class-type, we must be redeclaring it here.  Make sure
5935 	     that the redeclaration is valid.  */
5936 	  redeclare_class_template (TREE_TYPE (decl),
5937 				    current_template_parms,
5938 				    current_template_constraints ());
5939 	  /* We don't need to create a new TEMPLATE_DECL; just use the
5940 	     one we already had.  */
5941 	  tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
5942 	}
5943       else
5944 	{
5945 	  tmpl = build_template_decl (decl, current_template_parms,
5946 				      member_template_p);
5947 	  new_template_p = true;
5948 
5949 	  if (DECL_LANG_SPECIFIC (decl)
5950 	      && DECL_TEMPLATE_SPECIALIZATION (decl))
5951 	    {
5952 	      /* A specialization of a member template of a template
5953 		 class.  */
5954 	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5955 	      DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
5956 	      DECL_TEMPLATE_INFO (decl) = NULL_TREE;
5957 	    }
5958 	}
5959     }
5960   else
5961     {
5962       tree a, t, current, parms;
5963       int i;
5964       tree tinfo = get_template_info (decl);
5965 
5966       if (!tinfo)
5967 	{
5968 	  error ("template definition of non-template %q#D", decl);
5969 	  return error_mark_node;
5970 	}
5971 
5972       tmpl = TI_TEMPLATE (tinfo);
5973 
5974       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
5975 	  && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
5976 	  && DECL_TEMPLATE_SPECIALIZATION (decl)
5977 	  && DECL_MEMBER_TEMPLATE_P (tmpl))
5978 	{
5979 	  /* The declaration is a specialization of a member
5980 	     template, declared outside the class.  Therefore, the
5981 	     innermost template arguments will be NULL, so we
5982 	     replace them with the arguments determined by the
5983 	     earlier call to check_explicit_specialization.  */
5984 	  args = DECL_TI_ARGS (decl);
5985 
5986 	  tree new_tmpl
5987 	    = build_template_decl (decl, current_template_parms,
5988 				   member_template_p);
5989 	  DECL_TI_TEMPLATE (decl) = new_tmpl;
5990 	  SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
5991 	  DECL_TEMPLATE_INFO (new_tmpl)
5992 	    = build_template_info (tmpl, args);
5993 
5994 	  register_specialization (new_tmpl,
5995 				   most_general_template (tmpl),
5996 				   args,
5997 				   is_friend, 0);
5998 	  return decl;
5999 	}
6000 
6001       /* Make sure the template headers we got make sense.  */
6002 
6003       parms = DECL_TEMPLATE_PARMS (tmpl);
6004       i = TMPL_PARMS_DEPTH (parms);
6005       if (TMPL_ARGS_DEPTH (args) != i)
6006 	{
6007 	  error ("expected %d levels of template parms for %q#D, got %d",
6008 		 i, decl, TMPL_ARGS_DEPTH (args));
6009 	  DECL_INTERFACE_KNOWN (decl) = 1;
6010 	  return error_mark_node;
6011 	}
6012       else
6013 	for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
6014 	  {
6015 	    a = TMPL_ARGS_LEVEL (args, i);
6016 	    t = INNERMOST_TEMPLATE_PARMS (parms);
6017 
6018 	    if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
6019 	      {
6020 		if (current == decl)
6021 		  error ("got %d template parameters for %q#D",
6022 			 TREE_VEC_LENGTH (a), decl);
6023 		else
6024 		  error ("got %d template parameters for %q#T",
6025 			 TREE_VEC_LENGTH (a), current);
6026 		error ("  but %d required", TREE_VEC_LENGTH (t));
6027 		/* Avoid crash in import_export_decl.  */
6028 		DECL_INTERFACE_KNOWN (decl) = 1;
6029 		return error_mark_node;
6030 	      }
6031 
6032 	    if (current == decl)
6033 	      current = ctx;
6034 	    else if (current == NULL_TREE)
6035 	      /* Can happen in erroneous input.  */
6036 	      break;
6037 	    else
6038 	      current = get_containing_scope (current);
6039 	  }
6040 
6041       /* Check that the parms are used in the appropriate qualifying scopes
6042 	 in the declarator.  */
6043       if (!comp_template_args
6044 	  (TI_ARGS (tinfo),
6045 	   TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
6046 	{
6047 	  error ("template arguments to %qD do not match original "
6048 		 "template %qD", decl, DECL_TEMPLATE_RESULT (tmpl));
6049 	  if (!uses_template_parms (TI_ARGS (tinfo)))
6050 	    inform (input_location, "use %<template<>%> for"
6051 		    " an explicit specialization");
6052 	  /* Avoid crash in import_export_decl.  */
6053 	  DECL_INTERFACE_KNOWN (decl) = 1;
6054 	  return error_mark_node;
6055 	}
6056     }
6057 
6058   gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
6059 
6060   if (new_template_p)
6061     {
6062       /* Push template declarations for global functions and types.
6063 	 Note that we do not try to push a global template friend
6064 	 declared in a template class; such a thing may well depend on
6065 	 the template parameters of the class and we'll push it when
6066 	 instantiating the befriending class.  */
6067       if (!ctx
6068 	  && !(is_friend && template_class_depth (current_class_type) > 0))
6069 	{
6070 	  tree pushed = pushdecl_namespace_level (tmpl, /*hiding=*/is_friend);
6071 	  if (pushed == error_mark_node)
6072 	    return error_mark_node;
6073 
6074 	  /* pushdecl may have found an existing template.  */
6075 	  if (pushed != tmpl)
6076 	    {
6077 	      decl = DECL_TEMPLATE_RESULT (pushed);
6078 	      tmpl = NULL_TREE;
6079 	    }
6080 	}
6081       else if (is_friend)
6082 	{
6083 	  /* Record this decl as belonging to the current class.  It's
6084 	     not chained onto anything else.  */
6085 	  DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (tmpl) = true;
6086 	  gcc_checking_assert (!DECL_CHAIN (tmpl));
6087 	  DECL_CHAIN (tmpl) = current_scope ();
6088 	}
6089     }
6090   else if (tmpl)
6091     /* The type may have been completed, or (erroneously) changed.  */
6092     TREE_TYPE (tmpl) = TREE_TYPE (decl);
6093 
6094   if (tmpl)
6095     {
6096       if (is_primary)
6097 	{
6098 	  tree parms = DECL_TEMPLATE_PARMS (tmpl);
6099 
6100 	  DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6101 
6102 	  /* Give template template parms a DECL_CONTEXT of the template
6103 	     for which they are a parameter.  */
6104 	  parms = INNERMOST_TEMPLATE_PARMS (parms);
6105 	  for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
6106 	    {
6107 	      tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6108 	      if (TREE_CODE (parm) == TEMPLATE_DECL)
6109 		DECL_CONTEXT (parm) = tmpl;
6110 	    }
6111 
6112 	  if (TREE_CODE (decl) == TYPE_DECL
6113 	      && TYPE_DECL_ALIAS_P (decl))
6114 	    {
6115 	      if (tree constr
6116 		  = TEMPLATE_PARMS_CONSTRAINTS (DECL_TEMPLATE_PARMS (tmpl)))
6117 		{
6118 		  /* ??? Why don't we do this here for all templates?  */
6119 		  constr = build_constraints (constr, NULL_TREE);
6120 		  set_constraints (decl, constr);
6121 		}
6122 	      if (complex_alias_template_p (tmpl))
6123 		TEMPLATE_DECL_COMPLEX_ALIAS_P (tmpl) = true;
6124 	    }
6125 	}
6126 
6127       /* The DECL_TI_ARGS of DECL contains full set of arguments
6128 	 referring wback to its most general template.  If TMPL is a
6129 	 specialization, ARGS may only have the innermost set of
6130 	 arguments.  Add the missing argument levels if necessary.  */
6131       if (DECL_TEMPLATE_INFO (tmpl))
6132 	args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
6133 
6134       tree info = build_template_info (tmpl, args);
6135 
6136       if (DECL_IMPLICIT_TYPEDEF_P (decl))
6137 	SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
6138       else
6139 	{
6140 	  retrofit_lang_decl (decl);
6141 	  DECL_TEMPLATE_INFO (decl) = info;
6142 	}
6143     }
6144 
6145   if (flag_implicit_templates
6146       && !is_friend
6147       && TREE_PUBLIC (decl)
6148       && VAR_OR_FUNCTION_DECL_P (decl))
6149     /* Set DECL_COMDAT on template instantiations; if we force
6150        them to be emitted by explicit instantiation,
6151        mark_needed will tell cgraph to do the right thing.  */
6152     DECL_COMDAT (decl) = true;
6153 
6154   gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
6155 
6156   return decl;
6157 }
6158 
6159 /* FN is an inheriting constructor that inherits from the constructor
6160    template INHERITED; turn FN into a constructor template with a matching
6161    template header.  */
6162 
6163 tree
add_inherited_template_parms(tree fn,tree inherited)6164 add_inherited_template_parms (tree fn, tree inherited)
6165 {
6166   tree inner_parms
6167     = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
6168   inner_parms = copy_node (inner_parms);
6169   tree parms
6170     = tree_cons (size_int (processing_template_decl + 1),
6171 		 inner_parms, current_template_parms);
6172   tree tmpl = build_template_decl (fn, parms, /*member*/true);
6173   tree args = template_parms_to_args (parms);
6174   DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
6175   DECL_ARTIFICIAL (tmpl) = true;
6176   DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6177   return tmpl;
6178 }
6179 
6180 /* Called when a class template TYPE is redeclared with the indicated
6181    template PARMS, e.g.:
6182 
6183      template <class T> struct S;
6184      template <class T> struct S {};  */
6185 
6186 bool
redeclare_class_template(tree type,tree parms,tree cons)6187 redeclare_class_template (tree type, tree parms, tree cons)
6188 {
6189   tree tmpl;
6190   tree tmpl_parms;
6191   int i;
6192 
6193   if (!TYPE_TEMPLATE_INFO (type))
6194     {
6195       error ("%qT is not a template type", type);
6196       return false;
6197     }
6198 
6199   tmpl = TYPE_TI_TEMPLATE (type);
6200   if (!PRIMARY_TEMPLATE_P (tmpl))
6201     /* The type is nested in some template class.  Nothing to worry
6202        about here; there are no new template parameters for the nested
6203        type.  */
6204     return true;
6205 
6206   if (!parms)
6207     {
6208       error ("template specifiers not specified in declaration of %qD",
6209 	     tmpl);
6210       return false;
6211     }
6212 
6213   parms = INNERMOST_TEMPLATE_PARMS (parms);
6214   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
6215 
6216   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
6217     {
6218       error_n (input_location, TREE_VEC_LENGTH (parms),
6219                "redeclared with %d template parameter",
6220                "redeclared with %d template parameters",
6221                TREE_VEC_LENGTH (parms));
6222       inform_n (DECL_SOURCE_LOCATION (tmpl), TREE_VEC_LENGTH (tmpl_parms),
6223                 "previous declaration %qD used %d template parameter",
6224                 "previous declaration %qD used %d template parameters",
6225                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
6226       return false;
6227     }
6228 
6229   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
6230     {
6231       tree tmpl_parm;
6232       tree parm;
6233       tree tmpl_default;
6234       tree parm_default;
6235 
6236       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
6237           || TREE_VEC_ELT (parms, i) == error_mark_node)
6238         continue;
6239 
6240       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
6241       if (error_operand_p (tmpl_parm))
6242 	return false;
6243 
6244       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6245       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
6246       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
6247 
6248       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
6249 	 TEMPLATE_DECL.  */
6250       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
6251 	  || (TREE_CODE (tmpl_parm) != TYPE_DECL
6252 	      && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
6253 	  || (TREE_CODE (tmpl_parm) != PARM_DECL
6254 	      && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
6255 		  != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
6256 	  || (TREE_CODE (tmpl_parm) == PARM_DECL
6257 	      && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
6258 		  != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
6259 	{
6260 	  auto_diagnostic_group d;
6261 	  error ("template parameter %q+#D", tmpl_parm);
6262 	  inform (input_location, "redeclared here as %q#D", parm);
6263 	  return false;
6264 	}
6265 
6266       /* The parameters can be declared to introduce different
6267 	 constraints.  */
6268       tree p1 = TREE_VEC_ELT (tmpl_parms, i);
6269       tree p2 = TREE_VEC_ELT (parms, i);
6270       if (!template_parameter_constraints_equivalent_p (p1, p2))
6271 	{
6272 	  auto_diagnostic_group d;
6273 	  error ("declaration of template parameter %q+#D with different "
6274 		 "constraints", parm);
6275 	  inform (DECL_SOURCE_LOCATION (tmpl_parm),
6276 		  "original declaration appeared here");
6277 	  return false;
6278 	}
6279 
6280       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
6281 	{
6282 	  /* We have in [temp.param]:
6283 
6284 	     A template-parameter may not be given default arguments
6285 	     by two different declarations in the same scope.  */
6286 	  auto_diagnostic_group d;
6287 	  error_at (input_location, "redefinition of default argument for %q#D", parm);
6288 	  inform (DECL_SOURCE_LOCATION (tmpl_parm),
6289 		  "original definition appeared here");
6290 	  return false;
6291 	}
6292 
6293       if (parm_default != NULL_TREE)
6294 	/* Update the previous template parameters (which are the ones
6295 	   that will really count) with the new default value.  */
6296 	TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
6297       else if (tmpl_default != NULL_TREE)
6298 	/* Update the new parameters, too; they'll be used as the
6299 	   parameters for any members.  */
6300 	TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
6301 
6302       /* Give each template template parm in this redeclaration a
6303 	 DECL_CONTEXT of the template for which they are a parameter.  */
6304       if (TREE_CODE (parm) == TEMPLATE_DECL)
6305 	{
6306 	  gcc_assert (DECL_CONTEXT (parm) == NULL_TREE);
6307 	  DECL_CONTEXT (parm) = tmpl;
6308 	}
6309 
6310       if (TREE_CODE (parm) == TYPE_DECL)
6311 	TEMPLATE_TYPE_PARM_FOR_CLASS (TREE_TYPE (parm)) = true;
6312     }
6313 
6314   tree ci = get_constraints (tmpl);
6315   tree req1 = ci ? CI_TEMPLATE_REQS (ci) : NULL_TREE;
6316   tree req2 = cons ? CI_TEMPLATE_REQS (cons) : NULL_TREE;
6317 
6318   /* Two classes with different constraints declare different entities.  */
6319   if (!cp_tree_equal (req1, req2))
6320     {
6321       auto_diagnostic_group d;
6322       error_at (input_location, "redeclaration %q#D with different "
6323                                 "constraints", tmpl);
6324       inform (DECL_SOURCE_LOCATION (tmpl),
6325               "original declaration appeared here");
6326       return false;
6327     }
6328 
6329     return true;
6330 }
6331 
6332 /* The actual substitution part of instantiate_non_dependent_expr_sfinae,
6333    to be used when the caller has already checked
6334    (processing_template_decl
6335     && !instantiation_dependent_expression_p (expr)
6336     && potential_constant_expression (expr))
6337    and cleared processing_template_decl.  */
6338 
6339 tree
instantiate_non_dependent_expr_internal(tree expr,tsubst_flags_t complain)6340 instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
6341 {
6342   return tsubst_copy_and_build (expr,
6343 				/*args=*/NULL_TREE,
6344 				complain,
6345 				/*in_decl=*/NULL_TREE,
6346 				/*function_p=*/false,
6347 				/*integral_constant_expression_p=*/true);
6348 }
6349 
6350 /* Simplify EXPR if it is a non-dependent expression.  Returns the
6351    (possibly simplified) expression.  */
6352 
6353 tree
instantiate_non_dependent_expr_sfinae(tree expr,tsubst_flags_t complain)6354 instantiate_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
6355 {
6356   if (expr == NULL_TREE)
6357     return NULL_TREE;
6358 
6359   /* If we're in a template, but EXPR isn't value dependent, simplify
6360      it.  We're supposed to treat:
6361 
6362        template <typename T> void f(T[1 + 1]);
6363        template <typename T> void f(T[2]);
6364 
6365      as two declarations of the same function, for example.  */
6366   if (processing_template_decl
6367       && is_nondependent_constant_expression (expr))
6368     {
6369       processing_template_decl_sentinel s;
6370       expr = instantiate_non_dependent_expr_internal (expr, complain);
6371     }
6372   return expr;
6373 }
6374 
6375 tree
instantiate_non_dependent_expr(tree expr)6376 instantiate_non_dependent_expr (tree expr)
6377 {
6378   return instantiate_non_dependent_expr_sfinae (expr, tf_error);
6379 }
6380 
6381 /* Like instantiate_non_dependent_expr, but return NULL_TREE rather than
6382    an uninstantiated expression.  */
6383 
6384 tree
instantiate_non_dependent_or_null(tree expr)6385 instantiate_non_dependent_or_null (tree expr)
6386 {
6387   if (expr == NULL_TREE)
6388     return NULL_TREE;
6389   if (processing_template_decl)
6390     {
6391       if (!is_nondependent_constant_expression (expr))
6392 	expr = NULL_TREE;
6393       else
6394 	{
6395 	  processing_template_decl_sentinel s;
6396 	  expr = instantiate_non_dependent_expr_internal (expr, tf_error);
6397 	}
6398     }
6399   return expr;
6400 }
6401 
6402 /* True iff T is a specialization of a variable template.  */
6403 
6404 bool
variable_template_specialization_p(tree t)6405 variable_template_specialization_p (tree t)
6406 {
6407   if (!VAR_P (t) || !DECL_LANG_SPECIFIC (t) || !DECL_TEMPLATE_INFO (t))
6408     return false;
6409   tree tmpl = DECL_TI_TEMPLATE (t);
6410   return variable_template_p (tmpl);
6411 }
6412 
6413 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
6414    template declaration, or a TYPE_DECL for an alias declaration.  */
6415 
6416 bool
alias_type_or_template_p(tree t)6417 alias_type_or_template_p (tree t)
6418 {
6419   if (t == NULL_TREE)
6420     return false;
6421   return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
6422 	  || (TYPE_P (t)
6423 	      && TYPE_NAME (t)
6424 	      && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
6425 	  || DECL_ALIAS_TEMPLATE_P (t));
6426 }
6427 
6428 /* If T is a specialization of an alias template, return it; otherwise return
6429    NULL_TREE.  If TRANSPARENT_TYPEDEFS is true, look through other aliases.  */
6430 
6431 tree
alias_template_specialization_p(const_tree t,bool transparent_typedefs)6432 alias_template_specialization_p (const_tree t,
6433 				 bool transparent_typedefs)
6434 {
6435   if (!TYPE_P (t))
6436     return NULL_TREE;
6437 
6438   /* It's an alias template specialization if it's an alias and its
6439      TYPE_NAME is a specialization of a primary template.  */
6440   if (typedef_variant_p (t))
6441     {
6442       if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
6443 	if (PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo)))
6444 	  return CONST_CAST_TREE (t);
6445       if (transparent_typedefs)
6446 	return alias_template_specialization_p (DECL_ORIGINAL_TYPE
6447 						(TYPE_NAME (t)),
6448 						transparent_typedefs);
6449     }
6450 
6451   return NULL_TREE;
6452 }
6453 
6454 /* An alias template is complex from a SFINAE perspective if a template-id
6455    using that alias can be ill-formed when the expansion is not, as with
6456    the void_t template.  We determine this by checking whether the
6457    expansion for the alias template uses all its template parameters.  */
6458 
6459 struct uses_all_template_parms_data
6460 {
6461   int level;
6462   bool *seen;
6463 };
6464 
6465 static int
uses_all_template_parms_r(tree t,void * data_)6466 uses_all_template_parms_r (tree t, void *data_)
6467 {
6468   struct uses_all_template_parms_data &data
6469     = *(struct uses_all_template_parms_data*)data_;
6470   tree idx = get_template_parm_index (t);
6471 
6472   if (TEMPLATE_PARM_LEVEL (idx) == data.level)
6473     data.seen[TEMPLATE_PARM_IDX (idx)] = true;
6474   return 0;
6475 }
6476 
6477 /* for_each_template_parm any_fn callback for complex_alias_template_p.  */
6478 
6479 static int
complex_pack_expansion_r(tree t,void * data_)6480 complex_pack_expansion_r (tree t, void *data_)
6481 {
6482   /* An alias template with a pack expansion that expands a pack from the
6483      enclosing class needs to be considered complex, to avoid confusion with
6484      the same pack being used as an argument to the alias's own template
6485      parameter (91966).  */
6486   if (!PACK_EXPANSION_P (t))
6487     return 0;
6488   struct uses_all_template_parms_data &data
6489     = *(struct uses_all_template_parms_data*)data_;
6490   for (tree pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
6491        pack = TREE_CHAIN (pack))
6492     {
6493       tree parm_pack = TREE_VALUE (pack);
6494       if (!TEMPLATE_PARM_P (parm_pack))
6495 	continue;
6496       int idx, level;
6497       template_parm_level_and_index (parm_pack, &level, &idx);
6498       if (level < data.level)
6499 	return 1;
6500     }
6501   return 0;
6502 }
6503 
6504 static bool
complex_alias_template_p(const_tree tmpl)6505 complex_alias_template_p (const_tree tmpl)
6506 {
6507   /* A renaming alias isn't complex.  */
6508   if (get_underlying_template (CONST_CAST_TREE (tmpl)) != tmpl)
6509     return false;
6510 
6511   /* Any other constrained alias is complex.  */
6512   if (get_constraints (tmpl))
6513     return true;
6514 
6515   struct uses_all_template_parms_data data;
6516   tree pat = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6517   tree parms = DECL_TEMPLATE_PARMS (tmpl);
6518   data.level = TMPL_PARMS_DEPTH (parms);
6519   int len = TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS (parms));
6520   data.seen = XALLOCAVEC (bool, len);
6521   for (int i = 0; i < len; ++i)
6522     data.seen[i] = false;
6523 
6524   if (for_each_template_parm (pat, uses_all_template_parms_r, &data,
6525 			      NULL, true, complex_pack_expansion_r))
6526     return true;
6527   for (int i = 0; i < len; ++i)
6528     if (!data.seen[i])
6529       return true;
6530   return false;
6531 }
6532 
6533 /* If T is a specialization of a complex alias template with dependent
6534    template-arguments, return it; otherwise return NULL_TREE.  If T is a
6535    typedef to such a specialization, return the specialization.  */
6536 
6537 tree
dependent_alias_template_spec_p(const_tree t,bool transparent_typedefs)6538 dependent_alias_template_spec_p (const_tree t, bool transparent_typedefs)
6539 {
6540   if (t == error_mark_node)
6541     return NULL_TREE;
6542   gcc_assert (TYPE_P (t));
6543 
6544   if (!typedef_variant_p (t))
6545     return NULL_TREE;
6546 
6547   tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t);
6548   if (tinfo
6549       && TEMPLATE_DECL_COMPLEX_ALIAS_P (TI_TEMPLATE (tinfo))
6550       && (any_dependent_template_arguments_p
6551 	  (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)))))
6552     return CONST_CAST_TREE (t);
6553 
6554   if (transparent_typedefs)
6555     {
6556       tree utype = DECL_ORIGINAL_TYPE (TYPE_NAME (t));
6557       return dependent_alias_template_spec_p (utype, transparent_typedefs);
6558     }
6559 
6560   return NULL_TREE;
6561 }
6562 
6563 /* Return the number of innermost template parameters in TMPL.  */
6564 
6565 static int
num_innermost_template_parms(const_tree tmpl)6566 num_innermost_template_parms (const_tree tmpl)
6567 {
6568   tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6569   return TREE_VEC_LENGTH (parms);
6570 }
6571 
6572 /* Return either TMPL or another template that it is equivalent to under DR
6573    1286: An alias that just changes the name of a template is equivalent to
6574    the other template.  */
6575 
6576 static tree
get_underlying_template(tree tmpl)6577 get_underlying_template (tree tmpl)
6578 {
6579   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
6580   while (DECL_ALIAS_TEMPLATE_P (tmpl))
6581     {
6582       /* Determine if the alias is equivalent to an underlying template.  */
6583       tree orig_type = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6584       /* The underlying type may have been ill-formed. Don't proceed.  */
6585       if (!orig_type)
6586 	break;
6587       tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (orig_type);
6588       if (!tinfo)
6589 	break;
6590 
6591       tree underlying = TI_TEMPLATE (tinfo);
6592       if (!PRIMARY_TEMPLATE_P (underlying)
6593 	  || (num_innermost_template_parms (tmpl)
6594 	      != num_innermost_template_parms (underlying)))
6595 	break;
6596 
6597       /* Does the alias add cv-quals?  */
6598       if (TYPE_QUALS (TREE_TYPE (underlying)) != TYPE_QUALS (TREE_TYPE (tmpl)))
6599 	break;
6600 
6601       tree alias_args = INNERMOST_TEMPLATE_ARGS (generic_targs_for (tmpl));
6602       if (!comp_template_args (TI_ARGS (tinfo), alias_args))
6603 	break;
6604 
6605       /* If TMPL adds or changes any constraints, it isn't equivalent.  I think
6606 	 it's appropriate to treat a less-constrained alias as equivalent.  */
6607       if (!at_least_as_constrained (underlying, tmpl))
6608 	break;
6609 
6610       /* Alias is equivalent.  Strip it and repeat.  */
6611       tmpl = underlying;
6612     }
6613 
6614   return tmpl;
6615 }
6616 
6617 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
6618    must be a reference-to-function or a pointer-to-function type, as specified
6619    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
6620    and check that the resulting function has external linkage.  */
6621 
6622 static tree
convert_nontype_argument_function(tree type,tree expr,tsubst_flags_t complain)6623 convert_nontype_argument_function (tree type, tree expr,
6624 				   tsubst_flags_t complain)
6625 {
6626   tree fns = expr;
6627   tree fn, fn_no_ptr;
6628   linkage_kind linkage;
6629 
6630   fn = instantiate_type (type, fns, tf_none);
6631   if (fn == error_mark_node)
6632     return error_mark_node;
6633 
6634   if (value_dependent_expression_p (fn))
6635     goto accept;
6636 
6637   fn_no_ptr = fn;
6638   if (REFERENCE_REF_P (fn_no_ptr))
6639     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6640   fn_no_ptr = strip_fnptr_conv (fn_no_ptr);
6641   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
6642     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6643   if (BASELINK_P (fn_no_ptr))
6644     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
6645 
6646   /* [temp.arg.nontype]/1
6647 
6648      A template-argument for a non-type, non-template template-parameter
6649      shall be one of:
6650      [...]
6651      -- the address of an object or function with external [C++11: or
6652         internal] linkage.  */
6653 
6654   STRIP_ANY_LOCATION_WRAPPER (fn_no_ptr);
6655   if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
6656     {
6657       if (complain & tf_error)
6658 	{
6659 	  location_t loc = cp_expr_loc_or_input_loc (expr);
6660 	  error_at (loc, "%qE is not a valid template argument for type %qT",
6661 		    expr, type);
6662 	  if (TYPE_PTR_P (type))
6663 	    inform (loc, "it must be the address of a function "
6664 		    "with external linkage");
6665 	  else
6666 	    inform (loc, "it must be the name of a function with "
6667 		    "external linkage");
6668 	}
6669       return NULL_TREE;
6670     }
6671 
6672   linkage = decl_linkage (fn_no_ptr);
6673   if (cxx_dialect >= cxx11 ? linkage == lk_none : linkage != lk_external)
6674     {
6675       if (complain & tf_error)
6676 	{
6677 	  location_t loc = cp_expr_loc_or_input_loc (expr);
6678 	  if (cxx_dialect >= cxx11)
6679 	    error_at (loc, "%qE is not a valid template argument for type "
6680 		      "%qT because %qD has no linkage",
6681 		      expr, type, fn_no_ptr);
6682 	  else
6683 	    error_at (loc, "%qE is not a valid template argument for type "
6684 		      "%qT because %qD does not have external linkage",
6685 		      expr, type, fn_no_ptr);
6686 	}
6687       return NULL_TREE;
6688     }
6689 
6690  accept:
6691   if (TYPE_REF_P (type))
6692     {
6693       if (REFERENCE_REF_P (fn))
6694 	fn = TREE_OPERAND (fn, 0);
6695       else
6696 	fn = build_address (fn);
6697     }
6698   if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (fn)))
6699     fn = build_nop (type, fn);
6700 
6701   return fn;
6702 }
6703 
6704 /* Subroutine of convert_nontype_argument.
6705    Check if EXPR of type TYPE is a valid pointer-to-member constant.
6706    Emit an error otherwise.  */
6707 
6708 static bool
check_valid_ptrmem_cst_expr(tree type,tree expr,tsubst_flags_t complain)6709 check_valid_ptrmem_cst_expr (tree type, tree expr,
6710 			     tsubst_flags_t complain)
6711 {
6712   tree orig_expr = expr;
6713   STRIP_NOPS (expr);
6714   if (null_ptr_cst_p (expr))
6715     return true;
6716   if (TREE_CODE (expr) == PTRMEM_CST
6717       && same_type_p (TYPE_PTRMEM_CLASS_TYPE (type),
6718 		      PTRMEM_CST_CLASS (expr)))
6719     return true;
6720   if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
6721     return true;
6722   if (processing_template_decl
6723       && TREE_CODE (expr) == ADDR_EXPR
6724       && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
6725     return true;
6726   if (complain & tf_error)
6727     {
6728       location_t loc = cp_expr_loc_or_input_loc (orig_expr);
6729       error_at (loc, "%qE is not a valid template argument for type %qT",
6730 		orig_expr, type);
6731       if (TREE_CODE (expr) != PTRMEM_CST)
6732 	inform (loc, "it must be a pointer-to-member of the form %<&X::Y%>");
6733       else
6734 	inform (loc, "because it is a member of %qT", PTRMEM_CST_CLASS (expr));
6735     }
6736   return false;
6737 }
6738 
6739 /* Returns TRUE iff the address of OP is value-dependent.
6740 
6741    14.6.2.4 [temp.dep.temp]:
6742    A non-integral non-type template-argument is dependent if its type is
6743    dependent or it has either of the following forms
6744      qualified-id
6745      & qualified-id
6746    and contains a nested-name-specifier which specifies a class-name that
6747    names a dependent type.
6748 
6749    We generalize this to just say that the address of a member of a
6750    dependent class is value-dependent; the above doesn't cover the
6751    address of a static data member named with an unqualified-id.  */
6752 
6753 static bool
has_value_dependent_address(tree op)6754 has_value_dependent_address (tree op)
6755 {
6756   STRIP_ANY_LOCATION_WRAPPER (op);
6757 
6758   /* We could use get_inner_reference here, but there's no need;
6759      this is only relevant for template non-type arguments, which
6760      can only be expressed as &id-expression.  */
6761   if (DECL_P (op))
6762     {
6763       tree ctx = CP_DECL_CONTEXT (op);
6764       if (TYPE_P (ctx) && dependent_type_p (ctx))
6765 	return true;
6766     }
6767 
6768   return false;
6769 }
6770 
6771 /* The next set of functions are used for providing helpful explanatory
6772    diagnostics for failed overload resolution.  Their messages should be
6773    indented by two spaces for consistency with the messages in
6774    call.c  */
6775 
6776 static int
unify_success(bool)6777 unify_success (bool /*explain_p*/)
6778 {
6779   return 0;
6780 }
6781 
6782 /* Other failure functions should call this one, to provide a single function
6783    for setting a breakpoint on.  */
6784 
6785 static int
unify_invalid(bool)6786 unify_invalid (bool /*explain_p*/)
6787 {
6788   return 1;
6789 }
6790 
6791 static int
unify_parameter_deduction_failure(bool explain_p,tree parm)6792 unify_parameter_deduction_failure (bool explain_p, tree parm)
6793 {
6794   if (explain_p)
6795     inform (input_location,
6796 	    "  couldn%'t deduce template parameter %qD", parm);
6797   return unify_invalid (explain_p);
6798 }
6799 
6800 static int
unify_cv_qual_mismatch(bool explain_p,tree parm,tree arg)6801 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
6802 {
6803   if (explain_p)
6804     inform (input_location,
6805 	    "  types %qT and %qT have incompatible cv-qualifiers",
6806 	    parm, arg);
6807   return unify_invalid (explain_p);
6808 }
6809 
6810 static int
unify_type_mismatch(bool explain_p,tree parm,tree arg)6811 unify_type_mismatch (bool explain_p, tree parm, tree arg)
6812 {
6813   if (explain_p)
6814     inform (input_location, "  mismatched types %qT and %qT", parm, arg);
6815   return unify_invalid (explain_p);
6816 }
6817 
6818 static int
unify_parameter_pack_mismatch(bool explain_p,tree parm,tree arg)6819 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
6820 {
6821   if (explain_p)
6822     inform (input_location,
6823 	    "  template parameter %qD is not a parameter pack, but "
6824 	    "argument %qD is",
6825 	    parm, arg);
6826   return unify_invalid (explain_p);
6827 }
6828 
6829 static int
unify_ptrmem_cst_mismatch(bool explain_p,tree parm,tree arg)6830 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
6831 {
6832   if (explain_p)
6833     inform (input_location,
6834 	    "  template argument %qE does not match "
6835 	    "pointer-to-member constant %qE",
6836 	    arg, parm);
6837   return unify_invalid (explain_p);
6838 }
6839 
6840 static int
unify_expression_unequal(bool explain_p,tree parm,tree arg)6841 unify_expression_unequal (bool explain_p, tree parm, tree arg)
6842 {
6843   if (explain_p)
6844     inform (input_location, "  %qE is not equivalent to %qE", parm, arg);
6845   return unify_invalid (explain_p);
6846 }
6847 
6848 static int
unify_parameter_pack_inconsistent(bool explain_p,tree old_arg,tree new_arg)6849 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
6850 {
6851   if (explain_p)
6852     inform (input_location,
6853 	    "  inconsistent parameter pack deduction with %qT and %qT",
6854 	    old_arg, new_arg);
6855   return unify_invalid (explain_p);
6856 }
6857 
6858 static int
unify_inconsistency(bool explain_p,tree parm,tree first,tree second)6859 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
6860 {
6861   if (explain_p)
6862     {
6863       if (TYPE_P (parm))
6864 	inform (input_location,
6865 		"  deduced conflicting types for parameter %qT (%qT and %qT)",
6866 		parm, first, second);
6867       else
6868 	inform (input_location,
6869 		"  deduced conflicting values for non-type parameter "
6870 		"%qE (%qE and %qE)", parm, first, second);
6871     }
6872   return unify_invalid (explain_p);
6873 }
6874 
6875 static int
unify_vla_arg(bool explain_p,tree arg)6876 unify_vla_arg (bool explain_p, tree arg)
6877 {
6878   if (explain_p)
6879     inform (input_location,
6880 	    "  variable-sized array type %qT is not "
6881 	    "a valid template argument",
6882 	    arg);
6883   return unify_invalid (explain_p);
6884 }
6885 
6886 static int
unify_method_type_error(bool explain_p,tree arg)6887 unify_method_type_error (bool explain_p, tree arg)
6888 {
6889   if (explain_p)
6890     inform (input_location,
6891 	    "  member function type %qT is not a valid template argument",
6892 	    arg);
6893   return unify_invalid (explain_p);
6894 }
6895 
6896 static int
6897 unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
6898 {
6899   if (explain_p)
6900     {
6901       if (least_p)
6902 	inform_n (input_location, wanted,
6903 		  "  candidate expects at least %d argument, %d provided",
6904 		  "  candidate expects at least %d arguments, %d provided",
6905 		  wanted, have);
6906       else
6907 	inform_n (input_location, wanted,
6908 		  "  candidate expects %d argument, %d provided",
6909 		  "  candidate expects %d arguments, %d provided",
6910 		  wanted, have);
6911     }
6912   return unify_invalid (explain_p);
6913 }
6914 
6915 static int
unify_too_many_arguments(bool explain_p,int have,int wanted)6916 unify_too_many_arguments (bool explain_p, int have, int wanted)
6917 {
6918   return unify_arity (explain_p, have, wanted);
6919 }
6920 
6921 static int
6922 unify_too_few_arguments (bool explain_p, int have, int wanted,
6923 			 bool least_p = false)
6924 {
6925   return unify_arity (explain_p, have, wanted, least_p);
6926 }
6927 
6928 static int
unify_arg_conversion(bool explain_p,tree to_type,tree from_type,tree arg)6929 unify_arg_conversion (bool explain_p, tree to_type,
6930 		      tree from_type, tree arg)
6931 {
6932   if (explain_p)
6933     inform (cp_expr_loc_or_input_loc (arg),
6934 	    "  cannot convert %qE (type %qT) to type %qT",
6935 	    arg, from_type, to_type);
6936   return unify_invalid (explain_p);
6937 }
6938 
6939 static int
unify_no_common_base(bool explain_p,enum template_base_result r,tree parm,tree arg)6940 unify_no_common_base (bool explain_p, enum template_base_result r,
6941 		      tree parm, tree arg)
6942 {
6943   if (explain_p)
6944     switch (r)
6945       {
6946       case tbr_ambiguous_baseclass:
6947 	inform (input_location, "  %qT is an ambiguous base class of %qT",
6948 		parm, arg);
6949 	break;
6950       default:
6951 	inform (input_location, "  %qT is not derived from %qT", arg, parm);
6952 	break;
6953       }
6954   return unify_invalid (explain_p);
6955 }
6956 
6957 static int
unify_inconsistent_template_template_parameters(bool explain_p)6958 unify_inconsistent_template_template_parameters (bool explain_p)
6959 {
6960   if (explain_p)
6961     inform (input_location,
6962 	    "  template parameters of a template template argument are "
6963 	    "inconsistent with other deduced template arguments");
6964   return unify_invalid (explain_p);
6965 }
6966 
6967 static int
unify_template_deduction_failure(bool explain_p,tree parm,tree arg)6968 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
6969 {
6970   if (explain_p)
6971     inform (input_location,
6972 	    "  cannot deduce a template for %qT from non-template type %qT",
6973 	    parm, arg);
6974   return unify_invalid (explain_p);
6975 }
6976 
6977 static int
unify_template_argument_mismatch(bool explain_p,tree parm,tree arg)6978 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
6979 {
6980   if (explain_p)
6981     inform (input_location,
6982 	    "  template argument %qE does not match %qE", arg, parm);
6983   return unify_invalid (explain_p);
6984 }
6985 
6986 /* True if T is a C++20 template parameter object to store the argument for a
6987    template parameter of class type.  */
6988 
6989 bool
template_parm_object_p(const_tree t)6990 template_parm_object_p (const_tree t)
6991 {
6992   return (TREE_CODE (t) == VAR_DECL && DECL_ARTIFICIAL (t) && DECL_NAME (t)
6993 	  && !strncmp (IDENTIFIER_POINTER (DECL_NAME (t)), "_ZTA", 4));
6994 }
6995 
6996 /* Subroutine of convert_nontype_argument, to check whether EXPR, as an
6997    argument for TYPE, points to an unsuitable object.
6998 
6999    Also adjust the type of the index in C++20 array subobject references.  */
7000 
7001 static bool
invalid_tparm_referent_p(tree type,tree expr,tsubst_flags_t complain)7002 invalid_tparm_referent_p (tree type, tree expr, tsubst_flags_t complain)
7003 {
7004   switch (TREE_CODE (expr))
7005     {
7006     CASE_CONVERT:
7007       return invalid_tparm_referent_p (type, TREE_OPERAND (expr, 0),
7008 				       complain);
7009 
7010     case TARGET_EXPR:
7011       return invalid_tparm_referent_p (type, TARGET_EXPR_INITIAL (expr),
7012 				       complain);
7013 
7014     case CONSTRUCTOR:
7015       {
7016 	unsigned i; tree elt;
7017 	FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expr), i, elt)
7018 	  if (invalid_tparm_referent_p (TREE_TYPE (elt), elt, complain))
7019 	    return true;
7020       }
7021       break;
7022 
7023     case ADDR_EXPR:
7024       {
7025 	tree decl = TREE_OPERAND (expr, 0);
7026 
7027 	if (cxx_dialect >= cxx20)
7028 	  while (TREE_CODE (decl) == COMPONENT_REF
7029 		 || TREE_CODE (decl) == ARRAY_REF)
7030 	    {
7031 	      tree &op = TREE_OPERAND (decl, 1);
7032 	      if (TREE_CODE (decl) == ARRAY_REF
7033 		  && TREE_CODE (op) == INTEGER_CST)
7034 		/* Canonicalize array offsets to ptrdiff_t; how they were
7035 		   written doesn't matter for subobject identity.  */
7036 		op = fold_convert (ptrdiff_type_node, op);
7037 	      decl = TREE_OPERAND (decl, 0);
7038 	    }
7039 
7040 	if (!VAR_P (decl))
7041 	  {
7042 	    if (complain & tf_error)
7043 	      error_at (cp_expr_loc_or_input_loc (expr),
7044 			"%qE is not a valid template argument of type %qT "
7045 			"because %qE is not a variable", expr, type, decl);
7046 	    return true;
7047 	  }
7048 	else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
7049 	  {
7050 	    if (complain & tf_error)
7051 	      error_at (cp_expr_loc_or_input_loc (expr),
7052 			"%qE is not a valid template argument of type %qT "
7053 			"in C++98 because %qD does not have external linkage",
7054 			expr, type, decl);
7055 	    return true;
7056 	  }
7057 	else if ((cxx_dialect >= cxx11 && cxx_dialect < cxx17)
7058 		 && decl_linkage (decl) == lk_none)
7059 	  {
7060 	    if (complain & tf_error)
7061 	      error_at (cp_expr_loc_or_input_loc (expr),
7062 			"%qE is not a valid template argument of type %qT "
7063 			"because %qD has no linkage", expr, type, decl);
7064 	    return true;
7065 	  }
7066 	/* C++17: For a non-type template-parameter of reference or pointer
7067 	   type, the value of the constant expression shall not refer to (or
7068 	   for a pointer type, shall not be the address of):
7069 	   * a subobject (4.5),
7070 	   * a temporary object (15.2),
7071 	   * a string literal (5.13.5),
7072 	   * the result of a typeid expression (8.2.8), or
7073 	   * a predefined __func__ variable (11.4.1).  */
7074 	else if (DECL_ARTIFICIAL (decl))
7075 	  {
7076 	    if (complain & tf_error)
7077 	      error ("the address of %qD is not a valid template argument",
7078 		     decl);
7079 	    return true;
7080 	  }
7081 	else if (cxx_dialect < cxx20
7082 		 && !(same_type_ignoring_top_level_qualifiers_p
7083 		      (strip_array_types (TREE_TYPE (type)),
7084 		       strip_array_types (TREE_TYPE (decl)))))
7085 	  {
7086 	    if (complain & tf_error)
7087 	      error ("the address of the %qT subobject of %qD is not a "
7088 		     "valid template argument", TREE_TYPE (type), decl);
7089 	    return true;
7090 	  }
7091 	else if (!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
7092 	  {
7093 	    if (complain & tf_error)
7094 	      error ("the address of %qD is not a valid template argument "
7095 		     "because it does not have static storage duration",
7096 		     decl);
7097 	    return true;
7098 	  }
7099       }
7100       break;
7101 
7102     default:
7103       if (!INDIRECT_TYPE_P (type))
7104 	/* We're only concerned about pointers and references here.  */;
7105       else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7106 	/* Null pointer values are OK in C++11.  */;
7107       else
7108 	{
7109 	  if (VAR_P (expr))
7110 	    {
7111 	      if (complain & tf_error)
7112 		error ("%qD is not a valid template argument "
7113 		       "because %qD is a variable, not the address of "
7114 		       "a variable", expr, expr);
7115 	      return true;
7116 	    }
7117 	  else
7118 	    {
7119 	      if (complain & tf_error)
7120 		error ("%qE is not a valid template argument for %qT "
7121 		       "because it is not the address of a variable",
7122 		       expr, type);
7123 	      return true;
7124 	    }
7125 	}
7126     }
7127   return false;
7128 
7129 }
7130 
7131 /* The template arguments corresponding to template parameter objects of types
7132    that contain pointers to members.  */
7133 
7134 static GTY(()) hash_map<tree, tree> *tparm_obj_values;
7135 
7136 /* Return a VAR_DECL for the C++20 template parameter object corresponding to
7137    template argument EXPR.  */
7138 
7139 static tree
get_template_parm_object(tree expr,tsubst_flags_t complain)7140 get_template_parm_object (tree expr, tsubst_flags_t complain)
7141 {
7142   if (TREE_CODE (expr) == TARGET_EXPR)
7143     expr = TARGET_EXPR_INITIAL (expr);
7144 
7145   if (!TREE_CONSTANT (expr))
7146     {
7147       if ((complain & tf_error)
7148 	  && require_rvalue_constant_expression (expr))
7149 	cxx_constant_value (expr);
7150       return error_mark_node;
7151     }
7152   if (invalid_tparm_referent_p (TREE_TYPE (expr), expr, complain))
7153     return error_mark_node;
7154 
7155   /* This is no longer a compound literal.  */
7156   TREE_HAS_CONSTRUCTOR (expr) = 0;
7157 
7158   tree name = mangle_template_parm_object (expr);
7159   tree decl = get_global_binding (name);
7160   if (decl)
7161     return decl;
7162 
7163   tree type = cp_build_qualified_type (TREE_TYPE (expr), TYPE_QUAL_CONST);
7164   decl = create_temporary_var (type);
7165   DECL_CONTEXT (decl) = NULL_TREE;
7166   TREE_STATIC (decl) = true;
7167   DECL_DECLARED_CONSTEXPR_P (decl) = true;
7168   TREE_READONLY (decl) = true;
7169   DECL_NAME (decl) = name;
7170   SET_DECL_ASSEMBLER_NAME (decl, name);
7171   comdat_linkage (decl);
7172 
7173   if (!zero_init_p (type))
7174     {
7175       /* If EXPR contains any PTRMEM_CST, they will get clobbered by
7176 	 lower_var_init before we're done mangling.  So store the original
7177 	 value elsewhere.  */
7178       tree copy = unshare_constructor (expr);
7179       hash_map_safe_put<hm_ggc> (tparm_obj_values, decl, copy);
7180     }
7181 
7182   pushdecl_top_level_and_finish (decl, expr);
7183 
7184   return decl;
7185 }
7186 
7187 /* Return the actual template argument corresponding to template parameter
7188    object VAR.  */
7189 
7190 tree
tparm_object_argument(tree var)7191 tparm_object_argument (tree var)
7192 {
7193   if (zero_init_p (TREE_TYPE (var)))
7194     return DECL_INITIAL (var);
7195   return *(tparm_obj_values->get (var));
7196 }
7197 
7198 /* Attempt to convert the non-type template parameter EXPR to the
7199    indicated TYPE.  If the conversion is successful, return the
7200    converted value.  If the conversion is unsuccessful, return
7201    NULL_TREE if we issued an error message, or error_mark_node if we
7202    did not.  We issue error messages for out-and-out bad template
7203    parameters, but not simply because the conversion failed, since we
7204    might be just trying to do argument deduction.  Both TYPE and EXPR
7205    must be non-dependent.
7206 
7207    The conversion follows the special rules described in
7208    [temp.arg.nontype], and it is much more strict than an implicit
7209    conversion.
7210 
7211    This function is called twice for each template argument (see
7212    lookup_template_class for a more accurate description of this
7213    problem). This means that we need to handle expressions which
7214    are not valid in a C++ source, but can be created from the
7215    first call (for instance, casts to perform conversions). These
7216    hacks can go away after we fix the double coercion problem.  */
7217 
7218 static tree
convert_nontype_argument(tree type,tree expr,tsubst_flags_t complain)7219 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
7220 {
7221   tree expr_type;
7222   location_t loc = cp_expr_loc_or_input_loc (expr);
7223 
7224   /* Detect immediately string literals as invalid non-type argument.
7225      This special-case is not needed for correctness (we would easily
7226      catch this later), but only to provide better diagnostic for this
7227      common user mistake. As suggested by DR 100, we do not mention
7228      linkage issues in the diagnostic as this is not the point.  */
7229   if (TREE_CODE (expr) == STRING_CST && !CLASS_TYPE_P (type))
7230     {
7231       if (complain & tf_error)
7232 	error ("%qE is not a valid template argument for type %qT "
7233 	       "because string literals can never be used in this context",
7234 	       expr, type);
7235       return NULL_TREE;
7236     }
7237 
7238   /* Add the ADDR_EXPR now for the benefit of
7239      value_dependent_expression_p.  */
7240   if (TYPE_PTROBV_P (type)
7241       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
7242     {
7243       expr = decay_conversion (expr, complain);
7244       if (expr == error_mark_node)
7245 	return error_mark_node;
7246     }
7247 
7248   /* If we are in a template, EXPR may be non-dependent, but still
7249      have a syntactic, rather than semantic, form.  For example, EXPR
7250      might be a SCOPE_REF, rather than the VAR_DECL to which the
7251      SCOPE_REF refers.  Preserving the qualifying scope is necessary
7252      so that access checking can be performed when the template is
7253      instantiated -- but here we need the resolved form so that we can
7254      convert the argument.  */
7255   bool non_dep = false;
7256   if (TYPE_REF_OBJ_P (type)
7257       && has_value_dependent_address (expr))
7258     /* If we want the address and it's value-dependent, don't fold.  */;
7259   else if (processing_template_decl
7260 	   && is_nondependent_constant_expression (expr))
7261     non_dep = true;
7262   if (error_operand_p (expr))
7263     return error_mark_node;
7264   expr_type = TREE_TYPE (expr);
7265 
7266   /* If the argument is non-dependent, perform any conversions in
7267      non-dependent context as well.  */
7268   processing_template_decl_sentinel s (non_dep);
7269   if (non_dep)
7270     expr = instantiate_non_dependent_expr_internal (expr, complain);
7271 
7272   const bool val_dep_p = value_dependent_expression_p (expr);
7273   if (val_dep_p)
7274     expr = canonicalize_expr_argument (expr, complain);
7275 
7276   /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
7277      to a non-type argument of "nullptr".  */
7278   if (NULLPTR_TYPE_P (expr_type) && TYPE_PTR_OR_PTRMEM_P (type))
7279     expr = fold_simple (convert (type, expr));
7280 
7281   /* In C++11, integral or enumeration non-type template arguments can be
7282      arbitrary constant expressions.  Pointer and pointer to
7283      member arguments can be general constant expressions that evaluate
7284      to a null value, but otherwise still need to be of a specific form.  */
7285   if (cxx_dialect >= cxx11)
7286     {
7287       if (TREE_CODE (expr) == PTRMEM_CST && TYPE_PTRMEM_P (type))
7288 	/* A PTRMEM_CST is already constant, and a valid template
7289 	   argument for a parameter of pointer to member type, we just want
7290 	   to leave it in that form rather than lower it to a
7291 	   CONSTRUCTOR.  */;
7292       else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7293 	       || cxx_dialect >= cxx17)
7294 	{
7295 	  /* C++17: A template-argument for a non-type template-parameter shall
7296 	     be a converted constant expression (8.20) of the type of the
7297 	     template-parameter.  */
7298 	  expr = build_converted_constant_expr (type, expr, complain);
7299 	  if (expr == error_mark_node)
7300 	    /* Make sure we return NULL_TREE only if we have really issued
7301 	       an error, as described above.  */
7302 	    return (complain & tf_error) ? NULL_TREE : error_mark_node;
7303 	  else if (TREE_CODE (expr) == IMPLICIT_CONV_EXPR)
7304 	    {
7305 	      IMPLICIT_CONV_EXPR_NONTYPE_ARG (expr) = true;
7306 	      return expr;
7307 	    }
7308 	  expr = maybe_constant_value (expr, NULL_TREE,
7309 				       /*manifestly_const_eval=*/true);
7310 	  expr = convert_from_reference (expr);
7311 	}
7312       else if (TYPE_PTR_OR_PTRMEM_P (type))
7313 	{
7314 	  tree folded = maybe_constant_value (expr, NULL_TREE,
7315 					      /*manifestly_const_eval=*/true);
7316 	  if (TYPE_PTR_P (type) ? integer_zerop (folded)
7317 	      : null_member_pointer_value_p (folded))
7318 	    expr = folded;
7319 	}
7320     }
7321 
7322   if (TYPE_REF_P (type))
7323     expr = mark_lvalue_use (expr);
7324   else
7325     expr = mark_rvalue_use (expr);
7326 
7327   /* HACK: Due to double coercion, we can get a
7328      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
7329      which is the tree that we built on the first call (see
7330      below when coercing to reference to object or to reference to
7331      function). We just strip everything and get to the arg.
7332      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
7333      for examples.  */
7334   if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
7335     {
7336       tree probe_type, probe = expr;
7337       if (REFERENCE_REF_P (probe))
7338 	probe = TREE_OPERAND (probe, 0);
7339       probe_type = TREE_TYPE (probe);
7340       if (TREE_CODE (probe) == NOP_EXPR)
7341 	{
7342 	  /* ??? Maybe we could use convert_from_reference here, but we
7343 	     would need to relax its constraints because the NOP_EXPR
7344 	     could actually change the type to something more cv-qualified,
7345 	     and this is not folded by convert_from_reference.  */
7346 	  tree addr = TREE_OPERAND (probe, 0);
7347 	  if (TYPE_REF_P (probe_type)
7348 	      && TREE_CODE (addr) == ADDR_EXPR
7349 	      && TYPE_PTR_P (TREE_TYPE (addr))
7350 	      && (same_type_ignoring_top_level_qualifiers_p
7351 		  (TREE_TYPE (probe_type),
7352 		   TREE_TYPE (TREE_TYPE (addr)))))
7353 	    {
7354 	      expr = TREE_OPERAND (addr, 0);
7355 	      expr_type = TREE_TYPE (probe_type);
7356 	    }
7357 	}
7358     }
7359 
7360   /* [temp.arg.nontype]/5, bullet 1
7361 
7362      For a non-type template-parameter of integral or enumeration type,
7363      integral promotions (_conv.prom_) and integral conversions
7364      (_conv.integral_) are applied.  */
7365   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7366       || TREE_CODE (type) == REAL_TYPE)
7367     {
7368       if (cxx_dialect < cxx11)
7369 	{
7370 	  tree t = build_converted_constant_expr (type, expr, complain);
7371 	  t = maybe_constant_value (t);
7372 	  if (t != error_mark_node)
7373 	    expr = t;
7374 	}
7375 
7376       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
7377 	return error_mark_node;
7378 
7379       /* Notice that there are constant expressions like '4 % 0' which
7380 	 do not fold into integer constants.  */
7381       if (!CONSTANT_CLASS_P (expr) && !val_dep_p)
7382 	{
7383 	  if (complain & tf_error)
7384 	    {
7385 	      int errs = errorcount, warns = warningcount + werrorcount;
7386 	      if (!require_potential_constant_expression (expr))
7387 		expr = error_mark_node;
7388 	      else
7389 		expr = cxx_constant_value (expr);
7390 	      if (errorcount > errs || warningcount + werrorcount > warns)
7391 		inform (loc, "in template argument for type %qT", type);
7392 	      if (expr == error_mark_node)
7393 		return NULL_TREE;
7394 	      /* else cxx_constant_value complained but gave us
7395 		 a real constant, so go ahead.  */
7396 	      if (!CONSTANT_CLASS_P (expr))
7397 		{
7398 		  /* Some assemble time constant expressions like
7399 		     (intptr_t)&&lab1 - (intptr_t)&&lab2 or
7400 		     4 + (intptr_t)&&var satisfy reduced_constant_expression_p
7401 		     as we can emit them into .rodata initializers of
7402 		     variables, yet they can't fold into an INTEGER_CST at
7403 		     compile time.  Refuse them here.  */
7404 		  gcc_checking_assert (reduced_constant_expression_p (expr));
7405 		  error_at (loc, "template argument %qE for type %qT not "
7406 				 "a compile-time constant", expr, type);
7407 		  return NULL_TREE;
7408 		}
7409 	    }
7410 	  else
7411 	    return NULL_TREE;
7412 	}
7413 
7414       /* Avoid typedef problems.  */
7415       if (TREE_TYPE (expr) != type)
7416 	expr = fold_convert (type, expr);
7417     }
7418   /* [temp.arg.nontype]/5, bullet 2
7419 
7420      For a non-type template-parameter of type pointer to object,
7421      qualification conversions (_conv.qual_) and the array-to-pointer
7422      conversion (_conv.array_) are applied.  */
7423   else if (TYPE_PTROBV_P (type))
7424     {
7425       tree decayed = expr;
7426 
7427       /* Look through any NOP_EXPRs around an ADDR_EXPR, whether they come from
7428 	 decay_conversion or an explicit cast.  If it's a problematic cast,
7429 	 we'll complain about it below.  */
7430       if (TREE_CODE (expr) == NOP_EXPR)
7431 	{
7432 	  tree probe = expr;
7433 	  STRIP_NOPS (probe);
7434 	  if (TREE_CODE (probe) == ADDR_EXPR
7435 	      && TYPE_PTR_P (TREE_TYPE (probe)))
7436 	    {
7437 	      expr = probe;
7438 	      expr_type = TREE_TYPE (expr);
7439 	    }
7440 	}
7441 
7442       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
7443 
7444 	 A template-argument for a non-type, non-template template-parameter
7445 	 shall be one of: [...]
7446 
7447 	 -- the name of a non-type template-parameter;
7448 	 -- the address of an object or function with external linkage, [...]
7449 	    expressed as "& id-expression" where the & is optional if the name
7450 	    refers to a function or array, or if the corresponding
7451 	    template-parameter is a reference.
7452 
7453 	Here, we do not care about functions, as they are invalid anyway
7454 	for a parameter of type pointer-to-object.  */
7455 
7456       if (val_dep_p)
7457 	/* Non-type template parameters are OK.  */
7458 	;
7459       else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7460 	/* Null pointer values are OK in C++11.  */;
7461       else if (TREE_CODE (expr) != ADDR_EXPR
7462 	       && !INDIRECT_TYPE_P (expr_type))
7463 	/* Other values, like integer constants, might be valid
7464 	   non-type arguments of some other type.  */
7465 	return error_mark_node;
7466       else if (invalid_tparm_referent_p (type, expr, complain))
7467 	return NULL_TREE;
7468 
7469       expr = decayed;
7470 
7471       expr = perform_qualification_conversions (type, expr);
7472       if (expr == error_mark_node)
7473 	return error_mark_node;
7474     }
7475   /* [temp.arg.nontype]/5, bullet 3
7476 
7477      For a non-type template-parameter of type reference to object, no
7478      conversions apply. The type referred to by the reference may be more
7479      cv-qualified than the (otherwise identical) type of the
7480      template-argument. The template-parameter is bound directly to the
7481      template-argument, which must be an lvalue.  */
7482   else if (TYPE_REF_OBJ_P (type))
7483     {
7484       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
7485 						      expr_type))
7486 	return error_mark_node;
7487 
7488       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
7489 	{
7490 	  if (complain & tf_error)
7491 	    error ("%qE is not a valid template argument for type %qT "
7492 		   "because of conflicts in cv-qualification", expr, type);
7493 	  return NULL_TREE;
7494 	}
7495 
7496       if (!lvalue_p (expr))
7497 	{
7498 	  if (complain & tf_error)
7499 	    error ("%qE is not a valid template argument for type %qT "
7500 		   "because it is not an lvalue", expr, type);
7501 	  return NULL_TREE;
7502 	}
7503 
7504       /* [temp.arg.nontype]/1
7505 
7506 	 A template-argument for a non-type, non-template template-parameter
7507 	 shall be one of: [...]
7508 
7509 	 -- the address of an object or function with external linkage.  */
7510       if (INDIRECT_REF_P (expr)
7511 	  && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
7512 	{
7513 	  expr = TREE_OPERAND (expr, 0);
7514 	  if (DECL_P (expr))
7515 	    {
7516 	      if (complain & tf_error)
7517 		error ("%q#D is not a valid template argument for type %qT "
7518 		       "because a reference variable does not have a constant "
7519 		       "address", expr, type);
7520 	      return NULL_TREE;
7521 	    }
7522 	}
7523 
7524       if (TYPE_REF_OBJ_P (TREE_TYPE (expr)) && val_dep_p)
7525 	/* OK, dependent reference.  We don't want to ask whether a DECL is
7526 	   itself value-dependent, since what we want here is its address.  */;
7527       else
7528 	{
7529 	  expr = build_address (expr);
7530 
7531 	  if (invalid_tparm_referent_p (type, expr, complain))
7532 	    return NULL_TREE;
7533 	}
7534 
7535       if (!same_type_p (type, TREE_TYPE (expr)))
7536 	expr = build_nop (type, expr);
7537     }
7538   /* [temp.arg.nontype]/5, bullet 4
7539 
7540      For a non-type template-parameter of type pointer to function, only
7541      the function-to-pointer conversion (_conv.func_) is applied. If the
7542      template-argument represents a set of overloaded functions (or a
7543      pointer to such), the matching function is selected from the set
7544      (_over.over_).  */
7545   else if (TYPE_PTRFN_P (type))
7546     {
7547       /* If the argument is a template-id, we might not have enough
7548 	 context information to decay the pointer.  */
7549       if (!type_unknown_p (expr_type))
7550 	{
7551 	  expr = decay_conversion (expr, complain);
7552 	  if (expr == error_mark_node)
7553 	    return error_mark_node;
7554 	}
7555 
7556       if (cxx_dialect >= cxx11 && integer_zerop (expr))
7557 	/* Null pointer values are OK in C++11.  */
7558 	return perform_qualification_conversions (type, expr);
7559 
7560       expr = convert_nontype_argument_function (type, expr, complain);
7561       if (!expr || expr == error_mark_node)
7562 	return expr;
7563     }
7564   /* [temp.arg.nontype]/5, bullet 5
7565 
7566      For a non-type template-parameter of type reference to function, no
7567      conversions apply. If the template-argument represents a set of
7568      overloaded functions, the matching function is selected from the set
7569      (_over.over_).  */
7570   else if (TYPE_REFFN_P (type))
7571     {
7572       if (TREE_CODE (expr) == ADDR_EXPR)
7573 	{
7574 	  if (complain & tf_error)
7575 	    {
7576 	      error ("%qE is not a valid template argument for type %qT "
7577 		     "because it is a pointer", expr, type);
7578 	      inform (input_location, "try using %qE instead",
7579 		      TREE_OPERAND (expr, 0));
7580 	    }
7581 	  return NULL_TREE;
7582 	}
7583 
7584       expr = convert_nontype_argument_function (type, expr, complain);
7585       if (!expr || expr == error_mark_node)
7586 	return expr;
7587     }
7588   /* [temp.arg.nontype]/5, bullet 6
7589 
7590      For a non-type template-parameter of type pointer to member function,
7591      no conversions apply. If the template-argument represents a set of
7592      overloaded member functions, the matching member function is selected
7593      from the set (_over.over_).  */
7594   else if (TYPE_PTRMEMFUNC_P (type))
7595     {
7596       expr = instantiate_type (type, expr, tf_none);
7597       if (expr == error_mark_node)
7598 	return error_mark_node;
7599 
7600       /* [temp.arg.nontype] bullet 1 says the pointer to member
7601          expression must be a pointer-to-member constant.  */
7602       if (!val_dep_p
7603 	  && !check_valid_ptrmem_cst_expr (type, expr, complain))
7604 	return NULL_TREE;
7605 
7606       /* Repeated conversion can't deal with a conversion that turns PTRMEM_CST
7607 	 into a CONSTRUCTOR, so build up a new PTRMEM_CST instead.  */
7608       if (fnptr_conv_p (type, TREE_TYPE (expr)))
7609 	expr = make_ptrmem_cst (type, PTRMEM_CST_MEMBER (expr));
7610     }
7611   /* [temp.arg.nontype]/5, bullet 7
7612 
7613      For a non-type template-parameter of type pointer to data member,
7614      qualification conversions (_conv.qual_) are applied.  */
7615   else if (TYPE_PTRDATAMEM_P (type))
7616     {
7617       /* [temp.arg.nontype] bullet 1 says the pointer to member
7618          expression must be a pointer-to-member constant.  */
7619       if (!val_dep_p
7620 	  && !check_valid_ptrmem_cst_expr (type, expr, complain))
7621 	return NULL_TREE;
7622 
7623       expr = perform_qualification_conversions (type, expr);
7624       if (expr == error_mark_node)
7625 	return expr;
7626     }
7627   else if (NULLPTR_TYPE_P (type))
7628     {
7629       if (!NULLPTR_TYPE_P (TREE_TYPE (expr)))
7630 	{
7631 	  if (complain & tf_error)
7632 	    error ("%qE is not a valid template argument for type %qT "
7633 		   "because it is of type %qT", expr, type, TREE_TYPE (expr));
7634 	  return NULL_TREE;
7635 	}
7636       return expr;
7637     }
7638   else if (CLASS_TYPE_P (type))
7639     {
7640       /* Replace the argument with a reference to the corresponding template
7641 	 parameter object.  */
7642       if (!val_dep_p)
7643 	expr = get_template_parm_object (expr, complain);
7644       if (expr == error_mark_node)
7645 	return NULL_TREE;
7646     }
7647   /* A template non-type parameter must be one of the above.  */
7648   else
7649     gcc_unreachable ();
7650 
7651   /* Sanity check: did we actually convert the argument to the
7652      right type?  */
7653   gcc_assert (same_type_ignoring_top_level_qualifiers_p
7654 	      (type, TREE_TYPE (expr)));
7655   return convert_from_reference (expr);
7656 }
7657 
7658 /* Subroutine of coerce_template_template_parms, which returns 1 if
7659    PARM_PARM and ARG_PARM match using the rule for the template
7660    parameters of template template parameters. Both PARM and ARG are
7661    template parameters; the rest of the arguments are the same as for
7662    coerce_template_template_parms.
7663  */
7664 static int
coerce_template_template_parm(tree parm,tree arg,tsubst_flags_t complain,tree in_decl,tree outer_args)7665 coerce_template_template_parm (tree parm,
7666                               tree arg,
7667                               tsubst_flags_t complain,
7668                               tree in_decl,
7669                               tree outer_args)
7670 {
7671   if (arg == NULL_TREE || error_operand_p (arg)
7672       || parm == NULL_TREE || error_operand_p (parm))
7673     return 0;
7674 
7675   if (TREE_CODE (arg) != TREE_CODE (parm))
7676     return 0;
7677 
7678   switch (TREE_CODE (parm))
7679     {
7680     case TEMPLATE_DECL:
7681       /* We encounter instantiations of templates like
7682 	 template <template <template <class> class> class TT>
7683 	 class C;  */
7684       {
7685 	tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
7686 	tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
7687 
7688 	if (!coerce_template_template_parms
7689 	    (parmparm, argparm, complain, in_decl, outer_args))
7690 	  return 0;
7691       }
7692       /* Fall through.  */
7693 
7694     case TYPE_DECL:
7695       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
7696 	  && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7697 	/* Argument is a parameter pack but parameter is not.  */
7698 	return 0;
7699       break;
7700 
7701     case PARM_DECL:
7702       /* The tsubst call is used to handle cases such as
7703 
7704            template <int> class C {};
7705 	   template <class T, template <T> class TT> class D {};
7706 	   D<int, C> d;
7707 
7708 	 i.e. the parameter list of TT depends on earlier parameters.  */
7709       if (!uses_template_parms (TREE_TYPE (arg)))
7710 	{
7711 	  tree t = tsubst (TREE_TYPE (parm), outer_args, complain, in_decl);
7712 	  if (!uses_template_parms (t)
7713 	      && !same_type_p (t, TREE_TYPE (arg)))
7714 	    return 0;
7715 	}
7716 
7717       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
7718 	  && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7719 	/* Argument is a parameter pack but parameter is not.  */
7720 	return 0;
7721 
7722       break;
7723 
7724     default:
7725       gcc_unreachable ();
7726     }
7727 
7728   return 1;
7729 }
7730 
7731 /* Coerce template argument list ARGLIST for use with template
7732    template-parameter TEMPL.  */
7733 
7734 static tree
coerce_template_args_for_ttp(tree templ,tree arglist,tsubst_flags_t complain)7735 coerce_template_args_for_ttp (tree templ, tree arglist,
7736 			      tsubst_flags_t complain)
7737 {
7738   /* Consider an example where a template template parameter declared as
7739 
7740      template <class T, class U = std::allocator<T> > class TT
7741 
7742      The template parameter level of T and U are one level larger than
7743      of TT.  To proper process the default argument of U, say when an
7744      instantiation `TT<int>' is seen, we need to build the full
7745      arguments containing {int} as the innermost level.  Outer levels,
7746      available when not appearing as default template argument, can be
7747      obtained from the arguments of the enclosing template.
7748 
7749      Suppose that TT is later substituted with std::vector.  The above
7750      instantiation is `TT<int, std::allocator<T> >' with TT at
7751      level 1, and T at level 2, while the template arguments at level 1
7752      becomes {std::vector} and the inner level 2 is {int}.  */
7753 
7754   tree outer = DECL_CONTEXT (templ);
7755   if (outer)
7756     outer = generic_targs_for (outer);
7757   else if (current_template_parms)
7758     {
7759       /* This is an argument of the current template, so we haven't set
7760 	 DECL_CONTEXT yet.  */
7761       tree relevant_template_parms;
7762 
7763       /* Parameter levels that are greater than the level of the given
7764 	 template template parm are irrelevant.  */
7765       relevant_template_parms = current_template_parms;
7766       while (TMPL_PARMS_DEPTH (relevant_template_parms)
7767 	     != TEMPLATE_TYPE_LEVEL (TREE_TYPE (templ)))
7768 	relevant_template_parms = TREE_CHAIN (relevant_template_parms);
7769 
7770       outer = template_parms_to_args (relevant_template_parms);
7771     }
7772 
7773   if (outer)
7774     arglist = add_to_template_args (outer, arglist);
7775 
7776   tree parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7777   return coerce_template_parms (parmlist, arglist, templ,
7778 				complain,
7779 				/*require_all_args=*/true,
7780 				/*use_default_args=*/true);
7781 }
7782 
7783 /* A cache of template template parameters with match-all default
7784    arguments.  */
7785 static GTY((deletable)) hash_map<tree,tree> *defaulted_ttp_cache;
7786 
7787 /* T is a bound template template-parameter.  Copy its arguments into default
7788    arguments of the template template-parameter's template parameters.  */
7789 
7790 static tree
add_defaults_to_ttp(tree otmpl)7791 add_defaults_to_ttp (tree otmpl)
7792 {
7793   if (tree *c = hash_map_safe_get (defaulted_ttp_cache, otmpl))
7794     return *c;
7795 
7796   tree ntmpl = copy_node (otmpl);
7797 
7798   tree ntype = copy_node (TREE_TYPE (otmpl));
7799   TYPE_STUB_DECL (ntype) = TYPE_NAME (ntype) = ntmpl;
7800   TYPE_MAIN_VARIANT (ntype) = ntype;
7801   TYPE_POINTER_TO (ntype) = TYPE_REFERENCE_TO (ntype) = NULL_TREE;
7802   TYPE_NAME (ntype) = ntmpl;
7803   SET_TYPE_STRUCTURAL_EQUALITY (ntype);
7804 
7805   tree idx = TEMPLATE_TYPE_PARM_INDEX (ntype)
7806     = copy_node (TEMPLATE_TYPE_PARM_INDEX (ntype));
7807   TEMPLATE_PARM_DECL (idx) = ntmpl;
7808   TREE_TYPE (ntmpl) = TREE_TYPE (idx) = ntype;
7809 
7810   tree oparms = DECL_TEMPLATE_PARMS (otmpl);
7811   tree parms = DECL_TEMPLATE_PARMS (ntmpl) = copy_node (oparms);
7812   TREE_CHAIN (parms) = TREE_CHAIN (oparms);
7813   tree vec = TREE_VALUE (parms) = copy_node (TREE_VALUE (parms));
7814   for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
7815     {
7816       tree o = TREE_VEC_ELT (vec, i);
7817       if (!template_parameter_pack_p (TREE_VALUE (o)))
7818 	{
7819 	  tree n = TREE_VEC_ELT (vec, i) = copy_node (o);
7820 	  TREE_PURPOSE (n) = any_targ_node;
7821 	}
7822     }
7823 
7824   hash_map_safe_put<hm_ggc> (defaulted_ttp_cache, otmpl, ntmpl);
7825   return ntmpl;
7826 }
7827 
7828 /* ARG is a bound potential template template-argument, and PARGS is a list
7829    of arguments for the corresponding template template-parameter.  Adjust
7830    PARGS as appropriate for application to ARG's template, and if ARG is a
7831    BOUND_TEMPLATE_TEMPLATE_PARM, possibly adjust it to add default template
7832    arguments to the template template parameter.  */
7833 
7834 static tree
coerce_ttp_args_for_tta(tree & arg,tree pargs,tsubst_flags_t complain)7835 coerce_ttp_args_for_tta (tree& arg, tree pargs, tsubst_flags_t complain)
7836 {
7837   ++processing_template_decl;
7838   tree arg_tmpl = TYPE_TI_TEMPLATE (arg);
7839   if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
7840     {
7841       /* When comparing two template template-parameters in partial ordering,
7842 	 rewrite the one currently being used as an argument to have default
7843 	 arguments for all parameters.  */
7844       arg_tmpl = add_defaults_to_ttp (arg_tmpl);
7845       pargs = coerce_template_args_for_ttp (arg_tmpl, pargs, complain);
7846       if (pargs != error_mark_node)
7847 	arg = bind_template_template_parm (TREE_TYPE (arg_tmpl),
7848 					   TYPE_TI_ARGS (arg));
7849     }
7850   else
7851     {
7852       tree aparms
7853 	= INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (arg_tmpl));
7854       pargs = coerce_template_parms (aparms, pargs, arg_tmpl, complain,
7855 				       /*require_all*/true,
7856 				       /*use_default*/true);
7857     }
7858   --processing_template_decl;
7859   return pargs;
7860 }
7861 
7862 /* Subroutine of unify for the case when PARM is a
7863    BOUND_TEMPLATE_TEMPLATE_PARM.  */
7864 
7865 static int
unify_bound_ttp_args(tree tparms,tree targs,tree parm,tree & arg,bool explain_p)7866 unify_bound_ttp_args (tree tparms, tree targs, tree parm, tree& arg,
7867 		      bool explain_p)
7868 {
7869   tree parmvec = TYPE_TI_ARGS (parm);
7870   tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
7871 
7872   /* The template template parm might be variadic and the argument
7873      not, so flatten both argument lists.  */
7874   parmvec = expand_template_argument_pack (parmvec);
7875   argvec = expand_template_argument_pack (argvec);
7876 
7877   if (flag_new_ttp)
7878     {
7879       /* In keeping with P0522R0, adjust P's template arguments
7880 	 to apply to A's template; then flatten it again.  */
7881       tree nparmvec = coerce_ttp_args_for_tta (arg, parmvec, tf_none);
7882       nparmvec = expand_template_argument_pack (nparmvec);
7883 
7884       if (unify (tparms, targs, nparmvec, argvec,
7885 		 UNIFY_ALLOW_NONE, explain_p))
7886 	return 1;
7887 
7888       /* If the P0522 adjustment eliminated a pack expansion, deduce
7889 	 empty packs.  */
7890       if (flag_new_ttp
7891 	  && TREE_VEC_LENGTH (nparmvec) < TREE_VEC_LENGTH (parmvec)
7892 	  && unify_pack_expansion (tparms, targs, parmvec, argvec,
7893 				   DEDUCE_EXACT, /*sub*/true, explain_p))
7894 	return 1;
7895     }
7896   else
7897     {
7898       /* Deduce arguments T, i from TT<T> or TT<i>.
7899 	 We check each element of PARMVEC and ARGVEC individually
7900 	 rather than the whole TREE_VEC since they can have
7901 	 different number of elements, which is allowed under N2555.  */
7902 
7903       int len = TREE_VEC_LENGTH (parmvec);
7904 
7905       /* Check if the parameters end in a pack, making them
7906 	 variadic.  */
7907       int parm_variadic_p = 0;
7908       if (len > 0
7909 	  && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
7910 	parm_variadic_p = 1;
7911 
7912       for (int i = 0; i < len - parm_variadic_p; ++i)
7913 	/* If the template argument list of P contains a pack
7914 	   expansion that is not the last template argument, the
7915 	   entire template argument list is a non-deduced
7916 	   context.  */
7917 	if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
7918 	  return unify_success (explain_p);
7919 
7920       if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
7921 	return unify_too_few_arguments (explain_p,
7922 					TREE_VEC_LENGTH (argvec), len);
7923 
7924       for (int i = 0; i < len - parm_variadic_p; ++i)
7925 	if (unify (tparms, targs,
7926 		   TREE_VEC_ELT (parmvec, i),
7927 		   TREE_VEC_ELT (argvec, i),
7928 		   UNIFY_ALLOW_NONE, explain_p))
7929 	  return 1;
7930 
7931       if (parm_variadic_p
7932 	  && unify_pack_expansion (tparms, targs,
7933 				   parmvec, argvec,
7934 				   DEDUCE_EXACT,
7935 				   /*subr=*/true, explain_p))
7936 	return 1;
7937     }
7938 
7939   return 0;
7940 }
7941 
7942 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
7943    template template parameters.  Both PARM_PARMS and ARG_PARMS are
7944    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
7945    or PARM_DECL.
7946 
7947    Consider the example:
7948      template <class T> class A;
7949      template<template <class U> class TT> class B;
7950 
7951    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
7952    the parameters to A, and OUTER_ARGS contains A.  */
7953 
7954 static int
coerce_template_template_parms(tree parm_parms,tree arg_parms,tsubst_flags_t complain,tree in_decl,tree outer_args)7955 coerce_template_template_parms (tree parm_parms,
7956 				tree arg_parms,
7957 				tsubst_flags_t complain,
7958 				tree in_decl,
7959 				tree outer_args)
7960 {
7961   int nparms, nargs, i;
7962   tree parm, arg;
7963   int variadic_p = 0;
7964 
7965   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
7966   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
7967 
7968   nparms = TREE_VEC_LENGTH (parm_parms);
7969   nargs = TREE_VEC_LENGTH (arg_parms);
7970 
7971   if (flag_new_ttp)
7972     {
7973       /* P0522R0: A template template-parameter P is at least as specialized as
7974 	 a template template-argument A if, given the following rewrite to two
7975 	 function templates, the function template corresponding to P is at
7976 	 least as specialized as the function template corresponding to A
7977 	 according to the partial ordering rules for function templates
7978 	 ([temp.func.order]). Given an invented class template X with the
7979 	 template parameter list of A (including default arguments):
7980 
7981 	 * Each of the two function templates has the same template parameters,
7982 	 respectively, as P or A.
7983 
7984 	 * Each function template has a single function parameter whose type is
7985 	 a specialization of X with template arguments corresponding to the
7986 	 template parameters from the respective function template where, for
7987 	 each template parameter PP in the template parameter list of the
7988 	 function template, a corresponding template argument AA is formed. If
7989 	 PP declares a parameter pack, then AA is the pack expansion
7990 	 PP... ([temp.variadic]); otherwise, AA is the id-expression PP.
7991 
7992 	 If the rewrite produces an invalid type, then P is not at least as
7993 	 specialized as A.  */
7994 
7995       /* So coerce P's args to apply to A's parms, and then deduce between A's
7996 	 args and the converted args.  If that succeeds, A is at least as
7997 	 specialized as P, so they match.*/
7998       tree pargs = template_parms_level_to_args (parm_parms);
7999       pargs = add_outermost_template_args (outer_args, pargs);
8000       ++processing_template_decl;
8001       pargs = coerce_template_parms (arg_parms, pargs, NULL_TREE, tf_none,
8002 				     /*require_all*/true, /*use_default*/true);
8003       --processing_template_decl;
8004       if (pargs != error_mark_node)
8005 	{
8006 	  tree targs = make_tree_vec (nargs);
8007 	  tree aargs = template_parms_level_to_args (arg_parms);
8008 	  if (!unify (arg_parms, targs, aargs, pargs, UNIFY_ALLOW_NONE,
8009 		      /*explain*/false))
8010 	    return 1;
8011 	}
8012     }
8013 
8014   /* Determine whether we have a parameter pack at the end of the
8015      template template parameter's template parameter list.  */
8016   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
8017     {
8018       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
8019 
8020       if (error_operand_p (parm))
8021 	return 0;
8022 
8023       switch (TREE_CODE (parm))
8024         {
8025         case TEMPLATE_DECL:
8026         case TYPE_DECL:
8027           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
8028             variadic_p = 1;
8029           break;
8030 
8031         case PARM_DECL:
8032           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
8033             variadic_p = 1;
8034           break;
8035 
8036         default:
8037           gcc_unreachable ();
8038         }
8039     }
8040 
8041   if (nargs != nparms
8042       && !(variadic_p && nargs >= nparms - 1))
8043     return 0;
8044 
8045   /* Check all of the template parameters except the parameter pack at
8046      the end (if any).  */
8047   for (i = 0; i < nparms - variadic_p; ++i)
8048     {
8049       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
8050           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
8051         continue;
8052 
8053       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
8054       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
8055 
8056       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
8057                                           outer_args))
8058 	return 0;
8059 
8060     }
8061 
8062   if (variadic_p)
8063     {
8064       /* Check each of the template parameters in the template
8065 	 argument against the template parameter pack at the end of
8066 	 the template template parameter.  */
8067       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
8068 	return 0;
8069 
8070       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
8071 
8072       for (; i < nargs; ++i)
8073         {
8074           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
8075             continue;
8076 
8077           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
8078 
8079           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
8080                                               outer_args))
8081             return 0;
8082         }
8083     }
8084 
8085   return 1;
8086 }
8087 
8088 /* Verifies that the deduced template arguments (in TARGS) for the
8089    template template parameters (in TPARMS) represent valid bindings,
8090    by comparing the template parameter list of each template argument
8091    to the template parameter list of its corresponding template
8092    template parameter, in accordance with DR150. This
8093    routine can only be called after all template arguments have been
8094    deduced. It will return TRUE if all of the template template
8095    parameter bindings are okay, FALSE otherwise.  */
8096 bool
template_template_parm_bindings_ok_p(tree tparms,tree targs)8097 template_template_parm_bindings_ok_p (tree tparms, tree targs)
8098 {
8099   int i, ntparms = TREE_VEC_LENGTH (tparms);
8100   bool ret = true;
8101 
8102   /* We're dealing with template parms in this process.  */
8103   ++processing_template_decl;
8104 
8105   targs = INNERMOST_TEMPLATE_ARGS (targs);
8106 
8107   for (i = 0; i < ntparms; ++i)
8108     {
8109       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
8110       tree targ = TREE_VEC_ELT (targs, i);
8111 
8112       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
8113 	{
8114 	  tree packed_args = NULL_TREE;
8115 	  int idx, len = 1;
8116 
8117 	  if (ARGUMENT_PACK_P (targ))
8118 	    {
8119 	      /* Look inside the argument pack.  */
8120 	      packed_args = ARGUMENT_PACK_ARGS (targ);
8121 	      len = TREE_VEC_LENGTH (packed_args);
8122 	    }
8123 
8124 	  for (idx = 0; idx < len; ++idx)
8125 	    {
8126 	      tree targ_parms = NULL_TREE;
8127 
8128 	      if (packed_args)
8129 		/* Extract the next argument from the argument
8130 		   pack.  */
8131 		targ = TREE_VEC_ELT (packed_args, idx);
8132 
8133 	      if (PACK_EXPANSION_P (targ))
8134 		/* Look at the pattern of the pack expansion.  */
8135 		targ = PACK_EXPANSION_PATTERN (targ);
8136 
8137 	      /* Extract the template parameters from the template
8138 		 argument.  */
8139 	      if (TREE_CODE (targ) == TEMPLATE_DECL)
8140 		targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
8141 	      else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
8142 		targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
8143 
8144 	      /* Verify that we can coerce the template template
8145 		 parameters from the template argument to the template
8146 		 parameter.  This requires an exact match.  */
8147 	      if (targ_parms
8148 		  && !coerce_template_template_parms
8149 		       (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
8150 			targ_parms,
8151 			tf_none,
8152 			tparm,
8153 			targs))
8154 		{
8155 		  ret = false;
8156 		  goto out;
8157 		}
8158 	    }
8159 	}
8160     }
8161 
8162  out:
8163 
8164   --processing_template_decl;
8165   return ret;
8166 }
8167 
8168 /* Since type attributes aren't mangled, we need to strip them from
8169    template type arguments.  */
8170 
8171 tree
canonicalize_type_argument(tree arg,tsubst_flags_t complain)8172 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
8173 {
8174   if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
8175     return arg;
8176   bool removed_attributes = false;
8177   tree canon = strip_typedefs (arg, &removed_attributes);
8178   if (removed_attributes
8179       && (complain & tf_warning))
8180     warning (OPT_Wignored_attributes,
8181 	     "ignoring attributes on template argument %qT", arg);
8182   return canon;
8183 }
8184 
8185 /* And from inside dependent non-type arguments like sizeof(Type).  */
8186 
8187 static tree
canonicalize_expr_argument(tree arg,tsubst_flags_t complain)8188 canonicalize_expr_argument (tree arg, tsubst_flags_t complain)
8189 {
8190   if (!arg || arg == error_mark_node)
8191     return arg;
8192   bool removed_attributes = false;
8193   tree canon = strip_typedefs_expr (arg, &removed_attributes);
8194   if (removed_attributes
8195       && (complain & tf_warning))
8196     warning (OPT_Wignored_attributes,
8197 	     "ignoring attributes in template argument %qE", arg);
8198   return canon;
8199 }
8200 
8201 /* A template declaration can be substituted for a constrained
8202    template template parameter only when the argument is no more
8203    constrained than the parameter.  */
8204 
8205 static bool
is_compatible_template_arg(tree parm,tree arg)8206 is_compatible_template_arg (tree parm, tree arg)
8207 {
8208   tree parm_cons = get_constraints (parm);
8209 
8210   /* For now, allow constrained template template arguments
8211      and unconstrained template template parameters.  */
8212   if (parm_cons == NULL_TREE)
8213     return true;
8214 
8215   /* If the template parameter is constrained, we need to rewrite its
8216      constraints in terms of the ARG's template parameters. This ensures
8217      that all of the template parameter types will have the same depth.
8218 
8219      Note that this is only valid when coerce_template_template_parm is
8220      true for the innermost template parameters of PARM and ARG. In other
8221      words, because coercion is successful, this conversion will be valid.  */
8222   tree new_args = NULL_TREE;
8223   if (parm_cons)
8224     {
8225       tree aparms = DECL_INNERMOST_TEMPLATE_PARMS (arg);
8226       new_args = template_parms_level_to_args (aparms);
8227       parm_cons = tsubst_constraint_info (parm_cons, new_args,
8228 					  tf_none, NULL_TREE);
8229       if (parm_cons == error_mark_node)
8230         return false;
8231     }
8232 
8233   return weakly_subsumes (parm_cons, arg);
8234 }
8235 
8236 // Convert a placeholder argument into a binding to the original
8237 // parameter. The original parameter is saved as the TREE_TYPE of
8238 // ARG.
8239 static inline tree
convert_wildcard_argument(tree parm,tree arg)8240 convert_wildcard_argument (tree parm, tree arg)
8241 {
8242   TREE_TYPE (arg) = parm;
8243   return arg;
8244 }
8245 
8246 /* We can't fully resolve ARG given as a non-type template argument to TYPE,
8247    because one of them is dependent.  But we need to represent the
8248    conversion for the benefit of cp_tree_equal.  */
8249 
8250 static tree
maybe_convert_nontype_argument(tree type,tree arg)8251 maybe_convert_nontype_argument (tree type, tree arg)
8252 {
8253   /* Auto parms get no conversion.  */
8254   if (type_uses_auto (type))
8255     return arg;
8256   /* We don't need or want to add this conversion now if we're going to use the
8257      argument for deduction.  */
8258   if (value_dependent_expression_p (arg))
8259     return arg;
8260 
8261   type = cv_unqualified (type);
8262   tree argtype = TREE_TYPE (arg);
8263   if (same_type_p (type, argtype))
8264     return arg;
8265 
8266   arg = build1 (IMPLICIT_CONV_EXPR, type, arg);
8267   IMPLICIT_CONV_EXPR_NONTYPE_ARG (arg) = true;
8268   return arg;
8269 }
8270 
8271 /* Convert the indicated template ARG as necessary to match the
8272    indicated template PARM.  Returns the converted ARG, or
8273    error_mark_node if the conversion was unsuccessful.  Error and
8274    warning messages are issued under control of COMPLAIN.  This
8275    conversion is for the Ith parameter in the parameter list.  ARGS is
8276    the full set of template arguments deduced so far.  */
8277 
8278 static tree
convert_template_argument(tree parm,tree arg,tree args,tsubst_flags_t complain,int i,tree in_decl)8279 convert_template_argument (tree parm,
8280 			   tree arg,
8281 			   tree args,
8282 			   tsubst_flags_t complain,
8283 			   int i,
8284 			   tree in_decl)
8285 {
8286   tree orig_arg;
8287   tree val;
8288   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
8289 
8290   if (parm == error_mark_node || error_operand_p (arg))
8291     return error_mark_node;
8292 
8293   /* Trivially convert placeholders. */
8294   if (TREE_CODE (arg) == WILDCARD_DECL)
8295     return convert_wildcard_argument (parm, arg);
8296 
8297   if (arg == any_targ_node)
8298     return arg;
8299 
8300   if (TREE_CODE (arg) == TREE_LIST
8301       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
8302     {
8303       /* The template argument was the name of some
8304 	 member function.  That's usually
8305 	 invalid, but static members are OK.  In any
8306 	 case, grab the underlying fields/functions
8307 	 and issue an error later if required.  */
8308       TREE_TYPE (arg) = unknown_type_node;
8309     }
8310 
8311   orig_arg = arg;
8312 
8313   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
8314   requires_type = (TREE_CODE (parm) == TYPE_DECL
8315 		   || requires_tmpl_type);
8316 
8317   /* When determining whether an argument pack expansion is a template,
8318      look at the pattern.  */
8319   if (PACK_EXPANSION_P (arg))
8320     arg = PACK_EXPANSION_PATTERN (arg);
8321 
8322   /* Deal with an injected-class-name used as a template template arg.  */
8323   if (requires_tmpl_type && CLASS_TYPE_P (arg))
8324     {
8325       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
8326       if (TREE_CODE (t) == TEMPLATE_DECL)
8327 	{
8328 	  if (cxx_dialect >= cxx11)
8329 	    /* OK under DR 1004.  */;
8330 	  else if (complain & tf_warning_or_error)
8331 	    pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
8332 		     " used as template template argument", TYPE_NAME (arg));
8333 	  else if (flag_pedantic_errors)
8334 	    t = arg;
8335 
8336 	  arg = t;
8337 	}
8338     }
8339 
8340   is_tmpl_type =
8341     ((TREE_CODE (arg) == TEMPLATE_DECL
8342       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
8343      || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
8344      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8345      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
8346 
8347   if (is_tmpl_type
8348       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8349 	  || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
8350     arg = TYPE_STUB_DECL (arg);
8351 
8352   is_type = TYPE_P (arg) || is_tmpl_type;
8353 
8354   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
8355       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
8356     {
8357       if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
8358 	{
8359 	  if (complain & tf_error)
8360 	    error ("invalid use of destructor %qE as a type", orig_arg);
8361 	  return error_mark_node;
8362 	}
8363 
8364       permerror (input_location,
8365 		 "to refer to a type member of a template parameter, "
8366 		 "use %<typename %E%>", orig_arg);
8367 
8368       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
8369 				     TREE_OPERAND (arg, 1),
8370 				     typename_type,
8371 				     complain);
8372       arg = orig_arg;
8373       is_type = 1;
8374     }
8375   if (is_type != requires_type)
8376     {
8377       if (in_decl)
8378 	{
8379 	  if (complain & tf_error)
8380 	    {
8381 	      error ("type/value mismatch at argument %d in template "
8382 		     "parameter list for %qD",
8383 		     i + 1, in_decl);
8384 	      if (is_type)
8385 		{
8386 		  /* The template argument is a type, but we're expecting
8387 		     an expression.  */
8388 		  inform (input_location,
8389 			  "  expected a constant of type %qT, got %qT",
8390 			  TREE_TYPE (parm),
8391 			  (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
8392 		  /* [temp.arg]/2: "In a template-argument, an ambiguity
8393 		     between a type-id and an expression is resolved to a
8394 		     type-id, regardless of the form of the corresponding
8395 		     template-parameter."  So give the user a clue.  */
8396 		  if (TREE_CODE (arg) == FUNCTION_TYPE)
8397 		    inform (input_location, "  ambiguous template argument "
8398 			    "for non-type template parameter is treated as "
8399 			    "function type");
8400 		}
8401 	      else if (requires_tmpl_type)
8402 		inform (input_location,
8403 			"  expected a class template, got %qE", orig_arg);
8404 	      else
8405 		inform (input_location,
8406 			"  expected a type, got %qE", orig_arg);
8407 	    }
8408 	}
8409       return error_mark_node;
8410     }
8411   if (is_tmpl_type ^ requires_tmpl_type)
8412     {
8413       if (in_decl && (complain & tf_error))
8414 	{
8415 	  error ("type/value mismatch at argument %d in template "
8416 		 "parameter list for %qD",
8417 		 i + 1, in_decl);
8418 	  if (is_tmpl_type)
8419 	    inform (input_location,
8420 		    "  expected a type, got %qT", DECL_NAME (arg));
8421 	  else
8422 	    inform (input_location,
8423 		    "  expected a class template, got %qT", orig_arg);
8424 	}
8425       return error_mark_node;
8426     }
8427 
8428   if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
8429     /* We already did the appropriate conversion when packing args.  */
8430     val = orig_arg;
8431   else if (is_type)
8432     {
8433       if (requires_tmpl_type)
8434 	{
8435 	  if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
8436 	    /* The number of argument required is not known yet.
8437 	       Just accept it for now.  */
8438 	    val = orig_arg;
8439 	  else
8440 	    {
8441 	      tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
8442 	      tree argparm;
8443 
8444 	      /* Strip alias templates that are equivalent to another
8445 		 template.  */
8446 	      arg = get_underlying_template (arg);
8447               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
8448 
8449 	      if (coerce_template_template_parms (parmparm, argparm,
8450 						  complain, in_decl,
8451 						  args))
8452 		{
8453 		  val = arg;
8454 
8455 		  /* TEMPLATE_TEMPLATE_PARM node is preferred over
8456 		     TEMPLATE_DECL.  */
8457 		  if (val != error_mark_node)
8458                     {
8459                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
8460                         val = TREE_TYPE (val);
8461 		      if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
8462 			val = make_pack_expansion (val, complain);
8463                     }
8464 		}
8465 	      else
8466 		{
8467 		  if (in_decl && (complain & tf_error))
8468 		    {
8469 		      error ("type/value mismatch at argument %d in "
8470 			     "template parameter list for %qD",
8471 			     i + 1, in_decl);
8472 		      inform (input_location,
8473 			      "  expected a template of type %qD, got %qT",
8474 			      parm, orig_arg);
8475 		    }
8476 
8477 		  val = error_mark_node;
8478 		}
8479 
8480               // Check that the constraints are compatible before allowing the
8481               // substitution.
8482               if (val != error_mark_node)
8483                 if (!is_compatible_template_arg (parm, arg))
8484                   {
8485 		    if (in_decl && (complain & tf_error))
8486                       {
8487                         error ("constraint mismatch at argument %d in "
8488                                "template parameter list for %qD",
8489                                i + 1, in_decl);
8490                         inform (input_location, "  expected %qD but got %qD",
8491                                 parm, arg);
8492                       }
8493 		    val = error_mark_node;
8494                   }
8495 	    }
8496 	}
8497       else
8498 	val = orig_arg;
8499       /* We only form one instance of each template specialization.
8500 	 Therefore, if we use a non-canonical variant (i.e., a
8501 	 typedef), any future messages referring to the type will use
8502 	 the typedef, which is confusing if those future uses do not
8503 	 themselves also use the typedef.  */
8504       if (TYPE_P (val))
8505 	val = canonicalize_type_argument (val, complain);
8506     }
8507   else
8508     {
8509       tree t = TREE_TYPE (parm);
8510 
8511       if (TEMPLATE_PARM_LEVEL (get_template_parm_index (parm))
8512 	  > TMPL_ARGS_DEPTH (args))
8513 	/* We don't have enough levels of args to do any substitution.  This
8514 	   can happen in the context of -fnew-ttp-matching.  */;
8515       else if (tree a = type_uses_auto (t))
8516 	{
8517 	  t = do_auto_deduction (t, arg, a, complain, adc_unify, args);
8518 	  if (t == error_mark_node)
8519 	    return error_mark_node;
8520 	}
8521       else
8522 	t = tsubst (t, args, complain, in_decl);
8523 
8524       if (invalid_nontype_parm_type_p (t, complain))
8525 	return error_mark_node;
8526 
8527       if (t != TREE_TYPE (parm))
8528 	t = canonicalize_type_argument (t, complain);
8529 
8530       if (!type_dependent_expression_p (orig_arg)
8531 	  && !uses_template_parms (t))
8532 	/* We used to call digest_init here.  However, digest_init
8533 	   will report errors, which we don't want when complain
8534 	   is zero.  More importantly, digest_init will try too
8535 	   hard to convert things: for example, `0' should not be
8536 	   converted to pointer type at this point according to
8537 	   the standard.  Accepting this is not merely an
8538 	   extension, since deciding whether or not these
8539 	   conversions can occur is part of determining which
8540 	   function template to call, or whether a given explicit
8541 	   argument specification is valid.  */
8542 	val = convert_nontype_argument (t, orig_arg, complain);
8543       else
8544 	{
8545 	  val = canonicalize_expr_argument (orig_arg, complain);
8546 	  val = maybe_convert_nontype_argument (t, val);
8547 	}
8548 
8549 
8550       if (val == NULL_TREE)
8551 	val = error_mark_node;
8552       else if (val == error_mark_node && (complain & tf_error))
8553 	error_at (cp_expr_loc_or_input_loc (orig_arg),
8554 		  "could not convert template argument %qE from %qT to %qT",
8555 		  orig_arg, TREE_TYPE (orig_arg), t);
8556 
8557       if (INDIRECT_REF_P (val))
8558         {
8559           /* Reject template arguments that are references to built-in
8560              functions with no library fallbacks.  */
8561           const_tree inner = TREE_OPERAND (val, 0);
8562 	  const_tree innertype = TREE_TYPE (inner);
8563 	  if (innertype
8564 	      && TYPE_REF_P (innertype)
8565 	      && TREE_CODE (TREE_TYPE (innertype)) == FUNCTION_TYPE
8566 	      && TREE_OPERAND_LENGTH (inner) > 0
8567               && reject_gcc_builtin (TREE_OPERAND (inner, 0)))
8568               return error_mark_node;
8569         }
8570 
8571       if (TREE_CODE (val) == SCOPE_REF)
8572 	{
8573 	  /* Strip typedefs from the SCOPE_REF.  */
8574 	  tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
8575 	  tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
8576 						   complain);
8577 	  val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
8578 				      QUALIFIED_NAME_IS_TEMPLATE (val));
8579 	}
8580     }
8581 
8582   return val;
8583 }
8584 
8585 /* Coerces the remaining template arguments in INNER_ARGS (from
8586    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
8587    Returns the coerced argument pack. PARM_IDX is the position of this
8588    parameter in the template parameter list. ARGS is the original
8589    template argument list.  */
8590 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)8591 coerce_template_parameter_pack (tree parms,
8592                                 int parm_idx,
8593                                 tree args,
8594                                 tree inner_args,
8595                                 int arg_idx,
8596                                 tree new_args,
8597                                 int* lost,
8598                                 tree in_decl,
8599                                 tsubst_flags_t complain)
8600 {
8601   tree parm = TREE_VEC_ELT (parms, parm_idx);
8602   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8603   tree packed_args;
8604   tree argument_pack;
8605   tree packed_parms = NULL_TREE;
8606 
8607   if (arg_idx > nargs)
8608     arg_idx = nargs;
8609 
8610   if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
8611     {
8612       /* When the template parameter is a non-type template parameter pack
8613          or template template parameter pack whose type or template
8614          parameters use parameter packs, we know exactly how many arguments
8615          we are looking for.  Build a vector of the instantiated decls for
8616          these template parameters in PACKED_PARMS.  */
8617       /* We can't use make_pack_expansion here because it would interpret a
8618 	 _DECL as a use rather than a declaration.  */
8619       tree decl = TREE_VALUE (parm);
8620       tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
8621       SET_PACK_EXPANSION_PATTERN (exp, decl);
8622       PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
8623       SET_TYPE_STRUCTURAL_EQUALITY (exp);
8624 
8625       TREE_VEC_LENGTH (args)--;
8626       packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
8627       TREE_VEC_LENGTH (args)++;
8628 
8629       if (packed_parms == error_mark_node)
8630         return error_mark_node;
8631 
8632       /* If we're doing a partial instantiation of a member template,
8633          verify that all of the types used for the non-type
8634          template parameter pack are, in fact, valid for non-type
8635          template parameters.  */
8636       if (arg_idx < nargs
8637           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
8638         {
8639           int j, len = TREE_VEC_LENGTH (packed_parms);
8640           for (j = 0; j < len; ++j)
8641             {
8642               tree t = TREE_VEC_ELT (packed_parms, j);
8643               if (TREE_CODE (t) == PARM_DECL
8644 		  && invalid_nontype_parm_type_p (TREE_TYPE (t), complain))
8645                 return error_mark_node;
8646             }
8647 	  /* We don't know how many args we have yet, just
8648 	     use the unconverted ones for now.  */
8649 	  return NULL_TREE;
8650         }
8651 
8652       packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
8653     }
8654   /* Check if we have a placeholder pack, which indicates we're
8655      in the context of a introduction list.  In that case we want
8656      to match this pack to the single placeholder.  */
8657   else if (arg_idx < nargs
8658            && TREE_CODE (TREE_VEC_ELT (inner_args, arg_idx)) == WILDCARD_DECL
8659            && WILDCARD_PACK_P (TREE_VEC_ELT (inner_args, arg_idx)))
8660     {
8661       nargs = arg_idx + 1;
8662       packed_args = make_tree_vec (1);
8663     }
8664   else
8665     packed_args = make_tree_vec (nargs - arg_idx);
8666 
8667   /* Convert the remaining arguments, which will be a part of the
8668      parameter pack "parm".  */
8669   int first_pack_arg = arg_idx;
8670   for (; arg_idx < nargs; ++arg_idx)
8671     {
8672       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
8673       tree actual_parm = TREE_VALUE (parm);
8674       int pack_idx = arg_idx - first_pack_arg;
8675 
8676       if (packed_parms)
8677         {
8678 	  /* Once we've packed as many args as we have types, stop.  */
8679 	  if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
8680 	    break;
8681 	  else if (PACK_EXPANSION_P (arg))
8682 	    /* We don't know how many args we have yet, just
8683 	       use the unconverted ones for now.  */
8684 	    return NULL_TREE;
8685 	  else
8686 	    actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
8687         }
8688 
8689       if (arg == error_mark_node)
8690 	{
8691 	  if (complain & tf_error)
8692 	    error ("template argument %d is invalid", arg_idx + 1);
8693 	}
8694       else
8695 	arg = convert_template_argument (actual_parm,
8696 					 arg, new_args, complain, parm_idx,
8697 					 in_decl);
8698       if (arg == error_mark_node)
8699         (*lost)++;
8700       TREE_VEC_ELT (packed_args, pack_idx) = arg;
8701     }
8702 
8703   if (arg_idx - first_pack_arg < TREE_VEC_LENGTH (packed_args)
8704       && TREE_VEC_LENGTH (packed_args) > 0)
8705     {
8706       if (complain & tf_error)
8707 	error ("wrong number of template arguments (%d, should be %d)",
8708 	       arg_idx - first_pack_arg, TREE_VEC_LENGTH (packed_args));
8709       return error_mark_node;
8710     }
8711 
8712   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
8713       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
8714     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
8715   else
8716     {
8717       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
8718       TREE_CONSTANT (argument_pack) = 1;
8719     }
8720 
8721   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
8722   if (CHECKING_P)
8723     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
8724 					 TREE_VEC_LENGTH (packed_args));
8725   return argument_pack;
8726 }
8727 
8728 /* Returns the number of pack expansions in the template argument vector
8729    ARGS.  */
8730 
8731 static int
pack_expansion_args_count(tree args)8732 pack_expansion_args_count (tree args)
8733 {
8734   int i;
8735   int count = 0;
8736   if (args)
8737     for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
8738       {
8739 	tree elt = TREE_VEC_ELT (args, i);
8740 	if (elt && PACK_EXPANSION_P (elt))
8741 	  ++count;
8742       }
8743   return count;
8744 }
8745 
8746 /* Convert all template arguments to their appropriate types, and
8747    return a vector containing the innermost resulting template
8748    arguments.  If any error occurs, return error_mark_node. Error and
8749    warning messages are issued under control of COMPLAIN.
8750 
8751    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
8752    for arguments not specified in ARGS.  Otherwise, if
8753    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
8754    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
8755    USE_DEFAULT_ARGS is false, then all arguments must be specified in
8756    ARGS.  */
8757 
8758 static tree
coerce_template_parms(tree parms,tree args,tree in_decl,tsubst_flags_t complain,bool require_all_args,bool use_default_args)8759 coerce_template_parms (tree parms,
8760 		       tree args,
8761 		       tree in_decl,
8762 		       tsubst_flags_t complain,
8763 		       bool require_all_args,
8764 		       bool use_default_args)
8765 {
8766   int nparms, nargs, parm_idx, arg_idx, lost = 0;
8767   tree orig_inner_args;
8768   tree inner_args;
8769   tree new_args;
8770   tree new_inner_args;
8771 
8772   /* When used as a boolean value, indicates whether this is a
8773      variadic template parameter list. Since it's an int, we can also
8774      subtract it from nparms to get the number of non-variadic
8775      parameters.  */
8776   int variadic_p = 0;
8777   int variadic_args_p = 0;
8778   int post_variadic_parms = 0;
8779 
8780   /* Adjustment to nparms for fixed parameter packs.  */
8781   int fixed_pack_adjust = 0;
8782   int fixed_packs = 0;
8783   int missing = 0;
8784 
8785   /* Likewise for parameters with default arguments.  */
8786   int default_p = 0;
8787 
8788   if (args == error_mark_node)
8789     return error_mark_node;
8790 
8791   nparms = TREE_VEC_LENGTH (parms);
8792 
8793   /* Determine if there are any parameter packs or default arguments.  */
8794   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
8795     {
8796       tree parm = TREE_VEC_ELT (parms, parm_idx);
8797       if (variadic_p)
8798 	++post_variadic_parms;
8799       if (template_parameter_pack_p (TREE_VALUE (parm)))
8800 	++variadic_p;
8801       if (TREE_PURPOSE (parm))
8802 	++default_p;
8803     }
8804 
8805   inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
8806   /* If there are no parameters that follow a parameter pack, we need to
8807      expand any argument packs so that we can deduce a parameter pack from
8808      some non-packed args followed by an argument pack, as in variadic85.C.
8809      If there are such parameters, we need to leave argument packs intact
8810      so the arguments are assigned properly.  This can happen when dealing
8811      with a nested class inside a partial specialization of a class
8812      template, as in variadic92.C, or when deducing a template parameter pack
8813      from a sub-declarator, as in variadic114.C.  */
8814   if (!post_variadic_parms)
8815     inner_args = expand_template_argument_pack (inner_args);
8816 
8817   /* Count any pack expansion args.  */
8818   variadic_args_p = pack_expansion_args_count (inner_args);
8819 
8820   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8821   if ((nargs - variadic_args_p > nparms && !variadic_p)
8822       || (nargs < nparms - variadic_p
8823 	  && require_all_args
8824 	  && !variadic_args_p
8825 	  && (!use_default_args
8826 	      || (TREE_VEC_ELT (parms, nargs) != error_mark_node
8827                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
8828     {
8829     bad_nargs:
8830       if (complain & tf_error)
8831 	{
8832           if (variadic_p || default_p)
8833             {
8834               nparms -= variadic_p + default_p;
8835 	      error ("wrong number of template arguments "
8836 		     "(%d, should be at least %d)", nargs, nparms);
8837             }
8838 	  else
8839 	     error ("wrong number of template arguments "
8840 		    "(%d, should be %d)", nargs, nparms);
8841 
8842 	  if (in_decl)
8843 	    inform (DECL_SOURCE_LOCATION (in_decl),
8844 		    "provided for %qD", in_decl);
8845 	}
8846 
8847       return error_mark_node;
8848     }
8849   /* We can't pass a pack expansion to a non-pack parameter of an alias
8850      template (DR 1430).  */
8851   else if (in_decl
8852 	   && (DECL_ALIAS_TEMPLATE_P (in_decl)
8853 	       || concept_definition_p (in_decl))
8854 	   && variadic_args_p
8855 	   && nargs - variadic_args_p < nparms - variadic_p)
8856     {
8857       if (complain & tf_error)
8858 	{
8859 	  for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
8860 	    {
8861 	      tree arg = TREE_VEC_ELT (inner_args, i);
8862 	      tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
8863 
8864 	      if (PACK_EXPANSION_P (arg)
8865 		  && !template_parameter_pack_p (parm))
8866 		{
8867 		  if (DECL_ALIAS_TEMPLATE_P (in_decl))
8868 		    error_at (location_of (arg),
8869 			      "pack expansion argument for non-pack parameter "
8870 			      "%qD of alias template %qD", parm, in_decl);
8871 		  else
8872 		    error_at (location_of (arg),
8873 			      "pack expansion argument for non-pack parameter "
8874 			      "%qD of concept %qD", parm, in_decl);
8875 		  inform (DECL_SOURCE_LOCATION (parm), "declared here");
8876 		  goto found;
8877 		}
8878 	    }
8879 	  gcc_unreachable ();
8880 	found:;
8881 	}
8882       return error_mark_node;
8883     }
8884 
8885   /* We need to evaluate the template arguments, even though this
8886      template-id may be nested within a "sizeof".  */
8887   cp_evaluated ev;
8888 
8889   new_inner_args = make_tree_vec (nparms);
8890   new_args = add_outermost_template_args (args, new_inner_args);
8891   int pack_adjust = 0;
8892   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
8893     {
8894       tree arg;
8895       tree parm;
8896 
8897       /* Get the Ith template parameter.  */
8898       parm = TREE_VEC_ELT (parms, parm_idx);
8899 
8900       if (parm == error_mark_node)
8901 	{
8902 	  TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
8903 	  continue;
8904 	}
8905 
8906       /* Calculate the next argument.  */
8907       if (arg_idx < nargs)
8908 	arg = TREE_VEC_ELT (inner_args, arg_idx);
8909       else
8910 	arg = NULL_TREE;
8911 
8912       if (template_parameter_pack_p (TREE_VALUE (parm))
8913 	  && (arg || require_all_args || !(complain & tf_partial))
8914 	  && !(arg && ARGUMENT_PACK_P (arg)))
8915         {
8916 	  /* Some arguments will be placed in the
8917 	     template parameter pack PARM.  */
8918 	  arg = coerce_template_parameter_pack (parms, parm_idx, args,
8919 						inner_args, arg_idx,
8920 						new_args, &lost,
8921 						in_decl, complain);
8922 
8923 	  if (arg == NULL_TREE)
8924 	    {
8925 	      /* We don't know how many args we have yet, just use the
8926 		 unconverted (and still packed) ones for now.  */
8927 	      new_inner_args = orig_inner_args;
8928 	      arg_idx = nargs;
8929 	      break;
8930 	    }
8931 
8932           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
8933 
8934           /* Store this argument.  */
8935           if (arg == error_mark_node)
8936 	    {
8937 	      lost++;
8938 	      /* We are done with all of the arguments.  */
8939 	      arg_idx = nargs;
8940 	      break;
8941 	    }
8942 	  else
8943 	    {
8944 	      pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
8945 	      arg_idx += pack_adjust;
8946 	      if (fixed_parameter_pack_p (TREE_VALUE (parm)))
8947 		{
8948 		  ++fixed_packs;
8949 		  fixed_pack_adjust += pack_adjust;
8950 		}
8951 	    }
8952 
8953           continue;
8954         }
8955       else if (arg)
8956 	{
8957           if (PACK_EXPANSION_P (arg))
8958             {
8959 	      /* "If every valid specialization of a variadic template
8960 		 requires an empty template parameter pack, the template is
8961 		 ill-formed, no diagnostic required."  So check that the
8962 		 pattern works with this parameter.  */
8963 	      tree pattern = PACK_EXPANSION_PATTERN (arg);
8964 	      tree conv = convert_template_argument (TREE_VALUE (parm),
8965 						     pattern, new_args,
8966 						     complain, parm_idx,
8967 						     in_decl);
8968 	      if (conv == error_mark_node)
8969 		{
8970 		  if (complain & tf_error)
8971 		    inform (input_location, "so any instantiation with a "
8972 			    "non-empty parameter pack would be ill-formed");
8973 		  ++lost;
8974 		}
8975 	      else if (TYPE_P (conv) && !TYPE_P (pattern))
8976 		/* Recover from missing typename.  */
8977 		TREE_VEC_ELT (inner_args, arg_idx)
8978 		  = make_pack_expansion (conv, complain);
8979 
8980               /* We don't know how many args we have yet, just
8981                  use the unconverted ones for now.  */
8982               new_inner_args = inner_args;
8983 	      arg_idx = nargs;
8984               break;
8985             }
8986         }
8987       else if (require_all_args)
8988 	{
8989 	  /* There must be a default arg in this case.  */
8990 	  arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
8991 				     complain, in_decl);
8992 	  /* The position of the first default template argument,
8993 	     is also the number of non-defaulted arguments in NEW_INNER_ARGS.
8994 	     Record that.  */
8995 	  if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
8996 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
8997 						 arg_idx - pack_adjust);
8998 	}
8999       else
9000 	break;
9001 
9002       if (arg == error_mark_node)
9003 	{
9004 	  if (complain & tf_error)
9005 	    error ("template argument %d is invalid", arg_idx + 1);
9006 	}
9007       else if (!arg)
9008 	{
9009 	  /* This can occur if there was an error in the template
9010 	     parameter list itself (which we would already have
9011 	     reported) that we are trying to recover from, e.g., a class
9012 	     template with a parameter list such as
9013 	     template<typename..., typename> (cpp0x/variadic150.C).  */
9014 	  ++lost;
9015 
9016 	  /* This can also happen with a fixed parameter pack (71834).  */
9017 	  if (arg_idx >= nargs)
9018 	    ++missing;
9019 	}
9020       else
9021 	arg = convert_template_argument (TREE_VALUE (parm),
9022 					 arg, new_args, complain,
9023                                          parm_idx, in_decl);
9024 
9025       if (arg == error_mark_node)
9026 	lost++;
9027 
9028       TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
9029     }
9030 
9031   if (missing || arg_idx < nargs - variadic_args_p)
9032     {
9033       /* If we had fixed parameter packs, we didn't know how many arguments we
9034 	 actually needed earlier; now we do.  */
9035       nparms += fixed_pack_adjust;
9036       variadic_p -= fixed_packs;
9037       goto bad_nargs;
9038     }
9039 
9040   if (arg_idx < nargs)
9041     {
9042       /* We had some pack expansion arguments that will only work if the packs
9043 	 are empty, but wait until instantiation time to complain.
9044 	 See variadic-ttp3.C.  */
9045 
9046       /* Except that we can't provide empty packs to alias templates or
9047          concepts when there are no corresponding parameters. Basically,
9048          we can get here with this:
9049 
9050              template<typename T> concept C = true;
9051 
9052              template<typename... Args>
9053 	       requires C<Args...>
9054              void f();
9055 
9056          When parsing C<Args...>, we try to form a concept check of
9057          C<?, Args...>. Without the extra check for substituting an empty
9058          pack past the last parameter, we can accept the check as valid.
9059 
9060          FIXME: This may be valid for alias templates (but I doubt it).
9061 
9062          FIXME: The error could be better also.   */
9063       if (in_decl && concept_definition_p (in_decl))
9064 	{
9065 	  if (complain & tf_error)
9066 	    error_at (location_of (TREE_VEC_ELT (args, arg_idx)),
9067 		      "too many arguments");
9068 	  return error_mark_node;
9069 	}
9070 
9071       int len = nparms + (nargs - arg_idx);
9072       tree args = make_tree_vec (len);
9073       int i = 0;
9074       for (; i < nparms; ++i)
9075 	TREE_VEC_ELT (args, i) = TREE_VEC_ELT (new_inner_args, i);
9076       for (; i < len; ++i, ++arg_idx)
9077 	TREE_VEC_ELT (args, i) = TREE_VEC_ELT (inner_args,
9078 					       arg_idx - pack_adjust);
9079       new_inner_args = args;
9080     }
9081 
9082   if (lost)
9083     {
9084       gcc_assert (!(complain & tf_error) || seen_error ());
9085       return error_mark_node;
9086     }
9087 
9088   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
9089     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
9090 					 TREE_VEC_LENGTH (new_inner_args));
9091 
9092   return new_inner_args;
9093 }
9094 
9095 /* Convert all template arguments to their appropriate types, and
9096    return a vector containing the innermost resulting template
9097    arguments.  If any error occurs, return error_mark_node. Error and
9098    warning messages are not issued.
9099 
9100    Note that no function argument deduction is performed, and default
9101    arguments are used to fill in unspecified arguments. */
9102 tree
coerce_template_parms(tree parms,tree args,tree in_decl)9103 coerce_template_parms (tree parms, tree args, tree in_decl)
9104 {
9105   return coerce_template_parms (parms, args, in_decl, tf_none, true, true);
9106 }
9107 
9108 /* Convert all template arguments to their appropriate type, and
9109    instantiate default arguments as needed. This returns a vector
9110    containing the innermost resulting template arguments, or
9111    error_mark_node if unsuccessful.  */
9112 tree
coerce_template_parms(tree parms,tree args,tree in_decl,tsubst_flags_t complain)9113 coerce_template_parms (tree parms, tree args, tree in_decl,
9114                        tsubst_flags_t complain)
9115 {
9116   return coerce_template_parms (parms, args, in_decl, complain, true, true);
9117 }
9118 
9119 /* Like coerce_template_parms.  If PARMS represents all template
9120    parameters levels, this function returns a vector of vectors
9121    representing all the resulting argument levels.  Note that in this
9122    case, only the innermost arguments are coerced because the
9123    outermost ones are supposed to have been coerced already.
9124 
9125    Otherwise, if PARMS represents only (the innermost) vector of
9126    parameters, this function returns a vector containing just the
9127    innermost resulting arguments.  */
9128 
9129 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)9130 coerce_innermost_template_parms (tree parms,
9131 				  tree args,
9132 				  tree in_decl,
9133 				  tsubst_flags_t complain,
9134 				  bool require_all_args,
9135 				  bool use_default_args)
9136 {
9137   int parms_depth = TMPL_PARMS_DEPTH (parms);
9138   int args_depth = TMPL_ARGS_DEPTH (args);
9139   tree coerced_args;
9140 
9141   if (parms_depth > 1)
9142     {
9143       coerced_args = make_tree_vec (parms_depth);
9144       tree level;
9145       int cur_depth;
9146 
9147       for (level = parms, cur_depth = parms_depth;
9148 	   parms_depth > 0 && level != NULL_TREE;
9149 	   level = TREE_CHAIN (level), --cur_depth)
9150 	{
9151 	  tree l;
9152 	  if (cur_depth == args_depth)
9153 	    l = coerce_template_parms (TREE_VALUE (level),
9154 				       args, in_decl, complain,
9155 				       require_all_args,
9156 				       use_default_args);
9157 	  else
9158 	    l = TMPL_ARGS_LEVEL (args, cur_depth);
9159 
9160 	  if (l == error_mark_node)
9161 	    return error_mark_node;
9162 
9163 	  SET_TMPL_ARGS_LEVEL (coerced_args, cur_depth, l);
9164 	}
9165     }
9166   else
9167     coerced_args = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parms),
9168 					  args, in_decl, complain,
9169 					  require_all_args,
9170 					  use_default_args);
9171   return coerced_args;
9172 }
9173 
9174 /* Returns true if T is a wrapper to make a C++20 template parameter
9175    object const.  */
9176 
9177 static bool
class_nttp_const_wrapper_p(tree t)9178 class_nttp_const_wrapper_p (tree t)
9179 {
9180   if (cxx_dialect < cxx20)
9181     return false;
9182   return (TREE_CODE (t) == VIEW_CONVERT_EXPR
9183 	  && CP_TYPE_CONST_P (TREE_TYPE (t))
9184 	  && TREE_CODE (TREE_OPERAND (t, 0)) == TEMPLATE_PARM_INDEX);
9185 }
9186 
9187 /* Returns 1 if template args OT and NT are equivalent.  */
9188 
9189 int
template_args_equal(tree ot,tree nt,bool partial_order)9190 template_args_equal (tree ot, tree nt, bool partial_order /* = false */)
9191 {
9192   if (nt == ot)
9193     return 1;
9194   if (nt == NULL_TREE || ot == NULL_TREE)
9195     return false;
9196   if (nt == any_targ_node || ot == any_targ_node)
9197     return true;
9198 
9199   if (class_nttp_const_wrapper_p (nt))
9200     nt = TREE_OPERAND (nt, 0);
9201   if (class_nttp_const_wrapper_p (ot))
9202     ot = TREE_OPERAND (ot, 0);
9203 
9204   /* DR 1558: Don't treat an alias template specialization with dependent
9205      arguments as equivalent to its underlying type when used as a template
9206      argument; we need them to be distinct so that we substitute into the
9207      specialization arguments at instantiation time.  And aliases can't be
9208      equivalent without being ==, so we don't need to look any deeper.
9209 
9210      During partial ordering, however, we need to treat them normally so we can
9211      order uses of the same alias with different cv-qualification (79960).  */
9212   auto cso = make_temp_override (comparing_dependent_aliases);
9213   if (!partial_order)
9214     ++comparing_dependent_aliases;
9215 
9216   if (TREE_CODE (nt) == TREE_VEC || TREE_CODE (ot) == TREE_VEC)
9217     /* For member templates */
9218     return TREE_CODE (ot) == TREE_CODE (nt) && comp_template_args (ot, nt);
9219   else if (PACK_EXPANSION_P (ot) || PACK_EXPANSION_P (nt))
9220     return (PACK_EXPANSION_P (ot) && PACK_EXPANSION_P (nt)
9221 	    && template_args_equal (PACK_EXPANSION_PATTERN (ot),
9222 				    PACK_EXPANSION_PATTERN (nt))
9223 	    && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
9224 				    PACK_EXPANSION_EXTRA_ARGS (nt)));
9225   else if (ARGUMENT_PACK_P (ot) || ARGUMENT_PACK_P (nt))
9226     return cp_tree_equal (ot, nt);
9227   else if (TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
9228     gcc_unreachable ();
9229   else if (TYPE_P (nt) || TYPE_P (ot))
9230     {
9231       if (!(TYPE_P (nt) && TYPE_P (ot)))
9232 	return false;
9233       return same_type_p (ot, nt);
9234     }
9235   else
9236     {
9237       /* Try to treat a template non-type argument that has been converted
9238 	 to the parameter type as equivalent to one that hasn't yet.  */
9239       for (enum tree_code code1 = TREE_CODE (ot);
9240 	   CONVERT_EXPR_CODE_P (code1)
9241 	     || code1 == NON_LVALUE_EXPR;
9242 	   code1 = TREE_CODE (ot))
9243 	ot = TREE_OPERAND (ot, 0);
9244 
9245       for (enum tree_code code2 = TREE_CODE (nt);
9246 	   CONVERT_EXPR_CODE_P (code2)
9247 	     || code2 == NON_LVALUE_EXPR;
9248 	   code2 = TREE_CODE (nt))
9249 	nt = TREE_OPERAND (nt, 0);
9250 
9251       return cp_tree_equal (ot, nt);
9252     }
9253 }
9254 
9255 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
9256    template arguments.  Returns 0 otherwise, and updates OLDARG_PTR and
9257    NEWARG_PTR with the offending arguments if they are non-NULL.  */
9258 
9259 int
comp_template_args(tree oldargs,tree newargs,tree * oldarg_ptr,tree * newarg_ptr,bool partial_order)9260 comp_template_args (tree oldargs, tree newargs,
9261 		    tree *oldarg_ptr, tree *newarg_ptr,
9262 		    bool partial_order)
9263 {
9264   int i;
9265 
9266   if (oldargs == newargs)
9267     return 1;
9268 
9269   if (!oldargs || !newargs)
9270     return 0;
9271 
9272   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
9273     return 0;
9274 
9275   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
9276     {
9277       tree nt = TREE_VEC_ELT (newargs, i);
9278       tree ot = TREE_VEC_ELT (oldargs, i);
9279 
9280       if (! template_args_equal (ot, nt, partial_order))
9281 	{
9282 	  if (oldarg_ptr != NULL)
9283 	    *oldarg_ptr = ot;
9284 	  if (newarg_ptr != NULL)
9285 	    *newarg_ptr = nt;
9286 	  return 0;
9287 	}
9288     }
9289   return 1;
9290 }
9291 
9292 inline bool
comp_template_args_porder(tree oargs,tree nargs)9293 comp_template_args_porder (tree oargs, tree nargs)
9294 {
9295   return comp_template_args (oargs, nargs, NULL, NULL, true);
9296 }
9297 
9298 /* Implement a freelist interface for objects of type T.
9299 
9300    Head is a separate object, rather than a regular member, so that we
9301    can define it as a GTY deletable pointer, which is highly
9302    desirable.  A data member could be declared that way, but then the
9303    containing object would implicitly get GTY((user)), which would
9304    prevent us from instantiating freelists as global objects.
9305    Although this way we can create freelist global objects, they're
9306    such thin wrappers that instantiating temporaries at every use
9307    loses nothing and saves permanent storage for the freelist object.
9308 
9309    Member functions next, anew, poison and reinit have default
9310    implementations that work for most of the types we're interested
9311    in, but if they don't work for some type, they should be explicitly
9312    specialized.  See the comments before them for requirements, and
9313    the example specializations for the tree_list_freelist.  */
9314 template <typename T>
9315 class freelist
9316 {
9317   /* Return the next object in a chain.  We could just do type
9318      punning, but if we access the object with its underlying type, we
9319      avoid strict-aliasing trouble.  This needs only work between
9320      poison and reinit.  */
next(T * obj)9321   static T *&next (T *obj) { return obj->next; }
9322 
9323   /* Return a newly allocated, uninitialized or minimally-initialized
9324      object of type T.  Any initialization performed by anew should
9325      either remain across the life of the object and the execution of
9326      poison, or be redone by reinit.  */
anew()9327   static T *anew () { return ggc_alloc<T> (); }
9328 
9329   /* Optionally scribble all over the bits holding the object, so that
9330      they become (mostly?) uninitialized memory.  This is called while
9331      preparing to make the object part of the free list.  */
poison(T * obj)9332   static void poison (T *obj) {
9333     T *p ATTRIBUTE_UNUSED = obj;
9334     T **q ATTRIBUTE_UNUSED = &next (obj);
9335 
9336 #ifdef ENABLE_GC_CHECKING
9337     /* Poison the data, to indicate the data is garbage.  */
9338     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, sizeof (*p)));
9339     memset (p, 0xa5, sizeof (*p));
9340 #endif
9341     /* Let valgrind know the object is free.  */
9342     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, sizeof (*p)));
9343 
9344     /* Let valgrind know the next portion of the object is available,
9345        but uninitialized.  */
9346     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9347   }
9348 
9349   /* Bring an object that underwent at least one lifecycle after anew
9350      and before the most recent free and poison, back to a usable
9351      state, reinitializing whatever is needed for it to be
9352      functionally equivalent to an object just allocated and returned
9353      by anew.  This may poison or clear the next field, used by
9354      freelist housekeeping after poison was called.  */
reinit(T * obj)9355   static void reinit (T *obj) {
9356     T **q ATTRIBUTE_UNUSED = &next (obj);
9357 
9358 #ifdef ENABLE_GC_CHECKING
9359     memset (q, 0xa5, sizeof (*q));
9360 #endif
9361     /* Let valgrind know the entire object is available, but
9362        uninitialized.  */
9363     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (*obj)));
9364   }
9365 
9366   /* Reference a GTY-deletable pointer that points to the first object
9367      in the free list proper.  */
9368   T *&head;
9369 public:
9370   /* Construct a freelist object chaining objects off of HEAD.  */
freelist(T * & head)9371   freelist (T *&head) : head(head) {}
9372 
9373   /* Add OBJ to the free object list.  The former head becomes OBJ's
9374      successor.  */
free(T * obj)9375   void free (T *obj)
9376   {
9377     poison (obj);
9378     next (obj) = head;
9379     head = obj;
9380   }
9381 
9382   /* Take an object from the free list, if one is available, or
9383      allocate a new one.  Objects taken from the free list should be
9384      regarded as filled with garbage, except for bits that are
9385      configured to be preserved across free and alloc.  */
alloc()9386   T *alloc ()
9387   {
9388     if (head)
9389       {
9390 	T *obj = head;
9391 	head = next (head);
9392 	reinit (obj);
9393 	return obj;
9394       }
9395     else
9396       return anew ();
9397   }
9398 };
9399 
9400 /* Explicitly specialize the interfaces for freelist<tree_node>: we
9401    want to allocate a TREE_LIST using the usual interface, and ensure
9402    TREE_CHAIN remains functional.  Alas, we have to duplicate a bit of
9403    build_tree_list logic in reinit, so this could go out of sync.  */
9404 template <>
9405 inline tree &
next(tree obj)9406 freelist<tree_node>::next (tree obj)
9407 {
9408   return TREE_CHAIN (obj);
9409 }
9410 template <>
9411 inline tree
anew()9412 freelist<tree_node>::anew ()
9413 {
9414   return build_tree_list (NULL, NULL);
9415 }
9416 template <>
9417 inline void
poison(tree obj ATTRIBUTE_UNUSED)9418 freelist<tree_node>::poison (tree obj ATTRIBUTE_UNUSED)
9419 {
9420   int size ATTRIBUTE_UNUSED = sizeof (tree_list);
9421   tree p ATTRIBUTE_UNUSED = obj;
9422   tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9423   tree *q ATTRIBUTE_UNUSED = &next (obj);
9424 
9425 #ifdef ENABLE_GC_CHECKING
9426   gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9427 
9428   /* Poison the data, to indicate the data is garbage.  */
9429   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, size));
9430   memset (p, 0xa5, size);
9431 #endif
9432   /* Let valgrind know the object is free.  */
9433   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, size));
9434   /* But we still want to use the TREE_CODE and TREE_CHAIN parts.  */
9435   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9436   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9437 
9438 #ifdef ENABLE_GC_CHECKING
9439   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (b, sizeof (*b)));
9440   /* Keep TREE_CHAIN functional.  */
9441   TREE_SET_CODE (obj, TREE_LIST);
9442 #else
9443   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9444 #endif
9445 }
9446 template <>
9447 inline void
reinit(tree obj ATTRIBUTE_UNUSED)9448 freelist<tree_node>::reinit (tree obj ATTRIBUTE_UNUSED)
9449 {
9450   tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9451 
9452 #ifdef ENABLE_GC_CHECKING
9453   gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9454   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9455   memset (obj, 0, sizeof (tree_list));
9456 #endif
9457 
9458   /* Let valgrind know the entire object is available, but
9459      uninitialized.  */
9460   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9461 
9462 #ifdef ENABLE_GC_CHECKING
9463   TREE_SET_CODE (obj, TREE_LIST);
9464 #else
9465   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9466 #endif
9467 }
9468 
9469 /* Point to the first object in the TREE_LIST freelist.  */
9470 static GTY((deletable)) tree tree_list_freelist_head;
9471 /* Return the/an actual TREE_LIST freelist.  */
9472 static inline freelist<tree_node>
tree_list_freelist()9473 tree_list_freelist ()
9474 {
9475   return tree_list_freelist_head;
9476 }
9477 
9478 /* Point to the first object in the tinst_level freelist.  */
9479 static GTY((deletable)) tinst_level *tinst_level_freelist_head;
9480 /* Return the/an actual tinst_level freelist.  */
9481 static inline freelist<tinst_level>
tinst_level_freelist()9482 tinst_level_freelist ()
9483 {
9484   return tinst_level_freelist_head;
9485 }
9486 
9487 /* Point to the first object in the pending_template freelist.  */
9488 static GTY((deletable)) pending_template *pending_template_freelist_head;
9489 /* Return the/an actual pending_template freelist.  */
9490 static inline freelist<pending_template>
pending_template_freelist()9491 pending_template_freelist ()
9492 {
9493   return pending_template_freelist_head;
9494 }
9495 
9496 /* Build the TREE_LIST object out of a split list, store it
9497    permanently, and return it.  */
9498 tree
to_list()9499 tinst_level::to_list ()
9500 {
9501   gcc_assert (split_list_p ());
9502   tree ret = tree_list_freelist ().alloc ();
9503   TREE_PURPOSE (ret) = tldcl;
9504   TREE_VALUE (ret) = targs;
9505   tldcl = ret;
9506   targs = NULL;
9507   gcc_assert (tree_list_p ());
9508   return ret;
9509 }
9510 
9511 const unsigned short tinst_level::refcount_infinity;
9512 
9513 /* Increment OBJ's refcount unless it is already infinite.  */
9514 static tinst_level *
inc_refcount_use(tinst_level * obj)9515 inc_refcount_use (tinst_level *obj)
9516 {
9517   if (obj && obj->refcount != tinst_level::refcount_infinity)
9518     ++obj->refcount;
9519   return obj;
9520 }
9521 
9522 /* Release storage for OBJ and node, if it's a TREE_LIST.  */
9523 void
free(tinst_level * obj)9524 tinst_level::free (tinst_level *obj)
9525 {
9526   if (obj->tree_list_p ())
9527     tree_list_freelist ().free (obj->get_node ());
9528   tinst_level_freelist ().free (obj);
9529 }
9530 
9531 /* Decrement OBJ's refcount if not infinite.  If it reaches zero, release
9532    OBJ's DECL and OBJ, and start over with the tinst_level object that
9533    used to be referenced by OBJ's NEXT.  */
9534 static void
dec_refcount_use(tinst_level * obj)9535 dec_refcount_use (tinst_level *obj)
9536 {
9537   while (obj
9538 	 && obj->refcount != tinst_level::refcount_infinity
9539 	 && !--obj->refcount)
9540     {
9541       tinst_level *next = obj->next;
9542       tinst_level::free (obj);
9543       obj = next;
9544     }
9545 }
9546 
9547 /* Modify PTR so that it points to OBJ, adjusting the refcounts of OBJ
9548    and of the former PTR.  Omitting the second argument is equivalent
9549    to passing (T*)NULL; this is allowed because passing the
9550    zero-valued integral constant NULL confuses type deduction and/or
9551    overload resolution.  */
9552 template <typename T>
9553 static void
9554 set_refcount_ptr (T *& ptr, T *obj = NULL)
9555 {
9556   T *save = ptr;
9557   ptr = inc_refcount_use (obj);
9558   dec_refcount_use (save);
9559 }
9560 
9561 static void
add_pending_template(tree d)9562 add_pending_template (tree d)
9563 {
9564   tree ti = (TYPE_P (d)
9565 	     ? CLASSTYPE_TEMPLATE_INFO (d)
9566 	     : DECL_TEMPLATE_INFO (d));
9567   struct pending_template *pt;
9568   int level;
9569 
9570   if (TI_PENDING_TEMPLATE_FLAG (ti))
9571     return;
9572 
9573   /* We are called both from instantiate_decl, where we've already had a
9574      tinst_level pushed, and instantiate_template, where we haven't.
9575      Compensate.  */
9576   gcc_assert (TREE_CODE (d) != TREE_LIST);
9577   level = !current_tinst_level
9578     || current_tinst_level->maybe_get_node () != d;
9579 
9580   if (level)
9581     push_tinst_level (d);
9582 
9583   pt = pending_template_freelist ().alloc ();
9584   pt->next = NULL;
9585   pt->tinst = NULL;
9586   set_refcount_ptr (pt->tinst, current_tinst_level);
9587   if (last_pending_template)
9588     last_pending_template->next = pt;
9589   else
9590     pending_templates = pt;
9591 
9592   last_pending_template = pt;
9593 
9594   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
9595 
9596   if (level)
9597     pop_tinst_level ();
9598 }
9599 
9600 
9601 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
9602    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
9603    documentation for TEMPLATE_ID_EXPR.  */
9604 
9605 tree
lookup_template_function(tree fns,tree arglist)9606 lookup_template_function (tree fns, tree arglist)
9607 {
9608   if (fns == error_mark_node || arglist == error_mark_node)
9609     return error_mark_node;
9610 
9611   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
9612 
9613   if (!is_overloaded_fn (fns) && !identifier_p (fns))
9614     {
9615       error ("%q#D is not a function template", fns);
9616       return error_mark_node;
9617     }
9618 
9619   if (BASELINK_P (fns))
9620     {
9621       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
9622 					 unknown_type_node,
9623 					 BASELINK_FUNCTIONS (fns),
9624 					 arglist);
9625       return fns;
9626     }
9627 
9628   return build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, arglist);
9629 }
9630 
9631 /* Within the scope of a template class S<T>, the name S gets bound
9632    (in build_self_reference) to a TYPE_DECL for the class, not a
9633    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
9634    or one of its enclosing classes, and that type is a template,
9635    return the associated TEMPLATE_DECL.  Otherwise, the original
9636    DECL is returned.
9637 
9638    Also handle the case when DECL is a TREE_LIST of ambiguous
9639    injected-class-names from different bases.  */
9640 
9641 tree
maybe_get_template_decl_from_type_decl(tree decl)9642 maybe_get_template_decl_from_type_decl (tree decl)
9643 {
9644   if (decl == NULL_TREE)
9645     return decl;
9646 
9647   /* DR 176: A lookup that finds an injected-class-name (10.2
9648      [class.member.lookup]) can result in an ambiguity in certain cases
9649      (for example, if it is found in more than one base class). If all of
9650      the injected-class-names that are found refer to specializations of
9651      the same class template, and if the name is followed by a
9652      template-argument-list, the reference refers to the class template
9653      itself and not a specialization thereof, and is not ambiguous.  */
9654   if (TREE_CODE (decl) == TREE_LIST)
9655     {
9656       tree t, tmpl = NULL_TREE;
9657       for (t = decl; t; t = TREE_CHAIN (t))
9658 	{
9659 	  tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
9660 	  if (!tmpl)
9661 	    tmpl = elt;
9662 	  else if (tmpl != elt)
9663 	    break;
9664 	}
9665       if (tmpl && t == NULL_TREE)
9666 	return tmpl;
9667       else
9668 	return decl;
9669     }
9670 
9671   return (decl != NULL_TREE
9672 	  && DECL_SELF_REFERENCE_P (decl)
9673 	  && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
9674     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
9675 }
9676 
9677 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
9678    parameters, find the desired type.
9679 
9680    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
9681 
9682    IN_DECL, if non-NULL, is the template declaration we are trying to
9683    instantiate.
9684 
9685    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
9686    the class we are looking up.
9687 
9688    Issue error and warning messages under control of COMPLAIN.
9689 
9690    If the template class is really a local class in a template
9691    function, then the FUNCTION_CONTEXT is the function in which it is
9692    being instantiated.
9693 
9694    ??? Note that this function is currently called *twice* for each
9695    template-id: the first time from the parser, while creating the
9696    incomplete type (finish_template_type), and the second type during the
9697    real instantiation (instantiate_template_class). This is surely something
9698    that we want to avoid. It also causes some problems with argument
9699    coercion (see convert_nontype_argument for more information on this).  */
9700 
9701 static tree
lookup_template_class_1(tree d1,tree arglist,tree in_decl,tree context,int entering_scope,tsubst_flags_t complain)9702 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
9703 			 int entering_scope, tsubst_flags_t complain)
9704 {
9705   tree templ = NULL_TREE, parmlist;
9706   tree t;
9707   spec_entry **slot;
9708   spec_entry *entry;
9709   spec_entry elt;
9710   hashval_t hash;
9711 
9712   if (identifier_p (d1))
9713     {
9714       tree value = innermost_non_namespace_value (d1);
9715       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
9716 	templ = value;
9717       else
9718 	{
9719 	  if (context)
9720 	    push_decl_namespace (context);
9721 	  templ = lookup_name (d1);
9722 	  templ = maybe_get_template_decl_from_type_decl (templ);
9723 	  if (context)
9724 	    pop_decl_namespace ();
9725 	}
9726       if (templ)
9727 	context = DECL_CONTEXT (templ);
9728     }
9729   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
9730     {
9731       tree type = TREE_TYPE (d1);
9732 
9733       /* If we are declaring a constructor, say A<T>::A<T>, we will get
9734 	 an implicit typename for the second A.  Deal with it.  */
9735       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
9736 	type = TREE_TYPE (type);
9737 
9738       if (CLASSTYPE_TEMPLATE_INFO (type))
9739 	{
9740 	  templ = CLASSTYPE_TI_TEMPLATE (type);
9741 	  d1 = DECL_NAME (templ);
9742 	}
9743     }
9744   else if (TREE_CODE (d1) == ENUMERAL_TYPE
9745 	   || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
9746     {
9747       templ = TYPE_TI_TEMPLATE (d1);
9748       d1 = DECL_NAME (templ);
9749     }
9750   else if (DECL_TYPE_TEMPLATE_P (d1))
9751     {
9752       templ = d1;
9753       d1 = DECL_NAME (templ);
9754       context = DECL_CONTEXT (templ);
9755     }
9756   else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
9757     {
9758       templ = d1;
9759       d1 = DECL_NAME (templ);
9760     }
9761 
9762   /* Issue an error message if we didn't find a template.  */
9763   if (! templ)
9764     {
9765       if (complain & tf_error)
9766 	error ("%qT is not a template", d1);
9767       return error_mark_node;
9768     }
9769 
9770   if (TREE_CODE (templ) != TEMPLATE_DECL
9771 	 /* Make sure it's a user visible template, if it was named by
9772 	    the user.  */
9773       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
9774 	  && !PRIMARY_TEMPLATE_P (templ)))
9775     {
9776       if (complain & tf_error)
9777 	{
9778 	  error ("non-template type %qT used as a template", d1);
9779 	  if (in_decl)
9780 	    error ("for template declaration %q+D", in_decl);
9781 	}
9782       return error_mark_node;
9783     }
9784 
9785   complain &= ~tf_user;
9786 
9787   /* An alias that just changes the name of a template is equivalent to the
9788      other template, so if any of the arguments are pack expansions, strip
9789      the alias to avoid problems with a pack expansion passed to a non-pack
9790      alias template parameter (DR 1430).  */
9791   if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
9792     templ = get_underlying_template (templ);
9793 
9794   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
9795     {
9796       tree parm;
9797       tree arglist2 = coerce_template_args_for_ttp (templ, arglist, complain);
9798       if (arglist2 == error_mark_node
9799 	  || (!uses_template_parms (arglist2)
9800 	      && check_instantiated_args (templ, arglist2, complain)))
9801 	return error_mark_node;
9802 
9803       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
9804       return parm;
9805     }
9806   else
9807     {
9808       tree template_type = TREE_TYPE (templ);
9809       tree gen_tmpl;
9810       tree type_decl;
9811       tree found = NULL_TREE;
9812       int arg_depth;
9813       int parm_depth;
9814       int is_dependent_type;
9815       int use_partial_inst_tmpl = false;
9816 
9817       if (template_type == error_mark_node)
9818 	/* An error occurred while building the template TEMPL, and a
9819 	   diagnostic has most certainly been emitted for that
9820 	   already.  Let's propagate that error.  */
9821 	return error_mark_node;
9822 
9823       gen_tmpl = most_general_template (templ);
9824       if (modules_p ())
9825 	lazy_load_pendings (gen_tmpl);
9826 
9827       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
9828       parm_depth = TMPL_PARMS_DEPTH (parmlist);
9829       arg_depth = TMPL_ARGS_DEPTH (arglist);
9830 
9831       if (arg_depth == 1 && parm_depth > 1)
9832 	{
9833 	  /* We've been given an incomplete set of template arguments.
9834 	     For example, given:
9835 
9836 	       template <class T> struct S1 {
9837 		 template <class U> struct S2 {};
9838 		 template <class U> struct S2<U*> {};
9839 		};
9840 
9841 	     we will be called with an ARGLIST of `U*', but the
9842 	     TEMPLATE will be `template <class T> template
9843 	     <class U> struct S1<T>::S2'.  We must fill in the missing
9844 	     arguments.  */
9845 	  tree ti = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (templ));
9846 	  arglist = add_outermost_template_args (TI_ARGS (ti), arglist);
9847 	  arg_depth = TMPL_ARGS_DEPTH (arglist);
9848 	}
9849 
9850       /* Now we should have enough arguments.  */
9851       gcc_assert (parm_depth == arg_depth);
9852 
9853       /* From here on, we're only interested in the most general
9854 	 template.  */
9855 
9856       /* Calculate the BOUND_ARGS.  These will be the args that are
9857 	 actually tsubst'd into the definition to create the
9858 	 instantiation.  */
9859       arglist = coerce_innermost_template_parms (parmlist, arglist, gen_tmpl,
9860 						 complain,
9861 						 /*require_all_args=*/true,
9862 						 /*use_default_args=*/true);
9863 
9864       if (arglist == error_mark_node)
9865 	/* We were unable to bind the arguments.  */
9866 	return error_mark_node;
9867 
9868       /* In the scope of a template class, explicit references to the
9869 	 template class refer to the type of the template, not any
9870 	 instantiation of it.  For example, in:
9871 
9872 	   template <class T> class C { void f(C<T>); }
9873 
9874 	 the `C<T>' is just the same as `C'.  Outside of the
9875 	 class, however, such a reference is an instantiation.  */
9876       if (entering_scope
9877 	  || !PRIMARY_TEMPLATE_P (gen_tmpl)
9878 	  || currently_open_class (template_type))
9879 	{
9880 	  tree tinfo = TYPE_TEMPLATE_INFO (template_type);
9881 
9882 	  if (tinfo && comp_template_args (TI_ARGS (tinfo), arglist))
9883 	    return template_type;
9884 	}
9885 
9886       /* If we already have this specialization, return it.  */
9887       elt.tmpl = gen_tmpl;
9888       elt.args = arglist;
9889       elt.spec = NULL_TREE;
9890       hash = spec_hasher::hash (&elt);
9891       entry = type_specializations->find_with_hash (&elt, hash);
9892 
9893       if (entry)
9894 	return entry->spec;
9895 
9896       /* If the template's constraints are not satisfied,
9897          then we cannot form a valid type.
9898 
9899          Note that the check is deferred until after the hash
9900          lookup. This prevents redundant checks on previously
9901          instantiated specializations. */
9902       if (flag_concepts
9903 	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl)
9904 	  && !constraints_satisfied_p (gen_tmpl, arglist))
9905         {
9906           if (complain & tf_error)
9907             {
9908 	      auto_diagnostic_group d;
9909               error ("template constraint failure for %qD", gen_tmpl);
9910               diagnose_constraints (input_location, gen_tmpl, arglist);
9911             }
9912           return error_mark_node;
9913         }
9914 
9915       is_dependent_type = uses_template_parms (arglist);
9916 
9917       /* If the deduced arguments are invalid, then the binding
9918 	 failed.  */
9919       if (!is_dependent_type
9920 	  && check_instantiated_args (gen_tmpl,
9921 				      INNERMOST_TEMPLATE_ARGS (arglist),
9922 				      complain))
9923 	return error_mark_node;
9924 
9925       if (!is_dependent_type
9926 	  && !PRIMARY_TEMPLATE_P (gen_tmpl)
9927 	  && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
9928 	  && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
9929 	/* This occurs when the user has tried to define a tagged type
9930 	   in a scope that forbids it.  We emitted an error during the
9931 	   parse.  We didn't complete the bail out then, so here we
9932 	   are.  */
9933 	return error_mark_node;
9934 
9935       context = DECL_CONTEXT (gen_tmpl);
9936       if (context && TYPE_P (context))
9937 	{
9938 	  context = tsubst_aggr_type (context, arglist, complain, in_decl, true);
9939 	  context = complete_type (context);
9940 	}
9941       else
9942 	context = tsubst (context, arglist, complain, in_decl);
9943 
9944       if (context == error_mark_node)
9945 	return error_mark_node;
9946 
9947       if (!context)
9948 	context = global_namespace;
9949 
9950       /* Create the type.  */
9951       if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9952 	{
9953 	  /* The user referred to a specialization of an alias
9954 	    template represented by GEN_TMPL.
9955 
9956 	    [temp.alias]/2 says:
9957 
9958 	        When a template-id refers to the specialization of an
9959 		alias template, it is equivalent to the associated
9960 		type obtained by substitution of its
9961 		template-arguments for the template-parameters in the
9962 		type-id of the alias template.  */
9963 
9964 	  t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
9965 	  /* Note that the call above (by indirectly calling
9966 	     register_specialization in tsubst_decl) registers the
9967 	     TYPE_DECL representing the specialization of the alias
9968 	     template.  So next time someone substitutes ARGLIST for
9969 	     the template parms into the alias template (GEN_TMPL),
9970 	     she'll get that TYPE_DECL back.  */
9971 
9972 	  if (t == error_mark_node)
9973 	    return t;
9974 	}
9975       else if (TREE_CODE (template_type) == ENUMERAL_TYPE)
9976 	{
9977 	  if (!is_dependent_type)
9978 	    {
9979 	      set_current_access_from_decl (TYPE_NAME (template_type));
9980 	      t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
9981 			      tsubst (ENUM_UNDERLYING_TYPE (template_type),
9982 				      arglist, complain, in_decl),
9983 			      tsubst_attributes (TYPE_ATTRIBUTES (template_type),
9984 						 arglist, complain, in_decl),
9985 			      SCOPED_ENUM_P (template_type), NULL);
9986 
9987 	      if (t == error_mark_node)
9988 		return t;
9989 	    }
9990 	  else
9991             {
9992               /* We don't want to call start_enum for this type, since
9993                  the values for the enumeration constants may involve
9994                  template parameters.  And, no one should be interested
9995                  in the enumeration constants for such a type.  */
9996               t = cxx_make_type (ENUMERAL_TYPE);
9997               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
9998             }
9999           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
10000 	  ENUM_FIXED_UNDERLYING_TYPE_P (t)
10001 	    = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
10002 	}
10003       else if (CLASS_TYPE_P (template_type))
10004 	{
10005 	  /* Lambda closures are regenerated in tsubst_lambda_expr, not
10006 	     instantiated here.  */
10007 	  gcc_assert (!LAMBDA_TYPE_P (template_type));
10008 
10009 	  t = make_class_type (TREE_CODE (template_type));
10010 	  CLASSTYPE_DECLARED_CLASS (t)
10011 	    = CLASSTYPE_DECLARED_CLASS (template_type);
10012 	  SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
10013 
10014 	  /* A local class.  Make sure the decl gets registered properly.  */
10015 	  if (context == current_function_decl)
10016 	    if (pushtag (DECL_NAME (gen_tmpl), t)
10017 		== error_mark_node)
10018 	      return error_mark_node;
10019 
10020 	  if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
10021 	    /* This instantiation is another name for the primary
10022 	       template type. Set the TYPE_CANONICAL field
10023 	       appropriately. */
10024 	    TYPE_CANONICAL (t) = template_type;
10025 	  else if (any_template_arguments_need_structural_equality_p (arglist))
10026 	    /* Some of the template arguments require structural
10027 	       equality testing, so this template class requires
10028 	       structural equality testing. */
10029 	    SET_TYPE_STRUCTURAL_EQUALITY (t);
10030 	}
10031       else
10032 	gcc_unreachable ();
10033 
10034       /* If we called start_enum or pushtag above, this information
10035 	 will already be set up.  */
10036       type_decl = TYPE_NAME (t);
10037       if (!type_decl)
10038 	{
10039 	  TYPE_CONTEXT (t) = FROB_CONTEXT (context);
10040 
10041 	  type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
10042 	  DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
10043 	  DECL_SOURCE_LOCATION (type_decl)
10044 	    = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
10045 	}
10046 
10047       set_instantiating_module (type_decl);
10048       /* Although GEN_TMPL is the TEMPLATE_DECL, it has the same value
10049 	 of export flag.  We want to propagate this because it might
10050 	 be a friend declaration that pushes a new hidden binding.  */
10051       DECL_MODULE_EXPORT_P (type_decl) = DECL_MODULE_EXPORT_P (gen_tmpl);
10052 
10053       if (CLASS_TYPE_P (template_type))
10054 	{
10055 	  TREE_PRIVATE (type_decl)
10056 	    = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
10057 	  TREE_PROTECTED (type_decl)
10058 	    = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
10059 	  if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
10060 	    {
10061 	      DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
10062 	      DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
10063 	    }
10064 	}
10065 
10066       if (OVERLOAD_TYPE_P (t)
10067 	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10068 	{
10069 	  static const char *tags[] = {"abi_tag", "may_alias"};
10070 
10071 	  for (unsigned ix = 0; ix != 2; ix++)
10072 	    {
10073 	      tree attributes
10074 		= lookup_attribute (tags[ix], TYPE_ATTRIBUTES (template_type));
10075 
10076 	      if (attributes)
10077 		TYPE_ATTRIBUTES (t)
10078 		  = tree_cons (TREE_PURPOSE (attributes),
10079 			       TREE_VALUE (attributes),
10080 			       TYPE_ATTRIBUTES (t));
10081 	    }
10082 	}
10083 
10084       /* Let's consider the explicit specialization of a member
10085          of a class template specialization that is implicitly instantiated,
10086 	 e.g.:
10087 	     template<class T>
10088 	     struct S
10089 	     {
10090 	       template<class U> struct M {}; //#0
10091 	     };
10092 
10093 	     template<>
10094 	     template<>
10095 	     struct S<int>::M<char> //#1
10096 	     {
10097 	       int i;
10098 	     };
10099 	[temp.expl.spec]/4 says this is valid.
10100 
10101 	In this case, when we write:
10102 	S<int>::M<char> m;
10103 
10104 	M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
10105 	the one of #0.
10106 
10107 	When we encounter #1, we want to store the partial instantiation
10108 	of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
10109 
10110 	For all cases other than this "explicit specialization of member of a
10111 	class template", we just want to store the most general template into
10112 	the CLASSTYPE_TI_TEMPLATE of M.
10113 
10114 	This case of "explicit specialization of member of a class template"
10115 	only happens when:
10116 	1/ the enclosing class is an instantiation of, and therefore not
10117 	the same as, the context of the most general template, and
10118 	2/ we aren't looking at the partial instantiation itself, i.e.
10119 	the innermost arguments are not the same as the innermost parms of
10120 	the most general template.
10121 
10122 	So it's only when 1/ and 2/ happens that we want to use the partial
10123 	instantiation of the member template in lieu of its most general
10124 	template.  */
10125 
10126       if (PRIMARY_TEMPLATE_P (gen_tmpl)
10127 	  && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
10128 	  /* the enclosing class must be an instantiation...  */
10129 	  && CLASS_TYPE_P (context)
10130 	  && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
10131 	{
10132 	  TREE_VEC_LENGTH (arglist)--;
10133 	  ++processing_template_decl;
10134 	  tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (gen_tmpl));
10135 	  tree partial_inst_args =
10136 	    tsubst (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)),
10137 		    arglist, complain, NULL_TREE);
10138 	  --processing_template_decl;
10139 	  TREE_VEC_LENGTH (arglist)++;
10140 	  if (partial_inst_args == error_mark_node)
10141 	    return error_mark_node;
10142 	  use_partial_inst_tmpl =
10143 	    /*...and we must not be looking at the partial instantiation
10144 	     itself. */
10145 	    !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
10146 				 partial_inst_args);
10147 	}
10148 
10149       if (!use_partial_inst_tmpl)
10150 	/* This case is easy; there are no member templates involved.  */
10151 	found = gen_tmpl;
10152       else
10153 	{
10154 	  /* This is a full instantiation of a member template.  Find
10155 	     the partial instantiation of which this is an instance.  */
10156 
10157 	  /* Temporarily reduce by one the number of levels in the ARGLIST
10158 	     so as to avoid comparing the last set of arguments.  */
10159 	  TREE_VEC_LENGTH (arglist)--;
10160 	  /* We don't use COMPLAIN in the following call because this isn't
10161 	     the immediate context of deduction.  For instance, tf_partial
10162 	     could be set here as we might be at the beginning of template
10163 	     argument deduction when any explicitly specified template
10164 	     arguments are substituted into the function type.  tf_partial
10165 	     could lead into trouble because we wouldn't find the partial
10166 	     instantiation that might have been created outside tf_partial
10167 	     context, because the levels of template parameters wouldn't
10168 	     match, because in a tf_partial context, tsubst doesn't reduce
10169 	     TEMPLATE_PARM_LEVEL.  */
10170 	  found = tsubst (gen_tmpl, arglist, tf_none, NULL_TREE);
10171 	  TREE_VEC_LENGTH (arglist)++;
10172 	  /* FOUND is either a proper class type, or an alias
10173 	     template specialization.  In the later case, it's a
10174 	     TYPE_DECL, resulting from the substituting of arguments
10175 	     for parameters in the TYPE_DECL of the alias template
10176 	     done earlier.  So be careful while getting the template
10177 	     of FOUND.  */
10178 	  found = (TREE_CODE (found) == TEMPLATE_DECL
10179 		   ? found
10180 		   : (TREE_CODE (found) == TYPE_DECL
10181 		      ? DECL_TI_TEMPLATE (found)
10182 		      : CLASSTYPE_TI_TEMPLATE (found)));
10183 
10184 	  if (DECL_CLASS_TEMPLATE_P (found)
10185 	      && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (found)))
10186 	    {
10187 	      /* If this partial instantiation is specialized, we want to
10188 		 use it for hash table lookup.  */
10189 	      elt.tmpl = found;
10190 	      elt.args = arglist = INNERMOST_TEMPLATE_ARGS (arglist);
10191 	      hash = spec_hasher::hash (&elt);
10192 	    }
10193 	}
10194 
10195       /* Build template info for the new specialization.  */
10196       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
10197 
10198       elt.spec = t;
10199       slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
10200       gcc_checking_assert (*slot == NULL);
10201       entry = ggc_alloc<spec_entry> ();
10202       *entry = elt;
10203       *slot = entry;
10204 
10205       /* Note this use of the partial instantiation so we can check it
10206 	 later in maybe_process_partial_specialization.  */
10207       DECL_TEMPLATE_INSTANTIATIONS (found)
10208 	= tree_cons (arglist, t,
10209 		     DECL_TEMPLATE_INSTANTIATIONS (found));
10210 
10211       if (TREE_CODE (template_type) == ENUMERAL_TYPE
10212 	  && !uses_template_parms (current_nonlambda_scope ())
10213 	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10214 	/* Now that the type has been registered on the instantiations
10215 	   list, we set up the enumerators.  Because the enumeration
10216 	   constants may involve the enumeration type itself, we make
10217 	   sure to register the type first, and then create the
10218 	   constants.  That way, doing tsubst_expr for the enumeration
10219 	   constants won't result in recursive calls here; we'll find
10220 	   the instantiation and exit above.  */
10221 	tsubst_enum (template_type, t, arglist);
10222 
10223       if (CLASS_TYPE_P (template_type) && is_dependent_type)
10224 	/* If the type makes use of template parameters, the
10225 	   code that generates debugging information will crash.  */
10226 	DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
10227 
10228       /* Possibly limit visibility based on template args.  */
10229       TREE_PUBLIC (type_decl) = 1;
10230       determine_visibility (type_decl);
10231 
10232       inherit_targ_abi_tags (t);
10233 
10234       return t;
10235     }
10236 }
10237 
10238 /* Wrapper for lookup_template_class_1.  */
10239 
10240 tree
lookup_template_class(tree d1,tree arglist,tree in_decl,tree context,int entering_scope,tsubst_flags_t complain)10241 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
10242                        int entering_scope, tsubst_flags_t complain)
10243 {
10244   tree ret;
10245   timevar_push (TV_TEMPLATE_INST);
10246   ret = lookup_template_class_1 (d1, arglist, in_decl, context,
10247                                  entering_scope, complain);
10248   timevar_pop (TV_TEMPLATE_INST);
10249   return ret;
10250 }
10251 
10252 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST.  */
10253 
10254 tree
lookup_template_variable(tree templ,tree arglist)10255 lookup_template_variable (tree templ, tree arglist)
10256 {
10257   if (flag_concepts && variable_concept_p (templ))
10258     return build_concept_check (templ, arglist, tf_none);
10259 
10260   /* The type of the expression is NULL_TREE since the template-id could refer
10261      to an explicit or partial specialization. */
10262   return build2 (TEMPLATE_ID_EXPR, NULL_TREE, templ, arglist);
10263 }
10264 
10265 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR for use. */
10266 
10267 tree
finish_template_variable(tree var,tsubst_flags_t complain)10268 finish_template_variable (tree var, tsubst_flags_t complain)
10269 {
10270   tree templ = TREE_OPERAND (var, 0);
10271   tree arglist = TREE_OPERAND (var, 1);
10272 
10273   tree tmpl_args = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (templ));
10274   arglist = add_outermost_template_args (tmpl_args, arglist);
10275 
10276   templ = most_general_template (templ);
10277   tree parms = DECL_TEMPLATE_PARMS (templ);
10278   arglist = coerce_innermost_template_parms (parms, arglist, templ, complain,
10279 					     /*req_all*/true,
10280 					     /*use_default*/true);
10281   if (arglist == error_mark_node)
10282     return error_mark_node;
10283 
10284   if (flag_concepts && !constraints_satisfied_p (templ, arglist))
10285     {
10286       if (complain & tf_error)
10287 	{
10288 	  auto_diagnostic_group d;
10289 	  error ("use of invalid variable template %qE", var);
10290 	  diagnose_constraints (location_of (var), templ, arglist);
10291 	}
10292       return error_mark_node;
10293     }
10294 
10295   return instantiate_template (templ, arglist, complain);
10296 }
10297 
10298 /* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
10299    TARGS template args, and instantiate it if it's not dependent.  */
10300 
10301 tree
lookup_and_finish_template_variable(tree templ,tree targs,tsubst_flags_t complain)10302 lookup_and_finish_template_variable (tree templ, tree targs,
10303 				     tsubst_flags_t complain)
10304 {
10305   templ = lookup_template_variable (templ, targs);
10306   if (!any_dependent_template_arguments_p (targs))
10307     {
10308       templ = finish_template_variable (templ, complain);
10309       mark_used (templ);
10310     }
10311 
10312   return convert_from_reference (templ);
10313 }
10314 
10315 /* If the set of template parameters PARMS contains a template parameter
10316    at the given LEVEL and INDEX, then return this parameter.  Otherwise
10317    return NULL_TREE.  */
10318 
10319 static tree
corresponding_template_parameter(tree parms,int level,int index)10320 corresponding_template_parameter (tree parms, int level, int index)
10321 {
10322   while (TMPL_PARMS_DEPTH (parms) > level)
10323     parms = TREE_CHAIN (parms);
10324 
10325   if (TMPL_PARMS_DEPTH (parms) != level
10326       || TREE_VEC_LENGTH (TREE_VALUE (parms)) <= index)
10327     return NULL_TREE;
10328 
10329   tree t = TREE_VALUE (TREE_VEC_ELT (TREE_VALUE (parms), index));
10330   /* As in template_parm_to_arg.  */
10331   if (TREE_CODE (t) == TYPE_DECL || TREE_CODE (t) == TEMPLATE_DECL)
10332     t = TREE_TYPE (t);
10333   else
10334     t = DECL_INITIAL (t);
10335 
10336   gcc_assert (TEMPLATE_PARM_P (t));
10337   return t;
10338 }
10339 
10340 /* Return the template parameter from PARMS that positionally corresponds
10341    to the template parameter PARM, or else return NULL_TREE.  */
10342 
10343 static tree
corresponding_template_parameter(tree parms,tree parm)10344 corresponding_template_parameter (tree parms, tree parm)
10345 {
10346   int level, index;
10347   template_parm_level_and_index (parm, &level, &index);
10348   return corresponding_template_parameter (parms, level, index);
10349 }
10350 
10351 
10352 struct pair_fn_data
10353 {
10354   tree_fn_t fn;
10355   tree_fn_t any_fn;
10356   void *data;
10357   /* True when we should also visit template parameters that occur in
10358      non-deduced contexts.  */
10359   bool include_nondeduced_p;
10360   hash_set<tree> *visited;
10361 };
10362 
10363 /* Called from for_each_template_parm via walk_tree.  */
10364 
10365 static tree
for_each_template_parm_r(tree * tp,int * walk_subtrees,void * d)10366 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
10367 {
10368   tree t = *tp;
10369   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
10370   tree_fn_t fn = pfd->fn;
10371   void *data = pfd->data;
10372   tree result = NULL_TREE;
10373 
10374 #define WALK_SUBTREE(NODE)						\
10375   do									\
10376     {									\
10377       result = for_each_template_parm (NODE, fn, data, pfd->visited,	\
10378 				       pfd->include_nondeduced_p,	\
10379 				       pfd->any_fn);			\
10380       if (result) goto out;						\
10381     }									\
10382   while (0)
10383 
10384   if (pfd->any_fn && (*pfd->any_fn)(t, data))
10385     return t;
10386 
10387   if (TYPE_P (t)
10388       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
10389     WALK_SUBTREE (TYPE_CONTEXT (t));
10390 
10391   switch (TREE_CODE (t))
10392     {
10393     case RECORD_TYPE:
10394       if (TYPE_PTRMEMFUNC_P (t))
10395 	break;
10396       /* Fall through.  */
10397 
10398     case UNION_TYPE:
10399     case ENUMERAL_TYPE:
10400       if (!TYPE_TEMPLATE_INFO (t))
10401 	*walk_subtrees = 0;
10402       else
10403 	WALK_SUBTREE (TYPE_TI_ARGS (t));
10404       break;
10405 
10406     case INTEGER_TYPE:
10407       WALK_SUBTREE (TYPE_MIN_VALUE (t));
10408       WALK_SUBTREE (TYPE_MAX_VALUE (t));
10409       break;
10410 
10411     case METHOD_TYPE:
10412       /* Since we're not going to walk subtrees, we have to do this
10413 	 explicitly here.  */
10414       WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
10415       /* Fall through.  */
10416 
10417     case FUNCTION_TYPE:
10418       /* Check the return type.  */
10419       WALK_SUBTREE (TREE_TYPE (t));
10420 
10421       /* Check the parameter types.  Since default arguments are not
10422 	 instantiated until they are needed, the TYPE_ARG_TYPES may
10423 	 contain expressions that involve template parameters.  But,
10424 	 no-one should be looking at them yet.  And, once they're
10425 	 instantiated, they don't contain template parameters, so
10426 	 there's no point in looking at them then, either.  */
10427       {
10428 	tree parm;
10429 
10430 	for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
10431 	  WALK_SUBTREE (TREE_VALUE (parm));
10432 
10433 	/* Since we've already handled the TYPE_ARG_TYPES, we don't
10434 	   want walk_tree walking into them itself.  */
10435 	*walk_subtrees = 0;
10436       }
10437 
10438       if (flag_noexcept_type)
10439 	{
10440 	  tree spec = TYPE_RAISES_EXCEPTIONS (t);
10441 	  if (spec)
10442 	    WALK_SUBTREE (TREE_PURPOSE (spec));
10443 	}
10444       break;
10445 
10446     case TYPEOF_TYPE:
10447     case DECLTYPE_TYPE:
10448     case UNDERLYING_TYPE:
10449       if (pfd->include_nondeduced_p
10450 	  && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
10451 				     pfd->visited,
10452 				     pfd->include_nondeduced_p,
10453 				     pfd->any_fn))
10454 	return error_mark_node;
10455       *walk_subtrees = false;
10456       break;
10457 
10458     case FUNCTION_DECL:
10459     case VAR_DECL:
10460       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10461 	WALK_SUBTREE (DECL_TI_ARGS (t));
10462       /* Fall through.  */
10463 
10464     case PARM_DECL:
10465     case CONST_DECL:
10466       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t))
10467 	WALK_SUBTREE (DECL_INITIAL (t));
10468       if (DECL_CONTEXT (t)
10469 	  && pfd->include_nondeduced_p)
10470 	WALK_SUBTREE (DECL_CONTEXT (t));
10471       break;
10472 
10473     case BOUND_TEMPLATE_TEMPLATE_PARM:
10474       /* Record template parameters such as `T' inside `TT<T>'.  */
10475       WALK_SUBTREE (TYPE_TI_ARGS (t));
10476       /* Fall through.  */
10477 
10478     case TEMPLATE_TEMPLATE_PARM:
10479     case TEMPLATE_TYPE_PARM:
10480     case TEMPLATE_PARM_INDEX:
10481       if (fn && (*fn)(t, data))
10482 	return t;
10483       else if (!fn)
10484 	return t;
10485       break;
10486 
10487     case TEMPLATE_DECL:
10488       /* A template template parameter is encountered.  */
10489       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10490 	WALK_SUBTREE (TREE_TYPE (t));
10491 
10492       /* Already substituted template template parameter */
10493       *walk_subtrees = 0;
10494       break;
10495 
10496     case TYPENAME_TYPE:
10497       /* A template-id in a TYPENAME_TYPE might be a deduced context after
10498 	 partial instantiation.  */
10499       WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
10500       *walk_subtrees = 0;
10501       break;
10502 
10503     case CONSTRUCTOR:
10504       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
10505 	  && pfd->include_nondeduced_p)
10506 	WALK_SUBTREE (TYPE_PTRMEMFUNC_FN_TYPE (TREE_TYPE (t)));
10507       break;
10508 
10509     case INDIRECT_REF:
10510     case COMPONENT_REF:
10511       /* If there's no type, then this thing must be some expression
10512 	 involving template parameters.  */
10513       if (!fn && !TREE_TYPE (t))
10514 	return error_mark_node;
10515       break;
10516 
10517     case MODOP_EXPR:
10518     case CAST_EXPR:
10519     case IMPLICIT_CONV_EXPR:
10520     case REINTERPRET_CAST_EXPR:
10521     case CONST_CAST_EXPR:
10522     case STATIC_CAST_EXPR:
10523     case DYNAMIC_CAST_EXPR:
10524     case ARROW_EXPR:
10525     case DOTSTAR_EXPR:
10526     case TYPEID_EXPR:
10527     case PSEUDO_DTOR_EXPR:
10528       if (!fn)
10529 	return error_mark_node;
10530       break;
10531 
10532     case SCOPE_REF:
10533       if (pfd->include_nondeduced_p)
10534 	WALK_SUBTREE (TREE_OPERAND (t, 0));
10535       break;
10536 
10537     case REQUIRES_EXPR:
10538       {
10539 	if (!fn)
10540 	  return error_mark_node;
10541 
10542 	/* Recursively walk the type of each constraint variable.  */
10543 	tree p = TREE_OPERAND (t, 0);
10544 	while (p)
10545 	  {
10546 	    WALK_SUBTREE (TREE_TYPE (p));
10547 	    p = TREE_CHAIN (p);
10548 	  }
10549       }
10550       break;
10551 
10552     default:
10553       break;
10554     }
10555 
10556   #undef WALK_SUBTREE
10557 
10558   /* We didn't find any template parameters we liked.  */
10559  out:
10560   return result;
10561 }
10562 
10563 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
10564    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
10565    call FN with the parameter and the DATA.
10566    If FN returns nonzero, the iteration is terminated, and
10567    for_each_template_parm returns 1.  Otherwise, the iteration
10568    continues.  If FN never returns a nonzero value, the value
10569    returned by for_each_template_parm is 0.  If FN is NULL, it is
10570    considered to be the function which always returns 1.
10571 
10572    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
10573    parameters that occur in non-deduced contexts.  When false, only
10574    visits those template parameters that can be deduced.  */
10575 
10576 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)10577 for_each_template_parm (tree t, tree_fn_t fn, void* data,
10578 			hash_set<tree> *visited,
10579 			bool include_nondeduced_p,
10580 			tree_fn_t any_fn)
10581 {
10582   struct pair_fn_data pfd;
10583   tree result;
10584 
10585   /* Set up.  */
10586   pfd.fn = fn;
10587   pfd.any_fn = any_fn;
10588   pfd.data = data;
10589   pfd.include_nondeduced_p = include_nondeduced_p;
10590 
10591   /* Walk the tree.  (Conceptually, we would like to walk without
10592      duplicates, but for_each_template_parm_r recursively calls
10593      for_each_template_parm, so we would need to reorganize a fair
10594      bit to use walk_tree_without_duplicates, so we keep our own
10595      visited list.)  */
10596   if (visited)
10597     pfd.visited = visited;
10598   else
10599     pfd.visited = new hash_set<tree>;
10600   result = cp_walk_tree (&t,
10601 		         for_each_template_parm_r,
10602 		         &pfd,
10603 		         pfd.visited);
10604 
10605   /* Clean up.  */
10606   if (!visited)
10607     {
10608       delete pfd.visited;
10609       pfd.visited = 0;
10610     }
10611 
10612   return result;
10613 }
10614 
10615 struct find_template_parameter_info
10616 {
find_template_parameter_infofind_template_parameter_info10617   explicit find_template_parameter_info (tree ctx_parms)
10618     : parm_list (NULL_TREE),
10619       ctx_parms (ctx_parms),
10620       max_depth (TMPL_PARMS_DEPTH (ctx_parms))
10621   {}
10622 
10623   hash_set<tree> visited;
10624   hash_set<tree> parms;
10625   tree parm_list;
10626   tree ctx_parms;
10627   int max_depth;
10628 };
10629 
10630 /* Appends the declaration of T to the list in DATA.  */
10631 
10632 static int
keep_template_parm(tree t,void * data)10633 keep_template_parm (tree t, void* data)
10634 {
10635   find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10636 
10637   /* Template parameters declared within the expression are not part of
10638      the parameter mapping. For example, in this concept:
10639 
10640        template<typename T>
10641        concept C = requires { <expr> } -> same_as<int>;
10642 
10643      the return specifier same_as<int> declares a new decltype parameter
10644      that must not be part of the parameter mapping. The same is true
10645      for generic lambda parameters, lambda template parameters, etc.  */
10646   int level;
10647   int index;
10648   template_parm_level_and_index (t, &level, &index);
10649   if (level > ftpi->max_depth)
10650     return 0;
10651 
10652   if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10653     /* We want the underlying TEMPLATE_TEMPLATE_PARM, not the
10654        BOUND_TEMPLATE_TEMPLATE_PARM itself.  */
10655     t = TREE_TYPE (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (t));
10656 
10657   /* This template parameter might be an argument to a cached dependent
10658      specalization that was formed earlier inside some other template, in
10659      which case the parameter is not among the ones that are in-scope.
10660      Look in CTX_PARMS to find the corresponding in-scope template
10661      parameter, and use it instead.  */
10662   if (tree in_scope = corresponding_template_parameter (ftpi->ctx_parms, t))
10663     t = in_scope;
10664 
10665   /* Arguments like const T yield parameters like const T. This means that
10666      a template-id like X<T, const T> would yield two distinct parameters:
10667      T and const T. Adjust types to their unqualified versions.  */
10668   if (TYPE_P (t))
10669     t = TYPE_MAIN_VARIANT (t);
10670   if (!ftpi->parms.add (t))
10671     ftpi->parm_list = tree_cons (NULL_TREE, t, ftpi->parm_list);
10672 
10673   /* Verify the parameter we found has a valid index.  */
10674   if (flag_checking)
10675     {
10676       tree parms = ftpi->ctx_parms;
10677       while (TMPL_PARMS_DEPTH (parms) > level)
10678 	parms = TREE_CHAIN (parms);
10679       if (int len = TREE_VEC_LENGTH (TREE_VALUE (parms)))
10680 	gcc_assert (index < len);
10681     }
10682 
10683   return 0;
10684 }
10685 
10686 /* Ensure that we recursively examine certain terms that are not normally
10687    visited in for_each_template_parm_r.  */
10688 
10689 static int
any_template_parm_r(tree t,void * data)10690 any_template_parm_r (tree t, void *data)
10691 {
10692   find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10693 
10694 #define WALK_SUBTREE(NODE)						\
10695   do									\
10696     {									\
10697       for_each_template_parm (NODE, keep_template_parm, data,		\
10698 			      &ftpi->visited, true,			\
10699 			      any_template_parm_r);			\
10700     }									\
10701   while (0)
10702 
10703   /* A mention of a member alias/typedef is a use of all of its template
10704      arguments, including those from the enclosing class, so we don't use
10705      alias_template_specialization_p here.  */
10706   if (TYPE_P (t) && typedef_variant_p (t))
10707     if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
10708       WALK_SUBTREE (TI_ARGS (tinfo));
10709 
10710   switch (TREE_CODE (t))
10711     {
10712     case TEMPLATE_TYPE_PARM:
10713       /* Type constraints of a placeholder type may contain parameters.  */
10714       if (is_auto (t))
10715 	if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
10716 	  WALK_SUBTREE (constr);
10717       break;
10718 
10719     case TEMPLATE_ID_EXPR:
10720       /* Search through references to variable templates.  */
10721       WALK_SUBTREE (TREE_OPERAND (t, 0));
10722       WALK_SUBTREE (TREE_OPERAND (t, 1));
10723       break;
10724 
10725     case TEMPLATE_PARM_INDEX:
10726     case PARM_DECL:
10727       /* A parameter or constraint variable may also depend on a template
10728 	 parameter without explicitly naming it.  */
10729       WALK_SUBTREE (TREE_TYPE (t));
10730       break;
10731 
10732     case TEMPLATE_DECL:
10733       /* If T is a member template that shares template parameters with
10734 	 ctx_parms, we need to mark all those parameters for mapping.
10735 	 To that end, it should suffice to just walk the DECL_CONTEXT of
10736 	 the template (assuming the template is not overly general).  */
10737       WALK_SUBTREE (DECL_CONTEXT (t));
10738       break;
10739 
10740     case LAMBDA_EXPR:
10741       {
10742 	/* Look in the parms and body.  */
10743 	tree fn = lambda_function (t);
10744 	WALK_SUBTREE (TREE_TYPE (fn));
10745 	WALK_SUBTREE (DECL_SAVED_TREE (fn));
10746       }
10747       break;
10748 
10749     case IDENTIFIER_NODE:
10750       if (IDENTIFIER_CONV_OP_P (t))
10751 	/* The conversion-type-id of a conversion operator may be dependent.  */
10752 	WALK_SUBTREE (TREE_TYPE (t));
10753       break;
10754 
10755     default:
10756       break;
10757     }
10758 
10759   /* Keep walking.  */
10760   return 0;
10761 }
10762 
10763 /* Returns a list of unique template parameters found within T, where CTX_PARMS
10764    are the template parameters in scope.  */
10765 
10766 tree
find_template_parameters(tree t,tree ctx_parms)10767 find_template_parameters (tree t, tree ctx_parms)
10768 {
10769   if (!ctx_parms)
10770     return NULL_TREE;
10771 
10772   find_template_parameter_info ftpi (ctx_parms);
10773   for_each_template_parm (t, keep_template_parm, &ftpi, &ftpi.visited,
10774 			  /*include_nondeduced*/true, any_template_parm_r);
10775   return ftpi.parm_list;
10776 }
10777 
10778 /* Returns true if T depends on any template parameter.  */
10779 
10780 int
uses_template_parms(tree t)10781 uses_template_parms (tree t)
10782 {
10783   if (t == NULL_TREE)
10784     return false;
10785 
10786   bool dependent_p;
10787   int saved_processing_template_decl;
10788 
10789   saved_processing_template_decl = processing_template_decl;
10790   if (!saved_processing_template_decl)
10791     processing_template_decl = 1;
10792   if (TYPE_P (t))
10793     dependent_p = dependent_type_p (t);
10794   else if (TREE_CODE (t) == TREE_VEC)
10795     dependent_p = any_dependent_template_arguments_p (t);
10796   else if (TREE_CODE (t) == TREE_LIST)
10797     dependent_p = (uses_template_parms (TREE_VALUE (t))
10798 		   || uses_template_parms (TREE_CHAIN (t)));
10799   else if (TREE_CODE (t) == TYPE_DECL)
10800     dependent_p = dependent_type_p (TREE_TYPE (t));
10801   else if (t == error_mark_node)
10802     dependent_p = false;
10803   else
10804     dependent_p = instantiation_dependent_expression_p (t);
10805 
10806   processing_template_decl = saved_processing_template_decl;
10807 
10808   return dependent_p;
10809 }
10810 
10811 /* Returns true iff we're processing an incompletely instantiated function
10812    template.  Useful instead of processing_template_decl because the latter
10813    is set to 0 during instantiate_non_dependent_expr.  */
10814 
10815 bool
in_template_function(void)10816 in_template_function (void)
10817 {
10818   /* Inspect the less volatile cfun->decl instead of current_function_decl;
10819      the latter might get set for e.g. access checking during satisfaction.  */
10820   tree fn = cfun ? cfun->decl : NULL_TREE;
10821   bool ret;
10822   ++processing_template_decl;
10823   ret = (fn && DECL_LANG_SPECIFIC (fn)
10824 	 && DECL_TEMPLATE_INFO (fn)
10825 	 && any_dependent_template_arguments_p (DECL_TI_ARGS (fn)));
10826   --processing_template_decl;
10827   return ret;
10828 }
10829 
10830 /* Returns true if T depends on any template parameter with level LEVEL.  */
10831 
10832 bool
uses_template_parms_level(tree t,int level)10833 uses_template_parms_level (tree t, int level)
10834 {
10835   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
10836 				 /*include_nondeduced_p=*/true);
10837 }
10838 
10839 /* Returns true if the signature of DECL depends on any template parameter from
10840    its enclosing class.  */
10841 
10842 bool
uses_outer_template_parms(tree decl)10843 uses_outer_template_parms (tree decl)
10844 {
10845   int depth = template_class_depth (CP_DECL_CONTEXT (decl));
10846   if (depth == 0)
10847     return false;
10848   if (for_each_template_parm (TREE_TYPE (decl), template_parm_outer_level,
10849 			      &depth, NULL, /*include_nondeduced_p=*/true))
10850     return true;
10851   if (PRIMARY_TEMPLATE_P (decl)
10852       || DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
10853     {
10854       tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (decl));
10855       for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
10856 	{
10857 	  tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
10858 	  tree defarg = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
10859 	  if (TREE_CODE (parm) == PARM_DECL
10860 	      && for_each_template_parm (TREE_TYPE (parm),
10861 					 template_parm_outer_level,
10862 					 &depth, NULL, /*nondeduced*/true))
10863 	    return true;
10864 	  if (TREE_CODE (parm) == TEMPLATE_DECL
10865 	      && uses_outer_template_parms (parm))
10866 	    return true;
10867 	  if (defarg
10868 	      && for_each_template_parm (defarg, template_parm_outer_level,
10869 					 &depth, NULL, /*nondeduced*/true))
10870 	    return true;
10871 	}
10872     }
10873   tree ci = get_constraints (decl);
10874   if (ci)
10875     ci = CI_ASSOCIATED_CONSTRAINTS (ci);
10876   if (ci && for_each_template_parm (ci, template_parm_outer_level,
10877 				    &depth, NULL, /*nondeduced*/true))
10878     return true;
10879   return false;
10880 }
10881 
10882 /* Returns TRUE iff INST is an instantiation we don't need to do in an
10883    ill-formed translation unit, i.e. a variable or function that isn't
10884    usable in a constant expression.  */
10885 
10886 static inline bool
neglectable_inst_p(tree d)10887 neglectable_inst_p (tree d)
10888 {
10889   return (d && DECL_P (d)
10890 	  && !undeduced_auto_decl (d)
10891 	  && !(TREE_CODE (d) == FUNCTION_DECL ? DECL_DECLARED_CONSTEXPR_P (d)
10892 	       : decl_maybe_constant_var_p (d)));
10893 }
10894 
10895 /* Returns TRUE iff we should refuse to instantiate DECL because it's
10896    neglectable and instantiated from within an erroneous instantiation.  */
10897 
10898 static bool
limit_bad_template_recursion(tree decl)10899 limit_bad_template_recursion (tree decl)
10900 {
10901   struct tinst_level *lev = current_tinst_level;
10902   int errs = errorcount + sorrycount;
10903   if (lev == NULL || errs == 0 || !neglectable_inst_p (decl))
10904     return false;
10905 
10906   for (; lev; lev = lev->next)
10907     if (neglectable_inst_p (lev->maybe_get_node ()))
10908       break;
10909 
10910   return (lev && errs > lev->errors);
10911 }
10912 
10913 static int tinst_depth;
10914 extern int max_tinst_depth;
10915 int depth_reached;
10916 
10917 static GTY(()) struct tinst_level *last_error_tinst_level;
10918 
10919 /* We're starting to instantiate D; record the template instantiation context
10920    at LOC for diagnostics and to restore it later.  */
10921 
10922 bool
push_tinst_level_loc(tree tldcl,tree targs,location_t loc)10923 push_tinst_level_loc (tree tldcl, tree targs, location_t loc)
10924 {
10925   struct tinst_level *new_level;
10926 
10927   if (tinst_depth >= max_tinst_depth)
10928     {
10929       /* Tell error.c not to try to instantiate any templates.  */
10930       at_eof = 2;
10931       fatal_error (input_location,
10932 		   "template instantiation depth exceeds maximum of %d"
10933 		   " (use %<-ftemplate-depth=%> to increase the maximum)",
10934                    max_tinst_depth);
10935       return false;
10936     }
10937 
10938   /* If the current instantiation caused problems, don't let it instantiate
10939      anything else.  Do allow deduction substitution and decls usable in
10940      constant expressions.  */
10941   if (!targs && limit_bad_template_recursion (tldcl))
10942     {
10943       /* Avoid no_linkage_errors and unused function warnings for this
10944 	 decl.  */
10945       TREE_NO_WARNING (tldcl) = 1;
10946       return false;
10947     }
10948 
10949   /* When not -quiet, dump template instantiations other than functions, since
10950      announce_function will take care of those.  */
10951   if (!quiet_flag && !targs
10952       && TREE_CODE (tldcl) != TREE_LIST
10953       && TREE_CODE (tldcl) != FUNCTION_DECL)
10954     fprintf (stderr, " %s", decl_as_string (tldcl, TFF_DECL_SPECIFIERS));
10955 
10956   new_level = tinst_level_freelist ().alloc ();
10957   new_level->tldcl = tldcl;
10958   new_level->targs = targs;
10959   new_level->locus = loc;
10960   new_level->errors = errorcount + sorrycount;
10961   new_level->next = NULL;
10962   new_level->refcount = 0;
10963   new_level->path = new_level->visible = nullptr;
10964   set_refcount_ptr (new_level->next, current_tinst_level);
10965   set_refcount_ptr (current_tinst_level, new_level);
10966 
10967   ++tinst_depth;
10968   if (GATHER_STATISTICS && (tinst_depth > depth_reached))
10969     depth_reached = tinst_depth;
10970 
10971   return true;
10972 }
10973 
10974 /* We're starting substitution of TMPL<ARGS>; record the template
10975    substitution context for diagnostics and to restore it later.  */
10976 
10977 bool
push_tinst_level(tree tmpl,tree args)10978 push_tinst_level (tree tmpl, tree args)
10979 {
10980   return push_tinst_level_loc (tmpl, args, input_location);
10981 }
10982 
10983 /* We're starting to instantiate D; record INPUT_LOCATION and the
10984    template instantiation context for diagnostics and to restore it
10985    later.  */
10986 
10987 bool
push_tinst_level(tree d)10988 push_tinst_level (tree d)
10989 {
10990   return push_tinst_level_loc (d, input_location);
10991 }
10992 
10993 /* Likewise, but record LOC as the program location.  */
10994 
10995 bool
push_tinst_level_loc(tree d,location_t loc)10996 push_tinst_level_loc (tree d, location_t loc)
10997 {
10998   gcc_assert (TREE_CODE (d) != TREE_LIST);
10999   return push_tinst_level_loc (d, NULL, loc);
11000 }
11001 
11002 /* We're done instantiating this template; return to the instantiation
11003    context.  */
11004 
11005 void
pop_tinst_level(void)11006 pop_tinst_level (void)
11007 {
11008   /* Restore the filename and line number stashed away when we started
11009      this instantiation.  */
11010   input_location = current_tinst_level->locus;
11011   set_refcount_ptr (current_tinst_level, current_tinst_level->next);
11012   --tinst_depth;
11013 }
11014 
11015 /* We're instantiating a deferred template; restore the template
11016    instantiation context in which the instantiation was requested, which
11017    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
11018 
11019 static tree
reopen_tinst_level(struct tinst_level * level)11020 reopen_tinst_level (struct tinst_level *level)
11021 {
11022   struct tinst_level *t;
11023 
11024   tinst_depth = 0;
11025   for (t = level; t; t = t->next)
11026     ++tinst_depth;
11027 
11028   set_refcount_ptr (current_tinst_level, level);
11029   pop_tinst_level ();
11030   if (current_tinst_level)
11031     current_tinst_level->errors = errorcount+sorrycount;
11032   return level->maybe_get_node ();
11033 }
11034 
11035 /* Returns the TINST_LEVEL which gives the original instantiation
11036    context.  */
11037 
11038 struct tinst_level *
outermost_tinst_level(void)11039 outermost_tinst_level (void)
11040 {
11041   struct tinst_level *level = current_tinst_level;
11042   if (level)
11043     while (level->next)
11044       level = level->next;
11045   return level;
11046 }
11047 
11048 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
11049    vector of template arguments, as for tsubst.
11050 
11051    Returns an appropriate tsubst'd friend declaration.  */
11052 
11053 static tree
tsubst_friend_function(tree decl,tree args)11054 tsubst_friend_function (tree decl, tree args)
11055 {
11056   tree new_friend;
11057 
11058   if (TREE_CODE (decl) == FUNCTION_DECL
11059       && DECL_TEMPLATE_INSTANTIATION (decl)
11060       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
11061     /* This was a friend declared with an explicit template
11062        argument list, e.g.:
11063 
11064        friend void f<>(T);
11065 
11066        to indicate that f was a template instantiation, not a new
11067        function declaration.  Now, we have to figure out what
11068        instantiation of what template.  */
11069     {
11070       tree template_id, arglist, fns;
11071       tree new_args;
11072       tree tmpl;
11073       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
11074 
11075       /* Friend functions are looked up in the containing namespace scope.
11076 	 We must enter that scope, to avoid finding member functions of the
11077 	 current class with same name.  */
11078       push_nested_namespace (ns);
11079       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
11080 			 tf_warning_or_error, NULL_TREE,
11081 			 /*integral_constant_expression_p=*/false);
11082       pop_nested_namespace (ns);
11083       arglist = tsubst (DECL_TI_ARGS (decl), args,
11084 			tf_warning_or_error, NULL_TREE);
11085       template_id = lookup_template_function (fns, arglist);
11086 
11087       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11088       tmpl = determine_specialization (template_id, new_friend,
11089 				       &new_args,
11090 				       /*need_member_template=*/0,
11091 				       TREE_VEC_LENGTH (args),
11092 				       tsk_none);
11093       return instantiate_template (tmpl, new_args, tf_error);
11094     }
11095 
11096   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11097   if (new_friend == error_mark_node)
11098     return error_mark_node;
11099 
11100   /* The NEW_FRIEND will look like an instantiation, to the
11101      compiler, but is not an instantiation from the point of view of
11102      the language.  For example, we might have had:
11103 
11104      template <class T> struct S {
11105        template <class U> friend void f(T, U);
11106      };
11107 
11108      Then, in S<int>, template <class U> void f(int, U) is not an
11109      instantiation of anything.  */
11110 
11111   DECL_USE_TEMPLATE (new_friend) = 0;
11112   if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11113     {
11114       DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (new_friend) = false;
11115       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
11116       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
11117 	= DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
11118 
11119       /* Substitute TEMPLATE_PARMS_CONSTRAINTS so that parameter levels will
11120 	 match in decls_match.  */
11121       tree parms = DECL_TEMPLATE_PARMS (new_friend);
11122       tree treqs = TEMPLATE_PARMS_CONSTRAINTS (parms);
11123       treqs = maybe_substitute_reqs_for (treqs, new_friend);
11124       TEMPLATE_PARMS_CONSTRAINTS (parms) = treqs;
11125     }
11126 
11127   /* The mangled name for the NEW_FRIEND is incorrect.  The function
11128      is not a template instantiation and should not be mangled like
11129      one.  Therefore, we forget the mangling here; we'll recompute it
11130      later if we need it.  */
11131   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
11132     {
11133       SET_DECL_RTL (new_friend, NULL);
11134       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
11135     }
11136 
11137   if (DECL_NAMESPACE_SCOPE_P (new_friend))
11138     {
11139       tree old_decl;
11140       tree ns;
11141 
11142       /* We must save some information from NEW_FRIEND before calling
11143 	 duplicate decls since that function will free NEW_FRIEND if
11144 	 possible.  */
11145       tree new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
11146       tree new_friend_result_template_info = NULL_TREE;
11147       bool new_friend_is_defn =
11148 	(DECL_INITIAL (DECL_TEMPLATE_RESULT
11149 		       (template_for_substitution (new_friend)))
11150 	 != NULL_TREE);
11151       tree not_tmpl = new_friend;
11152 
11153       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11154 	{
11155 	  /* This declaration is a `primary' template.  */
11156 	  DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
11157 
11158 	  not_tmpl = DECL_TEMPLATE_RESULT (new_friend);
11159 	  new_friend_result_template_info = DECL_TEMPLATE_INFO (not_tmpl);
11160 	}
11161 
11162       /* Inside pushdecl_namespace_level, we will push into the
11163 	 current namespace. However, the friend function should go
11164 	 into the namespace of the template.  */
11165       ns = decl_namespace_context (new_friend);
11166       push_nested_namespace (ns);
11167       old_decl = pushdecl_namespace_level (new_friend, /*hiding=*/true);
11168       pop_nested_namespace (ns);
11169 
11170       if (old_decl == error_mark_node)
11171 	return error_mark_node;
11172 
11173       if (old_decl != new_friend)
11174 	{
11175 	  /* This new friend declaration matched an existing
11176 	     declaration.  For example, given:
11177 
11178 	       template <class T> void f(T);
11179 	       template <class U> class C {
11180 		 template <class T> friend void f(T) {}
11181 	       };
11182 
11183 	     the friend declaration actually provides the definition
11184 	     of `f', once C has been instantiated for some type.  So,
11185 	     old_decl will be the out-of-class template declaration,
11186 	     while new_friend is the in-class definition.
11187 
11188 	     But, if `f' was called before this point, the
11189 	     instantiation of `f' will have DECL_TI_ARGS corresponding
11190 	     to `T' but not to `U', references to which might appear
11191 	     in the definition of `f'.  Previously, the most general
11192 	     template for an instantiation of `f' was the out-of-class
11193 	     version; now it is the in-class version.  Therefore, we
11194 	     run through all specialization of `f', adding to their
11195 	     DECL_TI_ARGS appropriately.  In particular, they need a
11196 	     new set of outer arguments, corresponding to the
11197 	     arguments for this class instantiation.
11198 
11199 	     The same situation can arise with something like this:
11200 
11201 	       friend void f(int);
11202 	       template <class T> class C {
11203 		 friend void f(T) {}
11204 	       };
11205 
11206 	     when `C<int>' is instantiated.  Now, `f(int)' is defined
11207 	     in the class.  */
11208 
11209 	  if (!new_friend_is_defn)
11210 	    /* On the other hand, if the in-class declaration does
11211 	       *not* provide a definition, then we don't want to alter
11212 	       existing definitions.  We can just leave everything
11213 	       alone.  */
11214 	    ;
11215 	  else
11216 	    {
11217 	      tree new_template = TI_TEMPLATE (new_friend_template_info);
11218 	      tree new_args = TI_ARGS (new_friend_template_info);
11219 
11220 	      /* Overwrite whatever template info was there before, if
11221 		 any, with the new template information pertaining to
11222 		 the declaration.  */
11223 	      DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
11224 
11225 	      if (TREE_CODE (old_decl) != TEMPLATE_DECL)
11226 		{
11227 		  /* We should have called reregister_specialization in
11228 		     duplicate_decls.  */
11229 		  gcc_assert (retrieve_specialization (new_template,
11230 						       new_args, 0)
11231 			      == old_decl);
11232 
11233 		  /* Instantiate it if the global has already been used.  */
11234 		  if (DECL_ODR_USED (old_decl))
11235 		    instantiate_decl (old_decl, /*defer_ok=*/true,
11236 				      /*expl_inst_class_mem_p=*/false);
11237 		}
11238 	      else
11239 		{
11240 		  tree t;
11241 
11242 		  /* Indicate that the old function template is a partial
11243 		     instantiation.  */
11244 		  DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
11245 		    = new_friend_result_template_info;
11246 
11247 		  gcc_assert (new_template
11248 			      == most_general_template (new_template));
11249 		  gcc_assert (new_template != old_decl);
11250 
11251 		  /* Reassign any specializations already in the hash table
11252 		     to the new more general template, and add the
11253 		     additional template args.  */
11254 		  for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
11255 		       t != NULL_TREE;
11256 		       t = TREE_CHAIN (t))
11257 		    {
11258 		      tree spec = TREE_VALUE (t);
11259 		      spec_entry elt;
11260 
11261 		      elt.tmpl = old_decl;
11262 		      elt.args = DECL_TI_ARGS (spec);
11263 		      elt.spec = NULL_TREE;
11264 
11265 		      decl_specializations->remove_elt (&elt);
11266 
11267 		      DECL_TI_ARGS (spec)
11268 			= add_outermost_template_args (new_args,
11269 						       DECL_TI_ARGS (spec));
11270 
11271 		      register_specialization
11272 			(spec, new_template, DECL_TI_ARGS (spec), true, 0);
11273 
11274 		    }
11275 		  DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
11276 		}
11277 	    }
11278 
11279 	  /* The information from NEW_FRIEND has been merged into OLD_DECL
11280 	     by duplicate_decls.  */
11281 	  new_friend = old_decl;
11282 	}
11283     }
11284   else
11285     {
11286       tree context = DECL_CONTEXT (new_friend);
11287       bool dependent_p;
11288 
11289       /* In the code
11290 	   template <class T> class C {
11291 	     template <class U> friend void C1<U>::f (); // case 1
11292 	     friend void C2<T>::f ();			 // case 2
11293 	   };
11294 	 we only need to make sure CONTEXT is a complete type for
11295 	 case 2.  To distinguish between the two cases, we note that
11296 	 CONTEXT of case 1 remains dependent type after tsubst while
11297 	 this isn't true for case 2.  */
11298       ++processing_template_decl;
11299       dependent_p = dependent_type_p (context);
11300       --processing_template_decl;
11301 
11302       if (!dependent_p
11303 	  && !complete_type_or_else (context, NULL_TREE))
11304 	return error_mark_node;
11305 
11306       if (COMPLETE_TYPE_P (context))
11307 	{
11308 	  tree fn = new_friend;
11309 	  /* do_friend adds the TEMPLATE_DECL for any member friend
11310 	     template even if it isn't a member template, i.e.
11311 	       template <class T> friend A<T>::f();
11312 	     Look through it in that case.  */
11313 	  if (TREE_CODE (fn) == TEMPLATE_DECL
11314 	      && !PRIMARY_TEMPLATE_P (fn))
11315 	    fn = DECL_TEMPLATE_RESULT (fn);
11316 	  /* Check to see that the declaration is really present, and,
11317 	     possibly obtain an improved declaration.  */
11318 	  fn = check_classfn (context, fn, NULL_TREE);
11319 
11320 	  if (fn)
11321 	    new_friend = fn;
11322 	}
11323     }
11324 
11325   return new_friend;
11326 }
11327 
11328 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
11329    template arguments, as for tsubst.
11330 
11331    Returns an appropriate tsubst'd friend type or error_mark_node on
11332    failure.  */
11333 
11334 static tree
tsubst_friend_class(tree friend_tmpl,tree args)11335 tsubst_friend_class (tree friend_tmpl, tree args)
11336 {
11337   tree tmpl;
11338 
11339   if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
11340     {
11341       tmpl = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
11342       return TREE_TYPE (tmpl);
11343     }
11344 
11345   tree context = CP_DECL_CONTEXT (friend_tmpl);
11346   if (TREE_CODE (context) == NAMESPACE_DECL)
11347     push_nested_namespace (context);
11348   else
11349     {
11350       context = tsubst (context, args, tf_error, NULL_TREE);
11351       push_nested_class (context);
11352     }
11353 
11354   tmpl = lookup_name (DECL_NAME (friend_tmpl), LOOK_where::CLASS_NAMESPACE,
11355 		      LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND);
11356 
11357   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
11358     {
11359       /* The friend template has already been declared.  Just
11360 	 check to see that the declarations match, and install any new
11361 	 default parameters.  We must tsubst the default parameters,
11362 	 of course.  We only need the innermost template parameters
11363 	 because that is all that redeclare_class_template will look
11364 	 at.  */
11365       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
11366 	  > TMPL_ARGS_DEPTH (args))
11367 	{
11368 	  tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
11369 					      args, tf_warning_or_error);
11370           location_t saved_input_location = input_location;
11371           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
11372           tree cons = get_constraints (tmpl);
11373           redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
11374           input_location = saved_input_location;
11375 	}
11376     }
11377   else
11378     {
11379       /* The friend template has not already been declared.  In this
11380 	 case, the instantiation of the template class will cause the
11381 	 injection of this template into the namespace scope.  */
11382       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
11383 
11384       if (tmpl != error_mark_node)
11385 	{
11386 	  /* The new TMPL is not an instantiation of anything, so we
11387 	     forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE
11388 	     for the new type because that is supposed to be the
11389 	     corresponding template decl, i.e., TMPL.  */
11390 	  DECL_USE_TEMPLATE (tmpl) = 0;
11391 	  DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
11392 	  CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
11393 	  CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
11394 	    = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
11395 
11396 	  /* Substitute into and set the constraints on the new declaration.  */
11397 	  if (tree ci = get_constraints (friend_tmpl))
11398 	    {
11399 	      ++processing_template_decl;
11400 	      ci = tsubst_constraint_info (ci, args, tf_warning_or_error,
11401 					   DECL_FRIEND_CONTEXT (friend_tmpl));
11402 	      --processing_template_decl;
11403 	      set_constraints (tmpl, ci);
11404 	    }
11405 
11406 	  /* Inject this template into the enclosing namspace scope.  */
11407 	  tmpl = pushdecl_namespace_level (tmpl, /*hiding=*/true);
11408 	}
11409     }
11410 
11411   if (TREE_CODE (context) == NAMESPACE_DECL)
11412     pop_nested_namespace (context);
11413   else
11414     pop_nested_class ();
11415 
11416   return TREE_TYPE (tmpl);
11417 }
11418 
11419 /* Returns zero if TYPE cannot be completed later due to circularity.
11420    Otherwise returns one.  */
11421 
11422 static int
can_complete_type_without_circularity(tree type)11423 can_complete_type_without_circularity (tree type)
11424 {
11425   if (type == NULL_TREE || type == error_mark_node)
11426     return 0;
11427   else if (COMPLETE_TYPE_P (type))
11428     return 1;
11429   else if (TREE_CODE (type) == ARRAY_TYPE)
11430     return can_complete_type_without_circularity (TREE_TYPE (type));
11431   else if (CLASS_TYPE_P (type)
11432 	   && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
11433     return 0;
11434   else
11435     return 1;
11436 }
11437 
11438 static tree tsubst_omp_clauses (tree, enum c_omp_region_type, tree,
11439 				tsubst_flags_t, tree);
11440 
11441 /* Instantiate a single dependent attribute T (a TREE_LIST), and return either
11442    T or a new TREE_LIST, possibly a chain in the case of a pack expansion.  */
11443 
11444 static tree
tsubst_attribute(tree t,tree * decl_p,tree args,tsubst_flags_t complain,tree in_decl)11445 tsubst_attribute (tree t, tree *decl_p, tree args,
11446 		  tsubst_flags_t complain, tree in_decl)
11447 {
11448   gcc_assert (ATTR_IS_DEPENDENT (t));
11449 
11450   tree val = TREE_VALUE (t);
11451   if (val == NULL_TREE)
11452     /* Nothing to do.  */;
11453   else if ((flag_openmp || flag_openmp_simd)
11454 	   && is_attribute_p ("omp declare simd",
11455 			      get_attribute_name (t)))
11456     {
11457       tree clauses = TREE_VALUE (val);
11458       clauses = tsubst_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD, args,
11459 				    complain, in_decl);
11460       c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11461       clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11462       tree parms = DECL_ARGUMENTS (*decl_p);
11463       clauses
11464 	= c_omp_declare_simd_clauses_to_numbers (parms, clauses);
11465       if (clauses)
11466 	val = build_tree_list (NULL_TREE, clauses);
11467       else
11468 	val = NULL_TREE;
11469     }
11470   else if (flag_openmp
11471 	   && is_attribute_p ("omp declare variant base",
11472 			      get_attribute_name (t)))
11473     {
11474       ++cp_unevaluated_operand;
11475       tree varid
11476 	= tsubst_expr (TREE_PURPOSE (val), args, complain,
11477 		       in_decl, /*integral_constant_expression_p=*/false);
11478       --cp_unevaluated_operand;
11479       tree chain = TREE_CHAIN (val);
11480       location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
11481       tree ctx = copy_list (TREE_VALUE (val));
11482       tree simd = get_identifier ("simd");
11483       tree score = get_identifier (" score");
11484       tree condition = get_identifier ("condition");
11485       for (tree t1 = ctx; t1; t1 = TREE_CHAIN (t1))
11486 	{
11487 	  const char *set = IDENTIFIER_POINTER (TREE_PURPOSE (t1));
11488 	  TREE_VALUE (t1) = copy_list (TREE_VALUE (t1));
11489 	  for (tree t2 = TREE_VALUE (t1); t2; t2 = TREE_CHAIN (t2))
11490 	    {
11491 	      if (TREE_PURPOSE (t2) == simd && set[0] == 'c')
11492 		{
11493 		  tree clauses = TREE_VALUE (t2);
11494 		  clauses = tsubst_omp_clauses (clauses,
11495 						C_ORT_OMP_DECLARE_SIMD, args,
11496 						complain, in_decl);
11497 		  c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11498 		  clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11499 		  TREE_VALUE (t2) = clauses;
11500 		}
11501 	      else
11502 		{
11503 		  TREE_VALUE (t2) = copy_list (TREE_VALUE (t2));
11504 		  for (tree t3 = TREE_VALUE (t2); t3; t3 = TREE_CHAIN (t3))
11505 		    if (TREE_VALUE (t3))
11506 		      {
11507 			bool allow_string
11508 			  = ((TREE_PURPOSE (t2) != condition || set[0] != 'u')
11509 			     && TREE_PURPOSE (t3) != score);
11510 			tree v = TREE_VALUE (t3);
11511 			if (TREE_CODE (v) == STRING_CST && allow_string)
11512 			  continue;
11513 			v = tsubst_expr (v, args, complain, in_decl, true);
11514 			v = fold_non_dependent_expr (v);
11515 			if (!INTEGRAL_TYPE_P (TREE_TYPE (v))
11516 			    || (TREE_PURPOSE (t3) == score
11517 				? TREE_CODE (v) != INTEGER_CST
11518 				: !tree_fits_shwi_p (v)))
11519 			  {
11520 			    location_t loc
11521 			      = cp_expr_loc_or_loc (TREE_VALUE (t3),
11522 						    match_loc);
11523 			    if (TREE_PURPOSE (t3) == score)
11524 			      error_at (loc, "score argument must be "
11525 					     "constant integer expression");
11526 			    else if (allow_string)
11527 			      error_at (loc, "property must be constant "
11528 					     "integer expression or string "
11529 					     "literal");
11530 			    else
11531 			      error_at (loc, "property must be constant "
11532 					     "integer expression");
11533 			    return NULL_TREE;
11534 			  }
11535 			else if (TREE_PURPOSE (t3) == score
11536 				 && tree_int_cst_sgn (v) < 0)
11537 			  {
11538 			    location_t loc
11539 			      = cp_expr_loc_or_loc (TREE_VALUE (t3),
11540 						    match_loc);
11541 			    error_at (loc, "score argument must be "
11542 					   "non-negative");
11543 			    return NULL_TREE;
11544 			  }
11545 			TREE_VALUE (t3) = v;
11546 		      }
11547 		}
11548 	    }
11549 	}
11550       val = tree_cons (varid, ctx, chain);
11551     }
11552   /* If the first attribute argument is an identifier, don't
11553      pass it through tsubst.  Attributes like mode, format,
11554      cleanup and several target specific attributes expect it
11555      unmodified.  */
11556   else if (attribute_takes_identifier_p (get_attribute_name (t)))
11557     {
11558       tree chain
11559 	= tsubst_expr (TREE_CHAIN (val), args, complain, in_decl,
11560 		       /*integral_constant_expression_p=*/false);
11561       if (chain != TREE_CHAIN (val))
11562 	val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
11563     }
11564   else if (PACK_EXPANSION_P (val))
11565     {
11566       /* An attribute pack expansion.  */
11567       tree purp = TREE_PURPOSE (t);
11568       tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
11569       if (pack == error_mark_node)
11570 	return error_mark_node;
11571       int len = TREE_VEC_LENGTH (pack);
11572       tree list = NULL_TREE;
11573       tree *q = &list;
11574       for (int i = 0; i < len; ++i)
11575 	{
11576 	  tree elt = TREE_VEC_ELT (pack, i);
11577 	  *q = build_tree_list (purp, elt);
11578 	  q = &TREE_CHAIN (*q);
11579 	}
11580       return list;
11581     }
11582   else
11583     val = tsubst_expr (val, args, complain, in_decl,
11584 		       /*integral_constant_expression_p=*/false);
11585 
11586   if (val == error_mark_node)
11587     return error_mark_node;
11588   if (val != TREE_VALUE (t))
11589     return build_tree_list (TREE_PURPOSE (t), val);
11590   return t;
11591 }
11592 
11593 /* Instantiate any dependent attributes in ATTRIBUTES, returning either it
11594    unchanged or a new TREE_LIST chain.  */
11595 
11596 static tree
tsubst_attributes(tree attributes,tree args,tsubst_flags_t complain,tree in_decl)11597 tsubst_attributes (tree attributes, tree args,
11598 		   tsubst_flags_t complain, tree in_decl)
11599 {
11600   tree last_dep = NULL_TREE;
11601 
11602   for (tree t = attributes; t; t = TREE_CHAIN (t))
11603     if (ATTR_IS_DEPENDENT (t))
11604       {
11605 	last_dep = t;
11606 	attributes = copy_list (attributes);
11607 	break;
11608       }
11609 
11610   if (last_dep)
11611     for (tree *p = &attributes; *p; )
11612       {
11613 	tree t = *p;
11614 	if (ATTR_IS_DEPENDENT (t))
11615 	  {
11616 	    tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
11617 	    if (subst != t)
11618 	      {
11619 		*p = subst;
11620 		while (*p)
11621 		  p = &TREE_CHAIN (*p);
11622 		*p = TREE_CHAIN (t);
11623 		continue;
11624 	      }
11625 	  }
11626 	p = &TREE_CHAIN (*p);
11627       }
11628 
11629   return attributes;
11630 }
11631 
11632 /* Apply any attributes which had to be deferred until instantiation
11633    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
11634    ARGS, COMPLAIN, IN_DECL are as tsubst.  Returns true normally,
11635    false on error.  */
11636 
11637 static bool
apply_late_template_attributes(tree * decl_p,tree attributes,int attr_flags,tree args,tsubst_flags_t complain,tree in_decl)11638 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
11639 				tree args, tsubst_flags_t complain, tree in_decl)
11640 {
11641   tree last_dep = NULL_TREE;
11642   tree t;
11643   tree *p;
11644 
11645   if (attributes == NULL_TREE)
11646     return true;
11647 
11648   if (DECL_P (*decl_p))
11649     {
11650       if (TREE_TYPE (*decl_p) == error_mark_node)
11651 	return false;
11652       p = &DECL_ATTRIBUTES (*decl_p);
11653       /* DECL_ATTRIBUTES comes from copy_node in tsubst_decl, and is identical
11654          to our attributes parameter.  */
11655       gcc_assert (*p == attributes);
11656     }
11657   else
11658     {
11659       p = &TYPE_ATTRIBUTES (*decl_p);
11660       /* TYPE_ATTRIBUTES was set up (with abi_tag and may_alias) in
11661 	 lookup_template_class_1, and should be preserved.  */
11662       gcc_assert (*p != attributes);
11663       while (*p)
11664 	p = &TREE_CHAIN (*p);
11665     }
11666 
11667   for (t = attributes; t; t = TREE_CHAIN (t))
11668     if (ATTR_IS_DEPENDENT (t))
11669       {
11670 	last_dep = t;
11671 	attributes = copy_list (attributes);
11672 	break;
11673       }
11674 
11675   *p = attributes;
11676   if (last_dep)
11677     {
11678       tree late_attrs = NULL_TREE;
11679       tree *q = &late_attrs;
11680 
11681       for (; *p; )
11682 	{
11683 	  t = *p;
11684 	  if (ATTR_IS_DEPENDENT (t))
11685 	    {
11686 	      *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
11687 	      if (*q == error_mark_node)
11688 		return false;
11689 	      *p = TREE_CHAIN (t);
11690 	      TREE_CHAIN (t) = NULL_TREE;
11691 	      while (*q)
11692 		q = &TREE_CHAIN (*q);
11693 	    }
11694 	  else
11695 	    p = &TREE_CHAIN (t);
11696 	}
11697 
11698       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
11699     }
11700   return true;
11701 }
11702 
11703 /* The template TMPL is being instantiated with the template arguments TARGS.
11704    Perform the access checks that we deferred when parsing the template.  */
11705 
11706 static void
perform_instantiation_time_access_checks(tree tmpl,tree targs)11707 perform_instantiation_time_access_checks (tree tmpl, tree targs)
11708 {
11709   unsigned i;
11710   deferred_access_check *chk;
11711 
11712   if (!CLASS_TYPE_P (tmpl) && TREE_CODE (tmpl) != FUNCTION_DECL)
11713     return;
11714 
11715   if (vec<deferred_access_check, va_gc> *access_checks
11716       = TI_DEFERRED_ACCESS_CHECKS (get_template_info (tmpl)))
11717     FOR_EACH_VEC_ELT (*access_checks, i, chk)
11718       {
11719 	tree decl = chk->decl;
11720 	tree diag_decl = chk->diag_decl;
11721 	tree type_scope = TREE_TYPE (chk->binfo);
11722 
11723 	if (uses_template_parms (type_scope))
11724 	  type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
11725 
11726 	/* Make access check error messages point to the location
11727 	   of the use of the typedef.  */
11728 	iloc_sentinel ils (chk->loc);
11729 	perform_or_defer_access_check (TYPE_BINFO (type_scope),
11730 				       decl, diag_decl, tf_warning_or_error);
11731       }
11732 }
11733 
11734 static tree
instantiate_class_template_1(tree type)11735 instantiate_class_template_1 (tree type)
11736 {
11737   tree templ, args, pattern, t, member;
11738   tree typedecl;
11739   tree pbinfo;
11740   tree base_list;
11741   unsigned int saved_maximum_field_alignment;
11742   tree fn_context;
11743 
11744   if (type == error_mark_node)
11745     return error_mark_node;
11746 
11747   if (COMPLETE_OR_OPEN_TYPE_P (type)
11748       || uses_template_parms (type))
11749     return type;
11750 
11751   /* Figure out which template is being instantiated.  */
11752   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
11753   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
11754 
11755   /* Mark the type as in the process of being defined.  */
11756   TYPE_BEING_DEFINED (type) = 1;
11757 
11758   /* We may be in the middle of deferred access check.  Disable
11759      it now.  */
11760   deferring_access_check_sentinel acs (dk_no_deferred);
11761 
11762   /* Determine what specialization of the original template to
11763      instantiate.  */
11764   t = most_specialized_partial_spec (type, tf_warning_or_error);
11765   if (t == error_mark_node)
11766     return error_mark_node;
11767   else if (t)
11768     {
11769       /* This TYPE is actually an instantiation of a partial
11770 	 specialization.  We replace the innermost set of ARGS with
11771 	 the arguments appropriate for substitution.  For example,
11772 	 given:
11773 
11774 	   template <class T> struct S {};
11775 	   template <class T> struct S<T*> {};
11776 
11777 	 and supposing that we are instantiating S<int*>, ARGS will
11778 	 presently be {int*} -- but we need {int}.  */
11779       pattern = TREE_TYPE (t);
11780       args = TREE_PURPOSE (t);
11781     }
11782   else
11783     {
11784       pattern = TREE_TYPE (templ);
11785       args = CLASSTYPE_TI_ARGS (type);
11786     }
11787 
11788   /* If the template we're instantiating is incomplete, then clearly
11789      there's nothing we can do.  */
11790   if (!COMPLETE_TYPE_P (pattern))
11791     {
11792       /* We can try again later.  */
11793       TYPE_BEING_DEFINED (type) = 0;
11794       return type;
11795     }
11796 
11797   /* If we've recursively instantiated too many templates, stop.  */
11798   if (! push_tinst_level (type))
11799     return type;
11800 
11801   int saved_unevaluated_operand = cp_unevaluated_operand;
11802   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
11803 
11804   fn_context = decl_function_context (TYPE_MAIN_DECL (type));
11805   /* Also avoid push_to_top_level for a lambda in an NSDMI.  */
11806   if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
11807     fn_context = error_mark_node;
11808   if (!fn_context)
11809     push_to_top_level ();
11810   else
11811     {
11812       cp_unevaluated_operand = 0;
11813       c_inhibit_evaluation_warnings = 0;
11814     }
11815   /* Use #pragma pack from the template context.  */
11816   saved_maximum_field_alignment = maximum_field_alignment;
11817   maximum_field_alignment = TYPE_PRECISION (pattern);
11818 
11819   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
11820 
11821   /* Set the input location to the most specialized template definition.
11822      This is needed if tsubsting causes an error.  */
11823   typedecl = TYPE_MAIN_DECL (pattern);
11824   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
11825     DECL_SOURCE_LOCATION (typedecl);
11826 
11827   set_instantiating_module (TYPE_NAME (type));
11828 
11829   TYPE_PACKED (type) = TYPE_PACKED (pattern);
11830   SET_TYPE_ALIGN (type, TYPE_ALIGN (pattern));
11831   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
11832   CLASSTYPE_NON_AGGREGATE (type) = CLASSTYPE_NON_AGGREGATE (pattern);
11833   if (ANON_AGGR_TYPE_P (pattern))
11834     SET_ANON_AGGR_TYPE_P (type);
11835   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
11836     {
11837       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
11838       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
11839       /* Adjust visibility for template arguments.  */
11840       determine_visibility (TYPE_MAIN_DECL (type));
11841     }
11842   if (CLASS_TYPE_P (type))
11843     CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
11844 
11845   pbinfo = TYPE_BINFO (pattern);
11846 
11847   /* We should never instantiate a nested class before its enclosing
11848      class; we need to look up the nested class by name before we can
11849      instantiate it, and that lookup should instantiate the enclosing
11850      class.  */
11851   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
11852 	      || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
11853 
11854   base_list = NULL_TREE;
11855   /* Defer access checking while we substitute into the types named in
11856      the base-clause.  */
11857   push_deferring_access_checks (dk_deferred);
11858   if (BINFO_N_BASE_BINFOS (pbinfo))
11859     {
11860       tree pbase_binfo;
11861       int i;
11862 
11863       /* Substitute into each of the bases to determine the actual
11864 	 basetypes.  */
11865       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
11866 	{
11867 	  tree base;
11868 	  tree access = BINFO_BASE_ACCESS (pbinfo, i);
11869           tree expanded_bases = NULL_TREE;
11870           int idx, len = 1;
11871 
11872           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
11873             {
11874               expanded_bases =
11875 		tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
11876 				       args, tf_error, NULL_TREE);
11877               if (expanded_bases == error_mark_node)
11878                 continue;
11879 
11880               len = TREE_VEC_LENGTH (expanded_bases);
11881             }
11882 
11883           for (idx = 0; idx < len; idx++)
11884             {
11885               if (expanded_bases)
11886                 /* Extract the already-expanded base class.  */
11887                 base = TREE_VEC_ELT (expanded_bases, idx);
11888               else
11889                 /* Substitute to figure out the base class.  */
11890                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
11891                                NULL_TREE);
11892 
11893               if (base == error_mark_node)
11894                 continue;
11895 
11896               base_list = tree_cons (access, base, base_list);
11897               if (BINFO_VIRTUAL_P (pbase_binfo))
11898                 TREE_TYPE (base_list) = integer_type_node;
11899             }
11900 	}
11901 
11902       /* The list is now in reverse order; correct that.  */
11903       base_list = nreverse (base_list);
11904     }
11905   /* Now call xref_basetypes to set up all the base-class
11906      information.  */
11907   xref_basetypes (type, base_list);
11908 
11909   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
11910 				  (int) ATTR_FLAG_TYPE_IN_PLACE,
11911 				  args, tf_error, NULL_TREE);
11912   fixup_attribute_variants (type);
11913 
11914   /* Now that our base classes are set up, enter the scope of the
11915      class, so that name lookups into base classes, etc. will work
11916      correctly.  This is precisely analogous to what we do in
11917      begin_class_definition when defining an ordinary non-template
11918      class, except we also need to push the enclosing classes.  */
11919   push_nested_class (type);
11920 
11921   /* Now check accessibility of the types named in its base-clause,
11922      relative to the scope of the class.  */
11923   pop_to_parent_deferring_access_checks ();
11924 
11925   /* A vector to hold members marked with attribute used. */
11926   auto_vec<tree> used;
11927 
11928   /* Now members are processed in the order of declaration.  */
11929   for (member = CLASSTYPE_DECL_LIST (pattern);
11930        member; member = TREE_CHAIN (member))
11931     {
11932       tree t = TREE_VALUE (member);
11933 
11934       if (TREE_PURPOSE (member))
11935 	{
11936 	  if (TYPE_P (t))
11937 	    {
11938 	      if (LAMBDA_TYPE_P (t))
11939 		/* A closure type for a lambda in an NSDMI or default argument.
11940 		   Ignore it; it will be regenerated when needed.  */
11941 		continue;
11942 
11943 	      bool class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
11944 				       && TYPE_LANG_SPECIFIC (t)
11945 				       && CLASSTYPE_IS_TEMPLATE (t));
11946 
11947 	      /* If the member is a class template, then -- even after
11948 		 substitution -- there may be dependent types in the
11949 		 template argument list for the class.  We increment
11950 		 PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
11951 		 that function will assume that no types are dependent
11952 		 when outside of a template.  */
11953 	      if (class_template_p)
11954 		++processing_template_decl;
11955 	      tree newtag = tsubst (t, args, tf_error, NULL_TREE);
11956 	      if (class_template_p)
11957 		--processing_template_decl;
11958 	      if (newtag == error_mark_node)
11959 		continue;
11960 
11961 	      if (TREE_CODE (newtag) != ENUMERAL_TYPE)
11962 		{
11963 		  tree name = TYPE_IDENTIFIER (t);
11964 
11965 		  if (class_template_p)
11966 		    /* Unfortunately, lookup_template_class sets
11967 		       CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
11968 		       instantiation (i.e., for the type of a member
11969 		       template class nested within a template class.)
11970 		       This behavior is required for
11971 		       maybe_process_partial_specialization to work
11972 		       correctly, but is not accurate in this case;
11973 		       the TAG is not an instantiation of anything.
11974 		       (The corresponding TEMPLATE_DECL is an
11975 		       instantiation, but the TYPE is not.) */
11976 		    CLASSTYPE_USE_TEMPLATE (newtag) = 0;
11977 
11978 		  /* Now, install the tag.  We don't use pushtag
11979 		     because that does too much work -- creating an
11980 		     implicit typedef, which we've already done.  */
11981 		  set_identifier_type_value (name, TYPE_NAME (newtag));
11982 		  maybe_add_class_template_decl_list (type, newtag, false);
11983 		  TREE_PUBLIC (TYPE_NAME (newtag)) = true;
11984 		  determine_visibility (TYPE_NAME (newtag));
11985 		}
11986 	    }
11987 	  else if (DECL_DECLARES_FUNCTION_P (t))
11988 	    {
11989 	      tree r;
11990 
11991 	      if (TREE_CODE (t) == TEMPLATE_DECL)
11992 		++processing_template_decl;
11993 	      r = tsubst (t, args, tf_error, NULL_TREE);
11994 	      if (TREE_CODE (t) == TEMPLATE_DECL)
11995 		--processing_template_decl;
11996 	      set_current_access_from_decl (r);
11997 	      finish_member_declaration (r);
11998 	      /* Instantiate members marked with attribute used.  */
11999 	      if (r != error_mark_node && DECL_PRESERVE_P (r))
12000 		used.safe_push (r);
12001 	      if (TREE_CODE (r) == FUNCTION_DECL
12002 		  && DECL_OMP_DECLARE_REDUCTION_P (r))
12003 		cp_check_omp_declare_reduction (r);
12004 	    }
12005 	  else if ((DECL_CLASS_TEMPLATE_P (t) || DECL_IMPLICIT_TYPEDEF_P (t))
12006 		   && LAMBDA_TYPE_P (TREE_TYPE (t)))
12007 	    /* A closure type for a lambda in an NSDMI or default argument.
12008 	       Ignore it; it will be regenerated when needed.  */;
12009 	  else
12010 	    {
12011 	      /* Build new TYPE_FIELDS.  */
12012               if (TREE_CODE (t) == STATIC_ASSERT)
12013 		tsubst_expr (t, args, tf_warning_or_error, NULL_TREE,
12014 			     /*integral_constant_expression_p=*/true);
12015 	      else if (TREE_CODE (t) != CONST_DECL)
12016 		{
12017 		  tree r;
12018 		  tree vec = NULL_TREE;
12019 		  int len = 1;
12020 
12021 		  gcc_checking_assert (TREE_CODE (t) != CONST_DECL);
12022 		  /* The file and line for this declaration, to
12023 		     assist in error message reporting.  Since we
12024 		     called push_tinst_level above, we don't need to
12025 		     restore these.  */
12026 		  input_location = DECL_SOURCE_LOCATION (t);
12027 
12028 		  if (TREE_CODE (t) == TEMPLATE_DECL)
12029 		    ++processing_template_decl;
12030 		  r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
12031 		  if (TREE_CODE (t) == TEMPLATE_DECL)
12032 		    --processing_template_decl;
12033 
12034 		  if (TREE_CODE (r) == TREE_VEC)
12035 		    {
12036 		      /* A capture pack became multiple fields.  */
12037 		      vec = r;
12038 		      len = TREE_VEC_LENGTH (vec);
12039 		    }
12040 
12041 		  for (int i = 0; i < len; ++i)
12042 		    {
12043 		      if (vec)
12044 			r = TREE_VEC_ELT (vec, i);
12045 		      if (VAR_P (r))
12046 			{
12047 			  /* In [temp.inst]:
12048 
12049 			     [t]he initialization (and any associated
12050 			     side-effects) of a static data member does
12051 			     not occur unless the static data member is
12052 			     itself used in a way that requires the
12053 			     definition of the static data member to
12054 			     exist.
12055 
12056 			     Therefore, we do not substitute into the
12057 			     initialized for the static data member here.  */
12058 			  finish_static_data_member_decl
12059 			    (r,
12060 			     /*init=*/NULL_TREE,
12061 			     /*init_const_expr_p=*/false,
12062 			     /*asmspec_tree=*/NULL_TREE,
12063 			     /*flags=*/0);
12064 			  /* Instantiate members marked with attribute used. */
12065 			  if (r != error_mark_node && DECL_PRESERVE_P (r))
12066 			    used.safe_push (r);
12067 			}
12068 		      else if (TREE_CODE (r) == FIELD_DECL)
12069 			{
12070 			  /* Determine whether R has a valid type and can be
12071 			     completed later.  If R is invalid, then its type
12072 			     is replaced by error_mark_node.  */
12073 			  tree rtype = TREE_TYPE (r);
12074 			  if (can_complete_type_without_circularity (rtype))
12075 			    complete_type (rtype);
12076 
12077 			  if (!complete_or_array_type_p (rtype))
12078 			    {
12079 			      /* If R's type couldn't be completed and
12080 				 it isn't a flexible array member (whose
12081 				 type is incomplete by definition) give
12082 				 an error.  */
12083 			      cxx_incomplete_type_error (r, rtype);
12084 			      TREE_TYPE (r) = error_mark_node;
12085 			    }
12086 			  else if (TREE_CODE (rtype) == ARRAY_TYPE
12087 				   && TYPE_DOMAIN (rtype) == NULL_TREE
12088 				   && (TREE_CODE (type) == UNION_TYPE
12089 				       || TREE_CODE (type) == QUAL_UNION_TYPE))
12090 			    {
12091 			      error ("flexible array member %qD in union", r);
12092 			      TREE_TYPE (r) = error_mark_node;
12093 			    }
12094 			  else if (!verify_type_context (input_location,
12095 							 TCTX_FIELD, rtype))
12096 			    TREE_TYPE (r) = error_mark_node;
12097 			}
12098 
12099 		      /* If it is a TYPE_DECL for a class-scoped
12100 			 ENUMERAL_TYPE, such a thing will already have
12101 			 been added to the field list by tsubst_enum
12102 			 in finish_member_declaration case above.  */
12103 		      if (!(TREE_CODE (r) == TYPE_DECL
12104 			    && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
12105 			    && DECL_ARTIFICIAL (r)))
12106 			{
12107 			  set_current_access_from_decl (r);
12108 			  finish_member_declaration (r);
12109 			}
12110 		    }
12111 		}
12112 	    }
12113 	}
12114       else
12115 	{
12116 	  if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
12117 	      || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
12118 	    {
12119 	      /* Build new CLASSTYPE_FRIEND_CLASSES.  */
12120 
12121 	      tree friend_type = t;
12122 	      bool adjust_processing_template_decl = false;
12123 
12124 	      if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12125 		{
12126 		  /* template <class T> friend class C;  */
12127 		  friend_type = tsubst_friend_class (friend_type, args);
12128 		  adjust_processing_template_decl = true;
12129 		}
12130 	      else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
12131 		{
12132 		  /* template <class T> friend class C::D;  */
12133 		  friend_type = tsubst (friend_type, args,
12134 					tf_warning_or_error, NULL_TREE);
12135 		  if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12136 		    friend_type = TREE_TYPE (friend_type);
12137 		  adjust_processing_template_decl = true;
12138 		}
12139 	      else if (TREE_CODE (friend_type) == TYPENAME_TYPE
12140 		       || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
12141 		{
12142 		  /* This could be either
12143 
12144 		       friend class T::C;
12145 
12146 		     when dependent_type_p is false or
12147 
12148 		       template <class U> friend class T::C;
12149 
12150 		     otherwise.  */
12151 		  /* Bump processing_template_decl in case this is something like
12152 		     template <class T> friend struct A<T>::B.  */
12153 		  ++processing_template_decl;
12154 		  friend_type = tsubst (friend_type, args,
12155 					tf_warning_or_error, NULL_TREE);
12156 		  if (dependent_type_p (friend_type))
12157 		    adjust_processing_template_decl = true;
12158 		  --processing_template_decl;
12159 		}
12160 	      else if (uses_template_parms (friend_type))
12161 		/* friend class C<T>;  */
12162 		friend_type = tsubst (friend_type, args,
12163 				      tf_warning_or_error, NULL_TREE);
12164 
12165 	      /* Otherwise it's
12166 
12167 		   friend class C;
12168 
12169 		 where C is already declared or
12170 
12171 		   friend class C<int>;
12172 
12173 		 We don't have to do anything in these cases.  */
12174 
12175 	      if (adjust_processing_template_decl)
12176 		/* Trick make_friend_class into realizing that the friend
12177 		   we're adding is a template, not an ordinary class.  It's
12178 		   important that we use make_friend_class since it will
12179 		   perform some error-checking and output cross-reference
12180 		   information.  */
12181 		++processing_template_decl;
12182 
12183 	      if (friend_type != error_mark_node)
12184 		make_friend_class (type, friend_type, /*complain=*/false);
12185 
12186 	      if (adjust_processing_template_decl)
12187 		--processing_template_decl;
12188 	    }
12189 	  else
12190 	    {
12191 	      /* Build new DECL_FRIENDLIST.  */
12192 	      tree r;
12193 
12194 	      /* The file and line for this declaration, to
12195 		 assist in error message reporting.  Since we
12196 		 called push_tinst_level above, we don't need to
12197 		 restore these.  */
12198 	      input_location = DECL_SOURCE_LOCATION (t);
12199 
12200 	      if (TREE_CODE (t) == TEMPLATE_DECL)
12201 		{
12202 		  ++processing_template_decl;
12203 		  push_deferring_access_checks (dk_no_check);
12204 		}
12205 
12206 	      r = tsubst_friend_function (t, args);
12207 	      add_friend (type, r, /*complain=*/false);
12208 	      if (TREE_CODE (t) == TEMPLATE_DECL)
12209 		{
12210 		  pop_deferring_access_checks ();
12211 		  --processing_template_decl;
12212 		}
12213 	    }
12214 	}
12215     }
12216 
12217   if (fn_context)
12218     {
12219       /* Restore these before substituting into the lambda capture
12220 	 initializers.  */
12221       cp_unevaluated_operand = saved_unevaluated_operand;
12222       c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
12223     }
12224 
12225   /* Set the file and line number information to whatever is given for
12226      the class itself.  This puts error messages involving generated
12227      implicit functions at a predictable point, and the same point
12228      that would be used for non-template classes.  */
12229   input_location = DECL_SOURCE_LOCATION (typedecl);
12230 
12231   unreverse_member_declarations (type);
12232   finish_struct_1 (type);
12233   TYPE_BEING_DEFINED (type) = 0;
12234 
12235   /* We don't instantiate default arguments for member functions.  14.7.1:
12236 
12237      The implicit instantiation of a class template specialization causes
12238      the implicit instantiation of the declarations, but not of the
12239      definitions or default arguments, of the class member functions,
12240      member classes, static data members and member templates....  */
12241 
12242   perform_instantiation_time_access_checks (pattern, args);
12243   perform_deferred_access_checks (tf_warning_or_error);
12244   pop_nested_class ();
12245   maximum_field_alignment = saved_maximum_field_alignment;
12246   if (!fn_context)
12247     pop_from_top_level ();
12248   pop_tinst_level ();
12249 
12250   /* The vtable for a template class can be emitted in any translation
12251      unit in which the class is instantiated.  When there is no key
12252      method, however, finish_struct_1 will already have added TYPE to
12253      the keyed_classes.  */
12254   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
12255     vec_safe_push (keyed_classes, type);
12256 
12257   /* Now that we've gone through all the members, instantiate those
12258      marked with attribute used.  */
12259   for (tree x : used)
12260     mark_used (x);
12261 
12262   return type;
12263 }
12264 
12265 /* Wrapper for instantiate_class_template_1.  */
12266 
12267 tree
instantiate_class_template(tree type)12268 instantiate_class_template (tree type)
12269 {
12270   tree ret;
12271   timevar_push (TV_TEMPLATE_INST);
12272   ret = instantiate_class_template_1 (type);
12273   timevar_pop (TV_TEMPLATE_INST);
12274   return ret;
12275 }
12276 
12277 tree
tsubst_template_arg(tree t,tree args,tsubst_flags_t complain,tree in_decl)12278 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12279 {
12280   tree r;
12281 
12282   if (!t)
12283     r = t;
12284   else if (TYPE_P (t))
12285     r = tsubst (t, args, complain, in_decl);
12286   else
12287     {
12288       if (!(complain & tf_warning))
12289 	++c_inhibit_evaluation_warnings;
12290       r = tsubst_expr (t, args, complain, in_decl,
12291 		       /*integral_constant_expression_p=*/true);
12292       if (!(complain & tf_warning))
12293 	--c_inhibit_evaluation_warnings;
12294     }
12295 
12296   return r;
12297 }
12298 
12299 /* Given a function parameter pack TMPL_PARM and some function parameters
12300    instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
12301    and set *SPEC_P to point at the next point in the list.  */
12302 
12303 tree
extract_fnparm_pack(tree tmpl_parm,tree * spec_p)12304 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
12305 {
12306   /* Collect all of the extra "packed" parameters into an
12307      argument pack.  */
12308   tree argpack;
12309   tree spec_parm = *spec_p;
12310   int len;
12311 
12312   for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
12313     if (tmpl_parm
12314 	&& !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
12315       break;
12316 
12317   spec_parm = *spec_p;
12318   if (len == 1 && DECL_PACK_P (spec_parm))
12319     {
12320       /* The instantiation is still a parameter pack; don't wrap it in a
12321 	 NONTYPE_ARGUMENT_PACK.  */
12322       argpack = spec_parm;
12323       spec_parm = DECL_CHAIN (spec_parm);
12324     }
12325   else
12326     {
12327       /* Fill in PARMVEC with all of the parameters.  */
12328       tree parmvec = make_tree_vec (len);
12329       argpack = make_node (NONTYPE_ARGUMENT_PACK);
12330       for (int i = 0; i < len; i++)
12331 	{
12332 	  tree elt = spec_parm;
12333 	  if (DECL_PACK_P (elt))
12334 	    elt = make_pack_expansion (elt);
12335 	  TREE_VEC_ELT (parmvec, i) = elt;
12336 	  spec_parm = DECL_CHAIN (spec_parm);
12337 	}
12338 
12339       /* Build the argument packs.  */
12340       SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
12341     }
12342   *spec_p = spec_parm;
12343 
12344   return argpack;
12345 }
12346 
12347 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
12348    NONTYPE_ARGUMENT_PACK.  */
12349 
12350 static tree
make_fnparm_pack(tree spec_parm)12351 make_fnparm_pack (tree spec_parm)
12352 {
12353   return extract_fnparm_pack (NULL_TREE, &spec_parm);
12354 }
12355 
12356 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
12357    pack expansion with no extra args, 2 if it has extra args, or 0
12358    if it is not a pack expansion.  */
12359 
12360 static int
argument_pack_element_is_expansion_p(tree arg_pack,int i)12361 argument_pack_element_is_expansion_p (tree arg_pack, int i)
12362 {
12363   if (TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12364     /* We're being called before this happens in tsubst_pack_expansion.  */
12365     arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12366   tree vec = ARGUMENT_PACK_ARGS (arg_pack);
12367   if (i >= TREE_VEC_LENGTH (vec))
12368     return 0;
12369   tree elt = TREE_VEC_ELT (vec, i);
12370   if (DECL_P (elt))
12371     /* A decl pack is itself an expansion.  */
12372     elt = TREE_TYPE (elt);
12373   if (!PACK_EXPANSION_P (elt))
12374     return 0;
12375   if (PACK_EXPANSION_EXTRA_ARGS (elt))
12376     return 2;
12377   return 1;
12378 }
12379 
12380 
12381 /* Creates and return an ARGUMENT_PACK_SELECT tree node.  */
12382 
12383 static tree
make_argument_pack_select(tree arg_pack,unsigned index)12384 make_argument_pack_select (tree arg_pack, unsigned index)
12385 {
12386   tree aps = make_node (ARGUMENT_PACK_SELECT);
12387 
12388   ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
12389   ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12390 
12391   return aps;
12392 }
12393 
12394 /*  This is a subroutine of tsubst_pack_expansion.
12395 
12396     It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
12397     mechanism to store the (non complete list of) arguments of the
12398     substitution and return a non substituted pack expansion, in order
12399     to wait for when we have enough arguments to really perform the
12400     substitution.  */
12401 
12402 static bool
use_pack_expansion_extra_args_p(tree parm_packs,int arg_pack_len,bool has_empty_arg)12403 use_pack_expansion_extra_args_p (tree parm_packs,
12404 				 int arg_pack_len,
12405 				 bool has_empty_arg)
12406 {
12407   /* If one pack has an expansion and another pack has a normal
12408      argument or if one pack has an empty argument and an another
12409      one hasn't then tsubst_pack_expansion cannot perform the
12410      substitution and need to fall back on the
12411      PACK_EXPANSION_EXTRA mechanism.  */
12412   if (parm_packs == NULL_TREE)
12413     return false;
12414   else if (has_empty_arg)
12415     {
12416       /* If all the actual packs are pack expansions, we can still
12417 	 subsitute directly.  */
12418       for (tree p = parm_packs; p; p = TREE_CHAIN (p))
12419 	{
12420 	  tree a = TREE_VALUE (p);
12421 	  if (TREE_CODE (a) == ARGUMENT_PACK_SELECT)
12422 	    a = ARGUMENT_PACK_SELECT_FROM_PACK (a);
12423 	  a = ARGUMENT_PACK_ARGS (a);
12424 	  if (TREE_VEC_LENGTH (a) == 1)
12425 	    a = TREE_VEC_ELT (a, 0);
12426 	  if (PACK_EXPANSION_P (a))
12427 	    continue;
12428 	  return true;
12429 	}
12430       return false;
12431     }
12432 
12433   for (int i = 0 ; i < arg_pack_len; ++i)
12434     {
12435       bool has_expansion_arg = false;
12436       bool has_non_expansion_arg = false;
12437       for (tree parm_pack = parm_packs;
12438 	   parm_pack;
12439 	   parm_pack = TREE_CHAIN (parm_pack))
12440 	{
12441 	  tree arg = TREE_VALUE (parm_pack);
12442 
12443 	  int exp = argument_pack_element_is_expansion_p (arg, i);
12444 	  if (exp == 2)
12445 	    /* We can't substitute a pack expansion with extra args into
12446 	       our pattern.  */
12447 	    return true;
12448 	  else if (exp)
12449 	    has_expansion_arg = true;
12450 	  else
12451 	    has_non_expansion_arg = true;
12452 	}
12453 
12454       if (has_expansion_arg && has_non_expansion_arg)
12455 	{
12456 	  gcc_checking_assert (false);
12457 	  return true;
12458 	}
12459     }
12460   return false;
12461 }
12462 
12463 /* [temp.variadic]/6 says that:
12464 
12465        The instantiation of a pack expansion [...]
12466        produces a list E1,E2, ..., En, where N is the number of elements
12467        in the pack expansion parameters.
12468 
12469    This subroutine of tsubst_pack_expansion produces one of these Ei.
12470 
12471    PATTERN is the pattern of the pack expansion.  PARM_PACKS is a
12472    TREE_LIST in which each TREE_PURPOSE is a parameter pack of
12473    PATTERN, and each TREE_VALUE is its corresponding argument pack.
12474    INDEX is the index 'i' of the element Ei to produce.  ARGS,
12475    COMPLAIN, and IN_DECL are the same parameters as for the
12476    tsubst_pack_expansion function.
12477 
12478    The function returns the resulting Ei upon successful completion,
12479    or error_mark_node.
12480 
12481    Note that this function possibly modifies the ARGS parameter, so
12482    it's the responsibility of the caller to restore it.  */
12483 
12484 static tree
gen_elem_of_pack_expansion_instantiation(tree pattern,tree parm_packs,unsigned index,tree args,tsubst_flags_t complain,tree in_decl)12485 gen_elem_of_pack_expansion_instantiation (tree pattern,
12486 					  tree parm_packs,
12487 					  unsigned index,
12488 					  tree args /* This parm gets
12489 						       modified.  */,
12490 					  tsubst_flags_t complain,
12491 					  tree in_decl)
12492 {
12493   tree t;
12494   bool ith_elem_is_expansion = false;
12495 
12496   /* For each parameter pack, change the substitution of the parameter
12497      pack to the ith argument in its argument pack, then expand the
12498      pattern.  */
12499   for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
12500     {
12501       tree parm = TREE_PURPOSE (pack);
12502       tree arg_pack = TREE_VALUE (pack);
12503       tree aps;			/* instance of ARGUMENT_PACK_SELECT.  */
12504 
12505       ith_elem_is_expansion |=
12506 	argument_pack_element_is_expansion_p (arg_pack, index);
12507 
12508       /* Select the Ith argument from the pack.  */
12509       if (TREE_CODE (parm) == PARM_DECL
12510 	  || VAR_P (parm)
12511 	  || TREE_CODE (parm) == FIELD_DECL)
12512 	{
12513 	  if (index == 0)
12514 	    {
12515 	      aps = make_argument_pack_select (arg_pack, index);
12516 	      if (!mark_used (parm, complain) && !(complain & tf_error))
12517 		return error_mark_node;
12518 	      register_local_specialization (aps, parm);
12519 	    }
12520 	  else
12521 	    aps = retrieve_local_specialization (parm);
12522 	}
12523       else
12524 	{
12525 	  int idx, level;
12526 	  template_parm_level_and_index (parm, &level, &idx);
12527 
12528 	  if (index == 0)
12529 	    {
12530 	      aps = make_argument_pack_select (arg_pack, index);
12531 	      /* Update the corresponding argument.  */
12532 	      TMPL_ARG (args, level, idx) = aps;
12533 	    }
12534 	  else
12535 	    /* Re-use the ARGUMENT_PACK_SELECT.  */
12536 	    aps = TMPL_ARG (args, level, idx);
12537 	}
12538       ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12539     }
12540 
12541   /* Substitute into the PATTERN with the (possibly altered)
12542      arguments.  */
12543   if (pattern == in_decl)
12544     /* Expanding a fixed parameter pack from
12545        coerce_template_parameter_pack.  */
12546     t = tsubst_decl (pattern, args, complain);
12547   else if (pattern == error_mark_node)
12548     t = error_mark_node;
12549   else if (!TYPE_P (pattern))
12550     t = tsubst_expr (pattern, args, complain, in_decl,
12551 		     /*integral_constant_expression_p=*/false);
12552   else
12553     t = tsubst (pattern, args, complain, in_decl);
12554 
12555   /*  If the Ith argument pack element is a pack expansion, then
12556       the Ith element resulting from the substituting is going to
12557       be a pack expansion as well.  */
12558   if (ith_elem_is_expansion)
12559     t = make_pack_expansion (t, complain);
12560 
12561   return t;
12562 }
12563 
12564 /* When the unexpanded parameter pack in a fold expression expands to an empty
12565    sequence, the value of the expression is as follows; the program is
12566    ill-formed if the operator is not listed in this table.
12567 
12568    &&	true
12569    ||	false
12570    ,	void()  */
12571 
12572 tree
expand_empty_fold(tree t,tsubst_flags_t complain)12573 expand_empty_fold (tree t, tsubst_flags_t complain)
12574 {
12575   tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
12576   if (!FOLD_EXPR_MODIFY_P (t))
12577     switch (code)
12578       {
12579       case TRUTH_ANDIF_EXPR:
12580 	return boolean_true_node;
12581       case TRUTH_ORIF_EXPR:
12582 	return boolean_false_node;
12583       case COMPOUND_EXPR:
12584 	return void_node;
12585       default:
12586 	break;
12587       }
12588 
12589   if (complain & tf_error)
12590     error_at (location_of (t),
12591 	      "fold of empty expansion over %O", code);
12592   return error_mark_node;
12593 }
12594 
12595 /* Given a fold-expression T and a current LEFT and RIGHT operand,
12596    form an expression that combines the two terms using the
12597    operator of T. */
12598 
12599 static tree
fold_expression(tree t,tree left,tree right,tsubst_flags_t complain)12600 fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
12601 {
12602   tree op = FOLD_EXPR_OP (t);
12603   tree_code code = (tree_code)TREE_INT_CST_LOW (op);
12604 
12605   // Handle compound assignment operators.
12606   if (FOLD_EXPR_MODIFY_P (t))
12607     return build_x_modify_expr (input_location, left, code, right, complain);
12608 
12609   warning_sentinel s(warn_parentheses);
12610   switch (code)
12611     {
12612     case COMPOUND_EXPR:
12613       return build_x_compound_expr (input_location, left, right, complain);
12614     default:
12615       return build_x_binary_op (input_location, code,
12616                                 left, TREE_CODE (left),
12617                                 right, TREE_CODE (right),
12618                                 /*overload=*/NULL,
12619                                 complain);
12620     }
12621 }
12622 
12623 /* Substitute ARGS into the pack of a fold expression T. */
12624 
12625 static inline tree
tsubst_fold_expr_pack(tree t,tree args,tsubst_flags_t complain,tree in_decl)12626 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12627 {
12628   return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
12629 }
12630 
12631 /* Substitute ARGS into the pack of a fold expression T. */
12632 
12633 static inline tree
tsubst_fold_expr_init(tree t,tree args,tsubst_flags_t complain,tree in_decl)12634 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12635 {
12636   return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl, false);
12637 }
12638 
12639 /* Expand a PACK of arguments into a grouped as left fold.
12640    Given a pack containing elements A0, A1, ..., An and an
12641    operator @, this builds the expression:
12642 
12643       ((A0 @ A1) @ A2) ... @ An
12644 
12645    Note that PACK must not be empty.
12646 
12647    The operator is defined by the original fold expression T. */
12648 
12649 static tree
expand_left_fold(tree t,tree pack,tsubst_flags_t complain)12650 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
12651 {
12652   tree left = TREE_VEC_ELT (pack, 0);
12653   for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
12654     {
12655       tree right = TREE_VEC_ELT (pack, i);
12656       left = fold_expression (t, left, right, complain);
12657     }
12658   return left;
12659 }
12660 
12661 /* Substitute into a unary left fold expression. */
12662 
12663 static tree
tsubst_unary_left_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)12664 tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
12665                         tree in_decl)
12666 {
12667   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12668   if (pack == error_mark_node)
12669     return error_mark_node;
12670   if (PACK_EXPANSION_P (pack))
12671     {
12672       tree r = copy_node (t);
12673       FOLD_EXPR_PACK (r) = pack;
12674       return r;
12675     }
12676   if (TREE_VEC_LENGTH (pack) == 0)
12677     return expand_empty_fold (t, complain);
12678   else
12679     return expand_left_fold (t, pack, complain);
12680 }
12681 
12682 /* Substitute into a binary left fold expression.
12683 
12684    Do ths by building a single (non-empty) vector of argumnts and
12685    building the expression from those elements. */
12686 
12687 static tree
tsubst_binary_left_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)12688 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
12689                          tree in_decl)
12690 {
12691   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12692   if (pack == error_mark_node)
12693     return error_mark_node;
12694   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
12695   if (init == error_mark_node)
12696     return error_mark_node;
12697 
12698   if (PACK_EXPANSION_P (pack))
12699     {
12700       tree r = copy_node (t);
12701       FOLD_EXPR_PACK (r) = pack;
12702       FOLD_EXPR_INIT (r) = init;
12703       return r;
12704     }
12705 
12706   tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
12707   TREE_VEC_ELT (vec, 0) = init;
12708   for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
12709     TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
12710 
12711   return expand_left_fold (t, vec, complain);
12712 }
12713 
12714 /* Expand a PACK of arguments into a grouped as right fold.
12715    Given a pack containing elementns A0, A1, ..., and an
12716    operator @, this builds the expression:
12717 
12718       A0@ ... (An-2 @ (An-1 @ An))
12719 
12720    Note that PACK must not be empty.
12721 
12722    The operator is defined by the original fold expression T. */
12723 
12724 tree
expand_right_fold(tree t,tree pack,tsubst_flags_t complain)12725 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
12726 {
12727   // Build the expression.
12728   int n = TREE_VEC_LENGTH (pack);
12729   tree right = TREE_VEC_ELT (pack, n - 1);
12730   for (--n; n != 0; --n)
12731     {
12732       tree left = TREE_VEC_ELT (pack, n - 1);
12733       right = fold_expression (t, left, right, complain);
12734     }
12735   return right;
12736 }
12737 
12738 /* Substitute into a unary right fold expression. */
12739 
12740 static tree
tsubst_unary_right_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)12741 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
12742                          tree in_decl)
12743 {
12744   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12745   if (pack == error_mark_node)
12746     return error_mark_node;
12747   if (PACK_EXPANSION_P (pack))
12748     {
12749       tree r = copy_node (t);
12750       FOLD_EXPR_PACK (r) = pack;
12751       return r;
12752     }
12753   if (TREE_VEC_LENGTH (pack) == 0)
12754     return expand_empty_fold (t, complain);
12755   else
12756     return expand_right_fold (t, pack, complain);
12757 }
12758 
12759 /* Substitute into a binary right fold expression.
12760 
12761    Do ths by building a single (non-empty) vector of arguments and
12762    building the expression from those elements. */
12763 
12764 static tree
tsubst_binary_right_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)12765 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
12766                          tree in_decl)
12767 {
12768   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12769   if (pack == error_mark_node)
12770     return error_mark_node;
12771   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
12772   if (init == error_mark_node)
12773     return error_mark_node;
12774 
12775   if (PACK_EXPANSION_P (pack))
12776     {
12777       tree r = copy_node (t);
12778       FOLD_EXPR_PACK (r) = pack;
12779       FOLD_EXPR_INIT (r) = init;
12780       return r;
12781     }
12782 
12783   int n = TREE_VEC_LENGTH (pack);
12784   tree vec = make_tree_vec (n + 1);
12785   for (int i = 0; i < n; ++i)
12786     TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
12787   TREE_VEC_ELT (vec, n) = init;
12788 
12789   return expand_right_fold (t, vec, complain);
12790 }
12791 
12792 /* Walk through the pattern of a pack expansion, adding everything in
12793    local_specializations to a list.  */
12794 
12795 class el_data
12796 {
12797 public:
12798   /* Set of variables declared within the pattern.  */
12799   hash_set<tree> internal;
12800   /* Set of AST nodes that have been visited by the traversal.  */
12801   hash_set<tree> visited;
12802   /* List of local_specializations used within the pattern.  */
12803   tree extra;
12804   tsubst_flags_t complain;
12805 
el_data(tsubst_flags_t c)12806   el_data (tsubst_flags_t c)
12807     : extra (NULL_TREE), complain (c) {}
12808 };
12809 static tree
extract_locals_r(tree * tp,int *,void * data_)12810 extract_locals_r (tree *tp, int */*walk_subtrees*/, void *data_)
12811 {
12812   el_data &data = *reinterpret_cast<el_data*>(data_);
12813   tree *extra = &data.extra;
12814   tsubst_flags_t complain = data.complain;
12815 
12816   if (TYPE_P (*tp) && typedef_variant_p (*tp))
12817     /* Remember local typedefs (85214).  */
12818     tp = &TYPE_NAME (*tp);
12819 
12820   if (TREE_CODE (*tp) == DECL_EXPR)
12821     {
12822       tree decl = DECL_EXPR_DECL (*tp);
12823       data.internal.add (decl);
12824       if (VAR_P (decl)
12825 	  && DECL_DECOMPOSITION_P (decl)
12826 	  && TREE_TYPE (decl) != error_mark_node)
12827 	{
12828 	  gcc_assert (DECL_NAME (decl) == NULL_TREE);
12829 	  for (tree decl2 = DECL_CHAIN (decl);
12830 	       decl2
12831 	       && VAR_P (decl2)
12832 	       && DECL_DECOMPOSITION_P (decl2)
12833 	       && DECL_NAME (decl2)
12834 	       && TREE_TYPE (decl2) != error_mark_node;
12835 	       decl2 = DECL_CHAIN (decl2))
12836 	    {
12837 	      gcc_assert (DECL_DECOMP_BASE (decl2) == decl);
12838 	      data.internal.add (decl2);
12839 	    }
12840 	}
12841     }
12842   else if (TREE_CODE (*tp) == LAMBDA_EXPR)
12843     {
12844       /* Since we defer implicit capture, look in the parms and body.  */
12845       tree fn = lambda_function (*tp);
12846       cp_walk_tree (&TREE_TYPE (fn), &extract_locals_r, &data,
12847 		    &data.visited);
12848       cp_walk_tree (&DECL_SAVED_TREE (fn), &extract_locals_r, &data,
12849 		    &data.visited);
12850     }
12851   else if (tree spec = retrieve_local_specialization (*tp))
12852     {
12853       if (data.internal.contains (*tp))
12854 	/* Don't mess with variables declared within the pattern.  */
12855 	return NULL_TREE;
12856       if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
12857 	{
12858 	  /* Maybe pull out the PARM_DECL for a partial instantiation.  */
12859 	  tree args = ARGUMENT_PACK_ARGS (spec);
12860 	  if (TREE_VEC_LENGTH (args) == 1)
12861 	    {
12862 	      tree elt = TREE_VEC_ELT (args, 0);
12863 	      if (PACK_EXPANSION_P (elt))
12864 		elt = PACK_EXPANSION_PATTERN (elt);
12865 	      if (DECL_PACK_P (elt))
12866 		spec = elt;
12867 	    }
12868 	  if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
12869 	    {
12870 	      /* Handle lambda capture here, since we aren't doing any
12871 		 substitution now, and so tsubst_copy won't call
12872 		 process_outer_var_ref.  */
12873 	      tree args = ARGUMENT_PACK_ARGS (spec);
12874 	      int len = TREE_VEC_LENGTH (args);
12875 	      for (int i = 0; i < len; ++i)
12876 		{
12877 		  tree arg = TREE_VEC_ELT (args, i);
12878 		  tree carg = arg;
12879 		  if (outer_automatic_var_p (arg))
12880 		    carg = process_outer_var_ref (arg, complain);
12881 		  if (carg != arg)
12882 		    {
12883 		      /* Make a new NONTYPE_ARGUMENT_PACK of the capture
12884 			 proxies.  */
12885 		      if (i == 0)
12886 			{
12887 			  spec = copy_node (spec);
12888 			  args = copy_node (args);
12889 			  SET_ARGUMENT_PACK_ARGS (spec, args);
12890 			  register_local_specialization (spec, *tp);
12891 			}
12892 		      TREE_VEC_ELT (args, i) = carg;
12893 		    }
12894 		}
12895 	    }
12896 	}
12897       if (outer_automatic_var_p (spec))
12898 	spec = process_outer_var_ref (spec, complain);
12899       *extra = tree_cons (*tp, spec, *extra);
12900     }
12901   return NULL_TREE;
12902 }
12903 static tree
extract_local_specs(tree pattern,tsubst_flags_t complain)12904 extract_local_specs (tree pattern, tsubst_flags_t complain)
12905 {
12906   el_data data (complain);
12907   cp_walk_tree (&pattern, extract_locals_r, &data, &data.visited);
12908   return data.extra;
12909 }
12910 
12911 /* Extract any uses of local_specializations from PATTERN and add them to ARGS
12912    for use in PACK_EXPANSION_EXTRA_ARGS.  */
12913 
12914 tree
build_extra_args(tree pattern,tree args,tsubst_flags_t complain)12915 build_extra_args (tree pattern, tree args, tsubst_flags_t complain)
12916 {
12917   /* Make a copy of the extra arguments so that they won't get changed
12918      out from under us.  */
12919   tree extra = copy_template_args (args);
12920   if (local_specializations)
12921     if (tree locals = extract_local_specs (pattern, complain))
12922       extra = tree_cons (NULL_TREE, extra, locals);
12923   return extra;
12924 }
12925 
12926 /* Apply any local specializations from PACK_EXPANSION_EXTRA_ARGS and add the
12927    normal template args to ARGS.  */
12928 
12929 tree
add_extra_args(tree extra,tree args,tsubst_flags_t complain,tree in_decl)12930 add_extra_args (tree extra, tree args, tsubst_flags_t complain, tree in_decl)
12931 {
12932   if (extra && TREE_CODE (extra) == TREE_LIST)
12933     {
12934       for (tree elt = TREE_CHAIN (extra); elt; elt = TREE_CHAIN (elt))
12935 	{
12936 	  /* The partial instantiation involved local declarations collected in
12937 	     extract_local_specs; map from the general template to our local
12938 	     context.  */
12939 	  tree gen = TREE_PURPOSE (elt);
12940 	  tree inst = TREE_VALUE (elt);
12941 	  if (DECL_P (inst))
12942 	    if (tree local = retrieve_local_specialization (inst))
12943 	      inst = local;
12944 	  /* else inst is already a full instantiation of the pack.  */
12945 	  register_local_specialization (inst, gen);
12946 	}
12947       gcc_assert (!TREE_PURPOSE (extra));
12948       extra = TREE_VALUE (extra);
12949     }
12950   if (uses_template_parms (extra))
12951     {
12952       /* This can happen after dependent substitution into a
12953 	 requires-expr or a lambda that uses constexpr if.  */
12954       extra = tsubst_template_args (extra, args, complain, in_decl);
12955       args = add_outermost_template_args (args, extra);
12956     }
12957   else
12958     args = add_to_template_args (extra, args);
12959   return args;
12960 }
12961 
12962 /* Substitute ARGS into T, which is an pack expansion
12963    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
12964    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
12965    (if only a partial substitution could be performed) or
12966    ERROR_MARK_NODE if there was an error.  */
12967 tree
tsubst_pack_expansion(tree t,tree args,tsubst_flags_t complain,tree in_decl)12968 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
12969 		       tree in_decl)
12970 {
12971   tree pattern;
12972   tree pack, packs = NULL_TREE;
12973   bool unsubstituted_packs = false;
12974   int i, len = -1;
12975   tree result;
12976   bool need_local_specializations = false;
12977   int levels;
12978 
12979   gcc_assert (PACK_EXPANSION_P (t));
12980   pattern = PACK_EXPANSION_PATTERN (t);
12981 
12982   /* Add in any args remembered from an earlier partial instantiation.  */
12983   args = add_extra_args (PACK_EXPANSION_EXTRA_ARGS (t), args, complain, in_decl);
12984 
12985   levels = TMPL_ARGS_DEPTH (args);
12986 
12987   /* Determine the argument packs that will instantiate the parameter
12988      packs used in the expansion expression. While we're at it,
12989      compute the number of arguments to be expanded and make sure it
12990      is consistent.  */
12991   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
12992        pack = TREE_CHAIN (pack))
12993     {
12994       tree parm_pack = TREE_VALUE (pack);
12995       tree arg_pack = NULL_TREE;
12996       tree orig_arg = NULL_TREE;
12997       int level = 0;
12998 
12999       if (TREE_CODE (parm_pack) == BASES)
13000 	{
13001 	  gcc_assert (parm_pack == pattern);
13002 	  if (BASES_DIRECT (parm_pack))
13003 	    return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
13004 							args, complain,
13005 							in_decl, false),
13006 					   complain);
13007 	  else
13008 	    return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
13009 						 args, complain, in_decl,
13010 						 false), complain);
13011 	}
13012       else if (builtin_pack_call_p (parm_pack))
13013 	{
13014 	  if (parm_pack != pattern)
13015 	    {
13016 	      if (complain & tf_error)
13017 		sorry ("%qE is not the entire pattern of the pack expansion",
13018 		       parm_pack);
13019 	      return error_mark_node;
13020 	    }
13021 	  return expand_builtin_pack_call (parm_pack, args,
13022 					   complain, in_decl);
13023 	}
13024       else if (TREE_CODE (parm_pack) == PARM_DECL)
13025 	{
13026 	  /* We know we have correct local_specializations if this
13027 	     expansion is at function scope, or if we're dealing with a
13028 	     local parameter in a requires expression; for the latter,
13029 	     tsubst_requires_expr set it up appropriately.  */
13030 	  if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
13031 	    arg_pack = retrieve_local_specialization (parm_pack);
13032 	  else
13033 	    /* We can't rely on local_specializations for a parameter
13034 	       name used later in a function declaration (such as in a
13035 	       late-specified return type).  Even if it exists, it might
13036 	       have the wrong value for a recursive call.  */
13037 	    need_local_specializations = true;
13038 
13039 	  if (!arg_pack)
13040 	    {
13041 	      /* This parameter pack was used in an unevaluated context.  Just
13042 		 make a dummy decl, since it's only used for its type.  */
13043 	      ++cp_unevaluated_operand;
13044 	      arg_pack = tsubst_decl (parm_pack, args, complain);
13045 	      --cp_unevaluated_operand;
13046 	      if (arg_pack && DECL_PACK_P (arg_pack))
13047 		/* Partial instantiation of the parm_pack, we can't build
13048 		   up an argument pack yet.  */
13049 		arg_pack = NULL_TREE;
13050 	      else
13051 		arg_pack = make_fnparm_pack (arg_pack);
13052 	    }
13053 	  else if (DECL_PACK_P (arg_pack))
13054 	    /* This argument pack isn't fully instantiated yet.  */
13055 	    arg_pack = NULL_TREE;
13056 	}
13057       else if (is_capture_proxy (parm_pack))
13058 	{
13059 	  arg_pack = retrieve_local_specialization (parm_pack);
13060 	  if (DECL_PACK_P (arg_pack))
13061 	    arg_pack = NULL_TREE;
13062 	}
13063       else
13064         {
13065 	  int idx;
13066           template_parm_level_and_index (parm_pack, &level, &idx);
13067           if (level <= levels)
13068             arg_pack = TMPL_ARG (args, level, idx);
13069 
13070 	  if (arg_pack && TREE_CODE (arg_pack) == TEMPLATE_TYPE_PARM
13071 	      && TEMPLATE_TYPE_PARAMETER_PACK (arg_pack))
13072 	    arg_pack = NULL_TREE;
13073         }
13074 
13075       orig_arg = arg_pack;
13076       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
13077 	arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
13078 
13079       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
13080 	/* This can only happen if we forget to expand an argument
13081 	   pack somewhere else. Just return an error, silently.  */
13082 	{
13083 	  result = make_tree_vec (1);
13084 	  TREE_VEC_ELT (result, 0) = error_mark_node;
13085 	  return result;
13086 	}
13087 
13088       if (arg_pack)
13089         {
13090           int my_len =
13091             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
13092 
13093 	  /* Don't bother trying to do a partial substitution with
13094 	     incomplete packs; we'll try again after deduction.  */
13095           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
13096             return t;
13097 
13098           if (len < 0)
13099 	    len = my_len;
13100 	  else if (len != my_len)
13101             {
13102 	      if (!(complain & tf_error))
13103 		/* Fail quietly.  */;
13104               else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
13105                 error ("mismatched argument pack lengths while expanding %qT",
13106                        pattern);
13107               else
13108                 error ("mismatched argument pack lengths while expanding %qE",
13109                        pattern);
13110               return error_mark_node;
13111             }
13112 
13113           /* Keep track of the parameter packs and their corresponding
13114              argument packs.  */
13115           packs = tree_cons (parm_pack, arg_pack, packs);
13116           TREE_TYPE (packs) = orig_arg;
13117         }
13118       else
13119 	{
13120 	  /* We can't substitute for this parameter pack.  We use a flag as
13121 	     well as the missing_level counter because function parameter
13122 	     packs don't have a level.  */
13123 	  gcc_assert (processing_template_decl || is_auto (parm_pack));
13124 	  unsubstituted_packs = true;
13125 	}
13126     }
13127 
13128   /* If the expansion is just T..., return the matching argument pack, unless
13129      we need to call convert_from_reference on all the elements.  This is an
13130      important optimization; see c++/68422.  */
13131   if (!unsubstituted_packs
13132       && TREE_PURPOSE (packs) == pattern)
13133     {
13134       tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
13135 
13136       /* If the argument pack is a single pack expansion, pull it out.  */
13137       if (TREE_VEC_LENGTH (args) == 1
13138 	  && pack_expansion_args_count (args))
13139 	return TREE_VEC_ELT (args, 0);
13140 
13141       /* Types need no adjustment, nor does sizeof..., and if we still have
13142 	 some pack expansion args we won't do anything yet.  */
13143       if (TREE_CODE (t) == TYPE_PACK_EXPANSION
13144 	  || PACK_EXPANSION_SIZEOF_P (t)
13145 	  || pack_expansion_args_count (args))
13146 	return args;
13147       /* Also optimize expression pack expansions if we can tell that the
13148 	 elements won't have reference type.  */
13149       tree type = TREE_TYPE (pattern);
13150       if (type && !TYPE_REF_P (type)
13151 	  && !PACK_EXPANSION_P (type)
13152 	  && !WILDCARD_TYPE_P (type))
13153 	return args;
13154       /* Otherwise use the normal path so we get convert_from_reference.  */
13155     }
13156 
13157   /* We cannot expand this expansion expression, because we don't have
13158      all of the argument packs we need.  */
13159   if (use_pack_expansion_extra_args_p (packs, len, unsubstituted_packs))
13160     {
13161       /* We got some full packs, but we can't substitute them in until we
13162 	 have values for all the packs.  So remember these until then.  */
13163 
13164       t = make_pack_expansion (pattern, complain);
13165       PACK_EXPANSION_EXTRA_ARGS (t)
13166 	= build_extra_args (pattern, args, complain);
13167       return t;
13168     }
13169 
13170   /* If NEED_LOCAL_SPECIALIZATIONS then we're in a late-specified return
13171      type, so create our own local specializations map; the current map is
13172      either NULL or (in the case of recursive unification) might have
13173      bindings that we don't want to use or alter.  */
13174   local_specialization_stack lss (need_local_specializations
13175 				  ? lss_blank : lss_nop);
13176 
13177   if (unsubstituted_packs)
13178     {
13179       /* There were no real arguments, we're just replacing a parameter
13180 	 pack with another version of itself. Substitute into the
13181 	 pattern and return a PACK_EXPANSION_*. The caller will need to
13182 	 deal with that.  */
13183       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
13184 	result = tsubst_expr (pattern, args, complain, in_decl,
13185 			 /*integral_constant_expression_p=*/false);
13186       else
13187 	result = tsubst (pattern, args, complain, in_decl);
13188       result = make_pack_expansion (result, complain);
13189       PACK_EXPANSION_LOCAL_P (result) = PACK_EXPANSION_LOCAL_P (t);
13190       PACK_EXPANSION_SIZEOF_P (result) = PACK_EXPANSION_SIZEOF_P (t);
13191       if (PACK_EXPANSION_AUTO_P (t))
13192 	{
13193 	  /* This is a fake auto... pack expansion created in add_capture with
13194 	     _PACKS that don't appear in the pattern.  Copy one over.  */
13195 	  packs = PACK_EXPANSION_PARAMETER_PACKS (t);
13196 	  pack = retrieve_local_specialization (TREE_VALUE (packs));
13197 	  gcc_checking_assert (DECL_PACK_P (pack));
13198 	  PACK_EXPANSION_PARAMETER_PACKS (result)
13199 	    = build_tree_list (NULL_TREE, pack);
13200 	  PACK_EXPANSION_AUTO_P (result) = true;
13201 	}
13202       return result;
13203     }
13204 
13205   gcc_assert (len >= 0);
13206 
13207   /* For each argument in each argument pack, substitute into the
13208      pattern.  */
13209   result = make_tree_vec (len);
13210   tree elem_args = copy_template_args (args);
13211   for (i = 0; i < len; ++i)
13212     {
13213       t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
13214 						    i,
13215 						    elem_args, complain,
13216 						    in_decl);
13217       TREE_VEC_ELT (result, i) = t;
13218       if (t == error_mark_node)
13219 	{
13220 	  result = error_mark_node;
13221 	  break;
13222 	}
13223     }
13224 
13225   /* Update ARGS to restore the substitution from parameter packs to
13226      their argument packs.  */
13227   for (pack = packs; pack; pack = TREE_CHAIN (pack))
13228     {
13229       tree parm = TREE_PURPOSE (pack);
13230 
13231       if (TREE_CODE (parm) == PARM_DECL
13232 	  || VAR_P (parm)
13233 	  || TREE_CODE (parm) == FIELD_DECL)
13234         register_local_specialization (TREE_TYPE (pack), parm);
13235       else
13236         {
13237           int idx, level;
13238 
13239 	  if (TREE_VALUE (pack) == NULL_TREE)
13240 	    continue;
13241 
13242           template_parm_level_and_index (parm, &level, &idx);
13243 
13244           /* Update the corresponding argument.  */
13245           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
13246             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
13247               TREE_TYPE (pack);
13248           else
13249             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
13250         }
13251     }
13252 
13253   /* If the dependent pack arguments were such that we end up with only a
13254      single pack expansion again, there's no need to keep it in a TREE_VEC.  */
13255   if (len == 1 && TREE_CODE (result) == TREE_VEC
13256       && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
13257     return TREE_VEC_ELT (result, 0);
13258 
13259   return result;
13260 }
13261 
13262 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
13263    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
13264    parameter packs; all parms generated from a function parameter pack will
13265    have the same DECL_PARM_INDEX.  */
13266 
13267 tree
get_pattern_parm(tree parm,tree tmpl)13268 get_pattern_parm (tree parm, tree tmpl)
13269 {
13270   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
13271   tree patparm;
13272 
13273   if (DECL_ARTIFICIAL (parm))
13274     {
13275       for (patparm = DECL_ARGUMENTS (pattern);
13276 	   patparm; patparm = DECL_CHAIN (patparm))
13277 	if (DECL_ARTIFICIAL (patparm)
13278 	    && DECL_NAME (parm) == DECL_NAME (patparm))
13279 	  break;
13280     }
13281   else
13282     {
13283       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
13284       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
13285       gcc_assert (DECL_PARM_INDEX (patparm)
13286 		  == DECL_PARM_INDEX (parm));
13287     }
13288 
13289   return patparm;
13290 }
13291 
13292 /* Make an argument pack out of the TREE_VEC VEC.  */
13293 
13294 static tree
make_argument_pack(tree vec)13295 make_argument_pack (tree vec)
13296 {
13297   tree pack;
13298 
13299   if (TYPE_P (TREE_VEC_ELT (vec, 0)))
13300     pack = cxx_make_type (TYPE_ARGUMENT_PACK);
13301   else
13302     {
13303       pack = make_node (NONTYPE_ARGUMENT_PACK);
13304       TREE_CONSTANT (pack) = 1;
13305     }
13306   SET_ARGUMENT_PACK_ARGS (pack, vec);
13307   return pack;
13308 }
13309 
13310 /* Return an exact copy of template args T that can be modified
13311    independently.  */
13312 
13313 static tree
copy_template_args(tree t)13314 copy_template_args (tree t)
13315 {
13316   if (t == error_mark_node)
13317     return t;
13318 
13319   int len = TREE_VEC_LENGTH (t);
13320   tree new_vec = make_tree_vec (len);
13321 
13322   for (int i = 0; i < len; ++i)
13323     {
13324       tree elt = TREE_VEC_ELT (t, i);
13325       if (elt && TREE_CODE (elt) == TREE_VEC)
13326 	elt = copy_template_args (elt);
13327       TREE_VEC_ELT (new_vec, i) = elt;
13328     }
13329 
13330   NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
13331     = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13332 
13333   return new_vec;
13334 }
13335 
13336 /* Substitute ARGS into the *_ARGUMENT_PACK orig_arg.  */
13337 
13338 tree
tsubst_argument_pack(tree orig_arg,tree args,tsubst_flags_t complain,tree in_decl)13339 tsubst_argument_pack (tree orig_arg, tree args, tsubst_flags_t complain,
13340 		      tree in_decl)
13341 {
13342   /* Substitute into each of the arguments.  */
13343   tree pack_args = tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
13344 					 args, complain, in_decl);
13345   tree new_arg = error_mark_node;
13346   if (pack_args != error_mark_node)
13347     {
13348       if (TYPE_P (orig_arg))
13349 	{
13350 	  new_arg = cxx_make_type (TREE_CODE (orig_arg));
13351 	  SET_TYPE_STRUCTURAL_EQUALITY (new_arg);
13352 	}
13353       else
13354 	{
13355 	  new_arg = make_node (TREE_CODE (orig_arg));
13356 	  TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
13357 	}
13358 
13359       SET_ARGUMENT_PACK_ARGS (new_arg, pack_args);
13360     }
13361 
13362   return new_arg;
13363 }
13364 
13365 /* Substitute ARGS into the vector or list of template arguments T.  */
13366 
13367 tree
tsubst_template_args(tree t,tree args,tsubst_flags_t complain,tree in_decl)13368 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
13369 {
13370   tree orig_t = t;
13371   int len, need_new = 0, i, expanded_len_adjust = 0, out;
13372   tree *elts;
13373 
13374   if (t == error_mark_node)
13375     return error_mark_node;
13376 
13377   len = TREE_VEC_LENGTH (t);
13378   elts = XALLOCAVEC (tree, len);
13379 
13380   for (i = 0; i < len; i++)
13381     {
13382       tree orig_arg = TREE_VEC_ELT (t, i);
13383       tree new_arg;
13384 
13385       if (!orig_arg)
13386 	new_arg = NULL_TREE;
13387       else if (TREE_CODE (orig_arg) == TREE_VEC)
13388 	new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
13389       else if (PACK_EXPANSION_P (orig_arg))
13390         {
13391           /* Substitute into an expansion expression.  */
13392           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
13393 
13394           if (TREE_CODE (new_arg) == TREE_VEC)
13395             /* Add to the expanded length adjustment the number of
13396                expanded arguments. We subtract one from this
13397                measurement, because the argument pack expression
13398                itself is already counted as 1 in
13399                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
13400                the argument pack is empty.  */
13401             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
13402         }
13403       else if (ARGUMENT_PACK_P (orig_arg))
13404 	new_arg = tsubst_argument_pack (orig_arg, args, complain, in_decl);
13405       else
13406 	new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
13407 
13408       if (new_arg == error_mark_node)
13409 	return error_mark_node;
13410 
13411       elts[i] = new_arg;
13412       if (new_arg != orig_arg)
13413 	need_new = 1;
13414     }
13415 
13416   if (!need_new)
13417     return t;
13418 
13419   /* Make space for the expanded arguments coming from template
13420      argument packs.  */
13421   t = make_tree_vec (len + expanded_len_adjust);
13422   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
13423      arguments for a member template.
13424      In that case each TREE_VEC in ORIG_T represents a level of template
13425      arguments, and ORIG_T won't carry any non defaulted argument count.
13426      It will rather be the nested TREE_VECs that will carry one.
13427      In other words, ORIG_T carries a non defaulted argument count only
13428      if it doesn't contain any nested TREE_VEC.  */
13429   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
13430     {
13431       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
13432       count += expanded_len_adjust;
13433       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
13434     }
13435   for (i = 0, out = 0; i < len; i++)
13436     {
13437       tree orig_arg = TREE_VEC_ELT (orig_t, i);
13438       if (orig_arg
13439 	  && (PACK_EXPANSION_P (orig_arg) || ARGUMENT_PACK_P (orig_arg))
13440           && TREE_CODE (elts[i]) == TREE_VEC)
13441         {
13442           int idx;
13443 
13444           /* Now expand the template argument pack "in place".  */
13445           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
13446             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
13447         }
13448       else
13449         {
13450           TREE_VEC_ELT (t, out) = elts[i];
13451           out++;
13452         }
13453     }
13454 
13455   return t;
13456 }
13457 
13458 /* Substitute ARGS into one level PARMS of template parameters.  */
13459 
13460 static tree
tsubst_template_parms_level(tree parms,tree args,tsubst_flags_t complain)13461 tsubst_template_parms_level (tree parms, tree args, tsubst_flags_t complain)
13462 {
13463   if (parms == error_mark_node)
13464     return error_mark_node;
13465 
13466   tree new_vec = make_tree_vec (TREE_VEC_LENGTH (parms));
13467 
13468   for (int i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
13469     {
13470       tree tuple = TREE_VEC_ELT (parms, i);
13471 
13472       if (tuple == error_mark_node)
13473 	continue;
13474 
13475       TREE_VEC_ELT (new_vec, i) =
13476 	tsubst_template_parm (tuple, args, complain);
13477     }
13478 
13479   return new_vec;
13480 }
13481 
13482 /* Return the result of substituting ARGS into the template parameters
13483    given by PARMS.  If there are m levels of ARGS and m + n levels of
13484    PARMS, then the result will contain n levels of PARMS.  For
13485    example, if PARMS is `template <class T> template <class U>
13486    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
13487    result will be `template <int*, double, class V>'.  */
13488 
13489 static tree
tsubst_template_parms(tree parms,tree args,tsubst_flags_t complain)13490 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
13491 {
13492   tree r = NULL_TREE;
13493   tree* new_parms;
13494 
13495   /* When substituting into a template, we must set
13496      PROCESSING_TEMPLATE_DECL as the template parameters may be
13497      dependent if they are based on one-another, and the dependency
13498      predicates are short-circuit outside of templates.  */
13499   ++processing_template_decl;
13500 
13501   for (new_parms = &r;
13502        parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
13503        new_parms = &(TREE_CHAIN (*new_parms)),
13504 	 parms = TREE_CHAIN (parms))
13505     {
13506       tree new_vec = tsubst_template_parms_level (TREE_VALUE (parms),
13507 						  args, complain);
13508       *new_parms =
13509 	tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
13510 			     - TMPL_ARGS_DEPTH (args)),
13511 		   new_vec, NULL_TREE);
13512       TEMPLATE_PARMS_CONSTRAINTS (*new_parms)
13513 	= TEMPLATE_PARMS_CONSTRAINTS (parms);
13514     }
13515 
13516   --processing_template_decl;
13517 
13518   return r;
13519 }
13520 
13521 /* Return the result of substituting ARGS into one template parameter
13522    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
13523    parameter and which TREE_PURPOSE is the default argument of the
13524    template parameter.  */
13525 
13526 static tree
tsubst_template_parm(tree t,tree args,tsubst_flags_t complain)13527 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
13528 {
13529   tree default_value, parm_decl;
13530 
13531   if (args == NULL_TREE
13532       || t == NULL_TREE
13533       || t == error_mark_node)
13534     return t;
13535 
13536   gcc_assert (TREE_CODE (t) == TREE_LIST);
13537 
13538   default_value = TREE_PURPOSE (t);
13539   parm_decl = TREE_VALUE (t);
13540   tree constraint = TEMPLATE_PARM_CONSTRAINTS (t);
13541 
13542   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
13543   if (TREE_CODE (parm_decl) == PARM_DECL
13544       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
13545     parm_decl = error_mark_node;
13546   default_value = tsubst_template_arg (default_value, args,
13547 				       complain, NULL_TREE);
13548   constraint = tsubst_constraint (constraint, args, complain, NULL_TREE);
13549 
13550   tree r = build_tree_list (default_value, parm_decl);
13551   TEMPLATE_PARM_CONSTRAINTS (r) = constraint;
13552   return r;
13553 }
13554 
13555 /* Substitute the ARGS into the indicated aggregate (or enumeration)
13556    type T.  If T is not an aggregate or enumeration type, it is
13557    handled as if by tsubst.  IN_DECL is as for tsubst.  If
13558    ENTERING_SCOPE is nonzero, T is the context for a template which
13559    we are presently tsubst'ing.  Return the substituted value.  */
13560 
13561 static tree
tsubst_aggr_type(tree t,tree args,tsubst_flags_t complain,tree in_decl,int entering_scope)13562 tsubst_aggr_type (tree t,
13563 		  tree args,
13564 		  tsubst_flags_t complain,
13565 		  tree in_decl,
13566 		  int entering_scope)
13567 {
13568   if (t == NULL_TREE)
13569     return NULL_TREE;
13570 
13571   switch (TREE_CODE (t))
13572     {
13573     case RECORD_TYPE:
13574       if (TYPE_PTRMEMFUNC_P (t))
13575 	return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
13576 
13577       /* Fall through.  */
13578     case ENUMERAL_TYPE:
13579     case UNION_TYPE:
13580       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
13581 	{
13582 	  tree argvec;
13583 	  tree context;
13584 	  tree r;
13585 
13586 	  /* In "sizeof(X<I>)" we need to evaluate "I".  */
13587 	  cp_evaluated ev;
13588 
13589 	  /* First, determine the context for the type we are looking
13590 	     up.  */
13591 	  context = TYPE_CONTEXT (t);
13592 	  if (context && TYPE_P (context))
13593 	    {
13594 	      context = tsubst_aggr_type (context, args, complain,
13595 					  in_decl, /*entering_scope=*/1);
13596 	      /* If context is a nested class inside a class template,
13597 	         it may still need to be instantiated (c++/33959).  */
13598 	      context = complete_type (context);
13599 	    }
13600 
13601 	  /* Then, figure out what arguments are appropriate for the
13602 	     type we are trying to find.  For example, given:
13603 
13604 	       template <class T> struct S;
13605 	       template <class T, class U> void f(T, U) { S<U> su; }
13606 
13607 	     and supposing that we are instantiating f<int, double>,
13608 	     then our ARGS will be {int, double}, but, when looking up
13609 	     S we only want {double}.  */
13610 	  argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
13611 					 complain, in_decl);
13612 	  if (argvec == error_mark_node)
13613 	    r = error_mark_node;
13614 	  else if (!entering_scope
13615 		   && cxx_dialect >= cxx17 && dependent_scope_p (context))
13616 	    {
13617 	      /* See maybe_dependent_member_ref.  */
13618 	      tree name = TYPE_IDENTIFIER (t);
13619 	      tree fullname = name;
13620 	      if (instantiates_primary_template_p (t))
13621 		fullname = build_nt (TEMPLATE_ID_EXPR, name,
13622 				     INNERMOST_TEMPLATE_ARGS (argvec));
13623 	      return build_typename_type (context, name, fullname,
13624 					  typename_type);
13625 	    }
13626 	  else
13627 	    {
13628 	      r = lookup_template_class (t, argvec, in_decl, context,
13629 					 entering_scope, complain);
13630 	      r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
13631 	    }
13632 
13633 	  return r;
13634 	}
13635       else
13636 	/* This is not a template type, so there's nothing to do.  */
13637 	return t;
13638 
13639     default:
13640       return tsubst (t, args, complain, in_decl);
13641     }
13642 }
13643 
13644 static GTY((cache)) decl_tree_cache_map *defarg_inst;
13645 
13646 /* Substitute into the default argument ARG (a default argument for
13647    FN), which has the indicated TYPE.  */
13648 
13649 tree
tsubst_default_argument(tree fn,int parmnum,tree type,tree arg,tsubst_flags_t complain)13650 tsubst_default_argument (tree fn, int parmnum, tree type, tree arg,
13651 			 tsubst_flags_t complain)
13652 {
13653   int errs = errorcount + sorrycount;
13654 
13655   /* This can happen in invalid code.  */
13656   if (TREE_CODE (arg) == DEFERRED_PARSE)
13657     return arg;
13658 
13659   /* Shortcut {}.  */
13660   if (BRACE_ENCLOSED_INITIALIZER_P (arg)
13661       && CONSTRUCTOR_NELTS (arg) == 0)
13662     return arg;
13663 
13664   tree parm = FUNCTION_FIRST_USER_PARM (fn);
13665   parm = chain_index (parmnum, parm);
13666   tree parmtype = TREE_TYPE (parm);
13667   if (DECL_BY_REFERENCE (parm))
13668     parmtype = TREE_TYPE (parmtype);
13669   if (parmtype == error_mark_node)
13670     return error_mark_node;
13671 
13672   gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, parmtype));
13673 
13674   tree *slot;
13675   if (defarg_inst && (slot = defarg_inst->get (parm)))
13676     return *slot;
13677 
13678   /* This default argument came from a template.  Instantiate the
13679      default argument here, not in tsubst.  In the case of
13680      something like:
13681 
13682        template <class T>
13683        struct S {
13684 	 static T t();
13685 	 void f(T = t());
13686        };
13687 
13688      we must be careful to do name lookup in the scope of S<T>,
13689      rather than in the current class.  */
13690   push_to_top_level ();
13691   push_access_scope (fn);
13692   push_deferring_access_checks (dk_no_deferred);
13693   start_lambda_scope (parm);
13694 
13695   /* The default argument expression may cause implicitly defined
13696      member functions to be synthesized, which will result in garbage
13697      collection.  We must treat this situation as if we were within
13698      the body of function so as to avoid collecting live data on the
13699      stack.  */
13700   ++function_depth;
13701   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
13702 		     complain, NULL_TREE,
13703 		     /*integral_constant_expression_p=*/false);
13704   --function_depth;
13705 
13706   finish_lambda_scope ();
13707 
13708   /* Make sure the default argument is reasonable.  */
13709   arg = check_default_argument (type, arg, complain);
13710 
13711   if (errorcount+sorrycount > errs
13712       && (complain & tf_warning_or_error))
13713     inform (input_location,
13714 	    "  when instantiating default argument for call to %qD", fn);
13715 
13716   pop_deferring_access_checks ();
13717   pop_access_scope (fn);
13718   pop_from_top_level ();
13719 
13720   if (arg != error_mark_node && !cp_unevaluated_operand)
13721     {
13722       if (!defarg_inst)
13723 	defarg_inst = decl_tree_cache_map::create_ggc (37);
13724       defarg_inst->put (parm, arg);
13725     }
13726 
13727   return arg;
13728 }
13729 
13730 /* Substitute into all the default arguments for FN.  */
13731 
13732 static void
tsubst_default_arguments(tree fn,tsubst_flags_t complain)13733 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
13734 {
13735   tree arg;
13736   tree tmpl_args;
13737 
13738   tmpl_args = DECL_TI_ARGS (fn);
13739 
13740   /* If this function is not yet instantiated, we certainly don't need
13741      its default arguments.  */
13742   if (uses_template_parms (tmpl_args))
13743     return;
13744   /* Don't do this again for clones.  */
13745   if (DECL_CLONED_FUNCTION_P (fn))
13746     return;
13747 
13748   int i = 0;
13749   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
13750        arg;
13751        arg = TREE_CHAIN (arg), ++i)
13752     if (TREE_PURPOSE (arg))
13753       TREE_PURPOSE (arg) = tsubst_default_argument (fn, i,
13754 						    TREE_VALUE (arg),
13755 						    TREE_PURPOSE (arg),
13756 						    complain);
13757 }
13758 
13759 /* Hash table mapping a FUNCTION_DECL to its dependent explicit-specifier.  */
13760 static GTY((cache)) decl_tree_cache_map *explicit_specifier_map;
13761 
13762 /* Store a pair to EXPLICIT_SPECIFIER_MAP.  */
13763 
13764 void
store_explicit_specifier(tree v,tree t)13765 store_explicit_specifier (tree v, tree t)
13766 {
13767   if (!explicit_specifier_map)
13768     explicit_specifier_map = decl_tree_cache_map::create_ggc (37);
13769   DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (v) = true;
13770   explicit_specifier_map->put (v, t);
13771 }
13772 
13773 /* Lookup an element in EXPLICIT_SPECIFIER_MAP.  */
13774 
13775 static tree
lookup_explicit_specifier(tree v)13776 lookup_explicit_specifier (tree v)
13777 {
13778   return *explicit_specifier_map->get (v);
13779 }
13780 
13781 /* Given T, a FUNCTION_TYPE or METHOD_TYPE, construct and return a corresponding
13782    FUNCTION_TYPE or METHOD_TYPE whose return type is RETURN_TYPE, argument types
13783    are ARG_TYPES, and exception specification is RAISES, and otherwise is
13784    identical to T.  */
13785 
13786 static tree
rebuild_function_or_method_type(tree t,tree return_type,tree arg_types,tree raises,tsubst_flags_t complain)13787 rebuild_function_or_method_type (tree t, tree return_type, tree arg_types,
13788 				 tree raises, tsubst_flags_t complain)
13789 {
13790   gcc_assert (FUNC_OR_METHOD_TYPE_P (t));
13791 
13792   tree new_type;
13793   if (TREE_CODE (t) == FUNCTION_TYPE)
13794     {
13795       new_type = build_function_type (return_type, arg_types);
13796       new_type = apply_memfn_quals (new_type, type_memfn_quals (t));
13797     }
13798   else
13799     {
13800       tree r = TREE_TYPE (TREE_VALUE (arg_types));
13801       /* Don't pick up extra function qualifiers from the basetype.  */
13802       r = cp_build_qualified_type_real (r, type_memfn_quals (t), complain);
13803       if (! MAYBE_CLASS_TYPE_P (r))
13804 	{
13805 	  /* [temp.deduct]
13806 
13807 	     Type deduction may fail for any of the following
13808 	     reasons:
13809 
13810 	     -- Attempting to create "pointer to member of T" when T
13811 	     is not a class type.  */
13812 	  if (complain & tf_error)
13813 	    error ("creating pointer to member function of non-class type %qT",
13814 		   r);
13815 	  return error_mark_node;
13816 	}
13817 
13818       new_type = build_method_type_directly (r, return_type,
13819 					     TREE_CHAIN (arg_types));
13820     }
13821   new_type = cp_build_type_attribute_variant (new_type, TYPE_ATTRIBUTES (t));
13822 
13823   cp_ref_qualifier rqual = type_memfn_rqual (t);
13824   bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
13825   return build_cp_fntype_variant (new_type, rqual, raises, late_return_type_p);
13826 }
13827 
13828 /* Check if the function type of DECL, a FUNCTION_DECL, agrees with the type of
13829    each of its formal parameters.  If there is a disagreement then rebuild
13830    DECL's function type according to its formal parameter types, as part of a
13831    resolution for Core issues 1001/1322.  */
13832 
13833 static void
maybe_rebuild_function_decl_type(tree decl)13834 maybe_rebuild_function_decl_type (tree decl)
13835 {
13836   bool function_type_needs_rebuilding = false;
13837   if (tree parm_list = FUNCTION_FIRST_USER_PARM (decl))
13838     {
13839       tree parm_type_list = FUNCTION_FIRST_USER_PARMTYPE (decl);
13840       while (parm_type_list && parm_type_list != void_list_node)
13841 	{
13842 	  tree parm_type = TREE_VALUE (parm_type_list);
13843 	  tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
13844 	  if (!same_type_p (parm_type, formal_parm_type_unqual))
13845 	    {
13846 	      function_type_needs_rebuilding = true;
13847 	      break;
13848 	    }
13849 
13850 	  parm_list = DECL_CHAIN (parm_list);
13851 	  parm_type_list = TREE_CHAIN (parm_type_list);
13852 	}
13853     }
13854 
13855   if (!function_type_needs_rebuilding)
13856     return;
13857 
13858   const tree fntype = TREE_TYPE (decl);
13859   tree parm_list = DECL_ARGUMENTS (decl);
13860   tree old_parm_type_list = TYPE_ARG_TYPES (fntype);
13861   tree new_parm_type_list = NULL_TREE;
13862   tree *q = &new_parm_type_list;
13863   for (int skip = num_artificial_parms_for (decl); skip > 0; skip--)
13864     {
13865       *q = copy_node (old_parm_type_list);
13866       parm_list = DECL_CHAIN (parm_list);
13867       old_parm_type_list = TREE_CHAIN (old_parm_type_list);
13868       q = &TREE_CHAIN (*q);
13869     }
13870   while (old_parm_type_list && old_parm_type_list != void_list_node)
13871     {
13872       *q = copy_node (old_parm_type_list);
13873       tree *new_parm_type = &TREE_VALUE (*q);
13874       tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
13875       if (!same_type_p (*new_parm_type, formal_parm_type_unqual))
13876 	*new_parm_type = formal_parm_type_unqual;
13877 
13878       parm_list = DECL_CHAIN (parm_list);
13879       old_parm_type_list = TREE_CHAIN (old_parm_type_list);
13880       q = &TREE_CHAIN (*q);
13881     }
13882   if (old_parm_type_list == void_list_node)
13883     *q = void_list_node;
13884 
13885   TREE_TYPE (decl)
13886     = rebuild_function_or_method_type (fntype,
13887 				       TREE_TYPE (fntype), new_parm_type_list,
13888 				       TYPE_RAISES_EXCEPTIONS (fntype), tf_none);
13889 }
13890 
13891 /* Subroutine of tsubst_decl for the case when T is a FUNCTION_DECL.  */
13892 
13893 static tree
tsubst_function_decl(tree t,tree args,tsubst_flags_t complain,tree lambda_fntype)13894 tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
13895 		      tree lambda_fntype)
13896 {
13897   tree gen_tmpl = NULL_TREE, argvec = NULL_TREE;
13898   hashval_t hash = 0;
13899   tree in_decl = t;
13900 
13901   /* Nobody should be tsubst'ing into non-template functions.  */
13902   gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE
13903 	      || DECL_LOCAL_DECL_P (t));
13904 
13905   if (DECL_LOCAL_DECL_P (t))
13906     {
13907       if (tree spec = retrieve_local_specialization (t))
13908 	return spec;
13909     }
13910   else if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
13911     {
13912       /* If T is not dependent, just return it.  */
13913       if (!uses_template_parms (DECL_TI_ARGS (t))
13914 	  && !LAMBDA_FUNCTION_P (t))
13915 	return t;
13916 
13917       /* Calculate the most general template of which R is a
13918 	 specialization.  */
13919       gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
13920 
13921       /* We're substituting a lambda function under tsubst_lambda_expr but not
13922 	 directly from it; find the matching function we're already inside.
13923 	 But don't do this if T is a generic lambda with a single level of
13924 	 template parms, as in that case we're doing a normal instantiation. */
13925       if (LAMBDA_FUNCTION_P (t) && !lambda_fntype
13926 	  && (!generic_lambda_fn_p (t)
13927 	      || TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)) > 1))
13928 	return enclosing_instantiation_of (t);
13929 
13930       /* Calculate the complete set of arguments used to
13931 	 specialize R.  */
13932       argvec = tsubst_template_args (DECL_TI_ARGS
13933 				     (DECL_TEMPLATE_RESULT
13934 				      (DECL_TI_TEMPLATE (t))),
13935 				     args, complain, in_decl);
13936       if (argvec == error_mark_node)
13937 	return error_mark_node;
13938 
13939       /* Check to see if we already have this specialization.  */
13940       if (!lambda_fntype)
13941 	{
13942 	  hash = hash_tmpl_and_args (gen_tmpl, argvec);
13943 	  if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
13944 	    return spec;
13945 	}
13946     }
13947   else
13948     {
13949       /* This special case arises when we have something like this:
13950 
13951 	 template <class T> struct S {
13952 	 friend void f<int>(int, double);
13953 	 };
13954 
13955 	 Here, the DECL_TI_TEMPLATE for the friend declaration
13956 	 will be an IDENTIFIER_NODE.  We are being called from
13957 	 tsubst_friend_function, and we want only to create a
13958 	 new decl (R) with appropriate types so that we can call
13959 	 determine_specialization.  */
13960       gen_tmpl = NULL_TREE;
13961       argvec = NULL_TREE;
13962     }
13963 
13964   tree closure = (lambda_fntype ? TYPE_METHOD_BASETYPE (lambda_fntype)
13965 		  : NULL_TREE);
13966   tree ctx = closure ? closure : DECL_CONTEXT (t);
13967   bool member = ctx && TYPE_P (ctx);
13968 
13969   if (member && !closure)
13970     ctx = tsubst_aggr_type (ctx, args,
13971 			    complain, t, /*entering_scope=*/1);
13972 
13973   tree type = (lambda_fntype ? lambda_fntype
13974 	       : tsubst (TREE_TYPE (t), args,
13975 			 complain | tf_fndecl_type, in_decl));
13976   if (type == error_mark_node)
13977     return error_mark_node;
13978 
13979   /* If we hit excessive deduction depth, the type is bogus even if
13980      it isn't error_mark_node, so don't build a decl.  */
13981   if (excessive_deduction_depth)
13982     return error_mark_node;
13983 
13984   /* We do NOT check for matching decls pushed separately at this
13985      point, as they may not represent instantiations of this
13986      template, and in any case are considered separate under the
13987      discrete model.  */
13988   tree r = copy_decl (t);
13989   DECL_USE_TEMPLATE (r) = 0;
13990   TREE_TYPE (r) = type;
13991   /* Clear out the mangled name and RTL for the instantiation.  */
13992   SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
13993   SET_DECL_RTL (r, NULL);
13994   /* Leave DECL_INITIAL set on deleted instantiations.  */
13995   if (!DECL_DELETED_FN (r))
13996     DECL_INITIAL (r) = NULL_TREE;
13997   DECL_CONTEXT (r) = ctx;
13998   set_instantiating_module (r);
13999 
14000   /* Handle explicit(dependent-expr).  */
14001   if (DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (t))
14002     {
14003       tree spec = lookup_explicit_specifier (t);
14004       spec = tsubst_copy_and_build (spec, args, complain, in_decl,
14005 				    /*function_p=*/false,
14006 				    /*i_c_e_p=*/true);
14007       spec = build_explicit_specifier (spec, complain);
14008       DECL_NONCONVERTING_P (r) = (spec == boolean_true_node);
14009     }
14010 
14011   /* OpenMP UDRs have the only argument a reference to the declared
14012      type.  We want to diagnose if the declared type is a reference,
14013      which is invalid, but as references to references are usually
14014      quietly merged, diagnose it here.  */
14015   if (DECL_OMP_DECLARE_REDUCTION_P (t))
14016     {
14017       tree argtype
14018 	= TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
14019       argtype = tsubst (argtype, args, complain, in_decl);
14020       if (TYPE_REF_P (argtype))
14021 	error_at (DECL_SOURCE_LOCATION (t),
14022 		  "reference type %qT in "
14023 		  "%<#pragma omp declare reduction%>", argtype);
14024       if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
14025 	DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
14026 					  argtype);
14027     }
14028 
14029   if (member && DECL_CONV_FN_P (r))
14030     /* Type-conversion operator.  Reconstruct the name, in
14031        case it's the name of one of the template's parameters.  */
14032     DECL_NAME (r) = make_conv_op_name (TREE_TYPE (type));
14033 
14034   tree parms = DECL_ARGUMENTS (t);
14035   if (closure)
14036     parms = DECL_CHAIN (parms);
14037   parms = tsubst (parms, args, complain, t);
14038   for (tree parm = parms; parm; parm = DECL_CHAIN (parm))
14039     DECL_CONTEXT (parm) = r;
14040   if (closure)
14041     {
14042       tree tparm = build_this_parm (r, closure, type_memfn_quals (type));
14043       DECL_NAME (tparm) = closure_identifier;
14044       DECL_CHAIN (tparm) = parms;
14045       parms = tparm;
14046     }
14047   DECL_ARGUMENTS (r) = parms;
14048   DECL_RESULT (r) = NULL_TREE;
14049 
14050   maybe_rebuild_function_decl_type (r);
14051 
14052   TREE_STATIC (r) = 0;
14053   TREE_PUBLIC (r) = TREE_PUBLIC (t);
14054   DECL_EXTERNAL (r) = 1;
14055   /* If this is an instantiation of a function with internal
14056      linkage, we already know what object file linkage will be
14057      assigned to the instantiation.  */
14058   DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
14059   DECL_DEFER_OUTPUT (r) = 0;
14060   DECL_CHAIN (r) = NULL_TREE;
14061   DECL_PENDING_INLINE_INFO (r) = 0;
14062   DECL_PENDING_INLINE_P (r) = 0;
14063   DECL_SAVED_TREE (r) = NULL_TREE;
14064   DECL_STRUCT_FUNCTION (r) = NULL;
14065   TREE_USED (r) = 0;
14066   /* We'll re-clone as appropriate in instantiate_template.  */
14067   DECL_CLONED_FUNCTION (r) = NULL_TREE;
14068 
14069   /* If we aren't complaining now, return on error before we register
14070      the specialization so that we'll complain eventually.  */
14071   if ((complain & tf_error) == 0
14072       && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14073       && !grok_op_properties (r, /*complain=*/false))
14074     return error_mark_node;
14075 
14076   /* Associate the constraints directly with the instantiation. We
14077      don't substitute through the constraints; that's only done when
14078      they are checked.  */
14079   if (tree ci = get_constraints (t))
14080     set_constraints (r, ci);
14081 
14082   if (DECL_FRIEND_CONTEXT (t))
14083     SET_DECL_FRIEND_CONTEXT (r,
14084 			     tsubst (DECL_FRIEND_CONTEXT (t),
14085 				     args, complain, in_decl));
14086 
14087   if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14088 				       args, complain, in_decl))
14089     return error_mark_node;
14090 
14091   /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
14092      this in the special friend case mentioned above where
14093      GEN_TMPL is NULL.  */
14094   if (gen_tmpl && !closure)
14095     {
14096       DECL_TEMPLATE_INFO (r)
14097 	= build_template_info (gen_tmpl, argvec);
14098       SET_DECL_IMPLICIT_INSTANTIATION (r);
14099 
14100       tree new_r
14101 	= register_specialization (r, gen_tmpl, argvec, false, hash);
14102       if (new_r != r)
14103 	/* We instantiated this while substituting into
14104 	   the type earlier (template/friend54.C).  */
14105 	return new_r;
14106 
14107       /* We're not supposed to instantiate default arguments
14108 	 until they are called, for a template.  But, for a
14109 	 declaration like:
14110 
14111 	 template <class T> void f ()
14112 	 { extern void g(int i = T()); }
14113 
14114 	 we should do the substitution when the template is
14115 	 instantiated.  We handle the member function case in
14116 	 instantiate_class_template since the default arguments
14117 	 might refer to other members of the class.  */
14118       if (!member
14119 	  && !PRIMARY_TEMPLATE_P (gen_tmpl)
14120 	  && !uses_template_parms (argvec))
14121 	tsubst_default_arguments (r, complain);
14122     }
14123   else if (DECL_LOCAL_DECL_P (r))
14124     {
14125       if (!cp_unevaluated_operand)
14126 	register_local_specialization (r, t);
14127     }
14128   else
14129     DECL_TEMPLATE_INFO (r) = NULL_TREE;
14130 
14131   /* Copy the list of befriending classes.  */
14132   for (tree *friends = &DECL_BEFRIENDING_CLASSES (r);
14133        *friends;
14134        friends = &TREE_CHAIN (*friends))
14135     {
14136       *friends = copy_node (*friends);
14137       TREE_VALUE (*friends)
14138 	= tsubst (TREE_VALUE (*friends), args, complain, in_decl);
14139     }
14140 
14141   if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
14142     {
14143       maybe_retrofit_in_chrg (r);
14144       if (DECL_CONSTRUCTOR_P (r) && !grok_ctor_properties (ctx, r))
14145 	return error_mark_node;
14146       /* If this is an instantiation of a member template, clone it.
14147 	 If it isn't, that'll be handled by
14148 	 clone_constructors_and_destructors.  */
14149       if (PRIMARY_TEMPLATE_P (gen_tmpl))
14150 	clone_cdtor (r, /*update_methods=*/false);
14151     }
14152   else if ((complain & tf_error) != 0
14153 	   && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14154 	   && !grok_op_properties (r, /*complain=*/true))
14155     return error_mark_node;
14156 
14157   /* Possibly limit visibility based on template args.  */
14158   DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
14159   if (DECL_VISIBILITY_SPECIFIED (t))
14160     {
14161       DECL_VISIBILITY_SPECIFIED (r) = 0;
14162       DECL_ATTRIBUTES (r)
14163 	= remove_attribute ("visibility", DECL_ATTRIBUTES (r));
14164     }
14165   determine_visibility (r);
14166   if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
14167       && !processing_template_decl)
14168     defaulted_late_check (r);
14169 
14170   if (flag_openmp)
14171     if (tree attr = lookup_attribute ("omp declare variant base",
14172 				      DECL_ATTRIBUTES (r)))
14173       omp_declare_variant_finalize (r, attr);
14174 
14175   return r;
14176 }
14177 
14178 /* Subroutine of tsubst_decl for the case when T is a TEMPLATE_DECL.  */
14179 
14180 static tree
tsubst_template_decl(tree t,tree args,tsubst_flags_t complain,tree lambda_fntype)14181 tsubst_template_decl (tree t, tree args, tsubst_flags_t complain,
14182 		      tree lambda_fntype)
14183 {
14184   /* We can get here when processing a member function template,
14185      member class template, or template template parameter.  */
14186   tree decl = DECL_TEMPLATE_RESULT (t);
14187   tree in_decl = t;
14188   tree spec;
14189   tree tmpl_args;
14190   tree full_args;
14191   tree r;
14192   hashval_t hash = 0;
14193 
14194   if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
14195     {
14196       /* Template template parameter is treated here.  */
14197       tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14198       if (new_type == error_mark_node)
14199 	r = error_mark_node;
14200       /* If we get a real template back, return it.  This can happen in
14201 	 the context of most_specialized_partial_spec.  */
14202       else if (TREE_CODE (new_type) == TEMPLATE_DECL)
14203 	r = new_type;
14204       else
14205 	/* The new TEMPLATE_DECL was built in
14206 	   reduce_template_parm_level.  */
14207 	r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
14208       return r;
14209     }
14210 
14211   if (!lambda_fntype)
14212     {
14213       /* We might already have an instance of this template.
14214 	 The ARGS are for the surrounding class type, so the
14215 	 full args contain the tsubst'd args for the context,
14216 	 plus the innermost args from the template decl.  */
14217       tmpl_args = DECL_CLASS_TEMPLATE_P (t)
14218 	? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
14219 	: DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
14220       /* Because this is a template, the arguments will still be
14221 	 dependent, even after substitution.  If
14222 	 PROCESSING_TEMPLATE_DECL is not set, the dependency
14223 	 predicates will short-circuit.  */
14224       ++processing_template_decl;
14225       full_args = tsubst_template_args (tmpl_args, args,
14226 					complain, in_decl);
14227       --processing_template_decl;
14228       if (full_args == error_mark_node)
14229 	return error_mark_node;
14230 
14231       /* If this is a default template template argument,
14232 	 tsubst might not have changed anything.  */
14233       if (full_args == tmpl_args)
14234 	return t;
14235 
14236       hash = hash_tmpl_and_args (t, full_args);
14237       spec = retrieve_specialization (t, full_args, hash);
14238       if (spec != NULL_TREE)
14239 	{
14240 	  if (TYPE_P (spec))
14241 	    /* Type partial instantiations are stored as the type by
14242 	       lookup_template_class_1, not here as the template.  */
14243 	    spec = CLASSTYPE_TI_TEMPLATE (spec);
14244 	  return spec;
14245 	}
14246     }
14247 
14248   /* Make a new template decl.  It will be similar to the
14249      original, but will record the current template arguments.
14250      We also create a new function declaration, which is just
14251      like the old one, but points to this new template, rather
14252      than the old one.  */
14253   r = copy_decl (t);
14254   gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
14255   DECL_CHAIN (r) = NULL_TREE;
14256 
14257   // Build new template info linking to the original template decl.
14258   if (!lambda_fntype)
14259     {
14260       DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
14261       SET_DECL_IMPLICIT_INSTANTIATION (r);
14262     }
14263   else
14264     DECL_TEMPLATE_INFO (r) = NULL_TREE;
14265 
14266   /* The template parameters for this new template are all the
14267      template parameters for the old template, except the
14268      outermost level of parameters.  */
14269   auto tparm_guard = make_temp_override (current_template_parms);
14270   DECL_TEMPLATE_PARMS (r)
14271     = current_template_parms
14272     = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
14273 			     complain);
14274 
14275   bool class_p = false;
14276   tree inner = decl;
14277   ++processing_template_decl;
14278   if (TREE_CODE (inner) == FUNCTION_DECL)
14279     inner = tsubst_function_decl (inner, args, complain, lambda_fntype);
14280   else
14281     {
14282       if (TREE_CODE (inner) == TYPE_DECL && !TYPE_DECL_ALIAS_P (inner))
14283 	{
14284 	  class_p = true;
14285 	  inner = TREE_TYPE (inner);
14286 	}
14287       if (class_p)
14288 	inner = tsubst_aggr_type (inner, args, complain,
14289 				  in_decl, /*entering*/1);
14290       else
14291 	inner = tsubst (inner, args, complain, in_decl);
14292     }
14293   --processing_template_decl;
14294   if (inner == error_mark_node)
14295     return error_mark_node;
14296 
14297   if (class_p)
14298     {
14299       /* For a partial specialization, we need to keep pointing to
14300 	 the primary template.  */
14301       if (!DECL_TEMPLATE_SPECIALIZATION (t))
14302 	CLASSTYPE_TI_TEMPLATE (inner) = r;
14303 
14304       DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (inner);
14305       inner = TYPE_MAIN_DECL (inner);
14306     }
14307   else if (lambda_fntype)
14308     {
14309       tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (r));
14310       DECL_TEMPLATE_INFO (inner) = build_template_info (r, args);
14311     }
14312   else
14313     {
14314       DECL_TI_TEMPLATE (inner) = r;
14315       DECL_TI_ARGS (r) = DECL_TI_ARGS (inner);
14316     }
14317 
14318   DECL_TEMPLATE_RESULT (r) = inner;
14319   TREE_TYPE (r) = TREE_TYPE (inner);
14320   DECL_CONTEXT (r) = DECL_CONTEXT (inner);
14321 
14322   if (modules_p ())
14323     {
14324       /* Propagate module information from the decl.  */
14325       DECL_MODULE_EXPORT_P (r) = DECL_MODULE_EXPORT_P (inner);
14326       if (DECL_LANG_SPECIFIC (inner))
14327 	/* If this is a constrained template, the above tsubst of
14328 	   inner can find the unconstrained template, which may have
14329 	   come from an import.  This is ok, because we don't
14330 	   register this instantiation (see below).  */
14331 	gcc_checking_assert (!DECL_MODULE_IMPORT_P (inner)
14332 			     || (TEMPLATE_PARMS_CONSTRAINTS
14333 				 (DECL_TEMPLATE_PARMS (t))));
14334     }
14335 
14336   DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
14337   DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
14338 
14339   if (PRIMARY_TEMPLATE_P (t))
14340     DECL_PRIMARY_TEMPLATE (r) = r;
14341 
14342   if (TREE_CODE (decl) == FUNCTION_DECL && !lambda_fntype)
14343     /* Record this non-type partial instantiation.  */
14344     register_specialization (r, t,
14345 			     DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
14346 			     false, hash);
14347 
14348   return r;
14349 }
14350 
14351 /* True if FN is the op() for a lambda in an uninstantiated template.  */
14352 
14353 bool
lambda_fn_in_template_p(tree fn)14354 lambda_fn_in_template_p (tree fn)
14355 {
14356   if (!fn || !LAMBDA_FUNCTION_P (fn))
14357     return false;
14358   tree closure = DECL_CONTEXT (fn);
14359   return CLASSTYPE_TEMPLATE_INFO (closure) != NULL_TREE;
14360 }
14361 
14362 /* True if FN is the substitution (via tsubst_lambda_expr) of a function for
14363    which the above is true.  */
14364 
14365 bool
regenerated_lambda_fn_p(tree fn)14366 regenerated_lambda_fn_p (tree fn)
14367 {
14368   if (!fn || !LAMBDA_FUNCTION_P (fn))
14369     return false;
14370   tree closure = DECL_CONTEXT (fn);
14371   tree lam = CLASSTYPE_LAMBDA_EXPR (closure);
14372   return LAMBDA_EXPR_REGEN_INFO (lam) != NULL_TREE;
14373 }
14374 
14375 /* Return the LAMBDA_EXPR from which T was ultimately regenerated.
14376    If T is not a regenerated LAMBDA_EXPR, return T.  */
14377 
14378 tree
most_general_lambda(tree t)14379 most_general_lambda (tree t)
14380 {
14381   while (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
14382     t = TI_TEMPLATE (ti);
14383   return t;
14384 }
14385 
14386 /* We're instantiating a variable from template function TCTX.  Return the
14387    corresponding current enclosing scope.  This gets complicated because lambda
14388    functions in templates are regenerated rather than instantiated, but generic
14389    lambda functions are subsequently instantiated.  */
14390 
14391 static tree
enclosing_instantiation_of(tree otctx)14392 enclosing_instantiation_of (tree otctx)
14393 {
14394   tree tctx = otctx;
14395   tree fn = current_function_decl;
14396   int lambda_count = 0;
14397 
14398   for (; tctx && (lambda_fn_in_template_p (tctx)
14399 		  || regenerated_lambda_fn_p (tctx));
14400        tctx = decl_function_context (tctx))
14401     ++lambda_count;
14402 
14403   if (!tctx)
14404     {
14405       /* Match using DECL_SOURCE_LOCATION, which is unique for all lambdas.
14406 
14407 	 For GCC 11 the above condition limits this to the previously failing
14408 	 case where all enclosing functions are lambdas (95870).  FIXME.  */
14409       for (tree ofn = fn; ofn; ofn = decl_function_context (ofn))
14410 	if (DECL_SOURCE_LOCATION (ofn) == DECL_SOURCE_LOCATION (otctx))
14411 	  return ofn;
14412       gcc_unreachable ();
14413     }
14414 
14415   for (; fn; fn = decl_function_context (fn))
14416     {
14417       tree ofn = fn;
14418       int flambda_count = 0;
14419       for (; fn && regenerated_lambda_fn_p (fn);
14420 	   fn = decl_function_context (fn))
14421 	++flambda_count;
14422       if ((fn && DECL_TEMPLATE_INFO (fn))
14423 	  ? most_general_template (fn) != most_general_template (tctx)
14424 	  : fn != tctx)
14425 	continue;
14426       if (flambda_count != lambda_count)
14427 	{
14428 	  gcc_assert (flambda_count > lambda_count);
14429 	  for (; flambda_count > lambda_count; --flambda_count)
14430 	    ofn = decl_function_context (ofn);
14431 	}
14432       gcc_assert (DECL_NAME (ofn) == DECL_NAME (otctx)
14433 		  || DECL_CONV_FN_P (ofn));
14434       return ofn;
14435     }
14436   gcc_unreachable ();
14437 }
14438 
14439 /* Substitute the ARGS into the T, which is a _DECL.  Return the
14440    result of the substitution.  Issue error and warning messages under
14441    control of COMPLAIN.  */
14442 
14443 static tree
tsubst_decl(tree t,tree args,tsubst_flags_t complain)14444 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
14445 {
14446 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
14447   location_t saved_loc;
14448   tree r = NULL_TREE;
14449   tree in_decl = t;
14450   hashval_t hash = 0;
14451 
14452   /* Set the filename and linenumber to improve error-reporting.  */
14453   saved_loc = input_location;
14454   input_location = DECL_SOURCE_LOCATION (t);
14455 
14456   switch (TREE_CODE (t))
14457     {
14458     case TEMPLATE_DECL:
14459       r = tsubst_template_decl (t, args, complain, /*lambda*/NULL_TREE);
14460       break;
14461 
14462     case FUNCTION_DECL:
14463       r = tsubst_function_decl (t, args, complain, /*lambda*/NULL_TREE);
14464       break;
14465 
14466     case PARM_DECL:
14467       {
14468 	tree type = NULL_TREE;
14469         int i, len = 1;
14470         tree expanded_types = NULL_TREE;
14471         tree prev_r = NULL_TREE;
14472         tree first_r = NULL_TREE;
14473 
14474         if (DECL_PACK_P (t))
14475           {
14476             /* If there is a local specialization that isn't a
14477                parameter pack, it means that we're doing a "simple"
14478                substitution from inside tsubst_pack_expansion. Just
14479                return the local specialization (which will be a single
14480                parm).  */
14481             tree spec = retrieve_local_specialization (t);
14482             if (spec
14483                 && TREE_CODE (spec) == PARM_DECL
14484                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
14485               RETURN (spec);
14486 
14487             /* Expand the TYPE_PACK_EXPANSION that provides the types for
14488                the parameters in this function parameter pack.  */
14489             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
14490 						    complain, in_decl);
14491             if (TREE_CODE (expanded_types) == TREE_VEC)
14492               {
14493                 len = TREE_VEC_LENGTH (expanded_types);
14494 
14495                 /* Zero-length parameter packs are boring. Just substitute
14496                    into the chain.  */
14497 		if (len == 0 && !cp_unevaluated_operand)
14498                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
14499 				  TREE_CHAIN (t)));
14500               }
14501             else
14502               {
14503                 /* All we did was update the type. Make a note of that.  */
14504                 type = expanded_types;
14505                 expanded_types = NULL_TREE;
14506               }
14507           }
14508 
14509         /* Loop through all of the parameters we'll build. When T is
14510            a function parameter pack, LEN is the number of expanded
14511            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
14512         r = NULL_TREE;
14513         for (i = 0; i < len; ++i)
14514           {
14515             prev_r = r;
14516             r = copy_node (t);
14517             if (DECL_TEMPLATE_PARM_P (t))
14518               SET_DECL_TEMPLATE_PARM_P (r);
14519 
14520             if (expanded_types)
14521               /* We're on the Ith parameter of the function parameter
14522                  pack.  */
14523               {
14524                 /* Get the Ith type.  */
14525                 type = TREE_VEC_ELT (expanded_types, i);
14526 
14527 		/* Rename the parameter to include the index.  */
14528 		DECL_NAME (r)
14529 		  = make_ith_pack_parameter_name (DECL_NAME (r), i);
14530               }
14531             else if (!type)
14532               /* We're dealing with a normal parameter.  */
14533               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14534 
14535             type = type_decays_to (type);
14536             TREE_TYPE (r) = type;
14537             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14538 
14539             if (DECL_INITIAL (r))
14540               {
14541                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
14542                   DECL_INITIAL (r) = TREE_TYPE (r);
14543                 else
14544                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
14545                                              complain, in_decl);
14546               }
14547 
14548             DECL_CONTEXT (r) = NULL_TREE;
14549 
14550             if (!DECL_TEMPLATE_PARM_P (r))
14551               DECL_ARG_TYPE (r) = type_passed_as (type);
14552 
14553 	    if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14554 						 args, complain, in_decl))
14555 	      return error_mark_node;
14556 
14557             /* Keep track of the first new parameter we
14558                generate. That's what will be returned to the
14559                caller.  */
14560             if (!first_r)
14561               first_r = r;
14562 
14563             /* Build a proper chain of parameters when substituting
14564                into a function parameter pack.  */
14565             if (prev_r)
14566               DECL_CHAIN (prev_r) = r;
14567           }
14568 
14569 	/* If cp_unevaluated_operand is set, we're just looking for a
14570 	   single dummy parameter, so don't keep going.  */
14571 	if (DECL_CHAIN (t) && !cp_unevaluated_operand)
14572 	  DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
14573 				   complain, DECL_CHAIN (t));
14574 
14575         /* FIRST_R contains the start of the chain we've built.  */
14576         r = first_r;
14577       }
14578       break;
14579 
14580     case FIELD_DECL:
14581       {
14582 	tree type = NULL_TREE;
14583 	tree vec = NULL_TREE;
14584 	tree expanded_types = NULL_TREE;
14585 	int len = 1;
14586 
14587 	if (PACK_EXPANSION_P (TREE_TYPE (t)))
14588 	  {
14589 	    /* This field is a lambda capture pack.  Return a TREE_VEC of
14590 	       the expanded fields to instantiate_class_template_1.  */
14591             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
14592 						    complain, in_decl);
14593             if (TREE_CODE (expanded_types) == TREE_VEC)
14594               {
14595                 len = TREE_VEC_LENGTH (expanded_types);
14596 		vec = make_tree_vec (len);
14597               }
14598             else
14599               {
14600                 /* All we did was update the type. Make a note of that.  */
14601                 type = expanded_types;
14602                 expanded_types = NULL_TREE;
14603               }
14604 	  }
14605 
14606 	for (int i = 0; i < len; ++i)
14607 	  {
14608 	    r = copy_decl (t);
14609 	    if (expanded_types)
14610 	      {
14611 		type = TREE_VEC_ELT (expanded_types, i);
14612 		DECL_NAME (r)
14613 		  = make_ith_pack_parameter_name (DECL_NAME (r), i);
14614 	      }
14615             else if (!type)
14616               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14617 
14618 	    if (type == error_mark_node)
14619 	      RETURN (error_mark_node);
14620 	    TREE_TYPE (r) = type;
14621 	    cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14622 
14623 	    if (DECL_C_BIT_FIELD (r))
14624 	      /* For bit-fields, DECL_BIT_FIELD_REPRESENTATIVE gives the
14625 		 number of bits.  */
14626 	      DECL_BIT_FIELD_REPRESENTATIVE (r)
14627 		= tsubst_expr (DECL_BIT_FIELD_REPRESENTATIVE (t), args,
14628 			       complain, in_decl,
14629 			       /*integral_constant_expression_p=*/true);
14630 	    if (DECL_INITIAL (t))
14631 	      {
14632 		/* Set up DECL_TEMPLATE_INFO so that we can get at the
14633 		   NSDMI in perform_member_init.  Still set DECL_INITIAL
14634 		   so that we know there is one.  */
14635 		DECL_INITIAL (r) = void_node;
14636 		gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
14637 		retrofit_lang_decl (r);
14638 		DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
14639 	      }
14640 	    /* We don't have to set DECL_CONTEXT here; it is set by
14641 	       finish_member_declaration.  */
14642 	    DECL_CHAIN (r) = NULL_TREE;
14643 
14644 	    if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14645 						 args, complain, in_decl))
14646 	      return error_mark_node;
14647 
14648 	    if (vec)
14649 	      TREE_VEC_ELT (vec, i) = r;
14650 	  }
14651 
14652 	if (vec)
14653 	  r = vec;
14654       }
14655       break;
14656 
14657     case USING_DECL:
14658       /* We reach here only for member using decls.  We also need to check
14659 	 uses_template_parms because DECL_DEPENDENT_P is not set for a
14660 	 using-declaration that designates a member of the current
14661 	 instantiation (c++/53549).  */
14662       if (DECL_DEPENDENT_P (t)
14663 	  || uses_template_parms (USING_DECL_SCOPE (t)))
14664 	{
14665 	  tree scope = USING_DECL_SCOPE (t);
14666 	  tree name = tsubst_copy (DECL_NAME (t), args, complain, in_decl);
14667 	  if (PACK_EXPANSION_P (scope))
14668 	    {
14669 	      tree vec = tsubst_pack_expansion (scope, args, complain, in_decl);
14670 	      int len = TREE_VEC_LENGTH (vec);
14671 	      r = make_tree_vec (len);
14672 	      for (int i = 0; i < len; ++i)
14673 		{
14674 		  tree escope = TREE_VEC_ELT (vec, i);
14675 		  tree elt = do_class_using_decl (escope, name);
14676 		  if (!elt)
14677 		    {
14678 		      r = error_mark_node;
14679 		      break;
14680 		    }
14681 		  else
14682 		    {
14683 		      TREE_PROTECTED (elt) = TREE_PROTECTED (t);
14684 		      TREE_PRIVATE (elt) = TREE_PRIVATE (t);
14685 		    }
14686 		  TREE_VEC_ELT (r, i) = elt;
14687 		}
14688 	    }
14689 	  else
14690 	    {
14691 	      tree inst_scope = tsubst_copy (USING_DECL_SCOPE (t), args,
14692 					     complain, in_decl);
14693 	      r = do_class_using_decl (inst_scope, name);
14694 	      if (!r)
14695 		r = error_mark_node;
14696 	      else
14697 		{
14698 		  TREE_PROTECTED (r) = TREE_PROTECTED (t);
14699 		  TREE_PRIVATE (r) = TREE_PRIVATE (t);
14700 		}
14701 	    }
14702 	}
14703       else
14704 	{
14705 	  r = copy_node (t);
14706 	  DECL_CHAIN (r) = NULL_TREE;
14707 	}
14708       break;
14709 
14710     case TYPE_DECL:
14711     case VAR_DECL:
14712       {
14713 	tree argvec = NULL_TREE;
14714 	tree gen_tmpl = NULL_TREE;
14715 	tree tmpl = NULL_TREE;
14716 	tree type = NULL_TREE;
14717 
14718 	if (TREE_TYPE (t) == error_mark_node)
14719 	  RETURN (error_mark_node);
14720 
14721 	if (TREE_CODE (t) == TYPE_DECL
14722 	    && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
14723 	  {
14724 	    /* If this is the canonical decl, we don't have to
14725 	       mess with instantiations, and often we can't (for
14726 	       typename, template type parms and such).  Note that
14727 	       TYPE_NAME is not correct for the above test if
14728 	       we've copied the type for a typedef.  */
14729 	    type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14730 	    if (type == error_mark_node)
14731 	      RETURN (error_mark_node);
14732 	    r = TYPE_NAME (type);
14733 	    break;
14734 	  }
14735 
14736 	/* Check to see if we already have the specialization we
14737 	   need.  */
14738 	tree spec = NULL_TREE;
14739 	bool local_p = false;
14740 	tree ctx = DECL_CONTEXT (t);
14741 	if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t))
14742 	    && (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t)))
14743 	  {
14744 	    local_p = false;
14745 	    if (DECL_CLASS_SCOPE_P (t))
14746 	      {
14747 		ctx = tsubst_aggr_type (ctx, args,
14748 					complain,
14749 					in_decl, /*entering_scope=*/1);
14750 		/* If CTX is unchanged, then T is in fact the
14751 		   specialization we want.  That situation occurs when
14752 		   referencing a static data member within in its own
14753 		   class.  We can use pointer equality, rather than
14754 		   same_type_p, because DECL_CONTEXT is always
14755 		   canonical...  */
14756 		if (ctx == DECL_CONTEXT (t)
14757 		    /* ... unless T is a member template; in which
14758 		       case our caller can be willing to create a
14759 		       specialization of that template represented
14760 		       by T.  */
14761 		    && !(DECL_TI_TEMPLATE (t)
14762 			 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
14763 		  spec = t;
14764 	      }
14765 
14766 	    if (!spec)
14767 	      {
14768 		tmpl = DECL_TI_TEMPLATE (t);
14769 		gen_tmpl = most_general_template (tmpl);
14770 		argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
14771 		if (argvec != error_mark_node)
14772 		  argvec = (coerce_innermost_template_parms
14773 			    (DECL_TEMPLATE_PARMS (gen_tmpl),
14774 			     argvec, t, complain,
14775 			     /*all*/true, /*defarg*/true));
14776 		if (argvec == error_mark_node)
14777 		  RETURN (error_mark_node);
14778 		hash = hash_tmpl_and_args (gen_tmpl, argvec);
14779 		spec = retrieve_specialization (gen_tmpl, argvec, hash);
14780 	      }
14781 	  }
14782 	else
14783 	  {
14784 	    if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t)))
14785 	      /* Subsequent calls to pushdecl will fill this in.  */
14786 	      ctx = NULL_TREE;
14787 	    /* A local variable.  */
14788 	    local_p = true;
14789 	    /* Unless this is a reference to a static variable from an
14790 	       enclosing function, in which case we need to fill it in now.  */
14791 	    if (TREE_STATIC (t))
14792 	      {
14793 		tree fn = enclosing_instantiation_of (DECL_CONTEXT (t));
14794 		if (fn != current_function_decl)
14795 		  ctx = fn;
14796 	      }
14797 	    spec = retrieve_local_specialization (t);
14798 	  }
14799 	/* If we already have the specialization we need, there is
14800 	   nothing more to do.  */
14801 	if (spec)
14802 	  {
14803 	    r = spec;
14804 	    break;
14805 	  }
14806 
14807 	/* Create a new node for the specialization we need.  */
14808 	if (type == NULL_TREE)
14809 	  {
14810 	    if (is_typedef_decl (t))
14811 	      type = DECL_ORIGINAL_TYPE (t);
14812 	    else
14813 	      type = TREE_TYPE (t);
14814 	    if (VAR_P (t)
14815 		&& VAR_HAD_UNKNOWN_BOUND (t)
14816 		&& type != error_mark_node)
14817 	      type = strip_array_domain (type);
14818 	    tree sub_args = args;
14819 	    if (tree auto_node = type_uses_auto (type))
14820 	      {
14821 		/* Mask off any template args past the variable's context so we
14822 		   don't replace the auto with an unrelated argument.  */
14823 		int nouter = TEMPLATE_TYPE_LEVEL (auto_node) - 1;
14824 		int extra = TMPL_ARGS_DEPTH (args) - nouter;
14825 		if (extra > 0)
14826 		  /* This should never happen with the new lambda instantiation
14827 		     model, but keep the handling just in case.  */
14828 		  gcc_assert (!CHECKING_P),
14829 		  sub_args = strip_innermost_template_args (args, extra);
14830 	      }
14831 	    type = tsubst (type, sub_args, complain, in_decl);
14832 	    /* Substituting the type might have recursively instantiated this
14833 	       same alias (c++/86171).  */
14834 	    if (gen_tmpl && DECL_ALIAS_TEMPLATE_P (gen_tmpl)
14835 		&& (spec = retrieve_specialization (gen_tmpl, argvec, hash)))
14836 	      {
14837 		r = spec;
14838 		break;
14839 	      }
14840 	  }
14841 	r = copy_decl (t);
14842 	if (VAR_P (r))
14843 	  {
14844 	    DECL_INITIALIZED_P (r) = 0;
14845 	    DECL_TEMPLATE_INSTANTIATED (r) = 0;
14846 	    if (type == error_mark_node)
14847 	      RETURN (error_mark_node);
14848 	    if (TREE_CODE (type) == FUNCTION_TYPE)
14849 	      {
14850 		/* It may seem that this case cannot occur, since:
14851 
14852 		   typedef void f();
14853 		   void g() { f x; }
14854 
14855 		   declares a function, not a variable.  However:
14856 
14857 		   typedef void f();
14858 		   template <typename T> void g() { T t; }
14859 		   template void g<f>();
14860 
14861 		   is an attempt to declare a variable with function
14862 		   type.  */
14863 		error ("variable %qD has function type",
14864 		       /* R is not yet sufficiently initialized, so we
14865 			  just use its name.  */
14866 		       DECL_NAME (r));
14867 		RETURN (error_mark_node);
14868 	      }
14869 	    type = complete_type (type);
14870 	    /* Wait until cp_finish_decl to set this again, to handle
14871 	       circular dependency (template/instantiate6.C). */
14872 	    DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
14873 	    type = check_var_type (DECL_NAME (r), type,
14874 				   DECL_SOURCE_LOCATION (r));
14875 	    if (DECL_HAS_VALUE_EXPR_P (t))
14876 	      {
14877 		tree ve = DECL_VALUE_EXPR (t);
14878 		/* If the DECL_VALUE_EXPR is converted to the declared type,
14879 		   preserve the identity so that gimplify_type_sizes works.  */
14880 		bool nop = (TREE_CODE (ve) == NOP_EXPR);
14881 		if (nop)
14882 		  ve = TREE_OPERAND (ve, 0);
14883 		ve = tsubst_expr (ve, args, complain, in_decl,
14884 				  /*constant_expression_p=*/false);
14885 		if (REFERENCE_REF_P (ve))
14886 		  {
14887 		    gcc_assert (TYPE_REF_P (type));
14888 		    ve = TREE_OPERAND (ve, 0);
14889 		  }
14890 		if (nop)
14891 		  ve = build_nop (type, ve);
14892 		else if (DECL_LANG_SPECIFIC (t)
14893 			 && DECL_OMP_PRIVATIZED_MEMBER (t)
14894 			 && TREE_CODE (ve) == COMPONENT_REF
14895 			 && TREE_CODE (TREE_OPERAND (ve, 1)) == FIELD_DECL
14896 			 && DECL_BIT_FIELD_TYPE (TREE_OPERAND (ve, 1)) == type)
14897 		  type = TREE_TYPE (ve);
14898 		else
14899 		  gcc_checking_assert (TYPE_MAIN_VARIANT (TREE_TYPE (ve))
14900 				       == TYPE_MAIN_VARIANT (type));
14901 		SET_DECL_VALUE_EXPR (r, ve);
14902 	      }
14903 	    if (CP_DECL_THREAD_LOCAL_P (r)
14904 		&& !processing_template_decl)
14905 	      set_decl_tls_model (r, decl_default_tls_model (r));
14906 	  }
14907 	else if (DECL_SELF_REFERENCE_P (t))
14908 	  SET_DECL_SELF_REFERENCE_P (r);
14909 	TREE_TYPE (r) = type;
14910 	cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14911 	DECL_CONTEXT (r) = ctx;
14912 	/* Clear out the mangled name and RTL for the instantiation.  */
14913 	SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
14914 	if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
14915 	  SET_DECL_RTL (r, NULL);
14916 	set_instantiating_module (r);
14917 
14918 	/* The initializer must not be expanded until it is required;
14919 	   see [temp.inst].  */
14920 	DECL_INITIAL (r) = NULL_TREE;
14921 	DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
14922 	if (VAR_P (r))
14923 	  {
14924 	    if (DECL_LANG_SPECIFIC (r))
14925 	      SET_DECL_DEPENDENT_INIT_P (r, false);
14926 
14927 	    SET_DECL_MODE (r, VOIDmode);
14928 
14929 	    /* Possibly limit visibility based on template args.  */
14930 	    DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
14931 	    if (DECL_VISIBILITY_SPECIFIED (t))
14932 	      {
14933 		DECL_VISIBILITY_SPECIFIED (r) = 0;
14934 		DECL_ATTRIBUTES (r)
14935 		  = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
14936 	      }
14937 	    determine_visibility (r);
14938 	  }
14939 
14940 	if (!local_p)
14941 	  {
14942 	    /* A static data member declaration is always marked
14943 	       external when it is declared in-class, even if an
14944 	       initializer is present.  We mimic the non-template
14945 	       processing here.  */
14946 	    DECL_EXTERNAL (r) = 1;
14947 	    if (DECL_NAMESPACE_SCOPE_P (t))
14948 	      DECL_NOT_REALLY_EXTERN (r) = 1;
14949 
14950 	    DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
14951 	    SET_DECL_IMPLICIT_INSTANTIATION (r);
14952 	    if (!error_operand_p (r) || (complain & tf_error))
14953 	      register_specialization (r, gen_tmpl, argvec, false, hash);
14954 	  }
14955 	else
14956 	  {
14957 	    if (DECL_LANG_SPECIFIC (r))
14958 	      DECL_TEMPLATE_INFO (r) = NULL_TREE;
14959 	    if (!cp_unevaluated_operand)
14960 	      register_local_specialization (r, t);
14961 	  }
14962 
14963 	DECL_CHAIN (r) = NULL_TREE;
14964 
14965 	if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
14966 					     /*flags=*/0,
14967 					     args, complain, in_decl))
14968 	  return error_mark_node;
14969 
14970 	/* Preserve a typedef that names a type.  */
14971 	if (is_typedef_decl (r) && type != error_mark_node)
14972 	  {
14973 	    DECL_ORIGINAL_TYPE (r) = NULL_TREE;
14974 	    set_underlying_type (r);
14975 	  }
14976 
14977 	layout_decl (r, 0);
14978       }
14979       break;
14980 
14981     default:
14982       gcc_unreachable ();
14983     }
14984 #undef RETURN
14985 
14986  out:
14987   /* Restore the file and line information.  */
14988   input_location = saved_loc;
14989 
14990   return r;
14991 }
14992 
14993 /* Substitute into the complete parameter type list PARMS.  */
14994 
14995 tree
tsubst_function_parms(tree parms,tree args,tsubst_flags_t complain,tree in_decl)14996 tsubst_function_parms (tree parms,
14997 		       tree args,
14998 		       tsubst_flags_t complain,
14999 		       tree in_decl)
15000 {
15001   return tsubst_arg_types (parms, args, NULL_TREE, complain, in_decl);
15002 }
15003 
15004 /* Substitute into the ARG_TYPES of a function type.
15005    If END is a TREE_CHAIN, leave it and any following types
15006    un-substituted.  */
15007 
15008 static tree
tsubst_arg_types(tree arg_types,tree args,tree end,tsubst_flags_t complain,tree in_decl)15009 tsubst_arg_types (tree arg_types,
15010 		  tree args,
15011 		  tree end,
15012 		  tsubst_flags_t complain,
15013 		  tree in_decl)
15014 {
15015   tree remaining_arg_types;
15016   tree type = NULL_TREE;
15017   int i = 1;
15018   tree expanded_args = NULL_TREE;
15019   tree default_arg;
15020 
15021   if (!arg_types || arg_types == void_list_node || arg_types == end)
15022     return arg_types;
15023 
15024   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
15025 					  args, end, complain, in_decl);
15026   if (remaining_arg_types == error_mark_node)
15027     return error_mark_node;
15028 
15029   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
15030     {
15031       /* For a pack expansion, perform substitution on the
15032          entire expression. Later on, we'll handle the arguments
15033          one-by-one.  */
15034       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
15035                                             args, complain, in_decl);
15036 
15037       if (TREE_CODE (expanded_args) == TREE_VEC)
15038         /* So that we'll spin through the parameters, one by one.  */
15039         i = TREE_VEC_LENGTH (expanded_args);
15040       else
15041         {
15042           /* We only partially substituted into the parameter
15043              pack. Our type is TYPE_PACK_EXPANSION.  */
15044           type = expanded_args;
15045           expanded_args = NULL_TREE;
15046         }
15047     }
15048 
15049   while (i > 0) {
15050     --i;
15051 
15052     if (expanded_args)
15053       type = TREE_VEC_ELT (expanded_args, i);
15054     else if (!type)
15055       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
15056 
15057     if (type == error_mark_node)
15058       return error_mark_node;
15059     if (VOID_TYPE_P (type))
15060       {
15061         if (complain & tf_error)
15062           {
15063             error ("invalid parameter type %qT", type);
15064             if (in_decl)
15065               error ("in declaration %q+D", in_decl);
15066           }
15067         return error_mark_node;
15068     }
15069 
15070     /* Do array-to-pointer, function-to-pointer conversion, and ignore
15071        top-level qualifiers as required.  */
15072     type = cv_unqualified (type_decays_to (type));
15073 
15074     /* We do not substitute into default arguments here.  The standard
15075        mandates that they be instantiated only when needed, which is
15076        done in build_over_call.  */
15077     default_arg = TREE_PURPOSE (arg_types);
15078 
15079     /* Except that we do substitute default arguments under tsubst_lambda_expr,
15080        since the new op() won't have any associated template arguments for us
15081        to refer to later.  */
15082     if (lambda_fn_in_template_p (in_decl))
15083       default_arg = tsubst_copy_and_build (default_arg, args, complain, in_decl,
15084 					   false/*fn*/, false/*constexpr*/);
15085 
15086     if (default_arg && TREE_CODE (default_arg) == DEFERRED_PARSE)
15087       {
15088         /* We've instantiated a template before its default arguments
15089            have been parsed.  This can happen for a nested template
15090            class, and is not an error unless we require the default
15091            argument in a call of this function.  */
15092         remaining_arg_types =
15093           tree_cons (default_arg, type, remaining_arg_types);
15094 	vec_safe_push (DEFPARSE_INSTANTIATIONS (default_arg),
15095 		       remaining_arg_types);
15096       }
15097     else
15098       remaining_arg_types =
15099         hash_tree_cons (default_arg, type, remaining_arg_types);
15100   }
15101 
15102   return remaining_arg_types;
15103 }
15104 
15105 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
15106    *not* handle the exception-specification for FNTYPE, because the
15107    initial substitution of explicitly provided template parameters
15108    during argument deduction forbids substitution into the
15109    exception-specification:
15110 
15111      [temp.deduct]
15112 
15113      All references in the function type of the function template to  the
15114      corresponding template parameters are replaced by the specified tem-
15115      plate argument values.  If a substitution in a template parameter or
15116      in  the function type of the function template results in an invalid
15117      type, type deduction fails.  [Note: The equivalent  substitution  in
15118      exception specifications is done only when the function is instanti-
15119      ated, at which point a program is  ill-formed  if  the  substitution
15120      results in an invalid type.]  */
15121 
15122 static tree
tsubst_function_type(tree t,tree args,tsubst_flags_t complain,tree in_decl)15123 tsubst_function_type (tree t,
15124 		      tree args,
15125 		      tsubst_flags_t complain,
15126 		      tree in_decl)
15127 {
15128   tree return_type;
15129   tree arg_types = NULL_TREE;
15130 
15131   /* The TYPE_CONTEXT is not used for function/method types.  */
15132   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
15133 
15134   /* DR 1227: Mixing immediate and non-immediate contexts in deduction
15135      failure.  */
15136   bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
15137 
15138   if (late_return_type_p)
15139     {
15140       /* Substitute the argument types.  */
15141       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15142 				    complain, in_decl);
15143       if (arg_types == error_mark_node)
15144 	return error_mark_node;
15145 
15146       tree save_ccp = current_class_ptr;
15147       tree save_ccr = current_class_ref;
15148       tree this_type = (TREE_CODE (t) == METHOD_TYPE
15149 			? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
15150       bool do_inject = this_type && CLASS_TYPE_P (this_type);
15151       if (do_inject)
15152 	{
15153 	  /* DR 1207: 'this' is in scope in the trailing return type.  */
15154 	  inject_this_parameter (this_type, cp_type_quals (this_type));
15155 	}
15156 
15157       /* Substitute the return type.  */
15158       return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15159 
15160       if (do_inject)
15161 	{
15162 	  current_class_ptr = save_ccp;
15163 	  current_class_ref = save_ccr;
15164 	}
15165     }
15166   else
15167     /* Substitute the return type.  */
15168     return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15169 
15170   if (return_type == error_mark_node)
15171     return error_mark_node;
15172   /* DR 486 clarifies that creation of a function type with an
15173      invalid return type is a deduction failure.  */
15174   if (TREE_CODE (return_type) == ARRAY_TYPE
15175       || TREE_CODE (return_type) == FUNCTION_TYPE)
15176     {
15177       if (complain & tf_error)
15178 	{
15179 	  if (TREE_CODE (return_type) == ARRAY_TYPE)
15180 	    error ("function returning an array");
15181 	  else
15182 	    error ("function returning a function");
15183 	}
15184       return error_mark_node;
15185     }
15186 
15187   if (!late_return_type_p)
15188     {
15189       /* Substitute the argument types.  */
15190       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15191 				    complain, in_decl);
15192       if (arg_types == error_mark_node)
15193 	return error_mark_node;
15194     }
15195 
15196   /* Construct a new type node and return it.  */
15197   return rebuild_function_or_method_type (t, return_type, arg_types,
15198 					  /*raises=*/NULL_TREE, complain);
15199 }
15200 
15201 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
15202    ARGS into that specification, and return the substituted
15203    specification.  If there is no specification, return NULL_TREE.  */
15204 
15205 static tree
tsubst_exception_specification(tree fntype,tree args,tsubst_flags_t complain,tree in_decl,bool defer_ok)15206 tsubst_exception_specification (tree fntype,
15207 				tree args,
15208 				tsubst_flags_t complain,
15209 				tree in_decl,
15210 				bool defer_ok)
15211 {
15212   tree specs;
15213   tree new_specs;
15214 
15215   specs = TYPE_RAISES_EXCEPTIONS (fntype);
15216   new_specs = NULL_TREE;
15217   if (specs && TREE_PURPOSE (specs))
15218     {
15219       /* A noexcept-specifier.  */
15220       tree expr = TREE_PURPOSE (specs);
15221       if (TREE_CODE (expr) == INTEGER_CST)
15222 	new_specs = expr;
15223       else if (defer_ok)
15224 	{
15225 	  /* Defer instantiation of noexcept-specifiers to avoid
15226 	     excessive instantiations (c++/49107).  */
15227 	  new_specs = make_node (DEFERRED_NOEXCEPT);
15228 	  if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15229 	    {
15230 	      /* We already partially instantiated this member template,
15231 		 so combine the new args with the old.  */
15232 	      DEFERRED_NOEXCEPT_PATTERN (new_specs)
15233 		= DEFERRED_NOEXCEPT_PATTERN (expr);
15234 	      DEFERRED_NOEXCEPT_ARGS (new_specs)
15235 		= add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
15236 	    }
15237 	  else
15238 	    {
15239 	      DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
15240 	      DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
15241 	    }
15242 	}
15243       else
15244 	{
15245 	  if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15246 	    {
15247 	      args = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr),
15248 					   args);
15249 	      expr = DEFERRED_NOEXCEPT_PATTERN (expr);
15250 	    }
15251 	  new_specs = tsubst_copy_and_build
15252 	    (expr, args, complain, in_decl, /*function_p=*/false,
15253 	     /*integral_constant_expression_p=*/true);
15254 	}
15255       new_specs = build_noexcept_spec (new_specs, complain);
15256       /* We've instantiated a template before a noexcept-specifier
15257 	 contained therein has been parsed.  This can happen for
15258 	 a nested template class:
15259 
15260 	  struct S {
15261 	    template<typename> struct B { B() noexcept(...); };
15262 	    struct A : B<int> { ... use B() ... };
15263 	  };
15264 
15265 	 where completing B<int> will trigger instantiating the
15266 	 noexcept, even though we only parse it at the end of S.  */
15267       if (UNPARSED_NOEXCEPT_SPEC_P (specs))
15268 	{
15269 	  gcc_checking_assert (defer_ok);
15270 	  vec_safe_push (DEFPARSE_INSTANTIATIONS (expr), new_specs);
15271 	}
15272     }
15273   else if (specs)
15274     {
15275       if (! TREE_VALUE (specs))
15276 	new_specs = specs;
15277       else
15278 	while (specs)
15279 	  {
15280 	    tree spec;
15281             int i, len = 1;
15282             tree expanded_specs = NULL_TREE;
15283 
15284             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
15285               {
15286                 /* Expand the pack expansion type.  */
15287                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
15288                                                        args, complain,
15289                                                        in_decl);
15290 
15291 		if (expanded_specs == error_mark_node)
15292 		  return error_mark_node;
15293 		else if (TREE_CODE (expanded_specs) == TREE_VEC)
15294 		  len = TREE_VEC_LENGTH (expanded_specs);
15295 		else
15296 		  {
15297 		    /* We're substituting into a member template, so
15298 		       we got a TYPE_PACK_EXPANSION back.  Add that
15299 		       expansion and move on.  */
15300 		    gcc_assert (TREE_CODE (expanded_specs)
15301 				== TYPE_PACK_EXPANSION);
15302 		    new_specs = add_exception_specifier (new_specs,
15303 							 expanded_specs,
15304 							 complain);
15305 		    specs = TREE_CHAIN (specs);
15306 		    continue;
15307 		  }
15308               }
15309 
15310             for (i = 0; i < len; ++i)
15311               {
15312                 if (expanded_specs)
15313                   spec = TREE_VEC_ELT (expanded_specs, i);
15314                 else
15315                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
15316                 if (spec == error_mark_node)
15317                   return spec;
15318                 new_specs = add_exception_specifier (new_specs, spec,
15319                                                      complain);
15320               }
15321 
15322             specs = TREE_CHAIN (specs);
15323 	  }
15324     }
15325   return new_specs;
15326 }
15327 
15328 /* Substitute through a TREE_LIST of types or expressions, handling pack
15329    expansions.  */
15330 
15331 tree
tsubst_tree_list(tree t,tree args,tsubst_flags_t complain,tree in_decl)15332 tsubst_tree_list (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15333 {
15334   if (t == void_list_node)
15335     return t;
15336 
15337   tree purpose = TREE_PURPOSE (t);
15338   tree purposevec = NULL_TREE;
15339   if (!purpose)
15340     ;
15341   else if (PACK_EXPANSION_P (purpose))
15342     {
15343       purpose = tsubst_pack_expansion (purpose, args, complain, in_decl);
15344       if (TREE_CODE (purpose) == TREE_VEC)
15345 	purposevec = purpose;
15346     }
15347   else if (TYPE_P (purpose))
15348     purpose = tsubst (purpose, args, complain, in_decl);
15349   else
15350     purpose = tsubst_copy_and_build (purpose, args, complain, in_decl);
15351   if (purpose == error_mark_node || purposevec == error_mark_node)
15352     return error_mark_node;
15353 
15354   tree value = TREE_VALUE (t);
15355   tree valuevec = NULL_TREE;
15356   if (!value)
15357     ;
15358   else if (PACK_EXPANSION_P (value))
15359     {
15360       value = tsubst_pack_expansion (value, args, complain, in_decl);
15361       if (TREE_CODE (value) == TREE_VEC)
15362 	valuevec = value;
15363     }
15364   else if (TYPE_P (value))
15365     value = tsubst (value, args, complain, in_decl);
15366   else
15367     value = tsubst_copy_and_build (value, args, complain, in_decl);
15368   if (value == error_mark_node || valuevec == error_mark_node)
15369     return error_mark_node;
15370 
15371   tree chain = TREE_CHAIN (t);
15372   if (!chain)
15373     ;
15374   else if (TREE_CODE (chain) == TREE_LIST)
15375     chain = tsubst_tree_list (chain, args, complain, in_decl);
15376   else if (TYPE_P (chain))
15377     chain = tsubst (chain, args, complain, in_decl);
15378   else
15379     chain = tsubst_copy_and_build (chain, args, complain, in_decl);
15380   if (chain == error_mark_node)
15381     return error_mark_node;
15382 
15383   if (purpose == TREE_PURPOSE (t)
15384       && value == TREE_VALUE (t)
15385       && chain == TREE_CHAIN (t))
15386     return t;
15387 
15388   int len;
15389   /* Determine the number of arguments.  */
15390   if (purposevec)
15391     {
15392       len = TREE_VEC_LENGTH (purposevec);
15393       gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
15394     }
15395   else if (valuevec)
15396     len = TREE_VEC_LENGTH (valuevec);
15397   else
15398     len = 1;
15399 
15400   for (int i = len; i-- > 0; )
15401     {
15402       if (purposevec)
15403 	purpose = TREE_VEC_ELT (purposevec, i);
15404       if (valuevec)
15405 	value = TREE_VEC_ELT (valuevec, i);
15406 
15407       if (value && TYPE_P (value))
15408 	chain = hash_tree_cons (purpose, value, chain);
15409       else
15410 	chain = tree_cons (purpose, value, chain);
15411     }
15412 
15413   return chain;
15414 }
15415 
15416 /* Take the tree structure T and replace template parameters used
15417    therein with the argument vector ARGS.  IN_DECL is an associated
15418    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
15419    Issue error and warning messages under control of COMPLAIN.  Note
15420    that we must be relatively non-tolerant of extensions here, in
15421    order to preserve conformance; if we allow substitutions that
15422    should not be allowed, we may allow argument deductions that should
15423    not succeed, and therefore report ambiguous overload situations
15424    where there are none.  In theory, we could allow the substitution,
15425    but indicate that it should have failed, and allow our caller to
15426    make sure that the right thing happens, but we don't try to do this
15427    yet.
15428 
15429    This function is used for dealing with types, decls and the like;
15430    for expressions, use tsubst_expr or tsubst_copy.  */
15431 
15432 tree
tsubst(tree t,tree args,tsubst_flags_t complain,tree in_decl)15433 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15434 {
15435   enum tree_code code;
15436   tree type, r = NULL_TREE;
15437 
15438   if (t == NULL_TREE || t == error_mark_node
15439       || t == integer_type_node
15440       || t == void_type_node
15441       || t == char_type_node
15442       || t == unknown_type_node
15443       || TREE_CODE (t) == NAMESPACE_DECL
15444       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
15445     return t;
15446 
15447   if (DECL_P (t))
15448     return tsubst_decl (t, args, complain);
15449 
15450   if (args == NULL_TREE)
15451     return t;
15452 
15453   code = TREE_CODE (t);
15454 
15455   gcc_assert (code != IDENTIFIER_NODE);
15456   type = TREE_TYPE (t);
15457 
15458   gcc_assert (type != unknown_type_node);
15459 
15460   /* Reuse typedefs.  We need to do this to handle dependent attributes,
15461      such as attribute aligned.  */
15462   if (TYPE_P (t)
15463       && typedef_variant_p (t))
15464     {
15465       tree decl = TYPE_NAME (t);
15466 
15467       if (alias_template_specialization_p (t, nt_opaque))
15468 	{
15469 	  /* DECL represents an alias template and we want to
15470 	     instantiate it.  */
15471 	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15472 	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15473 	  r = instantiate_alias_template (tmpl, gen_args, complain);
15474 	}
15475       else if (DECL_CLASS_SCOPE_P (decl)
15476 	       && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
15477 	       && uses_template_parms (DECL_CONTEXT (decl)))
15478 	{
15479 	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15480 	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15481 	  r = retrieve_specialization (tmpl, gen_args, 0);
15482 	}
15483       else if (DECL_FUNCTION_SCOPE_P (decl)
15484 	       && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
15485 	       && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
15486 	r = retrieve_local_specialization (decl);
15487       else
15488 	/* The typedef is from a non-template context.  */
15489 	return t;
15490 
15491       if (r)
15492 	{
15493 	  r = TREE_TYPE (r);
15494 	  r = cp_build_qualified_type_real
15495 	    (r, cp_type_quals (t) | cp_type_quals (r),
15496 	     complain | tf_ignore_bad_quals);
15497 	  return r;
15498 	}
15499       else
15500 	{
15501 	  /* We don't have an instantiation yet, so drop the typedef.  */
15502 	  int quals = cp_type_quals (t);
15503 	  t = DECL_ORIGINAL_TYPE (decl);
15504 	  t = cp_build_qualified_type_real (t, quals,
15505 					    complain | tf_ignore_bad_quals);
15506 	}
15507     }
15508 
15509   bool fndecl_type = (complain & tf_fndecl_type);
15510   complain &= ~tf_fndecl_type;
15511 
15512   if (type
15513       && code != TYPENAME_TYPE
15514       && code != TEMPLATE_TYPE_PARM
15515       && code != TEMPLATE_PARM_INDEX
15516       && code != IDENTIFIER_NODE
15517       && code != FUNCTION_TYPE
15518       && code != METHOD_TYPE)
15519     type = tsubst (type, args, complain, in_decl);
15520   if (type == error_mark_node)
15521     return error_mark_node;
15522 
15523   switch (code)
15524     {
15525     case RECORD_TYPE:
15526     case UNION_TYPE:
15527     case ENUMERAL_TYPE:
15528       return tsubst_aggr_type (t, args, complain, in_decl,
15529 			       /*entering_scope=*/0);
15530 
15531     case ERROR_MARK:
15532     case IDENTIFIER_NODE:
15533     case VOID_TYPE:
15534     case OPAQUE_TYPE:
15535     case REAL_TYPE:
15536     case COMPLEX_TYPE:
15537     case VECTOR_TYPE:
15538     case BOOLEAN_TYPE:
15539     case NULLPTR_TYPE:
15540     case LANG_TYPE:
15541       return t;
15542 
15543     case INTEGER_TYPE:
15544       if (t == integer_type_node)
15545 	return t;
15546 
15547       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
15548           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
15549         return t;
15550 
15551       {
15552 	tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
15553 
15554 	max = tsubst_expr (omax, args, complain, in_decl,
15555 			   /*integral_constant_expression_p=*/false);
15556 
15557 	/* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
15558 	   needed.  */
15559 	if (TREE_CODE (max) == NOP_EXPR
15560 	    && TREE_SIDE_EFFECTS (omax)
15561 	    && !TREE_TYPE (max))
15562 	  TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
15563 
15564 	/* If we're in a partial instantiation, preserve the magic NOP_EXPR
15565 	   with TREE_SIDE_EFFECTS that indicates this is not an integral
15566 	   constant expression.  */
15567 	if (processing_template_decl
15568 	    && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
15569 	  {
15570 	    gcc_assert (TREE_CODE (max) == NOP_EXPR);
15571 	    TREE_SIDE_EFFECTS (max) = 1;
15572 	  }
15573 
15574 	return compute_array_index_type (NULL_TREE, max, complain);
15575       }
15576 
15577     case TEMPLATE_TYPE_PARM:
15578     case TEMPLATE_TEMPLATE_PARM:
15579     case BOUND_TEMPLATE_TEMPLATE_PARM:
15580     case TEMPLATE_PARM_INDEX:
15581       {
15582 	int idx;
15583 	int level;
15584 	int levels;
15585 	tree arg = NULL_TREE;
15586 
15587 	r = NULL_TREE;
15588 
15589 	gcc_assert (TREE_VEC_LENGTH (args) > 0);
15590 	template_parm_level_and_index (t, &level, &idx);
15591 
15592 	levels = TMPL_ARGS_DEPTH (args);
15593 	if (level <= levels
15594 	    && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
15595 	  {
15596 	    arg = TMPL_ARG (args, level, idx);
15597 
15598 	    /* See through ARGUMENT_PACK_SELECT arguments. */
15599 	    if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
15600 	      arg = argument_pack_select_arg (arg);
15601 	  }
15602 
15603 	if (arg == error_mark_node)
15604 	  return error_mark_node;
15605 	else if (arg != NULL_TREE)
15606 	  {
15607 	    if (ARGUMENT_PACK_P (arg))
15608 	      /* If ARG is an argument pack, we don't actually want to
15609 		 perform a substitution here, because substitutions
15610 		 for argument packs are only done
15611 		 element-by-element. We can get to this point when
15612 		 substituting the type of a non-type template
15613 		 parameter pack, when that type actually contains
15614 		 template parameter packs from an outer template, e.g.,
15615 
15616 	         template<typename... Types> struct A {
15617 		   template<Types... Values> struct B { };
15618                  };  */
15619 	      return t;
15620 
15621 	    if (code == TEMPLATE_TYPE_PARM)
15622 	      {
15623 		int quals;
15624 
15625 		/* When building concept checks for the purpose of
15626 		   deducing placeholders, we can end up with wildcards
15627 		   where types are expected. Adjust this to the deduced
15628 		   value.  */
15629 		if (TREE_CODE (arg) == WILDCARD_DECL)
15630 		  arg = TREE_TYPE (TREE_TYPE (arg));
15631 
15632 		gcc_assert (TYPE_P (arg));
15633 
15634 		quals = cp_type_quals (arg) | cp_type_quals (t);
15635 
15636 		return cp_build_qualified_type_real
15637 		  (arg, quals, complain | tf_ignore_bad_quals);
15638 	      }
15639 	    else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
15640 	      {
15641 		/* We are processing a type constructed from a
15642 		   template template parameter.  */
15643 		tree argvec = tsubst (TYPE_TI_ARGS (t),
15644 				      args, complain, in_decl);
15645 		if (argvec == error_mark_node)
15646 		  return error_mark_node;
15647 
15648 		gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
15649 			    || TREE_CODE (arg) == TEMPLATE_DECL
15650 			    || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
15651 
15652 		if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
15653 		  /* Consider this code:
15654 
15655 			template <template <class> class Template>
15656 			struct Internal {
15657 			template <class Arg> using Bind = Template<Arg>;
15658 			};
15659 
15660 			template <template <class> class Template, class Arg>
15661 			using Instantiate = Template<Arg>; //#0
15662 
15663 			template <template <class> class Template,
15664                                   class Argument>
15665 			using Bind =
15666 			  Instantiate<Internal<Template>::template Bind,
15667 				      Argument>; //#1
15668 
15669 		     When #1 is parsed, the
15670 		     BOUND_TEMPLATE_TEMPLATE_PARM representing the
15671 		     parameter `Template' in #0 matches the
15672 		     UNBOUND_CLASS_TEMPLATE representing the argument
15673 		     `Internal<Template>::template Bind'; We then want
15674 		     to assemble the type `Bind<Argument>' that can't
15675 		     be fully created right now, because
15676 		     `Internal<Template>' not being complete, the Bind
15677 		     template cannot be looked up in that context.  So
15678 		     we need to "store" `Bind<Argument>' for later
15679 		     when the context of Bind becomes complete.  Let's
15680 		     store that in a TYPENAME_TYPE.  */
15681 		  return make_typename_type (TYPE_CONTEXT (arg),
15682 					     build_nt (TEMPLATE_ID_EXPR,
15683 						       TYPE_IDENTIFIER (arg),
15684 						       argvec),
15685 					     typename_type,
15686 					     complain);
15687 
15688 		/* We can get a TEMPLATE_TEMPLATE_PARM here when we
15689 		   are resolving nested-types in the signature of a
15690 		   member function templates.  Otherwise ARG is a
15691 		   TEMPLATE_DECL and is the real template to be
15692 		   instantiated.  */
15693 		if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
15694 		  arg = TYPE_NAME (arg);
15695 
15696 		r = lookup_template_class (arg,
15697 					   argvec, in_decl,
15698 					   DECL_CONTEXT (arg),
15699 					    /*entering_scope=*/0,
15700 					   complain);
15701 		return cp_build_qualified_type_real
15702 		  (r, cp_type_quals (t) | cp_type_quals (r), complain);
15703 	      }
15704 	    else if (code == TEMPLATE_TEMPLATE_PARM)
15705 	      return arg;
15706 	    else
15707 	      /* TEMPLATE_PARM_INDEX.  */
15708 	      return convert_from_reference (unshare_expr (arg));
15709 	  }
15710 
15711 	if (level == 1)
15712 	  /* This can happen during the attempted tsubst'ing in
15713 	     unify.  This means that we don't yet have any information
15714 	     about the template parameter in question.  */
15715 	  return t;
15716 
15717 	/* Early in template argument deduction substitution, we don't
15718 	   want to reduce the level of 'auto', or it will be confused
15719 	   with a normal template parm in subsequent deduction.
15720 	   Similarly, don't reduce the level of template parameters to
15721 	   avoid mismatches when deducing their types.  */
15722 	if (complain & tf_partial)
15723 	  return t;
15724 
15725 	/* If we get here, we must have been looking at a parm for a
15726 	   more deeply nested template.  Make a new version of this
15727 	   template parameter, but with a lower level.  */
15728 	switch (code)
15729 	  {
15730 	  case TEMPLATE_TYPE_PARM:
15731 	  case TEMPLATE_TEMPLATE_PARM:
15732 	  case BOUND_TEMPLATE_TEMPLATE_PARM:
15733 	    if (cp_type_quals (t))
15734 	      {
15735 		r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
15736 		r = cp_build_qualified_type_real
15737 		  (r, cp_type_quals (t),
15738 		   complain | (code == TEMPLATE_TYPE_PARM
15739 			       ? tf_ignore_bad_quals : 0));
15740 	      }
15741 	    else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
15742 		     && PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t)
15743 		     && (r = (TEMPLATE_PARM_DESCENDANTS
15744 			      (TEMPLATE_TYPE_PARM_INDEX (t))))
15745 		     && (r = TREE_TYPE (r))
15746 		     && !PLACEHOLDER_TYPE_CONSTRAINTS_INFO (r))
15747 	      /* Break infinite recursion when substituting the constraints
15748 		 of a constrained placeholder.  */;
15749 	    else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
15750 		     && !PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t)
15751 		     && !CLASS_PLACEHOLDER_TEMPLATE (t)
15752 		     && (arg = TEMPLATE_TYPE_PARM_INDEX (t),
15753 			 r = TEMPLATE_PARM_DESCENDANTS (arg))
15754 		     && (TEMPLATE_PARM_LEVEL (r)
15755 			 == TEMPLATE_PARM_LEVEL (arg) - levels))
15756 		/* Cache the simple case of lowering a type parameter.  */
15757 	      r = TREE_TYPE (r);
15758 	    else
15759 	      {
15760 		r = copy_type (t);
15761 		TEMPLATE_TYPE_PARM_INDEX (r)
15762 		  = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
15763 						r, levels, args, complain);
15764 		TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
15765 		TYPE_MAIN_VARIANT (r) = r;
15766 		TYPE_POINTER_TO (r) = NULL_TREE;
15767 		TYPE_REFERENCE_TO (r) = NULL_TREE;
15768 
15769                 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
15770 		  {
15771 		    /* Propagate constraints on placeholders since they are
15772 		       only instantiated during satisfaction.  */
15773 		    if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t))
15774 		      PLACEHOLDER_TYPE_CONSTRAINTS_INFO (r) = ci;
15775 		    else if (tree pl = CLASS_PLACEHOLDER_TEMPLATE (t))
15776 		      {
15777 			pl = tsubst_copy (pl, args, complain, in_decl);
15778 			if (TREE_CODE (pl) == TEMPLATE_TEMPLATE_PARM)
15779 			  pl = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (pl);
15780 			CLASS_PLACEHOLDER_TEMPLATE (r) = pl;
15781 		      }
15782 		  }
15783 
15784 		if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
15785 		  /* We have reduced the level of the template
15786 		     template parameter, but not the levels of its
15787 		     template parameters, so canonical_type_parameter
15788 		     will not be able to find the canonical template
15789 		     template parameter for this level. Thus, we
15790 		     require structural equality checking to compare
15791 		     TEMPLATE_TEMPLATE_PARMs. */
15792 		  SET_TYPE_STRUCTURAL_EQUALITY (r);
15793 		else if (TYPE_STRUCTURAL_EQUALITY_P (t))
15794 		  SET_TYPE_STRUCTURAL_EQUALITY (r);
15795 		else
15796 		  TYPE_CANONICAL (r) = canonical_type_parameter (r);
15797 
15798 		if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
15799 		  {
15800 		    tree tinfo = TYPE_TEMPLATE_INFO (t);
15801 		    /* We might need to substitute into the types of non-type
15802 		       template parameters.  */
15803 		    tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
15804 					complain, in_decl);
15805 		    if (tmpl == error_mark_node)
15806 		      return error_mark_node;
15807 		    tree argvec = tsubst (TI_ARGS (tinfo), args,
15808 					  complain, in_decl);
15809 		    if (argvec == error_mark_node)
15810 		      return error_mark_node;
15811 
15812 		    TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
15813 		      = build_template_info (tmpl, argvec);
15814 		  }
15815 	      }
15816 	    break;
15817 
15818 	  case TEMPLATE_PARM_INDEX:
15819 	    /* OK, now substitute the type of the non-type parameter.  We
15820 	       couldn't do it earlier because it might be an auto parameter,
15821 	       and we wouldn't need to if we had an argument.  */
15822 	    type = tsubst (type, args, complain, in_decl);
15823 	    if (type == error_mark_node)
15824 	      return error_mark_node;
15825 	    r = reduce_template_parm_level (t, type, levels, args, complain);
15826 	    break;
15827 
15828 	  default:
15829 	    gcc_unreachable ();
15830 	  }
15831 
15832 	return r;
15833       }
15834 
15835     case TREE_LIST:
15836       return tsubst_tree_list (t, args, complain, in_decl);
15837 
15838     case TREE_BINFO:
15839       /* We should never be tsubsting a binfo.  */
15840       gcc_unreachable ();
15841 
15842     case TREE_VEC:
15843       /* A vector of template arguments.  */
15844       gcc_assert (!type);
15845       return tsubst_template_args (t, args, complain, in_decl);
15846 
15847     case POINTER_TYPE:
15848     case REFERENCE_TYPE:
15849       {
15850 	if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
15851 	  return t;
15852 
15853 	/* [temp.deduct]
15854 
15855 	   Type deduction may fail for any of the following
15856 	   reasons:
15857 
15858 	   -- Attempting to create a pointer to reference type.
15859 	   -- Attempting to create a reference to a reference type or
15860 	      a reference to void.
15861 
15862 	  Core issue 106 says that creating a reference to a reference
15863 	  during instantiation is no longer a cause for failure. We
15864 	  only enforce this check in strict C++98 mode.  */
15865 	if ((TYPE_REF_P (type)
15866 	     && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
15867 	    || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
15868 	  {
15869 	    static location_t last_loc;
15870 
15871 	    /* We keep track of the last time we issued this error
15872 	       message to avoid spewing a ton of messages during a
15873 	       single bad template instantiation.  */
15874 	    if (complain & tf_error
15875 		&& last_loc != input_location)
15876 	      {
15877 		if (VOID_TYPE_P (type))
15878 		  error ("forming reference to void");
15879                else if (code == POINTER_TYPE)
15880                  error ("forming pointer to reference type %qT", type);
15881                else
15882 		  error ("forming reference to reference type %qT", type);
15883 		last_loc = input_location;
15884 	      }
15885 
15886 	    return error_mark_node;
15887 	  }
15888 	else if (TREE_CODE (type) == FUNCTION_TYPE
15889 		 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
15890 		     || type_memfn_rqual (type) != REF_QUAL_NONE))
15891 	  {
15892 	    if (complain & tf_error)
15893 	      {
15894 		if (code == POINTER_TYPE)
15895 		  error ("forming pointer to qualified function type %qT",
15896 			 type);
15897 		else
15898 		  error ("forming reference to qualified function type %qT",
15899 			 type);
15900 	      }
15901 	    return error_mark_node;
15902 	  }
15903 	else if (code == POINTER_TYPE)
15904 	  {
15905 	    r = build_pointer_type (type);
15906 	    if (TREE_CODE (type) == METHOD_TYPE)
15907 	      r = build_ptrmemfunc_type (r);
15908 	  }
15909 	else if (TYPE_REF_P (type))
15910 	  /* In C++0x, during template argument substitution, when there is an
15911 	     attempt to create a reference to a reference type, reference
15912 	     collapsing is applied as described in [14.3.1/4 temp.arg.type]:
15913 
15914 	     "If a template-argument for a template-parameter T names a type
15915 	     that is a reference to a type A, an attempt to create the type
15916 	     'lvalue reference to cv T' creates the type 'lvalue reference to
15917 	     A,' while an attempt to create the type type rvalue reference to
15918 	     cv T' creates the type T"
15919 	  */
15920 	  r = cp_build_reference_type
15921 	      (TREE_TYPE (type),
15922 	       TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
15923 	else
15924 	  r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
15925 	r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
15926 
15927 	if (r != error_mark_node)
15928 	  /* Will this ever be needed for TYPE_..._TO values?  */
15929 	  layout_type (r);
15930 
15931 	return r;
15932       }
15933     case OFFSET_TYPE:
15934       {
15935 	r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
15936 	if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
15937 	  {
15938 	    /* [temp.deduct]
15939 
15940 	       Type deduction may fail for any of the following
15941 	       reasons:
15942 
15943 	       -- Attempting to create "pointer to member of T" when T
15944 		  is not a class type.  */
15945 	    if (complain & tf_error)
15946 	      error ("creating pointer to member of non-class type %qT", r);
15947 	    return error_mark_node;
15948 	  }
15949 	if (TYPE_REF_P (type))
15950 	  {
15951 	    if (complain & tf_error)
15952 	      error ("creating pointer to member reference type %qT", type);
15953 	    return error_mark_node;
15954 	  }
15955 	if (VOID_TYPE_P (type))
15956 	  {
15957 	    if (complain & tf_error)
15958 	      error ("creating pointer to member of type void");
15959 	    return error_mark_node;
15960 	  }
15961 	gcc_assert (TREE_CODE (type) != METHOD_TYPE);
15962 	if (TREE_CODE (type) == FUNCTION_TYPE)
15963 	  {
15964 	    /* The type of the implicit object parameter gets its
15965 	       cv-qualifiers from the FUNCTION_TYPE. */
15966 	    tree memptr;
15967 	    tree method_type
15968 	      = build_memfn_type (type, r, type_memfn_quals (type),
15969 				  type_memfn_rqual (type));
15970 	    memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
15971 	    return cp_build_qualified_type_real (memptr, cp_type_quals (t),
15972 						 complain);
15973 	  }
15974 	else
15975 	  return cp_build_qualified_type_real (build_ptrmem_type (r, type),
15976 					       cp_type_quals (t),
15977 					       complain);
15978       }
15979     case FUNCTION_TYPE:
15980     case METHOD_TYPE:
15981       {
15982 	tree fntype;
15983 	tree specs;
15984 	fntype = tsubst_function_type (t, args, complain, in_decl);
15985 	if (fntype == error_mark_node)
15986 	  return error_mark_node;
15987 
15988 	/* Substitute the exception specification.  */
15989 	specs = tsubst_exception_specification (t, args, complain, in_decl,
15990 						/*defer_ok*/fndecl_type);
15991 	if (specs == error_mark_node)
15992 	  return error_mark_node;
15993 	if (specs)
15994 	  fntype = build_exception_variant (fntype, specs);
15995 	return fntype;
15996       }
15997     case ARRAY_TYPE:
15998       {
15999 	tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
16000 	if (domain == error_mark_node)
16001 	  return error_mark_node;
16002 
16003 	/* As an optimization, we avoid regenerating the array type if
16004 	   it will obviously be the same as T.  */
16005 	if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
16006 	  return t;
16007 
16008 	/* These checks should match the ones in create_array_type_for_decl.
16009 
16010 	   [temp.deduct]
16011 
16012 	   The deduction may fail for any of the following reasons:
16013 
16014 	   -- Attempting to create an array with an element type that
16015 	      is void, a function type, or a reference type, or [DR337]
16016 	      an abstract class type.  */
16017 	if (VOID_TYPE_P (type)
16018 	    || TREE_CODE (type) == FUNCTION_TYPE
16019 	    || (TREE_CODE (type) == ARRAY_TYPE
16020 		&& TYPE_DOMAIN (type) == NULL_TREE)
16021 	    || TYPE_REF_P (type))
16022 	  {
16023 	    if (complain & tf_error)
16024 	      error ("creating array of %qT", type);
16025 	    return error_mark_node;
16026 	  }
16027 
16028 	if (!verify_type_context (input_location, TCTX_ARRAY_ELEMENT, type,
16029 				  !(complain & tf_error)))
16030 	  return error_mark_node;
16031 
16032 	r = build_cplus_array_type (type, domain);
16033 
16034 	if (!valid_array_size_p (input_location, r, in_decl,
16035 				 (complain & tf_error)))
16036 	  return error_mark_node;
16037 
16038 	if (TYPE_USER_ALIGN (t))
16039 	  {
16040 	    SET_TYPE_ALIGN (r, TYPE_ALIGN (t));
16041 	    TYPE_USER_ALIGN (r) = 1;
16042 	  }
16043 
16044 	return r;
16045       }
16046 
16047     case TYPENAME_TYPE:
16048       {
16049 	tree ctx = TYPE_CONTEXT (t);
16050 	if (TREE_CODE (ctx) == TYPE_PACK_EXPANSION)
16051 	  {
16052 	    ctx = tsubst_pack_expansion (ctx, args, complain, in_decl);
16053 	    if (ctx == error_mark_node
16054 		|| TREE_VEC_LENGTH (ctx) > 1)
16055 	      return error_mark_node;
16056 	    if (TREE_VEC_LENGTH (ctx) == 0)
16057 	      {
16058 		if (complain & tf_error)
16059 		  error ("%qD is instantiated for an empty pack",
16060 			 TYPENAME_TYPE_FULLNAME (t));
16061 		return error_mark_node;
16062 	      }
16063 	    ctx = TREE_VEC_ELT (ctx, 0);
16064 	  }
16065 	else
16066 	  ctx = tsubst_aggr_type (ctx, args, complain, in_decl,
16067 				  /*entering_scope=*/1);
16068 	if (ctx == error_mark_node)
16069 	  return error_mark_node;
16070 
16071 	tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
16072 			      complain, in_decl);
16073 	if (f == error_mark_node)
16074 	  return error_mark_node;
16075 
16076 	if (!MAYBE_CLASS_TYPE_P (ctx))
16077 	  {
16078 	    if (complain & tf_error)
16079 	      error ("%qT is not a class, struct, or union type", ctx);
16080 	    return error_mark_node;
16081 	  }
16082 	else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
16083 	  {
16084 	    /* Normally, make_typename_type does not require that the CTX
16085 	       have complete type in order to allow things like:
16086 
16087 		 template <class T> struct S { typename S<T>::X Y; };
16088 
16089 	       But, such constructs have already been resolved by this
16090 	       point, so here CTX really should have complete type, unless
16091 	       it's a partial instantiation.  */
16092 	    if (!complete_type_or_maybe_complain (ctx, NULL_TREE, complain))
16093 	      return error_mark_node;
16094 	  }
16095 
16096 	f = make_typename_type (ctx, f, typename_type,
16097 				complain | tf_keep_type_decl);
16098 	if (f == error_mark_node)
16099 	  return f;
16100 	if (TREE_CODE (f) == TYPE_DECL)
16101 	  {
16102 	    complain |= tf_ignore_bad_quals;
16103 	    f = TREE_TYPE (f);
16104 	  }
16105 
16106 	if (TREE_CODE (f) != TYPENAME_TYPE)
16107 	  {
16108 	    if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
16109 	      {
16110 		if (complain & tf_error)
16111 		  error ("%qT resolves to %qT, which is not an enumeration type",
16112 			 t, f);
16113 		else
16114 		  return error_mark_node;
16115 	      }
16116 	    else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
16117 	      {
16118 		if (complain & tf_error)
16119 		  error ("%qT resolves to %qT, which is not a class type",
16120 			 t, f);
16121 		else
16122 		  return error_mark_node;
16123 	      }
16124 	  }
16125 
16126 	return cp_build_qualified_type_real
16127 	  (f, cp_type_quals (f) | cp_type_quals (t), complain);
16128       }
16129 
16130     case UNBOUND_CLASS_TEMPLATE:
16131       {
16132 	tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
16133 				     in_decl, /*entering_scope=*/1);
16134 	tree name = TYPE_IDENTIFIER (t);
16135 	tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
16136 
16137 	if (ctx == error_mark_node || name == error_mark_node)
16138 	  return error_mark_node;
16139 
16140 	if (parm_list)
16141 	  parm_list = tsubst_template_parms (parm_list, args, complain);
16142 	return make_unbound_class_template (ctx, name, parm_list, complain);
16143       }
16144 
16145     case TYPEOF_TYPE:
16146       {
16147 	tree type;
16148 
16149 	++cp_unevaluated_operand;
16150 	++c_inhibit_evaluation_warnings;
16151 
16152 	type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
16153 			    complain, in_decl,
16154 			    /*integral_constant_expression_p=*/false);
16155 
16156 	--cp_unevaluated_operand;
16157 	--c_inhibit_evaluation_warnings;
16158 
16159 	type = finish_typeof (type);
16160 	return cp_build_qualified_type_real (type,
16161 					     cp_type_quals (t)
16162 					     | cp_type_quals (type),
16163 					     complain);
16164       }
16165 
16166     case DECLTYPE_TYPE:
16167       {
16168 	tree type;
16169 
16170 	++cp_unevaluated_operand;
16171 	++c_inhibit_evaluation_warnings;
16172 
16173 	type = tsubst_copy_and_build (DECLTYPE_TYPE_EXPR (t), args,
16174 				      complain|tf_decltype, in_decl,
16175 				      /*function_p*/false,
16176 				      /*integral_constant_expression*/false);
16177 
16178 	--cp_unevaluated_operand;
16179 	--c_inhibit_evaluation_warnings;
16180 
16181 	if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
16182 	  type = lambda_capture_field_type (type,
16183 					    false /*explicit_init*/,
16184 					    DECLTYPE_FOR_REF_CAPTURE (t));
16185 	else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
16186 	  type = lambda_proxy_type (type);
16187 	else
16188 	  {
16189 	    bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
16190 	    if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
16191 		&& EXPR_P (type))
16192 	      /* In a template ~id could be either a complement expression
16193 		 or an unqualified-id naming a destructor; if instantiating
16194 		 it produces an expression, it's not an id-expression or
16195 		 member access.  */
16196 	      id = false;
16197 	    type = finish_decltype_type (type, id, complain);
16198 	  }
16199 	return cp_build_qualified_type_real (type,
16200 					     cp_type_quals (t)
16201 					     | cp_type_quals (type),
16202 					     complain | tf_ignore_bad_quals);
16203       }
16204 
16205     case UNDERLYING_TYPE:
16206       {
16207 	tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
16208 			    complain, in_decl);
16209 	return finish_underlying_type (type);
16210       }
16211 
16212     case TYPE_ARGUMENT_PACK:
16213     case NONTYPE_ARGUMENT_PACK:
16214       return tsubst_argument_pack (t, args, complain, in_decl);
16215 
16216     case VOID_CST:
16217     case INTEGER_CST:
16218     case REAL_CST:
16219     case STRING_CST:
16220     case PLUS_EXPR:
16221     case MINUS_EXPR:
16222     case NEGATE_EXPR:
16223     case NOP_EXPR:
16224     case INDIRECT_REF:
16225     case ADDR_EXPR:
16226     case CALL_EXPR:
16227     case ARRAY_REF:
16228     case SCOPE_REF:
16229       /* We should use one of the expression tsubsts for these codes.  */
16230       gcc_unreachable ();
16231 
16232     default:
16233       sorry ("use of %qs in template", get_tree_code_name (code));
16234       return error_mark_node;
16235     }
16236 }
16237 
16238 /* tsubst a BASELINK.  OBJECT_TYPE, if non-NULL, is the type of the
16239    expression on the left-hand side of the "." or "->" operator.  We
16240    only do the lookup if we had a dependent BASELINK.  Otherwise we
16241    adjust it onto the instantiated heirarchy.  */
16242 
16243 static tree
tsubst_baselink(tree baselink,tree object_type,tree args,tsubst_flags_t complain,tree in_decl)16244 tsubst_baselink (tree baselink, tree object_type,
16245 		 tree args, tsubst_flags_t complain, tree in_decl)
16246 {
16247   bool qualified_p = BASELINK_QUALIFIED_P (baselink);
16248   tree qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
16249   qualifying_scope = tsubst (qualifying_scope, args, complain, in_decl);
16250 
16251   tree optype = BASELINK_OPTYPE (baselink);
16252   optype = tsubst (optype, args, complain, in_decl);
16253 
16254   tree template_args = NULL_TREE;
16255   bool template_id_p = false;
16256   tree fns = BASELINK_FUNCTIONS (baselink);
16257   if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
16258     {
16259       template_id_p = true;
16260       template_args = TREE_OPERAND (fns, 1);
16261       fns = TREE_OPERAND (fns, 0);
16262       if (template_args)
16263 	template_args = tsubst_template_args (template_args, args,
16264 					      complain, in_decl);
16265     }
16266 
16267   tree binfo_type = BINFO_TYPE (BASELINK_BINFO (baselink));
16268   binfo_type = tsubst (binfo_type, args, complain, in_decl);
16269   bool dependent_p = binfo_type != BINFO_TYPE (BASELINK_BINFO (baselink));
16270 
16271   if (dependent_p)
16272     {
16273       tree name = OVL_NAME (fns);
16274       if (IDENTIFIER_CONV_OP_P (name))
16275 	name = make_conv_op_name (optype);
16276 
16277       /* See maybe_dependent_member_ref.  */
16278       if (dependent_scope_p (qualifying_scope))
16279 	{
16280 	  if (template_id_p)
16281 	    name = build2 (TEMPLATE_ID_EXPR, unknown_type_node, name,
16282 			   template_args);
16283 	  return build_qualified_name (NULL_TREE, qualifying_scope, name,
16284 				       /* ::template */false);
16285 	}
16286 
16287       if (name == complete_dtor_identifier)
16288 	/* Treat as-if non-dependent below.  */
16289 	dependent_p = false;
16290 
16291       baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1,
16292 				  complain);
16293       if (!baselink)
16294 	{
16295 	  if ((complain & tf_error)
16296 	      && constructor_name_p (name, qualifying_scope))
16297 	    error ("cannot call constructor %<%T::%D%> directly",
16298 		   qualifying_scope, name);
16299 	  return error_mark_node;
16300 	}
16301 
16302       if (BASELINK_P (baselink))
16303 	fns = BASELINK_FUNCTIONS (baselink);
16304     }
16305   else
16306     {
16307       /* We're going to overwrite pieces below, make a duplicate.  */
16308       baselink = copy_node (baselink);
16309 
16310       if (qualifying_scope != BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink)))
16311 	{
16312 	  /* The decl we found was from non-dependent scope, but we still need
16313 	     to update the binfos for the instantiated qualifying_scope.  */
16314 	  BASELINK_ACCESS_BINFO (baselink) = TYPE_BINFO (qualifying_scope);
16315 	  BASELINK_BINFO (baselink) = lookup_base (qualifying_scope, binfo_type,
16316 						   ba_unique, nullptr, complain);
16317 	}
16318     }
16319 
16320   /* If lookup found a single function, mark it as used at this point.
16321      (If lookup found multiple functions the one selected later by
16322      overload resolution will be marked as used at that point.)  */
16323   if (!template_id_p && !really_overloaded_fn (fns))
16324     {
16325       tree fn = OVL_FIRST (fns);
16326       bool ok = mark_used (fn, complain);
16327       if (!ok && !(complain & tf_error))
16328 	return error_mark_node;
16329       if (ok && BASELINK_P (baselink))
16330 	/* We might have instantiated an auto function.  */
16331 	TREE_TYPE (baselink) = TREE_TYPE (fn);
16332     }
16333 
16334   if (BASELINK_P (baselink))
16335     {
16336       /* Add back the template arguments, if present.  */
16337       if (template_id_p)
16338 	BASELINK_FUNCTIONS (baselink)
16339 	  = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, template_args);
16340 
16341       /* Update the conversion operator type.  */
16342       BASELINK_OPTYPE (baselink) = optype;
16343     }
16344 
16345   if (!object_type)
16346     object_type = current_class_type;
16347 
16348   if (qualified_p || !dependent_p)
16349     {
16350       baselink = adjust_result_of_qualified_name_lookup (baselink,
16351 							 qualifying_scope,
16352 							 object_type);
16353       if (!qualified_p)
16354 	/* We need to call adjust_result_of_qualified_name_lookup in case the
16355 	   destructor names a base class, but we unset BASELINK_QUALIFIED_P
16356 	   so that we still get virtual function binding.  */
16357 	BASELINK_QUALIFIED_P (baselink) = false;
16358     }
16359 
16360   return baselink;
16361 }
16362 
16363 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
16364    true if the qualified-id will be a postfix-expression in-and-of
16365    itself; false if more of the postfix-expression follows the
16366    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
16367    of "&".  */
16368 
16369 static tree
tsubst_qualified_id(tree qualified_id,tree args,tsubst_flags_t complain,tree in_decl,bool done,bool address_p)16370 tsubst_qualified_id (tree qualified_id, tree args,
16371 		     tsubst_flags_t complain, tree in_decl,
16372 		     bool done, bool address_p)
16373 {
16374   tree expr;
16375   tree scope;
16376   tree name;
16377   bool is_template;
16378   tree template_args;
16379   location_t loc = EXPR_LOCATION (qualified_id);
16380 
16381   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
16382 
16383   /* Figure out what name to look up.  */
16384   name = TREE_OPERAND (qualified_id, 1);
16385   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
16386     {
16387       is_template = true;
16388       template_args = TREE_OPERAND (name, 1);
16389       if (template_args)
16390 	template_args = tsubst_template_args (template_args, args,
16391 					      complain, in_decl);
16392       if (template_args == error_mark_node)
16393 	return error_mark_node;
16394       name = TREE_OPERAND (name, 0);
16395     }
16396   else
16397     {
16398       is_template = false;
16399       template_args = NULL_TREE;
16400     }
16401 
16402   /* Substitute into the qualifying scope.  When there are no ARGS, we
16403      are just trying to simplify a non-dependent expression.  In that
16404      case the qualifying scope may be dependent, and, in any case,
16405      substituting will not help.  */
16406   scope = TREE_OPERAND (qualified_id, 0);
16407   if (args)
16408     {
16409       scope = tsubst (scope, args, complain, in_decl);
16410       expr = tsubst_copy (name, args, complain, in_decl);
16411     }
16412   else
16413     expr = name;
16414 
16415   if (dependent_scope_p (scope))
16416     {
16417       if (is_template)
16418 	expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr, template_args);
16419       tree r = build_qualified_name (NULL_TREE, scope, expr,
16420 				     QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
16421       REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (qualified_id);
16422       return r;
16423     }
16424 
16425   if (!BASELINK_P (name) && !DECL_P (expr))
16426     {
16427       if (TREE_CODE (expr) == BIT_NOT_EXPR)
16428 	{
16429 	  /* A BIT_NOT_EXPR is used to represent a destructor.  */
16430 	  if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
16431 	    {
16432 	      error ("qualifying type %qT does not match destructor name ~%qT",
16433 		     scope, TREE_OPERAND (expr, 0));
16434 	      expr = error_mark_node;
16435 	    }
16436 	  else
16437 	    expr = lookup_qualified_name (scope, complete_dtor_identifier,
16438 					  LOOK_want::NORMAL, false);
16439 	}
16440       else
16441 	expr = lookup_qualified_name (scope, expr, LOOK_want::NORMAL, false);
16442       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
16443 		     ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
16444 	{
16445 	  if (complain & tf_error)
16446 	    {
16447 	      error ("dependent-name %qE is parsed as a non-type, but "
16448 		     "instantiation yields a type", qualified_id);
16449 	      inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
16450 	    }
16451 	  return error_mark_node;
16452 	}
16453     }
16454 
16455   if (DECL_P (expr))
16456     {
16457       if (!check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
16458 						scope, complain))
16459 	return error_mark_node;
16460       /* Remember that there was a reference to this entity.  */
16461       if (!mark_used (expr, complain) && !(complain & tf_error))
16462 	return error_mark_node;
16463     }
16464 
16465   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
16466     {
16467       if (complain & tf_error)
16468 	qualified_name_lookup_error (scope,
16469 				     TREE_OPERAND (qualified_id, 1),
16470 				     expr, input_location);
16471       return error_mark_node;
16472     }
16473 
16474   if (is_template)
16475     {
16476       /* We may be repeating a check already done during parsing, but
16477 	 if it was well-formed and passed then, it will pass again
16478 	 now, and if it didn't, we wouldn't have got here.  The case
16479 	 we want to catch is when we couldn't tell then, and can now,
16480 	 namely when templ prior to substitution was an
16481 	 identifier.  */
16482       if (flag_concepts && check_auto_in_tmpl_args (expr, template_args))
16483 	return error_mark_node;
16484 
16485       if (variable_template_p (expr))
16486 	expr = lookup_and_finish_template_variable (expr, template_args,
16487 						    complain);
16488       else
16489 	expr = lookup_template_function (expr, template_args);
16490     }
16491 
16492   if (expr == error_mark_node && complain & tf_error)
16493     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
16494 				 expr, input_location);
16495   else if (TYPE_P (scope))
16496     {
16497       expr = (adjust_result_of_qualified_name_lookup
16498 	      (expr, scope, current_nonlambda_class_type ()));
16499       expr = (finish_qualified_id_expr
16500 	      (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
16501 	       QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
16502 	       /*template_arg_p=*/false, complain));
16503     }
16504 
16505   /* Expressions do not generally have reference type.  */
16506   if (TREE_CODE (expr) != SCOPE_REF
16507       /* However, if we're about to form a pointer-to-member, we just
16508 	 want the referenced member referenced.  */
16509       && TREE_CODE (expr) != OFFSET_REF)
16510     expr = convert_from_reference (expr);
16511 
16512   if (REF_PARENTHESIZED_P (qualified_id))
16513     expr = force_paren_expr (expr);
16514 
16515   expr = maybe_wrap_with_location (expr, loc);
16516 
16517   return expr;
16518 }
16519 
16520 /* tsubst the initializer for a VAR_DECL.  INIT is the unsubstituted
16521    initializer, DECL is the substituted VAR_DECL.  Other arguments are as
16522    for tsubst.  */
16523 
16524 static tree
tsubst_init(tree init,tree decl,tree args,tsubst_flags_t complain,tree in_decl)16525 tsubst_init (tree init, tree decl, tree args,
16526 	     tsubst_flags_t complain, tree in_decl)
16527 {
16528   if (!init)
16529     return NULL_TREE;
16530 
16531   init = tsubst_expr (init, args, complain, in_decl, false);
16532 
16533   tree type = TREE_TYPE (decl);
16534 
16535   if (!init && type != error_mark_node)
16536     {
16537       if (tree auto_node = type_uses_auto (type))
16538 	{
16539 	  if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
16540 	    {
16541 	      if (complain & tf_error)
16542 		error ("initializer for %q#D expands to an empty list "
16543 		       "of expressions", decl);
16544 	      return error_mark_node;
16545 	    }
16546 	}
16547       else if (!dependent_type_p (type))
16548 	{
16549 	  /* If we had an initializer but it
16550 	     instantiated to nothing,
16551 	     value-initialize the object.  This will
16552 	     only occur when the initializer was a
16553 	     pack expansion where the parameter packs
16554 	     used in that expansion were of length
16555 	     zero.  */
16556 	  init = build_value_init (type, complain);
16557 	  if (TREE_CODE (init) == AGGR_INIT_EXPR)
16558 	    init = get_target_expr_sfinae (init, complain);
16559 	  if (TREE_CODE (init) == TARGET_EXPR)
16560 	    TARGET_EXPR_DIRECT_INIT_P (init) = true;
16561 	}
16562     }
16563 
16564   return init;
16565 }
16566 
16567 /* If T is a reference to a dependent member of the current instantiation C and
16568    we are trying to refer to that member in a partial instantiation of C,
16569    return a SCOPE_REF; otherwise, return NULL_TREE.
16570 
16571    This can happen when forming a C++17 deduction guide, as in PR96199.  */
16572 
16573 static tree
maybe_dependent_member_ref(tree t,tree args,tsubst_flags_t complain,tree in_decl)16574 maybe_dependent_member_ref (tree t, tree args, tsubst_flags_t complain,
16575 			    tree in_decl)
16576 {
16577   if (cxx_dialect < cxx17)
16578     return NULL_TREE;
16579 
16580   tree ctx = context_for_name_lookup (t);
16581   if (!CLASS_TYPE_P (ctx))
16582     return NULL_TREE;
16583 
16584   ctx = tsubst (ctx, args, complain, in_decl);
16585   if (dependent_scope_p (ctx))
16586     return build_qualified_name (NULL_TREE, ctx, DECL_NAME (t),
16587 				 /*template_p=*/false);
16588 
16589   return NULL_TREE;
16590 }
16591 
16592 /* Like tsubst, but deals with expressions.  This function just replaces
16593    template parms; to finish processing the resultant expression, use
16594    tsubst_copy_and_build or tsubst_expr.  */
16595 
16596 static tree
tsubst_copy(tree t,tree args,tsubst_flags_t complain,tree in_decl)16597 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
16598 {
16599   enum tree_code code;
16600   tree r;
16601 
16602   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
16603     return t;
16604 
16605   code = TREE_CODE (t);
16606 
16607   switch (code)
16608     {
16609     case PARM_DECL:
16610       r = retrieve_local_specialization (t);
16611 
16612       if (r == NULL_TREE)
16613 	{
16614 	  /* We get here for a use of 'this' in an NSDMI.  */
16615 	  if (DECL_NAME (t) == this_identifier && current_class_ptr)
16616 	    return current_class_ptr;
16617 
16618 	  /* This can happen for a parameter name used later in a function
16619 	     declaration (such as in a late-specified return type).  Just
16620 	     make a dummy decl, since it's only used for its type.  */
16621 	  gcc_assert (cp_unevaluated_operand != 0);
16622 	  r = tsubst_decl (t, args, complain);
16623 	  /* Give it the template pattern as its context; its true context
16624 	     hasn't been instantiated yet and this is good enough for
16625 	     mangling.  */
16626 	  DECL_CONTEXT (r) = DECL_CONTEXT (t);
16627 	}
16628 
16629       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
16630 	r = argument_pack_select_arg (r);
16631       if (!mark_used (r, complain) && !(complain & tf_error))
16632 	return error_mark_node;
16633       return r;
16634 
16635     case CONST_DECL:
16636       {
16637 	tree enum_type;
16638 	tree v;
16639 
16640 	if (DECL_TEMPLATE_PARM_P (t))
16641 	  return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
16642 	/* There is no need to substitute into namespace-scope
16643 	   enumerators.  */
16644 	if (DECL_NAMESPACE_SCOPE_P (t))
16645 	  return t;
16646 	/* If ARGS is NULL, then T is known to be non-dependent.  */
16647 	if (args == NULL_TREE)
16648 	  return scalar_constant_value (t);
16649 
16650 	if (tree ref = maybe_dependent_member_ref (t, args, complain, in_decl))
16651 	  return ref;
16652 
16653 	/* Unfortunately, we cannot just call lookup_name here.
16654 	   Consider:
16655 
16656 	     template <int I> int f() {
16657 	     enum E { a = I };
16658 	     struct S { void g() { E e = a; } };
16659 	     };
16660 
16661 	   When we instantiate f<7>::S::g(), say, lookup_name is not
16662 	   clever enough to find f<7>::a.  */
16663 	enum_type
16664 	  = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
16665 			      /*entering_scope=*/0);
16666 
16667 	for (v = TYPE_VALUES (enum_type);
16668 	     v != NULL_TREE;
16669 	     v = TREE_CHAIN (v))
16670 	  if (TREE_PURPOSE (v) == DECL_NAME (t))
16671 	    return TREE_VALUE (v);
16672 
16673 	  /* We didn't find the name.  That should never happen; if
16674 	     name-lookup found it during preliminary parsing, we
16675 	     should find it again here during instantiation.  */
16676 	gcc_unreachable ();
16677       }
16678       return t;
16679 
16680     case FIELD_DECL:
16681       if (DECL_CONTEXT (t))
16682 	{
16683 	  tree ctx;
16684 
16685 	  ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
16686 				  /*entering_scope=*/1);
16687 	  if (ctx != DECL_CONTEXT (t))
16688 	    {
16689 	      tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
16690 	      if (!r)
16691 		{
16692 		  if (complain & tf_error)
16693 		    error ("using invalid field %qD", t);
16694 		  return error_mark_node;
16695 		}
16696 	      return r;
16697 	    }
16698 	}
16699 
16700       return t;
16701 
16702     case VAR_DECL:
16703       if (tree ref = maybe_dependent_member_ref (t, args, complain, in_decl))
16704 	return ref;
16705       gcc_fallthrough();
16706     case FUNCTION_DECL:
16707       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
16708 	r = tsubst (t, args, complain, in_decl);
16709       else if (DECL_LOCAL_DECL_P (t))
16710 	{
16711 	  /* Local specialization will usually have been created when
16712 	     we instantiated the DECL_EXPR_DECL. */
16713 	  r = retrieve_local_specialization (t);
16714 	  if (!r)
16715 	    {
16716 	      /* We're in a generic lambda referencing a local extern
16717 		 from an outer block-scope of a non-template.  */
16718 	      gcc_checking_assert (LAMBDA_FUNCTION_P (current_function_decl));
16719 	      r = t;
16720 	    }
16721 	}
16722       else if (local_variable_p (t)
16723 	       && uses_template_parms (DECL_CONTEXT (t)))
16724 	{
16725 	  r = retrieve_local_specialization (t);
16726 	  if (r == NULL_TREE)
16727 	    {
16728 	      /* First try name lookup to find the instantiation.  */
16729 	      r = lookup_name (DECL_NAME (t));
16730 	      if (r)
16731 		{
16732 		  if (!VAR_P (r))
16733 		    {
16734 		      /* During error-recovery we may find a non-variable,
16735 			 even an OVERLOAD: just bail out and avoid ICEs and
16736 			 duplicate diagnostics (c++/62207).  */
16737 		      gcc_assert (seen_error ());
16738 		      return error_mark_node;
16739 		    }
16740 		  if (!is_capture_proxy (r))
16741 		    {
16742 		      /* Make sure the one we found is the one we want.  */
16743 		      tree ctx = enclosing_instantiation_of (DECL_CONTEXT (t));
16744 		      if (ctx != DECL_CONTEXT (r))
16745 			r = NULL_TREE;
16746 		    }
16747 		}
16748 
16749 	      if (r)
16750 		/* OK */;
16751 	      else
16752 		{
16753 		  /* This can happen for a variable used in a
16754 		     late-specified return type of a local lambda, or for a
16755 		     local static or constant.  Building a new VAR_DECL
16756 		     should be OK in all those cases.  */
16757 		  r = tsubst_decl (t, args, complain);
16758 		  if (local_specializations)
16759 		    /* Avoid infinite recursion (79640).  */
16760 		    register_local_specialization (r, t);
16761 		  if (decl_maybe_constant_var_p (r))
16762 		    {
16763 		      /* We can't call cp_finish_decl, so handle the
16764 			 initializer by hand.  */
16765 		      tree init = tsubst_init (DECL_INITIAL (t), r, args,
16766 					       complain, in_decl);
16767 		      if (!processing_template_decl)
16768 			init = maybe_constant_init (init);
16769 		      if (processing_template_decl
16770 			  ? potential_constant_expression (init)
16771 			  : reduced_constant_expression_p (init))
16772 			DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
16773 			  = TREE_CONSTANT (r) = true;
16774 		      DECL_INITIAL (r) = init;
16775 		      if (tree auto_node = type_uses_auto (TREE_TYPE (r)))
16776 			TREE_TYPE (r)
16777 			  = do_auto_deduction (TREE_TYPE (r), init, auto_node,
16778 					       complain, adc_variable_type);
16779 		    }
16780 		  gcc_assert (cp_unevaluated_operand || TREE_STATIC (r)
16781 			      || decl_constant_var_p (r)
16782 			      || seen_error ());
16783 		  if (!processing_template_decl
16784 		      && !TREE_STATIC (r))
16785 		    r = process_outer_var_ref (r, complain);
16786 		}
16787 	      /* Remember this for subsequent uses.  */
16788 	      if (local_specializations)
16789 		register_local_specialization (r, t);
16790 	    }
16791 	  if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
16792 	    r = argument_pack_select_arg (r);
16793 	}
16794       else
16795 	r = t;
16796       if (!mark_used (r, complain))
16797 	return error_mark_node;
16798       return r;
16799 
16800     case NAMESPACE_DECL:
16801       return t;
16802 
16803     case OVERLOAD:
16804       return t;
16805 
16806     case BASELINK:
16807       return tsubst_baselink (t, current_nonlambda_class_type (),
16808 			      args, complain, in_decl);
16809 
16810     case TEMPLATE_DECL:
16811       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
16812 	return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
16813 		       args, complain, in_decl);
16814       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
16815 	return tsubst (t, args, complain, in_decl);
16816       else if (DECL_CLASS_SCOPE_P (t)
16817 	       && uses_template_parms (DECL_CONTEXT (t)))
16818 	{
16819 	  /* Template template argument like the following example need
16820 	     special treatment:
16821 
16822 	       template <template <class> class TT> struct C {};
16823 	       template <class T> struct D {
16824 		 template <class U> struct E {};
16825 		 C<E> c;				// #1
16826 	       };
16827 	       D<int> d;				// #2
16828 
16829 	     We are processing the template argument `E' in #1 for
16830 	     the template instantiation #2.  Originally, `E' is a
16831 	     TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
16832 	     have to substitute this with one having context `D<int>'.  */
16833 
16834 	  tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
16835 	  if (dependent_scope_p (context))
16836 	    {
16837 	      /* When rewriting a constructor into a deduction guide, a
16838 		 non-dependent name can become dependent, so memtmpl<args>
16839 		 becomes context::template memtmpl<args>.  */
16840 	      tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16841 	      return build_qualified_name (type, context, DECL_NAME (t),
16842 					   /*template*/true);
16843 	    }
16844 	  return lookup_field (context, DECL_NAME(t), 0, false);
16845 	}
16846       else
16847 	/* Ordinary template template argument.  */
16848 	return t;
16849 
16850     case NON_LVALUE_EXPR:
16851     case VIEW_CONVERT_EXPR:
16852 	{
16853 	  /* Handle location wrappers by substituting the wrapped node
16854 	     first, *then* reusing the resulting type.  Doing the type
16855 	     first ensures that we handle template parameters and
16856 	     parameter pack expansions.  */
16857 	  if (location_wrapper_p (t))
16858 	    {
16859 	      tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args,
16860 				      complain, in_decl);
16861 	      return maybe_wrap_with_location (op0, EXPR_LOCATION (t));
16862 	    }
16863 	  tree op = TREE_OPERAND (t, 0);
16864 	  if (code == VIEW_CONVERT_EXPR
16865 	      && TREE_CODE (op) == TEMPLATE_PARM_INDEX)
16866 	    {
16867 	      /* Wrapper to make a C++20 template parameter object const.  */
16868 	      op = tsubst_copy (op, args, complain, in_decl);
16869 	      if (!CP_TYPE_CONST_P (TREE_TYPE (op)))
16870 		{
16871 		  /* The template argument is not const, presumably because
16872 		     it is still dependent, and so not the const template parm
16873 		     object.  */
16874 		  tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16875 		  gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
16876 				       (type, TREE_TYPE (op)));
16877 		  if (TREE_CODE (op) == CONSTRUCTOR
16878 		      || TREE_CODE (op) == IMPLICIT_CONV_EXPR)
16879 		    {
16880 		      /* Don't add a wrapper to these.  */
16881 		      op = copy_node (op);
16882 		      TREE_TYPE (op) = type;
16883 		    }
16884 		  else
16885 		    /* Do add a wrapper otherwise (in particular, if op is
16886 		       another TEMPLATE_PARM_INDEX).  */
16887 		    op = build1 (code, type, op);
16888 		}
16889 	      return op;
16890 	    }
16891 	  /* force_paren_expr can also create a VIEW_CONVERT_EXPR.  */
16892 	  else if (code == VIEW_CONVERT_EXPR && REF_PARENTHESIZED_P (t))
16893 	    {
16894 	      op = tsubst_copy (op, args, complain, in_decl);
16895 	      op = build1 (code, TREE_TYPE (op), op);
16896 	      REF_PARENTHESIZED_P (op) = true;
16897 	      return op;
16898 	    }
16899 	  /* We shouldn't see any other uses of these in templates.  */
16900 	  gcc_unreachable ();
16901 	}
16902 
16903     case CAST_EXPR:
16904     case REINTERPRET_CAST_EXPR:
16905     case CONST_CAST_EXPR:
16906     case STATIC_CAST_EXPR:
16907     case DYNAMIC_CAST_EXPR:
16908     case IMPLICIT_CONV_EXPR:
16909     case CONVERT_EXPR:
16910     case NOP_EXPR:
16911       {
16912 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16913 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16914 	return build1 (code, type, op0);
16915       }
16916 
16917     case BIT_CAST_EXPR:
16918       {
16919 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16920 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16921 	r = build_min (BIT_CAST_EXPR, type, op0);
16922 	SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
16923 	return r;
16924       }
16925 
16926     case SIZEOF_EXPR:
16927       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
16928 	  || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
16929         {
16930           tree expanded, op = TREE_OPERAND (t, 0);
16931 	  int len = 0;
16932 
16933 	  if (SIZEOF_EXPR_TYPE_P (t))
16934 	    op = TREE_TYPE (op);
16935 
16936 	  ++cp_unevaluated_operand;
16937 	  ++c_inhibit_evaluation_warnings;
16938 	  /* We only want to compute the number of arguments.  */
16939 	  if (PACK_EXPANSION_P (op))
16940 	    expanded = tsubst_pack_expansion (op, args, complain, in_decl);
16941 	  else
16942 	    expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
16943 					     args, complain, in_decl);
16944 	  --cp_unevaluated_operand;
16945 	  --c_inhibit_evaluation_warnings;
16946 
16947 	  if (TREE_CODE (expanded) == TREE_VEC)
16948 	    {
16949 	      len = TREE_VEC_LENGTH (expanded);
16950 	      /* Set TREE_USED for the benefit of -Wunused.  */
16951 	      for (int i = 0; i < len; i++)
16952 		if (DECL_P (TREE_VEC_ELT (expanded, i)))
16953 		  TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
16954 	    }
16955 
16956 	  if (expanded == error_mark_node)
16957 	    return error_mark_node;
16958 	  else if (PACK_EXPANSION_P (expanded)
16959 		   || (TREE_CODE (expanded) == TREE_VEC
16960 		       && pack_expansion_args_count (expanded)))
16961 
16962 	    {
16963 	      if (PACK_EXPANSION_P (expanded))
16964 		/* OK.  */;
16965 	      else if (TREE_VEC_LENGTH (expanded) == 1)
16966 		expanded = TREE_VEC_ELT (expanded, 0);
16967 	      else
16968 		expanded = make_argument_pack (expanded);
16969 
16970 	      if (TYPE_P (expanded))
16971 		return cxx_sizeof_or_alignof_type (input_location,
16972 						   expanded, SIZEOF_EXPR,
16973 						   false,
16974 						   complain & tf_error);
16975 	      else
16976 		return cxx_sizeof_or_alignof_expr (input_location,
16977 						   expanded, SIZEOF_EXPR,
16978 						   false,
16979                                                    complain & tf_error);
16980 	    }
16981 	  else
16982 	    return build_int_cst (size_type_node, len);
16983         }
16984       if (SIZEOF_EXPR_TYPE_P (t))
16985 	{
16986 	  r = tsubst (TREE_TYPE (TREE_OPERAND (t, 0)),
16987 		      args, complain, in_decl);
16988 	  r = build1 (NOP_EXPR, r, error_mark_node);
16989 	  r = build1 (SIZEOF_EXPR,
16990 		      tsubst (TREE_TYPE (t), args, complain, in_decl), r);
16991 	  SIZEOF_EXPR_TYPE_P (r) = 1;
16992 	  return r;
16993 	}
16994       /* Fall through */
16995 
16996     case INDIRECT_REF:
16997     case NEGATE_EXPR:
16998     case TRUTH_NOT_EXPR:
16999     case BIT_NOT_EXPR:
17000     case ADDR_EXPR:
17001     case UNARY_PLUS_EXPR:      /* Unary + */
17002     case ALIGNOF_EXPR:
17003     case AT_ENCODE_EXPR:
17004     case ARROW_EXPR:
17005     case THROW_EXPR:
17006     case TYPEID_EXPR:
17007     case REALPART_EXPR:
17008     case IMAGPART_EXPR:
17009     case PAREN_EXPR:
17010       {
17011 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17012 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17013 	r = build1 (code, type, op0);
17014 	if (code == ALIGNOF_EXPR)
17015 	  ALIGNOF_EXPR_STD_P (r) = ALIGNOF_EXPR_STD_P (t);
17016 	return r;
17017       }
17018 
17019     case COMPONENT_REF:
17020       {
17021 	tree object;
17022 	tree name;
17023 
17024 	object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17025 	name = TREE_OPERAND (t, 1);
17026 	if (TREE_CODE (name) == BIT_NOT_EXPR)
17027 	  {
17028 	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
17029 				complain, in_decl);
17030 	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
17031 	  }
17032 	else if (TREE_CODE (name) == SCOPE_REF
17033 		 && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
17034 	  {
17035 	    tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
17036 				     complain, in_decl);
17037 	    name = TREE_OPERAND (name, 1);
17038 	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
17039 				complain, in_decl);
17040 	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
17041 	    name = build_qualified_name (/*type=*/NULL_TREE,
17042 					 base, name,
17043 					 /*template_p=*/false);
17044 	  }
17045 	else if (BASELINK_P (name))
17046 	  name = tsubst_baselink (name,
17047 				  non_reference (TREE_TYPE (object)),
17048 				  args, complain,
17049 				  in_decl);
17050 	else
17051 	  name = tsubst_copy (name, args, complain, in_decl);
17052 	return build_nt (COMPONENT_REF, object, name, NULL_TREE);
17053       }
17054 
17055     case PLUS_EXPR:
17056     case MINUS_EXPR:
17057     case MULT_EXPR:
17058     case TRUNC_DIV_EXPR:
17059     case CEIL_DIV_EXPR:
17060     case FLOOR_DIV_EXPR:
17061     case ROUND_DIV_EXPR:
17062     case EXACT_DIV_EXPR:
17063     case BIT_AND_EXPR:
17064     case BIT_IOR_EXPR:
17065     case BIT_XOR_EXPR:
17066     case TRUNC_MOD_EXPR:
17067     case FLOOR_MOD_EXPR:
17068     case TRUTH_ANDIF_EXPR:
17069     case TRUTH_ORIF_EXPR:
17070     case TRUTH_AND_EXPR:
17071     case TRUTH_OR_EXPR:
17072     case RSHIFT_EXPR:
17073     case LSHIFT_EXPR:
17074     case EQ_EXPR:
17075     case NE_EXPR:
17076     case MAX_EXPR:
17077     case MIN_EXPR:
17078     case LE_EXPR:
17079     case GE_EXPR:
17080     case LT_EXPR:
17081     case GT_EXPR:
17082     case COMPOUND_EXPR:
17083     case DOTSTAR_EXPR:
17084     case MEMBER_REF:
17085     case PREDECREMENT_EXPR:
17086     case PREINCREMENT_EXPR:
17087     case POSTDECREMENT_EXPR:
17088     case POSTINCREMENT_EXPR:
17089       {
17090 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17091 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17092 	return build_nt (code, op0, op1);
17093       }
17094 
17095     case SCOPE_REF:
17096       {
17097 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17098 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17099 	return build_qualified_name (/*type=*/NULL_TREE, op0, op1,
17100 				     QUALIFIED_NAME_IS_TEMPLATE (t));
17101       }
17102 
17103     case ARRAY_REF:
17104       {
17105 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17106 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17107 	return build_nt (ARRAY_REF, op0, op1, NULL_TREE, NULL_TREE);
17108       }
17109 
17110     case CALL_EXPR:
17111       {
17112 	int n = VL_EXP_OPERAND_LENGTH (t);
17113 	tree result = build_vl_exp (CALL_EXPR, n);
17114 	int i;
17115 	for (i = 0; i < n; i++)
17116 	  TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
17117 					     complain, in_decl);
17118 	return result;
17119       }
17120 
17121     case COND_EXPR:
17122     case MODOP_EXPR:
17123     case PSEUDO_DTOR_EXPR:
17124     case VEC_PERM_EXPR:
17125       {
17126 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17127 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17128 	tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
17129 	r = build_nt (code, op0, op1, op2);
17130 	TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
17131 	return r;
17132       }
17133 
17134     case NEW_EXPR:
17135       {
17136 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17137 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17138 	tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
17139 	r = build_nt (code, op0, op1, op2);
17140 	NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
17141 	return r;
17142       }
17143 
17144     case DELETE_EXPR:
17145       {
17146 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17147 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17148 	r = build_nt (code, op0, op1);
17149 	DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
17150 	DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
17151 	return r;
17152       }
17153 
17154     case TEMPLATE_ID_EXPR:
17155       {
17156 	/* Substituted template arguments */
17157 	tree tmpl = TREE_OPERAND (t, 0);
17158 	tree targs = TREE_OPERAND (t, 1);
17159 
17160 	tmpl = tsubst_copy (tmpl, args, complain, in_decl);
17161 	if (targs)
17162 	  targs = tsubst_template_args (targs, args, complain, in_decl);
17163 
17164 	if (variable_template_p (tmpl))
17165 	  return lookup_template_variable (tmpl, targs);
17166 	else
17167 	  return lookup_template_function (tmpl, targs);
17168       }
17169 
17170     case TREE_LIST:
17171       {
17172 	tree purpose, value, chain;
17173 
17174 	if (t == void_list_node)
17175 	  return t;
17176 
17177 	purpose = TREE_PURPOSE (t);
17178 	if (purpose)
17179 	  purpose = tsubst_copy (purpose, args, complain, in_decl);
17180 	value = TREE_VALUE (t);
17181 	if (value)
17182 	  value = tsubst_copy (value, args, complain, in_decl);
17183 	chain = TREE_CHAIN (t);
17184 	if (chain && chain != void_type_node)
17185 	  chain = tsubst_copy (chain, args, complain, in_decl);
17186 	if (purpose == TREE_PURPOSE (t)
17187 	    && value == TREE_VALUE (t)
17188 	    && chain == TREE_CHAIN (t))
17189 	  return t;
17190 	return tree_cons (purpose, value, chain);
17191       }
17192 
17193     case RECORD_TYPE:
17194     case UNION_TYPE:
17195     case ENUMERAL_TYPE:
17196     case INTEGER_TYPE:
17197     case TEMPLATE_TYPE_PARM:
17198     case TEMPLATE_TEMPLATE_PARM:
17199     case BOUND_TEMPLATE_TEMPLATE_PARM:
17200     case TEMPLATE_PARM_INDEX:
17201     case POINTER_TYPE:
17202     case REFERENCE_TYPE:
17203     case OFFSET_TYPE:
17204     case FUNCTION_TYPE:
17205     case METHOD_TYPE:
17206     case ARRAY_TYPE:
17207     case TYPENAME_TYPE:
17208     case UNBOUND_CLASS_TEMPLATE:
17209     case TYPEOF_TYPE:
17210     case DECLTYPE_TYPE:
17211     case TYPE_DECL:
17212       return tsubst (t, args, complain, in_decl);
17213 
17214     case USING_DECL:
17215       t = DECL_NAME (t);
17216       /* Fall through.  */
17217     case IDENTIFIER_NODE:
17218       if (IDENTIFIER_CONV_OP_P (t))
17219 	{
17220 	  tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17221 	  return make_conv_op_name (new_type);
17222 	}
17223       else
17224 	return t;
17225 
17226     case CONSTRUCTOR:
17227       /* This is handled by tsubst_copy_and_build.  */
17228       gcc_unreachable ();
17229 
17230     case VA_ARG_EXPR:
17231       {
17232 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17233 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17234 	return build_x_va_arg (EXPR_LOCATION (t), op0, type);
17235       }
17236 
17237     case CLEANUP_POINT_EXPR:
17238       /* We shouldn't have built any of these during initial template
17239 	 generation.  Instead, they should be built during instantiation
17240 	 in response to the saved STMT_IS_FULL_EXPR_P setting.  */
17241       gcc_unreachable ();
17242 
17243     case OFFSET_REF:
17244       {
17245 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17246 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17247 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17248 	r = build2 (code, type, op0, op1);
17249 	PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
17250 	if (!mark_used (TREE_OPERAND (r, 1), complain)
17251 	    && !(complain & tf_error))
17252 	  return error_mark_node;
17253 	return r;
17254       }
17255 
17256     case EXPR_PACK_EXPANSION:
17257       error ("invalid use of pack expansion expression");
17258       return error_mark_node;
17259 
17260     case NONTYPE_ARGUMENT_PACK:
17261       error ("use %<...%> to expand argument pack");
17262       return error_mark_node;
17263 
17264     case VOID_CST:
17265       gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
17266       return t;
17267 
17268     case INTEGER_CST:
17269     case REAL_CST:
17270     case COMPLEX_CST:
17271       {
17272 	/* Instantiate any typedefs in the type.  */
17273 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17274 	r = fold_convert (type, t);
17275 	gcc_assert (TREE_CODE (r) == code);
17276 	return r;
17277       }
17278 
17279     case STRING_CST:
17280       {
17281 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17282 	r = t;
17283 	if (type != TREE_TYPE (t))
17284 	  {
17285 	    r = copy_node (t);
17286 	    TREE_TYPE (r) = type;
17287 	  }
17288 	return r;
17289       }
17290 
17291     case PTRMEM_CST:
17292       /* These can sometimes show up in a partial instantiation, but never
17293 	 involve template parms.  */
17294       gcc_assert (!uses_template_parms (t));
17295       return t;
17296 
17297     case UNARY_LEFT_FOLD_EXPR:
17298       return tsubst_unary_left_fold (t, args, complain, in_decl);
17299     case UNARY_RIGHT_FOLD_EXPR:
17300       return tsubst_unary_right_fold (t, args, complain, in_decl);
17301     case BINARY_LEFT_FOLD_EXPR:
17302       return tsubst_binary_left_fold (t, args, complain, in_decl);
17303     case BINARY_RIGHT_FOLD_EXPR:
17304       return tsubst_binary_right_fold (t, args, complain, in_decl);
17305     case PREDICT_EXPR:
17306       return t;
17307 
17308     case DEBUG_BEGIN_STMT:
17309       /* ??? There's no point in copying it for now, but maybe some
17310 	 day it will contain more information, such as a pointer back
17311 	 to the containing function, inlined copy or so.  */
17312       return t;
17313 
17314     case CO_AWAIT_EXPR:
17315       return tsubst_expr (t, args, complain, in_decl,
17316 			  /*integral_constant_expression_p=*/false);
17317       break;
17318 
17319     default:
17320       /* We shouldn't get here, but keep going if !flag_checking.  */
17321       if (flag_checking)
17322 	gcc_unreachable ();
17323       return t;
17324     }
17325 }
17326 
17327 /* Helper function for tsubst_omp_clauses, used for instantiation of
17328    OMP_CLAUSE_DECL of clauses.  */
17329 
17330 static tree
tsubst_omp_clause_decl(tree decl,tree args,tsubst_flags_t complain,tree in_decl,tree * iterator_cache)17331 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
17332 			tree in_decl, tree *iterator_cache)
17333 {
17334   if (decl == NULL_TREE)
17335     return NULL_TREE;
17336 
17337   /* Handle OpenMP iterators.  */
17338   if (TREE_CODE (decl) == TREE_LIST
17339       && TREE_PURPOSE (decl)
17340       && TREE_CODE (TREE_PURPOSE (decl)) == TREE_VEC)
17341     {
17342       tree ret;
17343       if (iterator_cache[0] == TREE_PURPOSE (decl))
17344 	ret = iterator_cache[1];
17345       else
17346 	{
17347 	  tree *tp = &ret;
17348 	  begin_scope (sk_omp, NULL);
17349 	  for (tree it = TREE_PURPOSE (decl); it; it = TREE_CHAIN (it))
17350 	    {
17351 	      *tp = copy_node (it);
17352 	      TREE_VEC_ELT (*tp, 0)
17353 		= tsubst_decl (TREE_VEC_ELT (it, 0), args, complain);
17354 	      TREE_VEC_ELT (*tp, 1)
17355 		= tsubst_expr (TREE_VEC_ELT (it, 1), args, complain, in_decl,
17356 			       /*integral_constant_expression_p=*/false);
17357 	      TREE_VEC_ELT (*tp, 2)
17358 		= tsubst_expr (TREE_VEC_ELT (it, 2), args, complain, in_decl,
17359 			       /*integral_constant_expression_p=*/false);
17360 	      TREE_VEC_ELT (*tp, 3)
17361 		= tsubst_expr (TREE_VEC_ELT (it, 3), args, complain, in_decl,
17362 			       /*integral_constant_expression_p=*/false);
17363 	      TREE_CHAIN (*tp) = NULL_TREE;
17364 	      tp = &TREE_CHAIN (*tp);
17365 	    }
17366 	  TREE_VEC_ELT (ret, 5) = poplevel (1, 1, 0);
17367 	  iterator_cache[0] = TREE_PURPOSE (decl);
17368 	  iterator_cache[1] = ret;
17369 	}
17370       return build_tree_list (ret, tsubst_omp_clause_decl (TREE_VALUE (decl),
17371 							   args, complain,
17372 							   in_decl, NULL));
17373     }
17374 
17375   /* Handle an OpenMP array section represented as a TREE_LIST (or
17376      OMP_CLAUSE_DEPEND_KIND).  An OMP_CLAUSE_DEPEND (with a depend
17377      kind of OMP_CLAUSE_DEPEND_SINK) can also be represented as a
17378      TREE_LIST.  We can handle it exactly the same as an array section
17379      (purpose, value, and a chain), even though the nomenclature
17380      (low_bound, length, etc) is different.  */
17381   if (TREE_CODE (decl) == TREE_LIST)
17382     {
17383       tree low_bound
17384 	= tsubst_expr (TREE_PURPOSE (decl), args, complain, in_decl,
17385 		       /*integral_constant_expression_p=*/false);
17386       tree length = tsubst_expr (TREE_VALUE (decl), args, complain, in_decl,
17387 				 /*integral_constant_expression_p=*/false);
17388       tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
17389 					   in_decl, NULL);
17390       if (TREE_PURPOSE (decl) == low_bound
17391 	  && TREE_VALUE (decl) == length
17392 	  && TREE_CHAIN (decl) == chain)
17393 	return decl;
17394       tree ret = tree_cons (low_bound, length, chain);
17395       OMP_CLAUSE_DEPEND_SINK_NEGATIVE (ret)
17396 	= OMP_CLAUSE_DEPEND_SINK_NEGATIVE (decl);
17397       return ret;
17398     }
17399   tree ret = tsubst_expr (decl, args, complain, in_decl,
17400 			  /*integral_constant_expression_p=*/false);
17401   /* Undo convert_from_reference tsubst_expr could have called.  */
17402   if (decl
17403       && REFERENCE_REF_P (ret)
17404       && !REFERENCE_REF_P (decl))
17405     ret = TREE_OPERAND (ret, 0);
17406   return ret;
17407 }
17408 
17409 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
17410 
17411 static tree
tsubst_omp_clauses(tree clauses,enum c_omp_region_type ort,tree args,tsubst_flags_t complain,tree in_decl)17412 tsubst_omp_clauses (tree clauses, enum c_omp_region_type ort,
17413 		    tree args, tsubst_flags_t complain, tree in_decl)
17414 {
17415   tree new_clauses = NULL_TREE, nc, oc;
17416   tree linear_no_step = NULL_TREE;
17417   tree iterator_cache[2] = { NULL_TREE, NULL_TREE };
17418 
17419   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
17420     {
17421       nc = copy_node (oc);
17422       OMP_CLAUSE_CHAIN (nc) = new_clauses;
17423       new_clauses = nc;
17424 
17425       switch (OMP_CLAUSE_CODE (nc))
17426 	{
17427 	case OMP_CLAUSE_LASTPRIVATE:
17428 	  if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
17429 	    {
17430 	      OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
17431 	      tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
17432 			   in_decl, /*integral_constant_expression_p=*/false);
17433 	      OMP_CLAUSE_LASTPRIVATE_STMT (nc)
17434 		= pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
17435 	    }
17436 	  /* FALLTHRU */
17437 	case OMP_CLAUSE_PRIVATE:
17438 	case OMP_CLAUSE_SHARED:
17439 	case OMP_CLAUSE_FIRSTPRIVATE:
17440 	case OMP_CLAUSE_COPYIN:
17441 	case OMP_CLAUSE_COPYPRIVATE:
17442 	case OMP_CLAUSE_UNIFORM:
17443 	case OMP_CLAUSE_DEPEND:
17444 	case OMP_CLAUSE_FROM:
17445 	case OMP_CLAUSE_TO:
17446 	case OMP_CLAUSE_MAP:
17447 	case OMP_CLAUSE__CACHE_:
17448 	case OMP_CLAUSE_NONTEMPORAL:
17449 	case OMP_CLAUSE_USE_DEVICE_PTR:
17450 	case OMP_CLAUSE_USE_DEVICE_ADDR:
17451 	case OMP_CLAUSE_IS_DEVICE_PTR:
17452 	case OMP_CLAUSE_INCLUSIVE:
17453 	case OMP_CLAUSE_EXCLUSIVE:
17454 	  OMP_CLAUSE_DECL (nc)
17455 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17456 				      in_decl, iterator_cache);
17457 	  break;
17458 	case OMP_CLAUSE_TILE:
17459 	case OMP_CLAUSE_IF:
17460 	case OMP_CLAUSE_NUM_THREADS:
17461 	case OMP_CLAUSE_SCHEDULE:
17462 	case OMP_CLAUSE_COLLAPSE:
17463 	case OMP_CLAUSE_FINAL:
17464 	case OMP_CLAUSE_DEVICE:
17465 	case OMP_CLAUSE_DIST_SCHEDULE:
17466 	case OMP_CLAUSE_NUM_TEAMS:
17467 	case OMP_CLAUSE_THREAD_LIMIT:
17468 	case OMP_CLAUSE_SAFELEN:
17469 	case OMP_CLAUSE_SIMDLEN:
17470 	case OMP_CLAUSE_NUM_TASKS:
17471 	case OMP_CLAUSE_GRAINSIZE:
17472 	case OMP_CLAUSE_PRIORITY:
17473 	case OMP_CLAUSE_ORDERED:
17474 	case OMP_CLAUSE_HINT:
17475 	case OMP_CLAUSE_NUM_GANGS:
17476 	case OMP_CLAUSE_NUM_WORKERS:
17477 	case OMP_CLAUSE_VECTOR_LENGTH:
17478 	case OMP_CLAUSE_WORKER:
17479 	case OMP_CLAUSE_VECTOR:
17480 	case OMP_CLAUSE_ASYNC:
17481 	case OMP_CLAUSE_WAIT:
17482 	case OMP_CLAUSE_DETACH:
17483 	  OMP_CLAUSE_OPERAND (nc, 0)
17484 	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain,
17485 			   in_decl, /*integral_constant_expression_p=*/false);
17486 	  break;
17487 	case OMP_CLAUSE_REDUCTION:
17488 	case OMP_CLAUSE_IN_REDUCTION:
17489 	case OMP_CLAUSE_TASK_REDUCTION:
17490 	  if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
17491 	    {
17492 	      tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
17493 	      if (TREE_CODE (placeholder) == SCOPE_REF)
17494 		{
17495 		  tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
17496 				       complain, in_decl);
17497 		  OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
17498 		    = build_qualified_name (NULL_TREE, scope,
17499 					    TREE_OPERAND (placeholder, 1),
17500 					    false);
17501 		}
17502 	      else
17503 		gcc_assert (identifier_p (placeholder));
17504 	    }
17505 	  OMP_CLAUSE_DECL (nc)
17506 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17507 				      in_decl, NULL);
17508 	  break;
17509 	case OMP_CLAUSE_GANG:
17510 	case OMP_CLAUSE_ALIGNED:
17511 	case OMP_CLAUSE_ALLOCATE:
17512 	  OMP_CLAUSE_DECL (nc)
17513 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17514 				      in_decl, NULL);
17515 	  OMP_CLAUSE_OPERAND (nc, 1)
17516 	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain,
17517 			   in_decl, /*integral_constant_expression_p=*/false);
17518 	  break;
17519 	case OMP_CLAUSE_LINEAR:
17520 	  OMP_CLAUSE_DECL (nc)
17521 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17522 				      in_decl, NULL);
17523 	  if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
17524 	    {
17525 	      gcc_assert (!linear_no_step);
17526 	      linear_no_step = nc;
17527 	    }
17528 	  else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
17529 	    OMP_CLAUSE_LINEAR_STEP (nc)
17530 	      = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
17531 					complain, in_decl, NULL);
17532 	  else
17533 	    OMP_CLAUSE_LINEAR_STEP (nc)
17534 	      = tsubst_expr (OMP_CLAUSE_LINEAR_STEP (oc), args, complain,
17535 			     in_decl,
17536 			     /*integral_constant_expression_p=*/false);
17537 	  break;
17538 	case OMP_CLAUSE_NOWAIT:
17539 	case OMP_CLAUSE_DEFAULT:
17540 	case OMP_CLAUSE_UNTIED:
17541 	case OMP_CLAUSE_MERGEABLE:
17542 	case OMP_CLAUSE_INBRANCH:
17543 	case OMP_CLAUSE_NOTINBRANCH:
17544 	case OMP_CLAUSE_PROC_BIND:
17545 	case OMP_CLAUSE_FOR:
17546 	case OMP_CLAUSE_PARALLEL:
17547 	case OMP_CLAUSE_SECTIONS:
17548 	case OMP_CLAUSE_TASKGROUP:
17549 	case OMP_CLAUSE_NOGROUP:
17550 	case OMP_CLAUSE_THREADS:
17551 	case OMP_CLAUSE_SIMD:
17552 	case OMP_CLAUSE_DEFAULTMAP:
17553 	case OMP_CLAUSE_ORDER:
17554 	case OMP_CLAUSE_BIND:
17555 	case OMP_CLAUSE_INDEPENDENT:
17556 	case OMP_CLAUSE_AUTO:
17557 	case OMP_CLAUSE_SEQ:
17558 	case OMP_CLAUSE_IF_PRESENT:
17559 	case OMP_CLAUSE_FINALIZE:
17560 	  break;
17561 	default:
17562 	  gcc_unreachable ();
17563 	}
17564       if ((ort & C_ORT_OMP_DECLARE_SIMD) == C_ORT_OMP)
17565 	switch (OMP_CLAUSE_CODE (nc))
17566 	  {
17567 	  case OMP_CLAUSE_SHARED:
17568 	  case OMP_CLAUSE_PRIVATE:
17569 	  case OMP_CLAUSE_FIRSTPRIVATE:
17570 	  case OMP_CLAUSE_LASTPRIVATE:
17571 	  case OMP_CLAUSE_COPYPRIVATE:
17572 	  case OMP_CLAUSE_LINEAR:
17573 	  case OMP_CLAUSE_REDUCTION:
17574 	  case OMP_CLAUSE_IN_REDUCTION:
17575 	  case OMP_CLAUSE_TASK_REDUCTION:
17576 	  case OMP_CLAUSE_USE_DEVICE_PTR:
17577 	  case OMP_CLAUSE_USE_DEVICE_ADDR:
17578 	  case OMP_CLAUSE_IS_DEVICE_PTR:
17579 	  case OMP_CLAUSE_INCLUSIVE:
17580 	  case OMP_CLAUSE_EXCLUSIVE:
17581 	  case OMP_CLAUSE_ALLOCATE:
17582 	    /* tsubst_expr on SCOPE_REF results in returning
17583 	       finish_non_static_data_member result.  Undo that here.  */
17584 	    if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
17585 		&& (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
17586 		    == IDENTIFIER_NODE))
17587 	      {
17588 		tree t = OMP_CLAUSE_DECL (nc);
17589 		tree v = t;
17590 		while (v)
17591 		  switch (TREE_CODE (v))
17592 		    {
17593 		    case COMPONENT_REF:
17594 		    case MEM_REF:
17595 		    case INDIRECT_REF:
17596 		    CASE_CONVERT:
17597 		    case POINTER_PLUS_EXPR:
17598 		      v = TREE_OPERAND (v, 0);
17599 		      continue;
17600 		    case PARM_DECL:
17601 		      if (DECL_CONTEXT (v) == current_function_decl
17602 			  && DECL_ARTIFICIAL (v)
17603 			  && DECL_NAME (v) == this_identifier)
17604 			OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
17605 		      /* FALLTHRU */
17606 		    default:
17607 		      v = NULL_TREE;
17608 		      break;
17609 		    }
17610 	      }
17611 	    else if (VAR_P (OMP_CLAUSE_DECL (oc))
17612 		     && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
17613 		     && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
17614 		     && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
17615 		     && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
17616 	      {
17617 		tree decl = OMP_CLAUSE_DECL (nc);
17618 		if (VAR_P (decl))
17619 		  {
17620 		    retrofit_lang_decl (decl);
17621 		    DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
17622 		  }
17623 	      }
17624 	    break;
17625 	  default:
17626 	    break;
17627 	  }
17628     }
17629 
17630   new_clauses = nreverse (new_clauses);
17631   if (ort != C_ORT_OMP_DECLARE_SIMD)
17632     {
17633       new_clauses = finish_omp_clauses (new_clauses, ort);
17634       if (linear_no_step)
17635 	for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
17636 	  if (nc == linear_no_step)
17637 	    {
17638 	      OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
17639 	      break;
17640 	    }
17641     }
17642   return new_clauses;
17643 }
17644 
17645 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
17646 
17647 static tree
tsubst_copy_asm_operands(tree t,tree args,tsubst_flags_t complain,tree in_decl)17648 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
17649 			  tree in_decl)
17650 {
17651 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
17652 
17653   tree purpose, value, chain;
17654 
17655   if (t == NULL)
17656     return t;
17657 
17658   if (TREE_CODE (t) != TREE_LIST)
17659     return tsubst_copy_and_build (t, args, complain, in_decl,
17660 				  /*function_p=*/false,
17661 				  /*integral_constant_expression_p=*/false);
17662 
17663   if (t == void_list_node)
17664     return t;
17665 
17666   purpose = TREE_PURPOSE (t);
17667   if (purpose)
17668     purpose = RECUR (purpose);
17669   value = TREE_VALUE (t);
17670   if (value)
17671     {
17672       if (TREE_CODE (value) != LABEL_DECL)
17673 	value = RECUR (value);
17674       else
17675 	{
17676 	  value = lookup_label (DECL_NAME (value));
17677 	  gcc_assert (TREE_CODE (value) == LABEL_DECL);
17678 	  TREE_USED (value) = 1;
17679 	}
17680     }
17681   chain = TREE_CHAIN (t);
17682   if (chain && chain != void_type_node)
17683     chain = RECUR (chain);
17684   return tree_cons (purpose, value, chain);
17685 #undef RECUR
17686 }
17687 
17688 /* Used to temporarily communicate the list of #pragma omp parallel
17689    clauses to #pragma omp for instantiation if they are combined
17690    together.  */
17691 
17692 static tree *omp_parallel_combined_clauses;
17693 
17694 static tree tsubst_decomp_names (tree, tree, tree, tsubst_flags_t, tree,
17695 				 tree *, unsigned int *);
17696 
17697 /* Substitute one OMP_FOR iterator.  */
17698 
17699 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)17700 tsubst_omp_for_iterator (tree t, int i, tree declv, tree &orig_declv,
17701 			 tree initv, tree condv, tree incrv, tree *clauses,
17702 			 tree args, tsubst_flags_t complain, tree in_decl,
17703 			 bool integral_constant_expression_p)
17704 {
17705 #define RECUR(NODE)				\
17706   tsubst_expr ((NODE), args, complain, in_decl,	\
17707 	       integral_constant_expression_p)
17708   tree decl, init, cond = NULL_TREE, incr = NULL_TREE;
17709   bool ret = false;
17710 
17711   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
17712   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
17713 
17714   decl = TREE_OPERAND (init, 0);
17715   init = TREE_OPERAND (init, 1);
17716   tree decl_expr = NULL_TREE;
17717   bool range_for = TREE_VEC_ELT (OMP_FOR_COND (t), i) == global_namespace;
17718   if (range_for)
17719     {
17720       bool decomp = false;
17721       if (decl != error_mark_node && DECL_HAS_VALUE_EXPR_P (decl))
17722 	{
17723 	  tree v = DECL_VALUE_EXPR (decl);
17724 	  if (TREE_CODE (v) == ARRAY_REF
17725 	      && VAR_P (TREE_OPERAND (v, 0))
17726 	      && DECL_DECOMPOSITION_P (TREE_OPERAND (v, 0)))
17727 	    {
17728 	      tree decomp_first = NULL_TREE;
17729 	      unsigned decomp_cnt = 0;
17730 	      tree d = tsubst_decl (TREE_OPERAND (v, 0), args, complain);
17731 	      maybe_push_decl (d);
17732 	      d = tsubst_decomp_names (d, TREE_OPERAND (v, 0), args, complain,
17733 				       in_decl, &decomp_first, &decomp_cnt);
17734 	      decomp = true;
17735 	      if (d == error_mark_node)
17736 		decl = error_mark_node;
17737 	      else
17738 		for (unsigned int i = 0; i < decomp_cnt; i++)
17739 		  {
17740 		    if (!DECL_HAS_VALUE_EXPR_P (decomp_first))
17741 		      {
17742 			tree v = build_nt (ARRAY_REF, d,
17743 					   size_int (decomp_cnt - i - 1),
17744 					   NULL_TREE, NULL_TREE);
17745 			SET_DECL_VALUE_EXPR (decomp_first, v);
17746 			DECL_HAS_VALUE_EXPR_P (decomp_first) = 1;
17747 		      }
17748 		    fit_decomposition_lang_decl (decomp_first, d);
17749 		    decomp_first = DECL_CHAIN (decomp_first);
17750 		  }
17751 	    }
17752 	}
17753       decl = tsubst_decl (decl, args, complain);
17754       if (!decomp)
17755 	maybe_push_decl (decl);
17756     }
17757   else if (init && TREE_CODE (init) == DECL_EXPR)
17758     {
17759       /* We need to jump through some hoops to handle declarations in the
17760 	 init-statement, since we might need to handle auto deduction,
17761 	 but we need to keep control of initialization.  */
17762       decl_expr = init;
17763       init = DECL_INITIAL (DECL_EXPR_DECL (init));
17764       decl = tsubst_decl (decl, args, complain);
17765     }
17766   else
17767     {
17768       if (TREE_CODE (decl) == SCOPE_REF)
17769 	{
17770 	  decl = RECUR (decl);
17771 	  if (TREE_CODE (decl) == COMPONENT_REF)
17772 	    {
17773 	      tree v = decl;
17774 	      while (v)
17775 		switch (TREE_CODE (v))
17776 		  {
17777 		  case COMPONENT_REF:
17778 		  case MEM_REF:
17779 		  case INDIRECT_REF:
17780 		  CASE_CONVERT:
17781 		  case POINTER_PLUS_EXPR:
17782 		    v = TREE_OPERAND (v, 0);
17783 		    continue;
17784 		  case PARM_DECL:
17785 		    if (DECL_CONTEXT (v) == current_function_decl
17786 			&& DECL_ARTIFICIAL (v)
17787 			&& DECL_NAME (v) == this_identifier)
17788 		      {
17789 			decl = TREE_OPERAND (decl, 1);
17790 			decl = omp_privatize_field (decl, false);
17791 		      }
17792 		    /* FALLTHRU */
17793 		  default:
17794 		    v = NULL_TREE;
17795 		    break;
17796 		  }
17797 	    }
17798 	}
17799       else
17800 	decl = RECUR (decl);
17801     }
17802   if (init && TREE_CODE (init) == TREE_VEC)
17803     {
17804       init = copy_node (init);
17805       TREE_VEC_ELT (init, 0)
17806 	= tsubst_decl (TREE_VEC_ELT (init, 0), args, complain);
17807       TREE_VEC_ELT (init, 1) = RECUR (TREE_VEC_ELT (init, 1));
17808       TREE_VEC_ELT (init, 2) = RECUR (TREE_VEC_ELT (init, 2));
17809     }
17810   else
17811     init = RECUR (init);
17812 
17813   if (orig_declv && OMP_FOR_ORIG_DECLS (t))
17814     {
17815       tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
17816       if (TREE_CODE (o) == TREE_LIST)
17817 	TREE_VEC_ELT (orig_declv, i)
17818 	  = tree_cons (RECUR (TREE_PURPOSE (o)),
17819 		       RECUR (TREE_VALUE (o)),
17820 		       NULL_TREE);
17821       else
17822 	TREE_VEC_ELT (orig_declv, i) = RECUR (o);
17823     }
17824 
17825   if (range_for)
17826     {
17827       tree this_pre_body = NULL_TREE;
17828       tree orig_init = NULL_TREE;
17829       tree orig_decl = NULL_TREE;
17830       cp_convert_omp_range_for (this_pre_body, NULL, decl, orig_decl, init,
17831 				orig_init, cond, incr);
17832       if (orig_decl)
17833 	{
17834 	  if (orig_declv == NULL_TREE)
17835 	    orig_declv = copy_node (declv);
17836 	  TREE_VEC_ELT (orig_declv, i) = orig_decl;
17837 	  ret = true;
17838 	}
17839       else if (orig_declv)
17840 	TREE_VEC_ELT (orig_declv, i) = decl;
17841     }
17842 
17843   tree auto_node = type_uses_auto (TREE_TYPE (decl));
17844   if (!range_for && auto_node && init)
17845     TREE_TYPE (decl)
17846       = do_auto_deduction (TREE_TYPE (decl), init, auto_node, complain);
17847 
17848   gcc_assert (!type_dependent_expression_p (decl));
17849 
17850   if (!CLASS_TYPE_P (TREE_TYPE (decl)) || range_for)
17851     {
17852       if (decl_expr)
17853 	{
17854 	  /* Declare the variable, but don't let that initialize it.  */
17855 	  tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
17856 	  DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
17857 	  RECUR (decl_expr);
17858 	  DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
17859 	}
17860 
17861       if (!range_for)
17862 	{
17863 	  cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
17864 	  if (COMPARISON_CLASS_P (cond)
17865 	      && TREE_CODE (TREE_OPERAND (cond, 1)) == TREE_VEC)
17866 	    {
17867 	      tree lhs = RECUR (TREE_OPERAND (cond, 0));
17868 	      tree rhs = copy_node (TREE_OPERAND (cond, 1));
17869 	      TREE_VEC_ELT (rhs, 0)
17870 		= tsubst_decl (TREE_VEC_ELT (rhs, 0), args, complain);
17871 	      TREE_VEC_ELT (rhs, 1) = RECUR (TREE_VEC_ELT (rhs, 1));
17872 	      TREE_VEC_ELT (rhs, 2) = RECUR (TREE_VEC_ELT (rhs, 2));
17873 	      cond = build2 (TREE_CODE (cond), TREE_TYPE (cond),
17874 			     lhs, rhs);
17875 	    }
17876 	  else
17877 	    cond = RECUR (cond);
17878 	  incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
17879 	  if (TREE_CODE (incr) == MODIFY_EXPR)
17880 	    {
17881 	      tree lhs = RECUR (TREE_OPERAND (incr, 0));
17882 	      tree rhs = RECUR (TREE_OPERAND (incr, 1));
17883 	      incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
17884 					  NOP_EXPR, rhs, complain);
17885 	    }
17886 	  else
17887 	    incr = RECUR (incr);
17888 	  if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
17889 	    TREE_VEC_ELT (orig_declv, i) = decl;
17890 	}
17891       TREE_VEC_ELT (declv, i) = decl;
17892       TREE_VEC_ELT (initv, i) = init;
17893       TREE_VEC_ELT (condv, i) = cond;
17894       TREE_VEC_ELT (incrv, i) = incr;
17895       return ret;
17896     }
17897 
17898   if (decl_expr)
17899     {
17900       /* Declare and initialize the variable.  */
17901       RECUR (decl_expr);
17902       init = NULL_TREE;
17903     }
17904   else if (init)
17905     {
17906       tree *pc;
17907       int j;
17908       for (j = ((omp_parallel_combined_clauses == NULL
17909 		|| TREE_CODE (t) == OMP_LOOP) ? 1 : 0); j < 2; j++)
17910 	{
17911 	  for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
17912 	    {
17913 	      if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
17914 		  && OMP_CLAUSE_DECL (*pc) == decl)
17915 		break;
17916 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
17917 		       && OMP_CLAUSE_DECL (*pc) == decl)
17918 		{
17919 		  if (j)
17920 		    break;
17921 		  /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES.  */
17922 		  tree c = *pc;
17923 		  *pc = OMP_CLAUSE_CHAIN (c);
17924 		  OMP_CLAUSE_CHAIN (c) = *clauses;
17925 		  *clauses = c;
17926 		}
17927 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
17928 		       && OMP_CLAUSE_DECL (*pc) == decl)
17929 		{
17930 		  error ("iteration variable %qD should not be firstprivate",
17931 			 decl);
17932 		  *pc = OMP_CLAUSE_CHAIN (*pc);
17933 		}
17934 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
17935 		       && OMP_CLAUSE_DECL (*pc) == decl)
17936 		{
17937 		  error ("iteration variable %qD should not be reduction",
17938 			 decl);
17939 		  *pc = OMP_CLAUSE_CHAIN (*pc);
17940 		}
17941 	      else
17942 		pc = &OMP_CLAUSE_CHAIN (*pc);
17943 	    }
17944 	  if (*pc)
17945 	    break;
17946 	}
17947       if (*pc == NULL_TREE)
17948 	{
17949 	  tree c = build_omp_clause (input_location,
17950 				     TREE_CODE (t) == OMP_LOOP
17951 				     ? OMP_CLAUSE_LASTPRIVATE
17952 				     : OMP_CLAUSE_PRIVATE);
17953 	  OMP_CLAUSE_DECL (c) = decl;
17954 	  c = finish_omp_clauses (c, C_ORT_OMP);
17955 	  if (c)
17956 	    {
17957 	      OMP_CLAUSE_CHAIN (c) = *clauses;
17958 	      *clauses = c;
17959 	    }
17960 	}
17961     }
17962   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
17963   if (COMPARISON_CLASS_P (cond))
17964     {
17965       tree op0 = RECUR (TREE_OPERAND (cond, 0));
17966       tree op1 = RECUR (TREE_OPERAND (cond, 1));
17967       cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
17968     }
17969   else
17970     cond = RECUR (cond);
17971   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
17972   switch (TREE_CODE (incr))
17973     {
17974     case PREINCREMENT_EXPR:
17975     case PREDECREMENT_EXPR:
17976     case POSTINCREMENT_EXPR:
17977     case POSTDECREMENT_EXPR:
17978       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
17979 		     RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
17980       break;
17981     case MODIFY_EXPR:
17982       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
17983 	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
17984 	{
17985 	  tree rhs = TREE_OPERAND (incr, 1);
17986 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
17987 	  tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
17988 	  tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
17989 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
17990 			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
17991 				 rhs0, rhs1));
17992 	}
17993       else
17994 	incr = RECUR (incr);
17995       break;
17996     case MODOP_EXPR:
17997       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
17998 	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
17999 	{
18000 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
18001 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18002 			 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
18003 				 TREE_TYPE (decl), lhs,
18004 				 RECUR (TREE_OPERAND (incr, 2))));
18005 	}
18006       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
18007 	       && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
18008 		   || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
18009 	{
18010 	  tree rhs = TREE_OPERAND (incr, 2);
18011 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
18012 	  tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
18013 	  tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
18014 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18015 			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
18016 				 rhs0, rhs1));
18017 	}
18018       else
18019 	incr = RECUR (incr);
18020       break;
18021     default:
18022       incr = RECUR (incr);
18023       break;
18024     }
18025 
18026   if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
18027     TREE_VEC_ELT (orig_declv, i) = decl;
18028   TREE_VEC_ELT (declv, i) = decl;
18029   TREE_VEC_ELT (initv, i) = init;
18030   TREE_VEC_ELT (condv, i) = cond;
18031   TREE_VEC_ELT (incrv, i) = incr;
18032   return false;
18033 #undef RECUR
18034 }
18035 
18036 /* Helper function of tsubst_expr, find OMP_TEAMS inside
18037    of OMP_TARGET's body.  */
18038 
18039 static tree
tsubst_find_omp_teams(tree * tp,int * walk_subtrees,void *)18040 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
18041 {
18042   *walk_subtrees = 0;
18043   switch (TREE_CODE (*tp))
18044     {
18045     case OMP_TEAMS:
18046       return *tp;
18047     case BIND_EXPR:
18048     case STATEMENT_LIST:
18049       *walk_subtrees = 1;
18050       break;
18051     default:
18052       break;
18053     }
18054   return NULL_TREE;
18055 }
18056 
18057 /* Helper function for tsubst_expr.  For decomposition declaration
18058    artificial base DECL, which is tsubsted PATTERN_DECL, tsubst
18059    also the corresponding decls representing the identifiers
18060    of the decomposition declaration.  Return DECL if successful
18061    or error_mark_node otherwise, set *FIRST to the first decl
18062    in the list chained through DECL_CHAIN and *CNT to the number
18063    of such decls.  */
18064 
18065 static tree
tsubst_decomp_names(tree decl,tree pattern_decl,tree args,tsubst_flags_t complain,tree in_decl,tree * first,unsigned int * cnt)18066 tsubst_decomp_names (tree decl, tree pattern_decl, tree args,
18067 		     tsubst_flags_t complain, tree in_decl, tree *first,
18068 		     unsigned int *cnt)
18069 {
18070   tree decl2, decl3, prev = decl;
18071   *cnt = 0;
18072   gcc_assert (DECL_NAME (decl) == NULL_TREE);
18073   for (decl2 = DECL_CHAIN (pattern_decl);
18074        decl2
18075        && VAR_P (decl2)
18076        && DECL_DECOMPOSITION_P (decl2)
18077        && DECL_NAME (decl2);
18078        decl2 = DECL_CHAIN (decl2))
18079     {
18080       if (TREE_TYPE (decl2) == error_mark_node && *cnt == 0)
18081 	{
18082 	  gcc_assert (errorcount);
18083 	  return error_mark_node;
18084 	}
18085       (*cnt)++;
18086       gcc_assert (DECL_DECOMP_BASE (decl2) == pattern_decl);
18087       gcc_assert (DECL_HAS_VALUE_EXPR_P (decl2));
18088       tree v = DECL_VALUE_EXPR (decl2);
18089       DECL_HAS_VALUE_EXPR_P (decl2) = 0;
18090       SET_DECL_VALUE_EXPR (decl2, NULL_TREE);
18091       decl3 = tsubst (decl2, args, complain, in_decl);
18092       SET_DECL_VALUE_EXPR (decl2, v);
18093       DECL_HAS_VALUE_EXPR_P (decl2) = 1;
18094       if (VAR_P (decl3))
18095 	DECL_TEMPLATE_INSTANTIATED (decl3) = 1;
18096       else
18097 	{
18098 	  gcc_assert (errorcount);
18099 	  decl = error_mark_node;
18100 	  continue;
18101 	}
18102       maybe_push_decl (decl3);
18103       if (error_operand_p (decl3))
18104 	decl = error_mark_node;
18105       else if (decl != error_mark_node
18106 	       && DECL_CHAIN (decl3) != prev
18107 	       && decl != prev)
18108 	{
18109 	  gcc_assert (errorcount);
18110 	  decl = error_mark_node;
18111 	}
18112       else
18113 	prev = decl3;
18114     }
18115   *first = prev;
18116   return decl;
18117 }
18118 
18119 /* Return the proper local_specialization for init-capture pack DECL.  */
18120 
18121 static tree
lookup_init_capture_pack(tree decl)18122 lookup_init_capture_pack (tree decl)
18123 {
18124   /* We handle normal pack captures by forwarding to the specialization of the
18125      captured parameter.  We can't do that for pack init-captures; we need them
18126      to have their own local_specialization.  We created the individual
18127      VAR_DECLs (if any) under build_capture_proxy, and we need to collect them
18128      when we process the DECL_EXPR for the pack init-capture in the template.
18129      So, how do we find them?  We don't know the capture proxy pack when
18130      building the individual resulting proxies, and we don't know the
18131      individual proxies when instantiating the pack.  What we have in common is
18132      the FIELD_DECL.
18133 
18134      So...when we instantiate the FIELD_DECL, we stick the result in
18135      local_specializations.  Then at the DECL_EXPR we look up that result, see
18136      how many elements it has, synthesize the names, and look them up.  */
18137 
18138   tree cname = DECL_NAME (decl);
18139   tree val = DECL_VALUE_EXPR (decl);
18140   tree field = TREE_OPERAND (val, 1);
18141   gcc_assert (TREE_CODE (field) == FIELD_DECL);
18142   tree fpack = retrieve_local_specialization (field);
18143   if (fpack == error_mark_node)
18144     return error_mark_node;
18145 
18146   int len = 1;
18147   tree vec = NULL_TREE;
18148   tree r = NULL_TREE;
18149   if (TREE_CODE (fpack) == TREE_VEC)
18150     {
18151       len = TREE_VEC_LENGTH (fpack);
18152       vec = make_tree_vec (len);
18153       r = make_node (NONTYPE_ARGUMENT_PACK);
18154       SET_ARGUMENT_PACK_ARGS (r, vec);
18155     }
18156   for (int i = 0; i < len; ++i)
18157     {
18158       tree ename = vec ? make_ith_pack_parameter_name (cname, i) : cname;
18159       tree elt = lookup_name (ename);
18160       if (vec)
18161 	TREE_VEC_ELT (vec, i) = elt;
18162       else
18163 	r = elt;
18164     }
18165   return r;
18166 }
18167 
18168 /* Like tsubst_copy for expressions, etc. but also does semantic
18169    processing.  */
18170 
18171 tree
tsubst_expr(tree t,tree args,tsubst_flags_t complain,tree in_decl,bool integral_constant_expression_p)18172 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
18173 	     bool integral_constant_expression_p)
18174 {
18175 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
18176 #define RECUR(NODE)				\
18177   tsubst_expr ((NODE), args, complain, in_decl,	\
18178 	       integral_constant_expression_p)
18179 
18180   tree stmt, tmp;
18181   tree r;
18182   location_t loc;
18183 
18184   if (t == NULL_TREE || t == error_mark_node)
18185     return t;
18186 
18187   loc = input_location;
18188   if (location_t eloc = cp_expr_location (t))
18189     input_location = eloc;
18190   if (STATEMENT_CODE_P (TREE_CODE (t)))
18191     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
18192 
18193   switch (TREE_CODE (t))
18194     {
18195     case STATEMENT_LIST:
18196       {
18197 	tree_stmt_iterator i;
18198 	for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
18199 	  RECUR (tsi_stmt (i));
18200 	break;
18201       }
18202 
18203     case CTOR_INITIALIZER:
18204       finish_mem_initializers (tsubst_initializer_list
18205 			       (TREE_OPERAND (t, 0), args));
18206       break;
18207 
18208     case RETURN_EXPR:
18209       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
18210       break;
18211 
18212     case CO_RETURN_EXPR:
18213       finish_co_return_stmt (input_location, RECUR (TREE_OPERAND (t, 0)));
18214       break;
18215 
18216     case CO_YIELD_EXPR:
18217       stmt = finish_co_yield_expr (input_location,
18218 				   RECUR (TREE_OPERAND (t, 0)));
18219       RETURN (stmt);
18220       break;
18221 
18222     case CO_AWAIT_EXPR:
18223       stmt = finish_co_await_expr (input_location,
18224 				   RECUR (TREE_OPERAND (t, 0)));
18225       RETURN (stmt);
18226       break;
18227 
18228     case EXPR_STMT:
18229       tmp = RECUR (EXPR_STMT_EXPR (t));
18230       if (EXPR_STMT_STMT_EXPR_RESULT (t))
18231 	finish_stmt_expr_expr (tmp, cur_stmt_expr);
18232       else
18233 	finish_expr_stmt (tmp);
18234       break;
18235 
18236     case USING_STMT:
18237       finish_using_directive (USING_STMT_NAMESPACE (t), /*attribs=*/NULL_TREE);
18238       break;
18239 
18240     case DECL_EXPR:
18241       {
18242 	tree decl, pattern_decl;
18243 	tree init;
18244 
18245 	pattern_decl = decl = DECL_EXPR_DECL (t);
18246 	if (TREE_CODE (decl) == LABEL_DECL)
18247 	  finish_label_decl (DECL_NAME (decl));
18248 	else if (TREE_CODE (decl) == USING_DECL)
18249 	  {
18250 	    tree scope = USING_DECL_SCOPE (decl);
18251 	    if (DECL_DEPENDENT_P (decl))
18252 	      {
18253 		scope = tsubst (scope, args, complain, in_decl);
18254 		if (!MAYBE_CLASS_TYPE_P (scope)
18255 		    && TREE_CODE (scope) != ENUMERAL_TYPE)
18256 		  {
18257 		    if (complain & tf_error)
18258 		      error_at (DECL_SOURCE_LOCATION (decl), "%qT is not a "
18259 				"class, namespace, or enumeration", scope);
18260 		    return error_mark_node;
18261 		  }
18262 		finish_nonmember_using_decl (scope, DECL_NAME (decl));
18263 	      }
18264 	    else
18265 	      {
18266 		/* This is a non-dependent using-decl, and we'll have
18267 		   used the names it found during template parsing.  We do
18268 		   not want to do the lookup again, because we might not
18269 		   find the things we found then.  */
18270 		gcc_checking_assert (scope == tsubst (scope, args,
18271 						      complain, in_decl));
18272 		/* We still need to push the bindings so that we can look up
18273 		   this name later.  */
18274 		push_using_decl_bindings (DECL_NAME (decl),
18275 					  USING_DECL_DECLS (decl));
18276 	      }
18277 	  }
18278 	else if (is_capture_proxy (decl)
18279 		 && !DECL_TEMPLATE_INSTANTIATION (current_function_decl))
18280 	  {
18281 	    /* We're in tsubst_lambda_expr, we've already inserted a new
18282 	       capture proxy, so look it up and register it.  */
18283 	    tree inst;
18284 	    if (!DECL_PACK_P (decl))
18285 	      {
18286 		inst = lookup_name (DECL_NAME (decl), LOOK_where::BLOCK,
18287 				    LOOK_want::HIDDEN_LAMBDA);
18288 		gcc_assert (inst != decl && is_capture_proxy (inst));
18289 	      }
18290 	    else if (is_normal_capture_proxy (decl))
18291 	      {
18292 		inst = (retrieve_local_specialization
18293 			(DECL_CAPTURED_VARIABLE (decl)));
18294 		gcc_assert (TREE_CODE (inst) == NONTYPE_ARGUMENT_PACK
18295 			    || DECL_PACK_P (inst));
18296 	      }
18297 	    else
18298 	      inst = lookup_init_capture_pack (decl);
18299 
18300 	    register_local_specialization (inst, decl);
18301 	    break;
18302 	  }
18303 	else if (DECL_PRETTY_FUNCTION_P (decl))
18304 	  decl = make_fname_decl (DECL_SOURCE_LOCATION (decl),
18305 				  DECL_NAME (decl),
18306 				  true/*DECL_PRETTY_FUNCTION_P (decl)*/);
18307 	else if (DECL_IMPLICIT_TYPEDEF_P (decl)
18308 		 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
18309 	  /* Don't copy the old closure; we'll create a new one in
18310 	     tsubst_lambda_expr.  */
18311 	  break;
18312 	else
18313 	  {
18314 	    init = DECL_INITIAL (decl);
18315 	    decl = tsubst (decl, args, complain, in_decl);
18316 	    if (decl != error_mark_node)
18317 	      {
18318 		/* By marking the declaration as instantiated, we avoid
18319 		   trying to instantiate it.  Since instantiate_decl can't
18320 		   handle local variables, and since we've already done
18321 		   all that needs to be done, that's the right thing to
18322 		   do.  */
18323 		if (VAR_P (decl))
18324 		  DECL_TEMPLATE_INSTANTIATED (decl) = 1;
18325 		if (VAR_P (decl) && !DECL_NAME (decl)
18326 		    && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
18327 		  /* Anonymous aggregates are a special case.  */
18328 		  finish_anon_union (decl);
18329 		else if (is_capture_proxy (DECL_EXPR_DECL (t)))
18330 		  {
18331 		    DECL_CONTEXT (decl) = current_function_decl;
18332 		    if (DECL_NAME (decl) == this_identifier)
18333 		      {
18334 			tree lam = DECL_CONTEXT (current_function_decl);
18335 			lam = CLASSTYPE_LAMBDA_EXPR (lam);
18336 			LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
18337 		      }
18338 		    insert_capture_proxy (decl);
18339 		  }
18340 		else if (DECL_IMPLICIT_TYPEDEF_P (t))
18341 		  /* We already did a pushtag.  */;
18342 		else if (VAR_OR_FUNCTION_DECL_P (decl)
18343 			 && DECL_LOCAL_DECL_P (decl))
18344 		  {
18345 		    if (TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL)
18346 		      DECL_CONTEXT (decl) = NULL_TREE;
18347 		    decl = pushdecl (decl);
18348 		    if (TREE_CODE (decl) == FUNCTION_DECL
18349 			&& DECL_OMP_DECLARE_REDUCTION_P (decl)
18350 			&& cp_check_omp_declare_reduction (decl))
18351 		      instantiate_body (pattern_decl, args, decl, true);
18352 		  }
18353 		else
18354 		  {
18355 		    bool const_init = false;
18356 		    unsigned int cnt = 0;
18357 		    tree first = NULL_TREE, ndecl = error_mark_node;
18358 		    tree asmspec_tree = NULL_TREE;
18359 		    maybe_push_decl (decl);
18360 
18361 		    if (VAR_P (decl)
18362 			&& DECL_DECOMPOSITION_P (decl)
18363 			&& TREE_TYPE (pattern_decl) != error_mark_node)
18364 		      ndecl = tsubst_decomp_names (decl, pattern_decl, args,
18365 						   complain, in_decl, &first,
18366 						   &cnt);
18367 
18368 		    init = tsubst_init (init, decl, args, complain, in_decl);
18369 
18370 		    if (VAR_P (decl))
18371 		      const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
18372 				    (pattern_decl));
18373 
18374 		    if (ndecl != error_mark_node)
18375 		      cp_maybe_mangle_decomp (ndecl, first, cnt);
18376 
18377 		    /* In a non-template function, VLA type declarations are
18378 		       handled in grokdeclarator; for templates, handle them
18379 		       now.  */
18380 		    predeclare_vla (decl);
18381 
18382 		    if (VAR_P (decl) && DECL_HARD_REGISTER (pattern_decl))
18383 		      {
18384 			tree id = DECL_ASSEMBLER_NAME (pattern_decl);
18385 			const char *asmspec = IDENTIFIER_POINTER (id);
18386 			gcc_assert (asmspec[0] == '*');
18387 			asmspec_tree
18388 			  = build_string (IDENTIFIER_LENGTH (id) - 1,
18389 					  asmspec + 1);
18390 			TREE_TYPE (asmspec_tree) = char_array_type_node;
18391 		      }
18392 
18393 		    cp_finish_decl (decl, init, const_init, asmspec_tree, 0);
18394 
18395 		    if (ndecl != error_mark_node)
18396 		      cp_finish_decomp (ndecl, first, cnt);
18397 		  }
18398 	      }
18399 	  }
18400 
18401 	break;
18402       }
18403 
18404     case FOR_STMT:
18405       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
18406       RECUR (FOR_INIT_STMT (t));
18407       finish_init_stmt (stmt);
18408       tmp = RECUR (FOR_COND (t));
18409       finish_for_cond (tmp, stmt, false, 0);
18410       tmp = RECUR (FOR_EXPR (t));
18411       finish_for_expr (tmp, stmt);
18412       {
18413 	bool prev = note_iteration_stmt_body_start ();
18414 	RECUR (FOR_BODY (t));
18415 	note_iteration_stmt_body_end (prev);
18416       }
18417       finish_for_stmt (stmt);
18418       break;
18419 
18420     case RANGE_FOR_STMT:
18421       {
18422 	/* Construct another range_for, if this is not a final
18423 	   substitution (for inside a generic lambda of a
18424 	   template).  Otherwise convert to a regular for.  */
18425         tree decl, expr;
18426         stmt = (processing_template_decl
18427 		? begin_range_for_stmt (NULL_TREE, NULL_TREE)
18428 		: begin_for_stmt (NULL_TREE, NULL_TREE));
18429 	RECUR (RANGE_FOR_INIT_STMT (t));
18430         decl = RANGE_FOR_DECL (t);
18431         decl = tsubst (decl, args, complain, in_decl);
18432         maybe_push_decl (decl);
18433         expr = RECUR (RANGE_FOR_EXPR (t));
18434 
18435 	tree decomp_first = NULL_TREE;
18436 	unsigned decomp_cnt = 0;
18437 	if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
18438 	  decl = tsubst_decomp_names (decl, RANGE_FOR_DECL (t), args,
18439 				      complain, in_decl,
18440 				      &decomp_first, &decomp_cnt);
18441 
18442 	if (processing_template_decl)
18443 	  {
18444 	    RANGE_FOR_IVDEP (stmt) = RANGE_FOR_IVDEP (t);
18445 	    RANGE_FOR_UNROLL (stmt) = RANGE_FOR_UNROLL (t);
18446 	    finish_range_for_decl (stmt, decl, expr);
18447 	    if (decomp_first && decl != error_mark_node)
18448 	      cp_finish_decomp (decl, decomp_first, decomp_cnt);
18449 	  }
18450 	else
18451 	  {
18452 	    unsigned short unroll = (RANGE_FOR_UNROLL (t)
18453 				     ? tree_to_uhwi (RANGE_FOR_UNROLL (t)) : 0);
18454 	    stmt = cp_convert_range_for (stmt, decl, expr,
18455 					 decomp_first, decomp_cnt,
18456 					 RANGE_FOR_IVDEP (t), unroll);
18457 	  }
18458 
18459 	bool prev = note_iteration_stmt_body_start ();
18460         RECUR (RANGE_FOR_BODY (t));
18461 	note_iteration_stmt_body_end (prev);
18462         finish_for_stmt (stmt);
18463       }
18464       break;
18465 
18466     case WHILE_STMT:
18467       stmt = begin_while_stmt ();
18468       tmp = RECUR (WHILE_COND (t));
18469       finish_while_stmt_cond (tmp, stmt, false, 0);
18470       {
18471 	bool prev = note_iteration_stmt_body_start ();
18472 	RECUR (WHILE_BODY (t));
18473 	note_iteration_stmt_body_end (prev);
18474       }
18475       finish_while_stmt (stmt);
18476       break;
18477 
18478     case DO_STMT:
18479       stmt = begin_do_stmt ();
18480       {
18481 	bool prev = note_iteration_stmt_body_start ();
18482 	RECUR (DO_BODY (t));
18483 	note_iteration_stmt_body_end (prev);
18484       }
18485       finish_do_body (stmt);
18486       tmp = RECUR (DO_COND (t));
18487       finish_do_stmt (tmp, stmt, false, 0);
18488       break;
18489 
18490     case IF_STMT:
18491       stmt = begin_if_stmt ();
18492       IF_STMT_CONSTEXPR_P (stmt) = IF_STMT_CONSTEXPR_P (t);
18493       if (IF_STMT_CONSTEXPR_P (t))
18494 	args = add_extra_args (IF_STMT_EXTRA_ARGS (t), args, complain, in_decl);
18495       tmp = RECUR (IF_COND (t));
18496       tmp = finish_if_stmt_cond (tmp, stmt);
18497       if (IF_STMT_CONSTEXPR_P (t)
18498 	  && instantiation_dependent_expression_p (tmp))
18499 	{
18500 	  /* We're partially instantiating a generic lambda, but the condition
18501 	     of the constexpr if is still dependent.  Don't substitute into the
18502 	     branches now, just remember the template arguments.  */
18503 	  do_poplevel (IF_SCOPE (stmt));
18504 	  IF_COND (stmt) = IF_COND (t);
18505 	  THEN_CLAUSE (stmt) = THEN_CLAUSE (t);
18506 	  ELSE_CLAUSE (stmt) = ELSE_CLAUSE (t);
18507 	  IF_STMT_EXTRA_ARGS (stmt) = build_extra_args (t, args, complain);
18508 	  add_stmt (stmt);
18509 	  break;
18510 	}
18511       if (IF_STMT_CONSTEXPR_P (t) && integer_zerop (tmp))
18512 	/* Don't instantiate the THEN_CLAUSE. */;
18513       else
18514 	{
18515 	  tree folded = fold_non_dependent_expr (tmp, complain);
18516 	  bool inhibit = integer_zerop (folded);
18517 	  if (inhibit)
18518 	    ++c_inhibit_evaluation_warnings;
18519 	  RECUR (THEN_CLAUSE (t));
18520 	  if (inhibit)
18521 	    --c_inhibit_evaluation_warnings;
18522 	}
18523       finish_then_clause (stmt);
18524 
18525       if (IF_STMT_CONSTEXPR_P (t) && integer_nonzerop (tmp))
18526 	/* Don't instantiate the ELSE_CLAUSE. */;
18527       else if (ELSE_CLAUSE (t))
18528 	{
18529 	  tree folded = fold_non_dependent_expr (tmp, complain);
18530 	  bool inhibit = integer_nonzerop (folded);
18531 	  begin_else_clause (stmt);
18532 	  if (inhibit)
18533 	    ++c_inhibit_evaluation_warnings;
18534 	  RECUR (ELSE_CLAUSE (t));
18535 	  if (inhibit)
18536 	    --c_inhibit_evaluation_warnings;
18537 	  finish_else_clause (stmt);
18538 	}
18539 
18540       finish_if_stmt (stmt);
18541       break;
18542 
18543     case BIND_EXPR:
18544       if (BIND_EXPR_BODY_BLOCK (t))
18545 	stmt = begin_function_body ();
18546       else
18547 	stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
18548 				    ? BCS_TRY_BLOCK : 0);
18549 
18550       RECUR (BIND_EXPR_BODY (t));
18551 
18552       if (BIND_EXPR_BODY_BLOCK (t))
18553 	finish_function_body (stmt);
18554       else
18555 	finish_compound_stmt (stmt);
18556       break;
18557 
18558     case BREAK_STMT:
18559       finish_break_stmt ();
18560       break;
18561 
18562     case CONTINUE_STMT:
18563       finish_continue_stmt ();
18564       break;
18565 
18566     case SWITCH_STMT:
18567       stmt = begin_switch_stmt ();
18568       tmp = RECUR (SWITCH_STMT_COND (t));
18569       finish_switch_cond (tmp, stmt);
18570       RECUR (SWITCH_STMT_BODY (t));
18571       finish_switch_stmt (stmt);
18572       break;
18573 
18574     case CASE_LABEL_EXPR:
18575       {
18576 	tree decl = CASE_LABEL (t);
18577 	tree low = RECUR (CASE_LOW (t));
18578 	tree high = RECUR (CASE_HIGH (t));
18579 	tree l = finish_case_label (EXPR_LOCATION (t), low, high);
18580 	if (l && TREE_CODE (l) == CASE_LABEL_EXPR)
18581 	  {
18582 	    tree label = CASE_LABEL (l);
18583 	    FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
18584 	    if (DECL_ATTRIBUTES (decl) != NULL_TREE)
18585 	      cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
18586 	  }
18587       }
18588       break;
18589 
18590     case LABEL_EXPR:
18591       {
18592 	tree decl = LABEL_EXPR_LABEL (t);
18593 	tree label;
18594 
18595 	label = finish_label_stmt (DECL_NAME (decl));
18596 	if (TREE_CODE (label) == LABEL_DECL)
18597 	  FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
18598 	if (DECL_ATTRIBUTES (decl) != NULL_TREE)
18599 	  cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
18600       }
18601       break;
18602 
18603     case GOTO_EXPR:
18604       tmp = GOTO_DESTINATION (t);
18605       if (TREE_CODE (tmp) != LABEL_DECL)
18606 	/* Computed goto's must be tsubst'd into.  On the other hand,
18607 	   non-computed gotos must not be; the identifier in question
18608 	   will have no binding.  */
18609 	tmp = RECUR (tmp);
18610       else
18611 	tmp = DECL_NAME (tmp);
18612       finish_goto_stmt (tmp);
18613       break;
18614 
18615     case ASM_EXPR:
18616       {
18617 	tree string = RECUR (ASM_STRING (t));
18618 	tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
18619 						 complain, in_decl);
18620 	tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
18621 						complain, in_decl);
18622 	tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
18623 	 					  complain, in_decl);
18624 	tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
18625 						complain, in_decl);
18626 	tmp = finish_asm_stmt (EXPR_LOCATION (t), ASM_VOLATILE_P (t), string,
18627 			       outputs, inputs, clobbers, labels,
18628 			       ASM_INLINE_P (t));
18629 	tree asm_expr = tmp;
18630 	if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
18631 	  asm_expr = TREE_OPERAND (asm_expr, 0);
18632 	ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
18633       }
18634       break;
18635 
18636     case TRY_BLOCK:
18637       if (CLEANUP_P (t))
18638 	{
18639 	  stmt = begin_try_block ();
18640 	  RECUR (TRY_STMTS (t));
18641 	  finish_cleanup_try_block (stmt);
18642 	  finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
18643 	}
18644       else
18645 	{
18646 	  tree compound_stmt = NULL_TREE;
18647 
18648 	  if (FN_TRY_BLOCK_P (t))
18649 	    stmt = begin_function_try_block (&compound_stmt);
18650 	  else
18651 	    stmt = begin_try_block ();
18652 
18653 	  RECUR (TRY_STMTS (t));
18654 
18655 	  if (FN_TRY_BLOCK_P (t))
18656 	    finish_function_try_block (stmt);
18657 	  else
18658 	    finish_try_block (stmt);
18659 
18660 	  RECUR (TRY_HANDLERS (t));
18661 	  if (FN_TRY_BLOCK_P (t))
18662 	    finish_function_handler_sequence (stmt, compound_stmt);
18663 	  else
18664 	    finish_handler_sequence (stmt);
18665 	}
18666       break;
18667 
18668     case HANDLER:
18669       {
18670 	tree decl = HANDLER_PARMS (t);
18671 
18672 	if (decl)
18673 	  {
18674 	    decl = tsubst (decl, args, complain, in_decl);
18675 	    /* Prevent instantiate_decl from trying to instantiate
18676 	       this variable.  We've already done all that needs to be
18677 	       done.  */
18678 	    if (decl != error_mark_node)
18679 	      DECL_TEMPLATE_INSTANTIATED (decl) = 1;
18680 	  }
18681 	stmt = begin_handler ();
18682 	finish_handler_parms (decl, stmt);
18683 	RECUR (HANDLER_BODY (t));
18684 	finish_handler (stmt);
18685       }
18686       break;
18687 
18688     case TAG_DEFN:
18689       tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
18690       if (CLASS_TYPE_P (tmp))
18691 	{
18692 	  /* Local classes are not independent templates; they are
18693 	     instantiated along with their containing function.  And this
18694 	     way we don't have to deal with pushing out of one local class
18695 	     to instantiate a member of another local class.  */
18696 	  /* Closures are handled by the LAMBDA_EXPR.  */
18697 	  gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
18698 	  complete_type (tmp);
18699 	  for (tree fld = TYPE_FIELDS (tmp); fld; fld = DECL_CHAIN (fld))
18700 	    if ((VAR_P (fld)
18701 		 || (TREE_CODE (fld) == FUNCTION_DECL
18702 		     && !DECL_ARTIFICIAL (fld)))
18703 		&& DECL_TEMPLATE_INSTANTIATION (fld))
18704 	      instantiate_decl (fld, /*defer_ok=*/false,
18705 				/*expl_inst_class=*/false);
18706 	}
18707       break;
18708 
18709     case STATIC_ASSERT:
18710       {
18711 	tree condition;
18712 
18713 	++c_inhibit_evaluation_warnings;
18714 	condition =
18715 	  tsubst_expr (STATIC_ASSERT_CONDITION (t),
18716                        args,
18717                        complain, in_decl,
18718                        /*integral_constant_expression_p=*/true);
18719 	--c_inhibit_evaluation_warnings;
18720 
18721         finish_static_assert (condition,
18722                               STATIC_ASSERT_MESSAGE (t),
18723                               STATIC_ASSERT_SOURCE_LOCATION (t),
18724 			      /*member_p=*/false, /*show_expr_p=*/true);
18725       }
18726       break;
18727 
18728     case OACC_KERNELS:
18729     case OACC_PARALLEL:
18730     case OACC_SERIAL:
18731       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_ACC, args, complain,
18732 				in_decl);
18733       stmt = begin_omp_parallel ();
18734       RECUR (OMP_BODY (t));
18735       finish_omp_construct (TREE_CODE (t), stmt, tmp);
18736       break;
18737 
18738     case OMP_PARALLEL:
18739       r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
18740       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), C_ORT_OMP, args,
18741 				complain, in_decl);
18742       if (OMP_PARALLEL_COMBINED (t))
18743 	omp_parallel_combined_clauses = &tmp;
18744       stmt = begin_omp_parallel ();
18745       RECUR (OMP_PARALLEL_BODY (t));
18746       gcc_assert (omp_parallel_combined_clauses == NULL);
18747       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
18748 	= OMP_PARALLEL_COMBINED (t);
18749       pop_omp_privatization_clauses (r);
18750       break;
18751 
18752     case OMP_TASK:
18753       if (OMP_TASK_BODY (t) == NULL_TREE)
18754 	{
18755 	  tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
18756 				    complain, in_decl);
18757 	  t = copy_node (t);
18758 	  OMP_TASK_CLAUSES (t) = tmp;
18759 	  add_stmt (t);
18760 	  break;
18761 	}
18762       r = push_omp_privatization_clauses (false);
18763       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
18764 				complain, in_decl);
18765       stmt = begin_omp_task ();
18766       RECUR (OMP_TASK_BODY (t));
18767       finish_omp_task (tmp, stmt);
18768       pop_omp_privatization_clauses (r);
18769       break;
18770 
18771     case OMP_FOR:
18772     case OMP_LOOP:
18773     case OMP_SIMD:
18774     case OMP_DISTRIBUTE:
18775     case OMP_TASKLOOP:
18776     case OACC_LOOP:
18777       {
18778 	tree clauses, body, pre_body;
18779 	tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
18780 	tree orig_declv = NULL_TREE;
18781 	tree incrv = NULL_TREE;
18782 	enum c_omp_region_type ort = C_ORT_OMP;
18783 	bool any_range_for = false;
18784 	int i;
18785 
18786 	if (TREE_CODE (t) == OACC_LOOP)
18787 	  ort = C_ORT_ACC;
18788 
18789 	r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
18790 	clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), ort, args, complain,
18791 				      in_decl);
18792 	if (OMP_FOR_INIT (t) != NULL_TREE)
18793 	  {
18794 	    declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18795 	    if (OMP_FOR_ORIG_DECLS (t))
18796 	      orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18797 	    initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18798 	    condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18799 	    incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18800 	  }
18801 
18802 	keep_next_level (true);
18803 	stmt = begin_omp_structured_block ();
18804 
18805 	pre_body = push_stmt_list ();
18806 	RECUR (OMP_FOR_PRE_BODY (t));
18807 	pre_body = pop_stmt_list (pre_body);
18808 
18809 	if (OMP_FOR_INIT (t) != NULL_TREE)
18810 	  for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
18811 	    any_range_for
18812 	      |= tsubst_omp_for_iterator (t, i, declv, orig_declv, initv,
18813 					  condv, incrv, &clauses, args,
18814 					  complain, in_decl,
18815 					  integral_constant_expression_p);
18816 	omp_parallel_combined_clauses = NULL;
18817 
18818 	if (any_range_for)
18819 	  {
18820 	    gcc_assert (orig_declv);
18821 	    body = begin_omp_structured_block ();
18822 	    for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
18823 	      if (TREE_VEC_ELT (orig_declv, i) != TREE_VEC_ELT (declv, i)
18824 		  && TREE_CODE (TREE_VEC_ELT (orig_declv, i)) == TREE_LIST
18825 		  && TREE_CHAIN (TREE_VEC_ELT (orig_declv, i)))
18826 		cp_finish_omp_range_for (TREE_VEC_ELT (orig_declv, i),
18827 					 TREE_VEC_ELT (declv, i));
18828 	  }
18829 	else
18830 	  body = push_stmt_list ();
18831 	RECUR (OMP_FOR_BODY (t));
18832 	if (any_range_for)
18833 	  body = finish_omp_structured_block (body);
18834 	else
18835 	  body = pop_stmt_list (body);
18836 
18837 	if (OMP_FOR_INIT (t) != NULL_TREE)
18838 	  t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
18839 			      orig_declv, initv, condv, incrv, body, pre_body,
18840 			      NULL, clauses);
18841 	else
18842 	  {
18843 	    t = make_node (TREE_CODE (t));
18844 	    TREE_TYPE (t) = void_type_node;
18845 	    OMP_FOR_BODY (t) = body;
18846 	    OMP_FOR_PRE_BODY (t) = pre_body;
18847 	    OMP_FOR_CLAUSES (t) = clauses;
18848 	    SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
18849 	    add_stmt (t);
18850 	  }
18851 
18852 	add_stmt (finish_omp_for_block (finish_omp_structured_block (stmt),
18853 					t));
18854 	pop_omp_privatization_clauses (r);
18855       }
18856       break;
18857 
18858     case OMP_SECTIONS:
18859       omp_parallel_combined_clauses = NULL;
18860       /* FALLTHRU */
18861     case OMP_SINGLE:
18862     case OMP_TEAMS:
18863     case OMP_CRITICAL:
18864     case OMP_TASKGROUP:
18865     case OMP_SCAN:
18866       r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
18867 					  && OMP_TEAMS_COMBINED (t));
18868       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_OMP, args, complain,
18869 				in_decl);
18870       if (TREE_CODE (t) == OMP_TEAMS)
18871 	{
18872 	  keep_next_level (true);
18873 	  stmt = begin_omp_structured_block ();
18874 	  RECUR (OMP_BODY (t));
18875 	  stmt = finish_omp_structured_block (stmt);
18876 	}
18877       else
18878 	{
18879 	  stmt = push_stmt_list ();
18880 	  RECUR (OMP_BODY (t));
18881 	  stmt = pop_stmt_list (stmt);
18882 	}
18883 
18884       if (TREE_CODE (t) == OMP_CRITICAL
18885 	  && tmp != NULL_TREE
18886 	  && integer_nonzerop (OMP_CLAUSE_HINT_EXPR (tmp)))
18887 	{
18888 	  error_at (OMP_CLAUSE_LOCATION (tmp),
18889 		    "%<#pragma omp critical%> with %<hint%> clause requires "
18890 		    "a name, except when %<omp_sync_hint_none%> is used");
18891 	  RETURN (error_mark_node);
18892 	}
18893       t = copy_node (t);
18894       OMP_BODY (t) = stmt;
18895       OMP_CLAUSES (t) = tmp;
18896       add_stmt (t);
18897       pop_omp_privatization_clauses (r);
18898       break;
18899 
18900     case OMP_DEPOBJ:
18901       r = RECUR (OMP_DEPOBJ_DEPOBJ (t));
18902       if (OMP_DEPOBJ_CLAUSES (t) && OMP_DEPOBJ_CLAUSES (t) != error_mark_node)
18903 	{
18904 	  enum omp_clause_depend_kind kind = OMP_CLAUSE_DEPEND_SOURCE;
18905 	  if (TREE_CODE (OMP_DEPOBJ_CLAUSES (t)) == OMP_CLAUSE)
18906 	    {
18907 	      tmp = tsubst_omp_clauses (OMP_DEPOBJ_CLAUSES (t), C_ORT_OMP,
18908 					args, complain, in_decl);
18909 	      if (tmp == NULL_TREE)
18910 		tmp = error_mark_node;
18911 	    }
18912 	  else
18913 	    {
18914 	      kind = (enum omp_clause_depend_kind)
18915 		     tree_to_uhwi (OMP_DEPOBJ_CLAUSES (t));
18916 	      tmp = NULL_TREE;
18917 	    }
18918 	  finish_omp_depobj (EXPR_LOCATION (t), r, kind, tmp);
18919 	}
18920       else
18921 	finish_omp_depobj (EXPR_LOCATION (t), r,
18922 			   OMP_CLAUSE_DEPEND_SOURCE,
18923 			   OMP_DEPOBJ_CLAUSES (t));
18924       break;
18925 
18926     case OACC_DATA:
18927     case OMP_TARGET_DATA:
18928     case OMP_TARGET:
18929       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), (TREE_CODE (t) == OACC_DATA)
18930 				? C_ORT_ACC : C_ORT_OMP, args, complain,
18931 				in_decl);
18932       keep_next_level (true);
18933       stmt = begin_omp_structured_block ();
18934 
18935       RECUR (OMP_BODY (t));
18936       stmt = finish_omp_structured_block (stmt);
18937 
18938       t = copy_node (t);
18939       OMP_BODY (t) = stmt;
18940       OMP_CLAUSES (t) = tmp;
18941       if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
18942 	{
18943 	  tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
18944 	  if (teams)
18945 	    {
18946 	      /* For combined target teams, ensure the num_teams and
18947 		 thread_limit clause expressions are evaluated on the host,
18948 		 before entering the target construct.  */
18949 	      tree c;
18950 	      for (c = OMP_TEAMS_CLAUSES (teams);
18951 		   c; c = OMP_CLAUSE_CHAIN (c))
18952 		if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
18953 		     || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
18954 		    && TREE_CODE (OMP_CLAUSE_OPERAND (c, 0)) != INTEGER_CST)
18955 		  {
18956 		    tree expr = OMP_CLAUSE_OPERAND (c, 0);
18957 		    expr = force_target_expr (TREE_TYPE (expr), expr, tf_none);
18958 		    if (expr == error_mark_node)
18959 		      continue;
18960 		    tmp = TARGET_EXPR_SLOT (expr);
18961 		    add_stmt (expr);
18962 		    OMP_CLAUSE_OPERAND (c, 0) = expr;
18963 		    tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
18964 						OMP_CLAUSE_FIRSTPRIVATE);
18965 		    OMP_CLAUSE_DECL (tc) = tmp;
18966 		    OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
18967 		    OMP_TARGET_CLAUSES (t) = tc;
18968 		  }
18969 	    }
18970 	}
18971       add_stmt (t);
18972       break;
18973 
18974     case OACC_DECLARE:
18975       t = copy_node (t);
18976       tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), C_ORT_ACC, args,
18977 				complain, in_decl);
18978       OACC_DECLARE_CLAUSES (t) = tmp;
18979       add_stmt (t);
18980       break;
18981 
18982     case OMP_TARGET_UPDATE:
18983     case OMP_TARGET_ENTER_DATA:
18984     case OMP_TARGET_EXIT_DATA:
18985       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_OMP, args,
18986 				complain, in_decl);
18987       t = copy_node (t);
18988       OMP_STANDALONE_CLAUSES (t) = tmp;
18989       add_stmt (t);
18990       break;
18991 
18992     case OACC_CACHE:
18993     case OACC_ENTER_DATA:
18994     case OACC_EXIT_DATA:
18995     case OACC_UPDATE:
18996       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_ACC, args,
18997 				complain, in_decl);
18998       t = copy_node (t);
18999       OMP_STANDALONE_CLAUSES (t) = tmp;
19000       add_stmt (t);
19001       break;
19002 
19003     case OMP_ORDERED:
19004       tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), C_ORT_OMP, args,
19005 				complain, in_decl);
19006       stmt = push_stmt_list ();
19007       RECUR (OMP_BODY (t));
19008       stmt = pop_stmt_list (stmt);
19009 
19010       t = copy_node (t);
19011       OMP_BODY (t) = stmt;
19012       OMP_ORDERED_CLAUSES (t) = tmp;
19013       add_stmt (t);
19014       break;
19015 
19016     case OMP_MASTER:
19017       omp_parallel_combined_clauses = NULL;
19018       /* FALLTHRU */
19019     case OMP_SECTION:
19020       stmt = push_stmt_list ();
19021       RECUR (OMP_BODY (t));
19022       stmt = pop_stmt_list (stmt);
19023 
19024       t = copy_node (t);
19025       OMP_BODY (t) = stmt;
19026       add_stmt (t);
19027       break;
19028 
19029     case OMP_ATOMIC:
19030       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
19031       tmp = NULL_TREE;
19032       if (TREE_CODE (TREE_OPERAND (t, 0)) == OMP_CLAUSE)
19033 	tmp = tsubst_omp_clauses (TREE_OPERAND (t, 0), C_ORT_OMP, args,
19034 				  complain, in_decl);
19035       if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
19036 	{
19037 	  tree op1 = TREE_OPERAND (t, 1);
19038 	  tree rhs1 = NULL_TREE;
19039 	  tree lhs, rhs;
19040 	  if (TREE_CODE (op1) == COMPOUND_EXPR)
19041 	    {
19042 	      rhs1 = RECUR (TREE_OPERAND (op1, 0));
19043 	      op1 = TREE_OPERAND (op1, 1);
19044 	    }
19045 	  lhs = RECUR (TREE_OPERAND (op1, 0));
19046 	  rhs = RECUR (TREE_OPERAND (op1, 1));
19047 	  finish_omp_atomic (EXPR_LOCATION (t), OMP_ATOMIC, TREE_CODE (op1),
19048 			     lhs, rhs, NULL_TREE, NULL_TREE, rhs1, tmp,
19049 			     OMP_ATOMIC_MEMORY_ORDER (t));
19050 	}
19051       else
19052 	{
19053 	  tree op1 = TREE_OPERAND (t, 1);
19054 	  tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
19055 	  tree rhs1 = NULL_TREE;
19056 	  enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
19057 	  enum tree_code opcode = NOP_EXPR;
19058 	  if (code == OMP_ATOMIC_READ)
19059 	    {
19060 	      v = RECUR (TREE_OPERAND (op1, 0));
19061 	      lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19062 	    }
19063 	  else if (code == OMP_ATOMIC_CAPTURE_OLD
19064 		   || code == OMP_ATOMIC_CAPTURE_NEW)
19065 	    {
19066 	      tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
19067 	      v = RECUR (TREE_OPERAND (op1, 0));
19068 	      lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19069 	      if (TREE_CODE (op11) == COMPOUND_EXPR)
19070 		{
19071 		  rhs1 = RECUR (TREE_OPERAND (op11, 0));
19072 		  op11 = TREE_OPERAND (op11, 1);
19073 		}
19074 	      lhs = RECUR (TREE_OPERAND (op11, 0));
19075 	      rhs = RECUR (TREE_OPERAND (op11, 1));
19076 	      opcode = TREE_CODE (op11);
19077 	      if (opcode == MODIFY_EXPR)
19078 		opcode = NOP_EXPR;
19079 	    }
19080 	  else
19081 	    {
19082 	      code = OMP_ATOMIC;
19083 	      lhs = RECUR (TREE_OPERAND (op1, 0));
19084 	      rhs = RECUR (TREE_OPERAND (op1, 1));
19085 	    }
19086 	  finish_omp_atomic (EXPR_LOCATION (t), code, opcode, lhs, rhs, v,
19087 			     lhs1, rhs1, tmp, OMP_ATOMIC_MEMORY_ORDER (t));
19088 	}
19089       break;
19090 
19091     case TRANSACTION_EXPR:
19092       {
19093 	int flags = 0;
19094 	flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
19095 	flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
19096 
19097         if (TRANSACTION_EXPR_IS_STMT (t))
19098           {
19099 	    tree body = TRANSACTION_EXPR_BODY (t);
19100 	    tree noex = NULL_TREE;
19101 	    if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
19102 	      {
19103 		noex = MUST_NOT_THROW_COND (body);
19104 		if (noex == NULL_TREE)
19105 		  noex = boolean_true_node;
19106 		body = TREE_OPERAND (body, 0);
19107 	      }
19108             stmt = begin_transaction_stmt (input_location, NULL, flags);
19109             RECUR (body);
19110             finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
19111           }
19112         else
19113           {
19114             stmt = build_transaction_expr (EXPR_LOCATION (t),
19115 					   RECUR (TRANSACTION_EXPR_BODY (t)),
19116 					   flags, NULL_TREE);
19117             RETURN (stmt);
19118           }
19119       }
19120       break;
19121 
19122     case MUST_NOT_THROW_EXPR:
19123       {
19124 	tree op0 = RECUR (TREE_OPERAND (t, 0));
19125 	tree cond = RECUR (MUST_NOT_THROW_COND (t));
19126 	RETURN (build_must_not_throw_expr (op0, cond));
19127       }
19128 
19129     case EXPR_PACK_EXPANSION:
19130       error ("invalid use of pack expansion expression");
19131       RETURN (error_mark_node);
19132 
19133     case NONTYPE_ARGUMENT_PACK:
19134       error ("use %<...%> to expand argument pack");
19135       RETURN (error_mark_node);
19136 
19137     case COMPOUND_EXPR:
19138       tmp = RECUR (TREE_OPERAND (t, 0));
19139       if (tmp == NULL_TREE)
19140 	/* If the first operand was a statement, we're done with it.  */
19141 	RETURN (RECUR (TREE_OPERAND (t, 1)));
19142       RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
19143 				    RECUR (TREE_OPERAND (t, 1)),
19144 				    complain));
19145 
19146     case ANNOTATE_EXPR:
19147       tmp = RECUR (TREE_OPERAND (t, 0));
19148       RETURN (build3_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
19149 			  TREE_TYPE (tmp), tmp,
19150 			  RECUR (TREE_OPERAND (t, 1)),
19151 			  RECUR (TREE_OPERAND (t, 2))));
19152 
19153     case PREDICT_EXPR:
19154       RETURN (add_stmt (copy_node (t)));
19155 
19156     default:
19157       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
19158 
19159       RETURN (tsubst_copy_and_build (t, args, complain, in_decl,
19160 				    /*function_p=*/false,
19161 				    integral_constant_expression_p));
19162     }
19163 
19164   RETURN (NULL_TREE);
19165  out:
19166   input_location = loc;
19167   return r;
19168 #undef RECUR
19169 #undef RETURN
19170 }
19171 
19172 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
19173    function.  For description of the body see comment above
19174    cp_parser_omp_declare_reduction_exprs.  */
19175 
19176 static void
tsubst_omp_udr(tree t,tree args,tsubst_flags_t complain,tree in_decl)19177 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19178 {
19179   if (t == NULL_TREE || t == error_mark_node)
19180     return;
19181 
19182   gcc_assert (TREE_CODE (t) == STATEMENT_LIST && current_function_decl);
19183 
19184   tree_stmt_iterator tsi;
19185   int i;
19186   tree stmts[7];
19187   memset (stmts, 0, sizeof stmts);
19188   for (i = 0, tsi = tsi_start (t);
19189        i < 7 && !tsi_end_p (tsi);
19190        i++, tsi_next (&tsi))
19191     stmts[i] = tsi_stmt (tsi);
19192   gcc_assert (tsi_end_p (tsi));
19193 
19194   if (i >= 3)
19195     {
19196       gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
19197 		  && TREE_CODE (stmts[1]) == DECL_EXPR);
19198       tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
19199 			     args, complain, in_decl);
19200       tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
19201 			    args, complain, in_decl);
19202       /* tsubsting a local var_decl leaves DECL_CONTEXT null, as we
19203 	 expect to be pushing it.  */
19204       DECL_CONTEXT (omp_out) = current_function_decl;
19205       DECL_CONTEXT (omp_in) = current_function_decl;
19206       keep_next_level (true);
19207       tree block = begin_omp_structured_block ();
19208       tsubst_expr (stmts[2], args, complain, in_decl, false);
19209       block = finish_omp_structured_block (block);
19210       block = maybe_cleanup_point_expr_void (block);
19211       add_decl_expr (omp_out);
19212       if (TREE_NO_WARNING (DECL_EXPR_DECL (stmts[0])))
19213 	TREE_NO_WARNING (omp_out) = 1;
19214       add_decl_expr (omp_in);
19215       finish_expr_stmt (block);
19216     }
19217   if (i >= 6)
19218     {
19219       gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
19220 		  && TREE_CODE (stmts[4]) == DECL_EXPR);
19221       tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
19222 			      args, complain, in_decl);
19223       tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
19224 			      args, complain, in_decl);
19225       DECL_CONTEXT (omp_priv) = current_function_decl;
19226       DECL_CONTEXT (omp_orig) = current_function_decl;
19227       keep_next_level (true);
19228       tree block = begin_omp_structured_block ();
19229       tsubst_expr (stmts[5], args, complain, in_decl, false);
19230       block = finish_omp_structured_block (block);
19231       block = maybe_cleanup_point_expr_void (block);
19232       cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
19233       add_decl_expr (omp_priv);
19234       add_decl_expr (omp_orig);
19235       finish_expr_stmt (block);
19236       if (i == 7)
19237 	add_decl_expr (omp_orig);
19238     }
19239 }
19240 
19241 /* T is a postfix-expression that is not being used in a function
19242    call.  Return the substituted version of T.  */
19243 
19244 static tree
tsubst_non_call_postfix_expression(tree t,tree args,tsubst_flags_t complain,tree in_decl)19245 tsubst_non_call_postfix_expression (tree t, tree args,
19246 				    tsubst_flags_t complain,
19247 				    tree in_decl)
19248 {
19249   if (TREE_CODE (t) == SCOPE_REF)
19250     t = tsubst_qualified_id (t, args, complain, in_decl,
19251 			     /*done=*/false, /*address_p=*/false);
19252   else
19253     t = tsubst_copy_and_build (t, args, complain, in_decl,
19254 			       /*function_p=*/false,
19255 			       /*integral_constant_expression_p=*/false);
19256 
19257   return t;
19258 }
19259 
19260 /* Subroutine of tsubst_lambda_expr: add the FIELD/INIT capture pair to the
19261    LAMBDA_EXPR_CAPTURE_LIST passed in LIST.  Do deduction for a previously
19262    dependent init-capture.  */
19263 
19264 static void
prepend_one_capture(tree field,tree init,tree & list,tsubst_flags_t complain)19265 prepend_one_capture (tree field, tree init, tree &list,
19266 		     tsubst_flags_t complain)
19267 {
19268   if (tree auto_node = type_uses_auto (TREE_TYPE (field)))
19269     {
19270       tree type = NULL_TREE;
19271       if (!init)
19272 	{
19273 	  if (complain & tf_error)
19274 	    error ("empty initializer in lambda init-capture");
19275 	  init = error_mark_node;
19276 	}
19277       else if (TREE_CODE (init) == TREE_LIST)
19278 	init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19279       if (!type)
19280 	type = do_auto_deduction (TREE_TYPE (field), init, auto_node, complain);
19281       TREE_TYPE (field) = type;
19282       cp_apply_type_quals_to_decl (cp_type_quals (type), field);
19283     }
19284   list = tree_cons (field, init, list);
19285 }
19286 
19287 /* T is a LAMBDA_EXPR.  Generate a new LAMBDA_EXPR for the current
19288    instantiation context.  Instantiating a pack expansion containing a lambda
19289    might result in multiple lambdas all based on the same lambda in the
19290    template.  */
19291 
19292 tree
tsubst_lambda_expr(tree t,tree args,tsubst_flags_t complain,tree in_decl)19293 tsubst_lambda_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19294 {
19295   tree oldfn = lambda_function (t);
19296   in_decl = oldfn;
19297 
19298   tree r = build_lambda_expr ();
19299 
19300   LAMBDA_EXPR_LOCATION (r)
19301     = LAMBDA_EXPR_LOCATION (t);
19302   LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
19303     = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
19304   LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
19305   if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
19306     LAMBDA_EXPR_REGEN_INFO (r)
19307       = build_template_info (t, add_to_template_args (TI_ARGS (ti), args));
19308   else
19309     LAMBDA_EXPR_REGEN_INFO (r)
19310       = build_template_info (t, args);
19311 
19312   gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
19313 	      && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
19314 
19315   vec<tree,va_gc>* field_packs = NULL;
19316 
19317   for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t); cap;
19318        cap = TREE_CHAIN (cap))
19319     {
19320       tree ofield = TREE_PURPOSE (cap);
19321       tree init = TREE_VALUE (cap);
19322       if (PACK_EXPANSION_P (init))
19323 	init = tsubst_pack_expansion (init, args, complain, in_decl);
19324       else
19325 	init = tsubst_copy_and_build (init, args, complain, in_decl,
19326 				      /*fn*/false, /*constexpr*/false);
19327 
19328       if (init == error_mark_node)
19329 	return error_mark_node;
19330 
19331       if (init && TREE_CODE (init) == TREE_LIST)
19332 	init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19333 
19334       if (!processing_template_decl
19335 	  && init && TREE_CODE (init) != TREE_VEC
19336 	  && variably_modified_type_p (TREE_TYPE (init), NULL_TREE))
19337 	{
19338 	  /* For a VLA, simply tsubsting the field type won't work, we need to
19339 	     go through add_capture again.  XXX do we want to do this for all
19340 	     captures?  */
19341 	  tree name = (get_identifier
19342 		       (IDENTIFIER_POINTER (DECL_NAME (ofield)) + 2));
19343 	  tree ftype = TREE_TYPE (ofield);
19344 	  bool by_ref = (TYPE_REF_P (ftype)
19345 			 || (TREE_CODE (ftype) == DECLTYPE_TYPE
19346 			     && DECLTYPE_FOR_REF_CAPTURE (ftype)));
19347 	  add_capture (r, name, init, by_ref, !DECL_NORMAL_CAPTURE_P (ofield));
19348 	  continue;
19349 	}
19350 
19351       if (PACK_EXPANSION_P (ofield))
19352 	ofield = PACK_EXPANSION_PATTERN (ofield);
19353       tree field = tsubst_decl (ofield, args, complain);
19354 
19355       if (DECL_PACK_P (ofield) && !DECL_NORMAL_CAPTURE_P (ofield))
19356 	{
19357 	  /* Remember these for when we've pushed local_specializations.  */
19358 	  vec_safe_push (field_packs, ofield);
19359 	  vec_safe_push (field_packs, field);
19360 	}
19361 
19362       if (field == error_mark_node)
19363 	return error_mark_node;
19364 
19365       if (TREE_CODE (field) == TREE_VEC)
19366 	{
19367 	  int len = TREE_VEC_LENGTH (field);
19368 	  gcc_assert (TREE_CODE (init) == TREE_VEC
19369 		      && TREE_VEC_LENGTH (init) == len);
19370 	  for (int i = 0; i < len; ++i)
19371 	    prepend_one_capture (TREE_VEC_ELT (field, i),
19372 				 TREE_VEC_ELT (init, i),
19373 				 LAMBDA_EXPR_CAPTURE_LIST (r),
19374 				 complain);
19375 	}
19376       else
19377 	{
19378 	  prepend_one_capture (field, init, LAMBDA_EXPR_CAPTURE_LIST (r),
19379 			       complain);
19380 
19381 	  if (id_equal (DECL_NAME (field), "__this"))
19382 	    LAMBDA_EXPR_THIS_CAPTURE (r) = field;
19383 	}
19384     }
19385 
19386   tree type = begin_lambda_type (r);
19387   if (type == error_mark_node)
19388     return error_mark_node;
19389 
19390   if (LAMBDA_EXPR_EXTRA_SCOPE (t) == NULL_TREE)
19391     /* A lambda in a default argument outside a class gets no
19392        LAMBDA_EXPR_EXTRA_SCOPE, as specified by the ABI.  But
19393        tsubst_default_argument calls start_lambda_scope, so we need to
19394        specifically ignore it here, and use the global scope.  */
19395     record_null_lambda_scope (r);
19396   else
19397     record_lambda_scope (r);
19398 
19399   /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
19400   determine_visibility (TYPE_NAME (type));
19401 
19402   register_capture_members (LAMBDA_EXPR_CAPTURE_LIST (r));
19403 
19404   tree oldtmpl = (generic_lambda_fn_p (oldfn)
19405 		  ? DECL_TI_TEMPLATE (oldfn)
19406 		  : NULL_TREE);
19407 
19408   tree fntype = static_fn_type (oldfn);
19409   if (oldtmpl)
19410     ++processing_template_decl;
19411   fntype = tsubst (fntype, args, complain, in_decl);
19412   if (oldtmpl)
19413     --processing_template_decl;
19414 
19415   if (fntype == error_mark_node)
19416     r = error_mark_node;
19417   else
19418     {
19419       /* The body of a lambda-expression is not a subexpression of the
19420 	 enclosing expression.  Parms are to have DECL_CHAIN tsubsted,
19421 	 which would be skipped if cp_unevaluated_operand.  */
19422       cp_evaluated ev;
19423 
19424       /* Fix the type of 'this'.  */
19425       fntype = build_memfn_type (fntype, type,
19426 				 type_memfn_quals (fntype),
19427 				 type_memfn_rqual (fntype));
19428       tree fn, tmpl;
19429       if (oldtmpl)
19430 	{
19431 	  tmpl = tsubst_template_decl (oldtmpl, args, complain, fntype);
19432 	  if (tmpl == error_mark_node)
19433 	    {
19434 	      r = error_mark_node;
19435 	      goto out;
19436 	    }
19437 	  fn = DECL_TEMPLATE_RESULT (tmpl);
19438 	  finish_member_declaration (tmpl);
19439 	}
19440       else
19441 	{
19442 	  tmpl = NULL_TREE;
19443 	  fn = tsubst_function_decl (oldfn, args, complain, fntype);
19444 	  if (fn == error_mark_node)
19445 	    {
19446 	      r = error_mark_node;
19447 	      goto out;
19448 	    }
19449 	  finish_member_declaration (fn);
19450 	}
19451 
19452       /* Let finish_function set this.  */
19453       DECL_DECLARED_CONSTEXPR_P (fn) = false;
19454 
19455       bool nested = cfun;
19456       if (nested)
19457 	push_function_context ();
19458       else
19459 	/* Still increment function_depth so that we don't GC in the
19460 	   middle of an expression.  */
19461 	++function_depth;
19462 
19463       local_specialization_stack s (lss_copy);
19464 
19465       tree body = start_lambda_function (fn, r);
19466 
19467       /* Now record them for lookup_init_capture_pack.  */
19468       int fplen = vec_safe_length (field_packs);
19469       for (int i = 0; i < fplen; )
19470 	{
19471 	  tree pack = (*field_packs)[i++];
19472 	  tree inst = (*field_packs)[i++];
19473 	  register_local_specialization (inst, pack);
19474 	}
19475       release_tree_vector (field_packs);
19476 
19477       register_parameter_specializations (oldfn, fn);
19478 
19479       if (oldtmpl)
19480 	{
19481 	  /* We might not partially instantiate some parts of the function, so
19482 	     copy these flags from the original template.  */
19483 	  language_function *ol = DECL_STRUCT_FUNCTION (oldfn)->language;
19484 	  current_function_returns_value = ol->returns_value;
19485 	  current_function_returns_null = ol->returns_null;
19486 	  current_function_returns_abnormally = ol->returns_abnormally;
19487 	  current_function_infinite_loop = ol->infinite_loop;
19488 	}
19489 
19490       /* [temp.deduct] A lambda-expression appearing in a function type or a
19491 	 template parameter is not considered part of the immediate context for
19492 	 the purposes of template argument deduction. */
19493       complain = tf_warning_or_error;
19494 
19495       tree saved = DECL_SAVED_TREE (oldfn);
19496       if (TREE_CODE (saved) == BIND_EXPR && BIND_EXPR_BODY_BLOCK (saved))
19497 	/* We already have a body block from start_lambda_function, we don't
19498 	   need another to confuse NRV (91217).  */
19499 	saved = BIND_EXPR_BODY (saved);
19500 
19501       tsubst_expr (saved, args, complain, r, /*constexpr*/false);
19502 
19503       finish_lambda_function (body);
19504 
19505       if (nested)
19506 	pop_function_context ();
19507       else
19508 	--function_depth;
19509 
19510       /* The capture list was built up in reverse order; fix that now.  */
19511       LAMBDA_EXPR_CAPTURE_LIST (r)
19512 	= nreverse (LAMBDA_EXPR_CAPTURE_LIST (r));
19513 
19514       LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
19515 
19516       maybe_add_lambda_conv_op (type);
19517     }
19518 
19519 out:
19520   finish_struct (type, /*attr*/NULL_TREE);
19521 
19522   insert_pending_capture_proxies ();
19523 
19524   return r;
19525 }
19526 
19527 /* Like tsubst but deals with expressions and performs semantic
19528    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)" or
19529    "F<TARGS> (ARGS)".  */
19530 
19531 tree
tsubst_copy_and_build(tree t,tree args,tsubst_flags_t complain,tree in_decl,bool function_p,bool integral_constant_expression_p)19532 tsubst_copy_and_build (tree t,
19533 		       tree args,
19534 		       tsubst_flags_t complain,
19535 		       tree in_decl,
19536 		       bool function_p,
19537 		       bool integral_constant_expression_p)
19538 {
19539 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
19540 #define RECUR(NODE)						\
19541   tsubst_copy_and_build (NODE, args, complain, in_decl, 	\
19542 			 /*function_p=*/false,			\
19543 			 integral_constant_expression_p)
19544 
19545   tree retval, op1;
19546   location_t save_loc;
19547 
19548   if (t == NULL_TREE || t == error_mark_node)
19549     return t;
19550 
19551   save_loc = input_location;
19552   if (location_t eloc = cp_expr_location (t))
19553     input_location = eloc;
19554 
19555   /* N3276 decltype magic only applies to calls at the top level or on the
19556      right side of a comma.  */
19557   tsubst_flags_t decltype_flag = (complain & tf_decltype);
19558   complain &= ~tf_decltype;
19559 
19560   switch (TREE_CODE (t))
19561     {
19562     case USING_DECL:
19563       t = DECL_NAME (t);
19564       /* Fall through.  */
19565     case IDENTIFIER_NODE:
19566       {
19567 	tree decl;
19568 	cp_id_kind idk;
19569 	bool non_integral_constant_expression_p;
19570 	const char *error_msg;
19571 
19572 	if (IDENTIFIER_CONV_OP_P (t))
19573 	  {
19574 	    tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19575 	    t = make_conv_op_name (new_type);
19576 	  }
19577 
19578 	/* Look up the name.  */
19579 	decl = lookup_name (t);
19580 
19581 	/* By convention, expressions use ERROR_MARK_NODE to indicate
19582 	   failure, not NULL_TREE.  */
19583 	if (decl == NULL_TREE)
19584 	  decl = error_mark_node;
19585 
19586 	decl = finish_id_expression (t, decl, NULL_TREE,
19587 				     &idk,
19588 				     integral_constant_expression_p,
19589           /*allow_non_integral_constant_expression_p=*/(cxx_dialect >= cxx11),
19590 				     &non_integral_constant_expression_p,
19591 				     /*template_p=*/false,
19592 				     /*done=*/true,
19593 				     /*address_p=*/false,
19594 				     /*template_arg_p=*/false,
19595 				     &error_msg,
19596 				     input_location);
19597 	if (error_msg)
19598 	  error (error_msg);
19599 	if (!function_p && identifier_p (decl))
19600 	  {
19601 	    if (complain & tf_error)
19602 	      unqualified_name_lookup_error (decl);
19603 	    decl = error_mark_node;
19604 	  }
19605 	RETURN (decl);
19606       }
19607 
19608     case TEMPLATE_ID_EXPR:
19609       {
19610 	tree object;
19611 	tree templ = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
19612 					    complain, in_decl,
19613 					    function_p,
19614 					    integral_constant_expression_p);
19615 	tree targs = TREE_OPERAND (t, 1);
19616 
19617 	if (targs)
19618 	  targs = tsubst_template_args (targs, args, complain, in_decl);
19619 	if (targs == error_mark_node)
19620 	  RETURN (error_mark_node);
19621 
19622 	if (TREE_CODE (templ) == SCOPE_REF)
19623 	  {
19624 	    tree name = TREE_OPERAND (templ, 1);
19625 	    tree tid = lookup_template_function (name, targs);
19626 	    TREE_OPERAND (templ, 1) = tid;
19627 	    RETURN (templ);
19628 	  }
19629 
19630 	if (concept_definition_p (templ))
19631 	  {
19632 	    tree check = build_concept_check (templ, targs, complain);
19633 	    if (check == error_mark_node)
19634 	      RETURN (error_mark_node);
19635 
19636 	    tree id = unpack_concept_check (check);
19637 
19638 	    /* If we built a function concept check, return the underlying
19639 	       template-id. So we can evaluate it as a function call.  */
19640 	    if (function_concept_p (TREE_OPERAND (id, 0)))
19641 	      RETURN (id);
19642 
19643 	    RETURN (check);
19644 	  }
19645 
19646 	if (variable_template_p (templ))
19647 	  {
19648 	    tree r = lookup_and_finish_template_variable (templ, targs,
19649 							  complain);
19650 	    r = maybe_wrap_with_location (r, EXPR_LOCATION (t));
19651 	    RETURN (r);
19652 	  }
19653 
19654 	if (TREE_CODE (templ) == COMPONENT_REF)
19655 	  {
19656 	    object = TREE_OPERAND (templ, 0);
19657 	    templ = TREE_OPERAND (templ, 1);
19658 	  }
19659 	else
19660 	  object = NULL_TREE;
19661 
19662 	tree tid = lookup_template_function (templ, targs);
19663 
19664 	if (object)
19665 	  RETURN (build3 (COMPONENT_REF, TREE_TYPE (tid),
19666 			 object, tid, NULL_TREE));
19667 	else if (identifier_p (templ))
19668 	  {
19669 	    /* C++20 P0846: we can encounter an IDENTIFIER_NODE here when
19670 	       name lookup found nothing when parsing the template name.  */
19671 	    gcc_assert (cxx_dialect >= cxx20 || seen_error ());
19672 	    RETURN (tid);
19673 	  }
19674 	else
19675 	  RETURN (baselink_for_fns (tid));
19676       }
19677 
19678     case INDIRECT_REF:
19679       {
19680 	tree r = RECUR (TREE_OPERAND (t, 0));
19681 
19682 	if (REFERENCE_REF_P (t))
19683 	  {
19684 	    /* A type conversion to reference type will be enclosed in
19685 	       such an indirect ref, but the substitution of the cast
19686 	       will have also added such an indirect ref.  */
19687 	    r = convert_from_reference (r);
19688 	  }
19689 	else
19690 	  r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
19691 				    complain|decltype_flag);
19692 
19693 	if (REF_PARENTHESIZED_P (t))
19694 	  r = force_paren_expr (r);
19695 
19696 	RETURN (r);
19697       }
19698 
19699     case NOP_EXPR:
19700       {
19701 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19702 	tree op0 = RECUR (TREE_OPERAND (t, 0));
19703 	RETURN (build_nop (type, op0));
19704       }
19705 
19706     case IMPLICIT_CONV_EXPR:
19707       {
19708 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19709 	tree expr = RECUR (TREE_OPERAND (t, 0));
19710 	if (dependent_type_p (type) || type_dependent_expression_p (expr))
19711 	  {
19712 	    retval = copy_node (t);
19713 	    TREE_TYPE (retval) = type;
19714 	    TREE_OPERAND (retval, 0) = expr;
19715 	    RETURN (retval);
19716 	  }
19717 	if (IMPLICIT_CONV_EXPR_NONTYPE_ARG (t))
19718 	  /* We'll pass this to convert_nontype_argument again, we don't need
19719 	     to actually perform any conversion here.  */
19720 	  RETURN (expr);
19721 	int flags = LOOKUP_IMPLICIT;
19722 	if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
19723 	  flags = LOOKUP_NORMAL;
19724 	if (IMPLICIT_CONV_EXPR_BRACED_INIT (t))
19725 	  flags |= LOOKUP_NO_NARROWING;
19726 	RETURN (perform_implicit_conversion_flags (type, expr, complain,
19727 						  flags));
19728       }
19729 
19730     case CONVERT_EXPR:
19731       {
19732 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19733 	tree op0 = RECUR (TREE_OPERAND (t, 0));
19734 	if (op0 == error_mark_node)
19735 	  RETURN (error_mark_node);
19736 	RETURN (build1 (CONVERT_EXPR, type, op0));
19737       }
19738 
19739     case CAST_EXPR:
19740     case REINTERPRET_CAST_EXPR:
19741     case CONST_CAST_EXPR:
19742     case DYNAMIC_CAST_EXPR:
19743     case STATIC_CAST_EXPR:
19744       {
19745 	tree type;
19746 	tree op, r = NULL_TREE;
19747 
19748 	type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19749 	if (integral_constant_expression_p
19750 	    && !cast_valid_in_integral_constant_expression_p (type))
19751 	  {
19752             if (complain & tf_error)
19753               error ("a cast to a type other than an integral or "
19754                      "enumeration type cannot appear in a constant-expression");
19755 	    RETURN (error_mark_node);
19756 	  }
19757 
19758 	op = RECUR (TREE_OPERAND (t, 0));
19759 
19760 	warning_sentinel s(warn_useless_cast);
19761 	warning_sentinel s2(warn_ignored_qualifiers);
19762 	switch (TREE_CODE (t))
19763 	  {
19764 	  case CAST_EXPR:
19765 	    r = build_functional_cast (input_location, type, op, complain);
19766 	    break;
19767 	  case REINTERPRET_CAST_EXPR:
19768 	    r = build_reinterpret_cast (input_location, type, op, complain);
19769 	    break;
19770 	  case CONST_CAST_EXPR:
19771 	    r = build_const_cast (input_location, type, op, complain);
19772 	    break;
19773 	  case DYNAMIC_CAST_EXPR:
19774 	    r = build_dynamic_cast (input_location, type, op, complain);
19775 	    break;
19776 	  case STATIC_CAST_EXPR:
19777 	    r = build_static_cast (input_location, type, op, complain);
19778 	    if (IMPLICIT_RVALUE_P (t))
19779 	      set_implicit_rvalue_p (r);
19780 	    break;
19781 	  default:
19782 	    gcc_unreachable ();
19783 	  }
19784 
19785 	RETURN (r);
19786       }
19787 
19788     case BIT_CAST_EXPR:
19789       {
19790 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19791 	tree op0 = RECUR (TREE_OPERAND (t, 0));
19792 	RETURN (cp_build_bit_cast (EXPR_LOCATION (t), type, op0, complain));
19793       }
19794 
19795     case POSTDECREMENT_EXPR:
19796     case POSTINCREMENT_EXPR:
19797       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
19798 						args, complain, in_decl);
19799       RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
19800 				complain|decltype_flag));
19801 
19802     case PREDECREMENT_EXPR:
19803     case PREINCREMENT_EXPR:
19804     case NEGATE_EXPR:
19805     case BIT_NOT_EXPR:
19806     case ABS_EXPR:
19807     case TRUTH_NOT_EXPR:
19808     case UNARY_PLUS_EXPR:  /* Unary + */
19809     case REALPART_EXPR:
19810     case IMAGPART_EXPR:
19811       RETURN (build_x_unary_op (input_location, TREE_CODE (t),
19812 				RECUR (TREE_OPERAND (t, 0)),
19813 				complain|decltype_flag));
19814 
19815     case FIX_TRUNC_EXPR:
19816       /* convert_like should have created an IMPLICIT_CONV_EXPR.  */
19817       gcc_unreachable ();
19818 
19819     case ADDR_EXPR:
19820       op1 = TREE_OPERAND (t, 0);
19821       if (TREE_CODE (op1) == LABEL_DECL)
19822 	RETURN (finish_label_address_expr (DECL_NAME (op1),
19823 					  EXPR_LOCATION (op1)));
19824       if (TREE_CODE (op1) == SCOPE_REF)
19825 	op1 = tsubst_qualified_id (op1, args, complain, in_decl,
19826 				   /*done=*/true, /*address_p=*/true);
19827       else
19828 	op1 = tsubst_non_call_postfix_expression (op1, args, complain,
19829 						  in_decl);
19830       RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
19831 				complain|decltype_flag));
19832 
19833     case PLUS_EXPR:
19834     case MINUS_EXPR:
19835     case MULT_EXPR:
19836     case TRUNC_DIV_EXPR:
19837     case CEIL_DIV_EXPR:
19838     case FLOOR_DIV_EXPR:
19839     case ROUND_DIV_EXPR:
19840     case EXACT_DIV_EXPR:
19841     case BIT_AND_EXPR:
19842     case BIT_IOR_EXPR:
19843     case BIT_XOR_EXPR:
19844     case TRUNC_MOD_EXPR:
19845     case FLOOR_MOD_EXPR:
19846     case TRUTH_ANDIF_EXPR:
19847     case TRUTH_ORIF_EXPR:
19848     case TRUTH_AND_EXPR:
19849     case TRUTH_OR_EXPR:
19850     case RSHIFT_EXPR:
19851     case LSHIFT_EXPR:
19852     case EQ_EXPR:
19853     case NE_EXPR:
19854     case MAX_EXPR:
19855     case MIN_EXPR:
19856     case LE_EXPR:
19857     case GE_EXPR:
19858     case LT_EXPR:
19859     case GT_EXPR:
19860     case SPACESHIP_EXPR:
19861     case MEMBER_REF:
19862     case DOTSTAR_EXPR:
19863       {
19864 	/* If either OP0 or OP1 was value- or type-dependent, suppress
19865 	   warnings that depend on the range of the types involved.  */
19866 	tree op0 = TREE_OPERAND (t, 0);
19867 	tree op1 = TREE_OPERAND (t, 1);
19868 	auto dep_p = [](tree t) {
19869 	  ++processing_template_decl;
19870 	  bool r = (potential_constant_expression (t)
19871 		    ? value_dependent_expression_p (t)
19872 		    : type_dependent_expression_p (t));
19873 	  --processing_template_decl;
19874 	  return r;
19875 	};
19876 	const bool was_dep = dep_p (op0) || dep_p (op1);
19877 	op0 = RECUR (op0);
19878 	op1 = RECUR (op1);
19879 
19880 	warning_sentinel s1(warn_type_limits, was_dep);
19881 	warning_sentinel s2(warn_div_by_zero, was_dep);
19882 	warning_sentinel s3(warn_logical_op, was_dep);
19883 	warning_sentinel s4(warn_tautological_compare, was_dep);
19884 
19885 	tree r = build_x_binary_op
19886 	  (input_location, TREE_CODE (t),
19887 	   op0,
19888 	   (TREE_NO_WARNING (TREE_OPERAND (t, 0))
19889 	    ? ERROR_MARK
19890 	    : TREE_CODE (TREE_OPERAND (t, 0))),
19891 	   op1,
19892 	   (TREE_NO_WARNING (TREE_OPERAND (t, 1))
19893 	    ? ERROR_MARK
19894 	    : TREE_CODE (TREE_OPERAND (t, 1))),
19895 	   /*overload=*/NULL,
19896 	   complain|decltype_flag);
19897 	if (EXPR_P (r) && TREE_NO_WARNING (t))
19898 	  TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
19899 
19900 	RETURN (r);
19901       }
19902 
19903     case POINTER_PLUS_EXPR:
19904       {
19905 	tree op0 = RECUR (TREE_OPERAND (t, 0));
19906 	if (op0 == error_mark_node)
19907 	  RETURN (error_mark_node);
19908 	tree op1 = RECUR (TREE_OPERAND (t, 1));
19909 	if (op1 == error_mark_node)
19910 	  RETURN (error_mark_node);
19911 	RETURN (fold_build_pointer_plus (op0, op1));
19912       }
19913 
19914     case SCOPE_REF:
19915       RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
19916 				  /*address_p=*/false));
19917 
19918     case BASELINK:
19919       RETURN (tsubst_baselink (t, current_nonlambda_class_type (),
19920 			       args, complain, in_decl));
19921 
19922     case ARRAY_REF:
19923       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
19924 						args, complain, in_decl);
19925       RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
19926 				 RECUR (TREE_OPERAND (t, 1)),
19927 				 complain|decltype_flag));
19928 
19929     case SIZEOF_EXPR:
19930       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
19931 	  || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
19932 	RETURN (tsubst_copy (t, args, complain, in_decl));
19933       /* Fall through */
19934 
19935     case ALIGNOF_EXPR:
19936       {
19937 	tree r;
19938 
19939 	op1 = TREE_OPERAND (t, 0);
19940 	if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
19941 	  op1 = TREE_TYPE (op1);
19942 	bool std_alignof = (TREE_CODE (t) == ALIGNOF_EXPR
19943 			    && ALIGNOF_EXPR_STD_P (t));
19944         if (!args)
19945 	  {
19946 	    /* When there are no ARGS, we are trying to evaluate a
19947 	       non-dependent expression from the parser.  Trying to do
19948 	       the substitutions may not work.  */
19949 	    if (!TYPE_P (op1))
19950 	      op1 = TREE_TYPE (op1);
19951 	  }
19952 	else
19953 	  {
19954 	    ++cp_unevaluated_operand;
19955 	    ++c_inhibit_evaluation_warnings;
19956 	    if (TYPE_P (op1))
19957 	      op1 = tsubst (op1, args, complain, in_decl);
19958 	    else
19959 	      op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
19960 					   /*function_p=*/false,
19961 					   /*integral_constant_expression_p=*/
19962 					   false);
19963 	    --cp_unevaluated_operand;
19964 	    --c_inhibit_evaluation_warnings;
19965 	  }
19966         if (TYPE_P (op1))
19967 	  r = cxx_sizeof_or_alignof_type (input_location,
19968 					  op1, TREE_CODE (t), std_alignof,
19969 					  complain & tf_error);
19970 	else
19971 	  r = cxx_sizeof_or_alignof_expr (input_location,
19972 					  op1, TREE_CODE (t), std_alignof,
19973 					  complain & tf_error);
19974 	if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
19975 	  {
19976 	    if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
19977 	      {
19978 		if (!processing_template_decl && TYPE_P (op1))
19979 		  {
19980 		    r = build_min (SIZEOF_EXPR, size_type_node,
19981 				   build1 (NOP_EXPR, op1, error_mark_node));
19982 		    SIZEOF_EXPR_TYPE_P (r) = 1;
19983 		  }
19984 		else
19985 		  r = build_min (SIZEOF_EXPR, size_type_node, op1);
19986 		TREE_SIDE_EFFECTS (r) = 0;
19987 		TREE_READONLY (r) = 1;
19988 	      }
19989 	    SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
19990 	  }
19991 	RETURN (r);
19992       }
19993 
19994     case AT_ENCODE_EXPR:
19995       {
19996 	op1 = TREE_OPERAND (t, 0);
19997 	++cp_unevaluated_operand;
19998 	++c_inhibit_evaluation_warnings;
19999 	op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
20000 				     /*function_p=*/false,
20001 				     /*integral_constant_expression_p=*/false);
20002 	--cp_unevaluated_operand;
20003 	--c_inhibit_evaluation_warnings;
20004 	RETURN (objc_build_encode_expr (op1));
20005       }
20006 
20007     case NOEXCEPT_EXPR:
20008       op1 = TREE_OPERAND (t, 0);
20009       ++cp_unevaluated_operand;
20010       ++c_inhibit_evaluation_warnings;
20011       ++cp_noexcept_operand;
20012       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
20013 				   /*function_p=*/false,
20014 				   /*integral_constant_expression_p=*/false);
20015       --cp_unevaluated_operand;
20016       --c_inhibit_evaluation_warnings;
20017       --cp_noexcept_operand;
20018       RETURN (finish_noexcept_expr (op1, complain));
20019 
20020     case MODOP_EXPR:
20021       {
20022 	warning_sentinel s(warn_div_by_zero);
20023 	tree lhs = RECUR (TREE_OPERAND (t, 0));
20024 	tree rhs = RECUR (TREE_OPERAND (t, 2));
20025 	tree r = build_x_modify_expr
20026 	  (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
20027 	   complain|decltype_flag);
20028 	/* TREE_NO_WARNING must be set if either the expression was
20029 	   parenthesized or it uses an operator such as >>= rather
20030 	   than plain assignment.  In the former case, it was already
20031 	   set and must be copied.  In the latter case,
20032 	   build_x_modify_expr sets it and it must not be reset
20033 	   here.  */
20034 	if (TREE_NO_WARNING (t))
20035 	  TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
20036 
20037 	RETURN (r);
20038       }
20039 
20040     case ARROW_EXPR:
20041       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20042 						args, complain, in_decl);
20043       /* Remember that there was a reference to this entity.  */
20044       if (DECL_P (op1)
20045 	  && !mark_used (op1, complain) && !(complain & tf_error))
20046 	RETURN (error_mark_node);
20047       RETURN (build_x_arrow (input_location, op1, complain));
20048 
20049     case NEW_EXPR:
20050       {
20051 	tree placement = RECUR (TREE_OPERAND (t, 0));
20052 	tree init = RECUR (TREE_OPERAND (t, 3));
20053 	vec<tree, va_gc> *placement_vec;
20054 	vec<tree, va_gc> *init_vec;
20055 	tree ret;
20056 	location_t loc = EXPR_LOCATION (t);
20057 
20058 	if (placement == NULL_TREE)
20059 	  placement_vec = NULL;
20060 	else if (placement == error_mark_node)
20061 	  RETURN (error_mark_node);
20062 	else
20063 	  {
20064 	    placement_vec = make_tree_vector ();
20065 	    for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
20066 	      vec_safe_push (placement_vec, TREE_VALUE (placement));
20067 	  }
20068 
20069 	/* If there was an initializer in the original tree, but it
20070 	   instantiated to an empty list, then we should pass a
20071 	   non-NULL empty vector to tell build_new that it was an
20072 	   empty initializer() rather than no initializer.  This can
20073 	   only happen when the initializer is a pack expansion whose
20074 	   parameter packs are of length zero.  */
20075 	if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
20076 	  init_vec = NULL;
20077 	else if (init == error_mark_node)
20078 	  RETURN (error_mark_node);
20079 	else
20080 	  {
20081 	    init_vec = make_tree_vector ();
20082 	    if (init == void_node)
20083 	      gcc_assert (init_vec != NULL);
20084 	    else
20085 	      {
20086 		for (; init != NULL_TREE; init = TREE_CHAIN (init))
20087 		  vec_safe_push (init_vec, TREE_VALUE (init));
20088 	      }
20089 	  }
20090 
20091 	/* Avoid passing an enclosing decl to valid_array_size_p.  */
20092 	in_decl = NULL_TREE;
20093 
20094 	tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
20095 	tree op2 = RECUR (TREE_OPERAND (t, 2));
20096 	ret = build_new (loc, &placement_vec, op1, op2,
20097 			 &init_vec, NEW_EXPR_USE_GLOBAL (t),
20098 			 complain);
20099 
20100 	if (placement_vec != NULL)
20101 	  release_tree_vector (placement_vec);
20102 	if (init_vec != NULL)
20103 	  release_tree_vector (init_vec);
20104 
20105 	RETURN (ret);
20106       }
20107 
20108     case DELETE_EXPR:
20109       {
20110 	tree op0 = RECUR (TREE_OPERAND (t, 0));
20111 	tree op1 = RECUR (TREE_OPERAND (t, 1));
20112 	RETURN (delete_sanity (input_location, op0, op1,
20113 			       DELETE_EXPR_USE_VEC (t),
20114 			       DELETE_EXPR_USE_GLOBAL (t),
20115 			       complain));
20116       }
20117 
20118     case COMPOUND_EXPR:
20119       {
20120 	tree op0 = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
20121 					  complain & ~tf_decltype, in_decl,
20122 					  /*function_p=*/false,
20123 					  integral_constant_expression_p);
20124 	RETURN (build_x_compound_expr (EXPR_LOCATION (t),
20125 				       op0,
20126 				       RECUR (TREE_OPERAND (t, 1)),
20127 				       complain|decltype_flag));
20128       }
20129 
20130     case CALL_EXPR:
20131       {
20132 	tree function;
20133 	unsigned int nargs, i;
20134 	bool qualified_p;
20135 	bool koenig_p;
20136 	tree ret;
20137 
20138 	function = CALL_EXPR_FN (t);
20139 	/* Internal function with no arguments.  */
20140 	if (function == NULL_TREE && call_expr_nargs (t) == 0)
20141 	  RETURN (t);
20142 
20143 	/* When we parsed the expression, we determined whether or
20144 	   not Koenig lookup should be performed.  */
20145 	koenig_p = KOENIG_LOOKUP_P (t);
20146 	if (function == NULL_TREE)
20147 	  {
20148 	    koenig_p = false;
20149 	    qualified_p = false;
20150 	  }
20151 	else if (TREE_CODE (function) == SCOPE_REF)
20152 	  {
20153 	    qualified_p = true;
20154 	    function = tsubst_qualified_id (function, args, complain, in_decl,
20155 					    /*done=*/false,
20156 					    /*address_p=*/false);
20157 	  }
20158 	else if (koenig_p && identifier_p (function))
20159 	  {
20160 	    /* Do nothing; calling tsubst_copy_and_build on an identifier
20161 	       would incorrectly perform unqualified lookup again.
20162 
20163 	       Note that we can also have an IDENTIFIER_NODE if the earlier
20164 	       unqualified lookup found a member function; in that case
20165 	       koenig_p will be false and we do want to do the lookup
20166 	       again to find the instantiated member function.
20167 
20168 	       FIXME but doing that causes c++/15272, so we need to stop
20169 	       using IDENTIFIER_NODE in that situation.  */
20170 	    qualified_p = false;
20171 	  }
20172 	else
20173 	  {
20174 	    if (TREE_CODE (function) == COMPONENT_REF)
20175 	      {
20176 		tree op = TREE_OPERAND (function, 1);
20177 
20178 		qualified_p = (TREE_CODE (op) == SCOPE_REF
20179 			       || (BASELINK_P (op)
20180 				   && BASELINK_QUALIFIED_P (op)));
20181 	      }
20182 	    else
20183 	      qualified_p = false;
20184 
20185 	    if (TREE_CODE (function) == ADDR_EXPR
20186 		&& TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
20187 	      /* Avoid error about taking the address of a constructor.  */
20188 	      function = TREE_OPERAND (function, 0);
20189 
20190 	    function = tsubst_copy_and_build (function, args, complain,
20191 					      in_decl,
20192 					      !qualified_p,
20193 					      integral_constant_expression_p);
20194 
20195 	    if (BASELINK_P (function))
20196 	      qualified_p = true;
20197 	  }
20198 
20199 	nargs = call_expr_nargs (t);
20200 	releasing_vec call_args;
20201 	for (i = 0; i < nargs; ++i)
20202 	  {
20203 	    tree arg = CALL_EXPR_ARG (t, i);
20204 
20205 	    if (!PACK_EXPANSION_P (arg))
20206 	      vec_safe_push (call_args, RECUR (CALL_EXPR_ARG (t, i)));
20207 	    else
20208 	      {
20209 		/* Expand the pack expansion and push each entry onto
20210 		   CALL_ARGS.  */
20211 		arg = tsubst_pack_expansion (arg, args, complain, in_decl);
20212 		if (TREE_CODE (arg) == TREE_VEC)
20213 		  {
20214 		    unsigned int len, j;
20215 
20216 		    len = TREE_VEC_LENGTH (arg);
20217 		    for (j = 0; j < len; ++j)
20218 		      {
20219 			tree value = TREE_VEC_ELT (arg, j);
20220 			if (value != NULL_TREE)
20221 			  value = convert_from_reference (value);
20222 			vec_safe_push (call_args, value);
20223 		      }
20224 		  }
20225 		else
20226 		  {
20227 		    /* A partial substitution.  Add one entry.  */
20228 		    vec_safe_push (call_args, arg);
20229 		  }
20230 	      }
20231 	  }
20232 
20233 	/* Stripped-down processing for a call in a thunk.  Specifically, in
20234 	   the thunk template for a generic lambda.  */
20235 	if (call_from_lambda_thunk_p (t))
20236 	  {
20237 	    /* Now that we've expanded any packs, the number of call args
20238 	       might be different.  */
20239 	    unsigned int cargs = call_args->length ();
20240 	    tree thisarg = NULL_TREE;
20241 	    if (TREE_CODE (function) == COMPONENT_REF)
20242 	      {
20243 		thisarg = TREE_OPERAND (function, 0);
20244 		if (TREE_CODE (thisarg) == INDIRECT_REF)
20245 		  thisarg = TREE_OPERAND (thisarg, 0);
20246 		function = TREE_OPERAND (function, 1);
20247 		if (TREE_CODE (function) == BASELINK)
20248 		  function = BASELINK_FUNCTIONS (function);
20249 	      }
20250 	    /* We aren't going to do normal overload resolution, so force the
20251 	       template-id to resolve.  */
20252 	    function = resolve_nondeduced_context (function, complain);
20253 	    for (unsigned i = 0; i < cargs; ++i)
20254 	      {
20255 		/* In a thunk, pass through args directly, without any
20256 		   conversions.  */
20257 		tree arg = (*call_args)[i];
20258 		while (TREE_CODE (arg) != PARM_DECL)
20259 		  arg = TREE_OPERAND (arg, 0);
20260 		(*call_args)[i] = arg;
20261 	      }
20262 	    if (thisarg)
20263 	      {
20264 		/* If there are no other args, just push 'this'.  */
20265 		if (cargs == 0)
20266 		  vec_safe_push (call_args, thisarg);
20267 		else
20268 		  {
20269 		    /* Otherwise, shift the other args over to make room.  */
20270 		    tree last = (*call_args)[cargs - 1];
20271 		    vec_safe_push (call_args, last);
20272 		    for (int i = cargs - 1; i > 0; --i)
20273 		      (*call_args)[i] = (*call_args)[i - 1];
20274 		    (*call_args)[0] = thisarg;
20275 		  }
20276 	      }
20277 	    ret = build_call_a (function, call_args->length (),
20278 				call_args->address ());
20279 	    /* The thunk location is not interesting.  */
20280 	    SET_EXPR_LOCATION (ret, UNKNOWN_LOCATION);
20281 	    CALL_FROM_THUNK_P (ret) = true;
20282 	    if (CLASS_TYPE_P (TREE_TYPE (ret)))
20283 	      CALL_EXPR_RETURN_SLOT_OPT (ret) = true;
20284 
20285 	    RETURN (ret);
20286 	  }
20287 
20288 	/* We do not perform argument-dependent lookup if normal
20289 	   lookup finds a non-function, in accordance with the
20290 	   resolution of DR 218.  */
20291 	if (koenig_p
20292 	    && ((is_overloaded_fn (function)
20293 		 /* If lookup found a member function, the Koenig lookup is
20294 		    not appropriate, even if an unqualified-name was used
20295 		    to denote the function.  */
20296 		 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
20297 		|| identifier_p (function)
20298 		/* C++20 P0846: Lookup found nothing.  */
20299 		|| (TREE_CODE (function) == TEMPLATE_ID_EXPR
20300 		    && identifier_p (TREE_OPERAND (function, 0))))
20301 	    /* Only do this when substitution turns a dependent call
20302 	       into a non-dependent call.  */
20303 	    && type_dependent_expression_p_push (t)
20304 	    && !any_type_dependent_arguments_p (call_args))
20305 	  function = perform_koenig_lookup (function, call_args, tf_none);
20306 
20307 	if (function != NULL_TREE
20308 	    && (identifier_p (function)
20309 		|| (TREE_CODE (function) == TEMPLATE_ID_EXPR
20310 		    && identifier_p (TREE_OPERAND (function, 0))))
20311 	    && !any_type_dependent_arguments_p (call_args))
20312 	  {
20313 	    if (TREE_CODE (function) == TEMPLATE_ID_EXPR)
20314 	      function = TREE_OPERAND (function, 0);
20315 	    if (koenig_p && (complain & tf_warning_or_error))
20316 	      {
20317 		/* For backwards compatibility and good diagnostics, try
20318 		   the unqualified lookup again if we aren't in SFINAE
20319 		   context.  */
20320 		tree unq = (tsubst_copy_and_build
20321 			    (function, args, complain, in_decl, true,
20322 			     integral_constant_expression_p));
20323 		if (unq == error_mark_node)
20324 		  RETURN (error_mark_node);
20325 
20326 		if (unq != function)
20327 		  {
20328 		    /* In a lambda fn, we have to be careful to not
20329 		       introduce new this captures.  Legacy code can't
20330 		       be using lambdas anyway, so it's ok to be
20331 		       stricter.  */
20332 		    bool in_lambda = (current_class_type
20333 				      && LAMBDA_TYPE_P (current_class_type));
20334 		    char const *const msg
20335 		      = G_("%qD was not declared in this scope, "
20336 			   "and no declarations were found by "
20337 			   "argument-dependent lookup at the point "
20338 			   "of instantiation");
20339 
20340 		    bool diag = true;
20341 		    if (in_lambda)
20342 		      error_at (cp_expr_loc_or_input_loc (t),
20343 				msg, function);
20344 		    else
20345 		      diag = permerror (cp_expr_loc_or_input_loc (t),
20346 					msg, function);
20347 		    if (diag)
20348 		      {
20349 			tree fn = unq;
20350 
20351 			if (INDIRECT_REF_P (fn))
20352 			  fn = TREE_OPERAND (fn, 0);
20353 			if (is_overloaded_fn (fn))
20354 			  fn = get_first_fn (fn);
20355 
20356 			if (!DECL_P (fn))
20357 			  /* Can't say anything more.  */;
20358 			else if (DECL_CLASS_SCOPE_P (fn))
20359 			  {
20360 			    location_t loc = cp_expr_loc_or_input_loc (t);
20361 			    inform (loc,
20362 				    "declarations in dependent base %qT are "
20363 				    "not found by unqualified lookup",
20364 				    DECL_CLASS_CONTEXT (fn));
20365 			    if (current_class_ptr)
20366 			      inform (loc,
20367 				      "use %<this->%D%> instead", function);
20368 			    else
20369 			      inform (loc,
20370 				      "use %<%T::%D%> instead",
20371 				      current_class_name, function);
20372 			  }
20373 			else
20374 			  inform (DECL_SOURCE_LOCATION (fn),
20375 				  "%qD declared here, later in the "
20376 				  "translation unit", fn);
20377 			if (in_lambda)
20378 			  RETURN (error_mark_node);
20379 		      }
20380 
20381 		    function = unq;
20382 		  }
20383 	      }
20384 	    if (identifier_p (function))
20385 	      {
20386 		if (complain & tf_error)
20387 		  unqualified_name_lookup_error (function);
20388 		RETURN (error_mark_node);
20389 	      }
20390 	  }
20391 
20392 	/* Remember that there was a reference to this entity.  */
20393 	if (function != NULL_TREE
20394 	    && DECL_P (function)
20395 	    && !mark_used (function, complain) && !(complain & tf_error))
20396 	  RETURN (error_mark_node);
20397 
20398 	/* Put back tf_decltype for the actual call.  */
20399 	complain |= decltype_flag;
20400 
20401 	if (function == NULL_TREE)
20402 	  switch (CALL_EXPR_IFN (t))
20403 	    {
20404 	    case IFN_LAUNDER:
20405 	      gcc_assert (nargs == 1);
20406 	      if (vec_safe_length (call_args) != 1)
20407 		{
20408 		  error_at (cp_expr_loc_or_input_loc (t),
20409 			    "wrong number of arguments to "
20410 			    "%<__builtin_launder%>");
20411 		  ret = error_mark_node;
20412 		}
20413 	      else
20414 		ret = finish_builtin_launder (cp_expr_loc_or_input_loc (t),
20415 					      (*call_args)[0], complain);
20416 	      break;
20417 
20418 	    case IFN_VEC_CONVERT:
20419 	      gcc_assert (nargs == 1);
20420 	      if (vec_safe_length (call_args) != 1)
20421 		{
20422 		  error_at (cp_expr_loc_or_input_loc (t),
20423 			    "wrong number of arguments to "
20424 			    "%<__builtin_convertvector%>");
20425 		  ret = error_mark_node;
20426 		  break;
20427 		}
20428 	      ret = cp_build_vec_convert ((*call_args)[0], input_location,
20429 					  tsubst (TREE_TYPE (t), args,
20430 						  complain, in_decl),
20431 					  complain);
20432 	      if (TREE_CODE (ret) == VIEW_CONVERT_EXPR)
20433 		RETURN (ret);
20434 	      break;
20435 
20436 	    default:
20437 	      /* Unsupported internal function with arguments.  */
20438 	      gcc_unreachable ();
20439 	    }
20440 	else if (TREE_CODE (function) == OFFSET_REF
20441 		 || TREE_CODE (function) == DOTSTAR_EXPR
20442 		 || TREE_CODE (function) == MEMBER_REF)
20443 	  ret = build_offset_ref_call_from_tree (function, &call_args,
20444 						 complain);
20445 	else if (TREE_CODE (function) == COMPONENT_REF)
20446 	  {
20447 	    tree instance = TREE_OPERAND (function, 0);
20448 	    tree fn = TREE_OPERAND (function, 1);
20449 
20450 	    if (processing_template_decl
20451 		&& (type_dependent_expression_p (instance)
20452 		    || (!BASELINK_P (fn)
20453 			&& TREE_CODE (fn) != FIELD_DECL)
20454 		    || type_dependent_expression_p (fn)
20455 		    || any_type_dependent_arguments_p (call_args)))
20456 	      ret = build_min_nt_call_vec (function, call_args);
20457 	    else if (!BASELINK_P (fn))
20458 	      ret = finish_call_expr (function, &call_args,
20459 				       /*disallow_virtual=*/false,
20460 				       /*koenig_p=*/false,
20461 				       complain);
20462 	    else
20463 	      ret = (build_new_method_call
20464 		      (instance, fn,
20465 		       &call_args, NULL_TREE,
20466 		       qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
20467 		       /*fn_p=*/NULL,
20468 		       complain));
20469 	  }
20470 	else if (concept_check_p (function))
20471 	  {
20472 	    /* FUNCTION is a template-id referring to a concept definition.  */
20473 	    tree id = unpack_concept_check (function);
20474 	    tree tmpl = TREE_OPERAND (id, 0);
20475 	    tree args = TREE_OPERAND (id, 1);
20476 
20477 	    /* Calls to standard and variable concepts should have been
20478 	       previously diagnosed.  */
20479 	    gcc_assert (function_concept_p (tmpl));
20480 
20481 	    /* Ensure the result is wrapped as a call expression.  */
20482 	    ret = build_concept_check (tmpl, args, tf_warning_or_error);
20483 	  }
20484 	else
20485 	  ret = finish_call_expr (function, &call_args,
20486 				  /*disallow_virtual=*/qualified_p,
20487 				  koenig_p,
20488 				  complain);
20489 
20490 	if (ret != error_mark_node)
20491 	  {
20492 	    bool op = CALL_EXPR_OPERATOR_SYNTAX (t);
20493 	    bool ord = CALL_EXPR_ORDERED_ARGS (t);
20494 	    bool rev = CALL_EXPR_REVERSE_ARGS (t);
20495 	    if (op || ord || rev)
20496 	      {
20497 		function = extract_call_expr (ret);
20498 		CALL_EXPR_OPERATOR_SYNTAX (function) = op;
20499 		CALL_EXPR_ORDERED_ARGS (function) = ord;
20500 		CALL_EXPR_REVERSE_ARGS (function) = rev;
20501 	      }
20502 	  }
20503 
20504 	RETURN (ret);
20505       }
20506 
20507     case COND_EXPR:
20508       {
20509 	tree cond = RECUR (TREE_OPERAND (t, 0));
20510 	cond = mark_rvalue_use (cond);
20511 	tree folded_cond = fold_non_dependent_expr (cond, complain);
20512 	tree exp1, exp2;
20513 
20514 	if (TREE_CODE (folded_cond) == INTEGER_CST)
20515 	  {
20516 	    if (integer_zerop (folded_cond))
20517 	      {
20518 		++c_inhibit_evaluation_warnings;
20519 		exp1 = RECUR (TREE_OPERAND (t, 1));
20520 		--c_inhibit_evaluation_warnings;
20521 		exp2 = RECUR (TREE_OPERAND (t, 2));
20522 	      }
20523 	    else
20524 	      {
20525 		exp1 = RECUR (TREE_OPERAND (t, 1));
20526 		++c_inhibit_evaluation_warnings;
20527 		exp2 = RECUR (TREE_OPERAND (t, 2));
20528 		--c_inhibit_evaluation_warnings;
20529 	      }
20530 	    cond = folded_cond;
20531 	  }
20532 	else
20533 	  {
20534 	    exp1 = RECUR (TREE_OPERAND (t, 1));
20535 	    exp2 = RECUR (TREE_OPERAND (t, 2));
20536 	  }
20537 
20538 	warning_sentinel s(warn_duplicated_branches);
20539 	RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
20540 					 cond, exp1, exp2, complain));
20541       }
20542 
20543     case PSEUDO_DTOR_EXPR:
20544       {
20545 	tree op0 = RECUR (TREE_OPERAND (t, 0));
20546 	tree op1 = RECUR (TREE_OPERAND (t, 1));
20547 	tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
20548 	RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
20549 					       input_location));
20550       }
20551 
20552     case TREE_LIST:
20553       RETURN (tsubst_tree_list (t, args, complain, in_decl));
20554 
20555     case COMPONENT_REF:
20556       {
20557 	tree object;
20558 	tree object_type;
20559 	tree member;
20560 	tree r;
20561 
20562 	object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20563 						     args, complain, in_decl);
20564 	/* Remember that there was a reference to this entity.  */
20565 	if (DECL_P (object)
20566 	    && !mark_used (object, complain) && !(complain & tf_error))
20567 	  RETURN (error_mark_node);
20568 	object_type = TREE_TYPE (object);
20569 
20570 	member = TREE_OPERAND (t, 1);
20571 	if (BASELINK_P (member))
20572 	  member = tsubst_baselink (member,
20573 				    non_reference (TREE_TYPE (object)),
20574 				    args, complain, in_decl);
20575 	else
20576 	  member = tsubst_copy (member, args, complain, in_decl);
20577 	if (member == error_mark_node)
20578 	  RETURN (error_mark_node);
20579 
20580 	if (TREE_CODE (member) == FIELD_DECL)
20581 	  {
20582 	    r = finish_non_static_data_member (member, object, NULL_TREE);
20583 	    if (TREE_CODE (r) == COMPONENT_REF)
20584 	      REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
20585 	    RETURN (r);
20586 	  }
20587 	else if (type_dependent_expression_p (object))
20588 	  /* We can't do much here.  */;
20589 	else if (!CLASS_TYPE_P (object_type))
20590 	  {
20591 	    if (scalarish_type_p (object_type))
20592 	      {
20593 		tree s = NULL_TREE;
20594 		tree dtor = member;
20595 
20596 		if (TREE_CODE (dtor) == SCOPE_REF)
20597 		  {
20598 		    s = TREE_OPERAND (dtor, 0);
20599 		    dtor = TREE_OPERAND (dtor, 1);
20600 		  }
20601 		if (TREE_CODE (dtor) == BIT_NOT_EXPR)
20602 		  {
20603 		    dtor = TREE_OPERAND (dtor, 0);
20604 		    if (TYPE_P (dtor))
20605 		      RETURN (finish_pseudo_destructor_expr
20606 			      (object, s, dtor, input_location));
20607 		  }
20608 	      }
20609 	  }
20610 	else if (TREE_CODE (member) == SCOPE_REF
20611 		 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
20612 	  {
20613 	    /* Lookup the template functions now that we know what the
20614 	       scope is.  */
20615 	    tree scope = TREE_OPERAND (member, 0);
20616 	    tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
20617 	    tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
20618 	    member = lookup_qualified_name (scope, tmpl, LOOK_want::NORMAL,
20619 					    /*complain=*/false);
20620 	    if (BASELINK_P (member))
20621 	      {
20622 		BASELINK_FUNCTIONS (member)
20623 		  = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
20624 			      args);
20625 		member = (adjust_result_of_qualified_name_lookup
20626 			  (member, BINFO_TYPE (BASELINK_BINFO (member)),
20627 			   object_type));
20628 	      }
20629 	    else
20630 	      {
20631 		qualified_name_lookup_error (scope, tmpl, member,
20632 					     input_location);
20633 		RETURN (error_mark_node);
20634 	      }
20635 	  }
20636 	else if (TREE_CODE (member) == SCOPE_REF
20637 		 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
20638 		 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
20639 	  {
20640 	    if (complain & tf_error)
20641 	      {
20642 		if (TYPE_P (TREE_OPERAND (member, 0)))
20643 		  error ("%qT is not a class or namespace",
20644 			 TREE_OPERAND (member, 0));
20645 		else
20646 		  error ("%qD is not a class or namespace",
20647 			 TREE_OPERAND (member, 0));
20648 	      }
20649 	    RETURN (error_mark_node);
20650 	  }
20651 
20652 	r = finish_class_member_access_expr (object, member,
20653 					     /*template_p=*/false,
20654 					     complain);
20655 	if (TREE_CODE (r) == COMPONENT_REF)
20656 	  REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
20657 	RETURN (r);
20658       }
20659 
20660     case THROW_EXPR:
20661       RETURN (build_throw
20662        (input_location, RECUR (TREE_OPERAND (t, 0))));
20663 
20664     case CONSTRUCTOR:
20665       {
20666 	vec<constructor_elt, va_gc> *n;
20667 	constructor_elt *ce;
20668 	unsigned HOST_WIDE_INT idx;
20669 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20670 	bool process_index_p;
20671         int newlen;
20672         bool need_copy_p = false;
20673 	tree r;
20674 
20675 	if (type == error_mark_node)
20676 	  RETURN (error_mark_node);
20677 
20678 	/* We do not want to process the index of aggregate
20679 	   initializers as they are identifier nodes which will be
20680 	   looked up by digest_init.  */
20681 	process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
20682 
20683 	if (null_member_pointer_value_p (t))
20684 	  {
20685 	    gcc_assert (same_type_p (type, TREE_TYPE (t)));
20686 	    RETURN (t);
20687 	  }
20688 
20689 	n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
20690         newlen = vec_safe_length (n);
20691 	FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
20692 	  {
20693 	    if (ce->index && process_index_p
20694 		/* An identifier index is looked up in the type
20695 		   being initialized, not the current scope.  */
20696 		&& TREE_CODE (ce->index) != IDENTIFIER_NODE)
20697 	      ce->index = RECUR (ce->index);
20698 
20699             if (PACK_EXPANSION_P (ce->value))
20700               {
20701                 /* Substitute into the pack expansion.  */
20702                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
20703                                                   in_decl);
20704 
20705 		if (ce->value == error_mark_node
20706 		    || PACK_EXPANSION_P (ce->value))
20707 		  ;
20708 		else if (TREE_VEC_LENGTH (ce->value) == 1)
20709                   /* Just move the argument into place.  */
20710                   ce->value = TREE_VEC_ELT (ce->value, 0);
20711                 else
20712                   {
20713                     /* Update the length of the final CONSTRUCTOR
20714                        arguments vector, and note that we will need to
20715                        copy.*/
20716                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
20717                     need_copy_p = true;
20718                   }
20719               }
20720             else
20721               ce->value = RECUR (ce->value);
20722 	  }
20723 
20724         if (need_copy_p)
20725           {
20726             vec<constructor_elt, va_gc> *old_n = n;
20727 
20728             vec_alloc (n, newlen);
20729             FOR_EACH_VEC_ELT (*old_n, idx, ce)
20730               {
20731                 if (TREE_CODE (ce->value) == TREE_VEC)
20732                   {
20733                     int i, len = TREE_VEC_LENGTH (ce->value);
20734                     for (i = 0; i < len; ++i)
20735                       CONSTRUCTOR_APPEND_ELT (n, 0,
20736                                               TREE_VEC_ELT (ce->value, i));
20737                   }
20738                 else
20739                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
20740               }
20741           }
20742 
20743 	r = build_constructor (init_list_type_node, n);
20744 	CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
20745 	CONSTRUCTOR_IS_DESIGNATED_INIT (r)
20746 	  = CONSTRUCTOR_IS_DESIGNATED_INIT (t);
20747 
20748 	if (TREE_HAS_CONSTRUCTOR (t))
20749 	  {
20750 	    fcl_t cl = fcl_functional;
20751 	    if (CONSTRUCTOR_C99_COMPOUND_LITERAL (t))
20752 	      cl = fcl_c99;
20753 	    RETURN (finish_compound_literal (type, r, complain, cl));
20754 	  }
20755 
20756 	TREE_TYPE (r) = type;
20757 	RETURN (r);
20758       }
20759 
20760     case TYPEID_EXPR:
20761       {
20762 	tree operand_0 = TREE_OPERAND (t, 0);
20763 	if (TYPE_P (operand_0))
20764 	  {
20765 	    operand_0 = tsubst (operand_0, args, complain, in_decl);
20766 	    RETURN (get_typeid (operand_0, complain));
20767 	  }
20768 	else
20769 	  {
20770 	    operand_0 = RECUR (operand_0);
20771 	    RETURN (build_typeid (operand_0, complain));
20772 	  }
20773       }
20774 
20775     case VAR_DECL:
20776       if (!args)
20777 	RETURN (t);
20778       /* Fall through */
20779 
20780     case PARM_DECL:
20781       {
20782 	tree r = tsubst_copy (t, args, complain, in_decl);
20783 	/* ??? We're doing a subset of finish_id_expression here.  */
20784 	if (tree wrap = maybe_get_tls_wrapper_call (r))
20785 	  /* Replace an evaluated use of the thread_local variable with
20786 	     a call to its wrapper.  */
20787 	  r = wrap;
20788 	else if (outer_automatic_var_p (r))
20789 	  r = process_outer_var_ref (r, complain);
20790 
20791 	if (!TYPE_REF_P (TREE_TYPE (t)))
20792 	  /* If the original type was a reference, we'll be wrapped in
20793 	     the appropriate INDIRECT_REF.  */
20794 	  r = convert_from_reference (r);
20795 	RETURN (r);
20796       }
20797 
20798     case VA_ARG_EXPR:
20799       {
20800 	tree op0 = RECUR (TREE_OPERAND (t, 0));
20801 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20802 	RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
20803       }
20804 
20805     case OFFSETOF_EXPR:
20806       {
20807 	tree object_ptr
20808 	  = tsubst_copy_and_build (TREE_OPERAND (t, 1), args, complain,
20809 				   in_decl, /*function_p=*/false,
20810 				   /*integral_constant_expression_p=*/false);
20811 	RETURN (finish_offsetof (object_ptr,
20812 				 RECUR (TREE_OPERAND (t, 0)),
20813 				 EXPR_LOCATION (t)));
20814       }
20815 
20816     case ADDRESSOF_EXPR:
20817       RETURN (cp_build_addressof (EXPR_LOCATION (t),
20818 				  RECUR (TREE_OPERAND (t, 0)), complain));
20819 
20820     case TRAIT_EXPR:
20821       {
20822 	tree type1 = tsubst (TRAIT_EXPR_TYPE1 (t), args,
20823 			     complain, in_decl);
20824 	tree type2 = tsubst (TRAIT_EXPR_TYPE2 (t), args,
20825 			     complain, in_decl);
20826 	RETURN (finish_trait_expr (TRAIT_EXPR_LOCATION (t),
20827 				   TRAIT_EXPR_KIND (t), type1, type2));
20828       }
20829 
20830     case STMT_EXPR:
20831       {
20832 	tree old_stmt_expr = cur_stmt_expr;
20833 	tree stmt_expr = begin_stmt_expr ();
20834 
20835 	cur_stmt_expr = stmt_expr;
20836 	tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
20837 		     integral_constant_expression_p);
20838 	stmt_expr = finish_stmt_expr (stmt_expr, false);
20839 	cur_stmt_expr = old_stmt_expr;
20840 
20841 	/* If the resulting list of expression statement is empty,
20842 	   fold it further into void_node.  */
20843 	if (empty_expr_stmt_p (stmt_expr))
20844 	  stmt_expr = void_node;
20845 
20846 	RETURN (stmt_expr);
20847       }
20848 
20849     case LAMBDA_EXPR:
20850       {
20851 	if (complain & tf_partial)
20852 	  {
20853 	    /* We don't have a full set of template arguments yet; don't touch
20854 	       the lambda at all.  */
20855 	    gcc_assert (processing_template_decl);
20856 	    return t;
20857 	  }
20858 	tree r = tsubst_lambda_expr (t, args, complain, in_decl);
20859 
20860 	RETURN (build_lambda_object (r));
20861       }
20862 
20863     case TARGET_EXPR:
20864       /* We can get here for a constant initializer of non-dependent type.
20865          FIXME stop folding in cp_parser_initializer_clause.  */
20866       {
20867 	tree r = get_target_expr_sfinae (RECUR (TARGET_EXPR_INITIAL (t)),
20868 					 complain);
20869 	RETURN (r);
20870       }
20871 
20872     case TRANSACTION_EXPR:
20873       RETURN (tsubst_expr(t, args, complain, in_decl,
20874 	     integral_constant_expression_p));
20875 
20876     case PAREN_EXPR:
20877       RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
20878 
20879     case VEC_PERM_EXPR:
20880       {
20881 	tree op0 = RECUR (TREE_OPERAND (t, 0));
20882 	tree op1 = RECUR (TREE_OPERAND (t, 1));
20883 	tree op2 = RECUR (TREE_OPERAND (t, 2));
20884 	RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
20885 				       complain));
20886       }
20887 
20888     case REQUIRES_EXPR:
20889       {
20890 	tree r = tsubst_requires_expr (t, args, tf_none, in_decl);
20891 	RETURN (r);
20892       }
20893 
20894     case RANGE_EXPR:
20895       /* No need to substitute further, a RANGE_EXPR will always be built
20896 	 with constant operands.  */
20897       RETURN (t);
20898 
20899     case NON_LVALUE_EXPR:
20900     case VIEW_CONVERT_EXPR:
20901       if (location_wrapper_p (t))
20902 	/* We need to do this here as well as in tsubst_copy so we get the
20903 	   other tsubst_copy_and_build semantics for a PARM_DECL operand.  */
20904 	RETURN (maybe_wrap_with_location (RECUR (TREE_OPERAND (t, 0)),
20905 					  EXPR_LOCATION (t)));
20906       /* fallthrough.  */
20907 
20908     default:
20909       /* Handle Objective-C++ constructs, if appropriate.  */
20910       {
20911 	tree subst
20912 	  = objcp_tsubst_copy_and_build (t, args, complain,
20913 					 in_decl, /*function_p=*/false);
20914 	if (subst)
20915 	  RETURN (subst);
20916       }
20917       RETURN (tsubst_copy (t, args, complain, in_decl));
20918     }
20919 
20920 #undef RECUR
20921 #undef RETURN
20922  out:
20923   input_location = save_loc;
20924   return retval;
20925 }
20926 
20927 /* Verify that the instantiated ARGS are valid. For type arguments,
20928    make sure that the type's linkage is ok. For non-type arguments,
20929    make sure they are constants if they are integral or enumerations.
20930    Emit an error under control of COMPLAIN, and return TRUE on error.  */
20931 
20932 static bool
check_instantiated_arg(tree tmpl,tree t,tsubst_flags_t complain)20933 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
20934 {
20935   if (dependent_template_arg_p (t))
20936     return false;
20937   if (ARGUMENT_PACK_P (t))
20938     {
20939       tree vec = ARGUMENT_PACK_ARGS (t);
20940       int len = TREE_VEC_LENGTH (vec);
20941       bool result = false;
20942       int i;
20943 
20944       for (i = 0; i < len; ++i)
20945 	if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
20946 	  result = true;
20947       return result;
20948     }
20949   else if (TYPE_P (t))
20950     {
20951       /* [basic.link]: A name with no linkage (notably, the name
20952 	 of a class or enumeration declared in a local scope)
20953 	 shall not be used to declare an entity with linkage.
20954 	 This implies that names with no linkage cannot be used as
20955 	 template arguments
20956 
20957 	 DR 757 relaxes this restriction for C++0x.  */
20958       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
20959 		 : no_linkage_check (t, /*relaxed_p=*/false));
20960 
20961       if (nt)
20962 	{
20963 	  /* DR 488 makes use of a type with no linkage cause
20964 	     type deduction to fail.  */
20965 	  if (complain & tf_error)
20966 	    {
20967 	      if (TYPE_UNNAMED_P (nt))
20968 		error ("%qT is/uses unnamed type", t);
20969 	      else
20970 		error ("template argument for %qD uses local type %qT",
20971 		       tmpl, t);
20972 	    }
20973 	  return true;
20974 	}
20975       /* In order to avoid all sorts of complications, we do not
20976 	 allow variably-modified types as template arguments.  */
20977       else if (variably_modified_type_p (t, NULL_TREE))
20978 	{
20979 	  if (complain & tf_error)
20980 	    error ("%qT is a variably modified type", t);
20981 	  return true;
20982 	}
20983     }
20984   /* Class template and alias template arguments should be OK.  */
20985   else if (DECL_TYPE_TEMPLATE_P (t))
20986     ;
20987   /* A non-type argument of integral or enumerated type must be a
20988      constant.  */
20989   else if (TREE_TYPE (t)
20990 	   && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
20991 	   && !REFERENCE_REF_P (t)
20992 	   && !TREE_CONSTANT (t))
20993     {
20994       if (complain & tf_error)
20995 	error ("integral expression %qE is not constant", t);
20996       return true;
20997     }
20998   return false;
20999 }
21000 
21001 static bool
check_instantiated_args(tree tmpl,tree args,tsubst_flags_t complain)21002 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
21003 {
21004   int ix, len = DECL_NTPARMS (tmpl);
21005   bool result = false;
21006 
21007   for (ix = 0; ix != len; ix++)
21008     {
21009       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
21010 	result = true;
21011     }
21012   if (result && (complain & tf_error))
21013     error ("  trying to instantiate %qD", tmpl);
21014   return result;
21015 }
21016 
21017 /* We're out of SFINAE context now, so generate diagnostics for the access
21018    errors we saw earlier when instantiating D from TMPL and ARGS.  */
21019 
21020 static void
recheck_decl_substitution(tree d,tree tmpl,tree args)21021 recheck_decl_substitution (tree d, tree tmpl, tree args)
21022 {
21023   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
21024   tree type = TREE_TYPE (pattern);
21025   location_t loc = input_location;
21026 
21027   push_access_scope (d);
21028   push_deferring_access_checks (dk_no_deferred);
21029   input_location = DECL_SOURCE_LOCATION (pattern);
21030   tsubst (type, args, tf_warning_or_error, d);
21031   input_location = loc;
21032   pop_deferring_access_checks ();
21033   pop_access_scope (d);
21034 }
21035 
21036 /* Instantiate the indicated variable, function, or alias template TMPL with
21037    the template arguments in TARG_PTR.  */
21038 
21039 static tree
instantiate_template_1(tree tmpl,tree orig_args,tsubst_flags_t complain)21040 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
21041 {
21042   tree targ_ptr = orig_args;
21043   tree fndecl;
21044   tree gen_tmpl;
21045   tree spec;
21046   bool access_ok = true;
21047 
21048   if (tmpl == error_mark_node)
21049     return error_mark_node;
21050 
21051   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
21052 
21053   if (modules_p ())
21054     lazy_load_pendings (tmpl);
21055 
21056   /* If this function is a clone, handle it specially.  */
21057   if (DECL_CLONED_FUNCTION_P (tmpl))
21058     {
21059       tree spec;
21060       tree clone;
21061 
21062       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
21063 	 DECL_CLONED_FUNCTION.  */
21064       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
21065 				   targ_ptr, complain);
21066       if (spec == error_mark_node)
21067 	return error_mark_node;
21068 
21069       /* Look for the clone.  */
21070       FOR_EACH_CLONE (clone, spec)
21071 	if (DECL_NAME (clone) == DECL_NAME (tmpl))
21072 	  return clone;
21073       /* We should always have found the clone by now.  */
21074       gcc_unreachable ();
21075       return NULL_TREE;
21076     }
21077 
21078   if (targ_ptr == error_mark_node)
21079     return error_mark_node;
21080 
21081   /* Check to see if we already have this specialization.  */
21082   gen_tmpl = most_general_template (tmpl);
21083   if (TMPL_ARGS_DEPTH (targ_ptr)
21084       < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)))
21085     /* targ_ptr only has the innermost template args, so add the outer ones
21086        from tmpl, which could be either a partial instantiation or gen_tmpl (in
21087        the case of a non-dependent call within a template definition).  */
21088     targ_ptr = (add_outermost_template_args
21089 		(DECL_TI_ARGS (DECL_TEMPLATE_RESULT (tmpl)),
21090 		 targ_ptr));
21091 
21092   /* It would be nice to avoid hashing here and then again in tsubst_decl,
21093      but it doesn't seem to be on the hot path.  */
21094   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
21095 
21096   gcc_checking_assert (tmpl == gen_tmpl
21097 		       || ((fndecl
21098 			    = retrieve_specialization (tmpl, orig_args, 0))
21099 			   == spec)
21100 		       || fndecl == NULL_TREE);
21101 
21102   if (spec != NULL_TREE)
21103     {
21104       if (FNDECL_HAS_ACCESS_ERRORS (spec))
21105 	{
21106 	  if (complain & tf_error)
21107 	    recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
21108 	  return error_mark_node;
21109 	}
21110       return spec;
21111     }
21112 
21113   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
21114 			       complain))
21115     return error_mark_node;
21116 
21117   /* We are building a FUNCTION_DECL, during which the access of its
21118      parameters and return types have to be checked.  However this
21119      FUNCTION_DECL which is the desired context for access checking
21120      is not built yet.  We solve this chicken-and-egg problem by
21121      deferring all checks until we have the FUNCTION_DECL.  */
21122   push_deferring_access_checks (dk_deferred);
21123 
21124   /* Instantiation of the function happens in the context of the function
21125      template, not the context of the overload resolution we're doing.  */
21126   push_to_top_level ();
21127   /* If there are dependent arguments, e.g. because we're doing partial
21128      ordering, make sure processing_template_decl stays set.  */
21129   if (uses_template_parms (targ_ptr))
21130     ++processing_template_decl;
21131   if (DECL_CLASS_SCOPE_P (gen_tmpl))
21132     {
21133       tree ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
21134 				   complain, gen_tmpl, true);
21135       push_nested_class (ctx);
21136     }
21137 
21138   tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
21139 
21140   fndecl = NULL_TREE;
21141   if (VAR_P (pattern))
21142     {
21143       /* We need to determine if we're using a partial or explicit
21144 	 specialization now, because the type of the variable could be
21145 	 different.  */
21146       tree tid = lookup_template_variable (gen_tmpl, targ_ptr);
21147       tree elt = most_specialized_partial_spec (tid, complain);
21148       if (elt == error_mark_node)
21149 	pattern = error_mark_node;
21150       else if (elt)
21151 	{
21152 	  tree partial_tmpl = TREE_VALUE (elt);
21153 	  tree partial_args = TREE_PURPOSE (elt);
21154 	  tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
21155 	  fndecl = tsubst (partial_pat, partial_args, complain, gen_tmpl);
21156 	}
21157     }
21158 
21159   /* Substitute template parameters to obtain the specialization.  */
21160   if (fndecl == NULL_TREE)
21161     fndecl = tsubst (pattern, targ_ptr, complain, gen_tmpl);
21162   if (DECL_CLASS_SCOPE_P (gen_tmpl))
21163     pop_nested_class ();
21164   pop_from_top_level ();
21165 
21166   if (fndecl == error_mark_node)
21167     {
21168       pop_deferring_access_checks ();
21169       return error_mark_node;
21170     }
21171 
21172   /* The DECL_TI_TEMPLATE should always be the immediate parent
21173      template, not the most general template.  */
21174   DECL_TI_TEMPLATE (fndecl) = tmpl;
21175   DECL_TI_ARGS (fndecl) = targ_ptr;
21176 
21177   set_instantiating_module (fndecl);
21178 
21179   /* Now we know the specialization, compute access previously
21180      deferred.  Do no access control for inheriting constructors,
21181      as we already checked access for the inherited constructor.  */
21182   if (!(flag_new_inheriting_ctors
21183 	&& DECL_INHERITED_CTOR (fndecl)))
21184     {
21185       push_access_scope (fndecl);
21186       if (!perform_deferred_access_checks (complain))
21187 	access_ok = false;
21188       pop_access_scope (fndecl);
21189     }
21190   pop_deferring_access_checks ();
21191 
21192   /* If we've just instantiated the main entry point for a function,
21193      instantiate all the alternate entry points as well.  We do this
21194      by cloning the instantiation of the main entry point, not by
21195      instantiating the template clones.  */
21196   if (tree chain = DECL_CHAIN (gen_tmpl))
21197     if (DECL_P (chain) && DECL_CLONED_FUNCTION_P (chain))
21198       clone_cdtor (fndecl, /*update_methods=*/false);
21199 
21200   if (!access_ok)
21201     {
21202       if (!(complain & tf_error))
21203 	{
21204 	  /* Remember to reinstantiate when we're out of SFINAE so the user
21205 	     can see the errors.  */
21206 	  FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
21207 	}
21208       return error_mark_node;
21209     }
21210   return fndecl;
21211 }
21212 
21213 /* Wrapper for instantiate_template_1.  */
21214 
21215 tree
instantiate_template(tree tmpl,tree orig_args,tsubst_flags_t complain)21216 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
21217 {
21218   tree ret;
21219   timevar_push (TV_TEMPLATE_INST);
21220   ret = instantiate_template_1 (tmpl, orig_args,  complain);
21221   timevar_pop (TV_TEMPLATE_INST);
21222   return ret;
21223 }
21224 
21225 /* Instantiate the alias template TMPL with ARGS.  Also push a template
21226    instantiation level, which instantiate_template doesn't do because
21227    functions and variables have sufficient context established by the
21228    callers.  */
21229 
21230 static tree
instantiate_alias_template(tree tmpl,tree args,tsubst_flags_t complain)21231 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
21232 {
21233   if (tmpl == error_mark_node || args == error_mark_node)
21234     return error_mark_node;
21235 
21236   args =
21237     coerce_innermost_template_parms (DECL_TEMPLATE_PARMS (tmpl),
21238 				     args, tmpl, complain,
21239 				     /*require_all_args=*/true,
21240 				     /*use_default_args=*/true);
21241 
21242   /* FIXME check for satisfaction in check_instantiated_args.  */
21243   if (flag_concepts
21244       && !any_dependent_template_arguments_p (args)
21245       && !constraints_satisfied_p (tmpl, args))
21246     {
21247       if (complain & tf_error)
21248 	{
21249 	  auto_diagnostic_group d;
21250 	  error ("template constraint failure for %qD", tmpl);
21251 	  diagnose_constraints (input_location, tmpl, args);
21252 	}
21253       return error_mark_node;
21254     }
21255 
21256   if (!push_tinst_level (tmpl, args))
21257     return error_mark_node;
21258   tree r = instantiate_template (tmpl, args, complain);
21259   pop_tinst_level ();
21260 
21261   if (tree d = dependent_alias_template_spec_p (TREE_TYPE (r), nt_opaque))
21262     {
21263       /* An alias template specialization can be dependent
21264 	 even if its underlying type is not.  */
21265       TYPE_DEPENDENT_P (d) = true;
21266       TYPE_DEPENDENT_P_VALID (d) = true;
21267       /* Sometimes a dependent alias spec is equivalent to its expansion,
21268 	 sometimes not.  So always use structural_comptypes.  */
21269       SET_TYPE_STRUCTURAL_EQUALITY (d);
21270     }
21271 
21272   return r;
21273 }
21274 
21275 /* PARM is a template parameter pack for FN.  Returns true iff
21276    PARM is used in a deducible way in the argument list of FN.  */
21277 
21278 static bool
pack_deducible_p(tree parm,tree fn)21279 pack_deducible_p (tree parm, tree fn)
21280 {
21281   tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
21282   for (; t; t = TREE_CHAIN (t))
21283     {
21284       tree type = TREE_VALUE (t);
21285       tree packs;
21286       if (!PACK_EXPANSION_P (type))
21287 	continue;
21288       for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
21289 	   packs; packs = TREE_CHAIN (packs))
21290 	if (template_args_equal (TREE_VALUE (packs), parm))
21291 	  {
21292 	    /* The template parameter pack is used in a function parameter
21293 	       pack.  If this is the end of the parameter list, the
21294 	       template parameter pack is deducible.  */
21295 	    if (TREE_CHAIN (t) == void_list_node)
21296 	      return true;
21297 	    else
21298 	      /* Otherwise, not.  Well, it could be deduced from
21299 		 a non-pack parameter, but doing so would end up with
21300 		 a deduction mismatch, so don't bother.  */
21301 	      return false;
21302 	  }
21303     }
21304   /* The template parameter pack isn't used in any function parameter
21305      packs, but it might be used deeper, e.g. tuple<Args...>.  */
21306   return true;
21307 }
21308 
21309 /* Subroutine of fn_type_unification: check non-dependent parms for
21310    convertibility.  */
21311 
21312 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)21313 check_non_deducible_conversions (tree parms, const tree *args, unsigned nargs,
21314 				 tree fn, unification_kind_t strict, int flags,
21315 				 struct conversion **convs, bool explain_p)
21316 {
21317   /* Non-constructor methods need to leave a conversion for 'this', which
21318      isn't included in nargs here.  */
21319   unsigned offset = (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
21320 		     && !DECL_CONSTRUCTOR_P (fn));
21321 
21322   for (unsigned ia = 0;
21323        parms && parms != void_list_node && ia < nargs; )
21324     {
21325       tree parm = TREE_VALUE (parms);
21326 
21327       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
21328 	  && (!TREE_CHAIN (parms)
21329 	      || TREE_CHAIN (parms) == void_list_node))
21330 	/* For a function parameter pack that occurs at the end of the
21331 	   parameter-declaration-list, the type A of each remaining
21332 	   argument of the call is compared with the type P of the
21333 	   declarator-id of the function parameter pack.  */
21334 	break;
21335 
21336       parms = TREE_CHAIN (parms);
21337 
21338       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
21339 	/* For a function parameter pack that does not occur at the
21340 	   end of the parameter-declaration-list, the type of the
21341 	   parameter pack is a non-deduced context.  */
21342 	continue;
21343 
21344       if (!uses_template_parms (parm))
21345 	{
21346 	  tree arg = args[ia];
21347 	  conversion **conv_p = convs ? &convs[ia+offset] : NULL;
21348 	  int lflags = conv_flags (ia, nargs, fn, arg, flags);
21349 
21350 	  if (check_non_deducible_conversion (parm, arg, strict, lflags,
21351 					      conv_p, explain_p))
21352 	    return 1;
21353 	}
21354 
21355       ++ia;
21356     }
21357 
21358   return 0;
21359 }
21360 
21361 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
21362    NARGS elements of the arguments that are being used when calling
21363    it.  TARGS is a vector into which the deduced template arguments
21364    are placed.
21365 
21366    Returns either a FUNCTION_DECL for the matching specialization of FN or
21367    NULL_TREE if no suitable specialization can be found.  If EXPLAIN_P is
21368    true, diagnostics will be printed to explain why it failed.
21369 
21370    If FN is a conversion operator, or we are trying to produce a specific
21371    specialization, RETURN_TYPE is the return type desired.
21372 
21373    The EXPLICIT_TARGS are explicit template arguments provided via a
21374    template-id.
21375 
21376    The parameter STRICT is one of:
21377 
21378    DEDUCE_CALL:
21379      We are deducing arguments for a function call, as in
21380      [temp.deduct.call].  If RETURN_TYPE is non-null, we are
21381      deducing arguments for a call to the result of a conversion
21382      function template, as in [over.call.object].
21383 
21384    DEDUCE_CONV:
21385      We are deducing arguments for a conversion function, as in
21386      [temp.deduct.conv].
21387 
21388    DEDUCE_EXACT:
21389      We are deducing arguments when doing an explicit instantiation
21390      as in [temp.explicit], when determining an explicit specialization
21391      as in [temp.expl.spec], or when taking the address of a function
21392      template, as in [temp.deduct.funcaddr].  */
21393 
21394 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)21395 fn_type_unification (tree fn,
21396 		     tree explicit_targs,
21397 		     tree targs,
21398 		     const tree *args,
21399 		     unsigned int nargs,
21400 		     tree return_type,
21401 		     unification_kind_t strict,
21402 		     int flags,
21403 		     struct conversion **convs,
21404 		     bool explain_p,
21405 		     bool decltype_p)
21406 {
21407   tree parms;
21408   tree fntype;
21409   tree decl = NULL_TREE;
21410   tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
21411   bool ok;
21412   static int deduction_depth;
21413   /* type_unification_real will pass back any access checks from default
21414      template argument substitution.  */
21415   vec<deferred_access_check, va_gc> *checks = NULL;
21416   /* We don't have all the template args yet.  */
21417   bool incomplete = true;
21418 
21419   tree orig_fn = fn;
21420   if (flag_new_inheriting_ctors)
21421     fn = strip_inheriting_ctors (fn);
21422 
21423   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
21424   tree r = error_mark_node;
21425 
21426   tree full_targs = targs;
21427   if (TMPL_ARGS_DEPTH (targs)
21428       < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (fn)))
21429     full_targs = (add_outermost_template_args
21430 		  (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (fn)),
21431 		   targs));
21432 
21433   if (decltype_p)
21434     complain |= tf_decltype;
21435 
21436   /* In C++0x, it's possible to have a function template whose type depends
21437      on itself recursively.  This is most obvious with decltype, but can also
21438      occur with enumeration scope (c++/48969).  So we need to catch infinite
21439      recursion and reject the substitution at deduction time; this function
21440      will return error_mark_node for any repeated substitution.
21441 
21442      This also catches excessive recursion such as when f<N> depends on
21443      f<N-1> across all integers, and returns error_mark_node for all the
21444      substitutions back up to the initial one.
21445 
21446      This is, of course, not reentrant.  */
21447   if (excessive_deduction_depth)
21448     return error_mark_node;
21449   ++deduction_depth;
21450 
21451   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
21452 
21453   fntype = TREE_TYPE (fn);
21454   if (explicit_targs)
21455     {
21456       /* [temp.deduct]
21457 
21458 	 The specified template arguments must match the template
21459 	 parameters in kind (i.e., type, nontype, template), and there
21460 	 must not be more arguments than there are parameters;
21461 	 otherwise type deduction fails.
21462 
21463 	 Nontype arguments must match the types of the corresponding
21464 	 nontype template parameters, or must be convertible to the
21465 	 types of the corresponding nontype parameters as specified in
21466 	 _temp.arg.nontype_, otherwise type deduction fails.
21467 
21468 	 All references in the function type of the function template
21469 	 to the corresponding template parameters are replaced by the
21470 	 specified template argument values.  If a substitution in a
21471 	 template parameter or in the function type of the function
21472 	 template results in an invalid type, type deduction fails.  */
21473       int i, len = TREE_VEC_LENGTH (tparms);
21474       location_t loc = input_location;
21475       incomplete = false;
21476 
21477       if (explicit_targs == error_mark_node)
21478 	goto fail;
21479 
21480       if (TMPL_ARGS_DEPTH (explicit_targs)
21481 	  < TMPL_ARGS_DEPTH (full_targs))
21482 	explicit_targs = add_outermost_template_args (full_targs,
21483 						      explicit_targs);
21484 
21485       /* Adjust any explicit template arguments before entering the
21486 	 substitution context.  */
21487       explicit_targs
21488 	= (coerce_template_parms (tparms, explicit_targs, fn,
21489 				  complain|tf_partial,
21490 				  /*require_all_args=*/false,
21491 				  /*use_default_args=*/false));
21492       if (explicit_targs == error_mark_node)
21493 	goto fail;
21494 
21495       /* Substitute the explicit args into the function type.  This is
21496 	 necessary so that, for instance, explicitly declared function
21497 	 arguments can match null pointed constants.  If we were given
21498 	 an incomplete set of explicit args, we must not do semantic
21499 	 processing during substitution as we could create partial
21500 	 instantiations.  */
21501       for (i = 0; i < len; i++)
21502         {
21503           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
21504           bool parameter_pack = false;
21505 	  tree targ = TREE_VEC_ELT (explicit_targs, i);
21506 
21507           /* Dig out the actual parm.  */
21508           if (TREE_CODE (parm) == TYPE_DECL
21509               || TREE_CODE (parm) == TEMPLATE_DECL)
21510             {
21511               parm = TREE_TYPE (parm);
21512               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
21513             }
21514           else if (TREE_CODE (parm) == PARM_DECL)
21515             {
21516               parm = DECL_INITIAL (parm);
21517               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
21518             }
21519 
21520 	  if (targ == NULL_TREE)
21521 	    /* No explicit argument for this template parameter.  */
21522 	    incomplete = true;
21523 	  else if (parameter_pack && pack_deducible_p (parm, fn))
21524             {
21525               /* Mark the argument pack as "incomplete". We could
21526                  still deduce more arguments during unification.
21527 	         We remove this mark in type_unification_real.  */
21528 	      ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
21529 	      ARGUMENT_PACK_EXPLICIT_ARGS (targ)
21530 		= ARGUMENT_PACK_ARGS (targ);
21531 
21532               /* We have some incomplete argument packs.  */
21533               incomplete = true;
21534             }
21535         }
21536 
21537       if (incomplete)
21538 	{
21539 	  if (!push_tinst_level (fn, explicit_targs))
21540 	    {
21541 	      excessive_deduction_depth = true;
21542 	      goto fail;
21543 	    }
21544 	  ++processing_template_decl;
21545 	  input_location = DECL_SOURCE_LOCATION (fn);
21546 	  /* Ignore any access checks; we'll see them again in
21547 	     instantiate_template and they might have the wrong
21548 	     access path at this point.  */
21549 	  push_deferring_access_checks (dk_deferred);
21550 	  tsubst_flags_t ecomplain = complain | tf_partial | tf_fndecl_type;
21551 	  fntype = tsubst (TREE_TYPE (fn), explicit_targs, ecomplain, NULL_TREE);
21552 	  pop_deferring_access_checks ();
21553 	  input_location = loc;
21554 	  --processing_template_decl;
21555 	  pop_tinst_level ();
21556 
21557 	  if (fntype == error_mark_node)
21558 	    goto fail;
21559 	}
21560 
21561       /* Place the explicitly specified arguments in TARGS.  */
21562       explicit_targs = INNERMOST_TEMPLATE_ARGS (explicit_targs);
21563       for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
21564 	TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
21565       if (!incomplete && CHECKING_P
21566 	  && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
21567 	SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
21568 	  (targs, NUM_TMPL_ARGS (explicit_targs));
21569     }
21570 
21571   if (return_type && strict != DEDUCE_CALL)
21572     {
21573       tree *new_args = XALLOCAVEC (tree, nargs + 1);
21574       new_args[0] = return_type;
21575       memcpy (new_args + 1, args, nargs * sizeof (tree));
21576       args = new_args;
21577       ++nargs;
21578     }
21579 
21580   if (!incomplete)
21581     goto deduced;
21582 
21583   /* Never do unification on the 'this' parameter.  */
21584   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
21585 
21586   if (return_type && strict == DEDUCE_CALL)
21587     {
21588       /* We're deducing for a call to the result of a template conversion
21589          function.  The parms we really want are in return_type.  */
21590       if (INDIRECT_TYPE_P (return_type))
21591 	return_type = TREE_TYPE (return_type);
21592       parms = TYPE_ARG_TYPES (return_type);
21593     }
21594   else if (return_type)
21595     {
21596       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
21597     }
21598 
21599   /* We allow incomplete unification without an error message here
21600      because the standard doesn't seem to explicitly prohibit it.  Our
21601      callers must be ready to deal with unification failures in any
21602      event.  */
21603 
21604   /* If we aren't explaining yet, push tinst context so we can see where
21605      any errors (e.g. from class instantiations triggered by instantiation
21606      of default template arguments) come from.  If we are explaining, this
21607      context is redundant.  */
21608   if (!explain_p && !push_tinst_level (fn, targs))
21609     {
21610       excessive_deduction_depth = true;
21611       goto fail;
21612     }
21613 
21614   ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
21615 			       full_targs, parms, args, nargs, /*subr=*/0,
21616 			       strict, &checks, explain_p);
21617   if (!explain_p)
21618     pop_tinst_level ();
21619   if (!ok)
21620     goto fail;
21621 
21622   /* Now that we have bindings for all of the template arguments,
21623      ensure that the arguments deduced for the template template
21624      parameters have compatible template parameter lists.  We cannot
21625      check this property before we have deduced all template
21626      arguments, because the template parameter types of a template
21627      template parameter might depend on prior template parameters
21628      deduced after the template template parameter.  The following
21629      ill-formed example illustrates this issue:
21630 
21631        template<typename T, template<T> class C> void f(C<5>, T);
21632 
21633        template<int N> struct X {};
21634 
21635        void g() {
21636          f(X<5>(), 5l); // error: template argument deduction fails
21637        }
21638 
21639      The template parameter list of 'C' depends on the template type
21640      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
21641      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
21642      time that we deduce 'C'.  */
21643   if (!template_template_parm_bindings_ok_p
21644            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
21645     {
21646       unify_inconsistent_template_template_parameters (explain_p);
21647       goto fail;
21648     }
21649 
21650  deduced:
21651 
21652   /* CWG2369: Check satisfaction before non-deducible conversions.  */
21653   if (!constraints_satisfied_p (fn, targs))
21654     {
21655       if (explain_p)
21656 	diagnose_constraints (DECL_SOURCE_LOCATION (fn), fn, targs);
21657       goto fail;
21658     }
21659 
21660   /* DR 1391: All parameters have args, now check non-dependent parms for
21661      convertibility.  We don't do this if all args were explicitly specified,
21662      as the standard says that we substitute explicit args immediately.  */
21663   if (incomplete
21664       && check_non_deducible_conversions (parms, args, nargs, fn, strict, flags,
21665 					  convs, explain_p))
21666     goto fail;
21667 
21668   /* All is well so far.  Now, check:
21669 
21670      [temp.deduct]
21671 
21672      When all template arguments have been deduced, all uses of
21673      template parameters in nondeduced contexts are replaced with
21674      the corresponding deduced argument values.  If the
21675      substitution results in an invalid type, as described above,
21676      type deduction fails.  */
21677   if (!push_tinst_level (fn, targs))
21678     {
21679       excessive_deduction_depth = true;
21680       goto fail;
21681     }
21682 
21683   /* Also collect access checks from the instantiation.  */
21684   reopen_deferring_access_checks (checks);
21685 
21686   decl = instantiate_template (fn, targs, complain);
21687 
21688   checks = get_deferred_access_checks ();
21689   pop_deferring_access_checks ();
21690 
21691   pop_tinst_level ();
21692 
21693   if (decl == error_mark_node)
21694     goto fail;
21695 
21696   /* Now perform any access checks encountered during substitution.  */
21697   push_access_scope (decl);
21698   ok = perform_access_checks (checks, complain);
21699   pop_access_scope (decl);
21700   if (!ok)
21701     goto fail;
21702 
21703   /* If we're looking for an exact match, check that what we got
21704      is indeed an exact match.  It might not be if some template
21705      parameters are used in non-deduced contexts.  But don't check
21706      for an exact match if we have dependent template arguments;
21707      in that case we're doing partial ordering, and we already know
21708      that we have two candidates that will provide the actual type.  */
21709   if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
21710     {
21711       tree substed = TREE_TYPE (decl);
21712       unsigned int i;
21713 
21714       tree sarg
21715 	= skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
21716       if (return_type)
21717 	sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
21718       for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
21719 	if (!same_type_p (args[i], TREE_VALUE (sarg)))
21720 	  {
21721 	    unify_type_mismatch (explain_p, args[i],
21722 				 TREE_VALUE (sarg));
21723 	    goto fail;
21724 	  }
21725     }
21726 
21727   /* After doing deduction with the inherited constructor, actually return an
21728      instantiation of the inheriting constructor.  */
21729   if (orig_fn != fn)
21730     decl = instantiate_template (orig_fn, targs, complain);
21731 
21732   r = decl;
21733 
21734  fail:
21735   --deduction_depth;
21736   if (excessive_deduction_depth)
21737     {
21738       if (deduction_depth == 0)
21739 	/* Reset once we're all the way out.  */
21740 	excessive_deduction_depth = false;
21741     }
21742 
21743   return r;
21744 }
21745 
21746 /* Adjust types before performing type deduction, as described in
21747    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
21748    sections are symmetric.  PARM is the type of a function parameter
21749    or the return type of the conversion function.  ARG is the type of
21750    the argument passed to the call, or the type of the value
21751    initialized with the result of the conversion function.
21752    ARG_EXPR is the original argument expression, which may be null.  */
21753 
21754 static int
maybe_adjust_types_for_deduction(unification_kind_t strict,tree * parm,tree * arg,tree arg_expr)21755 maybe_adjust_types_for_deduction (unification_kind_t strict,
21756 				  tree* parm,
21757 				  tree* arg,
21758 				  tree arg_expr)
21759 {
21760   int result = 0;
21761 
21762   switch (strict)
21763     {
21764     case DEDUCE_CALL:
21765       break;
21766 
21767     case DEDUCE_CONV:
21768       /* Swap PARM and ARG throughout the remainder of this
21769 	 function; the handling is precisely symmetric since PARM
21770 	 will initialize ARG rather than vice versa.  */
21771       std::swap (parm, arg);
21772       break;
21773 
21774     case DEDUCE_EXACT:
21775       /* Core issue #873: Do the DR606 thing (see below) for these cases,
21776 	 too, but here handle it by stripping the reference from PARM
21777 	 rather than by adding it to ARG.  */
21778       if (TYPE_REF_P (*parm)
21779 	  && TYPE_REF_IS_RVALUE (*parm)
21780 	  && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
21781 	  && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
21782 	  && TYPE_REF_P (*arg)
21783 	  && !TYPE_REF_IS_RVALUE (*arg))
21784 	*parm = TREE_TYPE (*parm);
21785       /* Nothing else to do in this case.  */
21786       return 0;
21787 
21788     default:
21789       gcc_unreachable ();
21790     }
21791 
21792   if (!TYPE_REF_P (*parm))
21793     {
21794       /* [temp.deduct.call]
21795 
21796 	 If P is not a reference type:
21797 
21798 	 --If A is an array type, the pointer type produced by the
21799 	 array-to-pointer standard conversion (_conv.array_) is
21800 	 used in place of A for type deduction; otherwise,
21801 
21802 	 --If A is a function type, the pointer type produced by
21803 	 the function-to-pointer standard conversion
21804 	 (_conv.func_) is used in place of A for type deduction;
21805 	 otherwise,
21806 
21807 	 --If A is a cv-qualified type, the top level
21808 	 cv-qualifiers of A's type are ignored for type
21809 	 deduction.  */
21810       if (TREE_CODE (*arg) == ARRAY_TYPE)
21811 	*arg = build_pointer_type (TREE_TYPE (*arg));
21812       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
21813 	*arg = build_pointer_type (*arg);
21814       else
21815 	*arg = TYPE_MAIN_VARIANT (*arg);
21816     }
21817 
21818   /* [14.8.2.1/3 temp.deduct.call], "A forwarding reference is an rvalue
21819      reference to a cv-unqualified template parameter that does not represent a
21820      template parameter of a class template (during class template argument
21821      deduction (13.3.1.8)). If P is a forwarding reference and the argument is
21822      an lvalue, the type "lvalue reference to A" is used in place of A for type
21823      deduction. */
21824   if (TYPE_REF_P (*parm)
21825       && TYPE_REF_IS_RVALUE (*parm)
21826       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
21827       && !TEMPLATE_TYPE_PARM_FOR_CLASS (TREE_TYPE (*parm))
21828       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
21829       && (arg_expr ? lvalue_p (arg_expr)
21830 	  /* try_one_overload doesn't provide an arg_expr, but
21831 	     functions are always lvalues.  */
21832 	  : TREE_CODE (*arg) == FUNCTION_TYPE))
21833     *arg = build_reference_type (*arg);
21834 
21835   /* [temp.deduct.call]
21836 
21837      If P is a cv-qualified type, the top level cv-qualifiers
21838      of P's type are ignored for type deduction.  If P is a
21839      reference type, the type referred to by P is used for
21840      type deduction.  */
21841   *parm = TYPE_MAIN_VARIANT (*parm);
21842   if (TYPE_REF_P (*parm))
21843     {
21844       *parm = TREE_TYPE (*parm);
21845       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
21846     }
21847 
21848   /* DR 322. For conversion deduction, remove a reference type on parm
21849      too (which has been swapped into ARG).  */
21850   if (strict == DEDUCE_CONV && TYPE_REF_P (*arg))
21851     *arg = TREE_TYPE (*arg);
21852 
21853   return result;
21854 }
21855 
21856 /* Subroutine of fn_type_unification.  PARM is a function parameter of a
21857    template which doesn't contain any deducible template parameters; check if
21858    ARG is a suitable match for it.  STRICT, FLAGS and EXPLAIN_P are as in
21859    unify_one_argument.  */
21860 
21861 static int
check_non_deducible_conversion(tree parm,tree arg,int strict,int flags,struct conversion ** conv_p,bool explain_p)21862 check_non_deducible_conversion (tree parm, tree arg, int strict,
21863 				int flags, struct conversion **conv_p,
21864 				bool explain_p)
21865 {
21866   tree type;
21867 
21868   if (!TYPE_P (arg))
21869     type = TREE_TYPE (arg);
21870   else
21871     type = arg;
21872 
21873   if (same_type_p (parm, type))
21874     return unify_success (explain_p);
21875 
21876   tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
21877   if (strict == DEDUCE_CONV)
21878     {
21879       if (can_convert_arg (type, parm, NULL_TREE, flags, complain))
21880 	return unify_success (explain_p);
21881     }
21882   else if (strict != DEDUCE_EXACT)
21883     {
21884       bool ok = false;
21885       tree conv_arg = TYPE_P (arg) ? NULL_TREE : arg;
21886       if (conv_p)
21887 	/* Avoid recalculating this in add_function_candidate.  */
21888 	ok = (*conv_p
21889 	      = good_conversion (parm, type, conv_arg, flags, complain));
21890       else
21891 	ok = can_convert_arg (parm, type, conv_arg, flags, complain);
21892       if (ok)
21893 	return unify_success (explain_p);
21894     }
21895 
21896   if (strict == DEDUCE_EXACT)
21897     return unify_type_mismatch (explain_p, parm, arg);
21898   else
21899     return unify_arg_conversion (explain_p, parm, type, arg);
21900 }
21901 
21902 static bool uses_deducible_template_parms (tree type);
21903 
21904 /* Returns true iff the expression EXPR is one from which a template
21905    argument can be deduced.  In other words, if it's an undecorated
21906    use of a template non-type parameter.  */
21907 
21908 static bool
deducible_expression(tree expr)21909 deducible_expression (tree expr)
21910 {
21911   /* Strip implicit conversions and implicit INDIRECT_REFs.  */
21912   while (CONVERT_EXPR_P (expr)
21913 	 || TREE_CODE (expr) == VIEW_CONVERT_EXPR
21914 	 || REFERENCE_REF_P (expr))
21915     expr = TREE_OPERAND (expr, 0);
21916   return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
21917 }
21918 
21919 /* Returns true iff the array domain DOMAIN uses a template parameter in a
21920    deducible way; that is, if it has a max value of <PARM> - 1.  */
21921 
21922 static bool
deducible_array_bound(tree domain)21923 deducible_array_bound (tree domain)
21924 {
21925   if (domain == NULL_TREE)
21926     return false;
21927 
21928   tree max = TYPE_MAX_VALUE (domain);
21929   if (TREE_CODE (max) != MINUS_EXPR)
21930     return false;
21931 
21932   return deducible_expression (TREE_OPERAND (max, 0));
21933 }
21934 
21935 /* Returns true iff the template arguments ARGS use a template parameter
21936    in a deducible way.  */
21937 
21938 static bool
deducible_template_args(tree args)21939 deducible_template_args (tree args)
21940 {
21941   for (int i = 0; i < TREE_VEC_LENGTH (args); ++i)
21942     {
21943       bool deducible;
21944       tree elt = TREE_VEC_ELT (args, i);
21945       if (ARGUMENT_PACK_P (elt))
21946 	deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
21947       else
21948 	{
21949 	  if (PACK_EXPANSION_P (elt))
21950 	    elt = PACK_EXPANSION_PATTERN (elt);
21951 	  if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
21952 	    deducible = true;
21953 	  else if (TYPE_P (elt))
21954 	    deducible = uses_deducible_template_parms (elt);
21955 	  else
21956 	    deducible = deducible_expression (elt);
21957 	}
21958       if (deducible)
21959 	return true;
21960     }
21961   return false;
21962 }
21963 
21964 /* Returns true iff TYPE contains any deducible references to template
21965    parameters, as per 14.8.2.5.  */
21966 
21967 static bool
uses_deducible_template_parms(tree type)21968 uses_deducible_template_parms (tree type)
21969 {
21970   if (PACK_EXPANSION_P (type))
21971     type = PACK_EXPANSION_PATTERN (type);
21972 
21973   /* T
21974      cv-list T
21975      TT<T>
21976      TT<i>
21977      TT<> */
21978   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
21979       || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
21980     return true;
21981 
21982   /* T*
21983      T&
21984      T&&  */
21985   if (INDIRECT_TYPE_P (type))
21986     return uses_deducible_template_parms (TREE_TYPE (type));
21987 
21988   /* T[integer-constant ]
21989      type [i]  */
21990   if (TREE_CODE (type) == ARRAY_TYPE)
21991     return (uses_deducible_template_parms (TREE_TYPE (type))
21992 	    || deducible_array_bound (TYPE_DOMAIN (type)));
21993 
21994   /* T type ::*
21995      type T::*
21996      T T::*
21997      T (type ::*)()
21998      type (T::*)()
21999      type (type ::*)(T)
22000      type (T::*)(T)
22001      T (type ::*)(T)
22002      T (T::*)()
22003      T (T::*)(T) */
22004   if (TYPE_PTRMEM_P (type))
22005     return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
22006 	    || (uses_deducible_template_parms
22007 		(TYPE_PTRMEM_POINTED_TO_TYPE (type))));
22008 
22009   /* template-name <T> (where template-name refers to a class template)
22010      template-name <i> (where template-name refers to a class template) */
22011   if (CLASS_TYPE_P (type)
22012       && CLASSTYPE_TEMPLATE_INFO (type)
22013       && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
22014     return deducible_template_args (INNERMOST_TEMPLATE_ARGS
22015 				    (CLASSTYPE_TI_ARGS (type)));
22016 
22017   /* type (T)
22018      T()
22019      T(T)  */
22020   if (FUNC_OR_METHOD_TYPE_P (type))
22021     {
22022       if (uses_deducible_template_parms (TREE_TYPE (type)))
22023 	return true;
22024       tree parm = TYPE_ARG_TYPES (type);
22025       if (TREE_CODE (type) == METHOD_TYPE)
22026 	parm = TREE_CHAIN (parm);
22027       for (; parm; parm = TREE_CHAIN (parm))
22028 	if (uses_deducible_template_parms (TREE_VALUE (parm)))
22029 	  return true;
22030     }
22031 
22032   return false;
22033 }
22034 
22035 /* Subroutine of type_unification_real and unify_pack_expansion to
22036    handle unification of a single P/A pair.  Parameters are as
22037    for those functions.  */
22038 
22039 static int
unify_one_argument(tree tparms,tree targs,tree parm,tree arg,int subr,unification_kind_t strict,bool explain_p)22040 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
22041 		    int subr, unification_kind_t strict,
22042 		    bool explain_p)
22043 {
22044   tree arg_expr = NULL_TREE;
22045   int arg_strict;
22046 
22047   if (arg == error_mark_node || parm == error_mark_node)
22048     return unify_invalid (explain_p);
22049   if (arg == unknown_type_node)
22050     /* We can't deduce anything from this, but we might get all the
22051        template args from other function args.  */
22052     return unify_success (explain_p);
22053 
22054   /* Implicit conversions (Clause 4) will be performed on a function
22055      argument to convert it to the type of the corresponding function
22056      parameter if the parameter type contains no template-parameters that
22057      participate in template argument deduction.  */
22058   if (strict != DEDUCE_EXACT
22059       && TYPE_P (parm) && !uses_deducible_template_parms (parm))
22060     /* For function parameters with no deducible template parameters,
22061        just return.  We'll check non-dependent conversions later.  */
22062     return unify_success (explain_p);
22063 
22064   switch (strict)
22065     {
22066     case DEDUCE_CALL:
22067       arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
22068 		    | UNIFY_ALLOW_MORE_CV_QUAL
22069 		    | UNIFY_ALLOW_DERIVED);
22070       break;
22071 
22072     case DEDUCE_CONV:
22073       arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
22074       break;
22075 
22076     case DEDUCE_EXACT:
22077       arg_strict = UNIFY_ALLOW_NONE;
22078       break;
22079 
22080     default:
22081       gcc_unreachable ();
22082     }
22083 
22084   /* We only do these transformations if this is the top-level
22085      parameter_type_list in a call or declaration matching; in other
22086      situations (nested function declarators, template argument lists) we
22087      won't be comparing a type to an expression, and we don't do any type
22088      adjustments.  */
22089   if (!subr)
22090     {
22091       if (!TYPE_P (arg))
22092 	{
22093 	  gcc_assert (TREE_TYPE (arg) != NULL_TREE);
22094 	  if (type_unknown_p (arg))
22095 	    {
22096 	      /* [temp.deduct.type] A template-argument can be
22097 		 deduced from a pointer to function or pointer
22098 		 to member function argument if the set of
22099 		 overloaded functions does not contain function
22100 		 templates and at most one of a set of
22101 		 overloaded functions provides a unique
22102 		 match.  */
22103 	      resolve_overloaded_unification (tparms, targs, parm,
22104 					      arg, strict,
22105 					      arg_strict, explain_p);
22106 	      /* If a unique match was not found, this is a
22107 	         non-deduced context, so we still succeed. */
22108 	      return unify_success (explain_p);
22109 	    }
22110 
22111 	  arg_expr = arg;
22112 	  arg = unlowered_expr_type (arg);
22113 	  if (arg == error_mark_node)
22114 	    return unify_invalid (explain_p);
22115 	}
22116 
22117       arg_strict |=
22118 	maybe_adjust_types_for_deduction (strict, &parm, &arg, arg_expr);
22119     }
22120   else
22121     if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
22122 	!= (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
22123       return unify_template_argument_mismatch (explain_p, parm, arg);
22124 
22125   /* For deduction from an init-list we need the actual list.  */
22126   if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
22127     arg = arg_expr;
22128   return unify (tparms, targs, parm, arg, arg_strict, explain_p);
22129 }
22130 
22131 /* for_each_template_parm callback that always returns 0.  */
22132 
22133 static int
zero_r(tree,void *)22134 zero_r (tree, void *)
22135 {
22136   return 0;
22137 }
22138 
22139 /* for_each_template_parm any_fn callback to handle deduction of a template
22140    type argument from the type of an array bound.  */
22141 
22142 static int
array_deduction_r(tree t,void * data)22143 array_deduction_r (tree t, void *data)
22144 {
22145   tree_pair_p d = (tree_pair_p)data;
22146   tree &tparms = d->purpose;
22147   tree &targs = d->value;
22148 
22149   if (TREE_CODE (t) == ARRAY_TYPE)
22150     if (tree dom = TYPE_DOMAIN (t))
22151       if (tree max = TYPE_MAX_VALUE (dom))
22152 	{
22153 	  if (TREE_CODE (max) == MINUS_EXPR)
22154 	    max = TREE_OPERAND (max, 0);
22155 	  if (TREE_CODE (max) == TEMPLATE_PARM_INDEX)
22156 	    unify (tparms, targs, TREE_TYPE (max), size_type_node,
22157 		   UNIFY_ALLOW_NONE, /*explain*/false);
22158 	}
22159 
22160   /* Keep walking.  */
22161   return 0;
22162 }
22163 
22164 /* Try to deduce any not-yet-deduced template type arguments from the type of
22165    an array bound.  This is handled separately from unify because 14.8.2.5 says
22166    "The type of a type parameter is only deduced from an array bound if it is
22167    not otherwise deduced."  */
22168 
22169 static void
try_array_deduction(tree tparms,tree targs,tree parm)22170 try_array_deduction (tree tparms, tree targs, tree parm)
22171 {
22172   tree_pair_s data = { tparms, targs };
22173   hash_set<tree> visited;
22174   for_each_template_parm (parm, zero_r, &data, &visited,
22175 			  /*nondeduced*/false, array_deduction_r);
22176 }
22177 
22178 /* Most parms like fn_type_unification.
22179 
22180    If SUBR is 1, we're being called recursively (to unify the
22181    arguments of a function or method parameter of a function
22182    template).
22183 
22184    CHECKS is a pointer to a vector of access checks encountered while
22185    substituting default template arguments.  */
22186 
22187 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)22188 type_unification_real (tree tparms,
22189 		       tree full_targs,
22190 		       tree xparms,
22191 		       const tree *xargs,
22192 		       unsigned int xnargs,
22193 		       int subr,
22194 		       unification_kind_t strict,
22195 		       vec<deferred_access_check, va_gc> **checks,
22196 		       bool explain_p)
22197 {
22198   tree parm, arg;
22199   int i;
22200   int ntparms = TREE_VEC_LENGTH (tparms);
22201   int saw_undeduced = 0;
22202   tree parms;
22203   const tree *args;
22204   unsigned int nargs;
22205   unsigned int ia;
22206 
22207   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
22208   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
22209   gcc_assert (ntparms > 0);
22210 
22211   tree targs = INNERMOST_TEMPLATE_ARGS (full_targs);
22212 
22213   /* Reset the number of non-defaulted template arguments contained
22214      in TARGS.  */
22215   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
22216 
22217  again:
22218   parms = xparms;
22219   args = xargs;
22220   nargs = xnargs;
22221 
22222   ia = 0;
22223   while (parms && parms != void_list_node
22224 	 && ia < nargs)
22225     {
22226       parm = TREE_VALUE (parms);
22227 
22228       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
22229 	  && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
22230 	/* For a function parameter pack that occurs at the end of the
22231 	   parameter-declaration-list, the type A of each remaining
22232 	   argument of the call is compared with the type P of the
22233 	   declarator-id of the function parameter pack.  */
22234 	break;
22235 
22236       parms = TREE_CHAIN (parms);
22237 
22238       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
22239 	/* For a function parameter pack that does not occur at the
22240 	   end of the parameter-declaration-list, the type of the
22241 	   parameter pack is a non-deduced context.  */
22242 	continue;
22243 
22244       arg = args[ia];
22245       ++ia;
22246 
22247       if (unify_one_argument (tparms, full_targs, parm, arg, subr, strict,
22248 			      explain_p))
22249 	return 1;
22250     }
22251 
22252   if (parms
22253       && parms != void_list_node
22254       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
22255     {
22256       /* Unify the remaining arguments with the pack expansion type.  */
22257       tree argvec;
22258       tree parmvec = make_tree_vec (1);
22259 
22260       /* Allocate a TREE_VEC and copy in all of the arguments */
22261       argvec = make_tree_vec (nargs - ia);
22262       for (i = 0; ia < nargs; ++ia, ++i)
22263 	TREE_VEC_ELT (argvec, i) = args[ia];
22264 
22265       /* Copy the parameter into parmvec.  */
22266       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
22267       if (unify_pack_expansion (tparms, full_targs, parmvec, argvec, strict,
22268                                 /*subr=*/subr, explain_p))
22269         return 1;
22270 
22271       /* Advance to the end of the list of parameters.  */
22272       parms = TREE_CHAIN (parms);
22273     }
22274 
22275   /* Fail if we've reached the end of the parm list, and more args
22276      are present, and the parm list isn't variadic.  */
22277   if (ia < nargs && parms == void_list_node)
22278     return unify_too_many_arguments (explain_p, nargs, ia);
22279   /* Fail if parms are left and they don't have default values and
22280      they aren't all deduced as empty packs (c++/57397).  This is
22281      consistent with sufficient_parms_p.  */
22282   if (parms && parms != void_list_node
22283       && TREE_PURPOSE (parms) == NULL_TREE)
22284     {
22285       unsigned int count = nargs;
22286       tree p = parms;
22287       bool type_pack_p;
22288       do
22289 	{
22290 	  type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
22291 	  if (!type_pack_p)
22292 	    count++;
22293 	  p = TREE_CHAIN (p);
22294 	}
22295       while (p && p != void_list_node);
22296       if (count != nargs)
22297 	return unify_too_few_arguments (explain_p, ia, count,
22298 					type_pack_p);
22299     }
22300 
22301   if (!subr)
22302     {
22303       tsubst_flags_t complain = (explain_p
22304 				 ? tf_warning_or_error
22305 				 : tf_none);
22306       bool tried_array_deduction = (cxx_dialect < cxx17);
22307 
22308       for (i = 0; i < ntparms; i++)
22309 	{
22310 	  tree targ = TREE_VEC_ELT (targs, i);
22311 	  tree tparm = TREE_VEC_ELT (tparms, i);
22312 
22313 	  /* Clear the "incomplete" flags on all argument packs now so that
22314 	     substituting them into later default arguments works.  */
22315 	  if (targ && ARGUMENT_PACK_P (targ))
22316             {
22317               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
22318               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
22319             }
22320 
22321 	  if (targ || tparm == error_mark_node)
22322 	    continue;
22323 	  tparm = TREE_VALUE (tparm);
22324 
22325 	  if (TREE_CODE (tparm) == TYPE_DECL
22326 	      && !tried_array_deduction)
22327 	    {
22328 	      try_array_deduction (tparms, targs, xparms);
22329 	      tried_array_deduction = true;
22330 	      if (TREE_VEC_ELT (targs, i))
22331 		continue;
22332 	    }
22333 
22334 	  /* If this is an undeduced nontype parameter that depends on
22335 	     a type parameter, try another pass; its type may have been
22336 	     deduced from a later argument than the one from which
22337 	     this parameter can be deduced.  */
22338 	  if (TREE_CODE (tparm) == PARM_DECL
22339 	      && uses_template_parms (TREE_TYPE (tparm))
22340 	      && saw_undeduced < 2)
22341 	    {
22342 	      saw_undeduced = 1;
22343 	      continue;
22344 	    }
22345 
22346 	  /* Core issue #226 (C++0x) [temp.deduct]:
22347 
22348 	     If a template argument has not been deduced, its
22349 	     default template argument, if any, is used.
22350 
22351 	     When we are in C++98 mode, TREE_PURPOSE will either
22352 	     be NULL_TREE or ERROR_MARK_NODE, so we do not need
22353 	     to explicitly check cxx_dialect here.  */
22354 	  if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
22355 	    /* OK, there is a default argument.  Wait until after the
22356 	       conversion check to do substitution.  */
22357 	    continue;
22358 
22359 	  /* If the type parameter is a parameter pack, then it will
22360 	     be deduced to an empty parameter pack.  */
22361 	  if (template_parameter_pack_p (tparm))
22362 	    {
22363 	      tree arg;
22364 
22365 	      if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
22366 		{
22367 		  arg = make_node (NONTYPE_ARGUMENT_PACK);
22368 		  TREE_CONSTANT (arg) = 1;
22369 		}
22370 	      else
22371 		arg = cxx_make_type (TYPE_ARGUMENT_PACK);
22372 
22373 	      SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
22374 
22375 	      TREE_VEC_ELT (targs, i) = arg;
22376 	      continue;
22377 	    }
22378 
22379 	  return unify_parameter_deduction_failure (explain_p, tparm);
22380 	}
22381 
22382       /* Now substitute into the default template arguments.  */
22383       for (i = 0; i < ntparms; i++)
22384 	{
22385 	  tree targ = TREE_VEC_ELT (targs, i);
22386 	  tree tparm = TREE_VEC_ELT (tparms, i);
22387 
22388 	  if (targ || tparm == error_mark_node)
22389 	    continue;
22390 	  tree parm = TREE_VALUE (tparm);
22391 	  tree arg = TREE_PURPOSE (tparm);
22392 	  reopen_deferring_access_checks (*checks);
22393 	  location_t save_loc = input_location;
22394 	  if (DECL_P (parm))
22395 	    input_location = DECL_SOURCE_LOCATION (parm);
22396 
22397 	  if (saw_undeduced == 1
22398 	      && TREE_CODE (parm) == PARM_DECL
22399 	      && uses_template_parms (TREE_TYPE (parm)))
22400 	    {
22401 	      /* The type of this non-type parameter depends on undeduced
22402 		 parameters.  Don't try to use its default argument yet,
22403 		 since we might deduce an argument for it on the next pass,
22404 		 but do check whether the arguments we already have cause
22405 		 substitution failure, so that that happens before we try
22406 		 later default arguments (78489).  */
22407 	      ++processing_template_decl;
22408 	      tree type = tsubst (TREE_TYPE (parm), full_targs, complain,
22409 				  NULL_TREE);
22410 	      --processing_template_decl;
22411 	      if (type == error_mark_node)
22412 		arg = error_mark_node;
22413 	      else
22414 		arg = NULL_TREE;
22415 	    }
22416 	  else
22417 	    {
22418 	      /* Even if the call is happening in template context, getting
22419 		 here means it's non-dependent, and a default argument is
22420 		 considered a separate definition under [temp.decls], so we can
22421 		 do this substitution without processing_template_decl.  This
22422 		 is important if the default argument contains something that
22423 		 might be instantiation-dependent like access (87480).  */
22424 	      processing_template_decl_sentinel s;
22425 	      tree substed = NULL_TREE;
22426 	      if (saw_undeduced == 1)
22427 		{
22428 		  /* First instatiate in template context, in case we still
22429 		     depend on undeduced template parameters.  */
22430 		  ++processing_template_decl;
22431 		  substed = tsubst_template_arg (arg, full_targs, complain,
22432 						 NULL_TREE);
22433 		  --processing_template_decl;
22434 		  if (substed != error_mark_node
22435 		      && !uses_template_parms (substed))
22436 		    /* We replaced all the tparms, substitute again out of
22437 		       template context.  */
22438 		    substed = NULL_TREE;
22439 		}
22440 	      if (!substed)
22441 		substed = tsubst_template_arg (arg, full_targs, complain,
22442 					       NULL_TREE);
22443 
22444 	      if (!uses_template_parms (substed))
22445 		arg = convert_template_argument (parm, substed, full_targs,
22446 						 complain, i, NULL_TREE);
22447 	      else if (saw_undeduced == 1)
22448 		arg = NULL_TREE;
22449 	      else
22450 		arg = error_mark_node;
22451 	    }
22452 
22453 	  input_location = save_loc;
22454 	  *checks = get_deferred_access_checks ();
22455 	  pop_deferring_access_checks ();
22456 
22457 	  if (arg == error_mark_node)
22458 	    return 1;
22459 	  else if (arg)
22460 	    {
22461 	      TREE_VEC_ELT (targs, i) = arg;
22462 	      /* The position of the first default template argument,
22463 		 is also the number of non-defaulted arguments in TARGS.
22464 		 Record that.  */
22465 	      if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
22466 		SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
22467 	    }
22468 	}
22469 
22470       if (saw_undeduced++ == 1)
22471 	goto again;
22472     }
22473 
22474   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
22475     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
22476 
22477   return unify_success (explain_p);
22478 }
22479 
22480 /* Subroutine of type_unification_real.  Args are like the variables
22481    at the call site.  ARG is an overloaded function (or template-id);
22482    we try deducing template args from each of the overloads, and if
22483    only one succeeds, we go with that.  Modifies TARGS and returns
22484    true on success.  */
22485 
22486 static bool
resolve_overloaded_unification(tree tparms,tree targs,tree parm,tree arg,unification_kind_t strict,int sub_strict,bool explain_p)22487 resolve_overloaded_unification (tree tparms,
22488 				tree targs,
22489 				tree parm,
22490 				tree arg,
22491 				unification_kind_t strict,
22492 				int sub_strict,
22493 			        bool explain_p)
22494 {
22495   tree tempargs = copy_node (targs);
22496   int good = 0;
22497   tree goodfn = NULL_TREE;
22498   bool addr_p;
22499 
22500   if (TREE_CODE (arg) == ADDR_EXPR)
22501     {
22502       arg = TREE_OPERAND (arg, 0);
22503       addr_p = true;
22504     }
22505   else
22506     addr_p = false;
22507 
22508   if (TREE_CODE (arg) == COMPONENT_REF)
22509     /* Handle `&x' where `x' is some static or non-static member
22510        function name.  */
22511     arg = TREE_OPERAND (arg, 1);
22512 
22513   if (TREE_CODE (arg) == OFFSET_REF)
22514     arg = TREE_OPERAND (arg, 1);
22515 
22516   /* Strip baselink information.  */
22517   if (BASELINK_P (arg))
22518     arg = BASELINK_FUNCTIONS (arg);
22519 
22520   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
22521     {
22522       /* If we got some explicit template args, we need to plug them into
22523 	 the affected templates before we try to unify, in case the
22524 	 explicit args will completely resolve the templates in question.  */
22525 
22526       int ok = 0;
22527       tree expl_subargs = TREE_OPERAND (arg, 1);
22528       arg = TREE_OPERAND (arg, 0);
22529 
22530       for (lkp_iterator iter (arg); iter; ++iter)
22531 	{
22532 	  tree fn = *iter;
22533 	  tree subargs, elem;
22534 
22535 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
22536 	    continue;
22537 
22538 	  subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
22539 					   expl_subargs, NULL_TREE, tf_none,
22540 					   /*require_all_args=*/true,
22541 					   /*use_default_args=*/true);
22542 	  if (subargs != error_mark_node
22543 	      && !any_dependent_template_arguments_p (subargs))
22544 	    {
22545 	      fn = instantiate_template (fn, subargs, tf_none);
22546 	      if (!constraints_satisfied_p (fn))
22547 		continue;
22548 	      if (undeduced_auto_decl (fn))
22549 		{
22550 		  /* Instantiate the function to deduce its return type.  */
22551 		  ++function_depth;
22552 		  instantiate_decl (fn, /*defer*/false, /*class*/false);
22553 		  --function_depth;
22554 		}
22555 
22556 	      if (flag_noexcept_type)
22557 		maybe_instantiate_noexcept (fn, tf_none);
22558 
22559 	      elem = TREE_TYPE (fn);
22560 	      if (try_one_overload (tparms, targs, tempargs, parm,
22561 				    elem, strict, sub_strict, addr_p, explain_p)
22562 		  && (!goodfn || !same_type_p (goodfn, elem)))
22563 		{
22564 		  goodfn = elem;
22565 		  ++good;
22566 		}
22567 	    }
22568 	  else if (subargs)
22569 	    ++ok;
22570 	}
22571       /* If no templates (or more than one) are fully resolved by the
22572 	 explicit arguments, this template-id is a non-deduced context; it
22573 	 could still be OK if we deduce all template arguments for the
22574 	 enclosing call through other arguments.  */
22575       if (good != 1)
22576 	good = ok;
22577     }
22578   else if (!OVL_P (arg))
22579     /* If ARG is, for example, "(0, &f)" then its type will be unknown
22580        -- but the deduction does not succeed because the expression is
22581        not just the function on its own.  */
22582     return false;
22583   else
22584     for (lkp_iterator iter (arg); iter; ++iter)
22585       {
22586 	tree fn = *iter;
22587 	if (try_one_overload (tparms, targs, tempargs, parm, TREE_TYPE (fn),
22588 			      strict, sub_strict, addr_p, explain_p)
22589 	    && (!goodfn || !decls_match (goodfn, fn)))
22590 	  {
22591 	    goodfn = fn;
22592 	    ++good;
22593 	  }
22594       }
22595 
22596   /* [temp.deduct.type] A template-argument can be deduced from a pointer
22597      to function or pointer to member function argument if the set of
22598      overloaded functions does not contain function templates and at most
22599      one of a set of overloaded functions provides a unique match.
22600 
22601      So if we found multiple possibilities, we return success but don't
22602      deduce anything.  */
22603 
22604   if (good == 1)
22605     {
22606       int i = TREE_VEC_LENGTH (targs);
22607       for (; i--; )
22608 	if (TREE_VEC_ELT (tempargs, i))
22609 	  {
22610 	    tree old = TREE_VEC_ELT (targs, i);
22611 	    tree new_ = TREE_VEC_ELT (tempargs, i);
22612 	    if (new_ && old && ARGUMENT_PACK_P (old)
22613 		&& ARGUMENT_PACK_EXPLICIT_ARGS (old))
22614 	      /* Don't forget explicit template arguments in a pack.  */
22615 	      ARGUMENT_PACK_EXPLICIT_ARGS (new_)
22616 		= ARGUMENT_PACK_EXPLICIT_ARGS (old);
22617 	    TREE_VEC_ELT (targs, i) = new_;
22618 	  }
22619     }
22620   if (good)
22621     return true;
22622 
22623   return false;
22624 }
22625 
22626 /* Core DR 115: In contexts where deduction is done and fails, or in
22627    contexts where deduction is not done, if a template argument list is
22628    specified and it, along with any default template arguments, identifies
22629    a single function template specialization, then the template-id is an
22630    lvalue for the function template specialization.  */
22631 
22632 tree
resolve_nondeduced_context(tree orig_expr,tsubst_flags_t complain)22633 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
22634 {
22635   tree expr, offset, baselink;
22636   bool addr;
22637 
22638   if (!type_unknown_p (orig_expr))
22639     return orig_expr;
22640 
22641   expr = orig_expr;
22642   addr = false;
22643   offset = NULL_TREE;
22644   baselink = NULL_TREE;
22645 
22646   if (TREE_CODE (expr) == ADDR_EXPR)
22647     {
22648       expr = TREE_OPERAND (expr, 0);
22649       addr = true;
22650     }
22651   if (TREE_CODE (expr) == OFFSET_REF)
22652     {
22653       offset = expr;
22654       expr = TREE_OPERAND (expr, 1);
22655     }
22656   if (BASELINK_P (expr))
22657     {
22658       baselink = expr;
22659       expr = BASELINK_FUNCTIONS (expr);
22660     }
22661 
22662   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
22663     {
22664       int good = 0;
22665       tree goodfn = NULL_TREE;
22666 
22667       /* If we got some explicit template args, we need to plug them into
22668 	 the affected templates before we try to unify, in case the
22669 	 explicit args will completely resolve the templates in question.  */
22670 
22671       tree expl_subargs = TREE_OPERAND (expr, 1);
22672       tree arg = TREE_OPERAND (expr, 0);
22673       tree badfn = NULL_TREE;
22674       tree badargs = NULL_TREE;
22675 
22676       for (lkp_iterator iter (arg); iter; ++iter)
22677 	{
22678 	  tree fn = *iter;
22679 	  tree subargs, elem;
22680 
22681 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
22682 	    continue;
22683 
22684 	  subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
22685 					   expl_subargs, NULL_TREE, tf_none,
22686 					   /*require_all_args=*/true,
22687 					   /*use_default_args=*/true);
22688 	  if (subargs != error_mark_node
22689 	      && !any_dependent_template_arguments_p (subargs))
22690 	    {
22691 	      elem = instantiate_template (fn, subargs, tf_none);
22692 	      if (elem == error_mark_node)
22693 		{
22694 		  badfn = fn;
22695 		  badargs = subargs;
22696 		}
22697 	      else if (elem && (!goodfn || !decls_match (goodfn, elem))
22698 		       && constraints_satisfied_p (elem))
22699 		{
22700 		  goodfn = elem;
22701 		  ++good;
22702 		}
22703 	    }
22704 	}
22705       if (good == 1)
22706 	{
22707 	  mark_used (goodfn);
22708 	  expr = goodfn;
22709 	  if (baselink)
22710 	    expr = build_baselink (BASELINK_BINFO (baselink),
22711 				   BASELINK_ACCESS_BINFO (baselink),
22712 				   expr, BASELINK_OPTYPE (baselink));
22713 	  if (offset)
22714 	    {
22715 	      tree base
22716 		= TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
22717 	      expr = build_offset_ref (base, expr, addr, complain);
22718 	    }
22719 	  if (addr)
22720 	    expr = cp_build_addr_expr (expr, complain);
22721 	  return expr;
22722 	}
22723       else if (good == 0 && badargs && (complain & tf_error))
22724 	/* There were no good options and at least one bad one, so let the
22725 	   user know what the problem is.  */
22726 	instantiate_template (badfn, badargs, complain);
22727     }
22728   return orig_expr;
22729 }
22730 
22731 /* As above, but error out if the expression remains overloaded.  */
22732 
22733 tree
resolve_nondeduced_context_or_error(tree exp,tsubst_flags_t complain)22734 resolve_nondeduced_context_or_error (tree exp, tsubst_flags_t complain)
22735 {
22736   exp = resolve_nondeduced_context (exp, complain);
22737   if (type_unknown_p (exp))
22738     {
22739       if (complain & tf_error)
22740 	cxx_incomplete_type_error (exp, TREE_TYPE (exp));
22741       return error_mark_node;
22742     }
22743   return exp;
22744 }
22745 
22746 /* Subroutine of resolve_overloaded_unification; does deduction for a single
22747    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
22748    different overloads deduce different arguments for a given parm.
22749    ADDR_P is true if the expression for which deduction is being
22750    performed was of the form "& fn" rather than simply "fn".
22751 
22752    Returns 1 on success.  */
22753 
22754 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)22755 try_one_overload (tree tparms,
22756 		  tree orig_targs,
22757 		  tree targs,
22758 		  tree parm,
22759 		  tree arg,
22760 		  unification_kind_t strict,
22761 		  int sub_strict,
22762 		  bool addr_p,
22763 		  bool explain_p)
22764 {
22765   int nargs;
22766   tree tempargs;
22767   int i;
22768 
22769   if (arg == error_mark_node)
22770     return 0;
22771 
22772   /* [temp.deduct.type] A template-argument can be deduced from a pointer
22773      to function or pointer to member function argument if the set of
22774      overloaded functions does not contain function templates and at most
22775      one of a set of overloaded functions provides a unique match.
22776 
22777      So if this is a template, just return success.  */
22778 
22779   if (uses_template_parms (arg))
22780     return 1;
22781 
22782   if (TREE_CODE (arg) == METHOD_TYPE)
22783     arg = build_ptrmemfunc_type (build_pointer_type (arg));
22784   else if (addr_p)
22785     arg = build_pointer_type (arg);
22786 
22787   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
22788 
22789   /* We don't copy orig_targs for this because if we have already deduced
22790      some template args from previous args, unify would complain when we
22791      try to deduce a template parameter for the same argument, even though
22792      there isn't really a conflict.  */
22793   nargs = TREE_VEC_LENGTH (targs);
22794   tempargs = make_tree_vec (nargs);
22795 
22796   if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
22797     return 0;
22798 
22799   /* First make sure we didn't deduce anything that conflicts with
22800      explicitly specified args.  */
22801   for (i = nargs; i--; )
22802     {
22803       tree elt = TREE_VEC_ELT (tempargs, i);
22804       tree oldelt = TREE_VEC_ELT (orig_targs, i);
22805 
22806       if (!elt)
22807 	/*NOP*/;
22808       else if (uses_template_parms (elt))
22809 	/* Since we're unifying against ourselves, we will fill in
22810 	   template args used in the function parm list with our own
22811 	   template parms.  Discard them.  */
22812 	TREE_VEC_ELT (tempargs, i) = NULL_TREE;
22813       else if (oldelt && ARGUMENT_PACK_P (oldelt))
22814 	{
22815 	  /* Check that the argument at each index of the deduced argument pack
22816 	     is equivalent to the corresponding explicitly specified argument.
22817 	     We may have deduced more arguments than were explicitly specified,
22818 	     and that's OK.  */
22819 
22820 	  /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
22821 	     that's wrong if we deduce the same argument pack from multiple
22822 	     function arguments: it's only incomplete the first time.  */
22823 
22824 	  tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
22825 	  tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
22826 
22827 	  if (TREE_VEC_LENGTH (deduced_pack)
22828 	      < TREE_VEC_LENGTH (explicit_pack))
22829 	    return 0;
22830 
22831 	  for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
22832 	    if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
22833 				      TREE_VEC_ELT (deduced_pack, j)))
22834 	      return 0;
22835 	}
22836       else if (oldelt && !template_args_equal (oldelt, elt))
22837 	return 0;
22838     }
22839 
22840   for (i = nargs; i--; )
22841     {
22842       tree elt = TREE_VEC_ELT (tempargs, i);
22843 
22844       if (elt)
22845 	TREE_VEC_ELT (targs, i) = elt;
22846     }
22847 
22848   return 1;
22849 }
22850 
22851 /* PARM is a template class (perhaps with unbound template
22852    parameters).  ARG is a fully instantiated type.  If ARG can be
22853    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
22854    TARGS are as for unify.  */
22855 
22856 static tree
try_class_unification(tree tparms,tree targs,tree parm,tree arg,bool explain_p)22857 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
22858 		       bool explain_p)
22859 {
22860   tree copy_of_targs;
22861 
22862   if (!CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
22863     return NULL_TREE;
22864   else if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
22865     /* Matches anything.  */;
22866   else if (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
22867 	   != most_general_template (CLASSTYPE_TI_TEMPLATE (parm)))
22868     return NULL_TREE;
22869 
22870   /* We need to make a new template argument vector for the call to
22871      unify.  If we used TARGS, we'd clutter it up with the result of
22872      the attempted unification, even if this class didn't work out.
22873      We also don't want to commit ourselves to all the unifications
22874      we've already done, since unification is supposed to be done on
22875      an argument-by-argument basis.  In other words, consider the
22876      following pathological case:
22877 
22878        template <int I, int J, int K>
22879        struct S {};
22880 
22881        template <int I, int J>
22882        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
22883 
22884        template <int I, int J, int K>
22885        void f(S<I, J, K>, S<I, I, I>);
22886 
22887        void g() {
22888 	 S<0, 0, 0> s0;
22889 	 S<0, 1, 2> s2;
22890 
22891 	 f(s0, s2);
22892        }
22893 
22894      Now, by the time we consider the unification involving `s2', we
22895      already know that we must have `f<0, 0, 0>'.  But, even though
22896      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
22897      because there are two ways to unify base classes of S<0, 1, 2>
22898      with S<I, I, I>.  If we kept the already deduced knowledge, we
22899      would reject the possibility I=1.  */
22900   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
22901 
22902   if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
22903     {
22904       if (unify_bound_ttp_args (tparms, copy_of_targs, parm, arg, explain_p))
22905 	return NULL_TREE;
22906       return arg;
22907     }
22908 
22909   /* If unification failed, we're done.  */
22910   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
22911 	     CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
22912     return NULL_TREE;
22913 
22914   return arg;
22915 }
22916 
22917 /* Given a template type PARM and a class type ARG, find the unique
22918    base type in ARG that is an instance of PARM.  We do not examine
22919    ARG itself; only its base-classes.  If there is not exactly one
22920    appropriate base class, return NULL_TREE.  PARM may be the type of
22921    a partial specialization, as well as a plain template type.  Used
22922    by unify.  */
22923 
22924 static enum template_base_result
get_template_base(tree tparms,tree targs,tree parm,tree arg,bool explain_p,tree * result)22925 get_template_base (tree tparms, tree targs, tree parm, tree arg,
22926 		   bool explain_p, tree *result)
22927 {
22928   tree rval = NULL_TREE;
22929   tree binfo;
22930 
22931   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
22932 
22933   binfo = TYPE_BINFO (complete_type (arg));
22934   if (!binfo)
22935     {
22936       /* The type could not be completed.  */
22937       *result = NULL_TREE;
22938       return tbr_incomplete_type;
22939     }
22940 
22941   /* Walk in inheritance graph order.  The search order is not
22942      important, and this avoids multiple walks of virtual bases.  */
22943   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
22944     {
22945       tree r = try_class_unification (tparms, targs, parm,
22946 				      BINFO_TYPE (binfo), explain_p);
22947 
22948       if (r)
22949 	{
22950 	  /* If there is more than one satisfactory baseclass, then:
22951 
22952 	       [temp.deduct.call]
22953 
22954 	      If they yield more than one possible deduced A, the type
22955 	      deduction fails.
22956 
22957 	     applies.  */
22958 	  if (rval && !same_type_p (r, rval))
22959 	    {
22960 	      /* [temp.deduct.call]/4.3: If there is a class C that is a
22961 		 (direct or indirect) base class of D and derived (directly or
22962 		 indirectly) from a class B and that would be a valid deduced
22963 		 A, the deduced A cannot be B or pointer to B, respectively. */
22964 	      if (DERIVED_FROM_P (r, rval))
22965 		/* Ignore r.  */
22966 		continue;
22967 	      else if (DERIVED_FROM_P (rval, r))
22968 		/* Ignore rval.  */;
22969 	      else
22970 		{
22971 		  *result = NULL_TREE;
22972 		  return tbr_ambiguous_baseclass;
22973 		}
22974 	    }
22975 
22976 	  rval = r;
22977 	}
22978     }
22979 
22980   *result = rval;
22981   return tbr_success;
22982 }
22983 
22984 /* Returns the level of DECL, which declares a template parameter.  */
22985 
22986 static int
template_decl_level(tree decl)22987 template_decl_level (tree decl)
22988 {
22989   switch (TREE_CODE (decl))
22990     {
22991     case TYPE_DECL:
22992     case TEMPLATE_DECL:
22993       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
22994 
22995     case PARM_DECL:
22996       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
22997 
22998     default:
22999       gcc_unreachable ();
23000     }
23001   return 0;
23002 }
23003 
23004 /* Decide whether ARG can be unified with PARM, considering only the
23005    cv-qualifiers of each type, given STRICT as documented for unify.
23006    Returns nonzero iff the unification is OK on that basis.  */
23007 
23008 static int
check_cv_quals_for_unify(int strict,tree arg,tree parm)23009 check_cv_quals_for_unify (int strict, tree arg, tree parm)
23010 {
23011   int arg_quals = cp_type_quals (arg);
23012   int parm_quals = cp_type_quals (parm);
23013 
23014   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
23015       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
23016     {
23017       /*  Although a CVR qualifier is ignored when being applied to a
23018 	  substituted template parameter ([8.3.2]/1 for example), that
23019 	  does not allow us to unify "const T" with "int&" because both
23020 	  types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
23021 	  It is ok when we're allowing additional CV qualifiers
23022 	  at the outer level [14.8.2.1]/3,1st bullet.  */
23023       if ((TYPE_REF_P (arg)
23024 	   || FUNC_OR_METHOD_TYPE_P (arg))
23025 	  && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
23026 	return 0;
23027 
23028       if ((!INDIRECT_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
23029 	  && (parm_quals & TYPE_QUAL_RESTRICT))
23030 	return 0;
23031     }
23032 
23033   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
23034       && (arg_quals & parm_quals) != parm_quals)
23035     return 0;
23036 
23037   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
23038       && (parm_quals & arg_quals) != arg_quals)
23039     return 0;
23040 
23041   return 1;
23042 }
23043 
23044 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
23045 void
template_parm_level_and_index(tree parm,int * level,int * index)23046 template_parm_level_and_index (tree parm, int* level, int* index)
23047 {
23048   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
23049       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
23050       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23051     {
23052       *index = TEMPLATE_TYPE_IDX (parm);
23053       *level = TEMPLATE_TYPE_LEVEL (parm);
23054     }
23055   else
23056     {
23057       *index = TEMPLATE_PARM_IDX (parm);
23058       *level = TEMPLATE_PARM_LEVEL (parm);
23059     }
23060 }
23061 
23062 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)			\
23063   do {									\
23064     if (unify (TP, TA, P, A, S, EP))					\
23065       return 1;								\
23066   } while (0)
23067 
23068 /* Unifies the remaining arguments in PACKED_ARGS with the pack
23069    expansion at the end of PACKED_PARMS. Returns 0 if the type
23070    deduction succeeds, 1 otherwise. STRICT is the same as in
23071    fn_type_unification. CALL_ARGS_P is true iff PACKED_ARGS is actually a
23072    function call argument list. We'll need to adjust the arguments to make them
23073    types. SUBR tells us if this is from a recursive call to
23074    type_unification_real, or for comparing two template argument
23075    lists. */
23076 
23077 static int
unify_pack_expansion(tree tparms,tree targs,tree packed_parms,tree packed_args,unification_kind_t strict,bool subr,bool explain_p)23078 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
23079                       tree packed_args, unification_kind_t strict,
23080                       bool subr, bool explain_p)
23081 {
23082   tree parm
23083     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
23084   tree pattern = PACK_EXPANSION_PATTERN (parm);
23085   tree pack, packs = NULL_TREE;
23086   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
23087 
23088   /* Add in any args remembered from an earlier partial instantiation.  */
23089   targs = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (parm), targs);
23090   int levels = TMPL_ARGS_DEPTH (targs);
23091 
23092   packed_args = expand_template_argument_pack (packed_args);
23093 
23094   int len = TREE_VEC_LENGTH (packed_args);
23095 
23096   /* Determine the parameter packs we will be deducing from the
23097      pattern, and record their current deductions.  */
23098   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
23099        pack; pack = TREE_CHAIN (pack))
23100     {
23101       tree parm_pack = TREE_VALUE (pack);
23102       int idx, level;
23103 
23104       /* Only template parameter packs can be deduced, not e.g. function
23105 	 parameter packs or __bases or __integer_pack.  */
23106       if (!TEMPLATE_PARM_P (parm_pack))
23107 	continue;
23108 
23109       /* Determine the index and level of this parameter pack.  */
23110       template_parm_level_and_index (parm_pack, &level, &idx);
23111       if (level < levels)
23112 	continue;
23113 
23114       /* Keep track of the parameter packs and their corresponding
23115          argument packs.  */
23116       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
23117       TREE_TYPE (packs) = make_tree_vec (len - start);
23118     }
23119 
23120   /* Loop through all of the arguments that have not yet been
23121      unified and unify each with the pattern.  */
23122   for (i = start; i < len; i++)
23123     {
23124       tree parm;
23125       bool any_explicit = false;
23126       tree arg = TREE_VEC_ELT (packed_args, i);
23127 
23128       /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
23129 	 or the element of its argument pack at the current index if
23130 	 this argument was explicitly specified.  */
23131       for (pack = packs; pack; pack = TREE_CHAIN (pack))
23132         {
23133           int idx, level;
23134           tree arg, pargs;
23135           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
23136 
23137           arg = NULL_TREE;
23138           if (TREE_VALUE (pack)
23139               && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
23140               && (i - start < TREE_VEC_LENGTH (pargs)))
23141             {
23142               any_explicit = true;
23143               arg = TREE_VEC_ELT (pargs, i - start);
23144             }
23145           TMPL_ARG (targs, level, idx) = arg;
23146         }
23147 
23148       /* If we had explicit template arguments, substitute them into the
23149 	 pattern before deduction.  */
23150       if (any_explicit)
23151 	{
23152 	  /* Some arguments might still be unspecified or dependent.  */
23153 	  bool dependent;
23154 	  ++processing_template_decl;
23155 	  dependent = any_dependent_template_arguments_p (targs);
23156 	  if (!dependent)
23157 	    --processing_template_decl;
23158 	  parm = tsubst (pattern, targs,
23159 			 explain_p ? tf_warning_or_error : tf_none,
23160 			 NULL_TREE);
23161 	  if (dependent)
23162 	    --processing_template_decl;
23163 	  if (parm == error_mark_node)
23164 	    return 1;
23165 	}
23166       else
23167 	parm = pattern;
23168 
23169       /* Unify the pattern with the current argument.  */
23170       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
23171 			      explain_p))
23172 	return 1;
23173 
23174       /* For each parameter pack, collect the deduced value.  */
23175       for (pack = packs; pack; pack = TREE_CHAIN (pack))
23176         {
23177           int idx, level;
23178           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
23179 
23180           TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
23181             TMPL_ARG (targs, level, idx);
23182         }
23183     }
23184 
23185   /* Verify that the results of unification with the parameter packs
23186      produce results consistent with what we've seen before, and make
23187      the deduced argument packs available.  */
23188   for (pack = packs; pack; pack = TREE_CHAIN (pack))
23189     {
23190       tree old_pack = TREE_VALUE (pack);
23191       tree new_args = TREE_TYPE (pack);
23192       int i, len = TREE_VEC_LENGTH (new_args);
23193       int idx, level;
23194       bool nondeduced_p = false;
23195 
23196       /* By default keep the original deduced argument pack.
23197 	 If necessary, more specific code is going to update the
23198 	 resulting deduced argument later down in this function.  */
23199       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
23200       TMPL_ARG (targs, level, idx) = old_pack;
23201 
23202       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
23203 	 actually deduce anything.  */
23204       for (i = 0; i < len && !nondeduced_p; ++i)
23205 	if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
23206 	  nondeduced_p = true;
23207       if (nondeduced_p)
23208 	continue;
23209 
23210       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
23211         {
23212           /* If we had fewer function args than explicit template args,
23213              just use the explicits.  */
23214           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
23215           int explicit_len = TREE_VEC_LENGTH (explicit_args);
23216           if (len < explicit_len)
23217             new_args = explicit_args;
23218         }
23219 
23220       if (!old_pack)
23221         {
23222           tree result;
23223           /* Build the deduced *_ARGUMENT_PACK.  */
23224           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
23225             {
23226               result = make_node (NONTYPE_ARGUMENT_PACK);
23227               TREE_CONSTANT (result) = 1;
23228             }
23229           else
23230 	    result = cxx_make_type (TYPE_ARGUMENT_PACK);
23231 
23232           SET_ARGUMENT_PACK_ARGS (result, new_args);
23233 
23234           /* Note the deduced argument packs for this parameter
23235              pack.  */
23236           TMPL_ARG (targs, level, idx) = result;
23237         }
23238       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
23239                && (ARGUMENT_PACK_ARGS (old_pack)
23240                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
23241         {
23242           /* We only had the explicitly-provided arguments before, but
23243              now we have a complete set of arguments.  */
23244           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
23245 
23246           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
23247           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
23248           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
23249         }
23250       else
23251 	{
23252 	  tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
23253 	  tree old_args = ARGUMENT_PACK_ARGS (old_pack);
23254 	  temp_override<int> ovl (TREE_VEC_LENGTH (old_args));
23255 	  /* During template argument deduction for the aggregate deduction
23256 	     candidate, the number of elements in a trailing parameter pack
23257 	     is only deduced from the number of remaining function
23258 	     arguments if it is not otherwise deduced.  */
23259 	  if (cxx_dialect >= cxx20
23260 	      && TREE_VEC_LENGTH (new_args) < TREE_VEC_LENGTH (old_args)
23261 	      && builtin_guide_p (TPARMS_PRIMARY_TEMPLATE (tparms)))
23262 	    TREE_VEC_LENGTH (old_args) = TREE_VEC_LENGTH (new_args);
23263 	  if (!comp_template_args (old_args, new_args,
23264 				   &bad_old_arg, &bad_new_arg))
23265 	    /* Inconsistent unification of this parameter pack.  */
23266 	    return unify_parameter_pack_inconsistent (explain_p,
23267 						      bad_old_arg,
23268 						      bad_new_arg);
23269 	}
23270     }
23271 
23272   return unify_success (explain_p);
23273 }
23274 
23275 /* Handle unification of the domain of an array.  PARM_DOM and ARG_DOM are
23276    INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs.  The other
23277    parameters and return value are as for unify.  */
23278 
23279 static int
unify_array_domain(tree tparms,tree targs,tree parm_dom,tree arg_dom,bool explain_p)23280 unify_array_domain (tree tparms, tree targs,
23281 		    tree parm_dom, tree arg_dom,
23282 		    bool explain_p)
23283 {
23284   tree parm_max;
23285   tree arg_max;
23286   bool parm_cst;
23287   bool arg_cst;
23288 
23289   /* Our representation of array types uses "N - 1" as the
23290      TYPE_MAX_VALUE for an array with "N" elements, if "N" is
23291      not an integer constant.  We cannot unify arbitrarily
23292      complex expressions, so we eliminate the MINUS_EXPRs
23293      here.  */
23294   parm_max = TYPE_MAX_VALUE (parm_dom);
23295   parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
23296   if (!parm_cst)
23297     {
23298       gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
23299       parm_max = TREE_OPERAND (parm_max, 0);
23300     }
23301   arg_max = TYPE_MAX_VALUE (arg_dom);
23302   arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
23303   if (!arg_cst)
23304     {
23305       /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
23306 	 trying to unify the type of a variable with the type
23307 	 of a template parameter.  For example:
23308 
23309 	   template <unsigned int N>
23310 	   void f (char (&) [N]);
23311 	   int g();
23312 	   void h(int i) {
23313 	     char a[g(i)];
23314 	     f(a);
23315 	   }
23316 
23317 	 Here, the type of the ARG will be "int [g(i)]", and
23318 	 may be a SAVE_EXPR, etc.  */
23319       if (TREE_CODE (arg_max) != MINUS_EXPR)
23320 	return unify_vla_arg (explain_p, arg_dom);
23321       arg_max = TREE_OPERAND (arg_max, 0);
23322     }
23323 
23324   /* If only one of the bounds used a MINUS_EXPR, compensate
23325      by adding one to the other bound.  */
23326   if (parm_cst && !arg_cst)
23327     parm_max = fold_build2_loc (input_location, PLUS_EXPR,
23328 				integer_type_node,
23329 				parm_max,
23330 				integer_one_node);
23331   else if (arg_cst && !parm_cst)
23332     arg_max = fold_build2_loc (input_location, PLUS_EXPR,
23333 			       integer_type_node,
23334 			       arg_max,
23335 			       integer_one_node);
23336 
23337   return unify (tparms, targs, parm_max, arg_max,
23338 		UNIFY_ALLOW_INTEGER, explain_p);
23339 }
23340 
23341 /* Returns whether T, a P or A in unify, is a type, template or expression.  */
23342 
23343 enum pa_kind_t { pa_type, pa_tmpl, pa_expr };
23344 
23345 static pa_kind_t
pa_kind(tree t)23346 pa_kind (tree t)
23347 {
23348   if (PACK_EXPANSION_P (t))
23349     t = PACK_EXPANSION_PATTERN (t);
23350   if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
23351       || TREE_CODE (t) == UNBOUND_CLASS_TEMPLATE
23352       || DECL_TYPE_TEMPLATE_P (t))
23353     return pa_tmpl;
23354   else if (TYPE_P (t))
23355     return pa_type;
23356   else
23357     return pa_expr;
23358 }
23359 
23360 /* Deduce the value of template parameters.  TPARMS is the (innermost)
23361    set of template parameters to a template.  TARGS is the bindings
23362    for those template parameters, as determined thus far; TARGS may
23363    include template arguments for outer levels of template parameters
23364    as well.  PARM is a parameter to a template function, or a
23365    subcomponent of that parameter; ARG is the corresponding argument.
23366    This function attempts to match PARM with ARG in a manner
23367    consistent with the existing assignments in TARGS.  If more values
23368    are deduced, then TARGS is updated.
23369 
23370    Returns 0 if the type deduction succeeds, 1 otherwise.  The
23371    parameter STRICT is a bitwise or of the following flags:
23372 
23373      UNIFY_ALLOW_NONE:
23374        Require an exact match between PARM and ARG.
23375      UNIFY_ALLOW_MORE_CV_QUAL:
23376        Allow the deduced ARG to be more cv-qualified (by qualification
23377        conversion) than ARG.
23378      UNIFY_ALLOW_LESS_CV_QUAL:
23379        Allow the deduced ARG to be less cv-qualified than ARG.
23380      UNIFY_ALLOW_DERIVED:
23381        Allow the deduced ARG to be a template base class of ARG,
23382        or a pointer to a template base class of the type pointed to by
23383        ARG.
23384      UNIFY_ALLOW_INTEGER:
23385        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
23386        case for more information.
23387      UNIFY_ALLOW_OUTER_LEVEL:
23388        This is the outermost level of a deduction. Used to determine validity
23389        of qualification conversions. A valid qualification conversion must
23390        have const qualified pointers leading up to the inner type which
23391        requires additional CV quals, except at the outer level, where const
23392        is not required [conv.qual]. It would be normal to set this flag in
23393        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
23394      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
23395        This is the outermost level of a deduction, and PARM can be more CV
23396        qualified at this point.
23397      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
23398        This is the outermost level of a deduction, and PARM can be less CV
23399        qualified at this point.  */
23400 
23401 static int
unify(tree tparms,tree targs,tree parm,tree arg,int strict,bool explain_p)23402 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
23403        bool explain_p)
23404 {
23405   int idx;
23406   tree targ;
23407   tree tparm;
23408   int strict_in = strict;
23409   tsubst_flags_t complain = (explain_p
23410 			     ? tf_warning_or_error
23411 			     : tf_none);
23412 
23413   /* I don't think this will do the right thing with respect to types.
23414      But the only case I've seen it in so far has been array bounds, where
23415      signedness is the only information lost, and I think that will be
23416      okay.  VIEW_CONVERT_EXPR can appear with class NTTP, thanks to
23417      finish_id_expression_1, and are also OK.  */
23418   while (CONVERT_EXPR_P (parm) || TREE_CODE (parm) == VIEW_CONVERT_EXPR)
23419     parm = TREE_OPERAND (parm, 0);
23420 
23421   if (arg == error_mark_node)
23422     return unify_invalid (explain_p);
23423   if (arg == unknown_type_node
23424       || arg == init_list_type_node)
23425     /* We can't deduce anything from this, but we might get all the
23426        template args from other function args.  */
23427     return unify_success (explain_p);
23428 
23429   if (parm == any_targ_node || arg == any_targ_node)
23430     return unify_success (explain_p);
23431 
23432   /* If PARM uses template parameters, then we can't bail out here,
23433      even if ARG == PARM, since we won't record unifications for the
23434      template parameters.  We might need them if we're trying to
23435      figure out which of two things is more specialized.  */
23436   if (arg == parm && !uses_template_parms (parm))
23437     return unify_success (explain_p);
23438 
23439   /* Handle init lists early, so the rest of the function can assume
23440      we're dealing with a type. */
23441   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
23442     {
23443       tree elt, elttype;
23444       unsigned i;
23445       tree orig_parm = parm;
23446 
23447       if (!is_std_init_list (parm)
23448 	  && TREE_CODE (parm) != ARRAY_TYPE)
23449 	/* We can only deduce from an initializer list argument if the
23450 	   parameter is std::initializer_list or an array; otherwise this
23451 	   is a non-deduced context. */
23452 	return unify_success (explain_p);
23453 
23454       if (TREE_CODE (parm) == ARRAY_TYPE)
23455 	elttype = TREE_TYPE (parm);
23456       else
23457 	{
23458 	  elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
23459 	  /* Deduction is defined in terms of a single type, so just punt
23460 	     on the (bizarre) std::initializer_list<T...>.  */
23461 	  if (PACK_EXPANSION_P (elttype))
23462 	    return unify_success (explain_p);
23463 	}
23464 
23465       if (strict != DEDUCE_EXACT
23466 	  && TYPE_P (elttype)
23467 	  && !uses_deducible_template_parms (elttype))
23468 	/* If ELTTYPE has no deducible template parms, skip deduction from
23469 	   the list elements.  */;
23470       else
23471 	FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
23472 	  {
23473 	    int elt_strict = strict;
23474 
23475 	    if (elt == error_mark_node)
23476 	      return unify_invalid (explain_p);
23477 
23478 	    if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
23479 	      {
23480 		tree type = TREE_TYPE (elt);
23481 		if (type == error_mark_node)
23482 		  return unify_invalid (explain_p);
23483 		/* It should only be possible to get here for a call.  */
23484 		gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
23485 		elt_strict |= maybe_adjust_types_for_deduction
23486 		  (DEDUCE_CALL, &elttype, &type, elt);
23487 		elt = type;
23488 	      }
23489 
23490 	  RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
23491 				   explain_p);
23492 	}
23493 
23494       if (TREE_CODE (parm) == ARRAY_TYPE
23495 	  && deducible_array_bound (TYPE_DOMAIN (parm)))
23496 	{
23497 	  /* Also deduce from the length of the initializer list.  */
23498 	  tree max = size_int (CONSTRUCTOR_NELTS (arg));
23499 	  tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
23500 	  if (idx == error_mark_node)
23501 	    return unify_invalid (explain_p);
23502 	  return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
23503 				     idx, explain_p);
23504 	}
23505 
23506       /* If the std::initializer_list<T> deduction worked, replace the
23507 	 deduced A with std::initializer_list<A>.  */
23508       if (orig_parm != parm)
23509 	{
23510 	  idx = TEMPLATE_TYPE_IDX (orig_parm);
23511 	  targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
23512 	  targ = listify (targ);
23513 	  TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
23514 	}
23515       return unify_success (explain_p);
23516     }
23517 
23518   /* If parm and arg aren't the same kind of thing (template, type, or
23519      expression), fail early.  */
23520   if (pa_kind (parm) != pa_kind (arg))
23521     return unify_invalid (explain_p);
23522 
23523   /* Immediately reject some pairs that won't unify because of
23524      cv-qualification mismatches.  */
23525   if (TREE_CODE (arg) == TREE_CODE (parm)
23526       && TYPE_P (arg)
23527       /* It is the elements of the array which hold the cv quals of an array
23528 	 type, and the elements might be template type parms. We'll check
23529 	 when we recurse.  */
23530       && TREE_CODE (arg) != ARRAY_TYPE
23531       /* We check the cv-qualifiers when unifying with template type
23532 	 parameters below.  We want to allow ARG `const T' to unify with
23533 	 PARM `T' for example, when computing which of two templates
23534 	 is more specialized, for example.  */
23535       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
23536       && !check_cv_quals_for_unify (strict_in, arg, parm))
23537     return unify_cv_qual_mismatch (explain_p, parm, arg);
23538 
23539   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
23540       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
23541     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
23542   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
23543   strict &= ~UNIFY_ALLOW_DERIVED;
23544   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
23545   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
23546 
23547   switch (TREE_CODE (parm))
23548     {
23549     case TYPENAME_TYPE:
23550     case SCOPE_REF:
23551     case UNBOUND_CLASS_TEMPLATE:
23552       /* In a type which contains a nested-name-specifier, template
23553 	 argument values cannot be deduced for template parameters used
23554 	 within the nested-name-specifier.  */
23555       return unify_success (explain_p);
23556 
23557     case TEMPLATE_TYPE_PARM:
23558     case TEMPLATE_TEMPLATE_PARM:
23559     case BOUND_TEMPLATE_TEMPLATE_PARM:
23560       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
23561       if (error_operand_p (tparm))
23562 	return unify_invalid (explain_p);
23563 
23564       if (TEMPLATE_TYPE_LEVEL (parm)
23565 	  != template_decl_level (tparm))
23566 	/* The PARM is not one we're trying to unify.  Just check
23567 	   to see if it matches ARG.  */
23568 	{
23569 	  if (TREE_CODE (arg) == TREE_CODE (parm)
23570 	      && (is_auto (parm) ? is_auto (arg)
23571 		  : same_type_p (parm, arg)))
23572 	    return unify_success (explain_p);
23573 	  else
23574 	    return unify_type_mismatch (explain_p, parm, arg);
23575 	}
23576       idx = TEMPLATE_TYPE_IDX (parm);
23577       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
23578       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
23579       if (error_operand_p (tparm))
23580 	return unify_invalid (explain_p);
23581 
23582       /* Check for mixed types and values.  */
23583       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
23584 	   && TREE_CODE (tparm) != TYPE_DECL)
23585 	  || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
23586 	      && TREE_CODE (tparm) != TEMPLATE_DECL))
23587 	gcc_unreachable ();
23588 
23589       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23590 	{
23591 	  if ((strict_in & UNIFY_ALLOW_DERIVED)
23592 	      && CLASS_TYPE_P (arg))
23593 	    {
23594 	      /* First try to match ARG directly.  */
23595 	      tree t = try_class_unification (tparms, targs, parm, arg,
23596 					      explain_p);
23597 	      if (!t)
23598 		{
23599 		  /* Otherwise, look for a suitable base of ARG, as below.  */
23600 		  enum template_base_result r;
23601 		  r = get_template_base (tparms, targs, parm, arg,
23602 					 explain_p, &t);
23603 		  if (!t)
23604 		    return unify_no_common_base (explain_p, r, parm, arg);
23605 		  arg = t;
23606 		}
23607 	    }
23608 	  /* ARG must be constructed from a template class or a template
23609 	     template parameter.  */
23610 	  else if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
23611 		   && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
23612 	    return unify_template_deduction_failure (explain_p, parm, arg);
23613 
23614 	  /* Deduce arguments T, i from TT<T> or TT<i>.  */
23615 	  if (unify_bound_ttp_args (tparms, targs, parm, arg, explain_p))
23616 	    return 1;
23617 
23618 	  arg = TYPE_TI_TEMPLATE (arg);
23619 
23620 	  /* Fall through to deduce template name.  */
23621 	}
23622 
23623       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
23624 	  || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23625 	{
23626 	  /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
23627 
23628 	  /* Simple cases: Value already set, does match or doesn't.  */
23629 	  if (targ != NULL_TREE && template_args_equal (targ, arg))
23630 	    return unify_success (explain_p);
23631 	  else if (targ)
23632 	    return unify_inconsistency (explain_p, parm, targ, arg);
23633 	}
23634       else
23635 	{
23636 	  /* If PARM is `const T' and ARG is only `int', we don't have
23637 	     a match unless we are allowing additional qualification.
23638 	     If ARG is `const int' and PARM is just `T' that's OK;
23639 	     that binds `const int' to `T'.  */
23640 	  if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
23641 					 arg, parm))
23642 	    return unify_cv_qual_mismatch (explain_p, parm, arg);
23643 
23644 	  /* Consider the case where ARG is `const volatile int' and
23645 	     PARM is `const T'.  Then, T should be `volatile int'.  */
23646 	  arg = cp_build_qualified_type_real
23647 	    (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
23648 	  if (arg == error_mark_node)
23649 	    return unify_invalid (explain_p);
23650 
23651 	  /* Simple cases: Value already set, does match or doesn't.  */
23652 	  if (targ != NULL_TREE && same_type_p (targ, arg))
23653 	    return unify_success (explain_p);
23654 	  else if (targ)
23655 	    return unify_inconsistency (explain_p, parm, targ, arg);
23656 
23657 	  /* Make sure that ARG is not a variable-sized array.  (Note
23658 	     that were talking about variable-sized arrays (like
23659 	     `int[n]'), rather than arrays of unknown size (like
23660 	     `int[]').)  We'll get very confused by such a type since
23661 	     the bound of the array is not constant, and therefore
23662 	     not mangleable.  Besides, such types are not allowed in
23663 	     ISO C++, so we can do as we please here.  We do allow
23664 	     them for 'auto' deduction, since that isn't ABI-exposed.  */
23665 	  if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
23666 	    return unify_vla_arg (explain_p, arg);
23667 
23668 	  /* Strip typedefs as in convert_template_argument.  */
23669 	  arg = canonicalize_type_argument (arg, tf_none);
23670 	}
23671 
23672       /* If ARG is a parameter pack or an expansion, we cannot unify
23673 	 against it unless PARM is also a parameter pack.  */
23674       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
23675 	  && !template_parameter_pack_p (parm))
23676 	return unify_parameter_pack_mismatch (explain_p, parm, arg);
23677 
23678       /* If the argument deduction results is a METHOD_TYPE,
23679          then there is a problem.
23680          METHOD_TYPE doesn't map to any real C++ type the result of
23681 	 the deduction cannot be of that type.  */
23682       if (TREE_CODE (arg) == METHOD_TYPE)
23683 	return unify_method_type_error (explain_p, arg);
23684 
23685       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
23686       return unify_success (explain_p);
23687 
23688     case TEMPLATE_PARM_INDEX:
23689       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
23690       if (error_operand_p (tparm))
23691 	return unify_invalid (explain_p);
23692 
23693       if (TEMPLATE_PARM_LEVEL (parm)
23694 	  != template_decl_level (tparm))
23695 	{
23696 	  /* The PARM is not one we're trying to unify.  Just check
23697 	     to see if it matches ARG.  */
23698 	  int result = !(TREE_CODE (arg) == TREE_CODE (parm)
23699 			 && cp_tree_equal (parm, arg));
23700 	  if (result)
23701 	    unify_expression_unequal (explain_p, parm, arg);
23702 	  return result;
23703 	}
23704 
23705       idx = TEMPLATE_PARM_IDX (parm);
23706       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
23707 
23708       if (targ)
23709 	{
23710 	  if ((strict & UNIFY_ALLOW_INTEGER)
23711 	      && TREE_TYPE (targ) && TREE_TYPE (arg)
23712 	      && CP_INTEGRAL_TYPE_P (TREE_TYPE (targ)))
23713 	    /* We're deducing from an array bound, the type doesn't matter.  */
23714 	    arg = fold_convert (TREE_TYPE (targ), arg);
23715 	  int x = !cp_tree_equal (targ, arg);
23716 	  if (x)
23717 	    unify_inconsistency (explain_p, parm, targ, arg);
23718 	  return x;
23719 	}
23720 
23721       /* [temp.deduct.type] If, in the declaration of a function template
23722 	 with a non-type template-parameter, the non-type
23723 	 template-parameter is used in an expression in the function
23724 	 parameter-list and, if the corresponding template-argument is
23725 	 deduced, the template-argument type shall match the type of the
23726 	 template-parameter exactly, except that a template-argument
23727 	 deduced from an array bound may be of any integral type.
23728 	 The non-type parameter might use already deduced type parameters.  */
23729       tparm = TREE_TYPE (parm);
23730       if (TEMPLATE_PARM_LEVEL (parm) > TMPL_ARGS_DEPTH (targs))
23731 	/* We don't have enough levels of args to do any substitution.  This
23732 	   can happen in the context of -fnew-ttp-matching.  */;
23733       else
23734 	{
23735 	  ++processing_template_decl;
23736 	  tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
23737 	  --processing_template_decl;
23738 
23739 	  if (tree a = type_uses_auto (tparm))
23740 	    {
23741 	      tparm = do_auto_deduction (tparm, arg, a,
23742 					 complain, adc_unify, targs);
23743 	      if (tparm == error_mark_node)
23744 		return 1;
23745 	    }
23746 	}
23747 
23748       if (!TREE_TYPE (arg))
23749 	/* Template-parameter dependent expression.  Just accept it for now.
23750 	   It will later be processed in convert_template_argument.  */
23751 	;
23752       else if (same_type_ignoring_top_level_qualifiers_p
23753 	       (non_reference (TREE_TYPE (arg)),
23754 		non_reference (tparm)))
23755 	/* OK.  Ignore top-level quals here because a class-type template
23756 	   parameter object is const.  */;
23757       else if ((strict & UNIFY_ALLOW_INTEGER)
23758 	       && CP_INTEGRAL_TYPE_P (tparm))
23759 	/* Convert the ARG to the type of PARM; the deduced non-type
23760 	   template argument must exactly match the types of the
23761 	   corresponding parameter.  */
23762 	arg = fold (build_nop (tparm, arg));
23763       else if (uses_template_parms (tparm))
23764 	{
23765 	  /* We haven't deduced the type of this parameter yet.  */
23766 	  if (cxx_dialect >= cxx17
23767 	      /* We deduce from array bounds in try_array_deduction.  */
23768 	      && !(strict & UNIFY_ALLOW_INTEGER)
23769 	      && TEMPLATE_PARM_LEVEL (parm) <= TMPL_ARGS_DEPTH (targs))
23770 	    {
23771 	      /* Deduce it from the non-type argument.  */
23772 	      tree atype = TREE_TYPE (arg);
23773 	      RECUR_AND_CHECK_FAILURE (tparms, targs,
23774 				       tparm, atype,
23775 				       UNIFY_ALLOW_NONE, explain_p);
23776 	      /* Now check whether the type of this parameter is still
23777 		 dependent, and give up if so.  */
23778 	      ++processing_template_decl;
23779 	      tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
23780 	      --processing_template_decl;
23781 	      if (uses_template_parms (tparm))
23782 		return unify_success (explain_p);
23783 	    }
23784 	  else
23785 	    /* Try again later.  */
23786 	    return unify_success (explain_p);
23787 	}
23788       else
23789 	return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
23790 
23791       /* If ARG is a parameter pack or an expansion, we cannot unify
23792 	 against it unless PARM is also a parameter pack.  */
23793       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
23794 	  && !TEMPLATE_PARM_PARAMETER_PACK (parm))
23795 	return unify_parameter_pack_mismatch (explain_p, parm, arg);
23796 
23797       {
23798 	bool removed_attr = false;
23799 	arg = strip_typedefs_expr (arg, &removed_attr);
23800       }
23801       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
23802       return unify_success (explain_p);
23803 
23804     case PTRMEM_CST:
23805      {
23806 	/* A pointer-to-member constant can be unified only with
23807 	 another constant.  */
23808       if (TREE_CODE (arg) != PTRMEM_CST)
23809 	return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
23810 
23811       /* Just unify the class member. It would be useless (and possibly
23812 	 wrong, depending on the strict flags) to unify also
23813 	 PTRMEM_CST_CLASS, because we want to be sure that both parm and
23814 	 arg refer to the same variable, even if through different
23815 	 classes. For instance:
23816 
23817 	 struct A { int x; };
23818 	 struct B : A { };
23819 
23820 	 Unification of &A::x and &B::x must succeed.  */
23821       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
23822 		    PTRMEM_CST_MEMBER (arg), strict, explain_p);
23823      }
23824 
23825     case POINTER_TYPE:
23826       {
23827 	if (!TYPE_PTR_P (arg))
23828 	  return unify_type_mismatch (explain_p, parm, arg);
23829 
23830 	/* [temp.deduct.call]
23831 
23832 	   A can be another pointer or pointer to member type that can
23833 	   be converted to the deduced A via a qualification
23834 	   conversion (_conv.qual_).
23835 
23836 	   We pass down STRICT here rather than UNIFY_ALLOW_NONE.
23837 	   This will allow for additional cv-qualification of the
23838 	   pointed-to types if appropriate.  */
23839 
23840 	if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
23841 	  /* The derived-to-base conversion only persists through one
23842 	     level of pointers.  */
23843 	  strict |= (strict_in & UNIFY_ALLOW_DERIVED);
23844 
23845 	return unify (tparms, targs, TREE_TYPE (parm),
23846 		      TREE_TYPE (arg), strict, explain_p);
23847       }
23848 
23849     case REFERENCE_TYPE:
23850       if (!TYPE_REF_P (arg))
23851 	return unify_type_mismatch (explain_p, parm, arg);
23852       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
23853 		    strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
23854 
23855     case ARRAY_TYPE:
23856       if (TREE_CODE (arg) != ARRAY_TYPE)
23857 	return unify_type_mismatch (explain_p, parm, arg);
23858       if ((TYPE_DOMAIN (parm) == NULL_TREE)
23859 	  != (TYPE_DOMAIN (arg) == NULL_TREE))
23860 	return unify_type_mismatch (explain_p, parm, arg);
23861       RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
23862 			       strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
23863       if (TYPE_DOMAIN (parm) != NULL_TREE)
23864 	return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
23865 				   TYPE_DOMAIN (arg), explain_p);
23866       return unify_success (explain_p);
23867 
23868     case REAL_TYPE:
23869     case COMPLEX_TYPE:
23870     case VECTOR_TYPE:
23871     case INTEGER_TYPE:
23872     case BOOLEAN_TYPE:
23873     case ENUMERAL_TYPE:
23874     case VOID_TYPE:
23875     case OPAQUE_TYPE:
23876     case NULLPTR_TYPE:
23877       if (TREE_CODE (arg) != TREE_CODE (parm))
23878 	return unify_type_mismatch (explain_p, parm, arg);
23879 
23880       /* We have already checked cv-qualification at the top of the
23881 	 function.  */
23882       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
23883 	return unify_type_mismatch (explain_p, parm, arg);
23884 
23885       /* As far as unification is concerned, this wins.	 Later checks
23886 	 will invalidate it if necessary.  */
23887       return unify_success (explain_p);
23888 
23889       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
23890       /* Type INTEGER_CST can come from ordinary constant template args.  */
23891     case INTEGER_CST:
23892       while (CONVERT_EXPR_P (arg))
23893 	arg = TREE_OPERAND (arg, 0);
23894 
23895       if (TREE_CODE (arg) != INTEGER_CST)
23896 	return unify_template_argument_mismatch (explain_p, parm, arg);
23897       return (tree_int_cst_equal (parm, arg)
23898 	      ? unify_success (explain_p)
23899 	      : unify_template_argument_mismatch (explain_p, parm, arg));
23900 
23901     case TREE_VEC:
23902       {
23903 	int i, len, argslen;
23904 	int parm_variadic_p = 0;
23905 
23906 	if (TREE_CODE (arg) != TREE_VEC)
23907 	  return unify_template_argument_mismatch (explain_p, parm, arg);
23908 
23909 	len = TREE_VEC_LENGTH (parm);
23910 	argslen = TREE_VEC_LENGTH (arg);
23911 
23912 	/* Check for pack expansions in the parameters.  */
23913 	for (i = 0; i < len; ++i)
23914 	  {
23915 	    if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
23916 	      {
23917 		if (i == len - 1)
23918 		  /* We can unify against something with a trailing
23919 		     parameter pack.  */
23920 		  parm_variadic_p = 1;
23921 		else
23922 		  /* [temp.deduct.type]/9: If the template argument list of
23923 		     P contains a pack expansion that is not the last
23924 		     template argument, the entire template argument list
23925 		     is a non-deduced context.  */
23926 		  return unify_success (explain_p);
23927 	      }
23928 	  }
23929 
23930         /* If we don't have enough arguments to satisfy the parameters
23931            (not counting the pack expression at the end), or we have
23932            too many arguments for a parameter list that doesn't end in
23933            a pack expression, we can't unify.  */
23934 	if (parm_variadic_p
23935 	    ? argslen < len - parm_variadic_p
23936 	    : argslen != len)
23937 	  return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
23938 
23939 	/* Unify all of the parameters that precede the (optional)
23940 	   pack expression.  */
23941 	for (i = 0; i < len - parm_variadic_p; ++i)
23942 	  {
23943 	    RECUR_AND_CHECK_FAILURE (tparms, targs,
23944 				     TREE_VEC_ELT (parm, i),
23945 				     TREE_VEC_ELT (arg, i),
23946 				     UNIFY_ALLOW_NONE, explain_p);
23947 	  }
23948 	if (parm_variadic_p)
23949 	  return unify_pack_expansion (tparms, targs, parm, arg,
23950 				       DEDUCE_EXACT,
23951 				       /*subr=*/true, explain_p);
23952 	return unify_success (explain_p);
23953       }
23954 
23955     case RECORD_TYPE:
23956     case UNION_TYPE:
23957       if (TREE_CODE (arg) != TREE_CODE (parm))
23958 	return unify_type_mismatch (explain_p, parm, arg);
23959 
23960       if (TYPE_PTRMEMFUNC_P (parm))
23961 	{
23962 	  if (!TYPE_PTRMEMFUNC_P (arg))
23963 	    return unify_type_mismatch (explain_p, parm, arg);
23964 
23965 	  return unify (tparms, targs,
23966 			TYPE_PTRMEMFUNC_FN_TYPE (parm),
23967 			TYPE_PTRMEMFUNC_FN_TYPE (arg),
23968 			strict, explain_p);
23969 	}
23970       else if (TYPE_PTRMEMFUNC_P (arg))
23971 	return unify_type_mismatch (explain_p, parm, arg);
23972 
23973       if (CLASSTYPE_TEMPLATE_INFO (parm))
23974 	{
23975 	  tree t = NULL_TREE;
23976 
23977 	  if (strict_in & UNIFY_ALLOW_DERIVED)
23978 	    {
23979 	      /* First, we try to unify the PARM and ARG directly.  */
23980 	      t = try_class_unification (tparms, targs,
23981 					 parm, arg, explain_p);
23982 
23983 	      if (!t)
23984 		{
23985 		  /* Fallback to the special case allowed in
23986 		     [temp.deduct.call]:
23987 
23988 		       If P is a class, and P has the form
23989 		       template-id, then A can be a derived class of
23990 		       the deduced A.  Likewise, if P is a pointer to
23991 		       a class of the form template-id, A can be a
23992 		       pointer to a derived class pointed to by the
23993 		       deduced A.  */
23994 		  enum template_base_result r;
23995 		  r = get_template_base (tparms, targs, parm, arg,
23996 					 explain_p, &t);
23997 
23998 		  if (!t)
23999 		    {
24000 		      /* Don't give the derived diagnostic if we're
24001 			 already dealing with the same template.  */
24002 		      bool same_template
24003 			= (CLASSTYPE_TEMPLATE_INFO (arg)
24004 			   && (CLASSTYPE_TI_TEMPLATE (parm)
24005 			       == CLASSTYPE_TI_TEMPLATE (arg)));
24006 		      return unify_no_common_base (explain_p && !same_template,
24007 						   r, parm, arg);
24008 		    }
24009 		}
24010 	    }
24011 	  else if (CLASSTYPE_TEMPLATE_INFO (arg)
24012 		   && (CLASSTYPE_TI_TEMPLATE (parm)
24013 		       == CLASSTYPE_TI_TEMPLATE (arg)))
24014 	    /* Perhaps PARM is something like S<U> and ARG is S<int>.
24015 	       Then, we should unify `int' and `U'.  */
24016 	    t = arg;
24017 	  else
24018 	    /* There's no chance of unification succeeding.  */
24019 	    return unify_type_mismatch (explain_p, parm, arg);
24020 
24021 	  return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
24022 			CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
24023 	}
24024       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
24025 	return unify_type_mismatch (explain_p, parm, arg);
24026       return unify_success (explain_p);
24027 
24028     case METHOD_TYPE:
24029     case FUNCTION_TYPE:
24030       {
24031 	unsigned int nargs;
24032 	tree *args;
24033 	tree a;
24034 	unsigned int i;
24035 
24036 	if (TREE_CODE (arg) != TREE_CODE (parm))
24037 	  return unify_type_mismatch (explain_p, parm, arg);
24038 
24039 	/* CV qualifications for methods can never be deduced, they must
24040 	   match exactly.  We need to check them explicitly here,
24041 	   because type_unification_real treats them as any other
24042 	   cv-qualified parameter.  */
24043 	if (TREE_CODE (parm) == METHOD_TYPE
24044 	    && (!check_cv_quals_for_unify
24045 		(UNIFY_ALLOW_NONE,
24046 		 class_of_this_parm (arg),
24047 		 class_of_this_parm (parm))))
24048 	  return unify_cv_qual_mismatch (explain_p, parm, arg);
24049 	if (TREE_CODE (arg) == FUNCTION_TYPE
24050 	    && type_memfn_quals (parm) != type_memfn_quals (arg))
24051 	  return unify_cv_qual_mismatch (explain_p, parm, arg);
24052 	if (type_memfn_rqual (parm) != type_memfn_rqual (arg))
24053 	  return unify_type_mismatch (explain_p, parm, arg);
24054 
24055 	RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
24056 				 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
24057 
24058 	nargs = list_length (TYPE_ARG_TYPES (arg));
24059 	args = XALLOCAVEC (tree, nargs);
24060 	for (a = TYPE_ARG_TYPES (arg), i = 0;
24061 	     a != NULL_TREE && a != void_list_node;
24062 	     a = TREE_CHAIN (a), ++i)
24063 	  args[i] = TREE_VALUE (a);
24064 	nargs = i;
24065 
24066 	if (type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
24067 				   args, nargs, 1, DEDUCE_EXACT,
24068 				   NULL, explain_p))
24069 	  return 1;
24070 
24071 	if (flag_noexcept_type)
24072 	  {
24073 	    tree pspec = TYPE_RAISES_EXCEPTIONS (parm);
24074 	    tree aspec = canonical_eh_spec (TYPE_RAISES_EXCEPTIONS (arg));
24075 	    if (pspec == NULL_TREE) pspec = noexcept_false_spec;
24076 	    if (aspec == NULL_TREE) aspec = noexcept_false_spec;
24077 	    if (TREE_PURPOSE (pspec) && TREE_PURPOSE (aspec)
24078 		&& uses_template_parms (TREE_PURPOSE (pspec)))
24079 	      RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_PURPOSE (pspec),
24080 				       TREE_PURPOSE (aspec),
24081 				       UNIFY_ALLOW_NONE, explain_p);
24082 	    else if (nothrow_spec_p (pspec) && !nothrow_spec_p (aspec))
24083 	      return unify_type_mismatch (explain_p, parm, arg);
24084 	  }
24085 
24086 	return 0;
24087       }
24088 
24089     case OFFSET_TYPE:
24090       /* Unify a pointer to member with a pointer to member function, which
24091 	 deduces the type of the member as a function type. */
24092       if (TYPE_PTRMEMFUNC_P (arg))
24093 	{
24094 	  /* Check top-level cv qualifiers */
24095 	  if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
24096 	    return unify_cv_qual_mismatch (explain_p, parm, arg);
24097 
24098 	  RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
24099 				   TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
24100 				   UNIFY_ALLOW_NONE, explain_p);
24101 
24102 	  /* Determine the type of the function we are unifying against. */
24103 	  tree fntype = static_fn_type (arg);
24104 
24105 	  return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
24106 	}
24107 
24108       if (TREE_CODE (arg) != OFFSET_TYPE)
24109 	return unify_type_mismatch (explain_p, parm, arg);
24110       RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
24111 			       TYPE_OFFSET_BASETYPE (arg),
24112 			       UNIFY_ALLOW_NONE, explain_p);
24113       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24114 		    strict, explain_p);
24115 
24116     case CONST_DECL:
24117       if (DECL_TEMPLATE_PARM_P (parm))
24118 	return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
24119       if (arg != scalar_constant_value (parm))
24120 	return unify_template_argument_mismatch (explain_p, parm, arg);
24121       return unify_success (explain_p);
24122 
24123     case FIELD_DECL:
24124     case TEMPLATE_DECL:
24125       /* Matched cases are handled by the ARG == PARM test above.  */
24126       return unify_template_argument_mismatch (explain_p, parm, arg);
24127 
24128     case VAR_DECL:
24129       /* We might get a variable as a non-type template argument in parm if the
24130 	 corresponding parameter is type-dependent.  Make any necessary
24131 	 adjustments based on whether arg is a reference.  */
24132       if (CONSTANT_CLASS_P (arg))
24133 	parm = fold_non_dependent_expr (parm, complain);
24134       else if (REFERENCE_REF_P (arg))
24135 	{
24136 	  tree sub = TREE_OPERAND (arg, 0);
24137 	  STRIP_NOPS (sub);
24138 	  if (TREE_CODE (sub) == ADDR_EXPR)
24139 	    arg = TREE_OPERAND (sub, 0);
24140 	}
24141       /* Now use the normal expression code to check whether they match.  */
24142       goto expr;
24143 
24144     case TYPE_ARGUMENT_PACK:
24145     case NONTYPE_ARGUMENT_PACK:
24146       return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
24147 		    ARGUMENT_PACK_ARGS (arg), strict, explain_p);
24148 
24149     case TYPEOF_TYPE:
24150     case DECLTYPE_TYPE:
24151     case UNDERLYING_TYPE:
24152       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
24153 	 or UNDERLYING_TYPE nodes.  */
24154       return unify_success (explain_p);
24155 
24156     case ERROR_MARK:
24157       /* Unification fails if we hit an error node.  */
24158       return unify_invalid (explain_p);
24159 
24160     case INDIRECT_REF:
24161       if (REFERENCE_REF_P (parm))
24162 	{
24163 	  bool pexp = PACK_EXPANSION_P (arg);
24164 	  if (pexp)
24165 	    arg = PACK_EXPANSION_PATTERN (arg);
24166 	  if (REFERENCE_REF_P (arg))
24167 	    arg = TREE_OPERAND (arg, 0);
24168 	  if (pexp)
24169 	    arg = make_pack_expansion (arg, complain);
24170 	  return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
24171 			strict, explain_p);
24172 	}
24173       /* FALLTHRU */
24174 
24175     default:
24176       /* An unresolved overload is a nondeduced context.  */
24177       if (is_overloaded_fn (parm) || type_unknown_p (parm))
24178 	return unify_success (explain_p);
24179       gcc_assert (EXPR_P (parm)
24180 		  || COMPOUND_LITERAL_P (parm)
24181 		  || TREE_CODE (parm) == TRAIT_EXPR);
24182     expr:
24183       /* We must be looking at an expression.  This can happen with
24184 	 something like:
24185 
24186 	   template <int I>
24187 	   void foo(S<I>, S<I + 2>);
24188 
24189 	 or
24190 
24191 	   template<typename T>
24192 	   void foo(A<T, T{}>);
24193 
24194 	 This is a "non-deduced context":
24195 
24196 	   [deduct.type]
24197 
24198 	   The non-deduced contexts are:
24199 
24200 	   --A non-type template argument or an array bound in which
24201 	     a subexpression references a template parameter.
24202 
24203 	 In these cases, we assume deduction succeeded, but don't
24204 	 actually infer any unifications.  */
24205 
24206       if (!uses_template_parms (parm)
24207 	  && !template_args_equal (parm, arg))
24208 	return unify_expression_unequal (explain_p, parm, arg);
24209       else
24210 	return unify_success (explain_p);
24211     }
24212 }
24213 #undef RECUR_AND_CHECK_FAILURE
24214 
24215 /* Note that DECL can be defined in this translation unit, if
24216    required.  */
24217 
24218 static void
mark_definable(tree decl)24219 mark_definable (tree decl)
24220 {
24221   tree clone;
24222   DECL_NOT_REALLY_EXTERN (decl) = 1;
24223   FOR_EACH_CLONE (clone, decl)
24224     DECL_NOT_REALLY_EXTERN (clone) = 1;
24225 }
24226 
24227 /* Called if RESULT is explicitly instantiated, or is a member of an
24228    explicitly instantiated class.  */
24229 
24230 void
mark_decl_instantiated(tree result,int extern_p)24231 mark_decl_instantiated (tree result, int extern_p)
24232 {
24233   SET_DECL_EXPLICIT_INSTANTIATION (result);
24234 
24235   /* If this entity has already been written out, it's too late to
24236      make any modifications.  */
24237   if (TREE_ASM_WRITTEN (result))
24238     return;
24239 
24240   /* consteval functions are never emitted.  */
24241   if (TREE_CODE (result) == FUNCTION_DECL
24242       && DECL_IMMEDIATE_FUNCTION_P (result))
24243     return;
24244 
24245   /* For anonymous namespace we don't need to do anything.  */
24246   if (decl_anon_ns_mem_p (result))
24247     {
24248       gcc_assert (!TREE_PUBLIC (result));
24249       return;
24250     }
24251 
24252   if (TREE_CODE (result) != FUNCTION_DECL)
24253     /* The TREE_PUBLIC flag for function declarations will have been
24254        set correctly by tsubst.  */
24255     TREE_PUBLIC (result) = 1;
24256 
24257   /* This might have been set by an earlier implicit instantiation.  */
24258   DECL_COMDAT (result) = 0;
24259 
24260   if (extern_p)
24261     {
24262       DECL_EXTERNAL (result) = 1;
24263       DECL_NOT_REALLY_EXTERN (result) = 0;
24264     }
24265   else
24266     {
24267       mark_definable (result);
24268       mark_needed (result);
24269       /* Always make artificials weak.  */
24270       if (DECL_ARTIFICIAL (result) && flag_weak)
24271 	comdat_linkage (result);
24272       /* For WIN32 we also want to put explicit instantiations in
24273 	 linkonce sections.  */
24274       else if (TREE_PUBLIC (result))
24275 	maybe_make_one_only (result);
24276       if (TREE_CODE (result) == FUNCTION_DECL
24277 	  && DECL_TEMPLATE_INSTANTIATED (result))
24278 	/* If the function has already been instantiated, clear DECL_EXTERNAL,
24279 	   since start_preparsed_function wouldn't have if we had an earlier
24280 	   extern explicit instantiation.  */
24281 	DECL_EXTERNAL (result) = 0;
24282     }
24283 
24284   /* If EXTERN_P, then this function will not be emitted -- unless
24285      followed by an explicit instantiation, at which point its linkage
24286      will be adjusted.  If !EXTERN_P, then this function will be
24287      emitted here.  In neither circumstance do we want
24288      import_export_decl to adjust the linkage.  */
24289   DECL_INTERFACE_KNOWN (result) = 1;
24290 }
24291 
24292 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
24293    important template arguments.  If any are missing, we check whether
24294    they're important by using error_mark_node for substituting into any
24295    args that were used for partial ordering (the ones between ARGS and END)
24296    and seeing if it bubbles up.  */
24297 
24298 static bool
check_undeduced_parms(tree targs,tree args,tree end)24299 check_undeduced_parms (tree targs, tree args, tree end)
24300 {
24301   bool found = false;
24302   int i;
24303   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
24304     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
24305       {
24306 	found = true;
24307 	TREE_VEC_ELT (targs, i) = error_mark_node;
24308       }
24309   if (found)
24310     {
24311       tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
24312       if (substed == error_mark_node)
24313 	return true;
24314     }
24315   return false;
24316 }
24317 
24318 /* Given two function templates PAT1 and PAT2, return:
24319 
24320    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
24321    -1 if PAT2 is more specialized than PAT1.
24322    0 if neither is more specialized.
24323 
24324    LEN indicates the number of parameters we should consider
24325    (defaulted parameters should not be considered).
24326 
24327    The 1998 std underspecified function template partial ordering, and
24328    DR214 addresses the issue.  We take pairs of arguments, one from
24329    each of the templates, and deduce them against each other.  One of
24330    the templates will be more specialized if all the *other*
24331    template's arguments deduce against its arguments and at least one
24332    of its arguments *does* *not* deduce against the other template's
24333    corresponding argument.  Deduction is done as for class templates.
24334    The arguments used in deduction have reference and top level cv
24335    qualifiers removed.  Iff both arguments were originally reference
24336    types *and* deduction succeeds in both directions, an lvalue reference
24337    wins against an rvalue reference and otherwise the template
24338    with the more cv-qualified argument wins for that pairing (if
24339    neither is more cv-qualified, they both are equal).  Unlike regular
24340    deduction, after all the arguments have been deduced in this way,
24341    we do *not* verify the deduced template argument values can be
24342    substituted into non-deduced contexts.
24343 
24344    The logic can be a bit confusing here, because we look at deduce1 and
24345    targs1 to see if pat2 is at least as specialized, and vice versa; if we
24346    can find template arguments for pat1 to make arg1 look like arg2, that
24347    means that arg2 is at least as specialized as arg1.  */
24348 
24349 int
more_specialized_fn(tree pat1,tree pat2,int len)24350 more_specialized_fn (tree pat1, tree pat2, int len)
24351 {
24352   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
24353   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
24354   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
24355   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
24356   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
24357   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
24358   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
24359   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
24360   tree origs1, origs2;
24361   bool lose1 = false;
24362   bool lose2 = false;
24363 
24364   /* Remove the this parameter from non-static member functions.  If
24365      one is a non-static member function and the other is not a static
24366      member function, remove the first parameter from that function
24367      also.  This situation occurs for operator functions where we
24368      locate both a member function (with this pointer) and non-member
24369      operator (with explicit first operand).  */
24370   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
24371     {
24372       len--; /* LEN is the number of significant arguments for DECL1 */
24373       args1 = TREE_CHAIN (args1);
24374       if (!DECL_STATIC_FUNCTION_P (decl2))
24375 	args2 = TREE_CHAIN (args2);
24376     }
24377   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
24378     {
24379       args2 = TREE_CHAIN (args2);
24380       if (!DECL_STATIC_FUNCTION_P (decl1))
24381 	{
24382 	  len--;
24383 	  args1 = TREE_CHAIN (args1);
24384 	}
24385     }
24386 
24387   /* If only one is a conversion operator, they are unordered.  */
24388   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
24389     return 0;
24390 
24391   /* Consider the return type for a conversion function */
24392   if (DECL_CONV_FN_P (decl1))
24393     {
24394       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
24395       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
24396       len++;
24397     }
24398 
24399   processing_template_decl++;
24400 
24401   origs1 = args1;
24402   origs2 = args2;
24403 
24404   while (len--
24405 	 /* Stop when an ellipsis is seen.  */
24406 	 && args1 != NULL_TREE && args2 != NULL_TREE)
24407     {
24408       tree arg1 = TREE_VALUE (args1);
24409       tree arg2 = TREE_VALUE (args2);
24410       int deduce1, deduce2;
24411       int quals1 = -1;
24412       int quals2 = -1;
24413       int ref1 = 0;
24414       int ref2 = 0;
24415 
24416       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
24417           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
24418         {
24419           /* When both arguments are pack expansions, we need only
24420              unify the patterns themselves.  */
24421           arg1 = PACK_EXPANSION_PATTERN (arg1);
24422           arg2 = PACK_EXPANSION_PATTERN (arg2);
24423 
24424           /* This is the last comparison we need to do.  */
24425           len = 0;
24426         }
24427 
24428       if (TYPE_REF_P (arg1))
24429 	{
24430 	  ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
24431 	  arg1 = TREE_TYPE (arg1);
24432 	  quals1 = cp_type_quals (arg1);
24433 	}
24434 
24435       if (TYPE_REF_P (arg2))
24436 	{
24437 	  ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
24438 	  arg2 = TREE_TYPE (arg2);
24439 	  quals2 = cp_type_quals (arg2);
24440 	}
24441 
24442       arg1 = TYPE_MAIN_VARIANT (arg1);
24443       arg2 = TYPE_MAIN_VARIANT (arg2);
24444 
24445       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
24446         {
24447           int i, len2 = remaining_arguments (args2);
24448           tree parmvec = make_tree_vec (1);
24449           tree argvec = make_tree_vec (len2);
24450           tree ta = args2;
24451 
24452           /* Setup the parameter vector, which contains only ARG1.  */
24453           TREE_VEC_ELT (parmvec, 0) = arg1;
24454 
24455           /* Setup the argument vector, which contains the remaining
24456              arguments.  */
24457           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
24458             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
24459 
24460           deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
24461 					   argvec, DEDUCE_EXACT,
24462 					   /*subr=*/true, /*explain_p=*/false)
24463 		     == 0);
24464 
24465           /* We cannot deduce in the other direction, because ARG1 is
24466              a pack expansion but ARG2 is not.  */
24467           deduce2 = 0;
24468         }
24469       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
24470         {
24471           int i, len1 = remaining_arguments (args1);
24472           tree parmvec = make_tree_vec (1);
24473           tree argvec = make_tree_vec (len1);
24474           tree ta = args1;
24475 
24476           /* Setup the parameter vector, which contains only ARG1.  */
24477           TREE_VEC_ELT (parmvec, 0) = arg2;
24478 
24479           /* Setup the argument vector, which contains the remaining
24480              arguments.  */
24481           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
24482             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
24483 
24484           deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
24485 					   argvec, DEDUCE_EXACT,
24486 					   /*subr=*/true, /*explain_p=*/false)
24487 		     == 0);
24488 
24489           /* We cannot deduce in the other direction, because ARG2 is
24490              a pack expansion but ARG1 is not.*/
24491           deduce1 = 0;
24492         }
24493 
24494       else
24495         {
24496           /* The normal case, where neither argument is a pack
24497              expansion.  */
24498           deduce1 = (unify (tparms1, targs1, arg1, arg2,
24499 			    UNIFY_ALLOW_NONE, /*explain_p=*/false)
24500 		     == 0);
24501           deduce2 = (unify (tparms2, targs2, arg2, arg1,
24502 			    UNIFY_ALLOW_NONE, /*explain_p=*/false)
24503 		     == 0);
24504         }
24505 
24506       /* If we couldn't deduce arguments for tparms1 to make arg1 match
24507 	 arg2, then arg2 is not as specialized as arg1.  */
24508       if (!deduce1)
24509 	lose2 = true;
24510       if (!deduce2)
24511 	lose1 = true;
24512 
24513       /* "If, for a given type, deduction succeeds in both directions
24514 	 (i.e., the types are identical after the transformations above)
24515 	 and both P and A were reference types (before being replaced with
24516 	 the type referred to above):
24517 	 - if the type from the argument template was an lvalue reference and
24518 	 the type from the parameter template was not, the argument type is
24519 	 considered to be more specialized than the other; otherwise,
24520 	 - if the type from the argument template is more cv-qualified
24521 	 than the type from the parameter template (as described above),
24522 	 the argument type is considered to be more specialized than the other;
24523 	 otherwise,
24524 	 - neither type is more specialized than the other."  */
24525 
24526       if (deduce1 && deduce2)
24527 	{
24528 	  if (ref1 && ref2 && ref1 != ref2)
24529 	    {
24530 	      if (ref1 > ref2)
24531 		lose1 = true;
24532 	      else
24533 		lose2 = true;
24534 	    }
24535 	  else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
24536 	    {
24537 	      if ((quals1 & quals2) == quals2)
24538 		lose2 = true;
24539 	      if ((quals1 & quals2) == quals1)
24540 		lose1 = true;
24541 	    }
24542 	}
24543 
24544       if (lose1 && lose2)
24545 	/* We've failed to deduce something in either direction.
24546 	   These must be unordered.  */
24547 	break;
24548 
24549       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
24550           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
24551         /* We have already processed all of the arguments in our
24552            handing of the pack expansion type.  */
24553         len = 0;
24554 
24555       args1 = TREE_CHAIN (args1);
24556       args2 = TREE_CHAIN (args2);
24557     }
24558 
24559   /* "In most cases, all template parameters must have values in order for
24560      deduction to succeed, but for partial ordering purposes a template
24561      parameter may remain without a value provided it is not used in the
24562      types being used for partial ordering."
24563 
24564      Thus, if we are missing any of the targs1 we need to substitute into
24565      origs1, then pat2 is not as specialized as pat1.  This can happen when
24566      there is a nondeduced context.  */
24567   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
24568     lose2 = true;
24569   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
24570     lose1 = true;
24571 
24572   processing_template_decl--;
24573 
24574   /* If both deductions succeed, the partial ordering selects the more
24575      constrained template.  */
24576   /* P2113: If the corresponding template-parameters of the
24577      template-parameter-lists are not equivalent ([temp.over.link]) or if
24578      the function parameters that positionally correspond between the two
24579      templates are not of the same type, neither template is more
24580      specialized than the other.  */
24581   if (!lose1 && !lose2
24582       && comp_template_parms (DECL_TEMPLATE_PARMS (pat1),
24583 			      DECL_TEMPLATE_PARMS (pat2))
24584       && compparms (origs1, origs2))
24585     {
24586       int winner = more_constrained (decl1, decl2);
24587       if (winner > 0)
24588 	lose2 = true;
24589       else if (winner < 0)
24590 	lose1 = true;
24591     }
24592 
24593   /* All things being equal, if the next argument is a pack expansion
24594      for one function but not for the other, prefer the
24595      non-variadic function.  FIXME this is bogus; see c++/41958.  */
24596   if (lose1 == lose2
24597       && args1 && TREE_VALUE (args1)
24598       && args2 && TREE_VALUE (args2))
24599     {
24600       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
24601       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
24602     }
24603 
24604   if (lose1 == lose2)
24605     return 0;
24606   else if (!lose1)
24607     return 1;
24608   else
24609     return -1;
24610 }
24611 
24612 /* Determine which of two partial specializations of TMPL is more
24613    specialized.
24614 
24615    PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
24616    to the first partial specialization.  The TREE_PURPOSE is the
24617    innermost set of template parameters for the partial
24618    specialization.  PAT2 is similar, but for the second template.
24619 
24620    Return 1 if the first partial specialization is more specialized;
24621    -1 if the second is more specialized; 0 if neither is more
24622    specialized.
24623 
24624    See [temp.class.order] for information about determining which of
24625    two templates is more specialized.  */
24626 
24627 static int
more_specialized_partial_spec(tree tmpl,tree pat1,tree pat2)24628 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
24629 {
24630   tree targs;
24631   int winner = 0;
24632   bool any_deductions = false;
24633 
24634   tree tmpl1 = TREE_VALUE (pat1);
24635   tree tmpl2 = TREE_VALUE (pat2);
24636   tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
24637   tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
24638 
24639   /* Just like what happens for functions, if we are ordering between
24640      different template specializations, we may encounter dependent
24641      types in the arguments, and we need our dependency check functions
24642      to behave correctly.  */
24643   ++processing_template_decl;
24644   targs = get_partial_spec_bindings (tmpl, tmpl1, specargs2);
24645   if (targs)
24646     {
24647       --winner;
24648       any_deductions = true;
24649     }
24650 
24651   targs = get_partial_spec_bindings (tmpl, tmpl2, specargs1);
24652   if (targs)
24653     {
24654       ++winner;
24655       any_deductions = true;
24656     }
24657   --processing_template_decl;
24658 
24659   /* If both deductions succeed, the partial ordering selects the more
24660      constrained template.  */
24661   if (!winner && any_deductions)
24662     winner = more_constrained (tmpl1, tmpl2);
24663 
24664   /* In the case of a tie where at least one of the templates
24665      has a parameter pack at the end, the template with the most
24666      non-packed parameters wins.  */
24667   if (winner == 0
24668       && any_deductions
24669       && (template_args_variadic_p (TREE_PURPOSE (pat1))
24670           || template_args_variadic_p (TREE_PURPOSE (pat2))))
24671     {
24672       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
24673       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
24674       int len1 = TREE_VEC_LENGTH (args1);
24675       int len2 = TREE_VEC_LENGTH (args2);
24676 
24677       /* We don't count the pack expansion at the end.  */
24678       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
24679         --len1;
24680       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
24681         --len2;
24682 
24683       if (len1 > len2)
24684         return 1;
24685       else if (len1 < len2)
24686         return -1;
24687     }
24688 
24689   return winner;
24690 }
24691 
24692 /* Return the template arguments that will produce the function signature
24693    DECL from the function template FN, with the explicit template
24694    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
24695    also match.  Return NULL_TREE if no satisfactory arguments could be
24696    found.  */
24697 
24698 static tree
get_bindings(tree fn,tree decl,tree explicit_args,bool check_rettype)24699 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
24700 {
24701   int ntparms = DECL_NTPARMS (fn);
24702   tree targs = make_tree_vec (ntparms);
24703   tree decl_type = TREE_TYPE (decl);
24704   tree decl_arg_types;
24705   tree *args;
24706   unsigned int nargs, ix;
24707   tree arg;
24708 
24709   gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
24710 
24711   /* Never do unification on the 'this' parameter.  */
24712   decl_arg_types = skip_artificial_parms_for (decl,
24713 					      TYPE_ARG_TYPES (decl_type));
24714 
24715   nargs = list_length (decl_arg_types);
24716   args = XALLOCAVEC (tree, nargs);
24717   for (arg = decl_arg_types, ix = 0;
24718        arg != NULL_TREE && arg != void_list_node;
24719        arg = TREE_CHAIN (arg), ++ix)
24720     args[ix] = TREE_VALUE (arg);
24721 
24722   if (fn_type_unification (fn, explicit_args, targs,
24723 			   args, ix,
24724 			   (check_rettype || DECL_CONV_FN_P (fn)
24725 			    ? TREE_TYPE (decl_type) : NULL_TREE),
24726 			   DEDUCE_EXACT, LOOKUP_NORMAL, NULL,
24727 			   /*explain_p=*/false,
24728 			   /*decltype*/false)
24729       == error_mark_node)
24730     return NULL_TREE;
24731 
24732   return targs;
24733 }
24734 
24735 /* Return the innermost template arguments that, when applied to a partial
24736    specialization SPEC_TMPL of TMPL, yield the ARGS.
24737 
24738    For example, suppose we have:
24739 
24740      template <class T, class U> struct S {};
24741      template <class T> struct S<T*, int> {};
24742 
24743    Then, suppose we want to get `S<double*, int>'.  SPEC_TMPL will be the
24744    partial specialization and the ARGS will be {double*, int}.  The resulting
24745    vector will be {double}, indicating that `T' is bound to `double'.  */
24746 
24747 static tree
get_partial_spec_bindings(tree tmpl,tree spec_tmpl,tree args)24748 get_partial_spec_bindings (tree tmpl, tree spec_tmpl, tree args)
24749 {
24750   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
24751   tree spec_args
24752     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (spec_tmpl)));
24753   int i, ntparms = TREE_VEC_LENGTH (tparms);
24754   tree deduced_args;
24755   tree innermost_deduced_args;
24756 
24757   innermost_deduced_args = make_tree_vec (ntparms);
24758   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
24759     {
24760       deduced_args = copy_node (args);
24761       SET_TMPL_ARGS_LEVEL (deduced_args,
24762 			   TMPL_ARGS_DEPTH (deduced_args),
24763 			   innermost_deduced_args);
24764     }
24765   else
24766     deduced_args = innermost_deduced_args;
24767 
24768   bool tried_array_deduction = (cxx_dialect < cxx17);
24769  again:
24770   if (unify (tparms, deduced_args,
24771 	     INNERMOST_TEMPLATE_ARGS (spec_args),
24772 	     INNERMOST_TEMPLATE_ARGS (args),
24773 	     UNIFY_ALLOW_NONE, /*explain_p=*/false))
24774     return NULL_TREE;
24775 
24776   for (i =  0; i < ntparms; ++i)
24777     if (! TREE_VEC_ELT (innermost_deduced_args, i))
24778       {
24779 	if (!tried_array_deduction)
24780 	  {
24781 	    try_array_deduction (tparms, innermost_deduced_args,
24782 				 INNERMOST_TEMPLATE_ARGS (spec_args));
24783 	    tried_array_deduction = true;
24784 	    if (TREE_VEC_ELT (innermost_deduced_args, i))
24785 	      goto again;
24786 	  }
24787 	return NULL_TREE;
24788       }
24789 
24790   if (!push_tinst_level (spec_tmpl, deduced_args))
24791     {
24792       excessive_deduction_depth = true;
24793       return NULL_TREE;
24794     }
24795 
24796   /* Verify that nondeduced template arguments agree with the type
24797      obtained from argument deduction.
24798 
24799      For example:
24800 
24801        struct A { typedef int X; };
24802        template <class T, class U> struct C {};
24803        template <class T> struct C<T, typename T::X> {};
24804 
24805      Then with the instantiation `C<A, int>', we can deduce that
24806      `T' is `A' but unify () does not check whether `typename T::X'
24807      is `int'.  */
24808   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
24809 
24810   if (spec_args != error_mark_node)
24811     spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
24812 				       INNERMOST_TEMPLATE_ARGS (spec_args),
24813 				       tmpl, tf_none, false, false);
24814 
24815   pop_tinst_level ();
24816 
24817   if (spec_args == error_mark_node
24818       /* We only need to check the innermost arguments; the other
24819 	 arguments will always agree.  */
24820       || !comp_template_args_porder (INNERMOST_TEMPLATE_ARGS (spec_args),
24821 				     INNERMOST_TEMPLATE_ARGS (args)))
24822     return NULL_TREE;
24823 
24824   /* Now that we have bindings for all of the template arguments,
24825      ensure that the arguments deduced for the template template
24826      parameters have compatible template parameter lists.  See the use
24827      of template_template_parm_bindings_ok_p in fn_type_unification
24828      for more information.  */
24829   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
24830     return NULL_TREE;
24831 
24832   return deduced_args;
24833 }
24834 
24835 // Compare two function templates T1 and T2 by deducing bindings
24836 // from one against the other. If both deductions succeed, compare
24837 // constraints to see which is more constrained.
24838 static int
more_specialized_inst(tree t1,tree t2)24839 more_specialized_inst (tree t1, tree t2)
24840 {
24841   int fate = 0;
24842   int count = 0;
24843 
24844   if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
24845     {
24846       --fate;
24847       ++count;
24848     }
24849 
24850   if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
24851     {
24852       ++fate;
24853       ++count;
24854     }
24855 
24856   // If both deductions succeed, then one may be more constrained.
24857   if (count == 2 && fate == 0)
24858     fate = more_constrained (t1, t2);
24859 
24860   return fate;
24861 }
24862 
24863 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
24864    Return the TREE_LIST node with the most specialized template, if
24865    any.  If there is no most specialized template, the error_mark_node
24866    is returned.
24867 
24868    Note that this function does not look at, or modify, the
24869    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
24870    returned is one of the elements of INSTANTIATIONS, callers may
24871    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
24872    and retrieve it from the value returned.  */
24873 
24874 tree
most_specialized_instantiation(tree templates)24875 most_specialized_instantiation (tree templates)
24876 {
24877   tree fn, champ;
24878 
24879   ++processing_template_decl;
24880 
24881   champ = templates;
24882   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
24883     {
24884       gcc_assert (TREE_VALUE (champ) != TREE_VALUE (fn));
24885       int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
24886       if (fate == -1)
24887 	champ = fn;
24888       else if (!fate)
24889 	{
24890 	  /* Equally specialized, move to next function.  If there
24891 	     is no next function, nothing's most specialized.  */
24892 	  fn = TREE_CHAIN (fn);
24893 	  champ = fn;
24894 	  if (!fn)
24895 	    break;
24896 	}
24897     }
24898 
24899   if (champ)
24900     /* Now verify that champ is better than everything earlier in the
24901        instantiation list.  */
24902     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
24903       if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
24904       {
24905         champ = NULL_TREE;
24906         break;
24907       }
24908     }
24909 
24910   processing_template_decl--;
24911 
24912   if (!champ)
24913     return error_mark_node;
24914 
24915   return champ;
24916 }
24917 
24918 /* If DECL is a specialization of some template, return the most
24919    general such template.  Otherwise, returns NULL_TREE.
24920 
24921    For example, given:
24922 
24923      template <class T> struct S { template <class U> void f(U); };
24924 
24925    if TMPL is `template <class U> void S<int>::f(U)' this will return
24926    the full template.  This function will not trace past partial
24927    specializations, however.  For example, given in addition:
24928 
24929      template <class T> struct S<T*> { template <class U> void f(U); };
24930 
24931    if TMPL is `template <class U> void S<int*>::f(U)' this will return
24932    `template <class T> template <class U> S<T*>::f(U)'.  */
24933 
24934 tree
most_general_template(tree decl)24935 most_general_template (tree decl)
24936 {
24937   if (TREE_CODE (decl) != TEMPLATE_DECL)
24938     {
24939       if (tree tinfo = get_template_info (decl))
24940 	decl = TI_TEMPLATE (tinfo);
24941       /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
24942 	 template friend, or a FIELD_DECL for a capture pack.  */
24943       if (TREE_CODE (decl) != TEMPLATE_DECL)
24944 	return NULL_TREE;
24945     }
24946 
24947   /* Look for more and more general templates.  */
24948   while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
24949     {
24950       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
24951 	 (See cp-tree.h for details.)  */
24952       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
24953 	break;
24954 
24955       if (CLASS_TYPE_P (TREE_TYPE (decl))
24956 	  && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
24957 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
24958 	break;
24959 
24960       /* Stop if we run into an explicitly specialized class template.  */
24961       if (!DECL_NAMESPACE_SCOPE_P (decl)
24962 	  && DECL_CONTEXT (decl)
24963 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
24964 	break;
24965 
24966       decl = DECL_TI_TEMPLATE (decl);
24967     }
24968 
24969   return decl;
24970 }
24971 
24972 /* Return the most specialized of the template partial specializations
24973    which can produce TARGET, a specialization of some class or variable
24974    template.  The value returned is actually a TREE_LIST; the TREE_VALUE is
24975    a TEMPLATE_DECL node corresponding to the partial specialization, while
24976    the TREE_PURPOSE is the set of template arguments that must be
24977    substituted into the template pattern in order to generate TARGET.
24978 
24979    If the choice of partial specialization is ambiguous, a diagnostic
24980    is issued, and the error_mark_node is returned.  If there are no
24981    partial specializations matching TARGET, then NULL_TREE is
24982    returned, indicating that the primary template should be used.  */
24983 
24984 tree
most_specialized_partial_spec(tree target,tsubst_flags_t complain)24985 most_specialized_partial_spec (tree target, tsubst_flags_t complain)
24986 {
24987   tree list = NULL_TREE;
24988   tree t;
24989   tree champ;
24990   int fate;
24991   bool ambiguous_p;
24992   tree outer_args = NULL_TREE;
24993   tree tmpl, args;
24994 
24995   if (TYPE_P (target))
24996     {
24997       tree tinfo = CLASSTYPE_TEMPLATE_INFO (target);
24998       tmpl = TI_TEMPLATE (tinfo);
24999       args = TI_ARGS (tinfo);
25000     }
25001   else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
25002     {
25003       tmpl = TREE_OPERAND (target, 0);
25004       args = TREE_OPERAND (target, 1);
25005     }
25006   else if (VAR_P (target))
25007     {
25008       tree tinfo = DECL_TEMPLATE_INFO (target);
25009       tmpl = TI_TEMPLATE (tinfo);
25010       args = TI_ARGS (tinfo);
25011     }
25012   else
25013     gcc_unreachable ();
25014 
25015   tree main_tmpl = most_general_template (tmpl);
25016 
25017   /* For determining which partial specialization to use, only the
25018      innermost args are interesting.  */
25019   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
25020     {
25021       outer_args = strip_innermost_template_args (args, 1);
25022       args = INNERMOST_TEMPLATE_ARGS (args);
25023     }
25024 
25025   /* The caller hasn't called push_to_top_level yet, but we need
25026      get_partial_spec_bindings to be done in non-template context so that we'll
25027      fully resolve everything.  */
25028   processing_template_decl_sentinel ptds;
25029 
25030   for (t = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl); t; t = TREE_CHAIN (t))
25031     {
25032       const tree ospec_tmpl = TREE_VALUE (t);
25033 
25034       tree spec_tmpl;
25035       if (outer_args)
25036 	{
25037 	  /* Substitute in the template args from the enclosing class.  */
25038 	  ++processing_template_decl;
25039 	  spec_tmpl = tsubst (ospec_tmpl, outer_args, tf_none, NULL_TREE);
25040 	  --processing_template_decl;
25041 	  if (spec_tmpl == error_mark_node)
25042 	    return error_mark_node;
25043 	}
25044       else
25045 	spec_tmpl = ospec_tmpl;
25046 
25047       tree spec_args = get_partial_spec_bindings (tmpl, spec_tmpl, args);
25048       if (spec_args)
25049 	{
25050 	  if (outer_args)
25051 	    spec_args = add_to_template_args (outer_args, spec_args);
25052 
25053           /* Keep the candidate only if the constraints are satisfied,
25054              or if we're not compiling with concepts.  */
25055           if (!flag_concepts
25056 	      || constraints_satisfied_p (ospec_tmpl, spec_args))
25057             {
25058 	      list = tree_cons (spec_args, ospec_tmpl, list);
25059               TREE_TYPE (list) = TREE_TYPE (t);
25060             }
25061 	}
25062     }
25063 
25064   if (! list)
25065     return NULL_TREE;
25066 
25067   ambiguous_p = false;
25068   t = list;
25069   champ = t;
25070   t = TREE_CHAIN (t);
25071   for (; t; t = TREE_CHAIN (t))
25072     {
25073       fate = more_specialized_partial_spec (tmpl, champ, t);
25074       if (fate == 1)
25075 	;
25076       else
25077 	{
25078 	  if (fate == 0)
25079 	    {
25080 	      t = TREE_CHAIN (t);
25081 	      if (! t)
25082 		{
25083 		  ambiguous_p = true;
25084 		  break;
25085 		}
25086 	    }
25087 	  champ = t;
25088 	}
25089     }
25090 
25091   if (!ambiguous_p)
25092     for (t = list; t && t != champ; t = TREE_CHAIN (t))
25093       {
25094 	fate = more_specialized_partial_spec (tmpl, champ, t);
25095 	if (fate != 1)
25096 	  {
25097 	    ambiguous_p = true;
25098 	    break;
25099 	  }
25100       }
25101 
25102   if (ambiguous_p)
25103     {
25104       const char *str;
25105       char *spaces = NULL;
25106       if (!(complain & tf_error))
25107 	return error_mark_node;
25108       if (TYPE_P (target))
25109 	error ("ambiguous template instantiation for %q#T", target);
25110       else
25111 	error ("ambiguous template instantiation for %q#D", target);
25112       str = ngettext ("candidate is:", "candidates are:", list_length (list));
25113       for (t = list; t; t = TREE_CHAIN (t))
25114         {
25115 	  tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
25116           inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
25117 		  "%s %#qS", spaces ? spaces : str, subst);
25118           spaces = spaces ? spaces : get_spaces (str);
25119         }
25120       free (spaces);
25121       return error_mark_node;
25122     }
25123 
25124   return champ;
25125 }
25126 
25127 /* Explicitly instantiate DECL.  */
25128 
25129 void
do_decl_instantiation(tree decl,tree storage)25130 do_decl_instantiation (tree decl, tree storage)
25131 {
25132   tree result = NULL_TREE;
25133   int extern_p = 0;
25134 
25135   if (!decl || decl == error_mark_node)
25136     /* An error occurred, for which grokdeclarator has already issued
25137        an appropriate message.  */
25138     return;
25139   else if (! DECL_LANG_SPECIFIC (decl))
25140     {
25141       error ("explicit instantiation of non-template %q#D", decl);
25142       return;
25143     }
25144   else if (DECL_DECLARED_CONCEPT_P (decl))
25145     {
25146       if (VAR_P (decl))
25147 	error ("explicit instantiation of variable concept %q#D", decl);
25148       else
25149 	error ("explicit instantiation of function concept %q#D", decl);
25150       return;
25151     }
25152 
25153   bool var_templ = (DECL_TEMPLATE_INFO (decl)
25154                     && variable_template_p (DECL_TI_TEMPLATE (decl)));
25155 
25156   if (VAR_P (decl) && !var_templ)
25157     {
25158       /* There is an asymmetry here in the way VAR_DECLs and
25159 	 FUNCTION_DECLs are handled by grokdeclarator.  In the case of
25160 	 the latter, the DECL we get back will be marked as a
25161 	 template instantiation, and the appropriate
25162 	 DECL_TEMPLATE_INFO will be set up.  This does not happen for
25163 	 VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
25164 	 should handle VAR_DECLs as it currently handles
25165 	 FUNCTION_DECLs.  */
25166       if (!DECL_CLASS_SCOPE_P (decl))
25167 	{
25168 	  error ("%qD is not a static data member of a class template", decl);
25169 	  return;
25170 	}
25171       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
25172       if (!result || !VAR_P (result))
25173 	{
25174 	  error ("no matching template for %qD found", decl);
25175 	  return;
25176 	}
25177       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
25178 	{
25179 	  error ("type %qT for explicit instantiation %qD does not match "
25180 		 "declared type %qT", TREE_TYPE (result), decl,
25181 		 TREE_TYPE (decl));
25182 	  return;
25183 	}
25184     }
25185   else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
25186     {
25187       error ("explicit instantiation of %q#D", decl);
25188       return;
25189     }
25190   else
25191     result = decl;
25192 
25193   /* Check for various error cases.  Note that if the explicit
25194      instantiation is valid the RESULT will currently be marked as an
25195      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
25196      until we get here.  */
25197 
25198   if (DECL_TEMPLATE_SPECIALIZATION (result))
25199     {
25200       /* DR 259 [temp.spec].
25201 
25202 	 Both an explicit instantiation and a declaration of an explicit
25203 	 specialization shall not appear in a program unless the explicit
25204 	 instantiation follows a declaration of the explicit specialization.
25205 
25206 	 For a given set of template parameters, if an explicit
25207 	 instantiation of a template appears after a declaration of an
25208 	 explicit specialization for that template, the explicit
25209 	 instantiation has no effect.  */
25210       return;
25211     }
25212   else if (DECL_EXPLICIT_INSTANTIATION (result))
25213     {
25214       /* [temp.spec]
25215 
25216 	 No program shall explicitly instantiate any template more
25217 	 than once.
25218 
25219 	 We check DECL_NOT_REALLY_EXTERN so as not to complain when
25220 	 the first instantiation was `extern' and the second is not,
25221 	 and EXTERN_P for the opposite case.  */
25222       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
25223 	permerror (input_location, "duplicate explicit instantiation of %q#D", result);
25224       /* If an "extern" explicit instantiation follows an ordinary
25225 	 explicit instantiation, the template is instantiated.  */
25226       if (extern_p)
25227 	return;
25228     }
25229   else if (!DECL_IMPLICIT_INSTANTIATION (result))
25230     {
25231       error ("no matching template for %qD found", result);
25232       return;
25233     }
25234   else if (!DECL_TEMPLATE_INFO (result))
25235     {
25236       permerror (input_location, "explicit instantiation of non-template %q#D", result);
25237       return;
25238     }
25239 
25240   if (storage == NULL_TREE)
25241     ;
25242   else if (storage == ridpointers[(int) RID_EXTERN])
25243     {
25244       if (cxx_dialect == cxx98)
25245 	pedwarn (input_location, OPT_Wpedantic,
25246 		 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
25247 		 "instantiations");
25248       extern_p = 1;
25249     }
25250   else
25251     error ("storage class %qD applied to template instantiation", storage);
25252 
25253   check_explicit_instantiation_namespace (result);
25254   mark_decl_instantiated (result, extern_p);
25255   if (! extern_p)
25256     instantiate_decl (result, /*defer_ok=*/true,
25257 		      /*expl_inst_class_mem_p=*/false);
25258 }
25259 
25260 static void
mark_class_instantiated(tree t,int extern_p)25261 mark_class_instantiated (tree t, int extern_p)
25262 {
25263   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
25264   SET_CLASSTYPE_INTERFACE_KNOWN (t);
25265   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
25266   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
25267   if (! extern_p)
25268     {
25269       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
25270       rest_of_type_compilation (t, 1);
25271     }
25272 }
25273 
25274 /* Perform an explicit instantiation of template class T.  STORAGE, if
25275    non-null, is the RID for extern, inline or static.  COMPLAIN is
25276    nonzero if this is called from the parser, zero if called recursively,
25277    since the standard is unclear (as detailed below).  */
25278 
25279 void
do_type_instantiation(tree t,tree storage,tsubst_flags_t complain)25280 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
25281 {
25282   if (!(CLASS_TYPE_P (t) && CLASSTYPE_TEMPLATE_INFO (t)))
25283     {
25284       if (tree ti = TYPE_TEMPLATE_INFO (t))
25285 	error ("explicit instantiation of non-class template %qD",
25286 	       TI_TEMPLATE (ti));
25287       else
25288 	error ("explicit instantiation of non-template type %qT", t);
25289       return;
25290     }
25291 
25292   complete_type (t);
25293 
25294   if (!COMPLETE_TYPE_P (t))
25295     {
25296       if (complain & tf_error)
25297 	error ("explicit instantiation of %q#T before definition of template",
25298 	       t);
25299       return;
25300     }
25301 
25302   /* At most one of these will be true.  */
25303   bool extern_p = false;
25304   bool nomem_p = false;
25305   bool static_p = false;
25306 
25307   if (storage != NULL_TREE)
25308     {
25309       if (storage == ridpointers[(int) RID_EXTERN])
25310 	{
25311 	  if (cxx_dialect == cxx98)
25312 	    pedwarn (input_location, OPT_Wpedantic,
25313 		     "ISO C++ 1998 forbids the use of %<extern%> on "
25314 		     "explicit instantiations");
25315 	}
25316       else
25317 	pedwarn (input_location, OPT_Wpedantic,
25318 		 "ISO C++ forbids the use of %qE"
25319 		 " on explicit instantiations", storage);
25320 
25321       if (storage == ridpointers[(int) RID_INLINE])
25322 	nomem_p = true;
25323       else if (storage == ridpointers[(int) RID_EXTERN])
25324 	extern_p = true;
25325       else if (storage == ridpointers[(int) RID_STATIC])
25326 	static_p = true;
25327       else
25328 	error ("storage class %qD applied to template instantiation",
25329 	       storage);
25330     }
25331 
25332   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
25333     /* DR 259 [temp.spec].
25334 
25335        Both an explicit instantiation and a declaration of an explicit
25336        specialization shall not appear in a program unless the
25337        explicit instantiation follows a declaration of the explicit
25338        specialization.
25339 
25340        For a given set of template parameters, if an explicit
25341        instantiation of a template appears after a declaration of an
25342        explicit specialization for that template, the explicit
25343        instantiation has no effect.  */
25344     return;
25345 
25346   if (CLASSTYPE_EXPLICIT_INSTANTIATION (t) && !CLASSTYPE_INTERFACE_ONLY (t))
25347     {
25348       /* We've already instantiated the template.  */
25349 
25350       /* [temp.spec]
25351 
25352 	 No program shall explicitly instantiate any template more
25353 	 than once.
25354 
25355 	 If EXTERN_P then this is ok.  */
25356       if (!extern_p && (complain & tf_error))
25357 	permerror (input_location,
25358 		   "duplicate explicit instantiation of %q#T", t);
25359 
25360       return;
25361     }
25362 
25363   check_explicit_instantiation_namespace (TYPE_NAME (t));
25364   mark_class_instantiated (t, extern_p);
25365 
25366   if (nomem_p)
25367     return;
25368 
25369   /* In contrast to implicit instantiation, where only the
25370      declarations, and not the definitions, of members are
25371      instantiated, we have here:
25372 
25373 	 [temp.explicit]
25374 
25375 	 An explicit instantiation that names a class template
25376 	 specialization is also an explicit instantiation of the same
25377 	 kind (declaration or definition) of each of its members (not
25378 	 including members inherited from base classes and members
25379 	 that are templates) that has not been previously explicitly
25380 	 specialized in the translation unit containing the explicit
25381 	 instantiation, provided that the associated constraints, if
25382 	 any, of that member are satisfied by the template arguments
25383 	 of the explicit instantiation.  */
25384   for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
25385     if ((VAR_P (fld)
25386 	 || (TREE_CODE (fld) == FUNCTION_DECL
25387 	     && !static_p
25388 	     && user_provided_p (fld)))
25389 	&& DECL_TEMPLATE_INSTANTIATION (fld)
25390 	&& constraints_satisfied_p (fld))
25391       {
25392 	mark_decl_instantiated (fld, extern_p);
25393 	if (! extern_p)
25394 	  instantiate_decl (fld, /*defer_ok=*/true,
25395 			    /*expl_inst_class_mem_p=*/true);
25396       }
25397     else if (DECL_IMPLICIT_TYPEDEF_P (fld))
25398       {
25399 	tree type = TREE_TYPE (fld);
25400 
25401 	if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
25402 	    && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
25403 	  do_type_instantiation (type, storage, 0);
25404       }
25405 }
25406 
25407 /* Given a function DECL, which is a specialization of TMPL, modify
25408    DECL to be a re-instantiation of TMPL with the same template
25409    arguments.  TMPL should be the template into which tsubst'ing
25410    should occur for DECL, not the most general template.
25411 
25412    One reason for doing this is a scenario like this:
25413 
25414      template <class T>
25415      void f(const T&, int i);
25416 
25417      void g() { f(3, 7); }
25418 
25419      template <class T>
25420      void f(const T& t, const int i) { }
25421 
25422    Note that when the template is first instantiated, with
25423    instantiate_template, the resulting DECL will have no name for the
25424    first parameter, and the wrong type for the second.  So, when we go
25425    to instantiate the DECL, we regenerate it.  */
25426 
25427 static void
regenerate_decl_from_template(tree decl,tree tmpl,tree args)25428 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
25429 {
25430   /* The arguments used to instantiate DECL, from the most general
25431      template.  */
25432   tree code_pattern;
25433 
25434   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
25435 
25436   /* Make sure that we can see identifiers, and compute access
25437      correctly.  */
25438   push_access_scope (decl);
25439 
25440   if (TREE_CODE (decl) == FUNCTION_DECL)
25441     {
25442       tree specs;
25443       int args_depth;
25444       int parms_depth;
25445 
25446       args_depth = TMPL_ARGS_DEPTH (args);
25447       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
25448       if (args_depth > parms_depth)
25449 	args = get_innermost_template_args (args, parms_depth);
25450 
25451       /* Instantiate a dynamic exception-specification.  noexcept will be
25452 	 handled below.  */
25453       if (tree raises = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (code_pattern)))
25454 	if (TREE_VALUE (raises))
25455 	  {
25456 	    specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
25457 						    args, tf_error, NULL_TREE,
25458 						    /*defer_ok*/false);
25459 	    if (specs && specs != error_mark_node)
25460 	      TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
25461 							  specs);
25462 	  }
25463 
25464       /* Merge parameter declarations.  */
25465       if (tree pattern_parm
25466 	  = skip_artificial_parms_for (code_pattern,
25467 				       DECL_ARGUMENTS (code_pattern)))
25468 	{
25469 	  tree *p = &DECL_ARGUMENTS (decl);
25470 	  for (int skip = num_artificial_parms_for (decl); skip; --skip)
25471 	    p = &DECL_CHAIN (*p);
25472 	  *p = tsubst_decl (pattern_parm, args, tf_error);
25473 	  for (tree t = *p; t; t = DECL_CHAIN (t))
25474 	    DECL_CONTEXT (t) = decl;
25475 	}
25476 
25477       /* Merge additional specifiers from the CODE_PATTERN.  */
25478       if (DECL_DECLARED_INLINE_P (code_pattern)
25479 	  && !DECL_DECLARED_INLINE_P (decl))
25480 	DECL_DECLARED_INLINE_P (decl) = 1;
25481 
25482       maybe_instantiate_noexcept (decl, tf_error);
25483     }
25484   else if (VAR_P (decl))
25485     {
25486       start_lambda_scope (decl);
25487       DECL_INITIAL (decl) =
25488 	tsubst_init (DECL_INITIAL (code_pattern), decl, args,
25489 		     tf_error, DECL_TI_TEMPLATE (decl));
25490       finish_lambda_scope ();
25491       if (VAR_HAD_UNKNOWN_BOUND (decl))
25492 	TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
25493 				   tf_error, DECL_TI_TEMPLATE (decl));
25494     }
25495   else
25496     gcc_unreachable ();
25497 
25498   pop_access_scope (decl);
25499 }
25500 
25501 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
25502    substituted to get DECL.  */
25503 
25504 tree
template_for_substitution(tree decl)25505 template_for_substitution (tree decl)
25506 {
25507   tree tmpl = DECL_TI_TEMPLATE (decl);
25508 
25509   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
25510      for the instantiation.  This is not always the most general
25511      template.  Consider, for example:
25512 
25513 	template <class T>
25514 	struct S { template <class U> void f();
25515 		   template <> void f<int>(); };
25516 
25517      and an instantiation of S<double>::f<int>.  We want TD to be the
25518      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
25519   while (/* An instantiation cannot have a definition, so we need a
25520 	    more general template.  */
25521 	 DECL_TEMPLATE_INSTANTIATION (tmpl)
25522 	   /* We must also deal with friend templates.  Given:
25523 
25524 		template <class T> struct S {
25525 		  template <class U> friend void f() {};
25526 		};
25527 
25528 	      S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
25529 	      so far as the language is concerned, but that's still
25530 	      where we get the pattern for the instantiation from.  On
25531 	      other hand, if the definition comes outside the class, say:
25532 
25533 		template <class T> struct S {
25534 		  template <class U> friend void f();
25535 		};
25536 		template <class U> friend void f() {}
25537 
25538 	      we don't need to look any further.  That's what the check for
25539 	      DECL_INITIAL is for.  */
25540 	  || (TREE_CODE (decl) == FUNCTION_DECL
25541 	      && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
25542 	      && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
25543     {
25544       /* The present template, TD, should not be a definition.  If it
25545 	 were a definition, we should be using it!  Note that we
25546 	 cannot restructure the loop to just keep going until we find
25547 	 a template with a definition, since that might go too far if
25548 	 a specialization was declared, but not defined.  */
25549 
25550       /* Fetch the more general template.  */
25551       tmpl = DECL_TI_TEMPLATE (tmpl);
25552     }
25553 
25554   return tmpl;
25555 }
25556 
25557 /* Returns true if we need to instantiate this template instance even if we
25558    know we aren't going to emit it.  */
25559 
25560 bool
always_instantiate_p(tree decl)25561 always_instantiate_p (tree decl)
25562 {
25563   /* We always instantiate inline functions so that we can inline them.  An
25564      explicit instantiation declaration prohibits implicit instantiation of
25565      non-inline functions.  With high levels of optimization, we would
25566      normally inline non-inline functions -- but we're not allowed to do
25567      that for "extern template" functions.  Therefore, we check
25568      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
25569   return ((TREE_CODE (decl) == FUNCTION_DECL
25570 	   && (DECL_DECLARED_INLINE_P (decl)
25571 	       || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
25572 	  /* And we need to instantiate static data members so that
25573 	     their initializers are available in integral constant
25574 	     expressions.  */
25575 	  || (VAR_P (decl)
25576 	      && decl_maybe_constant_var_p (decl)));
25577 }
25578 
25579 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
25580    instantiate it now, modifying TREE_TYPE (fn).  Returns false on
25581    error, true otherwise.  */
25582 
25583 bool
maybe_instantiate_noexcept(tree fn,tsubst_flags_t complain)25584 maybe_instantiate_noexcept (tree fn, tsubst_flags_t complain)
25585 {
25586   if (fn == error_mark_node)
25587     return false;
25588 
25589   /* Don't instantiate a noexcept-specification from template context.  */
25590   if (processing_template_decl
25591       && (!flag_noexcept_type || type_dependent_expression_p (fn)))
25592     return true;
25593 
25594   if (DECL_MAYBE_DELETED (fn))
25595     {
25596       if (fn == current_function_decl)
25597 	/* We're in start_preparsed_function, keep going.  */
25598 	return true;
25599 
25600       ++function_depth;
25601       synthesize_method (fn);
25602       --function_depth;
25603       return !DECL_MAYBE_DELETED (fn);
25604     }
25605 
25606   tree fntype = TREE_TYPE (fn);
25607   tree spec = TYPE_RAISES_EXCEPTIONS (fntype);
25608 
25609   if (!spec || !TREE_PURPOSE (spec))
25610     return true;
25611 
25612   tree noex = TREE_PURPOSE (spec);
25613   if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
25614       && TREE_CODE (noex) != DEFERRED_PARSE)
25615     return true;
25616 
25617   tree orig_fn = NULL_TREE;
25618   /* For a member friend template we can get a TEMPLATE_DECL.  Let's use
25619      its FUNCTION_DECL for the rest of this function -- push_access_scope
25620      doesn't accept TEMPLATE_DECLs.  */
25621   if (DECL_FUNCTION_TEMPLATE_P (fn))
25622     {
25623       orig_fn = fn;
25624       fn = DECL_TEMPLATE_RESULT (fn);
25625     }
25626 
25627   if (DECL_CLONED_FUNCTION_P (fn))
25628     {
25629       tree prime = DECL_CLONED_FUNCTION (fn);
25630       if (!maybe_instantiate_noexcept (prime, complain))
25631 	return false;
25632       spec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (prime));
25633     }
25634   else if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
25635     {
25636       static hash_set<tree>* fns = new hash_set<tree>;
25637       bool added = false;
25638       if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
25639 	{
25640 	  spec = get_defaulted_eh_spec (fn, complain);
25641 	  if (spec == error_mark_node)
25642 	    /* This might have failed because of an unparsed DMI, so
25643 	       let's try again later.  */
25644 	    return false;
25645 	}
25646       else if (!(added = !fns->add (fn)))
25647 	{
25648 	  /* If hash_set::add returns true, the element was already there.  */
25649 	  location_t loc = cp_expr_loc_or_loc (DEFERRED_NOEXCEPT_PATTERN (noex),
25650 					    DECL_SOURCE_LOCATION (fn));
25651 	  error_at (loc,
25652 		    "exception specification of %qD depends on itself",
25653 		    fn);
25654 	  spec = noexcept_false_spec;
25655 	}
25656       else if (push_tinst_level (fn))
25657 	{
25658 	  push_to_top_level ();
25659 	  push_access_scope (fn);
25660 	  push_deferring_access_checks (dk_no_deferred);
25661 	  input_location = DECL_SOURCE_LOCATION (fn);
25662 
25663 	  if (!DECL_LOCAL_DECL_P (fn))
25664 	    {
25665 	      /* If needed, set current_class_ptr for the benefit of
25666 		 tsubst_copy/PARM_DECL.  The exception pattern will
25667 		 refer to the parm of the template, not the
25668 		 instantiation.  */
25669 	      tree tdecl = DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (fn));
25670 	      if (DECL_NONSTATIC_MEMBER_FUNCTION_P (tdecl))
25671 		{
25672 		  tree this_parm = DECL_ARGUMENTS (tdecl);
25673 		  current_class_ptr = NULL_TREE;
25674 		  current_class_ref = cp_build_fold_indirect_ref (this_parm);
25675 		  current_class_ptr = this_parm;
25676 		}
25677 	    }
25678 
25679 	  /* If this function is represented by a TEMPLATE_DECL, then
25680 	     the deferred noexcept-specification might still contain
25681 	     dependent types, even after substitution.  And we need the
25682 	     dependency check functions to work in build_noexcept_spec.  */
25683 	  if (orig_fn)
25684 	    ++processing_template_decl;
25685 
25686 	  /* Do deferred instantiation of the noexcept-specifier.  */
25687 	  noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
25688 					DEFERRED_NOEXCEPT_ARGS (noex),
25689 					tf_warning_or_error, fn,
25690 					/*function_p=*/false,
25691 					/*i_c_e_p=*/true);
25692 
25693 	  /* Build up the noexcept-specification.  */
25694 	  spec = build_noexcept_spec (noex, tf_warning_or_error);
25695 
25696 	  if (orig_fn)
25697 	    --processing_template_decl;
25698 
25699 	  pop_deferring_access_checks ();
25700 	  pop_access_scope (fn);
25701 	  pop_tinst_level ();
25702 	  pop_from_top_level ();
25703 	}
25704       else
25705 	spec = noexcept_false_spec;
25706 
25707       if (added)
25708 	fns->remove (fn);
25709     }
25710 
25711   if (spec == error_mark_node)
25712     {
25713       /* This failed with a hard error, so let's go with false.  */
25714       gcc_assert (seen_error ());
25715       spec = noexcept_false_spec;
25716     }
25717 
25718   TREE_TYPE (fn) = build_exception_variant (fntype, spec);
25719   if (orig_fn)
25720     TREE_TYPE (orig_fn) = TREE_TYPE (fn);
25721 
25722   return true;
25723 }
25724 
25725 /* We're starting to process the function INST, an instantiation of PATTERN;
25726    add their parameters to local_specializations.  */
25727 
25728 static void
register_parameter_specializations(tree pattern,tree inst)25729 register_parameter_specializations (tree pattern, tree inst)
25730 {
25731   tree tmpl_parm = DECL_ARGUMENTS (pattern);
25732   tree spec_parm = DECL_ARGUMENTS (inst);
25733   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (inst))
25734     {
25735       register_local_specialization (spec_parm, tmpl_parm);
25736       spec_parm = skip_artificial_parms_for (inst, spec_parm);
25737       tmpl_parm = skip_artificial_parms_for (pattern, tmpl_parm);
25738     }
25739   for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
25740     {
25741       if (!DECL_PACK_P (tmpl_parm))
25742 	{
25743 	  register_local_specialization (spec_parm, tmpl_parm);
25744 	  spec_parm = DECL_CHAIN (spec_parm);
25745 	}
25746       else
25747 	{
25748 	  /* Register the (value) argument pack as a specialization of
25749 	     TMPL_PARM, then move on.  */
25750 	  tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
25751 	  register_local_specialization (argpack, tmpl_parm);
25752 	}
25753     }
25754   gcc_assert (!spec_parm);
25755 }
25756 
25757 /* Instantiate the body of D using PATTERN with ARGS.  We have
25758    already determined PATTERN is the correct template to use.
25759    NESTED_P is true if this is a nested function, in which case
25760    PATTERN will be a FUNCTION_DECL not a TEMPLATE_DECL.  */
25761 
25762 static void
instantiate_body(tree pattern,tree args,tree d,bool nested_p)25763 instantiate_body (tree pattern, tree args, tree d, bool nested_p)
25764 {
25765   tree td = NULL_TREE;
25766   tree code_pattern = pattern;
25767 
25768   if (!nested_p)
25769     {
25770       td = pattern;
25771       code_pattern = DECL_TEMPLATE_RESULT (td);
25772     }
25773   else
25774     /* Only OMP reductions are nested.  */
25775     gcc_checking_assert (DECL_OMP_DECLARE_REDUCTION_P (code_pattern));
25776 
25777   vec<tree> omp_privatization_save;
25778   if (current_function_decl)
25779     save_omp_privatization_clauses (omp_privatization_save);
25780 
25781   bool push_to_top
25782     = !(current_function_decl
25783 	&& !LAMBDA_FUNCTION_P (d)
25784 	&& decl_function_context (d) == current_function_decl);
25785 
25786   if (push_to_top)
25787     push_to_top_level ();
25788   else
25789     {
25790       gcc_assert (!processing_template_decl);
25791       push_function_context ();
25792       cp_unevaluated_operand = 0;
25793       c_inhibit_evaluation_warnings = 0;
25794     }
25795 
25796   if (VAR_P (d))
25797     {
25798       /* The variable might be a lambda's extra scope, and that
25799 	 lambda's visibility depends on D's.  */
25800       maybe_commonize_var (d);
25801       determine_visibility (d);
25802     }
25803 
25804   /* Mark D as instantiated so that recursive calls to
25805      instantiate_decl do not try to instantiate it again.  */
25806   DECL_TEMPLATE_INSTANTIATED (d) = 1;
25807 
25808   if (td)
25809     /* Regenerate the declaration in case the template has been modified
25810        by a subsequent redeclaration.  */
25811     regenerate_decl_from_template (d, td, args);
25812 
25813   /* We already set the file and line above.  Reset them now in case
25814      they changed as a result of calling regenerate_decl_from_template.  */
25815   input_location = DECL_SOURCE_LOCATION (d);
25816 
25817   if (VAR_P (d))
25818     {
25819       /* Clear out DECL_RTL; whatever was there before may not be right
25820 	 since we've reset the type of the declaration.  */
25821       SET_DECL_RTL (d, NULL);
25822       DECL_IN_AGGR_P (d) = 0;
25823 
25824       /* The initializer is placed in DECL_INITIAL by
25825 	 regenerate_decl_from_template so we don't need to
25826 	 push/pop_access_scope again here.  Pull it out so that
25827 	 cp_finish_decl can process it.  */
25828       bool const_init = false;
25829       tree init = DECL_INITIAL (d);
25830       DECL_INITIAL (d) = NULL_TREE;
25831       DECL_INITIALIZED_P (d) = 0;
25832 
25833       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
25834 	 initializer.  That function will defer actual emission until
25835 	 we have a chance to determine linkage.  */
25836       DECL_EXTERNAL (d) = 0;
25837 
25838       /* Enter the scope of D so that access-checking works correctly.  */
25839       bool enter_context = DECL_CLASS_SCOPE_P (d);
25840       if (enter_context)
25841         push_nested_class (DECL_CONTEXT (d));
25842 
25843       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
25844       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
25845 
25846       if (enter_context)
25847         pop_nested_class ();
25848     }
25849   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
25850     synthesize_method (d);
25851   else if (TREE_CODE (d) == FUNCTION_DECL)
25852     {
25853       /* Set up the list of local specializations.  */
25854       local_specialization_stack lss (push_to_top ? lss_blank : lss_copy);
25855       tree block = NULL_TREE;
25856 
25857       /* Set up context.  */
25858       if (nested_p)
25859 	block = push_stmt_list ();
25860       else
25861 	{
25862 	  start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
25863 
25864 	  perform_instantiation_time_access_checks (code_pattern, args);
25865 	}
25866 
25867       /* Create substitution entries for the parameters.  */
25868       register_parameter_specializations (code_pattern, d);
25869 
25870       /* Substitute into the body of the function.  */
25871       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
25872 	tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
25873 			tf_warning_or_error, d);
25874       else
25875 	{
25876 	  tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
25877 		       tf_warning_or_error, DECL_TI_TEMPLATE (d),
25878 		       /*integral_constant_expression_p=*/false);
25879 
25880 	  /* Set the current input_location to the end of the function
25881 	     so that finish_function knows where we are.  */
25882 	  input_location
25883 	    = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
25884 
25885 	  /* Remember if we saw an infinite loop in the template.  */
25886 	  current_function_infinite_loop
25887 	    = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
25888 	}
25889 
25890       /* Finish the function.  */
25891       if (nested_p)
25892 	DECL_SAVED_TREE (d) = pop_stmt_list (block);
25893       else
25894 	{
25895 	  d = finish_function (/*inline_p=*/false);
25896 	  expand_or_defer_fn (d);
25897 	}
25898 
25899       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
25900 	cp_check_omp_declare_reduction (d);
25901     }
25902 
25903   /* We're not deferring instantiation any more.  */
25904   if (!nested_p)
25905     TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
25906 
25907   if (push_to_top)
25908     pop_from_top_level ();
25909   else
25910     pop_function_context ();
25911 
25912   if (current_function_decl)
25913     restore_omp_privatization_clauses (omp_privatization_save);
25914 }
25915 
25916 /* Produce the definition of D, a _DECL generated from a template.  If
25917    DEFER_OK is true, then we don't have to actually do the
25918    instantiation now; we just have to do it sometime.  Normally it is
25919    an error if this is an explicit instantiation but D is undefined.
25920    EXPL_INST_CLASS_MEM_P is true iff D is a member of an explicitly
25921    instantiated class template.  */
25922 
25923 tree
instantiate_decl(tree d,bool defer_ok,bool expl_inst_class_mem_p)25924 instantiate_decl (tree d, bool defer_ok, bool expl_inst_class_mem_p)
25925 {
25926   tree tmpl = DECL_TI_TEMPLATE (d);
25927   tree gen_args;
25928   tree args;
25929   tree td;
25930   tree code_pattern;
25931   tree spec;
25932   tree gen_tmpl;
25933   bool pattern_defined;
25934   location_t saved_loc = input_location;
25935   int saved_unevaluated_operand = cp_unevaluated_operand;
25936   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
25937   bool external_p;
25938   bool deleted_p;
25939 
25940   /* This function should only be used to instantiate templates for
25941      functions and static member variables.  */
25942   gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
25943 
25944   /* A concept is never instantiated. */
25945   gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
25946 
25947   gcc_checking_assert (!DECL_FUNCTION_SCOPE_P (d));
25948 
25949   if (modules_p ())
25950     /* We may have a pending instantiation of D itself.  */
25951     lazy_load_pendings (d);
25952 
25953   /* Variables are never deferred; if instantiation is required, they
25954      are instantiated right away.  That allows for better code in the
25955      case that an expression refers to the value of the variable --
25956      if the variable has a constant value the referring expression can
25957      take advantage of that fact.  */
25958   if (VAR_P (d))
25959     defer_ok = false;
25960 
25961   /* Don't instantiate cloned functions.  Instead, instantiate the
25962      functions they cloned.  */
25963   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
25964     d = DECL_CLONED_FUNCTION (d);
25965 
25966   if (DECL_TEMPLATE_INSTANTIATED (d)
25967       || TREE_TYPE (d) == error_mark_node
25968       || (TREE_CODE (d) == FUNCTION_DECL
25969 	  && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
25970       || DECL_TEMPLATE_SPECIALIZATION (d))
25971     /* D has already been instantiated or explicitly specialized, so
25972        there's nothing for us to do here.
25973 
25974        It might seem reasonable to check whether or not D is an explicit
25975        instantiation, and, if so, stop here.  But when an explicit
25976        instantiation is deferred until the end of the compilation,
25977        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
25978        the instantiation.  */
25979     return d;
25980 
25981   /* Check to see whether we know that this template will be
25982      instantiated in some other file, as with "extern template"
25983      extension.  */
25984   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
25985 
25986   /* In general, we do not instantiate such templates.  */
25987   if (external_p && !always_instantiate_p (d))
25988     return d;
25989 
25990   gen_tmpl = most_general_template (tmpl);
25991   gen_args = DECL_TI_ARGS (d);
25992 
25993   /* We should already have the extra args.  */
25994   gcc_checking_assert (tmpl == gen_tmpl
25995 		       || (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
25996 			   == TMPL_ARGS_DEPTH (gen_args)));
25997   /* And what's in the hash table should match D.  */
25998   gcc_checking_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0))
25999 		       == d
26000 		       || spec == NULL_TREE);
26001 
26002   /* This needs to happen before any tsubsting.  */
26003   if (! push_tinst_level (d))
26004     return d;
26005 
26006   timevar_push (TV_TEMPLATE_INST);
26007 
26008   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
26009      for the instantiation.  */
26010   td = template_for_substitution (d);
26011   args = gen_args;
26012 
26013   if (VAR_P (d))
26014     {
26015       /* Look up an explicit specialization, if any.  */
26016       tree tid = lookup_template_variable (gen_tmpl, gen_args);
26017       tree elt = most_specialized_partial_spec (tid, tf_warning_or_error);
26018       if (elt && elt != error_mark_node)
26019 	{
26020 	  td = TREE_VALUE (elt);
26021 	  args = TREE_PURPOSE (elt);
26022 	}
26023     }
26024 
26025   code_pattern = DECL_TEMPLATE_RESULT (td);
26026 
26027   /* We should never be trying to instantiate a member of a class
26028      template or partial specialization.  */
26029   gcc_assert (d != code_pattern);
26030 
26031   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
26032       || DECL_TEMPLATE_SPECIALIZATION (td))
26033     /* In the case of a friend template whose definition is provided
26034        outside the class, we may have too many arguments.  Drop the
26035        ones we don't need.  The same is true for specializations.  */
26036     args = get_innermost_template_args
26037       (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
26038 
26039   if (TREE_CODE (d) == FUNCTION_DECL)
26040     {
26041       deleted_p = DECL_DELETED_FN (code_pattern);
26042       pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
26043 			  && DECL_INITIAL (code_pattern) != error_mark_node)
26044 			 || DECL_DEFAULTED_FN (code_pattern)
26045 			 || deleted_p);
26046     }
26047   else
26048     {
26049       deleted_p = false;
26050       if (DECL_CLASS_SCOPE_P (code_pattern))
26051 	pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
26052       else
26053 	pattern_defined = ! DECL_EXTERNAL (code_pattern);
26054     }
26055 
26056   /* We may be in the middle of deferred access check.  Disable it now.  */
26057   push_deferring_access_checks (dk_no_deferred);
26058 
26059   /* Unless an explicit instantiation directive has already determined
26060      the linkage of D, remember that a definition is available for
26061      this entity.  */
26062   if (pattern_defined
26063       && !DECL_INTERFACE_KNOWN (d)
26064       && !DECL_NOT_REALLY_EXTERN (d))
26065     mark_definable (d);
26066 
26067   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
26068   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
26069   input_location = DECL_SOURCE_LOCATION (d);
26070 
26071   /* If D is a member of an explicitly instantiated class template,
26072      and no definition is available, treat it like an implicit
26073      instantiation.  */
26074   if (!pattern_defined && expl_inst_class_mem_p
26075       && DECL_EXPLICIT_INSTANTIATION (d))
26076     {
26077       /* Leave linkage flags alone on instantiations with anonymous
26078 	 visibility.  */
26079       if (TREE_PUBLIC (d))
26080 	{
26081 	  DECL_NOT_REALLY_EXTERN (d) = 0;
26082 	  DECL_INTERFACE_KNOWN (d) = 0;
26083 	}
26084       SET_DECL_IMPLICIT_INSTANTIATION (d);
26085     }
26086 
26087   /* Defer all other templates, unless we have been explicitly
26088      forbidden from doing so.  */
26089   if (/* If there is no definition, we cannot instantiate the
26090 	 template.  */
26091       ! pattern_defined
26092       /* If it's OK to postpone instantiation, do so.  */
26093       || defer_ok
26094       /* If this is a static data member that will be defined
26095 	 elsewhere, we don't want to instantiate the entire data
26096 	 member, but we do want to instantiate the initializer so that
26097 	 we can substitute that elsewhere.  */
26098       || (external_p && VAR_P (d))
26099       /* Handle here a deleted function too, avoid generating
26100 	 its body (c++/61080).  */
26101       || deleted_p)
26102     {
26103       /* The definition of the static data member is now required so
26104 	 we must substitute the initializer.  */
26105       if (VAR_P (d)
26106 	  && !DECL_INITIAL (d)
26107 	  && DECL_INITIAL (code_pattern))
26108 	{
26109 	  tree ns;
26110 	  tree init;
26111 	  bool const_init = false;
26112 	  bool enter_context = DECL_CLASS_SCOPE_P (d);
26113 
26114 	  ns = decl_namespace_context (d);
26115 	  push_nested_namespace (ns);
26116 	  if (enter_context)
26117 	    push_nested_class (DECL_CONTEXT (d));
26118 	  init = tsubst_expr (DECL_INITIAL (code_pattern),
26119 			      args,
26120 			      tf_warning_or_error, NULL_TREE,
26121 			      /*integral_constant_expression_p=*/false);
26122 	  /* If instantiating the initializer involved instantiating this
26123 	     again, don't call cp_finish_decl twice.  */
26124 	  if (!DECL_INITIAL (d))
26125 	    {
26126 	      /* Make sure the initializer is still constant, in case of
26127 		 circular dependency (template/instantiate6.C). */
26128 	      const_init
26129 		= DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
26130 	      cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
26131 			      /*asmspec_tree=*/NULL_TREE,
26132 			      LOOKUP_ONLYCONVERTING);
26133 	    }
26134 	  if (enter_context)
26135 	    pop_nested_class ();
26136 	  pop_nested_namespace (ns);
26137 	}
26138 
26139       /* We restore the source position here because it's used by
26140 	 add_pending_template.  */
26141       input_location = saved_loc;
26142 
26143       if (at_eof && !pattern_defined
26144 	  && DECL_EXPLICIT_INSTANTIATION (d)
26145 	  && DECL_NOT_REALLY_EXTERN (d))
26146 	/* [temp.explicit]
26147 
26148 	   The definition of a non-exported function template, a
26149 	   non-exported member function template, or a non-exported
26150 	   member function or static data member of a class template
26151 	   shall be present in every translation unit in which it is
26152 	   explicitly instantiated.  */
26153 	permerror (input_location,  "explicit instantiation of %qD "
26154 		   "but no definition available", d);
26155 
26156       /* If we're in unevaluated context, we just wanted to get the
26157 	 constant value; this isn't an odr use, so don't queue
26158 	 a full instantiation.  */
26159       if (!cp_unevaluated_operand
26160 	  /* ??? Historically, we have instantiated inline functions, even
26161 	     when marked as "extern template".  */
26162 	  && !(external_p && VAR_P (d)))
26163 	add_pending_template (d);
26164     }
26165   else
26166     {
26167       set_instantiating_module (d);
26168       if (variable_template_p (gen_tmpl))
26169 	note_variable_template_instantiation (d);
26170       instantiate_body (td, args, d, false);
26171     }
26172 
26173   pop_deferring_access_checks ();
26174   timevar_pop (TV_TEMPLATE_INST);
26175   pop_tinst_level ();
26176   input_location = saved_loc;
26177   cp_unevaluated_operand = saved_unevaluated_operand;
26178   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
26179 
26180   return d;
26181 }
26182 
26183 /* Run through the list of templates that we wish we could
26184    instantiate, and instantiate any we can.  RETRIES is the
26185    number of times we retry pending template instantiation.  */
26186 
26187 void
instantiate_pending_templates(int retries)26188 instantiate_pending_templates (int retries)
26189 {
26190   int reconsider;
26191   location_t saved_loc = input_location;
26192 
26193   /* Instantiating templates may trigger vtable generation.  This in turn
26194      may require further template instantiations.  We place a limit here
26195      to avoid infinite loop.  */
26196   if (pending_templates && retries >= max_tinst_depth)
26197     {
26198       tree decl = pending_templates->tinst->maybe_get_node ();
26199 
26200       fatal_error (input_location,
26201 		   "template instantiation depth exceeds maximum of %d"
26202 		   " instantiating %q+D, possibly from virtual table generation"
26203 		   " (use %<-ftemplate-depth=%> to increase the maximum)",
26204 		   max_tinst_depth, decl);
26205       if (TREE_CODE (decl) == FUNCTION_DECL)
26206 	/* Pretend that we defined it.  */
26207 	DECL_INITIAL (decl) = error_mark_node;
26208       return;
26209     }
26210 
26211   do
26212     {
26213       struct pending_template **t = &pending_templates;
26214       struct pending_template *last = NULL;
26215       reconsider = 0;
26216       while (*t)
26217 	{
26218 	  tree instantiation = reopen_tinst_level ((*t)->tinst);
26219 	  bool complete = false;
26220 
26221 	  if (TYPE_P (instantiation))
26222 	    {
26223 	      if (!COMPLETE_TYPE_P (instantiation))
26224 		{
26225 		  instantiate_class_template (instantiation);
26226 		  if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
26227 		    for (tree fld = TYPE_FIELDS (instantiation);
26228 			 fld; fld = TREE_CHAIN (fld))
26229 		      if ((VAR_P (fld)
26230 			   || (TREE_CODE (fld) == FUNCTION_DECL
26231 			       && !DECL_ARTIFICIAL (fld)))
26232 			  && DECL_TEMPLATE_INSTANTIATION (fld))
26233 			instantiate_decl (fld,
26234 					  /*defer_ok=*/false,
26235 					  /*expl_inst_class_mem_p=*/false);
26236 
26237 		  if (COMPLETE_TYPE_P (instantiation))
26238 		    reconsider = 1;
26239 		}
26240 
26241 	      complete = COMPLETE_TYPE_P (instantiation);
26242 	    }
26243 	  else
26244 	    {
26245 	      if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
26246 		  && !DECL_TEMPLATE_INSTANTIATED (instantiation))
26247 		{
26248 		  instantiation
26249 		    = instantiate_decl (instantiation,
26250 					/*defer_ok=*/false,
26251 					/*expl_inst_class_mem_p=*/false);
26252 		  if (DECL_TEMPLATE_INSTANTIATED (instantiation))
26253 		    reconsider = 1;
26254 		}
26255 
26256 	      complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
26257 			  || DECL_TEMPLATE_INSTANTIATED (instantiation));
26258 	    }
26259 
26260 	  if (complete)
26261 	    {
26262 	      /* If INSTANTIATION has been instantiated, then we don't
26263 		 need to consider it again in the future.  */
26264 	      struct pending_template *drop = *t;
26265 	      *t = (*t)->next;
26266 	      set_refcount_ptr (drop->tinst);
26267 	      pending_template_freelist ().free (drop);
26268 	    }
26269 	  else
26270 	    {
26271 	      last = *t;
26272 	      t = &(*t)->next;
26273 	    }
26274 	  tinst_depth = 0;
26275 	  set_refcount_ptr (current_tinst_level);
26276 	}
26277       last_pending_template = last;
26278     }
26279   while (reconsider);
26280 
26281   input_location = saved_loc;
26282 }
26283 
26284 /* Substitute ARGVEC into T, which is a list of initializers for
26285    either base class or a non-static data member.  The TREE_PURPOSEs
26286    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
26287    instantiate_decl.  */
26288 
26289 static tree
tsubst_initializer_list(tree t,tree argvec)26290 tsubst_initializer_list (tree t, tree argvec)
26291 {
26292   tree inits = NULL_TREE;
26293   tree target_ctor = error_mark_node;
26294 
26295   for (; t; t = TREE_CHAIN (t))
26296     {
26297       tree decl;
26298       tree init;
26299       tree expanded_bases = NULL_TREE;
26300       tree expanded_arguments = NULL_TREE;
26301       int i, len = 1;
26302 
26303       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
26304         {
26305           tree expr;
26306           tree arg;
26307 
26308           /* Expand the base class expansion type into separate base
26309              classes.  */
26310           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
26311                                                  tf_warning_or_error,
26312                                                  NULL_TREE);
26313           if (expanded_bases == error_mark_node)
26314             continue;
26315 
26316           /* We'll be building separate TREE_LISTs of arguments for
26317              each base.  */
26318           len = TREE_VEC_LENGTH (expanded_bases);
26319           expanded_arguments = make_tree_vec (len);
26320           for (i = 0; i < len; i++)
26321             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
26322 
26323           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
26324              expand each argument in the TREE_VALUE of t.  */
26325           expr = make_node (EXPR_PACK_EXPANSION);
26326 	  PACK_EXPANSION_LOCAL_P (expr) = true;
26327           PACK_EXPANSION_PARAMETER_PACKS (expr) =
26328             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
26329 
26330 	  if (TREE_VALUE (t) == void_type_node)
26331 	    /* VOID_TYPE_NODE is used to indicate
26332 	       value-initialization.  */
26333 	    {
26334 	      for (i = 0; i < len; i++)
26335 		TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
26336 	    }
26337 	  else
26338 	    {
26339 	      /* Substitute parameter packs into each argument in the
26340 		 TREE_LIST.  */
26341 	      in_base_initializer = 1;
26342 	      for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
26343 		{
26344 		  tree expanded_exprs;
26345 
26346 		  /* Expand the argument.  */
26347 		  SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
26348 		  expanded_exprs
26349 		    = tsubst_pack_expansion (expr, argvec,
26350 					     tf_warning_or_error,
26351 					     NULL_TREE);
26352 		  if (expanded_exprs == error_mark_node)
26353 		    continue;
26354 
26355 		  /* Prepend each of the expanded expressions to the
26356 		     corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
26357 		  for (i = 0; i < len; i++)
26358 		    {
26359 		      TREE_VEC_ELT (expanded_arguments, i) =
26360 			tree_cons (NULL_TREE,
26361 				   TREE_VEC_ELT (expanded_exprs, i),
26362 				   TREE_VEC_ELT (expanded_arguments, i));
26363 		    }
26364 		}
26365 	      in_base_initializer = 0;
26366 
26367 	      /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
26368 		 since we built them backwards.  */
26369 	      for (i = 0; i < len; i++)
26370 		{
26371 		  TREE_VEC_ELT (expanded_arguments, i) =
26372 		    nreverse (TREE_VEC_ELT (expanded_arguments, i));
26373 		}
26374 	    }
26375         }
26376 
26377       for (i = 0; i < len; ++i)
26378         {
26379           if (expanded_bases)
26380             {
26381               decl = TREE_VEC_ELT (expanded_bases, i);
26382               decl = expand_member_init (decl);
26383               init = TREE_VEC_ELT (expanded_arguments, i);
26384             }
26385           else
26386             {
26387 	      tree tmp;
26388               decl = tsubst_copy (TREE_PURPOSE (t), argvec,
26389                                   tf_warning_or_error, NULL_TREE);
26390 
26391               decl = expand_member_init (decl);
26392               if (decl && !DECL_P (decl))
26393                 in_base_initializer = 1;
26394 
26395 	      init = TREE_VALUE (t);
26396 	      tmp = init;
26397 	      if (init != void_type_node)
26398 		init = tsubst_expr (init, argvec,
26399 				    tf_warning_or_error, NULL_TREE,
26400 				    /*integral_constant_expression_p=*/false);
26401 	      if (init == NULL_TREE && tmp != NULL_TREE)
26402 		/* If we had an initializer but it instantiated to nothing,
26403 		   value-initialize the object.  This will only occur when
26404 		   the initializer was a pack expansion where the parameter
26405 		   packs used in that expansion were of length zero.  */
26406 		init = void_type_node;
26407               in_base_initializer = 0;
26408             }
26409 
26410 	  if (target_ctor != error_mark_node
26411 	      && init != error_mark_node)
26412 	    {
26413 	      error ("mem-initializer for %qD follows constructor delegation",
26414 		     decl);
26415 	      return inits;
26416 	    }
26417 	  /* Look for a target constructor. */
26418 	  if (init != error_mark_node
26419 	      && decl && CLASS_TYPE_P (decl)
26420 	      && same_type_p (decl, current_class_type))
26421 	    {
26422 	      maybe_warn_cpp0x (CPP0X_DELEGATING_CTORS);
26423 	      if (inits)
26424 		{
26425 		  error ("constructor delegation follows mem-initializer for %qD",
26426 			 TREE_PURPOSE (inits));
26427 		  continue;
26428 		}
26429 	      target_ctor = init;
26430 	    }
26431 
26432           if (decl)
26433             {
26434               init = build_tree_list (decl, init);
26435 	      /* Carry over the dummy TREE_TYPE node containing the source
26436 		 location.  */
26437 	      TREE_TYPE (init) = TREE_TYPE (t);
26438               TREE_CHAIN (init) = inits;
26439               inits = init;
26440             }
26441         }
26442     }
26443   return inits;
26444 }
26445 
26446 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
26447    is the instantiation (which should have been created with
26448    start_enum) and ARGS are the template arguments to use.  */
26449 
26450 static void
tsubst_enum(tree tag,tree newtag,tree args)26451 tsubst_enum (tree tag, tree newtag, tree args)
26452 {
26453   tree e;
26454 
26455   if (SCOPED_ENUM_P (newtag))
26456     begin_scope (sk_scoped_enum, newtag);
26457 
26458   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
26459     {
26460       tree value;
26461       tree decl;
26462 
26463       decl = TREE_VALUE (e);
26464       /* Note that in a template enum, the TREE_VALUE is the
26465 	 CONST_DECL, not the corresponding INTEGER_CST.  */
26466       value = tsubst_expr (DECL_INITIAL (decl),
26467 			   args, tf_warning_or_error, NULL_TREE,
26468 			   /*integral_constant_expression_p=*/true);
26469 
26470       /* Give this enumeration constant the correct access.  */
26471       set_current_access_from_decl (decl);
26472 
26473       /* Actually build the enumerator itself.  Here we're assuming that
26474 	 enumerators can't have dependent attributes.  */
26475       build_enumerator (DECL_NAME (decl), value, newtag,
26476 			DECL_ATTRIBUTES (decl), DECL_SOURCE_LOCATION (decl));
26477     }
26478 
26479   if (SCOPED_ENUM_P (newtag))
26480     finish_scope ();
26481 
26482   finish_enum_value_list (newtag);
26483   finish_enum (newtag);
26484 
26485   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
26486     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
26487 }
26488 
26489 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
26490    its type -- but without substituting the innermost set of template
26491    arguments.  So, innermost set of template parameters will appear in
26492    the type.  */
26493 
26494 tree
get_mostly_instantiated_function_type(tree decl)26495 get_mostly_instantiated_function_type (tree decl)
26496 {
26497   /* For a function, DECL_TI_TEMPLATE is partially instantiated.  */
26498   return TREE_TYPE (DECL_TI_TEMPLATE (decl));
26499 }
26500 
26501 /* Return truthvalue if we're processing a template different from
26502    the last one involved in diagnostics.  */
26503 bool
problematic_instantiation_changed(void)26504 problematic_instantiation_changed (void)
26505 {
26506   return current_tinst_level != last_error_tinst_level;
26507 }
26508 
26509 /* Remember current template involved in diagnostics.  */
26510 void
record_last_problematic_instantiation(void)26511 record_last_problematic_instantiation (void)
26512 {
26513   set_refcount_ptr (last_error_tinst_level, current_tinst_level);
26514 }
26515 
26516 struct tinst_level *
current_instantiation(void)26517 current_instantiation (void)
26518 {
26519   return current_tinst_level;
26520 }
26521 
26522 /* Return TRUE if current_function_decl is being instantiated, false
26523    otherwise.  */
26524 
26525 bool
instantiating_current_function_p(void)26526 instantiating_current_function_p (void)
26527 {
26528   return (current_instantiation ()
26529 	  && (current_instantiation ()->maybe_get_node ()
26530 	      == current_function_decl));
26531 }
26532 
26533 /* [temp.param] Check that template non-type parm TYPE is of an allowable
26534    type.  Return false for ok, true for disallowed.  Issue error and
26535    inform messages under control of COMPLAIN.  */
26536 
26537 static bool
invalid_nontype_parm_type_p(tree type,tsubst_flags_t complain)26538 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
26539 {
26540   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
26541     return false;
26542   else if (TYPE_PTR_P (type))
26543     return false;
26544   else if (TYPE_REF_P (type)
26545 	   && !TYPE_REF_IS_RVALUE (type))
26546     return false;
26547   else if (TYPE_PTRMEM_P (type))
26548     return false;
26549   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
26550     {
26551       if (CLASS_PLACEHOLDER_TEMPLATE (type) && cxx_dialect < cxx20)
26552 	{
26553 	  if (complain & tf_error)
26554 	    error ("non-type template parameters of deduced class type only "
26555 		   "available with %<-std=c++20%> or %<-std=gnu++20%>");
26556 	  return true;
26557 	}
26558       return false;
26559     }
26560   else if (TREE_CODE (type) == TYPENAME_TYPE)
26561     return false;
26562   else if (TREE_CODE (type) == DECLTYPE_TYPE)
26563     return false;
26564   else if (TREE_CODE (type) == NULLPTR_TYPE)
26565     return false;
26566   /* A bound template template parm could later be instantiated to have a valid
26567      nontype parm type via an alias template.  */
26568   else if (cxx_dialect >= cxx11
26569 	   && TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
26570     return false;
26571   else if (TREE_CODE (type) == COMPLEX_TYPE)
26572     /* Fall through.  */;
26573   else if (VOID_TYPE_P (type))
26574     /* Fall through.  */;
26575   else if (cxx_dialect >= cxx20)
26576     {
26577       if (dependent_type_p (type))
26578 	return false;
26579       if (!complete_type_or_maybe_complain (type, NULL_TREE, complain))
26580 	return true;
26581       if (structural_type_p (type))
26582 	return false;
26583       if (complain & tf_error)
26584 	{
26585 	  auto_diagnostic_group d;
26586 	  error ("%qT is not a valid type for a template non-type "
26587 		 "parameter because it is not structural", type);
26588 	  structural_type_p (type, true);
26589 	}
26590       return true;
26591     }
26592   else if (CLASS_TYPE_P (type))
26593     {
26594       if (complain & tf_error)
26595 	error ("non-type template parameters of class type only available "
26596 	       "with %<-std=c++20%> or %<-std=gnu++20%>");
26597       return true;
26598     }
26599 
26600   if (complain & tf_error)
26601     {
26602       if (type == error_mark_node)
26603 	inform (input_location, "invalid template non-type parameter");
26604       else
26605 	error ("%q#T is not a valid type for a template non-type parameter",
26606 	       type);
26607     }
26608   return true;
26609 }
26610 
26611 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
26612    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
26613 
26614 static bool
dependent_type_p_r(tree type)26615 dependent_type_p_r (tree type)
26616 {
26617   tree scope;
26618 
26619   /* [temp.dep.type]
26620 
26621      A type is dependent if it is:
26622 
26623      -- a template parameter. Template template parameters are types
26624 	for us (since TYPE_P holds true for them) so we handle
26625 	them here.  */
26626   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
26627       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
26628     return true;
26629   /* -- a qualified-id with a nested-name-specifier which contains a
26630 	class-name that names a dependent type or whose unqualified-id
26631 	names a dependent type.  */
26632   if (TREE_CODE (type) == TYPENAME_TYPE)
26633     return true;
26634 
26635   /* An alias template specialization can be dependent even if the
26636      resulting type is not.  */
26637   if (dependent_alias_template_spec_p (type, nt_transparent))
26638     return true;
26639 
26640   /* -- a cv-qualified type where the cv-unqualified type is
26641 	dependent.
26642      No code is necessary for this bullet; the code below handles
26643      cv-qualified types, and we don't want to strip aliases with
26644      TYPE_MAIN_VARIANT because of DR 1558.  */
26645   /* -- a compound type constructed from any dependent type.  */
26646   if (TYPE_PTRMEM_P (type))
26647     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
26648 	    || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
26649 					   (type)));
26650   else if (INDIRECT_TYPE_P (type))
26651     return dependent_type_p (TREE_TYPE (type));
26652   else if (FUNC_OR_METHOD_TYPE_P (type))
26653     {
26654       tree arg_type;
26655 
26656       if (dependent_type_p (TREE_TYPE (type)))
26657 	return true;
26658       for (arg_type = TYPE_ARG_TYPES (type);
26659 	   arg_type;
26660 	   arg_type = TREE_CHAIN (arg_type))
26661 	if (dependent_type_p (TREE_VALUE (arg_type)))
26662 	  return true;
26663       if (cxx_dialect >= cxx17)
26664 	/* A value-dependent noexcept-specifier makes the type dependent.  */
26665 	if (tree spec = TYPE_RAISES_EXCEPTIONS (type))
26666 	  if (tree noex = TREE_PURPOSE (spec))
26667 	    /* Treat DEFERRED_NOEXCEPT as non-dependent, since it doesn't
26668 	       affect overload resolution and treating it as dependent breaks
26669 	       things.  Same for an unparsed noexcept expression.  */
26670 	    if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
26671 		&& TREE_CODE (noex) != DEFERRED_PARSE
26672 		&& value_dependent_expression_p (noex))
26673 	      return true;
26674       return false;
26675     }
26676   /* -- an array type constructed from any dependent type or whose
26677 	size is specified by a constant expression that is
26678 	value-dependent.
26679 
26680         We checked for type- and value-dependence of the bounds in
26681         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
26682   if (TREE_CODE (type) == ARRAY_TYPE)
26683     {
26684       if (TYPE_DOMAIN (type)
26685 	  && dependent_type_p (TYPE_DOMAIN (type)))
26686 	return true;
26687       return dependent_type_p (TREE_TYPE (type));
26688     }
26689 
26690   /* -- a template-id in which either the template name is a template
26691      parameter ...  */
26692   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
26693     return true;
26694   /* ... or any of the template arguments is a dependent type or
26695 	an expression that is type-dependent or value-dependent.  */
26696   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
26697 	   && (any_dependent_template_arguments_p
26698 	       (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
26699     return true;
26700 
26701   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
26702      dependent; if the argument of the `typeof' expression is not
26703      type-dependent, then it should already been have resolved.  */
26704   if (TREE_CODE (type) == TYPEOF_TYPE
26705       || TREE_CODE (type) == DECLTYPE_TYPE
26706       || TREE_CODE (type) == UNDERLYING_TYPE)
26707     return true;
26708 
26709   /* A template argument pack is dependent if any of its packed
26710      arguments are.  */
26711   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
26712     {
26713       tree args = ARGUMENT_PACK_ARGS (type);
26714       int i, len = TREE_VEC_LENGTH (args);
26715       for (i = 0; i < len; ++i)
26716         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
26717           return true;
26718     }
26719 
26720   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
26721      be template parameters.  */
26722   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
26723     return true;
26724 
26725   if (any_dependent_type_attributes_p (TYPE_ATTRIBUTES (type)))
26726     return true;
26727 
26728   /* The standard does not specifically mention types that are local
26729      to template functions or local classes, but they should be
26730      considered dependent too.  For example:
26731 
26732        template <int I> void f() {
26733 	 enum E { a = I };
26734 	 S<sizeof (E)> s;
26735        }
26736 
26737      The size of `E' cannot be known until the value of `I' has been
26738      determined.  Therefore, `E' must be considered dependent.  */
26739   scope = TYPE_CONTEXT (type);
26740   if (scope && TYPE_P (scope))
26741     return dependent_type_p (scope);
26742   /* Don't use type_dependent_expression_p here, as it can lead
26743      to infinite recursion trying to determine whether a lambda
26744      nested in a lambda is dependent (c++/47687).  */
26745   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
26746 	   && DECL_LANG_SPECIFIC (scope)
26747 	   && DECL_TEMPLATE_INFO (scope)
26748 	   && (any_dependent_template_arguments_p
26749 	       (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
26750     return true;
26751 
26752   /* Other types are non-dependent.  */
26753   return false;
26754 }
26755 
26756 /* Returns TRUE if TYPE is dependent, in the sense of
26757    [temp.dep.type].  Note that a NULL type is considered dependent.  */
26758 
26759 bool
dependent_type_p(tree type)26760 dependent_type_p (tree type)
26761 {
26762   /* If there are no template parameters in scope, then there can't be
26763      any dependent types.  */
26764   if (!processing_template_decl)
26765     {
26766       /* If we are not processing a template, then nobody should be
26767 	 providing us with a dependent type.  */
26768       gcc_assert (type);
26769       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
26770       return false;
26771     }
26772 
26773   /* If the type is NULL, we have not computed a type for the entity
26774      in question; in that case, the type is dependent.  */
26775   if (!type)
26776     return true;
26777 
26778   /* Erroneous types can be considered non-dependent.  */
26779   if (type == error_mark_node)
26780     return false;
26781 
26782   /* If we have not already computed the appropriate value for TYPE,
26783      do so now.  */
26784   if (!TYPE_DEPENDENT_P_VALID (type))
26785     {
26786       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
26787       TYPE_DEPENDENT_P_VALID (type) = 1;
26788     }
26789 
26790   return TYPE_DEPENDENT_P (type);
26791 }
26792 
26793 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
26794    lookup.  In other words, a dependent type that is not the current
26795    instantiation.  */
26796 
26797 bool
dependent_scope_p(tree scope)26798 dependent_scope_p (tree scope)
26799 {
26800   return (scope && TYPE_P (scope) && dependent_type_p (scope)
26801 	  && !currently_open_class (scope));
26802 }
26803 
26804 /* T is a SCOPE_REF.  Return whether it represents a non-static member of
26805    an unknown base of 'this' (and is therefore instantiation-dependent).  */
26806 
26807 static bool
unknown_base_ref_p(tree t)26808 unknown_base_ref_p (tree t)
26809 {
26810   if (!current_class_ptr)
26811     return false;
26812 
26813   tree mem = TREE_OPERAND (t, 1);
26814   if (shared_member_p (mem))
26815     return false;
26816 
26817   tree cur = current_nonlambda_class_type ();
26818   if (!any_dependent_bases_p (cur))
26819     return false;
26820 
26821   tree ctx = TREE_OPERAND (t, 0);
26822   if (DERIVED_FROM_P (ctx, cur))
26823     return false;
26824 
26825   return true;
26826 }
26827 
26828 /* T is a SCOPE_REF; return whether we need to consider it
26829     instantiation-dependent so that we can check access at instantiation
26830     time even though we know which member it resolves to.  */
26831 
26832 static bool
instantiation_dependent_scope_ref_p(tree t)26833 instantiation_dependent_scope_ref_p (tree t)
26834 {
26835   if (DECL_P (TREE_OPERAND (t, 1))
26836       && CLASS_TYPE_P (TREE_OPERAND (t, 0))
26837       && !unknown_base_ref_p (t)
26838       && accessible_in_template_p (TREE_OPERAND (t, 0),
26839 				   TREE_OPERAND (t, 1)))
26840     return false;
26841   else
26842     return true;
26843 }
26844 
26845 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
26846    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
26847    expression.  */
26848 
26849 /* Note that this predicate is not appropriate for general expressions;
26850    only constant expressions (that satisfy potential_constant_expression)
26851    can be tested for value dependence.  */
26852 
26853 bool
value_dependent_expression_p(tree expression)26854 value_dependent_expression_p (tree expression)
26855 {
26856   if (!processing_template_decl || expression == NULL_TREE)
26857     return false;
26858 
26859   /* A type-dependent expression is also value-dependent.  */
26860   if (type_dependent_expression_p (expression))
26861     return true;
26862 
26863   switch (TREE_CODE (expression))
26864     {
26865     case BASELINK:
26866       /* A dependent member function of the current instantiation.  */
26867       return dependent_type_p (BINFO_TYPE (BASELINK_BINFO (expression)));
26868 
26869     case FUNCTION_DECL:
26870       /* A dependent member function of the current instantiation.  */
26871       if (DECL_CLASS_SCOPE_P (expression)
26872 	  && dependent_type_p (DECL_CONTEXT (expression)))
26873 	return true;
26874       break;
26875 
26876     case IDENTIFIER_NODE:
26877       /* A name that has not been looked up -- must be dependent.  */
26878       return true;
26879 
26880     case TEMPLATE_PARM_INDEX:
26881       /* A non-type template parm.  */
26882       return true;
26883 
26884     case CONST_DECL:
26885       /* A non-type template parm.  */
26886       if (DECL_TEMPLATE_PARM_P (expression))
26887 	return true;
26888       return value_dependent_expression_p (DECL_INITIAL (expression));
26889 
26890     case VAR_DECL:
26891        /* A constant with literal type and is initialized
26892 	  with an expression that is value-dependent.  */
26893       if (DECL_DEPENDENT_INIT_P (expression)
26894 	  /* FIXME cp_finish_decl doesn't fold reference initializers.  */
26895 	  || TYPE_REF_P (TREE_TYPE (expression)))
26896 	return true;
26897       if (DECL_HAS_VALUE_EXPR_P (expression))
26898 	{
26899 	  tree value_expr = DECL_VALUE_EXPR (expression);
26900 	  if (value_dependent_expression_p (value_expr)
26901 	      /* __PRETTY_FUNCTION__ inside a template function is dependent
26902 		 on the name of the function.  */
26903 	      || (DECL_PRETTY_FUNCTION_P (expression)
26904 		  /* It might be used in a template, but not a template
26905 		     function, in which case its DECL_VALUE_EXPR will be
26906 		     "top level".  */
26907 		  && value_expr == error_mark_node))
26908 	    return true;
26909 	}
26910       return false;
26911 
26912     case DYNAMIC_CAST_EXPR:
26913     case STATIC_CAST_EXPR:
26914     case CONST_CAST_EXPR:
26915     case REINTERPRET_CAST_EXPR:
26916     case CAST_EXPR:
26917     case IMPLICIT_CONV_EXPR:
26918       /* These expressions are value-dependent if the type to which
26919 	 the cast occurs is dependent or the expression being casted
26920 	 is value-dependent.  */
26921       {
26922 	tree type = TREE_TYPE (expression);
26923 
26924 	if (dependent_type_p (type))
26925 	  return true;
26926 
26927 	/* A functional cast has a list of operands.  */
26928 	expression = TREE_OPERAND (expression, 0);
26929 	if (!expression)
26930 	  {
26931 	    /* If there are no operands, it must be an expression such
26932 	       as "int()". This should not happen for aggregate types
26933 	       because it would form non-constant expressions.  */
26934 	    gcc_assert (cxx_dialect >= cxx11
26935 			|| INTEGRAL_OR_ENUMERATION_TYPE_P (type));
26936 
26937 	    return false;
26938 	  }
26939 
26940 	if (TREE_CODE (expression) == TREE_LIST)
26941 	  return any_value_dependent_elements_p (expression);
26942 
26943 	return value_dependent_expression_p (expression);
26944       }
26945 
26946     case SIZEOF_EXPR:
26947       if (SIZEOF_EXPR_TYPE_P (expression))
26948 	return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
26949       /* FALLTHRU */
26950     case ALIGNOF_EXPR:
26951     case TYPEID_EXPR:
26952       /* A `sizeof' expression is value-dependent if the operand is
26953 	 type-dependent or is a pack expansion.  */
26954       expression = TREE_OPERAND (expression, 0);
26955       if (PACK_EXPANSION_P (expression))
26956         return true;
26957       else if (TYPE_P (expression))
26958 	return dependent_type_p (expression);
26959       return instantiation_dependent_uneval_expression_p (expression);
26960 
26961     case AT_ENCODE_EXPR:
26962       /* An 'encode' expression is value-dependent if the operand is
26963 	 type-dependent.  */
26964       expression = TREE_OPERAND (expression, 0);
26965       return dependent_type_p (expression);
26966 
26967     case NOEXCEPT_EXPR:
26968       expression = TREE_OPERAND (expression, 0);
26969       return instantiation_dependent_uneval_expression_p (expression);
26970 
26971     case SCOPE_REF:
26972       /* All instantiation-dependent expressions should also be considered
26973 	 value-dependent.  */
26974       return instantiation_dependent_scope_ref_p (expression);
26975 
26976     case COMPONENT_REF:
26977       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
26978 	      || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
26979 
26980     case NONTYPE_ARGUMENT_PACK:
26981       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
26982          is value-dependent.  */
26983       {
26984         tree values = ARGUMENT_PACK_ARGS (expression);
26985         int i, len = TREE_VEC_LENGTH (values);
26986 
26987         for (i = 0; i < len; ++i)
26988           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
26989             return true;
26990 
26991         return false;
26992       }
26993 
26994     case TRAIT_EXPR:
26995       {
26996 	tree type2 = TRAIT_EXPR_TYPE2 (expression);
26997 
26998 	if (dependent_type_p (TRAIT_EXPR_TYPE1 (expression)))
26999 	  return true;
27000 
27001 	if (!type2)
27002 	  return false;
27003 
27004 	if (TREE_CODE (type2) != TREE_LIST)
27005 	  return dependent_type_p (type2);
27006 
27007 	for (; type2; type2 = TREE_CHAIN (type2))
27008 	  if (dependent_type_p (TREE_VALUE (type2)))
27009 	    return true;
27010 
27011 	return false;
27012       }
27013 
27014     case MODOP_EXPR:
27015       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
27016 	      || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
27017 
27018     case ARRAY_REF:
27019       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
27020 	      || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
27021 
27022     case ADDR_EXPR:
27023       {
27024 	tree op = TREE_OPERAND (expression, 0);
27025 	return (value_dependent_expression_p (op)
27026 		|| has_value_dependent_address (op));
27027       }
27028 
27029     case REQUIRES_EXPR:
27030       /* Treat all requires-expressions as value-dependent so
27031          we don't try to fold them.  */
27032       return true;
27033 
27034     case TYPE_REQ:
27035       return dependent_type_p (TREE_OPERAND (expression, 0));
27036 
27037     case CALL_EXPR:
27038       {
27039 	if (value_dependent_expression_p (CALL_EXPR_FN (expression)))
27040 	  return true;
27041 	tree fn = get_callee_fndecl (expression);
27042 	int i, nargs;
27043 	nargs = call_expr_nargs (expression);
27044 	for (i = 0; i < nargs; ++i)
27045 	  {
27046 	    tree op = CALL_EXPR_ARG (expression, i);
27047 	    /* In a call to a constexpr member function, look through the
27048 	       implicit ADDR_EXPR on the object argument so that it doesn't
27049 	       cause the call to be considered value-dependent.  We also
27050 	       look through it in potential_constant_expression.  */
27051 	    if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
27052 		&& DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
27053 		&& TREE_CODE (op) == ADDR_EXPR)
27054 	      op = TREE_OPERAND (op, 0);
27055 	    if (value_dependent_expression_p (op))
27056 	      return true;
27057 	  }
27058 	return false;
27059       }
27060 
27061     case TEMPLATE_ID_EXPR:
27062       return concept_definition_p (TREE_OPERAND (expression, 0));
27063 
27064     case CONSTRUCTOR:
27065       {
27066 	unsigned ix;
27067 	tree val;
27068 	if (dependent_type_p (TREE_TYPE (expression)))
27069 	  return true;
27070 	FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
27071 	  if (value_dependent_expression_p (val))
27072 	    return true;
27073 	return false;
27074       }
27075 
27076     case STMT_EXPR:
27077       /* Treat a GNU statement expression as dependent to avoid crashing
27078 	 under instantiate_non_dependent_expr; it can't be constant.  */
27079       return true;
27080 
27081     default:
27082       /* A constant expression is value-dependent if any subexpression is
27083 	 value-dependent.  */
27084       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
27085 	{
27086 	case tcc_reference:
27087 	case tcc_unary:
27088 	case tcc_comparison:
27089 	case tcc_binary:
27090 	case tcc_expression:
27091 	case tcc_vl_exp:
27092 	  {
27093 	    int i, len = cp_tree_operand_length (expression);
27094 
27095 	    for (i = 0; i < len; i++)
27096 	      {
27097 		tree t = TREE_OPERAND (expression, i);
27098 
27099 		/* In some cases, some of the operands may be missing.
27100 		   (For example, in the case of PREDECREMENT_EXPR, the
27101 		   amount to increment by may be missing.)  That doesn't
27102 		   make the expression dependent.  */
27103 		if (t && value_dependent_expression_p (t))
27104 		  return true;
27105 	      }
27106 	  }
27107 	  break;
27108 	default:
27109 	  break;
27110 	}
27111       break;
27112     }
27113 
27114   /* The expression is not value-dependent.  */
27115   return false;
27116 }
27117 
27118 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
27119    [temp.dep.expr].  Note that an expression with no type is
27120    considered dependent.  Other parts of the compiler arrange for an
27121    expression with type-dependent subexpressions to have no type, so
27122    this function doesn't have to be fully recursive.  */
27123 
27124 bool
type_dependent_expression_p(tree expression)27125 type_dependent_expression_p (tree expression)
27126 {
27127   if (!processing_template_decl)
27128     return false;
27129 
27130   if (expression == NULL_TREE || expression == error_mark_node)
27131     return false;
27132 
27133   STRIP_ANY_LOCATION_WRAPPER (expression);
27134 
27135   /* An unresolved name is always dependent.  */
27136   if (identifier_p (expression)
27137       || TREE_CODE (expression) == USING_DECL
27138       || TREE_CODE (expression) == WILDCARD_DECL)
27139     return true;
27140 
27141   /* A lambda-expression in template context is dependent.  dependent_type_p is
27142      true for a lambda in the scope of a class or function template, but that
27143      doesn't cover all template contexts, like a default template argument.  */
27144   if (TREE_CODE (expression) == LAMBDA_EXPR)
27145     return true;
27146 
27147   /* A fold expression is type-dependent. */
27148   if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
27149       || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
27150       || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
27151       || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
27152     return true;
27153 
27154   /* Some expression forms are never type-dependent.  */
27155   if (TREE_CODE (expression) == SIZEOF_EXPR
27156       || TREE_CODE (expression) == ALIGNOF_EXPR
27157       || TREE_CODE (expression) == AT_ENCODE_EXPR
27158       || TREE_CODE (expression) == NOEXCEPT_EXPR
27159       || TREE_CODE (expression) == TRAIT_EXPR
27160       || TREE_CODE (expression) == TYPEID_EXPR
27161       || TREE_CODE (expression) == DELETE_EXPR
27162       || TREE_CODE (expression) == VEC_DELETE_EXPR
27163       || TREE_CODE (expression) == THROW_EXPR
27164       || TREE_CODE (expression) == REQUIRES_EXPR)
27165     return false;
27166 
27167   /* The types of these expressions depends only on the type to which
27168      the cast occurs.  */
27169   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
27170       || TREE_CODE (expression) == STATIC_CAST_EXPR
27171       || TREE_CODE (expression) == CONST_CAST_EXPR
27172       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
27173       || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
27174       || TREE_CODE (expression) == CAST_EXPR)
27175     return dependent_type_p (TREE_TYPE (expression));
27176 
27177   /* The types of these expressions depends only on the type created
27178      by the expression.  */
27179   if (TREE_CODE (expression) == NEW_EXPR
27180       || TREE_CODE (expression) == VEC_NEW_EXPR)
27181     {
27182       /* For NEW_EXPR tree nodes created inside a template, either
27183 	 the object type itself or a TREE_LIST may appear as the
27184 	 operand 1.  */
27185       tree type = TREE_OPERAND (expression, 1);
27186       if (TREE_CODE (type) == TREE_LIST)
27187 	/* This is an array type.  We need to check array dimensions
27188 	   as well.  */
27189 	return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
27190 	       || value_dependent_expression_p
27191 		    (TREE_OPERAND (TREE_VALUE (type), 1));
27192       /* Array type whose dimension has to be deduced.  */
27193       else if (TREE_CODE (type) == ARRAY_TYPE
27194 	       && TREE_OPERAND (expression, 2) == NULL_TREE)
27195 	return true;
27196       else
27197 	return dependent_type_p (type);
27198     }
27199 
27200   if (TREE_CODE (expression) == SCOPE_REF)
27201     {
27202       tree scope = TREE_OPERAND (expression, 0);
27203       tree name = TREE_OPERAND (expression, 1);
27204 
27205       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
27206 	 contains an identifier associated by name lookup with one or more
27207 	 declarations declared with a dependent type, or...a
27208 	 nested-name-specifier or qualified-id that names a member of an
27209 	 unknown specialization.  */
27210       return (type_dependent_expression_p (name)
27211 	      || dependent_scope_p (scope));
27212     }
27213 
27214   if (TREE_CODE (expression) == TEMPLATE_DECL
27215       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
27216     return uses_outer_template_parms (expression);
27217 
27218   if (TREE_CODE (expression) == STMT_EXPR)
27219     expression = stmt_expr_value_expr (expression);
27220 
27221   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
27222     {
27223       tree elt;
27224       unsigned i;
27225 
27226       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
27227 	{
27228 	  if (type_dependent_expression_p (elt))
27229 	    return true;
27230 	}
27231       return false;
27232     }
27233 
27234   /* A static data member of the current instantiation with incomplete
27235      array type is type-dependent, as the definition and specializations
27236      can have different bounds.  */
27237   if (VAR_P (expression)
27238       && DECL_CLASS_SCOPE_P (expression)
27239       && dependent_type_p (DECL_CONTEXT (expression))
27240       && VAR_HAD_UNKNOWN_BOUND (expression))
27241     return true;
27242 
27243   /* An array of unknown bound depending on a variadic parameter, eg:
27244 
27245      template<typename... Args>
27246        void foo (Args... args)
27247        {
27248          int arr[] = { args... };
27249        }
27250 
27251      template<int... vals>
27252        void bar ()
27253        {
27254          int arr[] = { vals... };
27255        }
27256 
27257      If the array has no length and has an initializer, it must be that
27258      we couldn't determine its length in cp_complete_array_type because
27259      it is dependent.  */
27260   if (VAR_P (expression)
27261       && TREE_TYPE (expression) != NULL_TREE
27262       && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
27263       && !TYPE_DOMAIN (TREE_TYPE (expression))
27264       && DECL_INITIAL (expression))
27265    return true;
27266 
27267   /* A function or variable template-id is type-dependent if it has any
27268      dependent template arguments.  */
27269   if (VAR_OR_FUNCTION_DECL_P (expression)
27270       && DECL_LANG_SPECIFIC (expression)
27271       && DECL_TEMPLATE_INFO (expression))
27272     {
27273       /* Consider the innermost template arguments, since those are the ones
27274 	 that come from the template-id; the template arguments for the
27275 	 enclosing class do not make it type-dependent unless they are used in
27276 	 the type of the decl.  */
27277       if (instantiates_primary_template_p (expression)
27278 	  && (any_dependent_template_arguments_p
27279 	      (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
27280 	return true;
27281     }
27282 
27283   /* Otherwise, if the function decl isn't from a dependent scope, it can't be
27284      type-dependent.  Checking this is important for functions with auto return
27285      type, which looks like a dependent type.  */
27286   if (TREE_CODE (expression) == FUNCTION_DECL
27287       && !(DECL_CLASS_SCOPE_P (expression)
27288 	   && dependent_type_p (DECL_CONTEXT (expression)))
27289       && !(DECL_LANG_SPECIFIC (expression)
27290 	   && DECL_UNIQUE_FRIEND_P (expression)
27291 	   && (!DECL_FRIEND_CONTEXT (expression)
27292 	       || dependent_type_p (DECL_FRIEND_CONTEXT (expression))))
27293       && !DECL_LOCAL_DECL_P (expression))
27294     {
27295       gcc_assert (!dependent_type_p (TREE_TYPE (expression))
27296 		  || undeduced_auto_decl (expression));
27297       return false;
27298     }
27299 
27300   /* Always dependent, on the number of arguments if nothing else.  */
27301   if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
27302     return true;
27303 
27304   if (TREE_TYPE (expression) == unknown_type_node)
27305     {
27306       if (TREE_CODE (expression) == ADDR_EXPR)
27307 	return type_dependent_expression_p (TREE_OPERAND (expression, 0));
27308       if (TREE_CODE (expression) == COMPONENT_REF
27309 	  || TREE_CODE (expression) == OFFSET_REF)
27310 	{
27311 	  if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
27312 	    return true;
27313 	  expression = TREE_OPERAND (expression, 1);
27314 	  if (identifier_p (expression))
27315 	    return false;
27316 	}
27317       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
27318       if (TREE_CODE (expression) == SCOPE_REF)
27319 	return false;
27320 
27321       /* CO_AWAIT/YIELD_EXPR with unknown type is always dependent.  */
27322       if (TREE_CODE (expression) == CO_AWAIT_EXPR
27323 	  || TREE_CODE (expression) == CO_YIELD_EXPR)
27324 	return true;
27325 
27326       if (BASELINK_P (expression))
27327 	{
27328 	  if (BASELINK_OPTYPE (expression)
27329 	      && dependent_type_p (BASELINK_OPTYPE (expression)))
27330 	    return true;
27331 	  expression = BASELINK_FUNCTIONS (expression);
27332 	}
27333 
27334       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
27335 	{
27336 	  if (any_dependent_template_arguments_p
27337 	      (TREE_OPERAND (expression, 1)))
27338 	    return true;
27339 	  expression = TREE_OPERAND (expression, 0);
27340 	  if (identifier_p (expression))
27341 	    return true;
27342 	}
27343 
27344       gcc_assert (OVL_P (expression));
27345 
27346       for (lkp_iterator iter (expression); iter; ++iter)
27347 	if (type_dependent_expression_p (*iter))
27348 	  return true;
27349 
27350       return false;
27351     }
27352 
27353   /* The type of a non-type template parm declared with a placeholder type
27354      depends on the corresponding template argument, even though
27355      placeholders are not normally considered dependent.  */
27356   if (TREE_CODE (expression) == TEMPLATE_PARM_INDEX
27357       && is_auto (TREE_TYPE (expression)))
27358     return true;
27359 
27360   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
27361 
27362   /* Dependent type attributes might not have made it from the decl to
27363      the type yet.  */
27364   if (DECL_P (expression)
27365       && any_dependent_type_attributes_p (DECL_ATTRIBUTES (expression)))
27366     return true;
27367 
27368   return (dependent_type_p (TREE_TYPE (expression)));
27369 }
27370 
27371 /* [temp.dep.expr]/5: A class member access expression (5.2.5) is
27372    type-dependent if the expression refers to a member of the current
27373    instantiation and the type of the referenced member is dependent, or the
27374    class member access expression refers to a member of an unknown
27375    specialization.
27376 
27377    This function returns true if the OBJECT in such a class member access
27378    expression is of an unknown specialization.  */
27379 
27380 bool
type_dependent_object_expression_p(tree object)27381 type_dependent_object_expression_p (tree object)
27382 {
27383   /* An IDENTIFIER_NODE can sometimes have a TREE_TYPE, but it's still
27384      dependent.  */
27385   if (TREE_CODE (object) == IDENTIFIER_NODE)
27386     return true;
27387   tree scope = TREE_TYPE (object);
27388   return (!scope || dependent_scope_p (scope));
27389 }
27390 
27391 /* walk_tree callback function for instantiation_dependent_expression_p,
27392    below.  Returns non-zero if a dependent subexpression is found.  */
27393 
27394 static tree
instantiation_dependent_r(tree * tp,int * walk_subtrees,void *)27395 instantiation_dependent_r (tree *tp, int *walk_subtrees,
27396 			   void * /*data*/)
27397 {
27398   if (TYPE_P (*tp))
27399     {
27400       /* We don't have to worry about decltype currently because decltype
27401 	 of an instantiation-dependent expr is a dependent type.  This
27402 	 might change depending on the resolution of DR 1172.  */
27403       *walk_subtrees = false;
27404       return NULL_TREE;
27405     }
27406   enum tree_code code = TREE_CODE (*tp);
27407   switch (code)
27408     {
27409       /* Don't treat an argument list as dependent just because it has no
27410 	 TREE_TYPE.  */
27411     case TREE_LIST:
27412     case TREE_VEC:
27413     case NONTYPE_ARGUMENT_PACK:
27414       return NULL_TREE;
27415 
27416     case TEMPLATE_PARM_INDEX:
27417       if (dependent_type_p (TREE_TYPE (*tp)))
27418 	return *tp;
27419       if (TEMPLATE_PARM_PARAMETER_PACK (*tp))
27420 	return *tp;
27421       /* We'll check value-dependence separately.  */
27422       return NULL_TREE;
27423 
27424       /* Handle expressions with type operands.  */
27425     case SIZEOF_EXPR:
27426     case ALIGNOF_EXPR:
27427     case TYPEID_EXPR:
27428     case AT_ENCODE_EXPR:
27429       {
27430 	tree op = TREE_OPERAND (*tp, 0);
27431 	if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
27432 	  op = TREE_TYPE (op);
27433 	if (TYPE_P (op))
27434 	  {
27435 	    if (dependent_type_p (op))
27436 	      return *tp;
27437 	    else
27438 	      {
27439 		*walk_subtrees = false;
27440 		return NULL_TREE;
27441 	      }
27442 	  }
27443 	break;
27444       }
27445 
27446     case COMPONENT_REF:
27447       if (identifier_p (TREE_OPERAND (*tp, 1)))
27448 	/* In a template, finish_class_member_access_expr creates a
27449 	   COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
27450 	   type-dependent, so that we can check access control at
27451 	   instantiation time (PR 42277).  See also Core issue 1273.  */
27452 	return *tp;
27453       break;
27454 
27455     case SCOPE_REF:
27456       if (instantiation_dependent_scope_ref_p (*tp))
27457 	return *tp;
27458       else
27459 	break;
27460 
27461       /* Treat statement-expressions as dependent.  */
27462     case BIND_EXPR:
27463       return *tp;
27464 
27465       /* Treat requires-expressions as dependent. */
27466     case REQUIRES_EXPR:
27467       return *tp;
27468 
27469     case CALL_EXPR:
27470       /* Treat concept checks as dependent. */
27471       if (concept_check_p (*tp))
27472         return *tp;
27473       break;
27474 
27475     case TEMPLATE_ID_EXPR:
27476       /* Treat concept checks as dependent.  */
27477       if (concept_check_p (*tp))
27478 	return *tp;
27479       break;
27480 
27481     case CONSTRUCTOR:
27482       if (CONSTRUCTOR_IS_DEPENDENT (*tp))
27483 	return *tp;
27484       break;
27485 
27486     default:
27487       break;
27488     }
27489 
27490   if (type_dependent_expression_p (*tp))
27491     return *tp;
27492   else
27493     return NULL_TREE;
27494 }
27495 
27496 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
27497    sense defined by the ABI:
27498 
27499    "An expression is instantiation-dependent if it is type-dependent
27500    or value-dependent, or it has a subexpression that is type-dependent
27501    or value-dependent."
27502 
27503    Except don't actually check value-dependence for unevaluated expressions,
27504    because in sizeof(i) we don't care about the value of i.  Checking
27505    type-dependence will in turn check value-dependence of array bounds/template
27506    arguments as needed.  */
27507 
27508 bool
instantiation_dependent_uneval_expression_p(tree expression)27509 instantiation_dependent_uneval_expression_p (tree expression)
27510 {
27511   tree result;
27512 
27513   if (!processing_template_decl)
27514     return false;
27515 
27516   if (expression == error_mark_node)
27517     return false;
27518 
27519   result = cp_walk_tree_without_duplicates (&expression,
27520 					    instantiation_dependent_r, NULL);
27521   return result != NULL_TREE;
27522 }
27523 
27524 /* As above, but also check value-dependence of the expression as a whole.  */
27525 
27526 bool
instantiation_dependent_expression_p(tree expression)27527 instantiation_dependent_expression_p (tree expression)
27528 {
27529   return (instantiation_dependent_uneval_expression_p (expression)
27530 	  || (processing_template_decl
27531 	      && potential_constant_expression (expression)
27532 	      && value_dependent_expression_p (expression)));
27533 }
27534 
27535 /* Like type_dependent_expression_p, but it also works while not processing
27536    a template definition, i.e. during substitution or mangling.  */
27537 
27538 bool
type_dependent_expression_p_push(tree expr)27539 type_dependent_expression_p_push (tree expr)
27540 {
27541   bool b;
27542   ++processing_template_decl;
27543   b = type_dependent_expression_p (expr);
27544   --processing_template_decl;
27545   return b;
27546 }
27547 
27548 /* Returns TRUE if ARGS contains a type-dependent expression.  */
27549 
27550 bool
any_type_dependent_arguments_p(const vec<tree,va_gc> * args)27551 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
27552 {
27553   unsigned int i;
27554   tree arg;
27555 
27556   FOR_EACH_VEC_SAFE_ELT (args, i, arg)
27557     {
27558       if (type_dependent_expression_p (arg))
27559 	return true;
27560     }
27561   return false;
27562 }
27563 
27564 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
27565    expressions) contains any type-dependent expressions.  */
27566 
27567 bool
any_type_dependent_elements_p(const_tree list)27568 any_type_dependent_elements_p (const_tree list)
27569 {
27570   for (; list; list = TREE_CHAIN (list))
27571     if (type_dependent_expression_p (TREE_VALUE (list)))
27572       return true;
27573 
27574   return false;
27575 }
27576 
27577 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
27578    expressions) contains any value-dependent expressions.  */
27579 
27580 bool
any_value_dependent_elements_p(const_tree list)27581 any_value_dependent_elements_p (const_tree list)
27582 {
27583   for (; list; list = TREE_CHAIN (list))
27584     if (value_dependent_expression_p (TREE_VALUE (list)))
27585       return true;
27586 
27587   return false;
27588 }
27589 
27590 /* Returns TRUE if the ARG (a template argument) is dependent.  */
27591 
27592 bool
dependent_template_arg_p(tree arg)27593 dependent_template_arg_p (tree arg)
27594 {
27595   if (!processing_template_decl)
27596     return false;
27597 
27598   /* Assume a template argument that was wrongly written by the user
27599      is dependent. This is consistent with what
27600      any_dependent_template_arguments_p [that calls this function]
27601      does.  */
27602   if (!arg || arg == error_mark_node)
27603     return true;
27604 
27605   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
27606     arg = argument_pack_select_arg (arg);
27607 
27608   if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
27609     return true;
27610   if (TREE_CODE (arg) == TEMPLATE_DECL)
27611     {
27612       if (DECL_TEMPLATE_PARM_P (arg))
27613 	return true;
27614       /* A member template of a dependent class is not necessarily
27615 	 type-dependent, but it is a dependent template argument because it
27616 	 will be a member of an unknown specialization to that template.  */
27617       tree scope = CP_DECL_CONTEXT (arg);
27618       return TYPE_P (scope) && dependent_type_p (scope);
27619     }
27620   else if (ARGUMENT_PACK_P (arg))
27621     {
27622       tree args = ARGUMENT_PACK_ARGS (arg);
27623       int i, len = TREE_VEC_LENGTH (args);
27624       for (i = 0; i < len; ++i)
27625         {
27626           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
27627             return true;
27628         }
27629 
27630       return false;
27631     }
27632   else if (TYPE_P (arg))
27633     return dependent_type_p (arg);
27634   else
27635     return value_dependent_expression_p (arg);
27636 }
27637 
27638 /* Returns true if ARGS (a collection of template arguments) contains
27639    any types that require structural equality testing.  */
27640 
27641 bool
any_template_arguments_need_structural_equality_p(tree args)27642 any_template_arguments_need_structural_equality_p (tree args)
27643 {
27644   int i;
27645   int j;
27646 
27647   if (!args)
27648     return false;
27649   if (args == error_mark_node)
27650     return true;
27651 
27652   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
27653     {
27654       tree level = TMPL_ARGS_LEVEL (args, i + 1);
27655       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
27656 	{
27657 	  tree arg = TREE_VEC_ELT (level, j);
27658 	  tree packed_args = NULL_TREE;
27659 	  int k, len = 1;
27660 
27661 	  if (ARGUMENT_PACK_P (arg))
27662 	    {
27663 	      /* Look inside the argument pack.  */
27664 	      packed_args = ARGUMENT_PACK_ARGS (arg);
27665 	      len = TREE_VEC_LENGTH (packed_args);
27666 	    }
27667 
27668 	  for (k = 0; k < len; ++k)
27669 	    {
27670 	      if (packed_args)
27671 		arg = TREE_VEC_ELT (packed_args, k);
27672 
27673 	      if (error_operand_p (arg))
27674 		return true;
27675 	      else if (TREE_CODE (arg) == TEMPLATE_DECL)
27676 		continue;
27677 	      else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
27678 		return true;
27679 	      else if (!TYPE_P (arg) && TREE_TYPE (arg)
27680 		       && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
27681 		return true;
27682 	    }
27683 	}
27684     }
27685 
27686   return false;
27687 }
27688 
27689 /* Returns true if ARGS (a collection of template arguments) contains
27690    any dependent arguments.  */
27691 
27692 bool
any_dependent_template_arguments_p(const_tree args)27693 any_dependent_template_arguments_p (const_tree args)
27694 {
27695   int i;
27696   int j;
27697 
27698   if (!args)
27699     return false;
27700   if (args == error_mark_node)
27701     return true;
27702 
27703   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
27704     {
27705       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
27706       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
27707 	if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
27708 	  return true;
27709     }
27710 
27711   return false;
27712 }
27713 
27714 /* Returns true if ARGS contains any errors.  */
27715 
27716 bool
any_erroneous_template_args_p(const_tree args)27717 any_erroneous_template_args_p (const_tree args)
27718 {
27719   int i;
27720   int j;
27721 
27722   if (args == error_mark_node)
27723     return true;
27724 
27725   if (args && TREE_CODE (args) != TREE_VEC)
27726     {
27727       if (tree ti = get_template_info (args))
27728 	args = TI_ARGS (ti);
27729       else
27730 	args = NULL_TREE;
27731     }
27732 
27733   if (!args)
27734     return false;
27735 
27736   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
27737     {
27738       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
27739       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
27740 	if (error_operand_p (TREE_VEC_ELT (level, j)))
27741 	  return true;
27742     }
27743 
27744   return false;
27745 }
27746 
27747 /* Returns TRUE if the template TMPL is type-dependent.  */
27748 
27749 bool
dependent_template_p(tree tmpl)27750 dependent_template_p (tree tmpl)
27751 {
27752   if (TREE_CODE (tmpl) == OVERLOAD)
27753     {
27754       for (lkp_iterator iter (tmpl); iter; ++iter)
27755 	if (dependent_template_p (*iter))
27756 	  return true;
27757       return false;
27758     }
27759 
27760   /* Template template parameters are dependent.  */
27761   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
27762       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
27763     return true;
27764   /* So are names that have not been looked up.  */
27765   if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
27766     return true;
27767   return false;
27768 }
27769 
27770 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
27771 
27772 bool
dependent_template_id_p(tree tmpl,tree args)27773 dependent_template_id_p (tree tmpl, tree args)
27774 {
27775   return (dependent_template_p (tmpl)
27776 	  || any_dependent_template_arguments_p (args));
27777 }
27778 
27779 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
27780    are dependent.  */
27781 
27782 bool
dependent_omp_for_p(tree declv,tree initv,tree condv,tree incrv)27783 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
27784 {
27785   int i;
27786 
27787   if (!processing_template_decl)
27788     return false;
27789 
27790   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
27791     {
27792       tree decl = TREE_VEC_ELT (declv, i);
27793       tree init = TREE_VEC_ELT (initv, i);
27794       tree cond = TREE_VEC_ELT (condv, i);
27795       tree incr = TREE_VEC_ELT (incrv, i);
27796 
27797       if (type_dependent_expression_p (decl)
27798 	  || TREE_CODE (decl) == SCOPE_REF)
27799 	return true;
27800 
27801       if (init && type_dependent_expression_p (init))
27802 	return true;
27803 
27804       if (cond == global_namespace)
27805 	return true;
27806 
27807       if (type_dependent_expression_p (cond))
27808 	return true;
27809 
27810       if (COMPARISON_CLASS_P (cond)
27811 	  && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
27812 	      || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
27813 	return true;
27814 
27815       if (TREE_CODE (incr) == MODOP_EXPR)
27816 	{
27817 	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
27818 	      || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
27819 	    return true;
27820 	}
27821       else if (type_dependent_expression_p (incr))
27822 	return true;
27823       else if (TREE_CODE (incr) == MODIFY_EXPR)
27824 	{
27825 	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
27826 	    return true;
27827 	  else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
27828 	    {
27829 	      tree t = TREE_OPERAND (incr, 1);
27830 	      if (type_dependent_expression_p (TREE_OPERAND (t, 0))
27831 		  || type_dependent_expression_p (TREE_OPERAND (t, 1)))
27832 		return true;
27833 
27834 	      /* If this loop has a class iterator with != comparison
27835 		 with increment other than i++/++i/i--/--i, make sure the
27836 		 increment is constant.  */
27837 	      if (CLASS_TYPE_P (TREE_TYPE (decl))
27838 		  && TREE_CODE (cond) == NE_EXPR)
27839 		{
27840 		  if (TREE_OPERAND (t, 0) == decl)
27841 		    t = TREE_OPERAND (t, 1);
27842 		  else
27843 		    t = TREE_OPERAND (t, 0);
27844 		  if (TREE_CODE (t) != INTEGER_CST)
27845 		    return true;
27846 		}
27847 	    }
27848 	}
27849     }
27850 
27851   return false;
27852 }
27853 
27854 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
27855    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
27856    no such TYPE can be found.  Note that this function peers inside
27857    uninstantiated templates and therefore should be used only in
27858    extremely limited situations.  ONLY_CURRENT_P restricts this
27859    peering to the currently open classes hierarchy (which is required
27860    when comparing types).  */
27861 
27862 tree
resolve_typename_type(tree type,bool only_current_p)27863 resolve_typename_type (tree type, bool only_current_p)
27864 {
27865   tree scope;
27866   tree name;
27867   tree decl;
27868   int quals;
27869   tree pushed_scope;
27870   tree result;
27871 
27872   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
27873 
27874   scope = TYPE_CONTEXT (type);
27875   /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope.  */
27876   gcc_checking_assert (uses_template_parms (scope));
27877 
27878   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
27879      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of a
27880      TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL
27881      representing the typedef. In that case TYPE_IDENTIFIER (type) is
27882      not the non-qualified identifier of the TYPENAME_TYPE anymore.
27883      So by getting the TYPE_IDENTIFIER of the _main declaration_ of
27884      the TYPENAME_TYPE instead, we avoid messing up with a possible
27885      typedef variant case.  */
27886   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
27887 
27888   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
27889      it first before we can figure out what NAME refers to.  */
27890   if (TREE_CODE (scope) == TYPENAME_TYPE)
27891     {
27892       if (TYPENAME_IS_RESOLVING_P (scope))
27893 	/* Given a class template A with a dependent base with nested type C,
27894 	   typedef typename A::C::C C will land us here, as trying to resolve
27895 	   the initial A::C leads to the local C typedef, which leads back to
27896 	   A::C::C.  So we break the recursion now.  */
27897 	return type;
27898       else
27899 	scope = resolve_typename_type (scope, only_current_p);
27900     }
27901   /* If we don't know what SCOPE refers to, then we cannot resolve the
27902      TYPENAME_TYPE.  */
27903   if (!CLASS_TYPE_P (scope))
27904     return type;
27905   /* If this is a typedef, we don't want to look inside (c++/11987).  */
27906   if (typedef_variant_p (type))
27907     return type;
27908   /* If SCOPE isn't the template itself, it will not have a valid
27909      TYPE_FIELDS list.  */
27910   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
27911     /* scope is either the template itself or a compatible instantiation
27912        like X<T>, so look up the name in the original template.  */
27913     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
27914   /* If scope has no fields, it can't be a current instantiation.  Check this
27915      before currently_open_class to avoid infinite recursion (71515).  */
27916   if (!TYPE_FIELDS (scope))
27917     return type;
27918   /* If the SCOPE is not the current instantiation, there's no reason
27919      to look inside it.  */
27920   if (only_current_p && !currently_open_class (scope))
27921     return type;
27922   /* Enter the SCOPE so that name lookup will be resolved as if we
27923      were in the class definition.  In particular, SCOPE will no
27924      longer be considered a dependent type.  */
27925   pushed_scope = push_scope (scope);
27926   /* Look up the declaration.  */
27927   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
27928 			tf_warning_or_error);
27929 
27930   result = NULL_TREE;
27931 
27932   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
27933      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
27934   tree fullname = TYPENAME_TYPE_FULLNAME (type);
27935   if (!decl)
27936     /*nop*/;
27937   else if (identifier_p (fullname)
27938 	   && TREE_CODE (decl) == TYPE_DECL)
27939     {
27940       result = TREE_TYPE (decl);
27941       if (result == error_mark_node)
27942 	result = NULL_TREE;
27943     }
27944   else if (TREE_CODE (fullname) == TEMPLATE_ID_EXPR
27945 	   && DECL_CLASS_TEMPLATE_P (decl))
27946     {
27947       /* Obtain the template and the arguments.  */
27948       tree tmpl = TREE_OPERAND (fullname, 0);
27949       if (TREE_CODE (tmpl) == IDENTIFIER_NODE)
27950 	{
27951 	  /* We get here with a plain identifier because a previous tentative
27952 	     parse of the nested-name-specifier as part of a ptr-operator saw
27953 	     ::template X<A>.  The use of ::template is necessary in a
27954 	     ptr-operator, but wrong in a declarator-id.
27955 
27956 	     [temp.names]: In a qualified-id of a declarator-id, the keyword
27957 	     template shall not appear at the top level.  */
27958 	  pedwarn (cp_expr_loc_or_input_loc (fullname), OPT_Wpedantic,
27959 		   "keyword %<template%> not allowed in declarator-id");
27960 	  tmpl = decl;
27961 	}
27962       tree args = TREE_OPERAND (fullname, 1);
27963       /* Instantiate the template.  */
27964       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
27965 				      /*entering_scope=*/true,
27966 				      tf_error | tf_user);
27967       if (result == error_mark_node)
27968 	result = NULL_TREE;
27969     }
27970 
27971   /* Leave the SCOPE.  */
27972   if (pushed_scope)
27973     pop_scope (pushed_scope);
27974 
27975   /* If we failed to resolve it, return the original typename.  */
27976   if (!result)
27977     return type;
27978 
27979   /* If lookup found a typename type, resolve that too.  */
27980   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
27981     {
27982       /* Ill-formed programs can cause infinite recursion here, so we
27983 	 must catch that.  */
27984       TYPENAME_IS_RESOLVING_P (result) = 1;
27985       result = resolve_typename_type (result, only_current_p);
27986       TYPENAME_IS_RESOLVING_P (result) = 0;
27987     }
27988 
27989   /* Qualify the resulting type.  */
27990   quals = cp_type_quals (type);
27991   if (quals)
27992     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
27993 
27994   return result;
27995 }
27996 
27997 /* EXPR is an expression which is not type-dependent.  Return a proxy
27998    for EXPR that can be used to compute the types of larger
27999    expressions containing EXPR.  */
28000 
28001 tree
build_non_dependent_expr(tree expr)28002 build_non_dependent_expr (tree expr)
28003 {
28004   tree orig_expr = expr;
28005   tree inner_expr;
28006 
28007   /* When checking, try to get a constant value for all non-dependent
28008      expressions in order to expose bugs in *_dependent_expression_p
28009      and constexpr.  This can affect code generation, see PR70704, so
28010      only do this for -fchecking=2.  */
28011   if (flag_checking > 1
28012       && cxx_dialect >= cxx11
28013       /* Don't do this during nsdmi parsing as it can lead to
28014 	 unexpected recursive instantiations.  */
28015       && !parsing_nsdmi ()
28016       /* Don't do this during concept processing either and for
28017          the same reason.  */
28018       && !processing_constraint_expression_p ())
28019     fold_non_dependent_expr (expr, tf_none);
28020 
28021   STRIP_ANY_LOCATION_WRAPPER (expr);
28022 
28023   /* Preserve OVERLOADs; the functions must be available to resolve
28024      types.  */
28025   inner_expr = expr;
28026   if (TREE_CODE (inner_expr) == STMT_EXPR)
28027     inner_expr = stmt_expr_value_expr (inner_expr);
28028   if (TREE_CODE (inner_expr) == ADDR_EXPR)
28029     inner_expr = TREE_OPERAND (inner_expr, 0);
28030   if (TREE_CODE (inner_expr) == COMPONENT_REF)
28031     inner_expr = TREE_OPERAND (inner_expr, 1);
28032   if (is_overloaded_fn (inner_expr)
28033       || TREE_CODE (inner_expr) == OFFSET_REF)
28034     return orig_expr;
28035   /* There is no need to return a proxy for a variable or enumerator.  */
28036   if (VAR_P (expr) || TREE_CODE (expr) == CONST_DECL)
28037     return orig_expr;
28038   /* Preserve string constants; conversions from string constants to
28039      "char *" are allowed, even though normally a "const char *"
28040      cannot be used to initialize a "char *".  */
28041   if (TREE_CODE (expr) == STRING_CST)
28042     return orig_expr;
28043   /* Preserve void and arithmetic constants, as an optimization -- there is no
28044      reason to create a new node.  */
28045   if (TREE_CODE (expr) == VOID_CST
28046       || TREE_CODE (expr) == INTEGER_CST
28047       || TREE_CODE (expr) == REAL_CST)
28048     return orig_expr;
28049   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
28050      There is at least one place where we want to know that a
28051      particular expression is a throw-expression: when checking a ?:
28052      expression, there are special rules if the second or third
28053      argument is a throw-expression.  */
28054   if (TREE_CODE (expr) == THROW_EXPR)
28055     return orig_expr;
28056 
28057   /* Don't wrap an initializer list, we need to be able to look inside.  */
28058   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
28059     return orig_expr;
28060 
28061   /* Don't wrap a dummy object, we need to be able to test for it.  */
28062   if (is_dummy_object (expr))
28063     return orig_expr;
28064 
28065   if (TREE_CODE (expr) == COND_EXPR)
28066     return build3 (COND_EXPR,
28067 		   TREE_TYPE (expr),
28068 		   build_non_dependent_expr (TREE_OPERAND (expr, 0)),
28069 		   (TREE_OPERAND (expr, 1)
28070 		    ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
28071 		    : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
28072 		   build_non_dependent_expr (TREE_OPERAND (expr, 2)));
28073   if (TREE_CODE (expr) == COMPOUND_EXPR
28074       && !COMPOUND_EXPR_OVERLOADED (expr))
28075     return build2 (COMPOUND_EXPR,
28076 		   TREE_TYPE (expr),
28077 		   TREE_OPERAND (expr, 0),
28078 		   build_non_dependent_expr (TREE_OPERAND (expr, 1)));
28079 
28080   /* If the type is unknown, it can't really be non-dependent */
28081   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
28082 
28083   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
28084   return build1_loc (EXPR_LOCATION (orig_expr), NON_DEPENDENT_EXPR,
28085 		     TREE_TYPE (expr), expr);
28086 }
28087 
28088 /* ARGS is a vector of expressions as arguments to a function call.
28089    Replace the arguments with equivalent non-dependent expressions.
28090    This modifies ARGS in place.  */
28091 
28092 void
make_args_non_dependent(vec<tree,va_gc> * args)28093 make_args_non_dependent (vec<tree, va_gc> *args)
28094 {
28095   unsigned int ix;
28096   tree arg;
28097 
28098   FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
28099     {
28100       tree newarg = build_non_dependent_expr (arg);
28101       if (newarg != arg)
28102 	(*args)[ix] = newarg;
28103     }
28104 }
28105 
28106 /* Returns a type which represents 'auto' or 'decltype(auto)'.  We use a
28107    TEMPLATE_TYPE_PARM with a level one deeper than the actual template
28108    parms.  If set_canonical is true, we set TYPE_CANONICAL on it.  */
28109 
28110 static tree
make_auto_1(tree name,bool set_canonical)28111 make_auto_1 (tree name, bool set_canonical)
28112 {
28113   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
28114   TYPE_NAME (au) = build_decl (input_location, TYPE_DECL, name, au);
28115   TYPE_STUB_DECL (au) = TYPE_NAME (au);
28116   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
28117     (0, processing_template_decl + 1, processing_template_decl + 1,
28118      TYPE_NAME (au), NULL_TREE);
28119   if (set_canonical)
28120     TYPE_CANONICAL (au) = canonical_type_parameter (au);
28121   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
28122   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
28123   if (name == decltype_auto_identifier)
28124     AUTO_IS_DECLTYPE (au) = true;
28125 
28126   return au;
28127 }
28128 
28129 tree
make_decltype_auto(void)28130 make_decltype_auto (void)
28131 {
28132   return make_auto_1 (decltype_auto_identifier, true);
28133 }
28134 
28135 tree
make_auto(void)28136 make_auto (void)
28137 {
28138   return make_auto_1 (auto_identifier, true);
28139 }
28140 
28141 /* Return a C++17 deduction placeholder for class template TMPL.  */
28142 
28143 tree
make_template_placeholder(tree tmpl)28144 make_template_placeholder (tree tmpl)
28145 {
28146   tree t = make_auto_1 (auto_identifier, false);
28147   CLASS_PLACEHOLDER_TEMPLATE (t) = tmpl;
28148   /* Our canonical type depends on the placeholder.  */
28149   TYPE_CANONICAL (t) = canonical_type_parameter (t);
28150   return t;
28151 }
28152 
28153 /* True iff T is a C++17 class template deduction placeholder.  */
28154 
28155 bool
template_placeholder_p(tree t)28156 template_placeholder_p (tree t)
28157 {
28158   return is_auto (t) && CLASS_PLACEHOLDER_TEMPLATE (t);
28159 }
28160 
28161 /* Make a "constrained auto" type-specifier. This is an auto or
28162   decltype(auto) type with constraints that must be associated after
28163   deduction.  The constraint is formed from the given concept CON
28164   and its optional sequence of template arguments ARGS.
28165 
28166   TYPE must be the result of make_auto_type or make_decltype_auto_type. */
28167 
28168 static tree
make_constrained_placeholder_type(tree type,tree con,tree args)28169 make_constrained_placeholder_type (tree type, tree con, tree args)
28170 {
28171   /* Build the constraint. */
28172   tree tmpl = DECL_TI_TEMPLATE (con);
28173   tree expr = tmpl;
28174   if (TREE_CODE (con) == FUNCTION_DECL)
28175     expr = ovl_make (tmpl);
28176   ++processing_template_decl;
28177   expr = build_concept_check (expr, type, args, tf_warning_or_error);
28178   --processing_template_decl;
28179 
28180   PLACEHOLDER_TYPE_CONSTRAINTS_INFO (type)
28181     = build_tree_list (current_template_parms, expr);
28182 
28183   /* Our canonical type depends on the constraint.  */
28184   TYPE_CANONICAL (type) = canonical_type_parameter (type);
28185 
28186   /* Attach the constraint to the type declaration. */
28187   return TYPE_NAME (type);
28188 }
28189 
28190 /* Make a "constrained auto" type-specifier.  */
28191 
28192 tree
make_constrained_auto(tree con,tree args)28193 make_constrained_auto (tree con, tree args)
28194 {
28195   tree type = make_auto_1 (auto_identifier, false);
28196   return make_constrained_placeholder_type (type, con, args);
28197 }
28198 
28199 /* Make a "constrained decltype(auto)" type-specifier.  */
28200 
28201 tree
make_constrained_decltype_auto(tree con,tree args)28202 make_constrained_decltype_auto (tree con, tree args)
28203 {
28204   tree type = make_auto_1 (decltype_auto_identifier, false);
28205   return make_constrained_placeholder_type (type, con, args);
28206 }
28207 
28208 /* Returns true if the placeholder type constraint T has any dependent
28209    (explicit) template arguments.  */
28210 
28211 static bool
placeholder_type_constraint_dependent_p(tree t)28212 placeholder_type_constraint_dependent_p (tree t)
28213 {
28214   tree id = unpack_concept_check (t);
28215   tree args = TREE_OPERAND (id, 1);
28216   tree first = TREE_VEC_ELT (args, 0);
28217   if (ARGUMENT_PACK_P (first))
28218     {
28219       args = expand_template_argument_pack (args);
28220       first = TREE_VEC_ELT (args, 0);
28221     }
28222   gcc_checking_assert (TREE_CODE (first) == WILDCARD_DECL
28223 		       || is_auto (first));
28224   for (int i = 1; i < TREE_VEC_LENGTH (args); ++i)
28225     if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
28226       return true;
28227   return false;
28228 }
28229 
28230 /* Build and return a concept definition. Like other templates, the
28231    CONCEPT_DECL node is wrapped by a TEMPLATE_DECL.  This returns the
28232    the TEMPLATE_DECL. */
28233 
28234 tree
finish_concept_definition(cp_expr id,tree init)28235 finish_concept_definition (cp_expr id, tree init)
28236 {
28237   gcc_assert (identifier_p (id));
28238   gcc_assert (processing_template_decl);
28239 
28240   location_t loc = id.get_location();
28241 
28242   /* A concept-definition shall not have associated constraints.  */
28243   if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
28244     {
28245       error_at (loc, "a concept cannot be constrained");
28246       TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
28247     }
28248 
28249   /* A concept-definition shall appear in namespace scope.  Templates
28250      aren't allowed in block scope, so we only need to check for class
28251      scope.  */
28252   if (TYPE_P (current_scope()) || !DECL_NAMESPACE_SCOPE_P (current_scope ()))
28253     {
28254       error_at (loc, "concept %qE not in namespace scope", *id);
28255       return error_mark_node;
28256     }
28257 
28258   /* Initially build the concept declaration; its type is bool.  */
28259   tree decl = build_lang_decl_loc (loc, CONCEPT_DECL, *id, boolean_type_node);
28260   DECL_CONTEXT (decl) = current_scope ();
28261   DECL_INITIAL (decl) = init;
28262 
28263   set_originating_module (decl, false);
28264 
28265   /* Push the enclosing template.  */
28266   return push_template_decl (decl);
28267 }
28268 
28269 /* Given type ARG, return std::initializer_list<ARG>.  */
28270 
28271 static tree
listify(tree arg)28272 listify (tree arg)
28273 {
28274   tree std_init_list = get_namespace_binding (std_node, init_list_identifier);
28275 
28276   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
28277     {
28278       gcc_rich_location richloc (input_location);
28279       maybe_add_include_fixit (&richloc, "<initializer_list>", false);
28280       error_at (&richloc,
28281 		"deducing from brace-enclosed initializer list"
28282 		" requires %<#include <initializer_list>%>");
28283 
28284       return error_mark_node;
28285     }
28286   tree argvec = make_tree_vec (1);
28287   TREE_VEC_ELT (argvec, 0) = arg;
28288 
28289   return lookup_template_class (std_init_list, argvec, NULL_TREE,
28290 				NULL_TREE, 0, tf_warning_or_error);
28291 }
28292 
28293 /* Replace auto in TYPE with std::initializer_list<auto>.  */
28294 
28295 static tree
listify_autos(tree type,tree auto_node)28296 listify_autos (tree type, tree auto_node)
28297 {
28298   tree init_auto = listify (strip_top_quals (auto_node));
28299   tree argvec = make_tree_vec (1);
28300   TREE_VEC_ELT (argvec, 0) = init_auto;
28301   if (processing_template_decl)
28302     argvec = add_to_template_args (current_template_args (), argvec);
28303   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
28304 }
28305 
28306 /* Hash traits for hashing possibly constrained 'auto'
28307    TEMPLATE_TYPE_PARMs for use by do_auto_deduction.  */
28308 
28309 struct auto_hash : default_hash_traits<tree>
28310 {
28311   static inline hashval_t hash (tree);
28312   static inline bool equal (tree, tree);
28313 };
28314 
28315 /* Hash the 'auto' T.  */
28316 
28317 inline hashval_t
hash(tree t)28318 auto_hash::hash (tree t)
28319 {
28320   if (tree c = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (t)))
28321     /* Matching constrained-type-specifiers denote the same template
28322        parameter, so hash the constraint.  */
28323     return hash_placeholder_constraint (c);
28324   else
28325     /* But unconstrained autos are all separate, so just hash the pointer.  */
28326     return iterative_hash_object (t, 0);
28327 }
28328 
28329 /* Compare two 'auto's.  */
28330 
28331 inline bool
equal(tree t1,tree t2)28332 auto_hash::equal (tree t1, tree t2)
28333 {
28334   if (t1 == t2)
28335     return true;
28336 
28337   tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
28338   tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
28339 
28340   /* Two unconstrained autos are distinct.  */
28341   if (!c1 || !c2)
28342     return false;
28343 
28344   return equivalent_placeholder_constraints (c1, c2);
28345 }
28346 
28347 /* for_each_template_parm callback for extract_autos: if t is a (possibly
28348    constrained) auto, add it to the vector.  */
28349 
28350 static int
extract_autos_r(tree t,void * data)28351 extract_autos_r (tree t, void *data)
28352 {
28353   hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
28354   if (is_auto (t))
28355     {
28356       /* All the autos were built with index 0; fix that up now.  */
28357       tree *p = hash.find_slot (t, INSERT);
28358       unsigned idx;
28359       if (*p)
28360 	/* If this is a repeated constrained-type-specifier, use the index we
28361 	   chose before.  */
28362 	idx = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (*p));
28363       else
28364 	{
28365 	  /* Otherwise this is new, so use the current count.  */
28366 	  *p = t;
28367 	  idx = hash.elements () - 1;
28368 	}
28369       TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (t)) = idx;
28370     }
28371 
28372   /* Always keep walking.  */
28373   return 0;
28374 }
28375 
28376 /* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
28377    says they can appear anywhere in the type.  */
28378 
28379 static tree
extract_autos(tree type)28380 extract_autos (tree type)
28381 {
28382   hash_set<tree> visited;
28383   hash_table<auto_hash> hash (2);
28384 
28385   for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
28386 
28387   tree tree_vec = make_tree_vec (hash.elements());
28388   for (hash_table<auto_hash>::iterator iter = hash.begin();
28389        iter != hash.end(); ++iter)
28390     {
28391       tree elt = *iter;
28392       unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
28393       TREE_VEC_ELT (tree_vec, i)
28394 	= build_tree_list (NULL_TREE, TYPE_NAME (elt));
28395     }
28396 
28397   return tree_vec;
28398 }
28399 
28400 /* The stem for deduction guide names.  */
28401 const char *const dguide_base = "__dguide_";
28402 
28403 /* Return the name for a deduction guide for class template TMPL.  */
28404 
28405 tree
dguide_name(tree tmpl)28406 dguide_name (tree tmpl)
28407 {
28408   tree type = (TYPE_P (tmpl) ? tmpl : TREE_TYPE (tmpl));
28409   tree tname = TYPE_IDENTIFIER (type);
28410   char *buf = (char *) alloca (1 + strlen (dguide_base)
28411 			       + IDENTIFIER_LENGTH (tname));
28412   memcpy (buf, dguide_base, strlen (dguide_base));
28413   memcpy (buf + strlen (dguide_base), IDENTIFIER_POINTER (tname),
28414 	  IDENTIFIER_LENGTH (tname) + 1);
28415   tree dname = get_identifier (buf);
28416   TREE_TYPE (dname) = type;
28417   return dname;
28418 }
28419 
28420 /* True if NAME is the name of a deduction guide.  */
28421 
28422 bool
dguide_name_p(tree name)28423 dguide_name_p (tree name)
28424 {
28425   return (TREE_CODE (name) == IDENTIFIER_NODE
28426 	  && TREE_TYPE (name)
28427 	  && !strncmp (IDENTIFIER_POINTER (name), dguide_base,
28428 		       strlen (dguide_base)));
28429 }
28430 
28431 /* True if FN is a deduction guide.  */
28432 
28433 bool
deduction_guide_p(const_tree fn)28434 deduction_guide_p (const_tree fn)
28435 {
28436   if (DECL_P (fn))
28437     if (tree name = DECL_NAME (fn))
28438       return dguide_name_p (name);
28439   return false;
28440 }
28441 
28442 /* True if FN is the copy deduction guide, i.e. A(A)->A.  */
28443 
28444 bool
copy_guide_p(const_tree fn)28445 copy_guide_p (const_tree fn)
28446 {
28447   gcc_assert (deduction_guide_p (fn));
28448   if (!DECL_ARTIFICIAL (fn))
28449     return false;
28450   tree parms = FUNCTION_FIRST_USER_PARMTYPE (DECL_TI_TEMPLATE (fn));
28451   return (TREE_CHAIN (parms) == void_list_node
28452 	  && same_type_p (TREE_VALUE (parms), TREE_TYPE (DECL_NAME (fn))));
28453 }
28454 
28455 /* True if FN is a guide generated from a constructor template.  */
28456 
28457 bool
template_guide_p(const_tree fn)28458 template_guide_p (const_tree fn)
28459 {
28460   gcc_assert (deduction_guide_p (fn));
28461   if (!DECL_ARTIFICIAL (fn))
28462     return false;
28463   tree tmpl = DECL_TI_TEMPLATE (fn);
28464   if (tree org = DECL_ABSTRACT_ORIGIN (tmpl))
28465     return PRIMARY_TEMPLATE_P (org);
28466   return false;
28467 }
28468 
28469 /* True if FN is an aggregate initialization guide or the copy deduction
28470    guide.  */
28471 
28472 bool
builtin_guide_p(const_tree fn)28473 builtin_guide_p (const_tree fn)
28474 {
28475   if (!deduction_guide_p (fn))
28476     return false;
28477   if (!DECL_ARTIFICIAL (fn))
28478     /* Explicitly declared.  */
28479     return false;
28480   if (DECL_ABSTRACT_ORIGIN (fn))
28481     /* Derived from a constructor.  */
28482     return false;
28483   return true;
28484 }
28485 
28486 /* OLDDECL is a _DECL for a template parameter.  Return a similar parameter at
28487    LEVEL:INDEX, using tsubst_args and complain for substitution into non-type
28488    template parameter types.  Note that the handling of template template
28489    parameters relies on current_template_parms being set appropriately for the
28490    new template.  */
28491 
28492 static tree
rewrite_template_parm(tree olddecl,unsigned index,unsigned level,tree tsubst_args,tsubst_flags_t complain)28493 rewrite_template_parm (tree olddecl, unsigned index, unsigned level,
28494 		       tree tsubst_args, tsubst_flags_t complain)
28495 {
28496   if (olddecl == error_mark_node)
28497     return error_mark_node;
28498 
28499   tree oldidx = get_template_parm_index (olddecl);
28500 
28501   tree newtype;
28502   if (TREE_CODE (olddecl) == TYPE_DECL
28503       || TREE_CODE (olddecl) == TEMPLATE_DECL)
28504     {
28505       tree oldtype = TREE_TYPE (olddecl);
28506       newtype = cxx_make_type (TREE_CODE (oldtype));
28507       TYPE_MAIN_VARIANT (newtype) = newtype;
28508       if (TREE_CODE (oldtype) == TEMPLATE_TYPE_PARM)
28509 	TEMPLATE_TYPE_PARM_FOR_CLASS (newtype)
28510 	  = TEMPLATE_TYPE_PARM_FOR_CLASS (oldtype);
28511     }
28512   else
28513     {
28514       newtype = TREE_TYPE (olddecl);
28515       if (type_uses_auto (newtype))
28516 	{
28517 	  // Substitute once to fix references to other template parameters.
28518 	  newtype = tsubst (newtype, tsubst_args,
28519 			    complain|tf_partial, NULL_TREE);
28520 	  // Now substitute again to reduce the level of the auto.
28521 	  newtype = tsubst (newtype, current_template_args (),
28522 			    complain, NULL_TREE);
28523 	}
28524       else
28525 	newtype = tsubst (newtype, tsubst_args,
28526 			  complain, NULL_TREE);
28527     }
28528 
28529   tree newdecl
28530     = build_decl (DECL_SOURCE_LOCATION (olddecl), TREE_CODE (olddecl),
28531 		  DECL_NAME (olddecl), newtype);
28532   SET_DECL_TEMPLATE_PARM_P (newdecl);
28533 
28534   tree newidx;
28535   if (TREE_CODE (olddecl) == TYPE_DECL
28536       || TREE_CODE (olddecl) == TEMPLATE_DECL)
28537     {
28538       newidx = TEMPLATE_TYPE_PARM_INDEX (newtype)
28539 	= build_template_parm_index (index, level, level,
28540 				     newdecl, newtype);
28541       TEMPLATE_PARM_PARAMETER_PACK (newidx)
28542 	= TEMPLATE_PARM_PARAMETER_PACK (oldidx);
28543       TYPE_STUB_DECL (newtype) = TYPE_NAME (newtype) = newdecl;
28544       if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (olddecl)))
28545 	SET_TYPE_STRUCTURAL_EQUALITY (newtype);
28546       else
28547 	TYPE_CANONICAL (newtype) = canonical_type_parameter (newtype);
28548 
28549       if (TREE_CODE (olddecl) == TEMPLATE_DECL)
28550 	{
28551 	  DECL_TEMPLATE_RESULT (newdecl)
28552 	    = build_decl (DECL_SOURCE_LOCATION (olddecl), TYPE_DECL,
28553 			  DECL_NAME (olddecl), newtype);
28554 	  DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (newdecl)) = true;
28555 	  // First create a copy (ttargs) of tsubst_args with an
28556 	  // additional level for the template template parameter's own
28557 	  // template parameters (ttparms).
28558 	  tree ttparms = (INNERMOST_TEMPLATE_PARMS
28559 			  (DECL_TEMPLATE_PARMS (olddecl)));
28560 	  const int depth = TMPL_ARGS_DEPTH (tsubst_args);
28561 	  tree ttargs = make_tree_vec (depth + 1);
28562 	  for (int i = 0; i < depth; ++i)
28563 	    TREE_VEC_ELT (ttargs, i) = TREE_VEC_ELT (tsubst_args, i);
28564 	  TREE_VEC_ELT (ttargs, depth)
28565 	    = template_parms_level_to_args (ttparms);
28566 	  // Substitute ttargs into ttparms to fix references to
28567 	  // other template parameters.
28568 	  ttparms = tsubst_template_parms_level (ttparms, ttargs,
28569 						 complain|tf_partial);
28570 	  // Now substitute again with args based on tparms, to reduce
28571 	  // the level of the ttparms.
28572 	  ttargs = current_template_args ();
28573 	  ttparms = tsubst_template_parms_level (ttparms, ttargs,
28574 						 complain);
28575 	  // Finally, tack the adjusted parms onto tparms.
28576 	  ttparms = tree_cons (size_int (depth), ttparms,
28577 			       current_template_parms);
28578 	  DECL_TEMPLATE_PARMS (newdecl) = ttparms;
28579 	}
28580     }
28581   else
28582     {
28583       tree oldconst = TEMPLATE_PARM_DECL (oldidx);
28584       tree newconst
28585 	= build_decl (DECL_SOURCE_LOCATION (oldconst),
28586 		      TREE_CODE (oldconst),
28587 		      DECL_NAME (oldconst), newtype);
28588       TREE_CONSTANT (newconst) = TREE_CONSTANT (newdecl)
28589 	= TREE_READONLY (newconst) = TREE_READONLY (newdecl) = true;
28590       SET_DECL_TEMPLATE_PARM_P (newconst);
28591       newidx = build_template_parm_index (index, level, level,
28592 					  newconst, newtype);
28593       TEMPLATE_PARM_PARAMETER_PACK (newidx)
28594 	= TEMPLATE_PARM_PARAMETER_PACK (oldidx);
28595       DECL_INITIAL (newdecl) = DECL_INITIAL (newconst) = newidx;
28596     }
28597 
28598   return newdecl;
28599 }
28600 
28601 /* As rewrite_template_parm, but for the whole TREE_LIST representing a
28602    template parameter.  */
28603 
28604 static tree
rewrite_tparm_list(tree oldelt,unsigned index,unsigned level,tree targs,unsigned targs_index,tsubst_flags_t complain)28605 rewrite_tparm_list (tree oldelt, unsigned index, unsigned level,
28606 		    tree targs, unsigned targs_index, tsubst_flags_t complain)
28607 {
28608   tree olddecl = TREE_VALUE (oldelt);
28609   tree newdecl = rewrite_template_parm (olddecl, index, level,
28610 					targs, complain);
28611   if (newdecl == error_mark_node)
28612     return error_mark_node;
28613   tree newdef = tsubst_template_arg (TREE_PURPOSE (oldelt),
28614 				     targs, complain, NULL_TREE);
28615   tree list = build_tree_list (newdef, newdecl);
28616   TEMPLATE_PARM_CONSTRAINTS (list)
28617     = tsubst_constraint_info (TEMPLATE_PARM_CONSTRAINTS (oldelt),
28618 			      targs, complain, NULL_TREE);
28619   int depth = TMPL_ARGS_DEPTH (targs);
28620   TMPL_ARG (targs, depth, targs_index) = template_parm_to_arg (list);
28621   return list;
28622 }
28623 
28624 /* Returns a C++17 class deduction guide template based on the constructor
28625    CTOR.  As a special case, CTOR can be a RECORD_TYPE for an implicit default
28626    guide, REFERENCE_TYPE for an implicit copy/move guide, or TREE_LIST for an
28627    aggregate initialization guide.  OUTER_ARGS are the template arguments
28628    for the enclosing scope of the class.  */
28629 
28630 static tree
build_deduction_guide(tree type,tree ctor,tree outer_args,tsubst_flags_t complain)28631 build_deduction_guide (tree type, tree ctor, tree outer_args, tsubst_flags_t complain)
28632 {
28633   tree tparms, targs, fparms, fargs, ci;
28634   bool memtmpl = false;
28635   bool explicit_p;
28636   location_t loc;
28637   tree fn_tmpl = NULL_TREE;
28638 
28639   if (outer_args)
28640     {
28641       ++processing_template_decl;
28642       type = tsubst (type, outer_args, complain, CLASSTYPE_TI_TEMPLATE (type));
28643       --processing_template_decl;
28644     }
28645 
28646   if (!DECL_DECLARES_FUNCTION_P (ctor))
28647     {
28648       if (TYPE_P (ctor))
28649 	{
28650 	  bool copy_p = TYPE_REF_P (ctor);
28651 	  if (copy_p)
28652 	    fparms = tree_cons (NULL_TREE, type, void_list_node);
28653 	  else
28654 	    fparms = void_list_node;
28655 	}
28656       else if (TREE_CODE (ctor) == TREE_LIST)
28657 	fparms = ctor;
28658       else
28659 	gcc_unreachable ();
28660 
28661       tree ctmpl = CLASSTYPE_TI_TEMPLATE (type);
28662       tparms = DECL_TEMPLATE_PARMS (ctmpl);
28663       targs = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
28664       ci = NULL_TREE;
28665       fargs = NULL_TREE;
28666       loc = DECL_SOURCE_LOCATION (ctmpl);
28667       explicit_p = false;
28668     }
28669   else
28670     {
28671       ++processing_template_decl;
28672       bool ok = true;
28673 
28674       fn_tmpl
28675 	= (TREE_CODE (ctor) == TEMPLATE_DECL ? ctor
28676 	   : DECL_TI_TEMPLATE (ctor));
28677       if (outer_args)
28678 	fn_tmpl = tsubst (fn_tmpl, outer_args, complain, ctor);
28679       ctor = DECL_TEMPLATE_RESULT (fn_tmpl);
28680 
28681       tparms = DECL_TEMPLATE_PARMS (fn_tmpl);
28682       /* If type is a member class template, DECL_TI_ARGS (ctor) will have
28683 	 fully specialized args for the enclosing class.  Strip those off, as
28684 	 the deduction guide won't have those template parameters.  */
28685       targs = get_innermost_template_args (DECL_TI_ARGS (ctor),
28686 						TMPL_PARMS_DEPTH (tparms));
28687       /* Discard the 'this' parameter.  */
28688       fparms = FUNCTION_ARG_CHAIN (ctor);
28689       fargs = TREE_CHAIN (DECL_ARGUMENTS (ctor));
28690       ci = get_constraints (ctor);
28691       loc = DECL_SOURCE_LOCATION (ctor);
28692       explicit_p = DECL_NONCONVERTING_P (ctor);
28693 
28694       if (PRIMARY_TEMPLATE_P (fn_tmpl))
28695 	{
28696 	  memtmpl = true;
28697 
28698 	  /* For a member template constructor, we need to flatten the two
28699 	     template parameter lists into one, and then adjust the function
28700 	     signature accordingly.  This gets...complicated.  */
28701 	  tree save_parms = current_template_parms;
28702 
28703 	  /* For a member template we should have two levels of parms/args, one
28704 	     for the class and one for the constructor.  We stripped
28705 	     specialized args for further enclosing classes above.  */
28706 	  const int depth = 2;
28707 	  gcc_assert (TMPL_ARGS_DEPTH (targs) == depth);
28708 
28709 	  /* Template args for translating references to the two-level template
28710 	     parameters into references to the one-level template parameters we
28711 	     are creating.  */
28712 	  tree tsubst_args = copy_node (targs);
28713 	  TMPL_ARGS_LEVEL (tsubst_args, depth)
28714 	    = copy_node (TMPL_ARGS_LEVEL (tsubst_args, depth));
28715 
28716 	  /* Template parms for the constructor template.  */
28717 	  tree ftparms = TREE_VALUE (tparms);
28718 	  unsigned flen = TREE_VEC_LENGTH (ftparms);
28719 	  /* Template parms for the class template.  */
28720 	  tparms = TREE_CHAIN (tparms);
28721 	  tree ctparms = TREE_VALUE (tparms);
28722 	  unsigned clen = TREE_VEC_LENGTH (ctparms);
28723 	  /* Template parms for the deduction guide start as a copy of the
28724 	     template parms for the class.  We set current_template_parms for
28725 	     lookup_template_class_1.  */
28726 	  current_template_parms = tparms = copy_node (tparms);
28727 	  tree new_vec = TREE_VALUE (tparms) = make_tree_vec (flen + clen);
28728 	  for (unsigned i = 0; i < clen; ++i)
28729 	    TREE_VEC_ELT (new_vec, i) = TREE_VEC_ELT (ctparms, i);
28730 
28731 	  /* Now we need to rewrite the constructor parms to append them to the
28732 	     class parms.  */
28733 	  for (unsigned i = 0; i < flen; ++i)
28734 	    {
28735 	      unsigned index = i + clen;
28736 	      unsigned level = 1;
28737 	      tree oldelt = TREE_VEC_ELT (ftparms, i);
28738 	      tree newelt
28739 		= rewrite_tparm_list (oldelt, index, level,
28740 				      tsubst_args, i, complain);
28741 	      if (newelt == error_mark_node)
28742 		ok = false;
28743 	      TREE_VEC_ELT (new_vec, index) = newelt;
28744 	    }
28745 
28746 	  /* Now we have a final set of template parms to substitute into the
28747 	     function signature.  */
28748 	  targs = template_parms_to_args (tparms);
28749 	  fparms = tsubst_arg_types (fparms, tsubst_args, NULL_TREE,
28750 				     complain, ctor);
28751 	  if (fparms == error_mark_node)
28752 	    ok = false;
28753 	  if (ci)
28754 	    {
28755 	      if (outer_args)
28756 		/* FIXME: We'd like to avoid substituting outer template
28757 		   arguments into the constraint ahead of time, but the
28758 		   construction of tsubst_args assumes that outer arguments
28759 		   are already substituted in.  */
28760 		ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
28761 	      ci = tsubst_constraint_info (ci, tsubst_args, complain, ctor);
28762 	    }
28763 
28764 	  /* Parms are to have DECL_CHAIN tsubsted, which would be skipped if
28765 	     cp_unevaluated_operand.  */
28766 	  cp_evaluated ev;
28767 	  fargs = tsubst (fargs, tsubst_args, complain, ctor);
28768 	  current_template_parms = save_parms;
28769 	}
28770       else
28771 	{
28772 	  /* Substitute in the same arguments to rewrite class members into
28773 	     references to members of an unknown specialization.  */
28774 	  cp_evaluated ev;
28775 	  fparms = tsubst_arg_types (fparms, targs, NULL_TREE, complain, ctor);
28776 	  fargs = tsubst (fargs, targs, complain, ctor);
28777 	  if (ci)
28778 	    {
28779 	      if (outer_args)
28780 		/* FIXME: As above.  */
28781 		ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
28782 	      ci = tsubst_constraint_info (ci, targs, complain, ctor);
28783 	    }
28784 	}
28785 
28786       --processing_template_decl;
28787       if (!ok)
28788 	return error_mark_node;
28789     }
28790 
28791   if (!memtmpl)
28792     {
28793       /* Copy the parms so we can set DECL_PRIMARY_TEMPLATE.  */
28794       tparms = copy_node (tparms);
28795       INNERMOST_TEMPLATE_PARMS (tparms)
28796 	= copy_node (INNERMOST_TEMPLATE_PARMS (tparms));
28797     }
28798 
28799   tree fntype = build_function_type (type, fparms);
28800   tree ded_fn = build_lang_decl_loc (loc,
28801 				     FUNCTION_DECL,
28802 				     dguide_name (type), fntype);
28803   DECL_ARGUMENTS (ded_fn) = fargs;
28804   DECL_ARTIFICIAL (ded_fn) = true;
28805   DECL_NONCONVERTING_P (ded_fn) = explicit_p;
28806   tree ded_tmpl = build_template_decl (ded_fn, tparms, /*member*/false);
28807   DECL_ARTIFICIAL (ded_tmpl) = true;
28808   DECL_TEMPLATE_INFO (ded_fn) = build_template_info (ded_tmpl, targs);
28809   DECL_PRIMARY_TEMPLATE (ded_tmpl) = ded_tmpl;
28810   if (DECL_P (ctor))
28811     DECL_ABSTRACT_ORIGIN (ded_tmpl) = fn_tmpl;
28812   if (ci)
28813     set_constraints (ded_tmpl, ci);
28814 
28815   return ded_tmpl;
28816 }
28817 
28818 /* Add to LIST the member types for the reshaped initializer CTOR.  */
28819 
28820 static tree
28821 collect_ctor_idx_types (tree ctor, tree list, tree elt = NULL_TREE)
28822 {
28823   vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (ctor);
28824   tree idx, val; unsigned i;
FOR_EACH_CONSTRUCTOR_ELT(v,i,idx,val)28825   FOR_EACH_CONSTRUCTOR_ELT (v, i, idx, val)
28826     {
28827       tree ftype = elt ? elt : TREE_TYPE (idx);
28828       if (BRACE_ENCLOSED_INITIALIZER_P (val)
28829 	  && CONSTRUCTOR_NELTS (val)
28830 	  /* As in reshape_init_r, a non-aggregate or array-of-dependent-bound
28831 	     type gets a single initializer.  */
28832 	  && CP_AGGREGATE_TYPE_P (ftype)
28833 	  && !(TREE_CODE (ftype) == ARRAY_TYPE
28834 	       && uses_template_parms (TYPE_DOMAIN (ftype))))
28835 	{
28836 	  tree subelt = NULL_TREE;
28837 	  if (TREE_CODE (ftype) == ARRAY_TYPE)
28838 	    subelt = TREE_TYPE (ftype);
28839 	  list = collect_ctor_idx_types (val, list, subelt);
28840 	  continue;
28841 	}
28842       tree arg = NULL_TREE;
28843       if (i == v->length() - 1
28844 	  && PACK_EXPANSION_P (ftype))
28845 	/* Give the trailing pack expansion parameter a default argument to
28846 	   match aggregate initialization behavior, even if we deduce the
28847 	   length of the pack separately to more than we have initializers. */
28848 	arg = build_constructor (init_list_type_node, NULL);
28849       /* if ei is of array type and xi is a braced-init-list or string literal,
28850 	 Ti is an rvalue reference to the declared type of ei */
28851       STRIP_ANY_LOCATION_WRAPPER (val);
28852       if (TREE_CODE (ftype) == ARRAY_TYPE
28853 	  && (BRACE_ENCLOSED_INITIALIZER_P (val)
28854 	      || TREE_CODE (val) == STRING_CST))
28855 	{
28856 	  if (TREE_CODE (val) == STRING_CST)
28857 	    ftype = cp_build_qualified_type
28858 	      (ftype, cp_type_quals (ftype) | TYPE_QUAL_CONST);
28859 	  ftype = (cp_build_reference_type
28860 		   (ftype, BRACE_ENCLOSED_INITIALIZER_P (val)));
28861 	}
28862       list = tree_cons (arg, ftype, list);
28863     }
28864 
28865   return list;
28866 }
28867 
28868 /* Return whether ETYPE is, or is derived from, a specialization of TMPL.  */
28869 
28870 static bool
is_spec_or_derived(tree etype,tree tmpl)28871 is_spec_or_derived (tree etype, tree tmpl)
28872 {
28873   if (!etype || !CLASS_TYPE_P (etype))
28874     return false;
28875 
28876   etype = cv_unqualified (etype);
28877   tree type = TREE_TYPE (tmpl);
28878   tree tparms = (INNERMOST_TEMPLATE_PARMS
28879 		 (DECL_TEMPLATE_PARMS (tmpl)));
28880   tree targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
28881   int err = unify (tparms, targs, type, etype,
28882 		   UNIFY_ALLOW_DERIVED, /*explain*/false);
28883   ggc_free (targs);
28884   return !err;
28885 }
28886 
28887 static tree alias_ctad_tweaks (tree, tree);
28888 
28889 /* Return a C++20 aggregate deduction candidate for TYPE initialized from
28890    INIT.  */
28891 
28892 static tree
maybe_aggr_guide(tree tmpl,tree init,vec<tree,va_gc> * args)28893 maybe_aggr_guide (tree tmpl, tree init, vec<tree,va_gc> *args)
28894 {
28895   if (cxx_dialect < cxx20)
28896     return NULL_TREE;
28897 
28898   if (init == NULL_TREE)
28899     return NULL_TREE;
28900 
28901   if (DECL_ALIAS_TEMPLATE_P (tmpl))
28902     {
28903       tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
28904       tree tinfo = get_template_info (under);
28905       if (tree guide = maybe_aggr_guide (TI_TEMPLATE (tinfo), init, args))
28906 	return alias_ctad_tweaks (tmpl, guide);
28907       return NULL_TREE;
28908     }
28909 
28910   /* We might be creating a guide for a class member template, e.g.,
28911 
28912        template<typename U> struct A {
28913 	 template<typename T> struct B { T t; };
28914        };
28915 
28916      At this point, A will have been instantiated.  Below, we need to
28917      use both A<U>::B<T> (TEMPLATE_TYPE) and A<int>::B<T> (TYPE) types.  */
28918   const bool member_template_p
28919     = (DECL_TEMPLATE_INFO (tmpl)
28920        && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (tmpl)));
28921   tree type = TREE_TYPE (tmpl);
28922   tree template_type = (member_template_p
28923 			? TREE_TYPE (DECL_TI_TEMPLATE (tmpl))
28924 			: type);
28925   if (!CP_AGGREGATE_TYPE_P (template_type))
28926     return NULL_TREE;
28927 
28928   /* No aggregate candidate for copy-initialization.  */
28929   if (args->length() == 1)
28930     {
28931       tree val = (*args)[0];
28932       if (is_spec_or_derived (TREE_TYPE (val), tmpl))
28933 	return NULL_TREE;
28934     }
28935 
28936   /* If we encounter a problem, we just won't add the candidate.  */
28937   tsubst_flags_t complain = tf_none;
28938 
28939   tree parms = NULL_TREE;
28940   if (BRACE_ENCLOSED_INITIALIZER_P (init))
28941     {
28942       init = reshape_init (template_type, init, complain);
28943       if (init == error_mark_node)
28944 	return NULL_TREE;
28945       parms = collect_ctor_idx_types (init, parms);
28946       /* If we're creating a deduction guide for a member class template,
28947 	 we've used the original template pattern type for the reshape_init
28948 	 above; this is done because we want PARMS to be a template parameter
28949 	 type, something that can be deduced when used as a function template
28950 	 parameter.  At this point the outer class template has already been
28951 	 partially instantiated (we deferred the deduction until the enclosing
28952 	 scope is non-dependent).  Therefore we have to partially instantiate
28953 	 PARMS, so that its template level is properly reduced and we don't get
28954 	 mismatches when deducing types using the guide with PARMS.  */
28955       if (member_template_p)
28956 	parms = tsubst (parms, DECL_TI_ARGS (tmpl), complain, init);
28957     }
28958   else if (TREE_CODE (init) == TREE_LIST)
28959     {
28960       int len = list_length (init);
28961       for (tree field = TYPE_FIELDS (type);
28962 	   len;
28963 	   --len, field = DECL_CHAIN (field))
28964 	{
28965 	  field = next_initializable_field (field);
28966 	  if (!field)
28967 	    return NULL_TREE;
28968 	  tree ftype = finish_decltype_type (field, true, complain);
28969 	  parms = tree_cons (NULL_TREE, ftype, parms);
28970 	}
28971     }
28972   else
28973     /* Aggregate initialization doesn't apply to an initializer expression.  */
28974     return NULL_TREE;
28975 
28976   if (parms)
28977     {
28978       tree last = parms;
28979       parms = nreverse (parms);
28980       TREE_CHAIN (last) = void_list_node;
28981       tree guide = build_deduction_guide (type, parms, NULL_TREE, complain);
28982       return guide;
28983     }
28984 
28985   return NULL_TREE;
28986 }
28987 
28988 /* UGUIDES are the deduction guides for the underlying template of alias
28989    template TMPL; adjust them to be deduction guides for TMPL.  */
28990 
28991 static tree
alias_ctad_tweaks(tree tmpl,tree uguides)28992 alias_ctad_tweaks (tree tmpl, tree uguides)
28993 {
28994   /* [over.match.class.deduct]: When resolving a placeholder for a deduced
28995      class type (9.2.8.2) where the template-name names an alias template A,
28996      the defining-type-id of A must be of the form
28997 
28998      typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
28999 
29000      as specified in 9.2.8.2. The guides of A are the set of functions or
29001      function templates formed as follows. For each function or function
29002      template f in the guides of the template named by the simple-template-id
29003      of the defining-type-id, the template arguments of the return type of f
29004      are deduced from the defining-type-id of A according to the process in
29005      13.10.2.5 with the exception that deduction does not fail if not all
29006      template arguments are deduced. Let g denote the result of substituting
29007      these deductions into f. If substitution succeeds, form a function or
29008      function template f' with the following properties and add it to the set
29009      of guides of A:
29010 
29011      * The function type of f' is the function type of g.
29012 
29013      * If f is a function template, f' is a function template whose template
29014      parameter list consists of all the template parameters of A (including
29015      their default template arguments) that appear in the above deductions or
29016      (recursively) in their default template arguments, followed by the
29017      template parameters of f that were not deduced (including their default
29018      template arguments), otherwise f' is not a function template.
29019 
29020      * The associated constraints (13.5.2) are the conjunction of the
29021      associated constraints of g and a constraint that is satisfied if and only
29022      if the arguments of A are deducible (see below) from the return type.
29023 
29024      * If f is a copy deduction candidate (12.4.1.8), then f' is considered to
29025      be so as well.
29026 
29027      * If f was generated from a deduction-guide (12.4.1.8), then f' is
29028      considered to be so as well.
29029 
29030      * The explicit-specifier of f' is the explicit-specifier of g (if
29031      any).  */
29032 
29033   /* This implementation differs from the above in two significant ways:
29034 
29035      1) We include all template parameters of A, not just some.
29036      2) The added constraint is same_type instead of deducible.
29037 
29038      I believe that while it's probably possible to construct a testcase that
29039      behaves differently with this simplification, it should have the same
29040      effect for real uses.  Including all template parameters means that we
29041      deduce all parameters of A when resolving the call, so when we're in the
29042      constraint we don't need to deduce them again, we can just check whether
29043      the deduction produced the desired result.  */
29044 
29045   tsubst_flags_t complain = tf_warning_or_error;
29046   tree atype = TREE_TYPE (tmpl);
29047   tree aguides = NULL_TREE;
29048   tree atparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
29049   unsigned natparms = TREE_VEC_LENGTH (atparms);
29050   tree utype = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
29051   for (ovl_iterator iter (uguides); iter; ++iter)
29052     {
29053       tree f = *iter;
29054       tree in_decl = f;
29055       location_t loc = DECL_SOURCE_LOCATION (f);
29056       tree ret = TREE_TYPE (TREE_TYPE (f));
29057       tree fprime = f;
29058       if (TREE_CODE (f) == TEMPLATE_DECL)
29059 	{
29060 	  processing_template_decl_sentinel ptds (/*reset*/false);
29061 	  ++processing_template_decl;
29062 
29063 	  /* Deduce template arguments for f from the type-id of A.  */
29064 	  tree ftparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (f));
29065 	  unsigned len = TREE_VEC_LENGTH (ftparms);
29066 	  tree targs = make_tree_vec (len);
29067 	  int err = unify (ftparms, targs, ret, utype, UNIFY_ALLOW_NONE, false);
29068 	  if (err)
29069 	    continue;
29070 
29071 	  /* The number of parms for f' is the number of parms for A plus
29072 	     non-deduced parms of f.  */
29073 	  unsigned ndlen = 0;
29074 	  unsigned j;
29075 	  for (unsigned i = 0; i < len; ++i)
29076 	    if (TREE_VEC_ELT (targs, i) == NULL_TREE)
29077 	      ++ndlen;
29078 	  tree gtparms = make_tree_vec (natparms + ndlen);
29079 
29080 	  /* First copy over the parms of A.  */
29081 	  for (j = 0; j < natparms; ++j)
29082 	    TREE_VEC_ELT (gtparms, j) = TREE_VEC_ELT (atparms, j);
29083 	  /* Now rewrite the non-deduced parms of f.  */
29084 	  for (unsigned i = 0; ndlen && i < len; ++i)
29085 	    if (TREE_VEC_ELT (targs, i) == NULL_TREE)
29086 	      {
29087 		--ndlen;
29088 		unsigned index = j++;
29089 		unsigned level = 1;
29090 		tree oldlist = TREE_VEC_ELT (ftparms, i);
29091 		tree list = rewrite_tparm_list (oldlist, index, level,
29092 						targs, i, complain);
29093 		TREE_VEC_ELT (gtparms, index) = list;
29094 	      }
29095 	  gtparms = build_tree_list (size_one_node, gtparms);
29096 
29097 	  /* Substitute the deduced arguments plus the rewritten template
29098 	     parameters into f to get g.  This covers the type, copyness,
29099 	     guideness, and explicit-specifier.  */
29100 	  tree g;
29101 	    {
29102 	      /* Parms are to have DECL_CHAIN tsubsted, which would be skipped
29103 		 if cp_unevaluated_operand.  */
29104 	      cp_evaluated ev;
29105 	      g = tsubst_decl (DECL_TEMPLATE_RESULT (f), targs, complain);
29106 	    }
29107 	  if (g == error_mark_node)
29108 	    continue;
29109 	  DECL_USE_TEMPLATE (g) = 0;
29110 	  fprime = build_template_decl (g, gtparms, false);
29111 	  DECL_TEMPLATE_RESULT (fprime) = g;
29112 	  TREE_TYPE (fprime) = TREE_TYPE (g);
29113 	  tree gtargs = template_parms_to_args (gtparms);
29114 	  DECL_TEMPLATE_INFO (g) = build_template_info (fprime, gtargs);
29115 	  DECL_PRIMARY_TEMPLATE (fprime) = fprime;
29116 
29117 	  /* Substitute the associated constraints.  */
29118 	  tree ci = get_constraints (f);
29119 	  if (ci)
29120 	    ci = tsubst_constraint_info (ci, targs, complain, in_decl);
29121 	  if (ci == error_mark_node)
29122 	    continue;
29123 
29124 	  /* Add a constraint that the return type matches the instantiation of
29125 	     A with the same template arguments.  */
29126 	  ret = TREE_TYPE (TREE_TYPE (fprime));
29127 	  if (!same_type_p (atype, ret)
29128 	      /* FIXME this should mean they don't compare as equivalent.  */
29129 	      || dependent_alias_template_spec_p (atype, nt_opaque))
29130 	    {
29131 	      tree same = finish_trait_expr (loc, CPTK_IS_SAME_AS, atype, ret);
29132 	      ci = append_constraint (ci, same);
29133 	    }
29134 
29135 	  if (ci)
29136 	    {
29137 	      remove_constraints (fprime);
29138 	      set_constraints (fprime, ci);
29139 	    }
29140 	}
29141       else
29142 	{
29143 	  /* For a non-template deduction guide, if the arguments of A aren't
29144 	     deducible from the return type, don't add the candidate.  */
29145 	  tree targs = make_tree_vec (natparms);
29146 	  int err = unify (atparms, targs, utype, ret, UNIFY_ALLOW_NONE, false);
29147 	  for (unsigned i = 0; !err && i < natparms; ++i)
29148 	    if (TREE_VEC_ELT (targs, i) == NULL_TREE)
29149 	      err = true;
29150 	  if (err)
29151 	    continue;
29152 	}
29153 
29154       aguides = lookup_add (fprime, aguides);
29155     }
29156 
29157   return aguides;
29158 }
29159 
29160 /* Return artificial deduction guides built from the constructors of class
29161    template TMPL.  */
29162 
29163 static tree
ctor_deduction_guides_for(tree tmpl,tsubst_flags_t complain)29164 ctor_deduction_guides_for (tree tmpl, tsubst_flags_t complain)
29165 {
29166   tree type = TREE_TYPE (tmpl);
29167   tree outer_args = NULL_TREE;
29168   if (DECL_CLASS_SCOPE_P (tmpl)
29169       && CLASSTYPE_TEMPLATE_INSTANTIATION (DECL_CONTEXT (tmpl)))
29170     {
29171       outer_args = CLASSTYPE_TI_ARGS (DECL_CONTEXT (tmpl));
29172       type = TREE_TYPE (most_general_template (tmpl));
29173     }
29174 
29175   tree cands = NULL_TREE;
29176 
29177   for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (type)); iter; ++iter)
29178     {
29179       /* Skip inherited constructors.  */
29180       if (iter.using_p ())
29181 	continue;
29182 
29183       tree guide = build_deduction_guide (type, *iter, outer_args, complain);
29184       cands = lookup_add (guide, cands);
29185     }
29186 
29187   /* Add implicit default constructor deduction guide.  */
29188   if (!TYPE_HAS_USER_CONSTRUCTOR (type))
29189     {
29190       tree guide = build_deduction_guide (type, type, outer_args,
29191 					  complain);
29192       cands = lookup_add (guide, cands);
29193     }
29194 
29195   /* Add copy guide.  */
29196   {
29197     tree gtype = build_reference_type (type);
29198     tree guide = build_deduction_guide (type, gtype, outer_args,
29199 					complain);
29200     cands = lookup_add (guide, cands);
29201   }
29202 
29203   return cands;
29204 }
29205 
29206 static GTY((deletable)) hash_map<tree, tree_pair_p> *dguide_cache;
29207 
29208 /* Return the non-aggregate deduction guides for deducible template TMPL.  The
29209    aggregate candidate is added separately because it depends on the
29210    initializer.  Set ANY_DGUIDES_P if we find a non-implicit deduction
29211    guide.  */
29212 
29213 static tree
deduction_guides_for(tree tmpl,bool & any_dguides_p,tsubst_flags_t complain)29214 deduction_guides_for (tree tmpl, bool &any_dguides_p, tsubst_flags_t complain)
29215 {
29216   tree guides = NULL_TREE;
29217   if (DECL_ALIAS_TEMPLATE_P (tmpl))
29218     {
29219       tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
29220       tree tinfo = get_template_info (under);
29221       guides = deduction_guides_for (TI_TEMPLATE (tinfo), any_dguides_p,
29222 				     complain);
29223     }
29224   else
29225     {
29226       guides = lookup_qualified_name (CP_DECL_CONTEXT (tmpl),
29227 				      dguide_name (tmpl),
29228 				      LOOK_want::NORMAL, /*complain*/false);
29229       if (guides == error_mark_node)
29230 	guides = NULL_TREE;
29231       else
29232 	any_dguides_p = true;
29233     }
29234 
29235   /* Cache the deduction guides for a template.  We also remember the result of
29236      lookup, and rebuild everything if it changes; should be very rare.  */
29237   tree_pair_p cache = NULL;
29238   if (tree_pair_p &r
29239       = hash_map_safe_get_or_insert<hm_ggc> (dguide_cache, tmpl))
29240     {
29241       cache = r;
29242       if (cache->purpose == guides)
29243 	return cache->value;
29244     }
29245   else
29246     {
29247       r = cache = ggc_cleared_alloc<tree_pair_s> ();
29248       cache->purpose = guides;
29249     }
29250 
29251   tree cands = NULL_TREE;
29252   if (DECL_ALIAS_TEMPLATE_P (tmpl))
29253     cands = alias_ctad_tweaks (tmpl, guides);
29254   else
29255     {
29256       cands = ctor_deduction_guides_for (tmpl, complain);
29257       for (ovl_iterator it (guides); it; ++it)
29258 	cands = lookup_add (*it, cands);
29259     }
29260 
29261   cache->value = cands;
29262   return cands;
29263 }
29264 
29265 /* Return whether TMPL is a (class template argument-) deducible template.  */
29266 
29267 bool
ctad_template_p(tree tmpl)29268 ctad_template_p (tree tmpl)
29269 {
29270   /* A deducible template is either a class template or is an alias template
29271      whose defining-type-id is of the form
29272 
29273       typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
29274 
29275      where the nested-name-specifier (if any) is non-dependent and the
29276      template-name of the simple-template-id names a deducible template.  */
29277 
29278   if (DECL_CLASS_TEMPLATE_P (tmpl)
29279       || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
29280     return true;
29281   if (!DECL_ALIAS_TEMPLATE_P (tmpl))
29282     return false;
29283   tree orig = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
29284   if (tree tinfo = get_template_info (orig))
29285     return ctad_template_p (TI_TEMPLATE (tinfo));
29286   return false;
29287 }
29288 
29289 /* Deduce template arguments for the class template placeholder PTYPE for
29290    template TMPL based on the initializer INIT, and return the resulting
29291    type.  */
29292 
29293 static tree
do_class_deduction(tree ptype,tree tmpl,tree init,int flags,tsubst_flags_t complain)29294 do_class_deduction (tree ptype, tree tmpl, tree init,
29295 		    int flags, tsubst_flags_t complain)
29296 {
29297   /* We should have handled this in the caller.  */
29298   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
29299     return ptype;
29300 
29301   /* Wait until the enclosing scope is non-dependent.  */
29302   if (DECL_CLASS_SCOPE_P (tmpl)
29303       && dependent_type_p (DECL_CONTEXT (tmpl)))
29304     return ptype;
29305 
29306   /* Initializing one placeholder from another.  */
29307   if (init
29308       && (TREE_CODE (init) == TEMPLATE_PARM_INDEX
29309 	  || (TREE_CODE (init) == EXPR_PACK_EXPANSION
29310 	      && (TREE_CODE (PACK_EXPANSION_PATTERN (init))
29311 		  == TEMPLATE_PARM_INDEX)))
29312       && is_auto (TREE_TYPE (init))
29313       && CLASS_PLACEHOLDER_TEMPLATE (TREE_TYPE (init)) == tmpl)
29314     return cp_build_qualified_type (TREE_TYPE (init), cp_type_quals (ptype));
29315 
29316   /* Look through alias templates that just rename another template.  */
29317   tmpl = get_underlying_template (tmpl);
29318   if (!ctad_template_p (tmpl))
29319     {
29320       if (complain & tf_error)
29321 	error ("non-deducible template %qT used without template arguments", tmpl);
29322       return error_mark_node;
29323     }
29324   else if (cxx_dialect < cxx20 && DECL_ALIAS_TEMPLATE_P (tmpl))
29325     {
29326       if (complain & tf_error)
29327 	error ("alias template deduction only available "
29328 	       "with %<-std=c++20%> or %<-std=gnu++20%>");
29329       return error_mark_node;
29330     }
29331 
29332   /* Wait until the initializer is non-dependent.  */
29333   if (type_dependent_expression_p (init))
29334     return ptype;
29335 
29336   tree type = TREE_TYPE (tmpl);
29337 
29338   bool try_list_ctor = false;
29339   bool list_init_p = false;
29340 
29341   releasing_vec rv_args = NULL;
29342   vec<tree,va_gc> *&args = *&rv_args;
29343   if (init == NULL_TREE)
29344     args = make_tree_vector ();
29345   else if (BRACE_ENCLOSED_INITIALIZER_P (init))
29346     {
29347       list_init_p = true;
29348       try_list_ctor = TYPE_HAS_LIST_CTOR (type);
29349       if (try_list_ctor && CONSTRUCTOR_NELTS (init) == 1)
29350 	{
29351 	  /* As an exception, the first phase in 16.3.1.7 (considering the
29352 	     initializer list as a single argument) is omitted if the
29353 	     initializer list consists of a single expression of type cv U,
29354 	     where U is a specialization of C or a class derived from a
29355 	     specialization of C.  */
29356 	  tree elt = CONSTRUCTOR_ELT (init, 0)->value;
29357 	  if (is_spec_or_derived (TREE_TYPE (elt), tmpl))
29358 	    try_list_ctor = false;
29359 	}
29360       if (try_list_ctor || is_std_init_list (type))
29361 	args = make_tree_vector_single (init);
29362       else
29363 	args = make_tree_vector_from_ctor (init);
29364     }
29365   else if (TREE_CODE (init) == TREE_LIST)
29366     args = make_tree_vector_from_list (init);
29367   else
29368     args = make_tree_vector_single (init);
29369 
29370   /* Do this now to avoid problems with erroneous args later on.  */
29371   args = resolve_args (args, complain);
29372   if (args == NULL)
29373     return error_mark_node;
29374 
29375   bool any_dguides_p = false;
29376   tree cands = deduction_guides_for (tmpl, any_dguides_p, complain);
29377   if (cands == error_mark_node)
29378     return error_mark_node;
29379 
29380   /* Prune explicit deduction guides in copy-initialization context (but
29381      not copy-list-initialization).  */
29382   bool elided = false;
29383   if (!list_init_p && (flags & LOOKUP_ONLYCONVERTING))
29384     {
29385       for (lkp_iterator iter (cands); !elided && iter; ++iter)
29386 	if (DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
29387 	  elided = true;
29388 
29389       if (elided)
29390 	{
29391 	  /* Found a nonconverting guide, prune the candidates.  */
29392 	  tree pruned = NULL_TREE;
29393 	  for (lkp_iterator iter (cands); iter; ++iter)
29394 	    if (!DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
29395 	      pruned = lookup_add (*iter, pruned);
29396 
29397 	  cands = pruned;
29398 	}
29399     }
29400 
29401   if (!any_dguides_p)
29402     if (tree guide = maybe_aggr_guide (tmpl, init, args))
29403       cands = lookup_add (guide, cands);
29404 
29405   tree call = error_mark_node;
29406 
29407   /* If this is list-initialization and the class has a list constructor, first
29408      try deducing from the list as a single argument, as [over.match.list].  */
29409   tree list_cands = NULL_TREE;
29410   if (try_list_ctor && cands)
29411     for (lkp_iterator iter (cands); iter; ++iter)
29412       {
29413 	tree dg = *iter;
29414 	if (is_list_ctor (dg))
29415 	  list_cands = lookup_add (dg, list_cands);
29416       }
29417   if (list_cands)
29418     {
29419       ++cp_unevaluated_operand;
29420       call = build_new_function_call (list_cands, &args, tf_decltype);
29421       --cp_unevaluated_operand;
29422 
29423       if (call == error_mark_node)
29424 	{
29425 	  /* That didn't work, now try treating the list as a sequence of
29426 	     arguments.  */
29427 	  release_tree_vector (args);
29428 	  args = make_tree_vector_from_ctor (init);
29429 	}
29430     }
29431 
29432   if (elided && !cands)
29433     {
29434       error ("cannot deduce template arguments for copy-initialization"
29435 	     " of %qT, as it has no non-explicit deduction guides or "
29436 	     "user-declared constructors", type);
29437       return error_mark_node;
29438     }
29439   else if (!cands && call == error_mark_node)
29440     {
29441       error ("cannot deduce template arguments of %qT, as it has no viable "
29442 	     "deduction guides", type);
29443       return error_mark_node;
29444     }
29445 
29446   if (call == error_mark_node)
29447     {
29448       ++cp_unevaluated_operand;
29449       call = build_new_function_call (cands, &args, tf_decltype);
29450       --cp_unevaluated_operand;
29451     }
29452 
29453   if (call == error_mark_node)
29454     {
29455       if (complain & tf_warning_or_error)
29456 	{
29457 	  error ("class template argument deduction failed:");
29458 
29459 	  ++cp_unevaluated_operand;
29460 	  call = build_new_function_call (cands, &args,
29461 					  complain | tf_decltype);
29462 	  --cp_unevaluated_operand;
29463 
29464 	  if (elided)
29465 	    inform (input_location, "explicit deduction guides not considered "
29466 		    "for copy-initialization");
29467 	}
29468       return error_mark_node;
29469     }
29470   /* [over.match.list]/1: In copy-list-initialization, if an explicit
29471      constructor is chosen, the initialization is ill-formed.  */
29472   else if (flags & LOOKUP_ONLYCONVERTING)
29473     {
29474       tree fndecl = cp_get_callee_fndecl_nofold (call);
29475       if (fndecl && DECL_NONCONVERTING_P (fndecl))
29476 	{
29477 	  if (complain & tf_warning_or_error)
29478 	    {
29479 	      // TODO: Pass down location from cp_finish_decl.
29480 	      error ("class template argument deduction for %qT failed: "
29481 		     "explicit deduction guide selected in "
29482 		     "copy-list-initialization", type);
29483 	      inform (DECL_SOURCE_LOCATION (fndecl),
29484 		      "explicit deduction guide declared here");
29485 
29486 	    }
29487 	  return error_mark_node;
29488 	}
29489     }
29490 
29491   /* If CTAD succeeded but the type doesn't have any explicit deduction
29492      guides, this deduction might not be what the user intended.  */
29493   if (call != error_mark_node && !any_dguides_p)
29494     {
29495       tree fndecl = cp_get_callee_fndecl_nofold (call);
29496       if (fndecl != NULL_TREE
29497 	  && (!DECL_IN_SYSTEM_HEADER (fndecl)
29498 	      || global_dc->dc_warn_system_headers)
29499 	  && warning (OPT_Wctad_maybe_unsupported,
29500 		      "%qT may not intend to support class template argument "
29501 		      "deduction", type))
29502 	inform (input_location, "add a deduction guide to suppress this "
29503 		"warning");
29504     }
29505 
29506   return cp_build_qualified_type (TREE_TYPE (call), cp_type_quals (ptype));
29507 }
29508 
29509 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
29510    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
29511    The CONTEXT determines the context in which auto deduction is performed
29512    and is used to control error diagnostics.  FLAGS are the LOOKUP_* flags.
29513 
29514    OUTER_TARGS is used during template argument deduction (context == adc_unify)
29515    to properly substitute the result.  It's also used in the adc_unify and
29516    adc_requirement contexts to communicate the the necessary template arguments
29517    to satisfaction.  OUTER_TARGS is ignored in other contexts.
29518 
29519    For partial-concept-ids, extra args may be appended to the list of deduced
29520    template arguments prior to determining constraint satisfaction.  */
29521 
29522 tree
do_auto_deduction(tree type,tree init,tree auto_node,tsubst_flags_t complain,auto_deduction_context context,tree outer_targs,int flags)29523 do_auto_deduction (tree type, tree init, tree auto_node,
29524                    tsubst_flags_t complain, auto_deduction_context context,
29525 		   tree outer_targs, int flags)
29526 {
29527   if (init == error_mark_node)
29528     return error_mark_node;
29529 
29530   if (init && type_dependent_expression_p (init)
29531       && context != adc_unify)
29532     /* Defining a subset of type-dependent expressions that we can deduce
29533        from ahead of time isn't worth the trouble.  */
29534     return type;
29535 
29536   /* Similarly, we can't deduce from another undeduced decl.  */
29537   if (init && undeduced_auto_decl (init))
29538     return type;
29539 
29540   /* We may be doing a partial substitution, but we still want to replace
29541      auto_node.  */
29542   complain &= ~tf_partial;
29543 
29544   if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
29545     /* C++17 class template argument deduction.  */
29546     return do_class_deduction (type, tmpl, init, flags, complain);
29547 
29548   if (init == NULL_TREE || TREE_TYPE (init) == NULL_TREE)
29549     /* Nothing we can do with this, even in deduction context.  */
29550     return type;
29551 
29552   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
29553      with either a new invented type template parameter U or, if the
29554      initializer is a braced-init-list (8.5.4), with
29555      std::initializer_list<U>.  */
29556   if (BRACE_ENCLOSED_INITIALIZER_P (init))
29557     {
29558       if (!DIRECT_LIST_INIT_P (init))
29559 	type = listify_autos (type, auto_node);
29560       else if (CONSTRUCTOR_NELTS (init) == 1)
29561 	init = CONSTRUCTOR_ELT (init, 0)->value;
29562       else
29563 	{
29564           if (complain & tf_warning_or_error)
29565             {
29566 	      if (permerror (input_location, "direct-list-initialization of "
29567 			     "%<auto%> requires exactly one element"))
29568 	        inform (input_location,
29569 		        "for deduction to %<std::initializer_list%>, use copy-"
29570 		        "list-initialization (i.e. add %<=%> before the %<{%>)");
29571             }
29572 	  type = listify_autos (type, auto_node);
29573 	}
29574     }
29575 
29576   if (type == error_mark_node)
29577     return error_mark_node;
29578 
29579   if (BRACE_ENCLOSED_INITIALIZER_P (init))
29580     {
29581       /* We don't recurse here because we can't deduce from a nested
29582 	 initializer_list.  */
29583       if (CONSTRUCTOR_ELTS (init))
29584 	for (constructor_elt &elt : CONSTRUCTOR_ELTS (init))
29585 	  elt.value = resolve_nondeduced_context (elt.value, complain);
29586     }
29587   else
29588     init = resolve_nondeduced_context (init, complain);
29589 
29590   tree targs;
29591   if (context == adc_decomp_type
29592       && auto_node == type
29593       && init != error_mark_node
29594       && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
29595     {
29596       /* [dcl.struct.bind]/1 - if decomposition declaration has no ref-qualifiers
29597 	 and initializer has array type, deduce cv-qualified array type.  */
29598       targs = make_tree_vec (1);
29599       TREE_VEC_ELT (targs, 0) = TREE_TYPE (init);
29600     }
29601   else if (AUTO_IS_DECLTYPE (auto_node))
29602     {
29603       tree stripped_init = tree_strip_any_location_wrapper (init);
29604       if (REFERENCE_REF_P (stripped_init))
29605 	stripped_init = TREE_OPERAND (stripped_init, 0);
29606       bool id = (DECL_P (stripped_init)
29607 		 || ((TREE_CODE (init) == COMPONENT_REF
29608 		      || TREE_CODE (init) == SCOPE_REF)
29609 		     && !REF_PARENTHESIZED_P (init)));
29610       tree deduced = finish_decltype_type (init, id, complain);
29611       deduced = canonicalize_type_argument (deduced, complain);
29612       if (deduced == error_mark_node)
29613 	return error_mark_node;
29614       targs = make_tree_vec (1);
29615       TREE_VEC_ELT (targs, 0) = deduced;
29616       /* FIXME: These errors ought to be diagnosed at parse time. */
29617       if (type != auto_node)
29618 	{
29619           if (complain & tf_error)
29620 	    error ("%qT as type rather than plain %<decltype(auto)%>", type);
29621 	  return error_mark_node;
29622 	}
29623       else if (TYPE_QUALS (type) != TYPE_UNQUALIFIED)
29624 	{
29625 	  if (complain & tf_error)
29626 	    error ("%<decltype(auto)%> cannot be cv-qualified");
29627 	  return error_mark_node;
29628 	}
29629     }
29630   else
29631     {
29632       if (error_operand_p (init))
29633 	return error_mark_node;
29634 
29635       tree parms = build_tree_list (NULL_TREE, type);
29636       tree tparms;
29637 
29638       if (flag_concepts)
29639 	tparms = extract_autos (type);
29640       else
29641 	{
29642 	  tparms = make_tree_vec (1);
29643 	  TREE_VEC_ELT (tparms, 0)
29644 	    = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
29645 	}
29646 
29647       targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
29648       int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
29649 				       DEDUCE_CALL,
29650 				       NULL, /*explain_p=*/false);
29651       if (val > 0)
29652 	{
29653 	  if (processing_template_decl)
29654 	    /* Try again at instantiation time.  */
29655 	    return type;
29656 	  if (type && type != error_mark_node
29657 	      && (complain & tf_error))
29658 	    /* If type is error_mark_node a diagnostic must have been
29659 	       emitted by now.  Also, having a mention to '<type error>'
29660 	       in the diagnostic is not really useful to the user.  */
29661 	    {
29662 	      if (cfun
29663 		  && FNDECL_USED_AUTO (current_function_decl)
29664 		  && (auto_node
29665 		      == DECL_SAVED_AUTO_RETURN_TYPE (current_function_decl))
29666 		  && LAMBDA_FUNCTION_P (current_function_decl))
29667 		error ("unable to deduce lambda return type from %qE", init);
29668 	      else
29669 		error ("unable to deduce %qT from %qE", type, init);
29670 	      type_unification_real (tparms, targs, parms, &init, 1, 0,
29671 				     DEDUCE_CALL,
29672 				     NULL, /*explain_p=*/true);
29673 	    }
29674 	  return error_mark_node;
29675 	}
29676     }
29677 
29678   /* Check any placeholder constraints against the deduced type. */
29679   if (processing_template_decl && context == adc_unify)
29680     /* Constraints will be checked after deduction.  */;
29681   else if (tree constr = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (auto_node)))
29682     {
29683       if (processing_template_decl)
29684 	{
29685 	  gcc_checking_assert (context == adc_variable_type
29686 			       || context == adc_return_type
29687 			       || context == adc_decomp_type);
29688 	  gcc_checking_assert (!type_dependent_expression_p (init));
29689 	  /* If the constraint is dependent, we need to wait until
29690 	     instantiation time to resolve the placeholder.  */
29691 	  if (placeholder_type_constraint_dependent_p (constr))
29692 	    return type;
29693 	}
29694 
29695       if ((context == adc_return_type
29696 	   || context == adc_variable_type
29697 	   || context == adc_decomp_type)
29698 	  && current_function_decl
29699 	  && DECL_TEMPLATE_INFO (current_function_decl))
29700 	outer_targs = DECL_TI_ARGS (current_function_decl);
29701 
29702       tree full_targs = add_to_template_args (outer_targs, targs);
29703 
29704       /* HACK: Compensate for callers not always communicating all levels of
29705 	 outer template arguments by filling in the outermost missing levels
29706 	 with dummy levels before checking satisfaction.  We'll still crash
29707 	 if the constraint depends on a template argument belonging to one of
29708 	 these missing levels, but this hack otherwise allows us to handle a
29709 	 large subset of possible constraints (including all non-dependent
29710 	 constraints).  */
29711       if (int missing_levels = (TEMPLATE_TYPE_ORIG_LEVEL (auto_node)
29712 				- TMPL_ARGS_DEPTH (full_targs)))
29713 	{
29714 	  tree dummy_levels = make_tree_vec (missing_levels);
29715 	  for (int i = 0; i < missing_levels; ++i)
29716 	    TREE_VEC_ELT (dummy_levels, i) = make_tree_vec (0);
29717 	  full_targs = add_to_template_args (dummy_levels, full_targs);
29718 	}
29719 
29720       if (!constraints_satisfied_p (auto_node, full_targs))
29721 	{
29722 	  if (complain & tf_warning_or_error)
29723 	    {
29724 	      auto_diagnostic_group d;
29725 	      switch (context)
29726 		{
29727 		case adc_unspecified:
29728 		case adc_unify:
29729 		  error("placeholder constraints not satisfied");
29730 		  break;
29731 		case adc_variable_type:
29732 		case adc_decomp_type:
29733 		  error ("deduced initializer does not satisfy "
29734 			 "placeholder constraints");
29735 		  break;
29736 		case adc_return_type:
29737 		  error ("deduced return type does not satisfy "
29738 			 "placeholder constraints");
29739 		  break;
29740 		case adc_requirement:
29741 		  error ("deduced expression type does not satisfy "
29742 			 "placeholder constraints");
29743 		  break;
29744 		}
29745 	      diagnose_constraints (input_location, auto_node, full_targs);
29746 	    }
29747 	  return error_mark_node;
29748 	}
29749     }
29750 
29751   if (TEMPLATE_TYPE_LEVEL (auto_node) == 1)
29752     /* The outer template arguments are already substituted into type
29753        (but we still may have used them for constraint checking above).  */;
29754   else if (context == adc_unify)
29755     targs = add_to_template_args (outer_targs, targs);
29756   else if (processing_template_decl)
29757     targs = add_to_template_args (current_template_args (), targs);
29758   return tsubst (type, targs, complain, NULL_TREE);
29759 }
29760 
29761 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
29762    result.  */
29763 
29764 tree
splice_late_return_type(tree type,tree late_return_type)29765 splice_late_return_type (tree type, tree late_return_type)
29766 {
29767   if (late_return_type)
29768     {
29769       gcc_assert (is_auto (type) || seen_error ());
29770       return late_return_type;
29771     }
29772 
29773   if (tree auto_node = find_type_usage (type, is_auto))
29774     if (TEMPLATE_TYPE_LEVEL (auto_node) <= processing_template_decl)
29775       {
29776 	/* In an abbreviated function template we didn't know we were dealing
29777 	   with a function template when we saw the auto return type, so rebuild
29778 	   the return type using an auto with the correct level.  */
29779 	tree new_auto = make_auto_1 (TYPE_IDENTIFIER (auto_node), false);
29780 	tree auto_vec = make_tree_vec (1);
29781 	TREE_VEC_ELT (auto_vec, 0) = new_auto;
29782 	tree targs = add_outermost_template_args (current_template_args (),
29783 						  auto_vec);
29784 	/* Also rebuild the constraint info in terms of the new auto.  */
29785 	if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (auto_node))
29786 	  PLACEHOLDER_TYPE_CONSTRAINTS_INFO (new_auto)
29787 	    = build_tree_list (current_template_parms,
29788 			       tsubst_constraint (TREE_VALUE (ci), targs,
29789 						  tf_none, NULL_TREE));
29790 	TYPE_CANONICAL (new_auto) = canonical_type_parameter (new_auto);
29791 	return tsubst (type, targs, tf_none, NULL_TREE);
29792       }
29793   return type;
29794 }
29795 
29796 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
29797    'decltype(auto)' or a deduced class template.  */
29798 
29799 bool
is_auto(const_tree type)29800 is_auto (const_tree type)
29801 {
29802   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
29803       && (TYPE_IDENTIFIER (type) == auto_identifier
29804 	  || TYPE_IDENTIFIER (type) == decltype_auto_identifier))
29805     return true;
29806   else
29807     return false;
29808 }
29809 
29810 /* for_each_template_parm callback for type_uses_auto.  */
29811 
29812 int
is_auto_r(tree tp,void *)29813 is_auto_r (tree tp, void */*data*/)
29814 {
29815   return is_auto (tp);
29816 }
29817 
29818 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
29819    a use of `auto'.  Returns NULL_TREE otherwise.  */
29820 
29821 tree
type_uses_auto(tree type)29822 type_uses_auto (tree type)
29823 {
29824   if (type == NULL_TREE)
29825     return NULL_TREE;
29826   else if (flag_concepts)
29827     {
29828       /* The Concepts TS allows multiple autos in one type-specifier; just
29829 	 return the first one we find, do_auto_deduction will collect all of
29830 	 them.  */
29831       if (uses_template_parms (type))
29832 	return for_each_template_parm (type, is_auto_r, /*data*/NULL,
29833 				       /*visited*/NULL, /*nondeduced*/false);
29834       else
29835 	return NULL_TREE;
29836     }
29837   else
29838     return find_type_usage (type, is_auto);
29839 }
29840 
29841 /* Report ill-formed occurrences of auto types in ARGUMENTS.  If
29842    concepts are enabled, auto is acceptable in template arguments, but
29843    only when TEMPL identifies a template class.  Return TRUE if any
29844    such errors were reported.  */
29845 
29846 bool
check_auto_in_tmpl_args(tree tmpl,tree args)29847 check_auto_in_tmpl_args (tree tmpl, tree args)
29848 {
29849   /* If there were previous errors, nevermind.  */
29850   if (!args || TREE_CODE (args) != TREE_VEC)
29851     return false;
29852 
29853   /* If TMPL is an identifier, we're parsing and we can't tell yet
29854      whether TMPL is supposed to be a type, a function or a variable.
29855      We'll only be able to tell during template substitution, so we
29856      expect to be called again then.  If concepts are enabled and we
29857      know we have a type, we're ok.  */
29858   if (flag_concepts
29859       && (identifier_p (tmpl)
29860 	  || (DECL_P (tmpl)
29861 	      &&  (DECL_TYPE_TEMPLATE_P (tmpl)
29862 		   || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)))))
29863     return false;
29864 
29865   /* Quickly search for any occurrences of auto; usually there won't
29866      be any, and then we'll avoid allocating the vector.  */
29867   if (!type_uses_auto (args))
29868     return false;
29869 
29870   bool errors = false;
29871 
29872   tree vec = extract_autos (args);
29873   for (int i = 0; i < TREE_VEC_LENGTH (vec); i++)
29874     {
29875       tree xauto = TREE_VALUE (TREE_VEC_ELT (vec, i));
29876       error_at (DECL_SOURCE_LOCATION (xauto),
29877 		"invalid use of %qT in template argument", xauto);
29878       errors = true;
29879     }
29880 
29881   return errors;
29882 }
29883 
29884 /* Recursively walk over && expressions searching for EXPR. Return a reference
29885    to that expression.  */
29886 
find_template_requirement(tree * t,tree key)29887 static tree *find_template_requirement (tree *t, tree key)
29888 {
29889   if (*t == key)
29890     return t;
29891   if (TREE_CODE (*t) == TRUTH_ANDIF_EXPR)
29892     {
29893       if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 0), key))
29894 	return p;
29895       if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 1), key))
29896 	return p;
29897     }
29898   return 0;
29899 }
29900 
29901 /* Convert the generic type parameters in PARM that match the types given in the
29902    range [START_IDX, END_IDX) from the current_template_parms into generic type
29903    packs.  */
29904 
29905 tree
convert_generic_types_to_packs(tree parm,int start_idx,int end_idx)29906 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
29907 {
29908   tree current = current_template_parms;
29909   int depth = TMPL_PARMS_DEPTH (current);
29910   current = INNERMOST_TEMPLATE_PARMS (current);
29911   tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
29912 
29913   for (int i = 0; i < start_idx; ++i)
29914     TREE_VEC_ELT (replacement, i)
29915       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
29916 
29917   for (int i = start_idx; i < end_idx; ++i)
29918     {
29919       /* Create a distinct parameter pack type from the current parm and add it
29920 	 to the replacement args to tsubst below into the generic function
29921 	 parameter.  */
29922       tree node = TREE_VEC_ELT (current, i);
29923       tree o = TREE_TYPE (TREE_VALUE (node));
29924       tree t = copy_type (o);
29925       TEMPLATE_TYPE_PARM_INDEX (t)
29926 	= reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
29927 				      t, 0, 0, tf_none);
29928       TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
29929       TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
29930       TYPE_MAIN_VARIANT (t) = t;
29931       TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
29932       TYPE_CANONICAL (t) = canonical_type_parameter (t);
29933       TREE_VEC_ELT (replacement, i) = t;
29934 
29935       /* Replace the current template parameter with new pack.  */
29936       TREE_VALUE (node) = TREE_CHAIN (t);
29937 
29938       /* Surgically adjust the associated constraint of adjusted parameter
29939          and it's corresponding contribution to the current template
29940          requirements.  */
29941       if (tree constr = TEMPLATE_PARM_CONSTRAINTS (node))
29942 	{
29943 	  tree id = unpack_concept_check (constr);
29944 	  TREE_VEC_ELT (TREE_OPERAND (id, 1), 0) = t;
29945 	  tree fold = finish_left_unary_fold_expr (constr, TRUTH_ANDIF_EXPR);
29946 	  TEMPLATE_PARM_CONSTRAINTS (node) = fold;
29947 
29948 	  /* If there was a constraint, we also need to replace that in
29949 	     the template requirements, which we've already built.  */
29950 	  tree *reqs = &TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
29951 	  reqs = find_template_requirement (reqs, constr);
29952 	  *reqs = fold;
29953 	}
29954     }
29955 
29956   for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
29957     TREE_VEC_ELT (replacement, i)
29958       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
29959 
29960   /* If there are more levels then build up the replacement with the outer
29961      template parms.  */
29962   if (depth > 1)
29963     replacement = add_to_template_args (template_parms_to_args
29964 					(TREE_CHAIN (current_template_parms)),
29965 					replacement);
29966 
29967   return tsubst (parm, replacement, tf_none, NULL_TREE);
29968 }
29969 
29970 /* __integer_pack(N) in a pack expansion expands to a sequence of numbers from
29971    0..N-1.  */
29972 
29973 void
declare_integer_pack(void)29974 declare_integer_pack (void)
29975 {
29976   tree ipfn = push_library_fn (get_identifier ("__integer_pack"),
29977 			       build_function_type_list (integer_type_node,
29978 							 integer_type_node,
29979 							 NULL_TREE),
29980 			       NULL_TREE, ECF_CONST);
29981   DECL_DECLARED_CONSTEXPR_P (ipfn) = true;
29982   set_decl_built_in_function (ipfn, BUILT_IN_FRONTEND,
29983 			      CP_BUILT_IN_INTEGER_PACK);
29984 }
29985 
29986 /* Walk the decl or type specialization table calling FN on each
29987    entry.  */
29988 
29989 void
walk_specializations(bool decls_p,void (* fn)(bool decls_p,spec_entry * entry,void * data),void * data)29990 walk_specializations (bool decls_p,
29991 		      void (*fn) (bool decls_p, spec_entry *entry, void *data),
29992 		      void *data)
29993 {
29994   spec_hash_table *table = decls_p ? decl_specializations
29995     : type_specializations;
29996   spec_hash_table::iterator end (table->end ());
29997   for (spec_hash_table::iterator iter (table->begin ()); iter != end; ++iter)
29998     fn (decls_p, *iter, data);
29999 }
30000 
30001 /* Lookup the specialization of *ELT, in the decl or type
30002    specialization table.  Return the SPEC that's already there, or
30003    NULL if nothing.  */
30004 
30005 tree
match_mergeable_specialization(bool decl_p,spec_entry * elt)30006 match_mergeable_specialization (bool decl_p, spec_entry *elt)
30007 {
30008   hash_table<spec_hasher> *specializations
30009     = decl_p ? decl_specializations : type_specializations;
30010   hashval_t hash = spec_hasher::hash (elt);
30011   auto *slot = specializations->find_slot_with_hash (elt, hash, NO_INSERT);
30012 
30013   if (slot)
30014     return (*slot)->spec;
30015 
30016   return NULL_TREE;
30017 }
30018 
30019 /* Return flags encoding whether SPEC is on the instantiation and/or
30020    specialization lists of TMPL.  */
30021 
30022 unsigned
get_mergeable_specialization_flags(tree tmpl,tree decl)30023 get_mergeable_specialization_flags (tree tmpl, tree decl)
30024 {
30025   unsigned flags = 0;
30026 
30027   for (tree inst = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
30028        inst; inst = TREE_CHAIN (inst))
30029     if (TREE_VALUE (inst) == decl)
30030       {
30031 	flags |= 1;
30032 	break;
30033       }
30034 
30035   if (CLASS_TYPE_P (TREE_TYPE (decl))
30036       && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl))
30037       && CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)) == 2)
30038     /* Only need to search if DECL is a partial specialization.  */
30039     for (tree part = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
30040 	 part; part = TREE_CHAIN (part))
30041       if (TREE_VALUE (part) == decl)
30042 	{
30043 	  flags |= 2;
30044 	  break;
30045 	}
30046 
30047   return flags;
30048 }
30049 
30050 /* Add a new specialization described by SPEC.  DECL is the
30051    maybe-template decl and FLAGS is as returned from
30052    get_mergeable_specialization_flags.  */
30053 
30054 void
add_mergeable_specialization(bool decl_p,bool alias_p,spec_entry * elt,tree decl,unsigned flags)30055 add_mergeable_specialization (bool decl_p, bool alias_p, spec_entry *elt,
30056 			      tree decl, unsigned flags)
30057 {
30058   hashval_t hash = spec_hasher::hash (elt);
30059   if (decl_p)
30060     {
30061       auto *slot = decl_specializations->find_slot_with_hash (elt, hash, INSERT);
30062 
30063       gcc_checking_assert (!*slot);
30064       auto entry = ggc_alloc<spec_entry> ();
30065       *entry = *elt;
30066       *slot = entry;
30067 
30068       if (alias_p)
30069 	{
30070 	  elt->spec = TREE_TYPE (elt->spec);
30071 	  gcc_checking_assert (elt->spec);
30072 	}
30073     }
30074 
30075   if (!decl_p || alias_p)
30076     {
30077       auto *slot = type_specializations->find_slot_with_hash (elt, hash, INSERT);
30078 
30079       /* We don't distinguish different constrained partial type
30080 	 specializations, so there could be duplicates.  Everything else
30081 	 must be new.   */
30082       if (!(flags & 2 && *slot))
30083 	{
30084 	  gcc_checking_assert (!*slot);
30085 
30086 	  auto entry = ggc_alloc<spec_entry> ();
30087 	  *entry = *elt;
30088 	  *slot = entry;
30089 	}
30090     }
30091 
30092   if (flags & 1)
30093     DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl)
30094       = tree_cons (elt->args, decl, DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl));
30095 
30096   if (flags & 2)
30097     {
30098       /* A partial specialization.  */
30099       tree cons = tree_cons (elt->args, decl,
30100 			     DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl));
30101       TREE_TYPE (cons) = elt->spec;
30102       DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl) = cons;
30103     }
30104 }
30105 
30106 /* Set up the hash tables for template instantiations.  */
30107 
30108 void
init_template_processing(void)30109 init_template_processing (void)
30110 {
30111   decl_specializations = hash_table<spec_hasher>::create_ggc (37);
30112   type_specializations = hash_table<spec_hasher>::create_ggc (37);
30113 
30114   if (cxx_dialect >= cxx11)
30115     declare_integer_pack ();
30116 }
30117 
30118 /* Print stats about the template hash tables for -fstats.  */
30119 
30120 void
print_template_statistics(void)30121 print_template_statistics (void)
30122 {
30123   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
30124 	   "%f collisions\n", (long) decl_specializations->size (),
30125 	   (long) decl_specializations->elements (),
30126 	   decl_specializations->collisions ());
30127   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
30128 	   "%f collisions\n", (long) type_specializations->size (),
30129 	   (long) type_specializations->elements (),
30130 	   type_specializations->collisions ());
30131 }
30132 
30133 #if CHECKING_P
30134 
30135 namespace selftest {
30136 
30137 /* Verify that build_non_dependent_expr () works, for various expressions,
30138    and that location wrappers don't affect the results.  */
30139 
30140 static void
test_build_non_dependent_expr()30141 test_build_non_dependent_expr ()
30142 {
30143   location_t loc = BUILTINS_LOCATION;
30144 
30145   /* Verify constants, without and with location wrappers.  */
30146   tree int_cst = build_int_cst (integer_type_node, 42);
30147   ASSERT_EQ (int_cst, build_non_dependent_expr (int_cst));
30148 
30149   tree wrapped_int_cst = maybe_wrap_with_location (int_cst, loc);
30150   ASSERT_TRUE (location_wrapper_p (wrapped_int_cst));
30151   ASSERT_EQ (wrapped_int_cst, build_non_dependent_expr (wrapped_int_cst));
30152 
30153   tree string_lit = build_string (4, "foo");
30154   TREE_TYPE (string_lit) = char_array_type_node;
30155   string_lit = fix_string_type (string_lit);
30156   ASSERT_EQ (string_lit, build_non_dependent_expr (string_lit));
30157 
30158   tree wrapped_string_lit = maybe_wrap_with_location (string_lit, loc);
30159   ASSERT_TRUE (location_wrapper_p (wrapped_string_lit));
30160   ASSERT_EQ (wrapped_string_lit,
30161 	     build_non_dependent_expr (wrapped_string_lit));
30162 }
30163 
30164 /* Verify that type_dependent_expression_p () works correctly, even
30165    in the presence of location wrapper nodes.  */
30166 
30167 static void
test_type_dependent_expression_p()30168 test_type_dependent_expression_p ()
30169 {
30170   location_t loc = BUILTINS_LOCATION;
30171 
30172   tree name = get_identifier ("foo");
30173 
30174   /* If no templates are involved, nothing is type-dependent.  */
30175   gcc_assert (!processing_template_decl);
30176   ASSERT_FALSE (type_dependent_expression_p (name));
30177 
30178   ++processing_template_decl;
30179 
30180   /* Within a template, an unresolved name is always type-dependent.  */
30181   ASSERT_TRUE (type_dependent_expression_p (name));
30182 
30183   /* Ensure it copes with NULL_TREE and errors.  */
30184   ASSERT_FALSE (type_dependent_expression_p (NULL_TREE));
30185   ASSERT_FALSE (type_dependent_expression_p (error_mark_node));
30186 
30187   /* A USING_DECL in a template should be type-dependent, even if wrapped
30188      with a location wrapper (PR c++/83799).  */
30189   tree using_decl = build_lang_decl (USING_DECL, name, NULL_TREE);
30190   TREE_TYPE (using_decl) = integer_type_node;
30191   ASSERT_TRUE (type_dependent_expression_p (using_decl));
30192   tree wrapped_using_decl = maybe_wrap_with_location (using_decl, loc);
30193   ASSERT_TRUE (location_wrapper_p (wrapped_using_decl));
30194   ASSERT_TRUE (type_dependent_expression_p (wrapped_using_decl));
30195 
30196   --processing_template_decl;
30197 }
30198 
30199 /* Run all of the selftests within this file.  */
30200 
30201 void
cp_pt_c_tests()30202 cp_pt_c_tests ()
30203 {
30204   test_build_non_dependent_expr ();
30205   test_type_dependent_expression_p ();
30206 }
30207 
30208 } // namespace selftest
30209 
30210 #endif /* #if CHECKING_P */
30211 
30212 #include "gt-cp-pt.h"
30213