1 /* Handle parameterized types (templates) for GNU -*- C++ -*-.
2    Copyright (C) 1992-2020 Free Software Foundation, Inc.
3    Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
4    Rewritten by Jason Merrill (jason@cygnus.com).
5 
6 This file is part of GCC.
7 
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
12 
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17 
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21 
22 /* Known bugs or deficiencies include:
23 
24      all methods must be provided in header files; can't use a source
25      file that contains only the method templates and "just win".  */
26 
27 #include "config.h"
28 #include "system.h"
29 #include "coretypes.h"
30 #include "cp-tree.h"
31 #include "timevar.h"
32 #include "stringpool.h"
33 #include "varasm.h"
34 #include "attribs.h"
35 #include "stor-layout.h"
36 #include "intl.h"
37 #include "c-family/c-objc.h"
38 #include "cp-objcp-common.h"
39 #include "toplev.h"
40 #include "tree-iterator.h"
41 #include "type-utils.h"
42 #include "gimplify.h"
43 #include "gcc-rich-location.h"
44 #include "selftest.h"
45 #include "target.h"
46 
47 /* The type of functions taking a tree, and some additional data, and
48    returning an int.  */
49 typedef int (*tree_fn_t) (tree, void*);
50 
51 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
52    instantiations have been deferred, either because their definitions
53    were not yet available, or because we were putting off doing the work.  */
54 struct GTY ((chain_next ("%h.next"))) pending_template
55 {
56   struct pending_template *next;
57   struct tinst_level *tinst;
58 };
59 
60 static GTY(()) struct pending_template *pending_templates;
61 static GTY(()) struct pending_template *last_pending_template;
62 
63 int processing_template_parmlist;
64 static int template_header_count;
65 
66 static GTY(()) tree saved_trees;
67 static vec<int> inline_parm_levels;
68 
69 static GTY(()) struct tinst_level *current_tinst_level;
70 
71 static GTY(()) vec<tree, va_gc> *saved_access_scope;
72 
73 /* Live only within one (recursive) call to tsubst_expr.  We use
74    this to pass the statement expression node from the STMT_EXPR
75    to the EXPR_STMT that is its result.  */
76 static tree cur_stmt_expr;
77 
78 // -------------------------------------------------------------------------- //
79 // Local Specialization Stack
80 //
81 // Implementation of the RAII helper for creating new local
82 // specializations.
local_specialization_stack(lss_policy policy)83 local_specialization_stack::local_specialization_stack (lss_policy policy)
84   : saved (local_specializations)
85 {
86   if (policy == lss_nop)
87     ;
88   else if (policy == lss_blank || !saved)
89     local_specializations = new hash_map<tree, tree>;
90   else
91     local_specializations = new hash_map<tree, tree>(*saved);
92 }
93 
~local_specialization_stack()94 local_specialization_stack::~local_specialization_stack ()
95 {
96   if (local_specializations != saved)
97     {
98       delete local_specializations;
99       local_specializations = saved;
100     }
101 }
102 
103 /* True if we've recursed into fn_type_unification too many times.  */
104 static bool excessive_deduction_depth;
105 
106 struct GTY((for_user)) spec_entry
107 {
108   tree tmpl;
109   tree args;
110   tree spec;
111 };
112 
113 struct spec_hasher : ggc_ptr_hash<spec_entry>
114 {
115   static hashval_t hash (spec_entry *);
116   static bool equal (spec_entry *, spec_entry *);
117 };
118 
119 static GTY (()) hash_table<spec_hasher> *decl_specializations;
120 
121 static GTY (()) hash_table<spec_hasher> *type_specializations;
122 
123 /* Contains canonical template parameter types. The vector is indexed by
124    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
125    TREE_LIST, whose TREE_VALUEs contain the canonical template
126    parameters of various types and levels.  */
127 static GTY(()) vec<tree, va_gc> *canonical_template_parms;
128 
129 #define UNIFY_ALLOW_NONE 0
130 #define UNIFY_ALLOW_MORE_CV_QUAL 1
131 #define UNIFY_ALLOW_LESS_CV_QUAL 2
132 #define UNIFY_ALLOW_DERIVED 4
133 #define UNIFY_ALLOW_INTEGER 8
134 #define UNIFY_ALLOW_OUTER_LEVEL 16
135 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
136 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
137 
138 enum template_base_result {
139   tbr_incomplete_type,
140   tbr_ambiguous_baseclass,
141   tbr_success
142 };
143 
144 static bool resolve_overloaded_unification (tree, tree, tree, tree,
145 					    unification_kind_t, int,
146 					    bool);
147 static int try_one_overload (tree, tree, tree, tree, tree,
148 			     unification_kind_t, int, bool, bool);
149 static int unify (tree, tree, tree, tree, int, bool);
150 static void add_pending_template (tree);
151 static tree reopen_tinst_level (struct tinst_level *);
152 static tree tsubst_initializer_list (tree, tree);
153 static tree get_partial_spec_bindings (tree, tree, tree);
154 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
155 				   bool, bool);
156 static tree coerce_innermost_template_parms (tree, tree, tree, tsubst_flags_t,
157 					      bool, bool);
158 static void tsubst_enum	(tree, tree, tree);
159 static tree add_to_template_args (tree, tree);
160 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
161 static int check_non_deducible_conversion (tree, tree, int, int,
162 					   struct conversion **, bool);
163 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
164 					     tree);
165 static int type_unification_real (tree, tree, tree, const tree *,
166 				  unsigned int, int, unification_kind_t,
167 				  vec<deferred_access_check, va_gc> **,
168 				  bool);
169 static void note_template_header (int);
170 static tree convert_nontype_argument_function (tree, tree, tsubst_flags_t);
171 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
172 static tree convert_template_argument (tree, tree, tree,
173 				       tsubst_flags_t, int, tree);
174 static tree for_each_template_parm (tree, tree_fn_t, void*,
175 				    hash_set<tree> *, bool, tree_fn_t = NULL);
176 static tree expand_template_argument_pack (tree);
177 static tree build_template_parm_index (int, int, int, tree, tree);
178 static bool inline_needs_template_parms (tree, bool);
179 static void push_inline_template_parms_recursive (tree, int);
180 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
181 static int mark_template_parm (tree, void *);
182 static int template_parm_this_level_p (tree, void *);
183 static tree tsubst_friend_function (tree, tree);
184 static tree tsubst_friend_class (tree, tree);
185 static int can_complete_type_without_circularity (tree);
186 static tree get_bindings (tree, tree, tree, bool);
187 static int template_decl_level (tree);
188 static int check_cv_quals_for_unify (int, tree, tree);
189 static int unify_pack_expansion (tree, tree, tree,
190 				 tree, unification_kind_t, bool, bool);
191 static tree copy_template_args (tree);
192 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
193 tree most_specialized_partial_spec (tree, tsubst_flags_t);
194 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
195 static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
196 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
197 static bool check_specialization_scope (void);
198 static tree process_partial_specialization (tree);
199 static void set_current_access_from_decl (tree);
200 static enum template_base_result get_template_base (tree, tree, tree, tree,
201 						    bool , tree *);
202 static tree try_class_unification (tree, tree, tree, tree, bool);
203 static bool class_nttp_const_wrapper_p (tree t);
204 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
205 					   tree, tree);
206 static bool template_template_parm_bindings_ok_p (tree, tree);
207 static void tsubst_default_arguments (tree, tsubst_flags_t);
208 static tree for_each_template_parm_r (tree *, int *, void *);
209 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
210 static void copy_default_args_to_explicit_spec (tree);
211 static bool invalid_nontype_parm_type_p (tree, tsubst_flags_t);
212 static bool dependent_template_arg_p (tree);
213 static bool any_template_arguments_need_structural_equality_p (tree);
214 static bool dependent_type_p_r (tree);
215 static tree tsubst_copy	(tree, tree, tsubst_flags_t, tree);
216 static tree tsubst_decl (tree, tree, tsubst_flags_t);
217 static void perform_typedefs_access_check (tree tmpl, tree targs);
218 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
219 							location_t);
220 static tree listify (tree);
221 static tree listify_autos (tree, tree);
222 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
223 static tree instantiate_alias_template (tree, tree, tsubst_flags_t);
224 static bool complex_alias_template_p (const_tree tmpl);
225 static tree get_underlying_template (tree);
226 static tree tsubst_attributes (tree, tree, tsubst_flags_t, tree);
227 static tree canonicalize_expr_argument (tree, tsubst_flags_t);
228 static tree make_argument_pack (tree);
229 static void register_parameter_specializations (tree, tree);
230 static tree enclosing_instantiation_of (tree tctx);
231 
232 /* Make the current scope suitable for access checking when we are
233    processing T.  T can be FUNCTION_DECL for instantiated function
234    template, VAR_DECL for static member variable, or TYPE_DECL for
235    alias template (needed by instantiate_decl).  */
236 
237 void
push_access_scope(tree t)238 push_access_scope (tree t)
239 {
240   gcc_assert (VAR_OR_FUNCTION_DECL_P (t)
241 	      || TREE_CODE (t) == TYPE_DECL);
242 
243   if (DECL_FRIEND_CONTEXT (t))
244     push_nested_class (DECL_FRIEND_CONTEXT (t));
245   else if (DECL_CLASS_SCOPE_P (t))
246     push_nested_class (DECL_CONTEXT (t));
247   else
248     push_to_top_level ();
249 
250   if (TREE_CODE (t) == FUNCTION_DECL)
251     {
252       vec_safe_push (saved_access_scope, current_function_decl);
253       current_function_decl = t;
254     }
255 }
256 
257 /* Restore the scope set up by push_access_scope.  T is the node we
258    are processing.  */
259 
260 void
pop_access_scope(tree t)261 pop_access_scope (tree t)
262 {
263   if (TREE_CODE (t) == FUNCTION_DECL)
264     current_function_decl = saved_access_scope->pop();
265 
266   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
267     pop_nested_class ();
268   else
269     pop_from_top_level ();
270 }
271 
272 /* Do any processing required when DECL (a member template
273    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
274    to DECL, unless it is a specialization, in which case the DECL
275    itself is returned.  */
276 
277 tree
finish_member_template_decl(tree decl)278 finish_member_template_decl (tree decl)
279 {
280   if (decl == error_mark_node)
281     return error_mark_node;
282 
283   gcc_assert (DECL_P (decl));
284 
285   if (TREE_CODE (decl) == TYPE_DECL)
286     {
287       tree type;
288 
289       type = TREE_TYPE (decl);
290       if (type == error_mark_node)
291 	return error_mark_node;
292       if (MAYBE_CLASS_TYPE_P (type)
293 	  && CLASSTYPE_TEMPLATE_INFO (type)
294 	  && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
295 	{
296 	  tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
297 	  check_member_template (tmpl);
298 	  return tmpl;
299 	}
300       return NULL_TREE;
301     }
302   else if (TREE_CODE (decl) == FIELD_DECL)
303     error_at (DECL_SOURCE_LOCATION (decl),
304 	      "data member %qD cannot be a member template", decl);
305   else if (DECL_TEMPLATE_INFO (decl))
306     {
307       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
308 	{
309 	  check_member_template (DECL_TI_TEMPLATE (decl));
310 	  return DECL_TI_TEMPLATE (decl);
311 	}
312       else
313 	return decl;
314     }
315   else
316     error_at (DECL_SOURCE_LOCATION (decl),
317 	      "invalid member template declaration %qD", decl);
318 
319   return error_mark_node;
320 }
321 
322 /* Create a template info node.  */
323 
324 tree
build_template_info(tree template_decl,tree template_args)325 build_template_info (tree template_decl, tree template_args)
326 {
327   tree result = make_node (TEMPLATE_INFO);
328   TI_TEMPLATE (result) = template_decl;
329   TI_ARGS (result) = template_args;
330   return result;
331 }
332 
333 /* Return the template info node corresponding to T, whatever T is.  */
334 
335 tree
get_template_info(const_tree t)336 get_template_info (const_tree t)
337 {
338   tree tinfo = NULL_TREE;
339 
340   if (!t || t == error_mark_node)
341     return NULL;
342 
343   if (TREE_CODE (t) == NAMESPACE_DECL
344       || TREE_CODE (t) == PARM_DECL)
345     return NULL;
346 
347   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
348     tinfo = DECL_TEMPLATE_INFO (t);
349 
350   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
351     t = TREE_TYPE (t);
352 
353   if (OVERLOAD_TYPE_P (t))
354     tinfo = TYPE_TEMPLATE_INFO (t);
355   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
356     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
357 
358   return tinfo;
359 }
360 
361 /* Returns the template nesting level of the indicated class TYPE.
362 
363    For example, in:
364      template <class T>
365      struct A
366      {
367        template <class U>
368        struct B {};
369      };
370 
371    A<T>::B<U> has depth two, while A<T> has depth one.
372    Both A<T>::B<int> and A<int>::B<U> have depth one, if
373    they are instantiations, not specializations.
374 
375    This function is guaranteed to return 0 if passed NULL_TREE so
376    that, for example, `template_class_depth (current_class_type)' is
377    always safe.  */
378 
379 int
template_class_depth(tree type)380 template_class_depth (tree type)
381 {
382   int depth;
383 
384   for (depth = 0; type && TREE_CODE (type) != NAMESPACE_DECL; )
385     {
386       tree tinfo = get_template_info (type);
387 
388       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
389 	  && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
390 	++depth;
391 
392       if (DECL_P (type))
393 	{
394 	  if (tree fctx = DECL_FRIEND_CONTEXT (type))
395 	    type = fctx;
396 	  else
397 	    type = CP_DECL_CONTEXT (type);
398 	}
399       else if (LAMBDA_TYPE_P (type) && LAMBDA_TYPE_EXTRA_SCOPE (type))
400 	type = LAMBDA_TYPE_EXTRA_SCOPE (type);
401       else
402 	type = CP_TYPE_CONTEXT (type);
403     }
404 
405   return depth;
406 }
407 
408 /* Return TRUE if NODE instantiates a template that has arguments of
409    its own, be it directly a primary template or indirectly through a
410    partial specializations.  */
411 static bool
instantiates_primary_template_p(tree node)412 instantiates_primary_template_p (tree node)
413 {
414   tree tinfo = get_template_info (node);
415   if (!tinfo)
416     return false;
417 
418   tree tmpl = TI_TEMPLATE (tinfo);
419   if (PRIMARY_TEMPLATE_P (tmpl))
420     return true;
421 
422   if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
423     return false;
424 
425   /* So now we know we have a specialization, but it could be a full
426      or a partial specialization.  To tell which, compare the depth of
427      its template arguments with those of its context.  */
428 
429   tree ctxt = DECL_CONTEXT (tmpl);
430   tree ctinfo = get_template_info (ctxt);
431   if (!ctinfo)
432     return true;
433 
434   return (TMPL_ARGS_DEPTH (TI_ARGS (tinfo))
435 	  > TMPL_ARGS_DEPTH (TI_ARGS (ctinfo)));
436 }
437 
438 /* Subroutine of maybe_begin_member_template_processing.
439    Returns true if processing DECL needs us to push template parms.  */
440 
441 static bool
inline_needs_template_parms(tree decl,bool nsdmi)442 inline_needs_template_parms (tree decl, bool nsdmi)
443 {
444   if (!decl || (!nsdmi && ! DECL_TEMPLATE_INFO (decl)))
445     return false;
446 
447   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
448 	  > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
449 }
450 
451 /* Subroutine of maybe_begin_member_template_processing.
452    Push the template parms in PARMS, starting from LEVELS steps into the
453    chain, and ending at the beginning, since template parms are listed
454    innermost first.  */
455 
456 static void
push_inline_template_parms_recursive(tree parmlist,int levels)457 push_inline_template_parms_recursive (tree parmlist, int levels)
458 {
459   tree parms = TREE_VALUE (parmlist);
460   int i;
461 
462   if (levels > 1)
463     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
464 
465   ++processing_template_decl;
466   current_template_parms
467     = tree_cons (size_int (processing_template_decl),
468 		 parms, current_template_parms);
469   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
470 
471   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
472 	       NULL);
473   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
474     {
475       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
476 
477       if (error_operand_p (parm))
478 	continue;
479 
480       gcc_assert (DECL_P (parm));
481 
482       switch (TREE_CODE (parm))
483 	{
484 	case TYPE_DECL:
485 	case TEMPLATE_DECL:
486 	  pushdecl (parm);
487 	  break;
488 
489 	case PARM_DECL:
490 	  /* Push the CONST_DECL.  */
491 	  pushdecl (TEMPLATE_PARM_DECL (DECL_INITIAL (parm)));
492 	  break;
493 
494 	default:
495 	  gcc_unreachable ();
496 	}
497     }
498 }
499 
500 /* Restore the template parameter context for a member template, a
501    friend template defined in a class definition, or a non-template
502    member of template class.  */
503 
504 void
maybe_begin_member_template_processing(tree decl)505 maybe_begin_member_template_processing (tree decl)
506 {
507   tree parms;
508   int levels = 0;
509   bool nsdmi = TREE_CODE (decl) == FIELD_DECL;
510 
511   if (nsdmi)
512     {
513       tree ctx = DECL_CONTEXT (decl);
514       decl = (CLASSTYPE_TEMPLATE_INFO (ctx)
515 	      /* Disregard full specializations (c++/60999).  */
516 	      && uses_template_parms (ctx)
517 	      ? CLASSTYPE_TI_TEMPLATE (ctx) : NULL_TREE);
518     }
519 
520   if (inline_needs_template_parms (decl, nsdmi))
521     {
522       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
523       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
524 
525       if (DECL_TEMPLATE_SPECIALIZATION (decl))
526 	{
527 	  --levels;
528 	  parms = TREE_CHAIN (parms);
529 	}
530 
531       push_inline_template_parms_recursive (parms, levels);
532     }
533 
534   /* Remember how many levels of template parameters we pushed so that
535      we can pop them later.  */
536   inline_parm_levels.safe_push (levels);
537 }
538 
539 /* Undo the effects of maybe_begin_member_template_processing.  */
540 
541 void
maybe_end_member_template_processing(void)542 maybe_end_member_template_processing (void)
543 {
544   int i;
545   int last;
546 
547   if (inline_parm_levels.length () == 0)
548     return;
549 
550   last = inline_parm_levels.pop ();
551   for (i = 0; i < last; ++i)
552     {
553       --processing_template_decl;
554       current_template_parms = TREE_CHAIN (current_template_parms);
555       poplevel (0, 0, 0);
556     }
557 }
558 
559 /* Return a new template argument vector which contains all of ARGS,
560    but has as its innermost set of arguments the EXTRA_ARGS.  */
561 
562 static tree
add_to_template_args(tree args,tree extra_args)563 add_to_template_args (tree args, tree extra_args)
564 {
565   tree new_args;
566   int extra_depth;
567   int i;
568   int j;
569 
570   if (args == NULL_TREE || extra_args == error_mark_node)
571     return extra_args;
572 
573   extra_depth = TMPL_ARGS_DEPTH (extra_args);
574   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
575 
576   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
577     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
578 
579   for (j = 1; j <= extra_depth; ++j, ++i)
580     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
581 
582   return new_args;
583 }
584 
585 /* Like add_to_template_args, but only the outermost ARGS are added to
586    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
587    (EXTRA_ARGS) levels are added.  This function is used to combine
588    the template arguments from a partial instantiation with the
589    template arguments used to attain the full instantiation from the
590    partial instantiation.  */
591 
592 tree
add_outermost_template_args(tree args,tree extra_args)593 add_outermost_template_args (tree args, tree extra_args)
594 {
595   tree new_args;
596 
597   /* If there are more levels of EXTRA_ARGS than there are ARGS,
598      something very fishy is going on.  */
599   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
600 
601   /* If *all* the new arguments will be the EXTRA_ARGS, just return
602      them.  */
603   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
604     return extra_args;
605 
606   /* For the moment, we make ARGS look like it contains fewer levels.  */
607   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
608 
609   new_args = add_to_template_args (args, extra_args);
610 
611   /* Now, we restore ARGS to its full dimensions.  */
612   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
613 
614   return new_args;
615 }
616 
617 /* Return the N levels of innermost template arguments from the ARGS.  */
618 
619 tree
get_innermost_template_args(tree args,int n)620 get_innermost_template_args (tree args, int n)
621 {
622   tree new_args;
623   int extra_levels;
624   int i;
625 
626   gcc_assert (n >= 0);
627 
628   /* If N is 1, just return the innermost set of template arguments.  */
629   if (n == 1)
630     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
631 
632   /* If we're not removing anything, just return the arguments we were
633      given.  */
634   extra_levels = TMPL_ARGS_DEPTH (args) - n;
635   gcc_assert (extra_levels >= 0);
636   if (extra_levels == 0)
637     return args;
638 
639   /* Make a new set of arguments, not containing the outer arguments.  */
640   new_args = make_tree_vec (n);
641   for (i = 1; i <= n; ++i)
642     SET_TMPL_ARGS_LEVEL (new_args, i,
643 			 TMPL_ARGS_LEVEL (args, i + extra_levels));
644 
645   return new_args;
646 }
647 
648 /* The inverse of get_innermost_template_args: Return all but the innermost
649    EXTRA_LEVELS levels of template arguments from the ARGS.  */
650 
651 static tree
strip_innermost_template_args(tree args,int extra_levels)652 strip_innermost_template_args (tree args, int extra_levels)
653 {
654   tree new_args;
655   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
656   int i;
657 
658   gcc_assert (n >= 0);
659 
660   /* If N is 1, just return the outermost set of template arguments.  */
661   if (n == 1)
662     return TMPL_ARGS_LEVEL (args, 1);
663 
664   /* If we're not removing anything, just return the arguments we were
665      given.  */
666   gcc_assert (extra_levels >= 0);
667   if (extra_levels == 0)
668     return args;
669 
670   /* Make a new set of arguments, not containing the inner arguments.  */
671   new_args = make_tree_vec (n);
672   for (i = 1; i <= n; ++i)
673     SET_TMPL_ARGS_LEVEL (new_args, i,
674 			 TMPL_ARGS_LEVEL (args, i));
675 
676   return new_args;
677 }
678 
679 /* We've got a template header coming up; push to a new level for storing
680    the parms.  */
681 
682 void
begin_template_parm_list(void)683 begin_template_parm_list (void)
684 {
685   /* We use a non-tag-transparent scope here, which causes pushtag to
686      put tags in this scope, rather than in the enclosing class or
687      namespace scope.  This is the right thing, since we want
688      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
689      global template class, push_template_decl handles putting the
690      TEMPLATE_DECL into top-level scope.  For a nested template class,
691      e.g.:
692 
693        template <class T> struct S1 {
694 	 template <class T> struct S2 {};
695        };
696 
697      pushtag contains special code to insert the TEMPLATE_DECL for S2
698      at the right scope.  */
699   begin_scope (sk_template_parms, NULL);
700   ++processing_template_decl;
701   ++processing_template_parmlist;
702   note_template_header (0);
703 
704   /* Add a dummy parameter level while we process the parameter list.  */
705   current_template_parms
706     = tree_cons (size_int (processing_template_decl),
707 		 make_tree_vec (0),
708 		 current_template_parms);
709 }
710 
711 /* This routine is called when a specialization is declared.  If it is
712    invalid to declare a specialization here, an error is reported and
713    false is returned, otherwise this routine will return true.  */
714 
715 static bool
check_specialization_scope(void)716 check_specialization_scope (void)
717 {
718   tree scope = current_scope ();
719 
720   /* [temp.expl.spec]
721 
722      An explicit specialization shall be declared in the namespace of
723      which the template is a member, or, for member templates, in the
724      namespace of which the enclosing class or enclosing class
725      template is a member.  An explicit specialization of a member
726      function, member class or static data member of a class template
727      shall be declared in the namespace of which the class template
728      is a member.  */
729   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
730     {
731       error ("explicit specialization in non-namespace scope %qD", scope);
732       return false;
733     }
734 
735   /* [temp.expl.spec]
736 
737      In an explicit specialization declaration for a member of a class
738      template or a member template that appears in namespace scope,
739      the member template and some of its enclosing class templates may
740      remain unspecialized, except that the declaration shall not
741      explicitly specialize a class member template if its enclosing
742      class templates are not explicitly specialized as well.  */
743   if (current_template_parms)
744     {
745       error ("enclosing class templates are not explicitly specialized");
746       return false;
747     }
748 
749   return true;
750 }
751 
752 /* We've just seen template <>.  */
753 
754 bool
begin_specialization(void)755 begin_specialization (void)
756 {
757   begin_scope (sk_template_spec, NULL);
758   note_template_header (1);
759   return check_specialization_scope ();
760 }
761 
762 /* Called at then end of processing a declaration preceded by
763    template<>.  */
764 
765 void
end_specialization(void)766 end_specialization (void)
767 {
768   finish_scope ();
769   reset_specialization ();
770 }
771 
772 /* Any template <>'s that we have seen thus far are not referring to a
773    function specialization.  */
774 
775 void
reset_specialization(void)776 reset_specialization (void)
777 {
778   processing_specialization = 0;
779   template_header_count = 0;
780 }
781 
782 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
783    it was of the form template <>.  */
784 
785 static void
note_template_header(int specialization)786 note_template_header (int specialization)
787 {
788   processing_specialization = specialization;
789   template_header_count++;
790 }
791 
792 /* We're beginning an explicit instantiation.  */
793 
794 void
begin_explicit_instantiation(void)795 begin_explicit_instantiation (void)
796 {
797   gcc_assert (!processing_explicit_instantiation);
798   processing_explicit_instantiation = true;
799 }
800 
801 
802 void
end_explicit_instantiation(void)803 end_explicit_instantiation (void)
804 {
805   gcc_assert (processing_explicit_instantiation);
806   processing_explicit_instantiation = false;
807 }
808 
809 /* An explicit specialization or partial specialization of TMPL is being
810    declared.  Check that the namespace in which the specialization is
811    occurring is permissible.  Returns false iff it is invalid to
812    specialize TMPL in the current namespace.  */
813 
814 static bool
check_specialization_namespace(tree tmpl)815 check_specialization_namespace (tree tmpl)
816 {
817   tree tpl_ns = decl_namespace_context (tmpl);
818 
819   /* [tmpl.expl.spec]
820 
821      An explicit specialization shall be declared in a namespace enclosing the
822      specialized template. An explicit specialization whose declarator-id is
823      not qualified shall be declared in the nearest enclosing namespace of the
824      template, or, if the namespace is inline (7.3.1), any namespace from its
825      enclosing namespace set.  */
826   if (current_scope() != DECL_CONTEXT (tmpl)
827       && !at_namespace_scope_p ())
828     {
829       error ("specialization of %qD must appear at namespace scope", tmpl);
830       return false;
831     }
832 
833   if (is_nested_namespace (current_namespace, tpl_ns, cxx_dialect < cxx11))
834     /* Same or enclosing namespace.  */
835     return true;
836   else
837     {
838       auto_diagnostic_group d;
839       if (permerror (input_location,
840 		     "specialization of %qD in different namespace", tmpl))
841 	inform (DECL_SOURCE_LOCATION (tmpl),
842 		"  from definition of %q#D", tmpl);
843       return false;
844     }
845 }
846 
847 /* SPEC is an explicit instantiation.  Check that it is valid to
848    perform this explicit instantiation in the current namespace.  */
849 
850 static void
check_explicit_instantiation_namespace(tree spec)851 check_explicit_instantiation_namespace (tree spec)
852 {
853   tree ns;
854 
855   /* DR 275: An explicit instantiation shall appear in an enclosing
856      namespace of its template.  */
857   ns = decl_namespace_context (spec);
858   if (!is_nested_namespace (current_namespace, ns))
859     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
860 	       "(which does not enclose namespace %qD)",
861 	       spec, current_namespace, ns);
862 }
863 
864 /* Returns the type of a template specialization only if that
865    specialization needs to be defined. Otherwise (e.g., if the type has
866    already been defined), the function returns NULL_TREE.  */
867 
868 static tree
maybe_new_partial_specialization(tree type)869 maybe_new_partial_specialization (tree type)
870 {
871   /* An implicit instantiation of an incomplete type implies
872      the definition of a new class template.
873 
874 	template<typename T>
875 	  struct S;
876 
877 	template<typename T>
878 	  struct S<T*>;
879 
880      Here, S<T*> is an implicit instantiation of S whose type
881      is incomplete.  */
882   if (CLASSTYPE_IMPLICIT_INSTANTIATION (type) && !COMPLETE_TYPE_P (type))
883     return type;
884 
885   /* It can also be the case that TYPE is a completed specialization.
886      Continuing the previous example, suppose we also declare:
887 
888 	template<typename T>
889 	  requires Integral<T>
890 	    struct S<T*>;
891 
892      Here, S<T*> refers to the specialization S<T*> defined
893      above. However, we need to differentiate definitions because
894      we intend to define a new partial specialization. In this case,
895      we rely on the fact that the constraints are different for
896      this declaration than that above.
897 
898      Note that we also get here for injected class names and
899      late-parsed template definitions. We must ensure that we
900      do not create new type declarations for those cases.  */
901   if (flag_concepts && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
902     {
903       tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
904       tree args = CLASSTYPE_TI_ARGS (type);
905 
906       /* If there are no template parameters, this cannot be a new
907 	 partial template specialization?  */
908       if (!current_template_parms)
909         return NULL_TREE;
910 
911       /* The injected-class-name is not a new partial specialization.  */
912       if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
913 	return NULL_TREE;
914 
915       /* If the constraints are not the same as those of the primary
916 	 then, we can probably create a new specialization.  */
917       tree type_constr = current_template_constraints ();
918 
919       if (type == TREE_TYPE (tmpl))
920 	{
921 	  tree main_constr = get_constraints (tmpl);
922 	  if (equivalent_constraints (type_constr, main_constr))
923 	    return NULL_TREE;
924 	}
925 
926       /* Also, if there's a pre-existing specialization with matching
927 	 constraints, then this also isn't new.  */
928       tree specs = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
929       while (specs)
930         {
931           tree spec_tmpl = TREE_VALUE (specs);
932           tree spec_args = TREE_PURPOSE (specs);
933           tree spec_constr = get_constraints (spec_tmpl);
934           if (comp_template_args (args, spec_args)
935 	      && equivalent_constraints (type_constr, spec_constr))
936             return NULL_TREE;
937           specs = TREE_CHAIN (specs);
938         }
939 
940       /* Create a new type node (and corresponding type decl)
941 	 for the newly declared specialization.  */
942       tree t = make_class_type (TREE_CODE (type));
943       CLASSTYPE_DECLARED_CLASS (t) = CLASSTYPE_DECLARED_CLASS (type);
944       SET_TYPE_TEMPLATE_INFO (t, build_template_info (tmpl, args));
945 
946       /* We only need a separate type node for storing the definition of this
947 	 partial specialization; uses of S<T*> are unconstrained, so all are
948 	 equivalent.  So keep TYPE_CANONICAL the same.  */
949       TYPE_CANONICAL (t) = TYPE_CANONICAL (type);
950 
951       /* Build the corresponding type decl.  */
952       tree d = create_implicit_typedef (DECL_NAME (tmpl), t);
953       DECL_CONTEXT (d) = TYPE_CONTEXT (t);
954       DECL_SOURCE_LOCATION (d) = input_location;
955       TREE_PRIVATE (d) = (current_access_specifier == access_private_node);
956       TREE_PROTECTED (d) = (current_access_specifier == access_protected_node);
957 
958       return t;
959     }
960 
961   return NULL_TREE;
962 }
963 
964 /* The TYPE is being declared.  If it is a template type, that means it
965    is a partial specialization.  Do appropriate error-checking.  */
966 
967 tree
maybe_process_partial_specialization(tree type)968 maybe_process_partial_specialization (tree type)
969 {
970   tree context;
971 
972   if (type == error_mark_node)
973     return error_mark_node;
974 
975   /* A lambda that appears in specialization context is not itself a
976      specialization.  */
977   if (CLASS_TYPE_P (type) && CLASSTYPE_LAMBDA_EXPR (type))
978     return type;
979 
980   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
981     {
982       error ("name of class shadows template template parameter %qD",
983 	     TYPE_NAME (type));
984       return error_mark_node;
985     }
986 
987   context = TYPE_CONTEXT (type);
988 
989   if (TYPE_ALIAS_P (type))
990     {
991       tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (type);
992 
993       if (tinfo && DECL_ALIAS_TEMPLATE_P (TI_TEMPLATE (tinfo)))
994 	error ("specialization of alias template %qD",
995 	       TI_TEMPLATE (tinfo));
996       else
997 	error ("explicit specialization of non-template %qT", type);
998       return error_mark_node;
999     }
1000   else if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
1001     {
1002       /* This is for ordinary explicit specialization and partial
1003 	 specialization of a template class such as:
1004 
1005 	   template <> class C<int>;
1006 
1007 	 or:
1008 
1009 	   template <class T> class C<T*>;
1010 
1011 	 Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
1012 
1013       if (tree t = maybe_new_partial_specialization (type))
1014 	{
1015 	  if (!check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (t))
1016 	      && !at_namespace_scope_p ())
1017 	    return error_mark_node;
1018 	  SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (t);
1019 	  DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (t)) = input_location;
1020 	  if (processing_template_decl)
1021 	    {
1022 	      tree decl = push_template_decl (TYPE_MAIN_DECL (t));
1023 	      if (decl == error_mark_node)
1024 		return error_mark_node;
1025 	      return TREE_TYPE (decl);
1026 	    }
1027 	}
1028       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
1029 	error ("specialization of %qT after instantiation", type);
1030       else if (errorcount && !processing_specialization
1031 	        && CLASSTYPE_TEMPLATE_SPECIALIZATION (type)
1032 	       && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
1033 	/* Trying to define a specialization either without a template<> header
1034 	   or in an inappropriate place.  We've already given an error, so just
1035 	   bail now so we don't actually define the specialization.  */
1036 	return error_mark_node;
1037     }
1038   else if (CLASS_TYPE_P (type)
1039 	   && !CLASSTYPE_USE_TEMPLATE (type)
1040 	   && CLASSTYPE_TEMPLATE_INFO (type)
1041 	   && context && CLASS_TYPE_P (context)
1042 	   && CLASSTYPE_TEMPLATE_INFO (context))
1043     {
1044       /* This is for an explicit specialization of member class
1045 	 template according to [temp.expl.spec/18]:
1046 
1047 	   template <> template <class U> class C<int>::D;
1048 
1049 	 The context `C<int>' must be an implicit instantiation.
1050 	 Otherwise this is just a member class template declared
1051 	 earlier like:
1052 
1053 	   template <> class C<int> { template <class U> class D; };
1054 	   template <> template <class U> class C<int>::D;
1055 
1056 	 In the first case, `C<int>::D' is a specialization of `C<T>::D'
1057 	 while in the second case, `C<int>::D' is a primary template
1058 	 and `C<T>::D' may not exist.  */
1059 
1060       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
1061 	  && !COMPLETE_TYPE_P (type))
1062 	{
1063 	  tree t;
1064 	  tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
1065 
1066 	  if (current_namespace
1067 	      != decl_namespace_context (tmpl))
1068 	    {
1069 	      if (permerror (input_location,
1070 			     "specialization of %qD in different namespace",
1071 			     type))
1072 		inform (DECL_SOURCE_LOCATION (tmpl),
1073 			"from definition of %q#D", tmpl);
1074 	    }
1075 
1076 	  /* Check for invalid specialization after instantiation:
1077 
1078 	       template <> template <> class C<int>::D<int>;
1079 	       template <> template <class U> class C<int>::D;  */
1080 
1081 	  for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
1082 	       t; t = TREE_CHAIN (t))
1083 	    {
1084 	      tree inst = TREE_VALUE (t);
1085 	      if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst)
1086 		  || !COMPLETE_OR_OPEN_TYPE_P (inst))
1087 		{
1088 		  /* We already have a full specialization of this partial
1089 		     instantiation, or a full specialization has been
1090 		     looked up but not instantiated.  Reassign it to the
1091 		     new member specialization template.  */
1092 		  spec_entry elt;
1093 		  spec_entry *entry;
1094 
1095 		  elt.tmpl = most_general_template (tmpl);
1096 		  elt.args = CLASSTYPE_TI_ARGS (inst);
1097 		  elt.spec = inst;
1098 
1099 		  type_specializations->remove_elt (&elt);
1100 
1101 		  elt.tmpl = tmpl;
1102 		  CLASSTYPE_TI_ARGS (inst)
1103 		    = elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
1104 
1105 		  spec_entry **slot
1106 		    = type_specializations->find_slot (&elt, INSERT);
1107 		  entry = ggc_alloc<spec_entry> ();
1108 		  *entry = elt;
1109 		  *slot = entry;
1110 		}
1111 	      else
1112 		/* But if we've had an implicit instantiation, that's a
1113 		   problem ([temp.expl.spec]/6).  */
1114 		error ("specialization %qT after instantiation %qT",
1115 		       type, inst);
1116 	    }
1117 
1118 	  /* Mark TYPE as a specialization.  And as a result, we only
1119 	     have one level of template argument for the innermost
1120 	     class template.  */
1121 	  SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1122 	  DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1123 	  CLASSTYPE_TI_ARGS (type)
1124 	    = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
1125 	}
1126     }
1127   else if (processing_specialization)
1128     {
1129        /* Someday C++0x may allow for enum template specialization.  */
1130       if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
1131 	  && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
1132 	pedwarn (input_location, OPT_Wpedantic, "template specialization "
1133 		 "of %qD not allowed by ISO C++", type);
1134       else
1135 	{
1136 	  error ("explicit specialization of non-template %qT", type);
1137 	  return error_mark_node;
1138 	}
1139     }
1140 
1141   return type;
1142 }
1143 
1144 /* Returns nonzero if we can optimize the retrieval of specializations
1145    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
1146    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
1147 
1148 static inline bool
optimize_specialization_lookup_p(tree tmpl)1149 optimize_specialization_lookup_p (tree tmpl)
1150 {
1151   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
1152 	  && DECL_CLASS_SCOPE_P (tmpl)
1153 	  /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
1154 	     parameter.  */
1155 	  && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
1156 	  /* The optimized lookup depends on the fact that the
1157 	     template arguments for the member function template apply
1158 	     purely to the containing class, which is not true if the
1159 	     containing class is an explicit or partial
1160 	     specialization.  */
1161 	  && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
1162 	  && !DECL_MEMBER_TEMPLATE_P (tmpl)
1163 	  && !DECL_CONV_FN_P (tmpl)
1164 	  /* It is possible to have a template that is not a member
1165 	     template and is not a member of a template class:
1166 
1167 	     template <typename T>
1168 	     struct S { friend A::f(); };
1169 
1170 	     Here, the friend function is a template, but the context does
1171 	     not have template information.  The optimized lookup relies
1172 	     on having ARGS be the template arguments for both the class
1173 	     and the function template.  */
1174 	  && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
1175 }
1176 
1177 /* Make sure ARGS doesn't use any inappropriate typedefs; we should have
1178    gone through coerce_template_parms by now.  */
1179 
1180 static void
verify_unstripped_args_1(tree inner)1181 verify_unstripped_args_1 (tree inner)
1182 {
1183   for (int i = 0; i < TREE_VEC_LENGTH (inner); ++i)
1184     {
1185       tree arg = TREE_VEC_ELT (inner, i);
1186       if (TREE_CODE (arg) == TEMPLATE_DECL)
1187 	/* OK */;
1188       else if (TYPE_P (arg))
1189 	gcc_assert (strip_typedefs (arg, NULL) == arg);
1190       else if (ARGUMENT_PACK_P (arg))
1191 	verify_unstripped_args_1 (ARGUMENT_PACK_ARGS (arg));
1192       else if (strip_typedefs (TREE_TYPE (arg), NULL) != TREE_TYPE (arg))
1193 	/* Allow typedefs on the type of a non-type argument, since a
1194 	   parameter can have them.  */;
1195       else
1196 	gcc_assert (strip_typedefs_expr (arg, NULL) == arg);
1197     }
1198 }
1199 
1200 static void
verify_unstripped_args(tree args)1201 verify_unstripped_args (tree args)
1202 {
1203   ++processing_template_decl;
1204   if (!any_dependent_template_arguments_p (args))
1205     verify_unstripped_args_1 (INNERMOST_TEMPLATE_ARGS (args));
1206   --processing_template_decl;
1207 }
1208 
1209 /* Retrieve the specialization (in the sense of [temp.spec] - a
1210    specialization is either an instantiation or an explicit
1211    specialization) of TMPL for the given template ARGS.  If there is
1212    no such specialization, return NULL_TREE.  The ARGS are a vector of
1213    arguments, or a vector of vectors of arguments, in the case of
1214    templates with more than one level of parameters.
1215 
1216    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
1217    then we search for a partial specialization matching ARGS.  This
1218    parameter is ignored if TMPL is not a class template.
1219 
1220    We can also look up a FIELD_DECL, if it is a lambda capture pack; the
1221    result is a NONTYPE_ARGUMENT_PACK.  */
1222 
1223 static tree
retrieve_specialization(tree tmpl,tree args,hashval_t hash)1224 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1225 {
1226   if (tmpl == NULL_TREE)
1227     return NULL_TREE;
1228 
1229   if (args == error_mark_node)
1230     return NULL_TREE;
1231 
1232   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL
1233 	      || TREE_CODE (tmpl) == FIELD_DECL);
1234 
1235   /* There should be as many levels of arguments as there are
1236      levels of parameters.  */
1237   gcc_assert (TMPL_ARGS_DEPTH (args)
1238 	      == (TREE_CODE (tmpl) == TEMPLATE_DECL
1239 		  ? TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl))
1240 		  : template_class_depth (DECL_CONTEXT (tmpl))));
1241 
1242   if (flag_checking)
1243     verify_unstripped_args (args);
1244 
1245   /* Lambda functions in templates aren't instantiated normally, but through
1246      tsubst_lambda_expr.  */
1247   if (lambda_fn_in_template_p (tmpl))
1248     return NULL_TREE;
1249 
1250   if (optimize_specialization_lookup_p (tmpl))
1251     {
1252       /* The template arguments actually apply to the containing
1253 	 class.  Find the class specialization with those
1254 	 arguments.  */
1255       tree class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
1256       tree class_specialization
1257 	= retrieve_specialization (class_template, args, 0);
1258       if (!class_specialization)
1259 	return NULL_TREE;
1260 
1261       /* Find the instance of TMPL.  */
1262       tree fns = get_class_binding (class_specialization, DECL_NAME (tmpl));
1263       for (ovl_iterator iter (fns); iter; ++iter)
1264 	{
1265 	  tree fn = *iter;
1266 	  if (tree ti = get_template_info (fn))
1267 	    if (TI_TEMPLATE (ti) == tmpl
1268 		/* using-declarations can bring in a different
1269 		   instantiation of tmpl as a member of a different
1270 		   instantiation of tmpl's class.  We don't want those
1271 		   here.  */
1272 		&& DECL_CONTEXT (fn) == class_specialization)
1273 	      return fn;
1274 	}
1275       return NULL_TREE;
1276     }
1277   else
1278     {
1279       spec_entry *found;
1280       spec_entry elt;
1281       hash_table<spec_hasher> *specializations;
1282 
1283       elt.tmpl = tmpl;
1284       elt.args = args;
1285       elt.spec = NULL_TREE;
1286 
1287       if (DECL_CLASS_TEMPLATE_P (tmpl))
1288 	specializations = type_specializations;
1289       else
1290 	specializations = decl_specializations;
1291 
1292       if (hash == 0)
1293 	hash = spec_hasher::hash (&elt);
1294       found = specializations->find_with_hash (&elt, hash);
1295       if (found)
1296 	return found->spec;
1297     }
1298 
1299   return NULL_TREE;
1300 }
1301 
1302 /* Like retrieve_specialization, but for local declarations.  */
1303 
1304 tree
retrieve_local_specialization(tree tmpl)1305 retrieve_local_specialization (tree tmpl)
1306 {
1307   if (local_specializations == NULL)
1308     return NULL_TREE;
1309 
1310   tree *slot = local_specializations->get (tmpl);
1311   return slot ? *slot : NULL_TREE;
1312 }
1313 
1314 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1315 
1316 int
is_specialization_of(tree decl,tree tmpl)1317 is_specialization_of (tree decl, tree tmpl)
1318 {
1319   tree t;
1320 
1321   if (TREE_CODE (decl) == FUNCTION_DECL)
1322     {
1323       for (t = decl;
1324 	   t != NULL_TREE;
1325 	   t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1326 	if (t == tmpl)
1327 	  return 1;
1328     }
1329   else
1330     {
1331       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1332 
1333       for (t = TREE_TYPE (decl);
1334 	   t != NULL_TREE;
1335 	   t = CLASSTYPE_USE_TEMPLATE (t)
1336 	     ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1337 	if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1338 	  return 1;
1339     }
1340 
1341   return 0;
1342 }
1343 
1344 /* Returns nonzero iff DECL is a specialization of friend declaration
1345    FRIEND_DECL according to [temp.friend].  */
1346 
1347 bool
is_specialization_of_friend(tree decl,tree friend_decl)1348 is_specialization_of_friend (tree decl, tree friend_decl)
1349 {
1350   bool need_template = true;
1351   int template_depth;
1352 
1353   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1354 	      || TREE_CODE (decl) == TYPE_DECL);
1355 
1356   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1357      of a template class, we want to check if DECL is a specialization
1358      if this.  */
1359   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1360       && DECL_TEMPLATE_INFO (friend_decl)
1361       && !DECL_USE_TEMPLATE (friend_decl))
1362     {
1363       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1364       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1365       need_template = false;
1366     }
1367   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1368 	   && !PRIMARY_TEMPLATE_P (friend_decl))
1369     need_template = false;
1370 
1371   /* There is nothing to do if this is not a template friend.  */
1372   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1373     return false;
1374 
1375   if (is_specialization_of (decl, friend_decl))
1376     return true;
1377 
1378   /* [temp.friend/6]
1379      A member of a class template may be declared to be a friend of a
1380      non-template class.  In this case, the corresponding member of
1381      every specialization of the class template is a friend of the
1382      class granting friendship.
1383 
1384      For example, given a template friend declaration
1385 
1386        template <class T> friend void A<T>::f();
1387 
1388      the member function below is considered a friend
1389 
1390        template <> struct A<int> {
1391 	 void f();
1392        };
1393 
1394      For this type of template friend, TEMPLATE_DEPTH below will be
1395      nonzero.  To determine if DECL is a friend of FRIEND, we first
1396      check if the enclosing class is a specialization of another.  */
1397 
1398   template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1399   if (template_depth
1400       && DECL_CLASS_SCOPE_P (decl)
1401       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1402 			       CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1403     {
1404       /* Next, we check the members themselves.  In order to handle
1405 	 a few tricky cases, such as when FRIEND_DECL's are
1406 
1407 	   template <class T> friend void A<T>::g(T t);
1408 	   template <class T> template <T t> friend void A<T>::h();
1409 
1410 	 and DECL's are
1411 
1412 	   void A<int>::g(int);
1413 	   template <int> void A<int>::h();
1414 
1415 	 we need to figure out ARGS, the template arguments from
1416 	 the context of DECL.  This is required for template substitution
1417 	 of `T' in the function parameter of `g' and template parameter
1418 	 of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1419 
1420       tree context = DECL_CONTEXT (decl);
1421       tree args = NULL_TREE;
1422       int current_depth = 0;
1423 
1424       while (current_depth < template_depth)
1425 	{
1426 	  if (CLASSTYPE_TEMPLATE_INFO (context))
1427 	    {
1428 	      if (current_depth == 0)
1429 		args = TYPE_TI_ARGS (context);
1430 	      else
1431 		args = add_to_template_args (TYPE_TI_ARGS (context), args);
1432 	      current_depth++;
1433 	    }
1434 	  context = TYPE_CONTEXT (context);
1435 	}
1436 
1437       if (TREE_CODE (decl) == FUNCTION_DECL)
1438 	{
1439 	  bool is_template;
1440 	  tree friend_type;
1441 	  tree decl_type;
1442 	  tree friend_args_type;
1443 	  tree decl_args_type;
1444 
1445 	  /* Make sure that both DECL and FRIEND_DECL are templates or
1446 	     non-templates.  */
1447 	  is_template = DECL_TEMPLATE_INFO (decl)
1448 			&& PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1449 	  if (need_template ^ is_template)
1450 	    return false;
1451 	  else if (is_template)
1452 	    {
1453 	      /* If both are templates, check template parameter list.  */
1454 	      tree friend_parms
1455 		= tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1456 					 args, tf_none);
1457 	      if (!comp_template_parms
1458 		     (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1459 		      friend_parms))
1460 		return false;
1461 
1462 	      decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1463 	    }
1464 	  else
1465 	    decl_type = TREE_TYPE (decl);
1466 
1467 	  friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1468 					      tf_none, NULL_TREE);
1469 	  if (friend_type == error_mark_node)
1470 	    return false;
1471 
1472 	  /* Check if return types match.  */
1473 	  if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1474 	    return false;
1475 
1476 	  /* Check if function parameter types match, ignoring the
1477 	     `this' parameter.  */
1478 	  friend_args_type = TYPE_ARG_TYPES (friend_type);
1479 	  decl_args_type = TYPE_ARG_TYPES (decl_type);
1480 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1481 	    friend_args_type = TREE_CHAIN (friend_args_type);
1482 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1483 	    decl_args_type = TREE_CHAIN (decl_args_type);
1484 
1485 	  return compparms (decl_args_type, friend_args_type);
1486 	}
1487       else
1488 	{
1489 	  /* DECL is a TYPE_DECL */
1490 	  bool is_template;
1491 	  tree decl_type = TREE_TYPE (decl);
1492 
1493 	  /* Make sure that both DECL and FRIEND_DECL are templates or
1494 	     non-templates.  */
1495 	  is_template
1496 	    = CLASSTYPE_TEMPLATE_INFO (decl_type)
1497 	      && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1498 
1499 	  if (need_template ^ is_template)
1500 	    return false;
1501 	  else if (is_template)
1502 	    {
1503 	      tree friend_parms;
1504 	      /* If both are templates, check the name of the two
1505 		 TEMPLATE_DECL's first because is_friend didn't.  */
1506 	      if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1507 		  != DECL_NAME (friend_decl))
1508 		return false;
1509 
1510 	      /* Now check template parameter list.  */
1511 	      friend_parms
1512 		= tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1513 					 args, tf_none);
1514 	      return comp_template_parms
1515 		(DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1516 		 friend_parms);
1517 	    }
1518 	  else
1519 	    return (DECL_NAME (decl)
1520 		    == DECL_NAME (friend_decl));
1521 	}
1522     }
1523   return false;
1524 }
1525 
1526 /* Register the specialization SPEC as a specialization of TMPL with
1527    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1528    is actually just a friend declaration.  ATTRLIST is the list of
1529    attributes that the specialization is declared with or NULL when
1530    it isn't.  Returns SPEC, or an equivalent prior declaration, if
1531    available.
1532 
1533    We also store instantiations of field packs in the hash table, even
1534    though they are not themselves templates, to make lookup easier.  */
1535 
1536 static tree
register_specialization(tree spec,tree tmpl,tree args,bool is_friend,hashval_t hash)1537 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1538 			 hashval_t hash)
1539 {
1540   tree fn;
1541   spec_entry **slot = NULL;
1542   spec_entry elt;
1543 
1544   gcc_assert ((TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec))
1545 	      || (TREE_CODE (tmpl) == FIELD_DECL
1546 		  && TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK));
1547 
1548   if (TREE_CODE (spec) == FUNCTION_DECL
1549       && uses_template_parms (DECL_TI_ARGS (spec)))
1550     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1551        register it; we want the corresponding TEMPLATE_DECL instead.
1552        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1553        the more obvious `uses_template_parms (spec)' to avoid problems
1554        with default function arguments.  In particular, given
1555        something like this:
1556 
1557 	  template <class T> void f(T t1, T t = T())
1558 
1559        the default argument expression is not substituted for in an
1560        instantiation unless and until it is actually needed.  */
1561     return spec;
1562 
1563   if (optimize_specialization_lookup_p (tmpl))
1564     /* We don't put these specializations in the hash table, but we might
1565        want to give an error about a mismatch.  */
1566     fn = retrieve_specialization (tmpl, args, 0);
1567   else
1568     {
1569       elt.tmpl = tmpl;
1570       elt.args = args;
1571       elt.spec = spec;
1572 
1573       if (hash == 0)
1574 	hash = spec_hasher::hash (&elt);
1575 
1576       slot =
1577 	decl_specializations->find_slot_with_hash (&elt, hash, INSERT);
1578       if (*slot)
1579 	fn = ((spec_entry *) *slot)->spec;
1580       else
1581 	fn = NULL_TREE;
1582     }
1583 
1584   /* We can sometimes try to re-register a specialization that we've
1585      already got.  In particular, regenerate_decl_from_template calls
1586      duplicate_decls which will update the specialization list.  But,
1587      we'll still get called again here anyhow.  It's more convenient
1588      to simply allow this than to try to prevent it.  */
1589   if (fn == spec)
1590     return spec;
1591   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1592     {
1593       if (DECL_TEMPLATE_INSTANTIATION (fn))
1594 	{
1595 	  if (DECL_ODR_USED (fn)
1596 	      || DECL_EXPLICIT_INSTANTIATION (fn))
1597 	    {
1598 	      error ("specialization of %qD after instantiation",
1599 		     fn);
1600 	      return error_mark_node;
1601 	    }
1602 	  else
1603 	    {
1604 	      tree clone;
1605 	      /* This situation should occur only if the first
1606 		 specialization is an implicit instantiation, the
1607 		 second is an explicit specialization, and the
1608 		 implicit instantiation has not yet been used.  That
1609 		 situation can occur if we have implicitly
1610 		 instantiated a member function and then specialized
1611 		 it later.
1612 
1613 		 We can also wind up here if a friend declaration that
1614 		 looked like an instantiation turns out to be a
1615 		 specialization:
1616 
1617 		   template <class T> void foo(T);
1618 		   class S { friend void foo<>(int) };
1619 		   template <> void foo(int);
1620 
1621 		 We transform the existing DECL in place so that any
1622 		 pointers to it become pointers to the updated
1623 		 declaration.
1624 
1625 		 If there was a definition for the template, but not
1626 		 for the specialization, we want this to look as if
1627 		 there were no definition, and vice versa.  */
1628 	      DECL_INITIAL (fn) = NULL_TREE;
1629 	      duplicate_decls (spec, fn, is_friend);
1630 	      /* The call to duplicate_decls will have applied
1631 		 [temp.expl.spec]:
1632 
1633 		   An explicit specialization of a function template
1634 		   is inline only if it is explicitly declared to be,
1635 		   and independently of whether its function template
1636 		   is.
1637 
1638 		to the primary function; now copy the inline bits to
1639 		the various clones.  */
1640 	      FOR_EACH_CLONE (clone, fn)
1641 		{
1642 		  DECL_DECLARED_INLINE_P (clone)
1643 		    = DECL_DECLARED_INLINE_P (fn);
1644 		  DECL_SOURCE_LOCATION (clone)
1645 		    = DECL_SOURCE_LOCATION (fn);
1646 		  DECL_DELETED_FN (clone)
1647 		    = DECL_DELETED_FN (fn);
1648 		}
1649 	      check_specialization_namespace (tmpl);
1650 
1651 	      return fn;
1652 	    }
1653 	}
1654       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1655 	{
1656 	  tree dd = duplicate_decls (spec, fn, is_friend);
1657 	  if (dd == error_mark_node)
1658 	    /* We've already complained in duplicate_decls.  */
1659 	    return error_mark_node;
1660 
1661 	  if (dd == NULL_TREE && DECL_INITIAL (spec))
1662 	    /* Dup decl failed, but this is a new definition. Set the
1663 	       line number so any errors match this new
1664 	       definition.  */
1665 	    DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1666 
1667 	  return fn;
1668 	}
1669     }
1670   else if (fn)
1671     return duplicate_decls (spec, fn, is_friend);
1672 
1673   /* A specialization must be declared in the same namespace as the
1674      template it is specializing.  */
1675   if (DECL_P (spec) && DECL_TEMPLATE_SPECIALIZATION (spec)
1676       && !check_specialization_namespace (tmpl))
1677     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1678 
1679   if (slot != NULL /* !optimize_specialization_lookup_p (tmpl) */)
1680     {
1681       spec_entry *entry = ggc_alloc<spec_entry> ();
1682       gcc_assert (tmpl && args && spec);
1683       *entry = elt;
1684       *slot = entry;
1685       if ((TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1686 	   && PRIMARY_TEMPLATE_P (tmpl)
1687 	   && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1688 	  || variable_template_p (tmpl))
1689 	/* If TMPL is a forward declaration of a template function, keep a list
1690 	   of all specializations in case we need to reassign them to a friend
1691 	   template later in tsubst_friend_function.
1692 
1693 	   Also keep a list of all variable template instantiations so that
1694 	   process_partial_specialization can check whether a later partial
1695 	   specialization would have used it.  */
1696 	DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1697 	  = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1698     }
1699 
1700   return spec;
1701 }
1702 
1703 /* Returns true iff two spec_entry nodes are equivalent.  */
1704 
1705 int comparing_specializations;
1706 
1707 bool
equal(spec_entry * e1,spec_entry * e2)1708 spec_hasher::equal (spec_entry *e1, spec_entry *e2)
1709 {
1710   int equal;
1711 
1712   ++comparing_specializations;
1713   equal = (e1->tmpl == e2->tmpl
1714 	   && comp_template_args (e1->args, e2->args));
1715   if (equal && flag_concepts
1716       /* tmpl could be a FIELD_DECL for a capture pack.  */
1717       && TREE_CODE (e1->tmpl) == TEMPLATE_DECL
1718       && VAR_P (DECL_TEMPLATE_RESULT (e1->tmpl))
1719       && uses_template_parms (e1->args))
1720     {
1721       /* Partial specializations of a variable template can be distinguished by
1722 	 constraints.  */
1723       tree c1 = e1->spec ? get_constraints (e1->spec) : NULL_TREE;
1724       tree c2 = e2->spec ? get_constraints (e2->spec) : NULL_TREE;
1725       equal = equivalent_constraints (c1, c2);
1726     }
1727   --comparing_specializations;
1728 
1729   return equal;
1730 }
1731 
1732 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1733 
1734 static hashval_t
hash_tmpl_and_args(tree tmpl,tree args)1735 hash_tmpl_and_args (tree tmpl, tree args)
1736 {
1737   hashval_t val = iterative_hash_object (DECL_UID (tmpl), 0);
1738   return iterative_hash_template_arg (args, val);
1739 }
1740 
1741 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1742    ignoring SPEC.  */
1743 
1744 hashval_t
hash(spec_entry * e)1745 spec_hasher::hash (spec_entry *e)
1746 {
1747   return hash_tmpl_and_args (e->tmpl, e->args);
1748 }
1749 
1750 /* Recursively calculate a hash value for a template argument ARG, for use
1751    in the hash tables of template specializations.   We must be
1752    careful to (at least) skip the same entities template_args_equal
1753    does.  */
1754 
1755 hashval_t
iterative_hash_template_arg(tree arg,hashval_t val)1756 iterative_hash_template_arg (tree arg, hashval_t val)
1757 {
1758   if (arg == NULL_TREE)
1759     return iterative_hash_object (arg, val);
1760 
1761   if (!TYPE_P (arg))
1762     /* Strip nop-like things, but not the same as STRIP_NOPS.  */
1763     while (CONVERT_EXPR_P (arg)
1764 	   || TREE_CODE (arg) == NON_LVALUE_EXPR
1765 	   || class_nttp_const_wrapper_p (arg))
1766       arg = TREE_OPERAND (arg, 0);
1767 
1768   enum tree_code code = TREE_CODE (arg);
1769 
1770   val = iterative_hash_object (code, val);
1771 
1772   switch (code)
1773     {
1774     case ARGUMENT_PACK_SELECT:
1775       gcc_unreachable ();
1776 
1777     case ERROR_MARK:
1778       return val;
1779 
1780     case IDENTIFIER_NODE:
1781       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1782 
1783     case TREE_VEC:
1784       for (int i = 0, len = TREE_VEC_LENGTH (arg); i < len; ++i)
1785 	val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1786       return val;
1787 
1788     case TYPE_PACK_EXPANSION:
1789     case EXPR_PACK_EXPANSION:
1790       val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1791       return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1792 
1793     case TYPE_ARGUMENT_PACK:
1794     case NONTYPE_ARGUMENT_PACK:
1795       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1796 
1797     case TREE_LIST:
1798       for (; arg; arg = TREE_CHAIN (arg))
1799 	val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1800       return val;
1801 
1802     case OVERLOAD:
1803       for (lkp_iterator iter (arg); iter; ++iter)
1804 	val = iterative_hash_template_arg (*iter, val);
1805       return val;
1806 
1807     case CONSTRUCTOR:
1808       {
1809 	tree field, value;
1810 	unsigned i;
1811 	iterative_hash_template_arg (TREE_TYPE (arg), val);
1812 	FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1813 	  {
1814 	    val = iterative_hash_template_arg (field, val);
1815 	    val = iterative_hash_template_arg (value, val);
1816 	  }
1817 	return val;
1818       }
1819 
1820     case PARM_DECL:
1821       if (!DECL_ARTIFICIAL (arg))
1822 	{
1823 	  val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1824 	  val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1825 	}
1826       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1827 
1828     case TARGET_EXPR:
1829       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1830 
1831     case PTRMEM_CST:
1832       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1833       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1834 
1835     case TEMPLATE_PARM_INDEX:
1836       val = iterative_hash_template_arg
1837 	(TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1838       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1839       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1840 
1841     case TRAIT_EXPR:
1842       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1843       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1844       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1845 
1846     case BASELINK:
1847       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1848 					 val);
1849       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1850 					  val);
1851 
1852     case MODOP_EXPR:
1853       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1854       code = TREE_CODE (TREE_OPERAND (arg, 1));
1855       val = iterative_hash_object (code, val);
1856       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1857 
1858     case LAMBDA_EXPR:
1859       /* [temp.over.link] Two lambda-expressions are never considered
1860 	 equivalent.
1861 
1862          So just hash the closure type.  */
1863       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1864 
1865     case CAST_EXPR:
1866     case IMPLICIT_CONV_EXPR:
1867     case STATIC_CAST_EXPR:
1868     case REINTERPRET_CAST_EXPR:
1869     case CONST_CAST_EXPR:
1870     case DYNAMIC_CAST_EXPR:
1871     case NEW_EXPR:
1872       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1873       /* Now hash operands as usual.  */
1874       break;
1875 
1876     case CALL_EXPR:
1877       {
1878 	tree fn = CALL_EXPR_FN (arg);
1879 	if (tree name = dependent_name (fn))
1880 	  {
1881 	    if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
1882 	      val = iterative_hash_template_arg (TREE_OPERAND (fn, 1), val);
1883 	    fn = name;
1884 	  }
1885 	val = iterative_hash_template_arg (fn, val);
1886 	call_expr_arg_iterator ai;
1887 	for (tree x = first_call_expr_arg (arg, &ai); x;
1888 	     x = next_call_expr_arg (&ai))
1889 	  val = iterative_hash_template_arg (x, val);
1890 	return val;
1891       }
1892 
1893     default:
1894       break;
1895     }
1896 
1897   char tclass = TREE_CODE_CLASS (code);
1898   switch (tclass)
1899     {
1900     case tcc_type:
1901       if (tree ats = alias_template_specialization_p (arg, nt_transparent))
1902 	{
1903 	  // We want an alias specialization that survived strip_typedefs
1904 	  // to hash differently from its TYPE_CANONICAL, to avoid hash
1905 	  // collisions that compare as different in template_args_equal.
1906 	  // These could be dependent specializations that strip_typedefs
1907 	  // left alone, or untouched specializations because
1908 	  // coerce_template_parms returns the unconverted template
1909 	  // arguments if it sees incomplete argument packs.
1910 	  tree ti = TYPE_ALIAS_TEMPLATE_INFO (ats);
1911 	  return hash_tmpl_and_args (TI_TEMPLATE (ti), TI_ARGS (ti));
1912 	}
1913 
1914       switch (TREE_CODE (arg))
1915 	{
1916 	case TEMPLATE_TEMPLATE_PARM:
1917 	  {
1918 	    tree tpi = TEMPLATE_TYPE_PARM_INDEX (arg);
1919 
1920 	    /* Do not recurse with TPI directly, as that is unbounded
1921 	       recursion.  */
1922 	    val = iterative_hash_object (TEMPLATE_PARM_LEVEL (tpi), val);
1923 	    val = iterative_hash_object (TEMPLATE_PARM_IDX (tpi), val);
1924 	  }
1925 	  break;
1926 
1927 	case  DECLTYPE_TYPE:
1928 	  val = iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1929 	  break;
1930 
1931 	default:
1932 	  if (tree canonical = TYPE_CANONICAL (arg))
1933 	    val = iterative_hash_object (TYPE_HASH (canonical), val);
1934 	  break;
1935 	}
1936 
1937       return val;
1938 
1939     case tcc_declaration:
1940     case tcc_constant:
1941       return iterative_hash_expr (arg, val);
1942 
1943     default:
1944       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1945       for (int i = 0, n = cp_tree_operand_length (arg); i < n; ++i)
1946 	val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1947       return val;
1948     }
1949 
1950   gcc_unreachable ();
1951   return 0;
1952 }
1953 
1954 /* Unregister the specialization SPEC as a specialization of TMPL.
1955    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1956    if the SPEC was listed as a specialization of TMPL.
1957 
1958    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1959 
1960 bool
reregister_specialization(tree spec,tree tinfo,tree new_spec)1961 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1962 {
1963   spec_entry *entry;
1964   spec_entry elt;
1965 
1966   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1967   elt.args = TI_ARGS (tinfo);
1968   elt.spec = NULL_TREE;
1969 
1970   entry = decl_specializations->find (&elt);
1971   if (entry != NULL)
1972     {
1973       gcc_assert (entry->spec == spec || entry->spec == new_spec);
1974       gcc_assert (new_spec != NULL_TREE);
1975       entry->spec = new_spec;
1976       return 1;
1977     }
1978 
1979   return 0;
1980 }
1981 
1982 /* Like register_specialization, but for local declarations.  We are
1983    registering SPEC, an instantiation of TMPL.  */
1984 
1985 void
register_local_specialization(tree spec,tree tmpl)1986 register_local_specialization (tree spec, tree tmpl)
1987 {
1988   gcc_assert (tmpl != spec);
1989   local_specializations->put (tmpl, spec);
1990 }
1991 
1992 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1993    specialized class.  */
1994 
1995 bool
explicit_class_specialization_p(tree type)1996 explicit_class_specialization_p (tree type)
1997 {
1998   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1999     return false;
2000   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
2001 }
2002 
2003 /* Print the list of functions at FNS, going through all the overloads
2004    for each element of the list.  Alternatively, FNS cannot be a
2005    TREE_LIST, in which case it will be printed together with all the
2006    overloads.
2007 
2008    MORE and *STR should respectively be FALSE and NULL when the function
2009    is called from the outside.  They are used internally on recursive
2010    calls.  print_candidates manages the two parameters and leaves NULL
2011    in *STR when it ends.  */
2012 
2013 static void
2014 print_candidates_1 (tree fns, char **str, bool more = false)
2015 {
2016   if (TREE_CODE (fns) == TREE_LIST)
2017     for (; fns; fns = TREE_CHAIN (fns))
2018       print_candidates_1 (TREE_VALUE (fns), str, more || TREE_CHAIN (fns));
2019   else
2020     for (lkp_iterator iter (fns); iter;)
2021       {
2022 	tree cand = *iter;
2023 	++iter;
2024 
2025 	const char *pfx = *str;
2026 	if (!pfx)
2027 	  {
2028 	    if (more || iter)
2029 	      pfx = _("candidates are:");
2030 	    else
2031 	      pfx = _("candidate is:");
2032 	    *str = get_spaces (pfx);
2033 	  }
2034 	inform (DECL_SOURCE_LOCATION (cand), "%s %#qD", pfx, cand);
2035       }
2036 }
2037 
2038 /* Print the list of candidate FNS in an error message.  FNS can also
2039    be a TREE_LIST of non-functions in the case of an ambiguous lookup.  */
2040 
2041 void
print_candidates(tree fns)2042 print_candidates (tree fns)
2043 {
2044   char *str = NULL;
2045   print_candidates_1 (fns, &str);
2046   free (str);
2047 }
2048 
2049 /* Get a (possibly) constrained template declaration for the
2050    purpose of ordering candidates.  */
2051 static tree
get_template_for_ordering(tree list)2052 get_template_for_ordering (tree list)
2053 {
2054   gcc_assert (TREE_CODE (list) == TREE_LIST);
2055   tree f = TREE_VALUE (list);
2056   if (tree ti = DECL_TEMPLATE_INFO (f))
2057     return TI_TEMPLATE (ti);
2058   return f;
2059 }
2060 
2061 /* Among candidates having the same signature, return the
2062    most constrained or NULL_TREE if there is no best candidate.
2063    If the signatures of candidates vary (e.g., template
2064    specialization vs. member function), then there can be no
2065    most constrained.
2066 
2067    Note that we don't compare constraints on the functions
2068    themselves, but rather those of their templates. */
2069 static tree
most_constrained_function(tree candidates)2070 most_constrained_function (tree candidates)
2071 {
2072   // Try to find the best candidate in a first pass.
2073   tree champ = candidates;
2074   for (tree c = TREE_CHAIN (champ); c; c = TREE_CHAIN (c))
2075     {
2076       int winner = more_constrained (get_template_for_ordering (champ),
2077                                      get_template_for_ordering (c));
2078       if (winner == -1)
2079         champ = c; // The candidate is more constrained
2080       else if (winner == 0)
2081         return NULL_TREE; // Neither is more constrained
2082     }
2083 
2084   // Verify that the champ is better than previous candidates.
2085   for (tree c = candidates; c != champ; c = TREE_CHAIN (c)) {
2086     if (!more_constrained (get_template_for_ordering (champ),
2087                            get_template_for_ordering (c)))
2088       return NULL_TREE;
2089   }
2090 
2091   return champ;
2092 }
2093 
2094 
2095 /* Returns the template (one of the functions given by TEMPLATE_ID)
2096    which can be specialized to match the indicated DECL with the
2097    explicit template args given in TEMPLATE_ID.  The DECL may be
2098    NULL_TREE if none is available.  In that case, the functions in
2099    TEMPLATE_ID are non-members.
2100 
2101    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
2102    specialization of a member template.
2103 
2104    The TEMPLATE_COUNT is the number of references to qualifying
2105    template classes that appeared in the name of the function. See
2106    check_explicit_specialization for a more accurate description.
2107 
2108    TSK indicates what kind of template declaration (if any) is being
2109    declared.  TSK_TEMPLATE indicates that the declaration given by
2110    DECL, though a FUNCTION_DECL, has template parameters, and is
2111    therefore a template function.
2112 
2113    The template args (those explicitly specified and those deduced)
2114    are output in a newly created vector *TARGS_OUT.
2115 
2116    If it is impossible to determine the result, an error message is
2117    issued.  The error_mark_node is returned to indicate failure.  */
2118 
2119 static tree
determine_specialization(tree template_id,tree decl,tree * targs_out,int need_member_template,int template_count,tmpl_spec_kind tsk)2120 determine_specialization (tree template_id,
2121 			  tree decl,
2122 			  tree* targs_out,
2123 			  int need_member_template,
2124 			  int template_count,
2125 			  tmpl_spec_kind tsk)
2126 {
2127   tree fns;
2128   tree targs;
2129   tree explicit_targs;
2130   tree candidates = NULL_TREE;
2131 
2132   /* A TREE_LIST of templates of which DECL may be a specialization.
2133      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
2134      corresponding TREE_PURPOSE is the set of template arguments that,
2135      when used to instantiate the template, would produce a function
2136      with the signature of DECL.  */
2137   tree templates = NULL_TREE;
2138   int header_count;
2139   cp_binding_level *b;
2140 
2141   *targs_out = NULL_TREE;
2142 
2143   if (template_id == error_mark_node || decl == error_mark_node)
2144     return error_mark_node;
2145 
2146   /* We shouldn't be specializing a member template of an
2147      unspecialized class template; we already gave an error in
2148      check_specialization_scope, now avoid crashing.  */
2149   if (!VAR_P (decl)
2150       && template_count && DECL_CLASS_SCOPE_P (decl)
2151       && template_class_depth (DECL_CONTEXT (decl)) > 0)
2152     {
2153       gcc_assert (errorcount);
2154       return error_mark_node;
2155     }
2156 
2157   fns = TREE_OPERAND (template_id, 0);
2158   explicit_targs = TREE_OPERAND (template_id, 1);
2159 
2160   if (fns == error_mark_node)
2161     return error_mark_node;
2162 
2163   /* Check for baselinks.  */
2164   if (BASELINK_P (fns))
2165     fns = BASELINK_FUNCTIONS (fns);
2166 
2167   if (TREE_CODE (decl) == FUNCTION_DECL && !is_overloaded_fn (fns))
2168     {
2169       error_at (DECL_SOURCE_LOCATION (decl),
2170 		"%qD is not a function template", fns);
2171       return error_mark_node;
2172     }
2173   else if (VAR_P (decl) && !variable_template_p (fns))
2174     {
2175       error ("%qD is not a variable template", fns);
2176       return error_mark_node;
2177     }
2178 
2179   /* Count the number of template headers specified for this
2180      specialization.  */
2181   header_count = 0;
2182   for (b = current_binding_level;
2183        b->kind == sk_template_parms;
2184        b = b->level_chain)
2185     ++header_count;
2186 
2187   tree orig_fns = fns;
2188 
2189   if (variable_template_p (fns))
2190     {
2191       tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (fns));
2192       targs = coerce_template_parms (parms, explicit_targs, fns,
2193 				     tf_warning_or_error,
2194 				     /*req_all*/true, /*use_defarg*/true);
2195       if (targs != error_mark_node)
2196         templates = tree_cons (targs, fns, templates);
2197     }
2198   else for (lkp_iterator iter (fns); iter; ++iter)
2199     {
2200       tree fn = *iter;
2201 
2202       if (TREE_CODE (fn) == TEMPLATE_DECL)
2203 	{
2204 	  tree decl_arg_types;
2205 	  tree fn_arg_types;
2206 	  tree insttype;
2207 
2208 	  /* In case of explicit specialization, we need to check if
2209 	     the number of template headers appearing in the specialization
2210 	     is correct. This is usually done in check_explicit_specialization,
2211 	     but the check done there cannot be exhaustive when specializing
2212 	     member functions. Consider the following code:
2213 
2214 	     template <> void A<int>::f(int);
2215 	     template <> template <> void A<int>::f(int);
2216 
2217 	     Assuming that A<int> is not itself an explicit specialization
2218 	     already, the first line specializes "f" which is a non-template
2219 	     member function, whilst the second line specializes "f" which
2220 	     is a template member function. So both lines are syntactically
2221 	     correct, and check_explicit_specialization does not reject
2222 	     them.
2223 
2224 	     Here, we can do better, as we are matching the specialization
2225 	     against the declarations. We count the number of template
2226 	     headers, and we check if they match TEMPLATE_COUNT + 1
2227 	     (TEMPLATE_COUNT is the number of qualifying template classes,
2228 	     plus there must be another header for the member template
2229 	     itself).
2230 
2231 	     Notice that if header_count is zero, this is not a
2232 	     specialization but rather a template instantiation, so there
2233 	     is no check we can perform here.  */
2234 	  if (header_count && header_count != template_count + 1)
2235 	    continue;
2236 
2237 	  /* Check that the number of template arguments at the
2238 	     innermost level for DECL is the same as for FN.  */
2239 	  if (current_binding_level->kind == sk_template_parms
2240 	      && !current_binding_level->explicit_spec_p
2241 	      && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
2242 		  != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
2243 				      (current_template_parms))))
2244 	    continue;
2245 
2246 	  /* DECL might be a specialization of FN.  */
2247 	  decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2248 	  fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
2249 
2250 	  /* For a non-static member function, we need to make sure
2251 	     that the const qualification is the same.  Since
2252 	     get_bindings does not try to merge the "this" parameter,
2253 	     we must do the comparison explicitly.  */
2254 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
2255 	    {
2256 	      if (!same_type_p (TREE_VALUE (fn_arg_types),
2257 				TREE_VALUE (decl_arg_types)))
2258 		continue;
2259 
2260 	      /* And the ref-qualification.  */
2261 	      if (type_memfn_rqual (TREE_TYPE (decl))
2262 		  != type_memfn_rqual (TREE_TYPE (fn)))
2263 		continue;
2264 	    }
2265 
2266 	  /* Skip the "this" parameter and, for constructors of
2267 	     classes with virtual bases, the VTT parameter.  A
2268 	     full specialization of a constructor will have a VTT
2269 	     parameter, but a template never will.  */
2270 	  decl_arg_types
2271 	    = skip_artificial_parms_for (decl, decl_arg_types);
2272 	  fn_arg_types
2273 	    = skip_artificial_parms_for (fn, fn_arg_types);
2274 
2275 	  /* Function templates cannot be specializations; there are
2276 	     no partial specializations of functions.  Therefore, if
2277 	     the type of DECL does not match FN, there is no
2278 	     match.
2279 
2280              Note that it should never be the case that we have both
2281              candidates added here, and for regular member functions
2282              below. */
2283 	  if (tsk == tsk_template)
2284 	    {
2285 	      if (compparms (fn_arg_types, decl_arg_types))
2286 		candidates = tree_cons (NULL_TREE, fn, candidates);
2287 	      continue;
2288 	    }
2289 
2290 	  /* See whether this function might be a specialization of this
2291 	     template.  Suppress access control because we might be trying
2292 	     to make this specialization a friend, and we have already done
2293 	     access control for the declaration of the specialization.  */
2294 	  push_deferring_access_checks (dk_no_check);
2295 	  targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
2296 	  pop_deferring_access_checks ();
2297 
2298 	  if (!targs)
2299 	    /* We cannot deduce template arguments that when used to
2300 	       specialize TMPL will produce DECL.  */
2301 	    continue;
2302 
2303 	  if (uses_template_parms (targs))
2304 	    /* We deduced something involving 'auto', which isn't a valid
2305 	       template argument.  */
2306 	    continue;
2307 
2308           /* Remove, from the set of candidates, all those functions
2309              whose constraints are not satisfied. */
2310           if (flag_concepts && !constraints_satisfied_p (fn, targs))
2311             continue;
2312 
2313           // Then, try to form the new function type.
2314 	  insttype = tsubst (TREE_TYPE (fn), targs, tf_fndecl_type, NULL_TREE);
2315 	  if (insttype == error_mark_node)
2316 	    continue;
2317 	  fn_arg_types
2318 	    = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (insttype));
2319 	  if (!compparms (fn_arg_types, decl_arg_types))
2320 	    continue;
2321 
2322 	  /* Save this template, and the arguments deduced.  */
2323 	  templates = tree_cons (targs, fn, templates);
2324 	}
2325       else if (need_member_template)
2326 	/* FN is an ordinary member function, and we need a
2327 	   specialization of a member template.  */
2328 	;
2329       else if (TREE_CODE (fn) != FUNCTION_DECL)
2330 	/* We can get IDENTIFIER_NODEs here in certain erroneous
2331 	   cases.  */
2332 	;
2333       else if (!DECL_FUNCTION_MEMBER_P (fn))
2334 	/* This is just an ordinary non-member function.  Nothing can
2335 	   be a specialization of that.  */
2336 	;
2337       else if (DECL_ARTIFICIAL (fn))
2338 	/* Cannot specialize functions that are created implicitly.  */
2339 	;
2340       else
2341 	{
2342 	  tree decl_arg_types;
2343 
2344 	  /* This is an ordinary member function.  However, since
2345 	     we're here, we can assume its enclosing class is a
2346 	     template class.  For example,
2347 
2348 	       template <typename T> struct S { void f(); };
2349 	       template <> void S<int>::f() {}
2350 
2351 	     Here, S<int>::f is a non-template, but S<int> is a
2352 	     template class.  If FN has the same type as DECL, we
2353 	     might be in business.  */
2354 
2355 	  if (!DECL_TEMPLATE_INFO (fn))
2356 	    /* Its enclosing class is an explicit specialization
2357 	       of a template class.  This is not a candidate.  */
2358 	    continue;
2359 
2360 	  if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2361 			    TREE_TYPE (TREE_TYPE (fn))))
2362 	    /* The return types differ.  */
2363 	    continue;
2364 
2365 	  /* Adjust the type of DECL in case FN is a static member.  */
2366 	  decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2367 	  if (DECL_STATIC_FUNCTION_P (fn)
2368 	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2369 	    decl_arg_types = TREE_CHAIN (decl_arg_types);
2370 
2371 	  if (!compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2372 			 decl_arg_types))
2373             continue;
2374 
2375 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2376 	      && (type_memfn_rqual (TREE_TYPE (decl))
2377 		  != type_memfn_rqual (TREE_TYPE (fn))))
2378 	    continue;
2379 
2380           // If the deduced arguments do not satisfy the constraints,
2381           // this is not a candidate.
2382           if (flag_concepts && !constraints_satisfied_p (fn))
2383             continue;
2384 
2385           // Add the candidate.
2386           candidates = tree_cons (NULL_TREE, fn, candidates);
2387 	}
2388     }
2389 
2390   if (templates && TREE_CHAIN (templates))
2391     {
2392       /* We have:
2393 
2394 	   [temp.expl.spec]
2395 
2396 	   It is possible for a specialization with a given function
2397 	   signature to be instantiated from more than one function
2398 	   template.  In such cases, explicit specification of the
2399 	   template arguments must be used to uniquely identify the
2400 	   function template specialization being specialized.
2401 
2402 	 Note that here, there's no suggestion that we're supposed to
2403 	 determine which of the candidate templates is most
2404 	 specialized.  However, we, also have:
2405 
2406 	   [temp.func.order]
2407 
2408 	   Partial ordering of overloaded function template
2409 	   declarations is used in the following contexts to select
2410 	   the function template to which a function template
2411 	   specialization refers:
2412 
2413 	   -- when an explicit specialization refers to a function
2414 	      template.
2415 
2416 	 So, we do use the partial ordering rules, at least for now.
2417 	 This extension can only serve to make invalid programs valid,
2418 	 so it's safe.  And, there is strong anecdotal evidence that
2419 	 the committee intended the partial ordering rules to apply;
2420 	 the EDG front end has that behavior, and John Spicer claims
2421 	 that the committee simply forgot to delete the wording in
2422 	 [temp.expl.spec].  */
2423       tree tmpl = most_specialized_instantiation (templates);
2424       if (tmpl != error_mark_node)
2425 	{
2426 	  templates = tmpl;
2427 	  TREE_CHAIN (templates) = NULL_TREE;
2428 	}
2429     }
2430 
2431   // Concepts allows multiple declarations of member functions
2432   // with the same signature. Like above, we need to rely on
2433   // on the partial ordering of those candidates to determine which
2434   // is the best.
2435   if (flag_concepts && candidates && TREE_CHAIN (candidates))
2436     {
2437       if (tree cand = most_constrained_function (candidates))
2438         {
2439           candidates = cand;
2440           TREE_CHAIN (cand) = NULL_TREE;
2441         }
2442     }
2443 
2444   if (templates == NULL_TREE && candidates == NULL_TREE)
2445     {
2446       error ("template-id %qD for %q+D does not match any template "
2447 	     "declaration", template_id, decl);
2448       if (header_count && header_count != template_count + 1)
2449 	inform (DECL_SOURCE_LOCATION (decl),
2450 		"saw %d %<template<>%>, need %d for "
2451 		"specializing a member function template",
2452 		header_count, template_count + 1);
2453       else
2454 	print_candidates (orig_fns);
2455       return error_mark_node;
2456     }
2457   else if ((templates && TREE_CHAIN (templates))
2458 	   || (candidates && TREE_CHAIN (candidates))
2459 	   || (templates && candidates))
2460     {
2461       error ("ambiguous template specialization %qD for %q+D",
2462 	     template_id, decl);
2463       candidates = chainon (candidates, templates);
2464       print_candidates (candidates);
2465       return error_mark_node;
2466     }
2467 
2468   /* We have one, and exactly one, match.  */
2469   if (candidates)
2470     {
2471       tree fn = TREE_VALUE (candidates);
2472       *targs_out = copy_node (DECL_TI_ARGS (fn));
2473 
2474       /* Propagate the candidate's constraints to the declaration.  */
2475       set_constraints (decl, get_constraints (fn));
2476 
2477       /* DECL is a re-declaration or partial instantiation of a template
2478 	 function.  */
2479       if (TREE_CODE (fn) == TEMPLATE_DECL)
2480 	return fn;
2481       /* It was a specialization of an ordinary member function in a
2482 	 template class.  */
2483       return DECL_TI_TEMPLATE (fn);
2484     }
2485 
2486   /* It was a specialization of a template.  */
2487   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2488   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2489     {
2490       *targs_out = copy_node (targs);
2491       SET_TMPL_ARGS_LEVEL (*targs_out,
2492 			   TMPL_ARGS_DEPTH (*targs_out),
2493 			   TREE_PURPOSE (templates));
2494     }
2495   else
2496     *targs_out = TREE_PURPOSE (templates);
2497   return TREE_VALUE (templates);
2498 }
2499 
2500 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2501    but with the default argument values filled in from those in the
2502    TMPL_TYPES.  */
2503 
2504 static tree
copy_default_args_to_explicit_spec_1(tree spec_types,tree tmpl_types)2505 copy_default_args_to_explicit_spec_1 (tree spec_types,
2506 				      tree tmpl_types)
2507 {
2508   tree new_spec_types;
2509 
2510   if (!spec_types)
2511     return NULL_TREE;
2512 
2513   if (spec_types == void_list_node)
2514     return void_list_node;
2515 
2516   /* Substitute into the rest of the list.  */
2517   new_spec_types =
2518     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2519 					  TREE_CHAIN (tmpl_types));
2520 
2521   /* Add the default argument for this parameter.  */
2522   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2523 			 TREE_VALUE (spec_types),
2524 			 new_spec_types);
2525 }
2526 
2527 /* DECL is an explicit specialization.  Replicate default arguments
2528    from the template it specializes.  (That way, code like:
2529 
2530      template <class T> void f(T = 3);
2531      template <> void f(double);
2532      void g () { f (); }
2533 
2534    works, as required.)  An alternative approach would be to look up
2535    the correct default arguments at the call-site, but this approach
2536    is consistent with how implicit instantiations are handled.  */
2537 
2538 static void
copy_default_args_to_explicit_spec(tree decl)2539 copy_default_args_to_explicit_spec (tree decl)
2540 {
2541   tree tmpl;
2542   tree spec_types;
2543   tree tmpl_types;
2544   tree new_spec_types;
2545   tree old_type;
2546   tree new_type;
2547   tree t;
2548   tree object_type = NULL_TREE;
2549   tree in_charge = NULL_TREE;
2550   tree vtt = NULL_TREE;
2551 
2552   /* See if there's anything we need to do.  */
2553   tmpl = DECL_TI_TEMPLATE (decl);
2554   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2555   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2556     if (TREE_PURPOSE (t))
2557       break;
2558   if (!t)
2559     return;
2560 
2561   old_type = TREE_TYPE (decl);
2562   spec_types = TYPE_ARG_TYPES (old_type);
2563 
2564   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2565     {
2566       /* Remove the this pointer, but remember the object's type for
2567 	 CV quals.  */
2568       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2569       spec_types = TREE_CHAIN (spec_types);
2570       tmpl_types = TREE_CHAIN (tmpl_types);
2571 
2572       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2573 	{
2574 	  /* DECL may contain more parameters than TMPL due to the extra
2575 	     in-charge parameter in constructors and destructors.  */
2576 	  in_charge = spec_types;
2577 	  spec_types = TREE_CHAIN (spec_types);
2578 	}
2579       if (DECL_HAS_VTT_PARM_P (decl))
2580 	{
2581 	  vtt = spec_types;
2582 	  spec_types = TREE_CHAIN (spec_types);
2583 	}
2584     }
2585 
2586   /* Compute the merged default arguments.  */
2587   new_spec_types =
2588     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2589 
2590   /* Compute the new FUNCTION_TYPE.  */
2591   if (object_type)
2592     {
2593       if (vtt)
2594 	new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2595 					 TREE_VALUE (vtt),
2596 					 new_spec_types);
2597 
2598       if (in_charge)
2599 	/* Put the in-charge parameter back.  */
2600 	new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2601 					 TREE_VALUE (in_charge),
2602 					 new_spec_types);
2603 
2604       new_type = build_method_type_directly (object_type,
2605 					     TREE_TYPE (old_type),
2606 					     new_spec_types);
2607     }
2608   else
2609     new_type = build_function_type (TREE_TYPE (old_type),
2610 				    new_spec_types);
2611   new_type = cp_build_type_attribute_variant (new_type,
2612 					      TYPE_ATTRIBUTES (old_type));
2613   new_type = cxx_copy_lang_qualifiers (new_type, old_type);
2614 
2615   TREE_TYPE (decl) = new_type;
2616 }
2617 
2618 /* Return the number of template headers we expect to see for a definition
2619    or specialization of CTYPE or one of its non-template members.  */
2620 
2621 int
num_template_headers_for_class(tree ctype)2622 num_template_headers_for_class (tree ctype)
2623 {
2624   int num_templates = 0;
2625 
2626   while (ctype && CLASS_TYPE_P (ctype))
2627     {
2628       /* You're supposed to have one `template <...>' for every
2629 	 template class, but you don't need one for a full
2630 	 specialization.  For example:
2631 
2632 	 template <class T> struct S{};
2633 	 template <> struct S<int> { void f(); };
2634 	 void S<int>::f () {}
2635 
2636 	 is correct; there shouldn't be a `template <>' for the
2637 	 definition of `S<int>::f'.  */
2638       if (!CLASSTYPE_TEMPLATE_INFO (ctype))
2639 	/* If CTYPE does not have template information of any
2640 	   kind,  then it is not a template, nor is it nested
2641 	   within a template.  */
2642 	break;
2643       if (explicit_class_specialization_p (ctype))
2644 	break;
2645       if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (ctype)))
2646 	++num_templates;
2647 
2648       ctype = TYPE_CONTEXT (ctype);
2649     }
2650 
2651   return num_templates;
2652 }
2653 
2654 /* Do a simple sanity check on the template headers that precede the
2655    variable declaration DECL.  */
2656 
2657 void
check_template_variable(tree decl)2658 check_template_variable (tree decl)
2659 {
2660   tree ctx = CP_DECL_CONTEXT (decl);
2661   int wanted = num_template_headers_for_class (ctx);
2662   if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
2663       && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
2664     {
2665       if (cxx_dialect < cxx14)
2666         pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2667 		 "variable templates only available with "
2668 		 "%<-std=c++14%> or %<-std=gnu++14%>");
2669 
2670       // Namespace-scope variable templates should have a template header.
2671       ++wanted;
2672     }
2673   if (template_header_count > wanted)
2674     {
2675       auto_diagnostic_group d;
2676       bool warned = pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2677 			     "too many template headers for %qD "
2678 	                     "(should be %d)",
2679 			     decl, wanted);
2680       if (warned && CLASS_TYPE_P (ctx)
2681 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (ctx))
2682 	inform (DECL_SOURCE_LOCATION (decl),
2683 		"members of an explicitly specialized class are defined "
2684 		"without a template header");
2685     }
2686 }
2687 
2688 /* An explicit specialization whose declarator-id or class-head-name is not
2689    qualified shall be declared in the nearest enclosing namespace of the
2690    template, or, if the namespace is inline (7.3.1), any namespace from its
2691    enclosing namespace set.
2692 
2693    If the name declared in the explicit instantiation is an unqualified name,
2694    the explicit instantiation shall appear in the namespace where its template
2695    is declared or, if that namespace is inline (7.3.1), any namespace from its
2696    enclosing namespace set.  */
2697 
2698 void
check_unqualified_spec_or_inst(tree t,location_t loc)2699 check_unqualified_spec_or_inst (tree t, location_t loc)
2700 {
2701   tree tmpl = most_general_template (t);
2702   if (DECL_NAMESPACE_SCOPE_P (tmpl)
2703       && !is_nested_namespace (current_namespace,
2704 			       CP_DECL_CONTEXT (tmpl), true))
2705     {
2706       if (processing_specialization)
2707 	permerror (loc, "explicit specialization of %qD outside its "
2708 		   "namespace must use a nested-name-specifier", tmpl);
2709       else if (processing_explicit_instantiation
2710 	       && cxx_dialect >= cxx11)
2711 	/* This was allowed in C++98, so only pedwarn.  */
2712 	pedwarn (loc, OPT_Wpedantic, "explicit instantiation of %qD "
2713 		 "outside its namespace must use a nested-name-"
2714 		 "specifier", tmpl);
2715     }
2716 }
2717 
2718 /* Warn for a template specialization SPEC that is missing some of a set
2719    of function or type attributes that the template TEMPL is declared with.
2720    ATTRLIST is a list of additional attributes that SPEC should be taken
2721    to ultimately be declared with.  */
2722 
2723 static void
warn_spec_missing_attributes(tree tmpl,tree spec,tree attrlist)2724 warn_spec_missing_attributes (tree tmpl, tree spec, tree attrlist)
2725 {
2726   if (DECL_FUNCTION_TEMPLATE_P (tmpl))
2727     tmpl = DECL_TEMPLATE_RESULT (tmpl);
2728 
2729   /* Avoid warning if the difference between the primary and
2730      the specialization is not in one of the attributes below.  */
2731   const char* const blacklist[] = {
2732     "alloc_align", "alloc_size", "assume_aligned", "format",
2733     "format_arg", "malloc", "nonnull", NULL
2734   };
2735 
2736   /* Put together a list of the black listed attributes that the primary
2737      template is declared with that the specialization is not, in case
2738      it's not apparent from the most recent declaration of the primary.  */
2739   pretty_printer str;
2740   unsigned nattrs = decls_mismatched_attributes (tmpl, spec, attrlist,
2741 						 blacklist, &str);
2742 
2743   if (!nattrs)
2744     return;
2745 
2746   auto_diagnostic_group d;
2747   if (warning_at (DECL_SOURCE_LOCATION (spec), OPT_Wmissing_attributes,
2748 		  "explicit specialization %q#D may be missing attributes",
2749 		  spec))
2750     inform (DECL_SOURCE_LOCATION (tmpl),
2751 	    nattrs > 1
2752 	    ? G_("missing primary template attributes %s")
2753 	    : G_("missing primary template attribute %s"),
2754 	    pp_formatted_text (&str));
2755 }
2756 
2757 /* Check to see if the function just declared, as indicated in
2758    DECLARATOR, and in DECL, is a specialization of a function
2759    template.  We may also discover that the declaration is an explicit
2760    instantiation at this point.
2761 
2762    Returns DECL, or an equivalent declaration that should be used
2763    instead if all goes well.  Issues an error message if something is
2764    amiss.  Returns error_mark_node if the error is not easily
2765    recoverable.
2766 
2767    FLAGS is a bitmask consisting of the following flags:
2768 
2769    2: The function has a definition.
2770    4: The function is a friend.
2771 
2772    The TEMPLATE_COUNT is the number of references to qualifying
2773    template classes that appeared in the name of the function.  For
2774    example, in
2775 
2776      template <class T> struct S { void f(); };
2777      void S<int>::f();
2778 
2779    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2780    classes are not counted in the TEMPLATE_COUNT, so that in
2781 
2782      template <class T> struct S {};
2783      template <> struct S<int> { void f(); }
2784      template <> void S<int>::f();
2785 
2786    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2787    invalid; there should be no template <>.)
2788 
2789    If the function is a specialization, it is marked as such via
2790    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2791    is set up correctly, and it is added to the list of specializations
2792    for that template.  */
2793 
2794 tree
check_explicit_specialization(tree declarator,tree decl,int template_count,int flags,tree attrlist)2795 check_explicit_specialization (tree declarator,
2796 			       tree decl,
2797 			       int template_count,
2798 			       int flags,
2799 			       tree attrlist)
2800 {
2801   int have_def = flags & 2;
2802   int is_friend = flags & 4;
2803   bool is_concept = flags & 8;
2804   int specialization = 0;
2805   int explicit_instantiation = 0;
2806   int member_specialization = 0;
2807   tree ctype = DECL_CLASS_CONTEXT (decl);
2808   tree dname = DECL_NAME (decl);
2809   tmpl_spec_kind tsk;
2810 
2811   if (is_friend)
2812     {
2813       if (!processing_specialization)
2814 	tsk = tsk_none;
2815       else
2816 	tsk = tsk_excessive_parms;
2817     }
2818   else
2819     tsk = current_tmpl_spec_kind (template_count);
2820 
2821   switch (tsk)
2822     {
2823     case tsk_none:
2824       if (processing_specialization && !VAR_P (decl))
2825 	{
2826 	  specialization = 1;
2827 	  SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2828 	}
2829       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2830 	{
2831 	  if (is_friend)
2832 	    /* This could be something like:
2833 
2834 	       template <class T> void f(T);
2835 	       class S { friend void f<>(int); }  */
2836 	    specialization = 1;
2837 	  else
2838 	    {
2839 	      /* This case handles bogus declarations like template <>
2840 		 template <class T> void f<int>(); */
2841 
2842 	      error_at (cp_expr_loc_or_input_loc (declarator),
2843 			"template-id %qE in declaration of primary template",
2844 			declarator);
2845 	      return decl;
2846 	    }
2847 	}
2848       break;
2849 
2850     case tsk_invalid_member_spec:
2851       /* The error has already been reported in
2852 	 check_specialization_scope.  */
2853       return error_mark_node;
2854 
2855     case tsk_invalid_expl_inst:
2856       error ("template parameter list used in explicit instantiation");
2857 
2858       /* Fall through.  */
2859 
2860     case tsk_expl_inst:
2861       if (have_def)
2862 	error ("definition provided for explicit instantiation");
2863 
2864       explicit_instantiation = 1;
2865       break;
2866 
2867     case tsk_excessive_parms:
2868     case tsk_insufficient_parms:
2869       if (tsk == tsk_excessive_parms)
2870 	error ("too many template parameter lists in declaration of %qD",
2871 	       decl);
2872       else if (template_header_count)
2873 	error("too few template parameter lists in declaration of %qD", decl);
2874       else
2875 	error("explicit specialization of %qD must be introduced by "
2876 	      "%<template <>%>", decl);
2877 
2878       /* Fall through.  */
2879     case tsk_expl_spec:
2880       if (is_concept)
2881         error ("explicit specialization declared %<concept%>");
2882 
2883       if (VAR_P (decl) && TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2884 	/* In cases like template<> constexpr bool v = true;
2885 	   We'll give an error in check_template_variable.  */
2886 	break;
2887 
2888       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2889       if (ctype)
2890 	member_specialization = 1;
2891       else
2892 	specialization = 1;
2893       break;
2894 
2895     case tsk_template:
2896       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2897 	{
2898 	  /* This case handles bogus declarations like template <>
2899 	     template <class T> void f<int>(); */
2900 
2901 	  if (!uses_template_parms (TREE_OPERAND (declarator, 1)))
2902 	    error_at (cp_expr_loc_or_input_loc (declarator),
2903 		      "template-id %qE in declaration of primary template",
2904 		      declarator);
2905 	  else if (variable_template_p (TREE_OPERAND (declarator, 0)))
2906 	    {
2907 	      /* Partial specialization of variable template.  */
2908 	      SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2909 	      specialization = 1;
2910 	      goto ok;
2911 	    }
2912 	  else if (cxx_dialect < cxx14)
2913 	    error_at (cp_expr_loc_or_input_loc (declarator),
2914 		      "non-type partial specialization %qE "
2915 		      "is not allowed", declarator);
2916 	  else
2917 	    error_at (cp_expr_loc_or_input_loc (declarator),
2918 		      "non-class, non-variable partial specialization %qE "
2919 		      "is not allowed", declarator);
2920 	  return decl;
2921 	ok:;
2922 	}
2923 
2924       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2925 	/* This is a specialization of a member template, without
2926 	   specialization the containing class.  Something like:
2927 
2928 	     template <class T> struct S {
2929 	       template <class U> void f (U);
2930 	     };
2931 	     template <> template <class U> void S<int>::f(U) {}
2932 
2933 	   That's a specialization -- but of the entire template.  */
2934 	specialization = 1;
2935       break;
2936 
2937     default:
2938       gcc_unreachable ();
2939     }
2940 
2941   if ((specialization || member_specialization)
2942       /* This doesn't apply to variable templates.  */
2943       && FUNC_OR_METHOD_TYPE_P (TREE_TYPE (decl)))
2944     {
2945       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2946       for (; t; t = TREE_CHAIN (t))
2947 	if (TREE_PURPOSE (t))
2948 	  {
2949 	    permerror (input_location,
2950 		       "default argument specified in explicit specialization");
2951 	    break;
2952 	  }
2953     }
2954 
2955   if (specialization || member_specialization || explicit_instantiation)
2956     {
2957       tree tmpl = NULL_TREE;
2958       tree targs = NULL_TREE;
2959       bool was_template_id = (TREE_CODE (declarator) == TEMPLATE_ID_EXPR);
2960 
2961       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2962       if (!was_template_id)
2963 	{
2964 	  tree fns;
2965 
2966 	  gcc_assert (identifier_p (declarator));
2967 	  if (ctype)
2968 	    fns = dname;
2969 	  else
2970 	    {
2971 	      /* If there is no class context, the explicit instantiation
2972 		 must be at namespace scope.  */
2973 	      gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2974 
2975 	      /* Find the namespace binding, using the declaration
2976 		 context.  */
2977 	      fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2978 					   false, true);
2979 	      if (fns == error_mark_node)
2980 		/* If lookup fails, look for a friend declaration so we can
2981 		   give a better diagnostic.  */
2982 		fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2983 					     /*type*/false, /*complain*/true,
2984 					     /*hidden*/true);
2985 
2986 	      if (fns == error_mark_node || !is_overloaded_fn (fns))
2987 		{
2988 		  error ("%qD is not a template function", dname);
2989 		  fns = error_mark_node;
2990 		}
2991 	    }
2992 
2993 	  declarator = lookup_template_function (fns, NULL_TREE);
2994 	}
2995 
2996       if (declarator == error_mark_node)
2997 	return error_mark_node;
2998 
2999       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
3000 	{
3001 	  if (!explicit_instantiation)
3002 	    /* A specialization in class scope.  This is invalid,
3003 	       but the error will already have been flagged by
3004 	       check_specialization_scope.  */
3005 	    return error_mark_node;
3006 	  else
3007 	    {
3008 	      /* It's not valid to write an explicit instantiation in
3009 		 class scope, e.g.:
3010 
3011 		   class C { template void f(); }
3012 
3013 		   This case is caught by the parser.  However, on
3014 		   something like:
3015 
3016 		   template class C { void f(); };
3017 
3018 		   (which is invalid) we can get here.  The error will be
3019 		   issued later.  */
3020 	      ;
3021 	    }
3022 
3023 	  return decl;
3024 	}
3025       else if (ctype != NULL_TREE
3026 	       && (identifier_p (TREE_OPERAND (declarator, 0))))
3027 	{
3028 	  // We'll match variable templates in start_decl.
3029 	  if (VAR_P (decl))
3030 	    return decl;
3031 
3032 	  /* Find the list of functions in ctype that have the same
3033 	     name as the declared function.  */
3034 	  tree name = TREE_OPERAND (declarator, 0);
3035 
3036 	  if (constructor_name_p (name, ctype))
3037 	    {
3038 	      if (DECL_CONSTRUCTOR_P (decl)
3039 		  ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
3040 		  : !CLASSTYPE_DESTRUCTOR (ctype))
3041 		{
3042 		  /* From [temp.expl.spec]:
3043 
3044 		     If such an explicit specialization for the member
3045 		     of a class template names an implicitly-declared
3046 		     special member function (clause _special_), the
3047 		     program is ill-formed.
3048 
3049 		     Similar language is found in [temp.explicit].  */
3050 		  error ("specialization of implicitly-declared special member function");
3051 		  return error_mark_node;
3052 		}
3053 
3054 	      name = DECL_NAME (decl);
3055 	    }
3056 
3057 	  /* For a type-conversion operator, We might be looking for
3058 	     `operator int' which will be a specialization of
3059 	     `operator T'.  Grab all the conversion operators, and
3060 	     then select from them.  */
3061 	  tree fns = get_class_binding (ctype, IDENTIFIER_CONV_OP_P (name)
3062 					? conv_op_identifier : name);
3063 
3064 	  if (fns == NULL_TREE)
3065 	    {
3066 	      error ("no member function %qD declared in %qT", name, ctype);
3067 	      return error_mark_node;
3068 	    }
3069 	  else
3070 	    TREE_OPERAND (declarator, 0) = fns;
3071 	}
3072 
3073       /* Figure out what exactly is being specialized at this point.
3074 	 Note that for an explicit instantiation, even one for a
3075 	 member function, we cannot tell a priori whether the
3076 	 instantiation is for a member template, or just a member
3077 	 function of a template class.  Even if a member template is
3078 	 being instantiated, the member template arguments may be
3079 	 elided if they can be deduced from the rest of the
3080 	 declaration.  */
3081       tmpl = determine_specialization (declarator, decl,
3082 				       &targs,
3083 				       member_specialization,
3084 				       template_count,
3085 				       tsk);
3086 
3087       if (!tmpl || tmpl == error_mark_node)
3088 	/* We couldn't figure out what this declaration was
3089 	   specializing.  */
3090 	return error_mark_node;
3091       else
3092 	{
3093 	  if (TREE_CODE (decl) == FUNCTION_DECL
3094 	      && DECL_HIDDEN_FRIEND_P (tmpl))
3095 	    {
3096 	      auto_diagnostic_group d;
3097 	      if (pedwarn (DECL_SOURCE_LOCATION (decl), 0,
3098 			   "friend declaration %qD is not visible to "
3099 			   "explicit specialization", tmpl))
3100 		inform (DECL_SOURCE_LOCATION (tmpl),
3101 			"friend declaration here");
3102 	    }
3103 	  else if (!ctype && !is_friend
3104 		   && CP_DECL_CONTEXT (decl) == current_namespace)
3105 	    check_unqualified_spec_or_inst (tmpl, DECL_SOURCE_LOCATION (decl));
3106 
3107 	  tree gen_tmpl = most_general_template (tmpl);
3108 
3109 	  if (explicit_instantiation)
3110 	    {
3111 	      /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
3112 		 is done by do_decl_instantiation later.  */
3113 
3114 	      int arg_depth = TMPL_ARGS_DEPTH (targs);
3115 	      int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
3116 
3117 	      if (arg_depth > parm_depth)
3118 		{
3119 		  /* If TMPL is not the most general template (for
3120 		     example, if TMPL is a friend template that is
3121 		     injected into namespace scope), then there will
3122 		     be too many levels of TARGS.  Remove some of them
3123 		     here.  */
3124 		  int i;
3125 		  tree new_targs;
3126 
3127 		  new_targs = make_tree_vec (parm_depth);
3128 		  for (i = arg_depth - parm_depth; i < arg_depth; ++i)
3129 		    TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
3130 		      = TREE_VEC_ELT (targs, i);
3131 		  targs = new_targs;
3132 		}
3133 
3134 	      return instantiate_template (tmpl, targs, tf_error);
3135 	    }
3136 
3137 	  /* If we thought that the DECL was a member function, but it
3138 	     turns out to be specializing a static member function,
3139 	     make DECL a static member function as well.  */
3140 	  if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3141 	      && DECL_STATIC_FUNCTION_P (tmpl)
3142 	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
3143 	    revert_static_member_fn (decl);
3144 
3145 	  /* If this is a specialization of a member template of a
3146 	     template class, we want to return the TEMPLATE_DECL, not
3147 	     the specialization of it.  */
3148 	  if (tsk == tsk_template && !was_template_id)
3149 	    {
3150 	      tree result = DECL_TEMPLATE_RESULT (tmpl);
3151 	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3152 	      DECL_INITIAL (result) = NULL_TREE;
3153 	      if (have_def)
3154 		{
3155 		  tree parm;
3156 		  DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
3157 		  DECL_SOURCE_LOCATION (result)
3158 		    = DECL_SOURCE_LOCATION (decl);
3159 		  /* We want to use the argument list specified in the
3160 		     definition, not in the original declaration.  */
3161 		  DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
3162 		  for (parm = DECL_ARGUMENTS (result); parm;
3163 		       parm = DECL_CHAIN (parm))
3164 		    DECL_CONTEXT (parm) = result;
3165 		}
3166 	      return register_specialization (tmpl, gen_tmpl, targs,
3167 					      is_friend, 0);
3168 	    }
3169 
3170 	  /* Set up the DECL_TEMPLATE_INFO for DECL.  */
3171 	  DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
3172 
3173 	  if (was_template_id)
3174 	    TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl)) = true;
3175 
3176 	  /* Inherit default function arguments from the template
3177 	     DECL is specializing.  */
3178 	  if (DECL_FUNCTION_TEMPLATE_P (tmpl))
3179 	    copy_default_args_to_explicit_spec (decl);
3180 
3181 	  /* This specialization has the same protection as the
3182 	     template it specializes.  */
3183 	  TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
3184 	  TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
3185 
3186           /* 7.1.1-1 [dcl.stc]
3187 
3188              A storage-class-specifier shall not be specified in an
3189              explicit specialization...
3190 
3191              The parser rejects these, so unless action is taken here,
3192              explicit function specializations will always appear with
3193              global linkage.
3194 
3195              The action recommended by the C++ CWG in response to C++
3196              defect report 605 is to make the storage class and linkage
3197              of the explicit specialization match the templated function:
3198 
3199              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
3200            */
3201           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
3202             {
3203               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
3204               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
3205 
3206               /* A concept cannot be specialized.  */
3207               if (DECL_DECLARED_CONCEPT_P (tmpl_func))
3208                 {
3209                   error ("explicit specialization of function concept %qD",
3210                          gen_tmpl);
3211                   return error_mark_node;
3212                 }
3213 
3214               /* This specialization has the same linkage and visibility as
3215                  the function template it specializes.  */
3216               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
3217 	      if (! TREE_PUBLIC (decl))
3218 		{
3219 		  DECL_INTERFACE_KNOWN (decl) = 1;
3220 		  DECL_NOT_REALLY_EXTERN (decl) = 1;
3221 		}
3222               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
3223               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
3224                 {
3225                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
3226                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
3227                 }
3228             }
3229 
3230 	  /* If DECL is a friend declaration, declared using an
3231 	     unqualified name, the namespace associated with DECL may
3232 	     have been set incorrectly.  For example, in:
3233 
3234 	       template <typename T> void f(T);
3235 	       namespace N {
3236 		 struct S { friend void f<int>(int); }
3237 	       }
3238 
3239 	     we will have set the DECL_CONTEXT for the friend
3240 	     declaration to N, rather than to the global namespace.  */
3241 	  if (DECL_NAMESPACE_SCOPE_P (decl))
3242 	    DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
3243 
3244 	  if (is_friend && !have_def)
3245 	    /* This is not really a declaration of a specialization.
3246 	       It's just the name of an instantiation.  But, it's not
3247 	       a request for an instantiation, either.  */
3248 	    SET_DECL_IMPLICIT_INSTANTIATION (decl);
3249 	  else if (TREE_CODE (decl) == FUNCTION_DECL)
3250 	    /* A specialization is not necessarily COMDAT.  */
3251 	    DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
3252 				  && DECL_DECLARED_INLINE_P (decl));
3253 	  else if (VAR_P (decl))
3254 	    DECL_COMDAT (decl) = false;
3255 
3256 	  /* If this is a full specialization, register it so that we can find
3257 	     it again.  Partial specializations will be registered in
3258 	     process_partial_specialization.  */
3259 	  if (!processing_template_decl)
3260 	    {
3261 	      warn_spec_missing_attributes (gen_tmpl, decl, attrlist);
3262 
3263 	      decl = register_specialization (decl, gen_tmpl, targs,
3264 					      is_friend, 0);
3265 	    }
3266 
3267 
3268 	  /* A 'structor should already have clones.  */
3269 	  gcc_assert (decl == error_mark_node
3270 		      || variable_template_p (tmpl)
3271 		      || !(DECL_CONSTRUCTOR_P (decl)
3272 			   || DECL_DESTRUCTOR_P (decl))
3273 		      || DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
3274 	}
3275     }
3276 
3277   return decl;
3278 }
3279 
3280 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
3281    parameters.  These are represented in the same format used for
3282    DECL_TEMPLATE_PARMS.  */
3283 
3284 int
comp_template_parms(const_tree parms1,const_tree parms2)3285 comp_template_parms (const_tree parms1, const_tree parms2)
3286 {
3287   const_tree p1;
3288   const_tree p2;
3289 
3290   if (parms1 == parms2)
3291     return 1;
3292 
3293   for (p1 = parms1, p2 = parms2;
3294        p1 != NULL_TREE && p2 != NULL_TREE;
3295        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
3296     {
3297       tree t1 = TREE_VALUE (p1);
3298       tree t2 = TREE_VALUE (p2);
3299       int i;
3300 
3301       gcc_assert (TREE_CODE (t1) == TREE_VEC);
3302       gcc_assert (TREE_CODE (t2) == TREE_VEC);
3303 
3304       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
3305 	return 0;
3306 
3307       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
3308 	{
3309           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
3310           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
3311 
3312           /* If either of the template parameters are invalid, assume
3313              they match for the sake of error recovery. */
3314           if (error_operand_p (parm1) || error_operand_p (parm2))
3315             return 1;
3316 
3317 	  if (TREE_CODE (parm1) != TREE_CODE (parm2))
3318 	    return 0;
3319 
3320 	  if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
3321               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
3322                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
3323 	    continue;
3324 	  else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
3325 	    return 0;
3326 	}
3327     }
3328 
3329   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3330     /* One set of parameters has more parameters lists than the
3331        other.  */
3332     return 0;
3333 
3334   return 1;
3335 }
3336 
3337 /* Returns true if two template parameters are declared with
3338    equivalent constraints.  */
3339 
3340 static bool
template_parameter_constraints_equivalent_p(const_tree parm1,const_tree parm2)3341 template_parameter_constraints_equivalent_p (const_tree parm1, const_tree parm2)
3342 {
3343   tree req1 = TREE_TYPE (parm1);
3344   tree req2 = TREE_TYPE (parm2);
3345   if (!req1 != !req2)
3346     return false;
3347   if (req1)
3348     return cp_tree_equal (req1, req2);
3349   return true;
3350 }
3351 
3352 /* Returns true when two template parameters are equivalent.  */
3353 
3354 static bool
template_parameters_equivalent_p(const_tree parm1,const_tree parm2)3355 template_parameters_equivalent_p (const_tree parm1, const_tree parm2)
3356 {
3357   tree decl1 = TREE_VALUE (parm1);
3358   tree decl2 = TREE_VALUE (parm2);
3359 
3360   /* If either of the template parameters are invalid, assume
3361      they match for the sake of error recovery. */
3362   if (error_operand_p (decl1) || error_operand_p (decl2))
3363     return true;
3364 
3365   /* ... they declare parameters of the same kind.  */
3366   if (TREE_CODE (decl1) != TREE_CODE (decl2))
3367     return false;
3368 
3369   /* ... one parameter was introduced by a parameter declaration, then
3370      both are. This case arises as a result of eagerly rewriting declarations
3371      during parsing.  */
3372   if (DECL_VIRTUAL_P (decl1) != DECL_VIRTUAL_P (decl2))
3373     return false;
3374 
3375   /* ... if either declares a pack, they both do.  */
3376   if (template_parameter_pack_p (decl1) != template_parameter_pack_p (decl2))
3377     return false;
3378 
3379   if (TREE_CODE (decl1) == PARM_DECL)
3380     {
3381       /* ... if they declare non-type parameters, the types are equivalent.  */
3382       if (!same_type_p (TREE_TYPE (decl1), TREE_TYPE (decl2)))
3383 	return false;
3384     }
3385   else if (TREE_CODE (decl2) == TEMPLATE_DECL)
3386     {
3387       /* ... if they declare template template parameters, their template
3388 	 parameter lists are equivalent.  */
3389       if (!template_heads_equivalent_p (decl1, decl2))
3390 	return false;
3391     }
3392 
3393   /* ... if they are declared with a qualified-concept name, they both
3394      are, and those names are equivalent.  */
3395   return template_parameter_constraints_equivalent_p (parm1, parm2);
3396 }
3397 
3398 /* Returns true if two template parameters lists are equivalent.
3399    Two template parameter lists are equivalent if they have the
3400    same length and their corresponding parameters are equivalent.
3401 
3402    PARMS1 and PARMS2 are TREE_LISTs containing TREE_VECs: the
3403    data structure returned by DECL_TEMPLATE_PARMS.
3404 
3405    This is generally the same implementation as comp_template_parms
3406    except that it also the concept names and arguments used to
3407    introduce parameters.  */
3408 
3409 static bool
template_parameter_lists_equivalent_p(const_tree parms1,const_tree parms2)3410 template_parameter_lists_equivalent_p (const_tree parms1, const_tree parms2)
3411 {
3412   if (parms1 == parms2)
3413     return true;
3414 
3415   const_tree p1 = parms1;
3416   const_tree p2 = parms2;
3417   while (p1 != NULL_TREE && p2 != NULL_TREE)
3418     {
3419       tree list1 = TREE_VALUE (p1);
3420       tree list2 = TREE_VALUE (p2);
3421 
3422       if (TREE_VEC_LENGTH (list1) != TREE_VEC_LENGTH (list2))
3423 	return 0;
3424 
3425       for (int i = 0; i < TREE_VEC_LENGTH (list2); ++i)
3426 	{
3427 	  tree parm1 = TREE_VEC_ELT (list1, i);
3428 	  tree parm2 = TREE_VEC_ELT (list2, i);
3429 	  if (!template_parameters_equivalent_p (parm1, parm2))
3430 	    return false;
3431 	}
3432 
3433       p1 = TREE_CHAIN (p1);
3434       p2 = TREE_CHAIN (p2);
3435     }
3436 
3437   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3438     return false;
3439 
3440   return true;
3441 }
3442 
3443 /* Return true if the requires-clause of the template parameter lists are
3444    equivalent and false otherwise.  */
3445 static bool
template_requirements_equivalent_p(const_tree parms1,const_tree parms2)3446 template_requirements_equivalent_p (const_tree parms1, const_tree parms2)
3447 {
3448   tree req1 = TEMPLATE_PARMS_CONSTRAINTS (parms1);
3449   tree req2 = TEMPLATE_PARMS_CONSTRAINTS (parms2);
3450   if ((req1 != NULL_TREE) != (req2 != NULL_TREE))
3451     return false;
3452   if (!cp_tree_equal (req1, req2))
3453     return false;
3454   return true;
3455 }
3456 
3457 /* Returns true if two template heads are equivalent. 17.6.6.1p6:
3458    Two template heads are equivalent if their template parameter
3459    lists are equivalent and their requires clauses are equivalent.
3460 
3461    In pre-C++20, this is equivalent to calling comp_template_parms
3462    for the template parameters of TMPL1 and TMPL2.  */
3463 
3464 bool
template_heads_equivalent_p(const_tree tmpl1,const_tree tmpl2)3465 template_heads_equivalent_p (const_tree tmpl1, const_tree tmpl2)
3466 {
3467   tree parms1 = DECL_TEMPLATE_PARMS (tmpl1);
3468   tree parms2 = DECL_TEMPLATE_PARMS (tmpl2);
3469 
3470   /* Don't change the matching rules for pre-C++20.  */
3471   if (cxx_dialect < cxx2a)
3472     return comp_template_parms (parms1, parms2);
3473 
3474   /* ... have the same number of template parameters, and their
3475      corresponding parameters are equivalent.  */
3476   if (!template_parameter_lists_equivalent_p (parms1, parms2))
3477     return false;
3478 
3479   /* ... if either has a requires-clause, they both do and their
3480      corresponding constraint-expressions are equivalent.  */
3481   return template_requirements_equivalent_p (parms1, parms2);
3482 }
3483 
3484 /* Determine whether PARM is a parameter pack.  */
3485 
3486 bool
template_parameter_pack_p(const_tree parm)3487 template_parameter_pack_p (const_tree parm)
3488 {
3489   /* Determine if we have a non-type template parameter pack.  */
3490   if (TREE_CODE (parm) == PARM_DECL)
3491     return (DECL_TEMPLATE_PARM_P (parm)
3492             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
3493   if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
3494     return TEMPLATE_PARM_PARAMETER_PACK (parm);
3495 
3496   /* If this is a list of template parameters, we could get a
3497      TYPE_DECL or a TEMPLATE_DECL.  */
3498   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
3499     parm = TREE_TYPE (parm);
3500 
3501   /* Otherwise it must be a type template parameter.  */
3502   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
3503 	   || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
3504 	  && TEMPLATE_TYPE_PARAMETER_PACK (parm));
3505 }
3506 
3507 /* Determine if T is a function parameter pack.  */
3508 
3509 bool
function_parameter_pack_p(const_tree t)3510 function_parameter_pack_p (const_tree t)
3511 {
3512   if (t && TREE_CODE (t) == PARM_DECL)
3513     return DECL_PACK_P (t);
3514   return false;
3515 }
3516 
3517 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
3518    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
3519 
3520 tree
get_function_template_decl(const_tree primary_func_tmpl_inst)3521 get_function_template_decl (const_tree primary_func_tmpl_inst)
3522 {
3523   if (! primary_func_tmpl_inst
3524       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
3525       || ! primary_template_specialization_p (primary_func_tmpl_inst))
3526     return NULL;
3527 
3528   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
3529 }
3530 
3531 /* Return true iff the function parameter PARAM_DECL was expanded
3532    from the function parameter pack PACK.  */
3533 
3534 bool
function_parameter_expanded_from_pack_p(tree param_decl,tree pack)3535 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
3536 {
3537   if (DECL_ARTIFICIAL (param_decl)
3538       || !function_parameter_pack_p (pack))
3539     return false;
3540 
3541   /* The parameter pack and its pack arguments have the same
3542      DECL_PARM_INDEX.  */
3543   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
3544 }
3545 
3546 /* Determine whether ARGS describes a variadic template args list,
3547    i.e., one that is terminated by a template argument pack.  */
3548 
3549 static bool
template_args_variadic_p(tree args)3550 template_args_variadic_p (tree args)
3551 {
3552   int nargs;
3553   tree last_parm;
3554 
3555   if (args == NULL_TREE)
3556     return false;
3557 
3558   args = INNERMOST_TEMPLATE_ARGS (args);
3559   nargs = TREE_VEC_LENGTH (args);
3560 
3561   if (nargs == 0)
3562     return false;
3563 
3564   last_parm = TREE_VEC_ELT (args, nargs - 1);
3565 
3566   return ARGUMENT_PACK_P (last_parm);
3567 }
3568 
3569 /* Generate a new name for the parameter pack name NAME (an
3570    IDENTIFIER_NODE) that incorporates its */
3571 
3572 static tree
make_ith_pack_parameter_name(tree name,int i)3573 make_ith_pack_parameter_name (tree name, int i)
3574 {
3575   /* Munge the name to include the parameter index.  */
3576 #define NUMBUF_LEN 128
3577   char numbuf[NUMBUF_LEN];
3578   char* newname;
3579   int newname_len;
3580 
3581   if (name == NULL_TREE)
3582     return name;
3583   snprintf (numbuf, NUMBUF_LEN, "%i", i);
3584   newname_len = IDENTIFIER_LENGTH (name)
3585 	        + strlen (numbuf) + 2;
3586   newname = (char*)alloca (newname_len);
3587   snprintf (newname, newname_len,
3588 	    "%s#%i", IDENTIFIER_POINTER (name), i);
3589   return get_identifier (newname);
3590 }
3591 
3592 /* Return true if T is a primary function, class or alias template
3593    specialization, not including the template pattern.  */
3594 
3595 bool
primary_template_specialization_p(const_tree t)3596 primary_template_specialization_p (const_tree t)
3597 {
3598   if (!t)
3599     return false;
3600 
3601   if (TREE_CODE (t) == FUNCTION_DECL || VAR_P (t))
3602     return (DECL_LANG_SPECIFIC (t)
3603 	    && DECL_USE_TEMPLATE (t)
3604 	    && DECL_TEMPLATE_INFO (t)
3605 	    && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t)));
3606   else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
3607     return (CLASSTYPE_TEMPLATE_INFO (t)
3608 	    && CLASSTYPE_USE_TEMPLATE (t)
3609 	    && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)));
3610   else if (alias_template_specialization_p (t, nt_transparent))
3611     return true;
3612   return false;
3613 }
3614 
3615 /* Return true if PARM is a template template parameter.  */
3616 
3617 bool
template_template_parameter_p(const_tree parm)3618 template_template_parameter_p (const_tree parm)
3619 {
3620   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
3621 }
3622 
3623 /* Return true iff PARM is a DECL representing a type template
3624    parameter.  */
3625 
3626 bool
template_type_parameter_p(const_tree parm)3627 template_type_parameter_p (const_tree parm)
3628 {
3629   return (parm
3630 	  && (TREE_CODE (parm) == TYPE_DECL
3631 	      || TREE_CODE (parm) == TEMPLATE_DECL)
3632 	  && DECL_TEMPLATE_PARM_P (parm));
3633 }
3634 
3635 /* Return the template parameters of T if T is a
3636    primary template instantiation, NULL otherwise.  */
3637 
3638 tree
get_primary_template_innermost_parameters(const_tree t)3639 get_primary_template_innermost_parameters (const_tree t)
3640 {
3641   tree parms = NULL, template_info = NULL;
3642 
3643   if ((template_info = get_template_info (t))
3644       && primary_template_specialization_p (t))
3645     parms = INNERMOST_TEMPLATE_PARMS
3646 	(DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
3647 
3648   return parms;
3649 }
3650 
3651 /* Return the template parameters of the LEVELth level from the full list
3652    of template parameters PARMS.  */
3653 
3654 tree
get_template_parms_at_level(tree parms,int level)3655 get_template_parms_at_level (tree parms, int level)
3656 {
3657   tree p;
3658   if (!parms
3659       || TREE_CODE (parms) != TREE_LIST
3660       || level > TMPL_PARMS_DEPTH (parms))
3661     return NULL_TREE;
3662 
3663   for (p = parms; p; p = TREE_CHAIN (p))
3664     if (TMPL_PARMS_DEPTH (p) == level)
3665       return p;
3666 
3667   return NULL_TREE;
3668 }
3669 
3670 /* Returns the template arguments of T if T is a template instantiation,
3671    NULL otherwise.  */
3672 
3673 tree
get_template_innermost_arguments(const_tree t)3674 get_template_innermost_arguments (const_tree t)
3675 {
3676   tree args = NULL, template_info = NULL;
3677 
3678   if ((template_info = get_template_info (t))
3679       && TI_ARGS (template_info))
3680     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
3681 
3682   return args;
3683 }
3684 
3685 /* Return the argument pack elements of T if T is a template argument pack,
3686    NULL otherwise.  */
3687 
3688 tree
get_template_argument_pack_elems(const_tree t)3689 get_template_argument_pack_elems (const_tree t)
3690 {
3691   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
3692       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
3693     return NULL;
3694 
3695   return ARGUMENT_PACK_ARGS (t);
3696 }
3697 
3698 /* In an ARGUMENT_PACK_SELECT, the actual underlying argument that the
3699    ARGUMENT_PACK_SELECT represents. */
3700 
3701 static tree
argument_pack_select_arg(tree t)3702 argument_pack_select_arg (tree t)
3703 {
3704   tree args = ARGUMENT_PACK_ARGS (ARGUMENT_PACK_SELECT_FROM_PACK (t));
3705   tree arg = TREE_VEC_ELT (args, ARGUMENT_PACK_SELECT_INDEX (t));
3706 
3707   /* If the selected argument is an expansion E, that most likely means we were
3708      called from gen_elem_of_pack_expansion_instantiation during the
3709      substituting of an argument pack (of which the Ith element is a pack
3710      expansion, where I is ARGUMENT_PACK_SELECT_INDEX) into a pack expansion.
3711      In this case, the Ith element resulting from this substituting is going to
3712      be a pack expansion, which pattern is the pattern of E.  Let's return the
3713      pattern of E, and gen_elem_of_pack_expansion_instantiation will build the
3714      resulting pack expansion from it.  */
3715   if (PACK_EXPANSION_P (arg))
3716     {
3717       /* Make sure we aren't throwing away arg info.  */
3718       gcc_assert (!PACK_EXPANSION_EXTRA_ARGS (arg));
3719       arg = PACK_EXPANSION_PATTERN (arg);
3720     }
3721 
3722   return arg;
3723 }
3724 
3725 
3726 /* True iff FN is a function representing a built-in variadic parameter
3727    pack.  */
3728 
3729 bool
builtin_pack_fn_p(tree fn)3730 builtin_pack_fn_p (tree fn)
3731 {
3732   if (!fn
3733       || TREE_CODE (fn) != FUNCTION_DECL
3734       || !DECL_IS_BUILTIN (fn))
3735     return false;
3736 
3737   if (id_equal (DECL_NAME (fn), "__integer_pack"))
3738     return true;
3739 
3740   return false;
3741 }
3742 
3743 /* True iff CALL is a call to a function representing a built-in variadic
3744    parameter pack.  */
3745 
3746 static bool
builtin_pack_call_p(tree call)3747 builtin_pack_call_p (tree call)
3748 {
3749   if (TREE_CODE (call) != CALL_EXPR)
3750     return false;
3751   return builtin_pack_fn_p (CALL_EXPR_FN (call));
3752 }
3753 
3754 /* Return a TREE_VEC for the expansion of __integer_pack(HI).  */
3755 
3756 static tree
expand_integer_pack(tree call,tree args,tsubst_flags_t complain,tree in_decl)3757 expand_integer_pack (tree call, tree args, tsubst_flags_t complain,
3758 		     tree in_decl)
3759 {
3760   tree ohi = CALL_EXPR_ARG (call, 0);
3761   tree hi = tsubst_copy_and_build (ohi, args, complain, in_decl,
3762 				   false/*fn*/, true/*int_cst*/);
3763 
3764   if (value_dependent_expression_p (hi))
3765     {
3766       if (hi != ohi)
3767 	{
3768 	  call = copy_node (call);
3769 	  CALL_EXPR_ARG (call, 0) = hi;
3770 	}
3771       tree ex = make_pack_expansion (call, complain);
3772       tree vec = make_tree_vec (1);
3773       TREE_VEC_ELT (vec, 0) = ex;
3774       return vec;
3775     }
3776   else
3777     {
3778       hi = cxx_constant_value (hi);
3779       int len = valid_constant_size_p (hi) ? tree_to_shwi (hi) : -1;
3780 
3781       /* Calculate the largest value of len that won't make the size of the vec
3782 	 overflow an int.  The compiler will exceed resource limits long before
3783 	 this, but it seems a decent place to diagnose.  */
3784       int max = ((INT_MAX - sizeof (tree_vec)) / sizeof (tree)) + 1;
3785 
3786       if (len < 0 || len > max)
3787 	{
3788 	  if ((complain & tf_error)
3789 	      && hi != error_mark_node)
3790 	    error ("argument to %<__integer_pack%> must be between 0 and %d",
3791 		   max);
3792 	  return error_mark_node;
3793 	}
3794 
3795       tree vec = make_tree_vec (len);
3796 
3797       for (int i = 0; i < len; ++i)
3798 	TREE_VEC_ELT (vec, i) = size_int (i);
3799 
3800       return vec;
3801     }
3802 }
3803 
3804 /* Return a TREE_VEC for the expansion of built-in template parameter pack
3805    CALL.  */
3806 
3807 static tree
expand_builtin_pack_call(tree call,tree args,tsubst_flags_t complain,tree in_decl)3808 expand_builtin_pack_call (tree call, tree args, tsubst_flags_t complain,
3809 			  tree in_decl)
3810 {
3811   if (!builtin_pack_call_p (call))
3812     return NULL_TREE;
3813 
3814   tree fn = CALL_EXPR_FN (call);
3815 
3816   if (id_equal (DECL_NAME (fn), "__integer_pack"))
3817     return expand_integer_pack (call, args, complain, in_decl);
3818 
3819   return NULL_TREE;
3820 }
3821 
3822 /* Structure used to track the progress of find_parameter_packs_r.  */
3823 struct find_parameter_pack_data
3824 {
3825   /* TREE_LIST that will contain all of the parameter packs found by
3826      the traversal.  */
3827   tree* parameter_packs;
3828 
3829   /* Set of AST nodes that have been visited by the traversal.  */
3830   hash_set<tree> *visited;
3831 
3832   /* True iff we're making a type pack expansion.  */
3833   bool type_pack_expansion_p;
3834 };
3835 
3836 /* Identifies all of the argument packs that occur in a template
3837    argument and appends them to the TREE_LIST inside DATA, which is a
3838    find_parameter_pack_data structure. This is a subroutine of
3839    make_pack_expansion and uses_parameter_packs.  */
3840 static tree
find_parameter_packs_r(tree * tp,int * walk_subtrees,void * data)3841 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
3842 {
3843   tree t = *tp;
3844   struct find_parameter_pack_data* ppd =
3845     (struct find_parameter_pack_data*)data;
3846   bool parameter_pack_p = false;
3847 
3848   /* Don't look through typedefs; we are interested in whether a
3849      parameter pack is actually written in the expression/type we're
3850      looking at, not the target type.  */
3851   if (TYPE_P (t) && typedef_variant_p (t))
3852     {
3853       /* But do look at arguments for an alias template.  */
3854       if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
3855 	cp_walk_tree (&TI_ARGS (tinfo),
3856 		      &find_parameter_packs_r,
3857 		      ppd, ppd->visited);
3858       *walk_subtrees = 0;
3859       return NULL_TREE;
3860     }
3861 
3862   /* Identify whether this is a parameter pack or not.  */
3863   switch (TREE_CODE (t))
3864     {
3865     case TEMPLATE_PARM_INDEX:
3866       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3867         parameter_pack_p = true;
3868       break;
3869 
3870     case TEMPLATE_TYPE_PARM:
3871       t = TYPE_MAIN_VARIANT (t);
3872       /* FALLTHRU */
3873     case TEMPLATE_TEMPLATE_PARM:
3874       /* If the placeholder appears in the decl-specifier-seq of a function
3875 	 parameter pack (14.6.3), or the type-specifier-seq of a type-id that
3876 	 is a pack expansion, the invented template parameter is a template
3877 	 parameter pack.  */
3878       if (ppd->type_pack_expansion_p && is_auto (t))
3879 	TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
3880       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3881         parameter_pack_p = true;
3882       break;
3883 
3884     case FIELD_DECL:
3885     case PARM_DECL:
3886       if (DECL_PACK_P (t))
3887         {
3888           /* We don't want to walk into the type of a PARM_DECL,
3889              because we don't want to see the type parameter pack.  */
3890           *walk_subtrees = 0;
3891 	  parameter_pack_p = true;
3892         }
3893       break;
3894 
3895     case VAR_DECL:
3896       if (DECL_PACK_P (t))
3897         {
3898           /* We don't want to walk into the type of a variadic capture proxy,
3899              because we don't want to see the type parameter pack.  */
3900           *walk_subtrees = 0;
3901 	  parameter_pack_p = true;
3902         }
3903       else if (variable_template_specialization_p (t))
3904 	{
3905 	  cp_walk_tree (&DECL_TI_ARGS (t),
3906 			find_parameter_packs_r,
3907 			ppd, ppd->visited);
3908 	  *walk_subtrees = 0;
3909 	}
3910       break;
3911 
3912     case CALL_EXPR:
3913       if (builtin_pack_call_p (t))
3914 	parameter_pack_p = true;
3915       break;
3916 
3917     case BASES:
3918       parameter_pack_p = true;
3919       break;
3920     default:
3921       /* Not a parameter pack.  */
3922       break;
3923     }
3924 
3925   if (parameter_pack_p)
3926     {
3927       /* Add this parameter pack to the list.  */
3928       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
3929     }
3930 
3931   if (TYPE_P (t))
3932     cp_walk_tree (&TYPE_CONTEXT (t),
3933 		  &find_parameter_packs_r, ppd, ppd->visited);
3934 
3935   /* This switch statement will return immediately if we don't find a
3936      parameter pack.  ??? Should some of these be in cp_walk_subtrees?  */
3937   switch (TREE_CODE (t))
3938     {
3939     case BOUND_TEMPLATE_TEMPLATE_PARM:
3940       /* Check the template itself.  */
3941       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)),
3942 		    &find_parameter_packs_r, ppd, ppd->visited);
3943       return NULL_TREE;
3944 
3945     case DECL_EXPR:
3946       {
3947 	tree decl = DECL_EXPR_DECL (t);
3948 	/* Ignore the declaration of a capture proxy for a parameter pack.  */
3949 	if (is_capture_proxy (decl))
3950 	  *walk_subtrees = 0;
3951 	if (is_typedef_decl (decl))
3952 	  /* Since we stop at typedefs above, we need to look through them at
3953 	     the point of the DECL_EXPR.  */
3954 	  cp_walk_tree (&DECL_ORIGINAL_TYPE (decl),
3955 			&find_parameter_packs_r, ppd, ppd->visited);
3956 	return NULL_TREE;
3957       }
3958 
3959     case TEMPLATE_DECL:
3960       if (!DECL_TEMPLATE_TEMPLATE_PARM_P (t))
3961 	return NULL_TREE;
3962       cp_walk_tree (&TREE_TYPE (t),
3963 		    &find_parameter_packs_r, ppd, ppd->visited);
3964       return NULL_TREE;
3965 
3966     case TYPENAME_TYPE:
3967       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3968                    ppd, ppd->visited);
3969       *walk_subtrees = 0;
3970       return NULL_TREE;
3971 
3972     case TYPE_PACK_EXPANSION:
3973     case EXPR_PACK_EXPANSION:
3974       *walk_subtrees = 0;
3975       return NULL_TREE;
3976 
3977     case INTEGER_TYPE:
3978       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r,
3979 		    ppd, ppd->visited);
3980       *walk_subtrees = 0;
3981       return NULL_TREE;
3982 
3983     case IDENTIFIER_NODE:
3984       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd,
3985 		    ppd->visited);
3986       *walk_subtrees = 0;
3987       return NULL_TREE;
3988 
3989     case LAMBDA_EXPR:
3990       {
3991 	/* Look at explicit captures.  */
3992 	for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t);
3993 	     cap; cap = TREE_CHAIN (cap))
3994 	  cp_walk_tree (&TREE_VALUE (cap), &find_parameter_packs_r, ppd,
3995 			ppd->visited);
3996 	/* Since we defer implicit capture, look in the parms and body.  */
3997 	tree fn = lambda_function (t);
3998 	cp_walk_tree (&TREE_TYPE (fn), &find_parameter_packs_r, ppd,
3999 		      ppd->visited);
4000 	cp_walk_tree (&DECL_SAVED_TREE (fn), &find_parameter_packs_r, ppd,
4001 		      ppd->visited);
4002 	*walk_subtrees = 0;
4003 	return NULL_TREE;
4004       }
4005 
4006     case DECLTYPE_TYPE:
4007       {
4008 	/* When traversing a DECLTYPE_TYPE_EXPR, we need to set
4009 	   type_pack_expansion_p to false so that any placeholders
4010 	   within the expression don't get marked as parameter packs.  */
4011 	bool type_pack_expansion_p = ppd->type_pack_expansion_p;
4012 	ppd->type_pack_expansion_p = false;
4013 	cp_walk_tree (&DECLTYPE_TYPE_EXPR (t), &find_parameter_packs_r,
4014 		      ppd, ppd->visited);
4015 	ppd->type_pack_expansion_p = type_pack_expansion_p;
4016 	*walk_subtrees = 0;
4017 	return NULL_TREE;
4018       }
4019 
4020     case IF_STMT:
4021       cp_walk_tree (&IF_COND (t), &find_parameter_packs_r,
4022 		    ppd, ppd->visited);
4023       cp_walk_tree (&THEN_CLAUSE (t), &find_parameter_packs_r,
4024 		    ppd, ppd->visited);
4025       cp_walk_tree (&ELSE_CLAUSE (t), &find_parameter_packs_r,
4026 		    ppd, ppd->visited);
4027       /* Don't walk into IF_STMT_EXTRA_ARGS.  */
4028       *walk_subtrees = 0;
4029       return NULL_TREE;
4030 
4031     default:
4032       return NULL_TREE;
4033     }
4034 
4035   return NULL_TREE;
4036 }
4037 
4038 /* Determines if the expression or type T uses any parameter packs.  */
4039 tree
uses_parameter_packs(tree t)4040 uses_parameter_packs (tree t)
4041 {
4042   tree parameter_packs = NULL_TREE;
4043   struct find_parameter_pack_data ppd;
4044   ppd.parameter_packs = &parameter_packs;
4045   ppd.visited = new hash_set<tree>;
4046   ppd.type_pack_expansion_p = false;
4047   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4048   delete ppd.visited;
4049   return parameter_packs;
4050 }
4051 
4052 /* Turn ARG, which may be an expression, type, or a TREE_LIST
4053    representation a base-class initializer into a parameter pack
4054    expansion. If all goes well, the resulting node will be an
4055    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
4056    respectively.  */
4057 tree
make_pack_expansion(tree arg,tsubst_flags_t complain)4058 make_pack_expansion (tree arg, tsubst_flags_t complain)
4059 {
4060   tree result;
4061   tree parameter_packs = NULL_TREE;
4062   bool for_types = false;
4063   struct find_parameter_pack_data ppd;
4064 
4065   if (!arg || arg == error_mark_node)
4066     return arg;
4067 
4068   if (TREE_CODE (arg) == TREE_LIST && TREE_PURPOSE (arg))
4069     {
4070       /* A TREE_LIST with a non-null TREE_PURPOSE is for a base
4071          class initializer.  In this case, the TREE_PURPOSE will be a
4072          _TYPE node (representing the base class expansion we're
4073          initializing) and the TREE_VALUE will be a TREE_LIST
4074          containing the initialization arguments.
4075 
4076          The resulting expansion looks somewhat different from most
4077          expansions. Rather than returning just one _EXPANSION, we
4078          return a TREE_LIST whose TREE_PURPOSE is a
4079          TYPE_PACK_EXPANSION containing the bases that will be
4080          initialized.  The TREE_VALUE will be identical to the
4081          original TREE_VALUE, which is a list of arguments that will
4082          be passed to each base.  We do not introduce any new pack
4083          expansion nodes into the TREE_VALUE (although it is possible
4084          that some already exist), because the TREE_PURPOSE and
4085          TREE_VALUE all need to be expanded together with the same
4086          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
4087          resulting TREE_PURPOSE will mention the parameter packs in
4088          both the bases and the arguments to the bases.  */
4089       tree purpose;
4090       tree value;
4091       tree parameter_packs = NULL_TREE;
4092 
4093       /* Determine which parameter packs will be used by the base
4094          class expansion.  */
4095       ppd.visited = new hash_set<tree>;
4096       ppd.parameter_packs = &parameter_packs;
4097       ppd.type_pack_expansion_p = false;
4098       gcc_assert (TYPE_P (TREE_PURPOSE (arg)));
4099       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r,
4100                     &ppd, ppd.visited);
4101 
4102       if (parameter_packs == NULL_TREE)
4103         {
4104 	  if (complain & tf_error)
4105 	    error ("base initializer expansion %qT contains no parameter packs",
4106 		   arg);
4107           delete ppd.visited;
4108           return error_mark_node;
4109         }
4110 
4111       if (TREE_VALUE (arg) != void_type_node)
4112         {
4113           /* Collect the sets of parameter packs used in each of the
4114              initialization arguments.  */
4115           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
4116             {
4117               /* Determine which parameter packs will be expanded in this
4118                  argument.  */
4119               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r,
4120                             &ppd, ppd.visited);
4121             }
4122         }
4123 
4124       delete ppd.visited;
4125 
4126       /* Create the pack expansion type for the base type.  */
4127       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
4128       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
4129       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
4130       PACK_EXPANSION_LOCAL_P (purpose) = at_function_scope_p ();
4131 
4132       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4133 	 they will rarely be compared to anything.  */
4134       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
4135 
4136       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
4137     }
4138 
4139   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
4140     for_types = true;
4141 
4142   /* Build the PACK_EXPANSION_* node.  */
4143   result = for_types
4144      ? cxx_make_type (TYPE_PACK_EXPANSION)
4145      : make_node (EXPR_PACK_EXPANSION);
4146   SET_PACK_EXPANSION_PATTERN (result, arg);
4147   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
4148     {
4149       /* Propagate type and const-expression information.  */
4150       TREE_TYPE (result) = TREE_TYPE (arg);
4151       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
4152       /* Mark this read now, since the expansion might be length 0.  */
4153       mark_exp_read (arg);
4154     }
4155   else
4156     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4157        they will rarely be compared to anything.  */
4158     SET_TYPE_STRUCTURAL_EQUALITY (result);
4159 
4160   /* Determine which parameter packs will be expanded.  */
4161   ppd.parameter_packs = &parameter_packs;
4162   ppd.visited = new hash_set<tree>;
4163   ppd.type_pack_expansion_p = TYPE_P (arg);
4164   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
4165   delete ppd.visited;
4166 
4167   /* Make sure we found some parameter packs.  */
4168   if (parameter_packs == NULL_TREE)
4169     {
4170       if (complain & tf_error)
4171 	{
4172 	  if (TYPE_P (arg))
4173 	    error ("expansion pattern %qT contains no parameter packs", arg);
4174 	  else
4175 	    error ("expansion pattern %qE contains no parameter packs", arg);
4176 	}
4177       return error_mark_node;
4178     }
4179   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
4180 
4181   PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
4182 
4183   return result;
4184 }
4185 
4186 /* Checks T for any "bare" parameter packs, which have not yet been
4187    expanded, and issues an error if any are found. This operation can
4188    only be done on full expressions or types (e.g., an expression
4189    statement, "if" condition, etc.), because we could have expressions like:
4190 
4191      foo(f(g(h(args)))...)
4192 
4193    where "args" is a parameter pack. check_for_bare_parameter_packs
4194    should not be called for the subexpressions args, h(args),
4195    g(h(args)), or f(g(h(args))), because we would produce erroneous
4196    error messages.
4197 
4198    Returns TRUE and emits an error if there were bare parameter packs,
4199    returns FALSE otherwise.  */
4200 bool
check_for_bare_parameter_packs(tree t,location_t loc)4201 check_for_bare_parameter_packs (tree t, location_t loc /* = UNKNOWN_LOCATION */)
4202 {
4203   tree parameter_packs = NULL_TREE;
4204   struct find_parameter_pack_data ppd;
4205 
4206   if (!processing_template_decl || !t || t == error_mark_node)
4207     return false;
4208 
4209   /* A lambda might use a parameter pack from the containing context.  */
4210   if (current_class_type && LAMBDA_TYPE_P (current_class_type)
4211       && CLASSTYPE_TEMPLATE_INFO (current_class_type))
4212     return false;
4213 
4214   if (TREE_CODE (t) == TYPE_DECL)
4215     t = TREE_TYPE (t);
4216 
4217   ppd.parameter_packs = &parameter_packs;
4218   ppd.visited = new hash_set<tree>;
4219   ppd.type_pack_expansion_p = false;
4220   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4221   delete ppd.visited;
4222 
4223   if (parameter_packs)
4224     {
4225       if (loc == UNKNOWN_LOCATION)
4226 	loc = cp_expr_loc_or_input_loc (t);
4227       error_at (loc, "parameter packs not expanded with %<...%>:");
4228       while (parameter_packs)
4229         {
4230           tree pack = TREE_VALUE (parameter_packs);
4231           tree name = NULL_TREE;
4232 
4233           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
4234               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
4235             name = TYPE_NAME (pack);
4236           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
4237             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
4238 	  else if (TREE_CODE (pack) == CALL_EXPR)
4239 	    name = DECL_NAME (CALL_EXPR_FN (pack));
4240           else
4241             name = DECL_NAME (pack);
4242 
4243 	  if (name)
4244 	    inform (loc, "        %qD", name);
4245 	  else
4246 	    inform (loc, "        %s", "<anonymous>");
4247 
4248           parameter_packs = TREE_CHAIN (parameter_packs);
4249         }
4250 
4251       return true;
4252     }
4253 
4254   return false;
4255 }
4256 
4257 /* Expand any parameter packs that occur in the template arguments in
4258    ARGS.  */
4259 tree
expand_template_argument_pack(tree args)4260 expand_template_argument_pack (tree args)
4261 {
4262   if (args == error_mark_node)
4263     return error_mark_node;
4264 
4265   tree result_args = NULL_TREE;
4266   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
4267   int num_result_args = -1;
4268   int non_default_args_count = -1;
4269 
4270   /* First, determine if we need to expand anything, and the number of
4271      slots we'll need.  */
4272   for (in_arg = 0; in_arg < nargs; ++in_arg)
4273     {
4274       tree arg = TREE_VEC_ELT (args, in_arg);
4275       if (arg == NULL_TREE)
4276 	return args;
4277       if (ARGUMENT_PACK_P (arg))
4278         {
4279           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
4280           if (num_result_args < 0)
4281             num_result_args = in_arg + num_packed;
4282           else
4283             num_result_args += num_packed;
4284         }
4285       else
4286         {
4287           if (num_result_args >= 0)
4288             num_result_args++;
4289         }
4290     }
4291 
4292   /* If no expansion is necessary, we're done.  */
4293   if (num_result_args < 0)
4294     return args;
4295 
4296   /* Expand arguments.  */
4297   result_args = make_tree_vec (num_result_args);
4298   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
4299     non_default_args_count =
4300       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
4301   for (in_arg = 0; in_arg < nargs; ++in_arg)
4302     {
4303       tree arg = TREE_VEC_ELT (args, in_arg);
4304       if (ARGUMENT_PACK_P (arg))
4305         {
4306           tree packed = ARGUMENT_PACK_ARGS (arg);
4307           int i, num_packed = TREE_VEC_LENGTH (packed);
4308           for (i = 0; i < num_packed; ++i, ++out_arg)
4309             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
4310 	  if (non_default_args_count > 0)
4311 	    non_default_args_count += num_packed - 1;
4312         }
4313       else
4314         {
4315           TREE_VEC_ELT (result_args, out_arg) = arg;
4316           ++out_arg;
4317         }
4318     }
4319   if (non_default_args_count >= 0)
4320     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
4321   return result_args;
4322 }
4323 
4324 /* Checks if DECL shadows a template parameter.
4325 
4326    [temp.local]: A template-parameter shall not be redeclared within its
4327    scope (including nested scopes).
4328 
4329    Emits an error and returns TRUE if the DECL shadows a parameter,
4330    returns FALSE otherwise.  */
4331 
4332 bool
check_template_shadow(tree decl)4333 check_template_shadow (tree decl)
4334 {
4335   tree olddecl;
4336 
4337   /* If we're not in a template, we can't possibly shadow a template
4338      parameter.  */
4339   if (!current_template_parms)
4340     return true;
4341 
4342   /* Figure out what we're shadowing.  */
4343   decl = OVL_FIRST (decl);
4344   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
4345 
4346   /* If there's no previous binding for this name, we're not shadowing
4347      anything, let alone a template parameter.  */
4348   if (!olddecl)
4349     return true;
4350 
4351   /* If we're not shadowing a template parameter, we're done.  Note
4352      that OLDDECL might be an OVERLOAD (or perhaps even an
4353      ERROR_MARK), so we can't just blithely assume it to be a _DECL
4354      node.  */
4355   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
4356     return true;
4357 
4358   /* We check for decl != olddecl to avoid bogus errors for using a
4359      name inside a class.  We check TPFI to avoid duplicate errors for
4360      inline member templates.  */
4361   if (decl == olddecl
4362       || (DECL_TEMPLATE_PARM_P (decl)
4363 	  && TEMPLATE_PARMS_FOR_INLINE (current_template_parms)))
4364     return true;
4365 
4366   /* Don't complain about the injected class name, as we've already
4367      complained about the class itself.  */
4368   if (DECL_SELF_REFERENCE_P (decl))
4369     return false;
4370 
4371   if (DECL_TEMPLATE_PARM_P (decl))
4372     error ("declaration of template parameter %q+D shadows "
4373 	   "template parameter", decl);
4374   else
4375     error ("declaration of %q+#D shadows template parameter", decl);
4376   inform (DECL_SOURCE_LOCATION (olddecl),
4377 	  "template parameter %qD declared here", olddecl);
4378   return false;
4379 }
4380 
4381 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
4382    ORIG_LEVEL, DECL, and TYPE.  */
4383 
4384 static tree
build_template_parm_index(int index,int level,int orig_level,tree decl,tree type)4385 build_template_parm_index (int index,
4386 			   int level,
4387 			   int orig_level,
4388 			   tree decl,
4389 			   tree type)
4390 {
4391   tree t = make_node (TEMPLATE_PARM_INDEX);
4392   TEMPLATE_PARM_IDX (t) = index;
4393   TEMPLATE_PARM_LEVEL (t) = level;
4394   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
4395   TEMPLATE_PARM_DECL (t) = decl;
4396   TREE_TYPE (t) = type;
4397   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
4398   TREE_READONLY (t) = TREE_READONLY (decl);
4399 
4400   return t;
4401 }
4402 
4403 /* Find the canonical type parameter for the given template type
4404    parameter.  Returns the canonical type parameter, which may be TYPE
4405    if no such parameter existed.  */
4406 
4407 static tree
canonical_type_parameter(tree type)4408 canonical_type_parameter (tree type)
4409 {
4410   tree list;
4411   int idx = TEMPLATE_TYPE_IDX (type);
4412 
4413   gcc_assert (TREE_CODE (type) != TEMPLATE_TEMPLATE_PARM);
4414 
4415   if (!canonical_template_parms)
4416     vec_alloc (canonical_template_parms, idx + 1);
4417 
4418   if (canonical_template_parms->length () <= (unsigned) idx)
4419     vec_safe_grow_cleared (canonical_template_parms, idx + 1);
4420 
4421   list = (*canonical_template_parms)[idx];
4422   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
4423     list = TREE_CHAIN (list);
4424 
4425   if (list)
4426     return TREE_VALUE (list);
4427   else
4428     {
4429       (*canonical_template_parms)[idx]
4430 	= tree_cons (NULL_TREE, type, (*canonical_template_parms)[idx]);
4431       return type;
4432     }
4433 }
4434 
4435 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
4436    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
4437    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
4438    new one is created.  */
4439 
4440 static tree
reduce_template_parm_level(tree index,tree type,int levels,tree args,tsubst_flags_t complain)4441 reduce_template_parm_level (tree index, tree type, int levels, tree args,
4442 			    tsubst_flags_t complain)
4443 {
4444   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
4445       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
4446 	  != TEMPLATE_PARM_LEVEL (index) - levels)
4447       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
4448     {
4449       tree orig_decl = TEMPLATE_PARM_DECL (index);
4450 
4451       tree decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
4452 			      TREE_CODE (orig_decl), DECL_NAME (orig_decl),
4453 			      type);
4454       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
4455       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
4456       DECL_VIRTUAL_P (decl) = DECL_VIRTUAL_P (orig_decl);
4457       DECL_ARTIFICIAL (decl) = 1;
4458       SET_DECL_TEMPLATE_PARM_P (decl);
4459 
4460       tree tpi = build_template_parm_index (TEMPLATE_PARM_IDX (index),
4461 					    TEMPLATE_PARM_LEVEL (index) - levels,
4462 					    TEMPLATE_PARM_ORIG_LEVEL (index),
4463 					    decl, type);
4464       TEMPLATE_PARM_DESCENDANTS (index) = tpi;
4465       TEMPLATE_PARM_PARAMETER_PACK (tpi)
4466 	= TEMPLATE_PARM_PARAMETER_PACK (index);
4467 
4468 	/* Template template parameters need this.  */
4469       tree inner = decl;
4470       if (TREE_CODE (decl) == TEMPLATE_DECL)
4471 	{
4472 	  inner = build_decl (DECL_SOURCE_LOCATION (decl),
4473 			      TYPE_DECL, DECL_NAME (decl), type);
4474 	  DECL_TEMPLATE_RESULT (decl) = inner;
4475 	  DECL_ARTIFICIAL (inner) = true;
4476 	  DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
4477 	    (DECL_TEMPLATE_PARMS (orig_decl), args, complain);
4478 	}
4479 
4480       /* Attach the TPI to the decl.  */
4481       if (TREE_CODE (inner) == TYPE_DECL)
4482 	TEMPLATE_TYPE_PARM_INDEX (type) = tpi;
4483       else
4484 	DECL_INITIAL (decl) = tpi;
4485     }
4486 
4487   return TEMPLATE_PARM_DESCENDANTS (index);
4488 }
4489 
4490 /* Process information from new template parameter PARM and append it
4491    to the LIST being built.  This new parameter is a non-type
4492    parameter iff IS_NON_TYPE is true. This new parameter is a
4493    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
4494    is in PARM_LOC.  */
4495 
4496 tree
process_template_parm(tree list,location_t parm_loc,tree parm,bool is_non_type,bool is_parameter_pack)4497 process_template_parm (tree list, location_t parm_loc, tree parm,
4498 		       bool is_non_type, bool is_parameter_pack)
4499 {
4500   tree decl = 0;
4501   int idx = 0;
4502 
4503   gcc_assert (TREE_CODE (parm) == TREE_LIST);
4504   tree defval = TREE_PURPOSE (parm);
4505   tree constr = TREE_TYPE (parm);
4506 
4507   if (list)
4508     {
4509       tree p = tree_last (list);
4510 
4511       if (p && TREE_VALUE (p) != error_mark_node)
4512         {
4513           p = TREE_VALUE (p);
4514           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
4515             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
4516           else
4517             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
4518         }
4519 
4520       ++idx;
4521     }
4522 
4523   if (is_non_type)
4524     {
4525       parm = TREE_VALUE (parm);
4526 
4527       SET_DECL_TEMPLATE_PARM_P (parm);
4528 
4529       if (TREE_TYPE (parm) != error_mark_node)
4530 	{
4531 	  /* [temp.param]
4532 
4533 	     The top-level cv-qualifiers on the template-parameter are
4534 	     ignored when determining its type.  */
4535 	  TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
4536 	  if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
4537 	    TREE_TYPE (parm) = error_mark_node;
4538 	  else if (uses_parameter_packs (TREE_TYPE (parm))
4539 		   && !is_parameter_pack
4540 		   /* If we're in a nested template parameter list, the template
4541 		      template parameter could be a parameter pack.  */
4542 		   && processing_template_parmlist == 1)
4543 	    {
4544 	      /* This template parameter is not a parameter pack, but it
4545 		 should be. Complain about "bare" parameter packs.  */
4546 	      check_for_bare_parameter_packs (TREE_TYPE (parm));
4547 
4548 	      /* Recover by calling this a parameter pack.  */
4549 	      is_parameter_pack = true;
4550 	    }
4551 	}
4552 
4553       /* A template parameter is not modifiable.  */
4554       TREE_CONSTANT (parm) = 1;
4555       TREE_READONLY (parm) = 1;
4556       decl = build_decl (parm_loc,
4557 			 CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
4558       TREE_CONSTANT (decl) = 1;
4559       TREE_READONLY (decl) = 1;
4560       DECL_INITIAL (parm) = DECL_INITIAL (decl)
4561 	= build_template_parm_index (idx, processing_template_decl,
4562 				     processing_template_decl,
4563 				     decl, TREE_TYPE (parm));
4564 
4565       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4566 	= is_parameter_pack;
4567     }
4568   else
4569     {
4570       tree t;
4571       parm = TREE_VALUE (TREE_VALUE (parm));
4572 
4573       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
4574 	{
4575 	  t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
4576 	  /* This is for distinguishing between real templates and template
4577 	     template parameters */
4578 	  TREE_TYPE (parm) = t;
4579 
4580 	  /* any_template_parm_r expects to be able to get the targs of a
4581 	     DECL_TEMPLATE_RESULT.  */
4582 	  tree result = DECL_TEMPLATE_RESULT (parm);
4583 	  TREE_TYPE (result) = t;
4584 	  tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (parm));
4585 	  tree tinfo = build_template_info (parm, args);
4586 	  retrofit_lang_decl (result);
4587 	  DECL_TEMPLATE_INFO (result) = tinfo;
4588 
4589 	  decl = parm;
4590 	}
4591       else
4592 	{
4593 	  t = cxx_make_type (TEMPLATE_TYPE_PARM);
4594 	  /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
4595 	  decl = build_decl (parm_loc,
4596 			     TYPE_DECL, parm, t);
4597 	}
4598 
4599       TYPE_NAME (t) = decl;
4600       TYPE_STUB_DECL (t) = decl;
4601       parm = decl;
4602       TEMPLATE_TYPE_PARM_INDEX (t)
4603 	= build_template_parm_index (idx, processing_template_decl,
4604 				     processing_template_decl,
4605 				     decl, TREE_TYPE (parm));
4606       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
4607       if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
4608 	SET_TYPE_STRUCTURAL_EQUALITY (t);
4609       else
4610 	TYPE_CANONICAL (t) = canonical_type_parameter (t);
4611     }
4612   DECL_ARTIFICIAL (decl) = 1;
4613   SET_DECL_TEMPLATE_PARM_P (decl);
4614 
4615   /* Build requirements for the type/template parameter.
4616      This must be done after SET_DECL_TEMPLATE_PARM_P or
4617      process_template_parm could fail. */
4618   tree reqs = finish_shorthand_constraint (parm, constr);
4619 
4620   decl = pushdecl (decl);
4621   if (!is_non_type)
4622     parm = decl;
4623 
4624   /* Build the parameter node linking the parameter declaration,
4625      its default argument (if any), and its constraints (if any). */
4626   parm = build_tree_list (defval, parm);
4627   TEMPLATE_PARM_CONSTRAINTS (parm) = reqs;
4628 
4629   return chainon (list, parm);
4630 }
4631 
4632 /* The end of a template parameter list has been reached.  Process the
4633    tree list into a parameter vector, converting each parameter into a more
4634    useful form.	 Type parameters are saved as IDENTIFIER_NODEs, and others
4635    as PARM_DECLs.  */
4636 
4637 tree
end_template_parm_list(tree parms)4638 end_template_parm_list (tree parms)
4639 {
4640   int nparms;
4641   tree parm, next;
4642   tree saved_parmlist = make_tree_vec (list_length (parms));
4643 
4644   /* Pop the dummy parameter level and add the real one.  */
4645   current_template_parms = TREE_CHAIN (current_template_parms);
4646 
4647   current_template_parms
4648     = tree_cons (size_int (processing_template_decl),
4649 		 saved_parmlist, current_template_parms);
4650 
4651   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
4652     {
4653       next = TREE_CHAIN (parm);
4654       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
4655       TREE_CHAIN (parm) = NULL_TREE;
4656     }
4657 
4658   --processing_template_parmlist;
4659 
4660   return saved_parmlist;
4661 }
4662 
4663 // Explicitly indicate the end of the template parameter list. We assume
4664 // that the current template parameters have been constructed and/or
4665 // managed explicitly, as when creating new template template parameters
4666 // from a shorthand constraint.
4667 void
end_template_parm_list()4668 end_template_parm_list ()
4669 {
4670   --processing_template_parmlist;
4671 }
4672 
4673 /* end_template_decl is called after a template declaration is seen.  */
4674 
4675 void
end_template_decl(void)4676 end_template_decl (void)
4677 {
4678   reset_specialization ();
4679 
4680   if (! processing_template_decl)
4681     return;
4682 
4683   /* This matches the pushlevel in begin_template_parm_list.  */
4684   finish_scope ();
4685 
4686   --processing_template_decl;
4687   current_template_parms = TREE_CHAIN (current_template_parms);
4688 }
4689 
4690 /* Takes a TEMPLATE_PARM_P or DECL_TEMPLATE_PARM_P node or a TREE_LIST
4691    thereof, and converts it into an argument suitable to be passed to
4692    the type substitution functions.  Note that if the TREE_LIST contains
4693    an error_mark node, the returned argument is error_mark_node.  */
4694 
4695 tree
template_parm_to_arg(tree t)4696 template_parm_to_arg (tree t)
4697 {
4698   if (!t)
4699     return NULL_TREE;
4700 
4701   if (TREE_CODE (t) == TREE_LIST)
4702     t = TREE_VALUE (t);
4703 
4704   if (error_operand_p (t))
4705     return error_mark_node;
4706 
4707   if (DECL_P (t) && DECL_TEMPLATE_PARM_P (t))
4708     {
4709       if (TREE_CODE (t) == TYPE_DECL
4710 	  || TREE_CODE (t) == TEMPLATE_DECL)
4711 	t = TREE_TYPE (t);
4712       else
4713 	t = DECL_INITIAL (t);
4714     }
4715 
4716   gcc_assert (TEMPLATE_PARM_P (t));
4717 
4718   if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
4719       || TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
4720     {
4721       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
4722 	{
4723 	  /* Turn this argument into a TYPE_ARGUMENT_PACK
4724 	     with a single element, which expands T.  */
4725 	  tree vec = make_tree_vec (1);
4726 	  if (CHECKING_P)
4727 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4728 
4729 	  TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4730 
4731 	  t = cxx_make_type (TYPE_ARGUMENT_PACK);
4732 	  SET_ARGUMENT_PACK_ARGS (t, vec);
4733 	}
4734     }
4735   else
4736     {
4737       if (TEMPLATE_PARM_PARAMETER_PACK (t))
4738 	{
4739 	  /* Turn this argument into a NONTYPE_ARGUMENT_PACK
4740 	     with a single element, which expands T.  */
4741 	  tree vec = make_tree_vec (1);
4742 	  if (CHECKING_P)
4743 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4744 
4745 	  t = convert_from_reference (t);
4746 	  TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4747 
4748 	  t  = make_node (NONTYPE_ARGUMENT_PACK);
4749 	  SET_ARGUMENT_PACK_ARGS (t, vec);
4750 	}
4751       else
4752 	t = convert_from_reference (t);
4753     }
4754   return t;
4755 }
4756 
4757 /* Given a single level of template parameters (a TREE_VEC), return it
4758    as a set of template arguments.  */
4759 
4760 tree
template_parms_level_to_args(tree parms)4761 template_parms_level_to_args (tree parms)
4762 {
4763   tree a = copy_node (parms);
4764   TREE_TYPE (a) = NULL_TREE;
4765   for (int i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4766     TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4767 
4768   if (CHECKING_P)
4769     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4770 
4771   return a;
4772 }
4773 
4774 /* Given a set of template parameters, return them as a set of template
4775    arguments.  The template parameters are represented as a TREE_VEC, in
4776    the form documented in cp-tree.h for template arguments.  */
4777 
4778 tree
template_parms_to_args(tree parms)4779 template_parms_to_args (tree parms)
4780 {
4781   tree header;
4782   tree args = NULL_TREE;
4783   int length = TMPL_PARMS_DEPTH (parms);
4784   int l = length;
4785 
4786   /* If there is only one level of template parameters, we do not
4787      create a TREE_VEC of TREE_VECs.  Instead, we return a single
4788      TREE_VEC containing the arguments.  */
4789   if (length > 1)
4790     args = make_tree_vec (length);
4791 
4792   for (header = parms; header; header = TREE_CHAIN (header))
4793     {
4794       tree a = template_parms_level_to_args (TREE_VALUE (header));
4795 
4796       if (length > 1)
4797 	TREE_VEC_ELT (args, --l) = a;
4798       else
4799 	args = a;
4800     }
4801 
4802   return args;
4803 }
4804 
4805 /* Within the declaration of a template, return the currently active
4806    template parameters as an argument TREE_VEC.  */
4807 
4808 static tree
current_template_args(void)4809 current_template_args (void)
4810 {
4811   return template_parms_to_args (current_template_parms);
4812 }
4813 
4814 /* Return the fully generic arguments for of TMPL, i.e. what
4815    current_template_args would be while parsing it.  */
4816 
4817 tree
generic_targs_for(tree tmpl)4818 generic_targs_for (tree tmpl)
4819 {
4820   if (tmpl == NULL_TREE)
4821     return NULL_TREE;
4822   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
4823       || DECL_TEMPLATE_SPECIALIZATION (tmpl))
4824     /* DECL_TEMPLATE_RESULT doesn't have the arguments we want.  For a template
4825        template parameter, it has no TEMPLATE_INFO; for a partial
4826        specialization, it has the arguments for the primary template, and we
4827        want the arguments for the partial specialization.  */;
4828   else if (tree result = DECL_TEMPLATE_RESULT (tmpl))
4829     if (tree ti = get_template_info (result))
4830       return TI_ARGS (ti);
4831   return template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl));
4832 }
4833 
4834 /* Update the declared TYPE by doing any lookups which were thought to be
4835    dependent, but are not now that we know the SCOPE of the declarator.  */
4836 
4837 tree
maybe_update_decl_type(tree orig_type,tree scope)4838 maybe_update_decl_type (tree orig_type, tree scope)
4839 {
4840   tree type = orig_type;
4841 
4842   if (type == NULL_TREE)
4843     return type;
4844 
4845   if (TREE_CODE (orig_type) == TYPE_DECL)
4846     type = TREE_TYPE (type);
4847 
4848   if (scope && TYPE_P (scope) && dependent_type_p (scope)
4849       && dependent_type_p (type)
4850       /* Don't bother building up the args in this case.  */
4851       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4852     {
4853       /* tsubst in the args corresponding to the template parameters,
4854 	 including auto if present.  Most things will be unchanged, but
4855 	 make_typename_type and tsubst_qualified_id will resolve
4856 	 TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
4857       tree args = current_template_args ();
4858       tree auto_node = type_uses_auto (type);
4859       tree pushed;
4860       if (auto_node)
4861 	{
4862 	  tree auto_vec = make_tree_vec (1);
4863 	  TREE_VEC_ELT (auto_vec, 0) = auto_node;
4864 	  args = add_to_template_args (args, auto_vec);
4865 	}
4866       pushed = push_scope (scope);
4867       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4868       if (pushed)
4869 	pop_scope (scope);
4870     }
4871 
4872   if (type == error_mark_node)
4873     return orig_type;
4874 
4875   if (TREE_CODE (orig_type) == TYPE_DECL)
4876     {
4877       if (same_type_p (type, TREE_TYPE (orig_type)))
4878 	type = orig_type;
4879       else
4880 	type = TYPE_NAME (type);
4881     }
4882   return type;
4883 }
4884 
4885 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4886    template PARMS and constraints, CONSTR.  If MEMBER_TEMPLATE_P is true,
4887    the new  template is a member template. */
4888 
4889 static tree
build_template_decl(tree decl,tree parms,bool member_template_p)4890 build_template_decl (tree decl, tree parms, bool member_template_p)
4891 {
4892   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4893   SET_DECL_LANGUAGE (tmpl, DECL_LANGUAGE (decl));
4894   DECL_TEMPLATE_PARMS (tmpl) = parms;
4895   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4896   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
4897   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4898 
4899   return tmpl;
4900 }
4901 
4902 struct template_parm_data
4903 {
4904   /* The level of the template parameters we are currently
4905      processing.  */
4906   int level;
4907 
4908   /* The index of the specialization argument we are currently
4909      processing.  */
4910   int current_arg;
4911 
4912   /* An array whose size is the number of template parameters.  The
4913      elements are nonzero if the parameter has been used in any one
4914      of the arguments processed so far.  */
4915   int* parms;
4916 
4917   /* An array whose size is the number of template arguments.  The
4918      elements are nonzero if the argument makes use of template
4919      parameters of this level.  */
4920   int* arg_uses_template_parms;
4921 };
4922 
4923 /* Subroutine of push_template_decl used to see if each template
4924    parameter in a partial specialization is used in the explicit
4925    argument list.  If T is of the LEVEL given in DATA (which is
4926    treated as a template_parm_data*), then DATA->PARMS is marked
4927    appropriately.  */
4928 
4929 static int
mark_template_parm(tree t,void * data)4930 mark_template_parm (tree t, void* data)
4931 {
4932   int level;
4933   int idx;
4934   struct template_parm_data* tpd = (struct template_parm_data*) data;
4935 
4936   template_parm_level_and_index (t, &level, &idx);
4937 
4938   if (level == tpd->level)
4939     {
4940       tpd->parms[idx] = 1;
4941       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
4942     }
4943 
4944   /* In C++17 the type of a non-type argument is a deduced context.  */
4945   if (cxx_dialect >= cxx17
4946       && TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4947     for_each_template_parm (TREE_TYPE (t),
4948 			    &mark_template_parm,
4949 			    data,
4950 			    NULL,
4951 			    /*include_nondeduced_p=*/false);
4952 
4953   /* Return zero so that for_each_template_parm will continue the
4954      traversal of the tree; we want to mark *every* template parm.  */
4955   return 0;
4956 }
4957 
4958 /* Process the partial specialization DECL.  */
4959 
4960 static tree
process_partial_specialization(tree decl)4961 process_partial_specialization (tree decl)
4962 {
4963   tree type = TREE_TYPE (decl);
4964   tree tinfo = get_template_info (decl);
4965   tree maintmpl = TI_TEMPLATE (tinfo);
4966   tree specargs = TI_ARGS (tinfo);
4967   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
4968   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
4969   tree inner_parms;
4970   tree inst;
4971   int nargs = TREE_VEC_LENGTH (inner_args);
4972   int ntparms;
4973   int  i;
4974   bool did_error_intro = false;
4975   struct template_parm_data tpd;
4976   struct template_parm_data tpd2;
4977 
4978   gcc_assert (current_template_parms);
4979 
4980   /* A concept cannot be specialized.  */
4981   if (flag_concepts && variable_concept_p (maintmpl))
4982     {
4983       error ("specialization of variable concept %q#D", maintmpl);
4984       return error_mark_node;
4985     }
4986 
4987   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4988   ntparms = TREE_VEC_LENGTH (inner_parms);
4989 
4990   /* We check that each of the template parameters given in the
4991      partial specialization is used in the argument list to the
4992      specialization.  For example:
4993 
4994        template <class T> struct S;
4995        template <class T> struct S<T*>;
4996 
4997      The second declaration is OK because `T*' uses the template
4998      parameter T, whereas
4999 
5000        template <class T> struct S<int>;
5001 
5002      is no good.  Even trickier is:
5003 
5004        template <class T>
5005        struct S1
5006        {
5007 	  template <class U>
5008 	  struct S2;
5009 	  template <class U>
5010 	  struct S2<T>;
5011        };
5012 
5013      The S2<T> declaration is actually invalid; it is a
5014      full-specialization.  Of course,
5015 
5016 	  template <class U>
5017 	  struct S2<T (*)(U)>;
5018 
5019      or some such would have been OK.  */
5020   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
5021   tpd.parms = XALLOCAVEC (int, ntparms);
5022   memset (tpd.parms, 0, sizeof (int) * ntparms);
5023 
5024   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5025   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
5026   for (i = 0; i < nargs; ++i)
5027     {
5028       tpd.current_arg = i;
5029       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
5030 			      &mark_template_parm,
5031 			      &tpd,
5032 			      NULL,
5033 			      /*include_nondeduced_p=*/false);
5034     }
5035   for (i = 0; i < ntparms; ++i)
5036     if (tpd.parms[i] == 0)
5037       {
5038 	/* One of the template parms was not used in a deduced context in the
5039 	   specialization.  */
5040 	if (!did_error_intro)
5041 	  {
5042 	    error ("template parameters not deducible in "
5043 		   "partial specialization:");
5044 	    did_error_intro = true;
5045 	  }
5046 
5047 	inform (input_location, "        %qD",
5048 		TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
5049       }
5050 
5051   if (did_error_intro)
5052     return error_mark_node;
5053 
5054   /* [temp.class.spec]
5055 
5056      The argument list of the specialization shall not be identical to
5057      the implicit argument list of the primary template.  */
5058   tree main_args
5059     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
5060   if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args))
5061       && (!flag_concepts
5062 	  || !strictly_subsumes (current_template_constraints (),
5063 				 main_args, maintmpl)))
5064     {
5065       if (!flag_concepts)
5066         error ("partial specialization %q+D does not specialize "
5067 	       "any template arguments; to define the primary template, "
5068 	       "remove the template argument list", decl);
5069       else
5070         error ("partial specialization %q+D does not specialize any "
5071 	       "template arguments and is not more constrained than "
5072 	       "the primary template; to define the primary template, "
5073 	       "remove the template argument list", decl);
5074       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5075     }
5076 
5077   /* A partial specialization that replaces multiple parameters of the
5078      primary template with a pack expansion is less specialized for those
5079      parameters.  */
5080   if (nargs < DECL_NTPARMS (maintmpl))
5081     {
5082       error ("partial specialization is not more specialized than the "
5083 	     "primary template because it replaces multiple parameters "
5084 	     "with a pack expansion");
5085       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5086       /* Avoid crash in process_partial_specialization.  */
5087       return decl;
5088     }
5089 
5090   else if (nargs > DECL_NTPARMS (maintmpl))
5091     {
5092       error ("too many arguments for partial specialization %qT", type);
5093       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5094       /* Avoid crash below.  */
5095       return decl;
5096     }
5097 
5098   /* If we aren't in a dependent class, we can actually try deduction.  */
5099   else if (tpd.level == 1
5100 	   /* FIXME we should be able to handle a partial specialization of a
5101 	      partial instantiation, but currently we can't (c++/41727).  */
5102 	   && TMPL_ARGS_DEPTH (specargs) == 1
5103 	   && !get_partial_spec_bindings (maintmpl, maintmpl, specargs))
5104     {
5105       auto_diagnostic_group d;
5106       if (permerror (input_location, "partial specialization %qD is not "
5107 		     "more specialized than", decl))
5108 	inform (DECL_SOURCE_LOCATION (maintmpl), "primary template %qD",
5109 		maintmpl);
5110     }
5111 
5112   /* [temp.class.spec]
5113 
5114      A partially specialized non-type argument expression shall not
5115      involve template parameters of the partial specialization except
5116      when the argument expression is a simple identifier.
5117 
5118      The type of a template parameter corresponding to a specialized
5119      non-type argument shall not be dependent on a parameter of the
5120      specialization.
5121 
5122      Also, we verify that pack expansions only occur at the
5123      end of the argument list.  */
5124   tpd2.parms = 0;
5125   for (i = 0; i < nargs; ++i)
5126     {
5127       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
5128       tree arg = TREE_VEC_ELT (inner_args, i);
5129       tree packed_args = NULL_TREE;
5130       int j, len = 1;
5131 
5132       if (ARGUMENT_PACK_P (arg))
5133         {
5134           /* Extract the arguments from the argument pack. We'll be
5135              iterating over these in the following loop.  */
5136           packed_args = ARGUMENT_PACK_ARGS (arg);
5137           len = TREE_VEC_LENGTH (packed_args);
5138         }
5139 
5140       for (j = 0; j < len; j++)
5141         {
5142           if (packed_args)
5143             /* Get the Jth argument in the parameter pack.  */
5144             arg = TREE_VEC_ELT (packed_args, j);
5145 
5146           if (PACK_EXPANSION_P (arg))
5147             {
5148               /* Pack expansions must come at the end of the
5149                  argument list.  */
5150               if ((packed_args && j < len - 1)
5151                   || (!packed_args && i < nargs - 1))
5152                 {
5153                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5154                     error ("parameter pack argument %qE must be at the "
5155 			   "end of the template argument list", arg);
5156                   else
5157                     error ("parameter pack argument %qT must be at the "
5158 			   "end of the template argument list", arg);
5159                 }
5160             }
5161 
5162           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5163             /* We only care about the pattern.  */
5164             arg = PACK_EXPANSION_PATTERN (arg);
5165 
5166           if (/* These first two lines are the `non-type' bit.  */
5167               !TYPE_P (arg)
5168               && TREE_CODE (arg) != TEMPLATE_DECL
5169               /* This next two lines are the `argument expression is not just a
5170                  simple identifier' condition and also the `specialized
5171                  non-type argument' bit.  */
5172               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
5173 	      && !((REFERENCE_REF_P (arg)
5174 		    || TREE_CODE (arg) == VIEW_CONVERT_EXPR)
5175 		   && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
5176             {
5177               if ((!packed_args && tpd.arg_uses_template_parms[i])
5178                   || (packed_args && uses_template_parms (arg)))
5179 		error_at (cp_expr_loc_or_input_loc (arg),
5180 			  "template argument %qE involves template "
5181 			  "parameter(s)", arg);
5182               else
5183                 {
5184                   /* Look at the corresponding template parameter,
5185                      marking which template parameters its type depends
5186                      upon.  */
5187                   tree type = TREE_TYPE (parm);
5188 
5189                   if (!tpd2.parms)
5190                     {
5191                       /* We haven't yet initialized TPD2.  Do so now.  */
5192                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5193                       /* The number of parameters here is the number in the
5194                          main template, which, as checked in the assertion
5195                          above, is NARGS.  */
5196                       tpd2.parms = XALLOCAVEC (int, nargs);
5197                       tpd2.level =
5198                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
5199                     }
5200 
5201                   /* Mark the template parameters.  But this time, we're
5202                      looking for the template parameters of the main
5203                      template, not in the specialization.  */
5204                   tpd2.current_arg = i;
5205                   tpd2.arg_uses_template_parms[i] = 0;
5206                   memset (tpd2.parms, 0, sizeof (int) * nargs);
5207                   for_each_template_parm (type,
5208                                           &mark_template_parm,
5209                                           &tpd2,
5210                                           NULL,
5211 					  /*include_nondeduced_p=*/false);
5212 
5213                   if (tpd2.arg_uses_template_parms [i])
5214                     {
5215                       /* The type depended on some template parameters.
5216                          If they are fully specialized in the
5217                          specialization, that's OK.  */
5218                       int j;
5219                       int count = 0;
5220                       for (j = 0; j < nargs; ++j)
5221                         if (tpd2.parms[j] != 0
5222                             && tpd.arg_uses_template_parms [j])
5223                           ++count;
5224                       if (count != 0)
5225                         error_n (input_location, count,
5226                                  "type %qT of template argument %qE depends "
5227                                  "on a template parameter",
5228                                  "type %qT of template argument %qE depends "
5229                                  "on template parameters",
5230                                  type,
5231                                  arg);
5232                     }
5233                 }
5234             }
5235         }
5236     }
5237 
5238   /* We should only get here once.  */
5239   if (TREE_CODE (decl) == TYPE_DECL)
5240     gcc_assert (!COMPLETE_TYPE_P (type));
5241 
5242   // Build the template decl.
5243   tree tmpl = build_template_decl (decl, current_template_parms,
5244 				   DECL_MEMBER_TEMPLATE_P (maintmpl));
5245   TREE_TYPE (tmpl) = type;
5246   DECL_TEMPLATE_RESULT (tmpl) = decl;
5247   SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5248   DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
5249   DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
5250 
5251   /* Give template template parms a DECL_CONTEXT of the template
5252      for which they are a parameter.  */
5253   for (i = 0; i < ntparms; ++i)
5254     {
5255       tree parm = TREE_VALUE (TREE_VEC_ELT (inner_parms, i));
5256       if (TREE_CODE (parm) == TEMPLATE_DECL)
5257 	DECL_CONTEXT (parm) = tmpl;
5258     }
5259 
5260   if (VAR_P (decl))
5261     /* We didn't register this in check_explicit_specialization so we could
5262        wait until the constraints were set.  */
5263     decl = register_specialization (decl, maintmpl, specargs, false, 0);
5264   else
5265     associate_classtype_constraints (type);
5266 
5267   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
5268     = tree_cons (specargs, tmpl,
5269                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
5270   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
5271 
5272   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
5273        inst = TREE_CHAIN (inst))
5274     {
5275       tree instance = TREE_VALUE (inst);
5276       if (TYPE_P (instance)
5277 	  ? (COMPLETE_TYPE_P (instance)
5278 	     && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
5279 	  : DECL_TEMPLATE_INSTANTIATION (instance))
5280 	{
5281 	  tree spec = most_specialized_partial_spec (instance, tf_none);
5282 	  tree inst_decl = (DECL_P (instance)
5283 			    ? instance : TYPE_NAME (instance));
5284 	  if (!spec)
5285 	    /* OK */;
5286 	  else if (spec == error_mark_node)
5287 	    permerror (input_location,
5288 		       "declaration of %qD ambiguates earlier template "
5289 		       "instantiation for %qD", decl, inst_decl);
5290 	  else if (TREE_VALUE (spec) == tmpl)
5291 	    permerror (input_location,
5292 		       "partial specialization of %qD after instantiation "
5293 		       "of %qD", decl, inst_decl);
5294 	}
5295     }
5296 
5297   return decl;
5298 }
5299 
5300 /* PARM is a template parameter of some form; return the corresponding
5301    TEMPLATE_PARM_INDEX.  */
5302 
5303 static tree
get_template_parm_index(tree parm)5304 get_template_parm_index (tree parm)
5305 {
5306   if (TREE_CODE (parm) == PARM_DECL
5307       || TREE_CODE (parm) == CONST_DECL)
5308     parm = DECL_INITIAL (parm);
5309   else if (TREE_CODE (parm) == TYPE_DECL
5310 	   || TREE_CODE (parm) == TEMPLATE_DECL)
5311     parm = TREE_TYPE (parm);
5312   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
5313       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM
5314       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
5315     parm = TEMPLATE_TYPE_PARM_INDEX (parm);
5316   gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
5317   return parm;
5318 }
5319 
5320 /* Subroutine of fixed_parameter_pack_p below.  Look for any template
5321    parameter packs used by the template parameter PARM.  */
5322 
5323 static void
fixed_parameter_pack_p_1(tree parm,struct find_parameter_pack_data * ppd)5324 fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
5325 {
5326   /* A type parm can't refer to another parm.  */
5327   if (TREE_CODE (parm) == TYPE_DECL || parm == error_mark_node)
5328     return;
5329   else if (TREE_CODE (parm) == PARM_DECL)
5330     {
5331       cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
5332 		    ppd, ppd->visited);
5333       return;
5334     }
5335 
5336   gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
5337 
5338   tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
5339   for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
5340     {
5341       tree p = TREE_VALUE (TREE_VEC_ELT (vec, i));
5342       if (template_parameter_pack_p (p))
5343 	/* Any packs in the type are expanded by this parameter.  */;
5344       else
5345 	fixed_parameter_pack_p_1 (p, ppd);
5346     }
5347 }
5348 
5349 /* PARM is a template parameter pack.  Return any parameter packs used in
5350    its type or the type of any of its template parameters.  If there are
5351    any such packs, it will be instantiated into a fixed template parameter
5352    list by partial instantiation rather than be fully deduced.  */
5353 
5354 tree
fixed_parameter_pack_p(tree parm)5355 fixed_parameter_pack_p (tree parm)
5356 {
5357   /* This can only be true in a member template.  */
5358   if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
5359     return NULL_TREE;
5360   /* This can only be true for a parameter pack.  */
5361   if (!template_parameter_pack_p (parm))
5362     return NULL_TREE;
5363   /* A type parm can't refer to another parm.  */
5364   if (TREE_CODE (parm) == TYPE_DECL)
5365     return NULL_TREE;
5366 
5367   tree parameter_packs = NULL_TREE;
5368   struct find_parameter_pack_data ppd;
5369   ppd.parameter_packs = &parameter_packs;
5370   ppd.visited = new hash_set<tree>;
5371   ppd.type_pack_expansion_p = false;
5372 
5373   fixed_parameter_pack_p_1 (parm, &ppd);
5374 
5375   delete ppd.visited;
5376   return parameter_packs;
5377 }
5378 
5379 /* Check that a template declaration's use of default arguments and
5380    parameter packs is not invalid.  Here, PARMS are the template
5381    parameters.  IS_PRIMARY is true if DECL is the thing declared by
5382    a primary template.  IS_PARTIAL is true if DECL is a partial
5383    specialization.
5384 
5385    IS_FRIEND_DECL is nonzero if DECL is either a non-defining friend
5386    function template declaration or a friend class template
5387    declaration.  In the function case, 1 indicates a declaration, 2
5388    indicates a redeclaration.  When IS_FRIEND_DECL=2, no errors are
5389    emitted for extraneous default arguments.
5390 
5391    Returns TRUE if there were no errors found, FALSE otherwise. */
5392 
5393 bool
check_default_tmpl_args(tree decl,tree parms,bool is_primary,bool is_partial,int is_friend_decl)5394 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
5395                          bool is_partial, int is_friend_decl)
5396 {
5397   const char *msg;
5398   int last_level_to_check;
5399   tree parm_level;
5400   bool no_errors = true;
5401 
5402   /* [temp.param]
5403 
5404      A default template-argument shall not be specified in a
5405      function template declaration or a function template definition, nor
5406      in the template-parameter-list of the definition of a member of a
5407      class template.  */
5408 
5409   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
5410       || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_FUNCTION_P (decl)))
5411     /* You can't have a function template declaration in a local
5412        scope, nor you can you define a member of a class template in a
5413        local scope.  */
5414     return true;
5415 
5416   if ((TREE_CODE (decl) == TYPE_DECL
5417        && TREE_TYPE (decl)
5418        && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5419       || (TREE_CODE (decl) == FUNCTION_DECL
5420 	  && LAMBDA_FUNCTION_P (decl)))
5421     /* A lambda doesn't have an explicit declaration; don't complain
5422        about the parms of the enclosing class.  */
5423     return true;
5424 
5425   if (current_class_type
5426       && !TYPE_BEING_DEFINED (current_class_type)
5427       && DECL_LANG_SPECIFIC (decl)
5428       && DECL_DECLARES_FUNCTION_P (decl)
5429       /* If this is either a friend defined in the scope of the class
5430 	 or a member function.  */
5431       && (DECL_FUNCTION_MEMBER_P (decl)
5432 	  ? same_type_p (DECL_CONTEXT (decl), current_class_type)
5433 	  : DECL_FRIEND_CONTEXT (decl)
5434 	  ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
5435 	  : false)
5436       /* And, if it was a member function, it really was defined in
5437 	 the scope of the class.  */
5438       && (!DECL_FUNCTION_MEMBER_P (decl)
5439 	  || DECL_INITIALIZED_IN_CLASS_P (decl)))
5440     /* We already checked these parameters when the template was
5441        declared, so there's no need to do it again now.  This function
5442        was defined in class scope, but we're processing its body now
5443        that the class is complete.  */
5444     return true;
5445 
5446   /* Core issue 226 (C++0x only): the following only applies to class
5447      templates.  */
5448   if (is_primary
5449       && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
5450     {
5451       /* [temp.param]
5452 
5453          If a template-parameter has a default template-argument, all
5454          subsequent template-parameters shall have a default
5455          template-argument supplied.  */
5456       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
5457         {
5458           tree inner_parms = TREE_VALUE (parm_level);
5459           int ntparms = TREE_VEC_LENGTH (inner_parms);
5460           int seen_def_arg_p = 0;
5461           int i;
5462 
5463           for (i = 0; i < ntparms; ++i)
5464             {
5465               tree parm = TREE_VEC_ELT (inner_parms, i);
5466 
5467               if (parm == error_mark_node)
5468                 continue;
5469 
5470               if (TREE_PURPOSE (parm))
5471                 seen_def_arg_p = 1;
5472               else if (seen_def_arg_p
5473 		       && !template_parameter_pack_p (TREE_VALUE (parm)))
5474                 {
5475                   error ("no default argument for %qD", TREE_VALUE (parm));
5476                   /* For better subsequent error-recovery, we indicate that
5477                      there should have been a default argument.  */
5478                   TREE_PURPOSE (parm) = error_mark_node;
5479                   no_errors = false;
5480                 }
5481 	      else if (!is_partial
5482 		       && !is_friend_decl
5483 		       /* Don't complain about an enclosing partial
5484 			  specialization.  */
5485 		       && parm_level == parms
5486 		       && TREE_CODE (decl) == TYPE_DECL
5487 		       && i < ntparms - 1
5488 		       && template_parameter_pack_p (TREE_VALUE (parm))
5489 		       /* A fixed parameter pack will be partially
5490 			  instantiated into a fixed length list.  */
5491 		       && !fixed_parameter_pack_p (TREE_VALUE (parm)))
5492 		{
5493 		  /* A primary class template can only have one
5494 		     parameter pack, at the end of the template
5495 		     parameter list.  */
5496 
5497 		  error ("parameter pack %q+D must be at the end of the"
5498 			 " template parameter list", TREE_VALUE (parm));
5499 
5500 		  TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
5501 		    = error_mark_node;
5502 		  no_errors = false;
5503 		}
5504             }
5505         }
5506     }
5507 
5508   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
5509       || is_partial
5510       || !is_primary
5511       || is_friend_decl)
5512     /* For an ordinary class template, default template arguments are
5513        allowed at the innermost level, e.g.:
5514 	 template <class T = int>
5515 	 struct S {};
5516        but, in a partial specialization, they're not allowed even
5517        there, as we have in [temp.class.spec]:
5518 
5519 	 The template parameter list of a specialization shall not
5520 	 contain default template argument values.
5521 
5522        So, for a partial specialization, or for a function template
5523        (in C++98/C++03), we look at all of them.  */
5524     ;
5525   else
5526     /* But, for a primary class template that is not a partial
5527        specialization we look at all template parameters except the
5528        innermost ones.  */
5529     parms = TREE_CHAIN (parms);
5530 
5531   /* Figure out what error message to issue.  */
5532   if (is_friend_decl == 2)
5533     msg = G_("default template arguments may not be used in function template "
5534 	     "friend re-declaration");
5535   else if (is_friend_decl)
5536     msg = G_("default template arguments may not be used in template "
5537 	     "friend declarations");
5538   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
5539     msg = G_("default template arguments may not be used in function templates "
5540 	     "without %<-std=c++11%> or %<-std=gnu++11%>");
5541   else if (is_partial)
5542     msg = G_("default template arguments may not be used in "
5543 	     "partial specializations");
5544   else if (current_class_type && CLASSTYPE_IS_TEMPLATE (current_class_type))
5545     msg = G_("default argument for template parameter for class enclosing %qD");
5546   else
5547     /* Per [temp.param]/9, "A default template-argument shall not be
5548        specified in the template-parameter-lists of the definition of
5549        a member of a class template that appears outside of the member's
5550        class.", thus if we aren't handling a member of a class template
5551        there is no need to examine the parameters.  */
5552     return true;
5553 
5554   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
5555     /* If we're inside a class definition, there's no need to
5556        examine the parameters to the class itself.  On the one
5557        hand, they will be checked when the class is defined, and,
5558        on the other, default arguments are valid in things like:
5559 	 template <class T = double>
5560 	 struct S { template <class U> void f(U); };
5561        Here the default argument for `S' has no bearing on the
5562        declaration of `f'.  */
5563     last_level_to_check = template_class_depth (current_class_type) + 1;
5564   else
5565     /* Check everything.  */
5566     last_level_to_check = 0;
5567 
5568   for (parm_level = parms;
5569        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
5570        parm_level = TREE_CHAIN (parm_level))
5571     {
5572       tree inner_parms = TREE_VALUE (parm_level);
5573       int i;
5574       int ntparms;
5575 
5576       ntparms = TREE_VEC_LENGTH (inner_parms);
5577       for (i = 0; i < ntparms; ++i)
5578         {
5579           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
5580             continue;
5581 
5582 	  if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
5583 	    {
5584 	      if (msg)
5585 	        {
5586                   no_errors = false;
5587                   if (is_friend_decl == 2)
5588                     return no_errors;
5589 
5590 		  error (msg, decl);
5591 		  msg = 0;
5592 	        }
5593 
5594 	      /* Clear out the default argument so that we are not
5595 	         confused later.  */
5596 	      TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
5597 	    }
5598         }
5599 
5600       /* At this point, if we're still interested in issuing messages,
5601 	 they must apply to classes surrounding the object declared.  */
5602       if (msg)
5603 	msg = G_("default argument for template parameter for class "
5604 		 "enclosing %qD");
5605     }
5606 
5607   return no_errors;
5608 }
5609 
5610 /* Worker for push_template_decl_real, called via
5611    for_each_template_parm.  DATA is really an int, indicating the
5612    level of the parameters we are interested in.  If T is a template
5613    parameter of that level, return nonzero.  */
5614 
5615 static int
template_parm_this_level_p(tree t,void * data)5616 template_parm_this_level_p (tree t, void* data)
5617 {
5618   int this_level = *(int *)data;
5619   int level;
5620 
5621   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5622     level = TEMPLATE_PARM_LEVEL (t);
5623   else
5624     level = TEMPLATE_TYPE_LEVEL (t);
5625   return level == this_level;
5626 }
5627 
5628 /* Worker for uses_outer_template_parms, called via for_each_template_parm.
5629    DATA is really an int, indicating the innermost outer level of parameters.
5630    If T is a template parameter of that level or further out, return
5631    nonzero.  */
5632 
5633 static int
template_parm_outer_level(tree t,void * data)5634 template_parm_outer_level (tree t, void *data)
5635 {
5636   int this_level = *(int *)data;
5637   int level;
5638 
5639   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5640     level = TEMPLATE_PARM_LEVEL (t);
5641   else
5642     level = TEMPLATE_TYPE_LEVEL (t);
5643   return level <= this_level;
5644 }
5645 
5646 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
5647    parameters given by current_template_args, or reuses a
5648    previously existing one, if appropriate.  Returns the DECL, or an
5649    equivalent one, if it is replaced via a call to duplicate_decls.
5650 
5651    If IS_FRIEND is true, DECL is a friend declaration.  */
5652 
5653 tree
push_template_decl_real(tree decl,bool is_friend)5654 push_template_decl_real (tree decl, bool is_friend)
5655 {
5656   tree tmpl;
5657   tree args;
5658   tree info;
5659   tree ctx;
5660   bool is_primary;
5661   bool is_partial;
5662   int new_template_p = 0;
5663   /* True if the template is a member template, in the sense of
5664      [temp.mem].  */
5665   bool member_template_p = false;
5666 
5667   if (decl == error_mark_node || !current_template_parms)
5668     return error_mark_node;
5669 
5670   /* See if this is a partial specialization.  */
5671   is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
5672 		 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
5673 		 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
5674 		|| (VAR_P (decl)
5675 		    && DECL_LANG_SPECIFIC (decl)
5676 		    && DECL_TEMPLATE_SPECIALIZATION (decl)
5677 		    && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
5678 
5679   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
5680     is_friend = true;
5681 
5682   if (is_friend)
5683     /* For a friend, we want the context of the friend, not
5684        the type of which it is a friend.  */
5685     ctx = CP_DECL_CONTEXT (decl);
5686   else if (CP_DECL_CONTEXT (decl)
5687 	   && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
5688     /* In the case of a virtual function, we want the class in which
5689        it is defined.  */
5690     ctx = CP_DECL_CONTEXT (decl);
5691   else
5692     /* Otherwise, if we're currently defining some class, the DECL
5693        is assumed to be a member of the class.  */
5694     ctx = current_scope ();
5695 
5696   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
5697     ctx = NULL_TREE;
5698 
5699   if (!DECL_CONTEXT (decl))
5700     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5701 
5702   /* See if this is a primary template.  */
5703   if (is_friend && ctx
5704       && uses_template_parms_level (ctx, processing_template_decl))
5705     /* A friend template that specifies a class context, i.e.
5706          template <typename T> friend void A<T>::f();
5707        is not primary.  */
5708     is_primary = false;
5709   else if (TREE_CODE (decl) == TYPE_DECL
5710 	   && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5711     is_primary = false;
5712   else
5713     is_primary = template_parm_scope_p ();
5714 
5715   if (is_primary)
5716     {
5717       warning (OPT_Wtemplates, "template %qD declared", decl);
5718 
5719       if (DECL_CLASS_SCOPE_P (decl))
5720 	member_template_p = true;
5721       if (TREE_CODE (decl) == TYPE_DECL
5722 	  && IDENTIFIER_ANON_P (DECL_NAME (decl)))
5723 	{
5724 	  error ("template class without a name");
5725 	  return error_mark_node;
5726 	}
5727       else if (TREE_CODE (decl) == FUNCTION_DECL)
5728 	{
5729 	  if (member_template_p)
5730 	    {
5731 	      if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
5732 		error ("member template %qD may not have virt-specifiers", decl);
5733 	    }
5734 	  if (DECL_DESTRUCTOR_P (decl))
5735 	    {
5736 	      /* [temp.mem]
5737 
5738 		 A destructor shall not be a member template.  */
5739 	      error_at (DECL_SOURCE_LOCATION (decl),
5740 			"destructor %qD declared as member template", decl);
5741 	      return error_mark_node;
5742 	    }
5743 	  if (IDENTIFIER_NEWDEL_OP_P (DECL_NAME (decl))
5744 	      && (!prototype_p (TREE_TYPE (decl))
5745 		  || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
5746 		  || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5747 		  || (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5748 		      == void_list_node)))
5749 	    {
5750 	      /* [basic.stc.dynamic.allocation]
5751 
5752 		 An allocation function can be a function
5753 		 template. ... Template allocation functions shall
5754 		 have two or more parameters.  */
5755 	      error ("invalid template declaration of %qD", decl);
5756 	      return error_mark_node;
5757 	    }
5758 	}
5759       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5760 	       && CLASS_TYPE_P (TREE_TYPE (decl)))
5761 	{
5762 	  /* Class template, set TEMPLATE_TYPE_PARM_FOR_CLASS.  */
5763 	  tree parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
5764 	  for (int i = 0; i < TREE_VEC_LENGTH (parms); ++i)
5765 	    {
5766 	      tree t = TREE_VALUE (TREE_VEC_ELT (parms, i));
5767 	      if (TREE_CODE (t) == TYPE_DECL)
5768 		t = TREE_TYPE (t);
5769 	      if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
5770 		TEMPLATE_TYPE_PARM_FOR_CLASS (t) = true;
5771 	    }
5772 	}
5773       else if (TREE_CODE (decl) == TYPE_DECL
5774 	       && TYPE_DECL_ALIAS_P (decl))
5775 	/* alias-declaration */
5776 	gcc_assert (!DECL_ARTIFICIAL (decl));
5777       else if (VAR_P (decl))
5778 	/* C++14 variable template. */;
5779       else if (TREE_CODE (decl) == CONCEPT_DECL)
5780 	/* C++2a concept definitions.  */;
5781       else
5782 	{
5783 	  error ("template declaration of %q#D", decl);
5784 	  return error_mark_node;
5785 	}
5786     }
5787 
5788   /* Check to see that the rules regarding the use of default
5789      arguments are not being violated.  We check args for a friend
5790      functions when we know whether it's a definition, introducing
5791      declaration or re-declaration.  */
5792   if (!is_friend || TREE_CODE (decl) != FUNCTION_DECL)
5793     check_default_tmpl_args (decl, current_template_parms,
5794 			     is_primary, is_partial, is_friend);
5795 
5796   /* Ensure that there are no parameter packs in the type of this
5797      declaration that have not been expanded.  */
5798   if (TREE_CODE (decl) == FUNCTION_DECL)
5799     {
5800       /* Check each of the arguments individually to see if there are
5801          any bare parameter packs.  */
5802       tree type = TREE_TYPE (decl);
5803       tree arg = DECL_ARGUMENTS (decl);
5804       tree argtype = TYPE_ARG_TYPES (type);
5805 
5806       while (arg && argtype)
5807         {
5808           if (!DECL_PACK_P (arg)
5809               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
5810             {
5811             /* This is a PARM_DECL that contains unexpanded parameter
5812                packs. We have already complained about this in the
5813                check_for_bare_parameter_packs call, so just replace
5814                these types with ERROR_MARK_NODE.  */
5815               TREE_TYPE (arg) = error_mark_node;
5816               TREE_VALUE (argtype) = error_mark_node;
5817             }
5818 
5819           arg = DECL_CHAIN (arg);
5820           argtype = TREE_CHAIN (argtype);
5821         }
5822 
5823       /* Check for bare parameter packs in the return type and the
5824          exception specifiers.  */
5825       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
5826 	/* Errors were already issued, set return type to int
5827 	   as the frontend doesn't expect error_mark_node as
5828 	   the return type.  */
5829 	TREE_TYPE (type) = integer_type_node;
5830       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
5831 	TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
5832     }
5833   else if (check_for_bare_parameter_packs (is_typedef_decl (decl)
5834 					   ? DECL_ORIGINAL_TYPE (decl)
5835 					   : TREE_TYPE (decl)))
5836     {
5837       TREE_TYPE (decl) = error_mark_node;
5838       return error_mark_node;
5839     }
5840 
5841   if (is_partial)
5842     return process_partial_specialization (decl);
5843 
5844   args = current_template_args ();
5845 
5846   if (!ctx
5847       || TREE_CODE (ctx) == FUNCTION_DECL
5848       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
5849       || (TREE_CODE (decl) == TYPE_DECL
5850 	  && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5851       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
5852     {
5853       if (DECL_LANG_SPECIFIC (decl)
5854 	  && DECL_TEMPLATE_INFO (decl)
5855 	  && DECL_TI_TEMPLATE (decl))
5856 	tmpl = DECL_TI_TEMPLATE (decl);
5857       /* If DECL is a TYPE_DECL for a class-template, then there won't
5858 	 be DECL_LANG_SPECIFIC.  The information equivalent to
5859 	 DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
5860       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5861 	       && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
5862 	       && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
5863 	{
5864 	  /* Since a template declaration already existed for this
5865 	     class-type, we must be redeclaring it here.  Make sure
5866 	     that the redeclaration is valid.  */
5867 	  redeclare_class_template (TREE_TYPE (decl),
5868 				    current_template_parms,
5869 				    current_template_constraints ());
5870 	  /* We don't need to create a new TEMPLATE_DECL; just use the
5871 	     one we already had.  */
5872 	  tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
5873 	}
5874       else
5875 	{
5876 	  tmpl = build_template_decl (decl, current_template_parms,
5877 				      member_template_p);
5878 	  new_template_p = 1;
5879 
5880 	  if (DECL_LANG_SPECIFIC (decl)
5881 	      && DECL_TEMPLATE_SPECIALIZATION (decl))
5882 	    {
5883 	      /* A specialization of a member template of a template
5884 		 class.  */
5885 	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5886 	      DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
5887 	      DECL_TEMPLATE_INFO (decl) = NULL_TREE;
5888 	    }
5889 	}
5890     }
5891   else
5892     {
5893       tree a, t, current, parms;
5894       int i;
5895       tree tinfo = get_template_info (decl);
5896 
5897       if (!tinfo)
5898 	{
5899 	  error ("template definition of non-template %q#D", decl);
5900 	  return error_mark_node;
5901 	}
5902 
5903       tmpl = TI_TEMPLATE (tinfo);
5904 
5905       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
5906 	  && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
5907 	  && DECL_TEMPLATE_SPECIALIZATION (decl)
5908 	  && DECL_MEMBER_TEMPLATE_P (tmpl))
5909 	{
5910 	  tree new_tmpl;
5911 
5912 	  /* The declaration is a specialization of a member
5913 	     template, declared outside the class.  Therefore, the
5914 	     innermost template arguments will be NULL, so we
5915 	     replace them with the arguments determined by the
5916 	     earlier call to check_explicit_specialization.  */
5917 	  args = DECL_TI_ARGS (decl);
5918 
5919 	  new_tmpl
5920 	    = build_template_decl (decl, current_template_parms,
5921 				   member_template_p);
5922 	  DECL_TEMPLATE_RESULT (new_tmpl) = decl;
5923 	  TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
5924 	  DECL_TI_TEMPLATE (decl) = new_tmpl;
5925 	  SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
5926 	  DECL_TEMPLATE_INFO (new_tmpl)
5927 	    = build_template_info (tmpl, args);
5928 
5929 	  register_specialization (new_tmpl,
5930 				   most_general_template (tmpl),
5931 				   args,
5932 				   is_friend, 0);
5933 	  return decl;
5934 	}
5935 
5936       /* Make sure the template headers we got make sense.  */
5937 
5938       parms = DECL_TEMPLATE_PARMS (tmpl);
5939       i = TMPL_PARMS_DEPTH (parms);
5940       if (TMPL_ARGS_DEPTH (args) != i)
5941 	{
5942 	  error ("expected %d levels of template parms for %q#D, got %d",
5943 		 i, decl, TMPL_ARGS_DEPTH (args));
5944 	  DECL_INTERFACE_KNOWN (decl) = 1;
5945 	  return error_mark_node;
5946 	}
5947       else
5948 	for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
5949 	  {
5950 	    a = TMPL_ARGS_LEVEL (args, i);
5951 	    t = INNERMOST_TEMPLATE_PARMS (parms);
5952 
5953 	    if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
5954 	      {
5955 		if (current == decl)
5956 		  error ("got %d template parameters for %q#D",
5957 			 TREE_VEC_LENGTH (a), decl);
5958 		else
5959 		  error ("got %d template parameters for %q#T",
5960 			 TREE_VEC_LENGTH (a), current);
5961 		error ("  but %d required", TREE_VEC_LENGTH (t));
5962 		/* Avoid crash in import_export_decl.  */
5963 		DECL_INTERFACE_KNOWN (decl) = 1;
5964 		return error_mark_node;
5965 	      }
5966 
5967 	    if (current == decl)
5968 	      current = ctx;
5969 	    else if (current == NULL_TREE)
5970 	      /* Can happen in erroneous input.  */
5971 	      break;
5972 	    else
5973 	      current = get_containing_scope (current);
5974 	  }
5975 
5976       /* Check that the parms are used in the appropriate qualifying scopes
5977 	 in the declarator.  */
5978       if (!comp_template_args
5979 	  (TI_ARGS (tinfo),
5980 	   TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
5981 	{
5982 	  error ("template arguments to %qD do not match original "
5983 		 "template %qD", decl, DECL_TEMPLATE_RESULT (tmpl));
5984 	  if (!uses_template_parms (TI_ARGS (tinfo)))
5985 	    inform (input_location, "use %<template<>%> for"
5986 		    " an explicit specialization");
5987 	  /* Avoid crash in import_export_decl.  */
5988 	  DECL_INTERFACE_KNOWN (decl) = 1;
5989 	  return error_mark_node;
5990 	}
5991     }
5992 
5993   DECL_TEMPLATE_RESULT (tmpl) = decl;
5994   TREE_TYPE (tmpl) = TREE_TYPE (decl);
5995 
5996   /* Push template declarations for global functions and types.  Note
5997      that we do not try to push a global template friend declared in a
5998      template class; such a thing may well depend on the template
5999      parameters of the class.  */
6000   if (new_template_p && !ctx
6001       && !(is_friend && template_class_depth (current_class_type) > 0))
6002     {
6003       tmpl = pushdecl_namespace_level (tmpl, is_friend);
6004       if (tmpl == error_mark_node)
6005 	return error_mark_node;
6006 
6007       /* Hide template friend classes that haven't been declared yet.  */
6008       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
6009 	{
6010 	  DECL_ANTICIPATED (tmpl) = 1;
6011 	  DECL_FRIEND_P (tmpl) = 1;
6012 	}
6013     }
6014 
6015   if (is_primary)
6016     {
6017       tree parms = DECL_TEMPLATE_PARMS (tmpl);
6018 
6019       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6020 
6021       /* Give template template parms a DECL_CONTEXT of the template
6022 	 for which they are a parameter.  */
6023       parms = INNERMOST_TEMPLATE_PARMS (parms);
6024       for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
6025 	{
6026 	  tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6027 	  if (TREE_CODE (parm) == TEMPLATE_DECL)
6028 	    DECL_CONTEXT (parm) = tmpl;
6029 	}
6030 
6031       if (TREE_CODE (decl) == TYPE_DECL
6032 	  && TYPE_DECL_ALIAS_P (decl))
6033 	{
6034 	  if (tree constr
6035 	      = TEMPLATE_PARMS_CONSTRAINTS (DECL_TEMPLATE_PARMS (tmpl)))
6036 	    {
6037 	      /* ??? Why don't we do this here for all templates?  */
6038 	      constr = build_constraints (constr, NULL_TREE);
6039 	      set_constraints (decl, constr);
6040 	    }
6041 	  if (complex_alias_template_p (tmpl))
6042 	    TEMPLATE_DECL_COMPLEX_ALIAS_P (tmpl) = true;
6043 	}
6044     }
6045 
6046   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
6047      back to its most general template.  If TMPL is a specialization,
6048      ARGS may only have the innermost set of arguments.  Add the missing
6049      argument levels if necessary.  */
6050   if (DECL_TEMPLATE_INFO (tmpl))
6051     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
6052 
6053   info = build_template_info (tmpl, args);
6054 
6055   if (DECL_IMPLICIT_TYPEDEF_P (decl))
6056     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
6057   else
6058     {
6059       if (is_primary)
6060 	retrofit_lang_decl (decl);
6061       if (DECL_LANG_SPECIFIC (decl))
6062 	DECL_TEMPLATE_INFO (decl) = info;
6063     }
6064 
6065   if (flag_implicit_templates
6066       && !is_friend
6067       && TREE_PUBLIC (decl)
6068       && VAR_OR_FUNCTION_DECL_P (decl))
6069     /* Set DECL_COMDAT on template instantiations; if we force
6070        them to be emitted by explicit instantiation,
6071        mark_needed will tell cgraph to do the right thing.  */
6072     DECL_COMDAT (decl) = true;
6073 
6074   return DECL_TEMPLATE_RESULT (tmpl);
6075 }
6076 
6077 tree
push_template_decl(tree decl)6078 push_template_decl (tree decl)
6079 {
6080   return push_template_decl_real (decl, false);
6081 }
6082 
6083 /* FN is an inheriting constructor that inherits from the constructor
6084    template INHERITED; turn FN into a constructor template with a matching
6085    template header.  */
6086 
6087 tree
add_inherited_template_parms(tree fn,tree inherited)6088 add_inherited_template_parms (tree fn, tree inherited)
6089 {
6090   tree inner_parms
6091     = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
6092   inner_parms = copy_node (inner_parms);
6093   tree parms
6094     = tree_cons (size_int (processing_template_decl + 1),
6095 		 inner_parms, current_template_parms);
6096   tree tmpl = build_template_decl (fn, parms, /*member*/true);
6097   tree args = template_parms_to_args (parms);
6098   DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
6099   TREE_TYPE (tmpl) = TREE_TYPE (fn);
6100   DECL_TEMPLATE_RESULT (tmpl) = fn;
6101   DECL_ARTIFICIAL (tmpl) = true;
6102   DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6103   return tmpl;
6104 }
6105 
6106 /* Called when a class template TYPE is redeclared with the indicated
6107    template PARMS, e.g.:
6108 
6109      template <class T> struct S;
6110      template <class T> struct S {};  */
6111 
6112 bool
redeclare_class_template(tree type,tree parms,tree cons)6113 redeclare_class_template (tree type, tree parms, tree cons)
6114 {
6115   tree tmpl;
6116   tree tmpl_parms;
6117   int i;
6118 
6119   if (!TYPE_TEMPLATE_INFO (type))
6120     {
6121       error ("%qT is not a template type", type);
6122       return false;
6123     }
6124 
6125   tmpl = TYPE_TI_TEMPLATE (type);
6126   if (!PRIMARY_TEMPLATE_P (tmpl))
6127     /* The type is nested in some template class.  Nothing to worry
6128        about here; there are no new template parameters for the nested
6129        type.  */
6130     return true;
6131 
6132   if (!parms)
6133     {
6134       error ("template specifiers not specified in declaration of %qD",
6135 	     tmpl);
6136       return false;
6137     }
6138 
6139   parms = INNERMOST_TEMPLATE_PARMS (parms);
6140   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
6141 
6142   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
6143     {
6144       error_n (input_location, TREE_VEC_LENGTH (parms),
6145                "redeclared with %d template parameter",
6146                "redeclared with %d template parameters",
6147                TREE_VEC_LENGTH (parms));
6148       inform_n (DECL_SOURCE_LOCATION (tmpl), TREE_VEC_LENGTH (tmpl_parms),
6149                 "previous declaration %qD used %d template parameter",
6150                 "previous declaration %qD used %d template parameters",
6151                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
6152       return false;
6153     }
6154 
6155   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
6156     {
6157       tree tmpl_parm;
6158       tree parm;
6159       tree tmpl_default;
6160       tree parm_default;
6161 
6162       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
6163           || TREE_VEC_ELT (parms, i) == error_mark_node)
6164         continue;
6165 
6166       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
6167       if (error_operand_p (tmpl_parm))
6168 	return false;
6169 
6170       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6171       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
6172       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
6173 
6174       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
6175 	 TEMPLATE_DECL.  */
6176       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
6177 	  || (TREE_CODE (tmpl_parm) != TYPE_DECL
6178 	      && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
6179 	  || (TREE_CODE (tmpl_parm) != PARM_DECL
6180 	      && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
6181 		  != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
6182 	  || (TREE_CODE (tmpl_parm) == PARM_DECL
6183 	      && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
6184 		  != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
6185 	{
6186 	  auto_diagnostic_group d;
6187 	  error ("template parameter %q+#D", tmpl_parm);
6188 	  inform (input_location, "redeclared here as %q#D", parm);
6189 	  return false;
6190 	}
6191 
6192       /* The parameters can be declared to introduce different
6193 	 constraints.  */
6194       tree p1 = TREE_VEC_ELT (tmpl_parms, i);
6195       tree p2 = TREE_VEC_ELT (parms, i);
6196       if (!template_parameter_constraints_equivalent_p (p1, p2))
6197 	{
6198 	  auto_diagnostic_group d;
6199 	  error ("declaration of template parameter %q+#D with different "
6200 		 "constraints", parm);
6201 	  inform (DECL_SOURCE_LOCATION (tmpl_parm),
6202 		  "original declaration appeared here");
6203 	  return false;
6204 	}
6205 
6206       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
6207 	{
6208 	  /* We have in [temp.param]:
6209 
6210 	     A template-parameter may not be given default arguments
6211 	     by two different declarations in the same scope.  */
6212 	  auto_diagnostic_group d;
6213 	  error_at (input_location, "redefinition of default argument for %q#D", parm);
6214 	  inform (DECL_SOURCE_LOCATION (tmpl_parm),
6215 		  "original definition appeared here");
6216 	  return false;
6217 	}
6218 
6219       if (parm_default != NULL_TREE)
6220 	/* Update the previous template parameters (which are the ones
6221 	   that will really count) with the new default value.  */
6222 	TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
6223       else if (tmpl_default != NULL_TREE)
6224 	/* Update the new parameters, too; they'll be used as the
6225 	   parameters for any members.  */
6226 	TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
6227 
6228       /* Give each template template parm in this redeclaration a
6229 	 DECL_CONTEXT of the template for which they are a parameter.  */
6230       if (TREE_CODE (parm) == TEMPLATE_DECL)
6231 	{
6232 	  gcc_assert (DECL_CONTEXT (parm) == NULL_TREE);
6233 	  DECL_CONTEXT (parm) = tmpl;
6234 	}
6235 
6236       if (TREE_CODE (parm) == TYPE_DECL)
6237 	TEMPLATE_TYPE_PARM_FOR_CLASS (TREE_TYPE (parm)) = true;
6238     }
6239 
6240   tree ci = get_constraints (tmpl);
6241   tree req1 = ci ? CI_TEMPLATE_REQS (ci) : NULL_TREE;
6242   tree req2 = cons ? CI_TEMPLATE_REQS (cons) : NULL_TREE;
6243 
6244   /* Two classes with different constraints declare different entities.  */
6245   if (!cp_tree_equal (req1, req2))
6246     {
6247       auto_diagnostic_group d;
6248       error_at (input_location, "redeclaration %q#D with different "
6249                                 "constraints", tmpl);
6250       inform (DECL_SOURCE_LOCATION (tmpl),
6251               "original declaration appeared here");
6252       return false;
6253     }
6254 
6255     return true;
6256 }
6257 
6258 /* The actual substitution part of instantiate_non_dependent_expr_sfinae,
6259    to be used when the caller has already checked
6260    (processing_template_decl
6261     && !instantiation_dependent_expression_p (expr)
6262     && potential_constant_expression (expr))
6263    and cleared processing_template_decl.  */
6264 
6265 tree
instantiate_non_dependent_expr_internal(tree expr,tsubst_flags_t complain)6266 instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
6267 {
6268   return tsubst_copy_and_build (expr,
6269 				/*args=*/NULL_TREE,
6270 				complain,
6271 				/*in_decl=*/NULL_TREE,
6272 				/*function_p=*/false,
6273 				/*integral_constant_expression_p=*/true);
6274 }
6275 
6276 /* Simplify EXPR if it is a non-dependent expression.  Returns the
6277    (possibly simplified) expression.  */
6278 
6279 tree
instantiate_non_dependent_expr_sfinae(tree expr,tsubst_flags_t complain)6280 instantiate_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
6281 {
6282   if (expr == NULL_TREE)
6283     return NULL_TREE;
6284 
6285   /* If we're in a template, but EXPR isn't value dependent, simplify
6286      it.  We're supposed to treat:
6287 
6288        template <typename T> void f(T[1 + 1]);
6289        template <typename T> void f(T[2]);
6290 
6291      as two declarations of the same function, for example.  */
6292   if (processing_template_decl
6293       && is_nondependent_constant_expression (expr))
6294     {
6295       processing_template_decl_sentinel s;
6296       expr = instantiate_non_dependent_expr_internal (expr, complain);
6297     }
6298   return expr;
6299 }
6300 
6301 tree
instantiate_non_dependent_expr(tree expr)6302 instantiate_non_dependent_expr (tree expr)
6303 {
6304   return instantiate_non_dependent_expr_sfinae (expr, tf_error);
6305 }
6306 
6307 /* Like instantiate_non_dependent_expr, but return NULL_TREE rather than
6308    an uninstantiated expression.  */
6309 
6310 tree
instantiate_non_dependent_or_null(tree expr)6311 instantiate_non_dependent_or_null (tree expr)
6312 {
6313   if (expr == NULL_TREE)
6314     return NULL_TREE;
6315   if (processing_template_decl)
6316     {
6317       if (!is_nondependent_constant_expression (expr))
6318 	expr = NULL_TREE;
6319       else
6320 	{
6321 	  processing_template_decl_sentinel s;
6322 	  expr = instantiate_non_dependent_expr_internal (expr, tf_error);
6323 	}
6324     }
6325   return expr;
6326 }
6327 
6328 /* True iff T is a specialization of a variable template.  */
6329 
6330 bool
variable_template_specialization_p(tree t)6331 variable_template_specialization_p (tree t)
6332 {
6333   if (!VAR_P (t) || !DECL_LANG_SPECIFIC (t) || !DECL_TEMPLATE_INFO (t))
6334     return false;
6335   tree tmpl = DECL_TI_TEMPLATE (t);
6336   return variable_template_p (tmpl);
6337 }
6338 
6339 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
6340    template declaration, or a TYPE_DECL for an alias declaration.  */
6341 
6342 bool
alias_type_or_template_p(tree t)6343 alias_type_or_template_p (tree t)
6344 {
6345   if (t == NULL_TREE)
6346     return false;
6347   return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
6348 	  || (TYPE_P (t)
6349 	      && TYPE_NAME (t)
6350 	      && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
6351 	  || DECL_ALIAS_TEMPLATE_P (t));
6352 }
6353 
6354 /* If T is a specialization of an alias template, return it; otherwise return
6355    NULL_TREE.  If TRANSPARENT_TYPEDEFS is true, look through other aliases.  */
6356 
6357 tree
alias_template_specialization_p(const_tree t,bool transparent_typedefs)6358 alias_template_specialization_p (const_tree t,
6359 				 bool transparent_typedefs)
6360 {
6361   if (!TYPE_P (t))
6362     return NULL_TREE;
6363 
6364   /* It's an alias template specialization if it's an alias and its
6365      TYPE_NAME is a specialization of a primary template.  */
6366   if (typedef_variant_p (t))
6367     {
6368       if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
6369 	if (PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo)))
6370 	  return CONST_CAST_TREE (t);
6371       if (transparent_typedefs)
6372 	return alias_template_specialization_p (DECL_ORIGINAL_TYPE
6373 						(TYPE_NAME (t)),
6374 						transparent_typedefs);
6375     }
6376 
6377   return NULL_TREE;
6378 }
6379 
6380 /* An alias template is complex from a SFINAE perspective if a template-id
6381    using that alias can be ill-formed when the expansion is not, as with
6382    the void_t template.  We determine this by checking whether the
6383    expansion for the alias template uses all its template parameters.  */
6384 
6385 struct uses_all_template_parms_data
6386 {
6387   int level;
6388   bool *seen;
6389 };
6390 
6391 static int
uses_all_template_parms_r(tree t,void * data_)6392 uses_all_template_parms_r (tree t, void *data_)
6393 {
6394   struct uses_all_template_parms_data &data
6395     = *(struct uses_all_template_parms_data*)data_;
6396   tree idx = get_template_parm_index (t);
6397 
6398   if (TEMPLATE_PARM_LEVEL (idx) == data.level)
6399     data.seen[TEMPLATE_PARM_IDX (idx)] = true;
6400   return 0;
6401 }
6402 
6403 /* for_each_template_parm any_fn callback for complex_alias_template_p.  */
6404 
6405 static int
complex_pack_expansion_r(tree t,void * data_)6406 complex_pack_expansion_r (tree t, void *data_)
6407 {
6408   /* An alias template with a pack expansion that expands a pack from the
6409      enclosing class needs to be considered complex, to avoid confusion with
6410      the same pack being used as an argument to the alias's own template
6411      parameter (91966).  */
6412   if (!PACK_EXPANSION_P (t))
6413     return 0;
6414   struct uses_all_template_parms_data &data
6415     = *(struct uses_all_template_parms_data*)data_;
6416   for (tree pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
6417        pack = TREE_CHAIN (pack))
6418     {
6419       tree parm_pack = TREE_VALUE (pack);
6420       if (!TEMPLATE_PARM_P (parm_pack))
6421 	continue;
6422       int idx, level;
6423       template_parm_level_and_index (parm_pack, &level, &idx);
6424       if (level < data.level)
6425 	return 1;
6426     }
6427   return 0;
6428 }
6429 
6430 static bool
complex_alias_template_p(const_tree tmpl)6431 complex_alias_template_p (const_tree tmpl)
6432 {
6433   /* A renaming alias isn't complex.  */
6434   if (get_underlying_template (CONST_CAST_TREE (tmpl)) != tmpl)
6435     return false;
6436 
6437   /* Any other constrained alias is complex.  */
6438   if (get_constraints (tmpl))
6439     return true;
6440 
6441   struct uses_all_template_parms_data data;
6442   tree pat = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6443   tree parms = DECL_TEMPLATE_PARMS (tmpl);
6444   data.level = TMPL_PARMS_DEPTH (parms);
6445   int len = TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS (parms));
6446   data.seen = XALLOCAVEC (bool, len);
6447   for (int i = 0; i < len; ++i)
6448     data.seen[i] = false;
6449 
6450   if (for_each_template_parm (pat, uses_all_template_parms_r, &data,
6451 			      NULL, true, complex_pack_expansion_r))
6452     return true;
6453   for (int i = 0; i < len; ++i)
6454     if (!data.seen[i])
6455       return true;
6456   return false;
6457 }
6458 
6459 /* If T is a specialization of a complex alias template with dependent
6460    template-arguments, return it; otherwise return NULL_TREE.  If T is a
6461    typedef to such a specialization, return the specialization.  */
6462 
6463 tree
dependent_alias_template_spec_p(const_tree t,bool transparent_typedefs)6464 dependent_alias_template_spec_p (const_tree t, bool transparent_typedefs)
6465 {
6466   if (!TYPE_P (t) || !typedef_variant_p (t))
6467     return NULL_TREE;
6468 
6469   tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t);
6470   if (tinfo
6471       && TEMPLATE_DECL_COMPLEX_ALIAS_P (TI_TEMPLATE (tinfo))
6472       && (any_dependent_template_arguments_p
6473 	  (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)))))
6474     return CONST_CAST_TREE (t);
6475 
6476   if (transparent_typedefs)
6477     {
6478       tree utype = DECL_ORIGINAL_TYPE (TYPE_NAME (t));
6479       return dependent_alias_template_spec_p (utype, transparent_typedefs);
6480     }
6481 
6482   return NULL_TREE;
6483 }
6484 
6485 /* Return the number of innermost template parameters in TMPL.  */
6486 
6487 static int
num_innermost_template_parms(const_tree tmpl)6488 num_innermost_template_parms (const_tree tmpl)
6489 {
6490   tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6491   return TREE_VEC_LENGTH (parms);
6492 }
6493 
6494 /* Return either TMPL or another template that it is equivalent to under DR
6495    1286: An alias that just changes the name of a template is equivalent to
6496    the other template.  */
6497 
6498 static tree
get_underlying_template(tree tmpl)6499 get_underlying_template (tree tmpl)
6500 {
6501   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
6502   while (DECL_ALIAS_TEMPLATE_P (tmpl))
6503     {
6504       /* Determine if the alias is equivalent to an underlying template.  */
6505       tree orig_type = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6506       /* The underlying type may have been ill-formed. Don't proceed.  */
6507       if (!orig_type)
6508 	break;
6509       tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (orig_type);
6510       if (!tinfo)
6511 	break;
6512 
6513       tree underlying = TI_TEMPLATE (tinfo);
6514       if (!PRIMARY_TEMPLATE_P (underlying)
6515 	  || (num_innermost_template_parms (tmpl)
6516 	      != num_innermost_template_parms (underlying)))
6517 	break;
6518 
6519       tree alias_args = INNERMOST_TEMPLATE_ARGS (generic_targs_for (tmpl));
6520       if (!comp_template_args (TI_ARGS (tinfo), alias_args))
6521 	break;
6522 
6523       /* If TMPL adds or changes any constraints, it isn't equivalent.  I think
6524 	 it's appropriate to treat a less-constrained alias as equivalent.  */
6525       if (!at_least_as_constrained (underlying, tmpl))
6526 	break;
6527 
6528       /* Alias is equivalent.  Strip it and repeat.  */
6529       tmpl = underlying;
6530     }
6531 
6532   return tmpl;
6533 }
6534 
6535 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
6536    must be a reference-to-function or a pointer-to-function type, as specified
6537    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
6538    and check that the resulting function has external linkage.  */
6539 
6540 static tree
convert_nontype_argument_function(tree type,tree expr,tsubst_flags_t complain)6541 convert_nontype_argument_function (tree type, tree expr,
6542 				   tsubst_flags_t complain)
6543 {
6544   tree fns = expr;
6545   tree fn, fn_no_ptr;
6546   linkage_kind linkage;
6547 
6548   fn = instantiate_type (type, fns, tf_none);
6549   if (fn == error_mark_node)
6550     return error_mark_node;
6551 
6552   if (value_dependent_expression_p (fn))
6553     goto accept;
6554 
6555   fn_no_ptr = strip_fnptr_conv (fn);
6556   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
6557     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6558   if (BASELINK_P (fn_no_ptr))
6559     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
6560 
6561   /* [temp.arg.nontype]/1
6562 
6563      A template-argument for a non-type, non-template template-parameter
6564      shall be one of:
6565      [...]
6566      -- the address of an object or function with external [C++11: or
6567         internal] linkage.  */
6568 
6569   STRIP_ANY_LOCATION_WRAPPER (fn_no_ptr);
6570   if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
6571     {
6572       if (complain & tf_error)
6573 	{
6574 	  location_t loc = cp_expr_loc_or_input_loc (expr);
6575 	  error_at (loc, "%qE is not a valid template argument for type %qT",
6576 		    expr, type);
6577 	  if (TYPE_PTR_P (type))
6578 	    inform (loc, "it must be the address of a function "
6579 		    "with external linkage");
6580 	  else
6581 	    inform (loc, "it must be the name of a function with "
6582 		    "external linkage");
6583 	}
6584       return NULL_TREE;
6585     }
6586 
6587   linkage = decl_linkage (fn_no_ptr);
6588   if (cxx_dialect >= cxx11 ? linkage == lk_none : linkage != lk_external)
6589     {
6590       if (complain & tf_error)
6591 	{
6592 	  location_t loc = cp_expr_loc_or_input_loc (expr);
6593 	  if (cxx_dialect >= cxx11)
6594 	    error_at (loc, "%qE is not a valid template argument for type "
6595 		      "%qT because %qD has no linkage",
6596 		      expr, type, fn_no_ptr);
6597 	  else
6598 	    error_at (loc, "%qE is not a valid template argument for type "
6599 		      "%qT because %qD does not have external linkage",
6600 		      expr, type, fn_no_ptr);
6601 	}
6602       return NULL_TREE;
6603     }
6604 
6605  accept:
6606   if (TYPE_REF_P (type))
6607     {
6608       if (REFERENCE_REF_P (fn))
6609 	fn = TREE_OPERAND (fn, 0);
6610       else
6611 	fn = build_address (fn);
6612     }
6613   if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (fn)))
6614     fn = build_nop (type, fn);
6615 
6616   return fn;
6617 }
6618 
6619 /* Subroutine of convert_nontype_argument.
6620    Check if EXPR of type TYPE is a valid pointer-to-member constant.
6621    Emit an error otherwise.  */
6622 
6623 static bool
check_valid_ptrmem_cst_expr(tree type,tree expr,tsubst_flags_t complain)6624 check_valid_ptrmem_cst_expr (tree type, tree expr,
6625 			     tsubst_flags_t complain)
6626 {
6627   tree orig_expr = expr;
6628   STRIP_NOPS (expr);
6629   if (null_ptr_cst_p (expr))
6630     return true;
6631   if (TREE_CODE (expr) == PTRMEM_CST
6632       && same_type_p (TYPE_PTRMEM_CLASS_TYPE (type),
6633 		      PTRMEM_CST_CLASS (expr)))
6634     return true;
6635   if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
6636     return true;
6637   if (processing_template_decl
6638       && TREE_CODE (expr) == ADDR_EXPR
6639       && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
6640     return true;
6641   if (complain & tf_error)
6642     {
6643       location_t loc = cp_expr_loc_or_input_loc (orig_expr);
6644       error_at (loc, "%qE is not a valid template argument for type %qT",
6645 		orig_expr, type);
6646       if (TREE_CODE (expr) != PTRMEM_CST)
6647 	inform (loc, "it must be a pointer-to-member of the form %<&X::Y%>");
6648       else
6649 	inform (loc, "because it is a member of %qT", PTRMEM_CST_CLASS (expr));
6650     }
6651   return false;
6652 }
6653 
6654 /* Returns TRUE iff the address of OP is value-dependent.
6655 
6656    14.6.2.4 [temp.dep.temp]:
6657    A non-integral non-type template-argument is dependent if its type is
6658    dependent or it has either of the following forms
6659      qualified-id
6660      & qualified-id
6661    and contains a nested-name-specifier which specifies a class-name that
6662    names a dependent type.
6663 
6664    We generalize this to just say that the address of a member of a
6665    dependent class is value-dependent; the above doesn't cover the
6666    address of a static data member named with an unqualified-id.  */
6667 
6668 static bool
has_value_dependent_address(tree op)6669 has_value_dependent_address (tree op)
6670 {
6671   STRIP_ANY_LOCATION_WRAPPER (op);
6672 
6673   /* We could use get_inner_reference here, but there's no need;
6674      this is only relevant for template non-type arguments, which
6675      can only be expressed as &id-expression.  */
6676   if (DECL_P (op))
6677     {
6678       tree ctx = CP_DECL_CONTEXT (op);
6679       if (TYPE_P (ctx) && dependent_type_p (ctx))
6680 	return true;
6681     }
6682 
6683   return false;
6684 }
6685 
6686 /* The next set of functions are used for providing helpful explanatory
6687    diagnostics for failed overload resolution.  Their messages should be
6688    indented by two spaces for consistency with the messages in
6689    call.c  */
6690 
6691 static int
unify_success(bool)6692 unify_success (bool /*explain_p*/)
6693 {
6694   return 0;
6695 }
6696 
6697 /* Other failure functions should call this one, to provide a single function
6698    for setting a breakpoint on.  */
6699 
6700 static int
unify_invalid(bool)6701 unify_invalid (bool /*explain_p*/)
6702 {
6703   return 1;
6704 }
6705 
6706 static int
unify_parameter_deduction_failure(bool explain_p,tree parm)6707 unify_parameter_deduction_failure (bool explain_p, tree parm)
6708 {
6709   if (explain_p)
6710     inform (input_location,
6711 	    "  couldn%'t deduce template parameter %qD", parm);
6712   return unify_invalid (explain_p);
6713 }
6714 
6715 static int
unify_cv_qual_mismatch(bool explain_p,tree parm,tree arg)6716 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
6717 {
6718   if (explain_p)
6719     inform (input_location,
6720 	    "  types %qT and %qT have incompatible cv-qualifiers",
6721 	    parm, arg);
6722   return unify_invalid (explain_p);
6723 }
6724 
6725 static int
unify_type_mismatch(bool explain_p,tree parm,tree arg)6726 unify_type_mismatch (bool explain_p, tree parm, tree arg)
6727 {
6728   if (explain_p)
6729     inform (input_location, "  mismatched types %qT and %qT", parm, arg);
6730   return unify_invalid (explain_p);
6731 }
6732 
6733 static int
unify_parameter_pack_mismatch(bool explain_p,tree parm,tree arg)6734 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
6735 {
6736   if (explain_p)
6737     inform (input_location,
6738 	    "  template parameter %qD is not a parameter pack, but "
6739 	    "argument %qD is",
6740 	    parm, arg);
6741   return unify_invalid (explain_p);
6742 }
6743 
6744 static int
unify_ptrmem_cst_mismatch(bool explain_p,tree parm,tree arg)6745 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
6746 {
6747   if (explain_p)
6748     inform (input_location,
6749 	    "  template argument %qE does not match "
6750 	    "pointer-to-member constant %qE",
6751 	    arg, parm);
6752   return unify_invalid (explain_p);
6753 }
6754 
6755 static int
unify_expression_unequal(bool explain_p,tree parm,tree arg)6756 unify_expression_unequal (bool explain_p, tree parm, tree arg)
6757 {
6758   if (explain_p)
6759     inform (input_location, "  %qE is not equivalent to %qE", parm, arg);
6760   return unify_invalid (explain_p);
6761 }
6762 
6763 static int
unify_parameter_pack_inconsistent(bool explain_p,tree old_arg,tree new_arg)6764 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
6765 {
6766   if (explain_p)
6767     inform (input_location,
6768 	    "  inconsistent parameter pack deduction with %qT and %qT",
6769 	    old_arg, new_arg);
6770   return unify_invalid (explain_p);
6771 }
6772 
6773 static int
unify_inconsistency(bool explain_p,tree parm,tree first,tree second)6774 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
6775 {
6776   if (explain_p)
6777     {
6778       if (TYPE_P (parm))
6779 	inform (input_location,
6780 		"  deduced conflicting types for parameter %qT (%qT and %qT)",
6781 		parm, first, second);
6782       else
6783 	inform (input_location,
6784 		"  deduced conflicting values for non-type parameter "
6785 		"%qE (%qE and %qE)", parm, first, second);
6786     }
6787   return unify_invalid (explain_p);
6788 }
6789 
6790 static int
unify_vla_arg(bool explain_p,tree arg)6791 unify_vla_arg (bool explain_p, tree arg)
6792 {
6793   if (explain_p)
6794     inform (input_location,
6795 	    "  variable-sized array type %qT is not "
6796 	    "a valid template argument",
6797 	    arg);
6798   return unify_invalid (explain_p);
6799 }
6800 
6801 static int
unify_method_type_error(bool explain_p,tree arg)6802 unify_method_type_error (bool explain_p, tree arg)
6803 {
6804   if (explain_p)
6805     inform (input_location,
6806 	    "  member function type %qT is not a valid template argument",
6807 	    arg);
6808   return unify_invalid (explain_p);
6809 }
6810 
6811 static int
6812 unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
6813 {
6814   if (explain_p)
6815     {
6816       if (least_p)
6817 	inform_n (input_location, wanted,
6818 		  "  candidate expects at least %d argument, %d provided",
6819 		  "  candidate expects at least %d arguments, %d provided",
6820 		  wanted, have);
6821       else
6822 	inform_n (input_location, wanted,
6823 		  "  candidate expects %d argument, %d provided",
6824 		  "  candidate expects %d arguments, %d provided",
6825 		  wanted, have);
6826     }
6827   return unify_invalid (explain_p);
6828 }
6829 
6830 static int
unify_too_many_arguments(bool explain_p,int have,int wanted)6831 unify_too_many_arguments (bool explain_p, int have, int wanted)
6832 {
6833   return unify_arity (explain_p, have, wanted);
6834 }
6835 
6836 static int
6837 unify_too_few_arguments (bool explain_p, int have, int wanted,
6838 			 bool least_p = false)
6839 {
6840   return unify_arity (explain_p, have, wanted, least_p);
6841 }
6842 
6843 static int
unify_arg_conversion(bool explain_p,tree to_type,tree from_type,tree arg)6844 unify_arg_conversion (bool explain_p, tree to_type,
6845 		      tree from_type, tree arg)
6846 {
6847   if (explain_p)
6848     inform (cp_expr_loc_or_input_loc (arg),
6849 	    "  cannot convert %qE (type %qT) to type %qT",
6850 	    arg, from_type, to_type);
6851   return unify_invalid (explain_p);
6852 }
6853 
6854 static int
unify_no_common_base(bool explain_p,enum template_base_result r,tree parm,tree arg)6855 unify_no_common_base (bool explain_p, enum template_base_result r,
6856 		      tree parm, tree arg)
6857 {
6858   if (explain_p)
6859     switch (r)
6860       {
6861       case tbr_ambiguous_baseclass:
6862 	inform (input_location, "  %qT is an ambiguous base class of %qT",
6863 		parm, arg);
6864 	break;
6865       default:
6866 	inform (input_location, "  %qT is not derived from %qT", arg, parm);
6867 	break;
6868       }
6869   return unify_invalid (explain_p);
6870 }
6871 
6872 static int
unify_inconsistent_template_template_parameters(bool explain_p)6873 unify_inconsistent_template_template_parameters (bool explain_p)
6874 {
6875   if (explain_p)
6876     inform (input_location,
6877 	    "  template parameters of a template template argument are "
6878 	    "inconsistent with other deduced template arguments");
6879   return unify_invalid (explain_p);
6880 }
6881 
6882 static int
unify_template_deduction_failure(bool explain_p,tree parm,tree arg)6883 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
6884 {
6885   if (explain_p)
6886     inform (input_location,
6887 	    "  cannot deduce a template for %qT from non-template type %qT",
6888 	    parm, arg);
6889   return unify_invalid (explain_p);
6890 }
6891 
6892 static int
unify_template_argument_mismatch(bool explain_p,tree parm,tree arg)6893 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
6894 {
6895   if (explain_p)
6896     inform (input_location,
6897 	    "  template argument %qE does not match %qE", arg, parm);
6898   return unify_invalid (explain_p);
6899 }
6900 
6901 /* True if T is a C++20 template parameter object to store the argument for a
6902    template parameter of class type.  */
6903 
6904 bool
template_parm_object_p(const_tree t)6905 template_parm_object_p (const_tree t)
6906 {
6907   return (TREE_CODE (t) == VAR_DECL && DECL_ARTIFICIAL (t) && DECL_NAME (t)
6908 	  && !strncmp (IDENTIFIER_POINTER (DECL_NAME (t)), "_ZTA", 4));
6909 }
6910 
6911 /* Subroutine of convert_nontype_argument, to check whether EXPR, as an
6912    argument for TYPE, points to an unsuitable object.  */
6913 
6914 static bool
invalid_tparm_referent_p(tree type,tree expr,tsubst_flags_t complain)6915 invalid_tparm_referent_p (tree type, tree expr, tsubst_flags_t complain)
6916 {
6917   switch (TREE_CODE (expr))
6918     {
6919     CASE_CONVERT:
6920       return invalid_tparm_referent_p (type, TREE_OPERAND (expr, 0),
6921 				       complain);
6922 
6923     case TARGET_EXPR:
6924       return invalid_tparm_referent_p (type, TARGET_EXPR_INITIAL (expr),
6925 				       complain);
6926 
6927     case CONSTRUCTOR:
6928       {
6929 	unsigned i; tree elt;
6930 	FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expr), i, elt)
6931 	  if (invalid_tparm_referent_p (TREE_TYPE (elt), elt, complain))
6932 	    return true;
6933       }
6934       break;
6935 
6936     case ADDR_EXPR:
6937       {
6938 	tree decl = TREE_OPERAND (expr, 0);
6939 
6940 	if (!VAR_P (decl))
6941 	  {
6942 	    if (complain & tf_error)
6943 	      error_at (cp_expr_loc_or_input_loc (expr),
6944 			"%qE is not a valid template argument of type %qT "
6945 			"because %qE is not a variable", expr, type, decl);
6946 	    return true;
6947 	  }
6948 	else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
6949 	  {
6950 	    if (complain & tf_error)
6951 	      error_at (cp_expr_loc_or_input_loc (expr),
6952 			"%qE is not a valid template argument of type %qT "
6953 			"in C++98 because %qD does not have external linkage",
6954 			expr, type, decl);
6955 	    return true;
6956 	  }
6957 	else if ((cxx_dialect >= cxx11 && cxx_dialect < cxx17)
6958 		 && decl_linkage (decl) == lk_none)
6959 	  {
6960 	    if (complain & tf_error)
6961 	      error_at (cp_expr_loc_or_input_loc (expr),
6962 			"%qE is not a valid template argument of type %qT "
6963 			"because %qD has no linkage", expr, type, decl);
6964 	    return true;
6965 	  }
6966 	/* C++17: For a non-type template-parameter of reference or pointer
6967 	   type, the value of the constant expression shall not refer to (or
6968 	   for a pointer type, shall not be the address of):
6969 	   * a subobject (4.5),
6970 	   * a temporary object (15.2),
6971 	   * a string literal (5.13.5),
6972 	   * the result of a typeid expression (8.2.8), or
6973 	   * a predefined __func__ variable (11.4.1).  */
6974 	else if (DECL_ARTIFICIAL (decl))
6975 	  {
6976 	    if (complain & tf_error)
6977 	      error ("the address of %qD is not a valid template argument",
6978 		     decl);
6979 	    return true;
6980 	  }
6981 	else if (!same_type_ignoring_top_level_qualifiers_p
6982 		 (strip_array_types (TREE_TYPE (type)),
6983 		  strip_array_types (TREE_TYPE (decl))))
6984 	  {
6985 	    if (complain & tf_error)
6986 	      error ("the address of the %qT subobject of %qD is not a "
6987 		     "valid template argument", TREE_TYPE (type), decl);
6988 	    return true;
6989 	  }
6990 	else if (!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
6991 	  {
6992 	    if (complain & tf_error)
6993 	      error ("the address of %qD is not a valid template argument "
6994 		     "because it does not have static storage duration",
6995 		     decl);
6996 	    return true;
6997 	  }
6998       }
6999       break;
7000 
7001     default:
7002       if (!INDIRECT_TYPE_P (type))
7003 	/* We're only concerned about pointers and references here.  */;
7004       else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7005 	/* Null pointer values are OK in C++11.  */;
7006       else
7007 	{
7008 	  if (VAR_P (expr))
7009 	    {
7010 	      if (complain & tf_error)
7011 		error ("%qD is not a valid template argument "
7012 		       "because %qD is a variable, not the address of "
7013 		       "a variable", expr, expr);
7014 	      return true;
7015 	    }
7016 	  else
7017 	    {
7018 	      if (complain & tf_error)
7019 		error ("%qE is not a valid template argument for %qT "
7020 		       "because it is not the address of a variable",
7021 		       expr, type);
7022 	      return true;
7023 	    }
7024 	}
7025     }
7026   return false;
7027 
7028 }
7029 
7030 /* The template arguments corresponding to template parameter objects of types
7031    that contain pointers to members.  */
7032 
7033 static GTY(()) hash_map<tree, tree> *tparm_obj_values;
7034 
7035 /* Return a VAR_DECL for the C++20 template parameter object corresponding to
7036    template argument EXPR.  */
7037 
7038 static tree
get_template_parm_object(tree expr,tsubst_flags_t complain)7039 get_template_parm_object (tree expr, tsubst_flags_t complain)
7040 {
7041   if (TREE_CODE (expr) == TARGET_EXPR)
7042     expr = TARGET_EXPR_INITIAL (expr);
7043 
7044   if (!TREE_CONSTANT (expr))
7045     {
7046       if ((complain & tf_error)
7047 	  && require_rvalue_constant_expression (expr))
7048 	cxx_constant_value (expr);
7049       return error_mark_node;
7050     }
7051   if (invalid_tparm_referent_p (TREE_TYPE (expr), expr, complain))
7052     return error_mark_node;
7053 
7054   tree name = mangle_template_parm_object (expr);
7055   tree decl = get_global_binding (name);
7056   if (decl)
7057     return decl;
7058 
7059   tree type = cp_build_qualified_type (TREE_TYPE (expr), TYPE_QUAL_CONST);
7060   decl = create_temporary_var (type);
7061   TREE_STATIC (decl) = true;
7062   DECL_DECLARED_CONSTEXPR_P (decl) = true;
7063   TREE_READONLY (decl) = true;
7064   DECL_NAME (decl) = name;
7065   SET_DECL_ASSEMBLER_NAME (decl, name);
7066   DECL_CONTEXT (decl) = global_namespace;
7067   comdat_linkage (decl);
7068 
7069   if (!zero_init_p (type))
7070     {
7071       /* If EXPR contains any PTRMEM_CST, they will get clobbered by
7072 	 lower_var_init before we're done mangling.  So store the original
7073 	 value elsewhere.  */
7074       tree copy = unshare_constructor (expr);
7075       hash_map_safe_put<hm_ggc> (tparm_obj_values, decl, copy);
7076     }
7077 
7078   pushdecl_top_level_and_finish (decl, expr);
7079 
7080   return decl;
7081 }
7082 
7083 /* Return the actual template argument corresponding to template parameter
7084    object VAR.  */
7085 
7086 tree
tparm_object_argument(tree var)7087 tparm_object_argument (tree var)
7088 {
7089   if (zero_init_p (TREE_TYPE (var)))
7090     return DECL_INITIAL (var);
7091   return *(tparm_obj_values->get (var));
7092 }
7093 
7094 /* Attempt to convert the non-type template parameter EXPR to the
7095    indicated TYPE.  If the conversion is successful, return the
7096    converted value.  If the conversion is unsuccessful, return
7097    NULL_TREE if we issued an error message, or error_mark_node if we
7098    did not.  We issue error messages for out-and-out bad template
7099    parameters, but not simply because the conversion failed, since we
7100    might be just trying to do argument deduction.  Both TYPE and EXPR
7101    must be non-dependent.
7102 
7103    The conversion follows the special rules described in
7104    [temp.arg.nontype], and it is much more strict than an implicit
7105    conversion.
7106 
7107    This function is called twice for each template argument (see
7108    lookup_template_class for a more accurate description of this
7109    problem). This means that we need to handle expressions which
7110    are not valid in a C++ source, but can be created from the
7111    first call (for instance, casts to perform conversions). These
7112    hacks can go away after we fix the double coercion problem.  */
7113 
7114 static tree
convert_nontype_argument(tree type,tree expr,tsubst_flags_t complain)7115 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
7116 {
7117   tree expr_type;
7118   location_t loc = cp_expr_loc_or_input_loc (expr);
7119 
7120   /* Detect immediately string literals as invalid non-type argument.
7121      This special-case is not needed for correctness (we would easily
7122      catch this later), but only to provide better diagnostic for this
7123      common user mistake. As suggested by DR 100, we do not mention
7124      linkage issues in the diagnostic as this is not the point.  */
7125   if (TREE_CODE (expr) == STRING_CST && !CLASS_TYPE_P (type))
7126     {
7127       if (complain & tf_error)
7128 	error ("%qE is not a valid template argument for type %qT "
7129 	       "because string literals can never be used in this context",
7130 	       expr, type);
7131       return NULL_TREE;
7132     }
7133 
7134   /* Add the ADDR_EXPR now for the benefit of
7135      value_dependent_expression_p.  */
7136   if (TYPE_PTROBV_P (type)
7137       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
7138     {
7139       expr = decay_conversion (expr, complain);
7140       if (expr == error_mark_node)
7141 	return error_mark_node;
7142     }
7143 
7144   /* If we are in a template, EXPR may be non-dependent, but still
7145      have a syntactic, rather than semantic, form.  For example, EXPR
7146      might be a SCOPE_REF, rather than the VAR_DECL to which the
7147      SCOPE_REF refers.  Preserving the qualifying scope is necessary
7148      so that access checking can be performed when the template is
7149      instantiated -- but here we need the resolved form so that we can
7150      convert the argument.  */
7151   bool non_dep = false;
7152   if (TYPE_REF_OBJ_P (type)
7153       && has_value_dependent_address (expr))
7154     /* If we want the address and it's value-dependent, don't fold.  */;
7155   else if (processing_template_decl
7156 	   && is_nondependent_constant_expression (expr))
7157     non_dep = true;
7158   if (error_operand_p (expr))
7159     return error_mark_node;
7160   expr_type = TREE_TYPE (expr);
7161 
7162   /* If the argument is non-dependent, perform any conversions in
7163      non-dependent context as well.  */
7164   processing_template_decl_sentinel s (non_dep);
7165   if (non_dep)
7166     expr = instantiate_non_dependent_expr_internal (expr, complain);
7167 
7168   const bool val_dep_p = value_dependent_expression_p (expr);
7169   if (val_dep_p)
7170     expr = canonicalize_expr_argument (expr, complain);
7171 
7172   /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
7173      to a non-type argument of "nullptr".  */
7174   if (NULLPTR_TYPE_P (expr_type) && TYPE_PTR_OR_PTRMEM_P (type))
7175     expr = fold_simple (convert (type, expr));
7176 
7177   /* In C++11, integral or enumeration non-type template arguments can be
7178      arbitrary constant expressions.  Pointer and pointer to
7179      member arguments can be general constant expressions that evaluate
7180      to a null value, but otherwise still need to be of a specific form.  */
7181   if (cxx_dialect >= cxx11)
7182     {
7183       if (TREE_CODE (expr) == PTRMEM_CST && TYPE_PTRMEM_P (type))
7184 	/* A PTRMEM_CST is already constant, and a valid template
7185 	   argument for a parameter of pointer to member type, we just want
7186 	   to leave it in that form rather than lower it to a
7187 	   CONSTRUCTOR.  */;
7188       else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7189 	       || cxx_dialect >= cxx17)
7190 	{
7191 	  /* C++17: A template-argument for a non-type template-parameter shall
7192 	     be a converted constant expression (8.20) of the type of the
7193 	     template-parameter.  */
7194 	  expr = build_converted_constant_expr (type, expr, complain);
7195 	  if (expr == error_mark_node)
7196 	    /* Make sure we return NULL_TREE only if we have really issued
7197 	       an error, as described above.  */
7198 	    return (complain & tf_error) ? NULL_TREE : error_mark_node;
7199 	  else if (TREE_CODE (expr) == IMPLICIT_CONV_EXPR)
7200 	    {
7201 	      IMPLICIT_CONV_EXPR_NONTYPE_ARG (expr) = true;
7202 	      return expr;
7203 	    }
7204 	  expr = maybe_constant_value (expr, NULL_TREE,
7205 				       /*manifestly_const_eval=*/true);
7206 	  expr = convert_from_reference (expr);
7207 	}
7208       else if (TYPE_PTR_OR_PTRMEM_P (type))
7209 	{
7210 	  tree folded = maybe_constant_value (expr, NULL_TREE,
7211 					      /*manifestly_const_eval=*/true);
7212 	  if (TYPE_PTR_P (type) ? integer_zerop (folded)
7213 	      : null_member_pointer_value_p (folded))
7214 	    expr = folded;
7215 	}
7216     }
7217 
7218   if (TYPE_REF_P (type))
7219     expr = mark_lvalue_use (expr);
7220   else
7221     expr = mark_rvalue_use (expr);
7222 
7223   /* HACK: Due to double coercion, we can get a
7224      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
7225      which is the tree that we built on the first call (see
7226      below when coercing to reference to object or to reference to
7227      function). We just strip everything and get to the arg.
7228      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
7229      for examples.  */
7230   if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
7231     {
7232       tree probe_type, probe = expr;
7233       if (REFERENCE_REF_P (probe))
7234 	probe = TREE_OPERAND (probe, 0);
7235       probe_type = TREE_TYPE (probe);
7236       if (TREE_CODE (probe) == NOP_EXPR)
7237 	{
7238 	  /* ??? Maybe we could use convert_from_reference here, but we
7239 	     would need to relax its constraints because the NOP_EXPR
7240 	     could actually change the type to something more cv-qualified,
7241 	     and this is not folded by convert_from_reference.  */
7242 	  tree addr = TREE_OPERAND (probe, 0);
7243 	  if (TYPE_REF_P (probe_type)
7244 	      && TREE_CODE (addr) == ADDR_EXPR
7245 	      && TYPE_PTR_P (TREE_TYPE (addr))
7246 	      && (same_type_ignoring_top_level_qualifiers_p
7247 		  (TREE_TYPE (probe_type),
7248 		   TREE_TYPE (TREE_TYPE (addr)))))
7249 	    {
7250 	      expr = TREE_OPERAND (addr, 0);
7251 	      expr_type = TREE_TYPE (probe_type);
7252 	    }
7253 	}
7254     }
7255 
7256   /* [temp.arg.nontype]/5, bullet 1
7257 
7258      For a non-type template-parameter of integral or enumeration type,
7259      integral promotions (_conv.prom_) and integral conversions
7260      (_conv.integral_) are applied.  */
7261   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
7262     {
7263       if (cxx_dialect < cxx11)
7264 	{
7265 	  tree t = build_converted_constant_expr (type, expr, complain);
7266 	  t = maybe_constant_value (t);
7267 	  if (t != error_mark_node)
7268 	    expr = t;
7269 	}
7270 
7271       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
7272 	return error_mark_node;
7273 
7274       /* Notice that there are constant expressions like '4 % 0' which
7275 	 do not fold into integer constants.  */
7276       if (TREE_CODE (expr) != INTEGER_CST && !val_dep_p)
7277 	{
7278 	  if (complain & tf_error)
7279 	    {
7280 	      int errs = errorcount, warns = warningcount + werrorcount;
7281 	      if (!require_potential_constant_expression (expr))
7282 		expr = error_mark_node;
7283 	      else
7284 		expr = cxx_constant_value (expr);
7285 	      if (errorcount > errs || warningcount + werrorcount > warns)
7286 		inform (loc, "in template argument for type %qT", type);
7287 	      if (expr == error_mark_node)
7288 		return NULL_TREE;
7289 	      /* else cxx_constant_value complained but gave us
7290 		 a real constant, so go ahead.  */
7291 	      if (TREE_CODE (expr) != INTEGER_CST)
7292 		{
7293 		  /* Some assemble time constant expressions like
7294 		     (intptr_t)&&lab1 - (intptr_t)&&lab2 or
7295 		     4 + (intptr_t)&&var satisfy reduced_constant_expression_p
7296 		     as we can emit them into .rodata initializers of
7297 		     variables, yet they can't fold into an INTEGER_CST at
7298 		     compile time.  Refuse them here.  */
7299 		  gcc_checking_assert (reduced_constant_expression_p (expr));
7300 		  error_at (loc, "template argument %qE for type %qT not "
7301 				 "a constant integer", expr, type);
7302 		  return NULL_TREE;
7303 		}
7304 	    }
7305 	  else
7306 	    return NULL_TREE;
7307 	}
7308 
7309       /* Avoid typedef problems.  */
7310       if (TREE_TYPE (expr) != type)
7311 	expr = fold_convert (type, expr);
7312     }
7313   /* [temp.arg.nontype]/5, bullet 2
7314 
7315      For a non-type template-parameter of type pointer to object,
7316      qualification conversions (_conv.qual_) and the array-to-pointer
7317      conversion (_conv.array_) are applied.  */
7318   else if (TYPE_PTROBV_P (type))
7319     {
7320       tree decayed = expr;
7321 
7322       /* Look through any NOP_EXPRs around an ADDR_EXPR, whether they come from
7323 	 decay_conversion or an explicit cast.  If it's a problematic cast,
7324 	 we'll complain about it below.  */
7325       if (TREE_CODE (expr) == NOP_EXPR)
7326 	{
7327 	  tree probe = expr;
7328 	  STRIP_NOPS (probe);
7329 	  if (TREE_CODE (probe) == ADDR_EXPR
7330 	      && TYPE_PTR_P (TREE_TYPE (probe)))
7331 	    {
7332 	      expr = probe;
7333 	      expr_type = TREE_TYPE (expr);
7334 	    }
7335 	}
7336 
7337       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
7338 
7339 	 A template-argument for a non-type, non-template template-parameter
7340 	 shall be one of: [...]
7341 
7342 	 -- the name of a non-type template-parameter;
7343 	 -- the address of an object or function with external linkage, [...]
7344 	    expressed as "& id-expression" where the & is optional if the name
7345 	    refers to a function or array, or if the corresponding
7346 	    template-parameter is a reference.
7347 
7348 	Here, we do not care about functions, as they are invalid anyway
7349 	for a parameter of type pointer-to-object.  */
7350 
7351       if (val_dep_p)
7352 	/* Non-type template parameters are OK.  */
7353 	;
7354       else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7355 	/* Null pointer values are OK in C++11.  */;
7356       else if (TREE_CODE (expr) != ADDR_EXPR
7357 	       && !INDIRECT_TYPE_P (expr_type))
7358 	/* Other values, like integer constants, might be valid
7359 	   non-type arguments of some other type.  */
7360 	return error_mark_node;
7361       else if (invalid_tparm_referent_p (type, expr, complain))
7362 	return NULL_TREE;
7363 
7364       expr = decayed;
7365 
7366       expr = perform_qualification_conversions (type, expr);
7367       if (expr == error_mark_node)
7368 	return error_mark_node;
7369     }
7370   /* [temp.arg.nontype]/5, bullet 3
7371 
7372      For a non-type template-parameter of type reference to object, no
7373      conversions apply. The type referred to by the reference may be more
7374      cv-qualified than the (otherwise identical) type of the
7375      template-argument. The template-parameter is bound directly to the
7376      template-argument, which must be an lvalue.  */
7377   else if (TYPE_REF_OBJ_P (type))
7378     {
7379       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
7380 						      expr_type))
7381 	return error_mark_node;
7382 
7383       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
7384 	{
7385 	  if (complain & tf_error)
7386 	    error ("%qE is not a valid template argument for type %qT "
7387 		   "because of conflicts in cv-qualification", expr, type);
7388 	  return NULL_TREE;
7389 	}
7390 
7391       if (!lvalue_p (expr))
7392 	{
7393 	  if (complain & tf_error)
7394 	    error ("%qE is not a valid template argument for type %qT "
7395 		   "because it is not an lvalue", expr, type);
7396 	  return NULL_TREE;
7397 	}
7398 
7399       /* [temp.arg.nontype]/1
7400 
7401 	 A template-argument for a non-type, non-template template-parameter
7402 	 shall be one of: [...]
7403 
7404 	 -- the address of an object or function with external linkage.  */
7405       if (INDIRECT_REF_P (expr)
7406 	  && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
7407 	{
7408 	  expr = TREE_OPERAND (expr, 0);
7409 	  if (DECL_P (expr))
7410 	    {
7411 	      if (complain & tf_error)
7412 		error ("%q#D is not a valid template argument for type %qT "
7413 		       "because a reference variable does not have a constant "
7414 		       "address", expr, type);
7415 	      return NULL_TREE;
7416 	    }
7417 	}
7418 
7419       if (TYPE_REF_OBJ_P (TREE_TYPE (expr)) && val_dep_p)
7420 	/* OK, dependent reference.  We don't want to ask whether a DECL is
7421 	   itself value-dependent, since what we want here is its address.  */;
7422       else
7423 	{
7424 	  expr = build_address (expr);
7425 
7426 	  if (invalid_tparm_referent_p (type, expr, complain))
7427 	    return NULL_TREE;
7428 	}
7429 
7430       if (!same_type_p (type, TREE_TYPE (expr)))
7431 	expr = build_nop (type, expr);
7432     }
7433   /* [temp.arg.nontype]/5, bullet 4
7434 
7435      For a non-type template-parameter of type pointer to function, only
7436      the function-to-pointer conversion (_conv.func_) is applied. If the
7437      template-argument represents a set of overloaded functions (or a
7438      pointer to such), the matching function is selected from the set
7439      (_over.over_).  */
7440   else if (TYPE_PTRFN_P (type))
7441     {
7442       /* If the argument is a template-id, we might not have enough
7443 	 context information to decay the pointer.  */
7444       if (!type_unknown_p (expr_type))
7445 	{
7446 	  expr = decay_conversion (expr, complain);
7447 	  if (expr == error_mark_node)
7448 	    return error_mark_node;
7449 	}
7450 
7451       if (cxx_dialect >= cxx11 && integer_zerop (expr))
7452 	/* Null pointer values are OK in C++11.  */
7453 	return perform_qualification_conversions (type, expr);
7454 
7455       expr = convert_nontype_argument_function (type, expr, complain);
7456       if (!expr || expr == error_mark_node)
7457 	return expr;
7458     }
7459   /* [temp.arg.nontype]/5, bullet 5
7460 
7461      For a non-type template-parameter of type reference to function, no
7462      conversions apply. If the template-argument represents a set of
7463      overloaded functions, the matching function is selected from the set
7464      (_over.over_).  */
7465   else if (TYPE_REFFN_P (type))
7466     {
7467       if (TREE_CODE (expr) == ADDR_EXPR)
7468 	{
7469 	  if (complain & tf_error)
7470 	    {
7471 	      error ("%qE is not a valid template argument for type %qT "
7472 		     "because it is a pointer", expr, type);
7473 	      inform (input_location, "try using %qE instead",
7474 		      TREE_OPERAND (expr, 0));
7475 	    }
7476 	  return NULL_TREE;
7477 	}
7478 
7479       expr = convert_nontype_argument_function (type, expr, complain);
7480       if (!expr || expr == error_mark_node)
7481 	return expr;
7482     }
7483   /* [temp.arg.nontype]/5, bullet 6
7484 
7485      For a non-type template-parameter of type pointer to member function,
7486      no conversions apply. If the template-argument represents a set of
7487      overloaded member functions, the matching member function is selected
7488      from the set (_over.over_).  */
7489   else if (TYPE_PTRMEMFUNC_P (type))
7490     {
7491       expr = instantiate_type (type, expr, tf_none);
7492       if (expr == error_mark_node)
7493 	return error_mark_node;
7494 
7495       /* [temp.arg.nontype] bullet 1 says the pointer to member
7496          expression must be a pointer-to-member constant.  */
7497       if (!val_dep_p
7498 	  && !check_valid_ptrmem_cst_expr (type, expr, complain))
7499 	return NULL_TREE;
7500 
7501       /* Repeated conversion can't deal with a conversion that turns PTRMEM_CST
7502 	 into a CONSTRUCTOR, so build up a new PTRMEM_CST instead.  */
7503       if (fnptr_conv_p (type, TREE_TYPE (expr)))
7504 	expr = make_ptrmem_cst (type, PTRMEM_CST_MEMBER (expr));
7505     }
7506   /* [temp.arg.nontype]/5, bullet 7
7507 
7508      For a non-type template-parameter of type pointer to data member,
7509      qualification conversions (_conv.qual_) are applied.  */
7510   else if (TYPE_PTRDATAMEM_P (type))
7511     {
7512       /* [temp.arg.nontype] bullet 1 says the pointer to member
7513          expression must be a pointer-to-member constant.  */
7514       if (!val_dep_p
7515 	  && !check_valid_ptrmem_cst_expr (type, expr, complain))
7516 	return NULL_TREE;
7517 
7518       expr = perform_qualification_conversions (type, expr);
7519       if (expr == error_mark_node)
7520 	return expr;
7521     }
7522   else if (NULLPTR_TYPE_P (type))
7523     {
7524       if (!NULLPTR_TYPE_P (TREE_TYPE (expr)))
7525 	{
7526 	  if (complain & tf_error)
7527 	    error ("%qE is not a valid template argument for type %qT "
7528 		   "because it is of type %qT", expr, type, TREE_TYPE (expr));
7529 	  return NULL_TREE;
7530 	}
7531       return expr;
7532     }
7533   else if (CLASS_TYPE_P (type))
7534     {
7535       /* Replace the argument with a reference to the corresponding template
7536 	 parameter object.  */
7537       if (!val_dep_p)
7538 	expr = get_template_parm_object (expr, complain);
7539       if (expr == error_mark_node)
7540 	return NULL_TREE;
7541     }
7542   /* A template non-type parameter must be one of the above.  */
7543   else
7544     gcc_unreachable ();
7545 
7546   /* Sanity check: did we actually convert the argument to the
7547      right type?  */
7548   gcc_assert (same_type_ignoring_top_level_qualifiers_p
7549 	      (type, TREE_TYPE (expr)));
7550   return convert_from_reference (expr);
7551 }
7552 
7553 /* Subroutine of coerce_template_template_parms, which returns 1 if
7554    PARM_PARM and ARG_PARM match using the rule for the template
7555    parameters of template template parameters. Both PARM and ARG are
7556    template parameters; the rest of the arguments are the same as for
7557    coerce_template_template_parms.
7558  */
7559 static int
coerce_template_template_parm(tree parm,tree arg,tsubst_flags_t complain,tree in_decl,tree outer_args)7560 coerce_template_template_parm (tree parm,
7561                               tree arg,
7562                               tsubst_flags_t complain,
7563                               tree in_decl,
7564                               tree outer_args)
7565 {
7566   if (arg == NULL_TREE || error_operand_p (arg)
7567       || parm == NULL_TREE || error_operand_p (parm))
7568     return 0;
7569 
7570   if (TREE_CODE (arg) != TREE_CODE (parm))
7571     return 0;
7572 
7573   switch (TREE_CODE (parm))
7574     {
7575     case TEMPLATE_DECL:
7576       /* We encounter instantiations of templates like
7577 	 template <template <template <class> class> class TT>
7578 	 class C;  */
7579       {
7580 	tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
7581 	tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
7582 
7583 	if (!coerce_template_template_parms
7584 	    (parmparm, argparm, complain, in_decl, outer_args))
7585 	  return 0;
7586       }
7587       /* Fall through.  */
7588 
7589     case TYPE_DECL:
7590       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
7591 	  && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7592 	/* Argument is a parameter pack but parameter is not.  */
7593 	return 0;
7594       break;
7595 
7596     case PARM_DECL:
7597       /* The tsubst call is used to handle cases such as
7598 
7599            template <int> class C {};
7600 	   template <class T, template <T> class TT> class D {};
7601 	   D<int, C> d;
7602 
7603 	 i.e. the parameter list of TT depends on earlier parameters.  */
7604       if (!uses_template_parms (TREE_TYPE (arg)))
7605 	{
7606 	  tree t = tsubst (TREE_TYPE (parm), outer_args, complain, in_decl);
7607 	  if (!uses_template_parms (t)
7608 	      && !same_type_p (t, TREE_TYPE (arg)))
7609 	    return 0;
7610 	}
7611 
7612       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
7613 	  && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7614 	/* Argument is a parameter pack but parameter is not.  */
7615 	return 0;
7616 
7617       break;
7618 
7619     default:
7620       gcc_unreachable ();
7621     }
7622 
7623   return 1;
7624 }
7625 
7626 /* Coerce template argument list ARGLIST for use with template
7627    template-parameter TEMPL.  */
7628 
7629 static tree
coerce_template_args_for_ttp(tree templ,tree arglist,tsubst_flags_t complain)7630 coerce_template_args_for_ttp (tree templ, tree arglist,
7631 			      tsubst_flags_t complain)
7632 {
7633   /* Consider an example where a template template parameter declared as
7634 
7635      template <class T, class U = std::allocator<T> > class TT
7636 
7637      The template parameter level of T and U are one level larger than
7638      of TT.  To proper process the default argument of U, say when an
7639      instantiation `TT<int>' is seen, we need to build the full
7640      arguments containing {int} as the innermost level.  Outer levels,
7641      available when not appearing as default template argument, can be
7642      obtained from the arguments of the enclosing template.
7643 
7644      Suppose that TT is later substituted with std::vector.  The above
7645      instantiation is `TT<int, std::allocator<T> >' with TT at
7646      level 1, and T at level 2, while the template arguments at level 1
7647      becomes {std::vector} and the inner level 2 is {int}.  */
7648 
7649   tree outer = DECL_CONTEXT (templ);
7650   if (outer)
7651     outer = generic_targs_for (outer);
7652   else if (current_template_parms)
7653     {
7654       /* This is an argument of the current template, so we haven't set
7655 	 DECL_CONTEXT yet.  */
7656       tree relevant_template_parms;
7657 
7658       /* Parameter levels that are greater than the level of the given
7659 	 template template parm are irrelevant.  */
7660       relevant_template_parms = current_template_parms;
7661       while (TMPL_PARMS_DEPTH (relevant_template_parms)
7662 	     != TEMPLATE_TYPE_LEVEL (TREE_TYPE (templ)))
7663 	relevant_template_parms = TREE_CHAIN (relevant_template_parms);
7664 
7665       outer = template_parms_to_args (relevant_template_parms);
7666     }
7667 
7668   if (outer)
7669     arglist = add_to_template_args (outer, arglist);
7670 
7671   tree parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7672   return coerce_template_parms (parmlist, arglist, templ,
7673 				complain,
7674 				/*require_all_args=*/true,
7675 				/*use_default_args=*/true);
7676 }
7677 
7678 /* A cache of template template parameters with match-all default
7679    arguments.  */
7680 static GTY((deletable)) hash_map<tree,tree> *defaulted_ttp_cache;
7681 
7682 /* T is a bound template template-parameter.  Copy its arguments into default
7683    arguments of the template template-parameter's template parameters.  */
7684 
7685 static tree
add_defaults_to_ttp(tree otmpl)7686 add_defaults_to_ttp (tree otmpl)
7687 {
7688   if (tree *c = hash_map_safe_get (defaulted_ttp_cache, otmpl))
7689     return *c;
7690 
7691   tree ntmpl = copy_node (otmpl);
7692 
7693   tree ntype = copy_node (TREE_TYPE (otmpl));
7694   TYPE_STUB_DECL (ntype) = TYPE_NAME (ntype) = ntmpl;
7695   TYPE_MAIN_VARIANT (ntype) = ntype;
7696   TYPE_POINTER_TO (ntype) = TYPE_REFERENCE_TO (ntype) = NULL_TREE;
7697   TYPE_NAME (ntype) = ntmpl;
7698   SET_TYPE_STRUCTURAL_EQUALITY (ntype);
7699 
7700   tree idx = TEMPLATE_TYPE_PARM_INDEX (ntype)
7701     = copy_node (TEMPLATE_TYPE_PARM_INDEX (ntype));
7702   TEMPLATE_PARM_DECL (idx) = ntmpl;
7703   TREE_TYPE (ntmpl) = TREE_TYPE (idx) = ntype;
7704 
7705   tree oparms = DECL_TEMPLATE_PARMS (otmpl);
7706   tree parms = DECL_TEMPLATE_PARMS (ntmpl) = copy_node (oparms);
7707   TREE_CHAIN (parms) = TREE_CHAIN (oparms);
7708   tree vec = TREE_VALUE (parms) = copy_node (TREE_VALUE (parms));
7709   for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
7710     {
7711       tree o = TREE_VEC_ELT (vec, i);
7712       if (!template_parameter_pack_p (TREE_VALUE (o)))
7713 	{
7714 	  tree n = TREE_VEC_ELT (vec, i) = copy_node (o);
7715 	  TREE_PURPOSE (n) = any_targ_node;
7716 	}
7717     }
7718 
7719   hash_map_safe_put<hm_ggc> (defaulted_ttp_cache, otmpl, ntmpl);
7720   return ntmpl;
7721 }
7722 
7723 /* ARG is a bound potential template template-argument, and PARGS is a list
7724    of arguments for the corresponding template template-parameter.  Adjust
7725    PARGS as appropriate for application to ARG's template, and if ARG is a
7726    BOUND_TEMPLATE_TEMPLATE_PARM, possibly adjust it to add default template
7727    arguments to the template template parameter.  */
7728 
7729 static tree
coerce_ttp_args_for_tta(tree & arg,tree pargs,tsubst_flags_t complain)7730 coerce_ttp_args_for_tta (tree& arg, tree pargs, tsubst_flags_t complain)
7731 {
7732   ++processing_template_decl;
7733   tree arg_tmpl = TYPE_TI_TEMPLATE (arg);
7734   if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
7735     {
7736       /* When comparing two template template-parameters in partial ordering,
7737 	 rewrite the one currently being used as an argument to have default
7738 	 arguments for all parameters.  */
7739       arg_tmpl = add_defaults_to_ttp (arg_tmpl);
7740       pargs = coerce_template_args_for_ttp (arg_tmpl, pargs, complain);
7741       if (pargs != error_mark_node)
7742 	arg = bind_template_template_parm (TREE_TYPE (arg_tmpl),
7743 					   TYPE_TI_ARGS (arg));
7744     }
7745   else
7746     {
7747       tree aparms
7748 	= INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (arg_tmpl));
7749       pargs = coerce_template_parms (aparms, pargs, arg_tmpl, complain,
7750 				       /*require_all*/true,
7751 				       /*use_default*/true);
7752     }
7753   --processing_template_decl;
7754   return pargs;
7755 }
7756 
7757 /* Subroutine of unify for the case when PARM is a
7758    BOUND_TEMPLATE_TEMPLATE_PARM.  */
7759 
7760 static int
unify_bound_ttp_args(tree tparms,tree targs,tree parm,tree & arg,bool explain_p)7761 unify_bound_ttp_args (tree tparms, tree targs, tree parm, tree& arg,
7762 		      bool explain_p)
7763 {
7764   tree parmvec = TYPE_TI_ARGS (parm);
7765   tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
7766 
7767   /* The template template parm might be variadic and the argument
7768      not, so flatten both argument lists.  */
7769   parmvec = expand_template_argument_pack (parmvec);
7770   argvec = expand_template_argument_pack (argvec);
7771 
7772   if (flag_new_ttp)
7773     {
7774       /* In keeping with P0522R0, adjust P's template arguments
7775 	 to apply to A's template; then flatten it again.  */
7776       tree nparmvec = coerce_ttp_args_for_tta (arg, parmvec, tf_none);
7777       nparmvec = expand_template_argument_pack (nparmvec);
7778 
7779       if (unify (tparms, targs, nparmvec, argvec,
7780 		 UNIFY_ALLOW_NONE, explain_p))
7781 	return 1;
7782 
7783       /* If the P0522 adjustment eliminated a pack expansion, deduce
7784 	 empty packs.  */
7785       if (flag_new_ttp
7786 	  && TREE_VEC_LENGTH (nparmvec) < TREE_VEC_LENGTH (parmvec)
7787 	  && unify_pack_expansion (tparms, targs, parmvec, argvec,
7788 				   DEDUCE_EXACT, /*sub*/true, explain_p))
7789 	return 1;
7790     }
7791   else
7792     {
7793       /* Deduce arguments T, i from TT<T> or TT<i>.
7794 	 We check each element of PARMVEC and ARGVEC individually
7795 	 rather than the whole TREE_VEC since they can have
7796 	 different number of elements, which is allowed under N2555.  */
7797 
7798       int len = TREE_VEC_LENGTH (parmvec);
7799 
7800       /* Check if the parameters end in a pack, making them
7801 	 variadic.  */
7802       int parm_variadic_p = 0;
7803       if (len > 0
7804 	  && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
7805 	parm_variadic_p = 1;
7806 
7807       for (int i = 0; i < len - parm_variadic_p; ++i)
7808 	/* If the template argument list of P contains a pack
7809 	   expansion that is not the last template argument, the
7810 	   entire template argument list is a non-deduced
7811 	   context.  */
7812 	if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
7813 	  return unify_success (explain_p);
7814 
7815       if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
7816 	return unify_too_few_arguments (explain_p,
7817 					TREE_VEC_LENGTH (argvec), len);
7818 
7819       for (int i = 0; i < len - parm_variadic_p; ++i)
7820 	if (unify (tparms, targs,
7821 		   TREE_VEC_ELT (parmvec, i),
7822 		   TREE_VEC_ELT (argvec, i),
7823 		   UNIFY_ALLOW_NONE, explain_p))
7824 	  return 1;
7825 
7826       if (parm_variadic_p
7827 	  && unify_pack_expansion (tparms, targs,
7828 				   parmvec, argvec,
7829 				   DEDUCE_EXACT,
7830 				   /*subr=*/true, explain_p))
7831 	return 1;
7832     }
7833 
7834   return 0;
7835 }
7836 
7837 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
7838    template template parameters.  Both PARM_PARMS and ARG_PARMS are
7839    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
7840    or PARM_DECL.
7841 
7842    Consider the example:
7843      template <class T> class A;
7844      template<template <class U> class TT> class B;
7845 
7846    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
7847    the parameters to A, and OUTER_ARGS contains A.  */
7848 
7849 static int
coerce_template_template_parms(tree parm_parms,tree arg_parms,tsubst_flags_t complain,tree in_decl,tree outer_args)7850 coerce_template_template_parms (tree parm_parms,
7851 				tree arg_parms,
7852 				tsubst_flags_t complain,
7853 				tree in_decl,
7854 				tree outer_args)
7855 {
7856   int nparms, nargs, i;
7857   tree parm, arg;
7858   int variadic_p = 0;
7859 
7860   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
7861   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
7862 
7863   nparms = TREE_VEC_LENGTH (parm_parms);
7864   nargs = TREE_VEC_LENGTH (arg_parms);
7865 
7866   if (flag_new_ttp)
7867     {
7868       /* P0522R0: A template template-parameter P is at least as specialized as
7869 	 a template template-argument A if, given the following rewrite to two
7870 	 function templates, the function template corresponding to P is at
7871 	 least as specialized as the function template corresponding to A
7872 	 according to the partial ordering rules for function templates
7873 	 ([temp.func.order]). Given an invented class template X with the
7874 	 template parameter list of A (including default arguments):
7875 
7876 	 * Each of the two function templates has the same template parameters,
7877 	 respectively, as P or A.
7878 
7879 	 * Each function template has a single function parameter whose type is
7880 	 a specialization of X with template arguments corresponding to the
7881 	 template parameters from the respective function template where, for
7882 	 each template parameter PP in the template parameter list of the
7883 	 function template, a corresponding template argument AA is formed. If
7884 	 PP declares a parameter pack, then AA is the pack expansion
7885 	 PP... ([temp.variadic]); otherwise, AA is the id-expression PP.
7886 
7887 	 If the rewrite produces an invalid type, then P is not at least as
7888 	 specialized as A.  */
7889 
7890       /* So coerce P's args to apply to A's parms, and then deduce between A's
7891 	 args and the converted args.  If that succeeds, A is at least as
7892 	 specialized as P, so they match.*/
7893       tree pargs = template_parms_level_to_args (parm_parms);
7894       pargs = add_outermost_template_args (outer_args, pargs);
7895       ++processing_template_decl;
7896       pargs = coerce_template_parms (arg_parms, pargs, NULL_TREE, tf_none,
7897 				     /*require_all*/true, /*use_default*/true);
7898       --processing_template_decl;
7899       if (pargs != error_mark_node)
7900 	{
7901 	  tree targs = make_tree_vec (nargs);
7902 	  tree aargs = template_parms_level_to_args (arg_parms);
7903 	  if (!unify (arg_parms, targs, aargs, pargs, UNIFY_ALLOW_NONE,
7904 		      /*explain*/false))
7905 	    return 1;
7906 	}
7907     }
7908 
7909   /* Determine whether we have a parameter pack at the end of the
7910      template template parameter's template parameter list.  */
7911   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
7912     {
7913       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
7914 
7915       if (error_operand_p (parm))
7916 	return 0;
7917 
7918       switch (TREE_CODE (parm))
7919         {
7920         case TEMPLATE_DECL:
7921         case TYPE_DECL:
7922           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7923             variadic_p = 1;
7924           break;
7925 
7926         case PARM_DECL:
7927           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7928             variadic_p = 1;
7929           break;
7930 
7931         default:
7932           gcc_unreachable ();
7933         }
7934     }
7935 
7936   if (nargs != nparms
7937       && !(variadic_p && nargs >= nparms - 1))
7938     return 0;
7939 
7940   /* Check all of the template parameters except the parameter pack at
7941      the end (if any).  */
7942   for (i = 0; i < nparms - variadic_p; ++i)
7943     {
7944       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
7945           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
7946         continue;
7947 
7948       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
7949       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
7950 
7951       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
7952                                           outer_args))
7953 	return 0;
7954 
7955     }
7956 
7957   if (variadic_p)
7958     {
7959       /* Check each of the template parameters in the template
7960 	 argument against the template parameter pack at the end of
7961 	 the template template parameter.  */
7962       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
7963 	return 0;
7964 
7965       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
7966 
7967       for (; i < nargs; ++i)
7968         {
7969           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
7970             continue;
7971 
7972           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
7973 
7974           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
7975                                               outer_args))
7976             return 0;
7977         }
7978     }
7979 
7980   return 1;
7981 }
7982 
7983 /* Verifies that the deduced template arguments (in TARGS) for the
7984    template template parameters (in TPARMS) represent valid bindings,
7985    by comparing the template parameter list of each template argument
7986    to the template parameter list of its corresponding template
7987    template parameter, in accordance with DR150. This
7988    routine can only be called after all template arguments have been
7989    deduced. It will return TRUE if all of the template template
7990    parameter bindings are okay, FALSE otherwise.  */
7991 bool
template_template_parm_bindings_ok_p(tree tparms,tree targs)7992 template_template_parm_bindings_ok_p (tree tparms, tree targs)
7993 {
7994   int i, ntparms = TREE_VEC_LENGTH (tparms);
7995   bool ret = true;
7996 
7997   /* We're dealing with template parms in this process.  */
7998   ++processing_template_decl;
7999 
8000   targs = INNERMOST_TEMPLATE_ARGS (targs);
8001 
8002   for (i = 0; i < ntparms; ++i)
8003     {
8004       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
8005       tree targ = TREE_VEC_ELT (targs, i);
8006 
8007       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
8008 	{
8009 	  tree packed_args = NULL_TREE;
8010 	  int idx, len = 1;
8011 
8012 	  if (ARGUMENT_PACK_P (targ))
8013 	    {
8014 	      /* Look inside the argument pack.  */
8015 	      packed_args = ARGUMENT_PACK_ARGS (targ);
8016 	      len = TREE_VEC_LENGTH (packed_args);
8017 	    }
8018 
8019 	  for (idx = 0; idx < len; ++idx)
8020 	    {
8021 	      tree targ_parms = NULL_TREE;
8022 
8023 	      if (packed_args)
8024 		/* Extract the next argument from the argument
8025 		   pack.  */
8026 		targ = TREE_VEC_ELT (packed_args, idx);
8027 
8028 	      if (PACK_EXPANSION_P (targ))
8029 		/* Look at the pattern of the pack expansion.  */
8030 		targ = PACK_EXPANSION_PATTERN (targ);
8031 
8032 	      /* Extract the template parameters from the template
8033 		 argument.  */
8034 	      if (TREE_CODE (targ) == TEMPLATE_DECL)
8035 		targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
8036 	      else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
8037 		targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
8038 
8039 	      /* Verify that we can coerce the template template
8040 		 parameters from the template argument to the template
8041 		 parameter.  This requires an exact match.  */
8042 	      if (targ_parms
8043 		  && !coerce_template_template_parms
8044 		       (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
8045 			targ_parms,
8046 			tf_none,
8047 			tparm,
8048 			targs))
8049 		{
8050 		  ret = false;
8051 		  goto out;
8052 		}
8053 	    }
8054 	}
8055     }
8056 
8057  out:
8058 
8059   --processing_template_decl;
8060   return ret;
8061 }
8062 
8063 /* Since type attributes aren't mangled, we need to strip them from
8064    template type arguments.  */
8065 
8066 tree
canonicalize_type_argument(tree arg,tsubst_flags_t complain)8067 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
8068 {
8069   if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
8070     return arg;
8071   bool removed_attributes = false;
8072   tree canon = strip_typedefs (arg, &removed_attributes);
8073   if (removed_attributes
8074       && (complain & tf_warning))
8075     warning (OPT_Wignored_attributes,
8076 	     "ignoring attributes on template argument %qT", arg);
8077   return canon;
8078 }
8079 
8080 /* And from inside dependent non-type arguments like sizeof(Type).  */
8081 
8082 static tree
canonicalize_expr_argument(tree arg,tsubst_flags_t complain)8083 canonicalize_expr_argument (tree arg, tsubst_flags_t complain)
8084 {
8085   if (!arg || arg == error_mark_node)
8086     return arg;
8087   bool removed_attributes = false;
8088   tree canon = strip_typedefs_expr (arg, &removed_attributes);
8089   if (removed_attributes
8090       && (complain & tf_warning))
8091     warning (OPT_Wignored_attributes,
8092 	     "ignoring attributes in template argument %qE", arg);
8093   return canon;
8094 }
8095 
8096 /* A template declaration can be substituted for a constrained
8097    template template parameter only when the argument is no more
8098    constrained than the parameter.  */
8099 
8100 static bool
is_compatible_template_arg(tree parm,tree arg)8101 is_compatible_template_arg (tree parm, tree arg)
8102 {
8103   tree parm_cons = get_constraints (parm);
8104 
8105   /* For now, allow constrained template template arguments
8106      and unconstrained template template parameters.  */
8107   if (parm_cons == NULL_TREE)
8108     return true;
8109 
8110   /* If the template parameter is constrained, we need to rewrite its
8111      constraints in terms of the ARG's template parameters. This ensures
8112      that all of the template parameter types will have the same depth.
8113 
8114      Note that this is only valid when coerce_template_template_parm is
8115      true for the innermost template parameters of PARM and ARG. In other
8116      words, because coercion is successful, this conversion will be valid.  */
8117   tree new_args = NULL_TREE;
8118   if (parm_cons)
8119     {
8120       tree aparms = DECL_INNERMOST_TEMPLATE_PARMS (arg);
8121       new_args = template_parms_level_to_args (aparms);
8122       parm_cons = tsubst_constraint_info (parm_cons, new_args,
8123 					  tf_none, NULL_TREE);
8124       if (parm_cons == error_mark_node)
8125         return false;
8126     }
8127 
8128   return weakly_subsumes (parm_cons, new_args, arg);
8129 }
8130 
8131 // Convert a placeholder argument into a binding to the original
8132 // parameter. The original parameter is saved as the TREE_TYPE of
8133 // ARG.
8134 static inline tree
convert_wildcard_argument(tree parm,tree arg)8135 convert_wildcard_argument (tree parm, tree arg)
8136 {
8137   TREE_TYPE (arg) = parm;
8138   return arg;
8139 }
8140 
8141 /* We can't fully resolve ARG given as a non-type template argument to TYPE,
8142    because one of them is dependent.  But we need to represent the
8143    conversion for the benefit of cp_tree_equal.  */
8144 
8145 static tree
maybe_convert_nontype_argument(tree type,tree arg)8146 maybe_convert_nontype_argument (tree type, tree arg)
8147 {
8148   /* Auto parms get no conversion.  */
8149   if (type_uses_auto (type))
8150     return arg;
8151   /* We don't need or want to add this conversion now if we're going to use the
8152      argument for deduction.  */
8153   if (value_dependent_expression_p (arg))
8154     return arg;
8155 
8156   type = cv_unqualified (type);
8157   tree argtype = TREE_TYPE (arg);
8158   if (same_type_p (type, argtype))
8159     return arg;
8160 
8161   arg = build1 (IMPLICIT_CONV_EXPR, type, arg);
8162   IMPLICIT_CONV_EXPR_NONTYPE_ARG (arg) = true;
8163   return arg;
8164 }
8165 
8166 /* Convert the indicated template ARG as necessary to match the
8167    indicated template PARM.  Returns the converted ARG, or
8168    error_mark_node if the conversion was unsuccessful.  Error and
8169    warning messages are issued under control of COMPLAIN.  This
8170    conversion is for the Ith parameter in the parameter list.  ARGS is
8171    the full set of template arguments deduced so far.  */
8172 
8173 static tree
convert_template_argument(tree parm,tree arg,tree args,tsubst_flags_t complain,int i,tree in_decl)8174 convert_template_argument (tree parm,
8175 			   tree arg,
8176 			   tree args,
8177 			   tsubst_flags_t complain,
8178 			   int i,
8179 			   tree in_decl)
8180 {
8181   tree orig_arg;
8182   tree val;
8183   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
8184 
8185   if (parm == error_mark_node || error_operand_p (arg))
8186     return error_mark_node;
8187 
8188   /* Trivially convert placeholders. */
8189   if (TREE_CODE (arg) == WILDCARD_DECL)
8190     return convert_wildcard_argument (parm, arg);
8191 
8192   if (arg == any_targ_node)
8193     return arg;
8194 
8195   if (TREE_CODE (arg) == TREE_LIST
8196       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
8197     {
8198       /* The template argument was the name of some
8199 	 member function.  That's usually
8200 	 invalid, but static members are OK.  In any
8201 	 case, grab the underlying fields/functions
8202 	 and issue an error later if required.  */
8203       TREE_TYPE (arg) = unknown_type_node;
8204     }
8205 
8206   orig_arg = arg;
8207 
8208   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
8209   requires_type = (TREE_CODE (parm) == TYPE_DECL
8210 		   || requires_tmpl_type);
8211 
8212   /* When determining whether an argument pack expansion is a template,
8213      look at the pattern.  */
8214   if (PACK_EXPANSION_P (arg))
8215     arg = PACK_EXPANSION_PATTERN (arg);
8216 
8217   /* Deal with an injected-class-name used as a template template arg.  */
8218   if (requires_tmpl_type && CLASS_TYPE_P (arg))
8219     {
8220       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
8221       if (TREE_CODE (t) == TEMPLATE_DECL)
8222 	{
8223 	  if (cxx_dialect >= cxx11)
8224 	    /* OK under DR 1004.  */;
8225 	  else if (complain & tf_warning_or_error)
8226 	    pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
8227 		     " used as template template argument", TYPE_NAME (arg));
8228 	  else if (flag_pedantic_errors)
8229 	    t = arg;
8230 
8231 	  arg = t;
8232 	}
8233     }
8234 
8235   is_tmpl_type =
8236     ((TREE_CODE (arg) == TEMPLATE_DECL
8237       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
8238      || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
8239      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8240      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
8241 
8242   if (is_tmpl_type
8243       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8244 	  || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
8245     arg = TYPE_STUB_DECL (arg);
8246 
8247   is_type = TYPE_P (arg) || is_tmpl_type;
8248 
8249   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
8250       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
8251     {
8252       if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
8253 	{
8254 	  if (complain & tf_error)
8255 	    error ("invalid use of destructor %qE as a type", orig_arg);
8256 	  return error_mark_node;
8257 	}
8258 
8259       permerror (input_location,
8260 		 "to refer to a type member of a template parameter, "
8261 		 "use %<typename %E%>", orig_arg);
8262 
8263       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
8264 				     TREE_OPERAND (arg, 1),
8265 				     typename_type,
8266 				     complain);
8267       arg = orig_arg;
8268       is_type = 1;
8269     }
8270   if (is_type != requires_type)
8271     {
8272       if (in_decl)
8273 	{
8274 	  if (complain & tf_error)
8275 	    {
8276 	      error ("type/value mismatch at argument %d in template "
8277 		     "parameter list for %qD",
8278 		     i + 1, in_decl);
8279 	      if (is_type)
8280 		{
8281 		  /* The template argument is a type, but we're expecting
8282 		     an expression.  */
8283 		  inform (input_location,
8284 			  "  expected a constant of type %qT, got %qT",
8285 			  TREE_TYPE (parm),
8286 			  (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
8287 		  /* [temp.arg]/2: "In a template-argument, an ambiguity
8288 		     between a type-id and an expression is resolved to a
8289 		     type-id, regardless of the form of the corresponding
8290 		     template-parameter."  So give the user a clue.  */
8291 		  if (TREE_CODE (arg) == FUNCTION_TYPE)
8292 		    inform (input_location, "  ambiguous template argument "
8293 			    "for non-type template parameter is treated as "
8294 			    "function type");
8295 		}
8296 	      else if (requires_tmpl_type)
8297 		inform (input_location,
8298 			"  expected a class template, got %qE", orig_arg);
8299 	      else
8300 		inform (input_location,
8301 			"  expected a type, got %qE", orig_arg);
8302 	    }
8303 	}
8304       return error_mark_node;
8305     }
8306   if (is_tmpl_type ^ requires_tmpl_type)
8307     {
8308       if (in_decl && (complain & tf_error))
8309 	{
8310 	  error ("type/value mismatch at argument %d in template "
8311 		 "parameter list for %qD",
8312 		 i + 1, in_decl);
8313 	  if (is_tmpl_type)
8314 	    inform (input_location,
8315 		    "  expected a type, got %qT", DECL_NAME (arg));
8316 	  else
8317 	    inform (input_location,
8318 		    "  expected a class template, got %qT", orig_arg);
8319 	}
8320       return error_mark_node;
8321     }
8322 
8323   if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
8324     /* We already did the appropriate conversion when packing args.  */
8325     val = orig_arg;
8326   else if (is_type)
8327     {
8328       if (requires_tmpl_type)
8329 	{
8330 	  if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
8331 	    /* The number of argument required is not known yet.
8332 	       Just accept it for now.  */
8333 	    val = orig_arg;
8334 	  else
8335 	    {
8336 	      tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
8337 	      tree argparm;
8338 
8339 	      /* Strip alias templates that are equivalent to another
8340 		 template.  */
8341 	      arg = get_underlying_template (arg);
8342               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
8343 
8344 	      if (coerce_template_template_parms (parmparm, argparm,
8345 						  complain, in_decl,
8346 						  args))
8347 		{
8348 		  val = arg;
8349 
8350 		  /* TEMPLATE_TEMPLATE_PARM node is preferred over
8351 		     TEMPLATE_DECL.  */
8352 		  if (val != error_mark_node)
8353                     {
8354                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
8355                         val = TREE_TYPE (val);
8356 		      if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
8357 			val = make_pack_expansion (val, complain);
8358                     }
8359 		}
8360 	      else
8361 		{
8362 		  if (in_decl && (complain & tf_error))
8363 		    {
8364 		      error ("type/value mismatch at argument %d in "
8365 			     "template parameter list for %qD",
8366 			     i + 1, in_decl);
8367 		      inform (input_location,
8368 			      "  expected a template of type %qD, got %qT",
8369 			      parm, orig_arg);
8370 		    }
8371 
8372 		  val = error_mark_node;
8373 		}
8374 
8375               // Check that the constraints are compatible before allowing the
8376               // substitution.
8377               if (val != error_mark_node)
8378                 if (!is_compatible_template_arg (parm, arg))
8379                   {
8380 		    if (in_decl && (complain & tf_error))
8381                       {
8382                         error ("constraint mismatch at argument %d in "
8383                                "template parameter list for %qD",
8384                                i + 1, in_decl);
8385                         inform (input_location, "  expected %qD but got %qD",
8386                                 parm, arg);
8387                       }
8388 		    val = error_mark_node;
8389                   }
8390 	    }
8391 	}
8392       else
8393 	val = orig_arg;
8394       /* We only form one instance of each template specialization.
8395 	 Therefore, if we use a non-canonical variant (i.e., a
8396 	 typedef), any future messages referring to the type will use
8397 	 the typedef, which is confusing if those future uses do not
8398 	 themselves also use the typedef.  */
8399       if (TYPE_P (val))
8400 	val = canonicalize_type_argument (val, complain);
8401     }
8402   else
8403     {
8404       tree t = TREE_TYPE (parm);
8405 
8406       if (TEMPLATE_PARM_LEVEL (get_template_parm_index (parm))
8407 	  > TMPL_ARGS_DEPTH (args))
8408 	/* We don't have enough levels of args to do any substitution.  This
8409 	   can happen in the context of -fnew-ttp-matching.  */;
8410       else if (tree a = type_uses_auto (t))
8411 	{
8412 	  t = do_auto_deduction (t, arg, a, complain, adc_unify, args);
8413 	  if (t == error_mark_node)
8414 	    return error_mark_node;
8415 	}
8416       else
8417 	t = tsubst (t, args, complain, in_decl);
8418 
8419       if (invalid_nontype_parm_type_p (t, complain))
8420 	return error_mark_node;
8421 
8422       if (t != TREE_TYPE (parm))
8423 	t = canonicalize_type_argument (t, complain);
8424 
8425       if (!type_dependent_expression_p (orig_arg)
8426 	  && !uses_template_parms (t))
8427 	/* We used to call digest_init here.  However, digest_init
8428 	   will report errors, which we don't want when complain
8429 	   is zero.  More importantly, digest_init will try too
8430 	   hard to convert things: for example, `0' should not be
8431 	   converted to pointer type at this point according to
8432 	   the standard.  Accepting this is not merely an
8433 	   extension, since deciding whether or not these
8434 	   conversions can occur is part of determining which
8435 	   function template to call, or whether a given explicit
8436 	   argument specification is valid.  */
8437 	val = convert_nontype_argument (t, orig_arg, complain);
8438       else
8439 	{
8440 	  val = canonicalize_expr_argument (orig_arg, complain);
8441 	  val = maybe_convert_nontype_argument (t, val);
8442 	}
8443 
8444 
8445       if (val == NULL_TREE)
8446 	val = error_mark_node;
8447       else if (val == error_mark_node && (complain & tf_error))
8448 	error_at (cp_expr_loc_or_input_loc (orig_arg),
8449 		  "could not convert template argument %qE from %qT to %qT",
8450 		  orig_arg, TREE_TYPE (orig_arg), t);
8451 
8452       if (INDIRECT_REF_P (val))
8453         {
8454           /* Reject template arguments that are references to built-in
8455              functions with no library fallbacks.  */
8456           const_tree inner = TREE_OPERAND (val, 0);
8457 	  const_tree innertype = TREE_TYPE (inner);
8458 	  if (innertype
8459 	      && TYPE_REF_P (innertype)
8460 	      && TREE_CODE (TREE_TYPE (innertype)) == FUNCTION_TYPE
8461 	      && TREE_OPERAND_LENGTH (inner) > 0
8462               && reject_gcc_builtin (TREE_OPERAND (inner, 0)))
8463               return error_mark_node;
8464         }
8465 
8466       if (TREE_CODE (val) == SCOPE_REF)
8467 	{
8468 	  /* Strip typedefs from the SCOPE_REF.  */
8469 	  tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
8470 	  tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
8471 						   complain);
8472 	  val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
8473 				      QUALIFIED_NAME_IS_TEMPLATE (val));
8474 	}
8475     }
8476 
8477   return val;
8478 }
8479 
8480 /* Coerces the remaining template arguments in INNER_ARGS (from
8481    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
8482    Returns the coerced argument pack. PARM_IDX is the position of this
8483    parameter in the template parameter list. ARGS is the original
8484    template argument list.  */
8485 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)8486 coerce_template_parameter_pack (tree parms,
8487                                 int parm_idx,
8488                                 tree args,
8489                                 tree inner_args,
8490                                 int arg_idx,
8491                                 tree new_args,
8492                                 int* lost,
8493                                 tree in_decl,
8494                                 tsubst_flags_t complain)
8495 {
8496   tree parm = TREE_VEC_ELT (parms, parm_idx);
8497   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8498   tree packed_args;
8499   tree argument_pack;
8500   tree packed_parms = NULL_TREE;
8501 
8502   if (arg_idx > nargs)
8503     arg_idx = nargs;
8504 
8505   if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
8506     {
8507       /* When the template parameter is a non-type template parameter pack
8508          or template template parameter pack whose type or template
8509          parameters use parameter packs, we know exactly how many arguments
8510          we are looking for.  Build a vector of the instantiated decls for
8511          these template parameters in PACKED_PARMS.  */
8512       /* We can't use make_pack_expansion here because it would interpret a
8513 	 _DECL as a use rather than a declaration.  */
8514       tree decl = TREE_VALUE (parm);
8515       tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
8516       SET_PACK_EXPANSION_PATTERN (exp, decl);
8517       PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
8518       SET_TYPE_STRUCTURAL_EQUALITY (exp);
8519 
8520       TREE_VEC_LENGTH (args)--;
8521       packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
8522       TREE_VEC_LENGTH (args)++;
8523 
8524       if (packed_parms == error_mark_node)
8525         return error_mark_node;
8526 
8527       /* If we're doing a partial instantiation of a member template,
8528          verify that all of the types used for the non-type
8529          template parameter pack are, in fact, valid for non-type
8530          template parameters.  */
8531       if (arg_idx < nargs
8532           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
8533         {
8534           int j, len = TREE_VEC_LENGTH (packed_parms);
8535           for (j = 0; j < len; ++j)
8536             {
8537               tree t = TREE_VEC_ELT (packed_parms, j);
8538               if (TREE_CODE (t) == PARM_DECL
8539 		  && invalid_nontype_parm_type_p (TREE_TYPE (t), complain))
8540                 return error_mark_node;
8541             }
8542 	  /* We don't know how many args we have yet, just
8543 	     use the unconverted ones for now.  */
8544 	  return NULL_TREE;
8545         }
8546 
8547       packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
8548     }
8549   /* Check if we have a placeholder pack, which indicates we're
8550      in the context of a introduction list.  In that case we want
8551      to match this pack to the single placeholder.  */
8552   else if (arg_idx < nargs
8553            && TREE_CODE (TREE_VEC_ELT (inner_args, arg_idx)) == WILDCARD_DECL
8554            && WILDCARD_PACK_P (TREE_VEC_ELT (inner_args, arg_idx)))
8555     {
8556       nargs = arg_idx + 1;
8557       packed_args = make_tree_vec (1);
8558     }
8559   else
8560     packed_args = make_tree_vec (nargs - arg_idx);
8561 
8562   /* Convert the remaining arguments, which will be a part of the
8563      parameter pack "parm".  */
8564   int first_pack_arg = arg_idx;
8565   for (; arg_idx < nargs; ++arg_idx)
8566     {
8567       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
8568       tree actual_parm = TREE_VALUE (parm);
8569       int pack_idx = arg_idx - first_pack_arg;
8570 
8571       if (packed_parms)
8572         {
8573 	  /* Once we've packed as many args as we have types, stop.  */
8574 	  if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
8575 	    break;
8576 	  else if (PACK_EXPANSION_P (arg))
8577 	    /* We don't know how many args we have yet, just
8578 	       use the unconverted ones for now.  */
8579 	    return NULL_TREE;
8580 	  else
8581 	    actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
8582         }
8583 
8584       if (arg == error_mark_node)
8585 	{
8586 	  if (complain & tf_error)
8587 	    error ("template argument %d is invalid", arg_idx + 1);
8588 	}
8589       else
8590 	arg = convert_template_argument (actual_parm,
8591 					 arg, new_args, complain, parm_idx,
8592 					 in_decl);
8593       if (arg == error_mark_node)
8594         (*lost)++;
8595       TREE_VEC_ELT (packed_args, pack_idx) = arg;
8596     }
8597 
8598   if (arg_idx - first_pack_arg < TREE_VEC_LENGTH (packed_args)
8599       && TREE_VEC_LENGTH (packed_args) > 0)
8600     {
8601       if (complain & tf_error)
8602 	error ("wrong number of template arguments (%d, should be %d)",
8603 	       arg_idx - first_pack_arg, TREE_VEC_LENGTH (packed_args));
8604       return error_mark_node;
8605     }
8606 
8607   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
8608       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
8609     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
8610   else
8611     {
8612       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
8613       TREE_CONSTANT (argument_pack) = 1;
8614     }
8615 
8616   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
8617   if (CHECKING_P)
8618     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
8619 					 TREE_VEC_LENGTH (packed_args));
8620   return argument_pack;
8621 }
8622 
8623 /* Returns the number of pack expansions in the template argument vector
8624    ARGS.  */
8625 
8626 static int
pack_expansion_args_count(tree args)8627 pack_expansion_args_count (tree args)
8628 {
8629   int i;
8630   int count = 0;
8631   if (args)
8632     for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
8633       {
8634 	tree elt = TREE_VEC_ELT (args, i);
8635 	if (elt && PACK_EXPANSION_P (elt))
8636 	  ++count;
8637       }
8638   return count;
8639 }
8640 
8641 /* Convert all template arguments to their appropriate types, and
8642    return a vector containing the innermost resulting template
8643    arguments.  If any error occurs, return error_mark_node. Error and
8644    warning messages are issued under control of COMPLAIN.
8645 
8646    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
8647    for arguments not specified in ARGS.  Otherwise, if
8648    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
8649    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
8650    USE_DEFAULT_ARGS is false, then all arguments must be specified in
8651    ARGS.  */
8652 
8653 static tree
coerce_template_parms(tree parms,tree args,tree in_decl,tsubst_flags_t complain,bool require_all_args,bool use_default_args)8654 coerce_template_parms (tree parms,
8655 		       tree args,
8656 		       tree in_decl,
8657 		       tsubst_flags_t complain,
8658 		       bool require_all_args,
8659 		       bool use_default_args)
8660 {
8661   int nparms, nargs, parm_idx, arg_idx, lost = 0;
8662   tree orig_inner_args;
8663   tree inner_args;
8664   tree new_args;
8665   tree new_inner_args;
8666 
8667   /* When used as a boolean value, indicates whether this is a
8668      variadic template parameter list. Since it's an int, we can also
8669      subtract it from nparms to get the number of non-variadic
8670      parameters.  */
8671   int variadic_p = 0;
8672   int variadic_args_p = 0;
8673   int post_variadic_parms = 0;
8674 
8675   /* Adjustment to nparms for fixed parameter packs.  */
8676   int fixed_pack_adjust = 0;
8677   int fixed_packs = 0;
8678   int missing = 0;
8679 
8680   /* Likewise for parameters with default arguments.  */
8681   int default_p = 0;
8682 
8683   if (args == error_mark_node)
8684     return error_mark_node;
8685 
8686   nparms = TREE_VEC_LENGTH (parms);
8687 
8688   /* Determine if there are any parameter packs or default arguments.  */
8689   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
8690     {
8691       tree parm = TREE_VEC_ELT (parms, parm_idx);
8692       if (variadic_p)
8693 	++post_variadic_parms;
8694       if (template_parameter_pack_p (TREE_VALUE (parm)))
8695 	++variadic_p;
8696       if (TREE_PURPOSE (parm))
8697 	++default_p;
8698     }
8699 
8700   inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
8701   /* If there are no parameters that follow a parameter pack, we need to
8702      expand any argument packs so that we can deduce a parameter pack from
8703      some non-packed args followed by an argument pack, as in variadic85.C.
8704      If there are such parameters, we need to leave argument packs intact
8705      so the arguments are assigned properly.  This can happen when dealing
8706      with a nested class inside a partial specialization of a class
8707      template, as in variadic92.C, or when deducing a template parameter pack
8708      from a sub-declarator, as in variadic114.C.  */
8709   if (!post_variadic_parms)
8710     inner_args = expand_template_argument_pack (inner_args);
8711 
8712   /* Count any pack expansion args.  */
8713   variadic_args_p = pack_expansion_args_count (inner_args);
8714 
8715   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8716   if ((nargs - variadic_args_p > nparms && !variadic_p)
8717       || (nargs < nparms - variadic_p
8718 	  && require_all_args
8719 	  && !variadic_args_p
8720 	  && (!use_default_args
8721 	      || (TREE_VEC_ELT (parms, nargs) != error_mark_node
8722                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
8723     {
8724     bad_nargs:
8725       if (complain & tf_error)
8726 	{
8727           if (variadic_p || default_p)
8728             {
8729               nparms -= variadic_p + default_p;
8730 	      error ("wrong number of template arguments "
8731 		     "(%d, should be at least %d)", nargs, nparms);
8732             }
8733 	  else
8734 	     error ("wrong number of template arguments "
8735 		    "(%d, should be %d)", nargs, nparms);
8736 
8737 	  if (in_decl)
8738 	    inform (DECL_SOURCE_LOCATION (in_decl),
8739 		    "provided for %qD", in_decl);
8740 	}
8741 
8742       return error_mark_node;
8743     }
8744   /* We can't pass a pack expansion to a non-pack parameter of an alias
8745      template (DR 1430).  */
8746   else if (in_decl
8747 	   && (DECL_ALIAS_TEMPLATE_P (in_decl)
8748 	       || concept_definition_p (in_decl))
8749 	   && variadic_args_p
8750 	   && nargs - variadic_args_p < nparms - variadic_p)
8751     {
8752       if (complain & tf_error)
8753 	{
8754 	  for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
8755 	    {
8756 	      tree arg = TREE_VEC_ELT (inner_args, i);
8757 	      tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
8758 
8759 	      if (PACK_EXPANSION_P (arg)
8760 		  && !template_parameter_pack_p (parm))
8761 		{
8762 		  if (DECL_ALIAS_TEMPLATE_P (in_decl))
8763 		    error_at (location_of (arg),
8764 			      "pack expansion argument for non-pack parameter "
8765 			      "%qD of alias template %qD", parm, in_decl);
8766 		  else
8767 		    error_at (location_of (arg),
8768 			      "pack expansion argument for non-pack parameter "
8769 			      "%qD of concept %qD", parm, in_decl);
8770 		  inform (DECL_SOURCE_LOCATION (parm), "declared here");
8771 		  goto found;
8772 		}
8773 	    }
8774 	  gcc_unreachable ();
8775 	found:;
8776 	}
8777       return error_mark_node;
8778     }
8779 
8780   /* We need to evaluate the template arguments, even though this
8781      template-id may be nested within a "sizeof".  */
8782   cp_evaluated ev;
8783 
8784   new_inner_args = make_tree_vec (nparms);
8785   new_args = add_outermost_template_args (args, new_inner_args);
8786   int pack_adjust = 0;
8787   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
8788     {
8789       tree arg;
8790       tree parm;
8791 
8792       /* Get the Ith template parameter.  */
8793       parm = TREE_VEC_ELT (parms, parm_idx);
8794 
8795       if (parm == error_mark_node)
8796 	{
8797 	  TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
8798 	  continue;
8799 	}
8800 
8801       /* Calculate the next argument.  */
8802       if (arg_idx < nargs)
8803 	arg = TREE_VEC_ELT (inner_args, arg_idx);
8804       else
8805 	arg = NULL_TREE;
8806 
8807       if (template_parameter_pack_p (TREE_VALUE (parm))
8808 	  && (arg || require_all_args || !(complain & tf_partial))
8809 	  && !(arg && ARGUMENT_PACK_P (arg)))
8810         {
8811 	  /* Some arguments will be placed in the
8812 	     template parameter pack PARM.  */
8813 	  arg = coerce_template_parameter_pack (parms, parm_idx, args,
8814 						inner_args, arg_idx,
8815 						new_args, &lost,
8816 						in_decl, complain);
8817 
8818 	  if (arg == NULL_TREE)
8819 	    {
8820 	      /* We don't know how many args we have yet, just use the
8821 		 unconverted (and still packed) ones for now.  */
8822 	      new_inner_args = orig_inner_args;
8823 	      arg_idx = nargs;
8824 	      break;
8825 	    }
8826 
8827           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
8828 
8829           /* Store this argument.  */
8830           if (arg == error_mark_node)
8831 	    {
8832 	      lost++;
8833 	      /* We are done with all of the arguments.  */
8834 	      arg_idx = nargs;
8835 	      break;
8836 	    }
8837 	  else
8838 	    {
8839 	      pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
8840 	      arg_idx += pack_adjust;
8841 	      if (fixed_parameter_pack_p (TREE_VALUE (parm)))
8842 		{
8843 		  ++fixed_packs;
8844 		  fixed_pack_adjust += pack_adjust;
8845 		}
8846 	    }
8847 
8848           continue;
8849         }
8850       else if (arg)
8851 	{
8852           if (PACK_EXPANSION_P (arg))
8853             {
8854 	      /* "If every valid specialization of a variadic template
8855 		 requires an empty template parameter pack, the template is
8856 		 ill-formed, no diagnostic required."  So check that the
8857 		 pattern works with this parameter.  */
8858 	      tree pattern = PACK_EXPANSION_PATTERN (arg);
8859 	      tree conv = convert_template_argument (TREE_VALUE (parm),
8860 						     pattern, new_args,
8861 						     complain, parm_idx,
8862 						     in_decl);
8863 	      if (conv == error_mark_node)
8864 		{
8865 		  if (complain & tf_error)
8866 		    inform (input_location, "so any instantiation with a "
8867 			    "non-empty parameter pack would be ill-formed");
8868 		  ++lost;
8869 		}
8870 	      else if (TYPE_P (conv) && !TYPE_P (pattern))
8871 		/* Recover from missing typename.  */
8872 		TREE_VEC_ELT (inner_args, arg_idx)
8873 		  = make_pack_expansion (conv, complain);
8874 
8875               /* We don't know how many args we have yet, just
8876                  use the unconverted ones for now.  */
8877               new_inner_args = inner_args;
8878 	      arg_idx = nargs;
8879               break;
8880             }
8881         }
8882       else if (require_all_args)
8883 	{
8884 	  /* There must be a default arg in this case.  */
8885 	  arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
8886 				     complain, in_decl);
8887 	  /* The position of the first default template argument,
8888 	     is also the number of non-defaulted arguments in NEW_INNER_ARGS.
8889 	     Record that.  */
8890 	  if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
8891 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
8892 						 arg_idx - pack_adjust);
8893 	}
8894       else
8895 	break;
8896 
8897       if (arg == error_mark_node)
8898 	{
8899 	  if (complain & tf_error)
8900 	    error ("template argument %d is invalid", arg_idx + 1);
8901 	}
8902       else if (!arg)
8903 	{
8904 	  /* This can occur if there was an error in the template
8905 	     parameter list itself (which we would already have
8906 	     reported) that we are trying to recover from, e.g., a class
8907 	     template with a parameter list such as
8908 	     template<typename..., typename> (cpp0x/variadic150.C).  */
8909 	  ++lost;
8910 
8911 	  /* This can also happen with a fixed parameter pack (71834).  */
8912 	  if (arg_idx >= nargs)
8913 	    ++missing;
8914 	}
8915       else
8916 	arg = convert_template_argument (TREE_VALUE (parm),
8917 					 arg, new_args, complain,
8918                                          parm_idx, in_decl);
8919 
8920       if (arg == error_mark_node)
8921 	lost++;
8922 
8923       TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
8924     }
8925 
8926   if (missing || arg_idx < nargs - variadic_args_p)
8927     {
8928       /* If we had fixed parameter packs, we didn't know how many arguments we
8929 	 actually needed earlier; now we do.  */
8930       nparms += fixed_pack_adjust;
8931       variadic_p -= fixed_packs;
8932       goto bad_nargs;
8933     }
8934 
8935   if (arg_idx < nargs)
8936     {
8937       /* We had some pack expansion arguments that will only work if the packs
8938 	 are empty, but wait until instantiation time to complain.
8939 	 See variadic-ttp3.C.  */
8940 
8941       /* Except that we can't provide empty packs to alias templates or
8942          concepts when there are no corresponding parameters. Basically,
8943          we can get here with this:
8944 
8945              template<typename T> concept C = true;
8946 
8947              template<typename... Args>
8948 	       requires C<Args...>
8949              void f();
8950 
8951          When parsing C<Args...>, we try to form a concept check of
8952          C<?, Args...>. Without the extra check for substituting an empty
8953          pack past the last parameter, we can accept the check as valid.
8954 
8955          FIXME: This may be valid for alias templates (but I doubt it).
8956 
8957          FIXME: The error could be better also.   */
8958       if (in_decl && concept_definition_p (in_decl))
8959 	{
8960 	  if (complain & tf_error)
8961 	    error_at (location_of (TREE_VEC_ELT (args, arg_idx)),
8962 		      "too many arguments");
8963 	  return error_mark_node;
8964 	}
8965 
8966       int len = nparms + (nargs - arg_idx);
8967       tree args = make_tree_vec (len);
8968       int i = 0;
8969       for (; i < nparms; ++i)
8970 	TREE_VEC_ELT (args, i) = TREE_VEC_ELT (new_inner_args, i);
8971       for (; i < len; ++i, ++arg_idx)
8972 	TREE_VEC_ELT (args, i) = TREE_VEC_ELT (inner_args,
8973 					       arg_idx - pack_adjust);
8974       new_inner_args = args;
8975     }
8976 
8977   if (lost)
8978     {
8979       gcc_assert (!(complain & tf_error) || seen_error ());
8980       return error_mark_node;
8981     }
8982 
8983   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
8984     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
8985 					 TREE_VEC_LENGTH (new_inner_args));
8986 
8987   return new_inner_args;
8988 }
8989 
8990 /* Convert all template arguments to their appropriate types, and
8991    return a vector containing the innermost resulting template
8992    arguments.  If any error occurs, return error_mark_node. Error and
8993    warning messages are not issued.
8994 
8995    Note that no function argument deduction is performed, and default
8996    arguments are used to fill in unspecified arguments. */
8997 tree
coerce_template_parms(tree parms,tree args,tree in_decl)8998 coerce_template_parms (tree parms, tree args, tree in_decl)
8999 {
9000   return coerce_template_parms (parms, args, in_decl, tf_none, true, true);
9001 }
9002 
9003 /* Convert all template arguments to their appropriate type, and
9004    instantiate default arguments as needed. This returns a vector
9005    containing the innermost resulting template arguments, or
9006    error_mark_node if unsuccessful.  */
9007 tree
coerce_template_parms(tree parms,tree args,tree in_decl,tsubst_flags_t complain)9008 coerce_template_parms (tree parms, tree args, tree in_decl,
9009                        tsubst_flags_t complain)
9010 {
9011   return coerce_template_parms (parms, args, in_decl, complain, true, true);
9012 }
9013 
9014 /* Like coerce_template_parms.  If PARMS represents all template
9015    parameters levels, this function returns a vector of vectors
9016    representing all the resulting argument levels.  Note that in this
9017    case, only the innermost arguments are coerced because the
9018    outermost ones are supposed to have been coerced already.
9019 
9020    Otherwise, if PARMS represents only (the innermost) vector of
9021    parameters, this function returns a vector containing just the
9022    innermost resulting arguments.  */
9023 
9024 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)9025 coerce_innermost_template_parms (tree parms,
9026 				  tree args,
9027 				  tree in_decl,
9028 				  tsubst_flags_t complain,
9029 				  bool require_all_args,
9030 				  bool use_default_args)
9031 {
9032   int parms_depth = TMPL_PARMS_DEPTH (parms);
9033   int args_depth = TMPL_ARGS_DEPTH (args);
9034   tree coerced_args;
9035 
9036   if (parms_depth > 1)
9037     {
9038       coerced_args = make_tree_vec (parms_depth);
9039       tree level;
9040       int cur_depth;
9041 
9042       for (level = parms, cur_depth = parms_depth;
9043 	   parms_depth > 0 && level != NULL_TREE;
9044 	   level = TREE_CHAIN (level), --cur_depth)
9045 	{
9046 	  tree l;
9047 	  if (cur_depth == args_depth)
9048 	    l = coerce_template_parms (TREE_VALUE (level),
9049 				       args, in_decl, complain,
9050 				       require_all_args,
9051 				       use_default_args);
9052 	  else
9053 	    l = TMPL_ARGS_LEVEL (args, cur_depth);
9054 
9055 	  if (l == error_mark_node)
9056 	    return error_mark_node;
9057 
9058 	  SET_TMPL_ARGS_LEVEL (coerced_args, cur_depth, l);
9059 	}
9060     }
9061   else
9062     coerced_args = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parms),
9063 					  args, in_decl, complain,
9064 					  require_all_args,
9065 					  use_default_args);
9066   return coerced_args;
9067 }
9068 
9069 /* Returns true if T is a wrapper to make a C++20 template parameter
9070    object const.  */
9071 
9072 static bool
class_nttp_const_wrapper_p(tree t)9073 class_nttp_const_wrapper_p (tree t)
9074 {
9075   if (cxx_dialect < cxx2a)
9076     return false;
9077   return (TREE_CODE (t) == VIEW_CONVERT_EXPR
9078 	  && CP_TYPE_CONST_P (TREE_TYPE (t))
9079 	  && TREE_CODE (TREE_OPERAND (t, 0)) == TEMPLATE_PARM_INDEX);
9080 }
9081 
9082 /* Returns 1 if template args OT and NT are equivalent.  */
9083 
9084 int
template_args_equal(tree ot,tree nt,bool partial_order)9085 template_args_equal (tree ot, tree nt, bool partial_order /* = false */)
9086 {
9087   if (nt == ot)
9088     return 1;
9089   if (nt == NULL_TREE || ot == NULL_TREE)
9090     return false;
9091   if (nt == any_targ_node || ot == any_targ_node)
9092     return true;
9093 
9094   if (class_nttp_const_wrapper_p (nt))
9095     nt = TREE_OPERAND (nt, 0);
9096   if (class_nttp_const_wrapper_p (ot))
9097     ot = TREE_OPERAND (ot, 0);
9098 
9099   if (TREE_CODE (nt) == TREE_VEC)
9100     /* For member templates */
9101     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
9102   else if (PACK_EXPANSION_P (ot))
9103     return (PACK_EXPANSION_P (nt)
9104 	    && template_args_equal (PACK_EXPANSION_PATTERN (ot),
9105 				    PACK_EXPANSION_PATTERN (nt))
9106 	    && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
9107 				    PACK_EXPANSION_EXTRA_ARGS (nt)));
9108   else if (ARGUMENT_PACK_P (ot) || ARGUMENT_PACK_P (nt))
9109     return cp_tree_equal (ot, nt);
9110   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
9111     gcc_unreachable ();
9112   else if (TYPE_P (nt))
9113     {
9114       if (!TYPE_P (ot))
9115 	return false;
9116       /* Don't treat an alias template specialization with dependent
9117 	 arguments as equivalent to its underlying type when used as a
9118 	 template argument; we need them to be distinct so that we
9119 	 substitute into the specialization arguments at instantiation
9120 	 time.  And aliases can't be equivalent without being ==, so
9121 	 we don't need to look any deeper.
9122 
9123          During partial ordering, however, we need to treat them normally so
9124          that we can order uses of the same alias with different
9125          cv-qualification (79960).  */
9126       if (!partial_order
9127 	  && (TYPE_ALIAS_P (nt) || TYPE_ALIAS_P (ot)))
9128 	return false;
9129       else
9130 	return same_type_p (ot, nt);
9131     }
9132   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
9133     return 0;
9134   else
9135     {
9136       /* Try to treat a template non-type argument that has been converted
9137 	 to the parameter type as equivalent to one that hasn't yet.  */
9138       for (enum tree_code code1 = TREE_CODE (ot);
9139 	   CONVERT_EXPR_CODE_P (code1)
9140 	     || code1 == NON_LVALUE_EXPR;
9141 	   code1 = TREE_CODE (ot))
9142 	ot = TREE_OPERAND (ot, 0);
9143       for (enum tree_code code2 = TREE_CODE (nt);
9144 	   CONVERT_EXPR_CODE_P (code2)
9145 	     || code2 == NON_LVALUE_EXPR;
9146 	   code2 = TREE_CODE (nt))
9147 	nt = TREE_OPERAND (nt, 0);
9148 
9149       return cp_tree_equal (ot, nt);
9150     }
9151 }
9152 
9153 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
9154    template arguments.  Returns 0 otherwise, and updates OLDARG_PTR and
9155    NEWARG_PTR with the offending arguments if they are non-NULL.  */
9156 
9157 int
comp_template_args(tree oldargs,tree newargs,tree * oldarg_ptr,tree * newarg_ptr,bool partial_order)9158 comp_template_args (tree oldargs, tree newargs,
9159 		    tree *oldarg_ptr, tree *newarg_ptr,
9160 		    bool partial_order)
9161 {
9162   int i;
9163 
9164   if (oldargs == newargs)
9165     return 1;
9166 
9167   if (!oldargs || !newargs)
9168     return 0;
9169 
9170   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
9171     return 0;
9172 
9173   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
9174     {
9175       tree nt = TREE_VEC_ELT (newargs, i);
9176       tree ot = TREE_VEC_ELT (oldargs, i);
9177 
9178       if (! template_args_equal (ot, nt, partial_order))
9179 	{
9180 	  if (oldarg_ptr != NULL)
9181 	    *oldarg_ptr = ot;
9182 	  if (newarg_ptr != NULL)
9183 	    *newarg_ptr = nt;
9184 	  return 0;
9185 	}
9186     }
9187   return 1;
9188 }
9189 
9190 inline bool
comp_template_args_porder(tree oargs,tree nargs)9191 comp_template_args_porder (tree oargs, tree nargs)
9192 {
9193   return comp_template_args (oargs, nargs, NULL, NULL, true);
9194 }
9195 
9196 /* Implement a freelist interface for objects of type T.
9197 
9198    Head is a separate object, rather than a regular member, so that we
9199    can define it as a GTY deletable pointer, which is highly
9200    desirable.  A data member could be declared that way, but then the
9201    containing object would implicitly get GTY((user)), which would
9202    prevent us from instantiating freelists as global objects.
9203    Although this way we can create freelist global objects, they're
9204    such thin wrappers that instantiating temporaries at every use
9205    loses nothing and saves permanent storage for the freelist object.
9206 
9207    Member functions next, anew, poison and reinit have default
9208    implementations that work for most of the types we're interested
9209    in, but if they don't work for some type, they should be explicitly
9210    specialized.  See the comments before them for requirements, and
9211    the example specializations for the tree_list_freelist.  */
9212 template <typename T>
9213 class freelist
9214 {
9215   /* Return the next object in a chain.  We could just do type
9216      punning, but if we access the object with its underlying type, we
9217      avoid strict-aliasing trouble.  This needs only work between
9218      poison and reinit.  */
next(T * obj)9219   static T *&next (T *obj) { return obj->next; }
9220 
9221   /* Return a newly allocated, uninitialized or minimally-initialized
9222      object of type T.  Any initialization performed by anew should
9223      either remain across the life of the object and the execution of
9224      poison, or be redone by reinit.  */
anew()9225   static T *anew () { return ggc_alloc<T> (); }
9226 
9227   /* Optionally scribble all over the bits holding the object, so that
9228      they become (mostly?) uninitialized memory.  This is called while
9229      preparing to make the object part of the free list.  */
poison(T * obj)9230   static void poison (T *obj) {
9231     T *p ATTRIBUTE_UNUSED = obj;
9232     T **q ATTRIBUTE_UNUSED = &next (obj);
9233 
9234 #ifdef ENABLE_GC_CHECKING
9235     /* Poison the data, to indicate the data is garbage.  */
9236     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, sizeof (*p)));
9237     memset (p, 0xa5, sizeof (*p));
9238 #endif
9239     /* Let valgrind know the object is free.  */
9240     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, sizeof (*p)));
9241 
9242     /* Let valgrind know the next portion of the object is available,
9243        but uninitialized.  */
9244     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9245   }
9246 
9247   /* Bring an object that underwent at least one lifecycle after anew
9248      and before the most recent free and poison, back to a usable
9249      state, reinitializing whatever is needed for it to be
9250      functionally equivalent to an object just allocated and returned
9251      by anew.  This may poison or clear the next field, used by
9252      freelist housekeeping after poison was called.  */
reinit(T * obj)9253   static void reinit (T *obj) {
9254     T **q ATTRIBUTE_UNUSED = &next (obj);
9255 
9256 #ifdef ENABLE_GC_CHECKING
9257     memset (q, 0xa5, sizeof (*q));
9258 #endif
9259     /* Let valgrind know the entire object is available, but
9260        uninitialized.  */
9261     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (*obj)));
9262   }
9263 
9264   /* Reference a GTY-deletable pointer that points to the first object
9265      in the free list proper.  */
9266   T *&head;
9267 public:
9268   /* Construct a freelist object chaining objects off of HEAD.  */
freelist(T * & head)9269   freelist (T *&head) : head(head) {}
9270 
9271   /* Add OBJ to the free object list.  The former head becomes OBJ's
9272      successor.  */
free(T * obj)9273   void free (T *obj)
9274   {
9275     poison (obj);
9276     next (obj) = head;
9277     head = obj;
9278   }
9279 
9280   /* Take an object from the free list, if one is available, or
9281      allocate a new one.  Objects taken from the free list should be
9282      regarded as filled with garbage, except for bits that are
9283      configured to be preserved across free and alloc.  */
alloc()9284   T *alloc ()
9285   {
9286     if (head)
9287       {
9288 	T *obj = head;
9289 	head = next (head);
9290 	reinit (obj);
9291 	return obj;
9292       }
9293     else
9294       return anew ();
9295   }
9296 };
9297 
9298 /* Explicitly specialize the interfaces for freelist<tree_node>: we
9299    want to allocate a TREE_LIST using the usual interface, and ensure
9300    TREE_CHAIN remains functional.  Alas, we have to duplicate a bit of
9301    build_tree_list logic in reinit, so this could go out of sync.  */
9302 template <>
9303 inline tree &
next(tree obj)9304 freelist<tree_node>::next (tree obj)
9305 {
9306   return TREE_CHAIN (obj);
9307 }
9308 template <>
9309 inline tree
anew()9310 freelist<tree_node>::anew ()
9311 {
9312   return build_tree_list (NULL, NULL);
9313 }
9314 template <>
9315 inline void
poison(tree obj ATTRIBUTE_UNUSED)9316 freelist<tree_node>::poison (tree obj ATTRIBUTE_UNUSED)
9317 {
9318   int size ATTRIBUTE_UNUSED = sizeof (tree_list);
9319   tree p ATTRIBUTE_UNUSED = obj;
9320   tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9321   tree *q ATTRIBUTE_UNUSED = &next (obj);
9322 
9323 #ifdef ENABLE_GC_CHECKING
9324   gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9325 
9326   /* Poison the data, to indicate the data is garbage.  */
9327   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, size));
9328   memset (p, 0xa5, size);
9329 #endif
9330   /* Let valgrind know the object is free.  */
9331   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, size));
9332   /* But we still want to use the TREE_CODE and TREE_CHAIN parts.  */
9333   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9334   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9335 
9336 #ifdef ENABLE_GC_CHECKING
9337   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (b, sizeof (*b)));
9338   /* Keep TREE_CHAIN functional.  */
9339   TREE_SET_CODE (obj, TREE_LIST);
9340 #else
9341   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9342 #endif
9343 }
9344 template <>
9345 inline void
reinit(tree obj ATTRIBUTE_UNUSED)9346 freelist<tree_node>::reinit (tree obj ATTRIBUTE_UNUSED)
9347 {
9348   tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9349 
9350 #ifdef ENABLE_GC_CHECKING
9351   gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9352   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9353   memset (obj, 0, sizeof (tree_list));
9354 #endif
9355 
9356   /* Let valgrind know the entire object is available, but
9357      uninitialized.  */
9358   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9359 
9360 #ifdef ENABLE_GC_CHECKING
9361   TREE_SET_CODE (obj, TREE_LIST);
9362 #else
9363   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9364 #endif
9365 }
9366 
9367 /* Point to the first object in the TREE_LIST freelist.  */
9368 static GTY((deletable)) tree tree_list_freelist_head;
9369 /* Return the/an actual TREE_LIST freelist.  */
9370 static inline freelist<tree_node>
tree_list_freelist()9371 tree_list_freelist ()
9372 {
9373   return tree_list_freelist_head;
9374 }
9375 
9376 /* Point to the first object in the tinst_level freelist.  */
9377 static GTY((deletable)) tinst_level *tinst_level_freelist_head;
9378 /* Return the/an actual tinst_level freelist.  */
9379 static inline freelist<tinst_level>
tinst_level_freelist()9380 tinst_level_freelist ()
9381 {
9382   return tinst_level_freelist_head;
9383 }
9384 
9385 /* Point to the first object in the pending_template freelist.  */
9386 static GTY((deletable)) pending_template *pending_template_freelist_head;
9387 /* Return the/an actual pending_template freelist.  */
9388 static inline freelist<pending_template>
pending_template_freelist()9389 pending_template_freelist ()
9390 {
9391   return pending_template_freelist_head;
9392 }
9393 
9394 /* Build the TREE_LIST object out of a split list, store it
9395    permanently, and return it.  */
9396 tree
to_list()9397 tinst_level::to_list ()
9398 {
9399   gcc_assert (split_list_p ());
9400   tree ret = tree_list_freelist ().alloc ();
9401   TREE_PURPOSE (ret) = tldcl;
9402   TREE_VALUE (ret) = targs;
9403   tldcl = ret;
9404   targs = NULL;
9405   gcc_assert (tree_list_p ());
9406   return ret;
9407 }
9408 
9409 const unsigned short tinst_level::refcount_infinity;
9410 
9411 /* Increment OBJ's refcount unless it is already infinite.  */
9412 static tinst_level *
inc_refcount_use(tinst_level * obj)9413 inc_refcount_use (tinst_level *obj)
9414 {
9415   if (obj && obj->refcount != tinst_level::refcount_infinity)
9416     ++obj->refcount;
9417   return obj;
9418 }
9419 
9420 /* Release storage for OBJ and node, if it's a TREE_LIST.  */
9421 void
free(tinst_level * obj)9422 tinst_level::free (tinst_level *obj)
9423 {
9424   if (obj->tree_list_p ())
9425     tree_list_freelist ().free (obj->get_node ());
9426   tinst_level_freelist ().free (obj);
9427 }
9428 
9429 /* Decrement OBJ's refcount if not infinite.  If it reaches zero, release
9430    OBJ's DECL and OBJ, and start over with the tinst_level object that
9431    used to be referenced by OBJ's NEXT.  */
9432 static void
dec_refcount_use(tinst_level * obj)9433 dec_refcount_use (tinst_level *obj)
9434 {
9435   while (obj
9436 	 && obj->refcount != tinst_level::refcount_infinity
9437 	 && !--obj->refcount)
9438     {
9439       tinst_level *next = obj->next;
9440       tinst_level::free (obj);
9441       obj = next;
9442     }
9443 }
9444 
9445 /* Modify PTR so that it points to OBJ, adjusting the refcounts of OBJ
9446    and of the former PTR.  Omitting the second argument is equivalent
9447    to passing (T*)NULL; this is allowed because passing the
9448    zero-valued integral constant NULL confuses type deduction and/or
9449    overload resolution.  */
9450 template <typename T>
9451 static void
9452 set_refcount_ptr (T *& ptr, T *obj = NULL)
9453 {
9454   T *save = ptr;
9455   ptr = inc_refcount_use (obj);
9456   dec_refcount_use (save);
9457 }
9458 
9459 static void
add_pending_template(tree d)9460 add_pending_template (tree d)
9461 {
9462   tree ti = (TYPE_P (d)
9463 	     ? CLASSTYPE_TEMPLATE_INFO (d)
9464 	     : DECL_TEMPLATE_INFO (d));
9465   struct pending_template *pt;
9466   int level;
9467 
9468   if (TI_PENDING_TEMPLATE_FLAG (ti))
9469     return;
9470 
9471   /* We are called both from instantiate_decl, where we've already had a
9472      tinst_level pushed, and instantiate_template, where we haven't.
9473      Compensate.  */
9474   gcc_assert (TREE_CODE (d) != TREE_LIST);
9475   level = !current_tinst_level
9476     || current_tinst_level->maybe_get_node () != d;
9477 
9478   if (level)
9479     push_tinst_level (d);
9480 
9481   pt = pending_template_freelist ().alloc ();
9482   pt->next = NULL;
9483   pt->tinst = NULL;
9484   set_refcount_ptr (pt->tinst, current_tinst_level);
9485   if (last_pending_template)
9486     last_pending_template->next = pt;
9487   else
9488     pending_templates = pt;
9489 
9490   last_pending_template = pt;
9491 
9492   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
9493 
9494   if (level)
9495     pop_tinst_level ();
9496 }
9497 
9498 
9499 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
9500    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
9501    documentation for TEMPLATE_ID_EXPR.  */
9502 
9503 tree
lookup_template_function(tree fns,tree arglist)9504 lookup_template_function (tree fns, tree arglist)
9505 {
9506   if (fns == error_mark_node || arglist == error_mark_node)
9507     return error_mark_node;
9508 
9509   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
9510 
9511   if (!is_overloaded_fn (fns) && !identifier_p (fns))
9512     {
9513       error ("%q#D is not a function template", fns);
9514       return error_mark_node;
9515     }
9516 
9517   if (BASELINK_P (fns))
9518     {
9519       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
9520 					 unknown_type_node,
9521 					 BASELINK_FUNCTIONS (fns),
9522 					 arglist);
9523       return fns;
9524     }
9525 
9526   return build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, arglist);
9527 }
9528 
9529 /* Within the scope of a template class S<T>, the name S gets bound
9530    (in build_self_reference) to a TYPE_DECL for the class, not a
9531    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
9532    or one of its enclosing classes, and that type is a template,
9533    return the associated TEMPLATE_DECL.  Otherwise, the original
9534    DECL is returned.
9535 
9536    Also handle the case when DECL is a TREE_LIST of ambiguous
9537    injected-class-names from different bases.  */
9538 
9539 tree
maybe_get_template_decl_from_type_decl(tree decl)9540 maybe_get_template_decl_from_type_decl (tree decl)
9541 {
9542   if (decl == NULL_TREE)
9543     return decl;
9544 
9545   /* DR 176: A lookup that finds an injected-class-name (10.2
9546      [class.member.lookup]) can result in an ambiguity in certain cases
9547      (for example, if it is found in more than one base class). If all of
9548      the injected-class-names that are found refer to specializations of
9549      the same class template, and if the name is followed by a
9550      template-argument-list, the reference refers to the class template
9551      itself and not a specialization thereof, and is not ambiguous.  */
9552   if (TREE_CODE (decl) == TREE_LIST)
9553     {
9554       tree t, tmpl = NULL_TREE;
9555       for (t = decl; t; t = TREE_CHAIN (t))
9556 	{
9557 	  tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
9558 	  if (!tmpl)
9559 	    tmpl = elt;
9560 	  else if (tmpl != elt)
9561 	    break;
9562 	}
9563       if (tmpl && t == NULL_TREE)
9564 	return tmpl;
9565       else
9566 	return decl;
9567     }
9568 
9569   return (decl != NULL_TREE
9570 	  && DECL_SELF_REFERENCE_P (decl)
9571 	  && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
9572     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
9573 }
9574 
9575 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
9576    parameters, find the desired type.
9577 
9578    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
9579 
9580    IN_DECL, if non-NULL, is the template declaration we are trying to
9581    instantiate.
9582 
9583    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
9584    the class we are looking up.
9585 
9586    Issue error and warning messages under control of COMPLAIN.
9587 
9588    If the template class is really a local class in a template
9589    function, then the FUNCTION_CONTEXT is the function in which it is
9590    being instantiated.
9591 
9592    ??? Note that this function is currently called *twice* for each
9593    template-id: the first time from the parser, while creating the
9594    incomplete type (finish_template_type), and the second type during the
9595    real instantiation (instantiate_template_class). This is surely something
9596    that we want to avoid. It also causes some problems with argument
9597    coercion (see convert_nontype_argument for more information on this).  */
9598 
9599 static tree
lookup_template_class_1(tree d1,tree arglist,tree in_decl,tree context,int entering_scope,tsubst_flags_t complain)9600 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
9601 			 int entering_scope, tsubst_flags_t complain)
9602 {
9603   tree templ = NULL_TREE, parmlist;
9604   tree t;
9605   spec_entry **slot;
9606   spec_entry *entry;
9607   spec_entry elt;
9608   hashval_t hash;
9609 
9610   if (identifier_p (d1))
9611     {
9612       tree value = innermost_non_namespace_value (d1);
9613       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
9614 	templ = value;
9615       else
9616 	{
9617 	  if (context)
9618 	    push_decl_namespace (context);
9619 	  templ = lookup_name (d1);
9620 	  templ = maybe_get_template_decl_from_type_decl (templ);
9621 	  if (context)
9622 	    pop_decl_namespace ();
9623 	}
9624       if (templ)
9625 	context = DECL_CONTEXT (templ);
9626     }
9627   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
9628     {
9629       tree type = TREE_TYPE (d1);
9630 
9631       /* If we are declaring a constructor, say A<T>::A<T>, we will get
9632 	 an implicit typename for the second A.  Deal with it.  */
9633       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
9634 	type = TREE_TYPE (type);
9635 
9636       if (CLASSTYPE_TEMPLATE_INFO (type))
9637 	{
9638 	  templ = CLASSTYPE_TI_TEMPLATE (type);
9639 	  d1 = DECL_NAME (templ);
9640 	}
9641     }
9642   else if (TREE_CODE (d1) == ENUMERAL_TYPE
9643 	   || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
9644     {
9645       templ = TYPE_TI_TEMPLATE (d1);
9646       d1 = DECL_NAME (templ);
9647     }
9648   else if (DECL_TYPE_TEMPLATE_P (d1))
9649     {
9650       templ = d1;
9651       d1 = DECL_NAME (templ);
9652       context = DECL_CONTEXT (templ);
9653     }
9654   else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
9655     {
9656       templ = d1;
9657       d1 = DECL_NAME (templ);
9658     }
9659 
9660   /* Issue an error message if we didn't find a template.  */
9661   if (! templ)
9662     {
9663       if (complain & tf_error)
9664 	error ("%qT is not a template", d1);
9665       return error_mark_node;
9666     }
9667 
9668   if (TREE_CODE (templ) != TEMPLATE_DECL
9669 	 /* Make sure it's a user visible template, if it was named by
9670 	    the user.  */
9671       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
9672 	  && !PRIMARY_TEMPLATE_P (templ)))
9673     {
9674       if (complain & tf_error)
9675 	{
9676 	  error ("non-template type %qT used as a template", d1);
9677 	  if (in_decl)
9678 	    error ("for template declaration %q+D", in_decl);
9679 	}
9680       return error_mark_node;
9681     }
9682 
9683   complain &= ~tf_user;
9684 
9685   /* An alias that just changes the name of a template is equivalent to the
9686      other template, so if any of the arguments are pack expansions, strip
9687      the alias to avoid problems with a pack expansion passed to a non-pack
9688      alias template parameter (DR 1430).  */
9689   if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
9690     templ = get_underlying_template (templ);
9691 
9692   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
9693     {
9694       tree parm;
9695       tree arglist2 = coerce_template_args_for_ttp (templ, arglist, complain);
9696       if (arglist2 == error_mark_node
9697 	  || (!uses_template_parms (arglist2)
9698 	      && check_instantiated_args (templ, arglist2, complain)))
9699 	return error_mark_node;
9700 
9701       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
9702       return parm;
9703     }
9704   else
9705     {
9706       tree template_type = TREE_TYPE (templ);
9707       tree gen_tmpl;
9708       tree type_decl;
9709       tree found = NULL_TREE;
9710       int arg_depth;
9711       int parm_depth;
9712       int is_dependent_type;
9713       int use_partial_inst_tmpl = false;
9714 
9715       if (template_type == error_mark_node)
9716 	/* An error occurred while building the template TEMPL, and a
9717 	   diagnostic has most certainly been emitted for that
9718 	   already.  Let's propagate that error.  */
9719 	return error_mark_node;
9720 
9721       gen_tmpl = most_general_template (templ);
9722       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
9723       parm_depth = TMPL_PARMS_DEPTH (parmlist);
9724       arg_depth = TMPL_ARGS_DEPTH (arglist);
9725 
9726       if (arg_depth == 1 && parm_depth > 1)
9727 	{
9728 	  /* We've been given an incomplete set of template arguments.
9729 	     For example, given:
9730 
9731 	       template <class T> struct S1 {
9732 		 template <class U> struct S2 {};
9733 		 template <class U> struct S2<U*> {};
9734 		};
9735 
9736 	     we will be called with an ARGLIST of `U*', but the
9737 	     TEMPLATE will be `template <class T> template
9738 	     <class U> struct S1<T>::S2'.  We must fill in the missing
9739 	     arguments.  */
9740 	  tree ti = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (templ));
9741 	  arglist = add_outermost_template_args (TI_ARGS (ti), arglist);
9742 	  arg_depth = TMPL_ARGS_DEPTH (arglist);
9743 	}
9744 
9745       /* Now we should have enough arguments.  */
9746       gcc_assert (parm_depth == arg_depth);
9747 
9748       /* From here on, we're only interested in the most general
9749 	 template.  */
9750 
9751       /* Calculate the BOUND_ARGS.  These will be the args that are
9752 	 actually tsubst'd into the definition to create the
9753 	 instantiation.  */
9754       arglist = coerce_innermost_template_parms (parmlist, arglist, gen_tmpl,
9755 						 complain,
9756 						 /*require_all_args=*/true,
9757 						 /*use_default_args=*/true);
9758 
9759       if (arglist == error_mark_node)
9760 	/* We were unable to bind the arguments.  */
9761 	return error_mark_node;
9762 
9763       /* In the scope of a template class, explicit references to the
9764 	 template class refer to the type of the template, not any
9765 	 instantiation of it.  For example, in:
9766 
9767 	   template <class T> class C { void f(C<T>); }
9768 
9769 	 the `C<T>' is just the same as `C'.  Outside of the
9770 	 class, however, such a reference is an instantiation.  */
9771       if (entering_scope
9772 	  || !PRIMARY_TEMPLATE_P (gen_tmpl)
9773 	  || currently_open_class (template_type))
9774 	{
9775 	  tree tinfo = TYPE_TEMPLATE_INFO (template_type);
9776 
9777 	  if (tinfo && comp_template_args (TI_ARGS (tinfo), arglist))
9778 	    return template_type;
9779 	}
9780 
9781       /* If we already have this specialization, return it.  */
9782       elt.tmpl = gen_tmpl;
9783       elt.args = arglist;
9784       elt.spec = NULL_TREE;
9785       hash = spec_hasher::hash (&elt);
9786       entry = type_specializations->find_with_hash (&elt, hash);
9787 
9788       if (entry)
9789 	return entry->spec;
9790 
9791       /* If the template's constraints are not satisfied,
9792          then we cannot form a valid type.
9793 
9794          Note that the check is deferred until after the hash
9795          lookup. This prevents redundant checks on previously
9796          instantiated specializations. */
9797       if (flag_concepts
9798 	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl)
9799 	  && !constraints_satisfied_p (gen_tmpl, arglist))
9800         {
9801           if (complain & tf_error)
9802             {
9803 	      auto_diagnostic_group d;
9804               error ("template constraint failure for %qD", gen_tmpl);
9805               diagnose_constraints (input_location, gen_tmpl, arglist);
9806             }
9807           return error_mark_node;
9808         }
9809 
9810       is_dependent_type = uses_template_parms (arglist);
9811 
9812       /* If the deduced arguments are invalid, then the binding
9813 	 failed.  */
9814       if (!is_dependent_type
9815 	  && check_instantiated_args (gen_tmpl,
9816 				      INNERMOST_TEMPLATE_ARGS (arglist),
9817 				      complain))
9818 	return error_mark_node;
9819 
9820       if (!is_dependent_type
9821 	  && !PRIMARY_TEMPLATE_P (gen_tmpl)
9822 	  && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
9823 	  && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
9824 	{
9825 	  found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
9826 				      DECL_NAME (gen_tmpl),
9827 				      /*tag_scope=*/ts_global);
9828 	  return found;
9829 	}
9830 
9831       context = DECL_CONTEXT (gen_tmpl);
9832       if (context && TYPE_P (context))
9833 	{
9834 	  context = tsubst_aggr_type (context, arglist, complain, in_decl, true);
9835 	  context = complete_type (context);
9836 	}
9837       else
9838 	context = tsubst (context, arglist, complain, in_decl);
9839 
9840       if (context == error_mark_node)
9841 	return error_mark_node;
9842 
9843       if (!context)
9844 	context = global_namespace;
9845 
9846       /* Create the type.  */
9847       if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9848 	{
9849 	  /* The user referred to a specialization of an alias
9850 	    template represented by GEN_TMPL.
9851 
9852 	    [temp.alias]/2 says:
9853 
9854 	        When a template-id refers to the specialization of an
9855 		alias template, it is equivalent to the associated
9856 		type obtained by substitution of its
9857 		template-arguments for the template-parameters in the
9858 		type-id of the alias template.  */
9859 
9860 	  t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
9861 	  /* Note that the call above (by indirectly calling
9862 	     register_specialization in tsubst_decl) registers the
9863 	     TYPE_DECL representing the specialization of the alias
9864 	     template.  So next time someone substitutes ARGLIST for
9865 	     the template parms into the alias template (GEN_TMPL),
9866 	     she'll get that TYPE_DECL back.  */
9867 
9868 	  if (t == error_mark_node)
9869 	    return t;
9870 	}
9871       else if (TREE_CODE (template_type) == ENUMERAL_TYPE)
9872 	{
9873 	  if (!is_dependent_type)
9874 	    {
9875 	      set_current_access_from_decl (TYPE_NAME (template_type));
9876 	      t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
9877 			      tsubst (ENUM_UNDERLYING_TYPE (template_type),
9878 				      arglist, complain, in_decl),
9879 			      tsubst_attributes (TYPE_ATTRIBUTES (template_type),
9880 						 arglist, complain, in_decl),
9881 			      SCOPED_ENUM_P (template_type), NULL);
9882 
9883 	      if (t == error_mark_node)
9884 		return t;
9885 	    }
9886 	  else
9887             {
9888               /* We don't want to call start_enum for this type, since
9889                  the values for the enumeration constants may involve
9890                  template parameters.  And, no one should be interested
9891                  in the enumeration constants for such a type.  */
9892               t = cxx_make_type (ENUMERAL_TYPE);
9893               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
9894             }
9895           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
9896 	  ENUM_FIXED_UNDERLYING_TYPE_P (t)
9897 	    = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
9898 	}
9899       else if (CLASS_TYPE_P (template_type))
9900 	{
9901 	  /* Lambda closures are regenerated in tsubst_lambda_expr, not
9902 	     instantiated here.  */
9903 	  gcc_assert (!LAMBDA_TYPE_P (template_type));
9904 
9905 	  t = make_class_type (TREE_CODE (template_type));
9906 	  CLASSTYPE_DECLARED_CLASS (t)
9907 	    = CLASSTYPE_DECLARED_CLASS (template_type);
9908 	  SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
9909 
9910 	  /* A local class.  Make sure the decl gets registered properly.  */
9911 	  if (context == current_function_decl)
9912 	    if (pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current)
9913 		== error_mark_node)
9914 	      return error_mark_node;
9915 
9916 	  if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
9917 	    /* This instantiation is another name for the primary
9918 	       template type. Set the TYPE_CANONICAL field
9919 	       appropriately. */
9920 	    TYPE_CANONICAL (t) = template_type;
9921 	  else if (any_template_arguments_need_structural_equality_p (arglist))
9922 	    /* Some of the template arguments require structural
9923 	       equality testing, so this template class requires
9924 	       structural equality testing. */
9925 	    SET_TYPE_STRUCTURAL_EQUALITY (t);
9926 	}
9927       else
9928 	gcc_unreachable ();
9929 
9930       /* If we called start_enum or pushtag above, this information
9931 	 will already be set up.  */
9932       if (!TYPE_NAME (t))
9933 	{
9934 	  TYPE_CONTEXT (t) = FROB_CONTEXT (context);
9935 
9936 	  type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
9937 	  DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
9938 	  DECL_SOURCE_LOCATION (type_decl)
9939 	    = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
9940 	}
9941       else
9942 	type_decl = TYPE_NAME (t);
9943 
9944       if (CLASS_TYPE_P (template_type))
9945 	{
9946 	  TREE_PRIVATE (type_decl)
9947 	    = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
9948 	  TREE_PROTECTED (type_decl)
9949 	    = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
9950 	  if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
9951 	    {
9952 	      DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
9953 	      DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
9954 	    }
9955 	}
9956 
9957       if (OVERLOAD_TYPE_P (t)
9958 	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9959 	{
9960 	  static const char *tags[] = {"abi_tag", "may_alias"};
9961 
9962 	  for (unsigned ix = 0; ix != 2; ix++)
9963 	    {
9964 	      tree attributes
9965 		= lookup_attribute (tags[ix], TYPE_ATTRIBUTES (template_type));
9966 
9967 	      if (attributes)
9968 		TYPE_ATTRIBUTES (t)
9969 		  = tree_cons (TREE_PURPOSE (attributes),
9970 			       TREE_VALUE (attributes),
9971 			       TYPE_ATTRIBUTES (t));
9972 	    }
9973 	}
9974 
9975       /* Let's consider the explicit specialization of a member
9976          of a class template specialization that is implicitly instantiated,
9977 	 e.g.:
9978 	     template<class T>
9979 	     struct S
9980 	     {
9981 	       template<class U> struct M {}; //#0
9982 	     };
9983 
9984 	     template<>
9985 	     template<>
9986 	     struct S<int>::M<char> //#1
9987 	     {
9988 	       int i;
9989 	     };
9990 	[temp.expl.spec]/4 says this is valid.
9991 
9992 	In this case, when we write:
9993 	S<int>::M<char> m;
9994 
9995 	M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
9996 	the one of #0.
9997 
9998 	When we encounter #1, we want to store the partial instantiation
9999 	of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
10000 
10001 	For all cases other than this "explicit specialization of member of a
10002 	class template", we just want to store the most general template into
10003 	the CLASSTYPE_TI_TEMPLATE of M.
10004 
10005 	This case of "explicit specialization of member of a class template"
10006 	only happens when:
10007 	1/ the enclosing class is an instantiation of, and therefore not
10008 	the same as, the context of the most general template, and
10009 	2/ we aren't looking at the partial instantiation itself, i.e.
10010 	the innermost arguments are not the same as the innermost parms of
10011 	the most general template.
10012 
10013 	So it's only when 1/ and 2/ happens that we want to use the partial
10014 	instantiation of the member template in lieu of its most general
10015 	template.  */
10016 
10017       if (PRIMARY_TEMPLATE_P (gen_tmpl)
10018 	  && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
10019 	  /* the enclosing class must be an instantiation...  */
10020 	  && CLASS_TYPE_P (context)
10021 	  && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
10022 	{
10023 	  TREE_VEC_LENGTH (arglist)--;
10024 	  ++processing_template_decl;
10025 	  tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (gen_tmpl));
10026 	  tree partial_inst_args =
10027 	    tsubst (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)),
10028 		    arglist, complain, NULL_TREE);
10029 	  --processing_template_decl;
10030 	  TREE_VEC_LENGTH (arglist)++;
10031 	  if (partial_inst_args == error_mark_node)
10032 	    return error_mark_node;
10033 	  use_partial_inst_tmpl =
10034 	    /*...and we must not be looking at the partial instantiation
10035 	     itself. */
10036 	    !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
10037 				 partial_inst_args);
10038 	}
10039 
10040       if (!use_partial_inst_tmpl)
10041 	/* This case is easy; there are no member templates involved.  */
10042 	found = gen_tmpl;
10043       else
10044 	{
10045 	  /* This is a full instantiation of a member template.  Find
10046 	     the partial instantiation of which this is an instance.  */
10047 
10048 	  /* Temporarily reduce by one the number of levels in the ARGLIST
10049 	     so as to avoid comparing the last set of arguments.  */
10050 	  TREE_VEC_LENGTH (arglist)--;
10051 	  /* We don't use COMPLAIN in the following call because this isn't
10052 	     the immediate context of deduction.  For instance, tf_partial
10053 	     could be set here as we might be at the beginning of template
10054 	     argument deduction when any explicitly specified template
10055 	     arguments are substituted into the function type.  tf_partial
10056 	     could lead into trouble because we wouldn't find the partial
10057 	     instantiation that might have been created outside tf_partial
10058 	     context, because the levels of template parameters wouldn't
10059 	     match, because in a tf_partial context, tsubst doesn't reduce
10060 	     TEMPLATE_PARM_LEVEL.  */
10061 	  found = tsubst (gen_tmpl, arglist, tf_none, NULL_TREE);
10062 	  TREE_VEC_LENGTH (arglist)++;
10063 	  /* FOUND is either a proper class type, or an alias
10064 	     template specialization.  In the later case, it's a
10065 	     TYPE_DECL, resulting from the substituting of arguments
10066 	     for parameters in the TYPE_DECL of the alias template
10067 	     done earlier.  So be careful while getting the template
10068 	     of FOUND.  */
10069 	  found = (TREE_CODE (found) == TEMPLATE_DECL
10070 		   ? found
10071 		   : (TREE_CODE (found) == TYPE_DECL
10072 		      ? DECL_TI_TEMPLATE (found)
10073 		      : CLASSTYPE_TI_TEMPLATE (found)));
10074 
10075 	  if (DECL_CLASS_TEMPLATE_P (found)
10076 	      && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (found)))
10077 	    {
10078 	      /* If this partial instantiation is specialized, we want to
10079 		 use it for hash table lookup.  */
10080 	      elt.tmpl = found;
10081 	      elt.args = arglist = INNERMOST_TEMPLATE_ARGS (arglist);
10082 	      hash = spec_hasher::hash (&elt);
10083 	    }
10084 	}
10085 
10086       // Build template info for the new specialization.
10087       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
10088 
10089       elt.spec = t;
10090       slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
10091       gcc_checking_assert (*slot == NULL);
10092       entry = ggc_alloc<spec_entry> ();
10093       *entry = elt;
10094       *slot = entry;
10095 
10096       /* Note this use of the partial instantiation so we can check it
10097 	 later in maybe_process_partial_specialization.  */
10098       DECL_TEMPLATE_INSTANTIATIONS (found)
10099 	= tree_cons (arglist, t,
10100 		     DECL_TEMPLATE_INSTANTIATIONS (found));
10101 
10102       if (TREE_CODE (template_type) == ENUMERAL_TYPE && !is_dependent_type
10103 	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10104 	/* Now that the type has been registered on the instantiations
10105 	   list, we set up the enumerators.  Because the enumeration
10106 	   constants may involve the enumeration type itself, we make
10107 	   sure to register the type first, and then create the
10108 	   constants.  That way, doing tsubst_expr for the enumeration
10109 	   constants won't result in recursive calls here; we'll find
10110 	   the instantiation and exit above.  */
10111 	tsubst_enum (template_type, t, arglist);
10112 
10113       if (CLASS_TYPE_P (template_type) && is_dependent_type)
10114 	/* If the type makes use of template parameters, the
10115 	   code that generates debugging information will crash.  */
10116 	DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
10117 
10118       /* Possibly limit visibility based on template args.  */
10119       TREE_PUBLIC (type_decl) = 1;
10120       determine_visibility (type_decl);
10121 
10122       inherit_targ_abi_tags (t);
10123 
10124       return t;
10125     }
10126 }
10127 
10128 /* Wrapper for lookup_template_class_1.  */
10129 
10130 tree
lookup_template_class(tree d1,tree arglist,tree in_decl,tree context,int entering_scope,tsubst_flags_t complain)10131 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
10132                        int entering_scope, tsubst_flags_t complain)
10133 {
10134   tree ret;
10135   timevar_push (TV_TEMPLATE_INST);
10136   ret = lookup_template_class_1 (d1, arglist, in_decl, context,
10137                                  entering_scope, complain);
10138   timevar_pop (TV_TEMPLATE_INST);
10139   return ret;
10140 }
10141 
10142 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST.  */
10143 
10144 tree
lookup_template_variable(tree templ,tree arglist)10145 lookup_template_variable (tree templ, tree arglist)
10146 {
10147   if (flag_concepts && variable_concept_p (templ))
10148     return build_concept_check (templ, arglist, tf_none);
10149 
10150   /* The type of the expression is NULL_TREE since the template-id could refer
10151      to an explicit or partial specialization. */
10152   return build2 (TEMPLATE_ID_EXPR, NULL_TREE, templ, arglist);
10153 }
10154 
10155 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR for use. */
10156 
10157 tree
finish_template_variable(tree var,tsubst_flags_t complain)10158 finish_template_variable (tree var, tsubst_flags_t complain)
10159 {
10160   tree templ = TREE_OPERAND (var, 0);
10161   tree arglist = TREE_OPERAND (var, 1);
10162 
10163   tree tmpl_args = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (templ));
10164   arglist = add_outermost_template_args (tmpl_args, arglist);
10165 
10166   templ = most_general_template (templ);
10167   tree parms = DECL_TEMPLATE_PARMS (templ);
10168   arglist = coerce_innermost_template_parms (parms, arglist, templ, complain,
10169 					     /*req_all*/true,
10170 					     /*use_default*/true);
10171 
10172   if (flag_concepts && !constraints_satisfied_p (templ, arglist))
10173     {
10174       if (complain & tf_error)
10175 	{
10176 	  auto_diagnostic_group d;
10177 	  error ("use of invalid variable template %qE", var);
10178 	  diagnose_constraints (location_of (var), templ, arglist);
10179 	}
10180       return error_mark_node;
10181     }
10182 
10183   return instantiate_template (templ, arglist, complain);
10184 }
10185 
10186 /* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
10187    TARGS template args, and instantiate it if it's not dependent.  */
10188 
10189 tree
lookup_and_finish_template_variable(tree templ,tree targs,tsubst_flags_t complain)10190 lookup_and_finish_template_variable (tree templ, tree targs,
10191 				     tsubst_flags_t complain)
10192 {
10193   templ = lookup_template_variable (templ, targs);
10194   if (!any_dependent_template_arguments_p (targs))
10195     {
10196       templ = finish_template_variable (templ, complain);
10197       mark_used (templ);
10198     }
10199 
10200   return convert_from_reference (templ);
10201 }
10202 
10203 
10204 struct pair_fn_data
10205 {
10206   tree_fn_t fn;
10207   tree_fn_t any_fn;
10208   void *data;
10209   /* True when we should also visit template parameters that occur in
10210      non-deduced contexts.  */
10211   bool include_nondeduced_p;
10212   hash_set<tree> *visited;
10213 };
10214 
10215 /* Called from for_each_template_parm via walk_tree.  */
10216 
10217 static tree
for_each_template_parm_r(tree * tp,int * walk_subtrees,void * d)10218 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
10219 {
10220   tree t = *tp;
10221   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
10222   tree_fn_t fn = pfd->fn;
10223   void *data = pfd->data;
10224   tree result = NULL_TREE;
10225 
10226 #define WALK_SUBTREE(NODE)						\
10227   do									\
10228     {									\
10229       result = for_each_template_parm (NODE, fn, data, pfd->visited,	\
10230 				       pfd->include_nondeduced_p,	\
10231 				       pfd->any_fn);			\
10232       if (result) goto out;						\
10233     }									\
10234   while (0)
10235 
10236   if (pfd->any_fn && (*pfd->any_fn)(t, data))
10237     return t;
10238 
10239   if (TYPE_P (t)
10240       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
10241     WALK_SUBTREE (TYPE_CONTEXT (t));
10242 
10243   switch (TREE_CODE (t))
10244     {
10245     case RECORD_TYPE:
10246       if (TYPE_PTRMEMFUNC_P (t))
10247 	break;
10248       /* Fall through.  */
10249 
10250     case UNION_TYPE:
10251     case ENUMERAL_TYPE:
10252       if (!TYPE_TEMPLATE_INFO (t))
10253 	*walk_subtrees = 0;
10254       else
10255 	WALK_SUBTREE (TYPE_TI_ARGS (t));
10256       break;
10257 
10258     case INTEGER_TYPE:
10259       WALK_SUBTREE (TYPE_MIN_VALUE (t));
10260       WALK_SUBTREE (TYPE_MAX_VALUE (t));
10261       break;
10262 
10263     case METHOD_TYPE:
10264       /* Since we're not going to walk subtrees, we have to do this
10265 	 explicitly here.  */
10266       WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
10267       /* Fall through.  */
10268 
10269     case FUNCTION_TYPE:
10270       /* Check the return type.  */
10271       WALK_SUBTREE (TREE_TYPE (t));
10272 
10273       /* Check the parameter types.  Since default arguments are not
10274 	 instantiated until they are needed, the TYPE_ARG_TYPES may
10275 	 contain expressions that involve template parameters.  But,
10276 	 no-one should be looking at them yet.  And, once they're
10277 	 instantiated, they don't contain template parameters, so
10278 	 there's no point in looking at them then, either.  */
10279       {
10280 	tree parm;
10281 
10282 	for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
10283 	  WALK_SUBTREE (TREE_VALUE (parm));
10284 
10285 	/* Since we've already handled the TYPE_ARG_TYPES, we don't
10286 	   want walk_tree walking into them itself.  */
10287 	*walk_subtrees = 0;
10288       }
10289 
10290       if (flag_noexcept_type)
10291 	{
10292 	  tree spec = TYPE_RAISES_EXCEPTIONS (t);
10293 	  if (spec)
10294 	    WALK_SUBTREE (TREE_PURPOSE (spec));
10295 	}
10296       break;
10297 
10298     case TYPEOF_TYPE:
10299     case DECLTYPE_TYPE:
10300     case UNDERLYING_TYPE:
10301       if (pfd->include_nondeduced_p
10302 	  && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
10303 				     pfd->visited,
10304 				     pfd->include_nondeduced_p,
10305 				     pfd->any_fn))
10306 	return error_mark_node;
10307       *walk_subtrees = false;
10308       break;
10309 
10310     case FUNCTION_DECL:
10311     case VAR_DECL:
10312       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10313 	WALK_SUBTREE (DECL_TI_ARGS (t));
10314       /* Fall through.  */
10315 
10316     case PARM_DECL:
10317     case CONST_DECL:
10318       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t))
10319 	WALK_SUBTREE (DECL_INITIAL (t));
10320       if (DECL_CONTEXT (t)
10321 	  && pfd->include_nondeduced_p)
10322 	WALK_SUBTREE (DECL_CONTEXT (t));
10323       break;
10324 
10325     case BOUND_TEMPLATE_TEMPLATE_PARM:
10326       /* Record template parameters such as `T' inside `TT<T>'.  */
10327       WALK_SUBTREE (TYPE_TI_ARGS (t));
10328       /* Fall through.  */
10329 
10330     case TEMPLATE_TEMPLATE_PARM:
10331     case TEMPLATE_TYPE_PARM:
10332     case TEMPLATE_PARM_INDEX:
10333       if (fn && (*fn)(t, data))
10334 	return t;
10335       else if (!fn)
10336 	return t;
10337       break;
10338 
10339     case TEMPLATE_DECL:
10340       /* A template template parameter is encountered.  */
10341       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10342 	WALK_SUBTREE (TREE_TYPE (t));
10343 
10344       /* Already substituted template template parameter */
10345       *walk_subtrees = 0;
10346       break;
10347 
10348     case TYPENAME_TYPE:
10349       /* A template-id in a TYPENAME_TYPE might be a deduced context after
10350 	 partial instantiation.  */
10351       WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
10352       break;
10353 
10354     case CONSTRUCTOR:
10355       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
10356 	  && pfd->include_nondeduced_p)
10357 	WALK_SUBTREE (TYPE_PTRMEMFUNC_FN_TYPE (TREE_TYPE (t)));
10358       break;
10359 
10360     case INDIRECT_REF:
10361     case COMPONENT_REF:
10362       /* If there's no type, then this thing must be some expression
10363 	 involving template parameters.  */
10364       if (!fn && !TREE_TYPE (t))
10365 	return error_mark_node;
10366       break;
10367 
10368     case MODOP_EXPR:
10369     case CAST_EXPR:
10370     case IMPLICIT_CONV_EXPR:
10371     case REINTERPRET_CAST_EXPR:
10372     case CONST_CAST_EXPR:
10373     case STATIC_CAST_EXPR:
10374     case DYNAMIC_CAST_EXPR:
10375     case ARROW_EXPR:
10376     case DOTSTAR_EXPR:
10377     case TYPEID_EXPR:
10378     case PSEUDO_DTOR_EXPR:
10379       if (!fn)
10380 	return error_mark_node;
10381       break;
10382 
10383     case SCOPE_REF:
10384       if (pfd->include_nondeduced_p)
10385 	WALK_SUBTREE (TREE_OPERAND (t, 0));
10386       break;
10387 
10388     case REQUIRES_EXPR:
10389       {
10390 	if (!fn)
10391 	  return error_mark_node;
10392 
10393 	/* Recursively walk the type of each constraint variable.  */
10394 	tree p = TREE_OPERAND (t, 0);
10395 	while (p)
10396 	  {
10397 	    WALK_SUBTREE (TREE_TYPE (p));
10398 	    p = TREE_CHAIN (p);
10399 	  }
10400       }
10401       break;
10402 
10403     default:
10404       break;
10405     }
10406 
10407   #undef WALK_SUBTREE
10408 
10409   /* We didn't find any template parameters we liked.  */
10410  out:
10411   return result;
10412 }
10413 
10414 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
10415    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
10416    call FN with the parameter and the DATA.
10417    If FN returns nonzero, the iteration is terminated, and
10418    for_each_template_parm returns 1.  Otherwise, the iteration
10419    continues.  If FN never returns a nonzero value, the value
10420    returned by for_each_template_parm is 0.  If FN is NULL, it is
10421    considered to be the function which always returns 1.
10422 
10423    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
10424    parameters that occur in non-deduced contexts.  When false, only
10425    visits those template parameters that can be deduced.  */
10426 
10427 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)10428 for_each_template_parm (tree t, tree_fn_t fn, void* data,
10429 			hash_set<tree> *visited,
10430 			bool include_nondeduced_p,
10431 			tree_fn_t any_fn)
10432 {
10433   struct pair_fn_data pfd;
10434   tree result;
10435 
10436   /* Set up.  */
10437   pfd.fn = fn;
10438   pfd.any_fn = any_fn;
10439   pfd.data = data;
10440   pfd.include_nondeduced_p = include_nondeduced_p;
10441 
10442   /* Walk the tree.  (Conceptually, we would like to walk without
10443      duplicates, but for_each_template_parm_r recursively calls
10444      for_each_template_parm, so we would need to reorganize a fair
10445      bit to use walk_tree_without_duplicates, so we keep our own
10446      visited list.)  */
10447   if (visited)
10448     pfd.visited = visited;
10449   else
10450     pfd.visited = new hash_set<tree>;
10451   result = cp_walk_tree (&t,
10452 		         for_each_template_parm_r,
10453 		         &pfd,
10454 		         pfd.visited);
10455 
10456   /* Clean up.  */
10457   if (!visited)
10458     {
10459       delete pfd.visited;
10460       pfd.visited = 0;
10461     }
10462 
10463   return result;
10464 }
10465 
10466 struct find_template_parameter_info
10467 {
find_template_parameter_infofind_template_parameter_info10468   explicit find_template_parameter_info (tree ctx_parms)
10469     : parm_list (NULL_TREE),
10470       ctx_parms (ctx_parms),
10471       max_depth (TMPL_PARMS_DEPTH (ctx_parms))
10472   {}
10473 
10474   hash_set<tree> visited;
10475   hash_set<tree> parms;
10476   tree parm_list;
10477   tree ctx_parms;
10478   int max_depth;
10479 };
10480 
10481 /* Appends the declaration of T to the list in DATA.  */
10482 
10483 static int
keep_template_parm(tree t,void * data)10484 keep_template_parm (tree t, void* data)
10485 {
10486   find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10487 
10488   /* Template parameters declared within the expression are not part of
10489      the parameter mapping. For example, in this concept:
10490 
10491        template<typename T>
10492        concept C = requires { <expr> } -> same_as<int>;
10493 
10494      the return specifier same_as<int> declares a new decltype parameter
10495      that must not be part of the parameter mapping. The same is true
10496      for generic lambda parameters, lambda template parameters, etc.  */
10497   int level;
10498   int index;
10499   template_parm_level_and_index (t, &level, &index);
10500   if (level > ftpi->max_depth)
10501     return 0;
10502 
10503   if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10504     /* We want the underlying TEMPLATE_TEMPLATE_PARM, not the
10505        BOUND_TEMPLATE_TEMPLATE_PARM itself.  */
10506     t = TREE_TYPE (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (t));
10507 
10508   /* Arguments like const T yield parameters like const T. This means that
10509      a template-id like X<T, const T> would yield two distinct parameters:
10510      T and const T. Adjust types to their unqualified versions.  */
10511   if (TYPE_P (t))
10512     t = TYPE_MAIN_VARIANT (t);
10513   if (!ftpi->parms.add (t))
10514     ftpi->parm_list = tree_cons (NULL_TREE, t, ftpi->parm_list);
10515 
10516   return 0;
10517 }
10518 
10519 /* Ensure that we recursively examine certain terms that are not normally
10520    visited in for_each_template_parm_r.  */
10521 
10522 static int
any_template_parm_r(tree t,void * data)10523 any_template_parm_r (tree t, void *data)
10524 {
10525   find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10526 
10527 #define WALK_SUBTREE(NODE)						\
10528   do									\
10529     {									\
10530       for_each_template_parm (NODE, keep_template_parm, data,		\
10531 			      &ftpi->visited, true,			\
10532 			      any_template_parm_r);			\
10533     }									\
10534   while (0)
10535 
10536   /* A mention of a member alias/typedef is a use of all of its template
10537      arguments, including those from the enclosing class, so we don't use
10538      alias_template_specialization_p here.  */
10539   if (TYPE_P (t) && typedef_variant_p (t))
10540     if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
10541       WALK_SUBTREE (TI_ARGS (tinfo));
10542 
10543   switch (TREE_CODE (t))
10544     {
10545     case TEMPLATE_TYPE_PARM:
10546       /* Type constraints of a placeholder type may contain parameters.  */
10547       if (is_auto (t))
10548 	if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
10549 	  WALK_SUBTREE (constr);
10550       break;
10551 
10552     case TEMPLATE_ID_EXPR:
10553       /* Search through references to variable templates.  */
10554       WALK_SUBTREE (TREE_OPERAND (t, 0));
10555       WALK_SUBTREE (TREE_OPERAND (t, 1));
10556       break;
10557 
10558     case TEMPLATE_PARM_INDEX:
10559     case PARM_DECL:
10560       /* A parameter or constraint variable may also depend on a template
10561 	 parameter without explicitly naming it.  */
10562       WALK_SUBTREE (TREE_TYPE (t));
10563       break;
10564 
10565     case TEMPLATE_DECL:
10566       {
10567 	/* If T is a member template that shares template parameters with
10568 	   ctx_parms, we need to mark all those parameters for mapping.  */
10569 	tree dparms = DECL_TEMPLATE_PARMS (t);
10570 	tree cparms = ftpi->ctx_parms;
10571 	while (TMPL_PARMS_DEPTH (dparms) > ftpi->max_depth)
10572 	  dparms = TREE_CHAIN (dparms);
10573 	while (TMPL_PARMS_DEPTH (cparms) > TMPL_PARMS_DEPTH (dparms))
10574 	  cparms = TREE_CHAIN (cparms);
10575 	while (dparms
10576 	       && (TREE_TYPE (TREE_VALUE (dparms))
10577 		   != TREE_TYPE (TREE_VALUE (cparms))))
10578 	  dparms = TREE_CHAIN (dparms),
10579 	    cparms = TREE_CHAIN (cparms);
10580 	if (dparms)
10581 	  {
10582 	    int ddepth = TMPL_PARMS_DEPTH (dparms);
10583 	    tree dargs = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (t)));
10584 	    for (int i = 0; i < ddepth; ++i)
10585 	      WALK_SUBTREE (TMPL_ARGS_LEVEL (dargs, i+1));
10586 	  }
10587       }
10588       break;
10589 
10590     case LAMBDA_EXPR:
10591       {
10592 	/* Look in the parms and body.  */
10593 	tree fn = lambda_function (t);
10594 	WALK_SUBTREE (TREE_TYPE (fn));
10595 	WALK_SUBTREE (DECL_SAVED_TREE (fn));
10596       }
10597       break;
10598 
10599     case IDENTIFIER_NODE:
10600       if (IDENTIFIER_CONV_OP_P (t))
10601 	/* The conversion-type-id of a conversion operator may be dependent.  */
10602 	WALK_SUBTREE (TREE_TYPE (t));
10603       break;
10604 
10605     default:
10606       break;
10607     }
10608 
10609   /* Keep walking.  */
10610   return 0;
10611 }
10612 
10613 /* Returns a list of unique template parameters found within T, where CTX_PARMS
10614    are the template parameters in scope.  */
10615 
10616 tree
find_template_parameters(tree t,tree ctx_parms)10617 find_template_parameters (tree t, tree ctx_parms)
10618 {
10619   if (!ctx_parms)
10620     return NULL_TREE;
10621 
10622   find_template_parameter_info ftpi (ctx_parms);
10623   for_each_template_parm (t, keep_template_parm, &ftpi, &ftpi.visited,
10624 			  /*include_nondeduced*/true, any_template_parm_r);
10625   return ftpi.parm_list;
10626 }
10627 
10628 /* Returns true if T depends on any template parameter.  */
10629 
10630 int
uses_template_parms(tree t)10631 uses_template_parms (tree t)
10632 {
10633   if (t == NULL_TREE)
10634     return false;
10635 
10636   bool dependent_p;
10637   int saved_processing_template_decl;
10638 
10639   saved_processing_template_decl = processing_template_decl;
10640   if (!saved_processing_template_decl)
10641     processing_template_decl = 1;
10642   if (TYPE_P (t))
10643     dependent_p = dependent_type_p (t);
10644   else if (TREE_CODE (t) == TREE_VEC)
10645     dependent_p = any_dependent_template_arguments_p (t);
10646   else if (TREE_CODE (t) == TREE_LIST)
10647     dependent_p = (uses_template_parms (TREE_VALUE (t))
10648 		   || uses_template_parms (TREE_CHAIN (t)));
10649   else if (TREE_CODE (t) == TYPE_DECL)
10650     dependent_p = dependent_type_p (TREE_TYPE (t));
10651   else if (t == error_mark_node)
10652     dependent_p = false;
10653   else
10654     dependent_p = value_dependent_expression_p (t);
10655 
10656   processing_template_decl = saved_processing_template_decl;
10657 
10658   return dependent_p;
10659 }
10660 
10661 /* Returns true iff current_function_decl is an incompletely instantiated
10662    template.  Useful instead of processing_template_decl because the latter
10663    is set to 0 during instantiate_non_dependent_expr.  */
10664 
10665 bool
in_template_function(void)10666 in_template_function (void)
10667 {
10668   tree fn = current_function_decl;
10669   bool ret;
10670   ++processing_template_decl;
10671   ret = (fn && DECL_LANG_SPECIFIC (fn)
10672 	 && DECL_TEMPLATE_INFO (fn)
10673 	 && any_dependent_template_arguments_p (DECL_TI_ARGS (fn)));
10674   --processing_template_decl;
10675   return ret;
10676 }
10677 
10678 /* Returns true if T depends on any template parameter with level LEVEL.  */
10679 
10680 bool
uses_template_parms_level(tree t,int level)10681 uses_template_parms_level (tree t, int level)
10682 {
10683   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
10684 				 /*include_nondeduced_p=*/true);
10685 }
10686 
10687 /* Returns true if the signature of DECL depends on any template parameter from
10688    its enclosing class.  */
10689 
10690 bool
uses_outer_template_parms(tree decl)10691 uses_outer_template_parms (tree decl)
10692 {
10693   int depth = template_class_depth (CP_DECL_CONTEXT (decl));
10694   if (depth == 0)
10695     return false;
10696   if (for_each_template_parm (TREE_TYPE (decl), template_parm_outer_level,
10697 			      &depth, NULL, /*include_nondeduced_p=*/true))
10698     return true;
10699   if (PRIMARY_TEMPLATE_P (decl)
10700       && for_each_template_parm (INNERMOST_TEMPLATE_PARMS
10701 				 (DECL_TEMPLATE_PARMS (decl)),
10702 				 template_parm_outer_level,
10703 				 &depth, NULL, /*include_nondeduced_p=*/true))
10704     return true;
10705   tree ci = get_constraints (decl);
10706   if (ci)
10707     ci = CI_ASSOCIATED_CONSTRAINTS (ci);
10708   if (ci && for_each_template_parm (ci, template_parm_outer_level,
10709 				    &depth, NULL, /*nondeduced*/true))
10710     return true;
10711   return false;
10712 }
10713 
10714 /* Returns TRUE iff INST is an instantiation we don't need to do in an
10715    ill-formed translation unit, i.e. a variable or function that isn't
10716    usable in a constant expression.  */
10717 
10718 static inline bool
neglectable_inst_p(tree d)10719 neglectable_inst_p (tree d)
10720 {
10721   return (d && DECL_P (d)
10722 	  && !undeduced_auto_decl (d)
10723 	  && !(TREE_CODE (d) == FUNCTION_DECL ? DECL_DECLARED_CONSTEXPR_P (d)
10724 	       : decl_maybe_constant_var_p (d)));
10725 }
10726 
10727 /* Returns TRUE iff we should refuse to instantiate DECL because it's
10728    neglectable and instantiated from within an erroneous instantiation.  */
10729 
10730 static bool
limit_bad_template_recursion(tree decl)10731 limit_bad_template_recursion (tree decl)
10732 {
10733   struct tinst_level *lev = current_tinst_level;
10734   int errs = errorcount + sorrycount;
10735   if (lev == NULL || errs == 0 || !neglectable_inst_p (decl))
10736     return false;
10737 
10738   for (; lev; lev = lev->next)
10739     if (neglectable_inst_p (lev->maybe_get_node ()))
10740       break;
10741 
10742   return (lev && errs > lev->errors);
10743 }
10744 
10745 static int tinst_depth;
10746 extern int max_tinst_depth;
10747 int depth_reached;
10748 
10749 static GTY(()) struct tinst_level *last_error_tinst_level;
10750 
10751 /* We're starting to instantiate D; record the template instantiation context
10752    at LOC for diagnostics and to restore it later.  */
10753 
10754 static bool
push_tinst_level_loc(tree tldcl,tree targs,location_t loc)10755 push_tinst_level_loc (tree tldcl, tree targs, location_t loc)
10756 {
10757   struct tinst_level *new_level;
10758 
10759   if (tinst_depth >= max_tinst_depth)
10760     {
10761       /* Tell error.c not to try to instantiate any templates.  */
10762       at_eof = 2;
10763       fatal_error (input_location,
10764 		   "template instantiation depth exceeds maximum of %d"
10765 		   " (use %<-ftemplate-depth=%> to increase the maximum)",
10766                    max_tinst_depth);
10767       return false;
10768     }
10769 
10770   /* If the current instantiation caused problems, don't let it instantiate
10771      anything else.  Do allow deduction substitution and decls usable in
10772      constant expressions.  */
10773   if (!targs && limit_bad_template_recursion (tldcl))
10774     {
10775       /* Avoid no_linkage_errors and unused function warnings for this
10776 	 decl.  */
10777       TREE_NO_WARNING (tldcl) = 1;
10778       return false;
10779     }
10780 
10781   /* When not -quiet, dump template instantiations other than functions, since
10782      announce_function will take care of those.  */
10783   if (!quiet_flag && !targs
10784       && TREE_CODE (tldcl) != TREE_LIST
10785       && TREE_CODE (tldcl) != FUNCTION_DECL)
10786     fprintf (stderr, " %s", decl_as_string (tldcl, TFF_DECL_SPECIFIERS));
10787 
10788   new_level = tinst_level_freelist ().alloc ();
10789   new_level->tldcl = tldcl;
10790   new_level->targs = targs;
10791   new_level->locus = loc;
10792   new_level->errors = errorcount + sorrycount;
10793   new_level->next = NULL;
10794   new_level->refcount = 0;
10795   set_refcount_ptr (new_level->next, current_tinst_level);
10796   set_refcount_ptr (current_tinst_level, new_level);
10797 
10798   ++tinst_depth;
10799   if (GATHER_STATISTICS && (tinst_depth > depth_reached))
10800     depth_reached = tinst_depth;
10801 
10802   return true;
10803 }
10804 
10805 /* We're starting substitution of TMPL<ARGS>; record the template
10806    substitution context for diagnostics and to restore it later.  */
10807 
10808 static bool
push_tinst_level(tree tmpl,tree args)10809 push_tinst_level (tree tmpl, tree args)
10810 {
10811   return push_tinst_level_loc (tmpl, args, input_location);
10812 }
10813 
10814 /* We're starting to instantiate D; record INPUT_LOCATION and the
10815    template instantiation context for diagnostics and to restore it
10816    later.  */
10817 
10818 bool
push_tinst_level(tree d)10819 push_tinst_level (tree d)
10820 {
10821   return push_tinst_level_loc (d, input_location);
10822 }
10823 
10824 /* Likewise, but record LOC as the program location.  */
10825 
10826 bool
push_tinst_level_loc(tree d,location_t loc)10827 push_tinst_level_loc (tree d, location_t loc)
10828 {
10829   gcc_assert (TREE_CODE (d) != TREE_LIST);
10830   return push_tinst_level_loc (d, NULL, loc);
10831 }
10832 
10833 /* We're done instantiating this template; return to the instantiation
10834    context.  */
10835 
10836 void
pop_tinst_level(void)10837 pop_tinst_level (void)
10838 {
10839   /* Restore the filename and line number stashed away when we started
10840      this instantiation.  */
10841   input_location = current_tinst_level->locus;
10842   set_refcount_ptr (current_tinst_level, current_tinst_level->next);
10843   --tinst_depth;
10844 }
10845 
10846 /* We're instantiating a deferred template; restore the template
10847    instantiation context in which the instantiation was requested, which
10848    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
10849 
10850 static tree
reopen_tinst_level(struct tinst_level * level)10851 reopen_tinst_level (struct tinst_level *level)
10852 {
10853   struct tinst_level *t;
10854 
10855   tinst_depth = 0;
10856   for (t = level; t; t = t->next)
10857     ++tinst_depth;
10858 
10859   set_refcount_ptr (current_tinst_level, level);
10860   pop_tinst_level ();
10861   if (current_tinst_level)
10862     current_tinst_level->errors = errorcount+sorrycount;
10863   return level->maybe_get_node ();
10864 }
10865 
10866 /* Returns the TINST_LEVEL which gives the original instantiation
10867    context.  */
10868 
10869 struct tinst_level *
outermost_tinst_level(void)10870 outermost_tinst_level (void)
10871 {
10872   struct tinst_level *level = current_tinst_level;
10873   if (level)
10874     while (level->next)
10875       level = level->next;
10876   return level;
10877 }
10878 
10879 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
10880    vector of template arguments, as for tsubst.
10881 
10882    Returns an appropriate tsubst'd friend declaration.  */
10883 
10884 static tree
tsubst_friend_function(tree decl,tree args)10885 tsubst_friend_function (tree decl, tree args)
10886 {
10887   tree new_friend;
10888 
10889   if (TREE_CODE (decl) == FUNCTION_DECL
10890       && DECL_TEMPLATE_INSTANTIATION (decl)
10891       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
10892     /* This was a friend declared with an explicit template
10893        argument list, e.g.:
10894 
10895        friend void f<>(T);
10896 
10897        to indicate that f was a template instantiation, not a new
10898        function declaration.  Now, we have to figure out what
10899        instantiation of what template.  */
10900     {
10901       tree template_id, arglist, fns;
10902       tree new_args;
10903       tree tmpl;
10904       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
10905 
10906       /* Friend functions are looked up in the containing namespace scope.
10907 	 We must enter that scope, to avoid finding member functions of the
10908 	 current class with same name.  */
10909       push_nested_namespace (ns);
10910       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
10911 			 tf_warning_or_error, NULL_TREE,
10912 			 /*integral_constant_expression_p=*/false);
10913       pop_nested_namespace (ns);
10914       arglist = tsubst (DECL_TI_ARGS (decl), args,
10915 			tf_warning_or_error, NULL_TREE);
10916       template_id = lookup_template_function (fns, arglist);
10917 
10918       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
10919       tmpl = determine_specialization (template_id, new_friend,
10920 				       &new_args,
10921 				       /*need_member_template=*/0,
10922 				       TREE_VEC_LENGTH (args),
10923 				       tsk_none);
10924       return instantiate_template (tmpl, new_args, tf_error);
10925     }
10926 
10927   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
10928 
10929   /* The NEW_FRIEND will look like an instantiation, to the
10930      compiler, but is not an instantiation from the point of view of
10931      the language.  For example, we might have had:
10932 
10933      template <class T> struct S {
10934        template <class U> friend void f(T, U);
10935      };
10936 
10937      Then, in S<int>, template <class U> void f(int, U) is not an
10938      instantiation of anything.  */
10939   if (new_friend == error_mark_node)
10940     return error_mark_node;
10941 
10942   DECL_USE_TEMPLATE (new_friend) = 0;
10943   if (TREE_CODE (decl) == TEMPLATE_DECL)
10944     {
10945       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
10946       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
10947 	= DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
10948 
10949       /* Substitute TEMPLATE_PARMS_CONSTRAINTS so that parameter levels will
10950 	 match in decls_match.  */
10951       tree parms = DECL_TEMPLATE_PARMS (new_friend);
10952       tree treqs = TEMPLATE_PARMS_CONSTRAINTS (parms);
10953       treqs = maybe_substitute_reqs_for (treqs, new_friend);
10954       TEMPLATE_PARMS_CONSTRAINTS (parms) = treqs;
10955     }
10956 
10957   /* The mangled name for the NEW_FRIEND is incorrect.  The function
10958      is not a template instantiation and should not be mangled like
10959      one.  Therefore, we forget the mangling here; we'll recompute it
10960      later if we need it.  */
10961   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
10962     {
10963       SET_DECL_RTL (new_friend, NULL);
10964       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
10965     }
10966 
10967   if (DECL_NAMESPACE_SCOPE_P (new_friend))
10968     {
10969       tree old_decl;
10970       tree new_friend_template_info;
10971       tree new_friend_result_template_info;
10972       tree ns;
10973       int  new_friend_is_defn;
10974 
10975       /* We must save some information from NEW_FRIEND before calling
10976 	 duplicate decls since that function will free NEW_FRIEND if
10977 	 possible.  */
10978       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
10979       new_friend_is_defn =
10980 	    (DECL_INITIAL (DECL_TEMPLATE_RESULT
10981 			   (template_for_substitution (new_friend)))
10982 	     != NULL_TREE);
10983       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
10984 	{
10985 	  /* This declaration is a `primary' template.  */
10986 	  DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
10987 
10988 	  new_friend_result_template_info
10989 	    = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
10990 	}
10991       else
10992 	new_friend_result_template_info = NULL_TREE;
10993 
10994       /* Inside pushdecl_namespace_level, we will push into the
10995 	 current namespace. However, the friend function should go
10996 	 into the namespace of the template.  */
10997       ns = decl_namespace_context (new_friend);
10998       push_nested_namespace (ns);
10999       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
11000       pop_nested_namespace (ns);
11001 
11002       if (old_decl == error_mark_node)
11003 	return error_mark_node;
11004 
11005       if (old_decl != new_friend)
11006 	{
11007 	  /* This new friend declaration matched an existing
11008 	     declaration.  For example, given:
11009 
11010 	       template <class T> void f(T);
11011 	       template <class U> class C {
11012 		 template <class T> friend void f(T) {}
11013 	       };
11014 
11015 	     the friend declaration actually provides the definition
11016 	     of `f', once C has been instantiated for some type.  So,
11017 	     old_decl will be the out-of-class template declaration,
11018 	     while new_friend is the in-class definition.
11019 
11020 	     But, if `f' was called before this point, the
11021 	     instantiation of `f' will have DECL_TI_ARGS corresponding
11022 	     to `T' but not to `U', references to which might appear
11023 	     in the definition of `f'.  Previously, the most general
11024 	     template for an instantiation of `f' was the out-of-class
11025 	     version; now it is the in-class version.  Therefore, we
11026 	     run through all specialization of `f', adding to their
11027 	     DECL_TI_ARGS appropriately.  In particular, they need a
11028 	     new set of outer arguments, corresponding to the
11029 	     arguments for this class instantiation.
11030 
11031 	     The same situation can arise with something like this:
11032 
11033 	       friend void f(int);
11034 	       template <class T> class C {
11035 		 friend void f(T) {}
11036 	       };
11037 
11038 	     when `C<int>' is instantiated.  Now, `f(int)' is defined
11039 	     in the class.  */
11040 
11041 	  if (!new_friend_is_defn)
11042 	    /* On the other hand, if the in-class declaration does
11043 	       *not* provide a definition, then we don't want to alter
11044 	       existing definitions.  We can just leave everything
11045 	       alone.  */
11046 	    ;
11047 	  else
11048 	    {
11049 	      tree new_template = TI_TEMPLATE (new_friend_template_info);
11050 	      tree new_args = TI_ARGS (new_friend_template_info);
11051 
11052 	      /* Overwrite whatever template info was there before, if
11053 		 any, with the new template information pertaining to
11054 		 the declaration.  */
11055 	      DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
11056 
11057 	      if (TREE_CODE (old_decl) != TEMPLATE_DECL)
11058 		{
11059 		  /* We should have called reregister_specialization in
11060 		     duplicate_decls.  */
11061 		  gcc_assert (retrieve_specialization (new_template,
11062 						       new_args, 0)
11063 			      == old_decl);
11064 
11065 		  /* Instantiate it if the global has already been used.  */
11066 		  if (DECL_ODR_USED (old_decl))
11067 		    instantiate_decl (old_decl, /*defer_ok=*/true,
11068 				      /*expl_inst_class_mem_p=*/false);
11069 		}
11070 	      else
11071 		{
11072 		  tree t;
11073 
11074 		  /* Indicate that the old function template is a partial
11075 		     instantiation.  */
11076 		  DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
11077 		    = new_friend_result_template_info;
11078 
11079 		  gcc_assert (new_template
11080 			      == most_general_template (new_template));
11081 		  gcc_assert (new_template != old_decl);
11082 
11083 		  /* Reassign any specializations already in the hash table
11084 		     to the new more general template, and add the
11085 		     additional template args.  */
11086 		  for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
11087 		       t != NULL_TREE;
11088 		       t = TREE_CHAIN (t))
11089 		    {
11090 		      tree spec = TREE_VALUE (t);
11091 		      spec_entry elt;
11092 
11093 		      elt.tmpl = old_decl;
11094 		      elt.args = DECL_TI_ARGS (spec);
11095 		      elt.spec = NULL_TREE;
11096 
11097 		      decl_specializations->remove_elt (&elt);
11098 
11099 		      DECL_TI_ARGS (spec)
11100 			= add_outermost_template_args (new_args,
11101 						       DECL_TI_ARGS (spec));
11102 
11103 		      register_specialization
11104 			(spec, new_template, DECL_TI_ARGS (spec), true, 0);
11105 
11106 		    }
11107 		  DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
11108 		}
11109 	    }
11110 
11111 	  /* The information from NEW_FRIEND has been merged into OLD_DECL
11112 	     by duplicate_decls.  */
11113 	  new_friend = old_decl;
11114 	}
11115     }
11116   else
11117     {
11118       tree context = DECL_CONTEXT (new_friend);
11119       bool dependent_p;
11120 
11121       /* In the code
11122 	   template <class T> class C {
11123 	     template <class U> friend void C1<U>::f (); // case 1
11124 	     friend void C2<T>::f ();			 // case 2
11125 	   };
11126 	 we only need to make sure CONTEXT is a complete type for
11127 	 case 2.  To distinguish between the two cases, we note that
11128 	 CONTEXT of case 1 remains dependent type after tsubst while
11129 	 this isn't true for case 2.  */
11130       ++processing_template_decl;
11131       dependent_p = dependent_type_p (context);
11132       --processing_template_decl;
11133 
11134       if (!dependent_p
11135 	  && !complete_type_or_else (context, NULL_TREE))
11136 	return error_mark_node;
11137 
11138       if (COMPLETE_TYPE_P (context))
11139 	{
11140 	  tree fn = new_friend;
11141 	  /* do_friend adds the TEMPLATE_DECL for any member friend
11142 	     template even if it isn't a member template, i.e.
11143 	       template <class T> friend A<T>::f();
11144 	     Look through it in that case.  */
11145 	  if (TREE_CODE (fn) == TEMPLATE_DECL
11146 	      && !PRIMARY_TEMPLATE_P (fn))
11147 	    fn = DECL_TEMPLATE_RESULT (fn);
11148 	  /* Check to see that the declaration is really present, and,
11149 	     possibly obtain an improved declaration.  */
11150 	  fn = check_classfn (context, fn, NULL_TREE);
11151 
11152 	  if (fn)
11153 	    new_friend = fn;
11154 	}
11155     }
11156 
11157   return new_friend;
11158 }
11159 
11160 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
11161    template arguments, as for tsubst.
11162 
11163    Returns an appropriate tsubst'd friend type or error_mark_node on
11164    failure.  */
11165 
11166 static tree
tsubst_friend_class(tree friend_tmpl,tree args)11167 tsubst_friend_class (tree friend_tmpl, tree args)
11168 {
11169   tree tmpl;
11170 
11171   if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
11172     {
11173       tmpl = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
11174       return TREE_TYPE (tmpl);
11175     }
11176 
11177   tree context = CP_DECL_CONTEXT (friend_tmpl);
11178   if (TREE_CODE (context) == NAMESPACE_DECL)
11179     push_nested_namespace (context);
11180   else
11181     {
11182       context = tsubst (context, args, tf_error, NULL_TREE);
11183       push_nested_class (context);
11184     }
11185 
11186   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), /*prefer_type=*/false,
11187 			   /*non_class=*/false, /*block_p=*/false,
11188 			   /*namespaces_only=*/false, LOOKUP_HIDDEN);
11189 
11190   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
11191     {
11192       /* The friend template has already been declared.  Just
11193 	 check to see that the declarations match, and install any new
11194 	 default parameters.  We must tsubst the default parameters,
11195 	 of course.  We only need the innermost template parameters
11196 	 because that is all that redeclare_class_template will look
11197 	 at.  */
11198       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
11199 	  > TMPL_ARGS_DEPTH (args))
11200 	{
11201 	  tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
11202 					      args, tf_warning_or_error);
11203           location_t saved_input_location = input_location;
11204           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
11205           tree cons = get_constraints (tmpl);
11206           redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
11207           input_location = saved_input_location;
11208 	}
11209     }
11210   else
11211     {
11212       /* The friend template has not already been declared.  In this
11213 	 case, the instantiation of the template class will cause the
11214 	 injection of this template into the namespace scope.  */
11215       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
11216 
11217       if (tmpl != error_mark_node)
11218 	{
11219 	  /* The new TMPL is not an instantiation of anything, so we
11220 	     forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE
11221 	     for the new type because that is supposed to be the
11222 	     corresponding template decl, i.e., TMPL.  */
11223 	  DECL_USE_TEMPLATE (tmpl) = 0;
11224 	  DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
11225 	  CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
11226 	  CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
11227 	    = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
11228 
11229 	  /* It is hidden.  */
11230 	  retrofit_lang_decl (DECL_TEMPLATE_RESULT (tmpl));
11231 	  DECL_ANTICIPATED (tmpl)
11232 	    = DECL_ANTICIPATED (DECL_TEMPLATE_RESULT (tmpl)) = true;
11233 
11234 	  /* Substitute into and set the constraints on the new declaration.  */
11235 	  if (tree ci = get_constraints (friend_tmpl))
11236 	    {
11237 	      ++processing_template_decl;
11238 	      ci = tsubst_constraint_info (ci, args, tf_warning_or_error,
11239 					   DECL_FRIEND_CONTEXT (friend_tmpl));
11240 	      --processing_template_decl;
11241 	      set_constraints (tmpl, ci);
11242 	    }
11243 
11244 	  /* Inject this template into the enclosing namspace scope.  */
11245 	  tmpl = pushdecl_namespace_level (tmpl, true);
11246 	}
11247     }
11248 
11249   if (TREE_CODE (context) == NAMESPACE_DECL)
11250     pop_nested_namespace (context);
11251   else
11252     pop_nested_class ();
11253 
11254   return TREE_TYPE (tmpl);
11255 }
11256 
11257 /* Returns zero if TYPE cannot be completed later due to circularity.
11258    Otherwise returns one.  */
11259 
11260 static int
can_complete_type_without_circularity(tree type)11261 can_complete_type_without_circularity (tree type)
11262 {
11263   if (type == NULL_TREE || type == error_mark_node)
11264     return 0;
11265   else if (COMPLETE_TYPE_P (type))
11266     return 1;
11267   else if (TREE_CODE (type) == ARRAY_TYPE)
11268     return can_complete_type_without_circularity (TREE_TYPE (type));
11269   else if (CLASS_TYPE_P (type)
11270 	   && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
11271     return 0;
11272   else
11273     return 1;
11274 }
11275 
11276 static tree tsubst_omp_clauses (tree, enum c_omp_region_type, tree,
11277 				tsubst_flags_t, tree);
11278 
11279 /* Instantiate a single dependent attribute T (a TREE_LIST), and return either
11280    T or a new TREE_LIST, possibly a chain in the case of a pack expansion.  */
11281 
11282 static tree
tsubst_attribute(tree t,tree * decl_p,tree args,tsubst_flags_t complain,tree in_decl)11283 tsubst_attribute (tree t, tree *decl_p, tree args,
11284 		  tsubst_flags_t complain, tree in_decl)
11285 {
11286   gcc_assert (ATTR_IS_DEPENDENT (t));
11287 
11288   tree val = TREE_VALUE (t);
11289   if (val == NULL_TREE)
11290     /* Nothing to do.  */;
11291   else if ((flag_openmp || flag_openmp_simd)
11292 	   && is_attribute_p ("omp declare simd",
11293 			      get_attribute_name (t)))
11294     {
11295       tree clauses = TREE_VALUE (val);
11296       clauses = tsubst_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD, args,
11297 				    complain, in_decl);
11298       c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11299       clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11300       tree parms = DECL_ARGUMENTS (*decl_p);
11301       clauses
11302 	= c_omp_declare_simd_clauses_to_numbers (parms, clauses);
11303       if (clauses)
11304 	val = build_tree_list (NULL_TREE, clauses);
11305       else
11306 	val = NULL_TREE;
11307     }
11308   else if (flag_openmp
11309 	   && is_attribute_p ("omp declare variant base",
11310 			      get_attribute_name (t)))
11311     {
11312       ++cp_unevaluated_operand;
11313       tree varid
11314 	= tsubst_expr (TREE_PURPOSE (val), args, complain,
11315 		       in_decl, /*integral_constant_expression_p=*/false);
11316       --cp_unevaluated_operand;
11317       tree chain = TREE_CHAIN (val);
11318       location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
11319       tree ctx = copy_list (TREE_VALUE (val));
11320       tree simd = get_identifier ("simd");
11321       tree score = get_identifier (" score");
11322       tree condition = get_identifier ("condition");
11323       for (tree t1 = ctx; t1; t1 = TREE_CHAIN (t1))
11324 	{
11325 	  const char *set = IDENTIFIER_POINTER (TREE_PURPOSE (t1));
11326 	  TREE_VALUE (t1) = copy_list (TREE_VALUE (t1));
11327 	  for (tree t2 = TREE_VALUE (t1); t2; t2 = TREE_CHAIN (t2))
11328 	    {
11329 	      if (TREE_PURPOSE (t2) == simd && set[0] == 'c')
11330 		{
11331 		  tree clauses = TREE_VALUE (t2);
11332 		  clauses = tsubst_omp_clauses (clauses,
11333 						C_ORT_OMP_DECLARE_SIMD, args,
11334 						complain, in_decl);
11335 		  c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11336 		  clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11337 		  TREE_VALUE (t2) = clauses;
11338 		}
11339 	      else
11340 		{
11341 		  TREE_VALUE (t2) = copy_list (TREE_VALUE (t2));
11342 		  for (tree t3 = TREE_VALUE (t2); t3; t3 = TREE_CHAIN (t3))
11343 		    if (TREE_VALUE (t3))
11344 		      {
11345 			bool allow_string
11346 			  = ((TREE_PURPOSE (t2) != condition || set[0] != 'u')
11347 			     && TREE_PURPOSE (t3) != score);
11348 			tree v = TREE_VALUE (t3);
11349 			if (TREE_CODE (v) == STRING_CST && allow_string)
11350 			  continue;
11351 			v = tsubst_expr (v, args, complain, in_decl, true);
11352 			v = fold_non_dependent_expr (v);
11353 			if (!INTEGRAL_TYPE_P (TREE_TYPE (v))
11354 			    || (TREE_PURPOSE (t3) == score
11355 				? TREE_CODE (v) != INTEGER_CST
11356 				: !tree_fits_shwi_p (v)))
11357 			  {
11358 			    location_t loc
11359 			      = cp_expr_loc_or_loc (TREE_VALUE (t3),
11360 						    match_loc);
11361 			    if (TREE_PURPOSE (t3) == score)
11362 			      error_at (loc, "score argument must be "
11363 					     "constant integer expression");
11364 			    else if (allow_string)
11365 			      error_at (loc, "property must be constant "
11366 					     "integer expression or string "
11367 					     "literal");
11368 			    else
11369 			      error_at (loc, "property must be constant "
11370 					     "integer expression");
11371 			    return NULL_TREE;
11372 			  }
11373 			else if (TREE_PURPOSE (t3) == score
11374 				 && tree_int_cst_sgn (v) < 0)
11375 			  {
11376 			    location_t loc
11377 			      = cp_expr_loc_or_loc (TREE_VALUE (t3),
11378 						    match_loc);
11379 			    error_at (loc, "score argument must be "
11380 					   "non-negative");
11381 			    return NULL_TREE;
11382 			  }
11383 			TREE_VALUE (t3) = v;
11384 		      }
11385 		}
11386 	    }
11387 	}
11388       val = tree_cons (varid, ctx, chain);
11389     }
11390   /* If the first attribute argument is an identifier, don't
11391      pass it through tsubst.  Attributes like mode, format,
11392      cleanup and several target specific attributes expect it
11393      unmodified.  */
11394   else if (attribute_takes_identifier_p (get_attribute_name (t)))
11395     {
11396       tree chain
11397 	= tsubst_expr (TREE_CHAIN (val), args, complain, in_decl,
11398 		       /*integral_constant_expression_p=*/false);
11399       if (chain != TREE_CHAIN (val))
11400 	val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
11401     }
11402   else if (PACK_EXPANSION_P (val))
11403     {
11404       /* An attribute pack expansion.  */
11405       tree purp = TREE_PURPOSE (t);
11406       tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
11407       if (pack == error_mark_node)
11408 	return error_mark_node;
11409       int len = TREE_VEC_LENGTH (pack);
11410       tree list = NULL_TREE;
11411       tree *q = &list;
11412       for (int i = 0; i < len; ++i)
11413 	{
11414 	  tree elt = TREE_VEC_ELT (pack, i);
11415 	  *q = build_tree_list (purp, elt);
11416 	  q = &TREE_CHAIN (*q);
11417 	}
11418       return list;
11419     }
11420   else
11421     val = tsubst_expr (val, args, complain, in_decl,
11422 		       /*integral_constant_expression_p=*/false);
11423 
11424   if (val != TREE_VALUE (t))
11425     return build_tree_list (TREE_PURPOSE (t), val);
11426   return t;
11427 }
11428 
11429 /* Instantiate any dependent attributes in ATTRIBUTES, returning either it
11430    unchanged or a new TREE_LIST chain.  */
11431 
11432 static tree
tsubst_attributes(tree attributes,tree args,tsubst_flags_t complain,tree in_decl)11433 tsubst_attributes (tree attributes, tree args,
11434 		   tsubst_flags_t complain, tree in_decl)
11435 {
11436   tree last_dep = NULL_TREE;
11437 
11438   for (tree t = attributes; t; t = TREE_CHAIN (t))
11439     if (ATTR_IS_DEPENDENT (t))
11440       {
11441 	last_dep = t;
11442 	attributes = copy_list (attributes);
11443 	break;
11444       }
11445 
11446   if (last_dep)
11447     for (tree *p = &attributes; *p; )
11448       {
11449 	tree t = *p;
11450 	if (ATTR_IS_DEPENDENT (t))
11451 	  {
11452 	    tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
11453 	    if (subst != t)
11454 	      {
11455 		*p = subst;
11456 		while (*p)
11457 		  p = &TREE_CHAIN (*p);
11458 		*p = TREE_CHAIN (t);
11459 		continue;
11460 	      }
11461 	  }
11462 	p = &TREE_CHAIN (*p);
11463       }
11464 
11465   return attributes;
11466 }
11467 
11468 /* Apply any attributes which had to be deferred until instantiation
11469    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
11470    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
11471 
11472 static void
apply_late_template_attributes(tree * decl_p,tree attributes,int attr_flags,tree args,tsubst_flags_t complain,tree in_decl)11473 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
11474 				tree args, tsubst_flags_t complain, tree in_decl)
11475 {
11476   tree last_dep = NULL_TREE;
11477   tree t;
11478   tree *p;
11479 
11480   if (attributes == NULL_TREE)
11481     return;
11482 
11483   if (DECL_P (*decl_p))
11484     {
11485       if (TREE_TYPE (*decl_p) == error_mark_node)
11486 	return;
11487       p = &DECL_ATTRIBUTES (*decl_p);
11488       /* DECL_ATTRIBUTES comes from copy_node in tsubst_decl, and is identical
11489          to our attributes parameter.  */
11490       gcc_assert (*p == attributes);
11491     }
11492   else
11493     {
11494       p = &TYPE_ATTRIBUTES (*decl_p);
11495       /* TYPE_ATTRIBUTES was set up (with abi_tag and may_alias) in
11496 	 lookup_template_class_1, and should be preserved.  */
11497       gcc_assert (*p != attributes);
11498       while (*p)
11499 	p = &TREE_CHAIN (*p);
11500     }
11501 
11502   for (t = attributes; t; t = TREE_CHAIN (t))
11503     if (ATTR_IS_DEPENDENT (t))
11504       {
11505 	last_dep = t;
11506 	attributes = copy_list (attributes);
11507 	break;
11508       }
11509 
11510   *p = attributes;
11511   if (last_dep)
11512     {
11513       tree late_attrs = NULL_TREE;
11514       tree *q = &late_attrs;
11515 
11516       for (; *p; )
11517 	{
11518 	  t = *p;
11519 	  if (ATTR_IS_DEPENDENT (t))
11520 	    {
11521 	      *p = TREE_CHAIN (t);
11522 	      TREE_CHAIN (t) = NULL_TREE;
11523 	      *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
11524 	      while (*q)
11525 		q = &TREE_CHAIN (*q);
11526 	    }
11527 	  else
11528 	    p = &TREE_CHAIN (t);
11529 	}
11530 
11531       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
11532     }
11533 }
11534 
11535 /* Perform (or defer) access check for typedefs that were referenced
11536    from within the template TMPL code.
11537    This is a subroutine of instantiate_decl and instantiate_class_template.
11538    TMPL is the template to consider and TARGS is the list of arguments of
11539    that template.  */
11540 
11541 static void
perform_typedefs_access_check(tree tmpl,tree targs)11542 perform_typedefs_access_check (tree tmpl, tree targs)
11543 {
11544   unsigned i;
11545   qualified_typedef_usage_t *iter;
11546 
11547   if (!tmpl
11548       || (!CLASS_TYPE_P (tmpl)
11549 	  && TREE_CODE (tmpl) != FUNCTION_DECL))
11550     return;
11551 
11552   FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (tmpl), i, iter)
11553     {
11554       tree type_decl = iter->typedef_decl;
11555       tree type_scope = iter->context;
11556 
11557       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
11558 	continue;
11559 
11560       if (uses_template_parms (type_decl))
11561 	type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
11562       if (uses_template_parms (type_scope))
11563 	type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
11564 
11565       /* Make access check error messages point to the location
11566          of the use of the typedef.  */
11567       iloc_sentinel ils (iter->locus);
11568       perform_or_defer_access_check (TYPE_BINFO (type_scope),
11569 				     type_decl, type_decl,
11570 				     tf_warning_or_error);
11571     }
11572 }
11573 
11574 static tree
instantiate_class_template_1(tree type)11575 instantiate_class_template_1 (tree type)
11576 {
11577   tree templ, args, pattern, t, member;
11578   tree typedecl;
11579   tree pbinfo;
11580   tree base_list;
11581   unsigned int saved_maximum_field_alignment;
11582   tree fn_context;
11583 
11584   if (type == error_mark_node)
11585     return error_mark_node;
11586 
11587   if (COMPLETE_OR_OPEN_TYPE_P (type)
11588       || uses_template_parms (type))
11589     return type;
11590 
11591   /* Figure out which template is being instantiated.  */
11592   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
11593   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
11594 
11595   /* Mark the type as in the process of being defined.  */
11596   TYPE_BEING_DEFINED (type) = 1;
11597 
11598   /* We may be in the middle of deferred access check.  Disable
11599      it now.  */
11600   deferring_access_check_sentinel acs (dk_no_deferred);
11601 
11602   /* Determine what specialization of the original template to
11603      instantiate.  */
11604   t = most_specialized_partial_spec (type, tf_warning_or_error);
11605   if (t == error_mark_node)
11606     return error_mark_node;
11607   else if (t)
11608     {
11609       /* This TYPE is actually an instantiation of a partial
11610 	 specialization.  We replace the innermost set of ARGS with
11611 	 the arguments appropriate for substitution.  For example,
11612 	 given:
11613 
11614 	   template <class T> struct S {};
11615 	   template <class T> struct S<T*> {};
11616 
11617 	 and supposing that we are instantiating S<int*>, ARGS will
11618 	 presently be {int*} -- but we need {int}.  */
11619       pattern = TREE_TYPE (t);
11620       args = TREE_PURPOSE (t);
11621     }
11622   else
11623     {
11624       pattern = TREE_TYPE (templ);
11625       args = CLASSTYPE_TI_ARGS (type);
11626     }
11627 
11628   /* If the template we're instantiating is incomplete, then clearly
11629      there's nothing we can do.  */
11630   if (!COMPLETE_TYPE_P (pattern))
11631     {
11632       /* We can try again later.  */
11633       TYPE_BEING_DEFINED (type) = 0;
11634       return type;
11635     }
11636 
11637   /* If we've recursively instantiated too many templates, stop.  */
11638   if (! push_tinst_level (type))
11639     return type;
11640 
11641   int saved_unevaluated_operand = cp_unevaluated_operand;
11642   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
11643 
11644   fn_context = decl_function_context (TYPE_MAIN_DECL (type));
11645   /* Also avoid push_to_top_level for a lambda in an NSDMI.  */
11646   if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
11647     fn_context = error_mark_node;
11648   if (!fn_context)
11649     push_to_top_level ();
11650   else
11651     {
11652       cp_unevaluated_operand = 0;
11653       c_inhibit_evaluation_warnings = 0;
11654     }
11655   /* Use #pragma pack from the template context.  */
11656   saved_maximum_field_alignment = maximum_field_alignment;
11657   maximum_field_alignment = TYPE_PRECISION (pattern);
11658 
11659   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
11660 
11661   /* Set the input location to the most specialized template definition.
11662      This is needed if tsubsting causes an error.  */
11663   typedecl = TYPE_MAIN_DECL (pattern);
11664   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
11665     DECL_SOURCE_LOCATION (typedecl);
11666 
11667   TYPE_PACKED (type) = TYPE_PACKED (pattern);
11668   SET_TYPE_ALIGN (type, TYPE_ALIGN (pattern));
11669   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
11670   CLASSTYPE_NON_AGGREGATE (type) = CLASSTYPE_NON_AGGREGATE (pattern);
11671   if (ANON_AGGR_TYPE_P (pattern))
11672     SET_ANON_AGGR_TYPE_P (type);
11673   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
11674     {
11675       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
11676       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
11677       /* Adjust visibility for template arguments.  */
11678       determine_visibility (TYPE_MAIN_DECL (type));
11679     }
11680   if (CLASS_TYPE_P (type))
11681     CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
11682 
11683   pbinfo = TYPE_BINFO (pattern);
11684 
11685   /* We should never instantiate a nested class before its enclosing
11686      class; we need to look up the nested class by name before we can
11687      instantiate it, and that lookup should instantiate the enclosing
11688      class.  */
11689   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
11690 	      || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
11691 
11692   base_list = NULL_TREE;
11693   if (BINFO_N_BASE_BINFOS (pbinfo))
11694     {
11695       tree pbase_binfo;
11696       tree pushed_scope;
11697       int i;
11698 
11699       /* We must enter the scope containing the type, as that is where
11700 	 the accessibility of types named in dependent bases are
11701 	 looked up from.  */
11702       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
11703 
11704       /* Substitute into each of the bases to determine the actual
11705 	 basetypes.  */
11706       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
11707 	{
11708 	  tree base;
11709 	  tree access = BINFO_BASE_ACCESS (pbinfo, i);
11710           tree expanded_bases = NULL_TREE;
11711           int idx, len = 1;
11712 
11713           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
11714             {
11715               expanded_bases =
11716 		tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
11717 				       args, tf_error, NULL_TREE);
11718               if (expanded_bases == error_mark_node)
11719                 continue;
11720 
11721               len = TREE_VEC_LENGTH (expanded_bases);
11722             }
11723 
11724           for (idx = 0; idx < len; idx++)
11725             {
11726               if (expanded_bases)
11727                 /* Extract the already-expanded base class.  */
11728                 base = TREE_VEC_ELT (expanded_bases, idx);
11729               else
11730                 /* Substitute to figure out the base class.  */
11731                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
11732                                NULL_TREE);
11733 
11734               if (base == error_mark_node)
11735                 continue;
11736 
11737               base_list = tree_cons (access, base, base_list);
11738               if (BINFO_VIRTUAL_P (pbase_binfo))
11739                 TREE_TYPE (base_list) = integer_type_node;
11740             }
11741 	}
11742 
11743       /* The list is now in reverse order; correct that.  */
11744       base_list = nreverse (base_list);
11745 
11746       if (pushed_scope)
11747 	pop_scope (pushed_scope);
11748     }
11749   /* Now call xref_basetypes to set up all the base-class
11750      information.  */
11751   xref_basetypes (type, base_list);
11752 
11753   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
11754 				  (int) ATTR_FLAG_TYPE_IN_PLACE,
11755 				  args, tf_error, NULL_TREE);
11756   fixup_attribute_variants (type);
11757 
11758   /* Now that our base classes are set up, enter the scope of the
11759      class, so that name lookups into base classes, etc. will work
11760      correctly.  This is precisely analogous to what we do in
11761      begin_class_definition when defining an ordinary non-template
11762      class, except we also need to push the enclosing classes.  */
11763   push_nested_class (type);
11764 
11765   /* Now members are processed in the order of declaration.  */
11766   for (member = CLASSTYPE_DECL_LIST (pattern);
11767        member; member = TREE_CHAIN (member))
11768     {
11769       tree t = TREE_VALUE (member);
11770 
11771       if (TREE_PURPOSE (member))
11772 	{
11773 	  if (TYPE_P (t))
11774 	    {
11775 	      if (LAMBDA_TYPE_P (t))
11776 		/* A closure type for a lambda in an NSDMI or default argument.
11777 		   Ignore it; it will be regenerated when needed.  */
11778 		continue;
11779 
11780 	      /* Build new CLASSTYPE_NESTED_UTDS.  */
11781 
11782 	      tree newtag;
11783 	      bool class_template_p;
11784 
11785 	      class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
11786 				  && TYPE_LANG_SPECIFIC (t)
11787 				  && CLASSTYPE_IS_TEMPLATE (t));
11788 	      /* If the member is a class template, then -- even after
11789 		 substitution -- there may be dependent types in the
11790 		 template argument list for the class.  We increment
11791 		 PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
11792 		 that function will assume that no types are dependent
11793 		 when outside of a template.  */
11794 	      if (class_template_p)
11795 		++processing_template_decl;
11796 	      newtag = tsubst (t, args, tf_error, NULL_TREE);
11797 	      if (class_template_p)
11798 		--processing_template_decl;
11799 	      if (newtag == error_mark_node)
11800 		continue;
11801 
11802 	      if (TREE_CODE (newtag) != ENUMERAL_TYPE)
11803 		{
11804 		  tree name = TYPE_IDENTIFIER (t);
11805 
11806 		  if (class_template_p)
11807 		    /* Unfortunately, lookup_template_class sets
11808 		       CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
11809 		       instantiation (i.e., for the type of a member
11810 		       template class nested within a template class.)
11811 		       This behavior is required for
11812 		       maybe_process_partial_specialization to work
11813 		       correctly, but is not accurate in this case;
11814 		       the TAG is not an instantiation of anything.
11815 		       (The corresponding TEMPLATE_DECL is an
11816 		       instantiation, but the TYPE is not.) */
11817 		    CLASSTYPE_USE_TEMPLATE (newtag) = 0;
11818 
11819 		  /* Now, we call pushtag to put this NEWTAG into the scope of
11820 		     TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
11821 		     pushtag calling push_template_decl.  We don't have to do
11822 		     this for enums because it will already have been done in
11823 		     tsubst_enum.  */
11824 		  if (name)
11825 		    SET_IDENTIFIER_TYPE_VALUE (name, newtag);
11826 		  pushtag (name, newtag, /*tag_scope=*/ts_current);
11827 		}
11828 	    }
11829 	  else if (DECL_DECLARES_FUNCTION_P (t))
11830 	    {
11831 	      tree r;
11832 
11833 	      if (TREE_CODE (t) == TEMPLATE_DECL)
11834 		++processing_template_decl;
11835 	      r = tsubst (t, args, tf_error, NULL_TREE);
11836 	      if (TREE_CODE (t) == TEMPLATE_DECL)
11837 		--processing_template_decl;
11838 	      set_current_access_from_decl (r);
11839 	      finish_member_declaration (r);
11840 	      /* Instantiate members marked with attribute used.  */
11841 	      if (r != error_mark_node && DECL_PRESERVE_P (r))
11842 		mark_used (r);
11843 	      if (TREE_CODE (r) == FUNCTION_DECL
11844 		  && DECL_OMP_DECLARE_REDUCTION_P (r))
11845 		cp_check_omp_declare_reduction (r);
11846 	    }
11847 	  else if ((DECL_CLASS_TEMPLATE_P (t) || DECL_IMPLICIT_TYPEDEF_P (t))
11848 		   && LAMBDA_TYPE_P (TREE_TYPE (t)))
11849 	    /* A closure type for a lambda in an NSDMI or default argument.
11850 	       Ignore it; it will be regenerated when needed.  */;
11851 	  else
11852 	    {
11853 	      /* Build new TYPE_FIELDS.  */
11854               if (TREE_CODE (t) == STATIC_ASSERT)
11855                 {
11856                   tree condition;
11857 
11858 		  ++c_inhibit_evaluation_warnings;
11859 		  condition =
11860 		    tsubst_expr (STATIC_ASSERT_CONDITION (t), args,
11861 				 tf_warning_or_error, NULL_TREE,
11862 				 /*integral_constant_expression_p=*/true);
11863 		  --c_inhibit_evaluation_warnings;
11864 
11865                   finish_static_assert (condition,
11866                                         STATIC_ASSERT_MESSAGE (t),
11867                                         STATIC_ASSERT_SOURCE_LOCATION (t),
11868                                         /*member_p=*/true);
11869                 }
11870 	      else if (TREE_CODE (t) != CONST_DECL)
11871 		{
11872 		  tree r;
11873 		  tree vec = NULL_TREE;
11874 		  int len = 1;
11875 
11876 		  /* The file and line for this declaration, to
11877 		     assist in error message reporting.  Since we
11878 		     called push_tinst_level above, we don't need to
11879 		     restore these.  */
11880 		  input_location = DECL_SOURCE_LOCATION (t);
11881 
11882 		  if (TREE_CODE (t) == TEMPLATE_DECL)
11883 		    ++processing_template_decl;
11884 		  r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
11885 		  if (TREE_CODE (t) == TEMPLATE_DECL)
11886 		    --processing_template_decl;
11887 
11888 		  if (TREE_CODE (r) == TREE_VEC)
11889 		    {
11890 		      /* A capture pack became multiple fields.  */
11891 		      vec = r;
11892 		      len = TREE_VEC_LENGTH (vec);
11893 		    }
11894 
11895 		  for (int i = 0; i < len; ++i)
11896 		    {
11897 		      if (vec)
11898 			r = TREE_VEC_ELT (vec, i);
11899 		      if (VAR_P (r))
11900 			{
11901 			  /* In [temp.inst]:
11902 
11903 			     [t]he initialization (and any associated
11904 			     side-effects) of a static data member does
11905 			     not occur unless the static data member is
11906 			     itself used in a way that requires the
11907 			     definition of the static data member to
11908 			     exist.
11909 
11910 			     Therefore, we do not substitute into the
11911 			     initialized for the static data member here.  */
11912 			  finish_static_data_member_decl
11913 			    (r,
11914 			     /*init=*/NULL_TREE,
11915 			     /*init_const_expr_p=*/false,
11916 			     /*asmspec_tree=*/NULL_TREE,
11917 			     /*flags=*/0);
11918 			  /* Instantiate members marked with attribute used. */
11919 			  if (r != error_mark_node && DECL_PRESERVE_P (r))
11920 			    mark_used (r);
11921 			}
11922 		      else if (TREE_CODE (r) == FIELD_DECL)
11923 			{
11924 			  /* Determine whether R has a valid type and can be
11925 			     completed later.  If R is invalid, then its type
11926 			     is replaced by error_mark_node.  */
11927 			  tree rtype = TREE_TYPE (r);
11928 			  if (can_complete_type_without_circularity (rtype))
11929 			    complete_type (rtype);
11930 
11931 			  if (!complete_or_array_type_p (rtype))
11932 			    {
11933 			      /* If R's type couldn't be completed and
11934 				 it isn't a flexible array member (whose
11935 				 type is incomplete by definition) give
11936 				 an error.  */
11937 			      cxx_incomplete_type_error (r, rtype);
11938 			      TREE_TYPE (r) = error_mark_node;
11939 			    }
11940 			  else if (TREE_CODE (rtype) == ARRAY_TYPE
11941 				   && TYPE_DOMAIN (rtype) == NULL_TREE
11942 				   && (TREE_CODE (type) == UNION_TYPE
11943 				       || TREE_CODE (type) == QUAL_UNION_TYPE))
11944 			    {
11945 			      error ("flexible array member %qD in union", r);
11946 			      TREE_TYPE (r) = error_mark_node;
11947 			    }
11948 			  else if (!verify_type_context (input_location,
11949 							 TCTX_FIELD, rtype))
11950 			    TREE_TYPE (r) = error_mark_node;
11951 			}
11952 
11953 		      /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
11954 			 such a thing will already have been added to the field
11955 			 list by tsubst_enum in finish_member_declaration in the
11956 			 CLASSTYPE_NESTED_UTDS case above.  */
11957 		      if (!(TREE_CODE (r) == TYPE_DECL
11958 			    && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
11959 			    && DECL_ARTIFICIAL (r)))
11960 			{
11961 			  set_current_access_from_decl (r);
11962 			  finish_member_declaration (r);
11963 			}
11964 		    }
11965 		}
11966 	    }
11967 	}
11968       else
11969 	{
11970 	  if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
11971 	      || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11972 	    {
11973 	      /* Build new CLASSTYPE_FRIEND_CLASSES.  */
11974 
11975 	      tree friend_type = t;
11976 	      bool adjust_processing_template_decl = false;
11977 
11978 	      if (TREE_CODE (friend_type) == TEMPLATE_DECL)
11979 		{
11980 		  /* template <class T> friend class C;  */
11981 		  friend_type = tsubst_friend_class (friend_type, args);
11982 		  adjust_processing_template_decl = true;
11983 		}
11984 	      else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
11985 		{
11986 		  /* template <class T> friend class C::D;  */
11987 		  friend_type = tsubst (friend_type, args,
11988 					tf_warning_or_error, NULL_TREE);
11989 		  if (TREE_CODE (friend_type) == TEMPLATE_DECL)
11990 		    friend_type = TREE_TYPE (friend_type);
11991 		  adjust_processing_template_decl = true;
11992 		}
11993 	      else if (TREE_CODE (friend_type) == TYPENAME_TYPE
11994 		       || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
11995 		{
11996 		  /* This could be either
11997 
11998 		       friend class T::C;
11999 
12000 		     when dependent_type_p is false or
12001 
12002 		       template <class U> friend class T::C;
12003 
12004 		     otherwise.  */
12005 		  /* Bump processing_template_decl in case this is something like
12006 		     template <class T> friend struct A<T>::B.  */
12007 		  ++processing_template_decl;
12008 		  friend_type = tsubst (friend_type, args,
12009 					tf_warning_or_error, NULL_TREE);
12010 		  if (dependent_type_p (friend_type))
12011 		    adjust_processing_template_decl = true;
12012 		  --processing_template_decl;
12013 		}
12014 	      else if (TREE_CODE (friend_type) != BOUND_TEMPLATE_TEMPLATE_PARM
12015 		       && !CLASSTYPE_USE_TEMPLATE (friend_type)
12016 		       && TYPE_HIDDEN_P (friend_type))
12017 		{
12018 		  /* friend class C;
12019 
12020 		     where C hasn't been declared yet.  Let's lookup name
12021 		     from namespace scope directly, bypassing any name that
12022 		     come from dependent base class.  */
12023 		  tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
12024 
12025 		  /* The call to xref_tag_from_type does injection for friend
12026 		     classes.  */
12027 		  push_nested_namespace (ns);
12028 		  friend_type =
12029 		    xref_tag_from_type (friend_type, NULL_TREE,
12030 					/*tag_scope=*/ts_current);
12031 		  pop_nested_namespace (ns);
12032 		}
12033 	      else if (uses_template_parms (friend_type))
12034 		/* friend class C<T>;  */
12035 		friend_type = tsubst (friend_type, args,
12036 				      tf_warning_or_error, NULL_TREE);
12037 	      /* Otherwise it's
12038 
12039 		   friend class C;
12040 
12041 		 where C is already declared or
12042 
12043 		   friend class C<int>;
12044 
12045 		 We don't have to do anything in these cases.  */
12046 
12047 	      if (adjust_processing_template_decl)
12048 		/* Trick make_friend_class into realizing that the friend
12049 		   we're adding is a template, not an ordinary class.  It's
12050 		   important that we use make_friend_class since it will
12051 		   perform some error-checking and output cross-reference
12052 		   information.  */
12053 		++processing_template_decl;
12054 
12055 	      if (friend_type != error_mark_node)
12056 		make_friend_class (type, friend_type, /*complain=*/false);
12057 
12058 	      if (adjust_processing_template_decl)
12059 		--processing_template_decl;
12060 	    }
12061 	  else
12062 	    {
12063 	      /* Build new DECL_FRIENDLIST.  */
12064 	      tree r;
12065 
12066 	      /* The file and line for this declaration, to
12067 		 assist in error message reporting.  Since we
12068 		 called push_tinst_level above, we don't need to
12069 		 restore these.  */
12070 	      input_location = DECL_SOURCE_LOCATION (t);
12071 
12072 	      if (TREE_CODE (t) == TEMPLATE_DECL)
12073 		{
12074 		  ++processing_template_decl;
12075 		  push_deferring_access_checks (dk_no_check);
12076 		}
12077 
12078 	      r = tsubst_friend_function (t, args);
12079 	      add_friend (type, r, /*complain=*/false);
12080 	      if (TREE_CODE (t) == TEMPLATE_DECL)
12081 		{
12082 		  pop_deferring_access_checks ();
12083 		  --processing_template_decl;
12084 		}
12085 	    }
12086 	}
12087     }
12088 
12089   if (fn_context)
12090     {
12091       /* Restore these before substituting into the lambda capture
12092 	 initializers.  */
12093       cp_unevaluated_operand = saved_unevaluated_operand;
12094       c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
12095     }
12096 
12097   /* Set the file and line number information to whatever is given for
12098      the class itself.  This puts error messages involving generated
12099      implicit functions at a predictable point, and the same point
12100      that would be used for non-template classes.  */
12101   input_location = DECL_SOURCE_LOCATION (typedecl);
12102 
12103   unreverse_member_declarations (type);
12104   finish_struct_1 (type);
12105   TYPE_BEING_DEFINED (type) = 0;
12106 
12107   /* We don't instantiate default arguments for member functions.  14.7.1:
12108 
12109      The implicit instantiation of a class template specialization causes
12110      the implicit instantiation of the declarations, but not of the
12111      definitions or default arguments, of the class member functions,
12112      member classes, static data members and member templates....  */
12113 
12114   /* Some typedefs referenced from within the template code need to be access
12115      checked at template instantiation time, i.e now. These types were
12116      added to the template at parsing time. Let's get those and perform
12117      the access checks then.  */
12118   perform_typedefs_access_check (pattern, args);
12119   perform_deferred_access_checks (tf_warning_or_error);
12120   pop_nested_class ();
12121   maximum_field_alignment = saved_maximum_field_alignment;
12122   if (!fn_context)
12123     pop_from_top_level ();
12124   pop_tinst_level ();
12125 
12126   /* The vtable for a template class can be emitted in any translation
12127      unit in which the class is instantiated.  When there is no key
12128      method, however, finish_struct_1 will already have added TYPE to
12129      the keyed_classes.  */
12130   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
12131     vec_safe_push (keyed_classes, type);
12132 
12133   return type;
12134 }
12135 
12136 /* Wrapper for instantiate_class_template_1.  */
12137 
12138 tree
instantiate_class_template(tree type)12139 instantiate_class_template (tree type)
12140 {
12141   tree ret;
12142   timevar_push (TV_TEMPLATE_INST);
12143   ret = instantiate_class_template_1 (type);
12144   timevar_pop (TV_TEMPLATE_INST);
12145   return ret;
12146 }
12147 
12148 tree
tsubst_template_arg(tree t,tree args,tsubst_flags_t complain,tree in_decl)12149 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12150 {
12151   tree r;
12152 
12153   if (!t)
12154     r = t;
12155   else if (TYPE_P (t))
12156     r = tsubst (t, args, complain, in_decl);
12157   else
12158     {
12159       if (!(complain & tf_warning))
12160 	++c_inhibit_evaluation_warnings;
12161       r = tsubst_expr (t, args, complain, in_decl,
12162 		       /*integral_constant_expression_p=*/true);
12163       if (!(complain & tf_warning))
12164 	--c_inhibit_evaluation_warnings;
12165     }
12166 
12167   return r;
12168 }
12169 
12170 /* Given a function parameter pack TMPL_PARM and some function parameters
12171    instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
12172    and set *SPEC_P to point at the next point in the list.  */
12173 
12174 tree
extract_fnparm_pack(tree tmpl_parm,tree * spec_p)12175 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
12176 {
12177   /* Collect all of the extra "packed" parameters into an
12178      argument pack.  */
12179   tree argpack;
12180   tree spec_parm = *spec_p;
12181   int len;
12182 
12183   for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
12184     if (tmpl_parm
12185 	&& !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
12186       break;
12187 
12188   spec_parm = *spec_p;
12189   if (len == 1 && DECL_PACK_P (spec_parm))
12190     {
12191       /* The instantiation is still a parameter pack; don't wrap it in a
12192 	 NONTYPE_ARGUMENT_PACK.  */
12193       argpack = spec_parm;
12194       spec_parm = DECL_CHAIN (spec_parm);
12195     }
12196   else
12197     {
12198       /* Fill in PARMVEC with all of the parameters.  */
12199       tree parmvec = make_tree_vec (len);
12200       argpack = make_node (NONTYPE_ARGUMENT_PACK);
12201       for (int i = 0; i < len; i++)
12202 	{
12203 	  tree elt = spec_parm;
12204 	  if (DECL_PACK_P (elt))
12205 	    elt = make_pack_expansion (elt);
12206 	  TREE_VEC_ELT (parmvec, i) = elt;
12207 	  spec_parm = DECL_CHAIN (spec_parm);
12208 	}
12209 
12210       /* Build the argument packs.  */
12211       SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
12212     }
12213   *spec_p = spec_parm;
12214 
12215   return argpack;
12216 }
12217 
12218 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
12219    NONTYPE_ARGUMENT_PACK.  */
12220 
12221 static tree
make_fnparm_pack(tree spec_parm)12222 make_fnparm_pack (tree spec_parm)
12223 {
12224   return extract_fnparm_pack (NULL_TREE, &spec_parm);
12225 }
12226 
12227 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
12228    pack expansion with no extra args, 2 if it has extra args, or 0
12229    if it is not a pack expansion.  */
12230 
12231 static int
argument_pack_element_is_expansion_p(tree arg_pack,int i)12232 argument_pack_element_is_expansion_p (tree arg_pack, int i)
12233 {
12234   if (TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12235     /* We're being called before this happens in tsubst_pack_expansion.  */
12236     arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12237   tree vec = ARGUMENT_PACK_ARGS (arg_pack);
12238   if (i >= TREE_VEC_LENGTH (vec))
12239     return 0;
12240   tree elt = TREE_VEC_ELT (vec, i);
12241   if (DECL_P (elt))
12242     /* A decl pack is itself an expansion.  */
12243     elt = TREE_TYPE (elt);
12244   if (!PACK_EXPANSION_P (elt))
12245     return 0;
12246   if (PACK_EXPANSION_EXTRA_ARGS (elt))
12247     return 2;
12248   return 1;
12249 }
12250 
12251 
12252 /* Creates and return an ARGUMENT_PACK_SELECT tree node.  */
12253 
12254 static tree
make_argument_pack_select(tree arg_pack,unsigned index)12255 make_argument_pack_select (tree arg_pack, unsigned index)
12256 {
12257   tree aps = make_node (ARGUMENT_PACK_SELECT);
12258 
12259   ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
12260   ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12261 
12262   return aps;
12263 }
12264 
12265 /*  This is a subroutine of tsubst_pack_expansion.
12266 
12267     It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
12268     mechanism to store the (non complete list of) arguments of the
12269     substitution and return a non substituted pack expansion, in order
12270     to wait for when we have enough arguments to really perform the
12271     substitution.  */
12272 
12273 static bool
use_pack_expansion_extra_args_p(tree parm_packs,int arg_pack_len,bool has_empty_arg)12274 use_pack_expansion_extra_args_p (tree parm_packs,
12275 				 int arg_pack_len,
12276 				 bool has_empty_arg)
12277 {
12278   /* If one pack has an expansion and another pack has a normal
12279      argument or if one pack has an empty argument and an another
12280      one hasn't then tsubst_pack_expansion cannot perform the
12281      substitution and need to fall back on the
12282      PACK_EXPANSION_EXTRA mechanism.  */
12283   if (parm_packs == NULL_TREE)
12284     return false;
12285   else if (has_empty_arg)
12286     {
12287       /* If all the actual packs are pack expansions, we can still
12288 	 subsitute directly.  */
12289       for (tree p = parm_packs; p; p = TREE_CHAIN (p))
12290 	{
12291 	  tree a = TREE_VALUE (p);
12292 	  if (TREE_CODE (a) == ARGUMENT_PACK_SELECT)
12293 	    a = ARGUMENT_PACK_SELECT_FROM_PACK (a);
12294 	  a = ARGUMENT_PACK_ARGS (a);
12295 	  if (TREE_VEC_LENGTH (a) == 1)
12296 	    a = TREE_VEC_ELT (a, 0);
12297 	  if (PACK_EXPANSION_P (a))
12298 	    continue;
12299 	  return true;
12300 	}
12301       return false;
12302     }
12303 
12304   bool has_expansion_arg = false;
12305   for (int i = 0 ; i < arg_pack_len; ++i)
12306     {
12307       bool has_non_expansion_arg = false;
12308       for (tree parm_pack = parm_packs;
12309 	   parm_pack;
12310 	   parm_pack = TREE_CHAIN (parm_pack))
12311 	{
12312 	  tree arg = TREE_VALUE (parm_pack);
12313 
12314 	  int exp = argument_pack_element_is_expansion_p (arg, i);
12315 	  if (exp == 2)
12316 	    /* We can't substitute a pack expansion with extra args into
12317 	       our pattern.  */
12318 	    return true;
12319 	  else if (exp)
12320 	    has_expansion_arg = true;
12321 	  else
12322 	    has_non_expansion_arg = true;
12323 	}
12324 
12325       if (has_expansion_arg && has_non_expansion_arg)
12326 	return true;
12327     }
12328   return false;
12329 }
12330 
12331 /* [temp.variadic]/6 says that:
12332 
12333        The instantiation of a pack expansion [...]
12334        produces a list E1,E2, ..., En, where N is the number of elements
12335        in the pack expansion parameters.
12336 
12337    This subroutine of tsubst_pack_expansion produces one of these Ei.
12338 
12339    PATTERN is the pattern of the pack expansion.  PARM_PACKS is a
12340    TREE_LIST in which each TREE_PURPOSE is a parameter pack of
12341    PATTERN, and each TREE_VALUE is its corresponding argument pack.
12342    INDEX is the index 'i' of the element Ei to produce.  ARGS,
12343    COMPLAIN, and IN_DECL are the same parameters as for the
12344    tsubst_pack_expansion function.
12345 
12346    The function returns the resulting Ei upon successful completion,
12347    or error_mark_node.
12348 
12349    Note that this function possibly modifies the ARGS parameter, so
12350    it's the responsibility of the caller to restore it.  */
12351 
12352 static tree
gen_elem_of_pack_expansion_instantiation(tree pattern,tree parm_packs,unsigned index,tree args,tsubst_flags_t complain,tree in_decl)12353 gen_elem_of_pack_expansion_instantiation (tree pattern,
12354 					  tree parm_packs,
12355 					  unsigned index,
12356 					  tree args /* This parm gets
12357 						       modified.  */,
12358 					  tsubst_flags_t complain,
12359 					  tree in_decl)
12360 {
12361   tree t;
12362   bool ith_elem_is_expansion = false;
12363 
12364   /* For each parameter pack, change the substitution of the parameter
12365      pack to the ith argument in its argument pack, then expand the
12366      pattern.  */
12367   for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
12368     {
12369       tree parm = TREE_PURPOSE (pack);
12370       tree arg_pack = TREE_VALUE (pack);
12371       tree aps;			/* instance of ARGUMENT_PACK_SELECT.  */
12372 
12373       ith_elem_is_expansion |=
12374 	argument_pack_element_is_expansion_p (arg_pack, index);
12375 
12376       /* Select the Ith argument from the pack.  */
12377       if (TREE_CODE (parm) == PARM_DECL
12378 	  || VAR_P (parm)
12379 	  || TREE_CODE (parm) == FIELD_DECL)
12380 	{
12381 	  if (index == 0)
12382 	    {
12383 	      aps = make_argument_pack_select (arg_pack, index);
12384 	      if (!mark_used (parm, complain) && !(complain & tf_error))
12385 		return error_mark_node;
12386 	      register_local_specialization (aps, parm);
12387 	    }
12388 	  else
12389 	    aps = retrieve_local_specialization (parm);
12390 	}
12391       else
12392 	{
12393 	  int idx, level;
12394 	  template_parm_level_and_index (parm, &level, &idx);
12395 
12396 	  if (index == 0)
12397 	    {
12398 	      aps = make_argument_pack_select (arg_pack, index);
12399 	      /* Update the corresponding argument.  */
12400 	      TMPL_ARG (args, level, idx) = aps;
12401 	    }
12402 	  else
12403 	    /* Re-use the ARGUMENT_PACK_SELECT.  */
12404 	    aps = TMPL_ARG (args, level, idx);
12405 	}
12406       ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12407     }
12408 
12409   /* Substitute into the PATTERN with the (possibly altered)
12410      arguments.  */
12411   if (pattern == in_decl)
12412     /* Expanding a fixed parameter pack from
12413        coerce_template_parameter_pack.  */
12414     t = tsubst_decl (pattern, args, complain);
12415   else if (pattern == error_mark_node)
12416     t = error_mark_node;
12417   else if (!TYPE_P (pattern))
12418     t = tsubst_expr (pattern, args, complain, in_decl,
12419 		     /*integral_constant_expression_p=*/false);
12420   else
12421     t = tsubst (pattern, args, complain, in_decl);
12422 
12423   /*  If the Ith argument pack element is a pack expansion, then
12424       the Ith element resulting from the substituting is going to
12425       be a pack expansion as well.  */
12426   if (ith_elem_is_expansion)
12427     t = make_pack_expansion (t, complain);
12428 
12429   return t;
12430 }
12431 
12432 /* When the unexpanded parameter pack in a fold expression expands to an empty
12433    sequence, the value of the expression is as follows; the program is
12434    ill-formed if the operator is not listed in this table.
12435 
12436    &&	true
12437    ||	false
12438    ,	void()  */
12439 
12440 tree
expand_empty_fold(tree t,tsubst_flags_t complain)12441 expand_empty_fold (tree t, tsubst_flags_t complain)
12442 {
12443   tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
12444   if (!FOLD_EXPR_MODIFY_P (t))
12445     switch (code)
12446       {
12447       case TRUTH_ANDIF_EXPR:
12448 	return boolean_true_node;
12449       case TRUTH_ORIF_EXPR:
12450 	return boolean_false_node;
12451       case COMPOUND_EXPR:
12452 	return void_node;
12453       default:
12454 	break;
12455       }
12456 
12457   if (complain & tf_error)
12458     error_at (location_of (t),
12459 	      "fold of empty expansion over %O", code);
12460   return error_mark_node;
12461 }
12462 
12463 /* Given a fold-expression T and a current LEFT and RIGHT operand,
12464    form an expression that combines the two terms using the
12465    operator of T. */
12466 
12467 static tree
fold_expression(tree t,tree left,tree right,tsubst_flags_t complain)12468 fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
12469 {
12470   tree op = FOLD_EXPR_OP (t);
12471   tree_code code = (tree_code)TREE_INT_CST_LOW (op);
12472 
12473   // Handle compound assignment operators.
12474   if (FOLD_EXPR_MODIFY_P (t))
12475     return build_x_modify_expr (input_location, left, code, right, complain);
12476 
12477   warning_sentinel s(warn_parentheses);
12478   switch (code)
12479     {
12480     case COMPOUND_EXPR:
12481       return build_x_compound_expr (input_location, left, right, complain);
12482     default:
12483       return build_x_binary_op (input_location, code,
12484                                 left, TREE_CODE (left),
12485                                 right, TREE_CODE (right),
12486                                 /*overload=*/NULL,
12487                                 complain);
12488     }
12489 }
12490 
12491 /* Substitute ARGS into the pack of a fold expression T. */
12492 
12493 static inline tree
tsubst_fold_expr_pack(tree t,tree args,tsubst_flags_t complain,tree in_decl)12494 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12495 {
12496   return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
12497 }
12498 
12499 /* Substitute ARGS into the pack of a fold expression T. */
12500 
12501 static inline tree
tsubst_fold_expr_init(tree t,tree args,tsubst_flags_t complain,tree in_decl)12502 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12503 {
12504   return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl, false);
12505 }
12506 
12507 /* Expand a PACK of arguments into a grouped as left fold.
12508    Given a pack containing elements A0, A1, ..., An and an
12509    operator @, this builds the expression:
12510 
12511       ((A0 @ A1) @ A2) ... @ An
12512 
12513    Note that PACK must not be empty.
12514 
12515    The operator is defined by the original fold expression T. */
12516 
12517 static tree
expand_left_fold(tree t,tree pack,tsubst_flags_t complain)12518 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
12519 {
12520   tree left = TREE_VEC_ELT (pack, 0);
12521   for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
12522     {
12523       tree right = TREE_VEC_ELT (pack, i);
12524       left = fold_expression (t, left, right, complain);
12525     }
12526   return left;
12527 }
12528 
12529 /* Substitute into a unary left fold expression. */
12530 
12531 static tree
tsubst_unary_left_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)12532 tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
12533                         tree in_decl)
12534 {
12535   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12536   if (pack == error_mark_node)
12537     return error_mark_node;
12538   if (PACK_EXPANSION_P (pack))
12539     {
12540       tree r = copy_node (t);
12541       FOLD_EXPR_PACK (r) = pack;
12542       return r;
12543     }
12544   if (TREE_VEC_LENGTH (pack) == 0)
12545     return expand_empty_fold (t, complain);
12546   else
12547     return expand_left_fold (t, pack, complain);
12548 }
12549 
12550 /* Substitute into a binary left fold expression.
12551 
12552    Do ths by building a single (non-empty) vector of argumnts and
12553    building the expression from those elements. */
12554 
12555 static tree
tsubst_binary_left_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)12556 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
12557                          tree in_decl)
12558 {
12559   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12560   if (pack == error_mark_node)
12561     return error_mark_node;
12562   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
12563   if (init == error_mark_node)
12564     return error_mark_node;
12565 
12566   if (PACK_EXPANSION_P (pack))
12567     {
12568       tree r = copy_node (t);
12569       FOLD_EXPR_PACK (r) = pack;
12570       FOLD_EXPR_INIT (r) = init;
12571       return r;
12572     }
12573 
12574   tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
12575   TREE_VEC_ELT (vec, 0) = init;
12576   for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
12577     TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
12578 
12579   return expand_left_fold (t, vec, complain);
12580 }
12581 
12582 /* Expand a PACK of arguments into a grouped as right fold.
12583    Given a pack containing elementns A0, A1, ..., and an
12584    operator @, this builds the expression:
12585 
12586       A0@ ... (An-2 @ (An-1 @ An))
12587 
12588    Note that PACK must not be empty.
12589 
12590    The operator is defined by the original fold expression T. */
12591 
12592 tree
expand_right_fold(tree t,tree pack,tsubst_flags_t complain)12593 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
12594 {
12595   // Build the expression.
12596   int n = TREE_VEC_LENGTH (pack);
12597   tree right = TREE_VEC_ELT (pack, n - 1);
12598   for (--n; n != 0; --n)
12599     {
12600       tree left = TREE_VEC_ELT (pack, n - 1);
12601       right = fold_expression (t, left, right, complain);
12602     }
12603   return right;
12604 }
12605 
12606 /* Substitute into a unary right fold expression. */
12607 
12608 static tree
tsubst_unary_right_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)12609 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
12610                          tree in_decl)
12611 {
12612   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12613   if (pack == error_mark_node)
12614     return error_mark_node;
12615   if (PACK_EXPANSION_P (pack))
12616     {
12617       tree r = copy_node (t);
12618       FOLD_EXPR_PACK (r) = pack;
12619       return r;
12620     }
12621   if (TREE_VEC_LENGTH (pack) == 0)
12622     return expand_empty_fold (t, complain);
12623   else
12624     return expand_right_fold (t, pack, complain);
12625 }
12626 
12627 /* Substitute into a binary right fold expression.
12628 
12629    Do ths by building a single (non-empty) vector of arguments and
12630    building the expression from those elements. */
12631 
12632 static tree
tsubst_binary_right_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)12633 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
12634                          tree in_decl)
12635 {
12636   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12637   if (pack == error_mark_node)
12638     return error_mark_node;
12639   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
12640   if (init == error_mark_node)
12641     return error_mark_node;
12642 
12643   if (PACK_EXPANSION_P (pack))
12644     {
12645       tree r = copy_node (t);
12646       FOLD_EXPR_PACK (r) = pack;
12647       FOLD_EXPR_INIT (r) = init;
12648       return r;
12649     }
12650 
12651   int n = TREE_VEC_LENGTH (pack);
12652   tree vec = make_tree_vec (n + 1);
12653   for (int i = 0; i < n; ++i)
12654     TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
12655   TREE_VEC_ELT (vec, n) = init;
12656 
12657   return expand_right_fold (t, vec, complain);
12658 }
12659 
12660 /* Walk through the pattern of a pack expansion, adding everything in
12661    local_specializations to a list.  */
12662 
12663 class el_data
12664 {
12665 public:
12666   hash_set<tree> internal;
12667   tree extra;
12668   tsubst_flags_t complain;
12669 
el_data(tsubst_flags_t c)12670   el_data (tsubst_flags_t c)
12671     : extra (NULL_TREE), complain (c) {}
12672 };
12673 static tree
extract_locals_r(tree * tp,int *,void * data_)12674 extract_locals_r (tree *tp, int */*walk_subtrees*/, void *data_)
12675 {
12676   el_data &data = *reinterpret_cast<el_data*>(data_);
12677   tree *extra = &data.extra;
12678   tsubst_flags_t complain = data.complain;
12679 
12680   if (TYPE_P (*tp) && typedef_variant_p (*tp))
12681     /* Remember local typedefs (85214).  */
12682     tp = &TYPE_NAME (*tp);
12683 
12684   if (TREE_CODE (*tp) == DECL_EXPR)
12685     data.internal.add (DECL_EXPR_DECL (*tp));
12686   else if (tree spec = retrieve_local_specialization (*tp))
12687     {
12688       if (data.internal.contains (*tp))
12689 	/* Don't mess with variables declared within the pattern.  */
12690 	return NULL_TREE;
12691       if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
12692 	{
12693 	  /* Maybe pull out the PARM_DECL for a partial instantiation.  */
12694 	  tree args = ARGUMENT_PACK_ARGS (spec);
12695 	  if (TREE_VEC_LENGTH (args) == 1)
12696 	    {
12697 	      tree elt = TREE_VEC_ELT (args, 0);
12698 	      if (PACK_EXPANSION_P (elt))
12699 		elt = PACK_EXPANSION_PATTERN (elt);
12700 	      if (DECL_PACK_P (elt))
12701 		spec = elt;
12702 	    }
12703 	  if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
12704 	    {
12705 	      /* Handle lambda capture here, since we aren't doing any
12706 		 substitution now, and so tsubst_copy won't call
12707 		 process_outer_var_ref.  */
12708 	      tree args = ARGUMENT_PACK_ARGS (spec);
12709 	      int len = TREE_VEC_LENGTH (args);
12710 	      for (int i = 0; i < len; ++i)
12711 		{
12712 		  tree arg = TREE_VEC_ELT (args, i);
12713 		  tree carg = arg;
12714 		  if (outer_automatic_var_p (arg))
12715 		    carg = process_outer_var_ref (arg, complain);
12716 		  if (carg != arg)
12717 		    {
12718 		      /* Make a new NONTYPE_ARGUMENT_PACK of the capture
12719 			 proxies.  */
12720 		      if (i == 0)
12721 			{
12722 			  spec = copy_node (spec);
12723 			  args = copy_node (args);
12724 			  SET_ARGUMENT_PACK_ARGS (spec, args);
12725 			  register_local_specialization (spec, *tp);
12726 			}
12727 		      TREE_VEC_ELT (args, i) = carg;
12728 		    }
12729 		}
12730 	    }
12731 	}
12732       if (outer_automatic_var_p (spec))
12733 	spec = process_outer_var_ref (spec, complain);
12734       *extra = tree_cons (*tp, spec, *extra);
12735     }
12736   return NULL_TREE;
12737 }
12738 static tree
extract_local_specs(tree pattern,tsubst_flags_t complain)12739 extract_local_specs (tree pattern, tsubst_flags_t complain)
12740 {
12741   el_data data (complain);
12742   cp_walk_tree_without_duplicates (&pattern, extract_locals_r, &data);
12743   return data.extra;
12744 }
12745 
12746 /* Extract any uses of local_specializations from PATTERN and add them to ARGS
12747    for use in PACK_EXPANSION_EXTRA_ARGS.  */
12748 
12749 tree
build_extra_args(tree pattern,tree args,tsubst_flags_t complain)12750 build_extra_args (tree pattern, tree args, tsubst_flags_t complain)
12751 {
12752   tree extra = args;
12753   if (local_specializations)
12754     if (tree locals = extract_local_specs (pattern, complain))
12755       extra = tree_cons (NULL_TREE, extra, locals);
12756   return extra;
12757 }
12758 
12759 /* Apply any local specializations from PACK_EXPANSION_EXTRA_ARGS and add the
12760    normal template args to ARGS.  */
12761 
12762 tree
add_extra_args(tree extra,tree args)12763 add_extra_args (tree extra, tree args)
12764 {
12765   if (extra && TREE_CODE (extra) == TREE_LIST)
12766     {
12767       for (tree elt = TREE_CHAIN (extra); elt; elt = TREE_CHAIN (elt))
12768 	{
12769 	  /* The partial instantiation involved local declarations collected in
12770 	     extract_local_specs; map from the general template to our local
12771 	     context.  */
12772 	  tree gen = TREE_PURPOSE (elt);
12773 	  tree inst = TREE_VALUE (elt);
12774 	  if (DECL_P (inst))
12775 	    if (tree local = retrieve_local_specialization (inst))
12776 	      inst = local;
12777 	  /* else inst is already a full instantiation of the pack.  */
12778 	  register_local_specialization (inst, gen);
12779 	}
12780       gcc_assert (!TREE_PURPOSE (extra));
12781       extra = TREE_VALUE (extra);
12782     }
12783 #if 1
12784   /* I think we should always be able to substitute dependent args into the
12785      pattern.  If that turns out to be incorrect in some cases, enable the
12786      alternate code (and add complain/in_decl parms to this function).  */
12787   gcc_checking_assert (!uses_template_parms (extra));
12788 #else
12789   if (!uses_template_parms (extra))
12790     {
12791       gcc_unreachable ();
12792       extra = tsubst_template_args (extra, args, complain, in_decl);
12793       args = add_outermost_template_args (args, extra);
12794     }
12795   else
12796 #endif
12797     args = add_to_template_args (extra, args);
12798   return args;
12799 }
12800 
12801 /* Substitute ARGS into T, which is an pack expansion
12802    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
12803    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
12804    (if only a partial substitution could be performed) or
12805    ERROR_MARK_NODE if there was an error.  */
12806 tree
tsubst_pack_expansion(tree t,tree args,tsubst_flags_t complain,tree in_decl)12807 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
12808 		       tree in_decl)
12809 {
12810   tree pattern;
12811   tree pack, packs = NULL_TREE;
12812   bool unsubstituted_packs = false;
12813   int i, len = -1;
12814   tree result;
12815   bool need_local_specializations = false;
12816   int levels;
12817 
12818   gcc_assert (PACK_EXPANSION_P (t));
12819   pattern = PACK_EXPANSION_PATTERN (t);
12820 
12821   /* Add in any args remembered from an earlier partial instantiation.  */
12822   args = add_extra_args (PACK_EXPANSION_EXTRA_ARGS (t), args);
12823 
12824   levels = TMPL_ARGS_DEPTH (args);
12825 
12826   /* Determine the argument packs that will instantiate the parameter
12827      packs used in the expansion expression. While we're at it,
12828      compute the number of arguments to be expanded and make sure it
12829      is consistent.  */
12830   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
12831        pack = TREE_CHAIN (pack))
12832     {
12833       tree parm_pack = TREE_VALUE (pack);
12834       tree arg_pack = NULL_TREE;
12835       tree orig_arg = NULL_TREE;
12836       int level = 0;
12837 
12838       if (TREE_CODE (parm_pack) == BASES)
12839 	{
12840 	  gcc_assert (parm_pack == pattern);
12841 	  if (BASES_DIRECT (parm_pack))
12842 	    return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
12843 							args, complain,
12844 							in_decl, false),
12845 					   complain);
12846 	  else
12847 	    return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
12848 						 args, complain, in_decl,
12849 						 false), complain);
12850 	}
12851       else if (builtin_pack_call_p (parm_pack))
12852 	{
12853 	  if (parm_pack != pattern)
12854 	    {
12855 	      if (complain & tf_error)
12856 		sorry ("%qE is not the entire pattern of the pack expansion",
12857 		       parm_pack);
12858 	      return error_mark_node;
12859 	    }
12860 	  return expand_builtin_pack_call (parm_pack, args,
12861 					   complain, in_decl);
12862 	}
12863       else if (TREE_CODE (parm_pack) == PARM_DECL)
12864 	{
12865 	  /* We know we have correct local_specializations if this
12866 	     expansion is at function scope, or if we're dealing with a
12867 	     local parameter in a requires expression; for the latter,
12868 	     tsubst_requires_expr set it up appropriately.  */
12869 	  if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
12870 	    arg_pack = retrieve_local_specialization (parm_pack);
12871 	  else
12872 	    /* We can't rely on local_specializations for a parameter
12873 	       name used later in a function declaration (such as in a
12874 	       late-specified return type).  Even if it exists, it might
12875 	       have the wrong value for a recursive call.  */
12876 	    need_local_specializations = true;
12877 
12878 	  if (!arg_pack)
12879 	    {
12880 	      /* This parameter pack was used in an unevaluated context.  Just
12881 		 make a dummy decl, since it's only used for its type.  */
12882 	      ++cp_unevaluated_operand;
12883 	      arg_pack = tsubst_decl (parm_pack, args, complain);
12884 	      --cp_unevaluated_operand;
12885 	      if (arg_pack && DECL_PACK_P (arg_pack))
12886 		/* Partial instantiation of the parm_pack, we can't build
12887 		   up an argument pack yet.  */
12888 		arg_pack = NULL_TREE;
12889 	      else
12890 		arg_pack = make_fnparm_pack (arg_pack);
12891 	    }
12892 	  else if (DECL_PACK_P (arg_pack))
12893 	    /* This argument pack isn't fully instantiated yet.  */
12894 	    arg_pack = NULL_TREE;
12895 	}
12896       else if (is_capture_proxy (parm_pack))
12897 	{
12898 	  arg_pack = retrieve_local_specialization (parm_pack);
12899 	  if (DECL_PACK_P (arg_pack))
12900 	    arg_pack = NULL_TREE;
12901 	}
12902       else
12903         {
12904 	  int idx;
12905           template_parm_level_and_index (parm_pack, &level, &idx);
12906           if (level <= levels)
12907             arg_pack = TMPL_ARG (args, level, idx);
12908 
12909 	  if (arg_pack && TREE_CODE (arg_pack) == TEMPLATE_TYPE_PARM
12910 	      && TEMPLATE_TYPE_PARAMETER_PACK (arg_pack))
12911 	    arg_pack = NULL_TREE;
12912         }
12913 
12914       orig_arg = arg_pack;
12915       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12916 	arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12917 
12918       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
12919 	/* This can only happen if we forget to expand an argument
12920 	   pack somewhere else. Just return an error, silently.  */
12921 	{
12922 	  result = make_tree_vec (1);
12923 	  TREE_VEC_ELT (result, 0) = error_mark_node;
12924 	  return result;
12925 	}
12926 
12927       if (arg_pack)
12928         {
12929           int my_len =
12930             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
12931 
12932 	  /* Don't bother trying to do a partial substitution with
12933 	     incomplete packs; we'll try again after deduction.  */
12934           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
12935             return t;
12936 
12937           if (len < 0)
12938 	    len = my_len;
12939 	  else if (len != my_len)
12940             {
12941 	      if (!(complain & tf_error))
12942 		/* Fail quietly.  */;
12943               else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
12944                 error ("mismatched argument pack lengths while expanding %qT",
12945                        pattern);
12946               else
12947                 error ("mismatched argument pack lengths while expanding %qE",
12948                        pattern);
12949               return error_mark_node;
12950             }
12951 
12952           /* Keep track of the parameter packs and their corresponding
12953              argument packs.  */
12954           packs = tree_cons (parm_pack, arg_pack, packs);
12955           TREE_TYPE (packs) = orig_arg;
12956         }
12957       else
12958 	{
12959 	  /* We can't substitute for this parameter pack.  We use a flag as
12960 	     well as the missing_level counter because function parameter
12961 	     packs don't have a level.  */
12962 	  gcc_assert (processing_template_decl || is_auto (parm_pack));
12963 	  unsubstituted_packs = true;
12964 	}
12965     }
12966 
12967   /* If the expansion is just T..., return the matching argument pack, unless
12968      we need to call convert_from_reference on all the elements.  This is an
12969      important optimization; see c++/68422.  */
12970   if (!unsubstituted_packs
12971       && TREE_PURPOSE (packs) == pattern)
12972     {
12973       tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
12974 
12975       /* If the argument pack is a single pack expansion, pull it out.  */
12976       if (TREE_VEC_LENGTH (args) == 1
12977 	  && pack_expansion_args_count (args))
12978 	return TREE_VEC_ELT (args, 0);
12979 
12980       /* Types need no adjustment, nor does sizeof..., and if we still have
12981 	 some pack expansion args we won't do anything yet.  */
12982       if (TREE_CODE (t) == TYPE_PACK_EXPANSION
12983 	  || PACK_EXPANSION_SIZEOF_P (t)
12984 	  || pack_expansion_args_count (args))
12985 	return args;
12986       /* Also optimize expression pack expansions if we can tell that the
12987 	 elements won't have reference type.  */
12988       tree type = TREE_TYPE (pattern);
12989       if (type && !TYPE_REF_P (type)
12990 	  && !PACK_EXPANSION_P (type)
12991 	  && !WILDCARD_TYPE_P (type))
12992 	return args;
12993       /* Otherwise use the normal path so we get convert_from_reference.  */
12994     }
12995 
12996   /* We cannot expand this expansion expression, because we don't have
12997      all of the argument packs we need.  */
12998   if (use_pack_expansion_extra_args_p (packs, len, unsubstituted_packs))
12999     {
13000       /* We got some full packs, but we can't substitute them in until we
13001 	 have values for all the packs.  So remember these until then.  */
13002 
13003       t = make_pack_expansion (pattern, complain);
13004       PACK_EXPANSION_EXTRA_ARGS (t)
13005 	= build_extra_args (pattern, args, complain);
13006       return t;
13007     }
13008 
13009   /* If NEED_LOCAL_SPECIALIZATIONS then we're in a late-specified return
13010      type, so create our own local specializations map; the current map is
13011      either NULL or (in the case of recursive unification) might have
13012      bindings that we don't want to use or alter.  */
13013   local_specialization_stack lss (need_local_specializations
13014 				  ? lss_blank : lss_nop);
13015 
13016   if (unsubstituted_packs)
13017     {
13018       /* There were no real arguments, we're just replacing a parameter
13019 	 pack with another version of itself. Substitute into the
13020 	 pattern and return a PACK_EXPANSION_*. The caller will need to
13021 	 deal with that.  */
13022       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
13023 	t = tsubst_expr (pattern, args, complain, in_decl,
13024 			 /*integral_constant_expression_p=*/false);
13025       else
13026 	t = tsubst (pattern, args, complain, in_decl);
13027       t = make_pack_expansion (t, complain);
13028       return t;
13029     }
13030 
13031   gcc_assert (len >= 0);
13032 
13033   /* For each argument in each argument pack, substitute into the
13034      pattern.  */
13035   result = make_tree_vec (len);
13036   tree elem_args = copy_template_args (args);
13037   for (i = 0; i < len; ++i)
13038     {
13039       t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
13040 						    i,
13041 						    elem_args, complain,
13042 						    in_decl);
13043       TREE_VEC_ELT (result, i) = t;
13044       if (t == error_mark_node)
13045 	{
13046 	  result = error_mark_node;
13047 	  break;
13048 	}
13049     }
13050 
13051   /* Update ARGS to restore the substitution from parameter packs to
13052      their argument packs.  */
13053   for (pack = packs; pack; pack = TREE_CHAIN (pack))
13054     {
13055       tree parm = TREE_PURPOSE (pack);
13056 
13057       if (TREE_CODE (parm) == PARM_DECL
13058 	  || VAR_P (parm)
13059 	  || TREE_CODE (parm) == FIELD_DECL)
13060         register_local_specialization (TREE_TYPE (pack), parm);
13061       else
13062         {
13063           int idx, level;
13064 
13065 	  if (TREE_VALUE (pack) == NULL_TREE)
13066 	    continue;
13067 
13068           template_parm_level_and_index (parm, &level, &idx);
13069 
13070           /* Update the corresponding argument.  */
13071           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
13072             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
13073               TREE_TYPE (pack);
13074           else
13075             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
13076         }
13077     }
13078 
13079   /* If the dependent pack arguments were such that we end up with only a
13080      single pack expansion again, there's no need to keep it in a TREE_VEC.  */
13081   if (len == 1 && TREE_CODE (result) == TREE_VEC
13082       && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
13083     return TREE_VEC_ELT (result, 0);
13084 
13085   return result;
13086 }
13087 
13088 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
13089    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
13090    parameter packs; all parms generated from a function parameter pack will
13091    have the same DECL_PARM_INDEX.  */
13092 
13093 tree
get_pattern_parm(tree parm,tree tmpl)13094 get_pattern_parm (tree parm, tree tmpl)
13095 {
13096   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
13097   tree patparm;
13098 
13099   if (DECL_ARTIFICIAL (parm))
13100     {
13101       for (patparm = DECL_ARGUMENTS (pattern);
13102 	   patparm; patparm = DECL_CHAIN (patparm))
13103 	if (DECL_ARTIFICIAL (patparm)
13104 	    && DECL_NAME (parm) == DECL_NAME (patparm))
13105 	  break;
13106     }
13107   else
13108     {
13109       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
13110       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
13111       gcc_assert (DECL_PARM_INDEX (patparm)
13112 		  == DECL_PARM_INDEX (parm));
13113     }
13114 
13115   return patparm;
13116 }
13117 
13118 /* Make an argument pack out of the TREE_VEC VEC.  */
13119 
13120 static tree
make_argument_pack(tree vec)13121 make_argument_pack (tree vec)
13122 {
13123   tree pack;
13124   tree elt = TREE_VEC_ELT (vec, 0);
13125   if (TYPE_P (elt))
13126     pack = cxx_make_type (TYPE_ARGUMENT_PACK);
13127   else
13128     {
13129       pack = make_node (NONTYPE_ARGUMENT_PACK);
13130       TREE_CONSTANT (pack) = 1;
13131     }
13132   SET_ARGUMENT_PACK_ARGS (pack, vec);
13133   return pack;
13134 }
13135 
13136 /* Return an exact copy of template args T that can be modified
13137    independently.  */
13138 
13139 static tree
copy_template_args(tree t)13140 copy_template_args (tree t)
13141 {
13142   if (t == error_mark_node)
13143     return t;
13144 
13145   int len = TREE_VEC_LENGTH (t);
13146   tree new_vec = make_tree_vec (len);
13147 
13148   for (int i = 0; i < len; ++i)
13149     {
13150       tree elt = TREE_VEC_ELT (t, i);
13151       if (elt && TREE_CODE (elt) == TREE_VEC)
13152 	elt = copy_template_args (elt);
13153       TREE_VEC_ELT (new_vec, i) = elt;
13154     }
13155 
13156   NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
13157     = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13158 
13159   return new_vec;
13160 }
13161 
13162 /* Substitute ARGS into the *_ARGUMENT_PACK orig_arg.  */
13163 
13164 tree
tsubst_argument_pack(tree orig_arg,tree args,tsubst_flags_t complain,tree in_decl)13165 tsubst_argument_pack (tree orig_arg, tree args, tsubst_flags_t complain,
13166 		      tree in_decl)
13167 {
13168   /* Substitute into each of the arguments.  */
13169   tree new_arg = TYPE_P (orig_arg)
13170     ? cxx_make_type (TREE_CODE (orig_arg))
13171     : make_node (TREE_CODE (orig_arg));
13172 
13173   tree pack_args = tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
13174 					 args, complain, in_decl);
13175   if (pack_args == error_mark_node)
13176     new_arg = error_mark_node;
13177   else
13178     SET_ARGUMENT_PACK_ARGS (new_arg, pack_args);
13179 
13180   if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK)
13181     TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
13182 
13183   return new_arg;
13184 }
13185 
13186 /* Substitute ARGS into the vector or list of template arguments T.  */
13187 
13188 tree
tsubst_template_args(tree t,tree args,tsubst_flags_t complain,tree in_decl)13189 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
13190 {
13191   tree orig_t = t;
13192   int len, need_new = 0, i, expanded_len_adjust = 0, out;
13193   tree *elts;
13194 
13195   if (t == error_mark_node)
13196     return error_mark_node;
13197 
13198   len = TREE_VEC_LENGTH (t);
13199   elts = XALLOCAVEC (tree, len);
13200 
13201   for (i = 0; i < len; i++)
13202     {
13203       tree orig_arg = TREE_VEC_ELT (t, i);
13204       tree new_arg;
13205 
13206       if (TREE_CODE (orig_arg) == TREE_VEC)
13207 	new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
13208       else if (PACK_EXPANSION_P (orig_arg))
13209         {
13210           /* Substitute into an expansion expression.  */
13211           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
13212 
13213           if (TREE_CODE (new_arg) == TREE_VEC)
13214             /* Add to the expanded length adjustment the number of
13215                expanded arguments. We subtract one from this
13216                measurement, because the argument pack expression
13217                itself is already counted as 1 in
13218                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
13219                the argument pack is empty.  */
13220             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
13221         }
13222       else if (ARGUMENT_PACK_P (orig_arg))
13223 	new_arg = tsubst_argument_pack (orig_arg, args, complain, in_decl);
13224       else
13225 	new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
13226 
13227       if (new_arg == error_mark_node)
13228 	return error_mark_node;
13229 
13230       elts[i] = new_arg;
13231       if (new_arg != orig_arg)
13232 	need_new = 1;
13233     }
13234 
13235   if (!need_new)
13236     return t;
13237 
13238   /* Make space for the expanded arguments coming from template
13239      argument packs.  */
13240   t = make_tree_vec (len + expanded_len_adjust);
13241   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
13242      arguments for a member template.
13243      In that case each TREE_VEC in ORIG_T represents a level of template
13244      arguments, and ORIG_T won't carry any non defaulted argument count.
13245      It will rather be the nested TREE_VECs that will carry one.
13246      In other words, ORIG_T carries a non defaulted argument count only
13247      if it doesn't contain any nested TREE_VEC.  */
13248   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
13249     {
13250       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
13251       count += expanded_len_adjust;
13252       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
13253     }
13254   for (i = 0, out = 0; i < len; i++)
13255     {
13256       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
13257            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
13258           && TREE_CODE (elts[i]) == TREE_VEC)
13259         {
13260           int idx;
13261 
13262           /* Now expand the template argument pack "in place".  */
13263           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
13264             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
13265         }
13266       else
13267         {
13268           TREE_VEC_ELT (t, out) = elts[i];
13269           out++;
13270         }
13271     }
13272 
13273   return t;
13274 }
13275 
13276 /* Substitute ARGS into one level PARMS of template parameters.  */
13277 
13278 static tree
tsubst_template_parms_level(tree parms,tree args,tsubst_flags_t complain)13279 tsubst_template_parms_level (tree parms, tree args, tsubst_flags_t complain)
13280 {
13281   if (parms == error_mark_node)
13282     return error_mark_node;
13283 
13284   tree new_vec = make_tree_vec (TREE_VEC_LENGTH (parms));
13285 
13286   for (int i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
13287     {
13288       tree tuple = TREE_VEC_ELT (parms, i);
13289 
13290       if (tuple == error_mark_node)
13291 	continue;
13292 
13293       TREE_VEC_ELT (new_vec, i) =
13294 	tsubst_template_parm (tuple, args, complain);
13295     }
13296 
13297   return new_vec;
13298 }
13299 
13300 /* Return the result of substituting ARGS into the template parameters
13301    given by PARMS.  If there are m levels of ARGS and m + n levels of
13302    PARMS, then the result will contain n levels of PARMS.  For
13303    example, if PARMS is `template <class T> template <class U>
13304    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
13305    result will be `template <int*, double, class V>'.  */
13306 
13307 static tree
tsubst_template_parms(tree parms,tree args,tsubst_flags_t complain)13308 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
13309 {
13310   tree r = NULL_TREE;
13311   tree* new_parms;
13312 
13313   /* When substituting into a template, we must set
13314      PROCESSING_TEMPLATE_DECL as the template parameters may be
13315      dependent if they are based on one-another, and the dependency
13316      predicates are short-circuit outside of templates.  */
13317   ++processing_template_decl;
13318 
13319   for (new_parms = &r;
13320        parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
13321        new_parms = &(TREE_CHAIN (*new_parms)),
13322 	 parms = TREE_CHAIN (parms))
13323     {
13324       tree new_vec = tsubst_template_parms_level (TREE_VALUE (parms),
13325 						  args, complain);
13326       *new_parms =
13327 	tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
13328 			     - TMPL_ARGS_DEPTH (args)),
13329 		   new_vec, NULL_TREE);
13330       TEMPLATE_PARMS_CONSTRAINTS (*new_parms)
13331 	= TEMPLATE_PARMS_CONSTRAINTS (parms);
13332     }
13333 
13334   --processing_template_decl;
13335 
13336   return r;
13337 }
13338 
13339 /* Return the result of substituting ARGS into one template parameter
13340    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
13341    parameter and which TREE_PURPOSE is the default argument of the
13342    template parameter.  */
13343 
13344 static tree
tsubst_template_parm(tree t,tree args,tsubst_flags_t complain)13345 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
13346 {
13347   tree default_value, parm_decl;
13348 
13349   if (args == NULL_TREE
13350       || t == NULL_TREE
13351       || t == error_mark_node)
13352     return t;
13353 
13354   gcc_assert (TREE_CODE (t) == TREE_LIST);
13355 
13356   default_value = TREE_PURPOSE (t);
13357   parm_decl = TREE_VALUE (t);
13358   tree constraint = TEMPLATE_PARM_CONSTRAINTS (t);
13359 
13360   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
13361   if (TREE_CODE (parm_decl) == PARM_DECL
13362       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
13363     parm_decl = error_mark_node;
13364   default_value = tsubst_template_arg (default_value, args,
13365 				       complain, NULL_TREE);
13366   constraint = tsubst_constraint (constraint, args, complain, NULL_TREE);
13367 
13368   tree r = build_tree_list (default_value, parm_decl);
13369   TEMPLATE_PARM_CONSTRAINTS (r) = constraint;
13370   return r;
13371 }
13372 
13373 /* Substitute the ARGS into the indicated aggregate (or enumeration)
13374    type T.  If T is not an aggregate or enumeration type, it is
13375    handled as if by tsubst.  IN_DECL is as for tsubst.  If
13376    ENTERING_SCOPE is nonzero, T is the context for a template which
13377    we are presently tsubst'ing.  Return the substituted value.  */
13378 
13379 static tree
tsubst_aggr_type(tree t,tree args,tsubst_flags_t complain,tree in_decl,int entering_scope)13380 tsubst_aggr_type (tree t,
13381 		  tree args,
13382 		  tsubst_flags_t complain,
13383 		  tree in_decl,
13384 		  int entering_scope)
13385 {
13386   if (t == NULL_TREE)
13387     return NULL_TREE;
13388 
13389   switch (TREE_CODE (t))
13390     {
13391     case RECORD_TYPE:
13392       if (TYPE_PTRMEMFUNC_P (t))
13393 	return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
13394 
13395       /* Fall through.  */
13396     case ENUMERAL_TYPE:
13397     case UNION_TYPE:
13398       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
13399 	{
13400 	  tree argvec;
13401 	  tree context;
13402 	  tree r;
13403 
13404 	  /* In "sizeof(X<I>)" we need to evaluate "I".  */
13405 	  cp_evaluated ev;
13406 
13407 	  /* First, determine the context for the type we are looking
13408 	     up.  */
13409 	  context = TYPE_CONTEXT (t);
13410 	  if (context && TYPE_P (context))
13411 	    {
13412 	      context = tsubst_aggr_type (context, args, complain,
13413 					  in_decl, /*entering_scope=*/1);
13414 	      /* If context is a nested class inside a class template,
13415 	         it may still need to be instantiated (c++/33959).  */
13416 	      context = complete_type (context);
13417 	    }
13418 
13419 	  /* Then, figure out what arguments are appropriate for the
13420 	     type we are trying to find.  For example, given:
13421 
13422 	       template <class T> struct S;
13423 	       template <class T, class U> void f(T, U) { S<U> su; }
13424 
13425 	     and supposing that we are instantiating f<int, double>,
13426 	     then our ARGS will be {int, double}, but, when looking up
13427 	     S we only want {double}.  */
13428 	  argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
13429 					 complain, in_decl);
13430 	  if (argvec == error_mark_node)
13431 	    r = error_mark_node;
13432 	  else if (!entering_scope
13433 		   && cxx_dialect >= cxx2a && dependent_scope_p (context))
13434 	    {
13435 	      /* See maybe_dependent_member_ref.  */
13436 	      tree name = TYPE_IDENTIFIER (t);
13437 	      tree fullname = name;
13438 	      if (instantiates_primary_template_p (t))
13439 		fullname = build_nt (TEMPLATE_ID_EXPR, name,
13440 				     INNERMOST_TEMPLATE_ARGS (argvec));
13441 	      return build_typename_type (context, name, fullname,
13442 					  typename_type);
13443 	    }
13444 	  else
13445 	    {
13446 	      r = lookup_template_class (t, argvec, in_decl, context,
13447 					 entering_scope, complain);
13448 	      r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
13449 	    }
13450 
13451 	  return r;
13452 	}
13453       else
13454 	/* This is not a template type, so there's nothing to do.  */
13455 	return t;
13456 
13457     default:
13458       return tsubst (t, args, complain, in_decl);
13459     }
13460 }
13461 
13462 static GTY((cache)) decl_tree_cache_map *defarg_inst;
13463 
13464 /* Substitute into the default argument ARG (a default argument for
13465    FN), which has the indicated TYPE.  */
13466 
13467 tree
tsubst_default_argument(tree fn,int parmnum,tree type,tree arg,tsubst_flags_t complain)13468 tsubst_default_argument (tree fn, int parmnum, tree type, tree arg,
13469 			 tsubst_flags_t complain)
13470 {
13471   int errs = errorcount + sorrycount;
13472 
13473   /* This can happen in invalid code.  */
13474   if (TREE_CODE (arg) == DEFERRED_PARSE)
13475     return arg;
13476 
13477   tree parm = FUNCTION_FIRST_USER_PARM (fn);
13478   parm = chain_index (parmnum, parm);
13479   tree parmtype = TREE_TYPE (parm);
13480   if (DECL_BY_REFERENCE (parm))
13481     parmtype = TREE_TYPE (parmtype);
13482   if (parmtype == error_mark_node)
13483     return error_mark_node;
13484 
13485   gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, parmtype));
13486 
13487   tree *slot;
13488   if (defarg_inst && (slot = defarg_inst->get (parm)))
13489     return *slot;
13490 
13491   /* This default argument came from a template.  Instantiate the
13492      default argument here, not in tsubst.  In the case of
13493      something like:
13494 
13495        template <class T>
13496        struct S {
13497 	 static T t();
13498 	 void f(T = t());
13499        };
13500 
13501      we must be careful to do name lookup in the scope of S<T>,
13502      rather than in the current class.  */
13503   push_to_top_level ();
13504   push_access_scope (fn);
13505   push_deferring_access_checks (dk_no_deferred);
13506   start_lambda_scope (parm);
13507 
13508   /* The default argument expression may cause implicitly defined
13509      member functions to be synthesized, which will result in garbage
13510      collection.  We must treat this situation as if we were within
13511      the body of function so as to avoid collecting live data on the
13512      stack.  */
13513   ++function_depth;
13514   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
13515 		     complain, NULL_TREE,
13516 		     /*integral_constant_expression_p=*/false);
13517   --function_depth;
13518 
13519   finish_lambda_scope ();
13520 
13521   /* Make sure the default argument is reasonable.  */
13522   arg = check_default_argument (type, arg, complain);
13523 
13524   if (errorcount+sorrycount > errs
13525       && (complain & tf_warning_or_error))
13526     inform (input_location,
13527 	    "  when instantiating default argument for call to %qD", fn);
13528 
13529   pop_deferring_access_checks ();
13530   pop_access_scope (fn);
13531   pop_from_top_level ();
13532 
13533   if (arg != error_mark_node && !cp_unevaluated_operand)
13534     {
13535       if (!defarg_inst)
13536 	defarg_inst = decl_tree_cache_map::create_ggc (37);
13537       defarg_inst->put (parm, arg);
13538     }
13539 
13540   return arg;
13541 }
13542 
13543 /* Substitute into all the default arguments for FN.  */
13544 
13545 static void
tsubst_default_arguments(tree fn,tsubst_flags_t complain)13546 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
13547 {
13548   tree arg;
13549   tree tmpl_args;
13550 
13551   tmpl_args = DECL_TI_ARGS (fn);
13552 
13553   /* If this function is not yet instantiated, we certainly don't need
13554      its default arguments.  */
13555   if (uses_template_parms (tmpl_args))
13556     return;
13557   /* Don't do this again for clones.  */
13558   if (DECL_CLONED_FUNCTION_P (fn))
13559     return;
13560 
13561   int i = 0;
13562   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
13563        arg;
13564        arg = TREE_CHAIN (arg), ++i)
13565     if (TREE_PURPOSE (arg))
13566       TREE_PURPOSE (arg) = tsubst_default_argument (fn, i,
13567 						    TREE_VALUE (arg),
13568 						    TREE_PURPOSE (arg),
13569 						    complain);
13570 }
13571 
13572 /* Hash table mapping a FUNCTION_DECL to its dependent explicit-specifier.  */
13573 static GTY((cache)) decl_tree_cache_map *explicit_specifier_map;
13574 
13575 /* Store a pair to EXPLICIT_SPECIFIER_MAP.  */
13576 
13577 void
store_explicit_specifier(tree v,tree t)13578 store_explicit_specifier (tree v, tree t)
13579 {
13580   if (!explicit_specifier_map)
13581     explicit_specifier_map = decl_tree_cache_map::create_ggc (37);
13582   DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (v) = true;
13583   explicit_specifier_map->put (v, t);
13584 }
13585 
13586 /* Lookup an element in EXPLICIT_SPECIFIER_MAP.  */
13587 
13588 static tree
lookup_explicit_specifier(tree v)13589 lookup_explicit_specifier (tree v)
13590 {
13591   return *explicit_specifier_map->get (v);
13592 }
13593 
13594 /* Given T, a FUNCTION_TYPE or METHOD_TYPE, construct and return a corresponding
13595    FUNCTION_TYPE or METHOD_TYPE whose return type is RETURN_TYPE, argument types
13596    are ARG_TYPES, and exception specification is RAISES, and otherwise is
13597    identical to T.  */
13598 
13599 static tree
rebuild_function_or_method_type(tree t,tree return_type,tree arg_types,tree raises,tsubst_flags_t complain)13600 rebuild_function_or_method_type (tree t, tree return_type, tree arg_types,
13601 				 tree raises, tsubst_flags_t complain)
13602 {
13603   gcc_assert (FUNC_OR_METHOD_TYPE_P (t));
13604 
13605   tree new_type;
13606   if (TREE_CODE (t) == FUNCTION_TYPE)
13607     {
13608       new_type = build_function_type (return_type, arg_types);
13609       new_type = apply_memfn_quals (new_type, type_memfn_quals (t));
13610     }
13611   else
13612     {
13613       tree r = TREE_TYPE (TREE_VALUE (arg_types));
13614       /* Don't pick up extra function qualifiers from the basetype.  */
13615       r = cp_build_qualified_type_real (r, type_memfn_quals (t), complain);
13616       if (! MAYBE_CLASS_TYPE_P (r))
13617 	{
13618 	  /* [temp.deduct]
13619 
13620 	     Type deduction may fail for any of the following
13621 	     reasons:
13622 
13623 	     -- Attempting to create "pointer to member of T" when T
13624 	     is not a class type.  */
13625 	  if (complain & tf_error)
13626 	    error ("creating pointer to member function of non-class type %qT",
13627 		   r);
13628 	  return error_mark_node;
13629 	}
13630 
13631       new_type = build_method_type_directly (r, return_type,
13632 					     TREE_CHAIN (arg_types));
13633     }
13634   new_type = cp_build_type_attribute_variant (new_type, TYPE_ATTRIBUTES (t));
13635 
13636   cp_ref_qualifier rqual = type_memfn_rqual (t);
13637   bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
13638   return build_cp_fntype_variant (new_type, rqual, raises, late_return_type_p);
13639 }
13640 
13641 /* Check if the function type of DECL, a FUNCTION_DECL, agrees with the type of
13642    each of its formal parameters.  If there is a disagreement then rebuild
13643    DECL's function type according to its formal parameter types, as part of a
13644    resolution for Core issues 1001/1322.  */
13645 
13646 static void
maybe_rebuild_function_decl_type(tree decl)13647 maybe_rebuild_function_decl_type (tree decl)
13648 {
13649   bool function_type_needs_rebuilding = false;
13650   if (tree parm_list = FUNCTION_FIRST_USER_PARM (decl))
13651     {
13652       tree parm_type_list = FUNCTION_FIRST_USER_PARMTYPE (decl);
13653       while (parm_type_list && parm_type_list != void_list_node)
13654 	{
13655 	  tree parm_type = TREE_VALUE (parm_type_list);
13656 	  tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
13657 	  if (!same_type_p (parm_type, formal_parm_type_unqual))
13658 	    {
13659 	      function_type_needs_rebuilding = true;
13660 	      break;
13661 	    }
13662 
13663 	  parm_list = DECL_CHAIN (parm_list);
13664 	  parm_type_list = TREE_CHAIN (parm_type_list);
13665 	}
13666     }
13667 
13668   if (!function_type_needs_rebuilding)
13669     return;
13670 
13671   const tree fntype = TREE_TYPE (decl);
13672   tree parm_list = DECL_ARGUMENTS (decl);
13673   tree old_parm_type_list = TYPE_ARG_TYPES (fntype);
13674   tree new_parm_type_list = NULL_TREE;
13675   tree *q = &new_parm_type_list;
13676   for (int skip = num_artificial_parms_for (decl); skip > 0; skip--)
13677     {
13678       *q = copy_node (old_parm_type_list);
13679       parm_list = DECL_CHAIN (parm_list);
13680       old_parm_type_list = TREE_CHAIN (old_parm_type_list);
13681       q = &TREE_CHAIN (*q);
13682     }
13683   while (old_parm_type_list && old_parm_type_list != void_list_node)
13684     {
13685       *q = copy_node (old_parm_type_list);
13686       tree *new_parm_type = &TREE_VALUE (*q);
13687       tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
13688       if (!same_type_p (*new_parm_type, formal_parm_type_unqual))
13689 	*new_parm_type = formal_parm_type_unqual;
13690 
13691       parm_list = DECL_CHAIN (parm_list);
13692       old_parm_type_list = TREE_CHAIN (old_parm_type_list);
13693       q = &TREE_CHAIN (*q);
13694     }
13695   if (old_parm_type_list == void_list_node)
13696     *q = void_list_node;
13697 
13698   TREE_TYPE (decl)
13699     = rebuild_function_or_method_type (fntype,
13700 				       TREE_TYPE (fntype), new_parm_type_list,
13701 				       TYPE_RAISES_EXCEPTIONS (fntype), tf_none);
13702 }
13703 
13704 /* Subroutine of tsubst_decl for the case when T is a FUNCTION_DECL.  */
13705 
13706 static tree
tsubst_function_decl(tree t,tree args,tsubst_flags_t complain,tree lambda_fntype)13707 tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
13708 		      tree lambda_fntype)
13709 {
13710   tree gen_tmpl, argvec;
13711   hashval_t hash = 0;
13712   tree in_decl = t;
13713 
13714   /* Nobody should be tsubst'ing into non-template functions.  */
13715   gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
13716 
13717   if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
13718     {
13719       /* If T is not dependent, just return it.  */
13720       if (!uses_template_parms (DECL_TI_ARGS (t))
13721 	  && !LAMBDA_FUNCTION_P (t))
13722 	return t;
13723 
13724       /* Calculate the most general template of which R is a
13725 	 specialization.  */
13726       gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
13727 
13728       /* We're substituting a lambda function under tsubst_lambda_expr but not
13729 	 directly from it; find the matching function we're already inside.
13730 	 But don't do this if T is a generic lambda with a single level of
13731 	 template parms, as in that case we're doing a normal instantiation. */
13732       if (LAMBDA_FUNCTION_P (t) && !lambda_fntype
13733 	  && (!generic_lambda_fn_p (t)
13734 	      || TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)) > 1))
13735 	return enclosing_instantiation_of (t);
13736 
13737       /* Calculate the complete set of arguments used to
13738 	 specialize R.  */
13739       argvec = tsubst_template_args (DECL_TI_ARGS
13740 				     (DECL_TEMPLATE_RESULT
13741 				      (DECL_TI_TEMPLATE (t))),
13742 				     args, complain, in_decl);
13743       if (argvec == error_mark_node)
13744 	return error_mark_node;
13745 
13746       /* Check to see if we already have this specialization.  */
13747       if (!lambda_fntype)
13748 	{
13749 	  hash = hash_tmpl_and_args (gen_tmpl, argvec);
13750 	  if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
13751 	    return spec;
13752 	}
13753 
13754       /* We can see more levels of arguments than parameters if
13755 	 there was a specialization of a member template, like
13756 	 this:
13757 
13758 	 template <class T> struct S { template <class U> void f(); }
13759 	 template <> template <class U> void S<int>::f(U);
13760 
13761 	 Here, we'll be substituting into the specialization,
13762 	 because that's where we can find the code we actually
13763 	 want to generate, but we'll have enough arguments for
13764 	 the most general template.
13765 
13766 	 We also deal with the peculiar case:
13767 
13768 	 template <class T> struct S {
13769 	   template <class U> friend void f();
13770 	 };
13771 	 template <class U> void f() {}
13772 	 template S<int>;
13773 	 template void f<double>();
13774 
13775 	 Here, the ARGS for the instantiation of will be {int,
13776 	 double}.  But, we only need as many ARGS as there are
13777 	 levels of template parameters in CODE_PATTERN.  We are
13778 	 careful not to get fooled into reducing the ARGS in
13779 	 situations like:
13780 
13781 	 template <class T> struct S { template <class U> void f(U); }
13782 	 template <class T> template <> void S<T>::f(int) {}
13783 
13784 	 which we can spot because the pattern will be a
13785 	 specialization in this case.  */
13786       int args_depth = TMPL_ARGS_DEPTH (args);
13787       int parms_depth =
13788 	TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
13789 
13790       if (args_depth > parms_depth && !DECL_TEMPLATE_SPECIALIZATION (t))
13791 	args = get_innermost_template_args (args, parms_depth);
13792     }
13793   else
13794     {
13795       /* This special case arises when we have something like this:
13796 
13797 	 template <class T> struct S {
13798 	 friend void f<int>(int, double);
13799 	 };
13800 
13801 	 Here, the DECL_TI_TEMPLATE for the friend declaration
13802 	 will be an IDENTIFIER_NODE.  We are being called from
13803 	 tsubst_friend_function, and we want only to create a
13804 	 new decl (R) with appropriate types so that we can call
13805 	 determine_specialization.  */
13806       gen_tmpl = NULL_TREE;
13807       argvec = NULL_TREE;
13808     }
13809 
13810   tree closure = (lambda_fntype ? TYPE_METHOD_BASETYPE (lambda_fntype)
13811 		  : NULL_TREE);
13812   tree ctx = closure ? closure : DECL_CONTEXT (t);
13813   bool member = ctx && TYPE_P (ctx);
13814 
13815   if (member && !closure)
13816     ctx = tsubst_aggr_type (ctx, args,
13817 			    complain, t, /*entering_scope=*/1);
13818 
13819   tree type = (lambda_fntype ? lambda_fntype
13820 	       : tsubst (TREE_TYPE (t), args,
13821 			 complain | tf_fndecl_type, in_decl));
13822   if (type == error_mark_node)
13823     return error_mark_node;
13824 
13825   /* If we hit excessive deduction depth, the type is bogus even if
13826      it isn't error_mark_node, so don't build a decl.  */
13827   if (excessive_deduction_depth)
13828     return error_mark_node;
13829 
13830   /* We do NOT check for matching decls pushed separately at this
13831      point, as they may not represent instantiations of this
13832      template, and in any case are considered separate under the
13833      discrete model.  */
13834   tree r = copy_decl (t);
13835   DECL_USE_TEMPLATE (r) = 0;
13836   TREE_TYPE (r) = type;
13837   /* Clear out the mangled name and RTL for the instantiation.  */
13838   SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
13839   SET_DECL_RTL (r, NULL);
13840   /* Leave DECL_INITIAL set on deleted instantiations.  */
13841   if (!DECL_DELETED_FN (r))
13842     DECL_INITIAL (r) = NULL_TREE;
13843   DECL_CONTEXT (r) = ctx;
13844 
13845   /* Handle explicit(dependent-expr).  */
13846   if (DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (t))
13847     {
13848       tree spec = lookup_explicit_specifier (t);
13849       spec = tsubst_copy_and_build (spec, args, complain, in_decl,
13850 				    /*function_p=*/false,
13851 				    /*i_c_e_p=*/true);
13852       spec = build_explicit_specifier (spec, complain);
13853       DECL_NONCONVERTING_P (r) = (spec == boolean_true_node);
13854     }
13855 
13856   /* OpenMP UDRs have the only argument a reference to the declared
13857      type.  We want to diagnose if the declared type is a reference,
13858      which is invalid, but as references to references are usually
13859      quietly merged, diagnose it here.  */
13860   if (DECL_OMP_DECLARE_REDUCTION_P (t))
13861     {
13862       tree argtype
13863 	= TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
13864       argtype = tsubst (argtype, args, complain, in_decl);
13865       if (TYPE_REF_P (argtype))
13866 	error_at (DECL_SOURCE_LOCATION (t),
13867 		  "reference type %qT in "
13868 		  "%<#pragma omp declare reduction%>", argtype);
13869       if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
13870 	DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
13871 					  argtype);
13872     }
13873 
13874   if (member && DECL_CONV_FN_P (r))
13875     /* Type-conversion operator.  Reconstruct the name, in
13876        case it's the name of one of the template's parameters.  */
13877     DECL_NAME (r) = make_conv_op_name (TREE_TYPE (type));
13878 
13879   tree parms = DECL_ARGUMENTS (t);
13880   if (closure)
13881     parms = DECL_CHAIN (parms);
13882   parms = tsubst (parms, args, complain, t);
13883   for (tree parm = parms; parm; parm = DECL_CHAIN (parm))
13884     DECL_CONTEXT (parm) = r;
13885   if (closure)
13886     {
13887       tree tparm = build_this_parm (r, closure, type_memfn_quals (type));
13888       DECL_CHAIN (tparm) = parms;
13889       parms = tparm;
13890     }
13891   DECL_ARGUMENTS (r) = parms;
13892   DECL_RESULT (r) = NULL_TREE;
13893 
13894   maybe_rebuild_function_decl_type (r);
13895 
13896   TREE_STATIC (r) = 0;
13897   TREE_PUBLIC (r) = TREE_PUBLIC (t);
13898   DECL_EXTERNAL (r) = 1;
13899   /* If this is an instantiation of a function with internal
13900      linkage, we already know what object file linkage will be
13901      assigned to the instantiation.  */
13902   DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
13903   DECL_DEFER_OUTPUT (r) = 0;
13904   DECL_CHAIN (r) = NULL_TREE;
13905   DECL_PENDING_INLINE_INFO (r) = 0;
13906   DECL_PENDING_INLINE_P (r) = 0;
13907   DECL_SAVED_TREE (r) = NULL_TREE;
13908   DECL_STRUCT_FUNCTION (r) = NULL;
13909   TREE_USED (r) = 0;
13910   /* We'll re-clone as appropriate in instantiate_template.  */
13911   DECL_CLONED_FUNCTION (r) = NULL_TREE;
13912 
13913   /* If we aren't complaining now, return on error before we register
13914      the specialization so that we'll complain eventually.  */
13915   if ((complain & tf_error) == 0
13916       && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
13917       && !grok_op_properties (r, /*complain=*/false))
13918     return error_mark_node;
13919 
13920   /* Associate the constraints directly with the instantiation. We
13921      don't substitute through the constraints; that's only done when
13922      they are checked.  */
13923   if (tree ci = get_constraints (t))
13924     /* Unless we're regenerating a lambda, in which case we'll set the
13925        lambda's constraints in tsubst_lambda_expr.  */
13926     if (!lambda_fntype)
13927       set_constraints (r, ci);
13928 
13929   if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
13930     SET_DECL_FRIEND_CONTEXT (r,
13931 			     tsubst (DECL_FRIEND_CONTEXT (t),
13932 				     args, complain, in_decl));
13933 
13934   /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
13935      this in the special friend case mentioned above where
13936      GEN_TMPL is NULL.  */
13937   if (gen_tmpl && !closure)
13938     {
13939       DECL_TEMPLATE_INFO (r)
13940 	= build_template_info (gen_tmpl, argvec);
13941       SET_DECL_IMPLICIT_INSTANTIATION (r);
13942 
13943       tree new_r
13944 	= register_specialization (r, gen_tmpl, argvec, false, hash);
13945       if (new_r != r)
13946 	/* We instantiated this while substituting into
13947 	   the type earlier (template/friend54.C).  */
13948 	return new_r;
13949 
13950       /* We're not supposed to instantiate default arguments
13951 	 until they are called, for a template.  But, for a
13952 	 declaration like:
13953 
13954 	 template <class T> void f ()
13955 	 { extern void g(int i = T()); }
13956 
13957 	 we should do the substitution when the template is
13958 	 instantiated.  We handle the member function case in
13959 	 instantiate_class_template since the default arguments
13960 	 might refer to other members of the class.  */
13961       if (!member
13962 	  && !PRIMARY_TEMPLATE_P (gen_tmpl)
13963 	  && !uses_template_parms (argvec))
13964 	tsubst_default_arguments (r, complain);
13965     }
13966   else
13967     DECL_TEMPLATE_INFO (r) = NULL_TREE;
13968 
13969   /* Copy the list of befriending classes.  */
13970   for (tree *friends = &DECL_BEFRIENDING_CLASSES (r);
13971        *friends;
13972        friends = &TREE_CHAIN (*friends))
13973     {
13974       *friends = copy_node (*friends);
13975       TREE_VALUE (*friends)
13976 	= tsubst (TREE_VALUE (*friends), args, complain, in_decl);
13977     }
13978 
13979   if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
13980     {
13981       maybe_retrofit_in_chrg (r);
13982       if (DECL_CONSTRUCTOR_P (r) && !grok_ctor_properties (ctx, r))
13983 	return error_mark_node;
13984       /* If this is an instantiation of a member template, clone it.
13985 	 If it isn't, that'll be handled by
13986 	 clone_constructors_and_destructors.  */
13987       if (PRIMARY_TEMPLATE_P (gen_tmpl))
13988 	clone_function_decl (r, /*update_methods=*/false);
13989     }
13990   else if ((complain & tf_error) != 0
13991 	   && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
13992 	   && !grok_op_properties (r, /*complain=*/true))
13993     return error_mark_node;
13994 
13995   /* Possibly limit visibility based on template args.  */
13996   DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
13997   if (DECL_VISIBILITY_SPECIFIED (t))
13998     {
13999       DECL_VISIBILITY_SPECIFIED (r) = 0;
14000       DECL_ATTRIBUTES (r)
14001 	= remove_attribute ("visibility", DECL_ATTRIBUTES (r));
14002     }
14003   determine_visibility (r);
14004   if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
14005       && !processing_template_decl)
14006     defaulted_late_check (r);
14007 
14008   apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14009 				  args, complain, in_decl);
14010   if (flag_openmp)
14011     if (tree attr = lookup_attribute ("omp declare variant base",
14012 				      DECL_ATTRIBUTES (r)))
14013       omp_declare_variant_finalize (r, attr);
14014 
14015   return r;
14016 }
14017 
14018 /* Subroutine of tsubst_decl for the case when T is a TEMPLATE_DECL.  */
14019 
14020 static tree
tsubst_template_decl(tree t,tree args,tsubst_flags_t complain,tree lambda_fntype)14021 tsubst_template_decl (tree t, tree args, tsubst_flags_t complain,
14022 		      tree lambda_fntype)
14023 {
14024   /* We can get here when processing a member function template,
14025      member class template, or template template parameter.  */
14026   tree decl = DECL_TEMPLATE_RESULT (t);
14027   tree in_decl = t;
14028   tree spec;
14029   tree tmpl_args;
14030   tree full_args;
14031   tree r;
14032   hashval_t hash = 0;
14033 
14034   if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
14035     {
14036       /* Template template parameter is treated here.  */
14037       tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14038       if (new_type == error_mark_node)
14039 	r = error_mark_node;
14040       /* If we get a real template back, return it.  This can happen in
14041 	 the context of most_specialized_partial_spec.  */
14042       else if (TREE_CODE (new_type) == TEMPLATE_DECL)
14043 	r = new_type;
14044       else
14045 	/* The new TEMPLATE_DECL was built in
14046 	   reduce_template_parm_level.  */
14047 	r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
14048       return r;
14049     }
14050 
14051   if (!lambda_fntype)
14052     {
14053       /* We might already have an instance of this template.
14054 	 The ARGS are for the surrounding class type, so the
14055 	 full args contain the tsubst'd args for the context,
14056 	 plus the innermost args from the template decl.  */
14057       tmpl_args = DECL_CLASS_TEMPLATE_P (t)
14058 	? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
14059 	: DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
14060       /* Because this is a template, the arguments will still be
14061 	 dependent, even after substitution.  If
14062 	 PROCESSING_TEMPLATE_DECL is not set, the dependency
14063 	 predicates will short-circuit.  */
14064       ++processing_template_decl;
14065       full_args = tsubst_template_args (tmpl_args, args,
14066 					complain, in_decl);
14067       --processing_template_decl;
14068       if (full_args == error_mark_node)
14069 	return error_mark_node;
14070 
14071       /* If this is a default template template argument,
14072 	 tsubst might not have changed anything.  */
14073       if (full_args == tmpl_args)
14074 	return t;
14075 
14076       hash = hash_tmpl_and_args (t, full_args);
14077       spec = retrieve_specialization (t, full_args, hash);
14078       if (spec != NULL_TREE)
14079 	{
14080 	  if (TYPE_P (spec))
14081 	    /* Type partial instantiations are stored as the type by
14082 	       lookup_template_class_1, not here as the template.  */
14083 	    spec = CLASSTYPE_TI_TEMPLATE (spec);
14084 	  return spec;
14085 	}
14086     }
14087 
14088   /* Make a new template decl.  It will be similar to the
14089      original, but will record the current template arguments.
14090      We also create a new function declaration, which is just
14091      like the old one, but points to this new template, rather
14092      than the old one.  */
14093   r = copy_decl (t);
14094   gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
14095   DECL_CHAIN (r) = NULL_TREE;
14096 
14097   // Build new template info linking to the original template decl.
14098   if (!lambda_fntype)
14099     {
14100       DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
14101       SET_DECL_IMPLICIT_INSTANTIATION (r);
14102     }
14103   else
14104     DECL_TEMPLATE_INFO (r) = NULL_TREE;
14105 
14106   /* The template parameters for this new template are all the
14107      template parameters for the old template, except the
14108      outermost level of parameters.  */
14109   DECL_TEMPLATE_PARMS (r)
14110     = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
14111 			     complain);
14112 
14113   if (TREE_CODE (decl) == TYPE_DECL
14114       && !TYPE_DECL_ALIAS_P (decl))
14115     {
14116       tree new_type;
14117       ++processing_template_decl;
14118       if (CLASS_TYPE_P (TREE_TYPE (t)))
14119 	new_type = tsubst_aggr_type (TREE_TYPE (t), args, complain,
14120 				     in_decl, /*entering*/1);
14121       else
14122 	new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14123       --processing_template_decl;
14124       if (new_type == error_mark_node)
14125 	return error_mark_node;
14126 
14127       TREE_TYPE (r) = new_type;
14128       /* For a partial specialization, we need to keep pointing to
14129 	 the primary template.  */
14130       if (!DECL_TEMPLATE_SPECIALIZATION (t))
14131 	CLASSTYPE_TI_TEMPLATE (new_type) = r;
14132       DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
14133       DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
14134       DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
14135     }
14136   else
14137     {
14138       tree new_decl;
14139       ++processing_template_decl;
14140       if (TREE_CODE (decl) == FUNCTION_DECL)
14141 	new_decl = tsubst_function_decl (decl, args, complain, lambda_fntype);
14142       else
14143 	new_decl = tsubst (decl, args, complain, in_decl);
14144       --processing_template_decl;
14145       if (new_decl == error_mark_node)
14146 	return error_mark_node;
14147 
14148       DECL_TEMPLATE_RESULT (r) = new_decl;
14149       TREE_TYPE (r) = TREE_TYPE (new_decl);
14150       DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
14151       if (lambda_fntype)
14152 	{
14153 	  tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (r));
14154 	  DECL_TEMPLATE_INFO (new_decl) = build_template_info (r, args);
14155 	}
14156       else
14157 	{
14158 	  DECL_TI_TEMPLATE (new_decl) = r;
14159 	  DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
14160 	}
14161     }
14162 
14163   DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
14164   DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
14165 
14166   if (PRIMARY_TEMPLATE_P (t))
14167     DECL_PRIMARY_TEMPLATE (r) = r;
14168 
14169   if (TREE_CODE (decl) != TYPE_DECL && !VAR_P (decl)
14170       && !lambda_fntype)
14171     /* Record this non-type partial instantiation.  */
14172     register_specialization (r, t,
14173 			     DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
14174 			     false, hash);
14175 
14176   return r;
14177 }
14178 
14179 /* True if FN is the op() for a lambda in an uninstantiated template.  */
14180 
14181 bool
lambda_fn_in_template_p(tree fn)14182 lambda_fn_in_template_p (tree fn)
14183 {
14184   if (!fn || !LAMBDA_FUNCTION_P (fn))
14185     return false;
14186   tree closure = DECL_CONTEXT (fn);
14187   return CLASSTYPE_TEMPLATE_INFO (closure) != NULL_TREE;
14188 }
14189 
14190 /* True if FN is the substitution (via tsubst_lambda_expr) of a function for
14191    which the above is true.  */
14192 
14193 bool
instantiated_lambda_fn_p(tree fn)14194 instantiated_lambda_fn_p (tree fn)
14195 {
14196   if (!fn || !LAMBDA_FUNCTION_P (fn))
14197     return false;
14198   tree closure = DECL_CONTEXT (fn);
14199   tree lam = CLASSTYPE_LAMBDA_EXPR (closure);
14200   return LAMBDA_EXPR_INSTANTIATED (lam);
14201 }
14202 
14203 /* We're instantiating a variable from template function TCTX.  Return the
14204    corresponding current enclosing scope.  This gets complicated because lambda
14205    functions in templates are regenerated rather than instantiated, but generic
14206    lambda functions are subsequently instantiated.  */
14207 
14208 static tree
enclosing_instantiation_of(tree otctx)14209 enclosing_instantiation_of (tree otctx)
14210 {
14211   tree tctx = otctx;
14212   tree fn = current_function_decl;
14213   int lambda_count = 0;
14214 
14215   for (; tctx && (lambda_fn_in_template_p (tctx)
14216 		  || instantiated_lambda_fn_p (tctx));
14217        tctx = decl_function_context (tctx))
14218     ++lambda_count;
14219   for (; fn; fn = decl_function_context (fn))
14220     {
14221       tree ofn = fn;
14222       int flambda_count = 0;
14223       for (; fn && instantiated_lambda_fn_p (fn);
14224 	   fn = decl_function_context (fn))
14225 	++flambda_count;
14226       if ((fn && DECL_TEMPLATE_INFO (fn))
14227 	  ? most_general_template (fn) != most_general_template (tctx)
14228 	  : fn != tctx)
14229 	continue;
14230       if (flambda_count != lambda_count)
14231 	{
14232 	  gcc_assert (flambda_count > lambda_count);
14233 	  for (; flambda_count > lambda_count; --flambda_count)
14234 	    ofn = decl_function_context (ofn);
14235 	}
14236       gcc_assert (DECL_NAME (ofn) == DECL_NAME (otctx)
14237 		  || DECL_CONV_FN_P (ofn));
14238       return ofn;
14239     }
14240   gcc_unreachable ();
14241 }
14242 
14243 /* Substitute the ARGS into the T, which is a _DECL.  Return the
14244    result of the substitution.  Issue error and warning messages under
14245    control of COMPLAIN.  */
14246 
14247 static tree
tsubst_decl(tree t,tree args,tsubst_flags_t complain)14248 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
14249 {
14250 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
14251   location_t saved_loc;
14252   tree r = NULL_TREE;
14253   tree in_decl = t;
14254   hashval_t hash = 0;
14255 
14256   /* Set the filename and linenumber to improve error-reporting.  */
14257   saved_loc = input_location;
14258   input_location = DECL_SOURCE_LOCATION (t);
14259 
14260   switch (TREE_CODE (t))
14261     {
14262     case TEMPLATE_DECL:
14263       r = tsubst_template_decl (t, args, complain, /*lambda*/NULL_TREE);
14264       break;
14265 
14266     case FUNCTION_DECL:
14267       r = tsubst_function_decl (t, args, complain, /*lambda*/NULL_TREE);
14268       break;
14269 
14270     case PARM_DECL:
14271       {
14272 	tree type = NULL_TREE;
14273         int i, len = 1;
14274         tree expanded_types = NULL_TREE;
14275         tree prev_r = NULL_TREE;
14276         tree first_r = NULL_TREE;
14277 
14278         if (DECL_PACK_P (t))
14279           {
14280             /* If there is a local specialization that isn't a
14281                parameter pack, it means that we're doing a "simple"
14282                substitution from inside tsubst_pack_expansion. Just
14283                return the local specialization (which will be a single
14284                parm).  */
14285             tree spec = retrieve_local_specialization (t);
14286             if (spec
14287                 && TREE_CODE (spec) == PARM_DECL
14288                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
14289               RETURN (spec);
14290 
14291             /* Expand the TYPE_PACK_EXPANSION that provides the types for
14292                the parameters in this function parameter pack.  */
14293             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
14294 						    complain, in_decl);
14295             if (TREE_CODE (expanded_types) == TREE_VEC)
14296               {
14297                 len = TREE_VEC_LENGTH (expanded_types);
14298 
14299                 /* Zero-length parameter packs are boring. Just substitute
14300                    into the chain.  */
14301 		if (len == 0 && !cp_unevaluated_operand)
14302                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
14303 				  TREE_CHAIN (t)));
14304               }
14305             else
14306               {
14307                 /* All we did was update the type. Make a note of that.  */
14308                 type = expanded_types;
14309                 expanded_types = NULL_TREE;
14310               }
14311           }
14312 
14313         /* Loop through all of the parameters we'll build. When T is
14314            a function parameter pack, LEN is the number of expanded
14315            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
14316         r = NULL_TREE;
14317         for (i = 0; i < len; ++i)
14318           {
14319             prev_r = r;
14320             r = copy_node (t);
14321             if (DECL_TEMPLATE_PARM_P (t))
14322               SET_DECL_TEMPLATE_PARM_P (r);
14323 
14324             if (expanded_types)
14325               /* We're on the Ith parameter of the function parameter
14326                  pack.  */
14327               {
14328                 /* Get the Ith type.  */
14329                 type = TREE_VEC_ELT (expanded_types, i);
14330 
14331 		/* Rename the parameter to include the index.  */
14332 		DECL_NAME (r)
14333 		  = make_ith_pack_parameter_name (DECL_NAME (r), i);
14334               }
14335             else if (!type)
14336               /* We're dealing with a normal parameter.  */
14337               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14338 
14339             type = type_decays_to (type);
14340             TREE_TYPE (r) = type;
14341             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14342 
14343             if (DECL_INITIAL (r))
14344               {
14345                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
14346                   DECL_INITIAL (r) = TREE_TYPE (r);
14347                 else
14348                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
14349                                              complain, in_decl);
14350               }
14351 
14352             DECL_CONTEXT (r) = NULL_TREE;
14353 
14354             if (!DECL_TEMPLATE_PARM_P (r))
14355               DECL_ARG_TYPE (r) = type_passed_as (type);
14356 
14357 	    apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14358 					    args, complain, in_decl);
14359 
14360             /* Keep track of the first new parameter we
14361                generate. That's what will be returned to the
14362                caller.  */
14363             if (!first_r)
14364               first_r = r;
14365 
14366             /* Build a proper chain of parameters when substituting
14367                into a function parameter pack.  */
14368             if (prev_r)
14369               DECL_CHAIN (prev_r) = r;
14370           }
14371 
14372 	/* If cp_unevaluated_operand is set, we're just looking for a
14373 	   single dummy parameter, so don't keep going.  */
14374 	if (DECL_CHAIN (t) && !cp_unevaluated_operand)
14375 	  DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
14376 				   complain, DECL_CHAIN (t));
14377 
14378         /* FIRST_R contains the start of the chain we've built.  */
14379         r = first_r;
14380       }
14381       break;
14382 
14383     case FIELD_DECL:
14384       {
14385 	tree type = NULL_TREE;
14386 	tree vec = NULL_TREE;
14387 	tree expanded_types = NULL_TREE;
14388 	int len = 1;
14389 
14390 	if (PACK_EXPANSION_P (TREE_TYPE (t)))
14391 	  {
14392 	    /* This field is a lambda capture pack.  Return a TREE_VEC of
14393 	       the expanded fields to instantiate_class_template_1.  */
14394             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
14395 						    complain, in_decl);
14396             if (TREE_CODE (expanded_types) == TREE_VEC)
14397               {
14398                 len = TREE_VEC_LENGTH (expanded_types);
14399 		vec = make_tree_vec (len);
14400               }
14401             else
14402               {
14403                 /* All we did was update the type. Make a note of that.  */
14404                 type = expanded_types;
14405                 expanded_types = NULL_TREE;
14406               }
14407 	  }
14408 
14409 	for (int i = 0; i < len; ++i)
14410 	  {
14411 	    r = copy_decl (t);
14412 	    if (expanded_types)
14413 	      {
14414 		type = TREE_VEC_ELT (expanded_types, i);
14415 		DECL_NAME (r)
14416 		  = make_ith_pack_parameter_name (DECL_NAME (r), i);
14417 	      }
14418             else if (!type)
14419               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14420 
14421 	    if (type == error_mark_node)
14422 	      RETURN (error_mark_node);
14423 	    TREE_TYPE (r) = type;
14424 	    cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14425 
14426 	    if (DECL_C_BIT_FIELD (r))
14427 	      /* For bit-fields, DECL_BIT_FIELD_REPRESENTATIVE gives the
14428 		 number of bits.  */
14429 	      DECL_BIT_FIELD_REPRESENTATIVE (r)
14430 		= tsubst_expr (DECL_BIT_FIELD_REPRESENTATIVE (t), args,
14431 			       complain, in_decl,
14432 			       /*integral_constant_expression_p=*/true);
14433 	    if (DECL_INITIAL (t))
14434 	      {
14435 		/* Set up DECL_TEMPLATE_INFO so that we can get at the
14436 		   NSDMI in perform_member_init.  Still set DECL_INITIAL
14437 		   so that we know there is one.  */
14438 		DECL_INITIAL (r) = void_node;
14439 		gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
14440 		retrofit_lang_decl (r);
14441 		DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
14442 	      }
14443 	    /* We don't have to set DECL_CONTEXT here; it is set by
14444 	       finish_member_declaration.  */
14445 	    DECL_CHAIN (r) = NULL_TREE;
14446 
14447 	    apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14448 					    args, complain, in_decl);
14449 
14450 	    if (vec)
14451 	      TREE_VEC_ELT (vec, i) = r;
14452 	  }
14453 
14454 	if (vec)
14455 	  r = vec;
14456       }
14457       break;
14458 
14459     case USING_DECL:
14460       /* We reach here only for member using decls.  We also need to check
14461 	 uses_template_parms because DECL_DEPENDENT_P is not set for a
14462 	 using-declaration that designates a member of the current
14463 	 instantiation (c++/53549).  */
14464       if (DECL_DEPENDENT_P (t)
14465 	  || uses_template_parms (USING_DECL_SCOPE (t)))
14466 	{
14467 	  tree scope = USING_DECL_SCOPE (t);
14468 	  tree name = tsubst_copy (DECL_NAME (t), args, complain, in_decl);
14469 	  if (PACK_EXPANSION_P (scope))
14470 	    {
14471 	      tree vec = tsubst_pack_expansion (scope, args, complain, in_decl);
14472 	      int len = TREE_VEC_LENGTH (vec);
14473 	      r = make_tree_vec (len);
14474 	      for (int i = 0; i < len; ++i)
14475 		{
14476 		  tree escope = TREE_VEC_ELT (vec, i);
14477 		  tree elt = do_class_using_decl (escope, name);
14478 		  if (!elt)
14479 		    {
14480 		      r = error_mark_node;
14481 		      break;
14482 		    }
14483 		  else
14484 		    {
14485 		      TREE_PROTECTED (elt) = TREE_PROTECTED (t);
14486 		      TREE_PRIVATE (elt) = TREE_PRIVATE (t);
14487 		    }
14488 		  TREE_VEC_ELT (r, i) = elt;
14489 		}
14490 	    }
14491 	  else
14492 	    {
14493 	      tree inst_scope = tsubst_copy (USING_DECL_SCOPE (t), args,
14494 					     complain, in_decl);
14495 	      r = do_class_using_decl (inst_scope, name);
14496 	      if (!r)
14497 		r = error_mark_node;
14498 	      else
14499 		{
14500 		  TREE_PROTECTED (r) = TREE_PROTECTED (t);
14501 		  TREE_PRIVATE (r) = TREE_PRIVATE (t);
14502 		}
14503 	    }
14504 	}
14505       else
14506 	{
14507 	  r = copy_node (t);
14508 	  DECL_CHAIN (r) = NULL_TREE;
14509 	}
14510       break;
14511 
14512     case TYPE_DECL:
14513     case VAR_DECL:
14514       {
14515 	tree argvec = NULL_TREE;
14516 	tree gen_tmpl = NULL_TREE;
14517 	tree spec;
14518 	tree tmpl = NULL_TREE;
14519 	tree ctx;
14520 	tree type = NULL_TREE;
14521 	bool local_p;
14522 
14523 	if (TREE_TYPE (t) == error_mark_node)
14524 	  RETURN (error_mark_node);
14525 
14526 	if (TREE_CODE (t) == TYPE_DECL
14527 	    && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
14528 	  {
14529 	    /* If this is the canonical decl, we don't have to
14530 	       mess with instantiations, and often we can't (for
14531 	       typename, template type parms and such).  Note that
14532 	       TYPE_NAME is not correct for the above test if
14533 	       we've copied the type for a typedef.  */
14534 	    type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14535 	    if (type == error_mark_node)
14536 	      RETURN (error_mark_node);
14537 	    r = TYPE_NAME (type);
14538 	    break;
14539 	  }
14540 
14541 	/* Check to see if we already have the specialization we
14542 	   need.  */
14543 	spec = NULL_TREE;
14544 	if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
14545 	  {
14546 	    /* T is a static data member or namespace-scope entity.
14547 	       We have to substitute into namespace-scope variables
14548 	       (not just variable templates) because of cases like:
14549 
14550 	         template <class T> void f() { extern T t; }
14551 
14552 	       where the entity referenced is not known until
14553 	       instantiation time.  */
14554 	    local_p = false;
14555 	    ctx = DECL_CONTEXT (t);
14556 	    if (DECL_CLASS_SCOPE_P (t))
14557 	      {
14558 		ctx = tsubst_aggr_type (ctx, args,
14559 					complain,
14560 					in_decl, /*entering_scope=*/1);
14561 		/* If CTX is unchanged, then T is in fact the
14562 		   specialization we want.  That situation occurs when
14563 		   referencing a static data member within in its own
14564 		   class.  We can use pointer equality, rather than
14565 		   same_type_p, because DECL_CONTEXT is always
14566 		   canonical...  */
14567 		if (ctx == DECL_CONTEXT (t)
14568 		    /* ... unless T is a member template; in which
14569 		       case our caller can be willing to create a
14570 		       specialization of that template represented
14571 		       by T.  */
14572 		    && !(DECL_TI_TEMPLATE (t)
14573 			 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
14574 		  spec = t;
14575 	      }
14576 
14577 	    if (!spec)
14578 	      {
14579 		tmpl = DECL_TI_TEMPLATE (t);
14580 		gen_tmpl = most_general_template (tmpl);
14581 		argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
14582 		if (argvec != error_mark_node)
14583 		  argvec = (coerce_innermost_template_parms
14584 			    (DECL_TEMPLATE_PARMS (gen_tmpl),
14585 			     argvec, t, complain,
14586 			     /*all*/true, /*defarg*/true));
14587 		if (argvec == error_mark_node)
14588 		  RETURN (error_mark_node);
14589 		hash = hash_tmpl_and_args (gen_tmpl, argvec);
14590 		spec = retrieve_specialization (gen_tmpl, argvec, hash);
14591 	      }
14592 	  }
14593 	else
14594 	  {
14595 	    /* A local variable.  */
14596 	    local_p = true;
14597 	    /* Subsequent calls to pushdecl will fill this in.  */
14598 	    ctx = NULL_TREE;
14599 	    /* Unless this is a reference to a static variable from an
14600 	       enclosing function, in which case we need to fill it in now.  */
14601 	    if (TREE_STATIC (t))
14602 	      {
14603 		tree fn = enclosing_instantiation_of (DECL_CONTEXT (t));
14604 		if (fn != current_function_decl)
14605 		  ctx = fn;
14606 	      }
14607 	    spec = retrieve_local_specialization (t);
14608 	  }
14609 	/* If we already have the specialization we need, there is
14610 	   nothing more to do.  */
14611 	if (spec)
14612 	  {
14613 	    r = spec;
14614 	    break;
14615 	  }
14616 
14617 	/* Create a new node for the specialization we need.  */
14618 	if (type == NULL_TREE)
14619 	  {
14620 	    if (is_typedef_decl (t))
14621 	      type = DECL_ORIGINAL_TYPE (t);
14622 	    else
14623 	      type = TREE_TYPE (t);
14624 	    if (VAR_P (t)
14625 		&& VAR_HAD_UNKNOWN_BOUND (t)
14626 		&& type != error_mark_node)
14627 	      type = strip_array_domain (type);
14628 	    tree sub_args = args;
14629 	    if (tree auto_node = type_uses_auto (type))
14630 	      {
14631 		/* Mask off any template args past the variable's context so we
14632 		   don't replace the auto with an unrelated argument.  */
14633 		int nouter = TEMPLATE_TYPE_LEVEL (auto_node) - 1;
14634 		int extra = TMPL_ARGS_DEPTH (args) - nouter;
14635 		if (extra > 0)
14636 		  /* This should never happen with the new lambda instantiation
14637 		     model, but keep the handling just in case.  */
14638 		  gcc_assert (!CHECKING_P),
14639 		  sub_args = strip_innermost_template_args (args, extra);
14640 	      }
14641 	    type = tsubst (type, sub_args, complain, in_decl);
14642 	    /* Substituting the type might have recursively instantiated this
14643 	       same alias (c++/86171).  */
14644 	    if (gen_tmpl && DECL_ALIAS_TEMPLATE_P (gen_tmpl)
14645 		&& (spec = retrieve_specialization (gen_tmpl, argvec, hash)))
14646 	      {
14647 		r = spec;
14648 		break;
14649 	      }
14650 	  }
14651 	r = copy_decl (t);
14652 	if (VAR_P (r))
14653 	  {
14654 	    DECL_INITIALIZED_P (r) = 0;
14655 	    DECL_TEMPLATE_INSTANTIATED (r) = 0;
14656 	    if (type == error_mark_node)
14657 	      RETURN (error_mark_node);
14658 	    if (TREE_CODE (type) == FUNCTION_TYPE)
14659 	      {
14660 		/* It may seem that this case cannot occur, since:
14661 
14662 		   typedef void f();
14663 		   void g() { f x; }
14664 
14665 		   declares a function, not a variable.  However:
14666 
14667 		   typedef void f();
14668 		   template <typename T> void g() { T t; }
14669 		   template void g<f>();
14670 
14671 		   is an attempt to declare a variable with function
14672 		   type.  */
14673 		error ("variable %qD has function type",
14674 		       /* R is not yet sufficiently initialized, so we
14675 			  just use its name.  */
14676 		       DECL_NAME (r));
14677 		RETURN (error_mark_node);
14678 	      }
14679 	    type = complete_type (type);
14680 	    /* Wait until cp_finish_decl to set this again, to handle
14681 	       circular dependency (template/instantiate6.C). */
14682 	    DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
14683 	    type = check_var_type (DECL_NAME (r), type,
14684 				   DECL_SOURCE_LOCATION (r));
14685 	    if (DECL_HAS_VALUE_EXPR_P (t))
14686 	      {
14687 		tree ve = DECL_VALUE_EXPR (t);
14688 		/* If the DECL_VALUE_EXPR is converted to the declared type,
14689 		   preserve the identity so that gimplify_type_sizes works.  */
14690 		bool nop = (TREE_CODE (ve) == NOP_EXPR);
14691 		if (nop)
14692 		  ve = TREE_OPERAND (ve, 0);
14693 		ve = tsubst_expr (ve, args, complain, in_decl,
14694 				  /*constant_expression_p=*/false);
14695 		if (REFERENCE_REF_P (ve))
14696 		  {
14697 		    gcc_assert (TYPE_REF_P (type));
14698 		    ve = TREE_OPERAND (ve, 0);
14699 		  }
14700 		if (nop)
14701 		  ve = build_nop (type, ve);
14702 		else
14703 		  gcc_checking_assert (TREE_TYPE (ve) == type);
14704 		SET_DECL_VALUE_EXPR (r, ve);
14705 	      }
14706 	    if (CP_DECL_THREAD_LOCAL_P (r)
14707 		&& !processing_template_decl)
14708 	      set_decl_tls_model (r, decl_default_tls_model (r));
14709 	  }
14710 	else if (DECL_SELF_REFERENCE_P (t))
14711 	  SET_DECL_SELF_REFERENCE_P (r);
14712 	TREE_TYPE (r) = type;
14713 	cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14714 	DECL_CONTEXT (r) = ctx;
14715 	/* Clear out the mangled name and RTL for the instantiation.  */
14716 	SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
14717 	if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
14718 	  SET_DECL_RTL (r, NULL);
14719 	/* The initializer must not be expanded until it is required;
14720 	   see [temp.inst].  */
14721 	DECL_INITIAL (r) = NULL_TREE;
14722 	DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
14723 	if (VAR_P (r))
14724 	  {
14725 	    if (DECL_LANG_SPECIFIC (r))
14726 	      SET_DECL_DEPENDENT_INIT_P (r, false);
14727 
14728 	    SET_DECL_MODE (r, VOIDmode);
14729 
14730 	    /* Possibly limit visibility based on template args.  */
14731 	    DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
14732 	    if (DECL_VISIBILITY_SPECIFIED (t))
14733 	      {
14734 		DECL_VISIBILITY_SPECIFIED (r) = 0;
14735 		DECL_ATTRIBUTES (r)
14736 		  = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
14737 	      }
14738 	    determine_visibility (r);
14739 	  }
14740 
14741 	if (!local_p)
14742 	  {
14743 	    /* A static data member declaration is always marked
14744 	       external when it is declared in-class, even if an
14745 	       initializer is present.  We mimic the non-template
14746 	       processing here.  */
14747 	    DECL_EXTERNAL (r) = 1;
14748 	    if (DECL_NAMESPACE_SCOPE_P (t))
14749 	      DECL_NOT_REALLY_EXTERN (r) = 1;
14750 
14751 	    DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
14752 	    SET_DECL_IMPLICIT_INSTANTIATION (r);
14753 	    /* Remember whether we require constant initialization of
14754 	       a non-constant template variable.  */
14755 	    TINFO_VAR_DECLARED_CONSTINIT (DECL_TEMPLATE_INFO (r))
14756 	      = TINFO_VAR_DECLARED_CONSTINIT (DECL_TEMPLATE_INFO (t));
14757 	    if (!error_operand_p (r) || (complain & tf_error))
14758 	      register_specialization (r, gen_tmpl, argvec, false, hash);
14759 	  }
14760 	else
14761 	  {
14762 	    if (DECL_LANG_SPECIFIC (r))
14763 	      DECL_TEMPLATE_INFO (r) = NULL_TREE;
14764 	    if (!cp_unevaluated_operand)
14765 	      register_local_specialization (r, t);
14766 	  }
14767 
14768 	DECL_CHAIN (r) = NULL_TREE;
14769 
14770 	apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
14771 					/*flags=*/0,
14772 					args, complain, in_decl);
14773 
14774 	/* Preserve a typedef that names a type.  */
14775 	if (is_typedef_decl (r) && type != error_mark_node)
14776 	  {
14777 	    DECL_ORIGINAL_TYPE (r) = NULL_TREE;
14778 	    set_underlying_type (r);
14779 	    if (TYPE_DECL_ALIAS_P (r))
14780 	      /* An alias template specialization can be dependent
14781 		 even if its underlying type is not.  */
14782 	      TYPE_DEPENDENT_P_VALID (TREE_TYPE (r)) = false;
14783 	  }
14784 
14785 	layout_decl (r, 0);
14786       }
14787       break;
14788 
14789     default:
14790       gcc_unreachable ();
14791     }
14792 #undef RETURN
14793 
14794  out:
14795   /* Restore the file and line information.  */
14796   input_location = saved_loc;
14797 
14798   return r;
14799 }
14800 
14801 /* Substitute into the complete parameter type list PARMS.  */
14802 
14803 tree
tsubst_function_parms(tree parms,tree args,tsubst_flags_t complain,tree in_decl)14804 tsubst_function_parms (tree parms,
14805 		       tree args,
14806 		       tsubst_flags_t complain,
14807 		       tree in_decl)
14808 {
14809   return tsubst_arg_types (parms, args, NULL_TREE, complain, in_decl);
14810 }
14811 
14812 /* Substitute into the ARG_TYPES of a function type.
14813    If END is a TREE_CHAIN, leave it and any following types
14814    un-substituted.  */
14815 
14816 static tree
tsubst_arg_types(tree arg_types,tree args,tree end,tsubst_flags_t complain,tree in_decl)14817 tsubst_arg_types (tree arg_types,
14818 		  tree args,
14819 		  tree end,
14820 		  tsubst_flags_t complain,
14821 		  tree in_decl)
14822 {
14823   tree remaining_arg_types;
14824   tree type = NULL_TREE;
14825   int i = 1;
14826   tree expanded_args = NULL_TREE;
14827   tree default_arg;
14828 
14829   if (!arg_types || arg_types == void_list_node || arg_types == end)
14830     return arg_types;
14831 
14832   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
14833 					  args, end, complain, in_decl);
14834   if (remaining_arg_types == error_mark_node)
14835     return error_mark_node;
14836 
14837   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
14838     {
14839       /* For a pack expansion, perform substitution on the
14840          entire expression. Later on, we'll handle the arguments
14841          one-by-one.  */
14842       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
14843                                             args, complain, in_decl);
14844 
14845       if (TREE_CODE (expanded_args) == TREE_VEC)
14846         /* So that we'll spin through the parameters, one by one.  */
14847         i = TREE_VEC_LENGTH (expanded_args);
14848       else
14849         {
14850           /* We only partially substituted into the parameter
14851              pack. Our type is TYPE_PACK_EXPANSION.  */
14852           type = expanded_args;
14853           expanded_args = NULL_TREE;
14854         }
14855     }
14856 
14857   while (i > 0) {
14858     --i;
14859 
14860     if (expanded_args)
14861       type = TREE_VEC_ELT (expanded_args, i);
14862     else if (!type)
14863       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
14864 
14865     if (type == error_mark_node)
14866       return error_mark_node;
14867     if (VOID_TYPE_P (type))
14868       {
14869         if (complain & tf_error)
14870           {
14871             error ("invalid parameter type %qT", type);
14872             if (in_decl)
14873               error ("in declaration %q+D", in_decl);
14874           }
14875         return error_mark_node;
14876     }
14877     /* DR 657. */
14878     if (abstract_virtuals_error_sfinae (ACU_PARM, type, complain))
14879       return error_mark_node;
14880 
14881     /* Do array-to-pointer, function-to-pointer conversion, and ignore
14882        top-level qualifiers as required.  */
14883     type = cv_unqualified (type_decays_to (type));
14884 
14885     /* We do not substitute into default arguments here.  The standard
14886        mandates that they be instantiated only when needed, which is
14887        done in build_over_call.  */
14888     default_arg = TREE_PURPOSE (arg_types);
14889 
14890     /* Except that we do substitute default arguments under tsubst_lambda_expr,
14891        since the new op() won't have any associated template arguments for us
14892        to refer to later.  */
14893     if (lambda_fn_in_template_p (in_decl))
14894       default_arg = tsubst_copy_and_build (default_arg, args, complain, in_decl,
14895 					   false/*fn*/, false/*constexpr*/);
14896 
14897     if (default_arg && TREE_CODE (default_arg) == DEFERRED_PARSE)
14898       {
14899         /* We've instantiated a template before its default arguments
14900            have been parsed.  This can happen for a nested template
14901            class, and is not an error unless we require the default
14902            argument in a call of this function.  */
14903         remaining_arg_types =
14904           tree_cons (default_arg, type, remaining_arg_types);
14905 	vec_safe_push (DEFPARSE_INSTANTIATIONS (default_arg),
14906 		       remaining_arg_types);
14907       }
14908     else
14909       remaining_arg_types =
14910         hash_tree_cons (default_arg, type, remaining_arg_types);
14911   }
14912 
14913   return remaining_arg_types;
14914 }
14915 
14916 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
14917    *not* handle the exception-specification for FNTYPE, because the
14918    initial substitution of explicitly provided template parameters
14919    during argument deduction forbids substitution into the
14920    exception-specification:
14921 
14922      [temp.deduct]
14923 
14924      All references in the function type of the function template to  the
14925      corresponding template parameters are replaced by the specified tem-
14926      plate argument values.  If a substitution in a template parameter or
14927      in  the function type of the function template results in an invalid
14928      type, type deduction fails.  [Note: The equivalent  substitution  in
14929      exception specifications is done only when the function is instanti-
14930      ated, at which point a program is  ill-formed  if  the  substitution
14931      results in an invalid type.]  */
14932 
14933 static tree
tsubst_function_type(tree t,tree args,tsubst_flags_t complain,tree in_decl)14934 tsubst_function_type (tree t,
14935 		      tree args,
14936 		      tsubst_flags_t complain,
14937 		      tree in_decl)
14938 {
14939   tree return_type;
14940   tree arg_types = NULL_TREE;
14941 
14942   /* The TYPE_CONTEXT is not used for function/method types.  */
14943   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
14944 
14945   /* DR 1227: Mixing immediate and non-immediate contexts in deduction
14946      failure.  */
14947   bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
14948 
14949   if (late_return_type_p)
14950     {
14951       /* Substitute the argument types.  */
14952       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
14953 				    complain, in_decl);
14954       if (arg_types == error_mark_node)
14955 	return error_mark_node;
14956 
14957       tree save_ccp = current_class_ptr;
14958       tree save_ccr = current_class_ref;
14959       tree this_type = (TREE_CODE (t) == METHOD_TYPE
14960 			? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
14961       bool do_inject = this_type && CLASS_TYPE_P (this_type);
14962       if (do_inject)
14963 	{
14964 	  /* DR 1207: 'this' is in scope in the trailing return type.  */
14965 	  inject_this_parameter (this_type, cp_type_quals (this_type));
14966 	}
14967 
14968       /* Substitute the return type.  */
14969       return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14970 
14971       if (do_inject)
14972 	{
14973 	  current_class_ptr = save_ccp;
14974 	  current_class_ref = save_ccr;
14975 	}
14976     }
14977   else
14978     /* Substitute the return type.  */
14979     return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14980 
14981   if (return_type == error_mark_node)
14982     return error_mark_node;
14983   /* DR 486 clarifies that creation of a function type with an
14984      invalid return type is a deduction failure.  */
14985   if (TREE_CODE (return_type) == ARRAY_TYPE
14986       || TREE_CODE (return_type) == FUNCTION_TYPE)
14987     {
14988       if (complain & tf_error)
14989 	{
14990 	  if (TREE_CODE (return_type) == ARRAY_TYPE)
14991 	    error ("function returning an array");
14992 	  else
14993 	    error ("function returning a function");
14994 	}
14995       return error_mark_node;
14996     }
14997   /* And DR 657. */
14998   if (abstract_virtuals_error_sfinae (ACU_RETURN, return_type, complain))
14999     return error_mark_node;
15000 
15001   if (!late_return_type_p)
15002     {
15003       /* Substitute the argument types.  */
15004       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15005 				    complain, in_decl);
15006       if (arg_types == error_mark_node)
15007 	return error_mark_node;
15008     }
15009 
15010   /* Construct a new type node and return it.  */
15011   return rebuild_function_or_method_type (t, return_type, arg_types,
15012 					  /*raises=*/NULL_TREE, complain);
15013 }
15014 
15015 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
15016    ARGS into that specification, and return the substituted
15017    specification.  If there is no specification, return NULL_TREE.  */
15018 
15019 static tree
tsubst_exception_specification(tree fntype,tree args,tsubst_flags_t complain,tree in_decl,bool defer_ok)15020 tsubst_exception_specification (tree fntype,
15021 				tree args,
15022 				tsubst_flags_t complain,
15023 				tree in_decl,
15024 				bool defer_ok)
15025 {
15026   tree specs;
15027   tree new_specs;
15028 
15029   specs = TYPE_RAISES_EXCEPTIONS (fntype);
15030   new_specs = NULL_TREE;
15031   if (specs && TREE_PURPOSE (specs))
15032     {
15033       /* A noexcept-specifier.  */
15034       tree expr = TREE_PURPOSE (specs);
15035       if (TREE_CODE (expr) == INTEGER_CST)
15036 	new_specs = expr;
15037       else if (defer_ok)
15038 	{
15039 	  /* Defer instantiation of noexcept-specifiers to avoid
15040 	     excessive instantiations (c++/49107).  */
15041 	  new_specs = make_node (DEFERRED_NOEXCEPT);
15042 	  if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15043 	    {
15044 	      /* We already partially instantiated this member template,
15045 		 so combine the new args with the old.  */
15046 	      DEFERRED_NOEXCEPT_PATTERN (new_specs)
15047 		= DEFERRED_NOEXCEPT_PATTERN (expr);
15048 	      DEFERRED_NOEXCEPT_ARGS (new_specs)
15049 		= add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
15050 	    }
15051 	  else
15052 	    {
15053 	      DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
15054 	      DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
15055 	    }
15056 	}
15057       else
15058 	{
15059 	  if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15060 	    {
15061 	      args = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr),
15062 					   args);
15063 	      expr = DEFERRED_NOEXCEPT_PATTERN (expr);
15064 	    }
15065 	  new_specs = tsubst_copy_and_build
15066 	    (expr, args, complain, in_decl, /*function_p=*/false,
15067 	     /*integral_constant_expression_p=*/true);
15068 	}
15069       new_specs = build_noexcept_spec (new_specs, complain);
15070     }
15071   else if (specs)
15072     {
15073       if (! TREE_VALUE (specs))
15074 	new_specs = specs;
15075       else
15076 	while (specs)
15077 	  {
15078 	    tree spec;
15079             int i, len = 1;
15080             tree expanded_specs = NULL_TREE;
15081 
15082             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
15083               {
15084                 /* Expand the pack expansion type.  */
15085                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
15086                                                        args, complain,
15087                                                        in_decl);
15088 
15089 		if (expanded_specs == error_mark_node)
15090 		  return error_mark_node;
15091 		else if (TREE_CODE (expanded_specs) == TREE_VEC)
15092 		  len = TREE_VEC_LENGTH (expanded_specs);
15093 		else
15094 		  {
15095 		    /* We're substituting into a member template, so
15096 		       we got a TYPE_PACK_EXPANSION back.  Add that
15097 		       expansion and move on.  */
15098 		    gcc_assert (TREE_CODE (expanded_specs)
15099 				== TYPE_PACK_EXPANSION);
15100 		    new_specs = add_exception_specifier (new_specs,
15101 							 expanded_specs,
15102 							 complain);
15103 		    specs = TREE_CHAIN (specs);
15104 		    continue;
15105 		  }
15106               }
15107 
15108             for (i = 0; i < len; ++i)
15109               {
15110                 if (expanded_specs)
15111                   spec = TREE_VEC_ELT (expanded_specs, i);
15112                 else
15113                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
15114                 if (spec == error_mark_node)
15115                   return spec;
15116                 new_specs = add_exception_specifier (new_specs, spec,
15117                                                      complain);
15118               }
15119 
15120             specs = TREE_CHAIN (specs);
15121 	  }
15122     }
15123   return new_specs;
15124 }
15125 
15126 /* Take the tree structure T and replace template parameters used
15127    therein with the argument vector ARGS.  IN_DECL is an associated
15128    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
15129    Issue error and warning messages under control of COMPLAIN.  Note
15130    that we must be relatively non-tolerant of extensions here, in
15131    order to preserve conformance; if we allow substitutions that
15132    should not be allowed, we may allow argument deductions that should
15133    not succeed, and therefore report ambiguous overload situations
15134    where there are none.  In theory, we could allow the substitution,
15135    but indicate that it should have failed, and allow our caller to
15136    make sure that the right thing happens, but we don't try to do this
15137    yet.
15138 
15139    This function is used for dealing with types, decls and the like;
15140    for expressions, use tsubst_expr or tsubst_copy.  */
15141 
15142 tree
tsubst(tree t,tree args,tsubst_flags_t complain,tree in_decl)15143 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15144 {
15145   enum tree_code code;
15146   tree type, r = NULL_TREE;
15147 
15148   if (t == NULL_TREE || t == error_mark_node
15149       || t == integer_type_node
15150       || t == void_type_node
15151       || t == char_type_node
15152       || t == unknown_type_node
15153       || TREE_CODE (t) == NAMESPACE_DECL
15154       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
15155     return t;
15156 
15157   if (DECL_P (t))
15158     return tsubst_decl (t, args, complain);
15159 
15160   if (args == NULL_TREE)
15161     return t;
15162 
15163   code = TREE_CODE (t);
15164 
15165   if (code == IDENTIFIER_NODE)
15166     type = IDENTIFIER_TYPE_VALUE (t);
15167   else
15168     type = TREE_TYPE (t);
15169 
15170   gcc_assert (type != unknown_type_node);
15171 
15172   /* Reuse typedefs.  We need to do this to handle dependent attributes,
15173      such as attribute aligned.  */
15174   if (TYPE_P (t)
15175       && typedef_variant_p (t))
15176     {
15177       tree decl = TYPE_NAME (t);
15178 
15179       if (alias_template_specialization_p (t, nt_opaque))
15180 	{
15181 	  /* DECL represents an alias template and we want to
15182 	     instantiate it.  */
15183 	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15184 	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15185 	  r = instantiate_alias_template (tmpl, gen_args, complain);
15186 	}
15187       else if (DECL_CLASS_SCOPE_P (decl)
15188 	       && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
15189 	       && uses_template_parms (DECL_CONTEXT (decl)))
15190 	{
15191 	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15192 	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15193 	  r = retrieve_specialization (tmpl, gen_args, 0);
15194 	}
15195       else if (DECL_FUNCTION_SCOPE_P (decl)
15196 	       && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
15197 	       && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
15198 	r = retrieve_local_specialization (decl);
15199       else
15200 	/* The typedef is from a non-template context.  */
15201 	return t;
15202 
15203       if (r)
15204 	{
15205 	  r = TREE_TYPE (r);
15206 	  r = cp_build_qualified_type_real
15207 	    (r, cp_type_quals (t) | cp_type_quals (r),
15208 	     complain | tf_ignore_bad_quals);
15209 	  return r;
15210 	}
15211       else
15212 	{
15213 	  /* We don't have an instantiation yet, so drop the typedef.  */
15214 	  int quals = cp_type_quals (t);
15215 	  t = DECL_ORIGINAL_TYPE (decl);
15216 	  t = cp_build_qualified_type_real (t, quals,
15217 					    complain | tf_ignore_bad_quals);
15218 	}
15219     }
15220 
15221   bool fndecl_type = (complain & tf_fndecl_type);
15222   complain &= ~tf_fndecl_type;
15223 
15224   if (type
15225       && code != TYPENAME_TYPE
15226       && code != TEMPLATE_TYPE_PARM
15227       && code != TEMPLATE_PARM_INDEX
15228       && code != IDENTIFIER_NODE
15229       && code != FUNCTION_TYPE
15230       && code != METHOD_TYPE)
15231     type = tsubst (type, args, complain, in_decl);
15232   if (type == error_mark_node)
15233     return error_mark_node;
15234 
15235   switch (code)
15236     {
15237     case RECORD_TYPE:
15238     case UNION_TYPE:
15239     case ENUMERAL_TYPE:
15240       return tsubst_aggr_type (t, args, complain, in_decl,
15241 			       /*entering_scope=*/0);
15242 
15243     case ERROR_MARK:
15244     case IDENTIFIER_NODE:
15245     case VOID_TYPE:
15246     case REAL_TYPE:
15247     case COMPLEX_TYPE:
15248     case VECTOR_TYPE:
15249     case BOOLEAN_TYPE:
15250     case NULLPTR_TYPE:
15251     case LANG_TYPE:
15252       return t;
15253 
15254     case INTEGER_TYPE:
15255       if (t == integer_type_node)
15256 	return t;
15257 
15258       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
15259           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
15260         return t;
15261 
15262       {
15263 	tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
15264 
15265 	max = tsubst_expr (omax, args, complain, in_decl,
15266 			   /*integral_constant_expression_p=*/false);
15267 
15268 	/* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
15269 	   needed.  */
15270 	if (TREE_CODE (max) == NOP_EXPR
15271 	    && TREE_SIDE_EFFECTS (omax)
15272 	    && !TREE_TYPE (max))
15273 	  TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
15274 
15275 	/* If we're in a partial instantiation, preserve the magic NOP_EXPR
15276 	   with TREE_SIDE_EFFECTS that indicates this is not an integral
15277 	   constant expression.  */
15278 	if (processing_template_decl
15279 	    && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
15280 	  {
15281 	    gcc_assert (TREE_CODE (max) == NOP_EXPR);
15282 	    TREE_SIDE_EFFECTS (max) = 1;
15283 	  }
15284 
15285 	return compute_array_index_type (NULL_TREE, max, complain);
15286       }
15287 
15288     case TEMPLATE_TYPE_PARM:
15289     case TEMPLATE_TEMPLATE_PARM:
15290     case BOUND_TEMPLATE_TEMPLATE_PARM:
15291     case TEMPLATE_PARM_INDEX:
15292       {
15293 	int idx;
15294 	int level;
15295 	int levels;
15296 	tree arg = NULL_TREE;
15297 
15298 	r = NULL_TREE;
15299 
15300 	gcc_assert (TREE_VEC_LENGTH (args) > 0);
15301 	template_parm_level_and_index (t, &level, &idx);
15302 
15303 	levels = TMPL_ARGS_DEPTH (args);
15304 	if (level <= levels
15305 	    && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
15306 	  {
15307 	    arg = TMPL_ARG (args, level, idx);
15308 
15309 	    /* See through ARGUMENT_PACK_SELECT arguments. */
15310 	    if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
15311 	      arg = argument_pack_select_arg (arg);
15312 	  }
15313 
15314 	if (arg == error_mark_node)
15315 	  return error_mark_node;
15316 	else if (arg != NULL_TREE)
15317 	  {
15318 	    if (ARGUMENT_PACK_P (arg))
15319 	      /* If ARG is an argument pack, we don't actually want to
15320 		 perform a substitution here, because substitutions
15321 		 for argument packs are only done
15322 		 element-by-element. We can get to this point when
15323 		 substituting the type of a non-type template
15324 		 parameter pack, when that type actually contains
15325 		 template parameter packs from an outer template, e.g.,
15326 
15327 	         template<typename... Types> struct A {
15328 		   template<Types... Values> struct B { };
15329                  };  */
15330 	      return t;
15331 
15332 	    if (code == TEMPLATE_TYPE_PARM)
15333 	      {
15334 		int quals;
15335 
15336 		/* When building concept checks for the purpose of
15337 		   deducing placeholders, we can end up with wildcards
15338 		   where types are expected. Adjust this to the deduced
15339 		   value.  */
15340 		if (TREE_CODE (arg) == WILDCARD_DECL)
15341 		  arg = TREE_TYPE (TREE_TYPE (arg));
15342 
15343 		gcc_assert (TYPE_P (arg));
15344 
15345 		quals = cp_type_quals (arg) | cp_type_quals (t);
15346 
15347 		return cp_build_qualified_type_real
15348 		  (arg, quals, complain | tf_ignore_bad_quals);
15349 	      }
15350 	    else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
15351 	      {
15352 		/* We are processing a type constructed from a
15353 		   template template parameter.  */
15354 		tree argvec = tsubst (TYPE_TI_ARGS (t),
15355 				      args, complain, in_decl);
15356 		if (argvec == error_mark_node)
15357 		  return error_mark_node;
15358 
15359 		gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
15360 			    || TREE_CODE (arg) == TEMPLATE_DECL
15361 			    || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
15362 
15363 		if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
15364 		  /* Consider this code:
15365 
15366 			template <template <class> class Template>
15367 			struct Internal {
15368 			template <class Arg> using Bind = Template<Arg>;
15369 			};
15370 
15371 			template <template <class> class Template, class Arg>
15372 			using Instantiate = Template<Arg>; //#0
15373 
15374 			template <template <class> class Template,
15375                                   class Argument>
15376 			using Bind =
15377 			  Instantiate<Internal<Template>::template Bind,
15378 				      Argument>; //#1
15379 
15380 		     When #1 is parsed, the
15381 		     BOUND_TEMPLATE_TEMPLATE_PARM representing the
15382 		     parameter `Template' in #0 matches the
15383 		     UNBOUND_CLASS_TEMPLATE representing the argument
15384 		     `Internal<Template>::template Bind'; We then want
15385 		     to assemble the type `Bind<Argument>' that can't
15386 		     be fully created right now, because
15387 		     `Internal<Template>' not being complete, the Bind
15388 		     template cannot be looked up in that context.  So
15389 		     we need to "store" `Bind<Argument>' for later
15390 		     when the context of Bind becomes complete.  Let's
15391 		     store that in a TYPENAME_TYPE.  */
15392 		  return make_typename_type (TYPE_CONTEXT (arg),
15393 					     build_nt (TEMPLATE_ID_EXPR,
15394 						       TYPE_IDENTIFIER (arg),
15395 						       argvec),
15396 					     typename_type,
15397 					     complain);
15398 
15399 		/* We can get a TEMPLATE_TEMPLATE_PARM here when we
15400 		   are resolving nested-types in the signature of a
15401 		   member function templates.  Otherwise ARG is a
15402 		   TEMPLATE_DECL and is the real template to be
15403 		   instantiated.  */
15404 		if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
15405 		  arg = TYPE_NAME (arg);
15406 
15407 		r = lookup_template_class (arg,
15408 					   argvec, in_decl,
15409 					   DECL_CONTEXT (arg),
15410 					    /*entering_scope=*/0,
15411 					   complain);
15412 		return cp_build_qualified_type_real
15413 		  (r, cp_type_quals (t) | cp_type_quals (r), complain);
15414 	      }
15415 	    else if (code == TEMPLATE_TEMPLATE_PARM)
15416 	      return arg;
15417 	    else
15418 	      /* TEMPLATE_PARM_INDEX.  */
15419 	      return convert_from_reference (unshare_expr (arg));
15420 	  }
15421 
15422 	if (level == 1)
15423 	  /* This can happen during the attempted tsubst'ing in
15424 	     unify.  This means that we don't yet have any information
15425 	     about the template parameter in question.  */
15426 	  return t;
15427 
15428 	/* Early in template argument deduction substitution, we don't
15429 	   want to reduce the level of 'auto', or it will be confused
15430 	   with a normal template parm in subsequent deduction.
15431 	   Similarly, don't reduce the level of template parameters to
15432 	   avoid mismatches when deducing their types.  */
15433 	if (complain & tf_partial)
15434 	  return t;
15435 
15436 	/* If we get here, we must have been looking at a parm for a
15437 	   more deeply nested template.  Make a new version of this
15438 	   template parameter, but with a lower level.  */
15439 	switch (code)
15440 	  {
15441 	  case TEMPLATE_TYPE_PARM:
15442 	  case TEMPLATE_TEMPLATE_PARM:
15443 	  case BOUND_TEMPLATE_TEMPLATE_PARM:
15444 	    if (cp_type_quals (t))
15445 	      {
15446 		r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
15447 		r = cp_build_qualified_type_real
15448 		  (r, cp_type_quals (t),
15449 		   complain | (code == TEMPLATE_TYPE_PARM
15450 			       ? tf_ignore_bad_quals : 0));
15451 	      }
15452 	    else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
15453 		     && PLACEHOLDER_TYPE_CONSTRAINTS (t)
15454 		     && (r = (TEMPLATE_PARM_DESCENDANTS
15455 			      (TEMPLATE_TYPE_PARM_INDEX (t))))
15456 		     && (r = TREE_TYPE (r))
15457 		     && !PLACEHOLDER_TYPE_CONSTRAINTS (r))
15458 	      /* Break infinite recursion when substituting the constraints
15459 		 of a constrained placeholder.  */;
15460 	    else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
15461 		     && !PLACEHOLDER_TYPE_CONSTRAINTS (t)
15462 		     && !CLASS_PLACEHOLDER_TEMPLATE (t)
15463 		     && (arg = TEMPLATE_TYPE_PARM_INDEX (t),
15464 			 r = TEMPLATE_PARM_DESCENDANTS (arg))
15465 		     && (TEMPLATE_PARM_LEVEL (r)
15466 			 == TEMPLATE_PARM_LEVEL (arg) - levels))
15467 		/* Cache the simple case of lowering a type parameter.  */
15468 	      r = TREE_TYPE (r);
15469 	    else
15470 	      {
15471 		r = copy_type (t);
15472 		TEMPLATE_TYPE_PARM_INDEX (r)
15473 		  = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
15474 						r, levels, args, complain);
15475 		TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
15476 		TYPE_MAIN_VARIANT (r) = r;
15477 		TYPE_POINTER_TO (r) = NULL_TREE;
15478 		TYPE_REFERENCE_TO (r) = NULL_TREE;
15479 
15480                 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
15481 		  {
15482 		    /* Propagate constraints on placeholders since they are
15483 		       only instantiated during satisfaction.  */
15484 		    if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
15485 		      PLACEHOLDER_TYPE_CONSTRAINTS (r) = constr;
15486 		    else if (tree pl = CLASS_PLACEHOLDER_TEMPLATE (t))
15487 		      {
15488 			pl = tsubst_copy (pl, args, complain, in_decl);
15489 			CLASS_PLACEHOLDER_TEMPLATE (r) = pl;
15490 		      }
15491 		  }
15492 
15493 		if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
15494 		  /* We have reduced the level of the template
15495 		     template parameter, but not the levels of its
15496 		     template parameters, so canonical_type_parameter
15497 		     will not be able to find the canonical template
15498 		     template parameter for this level. Thus, we
15499 		     require structural equality checking to compare
15500 		     TEMPLATE_TEMPLATE_PARMs. */
15501 		  SET_TYPE_STRUCTURAL_EQUALITY (r);
15502 		else if (TYPE_STRUCTURAL_EQUALITY_P (t))
15503 		  SET_TYPE_STRUCTURAL_EQUALITY (r);
15504 		else
15505 		  TYPE_CANONICAL (r) = canonical_type_parameter (r);
15506 
15507 		if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
15508 		  {
15509 		    tree tinfo = TYPE_TEMPLATE_INFO (t);
15510 		    /* We might need to substitute into the types of non-type
15511 		       template parameters.  */
15512 		    tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
15513 					complain, in_decl);
15514 		    if (tmpl == error_mark_node)
15515 		      return error_mark_node;
15516 		    tree argvec = tsubst (TI_ARGS (tinfo), args,
15517 					  complain, in_decl);
15518 		    if (argvec == error_mark_node)
15519 		      return error_mark_node;
15520 
15521 		    TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
15522 		      = build_template_info (tmpl, argvec);
15523 		  }
15524 	      }
15525 	    break;
15526 
15527 	  case TEMPLATE_PARM_INDEX:
15528 	    /* OK, now substitute the type of the non-type parameter.  We
15529 	       couldn't do it earlier because it might be an auto parameter,
15530 	       and we wouldn't need to if we had an argument.  */
15531 	    type = tsubst (type, args, complain, in_decl);
15532 	    if (type == error_mark_node)
15533 	      return error_mark_node;
15534 	    r = reduce_template_parm_level (t, type, levels, args, complain);
15535 	    break;
15536 
15537 	  default:
15538 	    gcc_unreachable ();
15539 	  }
15540 
15541 	return r;
15542       }
15543 
15544     case TREE_LIST:
15545       {
15546 	tree purpose, value, chain;
15547 
15548 	if (t == void_list_node)
15549 	  return t;
15550 
15551 	if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
15552 	    || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
15553 	  {
15554 	    /* We have pack expansions, so expand those and
15555 	       create a new list out of it.  */
15556 
15557 	    /* Expand the argument expressions.  */
15558 	    tree purposevec = NULL_TREE;
15559 	    if (TREE_PURPOSE (t))
15560 	      purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
15561 						  complain, in_decl);
15562 	    if (purposevec == error_mark_node)
15563 	      return error_mark_node;
15564 
15565 	    tree valuevec = NULL_TREE;
15566 	    if (TREE_VALUE (t))
15567 	      valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
15568 						complain, in_decl);
15569 	    if (valuevec == error_mark_node)
15570 	      return error_mark_node;
15571 
15572 	    /* Build the rest of the list.  */
15573 	    tree chain = TREE_CHAIN (t);
15574 	    if (chain && chain != void_type_node)
15575 	      chain = tsubst (chain, args, complain, in_decl);
15576 	    if (chain == error_mark_node)
15577 	      return error_mark_node;
15578 
15579 	    /* Determine the number of arguments.  */
15580 	    int len = -1;
15581 	    if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
15582 	      {
15583 		len = TREE_VEC_LENGTH (purposevec);
15584 		gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
15585 	      }
15586 	    else if (TREE_CODE (valuevec) == TREE_VEC)
15587 	      len = TREE_VEC_LENGTH (valuevec);
15588 	    else
15589 	      {
15590 		/* Since we only performed a partial substitution into
15591 		   the argument pack, we only RETURN (a single list
15592 		   node.  */
15593 		if (purposevec == TREE_PURPOSE (t)
15594 		    && valuevec == TREE_VALUE (t)
15595 		    && chain == TREE_CHAIN (t))
15596 		  return t;
15597 
15598 		return tree_cons (purposevec, valuevec, chain);
15599 	      }
15600 
15601 	    /* Convert the argument vectors into a TREE_LIST.  */
15602 	    for (int i = len; i-- > 0; )
15603 	      {
15604 		purpose = (purposevec ? TREE_VEC_ELT (purposevec, i)
15605 			   : NULL_TREE);
15606 		value = (valuevec ? TREE_VEC_ELT (valuevec, i)
15607 			 : NULL_TREE);
15608 
15609 		/* Build the list (backwards).  */
15610 		chain = hash_tree_cons (purpose, value, chain);
15611 	      }
15612 
15613 	    return chain;
15614 	  }
15615 
15616 	purpose = TREE_PURPOSE (t);
15617 	if (purpose)
15618 	  {
15619 	    purpose = tsubst (purpose, args, complain, in_decl);
15620 	    if (purpose == error_mark_node)
15621 	      return error_mark_node;
15622 	  }
15623 	value = TREE_VALUE (t);
15624 	if (value)
15625 	  {
15626 	    value = tsubst (value, args, complain, in_decl);
15627 	    if (value == error_mark_node)
15628 	      return error_mark_node;
15629 	  }
15630 	chain = TREE_CHAIN (t);
15631 	if (chain && chain != void_type_node)
15632 	  {
15633 	    chain = tsubst (chain, args, complain, in_decl);
15634 	    if (chain == error_mark_node)
15635 	      return error_mark_node;
15636 	  }
15637 	if (purpose == TREE_PURPOSE (t)
15638 	    && value == TREE_VALUE (t)
15639 	    && chain == TREE_CHAIN (t))
15640 	  return t;
15641 	return hash_tree_cons (purpose, value, chain);
15642       }
15643 
15644     case TREE_BINFO:
15645       /* We should never be tsubsting a binfo.  */
15646       gcc_unreachable ();
15647 
15648     case TREE_VEC:
15649       /* A vector of template arguments.  */
15650       gcc_assert (!type);
15651       return tsubst_template_args (t, args, complain, in_decl);
15652 
15653     case POINTER_TYPE:
15654     case REFERENCE_TYPE:
15655       {
15656 	if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
15657 	  return t;
15658 
15659 	/* [temp.deduct]
15660 
15661 	   Type deduction may fail for any of the following
15662 	   reasons:
15663 
15664 	   -- Attempting to create a pointer to reference type.
15665 	   -- Attempting to create a reference to a reference type or
15666 	      a reference to void.
15667 
15668 	  Core issue 106 says that creating a reference to a reference
15669 	  during instantiation is no longer a cause for failure. We
15670 	  only enforce this check in strict C++98 mode.  */
15671 	if ((TYPE_REF_P (type)
15672 	     && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
15673 	    || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
15674 	  {
15675 	    static location_t last_loc;
15676 
15677 	    /* We keep track of the last time we issued this error
15678 	       message to avoid spewing a ton of messages during a
15679 	       single bad template instantiation.  */
15680 	    if (complain & tf_error
15681 		&& last_loc != input_location)
15682 	      {
15683 		if (VOID_TYPE_P (type))
15684 		  error ("forming reference to void");
15685                else if (code == POINTER_TYPE)
15686                  error ("forming pointer to reference type %qT", type);
15687                else
15688 		  error ("forming reference to reference type %qT", type);
15689 		last_loc = input_location;
15690 	      }
15691 
15692 	    return error_mark_node;
15693 	  }
15694 	else if (TREE_CODE (type) == FUNCTION_TYPE
15695 		 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
15696 		     || type_memfn_rqual (type) != REF_QUAL_NONE))
15697 	  {
15698 	    if (complain & tf_error)
15699 	      {
15700 		if (code == POINTER_TYPE)
15701 		  error ("forming pointer to qualified function type %qT",
15702 			 type);
15703 		else
15704 		  error ("forming reference to qualified function type %qT",
15705 			 type);
15706 	      }
15707 	    return error_mark_node;
15708 	  }
15709 	else if (code == POINTER_TYPE)
15710 	  {
15711 	    r = build_pointer_type (type);
15712 	    if (TREE_CODE (type) == METHOD_TYPE)
15713 	      r = build_ptrmemfunc_type (r);
15714 	  }
15715 	else if (TYPE_REF_P (type))
15716 	  /* In C++0x, during template argument substitution, when there is an
15717 	     attempt to create a reference to a reference type, reference
15718 	     collapsing is applied as described in [14.3.1/4 temp.arg.type]:
15719 
15720 	     "If a template-argument for a template-parameter T names a type
15721 	     that is a reference to a type A, an attempt to create the type
15722 	     'lvalue reference to cv T' creates the type 'lvalue reference to
15723 	     A,' while an attempt to create the type type rvalue reference to
15724 	     cv T' creates the type T"
15725 	  */
15726 	  r = cp_build_reference_type
15727 	      (TREE_TYPE (type),
15728 	       TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
15729 	else
15730 	  r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
15731 	r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
15732 
15733 	if (r != error_mark_node)
15734 	  /* Will this ever be needed for TYPE_..._TO values?  */
15735 	  layout_type (r);
15736 
15737 	return r;
15738       }
15739     case OFFSET_TYPE:
15740       {
15741 	r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
15742 	if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
15743 	  {
15744 	    /* [temp.deduct]
15745 
15746 	       Type deduction may fail for any of the following
15747 	       reasons:
15748 
15749 	       -- Attempting to create "pointer to member of T" when T
15750 		  is not a class type.  */
15751 	    if (complain & tf_error)
15752 	      error ("creating pointer to member of non-class type %qT", r);
15753 	    return error_mark_node;
15754 	  }
15755 	if (TYPE_REF_P (type))
15756 	  {
15757 	    if (complain & tf_error)
15758 	      error ("creating pointer to member reference type %qT", type);
15759 	    return error_mark_node;
15760 	  }
15761 	if (VOID_TYPE_P (type))
15762 	  {
15763 	    if (complain & tf_error)
15764 	      error ("creating pointer to member of type void");
15765 	    return error_mark_node;
15766 	  }
15767 	gcc_assert (TREE_CODE (type) != METHOD_TYPE);
15768 	if (TREE_CODE (type) == FUNCTION_TYPE)
15769 	  {
15770 	    /* The type of the implicit object parameter gets its
15771 	       cv-qualifiers from the FUNCTION_TYPE. */
15772 	    tree memptr;
15773 	    tree method_type
15774 	      = build_memfn_type (type, r, type_memfn_quals (type),
15775 				  type_memfn_rqual (type));
15776 	    memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
15777 	    return cp_build_qualified_type_real (memptr, cp_type_quals (t),
15778 						 complain);
15779 	  }
15780 	else
15781 	  return cp_build_qualified_type_real (build_ptrmem_type (r, type),
15782 					       cp_type_quals (t),
15783 					       complain);
15784       }
15785     case FUNCTION_TYPE:
15786     case METHOD_TYPE:
15787       {
15788 	tree fntype;
15789 	tree specs;
15790 	fntype = tsubst_function_type (t, args, complain, in_decl);
15791 	if (fntype == error_mark_node)
15792 	  return error_mark_node;
15793 
15794 	/* Substitute the exception specification.  */
15795 	specs = tsubst_exception_specification (t, args, complain, in_decl,
15796 						/*defer_ok*/fndecl_type);
15797 	if (specs == error_mark_node)
15798 	  return error_mark_node;
15799 	if (specs)
15800 	  fntype = build_exception_variant (fntype, specs);
15801 	return fntype;
15802       }
15803     case ARRAY_TYPE:
15804       {
15805 	tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
15806 	if (domain == error_mark_node)
15807 	  return error_mark_node;
15808 
15809 	/* As an optimization, we avoid regenerating the array type if
15810 	   it will obviously be the same as T.  */
15811 	if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
15812 	  return t;
15813 
15814 	/* These checks should match the ones in create_array_type_for_decl.
15815 
15816 	   [temp.deduct]
15817 
15818 	   The deduction may fail for any of the following reasons:
15819 
15820 	   -- Attempting to create an array with an element type that
15821 	      is void, a function type, or a reference type, or [DR337]
15822 	      an abstract class type.  */
15823 	if (VOID_TYPE_P (type)
15824 	    || TREE_CODE (type) == FUNCTION_TYPE
15825 	    || (TREE_CODE (type) == ARRAY_TYPE
15826 		&& TYPE_DOMAIN (type) == NULL_TREE)
15827 	    || TYPE_REF_P (type))
15828 	  {
15829 	    if (complain & tf_error)
15830 	      error ("creating array of %qT", type);
15831 	    return error_mark_node;
15832 	  }
15833 
15834 	if (!verify_type_context (input_location, TCTX_ARRAY_ELEMENT, type,
15835 				  !(complain & tf_error)))
15836 	  return error_mark_node;
15837 
15838 	if (abstract_virtuals_error_sfinae (ACU_ARRAY, type, complain))
15839 	  return error_mark_node;
15840 
15841 	r = build_cplus_array_type (type, domain);
15842 
15843 	if (!valid_array_size_p (input_location, r, in_decl,
15844 				 (complain & tf_error)))
15845 	  return error_mark_node;
15846 
15847 	if (TYPE_USER_ALIGN (t))
15848 	  {
15849 	    SET_TYPE_ALIGN (r, TYPE_ALIGN (t));
15850 	    TYPE_USER_ALIGN (r) = 1;
15851 	  }
15852 
15853 	return r;
15854       }
15855 
15856     case TYPENAME_TYPE:
15857       {
15858 	tree ctx = TYPE_CONTEXT (t);
15859 	if (TREE_CODE (ctx) == TYPE_PACK_EXPANSION)
15860 	  {
15861 	    ctx = tsubst_pack_expansion (ctx, args, complain, in_decl);
15862 	    if (ctx == error_mark_node
15863 		|| TREE_VEC_LENGTH (ctx) > 1)
15864 	      return error_mark_node;
15865 	    if (TREE_VEC_LENGTH (ctx) == 0)
15866 	      {
15867 		if (complain & tf_error)
15868 		  error ("%qD is instantiated for an empty pack",
15869 			 TYPENAME_TYPE_FULLNAME (t));
15870 		return error_mark_node;
15871 	      }
15872 	    ctx = TREE_VEC_ELT (ctx, 0);
15873 	  }
15874 	else
15875 	  ctx = tsubst_aggr_type (ctx, args, complain, in_decl,
15876 				  /*entering_scope=*/1);
15877 	if (ctx == error_mark_node)
15878 	  return error_mark_node;
15879 
15880 	tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
15881 			      complain, in_decl);
15882 	if (f == error_mark_node)
15883 	  return error_mark_node;
15884 
15885 	if (!MAYBE_CLASS_TYPE_P (ctx))
15886 	  {
15887 	    if (complain & tf_error)
15888 	      error ("%qT is not a class, struct, or union type", ctx);
15889 	    return error_mark_node;
15890 	  }
15891 	else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
15892 	  {
15893 	    /* Normally, make_typename_type does not require that the CTX
15894 	       have complete type in order to allow things like:
15895 
15896 		 template <class T> struct S { typename S<T>::X Y; };
15897 
15898 	       But, such constructs have already been resolved by this
15899 	       point, so here CTX really should have complete type, unless
15900 	       it's a partial instantiation.  */
15901 	    ctx = complete_type (ctx);
15902 	    if (!COMPLETE_TYPE_P (ctx))
15903 	      {
15904 		if (complain & tf_error)
15905 		  cxx_incomplete_type_error (NULL_TREE, ctx);
15906 		return error_mark_node;
15907 	      }
15908 	  }
15909 
15910 	f = make_typename_type (ctx, f, typename_type,
15911 				complain | tf_keep_type_decl);
15912 	if (f == error_mark_node)
15913 	  return f;
15914 	if (TREE_CODE (f) == TYPE_DECL)
15915 	  {
15916 	    complain |= tf_ignore_bad_quals;
15917 	    f = TREE_TYPE (f);
15918 	  }
15919 
15920 	if (TREE_CODE (f) != TYPENAME_TYPE)
15921 	  {
15922 	    if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
15923 	      {
15924 		if (complain & tf_error)
15925 		  error ("%qT resolves to %qT, which is not an enumeration type",
15926 			 t, f);
15927 		else
15928 		  return error_mark_node;
15929 	      }
15930 	    else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
15931 	      {
15932 		if (complain & tf_error)
15933 		  error ("%qT resolves to %qT, which is not a class type",
15934 			 t, f);
15935 		else
15936 		  return error_mark_node;
15937 	      }
15938 	  }
15939 
15940 	return cp_build_qualified_type_real
15941 	  (f, cp_type_quals (f) | cp_type_quals (t), complain);
15942       }
15943 
15944     case UNBOUND_CLASS_TEMPLATE:
15945       {
15946 	tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
15947 				     in_decl, /*entering_scope=*/1);
15948 	tree name = TYPE_IDENTIFIER (t);
15949 	tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
15950 
15951 	if (ctx == error_mark_node || name == error_mark_node)
15952 	  return error_mark_node;
15953 
15954 	if (parm_list)
15955 	  parm_list = tsubst_template_parms (parm_list, args, complain);
15956 	return make_unbound_class_template (ctx, name, parm_list, complain);
15957       }
15958 
15959     case TYPEOF_TYPE:
15960       {
15961 	tree type;
15962 
15963 	++cp_unevaluated_operand;
15964 	++c_inhibit_evaluation_warnings;
15965 
15966 	type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
15967 			    complain, in_decl,
15968 			    /*integral_constant_expression_p=*/false);
15969 
15970 	--cp_unevaluated_operand;
15971 	--c_inhibit_evaluation_warnings;
15972 
15973 	type = finish_typeof (type);
15974 	return cp_build_qualified_type_real (type,
15975 					     cp_type_quals (t)
15976 					     | cp_type_quals (type),
15977 					     complain);
15978       }
15979 
15980     case DECLTYPE_TYPE:
15981       {
15982 	tree type;
15983 
15984 	++cp_unevaluated_operand;
15985 	++c_inhibit_evaluation_warnings;
15986 
15987 	type = tsubst_copy_and_build (DECLTYPE_TYPE_EXPR (t), args,
15988 				      complain|tf_decltype, in_decl,
15989 				      /*function_p*/false,
15990 				      /*integral_constant_expression*/false);
15991 
15992 	--cp_unevaluated_operand;
15993 	--c_inhibit_evaluation_warnings;
15994 
15995 	if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
15996 	  type = lambda_capture_field_type (type,
15997 					    false /*explicit_init*/,
15998 					    DECLTYPE_FOR_REF_CAPTURE (t));
15999 	else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
16000 	  type = lambda_proxy_type (type);
16001 	else
16002 	  {
16003 	    bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
16004 	    if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
16005 		&& EXPR_P (type))
16006 	      /* In a template ~id could be either a complement expression
16007 		 or an unqualified-id naming a destructor; if instantiating
16008 		 it produces an expression, it's not an id-expression or
16009 		 member access.  */
16010 	      id = false;
16011 	    type = finish_decltype_type (type, id, complain);
16012 	  }
16013 	return cp_build_qualified_type_real (type,
16014 					     cp_type_quals (t)
16015 					     | cp_type_quals (type),
16016 					     complain | tf_ignore_bad_quals);
16017       }
16018 
16019     case UNDERLYING_TYPE:
16020       {
16021 	tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
16022 			    complain, in_decl);
16023 	return finish_underlying_type (type);
16024       }
16025 
16026     case TYPE_ARGUMENT_PACK:
16027     case NONTYPE_ARGUMENT_PACK:
16028       {
16029         tree r;
16030 
16031 	if (code == NONTYPE_ARGUMENT_PACK)
16032 	  r = make_node (code);
16033 	else
16034 	  r = cxx_make_type (code);
16035 
16036 	tree pack_args = ARGUMENT_PACK_ARGS (t);
16037 	pack_args = tsubst_template_args (pack_args, args, complain, in_decl);
16038 	SET_ARGUMENT_PACK_ARGS (r, pack_args);
16039 
16040 	return r;
16041       }
16042 
16043     case VOID_CST:
16044     case INTEGER_CST:
16045     case REAL_CST:
16046     case STRING_CST:
16047     case PLUS_EXPR:
16048     case MINUS_EXPR:
16049     case NEGATE_EXPR:
16050     case NOP_EXPR:
16051     case INDIRECT_REF:
16052     case ADDR_EXPR:
16053     case CALL_EXPR:
16054     case ARRAY_REF:
16055     case SCOPE_REF:
16056       /* We should use one of the expression tsubsts for these codes.  */
16057       gcc_unreachable ();
16058 
16059     default:
16060       sorry ("use of %qs in template", get_tree_code_name (code));
16061       return error_mark_node;
16062     }
16063 }
16064 
16065 /* tsubst a BASELINK.  OBJECT_TYPE, if non-NULL, is the type of the
16066    expression on the left-hand side of the "." or "->" operator.  We
16067    only do the lookup if we had a dependent BASELINK.  Otherwise we
16068    adjust it onto the instantiated heirarchy.  */
16069 
16070 static tree
tsubst_baselink(tree baselink,tree object_type,tree args,tsubst_flags_t complain,tree in_decl)16071 tsubst_baselink (tree baselink, tree object_type,
16072 		 tree args, tsubst_flags_t complain, tree in_decl)
16073 {
16074   bool qualified_p = BASELINK_QUALIFIED_P (baselink);
16075   tree qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
16076   qualifying_scope = tsubst (qualifying_scope, args, complain, in_decl);
16077 
16078   tree optype = BASELINK_OPTYPE (baselink);
16079   optype = tsubst (optype, args, complain, in_decl);
16080 
16081   tree template_args = NULL_TREE;
16082   bool template_id_p = false;
16083   tree fns = BASELINK_FUNCTIONS (baselink);
16084   if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
16085     {
16086       template_id_p = true;
16087       template_args = TREE_OPERAND (fns, 1);
16088       fns = TREE_OPERAND (fns, 0);
16089       if (template_args)
16090 	template_args = tsubst_template_args (template_args, args,
16091 					      complain, in_decl);
16092     }
16093 
16094   tree binfo_type = BINFO_TYPE (BASELINK_BINFO (baselink));
16095   binfo_type = tsubst (binfo_type, args, complain, in_decl);
16096   bool dependent_p = binfo_type != BINFO_TYPE (BASELINK_BINFO (baselink));
16097 
16098   if (dependent_p)
16099     {
16100       tree name = OVL_NAME (fns);
16101       if (IDENTIFIER_CONV_OP_P (name))
16102 	name = make_conv_op_name (optype);
16103 
16104       if (name == complete_dtor_identifier)
16105 	/* Treat as-if non-dependent below.  */
16106 	dependent_p = false;
16107 
16108       baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
16109       if (!baselink)
16110 	{
16111 	  if ((complain & tf_error)
16112 	      && constructor_name_p (name, qualifying_scope))
16113 	    error ("cannot call constructor %<%T::%D%> directly",
16114 		   qualifying_scope, name);
16115 	  return error_mark_node;
16116 	}
16117 
16118       if (BASELINK_P (baselink))
16119 	fns = BASELINK_FUNCTIONS (baselink);
16120     }
16121   else
16122     /* We're going to overwrite pieces below, make a duplicate.  */
16123     baselink = copy_node (baselink);
16124 
16125   /* If lookup found a single function, mark it as used at this point.
16126      (If lookup found multiple functions the one selected later by
16127      overload resolution will be marked as used at that point.)  */
16128   if (!template_id_p && !really_overloaded_fn (fns))
16129     {
16130       tree fn = OVL_FIRST (fns);
16131       bool ok = mark_used (fn, complain);
16132       if (!ok && !(complain & tf_error))
16133 	return error_mark_node;
16134       if (ok && BASELINK_P (baselink))
16135 	/* We might have instantiated an auto function.  */
16136 	TREE_TYPE (baselink) = TREE_TYPE (fn);
16137     }
16138 
16139   if (BASELINK_P (baselink))
16140     {
16141       /* Add back the template arguments, if present.  */
16142       if (template_id_p)
16143 	BASELINK_FUNCTIONS (baselink)
16144 	  = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, template_args);
16145 
16146       /* Update the conversion operator type.  */
16147       BASELINK_OPTYPE (baselink) = optype;
16148     }
16149 
16150   if (!object_type)
16151     object_type = current_class_type;
16152 
16153   if (qualified_p || !dependent_p)
16154     {
16155       baselink = adjust_result_of_qualified_name_lookup (baselink,
16156 							 qualifying_scope,
16157 							 object_type);
16158       if (!qualified_p)
16159 	/* We need to call adjust_result_of_qualified_name_lookup in case the
16160 	   destructor names a base class, but we unset BASELINK_QUALIFIED_P
16161 	   so that we still get virtual function binding.  */
16162 	BASELINK_QUALIFIED_P (baselink) = false;
16163     }
16164 
16165   return baselink;
16166 }
16167 
16168 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
16169    true if the qualified-id will be a postfix-expression in-and-of
16170    itself; false if more of the postfix-expression follows the
16171    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
16172    of "&".  */
16173 
16174 static tree
tsubst_qualified_id(tree qualified_id,tree args,tsubst_flags_t complain,tree in_decl,bool done,bool address_p)16175 tsubst_qualified_id (tree qualified_id, tree args,
16176 		     tsubst_flags_t complain, tree in_decl,
16177 		     bool done, bool address_p)
16178 {
16179   tree expr;
16180   tree scope;
16181   tree name;
16182   bool is_template;
16183   tree template_args;
16184   location_t loc = UNKNOWN_LOCATION;
16185 
16186   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
16187 
16188   /* Figure out what name to look up.  */
16189   name = TREE_OPERAND (qualified_id, 1);
16190   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
16191     {
16192       is_template = true;
16193       loc = EXPR_LOCATION (name);
16194       template_args = TREE_OPERAND (name, 1);
16195       if (template_args)
16196 	template_args = tsubst_template_args (template_args, args,
16197 					      complain, in_decl);
16198       if (template_args == error_mark_node)
16199 	return error_mark_node;
16200       name = TREE_OPERAND (name, 0);
16201     }
16202   else
16203     {
16204       is_template = false;
16205       template_args = NULL_TREE;
16206     }
16207 
16208   /* Substitute into the qualifying scope.  When there are no ARGS, we
16209      are just trying to simplify a non-dependent expression.  In that
16210      case the qualifying scope may be dependent, and, in any case,
16211      substituting will not help.  */
16212   scope = TREE_OPERAND (qualified_id, 0);
16213   if (args)
16214     {
16215       scope = tsubst (scope, args, complain, in_decl);
16216       expr = tsubst_copy (name, args, complain, in_decl);
16217     }
16218   else
16219     expr = name;
16220 
16221   if (dependent_scope_p (scope))
16222     {
16223       if (is_template)
16224 	expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr, template_args);
16225       tree r = build_qualified_name (NULL_TREE, scope, expr,
16226 				     QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
16227       REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (qualified_id);
16228       return r;
16229     }
16230 
16231   if (!BASELINK_P (name) && !DECL_P (expr))
16232     {
16233       if (TREE_CODE (expr) == BIT_NOT_EXPR)
16234 	{
16235 	  /* A BIT_NOT_EXPR is used to represent a destructor.  */
16236 	  if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
16237 	    {
16238 	      error ("qualifying type %qT does not match destructor name ~%qT",
16239 		     scope, TREE_OPERAND (expr, 0));
16240 	      expr = error_mark_node;
16241 	    }
16242 	  else
16243 	    expr = lookup_qualified_name (scope, complete_dtor_identifier,
16244 					  /*is_type_p=*/0, false);
16245 	}
16246       else
16247 	expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
16248       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
16249 		     ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
16250 	{
16251 	  if (complain & tf_error)
16252 	    {
16253 	      error ("dependent-name %qE is parsed as a non-type, but "
16254 		     "instantiation yields a type", qualified_id);
16255 	      inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
16256 	    }
16257 	  return error_mark_node;
16258 	}
16259     }
16260 
16261   if (DECL_P (expr))
16262     {
16263       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
16264 					   scope);
16265       /* Remember that there was a reference to this entity.  */
16266       if (!mark_used (expr, complain) && !(complain & tf_error))
16267 	return error_mark_node;
16268     }
16269 
16270   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
16271     {
16272       if (complain & tf_error)
16273 	qualified_name_lookup_error (scope,
16274 				     TREE_OPERAND (qualified_id, 1),
16275 				     expr, input_location);
16276       return error_mark_node;
16277     }
16278 
16279   if (is_template)
16280     {
16281       /* We may be repeating a check already done during parsing, but
16282 	 if it was well-formed and passed then, it will pass again
16283 	 now, and if it didn't, we wouldn't have got here.  The case
16284 	 we want to catch is when we couldn't tell then, and can now,
16285 	 namely when templ prior to substitution was an
16286 	 identifier.  */
16287       if (flag_concepts && check_auto_in_tmpl_args (expr, template_args))
16288 	return error_mark_node;
16289 
16290       if (variable_template_p (expr))
16291 	expr = lookup_and_finish_template_variable (expr, template_args,
16292 						    complain);
16293       else
16294 	expr = lookup_template_function (expr, template_args);
16295     }
16296 
16297   if (expr == error_mark_node && complain & tf_error)
16298     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
16299 				 expr, input_location);
16300   else if (TYPE_P (scope))
16301     {
16302       expr = (adjust_result_of_qualified_name_lookup
16303 	      (expr, scope, current_nonlambda_class_type ()));
16304       expr = (finish_qualified_id_expr
16305 	      (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
16306 	       QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
16307 	       /*template_arg_p=*/false, complain));
16308     }
16309 
16310   /* Expressions do not generally have reference type.  */
16311   if (TREE_CODE (expr) != SCOPE_REF
16312       /* However, if we're about to form a pointer-to-member, we just
16313 	 want the referenced member referenced.  */
16314       && TREE_CODE (expr) != OFFSET_REF)
16315     expr = convert_from_reference (expr);
16316 
16317   if (REF_PARENTHESIZED_P (qualified_id))
16318     expr = force_paren_expr (expr);
16319 
16320   return expr;
16321 }
16322 
16323 /* tsubst the initializer for a VAR_DECL.  INIT is the unsubstituted
16324    initializer, DECL is the substituted VAR_DECL.  Other arguments are as
16325    for tsubst.  */
16326 
16327 static tree
tsubst_init(tree init,tree decl,tree args,tsubst_flags_t complain,tree in_decl)16328 tsubst_init (tree init, tree decl, tree args,
16329 	     tsubst_flags_t complain, tree in_decl)
16330 {
16331   if (!init)
16332     return NULL_TREE;
16333 
16334   init = tsubst_expr (init, args, complain, in_decl, false);
16335 
16336   tree type = TREE_TYPE (decl);
16337 
16338   if (!init && type != error_mark_node)
16339     {
16340       if (tree auto_node = type_uses_auto (type))
16341 	{
16342 	  if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
16343 	    {
16344 	      if (complain & tf_error)
16345 		error ("initializer for %q#D expands to an empty list "
16346 		       "of expressions", decl);
16347 	      return error_mark_node;
16348 	    }
16349 	}
16350       else if (!dependent_type_p (type))
16351 	{
16352 	  /* If we had an initializer but it
16353 	     instantiated to nothing,
16354 	     value-initialize the object.  This will
16355 	     only occur when the initializer was a
16356 	     pack expansion where the parameter packs
16357 	     used in that expansion were of length
16358 	     zero.  */
16359 	  init = build_value_init (type, complain);
16360 	  if (TREE_CODE (init) == AGGR_INIT_EXPR)
16361 	    init = get_target_expr_sfinae (init, complain);
16362 	  if (TREE_CODE (init) == TARGET_EXPR)
16363 	    TARGET_EXPR_DIRECT_INIT_P (init) = true;
16364 	}
16365     }
16366 
16367   return init;
16368 }
16369 
16370 /* If T is a reference to a dependent member of the current instantiation C and
16371    we are trying to refer to that member in a partial instantiation of C,
16372    return a SCOPE_REF; otherwise, return NULL_TREE.
16373 
16374    This can happen when forming a C++20 alias template deduction guide, as in
16375    PR96199.  */
16376 
16377 static tree
maybe_dependent_member_ref(tree t,tree args,tsubst_flags_t complain,tree in_decl)16378 maybe_dependent_member_ref (tree t, tree args, tsubst_flags_t complain,
16379 			    tree in_decl)
16380 {
16381   if (cxx_dialect < cxx2a)
16382     return NULL_TREE;
16383 
16384   tree ctx = context_for_name_lookup (t);
16385   if (!CLASS_TYPE_P (ctx))
16386     return NULL_TREE;
16387 
16388   ctx = tsubst (ctx, args, complain, in_decl);
16389   if (dependent_scope_p (ctx))
16390     return build_qualified_name (NULL_TREE, ctx, DECL_NAME (t),
16391 				 /*template_p=*/false);
16392 
16393   return NULL_TREE;
16394 }
16395 
16396 /* Like tsubst, but deals with expressions.  This function just replaces
16397    template parms; to finish processing the resultant expression, use
16398    tsubst_copy_and_build or tsubst_expr.  */
16399 
16400 static tree
tsubst_copy(tree t,tree args,tsubst_flags_t complain,tree in_decl)16401 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
16402 {
16403   enum tree_code code;
16404   tree r;
16405 
16406   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
16407     return t;
16408 
16409   code = TREE_CODE (t);
16410 
16411   switch (code)
16412     {
16413     case PARM_DECL:
16414       r = retrieve_local_specialization (t);
16415 
16416       if (r == NULL_TREE)
16417 	{
16418 	  /* We get here for a use of 'this' in an NSDMI.  */
16419 	  if (DECL_NAME (t) == this_identifier && current_class_ptr)
16420 	    return current_class_ptr;
16421 
16422 	  /* This can happen for a parameter name used later in a function
16423 	     declaration (such as in a late-specified return type).  Just
16424 	     make a dummy decl, since it's only used for its type.  */
16425 	  gcc_assert (cp_unevaluated_operand != 0);
16426 	  r = tsubst_decl (t, args, complain);
16427 	  /* Give it the template pattern as its context; its true context
16428 	     hasn't been instantiated yet and this is good enough for
16429 	     mangling.  */
16430 	  DECL_CONTEXT (r) = DECL_CONTEXT (t);
16431 	}
16432 
16433       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
16434 	r = argument_pack_select_arg (r);
16435       if (!mark_used (r, complain) && !(complain & tf_error))
16436 	return error_mark_node;
16437       return r;
16438 
16439     case CONST_DECL:
16440       {
16441 	tree enum_type;
16442 	tree v;
16443 
16444 	if (DECL_TEMPLATE_PARM_P (t))
16445 	  return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
16446 	/* There is no need to substitute into namespace-scope
16447 	   enumerators.  */
16448 	if (DECL_NAMESPACE_SCOPE_P (t))
16449 	  return t;
16450 	/* If ARGS is NULL, then T is known to be non-dependent.  */
16451 	if (args == NULL_TREE)
16452 	  return scalar_constant_value (t);
16453 
16454 	if (tree ref = maybe_dependent_member_ref (t, args, complain, in_decl))
16455 	  return ref;
16456 
16457 	/* Unfortunately, we cannot just call lookup_name here.
16458 	   Consider:
16459 
16460 	     template <int I> int f() {
16461 	     enum E { a = I };
16462 	     struct S { void g() { E e = a; } };
16463 	     };
16464 
16465 	   When we instantiate f<7>::S::g(), say, lookup_name is not
16466 	   clever enough to find f<7>::a.  */
16467 	enum_type
16468 	  = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
16469 			      /*entering_scope=*/0);
16470 
16471 	for (v = TYPE_VALUES (enum_type);
16472 	     v != NULL_TREE;
16473 	     v = TREE_CHAIN (v))
16474 	  if (TREE_PURPOSE (v) == DECL_NAME (t))
16475 	    return TREE_VALUE (v);
16476 
16477 	  /* We didn't find the name.  That should never happen; if
16478 	     name-lookup found it during preliminary parsing, we
16479 	     should find it again here during instantiation.  */
16480 	gcc_unreachable ();
16481       }
16482       return t;
16483 
16484     case FIELD_DECL:
16485       if (DECL_CONTEXT (t))
16486 	{
16487 	  tree ctx;
16488 
16489 	  ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
16490 				  /*entering_scope=*/1);
16491 	  if (ctx != DECL_CONTEXT (t))
16492 	    {
16493 	      tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
16494 	      if (!r)
16495 		{
16496 		  if (complain & tf_error)
16497 		    error ("using invalid field %qD", t);
16498 		  return error_mark_node;
16499 		}
16500 	      return r;
16501 	    }
16502 	}
16503 
16504       return t;
16505 
16506     case VAR_DECL:
16507       if (tree ref = maybe_dependent_member_ref (t, args, complain, in_decl))
16508 	return ref;
16509       gcc_fallthrough();
16510     case FUNCTION_DECL:
16511       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
16512 	r = tsubst (t, args, complain, in_decl);
16513       else if (local_variable_p (t)
16514 	       && uses_template_parms (DECL_CONTEXT (t)))
16515 	{
16516 	  r = retrieve_local_specialization (t);
16517 	  if (r == NULL_TREE)
16518 	    {
16519 	      /* First try name lookup to find the instantiation.  */
16520 	      r = lookup_name (DECL_NAME (t));
16521 	      if (r)
16522 		{
16523 		  if (!VAR_P (r))
16524 		    {
16525 		      /* During error-recovery we may find a non-variable,
16526 			 even an OVERLOAD: just bail out and avoid ICEs and
16527 			 duplicate diagnostics (c++/62207).  */
16528 		      gcc_assert (seen_error ());
16529 		      return error_mark_node;
16530 		    }
16531 		  if (!is_capture_proxy (r))
16532 		    {
16533 		      /* Make sure the one we found is the one we want.  */
16534 		      tree ctx = enclosing_instantiation_of (DECL_CONTEXT (t));
16535 		      if (ctx != DECL_CONTEXT (r))
16536 			r = NULL_TREE;
16537 		    }
16538 		}
16539 
16540 	      if (r)
16541 		/* OK */;
16542 	      else
16543 		{
16544 		  /* This can happen for a variable used in a
16545 		     late-specified return type of a local lambda, or for a
16546 		     local static or constant.  Building a new VAR_DECL
16547 		     should be OK in all those cases.  */
16548 		  r = tsubst_decl (t, args, complain);
16549 		  if (local_specializations)
16550 		    /* Avoid infinite recursion (79640).  */
16551 		    register_local_specialization (r, t);
16552 		  if (decl_maybe_constant_var_p (r))
16553 		    {
16554 		      /* We can't call cp_finish_decl, so handle the
16555 			 initializer by hand.  */
16556 		      tree init = tsubst_init (DECL_INITIAL (t), r, args,
16557 					       complain, in_decl);
16558 		      if (!processing_template_decl)
16559 			init = maybe_constant_init (init);
16560 		      if (processing_template_decl
16561 			  ? potential_constant_expression (init)
16562 			  : reduced_constant_expression_p (init))
16563 			DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
16564 			  = TREE_CONSTANT (r) = true;
16565 		      DECL_INITIAL (r) = init;
16566 		      if (tree auto_node = type_uses_auto (TREE_TYPE (r)))
16567 			TREE_TYPE (r)
16568 			  = do_auto_deduction (TREE_TYPE (r), init, auto_node,
16569 					       complain, adc_variable_type);
16570 		    }
16571 		  gcc_assert (cp_unevaluated_operand || TREE_STATIC (r)
16572 			      || decl_constant_var_p (r)
16573 			      || seen_error ());
16574 		  if (!processing_template_decl
16575 		      && !TREE_STATIC (r))
16576 		    r = process_outer_var_ref (r, complain);
16577 		}
16578 	      /* Remember this for subsequent uses.  */
16579 	      if (local_specializations)
16580 		register_local_specialization (r, t);
16581 	    }
16582 	  if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
16583 	    r = argument_pack_select_arg (r);
16584 	}
16585       else
16586 	r = t;
16587       if (!mark_used (r, complain))
16588 	return error_mark_node;
16589       return r;
16590 
16591     case NAMESPACE_DECL:
16592       return t;
16593 
16594     case OVERLOAD:
16595       return t;
16596 
16597     case BASELINK:
16598       return tsubst_baselink (t, current_nonlambda_class_type (),
16599 			      args, complain, in_decl);
16600 
16601     case TEMPLATE_DECL:
16602       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
16603 	return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
16604 		       args, complain, in_decl);
16605       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
16606 	return tsubst (t, args, complain, in_decl);
16607       else if (DECL_CLASS_SCOPE_P (t)
16608 	       && uses_template_parms (DECL_CONTEXT (t)))
16609 	{
16610 	  /* Template template argument like the following example need
16611 	     special treatment:
16612 
16613 	       template <template <class> class TT> struct C {};
16614 	       template <class T> struct D {
16615 		 template <class U> struct E {};
16616 		 C<E> c;				// #1
16617 	       };
16618 	       D<int> d;				// #2
16619 
16620 	     We are processing the template argument `E' in #1 for
16621 	     the template instantiation #2.  Originally, `E' is a
16622 	     TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
16623 	     have to substitute this with one having context `D<int>'.  */
16624 
16625 	  tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
16626 	  if (dependent_scope_p (context))
16627 	    {
16628 	      /* When rewriting a constructor into a deduction guide, a
16629 		 non-dependent name can become dependent, so memtmpl<args>
16630 		 becomes context::template memtmpl<args>.  */
16631 	      tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16632 	      return build_qualified_name (type, context, DECL_NAME (t),
16633 					   /*template*/true);
16634 	    }
16635 	  return lookup_field (context, DECL_NAME(t), 0, false);
16636 	}
16637       else
16638 	/* Ordinary template template argument.  */
16639 	return t;
16640 
16641     case NON_LVALUE_EXPR:
16642     case VIEW_CONVERT_EXPR:
16643 	{
16644 	  /* Handle location wrappers by substituting the wrapped node
16645 	     first, *then* reusing the resulting type.  Doing the type
16646 	     first ensures that we handle template parameters and
16647 	     parameter pack expansions.  */
16648 	  if (location_wrapper_p (t))
16649 	    {
16650 	      tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args,
16651 				      complain, in_decl);
16652 	      return maybe_wrap_with_location (op0, EXPR_LOCATION (t));
16653 	    }
16654 	  tree op = TREE_OPERAND (t, 0);
16655 	  if (code == VIEW_CONVERT_EXPR
16656 	      && TREE_CODE (op) == TEMPLATE_PARM_INDEX)
16657 	    {
16658 	      /* Wrapper to make a C++20 template parameter object const.  */
16659 	      op = tsubst_copy (op, args, complain, in_decl);
16660 	      if (TREE_CODE (op) == TEMPLATE_PARM_INDEX)
16661 		{
16662 		  tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16663 		  return build1 (code, type, op);
16664 		}
16665 	      else if (!CP_TYPE_CONST_P (TREE_TYPE (op)))
16666 		{
16667 		  /* The template argument is not const, presumably because
16668 		     it is still dependent, and so not the const template parm
16669 		     object.  */
16670 		  tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16671 		  gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
16672 				       (type, TREE_TYPE (op)));
16673 		  if (TREE_CODE (op) == CONSTRUCTOR
16674 		      || TREE_CODE (op) == IMPLICIT_CONV_EXPR)
16675 		    {
16676 		      /* Don't add a wrapper to these.  */
16677 		      op = copy_node (op);
16678 		      TREE_TYPE (op) = type;
16679 		    }
16680 		  else
16681 		    /* Do add a wrapper otherwise.  */
16682 		    op = build1 (code, type, op);
16683 		}
16684 	      return op;
16685 	    }
16686 	  /* force_paren_expr can also create a VIEW_CONVERT_EXPR.  */
16687 	  else if (code == VIEW_CONVERT_EXPR && REF_PARENTHESIZED_P (t))
16688 	    {
16689 	      op = tsubst_copy (op, args, complain, in_decl);
16690 	      op = build1 (code, TREE_TYPE (op), op);
16691 	      REF_PARENTHESIZED_P (op) = true;
16692 	      return op;
16693 	    }
16694 	  /* We shouldn't see any other uses of these in templates.  */
16695 	  gcc_unreachable ();
16696 	}
16697 
16698     case CAST_EXPR:
16699     case REINTERPRET_CAST_EXPR:
16700     case CONST_CAST_EXPR:
16701     case STATIC_CAST_EXPR:
16702     case DYNAMIC_CAST_EXPR:
16703     case IMPLICIT_CONV_EXPR:
16704     case CONVERT_EXPR:
16705     case NOP_EXPR:
16706       {
16707 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16708 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16709 	return build1 (code, type, op0);
16710       }
16711 
16712     case SIZEOF_EXPR:
16713       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
16714 	  || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
16715         {
16716           tree expanded, op = TREE_OPERAND (t, 0);
16717 	  int len = 0;
16718 
16719 	  if (SIZEOF_EXPR_TYPE_P (t))
16720 	    op = TREE_TYPE (op);
16721 
16722 	  ++cp_unevaluated_operand;
16723 	  ++c_inhibit_evaluation_warnings;
16724 	  /* We only want to compute the number of arguments.  */
16725 	  if (PACK_EXPANSION_P (op))
16726 	    expanded = tsubst_pack_expansion (op, args, complain, in_decl);
16727 	  else
16728 	    expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
16729 					     args, complain, in_decl);
16730 	  --cp_unevaluated_operand;
16731 	  --c_inhibit_evaluation_warnings;
16732 
16733 	  if (TREE_CODE (expanded) == TREE_VEC)
16734 	    {
16735 	      len = TREE_VEC_LENGTH (expanded);
16736 	      /* Set TREE_USED for the benefit of -Wunused.  */
16737 	      for (int i = 0; i < len; i++)
16738 		if (DECL_P (TREE_VEC_ELT (expanded, i)))
16739 		  TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
16740 	    }
16741 
16742 	  if (expanded == error_mark_node)
16743 	    return error_mark_node;
16744 	  else if (PACK_EXPANSION_P (expanded)
16745 		   || (TREE_CODE (expanded) == TREE_VEC
16746 		       && pack_expansion_args_count (expanded)))
16747 
16748 	    {
16749 	      if (PACK_EXPANSION_P (expanded))
16750 		/* OK.  */;
16751 	      else if (TREE_VEC_LENGTH (expanded) == 1)
16752 		expanded = TREE_VEC_ELT (expanded, 0);
16753 	      else
16754 		expanded = make_argument_pack (expanded);
16755 
16756 	      if (TYPE_P (expanded))
16757 		return cxx_sizeof_or_alignof_type (input_location,
16758 						   expanded, SIZEOF_EXPR,
16759 						   false,
16760 						   complain & tf_error);
16761 	      else
16762 		return cxx_sizeof_or_alignof_expr (input_location,
16763 						   expanded, SIZEOF_EXPR,
16764                                                    complain & tf_error);
16765 	    }
16766 	  else
16767 	    return build_int_cst (size_type_node, len);
16768         }
16769       if (SIZEOF_EXPR_TYPE_P (t))
16770 	{
16771 	  r = tsubst (TREE_TYPE (TREE_OPERAND (t, 0)),
16772 		      args, complain, in_decl);
16773 	  r = build1 (NOP_EXPR, r, error_mark_node);
16774 	  r = build1 (SIZEOF_EXPR,
16775 		      tsubst (TREE_TYPE (t), args, complain, in_decl), r);
16776 	  SIZEOF_EXPR_TYPE_P (r) = 1;
16777 	  return r;
16778 	}
16779       /* Fall through */
16780 
16781     case INDIRECT_REF:
16782     case NEGATE_EXPR:
16783     case TRUTH_NOT_EXPR:
16784     case BIT_NOT_EXPR:
16785     case ADDR_EXPR:
16786     case UNARY_PLUS_EXPR:      /* Unary + */
16787     case ALIGNOF_EXPR:
16788     case AT_ENCODE_EXPR:
16789     case ARROW_EXPR:
16790     case THROW_EXPR:
16791     case TYPEID_EXPR:
16792     case REALPART_EXPR:
16793     case IMAGPART_EXPR:
16794     case PAREN_EXPR:
16795       {
16796 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16797 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16798 	r = build1 (code, type, op0);
16799 	if (code == ALIGNOF_EXPR)
16800 	  ALIGNOF_EXPR_STD_P (r) = ALIGNOF_EXPR_STD_P (t);
16801 	return r;
16802       }
16803 
16804     case COMPONENT_REF:
16805       {
16806 	tree object;
16807 	tree name;
16808 
16809 	object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16810 	name = TREE_OPERAND (t, 1);
16811 	if (TREE_CODE (name) == BIT_NOT_EXPR)
16812 	  {
16813 	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
16814 				complain, in_decl);
16815 	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
16816 	  }
16817 	else if (TREE_CODE (name) == SCOPE_REF
16818 		 && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
16819 	  {
16820 	    tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
16821 				     complain, in_decl);
16822 	    name = TREE_OPERAND (name, 1);
16823 	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
16824 				complain, in_decl);
16825 	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
16826 	    name = build_qualified_name (/*type=*/NULL_TREE,
16827 					 base, name,
16828 					 /*template_p=*/false);
16829 	  }
16830 	else if (BASELINK_P (name))
16831 	  name = tsubst_baselink (name,
16832 				  non_reference (TREE_TYPE (object)),
16833 				  args, complain,
16834 				  in_decl);
16835 	else
16836 	  name = tsubst_copy (name, args, complain, in_decl);
16837 	return build_nt (COMPONENT_REF, object, name, NULL_TREE);
16838       }
16839 
16840     case PLUS_EXPR:
16841     case MINUS_EXPR:
16842     case MULT_EXPR:
16843     case TRUNC_DIV_EXPR:
16844     case CEIL_DIV_EXPR:
16845     case FLOOR_DIV_EXPR:
16846     case ROUND_DIV_EXPR:
16847     case EXACT_DIV_EXPR:
16848     case BIT_AND_EXPR:
16849     case BIT_IOR_EXPR:
16850     case BIT_XOR_EXPR:
16851     case TRUNC_MOD_EXPR:
16852     case FLOOR_MOD_EXPR:
16853     case TRUTH_ANDIF_EXPR:
16854     case TRUTH_ORIF_EXPR:
16855     case TRUTH_AND_EXPR:
16856     case TRUTH_OR_EXPR:
16857     case RSHIFT_EXPR:
16858     case LSHIFT_EXPR:
16859     case EQ_EXPR:
16860     case NE_EXPR:
16861     case MAX_EXPR:
16862     case MIN_EXPR:
16863     case LE_EXPR:
16864     case GE_EXPR:
16865     case LT_EXPR:
16866     case GT_EXPR:
16867     case COMPOUND_EXPR:
16868     case DOTSTAR_EXPR:
16869     case MEMBER_REF:
16870     case PREDECREMENT_EXPR:
16871     case PREINCREMENT_EXPR:
16872     case POSTDECREMENT_EXPR:
16873     case POSTINCREMENT_EXPR:
16874       {
16875 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16876 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16877 	return build_nt (code, op0, op1);
16878       }
16879 
16880     case SCOPE_REF:
16881       {
16882 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16883 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16884 	return build_qualified_name (/*type=*/NULL_TREE, op0, op1,
16885 				     QUALIFIED_NAME_IS_TEMPLATE (t));
16886       }
16887 
16888     case ARRAY_REF:
16889       {
16890 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16891 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16892 	return build_nt (ARRAY_REF, op0, op1, NULL_TREE, NULL_TREE);
16893       }
16894 
16895     case CALL_EXPR:
16896       {
16897 	int n = VL_EXP_OPERAND_LENGTH (t);
16898 	tree result = build_vl_exp (CALL_EXPR, n);
16899 	int i;
16900 	for (i = 0; i < n; i++)
16901 	  TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
16902 					     complain, in_decl);
16903 	return result;
16904       }
16905 
16906     case COND_EXPR:
16907     case MODOP_EXPR:
16908     case PSEUDO_DTOR_EXPR:
16909     case VEC_PERM_EXPR:
16910       {
16911 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16912 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16913 	tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
16914 	r = build_nt (code, op0, op1, op2);
16915 	TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
16916 	return r;
16917       }
16918 
16919     case NEW_EXPR:
16920       {
16921 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16922 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16923 	tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
16924 	r = build_nt (code, op0, op1, op2);
16925 	NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
16926 	return r;
16927       }
16928 
16929     case DELETE_EXPR:
16930       {
16931 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16932 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16933 	r = build_nt (code, op0, op1);
16934 	DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
16935 	DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
16936 	return r;
16937       }
16938 
16939     case TEMPLATE_ID_EXPR:
16940       {
16941 	/* Substituted template arguments */
16942 	tree fn = TREE_OPERAND (t, 0);
16943 	tree targs = TREE_OPERAND (t, 1);
16944 
16945 	fn = tsubst_copy (fn, args, complain, in_decl);
16946 	if (targs)
16947 	  targs = tsubst_template_args (targs, args, complain, in_decl);
16948 
16949 	return lookup_template_function (fn, targs);
16950       }
16951 
16952     case TREE_LIST:
16953       {
16954 	tree purpose, value, chain;
16955 
16956 	if (t == void_list_node)
16957 	  return t;
16958 
16959 	purpose = TREE_PURPOSE (t);
16960 	if (purpose)
16961 	  purpose = tsubst_copy (purpose, args, complain, in_decl);
16962 	value = TREE_VALUE (t);
16963 	if (value)
16964 	  value = tsubst_copy (value, args, complain, in_decl);
16965 	chain = TREE_CHAIN (t);
16966 	if (chain && chain != void_type_node)
16967 	  chain = tsubst_copy (chain, args, complain, in_decl);
16968 	if (purpose == TREE_PURPOSE (t)
16969 	    && value == TREE_VALUE (t)
16970 	    && chain == TREE_CHAIN (t))
16971 	  return t;
16972 	return tree_cons (purpose, value, chain);
16973       }
16974 
16975     case RECORD_TYPE:
16976     case UNION_TYPE:
16977     case ENUMERAL_TYPE:
16978     case INTEGER_TYPE:
16979     case TEMPLATE_TYPE_PARM:
16980     case TEMPLATE_TEMPLATE_PARM:
16981     case BOUND_TEMPLATE_TEMPLATE_PARM:
16982     case TEMPLATE_PARM_INDEX:
16983     case POINTER_TYPE:
16984     case REFERENCE_TYPE:
16985     case OFFSET_TYPE:
16986     case FUNCTION_TYPE:
16987     case METHOD_TYPE:
16988     case ARRAY_TYPE:
16989     case TYPENAME_TYPE:
16990     case UNBOUND_CLASS_TEMPLATE:
16991     case TYPEOF_TYPE:
16992     case DECLTYPE_TYPE:
16993     case TYPE_DECL:
16994       return tsubst (t, args, complain, in_decl);
16995 
16996     case USING_DECL:
16997       t = DECL_NAME (t);
16998       /* Fall through.  */
16999     case IDENTIFIER_NODE:
17000       if (IDENTIFIER_CONV_OP_P (t))
17001 	{
17002 	  tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17003 	  return make_conv_op_name (new_type);
17004 	}
17005       else
17006 	return t;
17007 
17008     case CONSTRUCTOR:
17009       /* This is handled by tsubst_copy_and_build.  */
17010       gcc_unreachable ();
17011 
17012     case VA_ARG_EXPR:
17013       {
17014 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17015 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17016 	return build_x_va_arg (EXPR_LOCATION (t), op0, type);
17017       }
17018 
17019     case CLEANUP_POINT_EXPR:
17020       /* We shouldn't have built any of these during initial template
17021 	 generation.  Instead, they should be built during instantiation
17022 	 in response to the saved STMT_IS_FULL_EXPR_P setting.  */
17023       gcc_unreachable ();
17024 
17025     case OFFSET_REF:
17026       {
17027 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17028 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17029 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17030 	r = build2 (code, type, op0, op1);
17031 	PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
17032 	if (!mark_used (TREE_OPERAND (r, 1), complain)
17033 	    && !(complain & tf_error))
17034 	  return error_mark_node;
17035 	return r;
17036       }
17037 
17038     case EXPR_PACK_EXPANSION:
17039       error ("invalid use of pack expansion expression");
17040       return error_mark_node;
17041 
17042     case NONTYPE_ARGUMENT_PACK:
17043       error ("use %<...%> to expand argument pack");
17044       return error_mark_node;
17045 
17046     case VOID_CST:
17047       gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
17048       return t;
17049 
17050     case INTEGER_CST:
17051     case REAL_CST:
17052     case COMPLEX_CST:
17053       {
17054 	/* Instantiate any typedefs in the type.  */
17055 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17056 	r = fold_convert (type, t);
17057 	gcc_assert (TREE_CODE (r) == code);
17058 	return r;
17059       }
17060 
17061     case STRING_CST:
17062       {
17063 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17064 	r = t;
17065 	if (type != TREE_TYPE (t))
17066 	  {
17067 	    r = copy_node (t);
17068 	    TREE_TYPE (r) = type;
17069 	  }
17070 	return r;
17071       }
17072 
17073     case PTRMEM_CST:
17074       /* These can sometimes show up in a partial instantiation, but never
17075 	 involve template parms.  */
17076       gcc_assert (!uses_template_parms (t));
17077       return t;
17078 
17079     case UNARY_LEFT_FOLD_EXPR:
17080       return tsubst_unary_left_fold (t, args, complain, in_decl);
17081     case UNARY_RIGHT_FOLD_EXPR:
17082       return tsubst_unary_right_fold (t, args, complain, in_decl);
17083     case BINARY_LEFT_FOLD_EXPR:
17084       return tsubst_binary_left_fold (t, args, complain, in_decl);
17085     case BINARY_RIGHT_FOLD_EXPR:
17086       return tsubst_binary_right_fold (t, args, complain, in_decl);
17087     case PREDICT_EXPR:
17088       return t;
17089 
17090     case DEBUG_BEGIN_STMT:
17091       /* ??? There's no point in copying it for now, but maybe some
17092 	 day it will contain more information, such as a pointer back
17093 	 to the containing function, inlined copy or so.  */
17094       return t;
17095 
17096     case CO_AWAIT_EXPR:
17097       return tsubst_expr (t, args, complain, in_decl,
17098 			  /*integral_constant_expression_p=*/false);
17099       break;
17100 
17101     default:
17102       /* We shouldn't get here, but keep going if !flag_checking.  */
17103       if (flag_checking)
17104 	gcc_unreachable ();
17105       return t;
17106     }
17107 }
17108 
17109 /* Helper function for tsubst_omp_clauses, used for instantiation of
17110    OMP_CLAUSE_DECL of clauses.  */
17111 
17112 static tree
tsubst_omp_clause_decl(tree decl,tree args,tsubst_flags_t complain,tree in_decl,tree * iterator_cache)17113 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
17114 			tree in_decl, tree *iterator_cache)
17115 {
17116   if (decl == NULL_TREE)
17117     return NULL_TREE;
17118 
17119   /* Handle OpenMP iterators.  */
17120   if (TREE_CODE (decl) == TREE_LIST
17121       && TREE_PURPOSE (decl)
17122       && TREE_CODE (TREE_PURPOSE (decl)) == TREE_VEC)
17123     {
17124       tree ret;
17125       if (iterator_cache[0] == TREE_PURPOSE (decl))
17126 	ret = iterator_cache[1];
17127       else
17128 	{
17129 	  tree *tp = &ret;
17130 	  begin_scope (sk_omp, NULL);
17131 	  for (tree it = TREE_PURPOSE (decl); it; it = TREE_CHAIN (it))
17132 	    {
17133 	      *tp = copy_node (it);
17134 	      TREE_VEC_ELT (*tp, 0)
17135 		= tsubst_decl (TREE_VEC_ELT (it, 0), args, complain);
17136 	      TREE_VEC_ELT (*tp, 1)
17137 		= tsubst_expr (TREE_VEC_ELT (it, 1), args, complain, in_decl,
17138 			       /*integral_constant_expression_p=*/false);
17139 	      TREE_VEC_ELT (*tp, 2)
17140 		= tsubst_expr (TREE_VEC_ELT (it, 2), args, complain, in_decl,
17141 			       /*integral_constant_expression_p=*/false);
17142 	      TREE_VEC_ELT (*tp, 3)
17143 		= tsubst_expr (TREE_VEC_ELT (it, 3), args, complain, in_decl,
17144 			       /*integral_constant_expression_p=*/false);
17145 	      TREE_CHAIN (*tp) = NULL_TREE;
17146 	      tp = &TREE_CHAIN (*tp);
17147 	    }
17148 	  TREE_VEC_ELT (ret, 5) = poplevel (1, 1, 0);
17149 	  iterator_cache[0] = TREE_PURPOSE (decl);
17150 	  iterator_cache[1] = ret;
17151 	}
17152       return build_tree_list (ret, tsubst_omp_clause_decl (TREE_VALUE (decl),
17153 							   args, complain,
17154 							   in_decl, NULL));
17155     }
17156 
17157   /* Handle an OpenMP array section represented as a TREE_LIST (or
17158      OMP_CLAUSE_DEPEND_KIND).  An OMP_CLAUSE_DEPEND (with a depend
17159      kind of OMP_CLAUSE_DEPEND_SINK) can also be represented as a
17160      TREE_LIST.  We can handle it exactly the same as an array section
17161      (purpose, value, and a chain), even though the nomenclature
17162      (low_bound, length, etc) is different.  */
17163   if (TREE_CODE (decl) == TREE_LIST)
17164     {
17165       tree low_bound
17166 	= tsubst_expr (TREE_PURPOSE (decl), args, complain, in_decl,
17167 		       /*integral_constant_expression_p=*/false);
17168       tree length = tsubst_expr (TREE_VALUE (decl), args, complain, in_decl,
17169 				 /*integral_constant_expression_p=*/false);
17170       tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
17171 					   in_decl, NULL);
17172       if (TREE_PURPOSE (decl) == low_bound
17173 	  && TREE_VALUE (decl) == length
17174 	  && TREE_CHAIN (decl) == chain)
17175 	return decl;
17176       tree ret = tree_cons (low_bound, length, chain);
17177       OMP_CLAUSE_DEPEND_SINK_NEGATIVE (ret)
17178 	= OMP_CLAUSE_DEPEND_SINK_NEGATIVE (decl);
17179       return ret;
17180     }
17181   tree ret = tsubst_expr (decl, args, complain, in_decl,
17182 			  /*integral_constant_expression_p=*/false);
17183   /* Undo convert_from_reference tsubst_expr could have called.  */
17184   if (decl
17185       && REFERENCE_REF_P (ret)
17186       && !REFERENCE_REF_P (decl))
17187     ret = TREE_OPERAND (ret, 0);
17188   return ret;
17189 }
17190 
17191 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
17192 
17193 static tree
tsubst_omp_clauses(tree clauses,enum c_omp_region_type ort,tree args,tsubst_flags_t complain,tree in_decl)17194 tsubst_omp_clauses (tree clauses, enum c_omp_region_type ort,
17195 		    tree args, tsubst_flags_t complain, tree in_decl)
17196 {
17197   tree new_clauses = NULL_TREE, nc, oc;
17198   tree linear_no_step = NULL_TREE;
17199   tree iterator_cache[2] = { NULL_TREE, NULL_TREE };
17200 
17201   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
17202     {
17203       nc = copy_node (oc);
17204       OMP_CLAUSE_CHAIN (nc) = new_clauses;
17205       new_clauses = nc;
17206 
17207       switch (OMP_CLAUSE_CODE (nc))
17208 	{
17209 	case OMP_CLAUSE_LASTPRIVATE:
17210 	  if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
17211 	    {
17212 	      OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
17213 	      tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
17214 			   in_decl, /*integral_constant_expression_p=*/false);
17215 	      OMP_CLAUSE_LASTPRIVATE_STMT (nc)
17216 		= pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
17217 	    }
17218 	  /* FALLTHRU */
17219 	case OMP_CLAUSE_PRIVATE:
17220 	case OMP_CLAUSE_SHARED:
17221 	case OMP_CLAUSE_FIRSTPRIVATE:
17222 	case OMP_CLAUSE_COPYIN:
17223 	case OMP_CLAUSE_COPYPRIVATE:
17224 	case OMP_CLAUSE_UNIFORM:
17225 	case OMP_CLAUSE_DEPEND:
17226 	case OMP_CLAUSE_FROM:
17227 	case OMP_CLAUSE_TO:
17228 	case OMP_CLAUSE_MAP:
17229 	case OMP_CLAUSE__CACHE_:
17230 	case OMP_CLAUSE_NONTEMPORAL:
17231 	case OMP_CLAUSE_USE_DEVICE_PTR:
17232 	case OMP_CLAUSE_USE_DEVICE_ADDR:
17233 	case OMP_CLAUSE_IS_DEVICE_PTR:
17234 	case OMP_CLAUSE_INCLUSIVE:
17235 	case OMP_CLAUSE_EXCLUSIVE:
17236 	  OMP_CLAUSE_DECL (nc)
17237 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17238 				      in_decl, iterator_cache);
17239 	  break;
17240 	case OMP_CLAUSE_TILE:
17241 	case OMP_CLAUSE_IF:
17242 	case OMP_CLAUSE_NUM_THREADS:
17243 	case OMP_CLAUSE_SCHEDULE:
17244 	case OMP_CLAUSE_COLLAPSE:
17245 	case OMP_CLAUSE_FINAL:
17246 	case OMP_CLAUSE_DEVICE:
17247 	case OMP_CLAUSE_DIST_SCHEDULE:
17248 	case OMP_CLAUSE_NUM_TEAMS:
17249 	case OMP_CLAUSE_THREAD_LIMIT:
17250 	case OMP_CLAUSE_SAFELEN:
17251 	case OMP_CLAUSE_SIMDLEN:
17252 	case OMP_CLAUSE_NUM_TASKS:
17253 	case OMP_CLAUSE_GRAINSIZE:
17254 	case OMP_CLAUSE_PRIORITY:
17255 	case OMP_CLAUSE_ORDERED:
17256 	case OMP_CLAUSE_HINT:
17257 	case OMP_CLAUSE_NUM_GANGS:
17258 	case OMP_CLAUSE_NUM_WORKERS:
17259 	case OMP_CLAUSE_VECTOR_LENGTH:
17260 	case OMP_CLAUSE_WORKER:
17261 	case OMP_CLAUSE_VECTOR:
17262 	case OMP_CLAUSE_ASYNC:
17263 	case OMP_CLAUSE_WAIT:
17264 	  OMP_CLAUSE_OPERAND (nc, 0)
17265 	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain,
17266 			   in_decl, /*integral_constant_expression_p=*/false);
17267 	  break;
17268 	case OMP_CLAUSE_REDUCTION:
17269 	case OMP_CLAUSE_IN_REDUCTION:
17270 	case OMP_CLAUSE_TASK_REDUCTION:
17271 	  if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
17272 	    {
17273 	      tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
17274 	      if (TREE_CODE (placeholder) == SCOPE_REF)
17275 		{
17276 		  tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
17277 				       complain, in_decl);
17278 		  OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
17279 		    = build_qualified_name (NULL_TREE, scope,
17280 					    TREE_OPERAND (placeholder, 1),
17281 					    false);
17282 		}
17283 	      else
17284 		gcc_assert (identifier_p (placeholder));
17285 	    }
17286 	  OMP_CLAUSE_DECL (nc)
17287 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17288 				      in_decl, NULL);
17289 	  break;
17290 	case OMP_CLAUSE_GANG:
17291 	case OMP_CLAUSE_ALIGNED:
17292 	  OMP_CLAUSE_DECL (nc)
17293 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17294 				      in_decl, NULL);
17295 	  OMP_CLAUSE_OPERAND (nc, 1)
17296 	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain,
17297 			   in_decl, /*integral_constant_expression_p=*/false);
17298 	  break;
17299 	case OMP_CLAUSE_LINEAR:
17300 	  OMP_CLAUSE_DECL (nc)
17301 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17302 				      in_decl, NULL);
17303 	  if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
17304 	    {
17305 	      gcc_assert (!linear_no_step);
17306 	      linear_no_step = nc;
17307 	    }
17308 	  else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
17309 	    OMP_CLAUSE_LINEAR_STEP (nc)
17310 	      = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
17311 					complain, in_decl, NULL);
17312 	  else
17313 	    OMP_CLAUSE_LINEAR_STEP (nc)
17314 	      = tsubst_expr (OMP_CLAUSE_LINEAR_STEP (oc), args, complain,
17315 			     in_decl,
17316 			     /*integral_constant_expression_p=*/false);
17317 	  break;
17318 	case OMP_CLAUSE_NOWAIT:
17319 	case OMP_CLAUSE_DEFAULT:
17320 	case OMP_CLAUSE_UNTIED:
17321 	case OMP_CLAUSE_MERGEABLE:
17322 	case OMP_CLAUSE_INBRANCH:
17323 	case OMP_CLAUSE_NOTINBRANCH:
17324 	case OMP_CLAUSE_PROC_BIND:
17325 	case OMP_CLAUSE_FOR:
17326 	case OMP_CLAUSE_PARALLEL:
17327 	case OMP_CLAUSE_SECTIONS:
17328 	case OMP_CLAUSE_TASKGROUP:
17329 	case OMP_CLAUSE_NOGROUP:
17330 	case OMP_CLAUSE_THREADS:
17331 	case OMP_CLAUSE_SIMD:
17332 	case OMP_CLAUSE_DEFAULTMAP:
17333 	case OMP_CLAUSE_ORDER:
17334 	case OMP_CLAUSE_BIND:
17335 	case OMP_CLAUSE_INDEPENDENT:
17336 	case OMP_CLAUSE_AUTO:
17337 	case OMP_CLAUSE_SEQ:
17338 	case OMP_CLAUSE_IF_PRESENT:
17339 	case OMP_CLAUSE_FINALIZE:
17340 	  break;
17341 	default:
17342 	  gcc_unreachable ();
17343 	}
17344       if ((ort & C_ORT_OMP_DECLARE_SIMD) == C_ORT_OMP)
17345 	switch (OMP_CLAUSE_CODE (nc))
17346 	  {
17347 	  case OMP_CLAUSE_SHARED:
17348 	  case OMP_CLAUSE_PRIVATE:
17349 	  case OMP_CLAUSE_FIRSTPRIVATE:
17350 	  case OMP_CLAUSE_LASTPRIVATE:
17351 	  case OMP_CLAUSE_COPYPRIVATE:
17352 	  case OMP_CLAUSE_LINEAR:
17353 	  case OMP_CLAUSE_REDUCTION:
17354 	  case OMP_CLAUSE_IN_REDUCTION:
17355 	  case OMP_CLAUSE_TASK_REDUCTION:
17356 	  case OMP_CLAUSE_USE_DEVICE_PTR:
17357 	  case OMP_CLAUSE_USE_DEVICE_ADDR:
17358 	  case OMP_CLAUSE_IS_DEVICE_PTR:
17359 	  case OMP_CLAUSE_INCLUSIVE:
17360 	  case OMP_CLAUSE_EXCLUSIVE:
17361 	    /* tsubst_expr on SCOPE_REF results in returning
17362 	       finish_non_static_data_member result.  Undo that here.  */
17363 	    if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
17364 		&& (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
17365 		    == IDENTIFIER_NODE))
17366 	      {
17367 		tree t = OMP_CLAUSE_DECL (nc);
17368 		tree v = t;
17369 		while (v)
17370 		  switch (TREE_CODE (v))
17371 		    {
17372 		    case COMPONENT_REF:
17373 		    case MEM_REF:
17374 		    case INDIRECT_REF:
17375 		    CASE_CONVERT:
17376 		    case POINTER_PLUS_EXPR:
17377 		      v = TREE_OPERAND (v, 0);
17378 		      continue;
17379 		    case PARM_DECL:
17380 		      if (DECL_CONTEXT (v) == current_function_decl
17381 			  && DECL_ARTIFICIAL (v)
17382 			  && DECL_NAME (v) == this_identifier)
17383 			OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
17384 		      /* FALLTHRU */
17385 		    default:
17386 		      v = NULL_TREE;
17387 		      break;
17388 		    }
17389 	      }
17390 	    else if (VAR_P (OMP_CLAUSE_DECL (oc))
17391 		     && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
17392 		     && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
17393 		     && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
17394 		     && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
17395 	      {
17396 		tree decl = OMP_CLAUSE_DECL (nc);
17397 		if (VAR_P (decl))
17398 		  {
17399 		    retrofit_lang_decl (decl);
17400 		    DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
17401 		  }
17402 	      }
17403 	    break;
17404 	  default:
17405 	    break;
17406 	  }
17407     }
17408 
17409   new_clauses = nreverse (new_clauses);
17410   if (ort != C_ORT_OMP_DECLARE_SIMD)
17411     {
17412       new_clauses = finish_omp_clauses (new_clauses, ort);
17413       if (linear_no_step)
17414 	for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
17415 	  if (nc == linear_no_step)
17416 	    {
17417 	      OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
17418 	      break;
17419 	    }
17420     }
17421   return new_clauses;
17422 }
17423 
17424 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
17425 
17426 static tree
tsubst_copy_asm_operands(tree t,tree args,tsubst_flags_t complain,tree in_decl)17427 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
17428 			  tree in_decl)
17429 {
17430 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
17431 
17432   tree purpose, value, chain;
17433 
17434   if (t == NULL)
17435     return t;
17436 
17437   if (TREE_CODE (t) != TREE_LIST)
17438     return tsubst_copy_and_build (t, args, complain, in_decl,
17439 				  /*function_p=*/false,
17440 				  /*integral_constant_expression_p=*/false);
17441 
17442   if (t == void_list_node)
17443     return t;
17444 
17445   purpose = TREE_PURPOSE (t);
17446   if (purpose)
17447     purpose = RECUR (purpose);
17448   value = TREE_VALUE (t);
17449   if (value)
17450     {
17451       if (TREE_CODE (value) != LABEL_DECL)
17452 	value = RECUR (value);
17453       else
17454 	{
17455 	  value = lookup_label (DECL_NAME (value));
17456 	  gcc_assert (TREE_CODE (value) == LABEL_DECL);
17457 	  TREE_USED (value) = 1;
17458 	}
17459     }
17460   chain = TREE_CHAIN (t);
17461   if (chain && chain != void_type_node)
17462     chain = RECUR (chain);
17463   return tree_cons (purpose, value, chain);
17464 #undef RECUR
17465 }
17466 
17467 /* Used to temporarily communicate the list of #pragma omp parallel
17468    clauses to #pragma omp for instantiation if they are combined
17469    together.  */
17470 
17471 static tree *omp_parallel_combined_clauses;
17472 
17473 static tree tsubst_decomp_names (tree, tree, tree, tsubst_flags_t, tree,
17474 				 tree *, unsigned int *);
17475 
17476 /* Substitute one OMP_FOR iterator.  */
17477 
17478 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)17479 tsubst_omp_for_iterator (tree t, int i, tree declv, tree &orig_declv,
17480 			 tree initv, tree condv, tree incrv, tree *clauses,
17481 			 tree args, tsubst_flags_t complain, tree in_decl,
17482 			 bool integral_constant_expression_p)
17483 {
17484 #define RECUR(NODE)				\
17485   tsubst_expr ((NODE), args, complain, in_decl,	\
17486 	       integral_constant_expression_p)
17487   tree decl, init, cond = NULL_TREE, incr = NULL_TREE;
17488   bool ret = false;
17489 
17490   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
17491   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
17492 
17493   decl = TREE_OPERAND (init, 0);
17494   init = TREE_OPERAND (init, 1);
17495   tree decl_expr = NULL_TREE;
17496   bool range_for = TREE_VEC_ELT (OMP_FOR_COND (t), i) == global_namespace;
17497   if (range_for)
17498     {
17499       bool decomp = false;
17500       if (decl != error_mark_node && DECL_HAS_VALUE_EXPR_P (decl))
17501 	{
17502 	  tree v = DECL_VALUE_EXPR (decl);
17503 	  if (TREE_CODE (v) == ARRAY_REF
17504 	      && VAR_P (TREE_OPERAND (v, 0))
17505 	      && DECL_DECOMPOSITION_P (TREE_OPERAND (v, 0)))
17506 	    {
17507 	      tree decomp_first = NULL_TREE;
17508 	      unsigned decomp_cnt = 0;
17509 	      tree d = tsubst_decl (TREE_OPERAND (v, 0), args, complain);
17510 	      maybe_push_decl (d);
17511 	      d = tsubst_decomp_names (d, TREE_OPERAND (v, 0), args, complain,
17512 				       in_decl, &decomp_first, &decomp_cnt);
17513 	      decomp = true;
17514 	      if (d == error_mark_node)
17515 		decl = error_mark_node;
17516 	      else
17517 		for (unsigned int i = 0; i < decomp_cnt; i++)
17518 		  {
17519 		    if (!DECL_HAS_VALUE_EXPR_P (decomp_first))
17520 		      {
17521 			tree v = build_nt (ARRAY_REF, d,
17522 					   size_int (decomp_cnt - i - 1),
17523 					   NULL_TREE, NULL_TREE);
17524 			SET_DECL_VALUE_EXPR (decomp_first, v);
17525 			DECL_HAS_VALUE_EXPR_P (decomp_first) = 1;
17526 		      }
17527 		    fit_decomposition_lang_decl (decomp_first, d);
17528 		    decomp_first = DECL_CHAIN (decomp_first);
17529 		  }
17530 	    }
17531 	}
17532       decl = tsubst_decl (decl, args, complain);
17533       if (!decomp)
17534 	maybe_push_decl (decl);
17535     }
17536   else if (init && TREE_CODE (init) == DECL_EXPR)
17537     {
17538       /* We need to jump through some hoops to handle declarations in the
17539 	 init-statement, since we might need to handle auto deduction,
17540 	 but we need to keep control of initialization.  */
17541       decl_expr = init;
17542       init = DECL_INITIAL (DECL_EXPR_DECL (init));
17543       decl = tsubst_decl (decl, args, complain);
17544     }
17545   else
17546     {
17547       if (TREE_CODE (decl) == SCOPE_REF)
17548 	{
17549 	  decl = RECUR (decl);
17550 	  if (TREE_CODE (decl) == COMPONENT_REF)
17551 	    {
17552 	      tree v = decl;
17553 	      while (v)
17554 		switch (TREE_CODE (v))
17555 		  {
17556 		  case COMPONENT_REF:
17557 		  case MEM_REF:
17558 		  case INDIRECT_REF:
17559 		  CASE_CONVERT:
17560 		  case POINTER_PLUS_EXPR:
17561 		    v = TREE_OPERAND (v, 0);
17562 		    continue;
17563 		  case PARM_DECL:
17564 		    if (DECL_CONTEXT (v) == current_function_decl
17565 			&& DECL_ARTIFICIAL (v)
17566 			&& DECL_NAME (v) == this_identifier)
17567 		      {
17568 			decl = TREE_OPERAND (decl, 1);
17569 			decl = omp_privatize_field (decl, false);
17570 		      }
17571 		    /* FALLTHRU */
17572 		  default:
17573 		    v = NULL_TREE;
17574 		    break;
17575 		  }
17576 	    }
17577 	}
17578       else
17579 	decl = RECUR (decl);
17580     }
17581   init = RECUR (init);
17582 
17583   if (orig_declv && OMP_FOR_ORIG_DECLS (t))
17584     {
17585       tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
17586       if (TREE_CODE (o) == TREE_LIST)
17587 	TREE_VEC_ELT (orig_declv, i)
17588 	  = tree_cons (RECUR (TREE_PURPOSE (o)),
17589 		       RECUR (TREE_VALUE (o)),
17590 		       NULL_TREE);
17591       else
17592 	TREE_VEC_ELT (orig_declv, i) = RECUR (o);
17593     }
17594 
17595   if (range_for)
17596     {
17597       tree this_pre_body = NULL_TREE;
17598       tree orig_init = NULL_TREE;
17599       tree orig_decl = NULL_TREE;
17600       cp_convert_omp_range_for (this_pre_body, NULL, decl, orig_decl, init,
17601 				orig_init, cond, incr);
17602       if (orig_decl)
17603 	{
17604 	  if (orig_declv == NULL_TREE)
17605 	    orig_declv = copy_node (declv);
17606 	  TREE_VEC_ELT (orig_declv, i) = orig_decl;
17607 	  ret = true;
17608 	}
17609       else if (orig_declv)
17610 	TREE_VEC_ELT (orig_declv, i) = decl;
17611     }
17612 
17613   tree auto_node = type_uses_auto (TREE_TYPE (decl));
17614   if (!range_for && auto_node && init)
17615     TREE_TYPE (decl)
17616       = do_auto_deduction (TREE_TYPE (decl), init, auto_node, complain);
17617 
17618   gcc_assert (!type_dependent_expression_p (decl));
17619 
17620   if (!CLASS_TYPE_P (TREE_TYPE (decl)) || range_for)
17621     {
17622       if (decl_expr)
17623 	{
17624 	  /* Declare the variable, but don't let that initialize it.  */
17625 	  tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
17626 	  DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
17627 	  RECUR (decl_expr);
17628 	  DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
17629 	}
17630 
17631       if (!range_for)
17632 	{
17633 	  cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
17634 	  incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
17635 	  if (TREE_CODE (incr) == MODIFY_EXPR)
17636 	    {
17637 	      tree lhs = RECUR (TREE_OPERAND (incr, 0));
17638 	      tree rhs = RECUR (TREE_OPERAND (incr, 1));
17639 	      incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
17640 					  NOP_EXPR, rhs, complain);
17641 	    }
17642 	  else
17643 	    incr = RECUR (incr);
17644 	  if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
17645 	    TREE_VEC_ELT (orig_declv, i) = decl;
17646 	}
17647       TREE_VEC_ELT (declv, i) = decl;
17648       TREE_VEC_ELT (initv, i) = init;
17649       TREE_VEC_ELT (condv, i) = cond;
17650       TREE_VEC_ELT (incrv, i) = incr;
17651       return ret;
17652     }
17653 
17654   if (decl_expr)
17655     {
17656       /* Declare and initialize the variable.  */
17657       RECUR (decl_expr);
17658       init = NULL_TREE;
17659     }
17660   else if (init)
17661     {
17662       tree *pc;
17663       int j;
17664       for (j = ((omp_parallel_combined_clauses == NULL
17665 		|| TREE_CODE (t) == OMP_LOOP) ? 1 : 0); j < 2; j++)
17666 	{
17667 	  for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
17668 	    {
17669 	      if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
17670 		  && OMP_CLAUSE_DECL (*pc) == decl)
17671 		break;
17672 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
17673 		       && OMP_CLAUSE_DECL (*pc) == decl)
17674 		{
17675 		  if (j)
17676 		    break;
17677 		  /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES.  */
17678 		  tree c = *pc;
17679 		  *pc = OMP_CLAUSE_CHAIN (c);
17680 		  OMP_CLAUSE_CHAIN (c) = *clauses;
17681 		  *clauses = c;
17682 		}
17683 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
17684 		       && OMP_CLAUSE_DECL (*pc) == decl)
17685 		{
17686 		  error ("iteration variable %qD should not be firstprivate",
17687 			 decl);
17688 		  *pc = OMP_CLAUSE_CHAIN (*pc);
17689 		}
17690 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
17691 		       && OMP_CLAUSE_DECL (*pc) == decl)
17692 		{
17693 		  error ("iteration variable %qD should not be reduction",
17694 			 decl);
17695 		  *pc = OMP_CLAUSE_CHAIN (*pc);
17696 		}
17697 	      else
17698 		pc = &OMP_CLAUSE_CHAIN (*pc);
17699 	    }
17700 	  if (*pc)
17701 	    break;
17702 	}
17703       if (*pc == NULL_TREE)
17704 	{
17705 	  tree c = build_omp_clause (input_location,
17706 				     TREE_CODE (t) == OMP_LOOP
17707 				     ? OMP_CLAUSE_LASTPRIVATE
17708 				     : OMP_CLAUSE_PRIVATE);
17709 	  OMP_CLAUSE_DECL (c) = decl;
17710 	  c = finish_omp_clauses (c, C_ORT_OMP);
17711 	  if (c)
17712 	    {
17713 	      OMP_CLAUSE_CHAIN (c) = *clauses;
17714 	      *clauses = c;
17715 	    }
17716 	}
17717     }
17718   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
17719   if (COMPARISON_CLASS_P (cond))
17720     {
17721       tree op0 = RECUR (TREE_OPERAND (cond, 0));
17722       tree op1 = RECUR (TREE_OPERAND (cond, 1));
17723       cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
17724     }
17725   else
17726     cond = RECUR (cond);
17727   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
17728   switch (TREE_CODE (incr))
17729     {
17730     case PREINCREMENT_EXPR:
17731     case PREDECREMENT_EXPR:
17732     case POSTINCREMENT_EXPR:
17733     case POSTDECREMENT_EXPR:
17734       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
17735 		     RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
17736       break;
17737     case MODIFY_EXPR:
17738       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
17739 	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
17740 	{
17741 	  tree rhs = TREE_OPERAND (incr, 1);
17742 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
17743 	  tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
17744 	  tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
17745 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
17746 			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
17747 				 rhs0, rhs1));
17748 	}
17749       else
17750 	incr = RECUR (incr);
17751       break;
17752     case MODOP_EXPR:
17753       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
17754 	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
17755 	{
17756 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
17757 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
17758 			 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
17759 				 TREE_TYPE (decl), lhs,
17760 				 RECUR (TREE_OPERAND (incr, 2))));
17761 	}
17762       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
17763 	       && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
17764 		   || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
17765 	{
17766 	  tree rhs = TREE_OPERAND (incr, 2);
17767 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
17768 	  tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
17769 	  tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
17770 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
17771 			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
17772 				 rhs0, rhs1));
17773 	}
17774       else
17775 	incr = RECUR (incr);
17776       break;
17777     default:
17778       incr = RECUR (incr);
17779       break;
17780     }
17781 
17782   if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
17783     TREE_VEC_ELT (orig_declv, i) = decl;
17784   TREE_VEC_ELT (declv, i) = decl;
17785   TREE_VEC_ELT (initv, i) = init;
17786   TREE_VEC_ELT (condv, i) = cond;
17787   TREE_VEC_ELT (incrv, i) = incr;
17788   return false;
17789 #undef RECUR
17790 }
17791 
17792 /* Helper function of tsubst_expr, find OMP_TEAMS inside
17793    of OMP_TARGET's body.  */
17794 
17795 static tree
tsubst_find_omp_teams(tree * tp,int * walk_subtrees,void *)17796 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
17797 {
17798   *walk_subtrees = 0;
17799   switch (TREE_CODE (*tp))
17800     {
17801     case OMP_TEAMS:
17802       return *tp;
17803     case BIND_EXPR:
17804     case STATEMENT_LIST:
17805       *walk_subtrees = 1;
17806       break;
17807     default:
17808       break;
17809     }
17810   return NULL_TREE;
17811 }
17812 
17813 /* Helper function for tsubst_expr.  For decomposition declaration
17814    artificial base DECL, which is tsubsted PATTERN_DECL, tsubst
17815    also the corresponding decls representing the identifiers
17816    of the decomposition declaration.  Return DECL if successful
17817    or error_mark_node otherwise, set *FIRST to the first decl
17818    in the list chained through DECL_CHAIN and *CNT to the number
17819    of such decls.  */
17820 
17821 static tree
tsubst_decomp_names(tree decl,tree pattern_decl,tree args,tsubst_flags_t complain,tree in_decl,tree * first,unsigned int * cnt)17822 tsubst_decomp_names (tree decl, tree pattern_decl, tree args,
17823 		     tsubst_flags_t complain, tree in_decl, tree *first,
17824 		     unsigned int *cnt)
17825 {
17826   tree decl2, decl3, prev = decl;
17827   *cnt = 0;
17828   gcc_assert (DECL_NAME (decl) == NULL_TREE);
17829   for (decl2 = DECL_CHAIN (pattern_decl);
17830        decl2
17831        && VAR_P (decl2)
17832        && DECL_DECOMPOSITION_P (decl2)
17833        && DECL_NAME (decl2);
17834        decl2 = DECL_CHAIN (decl2))
17835     {
17836       if (TREE_TYPE (decl2) == error_mark_node && *cnt == 0)
17837 	{
17838 	  gcc_assert (errorcount);
17839 	  return error_mark_node;
17840 	}
17841       (*cnt)++;
17842       gcc_assert (DECL_DECOMP_BASE (decl2) == pattern_decl);
17843       gcc_assert (DECL_HAS_VALUE_EXPR_P (decl2));
17844       tree v = DECL_VALUE_EXPR (decl2);
17845       DECL_HAS_VALUE_EXPR_P (decl2) = 0;
17846       SET_DECL_VALUE_EXPR (decl2, NULL_TREE);
17847       decl3 = tsubst (decl2, args, complain, in_decl);
17848       SET_DECL_VALUE_EXPR (decl2, v);
17849       DECL_HAS_VALUE_EXPR_P (decl2) = 1;
17850       if (VAR_P (decl3))
17851 	DECL_TEMPLATE_INSTANTIATED (decl3) = 1;
17852       else
17853 	{
17854 	  gcc_assert (errorcount);
17855 	  decl = error_mark_node;
17856 	  continue;
17857 	}
17858       maybe_push_decl (decl3);
17859       if (error_operand_p (decl3))
17860 	decl = error_mark_node;
17861       else if (decl != error_mark_node
17862 	       && DECL_CHAIN (decl3) != prev
17863 	       && decl != prev)
17864 	{
17865 	  gcc_assert (errorcount);
17866 	  decl = error_mark_node;
17867 	}
17868       else
17869 	prev = decl3;
17870     }
17871   *first = prev;
17872   return decl;
17873 }
17874 
17875 /* Return the proper local_specialization for init-capture pack DECL.  */
17876 
17877 static tree
lookup_init_capture_pack(tree decl)17878 lookup_init_capture_pack (tree decl)
17879 {
17880   /* We handle normal pack captures by forwarding to the specialization of the
17881      captured parameter.  We can't do that for pack init-captures; we need them
17882      to have their own local_specialization.  We created the individual
17883      VAR_DECLs (if any) under build_capture_proxy, and we need to collect them
17884      when we process the DECL_EXPR for the pack init-capture in the template.
17885      So, how do we find them?  We don't know the capture proxy pack when
17886      building the individual resulting proxies, and we don't know the
17887      individual proxies when instantiating the pack.  What we have in common is
17888      the FIELD_DECL.
17889 
17890      So...when we instantiate the FIELD_DECL, we stick the result in
17891      local_specializations.  Then at the DECL_EXPR we look up that result, see
17892      how many elements it has, synthesize the names, and look them up.  */
17893 
17894   tree cname = DECL_NAME (decl);
17895   tree val = DECL_VALUE_EXPR (decl);
17896   tree field = TREE_OPERAND (val, 1);
17897   gcc_assert (TREE_CODE (field) == FIELD_DECL);
17898   tree fpack = retrieve_local_specialization (field);
17899   if (fpack == error_mark_node)
17900     return error_mark_node;
17901 
17902   int len = 1;
17903   tree vec = NULL_TREE;
17904   tree r = NULL_TREE;
17905   if (TREE_CODE (fpack) == TREE_VEC)
17906     {
17907       len = TREE_VEC_LENGTH (fpack);
17908       vec = make_tree_vec (len);
17909       r = make_node (NONTYPE_ARGUMENT_PACK);
17910       SET_ARGUMENT_PACK_ARGS (r, vec);
17911     }
17912   for (int i = 0; i < len; ++i)
17913     {
17914       tree ename = vec ? make_ith_pack_parameter_name (cname, i) : cname;
17915       tree elt = lookup_name_real (ename, 0, 0, true, 0, LOOKUP_NORMAL);
17916       if (vec)
17917 	TREE_VEC_ELT (vec, i) = elt;
17918       else
17919 	r = elt;
17920     }
17921   return r;
17922 }
17923 
17924 /* Like tsubst_copy for expressions, etc. but also does semantic
17925    processing.  */
17926 
17927 tree
tsubst_expr(tree t,tree args,tsubst_flags_t complain,tree in_decl,bool integral_constant_expression_p)17928 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
17929 	     bool integral_constant_expression_p)
17930 {
17931 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
17932 #define RECUR(NODE)				\
17933   tsubst_expr ((NODE), args, complain, in_decl,	\
17934 	       integral_constant_expression_p)
17935 
17936   tree stmt, tmp;
17937   tree r;
17938   location_t loc;
17939 
17940   if (t == NULL_TREE || t == error_mark_node)
17941     return t;
17942 
17943   loc = input_location;
17944   if (location_t eloc = cp_expr_location (t))
17945     input_location = eloc;
17946   if (STATEMENT_CODE_P (TREE_CODE (t)))
17947     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
17948 
17949   switch (TREE_CODE (t))
17950     {
17951     case STATEMENT_LIST:
17952       {
17953 	tree_stmt_iterator i;
17954 	for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
17955 	  RECUR (tsi_stmt (i));
17956 	break;
17957       }
17958 
17959     case CTOR_INITIALIZER:
17960       finish_mem_initializers (tsubst_initializer_list
17961 			       (TREE_OPERAND (t, 0), args));
17962       break;
17963 
17964     case RETURN_EXPR:
17965       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
17966       break;
17967 
17968     case CO_RETURN_EXPR:
17969       finish_co_return_stmt (input_location, RECUR (TREE_OPERAND (t, 0)));
17970       break;
17971 
17972     case CO_YIELD_EXPR:
17973       stmt = finish_co_yield_expr (input_location,
17974 				   RECUR (TREE_OPERAND (t, 0)));
17975       RETURN (stmt);
17976       break;
17977 
17978     case CO_AWAIT_EXPR:
17979       stmt = finish_co_await_expr (input_location,
17980 				   RECUR (TREE_OPERAND (t, 0)));
17981       RETURN (stmt);
17982       break;
17983 
17984     case EXPR_STMT:
17985       tmp = RECUR (EXPR_STMT_EXPR (t));
17986       if (EXPR_STMT_STMT_EXPR_RESULT (t))
17987 	finish_stmt_expr_expr (tmp, cur_stmt_expr);
17988       else
17989 	finish_expr_stmt (tmp);
17990       break;
17991 
17992     case USING_STMT:
17993       finish_using_directive (USING_STMT_NAMESPACE (t), /*attribs=*/NULL_TREE);
17994       break;
17995 
17996     case DECL_EXPR:
17997       {
17998 	tree decl, pattern_decl;
17999 	tree init;
18000 
18001 	pattern_decl = decl = DECL_EXPR_DECL (t);
18002 	if (TREE_CODE (decl) == LABEL_DECL)
18003 	  finish_label_decl (DECL_NAME (decl));
18004 	else if (TREE_CODE (decl) == USING_DECL)
18005 	  {
18006 	    tree scope = USING_DECL_SCOPE (decl);
18007 	    tree name = DECL_NAME (decl);
18008 
18009 	    scope = tsubst (scope, args, complain, in_decl);
18010 	    finish_nonmember_using_decl (scope, name);
18011 	  }
18012 	else if (is_capture_proxy (decl)
18013 		 && !DECL_TEMPLATE_INSTANTIATION (current_function_decl))
18014 	  {
18015 	    /* We're in tsubst_lambda_expr, we've already inserted a new
18016 	       capture proxy, so look it up and register it.  */
18017 	    tree inst;
18018 	    if (!DECL_PACK_P (decl))
18019 	      {
18020 		inst = lookup_name_real (DECL_NAME (decl), /*prefer_type*/0,
18021 					 /*nonclass*/1, /*block_p=*/true,
18022 					 /*ns_only*/0, LOOKUP_HIDDEN);
18023 		gcc_assert (inst != decl && is_capture_proxy (inst));
18024 	      }
18025 	    else if (is_normal_capture_proxy (decl))
18026 	      {
18027 		inst = (retrieve_local_specialization
18028 			(DECL_CAPTURED_VARIABLE (decl)));
18029 		gcc_assert (TREE_CODE (inst) == NONTYPE_ARGUMENT_PACK
18030 			    || DECL_PACK_P (inst));
18031 	      }
18032 	    else
18033 	      inst = lookup_init_capture_pack (decl);
18034 
18035 	    register_local_specialization (inst, decl);
18036 	    break;
18037 	  }
18038 	else if (DECL_PRETTY_FUNCTION_P (decl))
18039 	  decl = make_fname_decl (DECL_SOURCE_LOCATION (decl),
18040 				  DECL_NAME (decl),
18041 				  true/*DECL_PRETTY_FUNCTION_P (decl)*/);
18042 	else if (DECL_IMPLICIT_TYPEDEF_P (decl)
18043 		 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
18044 	  /* Don't copy the old closure; we'll create a new one in
18045 	     tsubst_lambda_expr.  */
18046 	  break;
18047 	else
18048 	  {
18049 	    init = DECL_INITIAL (decl);
18050 	    /* The following tsubst call will clear the DECL_TEMPLATE_INFO
18051 	       for local variables, so save if DECL was declared constinit.  */
18052 	    const bool constinit_p
18053 	      = (VAR_P (decl)
18054 		 && DECL_LANG_SPECIFIC (decl)
18055 		 && DECL_TEMPLATE_INFO (decl)
18056 		 && TINFO_VAR_DECLARED_CONSTINIT (DECL_TEMPLATE_INFO (decl)));
18057 	    decl = tsubst (decl, args, complain, in_decl);
18058 	    if (decl != error_mark_node)
18059 	      {
18060 		/* By marking the declaration as instantiated, we avoid
18061 		   trying to instantiate it.  Since instantiate_decl can't
18062 		   handle local variables, and since we've already done
18063 		   all that needs to be done, that's the right thing to
18064 		   do.  */
18065 		if (VAR_P (decl))
18066 		  DECL_TEMPLATE_INSTANTIATED (decl) = 1;
18067 		if (VAR_P (decl) && !DECL_NAME (decl)
18068 		    && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
18069 		  /* Anonymous aggregates are a special case.  */
18070 		  finish_anon_union (decl);
18071 		else if (is_capture_proxy (DECL_EXPR_DECL (t)))
18072 		  {
18073 		    DECL_CONTEXT (decl) = current_function_decl;
18074 		    if (DECL_NAME (decl) == this_identifier)
18075 		      {
18076 			tree lam = DECL_CONTEXT (current_function_decl);
18077 			lam = CLASSTYPE_LAMBDA_EXPR (lam);
18078 			LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
18079 		      }
18080 		    insert_capture_proxy (decl);
18081 		  }
18082 		else if (DECL_IMPLICIT_TYPEDEF_P (t))
18083 		  /* We already did a pushtag.  */;
18084 		else if (TREE_CODE (decl) == FUNCTION_DECL
18085 			 && DECL_OMP_DECLARE_REDUCTION_P (decl)
18086 			 && DECL_FUNCTION_SCOPE_P (pattern_decl))
18087 		  {
18088 		    DECL_CONTEXT (decl) = NULL_TREE;
18089 		    pushdecl (decl);
18090 		    DECL_CONTEXT (decl) = current_function_decl;
18091 		    cp_check_omp_declare_reduction (decl);
18092 		  }
18093 		else
18094 		  {
18095 		    bool const_init = false;
18096 		    unsigned int cnt = 0;
18097 		    tree first = NULL_TREE, ndecl = error_mark_node;
18098 		    tree asmspec_tree = NULL_TREE;
18099 		    maybe_push_decl (decl);
18100 
18101 		    if (VAR_P (decl)
18102 			&& DECL_DECOMPOSITION_P (decl)
18103 			&& TREE_TYPE (pattern_decl) != error_mark_node)
18104 		      ndecl = tsubst_decomp_names (decl, pattern_decl, args,
18105 						   complain, in_decl, &first,
18106 						   &cnt);
18107 
18108 		    init = tsubst_init (init, decl, args, complain, in_decl);
18109 
18110 		    if (VAR_P (decl))
18111 		      const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
18112 				    (pattern_decl));
18113 
18114 		    if (ndecl != error_mark_node)
18115 		      cp_maybe_mangle_decomp (ndecl, first, cnt);
18116 
18117 		    if (VAR_P (decl) && DECL_HARD_REGISTER (pattern_decl))
18118 		      {
18119 			tree id = DECL_ASSEMBLER_NAME (pattern_decl);
18120 			const char *asmspec = IDENTIFIER_POINTER (id);
18121 			gcc_assert (asmspec[0] == '*');
18122 			asmspec_tree
18123 			  = build_string (IDENTIFIER_LENGTH (id) - 1,
18124 					  asmspec + 1);
18125 			TREE_TYPE (asmspec_tree) = char_array_type_node;
18126 		      }
18127 
18128 		    cp_finish_decl (decl, init, const_init, asmspec_tree,
18129 				    constinit_p ? LOOKUP_CONSTINIT : 0);
18130 
18131 		    if (ndecl != error_mark_node)
18132 		      cp_finish_decomp (ndecl, first, cnt);
18133 		  }
18134 	      }
18135 	  }
18136 
18137 	break;
18138       }
18139 
18140     case FOR_STMT:
18141       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
18142       RECUR (FOR_INIT_STMT (t));
18143       finish_init_stmt (stmt);
18144       tmp = RECUR (FOR_COND (t));
18145       finish_for_cond (tmp, stmt, false, 0);
18146       tmp = RECUR (FOR_EXPR (t));
18147       finish_for_expr (tmp, stmt);
18148       {
18149 	bool prev = note_iteration_stmt_body_start ();
18150 	RECUR (FOR_BODY (t));
18151 	note_iteration_stmt_body_end (prev);
18152       }
18153       finish_for_stmt (stmt);
18154       break;
18155 
18156     case RANGE_FOR_STMT:
18157       {
18158 	/* Construct another range_for, if this is not a final
18159 	   substitution (for inside a generic lambda of a
18160 	   template).  Otherwise convert to a regular for.  */
18161         tree decl, expr;
18162         stmt = (processing_template_decl
18163 		? begin_range_for_stmt (NULL_TREE, NULL_TREE)
18164 		: begin_for_stmt (NULL_TREE, NULL_TREE));
18165 	RECUR (RANGE_FOR_INIT_STMT (t));
18166         decl = RANGE_FOR_DECL (t);
18167         decl = tsubst (decl, args, complain, in_decl);
18168         maybe_push_decl (decl);
18169         expr = RECUR (RANGE_FOR_EXPR (t));
18170 
18171 	tree decomp_first = NULL_TREE;
18172 	unsigned decomp_cnt = 0;
18173 	if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
18174 	  decl = tsubst_decomp_names (decl, RANGE_FOR_DECL (t), args,
18175 				      complain, in_decl,
18176 				      &decomp_first, &decomp_cnt);
18177 
18178 	if (processing_template_decl)
18179 	  {
18180 	    RANGE_FOR_IVDEP (stmt) = RANGE_FOR_IVDEP (t);
18181 	    RANGE_FOR_UNROLL (stmt) = RANGE_FOR_UNROLL (t);
18182 	    finish_range_for_decl (stmt, decl, expr);
18183 	    if (decomp_first && decl != error_mark_node)
18184 	      cp_finish_decomp (decl, decomp_first, decomp_cnt);
18185 	  }
18186 	else
18187 	  {
18188 	    unsigned short unroll = (RANGE_FOR_UNROLL (t)
18189 				     ? tree_to_uhwi (RANGE_FOR_UNROLL (t)) : 0);
18190 	    stmt = cp_convert_range_for (stmt, decl, expr,
18191 					 decomp_first, decomp_cnt,
18192 					 RANGE_FOR_IVDEP (t), unroll);
18193 	  }
18194 
18195 	bool prev = note_iteration_stmt_body_start ();
18196         RECUR (RANGE_FOR_BODY (t));
18197 	note_iteration_stmt_body_end (prev);
18198         finish_for_stmt (stmt);
18199       }
18200       break;
18201 
18202     case WHILE_STMT:
18203       stmt = begin_while_stmt ();
18204       tmp = RECUR (WHILE_COND (t));
18205       finish_while_stmt_cond (tmp, stmt, false, 0);
18206       {
18207 	bool prev = note_iteration_stmt_body_start ();
18208 	RECUR (WHILE_BODY (t));
18209 	note_iteration_stmt_body_end (prev);
18210       }
18211       finish_while_stmt (stmt);
18212       break;
18213 
18214     case DO_STMT:
18215       stmt = begin_do_stmt ();
18216       {
18217 	bool prev = note_iteration_stmt_body_start ();
18218 	RECUR (DO_BODY (t));
18219 	note_iteration_stmt_body_end (prev);
18220       }
18221       finish_do_body (stmt);
18222       tmp = RECUR (DO_COND (t));
18223       finish_do_stmt (tmp, stmt, false, 0);
18224       break;
18225 
18226     case IF_STMT:
18227       stmt = begin_if_stmt ();
18228       IF_STMT_CONSTEXPR_P (stmt) = IF_STMT_CONSTEXPR_P (t);
18229       if (IF_STMT_CONSTEXPR_P (t))
18230 	args = add_extra_args (IF_STMT_EXTRA_ARGS (t), args);
18231       tmp = RECUR (IF_COND (t));
18232       tmp = finish_if_stmt_cond (tmp, stmt);
18233       if (IF_STMT_CONSTEXPR_P (t)
18234 	  && instantiation_dependent_expression_p (tmp))
18235 	{
18236 	  /* We're partially instantiating a generic lambda, but the condition
18237 	     of the constexpr if is still dependent.  Don't substitute into the
18238 	     branches now, just remember the template arguments.  */
18239 	  do_poplevel (IF_SCOPE (stmt));
18240 	  IF_COND (stmt) = IF_COND (t);
18241 	  THEN_CLAUSE (stmt) = THEN_CLAUSE (t);
18242 	  ELSE_CLAUSE (stmt) = ELSE_CLAUSE (t);
18243 	  IF_STMT_EXTRA_ARGS (stmt) = build_extra_args (t, args, complain);
18244 	  add_stmt (stmt);
18245 	  break;
18246 	}
18247       if (IF_STMT_CONSTEXPR_P (t) && integer_zerop (tmp))
18248 	/* Don't instantiate the THEN_CLAUSE. */;
18249       else
18250 	{
18251 	  tree folded = fold_non_dependent_expr (tmp, complain);
18252 	  bool inhibit = integer_zerop (folded);
18253 	  if (inhibit)
18254 	    ++c_inhibit_evaluation_warnings;
18255 	  RECUR (THEN_CLAUSE (t));
18256 	  if (inhibit)
18257 	    --c_inhibit_evaluation_warnings;
18258 	}
18259       finish_then_clause (stmt);
18260 
18261       if (IF_STMT_CONSTEXPR_P (t) && integer_nonzerop (tmp))
18262 	/* Don't instantiate the ELSE_CLAUSE. */;
18263       else if (ELSE_CLAUSE (t))
18264 	{
18265 	  tree folded = fold_non_dependent_expr (tmp, complain);
18266 	  bool inhibit = integer_nonzerop (folded);
18267 	  begin_else_clause (stmt);
18268 	  if (inhibit)
18269 	    ++c_inhibit_evaluation_warnings;
18270 	  RECUR (ELSE_CLAUSE (t));
18271 	  if (inhibit)
18272 	    --c_inhibit_evaluation_warnings;
18273 	  finish_else_clause (stmt);
18274 	}
18275 
18276       finish_if_stmt (stmt);
18277       break;
18278 
18279     case BIND_EXPR:
18280       if (BIND_EXPR_BODY_BLOCK (t))
18281 	stmt = begin_function_body ();
18282       else
18283 	stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
18284 				    ? BCS_TRY_BLOCK : 0);
18285 
18286       RECUR (BIND_EXPR_BODY (t));
18287 
18288       if (BIND_EXPR_BODY_BLOCK (t))
18289 	finish_function_body (stmt);
18290       else
18291 	finish_compound_stmt (stmt);
18292       break;
18293 
18294     case BREAK_STMT:
18295       finish_break_stmt ();
18296       break;
18297 
18298     case CONTINUE_STMT:
18299       finish_continue_stmt ();
18300       break;
18301 
18302     case SWITCH_STMT:
18303       stmt = begin_switch_stmt ();
18304       tmp = RECUR (SWITCH_STMT_COND (t));
18305       finish_switch_cond (tmp, stmt);
18306       RECUR (SWITCH_STMT_BODY (t));
18307       finish_switch_stmt (stmt);
18308       break;
18309 
18310     case CASE_LABEL_EXPR:
18311       {
18312 	tree decl = CASE_LABEL (t);
18313 	tree low = RECUR (CASE_LOW (t));
18314 	tree high = RECUR (CASE_HIGH (t));
18315 	tree l = finish_case_label (EXPR_LOCATION (t), low, high);
18316 	if (l && TREE_CODE (l) == CASE_LABEL_EXPR)
18317 	  {
18318 	    tree label = CASE_LABEL (l);
18319 	    FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
18320 	    if (DECL_ATTRIBUTES (decl) != NULL_TREE)
18321 	      cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
18322 	  }
18323       }
18324       break;
18325 
18326     case LABEL_EXPR:
18327       {
18328 	tree decl = LABEL_EXPR_LABEL (t);
18329 	tree label;
18330 
18331 	label = finish_label_stmt (DECL_NAME (decl));
18332 	if (TREE_CODE (label) == LABEL_DECL)
18333 	  FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
18334 	if (DECL_ATTRIBUTES (decl) != NULL_TREE)
18335 	  cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
18336       }
18337       break;
18338 
18339     case GOTO_EXPR:
18340       tmp = GOTO_DESTINATION (t);
18341       if (TREE_CODE (tmp) != LABEL_DECL)
18342 	/* Computed goto's must be tsubst'd into.  On the other hand,
18343 	   non-computed gotos must not be; the identifier in question
18344 	   will have no binding.  */
18345 	tmp = RECUR (tmp);
18346       else
18347 	tmp = DECL_NAME (tmp);
18348       finish_goto_stmt (tmp);
18349       break;
18350 
18351     case ASM_EXPR:
18352       {
18353 	tree string = RECUR (ASM_STRING (t));
18354 	tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
18355 						 complain, in_decl);
18356 	tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
18357 						complain, in_decl);
18358 	tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
18359 	 					  complain, in_decl);
18360 	tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
18361 						complain, in_decl);
18362 	tmp = finish_asm_stmt (EXPR_LOCATION (t), ASM_VOLATILE_P (t), string,
18363 			       outputs, inputs, clobbers, labels,
18364 			       ASM_INLINE_P (t));
18365 	tree asm_expr = tmp;
18366 	if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
18367 	  asm_expr = TREE_OPERAND (asm_expr, 0);
18368 	ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
18369       }
18370       break;
18371 
18372     case TRY_BLOCK:
18373       if (CLEANUP_P (t))
18374 	{
18375 	  stmt = begin_try_block ();
18376 	  RECUR (TRY_STMTS (t));
18377 	  finish_cleanup_try_block (stmt);
18378 	  finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
18379 	}
18380       else
18381 	{
18382 	  tree compound_stmt = NULL_TREE;
18383 
18384 	  if (FN_TRY_BLOCK_P (t))
18385 	    stmt = begin_function_try_block (&compound_stmt);
18386 	  else
18387 	    stmt = begin_try_block ();
18388 
18389 	  RECUR (TRY_STMTS (t));
18390 
18391 	  if (FN_TRY_BLOCK_P (t))
18392 	    finish_function_try_block (stmt);
18393 	  else
18394 	    finish_try_block (stmt);
18395 
18396 	  RECUR (TRY_HANDLERS (t));
18397 	  if (FN_TRY_BLOCK_P (t))
18398 	    finish_function_handler_sequence (stmt, compound_stmt);
18399 	  else
18400 	    finish_handler_sequence (stmt);
18401 	}
18402       break;
18403 
18404     case HANDLER:
18405       {
18406 	tree decl = HANDLER_PARMS (t);
18407 
18408 	if (decl)
18409 	  {
18410 	    decl = tsubst (decl, args, complain, in_decl);
18411 	    /* Prevent instantiate_decl from trying to instantiate
18412 	       this variable.  We've already done all that needs to be
18413 	       done.  */
18414 	    if (decl != error_mark_node)
18415 	      DECL_TEMPLATE_INSTANTIATED (decl) = 1;
18416 	  }
18417 	stmt = begin_handler ();
18418 	finish_handler_parms (decl, stmt);
18419 	RECUR (HANDLER_BODY (t));
18420 	finish_handler (stmt);
18421       }
18422       break;
18423 
18424     case TAG_DEFN:
18425       tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
18426       if (CLASS_TYPE_P (tmp))
18427 	{
18428 	  /* Local classes are not independent templates; they are
18429 	     instantiated along with their containing function.  And this
18430 	     way we don't have to deal with pushing out of one local class
18431 	     to instantiate a member of another local class.  */
18432 	  /* Closures are handled by the LAMBDA_EXPR.  */
18433 	  gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
18434 	  complete_type (tmp);
18435 	  for (tree fld = TYPE_FIELDS (tmp); fld; fld = DECL_CHAIN (fld))
18436 	    if ((VAR_P (fld)
18437 		 || (TREE_CODE (fld) == FUNCTION_DECL
18438 		     && !DECL_ARTIFICIAL (fld)))
18439 		&& DECL_TEMPLATE_INSTANTIATION (fld))
18440 	      instantiate_decl (fld, /*defer_ok=*/false,
18441 				/*expl_inst_class=*/false);
18442 	}
18443       break;
18444 
18445     case STATIC_ASSERT:
18446       {
18447 	tree condition;
18448 
18449 	++c_inhibit_evaluation_warnings;
18450         condition =
18451           tsubst_expr (STATIC_ASSERT_CONDITION (t),
18452                        args,
18453                        complain, in_decl,
18454                        /*integral_constant_expression_p=*/true);
18455 	--c_inhibit_evaluation_warnings;
18456 
18457         finish_static_assert (condition,
18458                               STATIC_ASSERT_MESSAGE (t),
18459                               STATIC_ASSERT_SOURCE_LOCATION (t),
18460                               /*member_p=*/false);
18461       }
18462       break;
18463 
18464     case OACC_KERNELS:
18465     case OACC_PARALLEL:
18466     case OACC_SERIAL:
18467       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_ACC, args, complain,
18468 				in_decl);
18469       stmt = begin_omp_parallel ();
18470       RECUR (OMP_BODY (t));
18471       finish_omp_construct (TREE_CODE (t), stmt, tmp);
18472       break;
18473 
18474     case OMP_PARALLEL:
18475       r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
18476       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), C_ORT_OMP, args,
18477 				complain, in_decl);
18478       if (OMP_PARALLEL_COMBINED (t))
18479 	omp_parallel_combined_clauses = &tmp;
18480       stmt = begin_omp_parallel ();
18481       RECUR (OMP_PARALLEL_BODY (t));
18482       gcc_assert (omp_parallel_combined_clauses == NULL);
18483       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
18484 	= OMP_PARALLEL_COMBINED (t);
18485       pop_omp_privatization_clauses (r);
18486       break;
18487 
18488     case OMP_TASK:
18489       if (OMP_TASK_BODY (t) == NULL_TREE)
18490 	{
18491 	  tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
18492 				    complain, in_decl);
18493 	  t = copy_node (t);
18494 	  OMP_TASK_CLAUSES (t) = tmp;
18495 	  add_stmt (t);
18496 	  break;
18497 	}
18498       r = push_omp_privatization_clauses (false);
18499       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
18500 				complain, in_decl);
18501       stmt = begin_omp_task ();
18502       RECUR (OMP_TASK_BODY (t));
18503       finish_omp_task (tmp, stmt);
18504       pop_omp_privatization_clauses (r);
18505       break;
18506 
18507     case OMP_FOR:
18508     case OMP_LOOP:
18509     case OMP_SIMD:
18510     case OMP_DISTRIBUTE:
18511     case OMP_TASKLOOP:
18512     case OACC_LOOP:
18513       {
18514 	tree clauses, body, pre_body;
18515 	tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
18516 	tree orig_declv = NULL_TREE;
18517 	tree incrv = NULL_TREE;
18518 	enum c_omp_region_type ort = C_ORT_OMP;
18519 	bool any_range_for = false;
18520 	int i;
18521 
18522 	if (TREE_CODE (t) == OACC_LOOP)
18523 	  ort = C_ORT_ACC;
18524 
18525 	r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
18526 	clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), ort, args, complain,
18527 				      in_decl);
18528 	if (OMP_FOR_INIT (t) != NULL_TREE)
18529 	  {
18530 	    declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18531 	    if (OMP_FOR_ORIG_DECLS (t))
18532 	      orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18533 	    initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18534 	    condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18535 	    incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18536 	  }
18537 
18538 	keep_next_level (true);
18539 	stmt = begin_omp_structured_block ();
18540 
18541 	pre_body = push_stmt_list ();
18542 	RECUR (OMP_FOR_PRE_BODY (t));
18543 	pre_body = pop_stmt_list (pre_body);
18544 
18545 	if (OMP_FOR_INIT (t) != NULL_TREE)
18546 	  for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
18547 	    any_range_for
18548 	      |= tsubst_omp_for_iterator (t, i, declv, orig_declv, initv,
18549 					  condv, incrv, &clauses, args,
18550 					  complain, in_decl,
18551 					  integral_constant_expression_p);
18552 	omp_parallel_combined_clauses = NULL;
18553 
18554 	if (any_range_for)
18555 	  {
18556 	    gcc_assert (orig_declv);
18557 	    body = begin_omp_structured_block ();
18558 	    for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
18559 	      if (TREE_VEC_ELT (orig_declv, i) != TREE_VEC_ELT (declv, i)
18560 		  && TREE_CODE (TREE_VEC_ELT (orig_declv, i)) == TREE_LIST
18561 		  && TREE_CHAIN (TREE_VEC_ELT (orig_declv, i)))
18562 		cp_finish_omp_range_for (TREE_VEC_ELT (orig_declv, i),
18563 					 TREE_VEC_ELT (declv, i));
18564 	  }
18565 	else
18566 	  body = push_stmt_list ();
18567 	RECUR (OMP_FOR_BODY (t));
18568 	if (any_range_for)
18569 	  body = finish_omp_structured_block (body);
18570 	else
18571 	  body = pop_stmt_list (body);
18572 
18573 	if (OMP_FOR_INIT (t) != NULL_TREE)
18574 	  t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
18575 			      orig_declv, initv, condv, incrv, body, pre_body,
18576 			      NULL, clauses);
18577 	else
18578 	  {
18579 	    t = make_node (TREE_CODE (t));
18580 	    TREE_TYPE (t) = void_type_node;
18581 	    OMP_FOR_BODY (t) = body;
18582 	    OMP_FOR_PRE_BODY (t) = pre_body;
18583 	    OMP_FOR_CLAUSES (t) = clauses;
18584 	    SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
18585 	    add_stmt (t);
18586 	  }
18587 
18588 	add_stmt (finish_omp_for_block (finish_omp_structured_block (stmt),
18589 					t));
18590 	pop_omp_privatization_clauses (r);
18591       }
18592       break;
18593 
18594     case OMP_SECTIONS:
18595       omp_parallel_combined_clauses = NULL;
18596       /* FALLTHRU */
18597     case OMP_SINGLE:
18598     case OMP_TEAMS:
18599     case OMP_CRITICAL:
18600     case OMP_TASKGROUP:
18601     case OMP_SCAN:
18602       r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
18603 					  && OMP_TEAMS_COMBINED (t));
18604       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_OMP, args, complain,
18605 				in_decl);
18606       if (TREE_CODE (t) == OMP_TEAMS)
18607 	{
18608 	  keep_next_level (true);
18609 	  stmt = begin_omp_structured_block ();
18610 	  RECUR (OMP_BODY (t));
18611 	  stmt = finish_omp_structured_block (stmt);
18612 	}
18613       else
18614 	{
18615 	  stmt = push_stmt_list ();
18616 	  RECUR (OMP_BODY (t));
18617 	  stmt = pop_stmt_list (stmt);
18618 	}
18619 
18620       t = copy_node (t);
18621       OMP_BODY (t) = stmt;
18622       OMP_CLAUSES (t) = tmp;
18623       add_stmt (t);
18624       pop_omp_privatization_clauses (r);
18625       break;
18626 
18627     case OMP_DEPOBJ:
18628       r = RECUR (OMP_DEPOBJ_DEPOBJ (t));
18629       if (OMP_DEPOBJ_CLAUSES (t) && OMP_DEPOBJ_CLAUSES (t) != error_mark_node)
18630 	{
18631 	  enum omp_clause_depend_kind kind = OMP_CLAUSE_DEPEND_SOURCE;
18632 	  if (TREE_CODE (OMP_DEPOBJ_CLAUSES (t)) == OMP_CLAUSE)
18633 	    {
18634 	      tmp = tsubst_omp_clauses (OMP_DEPOBJ_CLAUSES (t), C_ORT_OMP,
18635 					args, complain, in_decl);
18636 	      if (tmp == NULL_TREE)
18637 		tmp = error_mark_node;
18638 	    }
18639 	  else
18640 	    {
18641 	      kind = (enum omp_clause_depend_kind)
18642 		     tree_to_uhwi (OMP_DEPOBJ_CLAUSES (t));
18643 	      tmp = NULL_TREE;
18644 	    }
18645 	  finish_omp_depobj (EXPR_LOCATION (t), r, kind, tmp);
18646 	}
18647       else
18648 	finish_omp_depobj (EXPR_LOCATION (t), r,
18649 			   OMP_CLAUSE_DEPEND_SOURCE,
18650 			   OMP_DEPOBJ_CLAUSES (t));
18651       break;
18652 
18653     case OACC_DATA:
18654     case OMP_TARGET_DATA:
18655     case OMP_TARGET:
18656       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), (TREE_CODE (t) == OACC_DATA)
18657 				? C_ORT_ACC : C_ORT_OMP, args, complain,
18658 				in_decl);
18659       keep_next_level (true);
18660       stmt = begin_omp_structured_block ();
18661 
18662       RECUR (OMP_BODY (t));
18663       stmt = finish_omp_structured_block (stmt);
18664 
18665       t = copy_node (t);
18666       OMP_BODY (t) = stmt;
18667       OMP_CLAUSES (t) = tmp;
18668       if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
18669 	{
18670 	  tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
18671 	  if (teams)
18672 	    {
18673 	      /* For combined target teams, ensure the num_teams and
18674 		 thread_limit clause expressions are evaluated on the host,
18675 		 before entering the target construct.  */
18676 	      tree c;
18677 	      for (c = OMP_TEAMS_CLAUSES (teams);
18678 		   c; c = OMP_CLAUSE_CHAIN (c))
18679 		if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
18680 		     || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
18681 		    && TREE_CODE (OMP_CLAUSE_OPERAND (c, 0)) != INTEGER_CST)
18682 		  {
18683 		    tree expr = OMP_CLAUSE_OPERAND (c, 0);
18684 		    expr = force_target_expr (TREE_TYPE (expr), expr, tf_none);
18685 		    if (expr == error_mark_node)
18686 		      continue;
18687 		    tmp = TARGET_EXPR_SLOT (expr);
18688 		    add_stmt (expr);
18689 		    OMP_CLAUSE_OPERAND (c, 0) = expr;
18690 		    tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
18691 						OMP_CLAUSE_FIRSTPRIVATE);
18692 		    OMP_CLAUSE_DECL (tc) = tmp;
18693 		    OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
18694 		    OMP_TARGET_CLAUSES (t) = tc;
18695 		  }
18696 	    }
18697 	}
18698       add_stmt (t);
18699       break;
18700 
18701     case OACC_DECLARE:
18702       t = copy_node (t);
18703       tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), C_ORT_ACC, args,
18704 				complain, in_decl);
18705       OACC_DECLARE_CLAUSES (t) = tmp;
18706       add_stmt (t);
18707       break;
18708 
18709     case OMP_TARGET_UPDATE:
18710     case OMP_TARGET_ENTER_DATA:
18711     case OMP_TARGET_EXIT_DATA:
18712       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_OMP, args,
18713 				complain, in_decl);
18714       t = copy_node (t);
18715       OMP_STANDALONE_CLAUSES (t) = tmp;
18716       add_stmt (t);
18717       break;
18718 
18719     case OACC_CACHE:
18720     case OACC_ENTER_DATA:
18721     case OACC_EXIT_DATA:
18722     case OACC_UPDATE:
18723       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_ACC, args,
18724 				complain, in_decl);
18725       t = copy_node (t);
18726       OMP_STANDALONE_CLAUSES (t) = tmp;
18727       add_stmt (t);
18728       break;
18729 
18730     case OMP_ORDERED:
18731       tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), C_ORT_OMP, args,
18732 				complain, in_decl);
18733       stmt = push_stmt_list ();
18734       RECUR (OMP_BODY (t));
18735       stmt = pop_stmt_list (stmt);
18736 
18737       t = copy_node (t);
18738       OMP_BODY (t) = stmt;
18739       OMP_ORDERED_CLAUSES (t) = tmp;
18740       add_stmt (t);
18741       break;
18742 
18743     case OMP_MASTER:
18744       omp_parallel_combined_clauses = NULL;
18745       /* FALLTHRU */
18746     case OMP_SECTION:
18747       stmt = push_stmt_list ();
18748       RECUR (OMP_BODY (t));
18749       stmt = pop_stmt_list (stmt);
18750 
18751       t = copy_node (t);
18752       OMP_BODY (t) = stmt;
18753       add_stmt (t);
18754       break;
18755 
18756     case OMP_ATOMIC:
18757       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
18758       tmp = NULL_TREE;
18759       if (TREE_CODE (TREE_OPERAND (t, 0)) == OMP_CLAUSE)
18760 	tmp = tsubst_omp_clauses (TREE_OPERAND (t, 0), C_ORT_OMP, args,
18761 				  complain, in_decl);
18762       if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
18763 	{
18764 	  tree op1 = TREE_OPERAND (t, 1);
18765 	  tree rhs1 = NULL_TREE;
18766 	  tree lhs, rhs;
18767 	  if (TREE_CODE (op1) == COMPOUND_EXPR)
18768 	    {
18769 	      rhs1 = RECUR (TREE_OPERAND (op1, 0));
18770 	      op1 = TREE_OPERAND (op1, 1);
18771 	    }
18772 	  lhs = RECUR (TREE_OPERAND (op1, 0));
18773 	  rhs = RECUR (TREE_OPERAND (op1, 1));
18774 	  finish_omp_atomic (EXPR_LOCATION (t), OMP_ATOMIC, TREE_CODE (op1),
18775 			     lhs, rhs, NULL_TREE, NULL_TREE, rhs1, tmp,
18776 			     OMP_ATOMIC_MEMORY_ORDER (t));
18777 	}
18778       else
18779 	{
18780 	  tree op1 = TREE_OPERAND (t, 1);
18781 	  tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
18782 	  tree rhs1 = NULL_TREE;
18783 	  enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
18784 	  enum tree_code opcode = NOP_EXPR;
18785 	  if (code == OMP_ATOMIC_READ)
18786 	    {
18787 	      v = RECUR (TREE_OPERAND (op1, 0));
18788 	      lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
18789 	    }
18790 	  else if (code == OMP_ATOMIC_CAPTURE_OLD
18791 		   || code == OMP_ATOMIC_CAPTURE_NEW)
18792 	    {
18793 	      tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
18794 	      v = RECUR (TREE_OPERAND (op1, 0));
18795 	      lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
18796 	      if (TREE_CODE (op11) == COMPOUND_EXPR)
18797 		{
18798 		  rhs1 = RECUR (TREE_OPERAND (op11, 0));
18799 		  op11 = TREE_OPERAND (op11, 1);
18800 		}
18801 	      lhs = RECUR (TREE_OPERAND (op11, 0));
18802 	      rhs = RECUR (TREE_OPERAND (op11, 1));
18803 	      opcode = TREE_CODE (op11);
18804 	      if (opcode == MODIFY_EXPR)
18805 		opcode = NOP_EXPR;
18806 	    }
18807 	  else
18808 	    {
18809 	      code = OMP_ATOMIC;
18810 	      lhs = RECUR (TREE_OPERAND (op1, 0));
18811 	      rhs = RECUR (TREE_OPERAND (op1, 1));
18812 	    }
18813 	  finish_omp_atomic (EXPR_LOCATION (t), code, opcode, lhs, rhs, v,
18814 			     lhs1, rhs1, tmp, OMP_ATOMIC_MEMORY_ORDER (t));
18815 	}
18816       break;
18817 
18818     case TRANSACTION_EXPR:
18819       {
18820 	int flags = 0;
18821 	flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
18822 	flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
18823 
18824         if (TRANSACTION_EXPR_IS_STMT (t))
18825           {
18826 	    tree body = TRANSACTION_EXPR_BODY (t);
18827 	    tree noex = NULL_TREE;
18828 	    if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
18829 	      {
18830 		noex = MUST_NOT_THROW_COND (body);
18831 		if (noex == NULL_TREE)
18832 		  noex = boolean_true_node;
18833 		body = TREE_OPERAND (body, 0);
18834 	      }
18835             stmt = begin_transaction_stmt (input_location, NULL, flags);
18836             RECUR (body);
18837             finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
18838           }
18839         else
18840           {
18841             stmt = build_transaction_expr (EXPR_LOCATION (t),
18842 					   RECUR (TRANSACTION_EXPR_BODY (t)),
18843 					   flags, NULL_TREE);
18844             RETURN (stmt);
18845           }
18846       }
18847       break;
18848 
18849     case MUST_NOT_THROW_EXPR:
18850       {
18851 	tree op0 = RECUR (TREE_OPERAND (t, 0));
18852 	tree cond = RECUR (MUST_NOT_THROW_COND (t));
18853 	RETURN (build_must_not_throw_expr (op0, cond));
18854       }
18855 
18856     case EXPR_PACK_EXPANSION:
18857       error ("invalid use of pack expansion expression");
18858       RETURN (error_mark_node);
18859 
18860     case NONTYPE_ARGUMENT_PACK:
18861       error ("use %<...%> to expand argument pack");
18862       RETURN (error_mark_node);
18863 
18864     case COMPOUND_EXPR:
18865       tmp = RECUR (TREE_OPERAND (t, 0));
18866       if (tmp == NULL_TREE)
18867 	/* If the first operand was a statement, we're done with it.  */
18868 	RETURN (RECUR (TREE_OPERAND (t, 1)));
18869       RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
18870 				    RECUR (TREE_OPERAND (t, 1)),
18871 				    complain));
18872 
18873     case ANNOTATE_EXPR:
18874       tmp = RECUR (TREE_OPERAND (t, 0));
18875       RETURN (build3_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
18876 			  TREE_TYPE (tmp), tmp,
18877 			  RECUR (TREE_OPERAND (t, 1)),
18878 			  RECUR (TREE_OPERAND (t, 2))));
18879 
18880     case PREDICT_EXPR:
18881       RETURN (add_stmt (copy_node (t)));
18882 
18883     default:
18884       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
18885 
18886       RETURN (tsubst_copy_and_build (t, args, complain, in_decl,
18887 				    /*function_p=*/false,
18888 				    integral_constant_expression_p));
18889     }
18890 
18891   RETURN (NULL_TREE);
18892  out:
18893   input_location = loc;
18894   return r;
18895 #undef RECUR
18896 #undef RETURN
18897 }
18898 
18899 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
18900    function.  For description of the body see comment above
18901    cp_parser_omp_declare_reduction_exprs.  */
18902 
18903 static void
tsubst_omp_udr(tree t,tree args,tsubst_flags_t complain,tree in_decl)18904 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
18905 {
18906   if (t == NULL_TREE || t == error_mark_node)
18907     return;
18908 
18909   gcc_assert (TREE_CODE (t) == STATEMENT_LIST);
18910 
18911   tree_stmt_iterator tsi;
18912   int i;
18913   tree stmts[7];
18914   memset (stmts, 0, sizeof stmts);
18915   for (i = 0, tsi = tsi_start (t);
18916        i < 7 && !tsi_end_p (tsi);
18917        i++, tsi_next (&tsi))
18918     stmts[i] = tsi_stmt (tsi);
18919   gcc_assert (tsi_end_p (tsi));
18920 
18921   if (i >= 3)
18922     {
18923       gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
18924 		  && TREE_CODE (stmts[1]) == DECL_EXPR);
18925       tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
18926 			     args, complain, in_decl);
18927       tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
18928 			    args, complain, in_decl);
18929       DECL_CONTEXT (omp_out) = current_function_decl;
18930       DECL_CONTEXT (omp_in) = current_function_decl;
18931       keep_next_level (true);
18932       tree block = begin_omp_structured_block ();
18933       tsubst_expr (stmts[2], args, complain, in_decl, false);
18934       block = finish_omp_structured_block (block);
18935       block = maybe_cleanup_point_expr_void (block);
18936       add_decl_expr (omp_out);
18937       if (TREE_NO_WARNING (DECL_EXPR_DECL (stmts[0])))
18938 	TREE_NO_WARNING (omp_out) = 1;
18939       add_decl_expr (omp_in);
18940       finish_expr_stmt (block);
18941     }
18942   if (i >= 6)
18943     {
18944       gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
18945 		  && TREE_CODE (stmts[4]) == DECL_EXPR);
18946       tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
18947 			      args, complain, in_decl);
18948       tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
18949 			      args, complain, in_decl);
18950       DECL_CONTEXT (omp_priv) = current_function_decl;
18951       DECL_CONTEXT (omp_orig) = current_function_decl;
18952       keep_next_level (true);
18953       tree block = begin_omp_structured_block ();
18954       tsubst_expr (stmts[5], args, complain, in_decl, false);
18955       block = finish_omp_structured_block (block);
18956       block = maybe_cleanup_point_expr_void (block);
18957       cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
18958       add_decl_expr (omp_priv);
18959       add_decl_expr (omp_orig);
18960       finish_expr_stmt (block);
18961       if (i == 7)
18962 	add_decl_expr (omp_orig);
18963     }
18964 }
18965 
18966 /* T is a postfix-expression that is not being used in a function
18967    call.  Return the substituted version of T.  */
18968 
18969 static tree
tsubst_non_call_postfix_expression(tree t,tree args,tsubst_flags_t complain,tree in_decl)18970 tsubst_non_call_postfix_expression (tree t, tree args,
18971 				    tsubst_flags_t complain,
18972 				    tree in_decl)
18973 {
18974   if (TREE_CODE (t) == SCOPE_REF)
18975     t = tsubst_qualified_id (t, args, complain, in_decl,
18976 			     /*done=*/false, /*address_p=*/false);
18977   else
18978     t = tsubst_copy_and_build (t, args, complain, in_decl,
18979 			       /*function_p=*/false,
18980 			       /*integral_constant_expression_p=*/false);
18981 
18982   return t;
18983 }
18984 
18985 /* Subroutine of tsubst_lambda_expr: add the FIELD/INIT capture pair to the
18986    LAMBDA_EXPR_CAPTURE_LIST passed in LIST.  Do deduction for a previously
18987    dependent init-capture.  */
18988 
18989 static void
prepend_one_capture(tree field,tree init,tree & list,tsubst_flags_t complain)18990 prepend_one_capture (tree field, tree init, tree &list,
18991 		     tsubst_flags_t complain)
18992 {
18993   if (tree auto_node = type_uses_auto (TREE_TYPE (field)))
18994     {
18995       tree type = NULL_TREE;
18996       if (!init)
18997 	{
18998 	  if (complain & tf_error)
18999 	    error ("empty initializer in lambda init-capture");
19000 	  init = error_mark_node;
19001 	}
19002       else if (TREE_CODE (init) == TREE_LIST)
19003 	init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19004       if (!type)
19005 	type = do_auto_deduction (TREE_TYPE (field), init, auto_node, complain);
19006       TREE_TYPE (field) = type;
19007       cp_apply_type_quals_to_decl (cp_type_quals (type), field);
19008     }
19009   list = tree_cons (field, init, list);
19010 }
19011 
19012 /* T is a LAMBDA_EXPR.  Generate a new LAMBDA_EXPR for the current
19013    instantiation context.  Instantiating a pack expansion containing a lambda
19014    might result in multiple lambdas all based on the same lambda in the
19015    template.  */
19016 
19017 tree
tsubst_lambda_expr(tree t,tree args,tsubst_flags_t complain,tree in_decl)19018 tsubst_lambda_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19019 {
19020   tree oldfn = lambda_function (t);
19021   in_decl = oldfn;
19022 
19023   tree r = build_lambda_expr ();
19024 
19025   LAMBDA_EXPR_LOCATION (r)
19026     = LAMBDA_EXPR_LOCATION (t);
19027   LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
19028     = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
19029   LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
19030   LAMBDA_EXPR_INSTANTIATED (r) = true;
19031 
19032   if (LAMBDA_EXPR_EXTRA_SCOPE (t) == NULL_TREE)
19033     /* A lambda in a default argument outside a class gets no
19034        LAMBDA_EXPR_EXTRA_SCOPE, as specified by the ABI.  But
19035        tsubst_default_argument calls start_lambda_scope, so we need to
19036        specifically ignore it here, and use the global scope.  */
19037     record_null_lambda_scope (r);
19038   else
19039     record_lambda_scope (r);
19040 
19041   gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
19042 	      && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
19043 
19044   vec<tree,va_gc>* field_packs = NULL;
19045 
19046   for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t); cap;
19047        cap = TREE_CHAIN (cap))
19048     {
19049       tree ofield = TREE_PURPOSE (cap);
19050       tree init = TREE_VALUE (cap);
19051       if (PACK_EXPANSION_P (init))
19052 	init = tsubst_pack_expansion (init, args, complain, in_decl);
19053       else
19054 	init = tsubst_copy_and_build (init, args, complain, in_decl,
19055 				      /*fn*/false, /*constexpr*/false);
19056 
19057       if (init == error_mark_node)
19058 	return error_mark_node;
19059 
19060       if (init && TREE_CODE (init) == TREE_LIST)
19061 	init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19062 
19063       if (!processing_template_decl
19064 	  && init && TREE_CODE (init) != TREE_VEC
19065 	  && variably_modified_type_p (TREE_TYPE (init), NULL_TREE))
19066 	{
19067 	  /* For a VLA, simply tsubsting the field type won't work, we need to
19068 	     go through add_capture again.  XXX do we want to do this for all
19069 	     captures?  */
19070 	  tree name = (get_identifier
19071 		       (IDENTIFIER_POINTER (DECL_NAME (ofield)) + 2));
19072 	  tree ftype = TREE_TYPE (ofield);
19073 	  bool by_ref = (TYPE_REF_P (ftype)
19074 			 || (TREE_CODE (ftype) == DECLTYPE_TYPE
19075 			     && DECLTYPE_FOR_REF_CAPTURE (ftype)));
19076 	  add_capture (r, name, init, by_ref, !DECL_NORMAL_CAPTURE_P (ofield));
19077 	  continue;
19078 	}
19079 
19080       if (PACK_EXPANSION_P (ofield))
19081 	ofield = PACK_EXPANSION_PATTERN (ofield);
19082       tree field = tsubst_decl (ofield, args, complain);
19083 
19084       if (DECL_PACK_P (ofield) && !DECL_NORMAL_CAPTURE_P (ofield))
19085 	{
19086 	  /* Remember these for when we've pushed local_specializations.  */
19087 	  vec_safe_push (field_packs, ofield);
19088 	  vec_safe_push (field_packs, field);
19089 	}
19090 
19091       if (field == error_mark_node)
19092 	return error_mark_node;
19093 
19094       if (TREE_CODE (field) == TREE_VEC)
19095 	{
19096 	  int len = TREE_VEC_LENGTH (field);
19097 	  gcc_assert (TREE_CODE (init) == TREE_VEC
19098 		      && TREE_VEC_LENGTH (init) == len);
19099 	  for (int i = 0; i < len; ++i)
19100 	    prepend_one_capture (TREE_VEC_ELT (field, i),
19101 				 TREE_VEC_ELT (init, i),
19102 				 LAMBDA_EXPR_CAPTURE_LIST (r),
19103 				 complain);
19104 	}
19105       else
19106 	{
19107 	  prepend_one_capture (field, init, LAMBDA_EXPR_CAPTURE_LIST (r),
19108 			       complain);
19109 
19110 	  if (id_equal (DECL_NAME (field), "__this"))
19111 	    LAMBDA_EXPR_THIS_CAPTURE (r) = field;
19112 	}
19113     }
19114 
19115   tree type = begin_lambda_type (r);
19116   if (type == error_mark_node)
19117     return error_mark_node;
19118 
19119   /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
19120   determine_visibility (TYPE_NAME (type));
19121 
19122   register_capture_members (LAMBDA_EXPR_CAPTURE_LIST (r));
19123 
19124   tree oldtmpl = (generic_lambda_fn_p (oldfn)
19125 		  ? DECL_TI_TEMPLATE (oldfn)
19126 		  : NULL_TREE);
19127 
19128   tree fntype = static_fn_type (oldfn);
19129   if (oldtmpl)
19130     ++processing_template_decl;
19131   fntype = tsubst (fntype, args, complain, in_decl);
19132   if (oldtmpl)
19133     --processing_template_decl;
19134 
19135   if (fntype == error_mark_node)
19136     r = error_mark_node;
19137   else
19138     {
19139       /* The body of a lambda-expression is not a subexpression of the
19140 	 enclosing expression.  Parms are to have DECL_CHAIN tsubsted,
19141 	 which would be skipped if cp_unevaluated_operand.  */
19142       cp_evaluated ev;
19143 
19144       /* Fix the type of 'this'.  */
19145       fntype = build_memfn_type (fntype, type,
19146 				 type_memfn_quals (fntype),
19147 				 type_memfn_rqual (fntype));
19148       tree fn, tmpl;
19149       if (oldtmpl)
19150 	{
19151 	  tmpl = tsubst_template_decl (oldtmpl, args, complain, fntype);
19152 	  if (tmpl == error_mark_node)
19153 	    {
19154 	      r = error_mark_node;
19155 	      goto out;
19156 	    }
19157 	  fn = DECL_TEMPLATE_RESULT (tmpl);
19158 	  finish_member_declaration (tmpl);
19159 	}
19160       else
19161 	{
19162 	  tmpl = NULL_TREE;
19163 	  fn = tsubst_function_decl (oldfn, args, complain, fntype);
19164 	  if (fn == error_mark_node)
19165 	    {
19166 	      r = error_mark_node;
19167 	      goto out;
19168 	    }
19169 	  finish_member_declaration (fn);
19170 	}
19171 
19172       if (tree ci = get_constraints (oldfn))
19173 	{
19174 	  /* Substitute into the lambda's constraints.  */
19175 	  if (oldtmpl)
19176 	    ++processing_template_decl;
19177 	  ci = tsubst_constraint_info (ci, args, complain, in_decl);
19178 	  if (oldtmpl)
19179 	    --processing_template_decl;
19180 	  set_constraints (fn, ci);
19181 	}
19182 
19183       /* Let finish_function set this.  */
19184       DECL_DECLARED_CONSTEXPR_P (fn) = false;
19185 
19186       bool nested = cfun;
19187       if (nested)
19188 	push_function_context ();
19189       else
19190 	/* Still increment function_depth so that we don't GC in the
19191 	   middle of an expression.  */
19192 	++function_depth;
19193 
19194       local_specialization_stack s (lss_copy);
19195 
19196       tree body = start_lambda_function (fn, r);
19197 
19198       /* Now record them for lookup_init_capture_pack.  */
19199       int fplen = vec_safe_length (field_packs);
19200       for (int i = 0; i < fplen; )
19201 	{
19202 	  tree pack = (*field_packs)[i++];
19203 	  tree inst = (*field_packs)[i++];
19204 	  register_local_specialization (inst, pack);
19205 	}
19206       release_tree_vector (field_packs);
19207 
19208       register_parameter_specializations (oldfn, fn);
19209 
19210       if (oldtmpl)
19211 	{
19212 	  /* We might not partially instantiate some parts of the function, so
19213 	     copy these flags from the original template.  */
19214 	  language_function *ol = DECL_STRUCT_FUNCTION (oldfn)->language;
19215 	  current_function_returns_value = ol->returns_value;
19216 	  current_function_returns_null = ol->returns_null;
19217 	  current_function_returns_abnormally = ol->returns_abnormally;
19218 	  current_function_infinite_loop = ol->infinite_loop;
19219 	}
19220 
19221       /* [temp.deduct] A lambda-expression appearing in a function type or a
19222 	 template parameter is not considered part of the immediate context for
19223 	 the purposes of template argument deduction. */
19224       complain = tf_warning_or_error;
19225 
19226       tsubst_expr (DECL_SAVED_TREE (oldfn), args, complain, r,
19227 		   /*constexpr*/false);
19228 
19229       finish_lambda_function (body);
19230 
19231       if (nested)
19232 	pop_function_context ();
19233       else
19234 	--function_depth;
19235 
19236       /* The capture list was built up in reverse order; fix that now.  */
19237       LAMBDA_EXPR_CAPTURE_LIST (r)
19238 	= nreverse (LAMBDA_EXPR_CAPTURE_LIST (r));
19239 
19240       LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
19241 
19242       maybe_add_lambda_conv_op (type);
19243     }
19244 
19245 out:
19246   finish_struct (type, /*attr*/NULL_TREE);
19247 
19248   insert_pending_capture_proxies ();
19249 
19250   return r;
19251 }
19252 
19253 /* Like tsubst but deals with expressions and performs semantic
19254    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)" or
19255    "F<TARGS> (ARGS)".  */
19256 
19257 tree
tsubst_copy_and_build(tree t,tree args,tsubst_flags_t complain,tree in_decl,bool function_p,bool integral_constant_expression_p)19258 tsubst_copy_and_build (tree t,
19259 		       tree args,
19260 		       tsubst_flags_t complain,
19261 		       tree in_decl,
19262 		       bool function_p,
19263 		       bool integral_constant_expression_p)
19264 {
19265 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
19266 #define RECUR(NODE)						\
19267   tsubst_copy_and_build (NODE, args, complain, in_decl, 	\
19268 			 /*function_p=*/false,			\
19269 			 integral_constant_expression_p)
19270 
19271   tree retval, op1;
19272   location_t save_loc;
19273 
19274   if (t == NULL_TREE || t == error_mark_node)
19275     return t;
19276 
19277   save_loc = input_location;
19278   if (location_t eloc = cp_expr_location (t))
19279     input_location = eloc;
19280 
19281   /* N3276 decltype magic only applies to calls at the top level or on the
19282      right side of a comma.  */
19283   tsubst_flags_t decltype_flag = (complain & tf_decltype);
19284   complain &= ~tf_decltype;
19285 
19286   switch (TREE_CODE (t))
19287     {
19288     case USING_DECL:
19289       t = DECL_NAME (t);
19290       /* Fall through.  */
19291     case IDENTIFIER_NODE:
19292       {
19293 	tree decl;
19294 	cp_id_kind idk;
19295 	bool non_integral_constant_expression_p;
19296 	const char *error_msg;
19297 
19298 	if (IDENTIFIER_CONV_OP_P (t))
19299 	  {
19300 	    tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19301 	    t = make_conv_op_name (new_type);
19302 	  }
19303 
19304 	/* Look up the name.  */
19305 	decl = lookup_name (t);
19306 
19307 	/* By convention, expressions use ERROR_MARK_NODE to indicate
19308 	   failure, not NULL_TREE.  */
19309 	if (decl == NULL_TREE)
19310 	  decl = error_mark_node;
19311 
19312 	decl = finish_id_expression (t, decl, NULL_TREE,
19313 				     &idk,
19314 				     integral_constant_expression_p,
19315           /*allow_non_integral_constant_expression_p=*/(cxx_dialect >= cxx11),
19316 				     &non_integral_constant_expression_p,
19317 				     /*template_p=*/false,
19318 				     /*done=*/true,
19319 				     /*address_p=*/false,
19320 				     /*template_arg_p=*/false,
19321 				     &error_msg,
19322 				     input_location);
19323 	if (error_msg)
19324 	  error (error_msg);
19325 	if (!function_p && identifier_p (decl))
19326 	  {
19327 	    if (complain & tf_error)
19328 	      unqualified_name_lookup_error (decl);
19329 	    decl = error_mark_node;
19330 	  }
19331 	RETURN (decl);
19332       }
19333 
19334     case TEMPLATE_ID_EXPR:
19335       {
19336 	tree object;
19337 	tree templ = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
19338 					    complain, in_decl,
19339 					    function_p,
19340 					    integral_constant_expression_p);
19341 	tree targs = TREE_OPERAND (t, 1);
19342 
19343 	if (targs)
19344 	  targs = tsubst_template_args (targs, args, complain, in_decl);
19345 	if (targs == error_mark_node)
19346 	  RETURN (error_mark_node);
19347 
19348 	if (TREE_CODE (templ) == SCOPE_REF)
19349 	  {
19350 	    tree name = TREE_OPERAND (templ, 1);
19351 	    tree tid = lookup_template_function (name, targs);
19352 	    TREE_OPERAND (templ, 1) = tid;
19353 	    RETURN (templ);
19354 	  }
19355 
19356 	if (concept_definition_p (templ))
19357 	  {
19358 	    tree check = build_concept_check (templ, targs, complain);
19359 	    if (check == error_mark_node)
19360 	      RETURN (error_mark_node);
19361 
19362 	    tree id = unpack_concept_check (check);
19363 
19364 	    /* If we built a function concept check, return the underlying
19365 	       template-id. So we can evaluate it as a function call.  */
19366 	    if (function_concept_p (TREE_OPERAND (id, 0)))
19367 	      RETURN (id);
19368 
19369 	    RETURN (check);
19370 	  }
19371 
19372 	if (variable_template_p (templ))
19373 	  {
19374 	    tree r = lookup_and_finish_template_variable (templ, targs,
19375 							  complain);
19376 	    r = maybe_wrap_with_location (r, EXPR_LOCATION (t));
19377 	    RETURN (r);
19378 	  }
19379 
19380 	if (TREE_CODE (templ) == COMPONENT_REF)
19381 	  {
19382 	    object = TREE_OPERAND (templ, 0);
19383 	    templ = TREE_OPERAND (templ, 1);
19384 	  }
19385 	else
19386 	  object = NULL_TREE;
19387 
19388 	tree tid = lookup_template_function (templ, targs);
19389 
19390 	if (object)
19391 	  RETURN (build3 (COMPONENT_REF, TREE_TYPE (tid),
19392 			 object, tid, NULL_TREE));
19393 	else if (identifier_p (templ))
19394 	  {
19395 	    /* C++20 P0846: we can encounter an IDENTIFIER_NODE here when
19396 	       name lookup found nothing when parsing the template name.  */
19397 	    gcc_assert (cxx_dialect >= cxx2a || seen_error ());
19398 	    RETURN (tid);
19399 	  }
19400 	else
19401 	  RETURN (baselink_for_fns (tid));
19402       }
19403 
19404     case INDIRECT_REF:
19405       {
19406 	tree r = RECUR (TREE_OPERAND (t, 0));
19407 
19408 	if (REFERENCE_REF_P (t))
19409 	  {
19410 	    /* A type conversion to reference type will be enclosed in
19411 	       such an indirect ref, but the substitution of the cast
19412 	       will have also added such an indirect ref.  */
19413 	    r = convert_from_reference (r);
19414 	  }
19415 	else
19416 	  r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
19417 				    complain|decltype_flag);
19418 
19419 	if (REF_PARENTHESIZED_P (t))
19420 	  r = force_paren_expr (r);
19421 
19422 	RETURN (r);
19423       }
19424 
19425     case NOP_EXPR:
19426       {
19427 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19428 	tree op0 = RECUR (TREE_OPERAND (t, 0));
19429 	RETURN (build_nop (type, op0));
19430       }
19431 
19432     case IMPLICIT_CONV_EXPR:
19433       {
19434 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19435 	tree expr = RECUR (TREE_OPERAND (t, 0));
19436 	if (dependent_type_p (type) || type_dependent_expression_p (expr))
19437 	  {
19438 	    retval = copy_node (t);
19439 	    TREE_TYPE (retval) = type;
19440 	    TREE_OPERAND (retval, 0) = expr;
19441 	    RETURN (retval);
19442 	  }
19443 	if (IMPLICIT_CONV_EXPR_NONTYPE_ARG (t))
19444 	  /* We'll pass this to convert_nontype_argument again, we don't need
19445 	     to actually perform any conversion here.  */
19446 	  RETURN (expr);
19447 	int flags = LOOKUP_IMPLICIT;
19448 	if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
19449 	  flags = LOOKUP_NORMAL;
19450 	if (IMPLICIT_CONV_EXPR_BRACED_INIT (t))
19451 	  flags |= LOOKUP_NO_NARROWING;
19452 	RETURN (perform_implicit_conversion_flags (type, expr, complain,
19453 						  flags));
19454       }
19455 
19456     case CONVERT_EXPR:
19457       {
19458 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19459 	tree op0 = RECUR (TREE_OPERAND (t, 0));
19460 	if (op0 == error_mark_node)
19461 	  RETURN (error_mark_node);
19462 	RETURN (build1 (CONVERT_EXPR, type, op0));
19463       }
19464 
19465     case CAST_EXPR:
19466     case REINTERPRET_CAST_EXPR:
19467     case CONST_CAST_EXPR:
19468     case DYNAMIC_CAST_EXPR:
19469     case STATIC_CAST_EXPR:
19470       {
19471 	tree type;
19472 	tree op, r = NULL_TREE;
19473 
19474 	type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19475 	if (integral_constant_expression_p
19476 	    && !cast_valid_in_integral_constant_expression_p (type))
19477 	  {
19478             if (complain & tf_error)
19479               error ("a cast to a type other than an integral or "
19480                      "enumeration type cannot appear in a constant-expression");
19481 	    RETURN (error_mark_node);
19482 	  }
19483 
19484 	op = RECUR (TREE_OPERAND (t, 0));
19485 
19486 	warning_sentinel s(warn_useless_cast);
19487 	warning_sentinel s2(warn_ignored_qualifiers);
19488 	switch (TREE_CODE (t))
19489 	  {
19490 	  case CAST_EXPR:
19491 	    r = build_functional_cast (input_location, type, op, complain);
19492 	    break;
19493 	  case REINTERPRET_CAST_EXPR:
19494 	    r = build_reinterpret_cast (input_location, type, op, complain);
19495 	    break;
19496 	  case CONST_CAST_EXPR:
19497 	    r = build_const_cast (input_location, type, op, complain);
19498 	    break;
19499 	  case DYNAMIC_CAST_EXPR:
19500 	    r = build_dynamic_cast (input_location, type, op, complain);
19501 	    break;
19502 	  case STATIC_CAST_EXPR:
19503 	    r = build_static_cast (input_location, type, op, complain);
19504 	    break;
19505 	  default:
19506 	    gcc_unreachable ();
19507 	  }
19508 
19509 	RETURN (r);
19510       }
19511 
19512     case POSTDECREMENT_EXPR:
19513     case POSTINCREMENT_EXPR:
19514       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
19515 						args, complain, in_decl);
19516       RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
19517 				complain|decltype_flag));
19518 
19519     case PREDECREMENT_EXPR:
19520     case PREINCREMENT_EXPR:
19521     case NEGATE_EXPR:
19522     case BIT_NOT_EXPR:
19523     case ABS_EXPR:
19524     case TRUTH_NOT_EXPR:
19525     case UNARY_PLUS_EXPR:  /* Unary + */
19526     case REALPART_EXPR:
19527     case IMAGPART_EXPR:
19528       RETURN (build_x_unary_op (input_location, TREE_CODE (t),
19529 				RECUR (TREE_OPERAND (t, 0)),
19530 				complain|decltype_flag));
19531 
19532     case FIX_TRUNC_EXPR:
19533       gcc_unreachable ();
19534 
19535     case ADDR_EXPR:
19536       op1 = TREE_OPERAND (t, 0);
19537       if (TREE_CODE (op1) == LABEL_DECL)
19538 	RETURN (finish_label_address_expr (DECL_NAME (op1),
19539 					  EXPR_LOCATION (op1)));
19540       if (TREE_CODE (op1) == SCOPE_REF)
19541 	op1 = tsubst_qualified_id (op1, args, complain, in_decl,
19542 				   /*done=*/true, /*address_p=*/true);
19543       else
19544 	op1 = tsubst_non_call_postfix_expression (op1, args, complain,
19545 						  in_decl);
19546       RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
19547 				complain|decltype_flag));
19548 
19549     case PLUS_EXPR:
19550     case MINUS_EXPR:
19551     case MULT_EXPR:
19552     case TRUNC_DIV_EXPR:
19553     case CEIL_DIV_EXPR:
19554     case FLOOR_DIV_EXPR:
19555     case ROUND_DIV_EXPR:
19556     case EXACT_DIV_EXPR:
19557     case BIT_AND_EXPR:
19558     case BIT_IOR_EXPR:
19559     case BIT_XOR_EXPR:
19560     case TRUNC_MOD_EXPR:
19561     case FLOOR_MOD_EXPR:
19562     case TRUTH_ANDIF_EXPR:
19563     case TRUTH_ORIF_EXPR:
19564     case TRUTH_AND_EXPR:
19565     case TRUTH_OR_EXPR:
19566     case RSHIFT_EXPR:
19567     case LSHIFT_EXPR:
19568     case EQ_EXPR:
19569     case NE_EXPR:
19570     case MAX_EXPR:
19571     case MIN_EXPR:
19572     case LE_EXPR:
19573     case GE_EXPR:
19574     case LT_EXPR:
19575     case GT_EXPR:
19576     case SPACESHIP_EXPR:
19577     case MEMBER_REF:
19578     case DOTSTAR_EXPR:
19579       {
19580 	/* If T was type-dependent, suppress warnings that depend on the range
19581 	   of the types involved.  */
19582 	++processing_template_decl;
19583 	const bool was_dep = (potential_constant_expression (t)
19584 			      ? value_dependent_expression_p (t)
19585 			      : type_dependent_expression_p (t));
19586 	--processing_template_decl;
19587 	tree op0 = RECUR (TREE_OPERAND (t, 0));
19588 	tree op1 = RECUR (TREE_OPERAND (t, 1));
19589 
19590 	warning_sentinel s1(warn_type_limits, was_dep);
19591 	warning_sentinel s2(warn_div_by_zero, was_dep);
19592 	warning_sentinel s3(warn_logical_op, was_dep);
19593 	warning_sentinel s4(warn_tautological_compare, was_dep);
19594 
19595 	tree r = build_x_binary_op
19596 	  (input_location, TREE_CODE (t),
19597 	   op0,
19598 	   (TREE_NO_WARNING (TREE_OPERAND (t, 0))
19599 	    ? ERROR_MARK
19600 	    : TREE_CODE (TREE_OPERAND (t, 0))),
19601 	   op1,
19602 	   (TREE_NO_WARNING (TREE_OPERAND (t, 1))
19603 	    ? ERROR_MARK
19604 	    : TREE_CODE (TREE_OPERAND (t, 1))),
19605 	   /*overload=*/NULL,
19606 	   complain|decltype_flag);
19607 	if (EXPR_P (r) && TREE_NO_WARNING (t))
19608 	  TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
19609 
19610 	RETURN (r);
19611       }
19612 
19613     case POINTER_PLUS_EXPR:
19614       {
19615 	tree op0 = RECUR (TREE_OPERAND (t, 0));
19616 	if (op0 == error_mark_node)
19617 	  RETURN (error_mark_node);
19618 	tree op1 = RECUR (TREE_OPERAND (t, 1));
19619 	if (op1 == error_mark_node)
19620 	  RETURN (error_mark_node);
19621 	RETURN (fold_build_pointer_plus (op0, op1));
19622       }
19623 
19624     case SCOPE_REF:
19625       RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
19626 				  /*address_p=*/false));
19627 
19628     case BASELINK:
19629       RETURN (tsubst_baselink (t, current_nonlambda_class_type (),
19630 			       args, complain, in_decl));
19631 
19632     case ARRAY_REF:
19633       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
19634 						args, complain, in_decl);
19635       RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
19636 				 RECUR (TREE_OPERAND (t, 1)),
19637 				 complain|decltype_flag));
19638 
19639     case SIZEOF_EXPR:
19640       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
19641 	  || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
19642 	RETURN (tsubst_copy (t, args, complain, in_decl));
19643       /* Fall through */
19644 
19645     case ALIGNOF_EXPR:
19646       {
19647 	tree r;
19648 
19649 	op1 = TREE_OPERAND (t, 0);
19650 	if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
19651 	  op1 = TREE_TYPE (op1);
19652 	bool std_alignof = (TREE_CODE (t) == ALIGNOF_EXPR
19653 			    && ALIGNOF_EXPR_STD_P (t));
19654         if (!args)
19655 	  {
19656 	    /* When there are no ARGS, we are trying to evaluate a
19657 	       non-dependent expression from the parser.  Trying to do
19658 	       the substitutions may not work.  */
19659 	    if (!TYPE_P (op1))
19660 	      op1 = TREE_TYPE (op1);
19661 	  }
19662 	else
19663 	  {
19664 	    ++cp_unevaluated_operand;
19665 	    ++c_inhibit_evaluation_warnings;
19666 	    if (TYPE_P (op1))
19667 	      op1 = tsubst (op1, args, complain, in_decl);
19668 	    else
19669 	      op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
19670 					   /*function_p=*/false,
19671 					   /*integral_constant_expression_p=*/
19672 					   false);
19673 	    --cp_unevaluated_operand;
19674 	    --c_inhibit_evaluation_warnings;
19675 	  }
19676         if (TYPE_P (op1))
19677 	  r = cxx_sizeof_or_alignof_type (input_location,
19678 					  op1, TREE_CODE (t), std_alignof,
19679 					  complain & tf_error);
19680 	else
19681 	  r = cxx_sizeof_or_alignof_expr (input_location,
19682 					  op1, TREE_CODE (t),
19683 					  complain & tf_error);
19684 	if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
19685 	  {
19686 	    if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
19687 	      {
19688 		if (!processing_template_decl && TYPE_P (op1))
19689 		  {
19690 		    r = build_min (SIZEOF_EXPR, size_type_node,
19691 				   build1 (NOP_EXPR, op1, error_mark_node));
19692 		    SIZEOF_EXPR_TYPE_P (r) = 1;
19693 		  }
19694 		else
19695 		  r = build_min (SIZEOF_EXPR, size_type_node, op1);
19696 		TREE_SIDE_EFFECTS (r) = 0;
19697 		TREE_READONLY (r) = 1;
19698 	      }
19699 	    SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
19700 	  }
19701 	RETURN (r);
19702       }
19703 
19704     case AT_ENCODE_EXPR:
19705       {
19706 	op1 = TREE_OPERAND (t, 0);
19707 	++cp_unevaluated_operand;
19708 	++c_inhibit_evaluation_warnings;
19709 	op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
19710 				     /*function_p=*/false,
19711 				     /*integral_constant_expression_p=*/false);
19712 	--cp_unevaluated_operand;
19713 	--c_inhibit_evaluation_warnings;
19714 	RETURN (objc_build_encode_expr (op1));
19715       }
19716 
19717     case NOEXCEPT_EXPR:
19718       op1 = TREE_OPERAND (t, 0);
19719       ++cp_unevaluated_operand;
19720       ++c_inhibit_evaluation_warnings;
19721       ++cp_noexcept_operand;
19722       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
19723 				   /*function_p=*/false,
19724 				   /*integral_constant_expression_p=*/false);
19725       --cp_unevaluated_operand;
19726       --c_inhibit_evaluation_warnings;
19727       --cp_noexcept_operand;
19728       RETURN (finish_noexcept_expr (op1, complain));
19729 
19730     case MODOP_EXPR:
19731       {
19732 	warning_sentinel s(warn_div_by_zero);
19733 	tree lhs = RECUR (TREE_OPERAND (t, 0));
19734 	tree rhs = RECUR (TREE_OPERAND (t, 2));
19735 	tree r = build_x_modify_expr
19736 	  (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
19737 	   complain|decltype_flag);
19738 	/* TREE_NO_WARNING must be set if either the expression was
19739 	   parenthesized or it uses an operator such as >>= rather
19740 	   than plain assignment.  In the former case, it was already
19741 	   set and must be copied.  In the latter case,
19742 	   build_x_modify_expr sets it and it must not be reset
19743 	   here.  */
19744 	if (TREE_NO_WARNING (t))
19745 	  TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
19746 
19747 	RETURN (r);
19748       }
19749 
19750     case ARROW_EXPR:
19751       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
19752 						args, complain, in_decl);
19753       /* Remember that there was a reference to this entity.  */
19754       if (DECL_P (op1)
19755 	  && !mark_used (op1, complain) && !(complain & tf_error))
19756 	RETURN (error_mark_node);
19757       RETURN (build_x_arrow (input_location, op1, complain));
19758 
19759     case NEW_EXPR:
19760       {
19761 	tree placement = RECUR (TREE_OPERAND (t, 0));
19762 	tree init = RECUR (TREE_OPERAND (t, 3));
19763 	vec<tree, va_gc> *placement_vec;
19764 	vec<tree, va_gc> *init_vec;
19765 	tree ret;
19766 	location_t loc = EXPR_LOCATION (t);
19767 
19768 	if (placement == NULL_TREE)
19769 	  placement_vec = NULL;
19770 	else
19771 	  {
19772 	    placement_vec = make_tree_vector ();
19773 	    for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
19774 	      vec_safe_push (placement_vec, TREE_VALUE (placement));
19775 	  }
19776 
19777 	/* If there was an initializer in the original tree, but it
19778 	   instantiated to an empty list, then we should pass a
19779 	   non-NULL empty vector to tell build_new that it was an
19780 	   empty initializer() rather than no initializer.  This can
19781 	   only happen when the initializer is a pack expansion whose
19782 	   parameter packs are of length zero.  */
19783 	if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
19784 	  init_vec = NULL;
19785 	else
19786 	  {
19787 	    init_vec = make_tree_vector ();
19788 	    if (init == void_node)
19789 	      gcc_assert (init_vec != NULL);
19790 	    else
19791 	      {
19792 		for (; init != NULL_TREE; init = TREE_CHAIN (init))
19793 		  vec_safe_push (init_vec, TREE_VALUE (init));
19794 	      }
19795 	  }
19796 
19797 	/* Avoid passing an enclosing decl to valid_array_size_p.  */
19798 	in_decl = NULL_TREE;
19799 
19800 	tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
19801 	tree op2 = RECUR (TREE_OPERAND (t, 2));
19802 	ret = build_new (loc, &placement_vec, op1, op2,
19803 			 &init_vec, NEW_EXPR_USE_GLOBAL (t),
19804 			 complain);
19805 
19806 	if (placement_vec != NULL)
19807 	  release_tree_vector (placement_vec);
19808 	if (init_vec != NULL)
19809 	  release_tree_vector (init_vec);
19810 
19811 	RETURN (ret);
19812       }
19813 
19814     case DELETE_EXPR:
19815       {
19816 	tree op0 = RECUR (TREE_OPERAND (t, 0));
19817 	tree op1 = RECUR (TREE_OPERAND (t, 1));
19818 	RETURN (delete_sanity (input_location, op0, op1,
19819 			       DELETE_EXPR_USE_VEC (t),
19820 			       DELETE_EXPR_USE_GLOBAL (t),
19821 			       complain));
19822       }
19823 
19824     case COMPOUND_EXPR:
19825       {
19826 	tree op0 = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
19827 					  complain & ~tf_decltype, in_decl,
19828 					  /*function_p=*/false,
19829 					  integral_constant_expression_p);
19830 	RETURN (build_x_compound_expr (EXPR_LOCATION (t),
19831 				       op0,
19832 				       RECUR (TREE_OPERAND (t, 1)),
19833 				       complain|decltype_flag));
19834       }
19835 
19836     case CALL_EXPR:
19837       {
19838 	tree function;
19839 	unsigned int nargs, i;
19840 	bool qualified_p;
19841 	bool koenig_p;
19842 	tree ret;
19843 
19844 	function = CALL_EXPR_FN (t);
19845 	/* Internal function with no arguments.  */
19846 	if (function == NULL_TREE && call_expr_nargs (t) == 0)
19847 	  RETURN (t);
19848 
19849 	/* When we parsed the expression, we determined whether or
19850 	   not Koenig lookup should be performed.  */
19851 	koenig_p = KOENIG_LOOKUP_P (t);
19852 	if (function == NULL_TREE)
19853 	  {
19854 	    koenig_p = false;
19855 	    qualified_p = false;
19856 	  }
19857 	else if (TREE_CODE (function) == SCOPE_REF)
19858 	  {
19859 	    qualified_p = true;
19860 	    function = tsubst_qualified_id (function, args, complain, in_decl,
19861 					    /*done=*/false,
19862 					    /*address_p=*/false);
19863 	  }
19864 	else if (koenig_p && identifier_p (function))
19865 	  {
19866 	    /* Do nothing; calling tsubst_copy_and_build on an identifier
19867 	       would incorrectly perform unqualified lookup again.
19868 
19869 	       Note that we can also have an IDENTIFIER_NODE if the earlier
19870 	       unqualified lookup found a member function; in that case
19871 	       koenig_p will be false and we do want to do the lookup
19872 	       again to find the instantiated member function.
19873 
19874 	       FIXME but doing that causes c++/15272, so we need to stop
19875 	       using IDENTIFIER_NODE in that situation.  */
19876 	    qualified_p = false;
19877 	  }
19878 	else
19879 	  {
19880 	    if (TREE_CODE (function) == COMPONENT_REF)
19881 	      {
19882 		tree op = TREE_OPERAND (function, 1);
19883 
19884 		qualified_p = (TREE_CODE (op) == SCOPE_REF
19885 			       || (BASELINK_P (op)
19886 				   && BASELINK_QUALIFIED_P (op)));
19887 	      }
19888 	    else
19889 	      qualified_p = false;
19890 
19891 	    if (TREE_CODE (function) == ADDR_EXPR
19892 		&& TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
19893 	      /* Avoid error about taking the address of a constructor.  */
19894 	      function = TREE_OPERAND (function, 0);
19895 
19896 	    function = tsubst_copy_and_build (function, args, complain,
19897 					      in_decl,
19898 					      !qualified_p,
19899 					      integral_constant_expression_p);
19900 
19901 	    if (BASELINK_P (function))
19902 	      qualified_p = true;
19903 	  }
19904 
19905 	nargs = call_expr_nargs (t);
19906 	releasing_vec call_args;
19907 	for (i = 0; i < nargs; ++i)
19908 	  {
19909 	    tree arg = CALL_EXPR_ARG (t, i);
19910 
19911 	    if (!PACK_EXPANSION_P (arg))
19912 	      vec_safe_push (call_args, RECUR (CALL_EXPR_ARG (t, i)));
19913 	    else
19914 	      {
19915 		/* Expand the pack expansion and push each entry onto
19916 		   CALL_ARGS.  */
19917 		arg = tsubst_pack_expansion (arg, args, complain, in_decl);
19918 		if (TREE_CODE (arg) == TREE_VEC)
19919 		  {
19920 		    unsigned int len, j;
19921 
19922 		    len = TREE_VEC_LENGTH (arg);
19923 		    for (j = 0; j < len; ++j)
19924 		      {
19925 			tree value = TREE_VEC_ELT (arg, j);
19926 			if (value != NULL_TREE)
19927 			  value = convert_from_reference (value);
19928 			vec_safe_push (call_args, value);
19929 		      }
19930 		  }
19931 		else
19932 		  {
19933 		    /* A partial substitution.  Add one entry.  */
19934 		    vec_safe_push (call_args, arg);
19935 		  }
19936 	      }
19937 	  }
19938 
19939 	/* Stripped-down processing for a call in a thunk.  Specifically, in
19940 	   the thunk template for a generic lambda.  */
19941 	if (CALL_FROM_THUNK_P (t))
19942 	  {
19943 	    /* Now that we've expanded any packs, the number of call args
19944 	       might be different.  */
19945 	    unsigned int cargs = call_args->length ();
19946 	    tree thisarg = NULL_TREE;
19947 	    if (TREE_CODE (function) == COMPONENT_REF)
19948 	      {
19949 		thisarg = TREE_OPERAND (function, 0);
19950 		if (TREE_CODE (thisarg) == INDIRECT_REF)
19951 		  thisarg = TREE_OPERAND (thisarg, 0);
19952 		function = TREE_OPERAND (function, 1);
19953 		if (TREE_CODE (function) == BASELINK)
19954 		  function = BASELINK_FUNCTIONS (function);
19955 	      }
19956 	    /* We aren't going to do normal overload resolution, so force the
19957 	       template-id to resolve.  */
19958 	    function = resolve_nondeduced_context (function, complain);
19959 	    for (unsigned i = 0; i < cargs; ++i)
19960 	      {
19961 		/* In a thunk, pass through args directly, without any
19962 		   conversions.  */
19963 		tree arg = (*call_args)[i];
19964 		while (TREE_CODE (arg) != PARM_DECL)
19965 		  arg = TREE_OPERAND (arg, 0);
19966 		(*call_args)[i] = arg;
19967 	      }
19968 	    if (thisarg)
19969 	      {
19970 		/* If there are no other args, just push 'this'.  */
19971 		if (cargs == 0)
19972 		  vec_safe_push (call_args, thisarg);
19973 		else
19974 		  {
19975 		    /* Otherwise, shift the other args over to make room.  */
19976 		    tree last = (*call_args)[cargs - 1];
19977 		    vec_safe_push (call_args, last);
19978 		    for (int i = cargs - 1; i > 0; --i)
19979 		      (*call_args)[i] = (*call_args)[i - 1];
19980 		    (*call_args)[0] = thisarg;
19981 		  }
19982 	      }
19983 	    ret = build_call_a (function, call_args->length (),
19984 				call_args->address ());
19985 	    /* The thunk location is not interesting.  */
19986 	    SET_EXPR_LOCATION (ret, UNKNOWN_LOCATION);
19987 	    CALL_FROM_THUNK_P (ret) = true;
19988 	    if (CLASS_TYPE_P (TREE_TYPE (ret)))
19989 	      CALL_EXPR_RETURN_SLOT_OPT (ret) = true;
19990 
19991 	    RETURN (ret);
19992 	  }
19993 
19994 	/* We do not perform argument-dependent lookup if normal
19995 	   lookup finds a non-function, in accordance with the
19996 	   resolution of DR 218.  */
19997 	if (koenig_p
19998 	    && ((is_overloaded_fn (function)
19999 		 /* If lookup found a member function, the Koenig lookup is
20000 		    not appropriate, even if an unqualified-name was used
20001 		    to denote the function.  */
20002 		 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
20003 		|| identifier_p (function)
20004 		/* C++20 P0846: Lookup found nothing.  */
20005 		|| (TREE_CODE (function) == TEMPLATE_ID_EXPR
20006 		    && identifier_p (TREE_OPERAND (function, 0))))
20007 	    /* Only do this when substitution turns a dependent call
20008 	       into a non-dependent call.  */
20009 	    && type_dependent_expression_p_push (t)
20010 	    && !any_type_dependent_arguments_p (call_args))
20011 	  function = perform_koenig_lookup (function, call_args, tf_none);
20012 
20013 	if (function != NULL_TREE
20014 	    && (identifier_p (function)
20015 		|| (TREE_CODE (function) == TEMPLATE_ID_EXPR
20016 		    && identifier_p (TREE_OPERAND (function, 0))))
20017 	    && !any_type_dependent_arguments_p (call_args))
20018 	  {
20019 	    if (TREE_CODE (function) == TEMPLATE_ID_EXPR)
20020 	      function = TREE_OPERAND (function, 0);
20021 	    if (koenig_p && (complain & tf_warning_or_error))
20022 	      {
20023 		/* For backwards compatibility and good diagnostics, try
20024 		   the unqualified lookup again if we aren't in SFINAE
20025 		   context.  */
20026 		tree unq = (tsubst_copy_and_build
20027 			    (function, args, complain, in_decl, true,
20028 			     integral_constant_expression_p));
20029 		if (unq == error_mark_node)
20030 		  RETURN (error_mark_node);
20031 
20032 		if (unq != function)
20033 		  {
20034 		    /* In a lambda fn, we have to be careful to not
20035 		       introduce new this captures.  Legacy code can't
20036 		       be using lambdas anyway, so it's ok to be
20037 		       stricter.  */
20038 		    bool in_lambda = (current_class_type
20039 				      && LAMBDA_TYPE_P (current_class_type));
20040 		    char const *const msg
20041 		      = G_("%qD was not declared in this scope, "
20042 			   "and no declarations were found by "
20043 			   "argument-dependent lookup at the point "
20044 			   "of instantiation");
20045 
20046 		    bool diag = true;
20047 		    if (in_lambda)
20048 		      error_at (cp_expr_loc_or_input_loc (t),
20049 				msg, function);
20050 		    else
20051 		      diag = permerror (cp_expr_loc_or_input_loc (t),
20052 					msg, function);
20053 		    if (diag)
20054 		      {
20055 			tree fn = unq;
20056 
20057 			if (INDIRECT_REF_P (fn))
20058 			  fn = TREE_OPERAND (fn, 0);
20059 			if (is_overloaded_fn (fn))
20060 			  fn = get_first_fn (fn);
20061 
20062 			if (!DECL_P (fn))
20063 			  /* Can't say anything more.  */;
20064 			else if (DECL_CLASS_SCOPE_P (fn))
20065 			  {
20066 			    location_t loc = cp_expr_loc_or_input_loc (t);
20067 			    inform (loc,
20068 				    "declarations in dependent base %qT are "
20069 				    "not found by unqualified lookup",
20070 				    DECL_CLASS_CONTEXT (fn));
20071 			    if (current_class_ptr)
20072 			      inform (loc,
20073 				      "use %<this->%D%> instead", function);
20074 			    else
20075 			      inform (loc,
20076 				      "use %<%T::%D%> instead",
20077 				      current_class_name, function);
20078 			  }
20079 			else
20080 			  inform (DECL_SOURCE_LOCATION (fn),
20081 				  "%qD declared here, later in the "
20082 				  "translation unit", fn);
20083 			if (in_lambda)
20084 			  RETURN (error_mark_node);
20085 		      }
20086 
20087 		    function = unq;
20088 		  }
20089 	      }
20090 	    if (identifier_p (function))
20091 	      {
20092 		if (complain & tf_error)
20093 		  unqualified_name_lookup_error (function);
20094 		RETURN (error_mark_node);
20095 	      }
20096 	  }
20097 
20098 	/* Remember that there was a reference to this entity.  */
20099 	if (function != NULL_TREE
20100 	    && DECL_P (function)
20101 	    && !mark_used (function, complain) && !(complain & tf_error))
20102 	  RETURN (error_mark_node);
20103 
20104 	/* Put back tf_decltype for the actual call.  */
20105 	complain |= decltype_flag;
20106 
20107 	if (function == NULL_TREE)
20108 	  switch (CALL_EXPR_IFN (t))
20109 	    {
20110 	    case IFN_LAUNDER:
20111 	      gcc_assert (nargs == 1);
20112 	      if (vec_safe_length (call_args) != 1)
20113 		{
20114 		  error_at (cp_expr_loc_or_input_loc (t),
20115 			    "wrong number of arguments to "
20116 			    "%<__builtin_launder%>");
20117 		  ret = error_mark_node;
20118 		}
20119 	      else
20120 		ret = finish_builtin_launder (cp_expr_loc_or_input_loc (t),
20121 					      (*call_args)[0], complain);
20122 	      break;
20123 
20124 	    case IFN_VEC_CONVERT:
20125 	      gcc_assert (nargs == 1);
20126 	      if (vec_safe_length (call_args) != 1)
20127 		{
20128 		  error_at (cp_expr_loc_or_input_loc (t),
20129 			    "wrong number of arguments to "
20130 			    "%<__builtin_convertvector%>");
20131 		  ret = error_mark_node;
20132 		  break;
20133 		}
20134 	      ret = cp_build_vec_convert ((*call_args)[0], input_location,
20135 					  tsubst (TREE_TYPE (t), args,
20136 						  complain, in_decl),
20137 					  complain);
20138 	      if (TREE_CODE (ret) == VIEW_CONVERT_EXPR)
20139 		RETURN (ret);
20140 	      break;
20141 
20142 	    default:
20143 	      /* Unsupported internal function with arguments.  */
20144 	      gcc_unreachable ();
20145 	    }
20146 	else if (TREE_CODE (function) == OFFSET_REF
20147 		 || TREE_CODE (function) == DOTSTAR_EXPR
20148 		 || TREE_CODE (function) == MEMBER_REF)
20149 	  ret = build_offset_ref_call_from_tree (function, &call_args,
20150 						 complain);
20151 	else if (TREE_CODE (function) == COMPONENT_REF)
20152 	  {
20153 	    tree instance = TREE_OPERAND (function, 0);
20154 	    tree fn = TREE_OPERAND (function, 1);
20155 
20156 	    if (processing_template_decl
20157 		&& (type_dependent_expression_p (instance)
20158 		    || (!BASELINK_P (fn)
20159 			&& TREE_CODE (fn) != FIELD_DECL)
20160 		    || type_dependent_expression_p (fn)
20161 		    || any_type_dependent_arguments_p (call_args)))
20162 	      ret = build_min_nt_call_vec (function, call_args);
20163 	    else if (!BASELINK_P (fn))
20164 	      ret = finish_call_expr (function, &call_args,
20165 				       /*disallow_virtual=*/false,
20166 				       /*koenig_p=*/false,
20167 				       complain);
20168 	    else
20169 	      ret = (build_new_method_call
20170 		      (instance, fn,
20171 		       &call_args, NULL_TREE,
20172 		       qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
20173 		       /*fn_p=*/NULL,
20174 		       complain));
20175 	  }
20176 	else if (concept_check_p (function))
20177 	  {
20178 	    /* FUNCTION is a template-id referring to a concept definition.  */
20179 	    tree id = unpack_concept_check (function);
20180 	    tree tmpl = TREE_OPERAND (id, 0);
20181 	    tree args = TREE_OPERAND (id, 1);
20182 
20183 	    /* Calls to standard and variable concepts should have been
20184 	       previously diagnosed.  */
20185 	    gcc_assert (function_concept_p (tmpl));
20186 
20187 	    /* Ensure the result is wrapped as a call expression.  */
20188 	    ret = build_concept_check (tmpl, args, tf_warning_or_error);
20189 	  }
20190 	else
20191 	  ret = finish_call_expr (function, &call_args,
20192 				  /*disallow_virtual=*/qualified_p,
20193 				  koenig_p,
20194 				  complain);
20195 
20196 	if (ret != error_mark_node)
20197 	  {
20198 	    bool op = CALL_EXPR_OPERATOR_SYNTAX (t);
20199 	    bool ord = CALL_EXPR_ORDERED_ARGS (t);
20200 	    bool rev = CALL_EXPR_REVERSE_ARGS (t);
20201 	    if (op || ord || rev)
20202 	      {
20203 		function = extract_call_expr (ret);
20204 		CALL_EXPR_OPERATOR_SYNTAX (function) = op;
20205 		CALL_EXPR_ORDERED_ARGS (function) = ord;
20206 		CALL_EXPR_REVERSE_ARGS (function) = rev;
20207 	      }
20208 	  }
20209 
20210 	RETURN (ret);
20211       }
20212 
20213     case COND_EXPR:
20214       {
20215 	tree cond = RECUR (TREE_OPERAND (t, 0));
20216 	cond = mark_rvalue_use (cond);
20217 	tree folded_cond = fold_non_dependent_expr (cond, complain);
20218 	tree exp1, exp2;
20219 
20220 	if (TREE_CODE (folded_cond) == INTEGER_CST)
20221 	  {
20222 	    if (integer_zerop (folded_cond))
20223 	      {
20224 		++c_inhibit_evaluation_warnings;
20225 		exp1 = RECUR (TREE_OPERAND (t, 1));
20226 		--c_inhibit_evaluation_warnings;
20227 		exp2 = RECUR (TREE_OPERAND (t, 2));
20228 	      }
20229 	    else
20230 	      {
20231 		exp1 = RECUR (TREE_OPERAND (t, 1));
20232 		++c_inhibit_evaluation_warnings;
20233 		exp2 = RECUR (TREE_OPERAND (t, 2));
20234 		--c_inhibit_evaluation_warnings;
20235 	      }
20236 	    cond = folded_cond;
20237 	  }
20238 	else
20239 	  {
20240 	    exp1 = RECUR (TREE_OPERAND (t, 1));
20241 	    exp2 = RECUR (TREE_OPERAND (t, 2));
20242 	  }
20243 
20244 	warning_sentinel s(warn_duplicated_branches);
20245 	RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
20246 					 cond, exp1, exp2, complain));
20247       }
20248 
20249     case PSEUDO_DTOR_EXPR:
20250       {
20251 	tree op0 = RECUR (TREE_OPERAND (t, 0));
20252 	tree op1 = RECUR (TREE_OPERAND (t, 1));
20253 	tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
20254 	RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
20255 					       input_location));
20256       }
20257 
20258     case TREE_LIST:
20259       {
20260 	tree purpose, value, chain;
20261 
20262 	if (t == void_list_node)
20263 	  RETURN (t);
20264 
20265         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
20266             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
20267           {
20268             /* We have pack expansions, so expand those and
20269                create a new list out of it.  */
20270             tree purposevec = NULL_TREE;
20271             tree valuevec = NULL_TREE;
20272             tree chain;
20273             int i, len = -1;
20274 
20275             /* Expand the argument expressions.  */
20276             if (TREE_PURPOSE (t))
20277               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
20278                                                  complain, in_decl);
20279             if (TREE_VALUE (t))
20280               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
20281                                                complain, in_decl);
20282 
20283             /* Build the rest of the list.  */
20284             chain = TREE_CHAIN (t);
20285             if (chain && chain != void_type_node)
20286               chain = RECUR (chain);
20287 
20288             /* Determine the number of arguments.  */
20289             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
20290               {
20291                 len = TREE_VEC_LENGTH (purposevec);
20292                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
20293               }
20294             else if (TREE_CODE (valuevec) == TREE_VEC)
20295               len = TREE_VEC_LENGTH (valuevec);
20296             else
20297               {
20298                 /* Since we only performed a partial substitution into
20299                    the argument pack, we only RETURN (a single list
20300                    node.  */
20301                 if (purposevec == TREE_PURPOSE (t)
20302                     && valuevec == TREE_VALUE (t)
20303                     && chain == TREE_CHAIN (t))
20304                   RETURN (t);
20305 
20306                 RETURN (tree_cons (purposevec, valuevec, chain));
20307               }
20308 
20309             /* Convert the argument vectors into a TREE_LIST */
20310             i = len;
20311             while (i > 0)
20312               {
20313                 /* Grab the Ith values.  */
20314                 i--;
20315                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i)
20316 		                     : NULL_TREE;
20317                 value
20318 		  = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i))
20319                              : NULL_TREE;
20320 
20321                 /* Build the list (backwards).  */
20322                 chain = tree_cons (purpose, value, chain);
20323               }
20324 
20325             RETURN (chain);
20326           }
20327 
20328 	purpose = TREE_PURPOSE (t);
20329 	if (purpose)
20330 	  purpose = RECUR (purpose);
20331 	value = TREE_VALUE (t);
20332 	if (value)
20333 	  value = RECUR (value);
20334 	chain = TREE_CHAIN (t);
20335 	if (chain && chain != void_type_node)
20336 	  chain = RECUR (chain);
20337 	if (purpose == TREE_PURPOSE (t)
20338 	    && value == TREE_VALUE (t)
20339 	    && chain == TREE_CHAIN (t))
20340 	  RETURN (t);
20341 	RETURN (tree_cons (purpose, value, chain));
20342       }
20343 
20344     case COMPONENT_REF:
20345       {
20346 	tree object;
20347 	tree object_type;
20348 	tree member;
20349 	tree r;
20350 
20351 	object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20352 						     args, complain, in_decl);
20353 	/* Remember that there was a reference to this entity.  */
20354 	if (DECL_P (object)
20355 	    && !mark_used (object, complain) && !(complain & tf_error))
20356 	  RETURN (error_mark_node);
20357 	object_type = TREE_TYPE (object);
20358 
20359 	member = TREE_OPERAND (t, 1);
20360 	if (BASELINK_P (member))
20361 	  member = tsubst_baselink (member,
20362 				    non_reference (TREE_TYPE (object)),
20363 				    args, complain, in_decl);
20364 	else
20365 	  member = tsubst_copy (member, args, complain, in_decl);
20366 	if (member == error_mark_node)
20367 	  RETURN (error_mark_node);
20368 
20369 	if (TREE_CODE (member) == FIELD_DECL)
20370 	  {
20371 	    r = finish_non_static_data_member (member, object, NULL_TREE);
20372 	    if (TREE_CODE (r) == COMPONENT_REF)
20373 	      REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
20374 	    RETURN (r);
20375 	  }
20376 	else if (type_dependent_expression_p (object))
20377 	  /* We can't do much here.  */;
20378 	else if (!CLASS_TYPE_P (object_type))
20379 	  {
20380 	    if (scalarish_type_p (object_type))
20381 	      {
20382 		tree s = NULL_TREE;
20383 		tree dtor = member;
20384 
20385 		if (TREE_CODE (dtor) == SCOPE_REF)
20386 		  {
20387 		    s = TREE_OPERAND (dtor, 0);
20388 		    dtor = TREE_OPERAND (dtor, 1);
20389 		  }
20390 		if (TREE_CODE (dtor) == BIT_NOT_EXPR)
20391 		  {
20392 		    dtor = TREE_OPERAND (dtor, 0);
20393 		    if (TYPE_P (dtor))
20394 		      RETURN (finish_pseudo_destructor_expr
20395 			      (object, s, dtor, input_location));
20396 		  }
20397 	      }
20398 	  }
20399 	else if (TREE_CODE (member) == SCOPE_REF
20400 		 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
20401 	  {
20402 	    /* Lookup the template functions now that we know what the
20403 	       scope is.  */
20404 	    tree scope = TREE_OPERAND (member, 0);
20405 	    tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
20406 	    tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
20407 	    member = lookup_qualified_name (scope, tmpl,
20408 					    /*is_type_p=*/false,
20409 					    /*complain=*/false);
20410 	    if (BASELINK_P (member))
20411 	      {
20412 		BASELINK_FUNCTIONS (member)
20413 		  = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
20414 			      args);
20415 		member = (adjust_result_of_qualified_name_lookup
20416 			  (member, BINFO_TYPE (BASELINK_BINFO (member)),
20417 			   object_type));
20418 	      }
20419 	    else
20420 	      {
20421 		qualified_name_lookup_error (scope, tmpl, member,
20422 					     input_location);
20423 		RETURN (error_mark_node);
20424 	      }
20425 	  }
20426 	else if (TREE_CODE (member) == SCOPE_REF
20427 		 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
20428 		 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
20429 	  {
20430 	    if (complain & tf_error)
20431 	      {
20432 		if (TYPE_P (TREE_OPERAND (member, 0)))
20433 		  error ("%qT is not a class or namespace",
20434 			 TREE_OPERAND (member, 0));
20435 		else
20436 		  error ("%qD is not a class or namespace",
20437 			 TREE_OPERAND (member, 0));
20438 	      }
20439 	    RETURN (error_mark_node);
20440 	  }
20441 
20442 	r = finish_class_member_access_expr (object, member,
20443 					     /*template_p=*/false,
20444 					     complain);
20445 	if (TREE_CODE (r) == COMPONENT_REF)
20446 	  REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
20447 	RETURN (r);
20448       }
20449 
20450     case THROW_EXPR:
20451       RETURN (build_throw
20452        (input_location, RECUR (TREE_OPERAND (t, 0))));
20453 
20454     case CONSTRUCTOR:
20455       {
20456 	vec<constructor_elt, va_gc> *n;
20457 	constructor_elt *ce;
20458 	unsigned HOST_WIDE_INT idx;
20459 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20460 	bool process_index_p;
20461         int newlen;
20462         bool need_copy_p = false;
20463 	tree r;
20464 
20465 	if (type == error_mark_node)
20466 	  RETURN (error_mark_node);
20467 
20468 	/* We do not want to process the index of aggregate
20469 	   initializers as they are identifier nodes which will be
20470 	   looked up by digest_init.  */
20471 	process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
20472 
20473 	if (null_member_pointer_value_p (t))
20474 	  {
20475 	    gcc_assert (same_type_p (type, TREE_TYPE (t)));
20476 	    RETURN (t);
20477 	  }
20478 
20479 	n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
20480         newlen = vec_safe_length (n);
20481 	FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
20482 	  {
20483 	    if (ce->index && process_index_p
20484 		/* An identifier index is looked up in the type
20485 		   being initialized, not the current scope.  */
20486 		&& TREE_CODE (ce->index) != IDENTIFIER_NODE)
20487 	      ce->index = RECUR (ce->index);
20488 
20489             if (PACK_EXPANSION_P (ce->value))
20490               {
20491                 /* Substitute into the pack expansion.  */
20492                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
20493                                                   in_decl);
20494 
20495 		if (ce->value == error_mark_node
20496 		    || PACK_EXPANSION_P (ce->value))
20497 		  ;
20498 		else if (TREE_VEC_LENGTH (ce->value) == 1)
20499                   /* Just move the argument into place.  */
20500                   ce->value = TREE_VEC_ELT (ce->value, 0);
20501                 else
20502                   {
20503                     /* Update the length of the final CONSTRUCTOR
20504                        arguments vector, and note that we will need to
20505                        copy.*/
20506                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
20507                     need_copy_p = true;
20508                   }
20509               }
20510             else
20511               ce->value = RECUR (ce->value);
20512 	  }
20513 
20514         if (need_copy_p)
20515           {
20516             vec<constructor_elt, va_gc> *old_n = n;
20517 
20518             vec_alloc (n, newlen);
20519             FOR_EACH_VEC_ELT (*old_n, idx, ce)
20520               {
20521                 if (TREE_CODE (ce->value) == TREE_VEC)
20522                   {
20523                     int i, len = TREE_VEC_LENGTH (ce->value);
20524                     for (i = 0; i < len; ++i)
20525                       CONSTRUCTOR_APPEND_ELT (n, 0,
20526                                               TREE_VEC_ELT (ce->value, i));
20527                   }
20528                 else
20529                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
20530               }
20531           }
20532 
20533 	r = build_constructor (init_list_type_node, n);
20534 	CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
20535 	CONSTRUCTOR_IS_DESIGNATED_INIT (r)
20536 	  = CONSTRUCTOR_IS_DESIGNATED_INIT (t);
20537 
20538 	if (TREE_HAS_CONSTRUCTOR (t))
20539 	  {
20540 	    fcl_t cl = fcl_functional;
20541 	    if (CONSTRUCTOR_C99_COMPOUND_LITERAL (t))
20542 	      cl = fcl_c99;
20543 	    RETURN (finish_compound_literal (type, r, complain, cl));
20544 	  }
20545 
20546 	TREE_TYPE (r) = type;
20547 	RETURN (r);
20548       }
20549 
20550     case TYPEID_EXPR:
20551       {
20552 	tree operand_0 = TREE_OPERAND (t, 0);
20553 	if (TYPE_P (operand_0))
20554 	  {
20555 	    operand_0 = tsubst (operand_0, args, complain, in_decl);
20556 	    RETURN (get_typeid (operand_0, complain));
20557 	  }
20558 	else
20559 	  {
20560 	    operand_0 = RECUR (operand_0);
20561 	    RETURN (build_typeid (operand_0, complain));
20562 	  }
20563       }
20564 
20565     case VAR_DECL:
20566       if (!args)
20567 	RETURN (t);
20568       /* Fall through */
20569 
20570     case PARM_DECL:
20571       {
20572 	tree r = tsubst_copy (t, args, complain, in_decl);
20573 	/* ??? We're doing a subset of finish_id_expression here.  */
20574 	if (tree wrap = maybe_get_tls_wrapper_call (r))
20575 	  /* Replace an evaluated use of the thread_local variable with
20576 	     a call to its wrapper.  */
20577 	  r = wrap;
20578 	else if (outer_automatic_var_p (r))
20579 	  r = process_outer_var_ref (r, complain);
20580 
20581 	if (!TYPE_REF_P (TREE_TYPE (t)))
20582 	  /* If the original type was a reference, we'll be wrapped in
20583 	     the appropriate INDIRECT_REF.  */
20584 	  r = convert_from_reference (r);
20585 	RETURN (r);
20586       }
20587 
20588     case VA_ARG_EXPR:
20589       {
20590 	tree op0 = RECUR (TREE_OPERAND (t, 0));
20591 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20592 	RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
20593       }
20594 
20595     case OFFSETOF_EXPR:
20596       {
20597 	tree object_ptr
20598 	  = tsubst_copy_and_build (TREE_OPERAND (t, 1), args, complain,
20599 				   in_decl, /*function_p=*/false,
20600 				   /*integral_constant_expression_p=*/false);
20601 	RETURN (finish_offsetof (object_ptr,
20602 				 RECUR (TREE_OPERAND (t, 0)),
20603 				 EXPR_LOCATION (t)));
20604       }
20605 
20606     case ADDRESSOF_EXPR:
20607       RETURN (cp_build_addressof (EXPR_LOCATION (t),
20608 				  RECUR (TREE_OPERAND (t, 0)), complain));
20609 
20610     case TRAIT_EXPR:
20611       {
20612 	tree type1 = tsubst (TRAIT_EXPR_TYPE1 (t), args,
20613 			     complain, in_decl);
20614 	tree type2 = tsubst (TRAIT_EXPR_TYPE2 (t), args,
20615 			     complain, in_decl);
20616 	RETURN (finish_trait_expr (TRAIT_EXPR_LOCATION (t),
20617 				   TRAIT_EXPR_KIND (t), type1, type2));
20618       }
20619 
20620     case STMT_EXPR:
20621       {
20622 	tree old_stmt_expr = cur_stmt_expr;
20623 	tree stmt_expr = begin_stmt_expr ();
20624 
20625 	cur_stmt_expr = stmt_expr;
20626 	tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
20627 		     integral_constant_expression_p);
20628 	stmt_expr = finish_stmt_expr (stmt_expr, false);
20629 	cur_stmt_expr = old_stmt_expr;
20630 
20631 	/* If the resulting list of expression statement is empty,
20632 	   fold it further into void_node.  */
20633 	if (empty_expr_stmt_p (stmt_expr))
20634 	  stmt_expr = void_node;
20635 
20636 	RETURN (stmt_expr);
20637       }
20638 
20639     case LAMBDA_EXPR:
20640       {
20641 	if (complain & tf_partial)
20642 	  {
20643 	    /* We don't have a full set of template arguments yet; don't touch
20644 	       the lambda at all.  */
20645 	    gcc_assert (processing_template_decl);
20646 	    return t;
20647 	  }
20648 	tree r = tsubst_lambda_expr (t, args, complain, in_decl);
20649 
20650 	RETURN (build_lambda_object (r));
20651       }
20652 
20653     case TARGET_EXPR:
20654       /* We can get here for a constant initializer of non-dependent type.
20655          FIXME stop folding in cp_parser_initializer_clause.  */
20656       {
20657 	tree r = get_target_expr_sfinae (RECUR (TARGET_EXPR_INITIAL (t)),
20658 					 complain);
20659 	RETURN (r);
20660       }
20661 
20662     case TRANSACTION_EXPR:
20663       RETURN (tsubst_expr(t, args, complain, in_decl,
20664 	     integral_constant_expression_p));
20665 
20666     case PAREN_EXPR:
20667       RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
20668 
20669     case VEC_PERM_EXPR:
20670       {
20671 	tree op0 = RECUR (TREE_OPERAND (t, 0));
20672 	tree op1 = RECUR (TREE_OPERAND (t, 1));
20673 	tree op2 = RECUR (TREE_OPERAND (t, 2));
20674 	RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
20675 				       complain));
20676       }
20677 
20678     case REQUIRES_EXPR:
20679       {
20680 	tree r = tsubst_requires_expr (t, args, tf_none, in_decl);
20681 	RETURN (r);
20682       }
20683 
20684     case RANGE_EXPR:
20685       /* No need to substitute further, a RANGE_EXPR will always be built
20686 	 with constant operands.  */
20687       RETURN (t);
20688 
20689     case NON_LVALUE_EXPR:
20690     case VIEW_CONVERT_EXPR:
20691       if (location_wrapper_p (t))
20692 	/* We need to do this here as well as in tsubst_copy so we get the
20693 	   other tsubst_copy_and_build semantics for a PARM_DECL operand.  */
20694 	RETURN (maybe_wrap_with_location (RECUR (TREE_OPERAND (t, 0)),
20695 					  EXPR_LOCATION (t)));
20696       /* fallthrough.  */
20697 
20698     default:
20699       /* Handle Objective-C++ constructs, if appropriate.  */
20700       {
20701 	tree subst
20702 	  = objcp_tsubst_copy_and_build (t, args, complain,
20703 					 in_decl, /*function_p=*/false);
20704 	if (subst)
20705 	  RETURN (subst);
20706       }
20707       RETURN (tsubst_copy (t, args, complain, in_decl));
20708     }
20709 
20710 #undef RECUR
20711 #undef RETURN
20712  out:
20713   input_location = save_loc;
20714   return retval;
20715 }
20716 
20717 /* Verify that the instantiated ARGS are valid. For type arguments,
20718    make sure that the type's linkage is ok. For non-type arguments,
20719    make sure they are constants if they are integral or enumerations.
20720    Emit an error under control of COMPLAIN, and return TRUE on error.  */
20721 
20722 static bool
check_instantiated_arg(tree tmpl,tree t,tsubst_flags_t complain)20723 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
20724 {
20725   if (dependent_template_arg_p (t))
20726     return false;
20727   if (ARGUMENT_PACK_P (t))
20728     {
20729       tree vec = ARGUMENT_PACK_ARGS (t);
20730       int len = TREE_VEC_LENGTH (vec);
20731       bool result = false;
20732       int i;
20733 
20734       for (i = 0; i < len; ++i)
20735 	if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
20736 	  result = true;
20737       return result;
20738     }
20739   else if (TYPE_P (t))
20740     {
20741       /* [basic.link]: A name with no linkage (notably, the name
20742 	 of a class or enumeration declared in a local scope)
20743 	 shall not be used to declare an entity with linkage.
20744 	 This implies that names with no linkage cannot be used as
20745 	 template arguments
20746 
20747 	 DR 757 relaxes this restriction for C++0x.  */
20748       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
20749 		 : no_linkage_check (t, /*relaxed_p=*/false));
20750 
20751       if (nt)
20752 	{
20753 	  /* DR 488 makes use of a type with no linkage cause
20754 	     type deduction to fail.  */
20755 	  if (complain & tf_error)
20756 	    {
20757 	      if (TYPE_UNNAMED_P (nt))
20758 		error ("%qT is/uses unnamed type", t);
20759 	      else
20760 		error ("template argument for %qD uses local type %qT",
20761 		       tmpl, t);
20762 	    }
20763 	  return true;
20764 	}
20765       /* In order to avoid all sorts of complications, we do not
20766 	 allow variably-modified types as template arguments.  */
20767       else if (variably_modified_type_p (t, NULL_TREE))
20768 	{
20769 	  if (complain & tf_error)
20770 	    error ("%qT is a variably modified type", t);
20771 	  return true;
20772 	}
20773     }
20774   /* Class template and alias template arguments should be OK.  */
20775   else if (DECL_TYPE_TEMPLATE_P (t))
20776     ;
20777   /* A non-type argument of integral or enumerated type must be a
20778      constant.  */
20779   else if (TREE_TYPE (t)
20780 	   && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
20781 	   && !REFERENCE_REF_P (t)
20782 	   && !TREE_CONSTANT (t))
20783     {
20784       if (complain & tf_error)
20785 	error ("integral expression %qE is not constant", t);
20786       return true;
20787     }
20788   return false;
20789 }
20790 
20791 static bool
check_instantiated_args(tree tmpl,tree args,tsubst_flags_t complain)20792 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
20793 {
20794   int ix, len = DECL_NTPARMS (tmpl);
20795   bool result = false;
20796 
20797   for (ix = 0; ix != len; ix++)
20798     {
20799       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
20800 	result = true;
20801     }
20802   if (result && (complain & tf_error))
20803     error ("  trying to instantiate %qD", tmpl);
20804   return result;
20805 }
20806 
20807 /* We're out of SFINAE context now, so generate diagnostics for the access
20808    errors we saw earlier when instantiating D from TMPL and ARGS.  */
20809 
20810 static void
recheck_decl_substitution(tree d,tree tmpl,tree args)20811 recheck_decl_substitution (tree d, tree tmpl, tree args)
20812 {
20813   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
20814   tree type = TREE_TYPE (pattern);
20815   location_t loc = input_location;
20816 
20817   push_access_scope (d);
20818   push_deferring_access_checks (dk_no_deferred);
20819   input_location = DECL_SOURCE_LOCATION (pattern);
20820   tsubst (type, args, tf_warning_or_error, d);
20821   input_location = loc;
20822   pop_deferring_access_checks ();
20823   pop_access_scope (d);
20824 }
20825 
20826 /* Instantiate the indicated variable, function, or alias template TMPL with
20827    the template arguments in TARG_PTR.  */
20828 
20829 static tree
instantiate_template_1(tree tmpl,tree orig_args,tsubst_flags_t complain)20830 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
20831 {
20832   tree targ_ptr = orig_args;
20833   tree fndecl;
20834   tree gen_tmpl;
20835   tree spec;
20836   bool access_ok = true;
20837 
20838   if (tmpl == error_mark_node)
20839     return error_mark_node;
20840 
20841   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
20842 
20843   /* If this function is a clone, handle it specially.  */
20844   if (DECL_CLONED_FUNCTION_P (tmpl))
20845     {
20846       tree spec;
20847       tree clone;
20848 
20849       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
20850 	 DECL_CLONED_FUNCTION.  */
20851       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
20852 				   targ_ptr, complain);
20853       if (spec == error_mark_node)
20854 	return error_mark_node;
20855 
20856       /* Look for the clone.  */
20857       FOR_EACH_CLONE (clone, spec)
20858 	if (DECL_NAME (clone) == DECL_NAME (tmpl))
20859 	  return clone;
20860       /* We should always have found the clone by now.  */
20861       gcc_unreachable ();
20862       return NULL_TREE;
20863     }
20864 
20865   if (targ_ptr == error_mark_node)
20866     return error_mark_node;
20867 
20868   /* Check to see if we already have this specialization.  */
20869   gen_tmpl = most_general_template (tmpl);
20870   if (TMPL_ARGS_DEPTH (targ_ptr)
20871       < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)))
20872     /* targ_ptr only has the innermost template args, so add the outer ones
20873        from tmpl, which could be either a partial instantiation or gen_tmpl (in
20874        the case of a non-dependent call within a template definition).  */
20875     targ_ptr = (add_outermost_template_args
20876 		(DECL_TI_ARGS (DECL_TEMPLATE_RESULT (tmpl)),
20877 		 targ_ptr));
20878 
20879   /* It would be nice to avoid hashing here and then again in tsubst_decl,
20880      but it doesn't seem to be on the hot path.  */
20881   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
20882 
20883   gcc_assert (tmpl == gen_tmpl
20884 	      || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
20885 		  == spec)
20886 	      || fndecl == NULL_TREE);
20887 
20888   if (spec != NULL_TREE)
20889     {
20890       if (FNDECL_HAS_ACCESS_ERRORS (spec))
20891 	{
20892 	  if (complain & tf_error)
20893 	    recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
20894 	  return error_mark_node;
20895 	}
20896       return spec;
20897     }
20898 
20899   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
20900 			       complain))
20901     return error_mark_node;
20902 
20903   /* We are building a FUNCTION_DECL, during which the access of its
20904      parameters and return types have to be checked.  However this
20905      FUNCTION_DECL which is the desired context for access checking
20906      is not built yet.  We solve this chicken-and-egg problem by
20907      deferring all checks until we have the FUNCTION_DECL.  */
20908   push_deferring_access_checks (dk_deferred);
20909 
20910   /* Instantiation of the function happens in the context of the function
20911      template, not the context of the overload resolution we're doing.  */
20912   push_to_top_level ();
20913   /* If there are dependent arguments, e.g. because we're doing partial
20914      ordering, make sure processing_template_decl stays set.  */
20915   if (uses_template_parms (targ_ptr))
20916     ++processing_template_decl;
20917   if (DECL_CLASS_SCOPE_P (gen_tmpl))
20918     {
20919       tree ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
20920 				   complain, gen_tmpl, true);
20921       push_nested_class (ctx);
20922     }
20923 
20924   tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
20925 
20926   fndecl = NULL_TREE;
20927   if (VAR_P (pattern))
20928     {
20929       /* We need to determine if we're using a partial or explicit
20930 	 specialization now, because the type of the variable could be
20931 	 different.  */
20932       tree tid = lookup_template_variable (gen_tmpl, targ_ptr);
20933       tree elt = most_specialized_partial_spec (tid, complain);
20934       if (elt == error_mark_node)
20935 	pattern = error_mark_node;
20936       else if (elt)
20937 	{
20938 	  tree partial_tmpl = TREE_VALUE (elt);
20939 	  tree partial_args = TREE_PURPOSE (elt);
20940 	  tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
20941 	  fndecl = tsubst (partial_pat, partial_args, complain, gen_tmpl);
20942 	}
20943     }
20944 
20945   /* Substitute template parameters to obtain the specialization.  */
20946   if (fndecl == NULL_TREE)
20947     fndecl = tsubst (pattern, targ_ptr, complain, gen_tmpl);
20948   if (DECL_CLASS_SCOPE_P (gen_tmpl))
20949     pop_nested_class ();
20950   pop_from_top_level ();
20951 
20952   if (fndecl == error_mark_node)
20953     {
20954       pop_deferring_access_checks ();
20955       return error_mark_node;
20956     }
20957 
20958   /* The DECL_TI_TEMPLATE should always be the immediate parent
20959      template, not the most general template.  */
20960   DECL_TI_TEMPLATE (fndecl) = tmpl;
20961   DECL_TI_ARGS (fndecl) = targ_ptr;
20962 
20963   /* Now we know the specialization, compute access previously
20964      deferred.  Do no access control for inheriting constructors,
20965      as we already checked access for the inherited constructor.  */
20966   if (!(flag_new_inheriting_ctors
20967 	&& DECL_INHERITED_CTOR (fndecl)))
20968     {
20969       push_access_scope (fndecl);
20970       if (!perform_deferred_access_checks (complain))
20971 	access_ok = false;
20972       pop_access_scope (fndecl);
20973     }
20974   pop_deferring_access_checks ();
20975 
20976   /* If we've just instantiated the main entry point for a function,
20977      instantiate all the alternate entry points as well.  We do this
20978      by cloning the instantiation of the main entry point, not by
20979      instantiating the template clones.  */
20980   if (tree chain = DECL_CHAIN (gen_tmpl))
20981     if (DECL_P (chain) && DECL_CLONED_FUNCTION_P (chain))
20982       clone_function_decl (fndecl, /*update_methods=*/false);
20983 
20984   if (!access_ok)
20985     {
20986       if (!(complain & tf_error))
20987 	{
20988 	  /* Remember to reinstantiate when we're out of SFINAE so the user
20989 	     can see the errors.  */
20990 	  FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
20991 	}
20992       return error_mark_node;
20993     }
20994   return fndecl;
20995 }
20996 
20997 /* Wrapper for instantiate_template_1.  */
20998 
20999 tree
instantiate_template(tree tmpl,tree orig_args,tsubst_flags_t complain)21000 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
21001 {
21002   tree ret;
21003   timevar_push (TV_TEMPLATE_INST);
21004   ret = instantiate_template_1 (tmpl, orig_args,  complain);
21005   timevar_pop (TV_TEMPLATE_INST);
21006   return ret;
21007 }
21008 
21009 /* Instantiate the alias template TMPL with ARGS.  Also push a template
21010    instantiation level, which instantiate_template doesn't do because
21011    functions and variables have sufficient context established by the
21012    callers.  */
21013 
21014 static tree
instantiate_alias_template(tree tmpl,tree args,tsubst_flags_t complain)21015 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
21016 {
21017   if (tmpl == error_mark_node || args == error_mark_node)
21018     return error_mark_node;
21019 
21020   args =
21021     coerce_innermost_template_parms (DECL_TEMPLATE_PARMS (tmpl),
21022 				     args, tmpl, complain,
21023 				     /*require_all_args=*/true,
21024 				     /*use_default_args=*/true);
21025 
21026   /* FIXME check for satisfaction in check_instantiated_args.  */
21027   if (flag_concepts
21028       && !any_dependent_template_arguments_p (args)
21029       && !constraints_satisfied_p (tmpl, args))
21030     {
21031       if (complain & tf_error)
21032 	{
21033 	  auto_diagnostic_group d;
21034 	  error ("template constraint failure for %qD", tmpl);
21035 	  diagnose_constraints (input_location, tmpl, args);
21036 	}
21037       return error_mark_node;
21038     }
21039 
21040   if (!push_tinst_level (tmpl, args))
21041     return error_mark_node;
21042   tree r = instantiate_template (tmpl, args, complain);
21043   pop_tinst_level ();
21044 
21045   return r;
21046 }
21047 
21048 /* PARM is a template parameter pack for FN.  Returns true iff
21049    PARM is used in a deducible way in the argument list of FN.  */
21050 
21051 static bool
pack_deducible_p(tree parm,tree fn)21052 pack_deducible_p (tree parm, tree fn)
21053 {
21054   tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
21055   for (; t; t = TREE_CHAIN (t))
21056     {
21057       tree type = TREE_VALUE (t);
21058       tree packs;
21059       if (!PACK_EXPANSION_P (type))
21060 	continue;
21061       for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
21062 	   packs; packs = TREE_CHAIN (packs))
21063 	if (template_args_equal (TREE_VALUE (packs), parm))
21064 	  {
21065 	    /* The template parameter pack is used in a function parameter
21066 	       pack.  If this is the end of the parameter list, the
21067 	       template parameter pack is deducible.  */
21068 	    if (TREE_CHAIN (t) == void_list_node)
21069 	      return true;
21070 	    else
21071 	      /* Otherwise, not.  Well, it could be deduced from
21072 		 a non-pack parameter, but doing so would end up with
21073 		 a deduction mismatch, so don't bother.  */
21074 	      return false;
21075 	  }
21076     }
21077   /* The template parameter pack isn't used in any function parameter
21078      packs, but it might be used deeper, e.g. tuple<Args...>.  */
21079   return true;
21080 }
21081 
21082 /* Subroutine of fn_type_unification: check non-dependent parms for
21083    convertibility.  */
21084 
21085 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)21086 check_non_deducible_conversions (tree parms, const tree *args, unsigned nargs,
21087 				 tree fn, unification_kind_t strict, int flags,
21088 				 struct conversion **convs, bool explain_p)
21089 {
21090   /* Non-constructor methods need to leave a conversion for 'this', which
21091      isn't included in nargs here.  */
21092   unsigned offset = (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
21093 		     && !DECL_CONSTRUCTOR_P (fn));
21094 
21095   for (unsigned ia = 0;
21096        parms && parms != void_list_node && ia < nargs; )
21097     {
21098       tree parm = TREE_VALUE (parms);
21099 
21100       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
21101 	  && (!TREE_CHAIN (parms)
21102 	      || TREE_CHAIN (parms) == void_list_node))
21103 	/* For a function parameter pack that occurs at the end of the
21104 	   parameter-declaration-list, the type A of each remaining
21105 	   argument of the call is compared with the type P of the
21106 	   declarator-id of the function parameter pack.  */
21107 	break;
21108 
21109       parms = TREE_CHAIN (parms);
21110 
21111       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
21112 	/* For a function parameter pack that does not occur at the
21113 	   end of the parameter-declaration-list, the type of the
21114 	   parameter pack is a non-deduced context.  */
21115 	continue;
21116 
21117       if (!uses_template_parms (parm))
21118 	{
21119 	  tree arg = args[ia];
21120 	  conversion **conv_p = convs ? &convs[ia+offset] : NULL;
21121 	  int lflags = conv_flags (ia, nargs, fn, arg, flags);
21122 
21123 	  if (check_non_deducible_conversion (parm, arg, strict, lflags,
21124 					      conv_p, explain_p))
21125 	    return 1;
21126 	}
21127 
21128       ++ia;
21129     }
21130 
21131   return 0;
21132 }
21133 
21134 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
21135    NARGS elements of the arguments that are being used when calling
21136    it.  TARGS is a vector into which the deduced template arguments
21137    are placed.
21138 
21139    Returns either a FUNCTION_DECL for the matching specialization of FN or
21140    NULL_TREE if no suitable specialization can be found.  If EXPLAIN_P is
21141    true, diagnostics will be printed to explain why it failed.
21142 
21143    If FN is a conversion operator, or we are trying to produce a specific
21144    specialization, RETURN_TYPE is the return type desired.
21145 
21146    The EXPLICIT_TARGS are explicit template arguments provided via a
21147    template-id.
21148 
21149    The parameter STRICT is one of:
21150 
21151    DEDUCE_CALL:
21152      We are deducing arguments for a function call, as in
21153      [temp.deduct.call].  If RETURN_TYPE is non-null, we are
21154      deducing arguments for a call to the result of a conversion
21155      function template, as in [over.call.object].
21156 
21157    DEDUCE_CONV:
21158      We are deducing arguments for a conversion function, as in
21159      [temp.deduct.conv].
21160 
21161    DEDUCE_EXACT:
21162      We are deducing arguments when doing an explicit instantiation
21163      as in [temp.explicit], when determining an explicit specialization
21164      as in [temp.expl.spec], or when taking the address of a function
21165      template, as in [temp.deduct.funcaddr].  */
21166 
21167 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)21168 fn_type_unification (tree fn,
21169 		     tree explicit_targs,
21170 		     tree targs,
21171 		     const tree *args,
21172 		     unsigned int nargs,
21173 		     tree return_type,
21174 		     unification_kind_t strict,
21175 		     int flags,
21176 		     struct conversion **convs,
21177 		     bool explain_p,
21178 		     bool decltype_p)
21179 {
21180   tree parms;
21181   tree fntype;
21182   tree decl = NULL_TREE;
21183   tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
21184   bool ok;
21185   static int deduction_depth;
21186   /* type_unification_real will pass back any access checks from default
21187      template argument substitution.  */
21188   vec<deferred_access_check, va_gc> *checks = NULL;
21189   /* We don't have all the template args yet.  */
21190   bool incomplete = true;
21191 
21192   tree orig_fn = fn;
21193   if (flag_new_inheriting_ctors)
21194     fn = strip_inheriting_ctors (fn);
21195 
21196   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
21197   tree r = error_mark_node;
21198 
21199   tree full_targs = targs;
21200   if (TMPL_ARGS_DEPTH (targs)
21201       < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (fn)))
21202     full_targs = (add_outermost_template_args
21203 		  (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (fn)),
21204 		   targs));
21205 
21206   if (decltype_p)
21207     complain |= tf_decltype;
21208 
21209   /* In C++0x, it's possible to have a function template whose type depends
21210      on itself recursively.  This is most obvious with decltype, but can also
21211      occur with enumeration scope (c++/48969).  So we need to catch infinite
21212      recursion and reject the substitution at deduction time; this function
21213      will return error_mark_node for any repeated substitution.
21214 
21215      This also catches excessive recursion such as when f<N> depends on
21216      f<N-1> across all integers, and returns error_mark_node for all the
21217      substitutions back up to the initial one.
21218 
21219      This is, of course, not reentrant.  */
21220   if (excessive_deduction_depth)
21221     return error_mark_node;
21222   ++deduction_depth;
21223 
21224   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
21225 
21226   fntype = TREE_TYPE (fn);
21227   if (explicit_targs)
21228     {
21229       /* [temp.deduct]
21230 
21231 	 The specified template arguments must match the template
21232 	 parameters in kind (i.e., type, nontype, template), and there
21233 	 must not be more arguments than there are parameters;
21234 	 otherwise type deduction fails.
21235 
21236 	 Nontype arguments must match the types of the corresponding
21237 	 nontype template parameters, or must be convertible to the
21238 	 types of the corresponding nontype parameters as specified in
21239 	 _temp.arg.nontype_, otherwise type deduction fails.
21240 
21241 	 All references in the function type of the function template
21242 	 to the corresponding template parameters are replaced by the
21243 	 specified template argument values.  If a substitution in a
21244 	 template parameter or in the function type of the function
21245 	 template results in an invalid type, type deduction fails.  */
21246       int i, len = TREE_VEC_LENGTH (tparms);
21247       location_t loc = input_location;
21248       incomplete = false;
21249 
21250       if (explicit_targs == error_mark_node)
21251 	goto fail;
21252 
21253       if (TMPL_ARGS_DEPTH (explicit_targs)
21254 	  < TMPL_ARGS_DEPTH (full_targs))
21255 	explicit_targs = add_outermost_template_args (full_targs,
21256 						      explicit_targs);
21257 
21258       /* Adjust any explicit template arguments before entering the
21259 	 substitution context.  */
21260       explicit_targs
21261 	= (coerce_template_parms (tparms, explicit_targs, NULL_TREE,
21262 				  complain|tf_partial,
21263 				  /*require_all_args=*/false,
21264 				  /*use_default_args=*/false));
21265       if (explicit_targs == error_mark_node)
21266 	goto fail;
21267 
21268       /* Substitute the explicit args into the function type.  This is
21269 	 necessary so that, for instance, explicitly declared function
21270 	 arguments can match null pointed constants.  If we were given
21271 	 an incomplete set of explicit args, we must not do semantic
21272 	 processing during substitution as we could create partial
21273 	 instantiations.  */
21274       for (i = 0; i < len; i++)
21275         {
21276           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
21277           bool parameter_pack = false;
21278 	  tree targ = TREE_VEC_ELT (explicit_targs, i);
21279 
21280           /* Dig out the actual parm.  */
21281           if (TREE_CODE (parm) == TYPE_DECL
21282               || TREE_CODE (parm) == TEMPLATE_DECL)
21283             {
21284               parm = TREE_TYPE (parm);
21285               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
21286             }
21287           else if (TREE_CODE (parm) == PARM_DECL)
21288             {
21289               parm = DECL_INITIAL (parm);
21290               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
21291             }
21292 
21293 	  if (targ == NULL_TREE)
21294 	    /* No explicit argument for this template parameter.  */
21295 	    incomplete = true;
21296 	  else if (parameter_pack && pack_deducible_p (parm, fn))
21297             {
21298               /* Mark the argument pack as "incomplete". We could
21299                  still deduce more arguments during unification.
21300 	         We remove this mark in type_unification_real.  */
21301 	      ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
21302 	      ARGUMENT_PACK_EXPLICIT_ARGS (targ)
21303 		= ARGUMENT_PACK_ARGS (targ);
21304 
21305               /* We have some incomplete argument packs.  */
21306               incomplete = true;
21307             }
21308         }
21309 
21310       if (incomplete)
21311 	{
21312 	  if (!push_tinst_level (fn, explicit_targs))
21313 	    {
21314 	      excessive_deduction_depth = true;
21315 	      goto fail;
21316 	    }
21317 	  ++processing_template_decl;
21318 	  input_location = DECL_SOURCE_LOCATION (fn);
21319 	  /* Ignore any access checks; we'll see them again in
21320 	     instantiate_template and they might have the wrong
21321 	     access path at this point.  */
21322 	  push_deferring_access_checks (dk_deferred);
21323 	  tsubst_flags_t ecomplain = complain | tf_partial | tf_fndecl_type;
21324 	  fntype = tsubst (TREE_TYPE (fn), explicit_targs, ecomplain, NULL_TREE);
21325 	  pop_deferring_access_checks ();
21326 	  input_location = loc;
21327 	  --processing_template_decl;
21328 	  pop_tinst_level ();
21329 
21330 	  if (fntype == error_mark_node)
21331 	    goto fail;
21332 	}
21333 
21334       /* Place the explicitly specified arguments in TARGS.  */
21335       explicit_targs = INNERMOST_TEMPLATE_ARGS (explicit_targs);
21336       for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
21337 	TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
21338       if (!incomplete && CHECKING_P
21339 	  && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
21340 	SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
21341 	  (targs, NUM_TMPL_ARGS (explicit_targs));
21342     }
21343 
21344   if (return_type && strict != DEDUCE_CALL)
21345     {
21346       tree *new_args = XALLOCAVEC (tree, nargs + 1);
21347       new_args[0] = return_type;
21348       memcpy (new_args + 1, args, nargs * sizeof (tree));
21349       args = new_args;
21350       ++nargs;
21351     }
21352 
21353   if (!incomplete)
21354     goto deduced;
21355 
21356   /* Never do unification on the 'this' parameter.  */
21357   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
21358 
21359   if (return_type && strict == DEDUCE_CALL)
21360     {
21361       /* We're deducing for a call to the result of a template conversion
21362          function.  The parms we really want are in return_type.  */
21363       if (INDIRECT_TYPE_P (return_type))
21364 	return_type = TREE_TYPE (return_type);
21365       parms = TYPE_ARG_TYPES (return_type);
21366     }
21367   else if (return_type)
21368     {
21369       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
21370     }
21371 
21372   /* We allow incomplete unification without an error message here
21373      because the standard doesn't seem to explicitly prohibit it.  Our
21374      callers must be ready to deal with unification failures in any
21375      event.  */
21376 
21377   /* If we aren't explaining yet, push tinst context so we can see where
21378      any errors (e.g. from class instantiations triggered by instantiation
21379      of default template arguments) come from.  If we are explaining, this
21380      context is redundant.  */
21381   if (!explain_p && !push_tinst_level (fn, targs))
21382     {
21383       excessive_deduction_depth = true;
21384       goto fail;
21385     }
21386 
21387   ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
21388 			       full_targs, parms, args, nargs, /*subr=*/0,
21389 			       strict, &checks, explain_p);
21390   if (!explain_p)
21391     pop_tinst_level ();
21392   if (!ok)
21393     goto fail;
21394 
21395   /* Now that we have bindings for all of the template arguments,
21396      ensure that the arguments deduced for the template template
21397      parameters have compatible template parameter lists.  We cannot
21398      check this property before we have deduced all template
21399      arguments, because the template parameter types of a template
21400      template parameter might depend on prior template parameters
21401      deduced after the template template parameter.  The following
21402      ill-formed example illustrates this issue:
21403 
21404        template<typename T, template<T> class C> void f(C<5>, T);
21405 
21406        template<int N> struct X {};
21407 
21408        void g() {
21409          f(X<5>(), 5l); // error: template argument deduction fails
21410        }
21411 
21412      The template parameter list of 'C' depends on the template type
21413      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
21414      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
21415      time that we deduce 'C'.  */
21416   if (!template_template_parm_bindings_ok_p
21417            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
21418     {
21419       unify_inconsistent_template_template_parameters (explain_p);
21420       goto fail;
21421     }
21422 
21423   /* DR 1391: All parameters have args, now check non-dependent parms for
21424      convertibility.  */
21425   if (check_non_deducible_conversions (parms, args, nargs, fn, strict, flags,
21426 				       convs, explain_p))
21427     goto fail;
21428 
21429  deduced:
21430   /* All is well so far.  Now, check:
21431 
21432      [temp.deduct]
21433 
21434      When all template arguments have been deduced, all uses of
21435      template parameters in nondeduced contexts are replaced with
21436      the corresponding deduced argument values.  If the
21437      substitution results in an invalid type, as described above,
21438      type deduction fails.  */
21439   if (!push_tinst_level (fn, targs))
21440     {
21441       excessive_deduction_depth = true;
21442       goto fail;
21443     }
21444 
21445   /* Also collect access checks from the instantiation.  */
21446   reopen_deferring_access_checks (checks);
21447 
21448   decl = instantiate_template (fn, targs, complain);
21449 
21450   checks = get_deferred_access_checks ();
21451   pop_deferring_access_checks ();
21452 
21453   pop_tinst_level ();
21454 
21455   if (decl == error_mark_node)
21456     goto fail;
21457 
21458   /* Now perform any access checks encountered during substitution.  */
21459   push_access_scope (decl);
21460   ok = perform_access_checks (checks, complain);
21461   pop_access_scope (decl);
21462   if (!ok)
21463     goto fail;
21464 
21465   /* If we're looking for an exact match, check that what we got
21466      is indeed an exact match.  It might not be if some template
21467      parameters are used in non-deduced contexts.  But don't check
21468      for an exact match if we have dependent template arguments;
21469      in that case we're doing partial ordering, and we already know
21470      that we have two candidates that will provide the actual type.  */
21471   if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
21472     {
21473       tree substed = TREE_TYPE (decl);
21474       unsigned int i;
21475 
21476       tree sarg
21477 	= skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
21478       if (return_type)
21479 	sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
21480       for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
21481 	if (!same_type_p (args[i], TREE_VALUE (sarg)))
21482 	  {
21483 	    unify_type_mismatch (explain_p, args[i],
21484 				 TREE_VALUE (sarg));
21485 	    goto fail;
21486 	  }
21487     }
21488 
21489   /* After doing deduction with the inherited constructor, actually return an
21490      instantiation of the inheriting constructor.  */
21491   if (orig_fn != fn)
21492     decl = instantiate_template (orig_fn, targs, complain);
21493 
21494   r = decl;
21495 
21496  fail:
21497   --deduction_depth;
21498   if (excessive_deduction_depth)
21499     {
21500       if (deduction_depth == 0)
21501 	/* Reset once we're all the way out.  */
21502 	excessive_deduction_depth = false;
21503     }
21504 
21505   return r;
21506 }
21507 
21508 /* Adjust types before performing type deduction, as described in
21509    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
21510    sections are symmetric.  PARM is the type of a function parameter
21511    or the return type of the conversion function.  ARG is the type of
21512    the argument passed to the call, or the type of the value
21513    initialized with the result of the conversion function.
21514    ARG_EXPR is the original argument expression, which may be null.  */
21515 
21516 static int
maybe_adjust_types_for_deduction(unification_kind_t strict,tree * parm,tree * arg,tree arg_expr)21517 maybe_adjust_types_for_deduction (unification_kind_t strict,
21518 				  tree* parm,
21519 				  tree* arg,
21520 				  tree arg_expr)
21521 {
21522   int result = 0;
21523 
21524   switch (strict)
21525     {
21526     case DEDUCE_CALL:
21527       break;
21528 
21529     case DEDUCE_CONV:
21530       /* Swap PARM and ARG throughout the remainder of this
21531 	 function; the handling is precisely symmetric since PARM
21532 	 will initialize ARG rather than vice versa.  */
21533       std::swap (parm, arg);
21534       break;
21535 
21536     case DEDUCE_EXACT:
21537       /* Core issue #873: Do the DR606 thing (see below) for these cases,
21538 	 too, but here handle it by stripping the reference from PARM
21539 	 rather than by adding it to ARG.  */
21540       if (TYPE_REF_P (*parm)
21541 	  && TYPE_REF_IS_RVALUE (*parm)
21542 	  && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
21543 	  && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
21544 	  && TYPE_REF_P (*arg)
21545 	  && !TYPE_REF_IS_RVALUE (*arg))
21546 	*parm = TREE_TYPE (*parm);
21547       /* Nothing else to do in this case.  */
21548       return 0;
21549 
21550     default:
21551       gcc_unreachable ();
21552     }
21553 
21554   if (!TYPE_REF_P (*parm))
21555     {
21556       /* [temp.deduct.call]
21557 
21558 	 If P is not a reference type:
21559 
21560 	 --If A is an array type, the pointer type produced by the
21561 	 array-to-pointer standard conversion (_conv.array_) is
21562 	 used in place of A for type deduction; otherwise,
21563 
21564 	 --If A is a function type, the pointer type produced by
21565 	 the function-to-pointer standard conversion
21566 	 (_conv.func_) is used in place of A for type deduction;
21567 	 otherwise,
21568 
21569 	 --If A is a cv-qualified type, the top level
21570 	 cv-qualifiers of A's type are ignored for type
21571 	 deduction.  */
21572       if (TREE_CODE (*arg) == ARRAY_TYPE)
21573 	*arg = build_pointer_type (TREE_TYPE (*arg));
21574       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
21575 	*arg = build_pointer_type (*arg);
21576       else
21577 	*arg = TYPE_MAIN_VARIANT (*arg);
21578     }
21579 
21580   /* [14.8.2.1/3 temp.deduct.call], "A forwarding reference is an rvalue
21581      reference to a cv-unqualified template parameter that does not represent a
21582      template parameter of a class template (during class template argument
21583      deduction (13.3.1.8)). If P is a forwarding reference and the argument is
21584      an lvalue, the type "lvalue reference to A" is used in place of A for type
21585      deduction. */
21586   if (TYPE_REF_P (*parm)
21587       && TYPE_REF_IS_RVALUE (*parm)
21588       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
21589       && !TEMPLATE_TYPE_PARM_FOR_CLASS (TREE_TYPE (*parm))
21590       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
21591       && (arg_expr ? lvalue_p (arg_expr)
21592 	  /* try_one_overload doesn't provide an arg_expr, but
21593 	     functions are always lvalues.  */
21594 	  : TREE_CODE (*arg) == FUNCTION_TYPE))
21595     *arg = build_reference_type (*arg);
21596 
21597   /* [temp.deduct.call]
21598 
21599      If P is a cv-qualified type, the top level cv-qualifiers
21600      of P's type are ignored for type deduction.  If P is a
21601      reference type, the type referred to by P is used for
21602      type deduction.  */
21603   *parm = TYPE_MAIN_VARIANT (*parm);
21604   if (TYPE_REF_P (*parm))
21605     {
21606       *parm = TREE_TYPE (*parm);
21607       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
21608     }
21609 
21610   /* DR 322. For conversion deduction, remove a reference type on parm
21611      too (which has been swapped into ARG).  */
21612   if (strict == DEDUCE_CONV && TYPE_REF_P (*arg))
21613     *arg = TREE_TYPE (*arg);
21614 
21615   return result;
21616 }
21617 
21618 /* Subroutine of fn_type_unification.  PARM is a function parameter of a
21619    template which doesn't contain any deducible template parameters; check if
21620    ARG is a suitable match for it.  STRICT, FLAGS and EXPLAIN_P are as in
21621    unify_one_argument.  */
21622 
21623 static int
check_non_deducible_conversion(tree parm,tree arg,int strict,int flags,struct conversion ** conv_p,bool explain_p)21624 check_non_deducible_conversion (tree parm, tree arg, int strict,
21625 				int flags, struct conversion **conv_p,
21626 				bool explain_p)
21627 {
21628   tree type;
21629 
21630   if (!TYPE_P (arg))
21631     type = TREE_TYPE (arg);
21632   else
21633     type = arg;
21634 
21635   if (same_type_p (parm, type))
21636     return unify_success (explain_p);
21637 
21638   tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
21639   if (strict == DEDUCE_CONV)
21640     {
21641       if (can_convert_arg (type, parm, NULL_TREE, flags, complain))
21642 	return unify_success (explain_p);
21643     }
21644   else if (strict != DEDUCE_EXACT)
21645     {
21646       bool ok = false;
21647       tree conv_arg = TYPE_P (arg) ? NULL_TREE : arg;
21648       if (conv_p)
21649 	/* Avoid recalculating this in add_function_candidate.  */
21650 	ok = (*conv_p
21651 	      = good_conversion (parm, type, conv_arg, flags, complain));
21652       else
21653 	ok = can_convert_arg (parm, type, conv_arg, flags, complain);
21654       if (ok)
21655 	return unify_success (explain_p);
21656     }
21657 
21658   if (strict == DEDUCE_EXACT)
21659     return unify_type_mismatch (explain_p, parm, arg);
21660   else
21661     return unify_arg_conversion (explain_p, parm, type, arg);
21662 }
21663 
21664 static bool uses_deducible_template_parms (tree type);
21665 
21666 /* Returns true iff the expression EXPR is one from which a template
21667    argument can be deduced.  In other words, if it's an undecorated
21668    use of a template non-type parameter.  */
21669 
21670 static bool
deducible_expression(tree expr)21671 deducible_expression (tree expr)
21672 {
21673   /* Strip implicit conversions.  */
21674   while (CONVERT_EXPR_P (expr) || TREE_CODE (expr) == VIEW_CONVERT_EXPR)
21675     expr = TREE_OPERAND (expr, 0);
21676   return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
21677 }
21678 
21679 /* Returns true iff the array domain DOMAIN uses a template parameter in a
21680    deducible way; that is, if it has a max value of <PARM> - 1.  */
21681 
21682 static bool
deducible_array_bound(tree domain)21683 deducible_array_bound (tree domain)
21684 {
21685   if (domain == NULL_TREE)
21686     return false;
21687 
21688   tree max = TYPE_MAX_VALUE (domain);
21689   if (TREE_CODE (max) != MINUS_EXPR)
21690     return false;
21691 
21692   return deducible_expression (TREE_OPERAND (max, 0));
21693 }
21694 
21695 /* Returns true iff the template arguments ARGS use a template parameter
21696    in a deducible way.  */
21697 
21698 static bool
deducible_template_args(tree args)21699 deducible_template_args (tree args)
21700 {
21701   for (int i = 0; i < TREE_VEC_LENGTH (args); ++i)
21702     {
21703       bool deducible;
21704       tree elt = TREE_VEC_ELT (args, i);
21705       if (ARGUMENT_PACK_P (elt))
21706 	deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
21707       else
21708 	{
21709 	  if (PACK_EXPANSION_P (elt))
21710 	    elt = PACK_EXPANSION_PATTERN (elt);
21711 	  if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
21712 	    deducible = true;
21713 	  else if (TYPE_P (elt))
21714 	    deducible = uses_deducible_template_parms (elt);
21715 	  else
21716 	    deducible = deducible_expression (elt);
21717 	}
21718       if (deducible)
21719 	return true;
21720     }
21721   return false;
21722 }
21723 
21724 /* Returns true iff TYPE contains any deducible references to template
21725    parameters, as per 14.8.2.5.  */
21726 
21727 static bool
uses_deducible_template_parms(tree type)21728 uses_deducible_template_parms (tree type)
21729 {
21730   if (PACK_EXPANSION_P (type))
21731     type = PACK_EXPANSION_PATTERN (type);
21732 
21733   /* T
21734      cv-list T
21735      TT<T>
21736      TT<i>
21737      TT<> */
21738   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
21739       || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
21740     return true;
21741 
21742   /* T*
21743      T&
21744      T&&  */
21745   if (INDIRECT_TYPE_P (type))
21746     return uses_deducible_template_parms (TREE_TYPE (type));
21747 
21748   /* T[integer-constant ]
21749      type [i]  */
21750   if (TREE_CODE (type) == ARRAY_TYPE)
21751     return (uses_deducible_template_parms (TREE_TYPE (type))
21752 	    || deducible_array_bound (TYPE_DOMAIN (type)));
21753 
21754   /* T type ::*
21755      type T::*
21756      T T::*
21757      T (type ::*)()
21758      type (T::*)()
21759      type (type ::*)(T)
21760      type (T::*)(T)
21761      T (type ::*)(T)
21762      T (T::*)()
21763      T (T::*)(T) */
21764   if (TYPE_PTRMEM_P (type))
21765     return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
21766 	    || (uses_deducible_template_parms
21767 		(TYPE_PTRMEM_POINTED_TO_TYPE (type))));
21768 
21769   /* template-name <T> (where template-name refers to a class template)
21770      template-name <i> (where template-name refers to a class template) */
21771   if (CLASS_TYPE_P (type)
21772       && CLASSTYPE_TEMPLATE_INFO (type)
21773       && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
21774     return deducible_template_args (INNERMOST_TEMPLATE_ARGS
21775 				    (CLASSTYPE_TI_ARGS (type)));
21776 
21777   /* type (T)
21778      T()
21779      T(T)  */
21780   if (FUNC_OR_METHOD_TYPE_P (type))
21781     {
21782       if (uses_deducible_template_parms (TREE_TYPE (type)))
21783 	return true;
21784       tree parm = TYPE_ARG_TYPES (type);
21785       if (TREE_CODE (type) == METHOD_TYPE)
21786 	parm = TREE_CHAIN (parm);
21787       for (; parm; parm = TREE_CHAIN (parm))
21788 	if (uses_deducible_template_parms (TREE_VALUE (parm)))
21789 	  return true;
21790     }
21791 
21792   return false;
21793 }
21794 
21795 /* Subroutine of type_unification_real and unify_pack_expansion to
21796    handle unification of a single P/A pair.  Parameters are as
21797    for those functions.  */
21798 
21799 static int
unify_one_argument(tree tparms,tree targs,tree parm,tree arg,int subr,unification_kind_t strict,bool explain_p)21800 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
21801 		    int subr, unification_kind_t strict,
21802 		    bool explain_p)
21803 {
21804   tree arg_expr = NULL_TREE;
21805   int arg_strict;
21806 
21807   if (arg == error_mark_node || parm == error_mark_node)
21808     return unify_invalid (explain_p);
21809   if (arg == unknown_type_node)
21810     /* We can't deduce anything from this, but we might get all the
21811        template args from other function args.  */
21812     return unify_success (explain_p);
21813 
21814   /* Implicit conversions (Clause 4) will be performed on a function
21815      argument to convert it to the type of the corresponding function
21816      parameter if the parameter type contains no template-parameters that
21817      participate in template argument deduction.  */
21818   if (strict != DEDUCE_EXACT
21819       && TYPE_P (parm) && !uses_deducible_template_parms (parm))
21820     /* For function parameters with no deducible template parameters,
21821        just return.  We'll check non-dependent conversions later.  */
21822     return unify_success (explain_p);
21823 
21824   switch (strict)
21825     {
21826     case DEDUCE_CALL:
21827       arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
21828 		    | UNIFY_ALLOW_MORE_CV_QUAL
21829 		    | UNIFY_ALLOW_DERIVED);
21830       break;
21831 
21832     case DEDUCE_CONV:
21833       arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
21834       break;
21835 
21836     case DEDUCE_EXACT:
21837       arg_strict = UNIFY_ALLOW_NONE;
21838       break;
21839 
21840     default:
21841       gcc_unreachable ();
21842     }
21843 
21844   /* We only do these transformations if this is the top-level
21845      parameter_type_list in a call or declaration matching; in other
21846      situations (nested function declarators, template argument lists) we
21847      won't be comparing a type to an expression, and we don't do any type
21848      adjustments.  */
21849   if (!subr)
21850     {
21851       if (!TYPE_P (arg))
21852 	{
21853 	  gcc_assert (TREE_TYPE (arg) != NULL_TREE);
21854 	  if (type_unknown_p (arg))
21855 	    {
21856 	      /* [temp.deduct.type] A template-argument can be
21857 		 deduced from a pointer to function or pointer
21858 		 to member function argument if the set of
21859 		 overloaded functions does not contain function
21860 		 templates and at most one of a set of
21861 		 overloaded functions provides a unique
21862 		 match.  */
21863 	      resolve_overloaded_unification (tparms, targs, parm,
21864 					      arg, strict,
21865 					      arg_strict, explain_p);
21866 	      /* If a unique match was not found, this is a
21867 	         non-deduced context, so we still succeed. */
21868 	      return unify_success (explain_p);
21869 	    }
21870 
21871 	  arg_expr = arg;
21872 	  arg = unlowered_expr_type (arg);
21873 	  if (arg == error_mark_node)
21874 	    return unify_invalid (explain_p);
21875 	}
21876 
21877       arg_strict |=
21878 	maybe_adjust_types_for_deduction (strict, &parm, &arg, arg_expr);
21879     }
21880   else
21881     if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
21882 	!= (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
21883       return unify_template_argument_mismatch (explain_p, parm, arg);
21884 
21885   /* For deduction from an init-list we need the actual list.  */
21886   if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
21887     arg = arg_expr;
21888   return unify (tparms, targs, parm, arg, arg_strict, explain_p);
21889 }
21890 
21891 /* for_each_template_parm callback that always returns 0.  */
21892 
21893 static int
zero_r(tree,void *)21894 zero_r (tree, void *)
21895 {
21896   return 0;
21897 }
21898 
21899 /* for_each_template_parm any_fn callback to handle deduction of a template
21900    type argument from the type of an array bound.  */
21901 
21902 static int
array_deduction_r(tree t,void * data)21903 array_deduction_r (tree t, void *data)
21904 {
21905   tree_pair_p d = (tree_pair_p)data;
21906   tree &tparms = d->purpose;
21907   tree &targs = d->value;
21908 
21909   if (TREE_CODE (t) == ARRAY_TYPE)
21910     if (tree dom = TYPE_DOMAIN (t))
21911       if (tree max = TYPE_MAX_VALUE (dom))
21912 	{
21913 	  if (TREE_CODE (max) == MINUS_EXPR)
21914 	    max = TREE_OPERAND (max, 0);
21915 	  if (TREE_CODE (max) == TEMPLATE_PARM_INDEX)
21916 	    unify (tparms, targs, TREE_TYPE (max), size_type_node,
21917 		   UNIFY_ALLOW_NONE, /*explain*/false);
21918 	}
21919 
21920   /* Keep walking.  */
21921   return 0;
21922 }
21923 
21924 /* Try to deduce any not-yet-deduced template type arguments from the type of
21925    an array bound.  This is handled separately from unify because 14.8.2.5 says
21926    "The type of a type parameter is only deduced from an array bound if it is
21927    not otherwise deduced."  */
21928 
21929 static void
try_array_deduction(tree tparms,tree targs,tree parm)21930 try_array_deduction (tree tparms, tree targs, tree parm)
21931 {
21932   tree_pair_s data = { tparms, targs };
21933   hash_set<tree> visited;
21934   for_each_template_parm (parm, zero_r, &data, &visited,
21935 			  /*nondeduced*/false, array_deduction_r);
21936 }
21937 
21938 /* Most parms like fn_type_unification.
21939 
21940    If SUBR is 1, we're being called recursively (to unify the
21941    arguments of a function or method parameter of a function
21942    template).
21943 
21944    CHECKS is a pointer to a vector of access checks encountered while
21945    substituting default template arguments.  */
21946 
21947 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)21948 type_unification_real (tree tparms,
21949 		       tree full_targs,
21950 		       tree xparms,
21951 		       const tree *xargs,
21952 		       unsigned int xnargs,
21953 		       int subr,
21954 		       unification_kind_t strict,
21955 		       vec<deferred_access_check, va_gc> **checks,
21956 		       bool explain_p)
21957 {
21958   tree parm, arg;
21959   int i;
21960   int ntparms = TREE_VEC_LENGTH (tparms);
21961   int saw_undeduced = 0;
21962   tree parms;
21963   const tree *args;
21964   unsigned int nargs;
21965   unsigned int ia;
21966 
21967   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
21968   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
21969   gcc_assert (ntparms > 0);
21970 
21971   tree targs = INNERMOST_TEMPLATE_ARGS (full_targs);
21972 
21973   /* Reset the number of non-defaulted template arguments contained
21974      in TARGS.  */
21975   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
21976 
21977  again:
21978   parms = xparms;
21979   args = xargs;
21980   nargs = xnargs;
21981 
21982   ia = 0;
21983   while (parms && parms != void_list_node
21984 	 && ia < nargs)
21985     {
21986       parm = TREE_VALUE (parms);
21987 
21988       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
21989 	  && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
21990 	/* For a function parameter pack that occurs at the end of the
21991 	   parameter-declaration-list, the type A of each remaining
21992 	   argument of the call is compared with the type P of the
21993 	   declarator-id of the function parameter pack.  */
21994 	break;
21995 
21996       parms = TREE_CHAIN (parms);
21997 
21998       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
21999 	/* For a function parameter pack that does not occur at the
22000 	   end of the parameter-declaration-list, the type of the
22001 	   parameter pack is a non-deduced context.  */
22002 	continue;
22003 
22004       arg = args[ia];
22005       ++ia;
22006 
22007       if (unify_one_argument (tparms, full_targs, parm, arg, subr, strict,
22008 			      explain_p))
22009 	return 1;
22010     }
22011 
22012   if (parms
22013       && parms != void_list_node
22014       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
22015     {
22016       /* Unify the remaining arguments with the pack expansion type.  */
22017       tree argvec;
22018       tree parmvec = make_tree_vec (1);
22019 
22020       /* Allocate a TREE_VEC and copy in all of the arguments */
22021       argvec = make_tree_vec (nargs - ia);
22022       for (i = 0; ia < nargs; ++ia, ++i)
22023 	TREE_VEC_ELT (argvec, i) = args[ia];
22024 
22025       /* Copy the parameter into parmvec.  */
22026       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
22027       if (unify_pack_expansion (tparms, full_targs, parmvec, argvec, strict,
22028                                 /*subr=*/subr, explain_p))
22029         return 1;
22030 
22031       /* Advance to the end of the list of parameters.  */
22032       parms = TREE_CHAIN (parms);
22033     }
22034 
22035   /* Fail if we've reached the end of the parm list, and more args
22036      are present, and the parm list isn't variadic.  */
22037   if (ia < nargs && parms == void_list_node)
22038     return unify_too_many_arguments (explain_p, nargs, ia);
22039   /* Fail if parms are left and they don't have default values and
22040      they aren't all deduced as empty packs (c++/57397).  This is
22041      consistent with sufficient_parms_p.  */
22042   if (parms && parms != void_list_node
22043       && TREE_PURPOSE (parms) == NULL_TREE)
22044     {
22045       unsigned int count = nargs;
22046       tree p = parms;
22047       bool type_pack_p;
22048       do
22049 	{
22050 	  type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
22051 	  if (!type_pack_p)
22052 	    count++;
22053 	  p = TREE_CHAIN (p);
22054 	}
22055       while (p && p != void_list_node);
22056       if (count != nargs)
22057 	return unify_too_few_arguments (explain_p, ia, count,
22058 					type_pack_p);
22059     }
22060 
22061   if (!subr)
22062     {
22063       tsubst_flags_t complain = (explain_p
22064 				 ? tf_warning_or_error
22065 				 : tf_none);
22066       bool tried_array_deduction = (cxx_dialect < cxx17);
22067 
22068       for (i = 0; i < ntparms; i++)
22069 	{
22070 	  tree targ = TREE_VEC_ELT (targs, i);
22071 	  tree tparm = TREE_VEC_ELT (tparms, i);
22072 
22073 	  /* Clear the "incomplete" flags on all argument packs now so that
22074 	     substituting them into later default arguments works.  */
22075 	  if (targ && ARGUMENT_PACK_P (targ))
22076             {
22077               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
22078               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
22079             }
22080 
22081 	  if (targ || tparm == error_mark_node)
22082 	    continue;
22083 	  tparm = TREE_VALUE (tparm);
22084 
22085 	  if (TREE_CODE (tparm) == TYPE_DECL
22086 	      && !tried_array_deduction)
22087 	    {
22088 	      try_array_deduction (tparms, targs, xparms);
22089 	      tried_array_deduction = true;
22090 	      if (TREE_VEC_ELT (targs, i))
22091 		continue;
22092 	    }
22093 
22094 	  /* If this is an undeduced nontype parameter that depends on
22095 	     a type parameter, try another pass; its type may have been
22096 	     deduced from a later argument than the one from which
22097 	     this parameter can be deduced.  */
22098 	  if (TREE_CODE (tparm) == PARM_DECL
22099 	      && uses_template_parms (TREE_TYPE (tparm))
22100 	      && saw_undeduced < 2)
22101 	    {
22102 	      saw_undeduced = 1;
22103 	      continue;
22104 	    }
22105 
22106 	  /* Core issue #226 (C++0x) [temp.deduct]:
22107 
22108 	     If a template argument has not been deduced, its
22109 	     default template argument, if any, is used.
22110 
22111 	     When we are in C++98 mode, TREE_PURPOSE will either
22112 	     be NULL_TREE or ERROR_MARK_NODE, so we do not need
22113 	     to explicitly check cxx_dialect here.  */
22114 	  if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
22115 	    /* OK, there is a default argument.  Wait until after the
22116 	       conversion check to do substitution.  */
22117 	    continue;
22118 
22119 	  /* If the type parameter is a parameter pack, then it will
22120 	     be deduced to an empty parameter pack.  */
22121 	  if (template_parameter_pack_p (tparm))
22122 	    {
22123 	      tree arg;
22124 
22125 	      if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
22126 		{
22127 		  arg = make_node (NONTYPE_ARGUMENT_PACK);
22128 		  TREE_CONSTANT (arg) = 1;
22129 		}
22130 	      else
22131 		arg = cxx_make_type (TYPE_ARGUMENT_PACK);
22132 
22133 	      SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
22134 
22135 	      TREE_VEC_ELT (targs, i) = arg;
22136 	      continue;
22137 	    }
22138 
22139 	  return unify_parameter_deduction_failure (explain_p, tparm);
22140 	}
22141 
22142       /* Now substitute into the default template arguments.  */
22143       for (i = 0; i < ntparms; i++)
22144 	{
22145 	  tree targ = TREE_VEC_ELT (targs, i);
22146 	  tree tparm = TREE_VEC_ELT (tparms, i);
22147 
22148 	  if (targ || tparm == error_mark_node)
22149 	    continue;
22150 	  tree parm = TREE_VALUE (tparm);
22151 	  tree arg = TREE_PURPOSE (tparm);
22152 	  reopen_deferring_access_checks (*checks);
22153 	  location_t save_loc = input_location;
22154 	  if (DECL_P (parm))
22155 	    input_location = DECL_SOURCE_LOCATION (parm);
22156 
22157 	  if (saw_undeduced == 1
22158 	      && TREE_CODE (parm) == PARM_DECL
22159 	      && uses_template_parms (TREE_TYPE (parm)))
22160 	    {
22161 	      /* The type of this non-type parameter depends on undeduced
22162 		 parameters.  Don't try to use its default argument yet,
22163 		 since we might deduce an argument for it on the next pass,
22164 		 but do check whether the arguments we already have cause
22165 		 substitution failure, so that that happens before we try
22166 		 later default arguments (78489).  */
22167 	      ++processing_template_decl;
22168 	      tree type = tsubst (TREE_TYPE (parm), full_targs, complain,
22169 				  NULL_TREE);
22170 	      --processing_template_decl;
22171 	      if (type == error_mark_node)
22172 		arg = error_mark_node;
22173 	      else
22174 		arg = NULL_TREE;
22175 	    }
22176 	  else
22177 	    {
22178 	      /* Even if the call is happening in template context, getting
22179 		 here means it's non-dependent, and a default argument is
22180 		 considered a separate definition under [temp.decls], so we can
22181 		 do this substitution without processing_template_decl.  This
22182 		 is important if the default argument contains something that
22183 		 might be instantiation-dependent like access (87480).  */
22184 	      processing_template_decl_sentinel s;
22185 	      tree substed = NULL_TREE;
22186 	      if (saw_undeduced == 1)
22187 		{
22188 		  /* First instatiate in template context, in case we still
22189 		     depend on undeduced template parameters.  */
22190 		  ++processing_template_decl;
22191 		  substed = tsubst_template_arg (arg, full_targs, complain,
22192 						 NULL_TREE);
22193 		  --processing_template_decl;
22194 		  if (substed != error_mark_node
22195 		      && !uses_template_parms (substed))
22196 		    /* We replaced all the tparms, substitute again out of
22197 		       template context.  */
22198 		    substed = NULL_TREE;
22199 		}
22200 	      if (!substed)
22201 		substed = tsubst_template_arg (arg, full_targs, complain,
22202 					       NULL_TREE);
22203 
22204 	      if (!uses_template_parms (substed))
22205 		arg = convert_template_argument (parm, substed, full_targs,
22206 						 complain, i, NULL_TREE);
22207 	      else if (saw_undeduced == 1)
22208 		arg = NULL_TREE;
22209 	      else
22210 		arg = error_mark_node;
22211 	    }
22212 
22213 	  input_location = save_loc;
22214 	  *checks = get_deferred_access_checks ();
22215 	  pop_deferring_access_checks ();
22216 
22217 	  if (arg == error_mark_node)
22218 	    return 1;
22219 	  else if (arg)
22220 	    {
22221 	      TREE_VEC_ELT (targs, i) = arg;
22222 	      /* The position of the first default template argument,
22223 		 is also the number of non-defaulted arguments in TARGS.
22224 		 Record that.  */
22225 	      if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
22226 		SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
22227 	    }
22228 	}
22229 
22230       if (saw_undeduced++ == 1)
22231 	goto again;
22232     }
22233 
22234   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
22235     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
22236 
22237   return unify_success (explain_p);
22238 }
22239 
22240 /* Subroutine of type_unification_real.  Args are like the variables
22241    at the call site.  ARG is an overloaded function (or template-id);
22242    we try deducing template args from each of the overloads, and if
22243    only one succeeds, we go with that.  Modifies TARGS and returns
22244    true on success.  */
22245 
22246 static bool
resolve_overloaded_unification(tree tparms,tree targs,tree parm,tree arg,unification_kind_t strict,int sub_strict,bool explain_p)22247 resolve_overloaded_unification (tree tparms,
22248 				tree targs,
22249 				tree parm,
22250 				tree arg,
22251 				unification_kind_t strict,
22252 				int sub_strict,
22253 			        bool explain_p)
22254 {
22255   tree tempargs = copy_node (targs);
22256   int good = 0;
22257   tree goodfn = NULL_TREE;
22258   bool addr_p;
22259 
22260   if (TREE_CODE (arg) == ADDR_EXPR)
22261     {
22262       arg = TREE_OPERAND (arg, 0);
22263       addr_p = true;
22264     }
22265   else
22266     addr_p = false;
22267 
22268   if (TREE_CODE (arg) == COMPONENT_REF)
22269     /* Handle `&x' where `x' is some static or non-static member
22270        function name.  */
22271     arg = TREE_OPERAND (arg, 1);
22272 
22273   if (TREE_CODE (arg) == OFFSET_REF)
22274     arg = TREE_OPERAND (arg, 1);
22275 
22276   /* Strip baselink information.  */
22277   if (BASELINK_P (arg))
22278     arg = BASELINK_FUNCTIONS (arg);
22279 
22280   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
22281     {
22282       /* If we got some explicit template args, we need to plug them into
22283 	 the affected templates before we try to unify, in case the
22284 	 explicit args will completely resolve the templates in question.  */
22285 
22286       int ok = 0;
22287       tree expl_subargs = TREE_OPERAND (arg, 1);
22288       arg = TREE_OPERAND (arg, 0);
22289 
22290       for (lkp_iterator iter (arg); iter; ++iter)
22291 	{
22292 	  tree fn = *iter;
22293 	  tree subargs, elem;
22294 
22295 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
22296 	    continue;
22297 
22298 	  subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
22299 					   expl_subargs, NULL_TREE, tf_none,
22300 					   /*require_all_args=*/true,
22301 					   /*use_default_args=*/true);
22302 	  if (subargs != error_mark_node
22303 	      && !any_dependent_template_arguments_p (subargs))
22304 	    {
22305 	      fn = instantiate_template (fn, subargs, tf_none);
22306 	      if (!constraints_satisfied_p (fn))
22307 		continue;
22308 	      if (undeduced_auto_decl (fn))
22309 		{
22310 		  /* Instantiate the function to deduce its return type.  */
22311 		  ++function_depth;
22312 		  instantiate_decl (fn, /*defer*/false, /*class*/false);
22313 		  --function_depth;
22314 		}
22315 
22316 	      if (flag_noexcept_type)
22317 		maybe_instantiate_noexcept (fn, tf_none);
22318 
22319 	      elem = TREE_TYPE (fn);
22320 	      if (try_one_overload (tparms, targs, tempargs, parm,
22321 				    elem, strict, sub_strict, addr_p, explain_p)
22322 		  && (!goodfn || !same_type_p (goodfn, elem)))
22323 		{
22324 		  goodfn = elem;
22325 		  ++good;
22326 		}
22327 	    }
22328 	  else if (subargs)
22329 	    ++ok;
22330 	}
22331       /* If no templates (or more than one) are fully resolved by the
22332 	 explicit arguments, this template-id is a non-deduced context; it
22333 	 could still be OK if we deduce all template arguments for the
22334 	 enclosing call through other arguments.  */
22335       if (good != 1)
22336 	good = ok;
22337     }
22338   else if (!OVL_P (arg))
22339     /* If ARG is, for example, "(0, &f)" then its type will be unknown
22340        -- but the deduction does not succeed because the expression is
22341        not just the function on its own.  */
22342     return false;
22343   else
22344     for (lkp_iterator iter (arg); iter; ++iter)
22345       {
22346 	tree fn = *iter;
22347 	if (try_one_overload (tparms, targs, tempargs, parm, TREE_TYPE (fn),
22348 			      strict, sub_strict, addr_p, explain_p)
22349 	    && (!goodfn || !decls_match (goodfn, fn)))
22350 	  {
22351 	    goodfn = fn;
22352 	    ++good;
22353 	  }
22354       }
22355 
22356   /* [temp.deduct.type] A template-argument can be deduced from a pointer
22357      to function or pointer to member function argument if the set of
22358      overloaded functions does not contain function templates and at most
22359      one of a set of overloaded functions provides a unique match.
22360 
22361      So if we found multiple possibilities, we return success but don't
22362      deduce anything.  */
22363 
22364   if (good == 1)
22365     {
22366       int i = TREE_VEC_LENGTH (targs);
22367       for (; i--; )
22368 	if (TREE_VEC_ELT (tempargs, i))
22369 	  {
22370 	    tree old = TREE_VEC_ELT (targs, i);
22371 	    tree new_ = TREE_VEC_ELT (tempargs, i);
22372 	    if (new_ && old && ARGUMENT_PACK_P (old)
22373 		&& ARGUMENT_PACK_EXPLICIT_ARGS (old))
22374 	      /* Don't forget explicit template arguments in a pack.  */
22375 	      ARGUMENT_PACK_EXPLICIT_ARGS (new_)
22376 		= ARGUMENT_PACK_EXPLICIT_ARGS (old);
22377 	    TREE_VEC_ELT (targs, i) = new_;
22378 	  }
22379     }
22380   if (good)
22381     return true;
22382 
22383   return false;
22384 }
22385 
22386 /* Core DR 115: In contexts where deduction is done and fails, or in
22387    contexts where deduction is not done, if a template argument list is
22388    specified and it, along with any default template arguments, identifies
22389    a single function template specialization, then the template-id is an
22390    lvalue for the function template specialization.  */
22391 
22392 tree
resolve_nondeduced_context(tree orig_expr,tsubst_flags_t complain)22393 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
22394 {
22395   tree expr, offset, baselink;
22396   bool addr;
22397 
22398   if (!type_unknown_p (orig_expr))
22399     return orig_expr;
22400 
22401   expr = orig_expr;
22402   addr = false;
22403   offset = NULL_TREE;
22404   baselink = NULL_TREE;
22405 
22406   if (TREE_CODE (expr) == ADDR_EXPR)
22407     {
22408       expr = TREE_OPERAND (expr, 0);
22409       addr = true;
22410     }
22411   if (TREE_CODE (expr) == OFFSET_REF)
22412     {
22413       offset = expr;
22414       expr = TREE_OPERAND (expr, 1);
22415     }
22416   if (BASELINK_P (expr))
22417     {
22418       baselink = expr;
22419       expr = BASELINK_FUNCTIONS (expr);
22420     }
22421 
22422   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
22423     {
22424       int good = 0;
22425       tree goodfn = NULL_TREE;
22426 
22427       /* If we got some explicit template args, we need to plug them into
22428 	 the affected templates before we try to unify, in case the
22429 	 explicit args will completely resolve the templates in question.  */
22430 
22431       tree expl_subargs = TREE_OPERAND (expr, 1);
22432       tree arg = TREE_OPERAND (expr, 0);
22433       tree badfn = NULL_TREE;
22434       tree badargs = NULL_TREE;
22435 
22436       for (lkp_iterator iter (arg); iter; ++iter)
22437 	{
22438 	  tree fn = *iter;
22439 	  tree subargs, elem;
22440 
22441 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
22442 	    continue;
22443 
22444 	  subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
22445 					   expl_subargs, NULL_TREE, tf_none,
22446 					   /*require_all_args=*/true,
22447 					   /*use_default_args=*/true);
22448 	  if (subargs != error_mark_node
22449 	      && !any_dependent_template_arguments_p (subargs))
22450 	    {
22451 	      elem = instantiate_template (fn, subargs, tf_none);
22452 	      if (elem == error_mark_node)
22453 		{
22454 		  badfn = fn;
22455 		  badargs = subargs;
22456 		}
22457 	      else if (elem && (!goodfn || !decls_match (goodfn, elem))
22458 		       && constraints_satisfied_p (elem))
22459 		{
22460 		  goodfn = elem;
22461 		  ++good;
22462 		}
22463 	    }
22464 	}
22465       if (good == 1)
22466 	{
22467 	  mark_used (goodfn);
22468 	  expr = goodfn;
22469 	  if (baselink)
22470 	    expr = build_baselink (BASELINK_BINFO (baselink),
22471 				   BASELINK_ACCESS_BINFO (baselink),
22472 				   expr, BASELINK_OPTYPE (baselink));
22473 	  if (offset)
22474 	    {
22475 	      tree base
22476 		= TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
22477 	      expr = build_offset_ref (base, expr, addr, complain);
22478 	    }
22479 	  if (addr)
22480 	    expr = cp_build_addr_expr (expr, complain);
22481 	  return expr;
22482 	}
22483       else if (good == 0 && badargs && (complain & tf_error))
22484 	/* There were no good options and at least one bad one, so let the
22485 	   user know what the problem is.  */
22486 	instantiate_template (badfn, badargs, complain);
22487     }
22488   return orig_expr;
22489 }
22490 
22491 /* As above, but error out if the expression remains overloaded.  */
22492 
22493 tree
resolve_nondeduced_context_or_error(tree exp,tsubst_flags_t complain)22494 resolve_nondeduced_context_or_error (tree exp, tsubst_flags_t complain)
22495 {
22496   exp = resolve_nondeduced_context (exp, complain);
22497   if (type_unknown_p (exp))
22498     {
22499       if (complain & tf_error)
22500 	cxx_incomplete_type_error (exp, TREE_TYPE (exp));
22501       return error_mark_node;
22502     }
22503   return exp;
22504 }
22505 
22506 /* Subroutine of resolve_overloaded_unification; does deduction for a single
22507    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
22508    different overloads deduce different arguments for a given parm.
22509    ADDR_P is true if the expression for which deduction is being
22510    performed was of the form "& fn" rather than simply "fn".
22511 
22512    Returns 1 on success.  */
22513 
22514 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)22515 try_one_overload (tree tparms,
22516 		  tree orig_targs,
22517 		  tree targs,
22518 		  tree parm,
22519 		  tree arg,
22520 		  unification_kind_t strict,
22521 		  int sub_strict,
22522 		  bool addr_p,
22523 		  bool explain_p)
22524 {
22525   int nargs;
22526   tree tempargs;
22527   int i;
22528 
22529   if (arg == error_mark_node)
22530     return 0;
22531 
22532   /* [temp.deduct.type] A template-argument can be deduced from a pointer
22533      to function or pointer to member function argument if the set of
22534      overloaded functions does not contain function templates and at most
22535      one of a set of overloaded functions provides a unique match.
22536 
22537      So if this is a template, just return success.  */
22538 
22539   if (uses_template_parms (arg))
22540     return 1;
22541 
22542   if (TREE_CODE (arg) == METHOD_TYPE)
22543     arg = build_ptrmemfunc_type (build_pointer_type (arg));
22544   else if (addr_p)
22545     arg = build_pointer_type (arg);
22546 
22547   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
22548 
22549   /* We don't copy orig_targs for this because if we have already deduced
22550      some template args from previous args, unify would complain when we
22551      try to deduce a template parameter for the same argument, even though
22552      there isn't really a conflict.  */
22553   nargs = TREE_VEC_LENGTH (targs);
22554   tempargs = make_tree_vec (nargs);
22555 
22556   if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
22557     return 0;
22558 
22559   /* First make sure we didn't deduce anything that conflicts with
22560      explicitly specified args.  */
22561   for (i = nargs; i--; )
22562     {
22563       tree elt = TREE_VEC_ELT (tempargs, i);
22564       tree oldelt = TREE_VEC_ELT (orig_targs, i);
22565 
22566       if (!elt)
22567 	/*NOP*/;
22568       else if (uses_template_parms (elt))
22569 	/* Since we're unifying against ourselves, we will fill in
22570 	   template args used in the function parm list with our own
22571 	   template parms.  Discard them.  */
22572 	TREE_VEC_ELT (tempargs, i) = NULL_TREE;
22573       else if (oldelt && ARGUMENT_PACK_P (oldelt))
22574 	{
22575 	  /* Check that the argument at each index of the deduced argument pack
22576 	     is equivalent to the corresponding explicitly specified argument.
22577 	     We may have deduced more arguments than were explicitly specified,
22578 	     and that's OK.  */
22579 
22580 	  /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
22581 	     that's wrong if we deduce the same argument pack from multiple
22582 	     function arguments: it's only incomplete the first time.  */
22583 
22584 	  tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
22585 	  tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
22586 
22587 	  if (TREE_VEC_LENGTH (deduced_pack)
22588 	      < TREE_VEC_LENGTH (explicit_pack))
22589 	    return 0;
22590 
22591 	  for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
22592 	    if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
22593 				      TREE_VEC_ELT (deduced_pack, j)))
22594 	      return 0;
22595 	}
22596       else if (oldelt && !template_args_equal (oldelt, elt))
22597 	return 0;
22598     }
22599 
22600   for (i = nargs; i--; )
22601     {
22602       tree elt = TREE_VEC_ELT (tempargs, i);
22603 
22604       if (elt)
22605 	TREE_VEC_ELT (targs, i) = elt;
22606     }
22607 
22608   return 1;
22609 }
22610 
22611 /* PARM is a template class (perhaps with unbound template
22612    parameters).  ARG is a fully instantiated type.  If ARG can be
22613    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
22614    TARGS are as for unify.  */
22615 
22616 static tree
try_class_unification(tree tparms,tree targs,tree parm,tree arg,bool explain_p)22617 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
22618 		       bool explain_p)
22619 {
22620   tree copy_of_targs;
22621 
22622   if (!CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
22623     return NULL_TREE;
22624   else if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
22625     /* Matches anything.  */;
22626   else if (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
22627 	   != most_general_template (CLASSTYPE_TI_TEMPLATE (parm)))
22628     return NULL_TREE;
22629 
22630   /* We need to make a new template argument vector for the call to
22631      unify.  If we used TARGS, we'd clutter it up with the result of
22632      the attempted unification, even if this class didn't work out.
22633      We also don't want to commit ourselves to all the unifications
22634      we've already done, since unification is supposed to be done on
22635      an argument-by-argument basis.  In other words, consider the
22636      following pathological case:
22637 
22638        template <int I, int J, int K>
22639        struct S {};
22640 
22641        template <int I, int J>
22642        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
22643 
22644        template <int I, int J, int K>
22645        void f(S<I, J, K>, S<I, I, I>);
22646 
22647        void g() {
22648 	 S<0, 0, 0> s0;
22649 	 S<0, 1, 2> s2;
22650 
22651 	 f(s0, s2);
22652        }
22653 
22654      Now, by the time we consider the unification involving `s2', we
22655      already know that we must have `f<0, 0, 0>'.  But, even though
22656      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
22657      because there are two ways to unify base classes of S<0, 1, 2>
22658      with S<I, I, I>.  If we kept the already deduced knowledge, we
22659      would reject the possibility I=1.  */
22660   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
22661 
22662   if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
22663     {
22664       if (unify_bound_ttp_args (tparms, copy_of_targs, parm, arg, explain_p))
22665 	return NULL_TREE;
22666       return arg;
22667     }
22668 
22669   /* If unification failed, we're done.  */
22670   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
22671 	     CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
22672     return NULL_TREE;
22673 
22674   return arg;
22675 }
22676 
22677 /* Given a template type PARM and a class type ARG, find the unique
22678    base type in ARG that is an instance of PARM.  We do not examine
22679    ARG itself; only its base-classes.  If there is not exactly one
22680    appropriate base class, return NULL_TREE.  PARM may be the type of
22681    a partial specialization, as well as a plain template type.  Used
22682    by unify.  */
22683 
22684 static enum template_base_result
get_template_base(tree tparms,tree targs,tree parm,tree arg,bool explain_p,tree * result)22685 get_template_base (tree tparms, tree targs, tree parm, tree arg,
22686 		   bool explain_p, tree *result)
22687 {
22688   tree rval = NULL_TREE;
22689   tree binfo;
22690 
22691   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
22692 
22693   binfo = TYPE_BINFO (complete_type (arg));
22694   if (!binfo)
22695     {
22696       /* The type could not be completed.  */
22697       *result = NULL_TREE;
22698       return tbr_incomplete_type;
22699     }
22700 
22701   /* Walk in inheritance graph order.  The search order is not
22702      important, and this avoids multiple walks of virtual bases.  */
22703   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
22704     {
22705       tree r = try_class_unification (tparms, targs, parm,
22706 				      BINFO_TYPE (binfo), explain_p);
22707 
22708       if (r)
22709 	{
22710 	  /* If there is more than one satisfactory baseclass, then:
22711 
22712 	       [temp.deduct.call]
22713 
22714 	      If they yield more than one possible deduced A, the type
22715 	      deduction fails.
22716 
22717 	     applies.  */
22718 	  if (rval && !same_type_p (r, rval))
22719 	    {
22720 	      *result = NULL_TREE;
22721 	      return tbr_ambiguous_baseclass;
22722 	    }
22723 
22724 	  rval = r;
22725 	}
22726     }
22727 
22728   *result = rval;
22729   return tbr_success;
22730 }
22731 
22732 /* Returns the level of DECL, which declares a template parameter.  */
22733 
22734 static int
template_decl_level(tree decl)22735 template_decl_level (tree decl)
22736 {
22737   switch (TREE_CODE (decl))
22738     {
22739     case TYPE_DECL:
22740     case TEMPLATE_DECL:
22741       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
22742 
22743     case PARM_DECL:
22744       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
22745 
22746     default:
22747       gcc_unreachable ();
22748     }
22749   return 0;
22750 }
22751 
22752 /* Decide whether ARG can be unified with PARM, considering only the
22753    cv-qualifiers of each type, given STRICT as documented for unify.
22754    Returns nonzero iff the unification is OK on that basis.  */
22755 
22756 static int
check_cv_quals_for_unify(int strict,tree arg,tree parm)22757 check_cv_quals_for_unify (int strict, tree arg, tree parm)
22758 {
22759   int arg_quals = cp_type_quals (arg);
22760   int parm_quals = cp_type_quals (parm);
22761 
22762   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
22763       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
22764     {
22765       /*  Although a CVR qualifier is ignored when being applied to a
22766 	  substituted template parameter ([8.3.2]/1 for example), that
22767 	  does not allow us to unify "const T" with "int&" because both
22768 	  types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
22769 	  It is ok when we're allowing additional CV qualifiers
22770 	  at the outer level [14.8.2.1]/3,1st bullet.  */
22771       if ((TYPE_REF_P (arg)
22772 	   || FUNC_OR_METHOD_TYPE_P (arg))
22773 	  && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
22774 	return 0;
22775 
22776       if ((!INDIRECT_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
22777 	  && (parm_quals & TYPE_QUAL_RESTRICT))
22778 	return 0;
22779     }
22780 
22781   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
22782       && (arg_quals & parm_quals) != parm_quals)
22783     return 0;
22784 
22785   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
22786       && (parm_quals & arg_quals) != arg_quals)
22787     return 0;
22788 
22789   return 1;
22790 }
22791 
22792 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
22793 void
template_parm_level_and_index(tree parm,int * level,int * index)22794 template_parm_level_and_index (tree parm, int* level, int* index)
22795 {
22796   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
22797       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
22798       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
22799     {
22800       *index = TEMPLATE_TYPE_IDX (parm);
22801       *level = TEMPLATE_TYPE_LEVEL (parm);
22802     }
22803   else
22804     {
22805       *index = TEMPLATE_PARM_IDX (parm);
22806       *level = TEMPLATE_PARM_LEVEL (parm);
22807     }
22808 }
22809 
22810 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)			\
22811   do {									\
22812     if (unify (TP, TA, P, A, S, EP))					\
22813       return 1;								\
22814   } while (0)
22815 
22816 /* Unifies the remaining arguments in PACKED_ARGS with the pack
22817    expansion at the end of PACKED_PARMS. Returns 0 if the type
22818    deduction succeeds, 1 otherwise. STRICT is the same as in
22819    fn_type_unification. CALL_ARGS_P is true iff PACKED_ARGS is actually a
22820    function call argument list. We'll need to adjust the arguments to make them
22821    types. SUBR tells us if this is from a recursive call to
22822    type_unification_real, or for comparing two template argument
22823    lists. */
22824 
22825 static int
unify_pack_expansion(tree tparms,tree targs,tree packed_parms,tree packed_args,unification_kind_t strict,bool subr,bool explain_p)22826 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
22827                       tree packed_args, unification_kind_t strict,
22828                       bool subr, bool explain_p)
22829 {
22830   tree parm
22831     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
22832   tree pattern = PACK_EXPANSION_PATTERN (parm);
22833   tree pack, packs = NULL_TREE;
22834   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
22835 
22836   /* Add in any args remembered from an earlier partial instantiation.  */
22837   targs = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (parm), targs);
22838   int levels = TMPL_ARGS_DEPTH (targs);
22839 
22840   packed_args = expand_template_argument_pack (packed_args);
22841 
22842   int len = TREE_VEC_LENGTH (packed_args);
22843 
22844   /* Determine the parameter packs we will be deducing from the
22845      pattern, and record their current deductions.  */
22846   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
22847        pack; pack = TREE_CHAIN (pack))
22848     {
22849       tree parm_pack = TREE_VALUE (pack);
22850       int idx, level;
22851 
22852       /* Only template parameter packs can be deduced, not e.g. function
22853 	 parameter packs or __bases or __integer_pack.  */
22854       if (!TEMPLATE_PARM_P (parm_pack))
22855 	continue;
22856 
22857       /* Determine the index and level of this parameter pack.  */
22858       template_parm_level_and_index (parm_pack, &level, &idx);
22859       if (level < levels)
22860 	continue;
22861 
22862       /* Keep track of the parameter packs and their corresponding
22863          argument packs.  */
22864       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
22865       TREE_TYPE (packs) = make_tree_vec (len - start);
22866     }
22867 
22868   /* Loop through all of the arguments that have not yet been
22869      unified and unify each with the pattern.  */
22870   for (i = start; i < len; i++)
22871     {
22872       tree parm;
22873       bool any_explicit = false;
22874       tree arg = TREE_VEC_ELT (packed_args, i);
22875 
22876       /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
22877 	 or the element of its argument pack at the current index if
22878 	 this argument was explicitly specified.  */
22879       for (pack = packs; pack; pack = TREE_CHAIN (pack))
22880         {
22881           int idx, level;
22882           tree arg, pargs;
22883           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
22884 
22885           arg = NULL_TREE;
22886           if (TREE_VALUE (pack)
22887               && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
22888               && (i - start < TREE_VEC_LENGTH (pargs)))
22889             {
22890               any_explicit = true;
22891               arg = TREE_VEC_ELT (pargs, i - start);
22892             }
22893           TMPL_ARG (targs, level, idx) = arg;
22894         }
22895 
22896       /* If we had explicit template arguments, substitute them into the
22897 	 pattern before deduction.  */
22898       if (any_explicit)
22899 	{
22900 	  /* Some arguments might still be unspecified or dependent.  */
22901 	  bool dependent;
22902 	  ++processing_template_decl;
22903 	  dependent = any_dependent_template_arguments_p (targs);
22904 	  if (!dependent)
22905 	    --processing_template_decl;
22906 	  parm = tsubst (pattern, targs,
22907 			 explain_p ? tf_warning_or_error : tf_none,
22908 			 NULL_TREE);
22909 	  if (dependent)
22910 	    --processing_template_decl;
22911 	  if (parm == error_mark_node)
22912 	    return 1;
22913 	}
22914       else
22915 	parm = pattern;
22916 
22917       /* Unify the pattern with the current argument.  */
22918       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
22919 			      explain_p))
22920 	return 1;
22921 
22922       /* For each parameter pack, collect the deduced value.  */
22923       for (pack = packs; pack; pack = TREE_CHAIN (pack))
22924         {
22925           int idx, level;
22926           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
22927 
22928           TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
22929             TMPL_ARG (targs, level, idx);
22930         }
22931     }
22932 
22933   /* Verify that the results of unification with the parameter packs
22934      produce results consistent with what we've seen before, and make
22935      the deduced argument packs available.  */
22936   for (pack = packs; pack; pack = TREE_CHAIN (pack))
22937     {
22938       tree old_pack = TREE_VALUE (pack);
22939       tree new_args = TREE_TYPE (pack);
22940       int i, len = TREE_VEC_LENGTH (new_args);
22941       int idx, level;
22942       bool nondeduced_p = false;
22943 
22944       /* By default keep the original deduced argument pack.
22945 	 If necessary, more specific code is going to update the
22946 	 resulting deduced argument later down in this function.  */
22947       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
22948       TMPL_ARG (targs, level, idx) = old_pack;
22949 
22950       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
22951 	 actually deduce anything.  */
22952       for (i = 0; i < len && !nondeduced_p; ++i)
22953 	if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
22954 	  nondeduced_p = true;
22955       if (nondeduced_p)
22956 	continue;
22957 
22958       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
22959         {
22960           /* If we had fewer function args than explicit template args,
22961              just use the explicits.  */
22962           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
22963           int explicit_len = TREE_VEC_LENGTH (explicit_args);
22964           if (len < explicit_len)
22965             new_args = explicit_args;
22966         }
22967 
22968       if (!old_pack)
22969         {
22970           tree result;
22971           /* Build the deduced *_ARGUMENT_PACK.  */
22972           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
22973             {
22974               result = make_node (NONTYPE_ARGUMENT_PACK);
22975               TREE_CONSTANT (result) = 1;
22976             }
22977           else
22978             result = cxx_make_type (TYPE_ARGUMENT_PACK);
22979 
22980           SET_ARGUMENT_PACK_ARGS (result, new_args);
22981 
22982           /* Note the deduced argument packs for this parameter
22983              pack.  */
22984           TMPL_ARG (targs, level, idx) = result;
22985         }
22986       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
22987                && (ARGUMENT_PACK_ARGS (old_pack)
22988                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
22989         {
22990           /* We only had the explicitly-provided arguments before, but
22991              now we have a complete set of arguments.  */
22992           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
22993 
22994           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
22995           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
22996           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
22997         }
22998       else
22999 	{
23000 	  tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
23001 	  tree old_args = ARGUMENT_PACK_ARGS (old_pack);
23002 
23003 	  if (!comp_template_args (old_args, new_args,
23004 				   &bad_old_arg, &bad_new_arg))
23005 	    /* Inconsistent unification of this parameter pack.  */
23006 	    return unify_parameter_pack_inconsistent (explain_p,
23007 						      bad_old_arg,
23008 						      bad_new_arg);
23009 	}
23010     }
23011 
23012   return unify_success (explain_p);
23013 }
23014 
23015 /* Handle unification of the domain of an array.  PARM_DOM and ARG_DOM are
23016    INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs.  The other
23017    parameters and return value are as for unify.  */
23018 
23019 static int
unify_array_domain(tree tparms,tree targs,tree parm_dom,tree arg_dom,bool explain_p)23020 unify_array_domain (tree tparms, tree targs,
23021 		    tree parm_dom, tree arg_dom,
23022 		    bool explain_p)
23023 {
23024   tree parm_max;
23025   tree arg_max;
23026   bool parm_cst;
23027   bool arg_cst;
23028 
23029   /* Our representation of array types uses "N - 1" as the
23030      TYPE_MAX_VALUE for an array with "N" elements, if "N" is
23031      not an integer constant.  We cannot unify arbitrarily
23032      complex expressions, so we eliminate the MINUS_EXPRs
23033      here.  */
23034   parm_max = TYPE_MAX_VALUE (parm_dom);
23035   parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
23036   if (!parm_cst)
23037     {
23038       gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
23039       parm_max = TREE_OPERAND (parm_max, 0);
23040     }
23041   arg_max = TYPE_MAX_VALUE (arg_dom);
23042   arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
23043   if (!arg_cst)
23044     {
23045       /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
23046 	 trying to unify the type of a variable with the type
23047 	 of a template parameter.  For example:
23048 
23049 	   template <unsigned int N>
23050 	   void f (char (&) [N]);
23051 	   int g();
23052 	   void h(int i) {
23053 	     char a[g(i)];
23054 	     f(a);
23055 	   }
23056 
23057 	 Here, the type of the ARG will be "int [g(i)]", and
23058 	 may be a SAVE_EXPR, etc.  */
23059       if (TREE_CODE (arg_max) != MINUS_EXPR)
23060 	return unify_vla_arg (explain_p, arg_dom);
23061       arg_max = TREE_OPERAND (arg_max, 0);
23062     }
23063 
23064   /* If only one of the bounds used a MINUS_EXPR, compensate
23065      by adding one to the other bound.  */
23066   if (parm_cst && !arg_cst)
23067     parm_max = fold_build2_loc (input_location, PLUS_EXPR,
23068 				integer_type_node,
23069 				parm_max,
23070 				integer_one_node);
23071   else if (arg_cst && !parm_cst)
23072     arg_max = fold_build2_loc (input_location, PLUS_EXPR,
23073 			       integer_type_node,
23074 			       arg_max,
23075 			       integer_one_node);
23076 
23077   return unify (tparms, targs, parm_max, arg_max,
23078 		UNIFY_ALLOW_INTEGER, explain_p);
23079 }
23080 
23081 /* Returns whether T, a P or A in unify, is a type, template or expression.  */
23082 
23083 enum pa_kind_t { pa_type, pa_tmpl, pa_expr };
23084 
23085 static pa_kind_t
pa_kind(tree t)23086 pa_kind (tree t)
23087 {
23088   if (PACK_EXPANSION_P (t))
23089     t = PACK_EXPANSION_PATTERN (t);
23090   if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
23091       || TREE_CODE (t) == UNBOUND_CLASS_TEMPLATE
23092       || DECL_TYPE_TEMPLATE_P (t))
23093     return pa_tmpl;
23094   else if (TYPE_P (t))
23095     return pa_type;
23096   else
23097     return pa_expr;
23098 }
23099 
23100 /* Deduce the value of template parameters.  TPARMS is the (innermost)
23101    set of template parameters to a template.  TARGS is the bindings
23102    for those template parameters, as determined thus far; TARGS may
23103    include template arguments for outer levels of template parameters
23104    as well.  PARM is a parameter to a template function, or a
23105    subcomponent of that parameter; ARG is the corresponding argument.
23106    This function attempts to match PARM with ARG in a manner
23107    consistent with the existing assignments in TARGS.  If more values
23108    are deduced, then TARGS is updated.
23109 
23110    Returns 0 if the type deduction succeeds, 1 otherwise.  The
23111    parameter STRICT is a bitwise or of the following flags:
23112 
23113      UNIFY_ALLOW_NONE:
23114        Require an exact match between PARM and ARG.
23115      UNIFY_ALLOW_MORE_CV_QUAL:
23116        Allow the deduced ARG to be more cv-qualified (by qualification
23117        conversion) than ARG.
23118      UNIFY_ALLOW_LESS_CV_QUAL:
23119        Allow the deduced ARG to be less cv-qualified than ARG.
23120      UNIFY_ALLOW_DERIVED:
23121        Allow the deduced ARG to be a template base class of ARG,
23122        or a pointer to a template base class of the type pointed to by
23123        ARG.
23124      UNIFY_ALLOW_INTEGER:
23125        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
23126        case for more information.
23127      UNIFY_ALLOW_OUTER_LEVEL:
23128        This is the outermost level of a deduction. Used to determine validity
23129        of qualification conversions. A valid qualification conversion must
23130        have const qualified pointers leading up to the inner type which
23131        requires additional CV quals, except at the outer level, where const
23132        is not required [conv.qual]. It would be normal to set this flag in
23133        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
23134      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
23135        This is the outermost level of a deduction, and PARM can be more CV
23136        qualified at this point.
23137      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
23138        This is the outermost level of a deduction, and PARM can be less CV
23139        qualified at this point.  */
23140 
23141 static int
unify(tree tparms,tree targs,tree parm,tree arg,int strict,bool explain_p)23142 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
23143        bool explain_p)
23144 {
23145   int idx;
23146   tree targ;
23147   tree tparm;
23148   int strict_in = strict;
23149   tsubst_flags_t complain = (explain_p
23150 			     ? tf_warning_or_error
23151 			     : tf_none);
23152 
23153   /* I don't think this will do the right thing with respect to types.
23154      But the only case I've seen it in so far has been array bounds, where
23155      signedness is the only information lost, and I think that will be
23156      okay.  VIEW_CONVERT_EXPR can appear with class NTTP, thanks to
23157      finish_id_expression_1, and are also OK.  */
23158   while (CONVERT_EXPR_P (parm) || TREE_CODE (parm) == VIEW_CONVERT_EXPR)
23159     parm = TREE_OPERAND (parm, 0);
23160 
23161   if (arg == error_mark_node)
23162     return unify_invalid (explain_p);
23163   if (arg == unknown_type_node
23164       || arg == init_list_type_node)
23165     /* We can't deduce anything from this, but we might get all the
23166        template args from other function args.  */
23167     return unify_success (explain_p);
23168 
23169   if (parm == any_targ_node || arg == any_targ_node)
23170     return unify_success (explain_p);
23171 
23172   /* If PARM uses template parameters, then we can't bail out here,
23173      even if ARG == PARM, since we won't record unifications for the
23174      template parameters.  We might need them if we're trying to
23175      figure out which of two things is more specialized.  */
23176   if (arg == parm && !uses_template_parms (parm))
23177     return unify_success (explain_p);
23178 
23179   /* Handle init lists early, so the rest of the function can assume
23180      we're dealing with a type. */
23181   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
23182     {
23183       tree elt, elttype;
23184       unsigned i;
23185       tree orig_parm = parm;
23186 
23187       if (!is_std_init_list (parm)
23188 	  && TREE_CODE (parm) != ARRAY_TYPE)
23189 	/* We can only deduce from an initializer list argument if the
23190 	   parameter is std::initializer_list or an array; otherwise this
23191 	   is a non-deduced context. */
23192 	return unify_success (explain_p);
23193 
23194       if (TREE_CODE (parm) == ARRAY_TYPE)
23195 	elttype = TREE_TYPE (parm);
23196       else
23197 	{
23198 	  elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
23199 	  /* Deduction is defined in terms of a single type, so just punt
23200 	     on the (bizarre) std::initializer_list<T...>.  */
23201 	  if (PACK_EXPANSION_P (elttype))
23202 	    return unify_success (explain_p);
23203 	}
23204 
23205       if (strict != DEDUCE_EXACT
23206 	  && TYPE_P (elttype)
23207 	  && !uses_deducible_template_parms (elttype))
23208 	/* If ELTTYPE has no deducible template parms, skip deduction from
23209 	   the list elements.  */;
23210       else
23211 	FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
23212 	  {
23213 	    int elt_strict = strict;
23214 
23215 	    if (elt == error_mark_node)
23216 	      return unify_invalid (explain_p);
23217 
23218 	    if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
23219 	      {
23220 		tree type = TREE_TYPE (elt);
23221 		if (type == error_mark_node)
23222 		  return unify_invalid (explain_p);
23223 		/* It should only be possible to get here for a call.  */
23224 		gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
23225 		elt_strict |= maybe_adjust_types_for_deduction
23226 		  (DEDUCE_CALL, &elttype, &type, elt);
23227 		elt = type;
23228 	      }
23229 
23230 	  RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
23231 				   explain_p);
23232 	}
23233 
23234       if (TREE_CODE (parm) == ARRAY_TYPE
23235 	  && deducible_array_bound (TYPE_DOMAIN (parm)))
23236 	{
23237 	  /* Also deduce from the length of the initializer list.  */
23238 	  tree max = size_int (CONSTRUCTOR_NELTS (arg));
23239 	  tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
23240 	  if (idx == error_mark_node)
23241 	    return unify_invalid (explain_p);
23242 	  return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
23243 				     idx, explain_p);
23244 	}
23245 
23246       /* If the std::initializer_list<T> deduction worked, replace the
23247 	 deduced A with std::initializer_list<A>.  */
23248       if (orig_parm != parm)
23249 	{
23250 	  idx = TEMPLATE_TYPE_IDX (orig_parm);
23251 	  targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
23252 	  targ = listify (targ);
23253 	  TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
23254 	}
23255       return unify_success (explain_p);
23256     }
23257 
23258   /* If parm and arg aren't the same kind of thing (template, type, or
23259      expression), fail early.  */
23260   if (pa_kind (parm) != pa_kind (arg))
23261     return unify_invalid (explain_p);
23262 
23263   /* Immediately reject some pairs that won't unify because of
23264      cv-qualification mismatches.  */
23265   if (TREE_CODE (arg) == TREE_CODE (parm)
23266       && TYPE_P (arg)
23267       /* It is the elements of the array which hold the cv quals of an array
23268 	 type, and the elements might be template type parms. We'll check
23269 	 when we recurse.  */
23270       && TREE_CODE (arg) != ARRAY_TYPE
23271       /* We check the cv-qualifiers when unifying with template type
23272 	 parameters below.  We want to allow ARG `const T' to unify with
23273 	 PARM `T' for example, when computing which of two templates
23274 	 is more specialized, for example.  */
23275       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
23276       && !check_cv_quals_for_unify (strict_in, arg, parm))
23277     return unify_cv_qual_mismatch (explain_p, parm, arg);
23278 
23279   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
23280       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
23281     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
23282   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
23283   strict &= ~UNIFY_ALLOW_DERIVED;
23284   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
23285   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
23286 
23287   switch (TREE_CODE (parm))
23288     {
23289     case TYPENAME_TYPE:
23290     case SCOPE_REF:
23291     case UNBOUND_CLASS_TEMPLATE:
23292       /* In a type which contains a nested-name-specifier, template
23293 	 argument values cannot be deduced for template parameters used
23294 	 within the nested-name-specifier.  */
23295       return unify_success (explain_p);
23296 
23297     case TEMPLATE_TYPE_PARM:
23298     case TEMPLATE_TEMPLATE_PARM:
23299     case BOUND_TEMPLATE_TEMPLATE_PARM:
23300       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
23301       if (error_operand_p (tparm))
23302 	return unify_invalid (explain_p);
23303 
23304       if (TEMPLATE_TYPE_LEVEL (parm)
23305 	  != template_decl_level (tparm))
23306 	/* The PARM is not one we're trying to unify.  Just check
23307 	   to see if it matches ARG.  */
23308 	{
23309 	  if (TREE_CODE (arg) == TREE_CODE (parm)
23310 	      && (is_auto (parm) ? is_auto (arg)
23311 		  : same_type_p (parm, arg)))
23312 	    return unify_success (explain_p);
23313 	  else
23314 	    return unify_type_mismatch (explain_p, parm, arg);
23315 	}
23316       idx = TEMPLATE_TYPE_IDX (parm);
23317       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
23318       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
23319       if (error_operand_p (tparm))
23320 	return unify_invalid (explain_p);
23321 
23322       /* Check for mixed types and values.  */
23323       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
23324 	   && TREE_CODE (tparm) != TYPE_DECL)
23325 	  || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
23326 	      && TREE_CODE (tparm) != TEMPLATE_DECL))
23327 	gcc_unreachable ();
23328 
23329       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23330 	{
23331 	  if ((strict_in & UNIFY_ALLOW_DERIVED)
23332 	      && CLASS_TYPE_P (arg))
23333 	    {
23334 	      /* First try to match ARG directly.  */
23335 	      tree t = try_class_unification (tparms, targs, parm, arg,
23336 					      explain_p);
23337 	      if (!t)
23338 		{
23339 		  /* Otherwise, look for a suitable base of ARG, as below.  */
23340 		  enum template_base_result r;
23341 		  r = get_template_base (tparms, targs, parm, arg,
23342 					 explain_p, &t);
23343 		  if (!t)
23344 		    return unify_no_common_base (explain_p, r, parm, arg);
23345 		  arg = t;
23346 		}
23347 	    }
23348 	  /* ARG must be constructed from a template class or a template
23349 	     template parameter.  */
23350 	  else if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
23351 		   && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
23352 	    return unify_template_deduction_failure (explain_p, parm, arg);
23353 
23354 	  /* Deduce arguments T, i from TT<T> or TT<i>.  */
23355 	  if (unify_bound_ttp_args (tparms, targs, parm, arg, explain_p))
23356 	    return 1;
23357 
23358 	  arg = TYPE_TI_TEMPLATE (arg);
23359 
23360 	  /* Fall through to deduce template name.  */
23361 	}
23362 
23363       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
23364 	  || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23365 	{
23366 	  /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
23367 
23368 	  /* Simple cases: Value already set, does match or doesn't.  */
23369 	  if (targ != NULL_TREE && template_args_equal (targ, arg))
23370 	    return unify_success (explain_p);
23371 	  else if (targ)
23372 	    return unify_inconsistency (explain_p, parm, targ, arg);
23373 	}
23374       else
23375 	{
23376 	  /* If PARM is `const T' and ARG is only `int', we don't have
23377 	     a match unless we are allowing additional qualification.
23378 	     If ARG is `const int' and PARM is just `T' that's OK;
23379 	     that binds `const int' to `T'.  */
23380 	  if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
23381 					 arg, parm))
23382 	    return unify_cv_qual_mismatch (explain_p, parm, arg);
23383 
23384 	  /* Consider the case where ARG is `const volatile int' and
23385 	     PARM is `const T'.  Then, T should be `volatile int'.  */
23386 	  arg = cp_build_qualified_type_real
23387 	    (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
23388 	  if (arg == error_mark_node)
23389 	    return unify_invalid (explain_p);
23390 
23391 	  /* Simple cases: Value already set, does match or doesn't.  */
23392 	  if (targ != NULL_TREE && same_type_p (targ, arg))
23393 	    return unify_success (explain_p);
23394 	  else if (targ)
23395 	    return unify_inconsistency (explain_p, parm, targ, arg);
23396 
23397 	  /* Make sure that ARG is not a variable-sized array.  (Note
23398 	     that were talking about variable-sized arrays (like
23399 	     `int[n]'), rather than arrays of unknown size (like
23400 	     `int[]').)  We'll get very confused by such a type since
23401 	     the bound of the array is not constant, and therefore
23402 	     not mangleable.  Besides, such types are not allowed in
23403 	     ISO C++, so we can do as we please here.  We do allow
23404 	     them for 'auto' deduction, since that isn't ABI-exposed.  */
23405 	  if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
23406 	    return unify_vla_arg (explain_p, arg);
23407 
23408 	  /* Strip typedefs as in convert_template_argument.  */
23409 	  arg = canonicalize_type_argument (arg, tf_none);
23410 	}
23411 
23412       /* If ARG is a parameter pack or an expansion, we cannot unify
23413 	 against it unless PARM is also a parameter pack.  */
23414       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
23415 	  && !template_parameter_pack_p (parm))
23416 	return unify_parameter_pack_mismatch (explain_p, parm, arg);
23417 
23418       /* If the argument deduction results is a METHOD_TYPE,
23419          then there is a problem.
23420          METHOD_TYPE doesn't map to any real C++ type the result of
23421 	 the deduction cannot be of that type.  */
23422       if (TREE_CODE (arg) == METHOD_TYPE)
23423 	return unify_method_type_error (explain_p, arg);
23424 
23425       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
23426       return unify_success (explain_p);
23427 
23428     case TEMPLATE_PARM_INDEX:
23429       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
23430       if (error_operand_p (tparm))
23431 	return unify_invalid (explain_p);
23432 
23433       if (TEMPLATE_PARM_LEVEL (parm)
23434 	  != template_decl_level (tparm))
23435 	{
23436 	  /* The PARM is not one we're trying to unify.  Just check
23437 	     to see if it matches ARG.  */
23438 	  int result = !(TREE_CODE (arg) == TREE_CODE (parm)
23439 			 && cp_tree_equal (parm, arg));
23440 	  if (result)
23441 	    unify_expression_unequal (explain_p, parm, arg);
23442 	  return result;
23443 	}
23444 
23445       idx = TEMPLATE_PARM_IDX (parm);
23446       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
23447 
23448       if (targ)
23449 	{
23450 	  if ((strict & UNIFY_ALLOW_INTEGER)
23451 	      && TREE_TYPE (targ) && TREE_TYPE (arg)
23452 	      && CP_INTEGRAL_TYPE_P (TREE_TYPE (targ)))
23453 	    /* We're deducing from an array bound, the type doesn't matter.  */
23454 	    arg = fold_convert (TREE_TYPE (targ), arg);
23455 	  int x = !cp_tree_equal (targ, arg);
23456 	  if (x)
23457 	    unify_inconsistency (explain_p, parm, targ, arg);
23458 	  return x;
23459 	}
23460 
23461       /* [temp.deduct.type] If, in the declaration of a function template
23462 	 with a non-type template-parameter, the non-type
23463 	 template-parameter is used in an expression in the function
23464 	 parameter-list and, if the corresponding template-argument is
23465 	 deduced, the template-argument type shall match the type of the
23466 	 template-parameter exactly, except that a template-argument
23467 	 deduced from an array bound may be of any integral type.
23468 	 The non-type parameter might use already deduced type parameters.  */
23469       tparm = TREE_TYPE (parm);
23470       if (TEMPLATE_PARM_LEVEL (parm) > TMPL_ARGS_DEPTH (targs))
23471 	/* We don't have enough levels of args to do any substitution.  This
23472 	   can happen in the context of -fnew-ttp-matching.  */;
23473       else
23474 	{
23475 	  ++processing_template_decl;
23476 	  tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
23477 	  --processing_template_decl;
23478 
23479 	  if (tree a = type_uses_auto (tparm))
23480 	    {
23481 	      tparm = do_auto_deduction (tparm, arg, a, complain, adc_unify);
23482 	      if (tparm == error_mark_node)
23483 		return 1;
23484 	    }
23485 	}
23486 
23487       if (!TREE_TYPE (arg))
23488 	/* Template-parameter dependent expression.  Just accept it for now.
23489 	   It will later be processed in convert_template_argument.  */
23490 	;
23491       else if (same_type_ignoring_top_level_qualifiers_p
23492 	       (non_reference (TREE_TYPE (arg)),
23493 		non_reference (tparm)))
23494 	/* OK.  Ignore top-level quals here because a class-type template
23495 	   parameter object is const.  */;
23496       else if ((strict & UNIFY_ALLOW_INTEGER)
23497 	       && CP_INTEGRAL_TYPE_P (tparm))
23498 	/* Convert the ARG to the type of PARM; the deduced non-type
23499 	   template argument must exactly match the types of the
23500 	   corresponding parameter.  */
23501 	arg = fold (build_nop (tparm, arg));
23502       else if (uses_template_parms (tparm))
23503 	{
23504 	  /* We haven't deduced the type of this parameter yet.  */
23505 	  if (cxx_dialect >= cxx17
23506 	      /* We deduce from array bounds in try_array_deduction.  */
23507 	      && !(strict & UNIFY_ALLOW_INTEGER))
23508 	    {
23509 	      /* Deduce it from the non-type argument.  */
23510 	      tree atype = TREE_TYPE (arg);
23511 	      RECUR_AND_CHECK_FAILURE (tparms, targs,
23512 				       tparm, atype,
23513 				       UNIFY_ALLOW_NONE, explain_p);
23514 	    }
23515 	  else
23516 	    /* Try again later.  */
23517 	    return unify_success (explain_p);
23518 	}
23519       else
23520 	return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
23521 
23522       /* If ARG is a parameter pack or an expansion, we cannot unify
23523 	 against it unless PARM is also a parameter pack.  */
23524       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
23525 	  && !TEMPLATE_PARM_PARAMETER_PACK (parm))
23526 	return unify_parameter_pack_mismatch (explain_p, parm, arg);
23527 
23528       {
23529 	bool removed_attr = false;
23530 	arg = strip_typedefs_expr (arg, &removed_attr);
23531       }
23532       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
23533       return unify_success (explain_p);
23534 
23535     case PTRMEM_CST:
23536      {
23537 	/* A pointer-to-member constant can be unified only with
23538 	 another constant.  */
23539       if (TREE_CODE (arg) != PTRMEM_CST)
23540 	return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
23541 
23542       /* Just unify the class member. It would be useless (and possibly
23543 	 wrong, depending on the strict flags) to unify also
23544 	 PTRMEM_CST_CLASS, because we want to be sure that both parm and
23545 	 arg refer to the same variable, even if through different
23546 	 classes. For instance:
23547 
23548 	 struct A { int x; };
23549 	 struct B : A { };
23550 
23551 	 Unification of &A::x and &B::x must succeed.  */
23552       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
23553 		    PTRMEM_CST_MEMBER (arg), strict, explain_p);
23554      }
23555 
23556     case POINTER_TYPE:
23557       {
23558 	if (!TYPE_PTR_P (arg))
23559 	  return unify_type_mismatch (explain_p, parm, arg);
23560 
23561 	/* [temp.deduct.call]
23562 
23563 	   A can be another pointer or pointer to member type that can
23564 	   be converted to the deduced A via a qualification
23565 	   conversion (_conv.qual_).
23566 
23567 	   We pass down STRICT here rather than UNIFY_ALLOW_NONE.
23568 	   This will allow for additional cv-qualification of the
23569 	   pointed-to types if appropriate.  */
23570 
23571 	if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
23572 	  /* The derived-to-base conversion only persists through one
23573 	     level of pointers.  */
23574 	  strict |= (strict_in & UNIFY_ALLOW_DERIVED);
23575 
23576 	return unify (tparms, targs, TREE_TYPE (parm),
23577 		      TREE_TYPE (arg), strict, explain_p);
23578       }
23579 
23580     case REFERENCE_TYPE:
23581       if (!TYPE_REF_P (arg))
23582 	return unify_type_mismatch (explain_p, parm, arg);
23583       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
23584 		    strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
23585 
23586     case ARRAY_TYPE:
23587       if (TREE_CODE (arg) != ARRAY_TYPE)
23588 	return unify_type_mismatch (explain_p, parm, arg);
23589       if ((TYPE_DOMAIN (parm) == NULL_TREE)
23590 	  != (TYPE_DOMAIN (arg) == NULL_TREE))
23591 	return unify_type_mismatch (explain_p, parm, arg);
23592       RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
23593 			       strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
23594       if (TYPE_DOMAIN (parm) != NULL_TREE)
23595 	return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
23596 				   TYPE_DOMAIN (arg), explain_p);
23597       return unify_success (explain_p);
23598 
23599     case REAL_TYPE:
23600     case COMPLEX_TYPE:
23601     case VECTOR_TYPE:
23602     case INTEGER_TYPE:
23603     case BOOLEAN_TYPE:
23604     case ENUMERAL_TYPE:
23605     case VOID_TYPE:
23606     case NULLPTR_TYPE:
23607       if (TREE_CODE (arg) != TREE_CODE (parm))
23608 	return unify_type_mismatch (explain_p, parm, arg);
23609 
23610       /* We have already checked cv-qualification at the top of the
23611 	 function.  */
23612       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
23613 	return unify_type_mismatch (explain_p, parm, arg);
23614 
23615       /* As far as unification is concerned, this wins.	 Later checks
23616 	 will invalidate it if necessary.  */
23617       return unify_success (explain_p);
23618 
23619       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
23620       /* Type INTEGER_CST can come from ordinary constant template args.  */
23621     case INTEGER_CST:
23622       while (CONVERT_EXPR_P (arg))
23623 	arg = TREE_OPERAND (arg, 0);
23624 
23625       if (TREE_CODE (arg) != INTEGER_CST)
23626 	return unify_template_argument_mismatch (explain_p, parm, arg);
23627       return (tree_int_cst_equal (parm, arg)
23628 	      ? unify_success (explain_p)
23629 	      : unify_template_argument_mismatch (explain_p, parm, arg));
23630 
23631     case TREE_VEC:
23632       {
23633 	int i, len, argslen;
23634 	int parm_variadic_p = 0;
23635 
23636 	if (TREE_CODE (arg) != TREE_VEC)
23637 	  return unify_template_argument_mismatch (explain_p, parm, arg);
23638 
23639 	len = TREE_VEC_LENGTH (parm);
23640 	argslen = TREE_VEC_LENGTH (arg);
23641 
23642 	/* Check for pack expansions in the parameters.  */
23643 	for (i = 0; i < len; ++i)
23644 	  {
23645 	    if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
23646 	      {
23647 		if (i == len - 1)
23648 		  /* We can unify against something with a trailing
23649 		     parameter pack.  */
23650 		  parm_variadic_p = 1;
23651 		else
23652 		  /* [temp.deduct.type]/9: If the template argument list of
23653 		     P contains a pack expansion that is not the last
23654 		     template argument, the entire template argument list
23655 		     is a non-deduced context.  */
23656 		  return unify_success (explain_p);
23657 	      }
23658 	  }
23659 
23660         /* If we don't have enough arguments to satisfy the parameters
23661            (not counting the pack expression at the end), or we have
23662            too many arguments for a parameter list that doesn't end in
23663            a pack expression, we can't unify.  */
23664 	if (parm_variadic_p
23665 	    ? argslen < len - parm_variadic_p
23666 	    : argslen != len)
23667 	  return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
23668 
23669 	/* Unify all of the parameters that precede the (optional)
23670 	   pack expression.  */
23671 	for (i = 0; i < len - parm_variadic_p; ++i)
23672 	  {
23673 	    RECUR_AND_CHECK_FAILURE (tparms, targs,
23674 				     TREE_VEC_ELT (parm, i),
23675 				     TREE_VEC_ELT (arg, i),
23676 				     UNIFY_ALLOW_NONE, explain_p);
23677 	  }
23678 	if (parm_variadic_p)
23679 	  return unify_pack_expansion (tparms, targs, parm, arg,
23680 				       DEDUCE_EXACT,
23681 				       /*subr=*/true, explain_p);
23682 	return unify_success (explain_p);
23683       }
23684 
23685     case RECORD_TYPE:
23686     case UNION_TYPE:
23687       if (TREE_CODE (arg) != TREE_CODE (parm))
23688 	return unify_type_mismatch (explain_p, parm, arg);
23689 
23690       if (TYPE_PTRMEMFUNC_P (parm))
23691 	{
23692 	  if (!TYPE_PTRMEMFUNC_P (arg))
23693 	    return unify_type_mismatch (explain_p, parm, arg);
23694 
23695 	  return unify (tparms, targs,
23696 			TYPE_PTRMEMFUNC_FN_TYPE (parm),
23697 			TYPE_PTRMEMFUNC_FN_TYPE (arg),
23698 			strict, explain_p);
23699 	}
23700       else if (TYPE_PTRMEMFUNC_P (arg))
23701 	return unify_type_mismatch (explain_p, parm, arg);
23702 
23703       if (CLASSTYPE_TEMPLATE_INFO (parm))
23704 	{
23705 	  tree t = NULL_TREE;
23706 
23707 	  if (strict_in & UNIFY_ALLOW_DERIVED)
23708 	    {
23709 	      /* First, we try to unify the PARM and ARG directly.  */
23710 	      t = try_class_unification (tparms, targs,
23711 					 parm, arg, explain_p);
23712 
23713 	      if (!t)
23714 		{
23715 		  /* Fallback to the special case allowed in
23716 		     [temp.deduct.call]:
23717 
23718 		       If P is a class, and P has the form
23719 		       template-id, then A can be a derived class of
23720 		       the deduced A.  Likewise, if P is a pointer to
23721 		       a class of the form template-id, A can be a
23722 		       pointer to a derived class pointed to by the
23723 		       deduced A.  */
23724 		  enum template_base_result r;
23725 		  r = get_template_base (tparms, targs, parm, arg,
23726 					 explain_p, &t);
23727 
23728 		  if (!t)
23729 		    {
23730 		      /* Don't give the derived diagnostic if we're
23731 			 already dealing with the same template.  */
23732 		      bool same_template
23733 			= (CLASSTYPE_TEMPLATE_INFO (arg)
23734 			   && (CLASSTYPE_TI_TEMPLATE (parm)
23735 			       == CLASSTYPE_TI_TEMPLATE (arg)));
23736 		      return unify_no_common_base (explain_p && !same_template,
23737 						   r, parm, arg);
23738 		    }
23739 		}
23740 	    }
23741 	  else if (CLASSTYPE_TEMPLATE_INFO (arg)
23742 		   && (CLASSTYPE_TI_TEMPLATE (parm)
23743 		       == CLASSTYPE_TI_TEMPLATE (arg)))
23744 	    /* Perhaps PARM is something like S<U> and ARG is S<int>.
23745 	       Then, we should unify `int' and `U'.  */
23746 	    t = arg;
23747 	  else
23748 	    /* There's no chance of unification succeeding.  */
23749 	    return unify_type_mismatch (explain_p, parm, arg);
23750 
23751 	  return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
23752 			CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
23753 	}
23754       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
23755 	return unify_type_mismatch (explain_p, parm, arg);
23756       return unify_success (explain_p);
23757 
23758     case METHOD_TYPE:
23759     case FUNCTION_TYPE:
23760       {
23761 	unsigned int nargs;
23762 	tree *args;
23763 	tree a;
23764 	unsigned int i;
23765 
23766 	if (TREE_CODE (arg) != TREE_CODE (parm))
23767 	  return unify_type_mismatch (explain_p, parm, arg);
23768 
23769 	/* CV qualifications for methods can never be deduced, they must
23770 	   match exactly.  We need to check them explicitly here,
23771 	   because type_unification_real treats them as any other
23772 	   cv-qualified parameter.  */
23773 	if (TREE_CODE (parm) == METHOD_TYPE
23774 	    && (!check_cv_quals_for_unify
23775 		(UNIFY_ALLOW_NONE,
23776 		 class_of_this_parm (arg),
23777 		 class_of_this_parm (parm))))
23778 	  return unify_cv_qual_mismatch (explain_p, parm, arg);
23779 	if (TREE_CODE (arg) == FUNCTION_TYPE
23780 	    && type_memfn_quals (parm) != type_memfn_quals (arg))
23781 	  return unify_cv_qual_mismatch (explain_p, parm, arg);
23782 	if (type_memfn_rqual (parm) != type_memfn_rqual (arg))
23783 	  return unify_type_mismatch (explain_p, parm, arg);
23784 
23785 	RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
23786 				 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
23787 
23788 	nargs = list_length (TYPE_ARG_TYPES (arg));
23789 	args = XALLOCAVEC (tree, nargs);
23790 	for (a = TYPE_ARG_TYPES (arg), i = 0;
23791 	     a != NULL_TREE && a != void_list_node;
23792 	     a = TREE_CHAIN (a), ++i)
23793 	  args[i] = TREE_VALUE (a);
23794 	nargs = i;
23795 
23796 	if (type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
23797 				   args, nargs, 1, DEDUCE_EXACT,
23798 				   NULL, explain_p))
23799 	  return 1;
23800 
23801 	if (flag_noexcept_type)
23802 	  {
23803 	    tree pspec = TYPE_RAISES_EXCEPTIONS (parm);
23804 	    tree aspec = canonical_eh_spec (TYPE_RAISES_EXCEPTIONS (arg));
23805 	    if (pspec == NULL_TREE) pspec = noexcept_false_spec;
23806 	    if (aspec == NULL_TREE) aspec = noexcept_false_spec;
23807 	    if (TREE_PURPOSE (pspec) && TREE_PURPOSE (aspec)
23808 		&& uses_template_parms (TREE_PURPOSE (pspec)))
23809 	      RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_PURPOSE (pspec),
23810 				       TREE_PURPOSE (aspec),
23811 				       UNIFY_ALLOW_NONE, explain_p);
23812 	    else if (nothrow_spec_p (pspec) && !nothrow_spec_p (aspec))
23813 	      return unify_type_mismatch (explain_p, parm, arg);
23814 	  }
23815 
23816 	return 0;
23817       }
23818 
23819     case OFFSET_TYPE:
23820       /* Unify a pointer to member with a pointer to member function, which
23821 	 deduces the type of the member as a function type. */
23822       if (TYPE_PTRMEMFUNC_P (arg))
23823 	{
23824 	  /* Check top-level cv qualifiers */
23825 	  if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
23826 	    return unify_cv_qual_mismatch (explain_p, parm, arg);
23827 
23828 	  RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
23829 				   TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
23830 				   UNIFY_ALLOW_NONE, explain_p);
23831 
23832 	  /* Determine the type of the function we are unifying against. */
23833 	  tree fntype = static_fn_type (arg);
23834 
23835 	  return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
23836 	}
23837 
23838       if (TREE_CODE (arg) != OFFSET_TYPE)
23839 	return unify_type_mismatch (explain_p, parm, arg);
23840       RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
23841 			       TYPE_OFFSET_BASETYPE (arg),
23842 			       UNIFY_ALLOW_NONE, explain_p);
23843       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
23844 		    strict, explain_p);
23845 
23846     case CONST_DECL:
23847       if (DECL_TEMPLATE_PARM_P (parm))
23848 	return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
23849       if (arg != scalar_constant_value (parm))
23850 	return unify_template_argument_mismatch (explain_p, parm, arg);
23851       return unify_success (explain_p);
23852 
23853     case FIELD_DECL:
23854     case TEMPLATE_DECL:
23855       /* Matched cases are handled by the ARG == PARM test above.  */
23856       return unify_template_argument_mismatch (explain_p, parm, arg);
23857 
23858     case VAR_DECL:
23859       /* We might get a variable as a non-type template argument in parm if the
23860 	 corresponding parameter is type-dependent.  Make any necessary
23861 	 adjustments based on whether arg is a reference.  */
23862       if (CONSTANT_CLASS_P (arg))
23863 	parm = fold_non_dependent_expr (parm, complain);
23864       else if (REFERENCE_REF_P (arg))
23865 	{
23866 	  tree sub = TREE_OPERAND (arg, 0);
23867 	  STRIP_NOPS (sub);
23868 	  if (TREE_CODE (sub) == ADDR_EXPR)
23869 	    arg = TREE_OPERAND (sub, 0);
23870 	}
23871       /* Now use the normal expression code to check whether they match.  */
23872       goto expr;
23873 
23874     case TYPE_ARGUMENT_PACK:
23875     case NONTYPE_ARGUMENT_PACK:
23876       return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
23877 		    ARGUMENT_PACK_ARGS (arg), strict, explain_p);
23878 
23879     case TYPEOF_TYPE:
23880     case DECLTYPE_TYPE:
23881     case UNDERLYING_TYPE:
23882       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
23883 	 or UNDERLYING_TYPE nodes.  */
23884       return unify_success (explain_p);
23885 
23886     case ERROR_MARK:
23887       /* Unification fails if we hit an error node.  */
23888       return unify_invalid (explain_p);
23889 
23890     case INDIRECT_REF:
23891       if (REFERENCE_REF_P (parm))
23892 	{
23893 	  bool pexp = PACK_EXPANSION_P (arg);
23894 	  if (pexp)
23895 	    arg = PACK_EXPANSION_PATTERN (arg);
23896 	  if (REFERENCE_REF_P (arg))
23897 	    arg = TREE_OPERAND (arg, 0);
23898 	  if (pexp)
23899 	    arg = make_pack_expansion (arg, complain);
23900 	  return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
23901 			strict, explain_p);
23902 	}
23903       /* FALLTHRU */
23904 
23905     default:
23906       /* An unresolved overload is a nondeduced context.  */
23907       if (is_overloaded_fn (parm) || type_unknown_p (parm))
23908 	return unify_success (explain_p);
23909       gcc_assert (EXPR_P (parm)
23910 		  || COMPOUND_LITERAL_P (parm)
23911 		  || TREE_CODE (parm) == TRAIT_EXPR);
23912     expr:
23913       /* We must be looking at an expression.  This can happen with
23914 	 something like:
23915 
23916 	   template <int I>
23917 	   void foo(S<I>, S<I + 2>);
23918 
23919 	 or
23920 
23921 	   template<typename T>
23922 	   void foo(A<T, T{}>);
23923 
23924 	 This is a "non-deduced context":
23925 
23926 	   [deduct.type]
23927 
23928 	   The non-deduced contexts are:
23929 
23930 	   --A non-type template argument or an array bound in which
23931 	     a subexpression references a template parameter.
23932 
23933 	 In these cases, we assume deduction succeeded, but don't
23934 	 actually infer any unifications.  */
23935 
23936       if (!uses_template_parms (parm)
23937 	  && !template_args_equal (parm, arg))
23938 	return unify_expression_unequal (explain_p, parm, arg);
23939       else
23940 	return unify_success (explain_p);
23941     }
23942 }
23943 #undef RECUR_AND_CHECK_FAILURE
23944 
23945 /* Note that DECL can be defined in this translation unit, if
23946    required.  */
23947 
23948 static void
mark_definable(tree decl)23949 mark_definable (tree decl)
23950 {
23951   tree clone;
23952   DECL_NOT_REALLY_EXTERN (decl) = 1;
23953   FOR_EACH_CLONE (clone, decl)
23954     DECL_NOT_REALLY_EXTERN (clone) = 1;
23955 }
23956 
23957 /* Called if RESULT is explicitly instantiated, or is a member of an
23958    explicitly instantiated class.  */
23959 
23960 void
mark_decl_instantiated(tree result,int extern_p)23961 mark_decl_instantiated (tree result, int extern_p)
23962 {
23963   SET_DECL_EXPLICIT_INSTANTIATION (result);
23964 
23965   /* If this entity has already been written out, it's too late to
23966      make any modifications.  */
23967   if (TREE_ASM_WRITTEN (result))
23968     return;
23969 
23970   /* consteval functions are never emitted.  */
23971   if (TREE_CODE (result) == FUNCTION_DECL
23972       && DECL_IMMEDIATE_FUNCTION_P (result))
23973     return;
23974 
23975   /* For anonymous namespace we don't need to do anything.  */
23976   if (decl_anon_ns_mem_p (result))
23977     {
23978       gcc_assert (!TREE_PUBLIC (result));
23979       return;
23980     }
23981 
23982   if (TREE_CODE (result) != FUNCTION_DECL)
23983     /* The TREE_PUBLIC flag for function declarations will have been
23984        set correctly by tsubst.  */
23985     TREE_PUBLIC (result) = 1;
23986 
23987   /* This might have been set by an earlier implicit instantiation.  */
23988   DECL_COMDAT (result) = 0;
23989 
23990   if (extern_p)
23991     DECL_NOT_REALLY_EXTERN (result) = 0;
23992   else
23993     {
23994       mark_definable (result);
23995       mark_needed (result);
23996       /* Always make artificials weak.  */
23997       if (DECL_ARTIFICIAL (result) && flag_weak)
23998 	comdat_linkage (result);
23999       /* For WIN32 we also want to put explicit instantiations in
24000 	 linkonce sections.  */
24001       else if (TREE_PUBLIC (result))
24002 	maybe_make_one_only (result);
24003       if (TREE_CODE (result) == FUNCTION_DECL
24004 	  && DECL_TEMPLATE_INSTANTIATED (result))
24005 	/* If the function has already been instantiated, clear DECL_EXTERNAL,
24006 	   since start_preparsed_function wouldn't have if we had an earlier
24007 	   extern explicit instantiation.  */
24008 	DECL_EXTERNAL (result) = 0;
24009     }
24010 
24011   /* If EXTERN_P, then this function will not be emitted -- unless
24012      followed by an explicit instantiation, at which point its linkage
24013      will be adjusted.  If !EXTERN_P, then this function will be
24014      emitted here.  In neither circumstance do we want
24015      import_export_decl to adjust the linkage.  */
24016   DECL_INTERFACE_KNOWN (result) = 1;
24017 }
24018 
24019 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
24020    important template arguments.  If any are missing, we check whether
24021    they're important by using error_mark_node for substituting into any
24022    args that were used for partial ordering (the ones between ARGS and END)
24023    and seeing if it bubbles up.  */
24024 
24025 static bool
check_undeduced_parms(tree targs,tree args,tree end)24026 check_undeduced_parms (tree targs, tree args, tree end)
24027 {
24028   bool found = false;
24029   int i;
24030   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
24031     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
24032       {
24033 	found = true;
24034 	TREE_VEC_ELT (targs, i) = error_mark_node;
24035       }
24036   if (found)
24037     {
24038       tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
24039       if (substed == error_mark_node)
24040 	return true;
24041     }
24042   return false;
24043 }
24044 
24045 /* Given two function templates PAT1 and PAT2, return:
24046 
24047    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
24048    -1 if PAT2 is more specialized than PAT1.
24049    0 if neither is more specialized.
24050 
24051    LEN indicates the number of parameters we should consider
24052    (defaulted parameters should not be considered).
24053 
24054    The 1998 std underspecified function template partial ordering, and
24055    DR214 addresses the issue.  We take pairs of arguments, one from
24056    each of the templates, and deduce them against each other.  One of
24057    the templates will be more specialized if all the *other*
24058    template's arguments deduce against its arguments and at least one
24059    of its arguments *does* *not* deduce against the other template's
24060    corresponding argument.  Deduction is done as for class templates.
24061    The arguments used in deduction have reference and top level cv
24062    qualifiers removed.  Iff both arguments were originally reference
24063    types *and* deduction succeeds in both directions, an lvalue reference
24064    wins against an rvalue reference and otherwise the template
24065    with the more cv-qualified argument wins for that pairing (if
24066    neither is more cv-qualified, they both are equal).  Unlike regular
24067    deduction, after all the arguments have been deduced in this way,
24068    we do *not* verify the deduced template argument values can be
24069    substituted into non-deduced contexts.
24070 
24071    The logic can be a bit confusing here, because we look at deduce1 and
24072    targs1 to see if pat2 is at least as specialized, and vice versa; if we
24073    can find template arguments for pat1 to make arg1 look like arg2, that
24074    means that arg2 is at least as specialized as arg1.  */
24075 
24076 int
more_specialized_fn(tree pat1,tree pat2,int len)24077 more_specialized_fn (tree pat1, tree pat2, int len)
24078 {
24079   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
24080   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
24081   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
24082   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
24083   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
24084   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
24085   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
24086   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
24087   tree origs1, origs2;
24088   bool lose1 = false;
24089   bool lose2 = false;
24090 
24091   /* Remove the this parameter from non-static member functions.  If
24092      one is a non-static member function and the other is not a static
24093      member function, remove the first parameter from that function
24094      also.  This situation occurs for operator functions where we
24095      locate both a member function (with this pointer) and non-member
24096      operator (with explicit first operand).  */
24097   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
24098     {
24099       len--; /* LEN is the number of significant arguments for DECL1 */
24100       args1 = TREE_CHAIN (args1);
24101       if (!DECL_STATIC_FUNCTION_P (decl2))
24102 	args2 = TREE_CHAIN (args2);
24103     }
24104   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
24105     {
24106       args2 = TREE_CHAIN (args2);
24107       if (!DECL_STATIC_FUNCTION_P (decl1))
24108 	{
24109 	  len--;
24110 	  args1 = TREE_CHAIN (args1);
24111 	}
24112     }
24113 
24114   /* If only one is a conversion operator, they are unordered.  */
24115   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
24116     return 0;
24117 
24118   /* Consider the return type for a conversion function */
24119   if (DECL_CONV_FN_P (decl1))
24120     {
24121       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
24122       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
24123       len++;
24124     }
24125 
24126   processing_template_decl++;
24127 
24128   origs1 = args1;
24129   origs2 = args2;
24130 
24131   while (len--
24132 	 /* Stop when an ellipsis is seen.  */
24133 	 && args1 != NULL_TREE && args2 != NULL_TREE)
24134     {
24135       tree arg1 = TREE_VALUE (args1);
24136       tree arg2 = TREE_VALUE (args2);
24137       int deduce1, deduce2;
24138       int quals1 = -1;
24139       int quals2 = -1;
24140       int ref1 = 0;
24141       int ref2 = 0;
24142 
24143       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
24144           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
24145         {
24146           /* When both arguments are pack expansions, we need only
24147              unify the patterns themselves.  */
24148           arg1 = PACK_EXPANSION_PATTERN (arg1);
24149           arg2 = PACK_EXPANSION_PATTERN (arg2);
24150 
24151           /* This is the last comparison we need to do.  */
24152           len = 0;
24153         }
24154 
24155       /* DR 1847: If a particular P contains no template-parameters that
24156 	 participate in template argument deduction, that P is not used to
24157 	 determine the ordering.  */
24158       if (!uses_deducible_template_parms (arg1)
24159 	  && !uses_deducible_template_parms (arg2))
24160 	goto next;
24161 
24162       if (TYPE_REF_P (arg1))
24163 	{
24164 	  ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
24165 	  arg1 = TREE_TYPE (arg1);
24166 	  quals1 = cp_type_quals (arg1);
24167 	}
24168 
24169       if (TYPE_REF_P (arg2))
24170 	{
24171 	  ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
24172 	  arg2 = TREE_TYPE (arg2);
24173 	  quals2 = cp_type_quals (arg2);
24174 	}
24175 
24176       arg1 = TYPE_MAIN_VARIANT (arg1);
24177       arg2 = TYPE_MAIN_VARIANT (arg2);
24178 
24179       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
24180         {
24181           int i, len2 = remaining_arguments (args2);
24182           tree parmvec = make_tree_vec (1);
24183           tree argvec = make_tree_vec (len2);
24184           tree ta = args2;
24185 
24186           /* Setup the parameter vector, which contains only ARG1.  */
24187           TREE_VEC_ELT (parmvec, 0) = arg1;
24188 
24189           /* Setup the argument vector, which contains the remaining
24190              arguments.  */
24191           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
24192             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
24193 
24194           deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
24195 					   argvec, DEDUCE_EXACT,
24196 					   /*subr=*/true, /*explain_p=*/false)
24197 		     == 0);
24198 
24199           /* We cannot deduce in the other direction, because ARG1 is
24200              a pack expansion but ARG2 is not.  */
24201           deduce2 = 0;
24202         }
24203       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
24204         {
24205           int i, len1 = remaining_arguments (args1);
24206           tree parmvec = make_tree_vec (1);
24207           tree argvec = make_tree_vec (len1);
24208           tree ta = args1;
24209 
24210           /* Setup the parameter vector, which contains only ARG1.  */
24211           TREE_VEC_ELT (parmvec, 0) = arg2;
24212 
24213           /* Setup the argument vector, which contains the remaining
24214              arguments.  */
24215           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
24216             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
24217 
24218           deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
24219 					   argvec, DEDUCE_EXACT,
24220 					   /*subr=*/true, /*explain_p=*/false)
24221 		     == 0);
24222 
24223           /* We cannot deduce in the other direction, because ARG2 is
24224              a pack expansion but ARG1 is not.*/
24225           deduce1 = 0;
24226         }
24227 
24228       else
24229         {
24230           /* The normal case, where neither argument is a pack
24231              expansion.  */
24232           deduce1 = (unify (tparms1, targs1, arg1, arg2,
24233 			    UNIFY_ALLOW_NONE, /*explain_p=*/false)
24234 		     == 0);
24235           deduce2 = (unify (tparms2, targs2, arg2, arg1,
24236 			    UNIFY_ALLOW_NONE, /*explain_p=*/false)
24237 		     == 0);
24238         }
24239 
24240       /* If we couldn't deduce arguments for tparms1 to make arg1 match
24241 	 arg2, then arg2 is not as specialized as arg1.  */
24242       if (!deduce1)
24243 	lose2 = true;
24244       if (!deduce2)
24245 	lose1 = true;
24246 
24247       /* "If, for a given type, deduction succeeds in both directions
24248 	 (i.e., the types are identical after the transformations above)
24249 	 and both P and A were reference types (before being replaced with
24250 	 the type referred to above):
24251 	 - if the type from the argument template was an lvalue reference and
24252 	 the type from the parameter template was not, the argument type is
24253 	 considered to be more specialized than the other; otherwise,
24254 	 - if the type from the argument template is more cv-qualified
24255 	 than the type from the parameter template (as described above),
24256 	 the argument type is considered to be more specialized than the other;
24257 	 otherwise,
24258 	 - neither type is more specialized than the other."  */
24259 
24260       if (deduce1 && deduce2)
24261 	{
24262 	  if (ref1 && ref2 && ref1 != ref2)
24263 	    {
24264 	      if (ref1 > ref2)
24265 		lose1 = true;
24266 	      else
24267 		lose2 = true;
24268 	    }
24269 	  else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
24270 	    {
24271 	      if ((quals1 & quals2) == quals2)
24272 		lose2 = true;
24273 	      if ((quals1 & quals2) == quals1)
24274 		lose1 = true;
24275 	    }
24276 	}
24277 
24278       if (lose1 && lose2)
24279 	/* We've failed to deduce something in either direction.
24280 	   These must be unordered.  */
24281 	break;
24282 
24283     next:
24284 
24285       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
24286           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
24287         /* We have already processed all of the arguments in our
24288            handing of the pack expansion type.  */
24289         len = 0;
24290 
24291       args1 = TREE_CHAIN (args1);
24292       args2 = TREE_CHAIN (args2);
24293     }
24294 
24295   /* "In most cases, all template parameters must have values in order for
24296      deduction to succeed, but for partial ordering purposes a template
24297      parameter may remain without a value provided it is not used in the
24298      types being used for partial ordering."
24299 
24300      Thus, if we are missing any of the targs1 we need to substitute into
24301      origs1, then pat2 is not as specialized as pat1.  This can happen when
24302      there is a nondeduced context.  */
24303   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
24304     lose2 = true;
24305   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
24306     lose1 = true;
24307 
24308   processing_template_decl--;
24309 
24310   /* If both deductions succeed, the partial ordering selects the more
24311      constrained template.  */
24312   /* P2113: If the corresponding template-parameters of the
24313      template-parameter-lists are not equivalent ([temp.over.link]) or if
24314      the function parameters that positionally correspond between the two
24315      templates are not of the same type, neither template is more
24316      specialized than the other.  */
24317   if (!lose1 && !lose2
24318       && comp_template_parms (DECL_TEMPLATE_PARMS (pat1),
24319 			      DECL_TEMPLATE_PARMS (pat2))
24320       && compparms (origs1, origs2))
24321     {
24322       int winner = more_constrained (decl1, decl2);
24323       if (winner > 0)
24324 	lose2 = true;
24325       else if (winner < 0)
24326 	lose1 = true;
24327     }
24328 
24329   /* All things being equal, if the next argument is a pack expansion
24330      for one function but not for the other, prefer the
24331      non-variadic function.  FIXME this is bogus; see c++/41958.  */
24332   if (lose1 == lose2
24333       && args1 && TREE_VALUE (args1)
24334       && args2 && TREE_VALUE (args2))
24335     {
24336       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
24337       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
24338     }
24339 
24340   if (lose1 == lose2)
24341     return 0;
24342   else if (!lose1)
24343     return 1;
24344   else
24345     return -1;
24346 }
24347 
24348 /* Determine which of two partial specializations of TMPL is more
24349    specialized.
24350 
24351    PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
24352    to the first partial specialization.  The TREE_PURPOSE is the
24353    innermost set of template parameters for the partial
24354    specialization.  PAT2 is similar, but for the second template.
24355 
24356    Return 1 if the first partial specialization is more specialized;
24357    -1 if the second is more specialized; 0 if neither is more
24358    specialized.
24359 
24360    See [temp.class.order] for information about determining which of
24361    two templates is more specialized.  */
24362 
24363 static int
more_specialized_partial_spec(tree tmpl,tree pat1,tree pat2)24364 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
24365 {
24366   tree targs;
24367   int winner = 0;
24368   bool any_deductions = false;
24369 
24370   tree tmpl1 = TREE_VALUE (pat1);
24371   tree tmpl2 = TREE_VALUE (pat2);
24372   tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
24373   tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
24374 
24375   /* Just like what happens for functions, if we are ordering between
24376      different template specializations, we may encounter dependent
24377      types in the arguments, and we need our dependency check functions
24378      to behave correctly.  */
24379   ++processing_template_decl;
24380   targs = get_partial_spec_bindings (tmpl, tmpl1, specargs2);
24381   if (targs)
24382     {
24383       --winner;
24384       any_deductions = true;
24385     }
24386 
24387   targs = get_partial_spec_bindings (tmpl, tmpl2, specargs1);
24388   if (targs)
24389     {
24390       ++winner;
24391       any_deductions = true;
24392     }
24393   --processing_template_decl;
24394 
24395   /* If both deductions succeed, the partial ordering selects the more
24396      constrained template.  */
24397   if (!winner && any_deductions)
24398     winner = more_constrained (tmpl1, tmpl2);
24399 
24400   /* In the case of a tie where at least one of the templates
24401      has a parameter pack at the end, the template with the most
24402      non-packed parameters wins.  */
24403   if (winner == 0
24404       && any_deductions
24405       && (template_args_variadic_p (TREE_PURPOSE (pat1))
24406           || template_args_variadic_p (TREE_PURPOSE (pat2))))
24407     {
24408       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
24409       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
24410       int len1 = TREE_VEC_LENGTH (args1);
24411       int len2 = TREE_VEC_LENGTH (args2);
24412 
24413       /* We don't count the pack expansion at the end.  */
24414       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
24415         --len1;
24416       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
24417         --len2;
24418 
24419       if (len1 > len2)
24420         return 1;
24421       else if (len1 < len2)
24422         return -1;
24423     }
24424 
24425   return winner;
24426 }
24427 
24428 /* Return the template arguments that will produce the function signature
24429    DECL from the function template FN, with the explicit template
24430    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
24431    also match.  Return NULL_TREE if no satisfactory arguments could be
24432    found.  */
24433 
24434 static tree
get_bindings(tree fn,tree decl,tree explicit_args,bool check_rettype)24435 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
24436 {
24437   int ntparms = DECL_NTPARMS (fn);
24438   tree targs = make_tree_vec (ntparms);
24439   tree decl_type = TREE_TYPE (decl);
24440   tree decl_arg_types;
24441   tree *args;
24442   unsigned int nargs, ix;
24443   tree arg;
24444 
24445   gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
24446 
24447   /* Never do unification on the 'this' parameter.  */
24448   decl_arg_types = skip_artificial_parms_for (decl,
24449 					      TYPE_ARG_TYPES (decl_type));
24450 
24451   nargs = list_length (decl_arg_types);
24452   args = XALLOCAVEC (tree, nargs);
24453   for (arg = decl_arg_types, ix = 0;
24454        arg != NULL_TREE && arg != void_list_node;
24455        arg = TREE_CHAIN (arg), ++ix)
24456     args[ix] = TREE_VALUE (arg);
24457 
24458   if (fn_type_unification (fn, explicit_args, targs,
24459 			   args, ix,
24460 			   (check_rettype || DECL_CONV_FN_P (fn)
24461 			    ? TREE_TYPE (decl_type) : NULL_TREE),
24462 			   DEDUCE_EXACT, LOOKUP_NORMAL, NULL,
24463 			   /*explain_p=*/false,
24464 			   /*decltype*/false)
24465       == error_mark_node)
24466     return NULL_TREE;
24467 
24468   return targs;
24469 }
24470 
24471 /* Return the innermost template arguments that, when applied to a partial
24472    specialization SPEC_TMPL of TMPL, yield the ARGS.
24473 
24474    For example, suppose we have:
24475 
24476      template <class T, class U> struct S {};
24477      template <class T> struct S<T*, int> {};
24478 
24479    Then, suppose we want to get `S<double*, int>'.  SPEC_TMPL will be the
24480    partial specialization and the ARGS will be {double*, int}.  The resulting
24481    vector will be {double}, indicating that `T' is bound to `double'.  */
24482 
24483 static tree
get_partial_spec_bindings(tree tmpl,tree spec_tmpl,tree args)24484 get_partial_spec_bindings (tree tmpl, tree spec_tmpl, tree args)
24485 {
24486   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
24487   tree spec_args
24488     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (spec_tmpl)));
24489   int i, ntparms = TREE_VEC_LENGTH (tparms);
24490   tree deduced_args;
24491   tree innermost_deduced_args;
24492 
24493   innermost_deduced_args = make_tree_vec (ntparms);
24494   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
24495     {
24496       deduced_args = copy_node (args);
24497       SET_TMPL_ARGS_LEVEL (deduced_args,
24498 			   TMPL_ARGS_DEPTH (deduced_args),
24499 			   innermost_deduced_args);
24500     }
24501   else
24502     deduced_args = innermost_deduced_args;
24503 
24504   bool tried_array_deduction = (cxx_dialect < cxx17);
24505  again:
24506   if (unify (tparms, deduced_args,
24507 	     INNERMOST_TEMPLATE_ARGS (spec_args),
24508 	     INNERMOST_TEMPLATE_ARGS (args),
24509 	     UNIFY_ALLOW_NONE, /*explain_p=*/false))
24510     return NULL_TREE;
24511 
24512   for (i =  0; i < ntparms; ++i)
24513     if (! TREE_VEC_ELT (innermost_deduced_args, i))
24514       {
24515 	if (!tried_array_deduction)
24516 	  {
24517 	    try_array_deduction (tparms, innermost_deduced_args,
24518 				 INNERMOST_TEMPLATE_ARGS (spec_args));
24519 	    tried_array_deduction = true;
24520 	    if (TREE_VEC_ELT (innermost_deduced_args, i))
24521 	      goto again;
24522 	  }
24523 	return NULL_TREE;
24524       }
24525 
24526   if (!push_tinst_level (spec_tmpl, deduced_args))
24527     {
24528       excessive_deduction_depth = true;
24529       return NULL_TREE;
24530     }
24531 
24532   /* Verify that nondeduced template arguments agree with the type
24533      obtained from argument deduction.
24534 
24535      For example:
24536 
24537        struct A { typedef int X; };
24538        template <class T, class U> struct C {};
24539        template <class T> struct C<T, typename T::X> {};
24540 
24541      Then with the instantiation `C<A, int>', we can deduce that
24542      `T' is `A' but unify () does not check whether `typename T::X'
24543      is `int'.  */
24544   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
24545 
24546   if (spec_args != error_mark_node)
24547     spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
24548 				       INNERMOST_TEMPLATE_ARGS (spec_args),
24549 				       tmpl, tf_none, false, false);
24550 
24551   pop_tinst_level ();
24552 
24553   if (spec_args == error_mark_node
24554       /* We only need to check the innermost arguments; the other
24555 	 arguments will always agree.  */
24556       || !comp_template_args_porder (INNERMOST_TEMPLATE_ARGS (spec_args),
24557 				     INNERMOST_TEMPLATE_ARGS (args)))
24558     return NULL_TREE;
24559 
24560   /* Now that we have bindings for all of the template arguments,
24561      ensure that the arguments deduced for the template template
24562      parameters have compatible template parameter lists.  See the use
24563      of template_template_parm_bindings_ok_p in fn_type_unification
24564      for more information.  */
24565   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
24566     return NULL_TREE;
24567 
24568   return deduced_args;
24569 }
24570 
24571 // Compare two function templates T1 and T2 by deducing bindings
24572 // from one against the other. If both deductions succeed, compare
24573 // constraints to see which is more constrained.
24574 static int
more_specialized_inst(tree t1,tree t2)24575 more_specialized_inst (tree t1, tree t2)
24576 {
24577   int fate = 0;
24578   int count = 0;
24579 
24580   if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
24581     {
24582       --fate;
24583       ++count;
24584     }
24585 
24586   if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
24587     {
24588       ++fate;
24589       ++count;
24590     }
24591 
24592   // If both deductions succeed, then one may be more constrained.
24593   if (count == 2 && fate == 0)
24594     fate = more_constrained (t1, t2);
24595 
24596   return fate;
24597 }
24598 
24599 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
24600    Return the TREE_LIST node with the most specialized template, if
24601    any.  If there is no most specialized template, the error_mark_node
24602    is returned.
24603 
24604    Note that this function does not look at, or modify, the
24605    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
24606    returned is one of the elements of INSTANTIATIONS, callers may
24607    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
24608    and retrieve it from the value returned.  */
24609 
24610 tree
most_specialized_instantiation(tree templates)24611 most_specialized_instantiation (tree templates)
24612 {
24613   tree fn, champ;
24614 
24615   ++processing_template_decl;
24616 
24617   champ = templates;
24618   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
24619     {
24620       gcc_assert (TREE_VALUE (champ) != TREE_VALUE (fn));
24621       int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
24622       if (fate == -1)
24623 	champ = fn;
24624       else if (!fate)
24625 	{
24626 	  /* Equally specialized, move to next function.  If there
24627 	     is no next function, nothing's most specialized.  */
24628 	  fn = TREE_CHAIN (fn);
24629 	  champ = fn;
24630 	  if (!fn)
24631 	    break;
24632 	}
24633     }
24634 
24635   if (champ)
24636     /* Now verify that champ is better than everything earlier in the
24637        instantiation list.  */
24638     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
24639       if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
24640       {
24641         champ = NULL_TREE;
24642         break;
24643       }
24644     }
24645 
24646   processing_template_decl--;
24647 
24648   if (!champ)
24649     return error_mark_node;
24650 
24651   return champ;
24652 }
24653 
24654 /* If DECL is a specialization of some template, return the most
24655    general such template.  Otherwise, returns NULL_TREE.
24656 
24657    For example, given:
24658 
24659      template <class T> struct S { template <class U> void f(U); };
24660 
24661    if TMPL is `template <class U> void S<int>::f(U)' this will return
24662    the full template.  This function will not trace past partial
24663    specializations, however.  For example, given in addition:
24664 
24665      template <class T> struct S<T*> { template <class U> void f(U); };
24666 
24667    if TMPL is `template <class U> void S<int*>::f(U)' this will return
24668    `template <class T> template <class U> S<T*>::f(U)'.  */
24669 
24670 tree
most_general_template(tree decl)24671 most_general_template (tree decl)
24672 {
24673   if (TREE_CODE (decl) != TEMPLATE_DECL)
24674     {
24675       if (tree tinfo = get_template_info (decl))
24676 	decl = TI_TEMPLATE (tinfo);
24677       /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
24678 	 template friend, or a FIELD_DECL for a capture pack.  */
24679       if (TREE_CODE (decl) != TEMPLATE_DECL)
24680 	return NULL_TREE;
24681     }
24682 
24683   /* Look for more and more general templates.  */
24684   while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
24685     {
24686       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
24687 	 (See cp-tree.h for details.)  */
24688       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
24689 	break;
24690 
24691       if (CLASS_TYPE_P (TREE_TYPE (decl))
24692 	  && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
24693 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
24694 	break;
24695 
24696       /* Stop if we run into an explicitly specialized class template.  */
24697       if (!DECL_NAMESPACE_SCOPE_P (decl)
24698 	  && DECL_CONTEXT (decl)
24699 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
24700 	break;
24701 
24702       decl = DECL_TI_TEMPLATE (decl);
24703     }
24704 
24705   return decl;
24706 }
24707 
24708 /* Return the most specialized of the template partial specializations
24709    which can produce TARGET, a specialization of some class or variable
24710    template.  The value returned is actually a TREE_LIST; the TREE_VALUE is
24711    a TEMPLATE_DECL node corresponding to the partial specialization, while
24712    the TREE_PURPOSE is the set of template arguments that must be
24713    substituted into the template pattern in order to generate TARGET.
24714 
24715    If the choice of partial specialization is ambiguous, a diagnostic
24716    is issued, and the error_mark_node is returned.  If there are no
24717    partial specializations matching TARGET, then NULL_TREE is
24718    returned, indicating that the primary template should be used.  */
24719 
24720 tree
most_specialized_partial_spec(tree target,tsubst_flags_t complain)24721 most_specialized_partial_spec (tree target, tsubst_flags_t complain)
24722 {
24723   tree list = NULL_TREE;
24724   tree t;
24725   tree champ;
24726   int fate;
24727   bool ambiguous_p;
24728   tree outer_args = NULL_TREE;
24729   tree tmpl, args;
24730 
24731   if (TYPE_P (target))
24732     {
24733       tree tinfo = CLASSTYPE_TEMPLATE_INFO (target);
24734       tmpl = TI_TEMPLATE (tinfo);
24735       args = TI_ARGS (tinfo);
24736     }
24737   else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
24738     {
24739       tmpl = TREE_OPERAND (target, 0);
24740       args = TREE_OPERAND (target, 1);
24741     }
24742   else if (VAR_P (target))
24743     {
24744       tree tinfo = DECL_TEMPLATE_INFO (target);
24745       tmpl = TI_TEMPLATE (tinfo);
24746       args = TI_ARGS (tinfo);
24747     }
24748   else
24749     gcc_unreachable ();
24750 
24751   tree main_tmpl = most_general_template (tmpl);
24752 
24753   /* For determining which partial specialization to use, only the
24754      innermost args are interesting.  */
24755   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
24756     {
24757       outer_args = strip_innermost_template_args (args, 1);
24758       args = INNERMOST_TEMPLATE_ARGS (args);
24759     }
24760 
24761   /* The caller hasn't called push_to_top_level yet, but we need
24762      get_partial_spec_bindings to be done in non-template context so that we'll
24763      fully resolve everything.  */
24764   processing_template_decl_sentinel ptds;
24765 
24766   for (t = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl); t; t = TREE_CHAIN (t))
24767     {
24768       const tree ospec_tmpl = TREE_VALUE (t);
24769 
24770       tree spec_tmpl;
24771       if (outer_args)
24772 	{
24773 	  /* Substitute in the template args from the enclosing class.  */
24774 	  ++processing_template_decl;
24775 	  spec_tmpl = tsubst (ospec_tmpl, outer_args, tf_none, NULL_TREE);
24776 	  --processing_template_decl;
24777 	  if (spec_tmpl == error_mark_node)
24778 	    return error_mark_node;
24779 	}
24780       else
24781 	spec_tmpl = ospec_tmpl;
24782 
24783       tree spec_args = get_partial_spec_bindings (tmpl, spec_tmpl, args);
24784       if (spec_args)
24785 	{
24786 	  if (outer_args)
24787 	    spec_args = add_to_template_args (outer_args, spec_args);
24788 
24789           /* Keep the candidate only if the constraints are satisfied,
24790              or if we're not compiling with concepts.  */
24791           if (!flag_concepts
24792 	      || constraints_satisfied_p (ospec_tmpl, spec_args))
24793             {
24794 	      list = tree_cons (spec_args, ospec_tmpl, list);
24795               TREE_TYPE (list) = TREE_TYPE (t);
24796             }
24797 	}
24798     }
24799 
24800   if (! list)
24801     return NULL_TREE;
24802 
24803   ambiguous_p = false;
24804   t = list;
24805   champ = t;
24806   t = TREE_CHAIN (t);
24807   for (; t; t = TREE_CHAIN (t))
24808     {
24809       fate = more_specialized_partial_spec (tmpl, champ, t);
24810       if (fate == 1)
24811 	;
24812       else
24813 	{
24814 	  if (fate == 0)
24815 	    {
24816 	      t = TREE_CHAIN (t);
24817 	      if (! t)
24818 		{
24819 		  ambiguous_p = true;
24820 		  break;
24821 		}
24822 	    }
24823 	  champ = t;
24824 	}
24825     }
24826 
24827   if (!ambiguous_p)
24828     for (t = list; t && t != champ; t = TREE_CHAIN (t))
24829       {
24830 	fate = more_specialized_partial_spec (tmpl, champ, t);
24831 	if (fate != 1)
24832 	  {
24833 	    ambiguous_p = true;
24834 	    break;
24835 	  }
24836       }
24837 
24838   if (ambiguous_p)
24839     {
24840       const char *str;
24841       char *spaces = NULL;
24842       if (!(complain & tf_error))
24843 	return error_mark_node;
24844       if (TYPE_P (target))
24845 	error ("ambiguous template instantiation for %q#T", target);
24846       else
24847 	error ("ambiguous template instantiation for %q#D", target);
24848       str = ngettext ("candidate is:", "candidates are:", list_length (list));
24849       for (t = list; t; t = TREE_CHAIN (t))
24850         {
24851 	  tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
24852           inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
24853 		  "%s %#qS", spaces ? spaces : str, subst);
24854           spaces = spaces ? spaces : get_spaces (str);
24855         }
24856       free (spaces);
24857       return error_mark_node;
24858     }
24859 
24860   return champ;
24861 }
24862 
24863 /* Explicitly instantiate DECL.  */
24864 
24865 void
do_decl_instantiation(tree decl,tree storage)24866 do_decl_instantiation (tree decl, tree storage)
24867 {
24868   tree result = NULL_TREE;
24869   int extern_p = 0;
24870 
24871   if (!decl || decl == error_mark_node)
24872     /* An error occurred, for which grokdeclarator has already issued
24873        an appropriate message.  */
24874     return;
24875   else if (! DECL_LANG_SPECIFIC (decl))
24876     {
24877       error ("explicit instantiation of non-template %q#D", decl);
24878       return;
24879     }
24880   else if (DECL_DECLARED_CONCEPT_P (decl))
24881     {
24882       if (VAR_P (decl))
24883 	error ("explicit instantiation of variable concept %q#D", decl);
24884       else
24885 	error ("explicit instantiation of function concept %q#D", decl);
24886       return;
24887     }
24888 
24889   bool var_templ = (DECL_TEMPLATE_INFO (decl)
24890                     && variable_template_p (DECL_TI_TEMPLATE (decl)));
24891 
24892   if (VAR_P (decl) && !var_templ)
24893     {
24894       /* There is an asymmetry here in the way VAR_DECLs and
24895 	 FUNCTION_DECLs are handled by grokdeclarator.  In the case of
24896 	 the latter, the DECL we get back will be marked as a
24897 	 template instantiation, and the appropriate
24898 	 DECL_TEMPLATE_INFO will be set up.  This does not happen for
24899 	 VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
24900 	 should handle VAR_DECLs as it currently handles
24901 	 FUNCTION_DECLs.  */
24902       if (!DECL_CLASS_SCOPE_P (decl))
24903 	{
24904 	  error ("%qD is not a static data member of a class template", decl);
24905 	  return;
24906 	}
24907       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
24908       if (!result || !VAR_P (result))
24909 	{
24910 	  error ("no matching template for %qD found", decl);
24911 	  return;
24912 	}
24913       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
24914 	{
24915 	  error ("type %qT for explicit instantiation %qD does not match "
24916 		 "declared type %qT", TREE_TYPE (result), decl,
24917 		 TREE_TYPE (decl));
24918 	  return;
24919 	}
24920     }
24921   else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
24922     {
24923       error ("explicit instantiation of %q#D", decl);
24924       return;
24925     }
24926   else
24927     result = decl;
24928 
24929   /* Check for various error cases.  Note that if the explicit
24930      instantiation is valid the RESULT will currently be marked as an
24931      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
24932      until we get here.  */
24933 
24934   if (DECL_TEMPLATE_SPECIALIZATION (result))
24935     {
24936       /* DR 259 [temp.spec].
24937 
24938 	 Both an explicit instantiation and a declaration of an explicit
24939 	 specialization shall not appear in a program unless the explicit
24940 	 instantiation follows a declaration of the explicit specialization.
24941 
24942 	 For a given set of template parameters, if an explicit
24943 	 instantiation of a template appears after a declaration of an
24944 	 explicit specialization for that template, the explicit
24945 	 instantiation has no effect.  */
24946       return;
24947     }
24948   else if (DECL_EXPLICIT_INSTANTIATION (result))
24949     {
24950       /* [temp.spec]
24951 
24952 	 No program shall explicitly instantiate any template more
24953 	 than once.
24954 
24955 	 We check DECL_NOT_REALLY_EXTERN so as not to complain when
24956 	 the first instantiation was `extern' and the second is not,
24957 	 and EXTERN_P for the opposite case.  */
24958       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
24959 	permerror (input_location, "duplicate explicit instantiation of %q#D", result);
24960       /* If an "extern" explicit instantiation follows an ordinary
24961 	 explicit instantiation, the template is instantiated.  */
24962       if (extern_p)
24963 	return;
24964     }
24965   else if (!DECL_IMPLICIT_INSTANTIATION (result))
24966     {
24967       error ("no matching template for %qD found", result);
24968       return;
24969     }
24970   else if (!DECL_TEMPLATE_INFO (result))
24971     {
24972       permerror (input_location, "explicit instantiation of non-template %q#D", result);
24973       return;
24974     }
24975 
24976   if (storage == NULL_TREE)
24977     ;
24978   else if (storage == ridpointers[(int) RID_EXTERN])
24979     {
24980       if (cxx_dialect == cxx98)
24981 	pedwarn (input_location, OPT_Wpedantic,
24982 		 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
24983 		 "instantiations");
24984       extern_p = 1;
24985     }
24986   else
24987     error ("storage class %qD applied to template instantiation", storage);
24988 
24989   check_explicit_instantiation_namespace (result);
24990   mark_decl_instantiated (result, extern_p);
24991   if (! extern_p)
24992     instantiate_decl (result, /*defer_ok=*/true,
24993 		      /*expl_inst_class_mem_p=*/false);
24994 }
24995 
24996 static void
mark_class_instantiated(tree t,int extern_p)24997 mark_class_instantiated (tree t, int extern_p)
24998 {
24999   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
25000   SET_CLASSTYPE_INTERFACE_KNOWN (t);
25001   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
25002   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
25003   if (! extern_p)
25004     {
25005       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
25006       rest_of_type_compilation (t, 1);
25007     }
25008 }
25009 
25010 /* Called from do_type_instantiation through binding_table_foreach to
25011    do recursive instantiation for the type bound in ENTRY.  */
25012 static void
bt_instantiate_type_proc(binding_entry entry,void * data)25013 bt_instantiate_type_proc (binding_entry entry, void *data)
25014 {
25015   tree storage = *(tree *) data;
25016 
25017   if (MAYBE_CLASS_TYPE_P (entry->type)
25018       && CLASSTYPE_TEMPLATE_INFO (entry->type)
25019       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
25020     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
25021 }
25022 
25023 /* Perform an explicit instantiation of template class T.  STORAGE, if
25024    non-null, is the RID for extern, inline or static.  COMPLAIN is
25025    nonzero if this is called from the parser, zero if called recursively,
25026    since the standard is unclear (as detailed below).  */
25027 
25028 void
do_type_instantiation(tree t,tree storage,tsubst_flags_t complain)25029 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
25030 {
25031   int extern_p = 0;
25032   int nomem_p = 0;
25033   int static_p = 0;
25034   int previous_instantiation_extern_p = 0;
25035 
25036   if (TREE_CODE (t) == TYPE_DECL)
25037     t = TREE_TYPE (t);
25038 
25039   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
25040     {
25041       tree tmpl =
25042 	(TYPE_TEMPLATE_INFO (t)) ? TYPE_TI_TEMPLATE (t) : NULL;
25043       if (tmpl)
25044 	error ("explicit instantiation of non-class template %qD", tmpl);
25045       else
25046 	error ("explicit instantiation of non-template type %qT", t);
25047       return;
25048     }
25049 
25050   complete_type (t);
25051 
25052   if (!COMPLETE_TYPE_P (t))
25053     {
25054       if (complain & tf_error)
25055 	error ("explicit instantiation of %q#T before definition of template",
25056 	       t);
25057       return;
25058     }
25059 
25060   if (storage != NULL_TREE)
25061     {
25062       if (storage == ridpointers[(int) RID_EXTERN])
25063 	{
25064 	  if (cxx_dialect == cxx98)
25065 	    pedwarn (input_location, OPT_Wpedantic,
25066 		     "ISO C++ 1998 forbids the use of %<extern%> on "
25067 		     "explicit instantiations");
25068 	}
25069       else
25070 	pedwarn (input_location, OPT_Wpedantic,
25071 		 "ISO C++ forbids the use of %qE"
25072 		 " on explicit instantiations", storage);
25073 
25074       if (storage == ridpointers[(int) RID_INLINE])
25075 	nomem_p = 1;
25076       else if (storage == ridpointers[(int) RID_EXTERN])
25077 	extern_p = 1;
25078       else if (storage == ridpointers[(int) RID_STATIC])
25079 	static_p = 1;
25080       else
25081 	{
25082 	  error ("storage class %qD applied to template instantiation",
25083 		 storage);
25084 	  extern_p = 0;
25085 	}
25086     }
25087 
25088   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
25089     {
25090       /* DR 259 [temp.spec].
25091 
25092 	 Both an explicit instantiation and a declaration of an explicit
25093 	 specialization shall not appear in a program unless the explicit
25094 	 instantiation follows a declaration of the explicit specialization.
25095 
25096 	 For a given set of template parameters, if an explicit
25097 	 instantiation of a template appears after a declaration of an
25098 	 explicit specialization for that template, the explicit
25099 	 instantiation has no effect.  */
25100       return;
25101     }
25102   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
25103     {
25104       /* [temp.spec]
25105 
25106 	 No program shall explicitly instantiate any template more
25107 	 than once.
25108 
25109 	 If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
25110 	 instantiation was `extern'.  If EXTERN_P then the second is.
25111 	 These cases are OK.  */
25112       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
25113 
25114       if (!previous_instantiation_extern_p && !extern_p
25115 	  && (complain & tf_error))
25116 	permerror (input_location, "duplicate explicit instantiation of %q#T", t);
25117 
25118       /* If we've already instantiated the template, just return now.  */
25119       if (!CLASSTYPE_INTERFACE_ONLY (t))
25120 	return;
25121     }
25122 
25123   check_explicit_instantiation_namespace (TYPE_NAME (t));
25124   mark_class_instantiated (t, extern_p);
25125 
25126   if (nomem_p)
25127     return;
25128 
25129   /* In contrast to implicit instantiation, where only the
25130      declarations, and not the definitions, of members are
25131      instantiated, we have here:
25132 
25133 	 [temp.explicit]
25134 
25135 	 An explicit instantiation that names a class template
25136 	 specialization is also an explicit instantiation of the same
25137 	 kind (declaration or definition) of each of its members (not
25138 	 including members inherited from base classes and members
25139 	 that are templates) that has not been previously explicitly
25140 	 specialized in the translation unit containing the explicit
25141 	 instantiation, provided that the associated constraints, if
25142 	 any, of that member are satisfied by the template arguments
25143 	 of the explicit instantiation.  */
25144   for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
25145     if ((VAR_P (fld)
25146 	 || (TREE_CODE (fld) == FUNCTION_DECL
25147 	     && !static_p
25148 	     && user_provided_p (fld)))
25149 	&& DECL_TEMPLATE_INSTANTIATION (fld)
25150 	&& constraints_satisfied_p (fld))
25151       {
25152 	mark_decl_instantiated (fld, extern_p);
25153 	if (! extern_p)
25154 	  instantiate_decl (fld, /*defer_ok=*/true,
25155 			    /*expl_inst_class_mem_p=*/true);
25156       }
25157 
25158   if (CLASSTYPE_NESTED_UTDS (t))
25159     binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
25160 			   bt_instantiate_type_proc, &storage);
25161 }
25162 
25163 /* Given a function DECL, which is a specialization of TMPL, modify
25164    DECL to be a re-instantiation of TMPL with the same template
25165    arguments.  TMPL should be the template into which tsubst'ing
25166    should occur for DECL, not the most general template.
25167 
25168    One reason for doing this is a scenario like this:
25169 
25170      template <class T>
25171      void f(const T&, int i);
25172 
25173      void g() { f(3, 7); }
25174 
25175      template <class T>
25176      void f(const T& t, const int i) { }
25177 
25178    Note that when the template is first instantiated, with
25179    instantiate_template, the resulting DECL will have no name for the
25180    first parameter, and the wrong type for the second.  So, when we go
25181    to instantiate the DECL, we regenerate it.  */
25182 
25183 static void
regenerate_decl_from_template(tree decl,tree tmpl,tree args)25184 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
25185 {
25186   /* The arguments used to instantiate DECL, from the most general
25187      template.  */
25188   tree code_pattern;
25189 
25190   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
25191 
25192   /* Make sure that we can see identifiers, and compute access
25193      correctly.  */
25194   push_access_scope (decl);
25195 
25196   if (TREE_CODE (decl) == FUNCTION_DECL)
25197     {
25198       tree decl_parm;
25199       tree pattern_parm;
25200       tree specs;
25201       int args_depth;
25202       int parms_depth;
25203 
25204       args_depth = TMPL_ARGS_DEPTH (args);
25205       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
25206       if (args_depth > parms_depth)
25207 	args = get_innermost_template_args (args, parms_depth);
25208 
25209       /* Instantiate a dynamic exception-specification.  noexcept will be
25210 	 handled below.  */
25211       if (tree raises = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (code_pattern)))
25212 	if (TREE_VALUE (raises))
25213 	  {
25214 	    specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
25215 						    args, tf_error, NULL_TREE,
25216 						    /*defer_ok*/false);
25217 	    if (specs && specs != error_mark_node)
25218 	      TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
25219 							  specs);
25220 	  }
25221 
25222       /* Merge parameter declarations.  */
25223       decl_parm = skip_artificial_parms_for (decl,
25224 					     DECL_ARGUMENTS (decl));
25225       pattern_parm
25226 	= skip_artificial_parms_for (code_pattern,
25227 				     DECL_ARGUMENTS (code_pattern));
25228       while (decl_parm && !DECL_PACK_P (pattern_parm))
25229 	{
25230 	  tree parm_type;
25231 	  tree attributes;
25232 
25233 	  if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
25234 	    DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
25235 	  parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
25236 			      NULL_TREE);
25237 	  parm_type = type_decays_to (parm_type);
25238 	  if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
25239 	    TREE_TYPE (decl_parm) = parm_type;
25240 	  attributes = DECL_ATTRIBUTES (pattern_parm);
25241 	  if (DECL_ATTRIBUTES (decl_parm) != attributes)
25242 	    {
25243 	      DECL_ATTRIBUTES (decl_parm) = attributes;
25244 	      cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
25245 	    }
25246 	  decl_parm = DECL_CHAIN (decl_parm);
25247 	  pattern_parm = DECL_CHAIN (pattern_parm);
25248 	}
25249       /* Merge any parameters that match with the function parameter
25250          pack.  */
25251       if (pattern_parm && DECL_PACK_P (pattern_parm))
25252         {
25253           int i, len;
25254           tree expanded_types;
25255           /* Expand the TYPE_PACK_EXPANSION that provides the types for
25256              the parameters in this function parameter pack.  */
25257           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm),
25258                                                  args, tf_error, NULL_TREE);
25259           len = TREE_VEC_LENGTH (expanded_types);
25260           for (i = 0; i < len; i++)
25261             {
25262               tree parm_type;
25263               tree attributes;
25264 
25265               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
25266                 /* Rename the parameter to include the index.  */
25267                 DECL_NAME (decl_parm) =
25268                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
25269               parm_type = TREE_VEC_ELT (expanded_types, i);
25270               parm_type = type_decays_to (parm_type);
25271               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
25272                 TREE_TYPE (decl_parm) = parm_type;
25273               attributes = DECL_ATTRIBUTES (pattern_parm);
25274               if (DECL_ATTRIBUTES (decl_parm) != attributes)
25275                 {
25276                   DECL_ATTRIBUTES (decl_parm) = attributes;
25277                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
25278                 }
25279               decl_parm = DECL_CHAIN (decl_parm);
25280             }
25281         }
25282       /* Merge additional specifiers from the CODE_PATTERN.  */
25283       if (DECL_DECLARED_INLINE_P (code_pattern)
25284 	  && !DECL_DECLARED_INLINE_P (decl))
25285 	DECL_DECLARED_INLINE_P (decl) = 1;
25286 
25287       maybe_instantiate_noexcept (decl, tf_error);
25288     }
25289   else if (VAR_P (decl))
25290     {
25291       start_lambda_scope (decl);
25292       DECL_INITIAL (decl) =
25293 	tsubst_init (DECL_INITIAL (code_pattern), decl, args,
25294 		     tf_error, DECL_TI_TEMPLATE (decl));
25295       finish_lambda_scope ();
25296       if (VAR_HAD_UNKNOWN_BOUND (decl))
25297 	TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
25298 				   tf_error, DECL_TI_TEMPLATE (decl));
25299     }
25300   else
25301     gcc_unreachable ();
25302 
25303   pop_access_scope (decl);
25304 }
25305 
25306 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
25307    substituted to get DECL.  */
25308 
25309 tree
template_for_substitution(tree decl)25310 template_for_substitution (tree decl)
25311 {
25312   tree tmpl = DECL_TI_TEMPLATE (decl);
25313 
25314   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
25315      for the instantiation.  This is not always the most general
25316      template.  Consider, for example:
25317 
25318 	template <class T>
25319 	struct S { template <class U> void f();
25320 		   template <> void f<int>(); };
25321 
25322      and an instantiation of S<double>::f<int>.  We want TD to be the
25323      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
25324   while (/* An instantiation cannot have a definition, so we need a
25325 	    more general template.  */
25326 	 DECL_TEMPLATE_INSTANTIATION (tmpl)
25327 	   /* We must also deal with friend templates.  Given:
25328 
25329 		template <class T> struct S {
25330 		  template <class U> friend void f() {};
25331 		};
25332 
25333 	      S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
25334 	      so far as the language is concerned, but that's still
25335 	      where we get the pattern for the instantiation from.  On
25336 	      other hand, if the definition comes outside the class, say:
25337 
25338 		template <class T> struct S {
25339 		  template <class U> friend void f();
25340 		};
25341 		template <class U> friend void f() {}
25342 
25343 	      we don't need to look any further.  That's what the check for
25344 	      DECL_INITIAL is for.  */
25345 	  || (TREE_CODE (decl) == FUNCTION_DECL
25346 	      && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
25347 	      && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
25348     {
25349       /* The present template, TD, should not be a definition.  If it
25350 	 were a definition, we should be using it!  Note that we
25351 	 cannot restructure the loop to just keep going until we find
25352 	 a template with a definition, since that might go too far if
25353 	 a specialization was declared, but not defined.  */
25354 
25355       /* Fetch the more general template.  */
25356       tmpl = DECL_TI_TEMPLATE (tmpl);
25357     }
25358 
25359   return tmpl;
25360 }
25361 
25362 /* Returns true if we need to instantiate this template instance even if we
25363    know we aren't going to emit it.  */
25364 
25365 bool
always_instantiate_p(tree decl)25366 always_instantiate_p (tree decl)
25367 {
25368   /* We always instantiate inline functions so that we can inline them.  An
25369      explicit instantiation declaration prohibits implicit instantiation of
25370      non-inline functions.  With high levels of optimization, we would
25371      normally inline non-inline functions -- but we're not allowed to do
25372      that for "extern template" functions.  Therefore, we check
25373      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
25374   return ((TREE_CODE (decl) == FUNCTION_DECL
25375 	   && (DECL_DECLARED_INLINE_P (decl)
25376 	       || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
25377 	  /* And we need to instantiate static data members so that
25378 	     their initializers are available in integral constant
25379 	     expressions.  */
25380 	  || (VAR_P (decl)
25381 	      && decl_maybe_constant_var_p (decl)));
25382 }
25383 
25384 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
25385    instantiate it now, modifying TREE_TYPE (fn).  Returns false on
25386    error, true otherwise.  */
25387 
25388 bool
maybe_instantiate_noexcept(tree fn,tsubst_flags_t complain)25389 maybe_instantiate_noexcept (tree fn, tsubst_flags_t complain)
25390 {
25391   tree fntype, spec, noex, clone;
25392 
25393   if (fn == error_mark_node)
25394     return false;
25395 
25396   /* Don't instantiate a noexcept-specification from template context.  */
25397   if (processing_template_decl
25398       && (!flag_noexcept_type || type_dependent_expression_p (fn)))
25399     return true;
25400 
25401   if (DECL_MAYBE_DELETED (fn))
25402     {
25403       if (fn == current_function_decl)
25404 	/* We're in start_preparsed_function, keep going.  */
25405 	return true;
25406 
25407       ++function_depth;
25408       synthesize_method (fn);
25409       --function_depth;
25410       return !DECL_MAYBE_DELETED (fn);
25411     }
25412 
25413   if (DECL_CLONED_FUNCTION_P (fn))
25414     fn = DECL_CLONED_FUNCTION (fn);
25415 
25416   tree orig_fn = NULL_TREE;
25417   /* For a member friend template we can get a TEMPLATE_DECL.  Let's use
25418      its FUNCTION_DECL for the rest of this function -- push_access_scope
25419      doesn't accept TEMPLATE_DECLs.  */
25420   if (DECL_FUNCTION_TEMPLATE_P (fn))
25421     {
25422       orig_fn = fn;
25423       fn = DECL_TEMPLATE_RESULT (fn);
25424     }
25425 
25426   fntype = TREE_TYPE (fn);
25427   spec = TYPE_RAISES_EXCEPTIONS (fntype);
25428 
25429   if (!spec || !TREE_PURPOSE (spec))
25430     return true;
25431 
25432   noex = TREE_PURPOSE (spec);
25433 
25434   if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
25435     {
25436       static hash_set<tree>* fns = new hash_set<tree>;
25437       bool added = false;
25438       if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
25439 	{
25440 	  spec = get_defaulted_eh_spec (fn, complain);
25441 	  if (spec == error_mark_node)
25442 	    /* This might have failed because of an unparsed DMI, so
25443 	       let's try again later.  */
25444 	    return false;
25445 	}
25446       else if (!(added = !fns->add (fn)))
25447 	{
25448 	  /* If hash_set::add returns true, the element was already there.  */
25449 	  location_t loc = cp_expr_loc_or_loc (DEFERRED_NOEXCEPT_PATTERN (noex),
25450 					    DECL_SOURCE_LOCATION (fn));
25451 	  error_at (loc,
25452 		    "exception specification of %qD depends on itself",
25453 		    fn);
25454 	  spec = noexcept_false_spec;
25455 	}
25456       else if (push_tinst_level (fn))
25457 	{
25458 	  push_to_top_level ();
25459 	  push_access_scope (fn);
25460 	  push_deferring_access_checks (dk_no_deferred);
25461 	  input_location = DECL_SOURCE_LOCATION (fn);
25462 
25463 	  /* If needed, set current_class_ptr for the benefit of
25464 	     tsubst_copy/PARM_DECL.  */
25465 	  tree tdecl = DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (fn));
25466 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (tdecl))
25467 	    {
25468 	      tree this_parm = DECL_ARGUMENTS (tdecl);
25469 	      current_class_ptr = NULL_TREE;
25470 	      current_class_ref = cp_build_fold_indirect_ref (this_parm);
25471 	      current_class_ptr = this_parm;
25472 	    }
25473 
25474 	  /* If this function is represented by a TEMPLATE_DECL, then
25475 	     the deferred noexcept-specification might still contain
25476 	     dependent types, even after substitution.  And we need the
25477 	     dependency check functions to work in build_noexcept_spec.  */
25478 	  if (orig_fn)
25479 	    ++processing_template_decl;
25480 
25481 	  /* Do deferred instantiation of the noexcept-specifier.  */
25482 	  noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
25483 					DEFERRED_NOEXCEPT_ARGS (noex),
25484 					tf_warning_or_error, fn,
25485 					/*function_p=*/false,
25486 					/*i_c_e_p=*/true);
25487 
25488 	  /* Build up the noexcept-specification.  */
25489 	  spec = build_noexcept_spec (noex, tf_warning_or_error);
25490 
25491 	  if (orig_fn)
25492 	    --processing_template_decl;
25493 
25494 	  pop_deferring_access_checks ();
25495 	  pop_access_scope (fn);
25496 	  pop_tinst_level ();
25497 	  pop_from_top_level ();
25498 	}
25499       else
25500 	spec = noexcept_false_spec;
25501 
25502       if (added)
25503 	fns->remove (fn);
25504 
25505       if (spec == error_mark_node)
25506 	{
25507 	  /* This failed with a hard error, so let's go with false.  */
25508 	  gcc_assert (seen_error ());
25509 	  spec = noexcept_false_spec;
25510 	}
25511 
25512       TREE_TYPE (fn) = build_exception_variant (fntype, spec);
25513       if (orig_fn)
25514 	TREE_TYPE (orig_fn) = TREE_TYPE (fn);
25515     }
25516 
25517   FOR_EACH_CLONE (clone, fn)
25518     {
25519       if (TREE_TYPE (clone) == fntype)
25520 	TREE_TYPE (clone) = TREE_TYPE (fn);
25521       else
25522 	TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone), spec);
25523     }
25524 
25525   return true;
25526 }
25527 
25528 /* We're starting to process the function INST, an instantiation of PATTERN;
25529    add their parameters to local_specializations.  */
25530 
25531 static void
register_parameter_specializations(tree pattern,tree inst)25532 register_parameter_specializations (tree pattern, tree inst)
25533 {
25534   tree tmpl_parm = DECL_ARGUMENTS (pattern);
25535   tree spec_parm = DECL_ARGUMENTS (inst);
25536   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (inst))
25537     {
25538       register_local_specialization (spec_parm, tmpl_parm);
25539       spec_parm = skip_artificial_parms_for (inst, spec_parm);
25540       tmpl_parm = skip_artificial_parms_for (pattern, tmpl_parm);
25541     }
25542   for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
25543     {
25544       if (!DECL_PACK_P (tmpl_parm))
25545 	{
25546 	  register_local_specialization (spec_parm, tmpl_parm);
25547 	  spec_parm = DECL_CHAIN (spec_parm);
25548 	}
25549       else
25550 	{
25551 	  /* Register the (value) argument pack as a specialization of
25552 	     TMPL_PARM, then move on.  */
25553 	  tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
25554 	  register_local_specialization (argpack, tmpl_parm);
25555 	}
25556     }
25557   gcc_assert (!spec_parm);
25558 }
25559 
25560 /* Produce the definition of D, a _DECL generated from a template.  If
25561    DEFER_OK is true, then we don't have to actually do the
25562    instantiation now; we just have to do it sometime.  Normally it is
25563    an error if this is an explicit instantiation but D is undefined.
25564    EXPL_INST_CLASS_MEM_P is true iff D is a member of an explicitly
25565    instantiated class template.  */
25566 
25567 tree
instantiate_decl(tree d,bool defer_ok,bool expl_inst_class_mem_p)25568 instantiate_decl (tree d, bool defer_ok, bool expl_inst_class_mem_p)
25569 {
25570   tree tmpl = DECL_TI_TEMPLATE (d);
25571   tree gen_args;
25572   tree args;
25573   tree td;
25574   tree code_pattern;
25575   tree spec;
25576   tree gen_tmpl;
25577   bool pattern_defined;
25578   location_t saved_loc = input_location;
25579   int saved_unevaluated_operand = cp_unevaluated_operand;
25580   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
25581   bool external_p;
25582   bool deleted_p;
25583 
25584   /* This function should only be used to instantiate templates for
25585      functions and static member variables.  */
25586   gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
25587 
25588   /* A concept is never instantiated. */
25589   gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
25590 
25591   /* Variables are never deferred; if instantiation is required, they
25592      are instantiated right away.  That allows for better code in the
25593      case that an expression refers to the value of the variable --
25594      if the variable has a constant value the referring expression can
25595      take advantage of that fact.  */
25596   if (VAR_P (d))
25597     defer_ok = false;
25598 
25599   /* Don't instantiate cloned functions.  Instead, instantiate the
25600      functions they cloned.  */
25601   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
25602     d = DECL_CLONED_FUNCTION (d);
25603 
25604   if (DECL_TEMPLATE_INSTANTIATED (d)
25605       || (TREE_CODE (d) == FUNCTION_DECL
25606 	  && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
25607       || DECL_TEMPLATE_SPECIALIZATION (d))
25608     /* D has already been instantiated or explicitly specialized, so
25609        there's nothing for us to do here.
25610 
25611        It might seem reasonable to check whether or not D is an explicit
25612        instantiation, and, if so, stop here.  But when an explicit
25613        instantiation is deferred until the end of the compilation,
25614        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
25615        the instantiation.  */
25616     return d;
25617 
25618   /* Check to see whether we know that this template will be
25619      instantiated in some other file, as with "extern template"
25620      extension.  */
25621   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
25622 
25623   /* In general, we do not instantiate such templates.  */
25624   if (external_p && !always_instantiate_p (d))
25625     return d;
25626 
25627   gen_tmpl = most_general_template (tmpl);
25628   gen_args = DECL_TI_ARGS (d);
25629 
25630   if (tmpl != gen_tmpl)
25631     /* We should already have the extra args.  */
25632     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
25633 		== TMPL_ARGS_DEPTH (gen_args));
25634   /* And what's in the hash table should match D.  */
25635   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
25636 	      || spec == NULL_TREE);
25637 
25638   /* This needs to happen before any tsubsting.  */
25639   if (! push_tinst_level (d))
25640     return d;
25641 
25642   timevar_push (TV_TEMPLATE_INST);
25643 
25644   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
25645      for the instantiation.  */
25646   td = template_for_substitution (d);
25647   args = gen_args;
25648 
25649   if (VAR_P (d))
25650     {
25651       /* Look up an explicit specialization, if any.  */
25652       tree tid = lookup_template_variable (gen_tmpl, gen_args);
25653       tree elt = most_specialized_partial_spec (tid, tf_warning_or_error);
25654       if (elt && elt != error_mark_node)
25655 	{
25656 	  td = TREE_VALUE (elt);
25657 	  args = TREE_PURPOSE (elt);
25658 	}
25659     }
25660 
25661   code_pattern = DECL_TEMPLATE_RESULT (td);
25662 
25663   /* We should never be trying to instantiate a member of a class
25664      template or partial specialization.  */
25665   gcc_assert (d != code_pattern);
25666 
25667   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
25668       || DECL_TEMPLATE_SPECIALIZATION (td))
25669     /* In the case of a friend template whose definition is provided
25670        outside the class, we may have too many arguments.  Drop the
25671        ones we don't need.  The same is true for specializations.  */
25672     args = get_innermost_template_args
25673       (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
25674 
25675   if (TREE_CODE (d) == FUNCTION_DECL)
25676     {
25677       deleted_p = DECL_DELETED_FN (code_pattern);
25678       pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
25679 			  && DECL_INITIAL (code_pattern) != error_mark_node)
25680 			 || DECL_DEFAULTED_FN (code_pattern)
25681 			 || deleted_p);
25682     }
25683   else
25684     {
25685       deleted_p = false;
25686       if (DECL_CLASS_SCOPE_P (code_pattern))
25687 	pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
25688       else
25689 	pattern_defined = ! DECL_EXTERNAL (code_pattern);
25690     }
25691 
25692   /* We may be in the middle of deferred access check.  Disable it now.  */
25693   push_deferring_access_checks (dk_no_deferred);
25694 
25695   /* Unless an explicit instantiation directive has already determined
25696      the linkage of D, remember that a definition is available for
25697      this entity.  */
25698   if (pattern_defined
25699       && !DECL_INTERFACE_KNOWN (d)
25700       && !DECL_NOT_REALLY_EXTERN (d))
25701     mark_definable (d);
25702 
25703   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
25704   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
25705   input_location = DECL_SOURCE_LOCATION (d);
25706 
25707   /* If D is a member of an explicitly instantiated class template,
25708      and no definition is available, treat it like an implicit
25709      instantiation.  */
25710   if (!pattern_defined && expl_inst_class_mem_p
25711       && DECL_EXPLICIT_INSTANTIATION (d))
25712     {
25713       /* Leave linkage flags alone on instantiations with anonymous
25714 	 visibility.  */
25715       if (TREE_PUBLIC (d))
25716 	{
25717 	  DECL_NOT_REALLY_EXTERN (d) = 0;
25718 	  DECL_INTERFACE_KNOWN (d) = 0;
25719 	}
25720       SET_DECL_IMPLICIT_INSTANTIATION (d);
25721     }
25722 
25723   /* Defer all other templates, unless we have been explicitly
25724      forbidden from doing so.  */
25725   if (/* If there is no definition, we cannot instantiate the
25726 	 template.  */
25727       ! pattern_defined
25728       /* If it's OK to postpone instantiation, do so.  */
25729       || defer_ok
25730       /* If this is a static data member that will be defined
25731 	 elsewhere, we don't want to instantiate the entire data
25732 	 member, but we do want to instantiate the initializer so that
25733 	 we can substitute that elsewhere.  */
25734       || (external_p && VAR_P (d))
25735       /* Handle here a deleted function too, avoid generating
25736 	 its body (c++/61080).  */
25737       || deleted_p)
25738     {
25739       /* The definition of the static data member is now required so
25740 	 we must substitute the initializer.  */
25741       if (VAR_P (d)
25742 	  && !DECL_INITIAL (d)
25743 	  && DECL_INITIAL (code_pattern))
25744 	{
25745 	  tree ns;
25746 	  tree init;
25747 	  bool const_init = false;
25748 	  bool enter_context = DECL_CLASS_SCOPE_P (d);
25749 
25750 	  ns = decl_namespace_context (d);
25751 	  push_nested_namespace (ns);
25752 	  if (enter_context)
25753 	    push_nested_class (DECL_CONTEXT (d));
25754 	  init = tsubst_expr (DECL_INITIAL (code_pattern),
25755 			      args,
25756 			      tf_warning_or_error, NULL_TREE,
25757 			      /*integral_constant_expression_p=*/false);
25758 	  /* If instantiating the initializer involved instantiating this
25759 	     again, don't call cp_finish_decl twice.  */
25760 	  if (!DECL_INITIAL (d))
25761 	    {
25762 	      /* Make sure the initializer is still constant, in case of
25763 		 circular dependency (template/instantiate6.C). */
25764 	      const_init
25765 		= DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
25766 	      cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
25767 			      /*asmspec_tree=*/NULL_TREE,
25768 			      LOOKUP_ONLYCONVERTING);
25769 	    }
25770 	  if (enter_context)
25771 	    pop_nested_class ();
25772 	  pop_nested_namespace (ns);
25773 	}
25774 
25775       /* We restore the source position here because it's used by
25776 	 add_pending_template.  */
25777       input_location = saved_loc;
25778 
25779       if (at_eof && !pattern_defined
25780 	  && DECL_EXPLICIT_INSTANTIATION (d)
25781 	  && DECL_NOT_REALLY_EXTERN (d))
25782 	/* [temp.explicit]
25783 
25784 	   The definition of a non-exported function template, a
25785 	   non-exported member function template, or a non-exported
25786 	   member function or static data member of a class template
25787 	   shall be present in every translation unit in which it is
25788 	   explicitly instantiated.  */
25789 	permerror (input_location,  "explicit instantiation of %qD "
25790 		   "but no definition available", d);
25791 
25792       /* If we're in unevaluated context, we just wanted to get the
25793 	 constant value; this isn't an odr use, so don't queue
25794 	 a full instantiation.  */
25795       if (cp_unevaluated_operand != 0)
25796 	goto out;
25797       /* ??? Historically, we have instantiated inline functions, even
25798 	 when marked as "extern template".  */
25799       if (!(external_p && VAR_P (d)))
25800 	add_pending_template (d);
25801       goto out;
25802     }
25803 
25804   bool push_to_top, nested;
25805   tree fn_context;
25806   fn_context = decl_function_context (d);
25807   if (LAMBDA_FUNCTION_P (d))
25808     /* tsubst_lambda_expr resolved any references to enclosing functions.  */
25809     fn_context = NULL_TREE;
25810   nested = current_function_decl != NULL_TREE;
25811   push_to_top = !(nested && fn_context == current_function_decl);
25812 
25813   vec<tree> omp_privatization_save;
25814   if (nested)
25815     save_omp_privatization_clauses (omp_privatization_save);
25816 
25817   if (push_to_top)
25818     push_to_top_level ();
25819   else
25820     {
25821       gcc_assert (!processing_template_decl);
25822       push_function_context ();
25823       cp_unevaluated_operand = 0;
25824       c_inhibit_evaluation_warnings = 0;
25825     }
25826 
25827   if (VAR_P (d))
25828     {
25829       /* The variable might be a lambda's extra scope, and that
25830 	 lambda's visibility depends on D's.  */
25831       maybe_commonize_var (d);
25832       determine_visibility (d);
25833     }
25834 
25835   /* Mark D as instantiated so that recursive calls to
25836      instantiate_decl do not try to instantiate it again.  */
25837   DECL_TEMPLATE_INSTANTIATED (d) = 1;
25838 
25839   /* Regenerate the declaration in case the template has been modified
25840      by a subsequent redeclaration.  */
25841   regenerate_decl_from_template (d, td, args);
25842 
25843   /* We already set the file and line above.  Reset them now in case
25844      they changed as a result of calling regenerate_decl_from_template.  */
25845   input_location = DECL_SOURCE_LOCATION (d);
25846 
25847   if (VAR_P (d))
25848     {
25849       tree init;
25850       bool const_init = false;
25851 
25852       /* Clear out DECL_RTL; whatever was there before may not be right
25853 	 since we've reset the type of the declaration.  */
25854       SET_DECL_RTL (d, NULL);
25855       DECL_IN_AGGR_P (d) = 0;
25856 
25857       /* The initializer is placed in DECL_INITIAL by
25858 	 regenerate_decl_from_template so we don't need to
25859 	 push/pop_access_scope again here.  Pull it out so that
25860 	 cp_finish_decl can process it.  */
25861       init = DECL_INITIAL (d);
25862       DECL_INITIAL (d) = NULL_TREE;
25863       DECL_INITIALIZED_P (d) = 0;
25864 
25865       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
25866 	 initializer.  That function will defer actual emission until
25867 	 we have a chance to determine linkage.  */
25868       DECL_EXTERNAL (d) = 0;
25869 
25870       /* Enter the scope of D so that access-checking works correctly.  */
25871       bool enter_context = DECL_CLASS_SCOPE_P (d);
25872       if (enter_context)
25873         push_nested_class (DECL_CONTEXT (d));
25874 
25875       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
25876       int flags = (TINFO_VAR_DECLARED_CONSTINIT (DECL_TEMPLATE_INFO (d))
25877 		   ? LOOKUP_CONSTINIT : 0);
25878       cp_finish_decl (d, init, const_init, NULL_TREE, flags);
25879 
25880       if (enter_context)
25881         pop_nested_class ();
25882 
25883       if (variable_template_p (gen_tmpl))
25884 	note_variable_template_instantiation (d);
25885     }
25886   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
25887     synthesize_method (d);
25888   else if (TREE_CODE (d) == FUNCTION_DECL)
25889     {
25890       /* Set up the list of local specializations.  */
25891       local_specialization_stack lss (push_to_top ? lss_blank : lss_copy);
25892       tree block = NULL_TREE;
25893 
25894       /* Set up context.  */
25895       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
25896 	  && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
25897 	block = push_stmt_list ();
25898       else
25899 	start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
25900 
25901       /* Some typedefs referenced from within the template code need to be
25902 	 access checked at template instantiation time, i.e now. These
25903 	 types were added to the template at parsing time. Let's get those
25904 	 and perform the access checks then.  */
25905       perform_typedefs_access_check (DECL_TEMPLATE_RESULT (td),
25906 				     args);
25907 
25908       /* Create substitution entries for the parameters.  */
25909       register_parameter_specializations (code_pattern, d);
25910 
25911       /* Substitute into the body of the function.  */
25912       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
25913 	tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
25914 			tf_warning_or_error, tmpl);
25915       else
25916 	{
25917 	  tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
25918 		       tf_warning_or_error, tmpl,
25919 		       /*integral_constant_expression_p=*/false);
25920 
25921 	  /* Set the current input_location to the end of the function
25922 	     so that finish_function knows where we are.  */
25923 	  input_location
25924 	    = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
25925 
25926 	  /* Remember if we saw an infinite loop in the template.  */
25927 	  current_function_infinite_loop
25928 	    = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
25929 	}
25930 
25931       /* Finish the function.  */
25932       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
25933 	  && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
25934 	DECL_SAVED_TREE (d) = pop_stmt_list (block);
25935       else
25936 	{
25937 	  d = finish_function (/*inline_p=*/false);
25938 	  expand_or_defer_fn (d);
25939 	}
25940 
25941       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
25942 	cp_check_omp_declare_reduction (d);
25943     }
25944 
25945   /* We're not deferring instantiation any more.  */
25946   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
25947 
25948   if (push_to_top)
25949     pop_from_top_level ();
25950   else
25951     pop_function_context ();
25952 
25953   if (nested)
25954     restore_omp_privatization_clauses (omp_privatization_save);
25955 
25956 out:
25957   pop_deferring_access_checks ();
25958   timevar_pop (TV_TEMPLATE_INST);
25959   pop_tinst_level ();
25960   input_location = saved_loc;
25961   cp_unevaluated_operand = saved_unevaluated_operand;
25962   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
25963 
25964   return d;
25965 }
25966 
25967 /* Run through the list of templates that we wish we could
25968    instantiate, and instantiate any we can.  RETRIES is the
25969    number of times we retry pending template instantiation.  */
25970 
25971 void
instantiate_pending_templates(int retries)25972 instantiate_pending_templates (int retries)
25973 {
25974   int reconsider;
25975   location_t saved_loc = input_location;
25976 
25977   /* Instantiating templates may trigger vtable generation.  This in turn
25978      may require further template instantiations.  We place a limit here
25979      to avoid infinite loop.  */
25980   if (pending_templates && retries >= max_tinst_depth)
25981     {
25982       tree decl = pending_templates->tinst->maybe_get_node ();
25983 
25984       fatal_error (input_location,
25985 		   "template instantiation depth exceeds maximum of %d"
25986 		   " instantiating %q+D, possibly from virtual table generation"
25987 		   " (use %<-ftemplate-depth=%> to increase the maximum)",
25988 		   max_tinst_depth, decl);
25989       if (TREE_CODE (decl) == FUNCTION_DECL)
25990 	/* Pretend that we defined it.  */
25991 	DECL_INITIAL (decl) = error_mark_node;
25992       return;
25993     }
25994 
25995   do
25996     {
25997       struct pending_template **t = &pending_templates;
25998       struct pending_template *last = NULL;
25999       reconsider = 0;
26000       while (*t)
26001 	{
26002 	  tree instantiation = reopen_tinst_level ((*t)->tinst);
26003 	  bool complete = false;
26004 
26005 	  if (TYPE_P (instantiation))
26006 	    {
26007 	      if (!COMPLETE_TYPE_P (instantiation))
26008 		{
26009 		  instantiate_class_template (instantiation);
26010 		  if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
26011 		    for (tree fld = TYPE_FIELDS (instantiation);
26012 			 fld; fld = TREE_CHAIN (fld))
26013 		      if ((VAR_P (fld)
26014 			   || (TREE_CODE (fld) == FUNCTION_DECL
26015 			       && !DECL_ARTIFICIAL (fld)))
26016 			  && DECL_TEMPLATE_INSTANTIATION (fld))
26017 			instantiate_decl (fld,
26018 					  /*defer_ok=*/false,
26019 					  /*expl_inst_class_mem_p=*/false);
26020 
26021 		  if (COMPLETE_TYPE_P (instantiation))
26022 		    reconsider = 1;
26023 		}
26024 
26025 	      complete = COMPLETE_TYPE_P (instantiation);
26026 	    }
26027 	  else
26028 	    {
26029 	      if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
26030 		  && !DECL_TEMPLATE_INSTANTIATED (instantiation))
26031 		{
26032 		  instantiation
26033 		    = instantiate_decl (instantiation,
26034 					/*defer_ok=*/false,
26035 					/*expl_inst_class_mem_p=*/false);
26036 		  if (DECL_TEMPLATE_INSTANTIATED (instantiation))
26037 		    reconsider = 1;
26038 		}
26039 
26040 	      complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
26041 			  || DECL_TEMPLATE_INSTANTIATED (instantiation));
26042 	    }
26043 
26044 	  if (complete)
26045 	    {
26046 	      /* If INSTANTIATION has been instantiated, then we don't
26047 		 need to consider it again in the future.  */
26048 	      struct pending_template *drop = *t;
26049 	      *t = (*t)->next;
26050 	      set_refcount_ptr (drop->tinst);
26051 	      pending_template_freelist ().free (drop);
26052 	    }
26053 	  else
26054 	    {
26055 	      last = *t;
26056 	      t = &(*t)->next;
26057 	    }
26058 	  tinst_depth = 0;
26059 	  set_refcount_ptr (current_tinst_level);
26060 	}
26061       last_pending_template = last;
26062     }
26063   while (reconsider);
26064 
26065   input_location = saved_loc;
26066 }
26067 
26068 /* Substitute ARGVEC into T, which is a list of initializers for
26069    either base class or a non-static data member.  The TREE_PURPOSEs
26070    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
26071    instantiate_decl.  */
26072 
26073 static tree
tsubst_initializer_list(tree t,tree argvec)26074 tsubst_initializer_list (tree t, tree argvec)
26075 {
26076   tree inits = NULL_TREE;
26077   tree target_ctor = error_mark_node;
26078 
26079   for (; t; t = TREE_CHAIN (t))
26080     {
26081       tree decl;
26082       tree init;
26083       tree expanded_bases = NULL_TREE;
26084       tree expanded_arguments = NULL_TREE;
26085       int i, len = 1;
26086 
26087       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
26088         {
26089           tree expr;
26090           tree arg;
26091 
26092           /* Expand the base class expansion type into separate base
26093              classes.  */
26094           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
26095                                                  tf_warning_or_error,
26096                                                  NULL_TREE);
26097           if (expanded_bases == error_mark_node)
26098             continue;
26099 
26100           /* We'll be building separate TREE_LISTs of arguments for
26101              each base.  */
26102           len = TREE_VEC_LENGTH (expanded_bases);
26103           expanded_arguments = make_tree_vec (len);
26104           for (i = 0; i < len; i++)
26105             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
26106 
26107           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
26108              expand each argument in the TREE_VALUE of t.  */
26109           expr = make_node (EXPR_PACK_EXPANSION);
26110 	  PACK_EXPANSION_LOCAL_P (expr) = true;
26111           PACK_EXPANSION_PARAMETER_PACKS (expr) =
26112             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
26113 
26114 	  if (TREE_VALUE (t) == void_type_node)
26115 	    /* VOID_TYPE_NODE is used to indicate
26116 	       value-initialization.  */
26117 	    {
26118 	      for (i = 0; i < len; i++)
26119 		TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
26120 	    }
26121 	  else
26122 	    {
26123 	      /* Substitute parameter packs into each argument in the
26124 		 TREE_LIST.  */
26125 	      in_base_initializer = 1;
26126 	      for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
26127 		{
26128 		  tree expanded_exprs;
26129 
26130 		  /* Expand the argument.  */
26131 		  SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
26132 		  expanded_exprs
26133 		    = tsubst_pack_expansion (expr, argvec,
26134 					     tf_warning_or_error,
26135 					     NULL_TREE);
26136 		  if (expanded_exprs == error_mark_node)
26137 		    continue;
26138 
26139 		  /* Prepend each of the expanded expressions to the
26140 		     corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
26141 		  for (i = 0; i < len; i++)
26142 		    {
26143 		      TREE_VEC_ELT (expanded_arguments, i) =
26144 			tree_cons (NULL_TREE,
26145 				   TREE_VEC_ELT (expanded_exprs, i),
26146 				   TREE_VEC_ELT (expanded_arguments, i));
26147 		    }
26148 		}
26149 	      in_base_initializer = 0;
26150 
26151 	      /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
26152 		 since we built them backwards.  */
26153 	      for (i = 0; i < len; i++)
26154 		{
26155 		  TREE_VEC_ELT (expanded_arguments, i) =
26156 		    nreverse (TREE_VEC_ELT (expanded_arguments, i));
26157 		}
26158 	    }
26159         }
26160 
26161       for (i = 0; i < len; ++i)
26162         {
26163           if (expanded_bases)
26164             {
26165               decl = TREE_VEC_ELT (expanded_bases, i);
26166               decl = expand_member_init (decl);
26167               init = TREE_VEC_ELT (expanded_arguments, i);
26168             }
26169           else
26170             {
26171 	      tree tmp;
26172               decl = tsubst_copy (TREE_PURPOSE (t), argvec,
26173                                   tf_warning_or_error, NULL_TREE);
26174 
26175               decl = expand_member_init (decl);
26176               if (decl && !DECL_P (decl))
26177                 in_base_initializer = 1;
26178 
26179 	      init = TREE_VALUE (t);
26180 	      tmp = init;
26181 	      if (init != void_type_node)
26182 		init = tsubst_expr (init, argvec,
26183 				    tf_warning_or_error, NULL_TREE,
26184 				    /*integral_constant_expression_p=*/false);
26185 	      if (init == NULL_TREE && tmp != NULL_TREE)
26186 		/* If we had an initializer but it instantiated to nothing,
26187 		   value-initialize the object.  This will only occur when
26188 		   the initializer was a pack expansion where the parameter
26189 		   packs used in that expansion were of length zero.  */
26190 		init = void_type_node;
26191               in_base_initializer = 0;
26192             }
26193 
26194 	  if (target_ctor != error_mark_node
26195 	      && init != error_mark_node)
26196 	    {
26197 	      error ("mem-initializer for %qD follows constructor delegation",
26198 		     decl);
26199 	      return inits;
26200 	    }
26201 	  /* Look for a target constructor. */
26202 	  if (init != error_mark_node
26203 	      && decl && CLASS_TYPE_P (decl)
26204 	      && same_type_p (decl, current_class_type))
26205 	    {
26206 	      maybe_warn_cpp0x (CPP0X_DELEGATING_CTORS);
26207 	      if (inits)
26208 		{
26209 		  error ("constructor delegation follows mem-initializer for %qD",
26210 			 TREE_PURPOSE (inits));
26211 		  continue;
26212 		}
26213 	      target_ctor = init;
26214 	    }
26215 
26216           if (decl)
26217             {
26218               init = build_tree_list (decl, init);
26219               TREE_CHAIN (init) = inits;
26220               inits = init;
26221             }
26222         }
26223     }
26224   return inits;
26225 }
26226 
26227 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
26228 
26229 static void
set_current_access_from_decl(tree decl)26230 set_current_access_from_decl (tree decl)
26231 {
26232   if (TREE_PRIVATE (decl))
26233     current_access_specifier = access_private_node;
26234   else if (TREE_PROTECTED (decl))
26235     current_access_specifier = access_protected_node;
26236   else
26237     current_access_specifier = access_public_node;
26238 }
26239 
26240 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
26241    is the instantiation (which should have been created with
26242    start_enum) and ARGS are the template arguments to use.  */
26243 
26244 static void
tsubst_enum(tree tag,tree newtag,tree args)26245 tsubst_enum (tree tag, tree newtag, tree args)
26246 {
26247   tree e;
26248 
26249   if (SCOPED_ENUM_P (newtag))
26250     begin_scope (sk_scoped_enum, newtag);
26251 
26252   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
26253     {
26254       tree value;
26255       tree decl;
26256 
26257       decl = TREE_VALUE (e);
26258       /* Note that in a template enum, the TREE_VALUE is the
26259 	 CONST_DECL, not the corresponding INTEGER_CST.  */
26260       value = tsubst_expr (DECL_INITIAL (decl),
26261 			   args, tf_warning_or_error, NULL_TREE,
26262 			   /*integral_constant_expression_p=*/true);
26263 
26264       /* Give this enumeration constant the correct access.  */
26265       set_current_access_from_decl (decl);
26266 
26267       /* Actually build the enumerator itself.  Here we're assuming that
26268 	 enumerators can't have dependent attributes.  */
26269       build_enumerator (DECL_NAME (decl), value, newtag,
26270 			DECL_ATTRIBUTES (decl), DECL_SOURCE_LOCATION (decl));
26271     }
26272 
26273   if (SCOPED_ENUM_P (newtag))
26274     finish_scope ();
26275 
26276   finish_enum_value_list (newtag);
26277   finish_enum (newtag);
26278 
26279   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
26280     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
26281 }
26282 
26283 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
26284    its type -- but without substituting the innermost set of template
26285    arguments.  So, innermost set of template parameters will appear in
26286    the type.  */
26287 
26288 tree
get_mostly_instantiated_function_type(tree decl)26289 get_mostly_instantiated_function_type (tree decl)
26290 {
26291   /* For a function, DECL_TI_TEMPLATE is partially instantiated.  */
26292   return TREE_TYPE (DECL_TI_TEMPLATE (decl));
26293 }
26294 
26295 /* Return truthvalue if we're processing a template different from
26296    the last one involved in diagnostics.  */
26297 bool
problematic_instantiation_changed(void)26298 problematic_instantiation_changed (void)
26299 {
26300   return current_tinst_level != last_error_tinst_level;
26301 }
26302 
26303 /* Remember current template involved in diagnostics.  */
26304 void
record_last_problematic_instantiation(void)26305 record_last_problematic_instantiation (void)
26306 {
26307   set_refcount_ptr (last_error_tinst_level, current_tinst_level);
26308 }
26309 
26310 struct tinst_level *
current_instantiation(void)26311 current_instantiation (void)
26312 {
26313   return current_tinst_level;
26314 }
26315 
26316 /* Return TRUE if current_function_decl is being instantiated, false
26317    otherwise.  */
26318 
26319 bool
instantiating_current_function_p(void)26320 instantiating_current_function_p (void)
26321 {
26322   return (current_instantiation ()
26323 	  && (current_instantiation ()->maybe_get_node ()
26324 	      == current_function_decl));
26325 }
26326 
26327 /* [temp.param] Check that template non-type parm TYPE is of an allowable
26328    type.  Return false for ok, true for disallowed.  Issue error and
26329    inform messages under control of COMPLAIN.  */
26330 
26331 static bool
invalid_nontype_parm_type_p(tree type,tsubst_flags_t complain)26332 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
26333 {
26334   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
26335     return false;
26336   else if (TYPE_PTR_P (type))
26337     return false;
26338   else if (TYPE_REF_P (type)
26339 	   && !TYPE_REF_IS_RVALUE (type))
26340     return false;
26341   else if (TYPE_PTRMEM_P (type))
26342     return false;
26343   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
26344     {
26345       if (CLASS_PLACEHOLDER_TEMPLATE (type) && cxx_dialect < cxx2a)
26346 	{
26347 	  if (complain & tf_error)
26348 	    error ("non-type template parameters of deduced class type only "
26349 		   "available with %<-std=c++2a%> or %<-std=gnu++2a%>");
26350 	  return true;
26351 	}
26352       return false;
26353     }
26354   else if (TREE_CODE (type) == TYPENAME_TYPE)
26355     return false;
26356   else if (TREE_CODE (type) == DECLTYPE_TYPE)
26357     return false;
26358   else if (TREE_CODE (type) == NULLPTR_TYPE)
26359     return false;
26360   /* A bound template template parm could later be instantiated to have a valid
26361      nontype parm type via an alias template.  */
26362   else if (cxx_dialect >= cxx11
26363 	   && TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
26364     return false;
26365   else if (CLASS_TYPE_P (type))
26366     {
26367       if (cxx_dialect < cxx2a)
26368 	{
26369 	  if (complain & tf_error)
26370 	    error ("non-type template parameters of class type only available "
26371 		   "with %<-std=c++2a%> or %<-std=gnu++2a%>");
26372 	  return true;
26373 	}
26374       if (dependent_type_p (type))
26375 	return false;
26376       if (!complete_type_or_else (type, NULL_TREE))
26377 	return true;
26378       if (!structural_type_p (type))
26379 	{
26380 	  if (complain & tf_error)
26381 	    {
26382 	      auto_diagnostic_group d;
26383 	      error ("%qT is not a valid type for a template non-type "
26384 		     "parameter because it is not structural", type);
26385 	      structural_type_p (type, true);
26386 	    }
26387 	  return true;
26388 	}
26389       return false;
26390     }
26391 
26392   if (complain & tf_error)
26393     {
26394       if (type == error_mark_node)
26395 	inform (input_location, "invalid template non-type parameter");
26396       else
26397 	error ("%q#T is not a valid type for a template non-type parameter",
26398 	       type);
26399     }
26400   return true;
26401 }
26402 
26403 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
26404    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
26405 
26406 static bool
dependent_type_p_r(tree type)26407 dependent_type_p_r (tree type)
26408 {
26409   tree scope;
26410 
26411   /* [temp.dep.type]
26412 
26413      A type is dependent if it is:
26414 
26415      -- a template parameter. Template template parameters are types
26416 	for us (since TYPE_P holds true for them) so we handle
26417 	them here.  */
26418   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
26419       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
26420     return true;
26421   /* -- a qualified-id with a nested-name-specifier which contains a
26422 	class-name that names a dependent type or whose unqualified-id
26423 	names a dependent type.  */
26424   if (TREE_CODE (type) == TYPENAME_TYPE)
26425     return true;
26426 
26427   /* An alias template specialization can be dependent even if the
26428      resulting type is not.  */
26429   if (dependent_alias_template_spec_p (type, nt_transparent))
26430     return true;
26431 
26432   /* -- a cv-qualified type where the cv-unqualified type is
26433 	dependent.
26434      No code is necessary for this bullet; the code below handles
26435      cv-qualified types, and we don't want to strip aliases with
26436      TYPE_MAIN_VARIANT because of DR 1558.  */
26437   /* -- a compound type constructed from any dependent type.  */
26438   if (TYPE_PTRMEM_P (type))
26439     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
26440 	    || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
26441 					   (type)));
26442   else if (INDIRECT_TYPE_P (type))
26443     return dependent_type_p (TREE_TYPE (type));
26444   else if (FUNC_OR_METHOD_TYPE_P (type))
26445     {
26446       tree arg_type;
26447 
26448       if (dependent_type_p (TREE_TYPE (type)))
26449 	return true;
26450       for (arg_type = TYPE_ARG_TYPES (type);
26451 	   arg_type;
26452 	   arg_type = TREE_CHAIN (arg_type))
26453 	if (dependent_type_p (TREE_VALUE (arg_type)))
26454 	  return true;
26455       if (cxx_dialect >= cxx17)
26456 	/* A value-dependent noexcept-specifier makes the type dependent.  */
26457 	if (tree spec = TYPE_RAISES_EXCEPTIONS (type))
26458 	  if (tree noex = TREE_PURPOSE (spec))
26459 	    /* Treat DEFERRED_NOEXCEPT as non-dependent, since it doesn't
26460 	       affect overload resolution and treating it as dependent breaks
26461 	       things.  Same for an unparsed noexcept expression.  */
26462 	    if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
26463 		&& TREE_CODE (noex) != DEFERRED_PARSE
26464 		&& value_dependent_expression_p (noex))
26465 	      return true;
26466       return false;
26467     }
26468   /* -- an array type constructed from any dependent type or whose
26469 	size is specified by a constant expression that is
26470 	value-dependent.
26471 
26472         We checked for type- and value-dependence of the bounds in
26473         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
26474   if (TREE_CODE (type) == ARRAY_TYPE)
26475     {
26476       if (TYPE_DOMAIN (type)
26477 	  && dependent_type_p (TYPE_DOMAIN (type)))
26478 	return true;
26479       return dependent_type_p (TREE_TYPE (type));
26480     }
26481 
26482   /* -- a template-id in which either the template name is a template
26483      parameter ...  */
26484   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
26485     return true;
26486   /* ... or any of the template arguments is a dependent type or
26487 	an expression that is type-dependent or value-dependent.  */
26488   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
26489 	   && (any_dependent_template_arguments_p
26490 	       (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
26491     return true;
26492 
26493   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
26494      dependent; if the argument of the `typeof' expression is not
26495      type-dependent, then it should already been have resolved.  */
26496   if (TREE_CODE (type) == TYPEOF_TYPE
26497       || TREE_CODE (type) == DECLTYPE_TYPE
26498       || TREE_CODE (type) == UNDERLYING_TYPE)
26499     return true;
26500 
26501   /* A template argument pack is dependent if any of its packed
26502      arguments are.  */
26503   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
26504     {
26505       tree args = ARGUMENT_PACK_ARGS (type);
26506       int i, len = TREE_VEC_LENGTH (args);
26507       for (i = 0; i < len; ++i)
26508         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
26509           return true;
26510     }
26511 
26512   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
26513      be template parameters.  */
26514   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
26515     return true;
26516 
26517   if (any_dependent_type_attributes_p (TYPE_ATTRIBUTES (type)))
26518     return true;
26519 
26520   /* The standard does not specifically mention types that are local
26521      to template functions or local classes, but they should be
26522      considered dependent too.  For example:
26523 
26524        template <int I> void f() {
26525 	 enum E { a = I };
26526 	 S<sizeof (E)> s;
26527        }
26528 
26529      The size of `E' cannot be known until the value of `I' has been
26530      determined.  Therefore, `E' must be considered dependent.  */
26531   scope = TYPE_CONTEXT (type);
26532   if (scope && TYPE_P (scope))
26533     return dependent_type_p (scope);
26534   /* Don't use type_dependent_expression_p here, as it can lead
26535      to infinite recursion trying to determine whether a lambda
26536      nested in a lambda is dependent (c++/47687).  */
26537   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
26538 	   && DECL_LANG_SPECIFIC (scope)
26539 	   && DECL_TEMPLATE_INFO (scope)
26540 	   && (any_dependent_template_arguments_p
26541 	       (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
26542     return true;
26543 
26544   /* Other types are non-dependent.  */
26545   return false;
26546 }
26547 
26548 /* Returns TRUE if TYPE is dependent, in the sense of
26549    [temp.dep.type].  Note that a NULL type is considered dependent.  */
26550 
26551 bool
dependent_type_p(tree type)26552 dependent_type_p (tree type)
26553 {
26554   /* If there are no template parameters in scope, then there can't be
26555      any dependent types.  */
26556   if (!processing_template_decl)
26557     {
26558       /* If we are not processing a template, then nobody should be
26559 	 providing us with a dependent type.  */
26560       gcc_assert (type);
26561       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
26562       return false;
26563     }
26564 
26565   /* If the type is NULL, we have not computed a type for the entity
26566      in question; in that case, the type is dependent.  */
26567   if (!type)
26568     return true;
26569 
26570   /* Erroneous types can be considered non-dependent.  */
26571   if (type == error_mark_node)
26572     return false;
26573 
26574   /* Getting here with global_type_node means we improperly called this
26575      function on the TREE_TYPE of an IDENTIFIER_NODE.  */
26576   gcc_checking_assert (type != global_type_node);
26577 
26578   /* If we have not already computed the appropriate value for TYPE,
26579      do so now.  */
26580   if (!TYPE_DEPENDENT_P_VALID (type))
26581     {
26582       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
26583       TYPE_DEPENDENT_P_VALID (type) = 1;
26584     }
26585 
26586   return TYPE_DEPENDENT_P (type);
26587 }
26588 
26589 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
26590    lookup.  In other words, a dependent type that is not the current
26591    instantiation.  */
26592 
26593 bool
dependent_scope_p(tree scope)26594 dependent_scope_p (tree scope)
26595 {
26596   return (scope && TYPE_P (scope) && dependent_type_p (scope)
26597 	  && !currently_open_class (scope));
26598 }
26599 
26600 /* T is a SCOPE_REF.  Return whether it represents a non-static member of
26601    an unknown base of 'this' (and is therefore instantiation-dependent).  */
26602 
26603 static bool
unknown_base_ref_p(tree t)26604 unknown_base_ref_p (tree t)
26605 {
26606   if (!current_class_ptr)
26607     return false;
26608 
26609   tree mem = TREE_OPERAND (t, 1);
26610   if (shared_member_p (mem))
26611     return false;
26612 
26613   tree cur = current_nonlambda_class_type ();
26614   if (!any_dependent_bases_p (cur))
26615     return false;
26616 
26617   tree ctx = TREE_OPERAND (t, 0);
26618   if (DERIVED_FROM_P (ctx, cur))
26619     return false;
26620 
26621   return true;
26622 }
26623 
26624 /* T is a SCOPE_REF; return whether we need to consider it
26625     instantiation-dependent so that we can check access at instantiation
26626     time even though we know which member it resolves to.  */
26627 
26628 static bool
instantiation_dependent_scope_ref_p(tree t)26629 instantiation_dependent_scope_ref_p (tree t)
26630 {
26631   if (DECL_P (TREE_OPERAND (t, 1))
26632       && CLASS_TYPE_P (TREE_OPERAND (t, 0))
26633       && !unknown_base_ref_p (t)
26634       && accessible_in_template_p (TREE_OPERAND (t, 0),
26635 				   TREE_OPERAND (t, 1)))
26636     return false;
26637   else
26638     return true;
26639 }
26640 
26641 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
26642    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
26643    expression.  */
26644 
26645 /* Note that this predicate is not appropriate for general expressions;
26646    only constant expressions (that satisfy potential_constant_expression)
26647    can be tested for value dependence.  */
26648 
26649 bool
value_dependent_expression_p(tree expression)26650 value_dependent_expression_p (tree expression)
26651 {
26652   if (!processing_template_decl || expression == NULL_TREE)
26653     return false;
26654 
26655   /* A type-dependent expression is also value-dependent.  */
26656   if (type_dependent_expression_p (expression))
26657     return true;
26658 
26659   switch (TREE_CODE (expression))
26660     {
26661     case BASELINK:
26662       /* A dependent member function of the current instantiation.  */
26663       return dependent_type_p (BINFO_TYPE (BASELINK_BINFO (expression)));
26664 
26665     case FUNCTION_DECL:
26666       /* A dependent member function of the current instantiation.  */
26667       if (DECL_CLASS_SCOPE_P (expression)
26668 	  && dependent_type_p (DECL_CONTEXT (expression)))
26669 	return true;
26670       break;
26671 
26672     case IDENTIFIER_NODE:
26673       /* A name that has not been looked up -- must be dependent.  */
26674       return true;
26675 
26676     case TEMPLATE_PARM_INDEX:
26677       /* A non-type template parm.  */
26678       return true;
26679 
26680     case CONST_DECL:
26681       /* A non-type template parm.  */
26682       if (DECL_TEMPLATE_PARM_P (expression))
26683 	return true;
26684       return value_dependent_expression_p (DECL_INITIAL (expression));
26685 
26686     case VAR_DECL:
26687        /* A constant with literal type and is initialized
26688 	  with an expression that is value-dependent.  */
26689       if (DECL_DEPENDENT_INIT_P (expression)
26690 	  /* FIXME cp_finish_decl doesn't fold reference initializers.  */
26691 	  || TYPE_REF_P (TREE_TYPE (expression)))
26692 	return true;
26693       if (DECL_HAS_VALUE_EXPR_P (expression))
26694 	{
26695 	  tree value_expr = DECL_VALUE_EXPR (expression);
26696 	  if (value_dependent_expression_p (value_expr)
26697 	      /* __PRETTY_FUNCTION__ inside a template function is dependent
26698 		 on the name of the function.  */
26699 	      || (DECL_PRETTY_FUNCTION_P (expression)
26700 		  /* It might be used in a template, but not a template
26701 		     function, in which case its DECL_VALUE_EXPR will be
26702 		     "top level".  */
26703 		  && value_expr == error_mark_node))
26704 	    return true;
26705 	}
26706       return false;
26707 
26708     case DYNAMIC_CAST_EXPR:
26709     case STATIC_CAST_EXPR:
26710     case CONST_CAST_EXPR:
26711     case REINTERPRET_CAST_EXPR:
26712     case CAST_EXPR:
26713     case IMPLICIT_CONV_EXPR:
26714       /* These expressions are value-dependent if the type to which
26715 	 the cast occurs is dependent or the expression being casted
26716 	 is value-dependent.  */
26717       {
26718 	tree type = TREE_TYPE (expression);
26719 
26720 	if (dependent_type_p (type))
26721 	  return true;
26722 
26723 	/* A functional cast has a list of operands.  */
26724 	expression = TREE_OPERAND (expression, 0);
26725 	if (!expression)
26726 	  {
26727 	    /* If there are no operands, it must be an expression such
26728 	       as "int()". This should not happen for aggregate types
26729 	       because it would form non-constant expressions.  */
26730 	    gcc_assert (cxx_dialect >= cxx11
26731 			|| INTEGRAL_OR_ENUMERATION_TYPE_P (type));
26732 
26733 	    return false;
26734 	  }
26735 
26736 	if (TREE_CODE (expression) == TREE_LIST)
26737 	  return any_value_dependent_elements_p (expression);
26738 
26739 	return value_dependent_expression_p (expression);
26740       }
26741 
26742     case SIZEOF_EXPR:
26743       if (SIZEOF_EXPR_TYPE_P (expression))
26744 	return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
26745       /* FALLTHRU */
26746     case ALIGNOF_EXPR:
26747     case TYPEID_EXPR:
26748       /* A `sizeof' expression is value-dependent if the operand is
26749 	 type-dependent or is a pack expansion.  */
26750       expression = TREE_OPERAND (expression, 0);
26751       if (PACK_EXPANSION_P (expression))
26752         return true;
26753       else if (TYPE_P (expression))
26754 	return dependent_type_p (expression);
26755       return instantiation_dependent_uneval_expression_p (expression);
26756 
26757     case AT_ENCODE_EXPR:
26758       /* An 'encode' expression is value-dependent if the operand is
26759 	 type-dependent.  */
26760       expression = TREE_OPERAND (expression, 0);
26761       return dependent_type_p (expression);
26762 
26763     case NOEXCEPT_EXPR:
26764       expression = TREE_OPERAND (expression, 0);
26765       return instantiation_dependent_uneval_expression_p (expression);
26766 
26767     case SCOPE_REF:
26768       /* All instantiation-dependent expressions should also be considered
26769 	 value-dependent.  */
26770       return instantiation_dependent_scope_ref_p (expression);
26771 
26772     case COMPONENT_REF:
26773       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
26774 	      || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
26775 
26776     case NONTYPE_ARGUMENT_PACK:
26777       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
26778          is value-dependent.  */
26779       {
26780         tree values = ARGUMENT_PACK_ARGS (expression);
26781         int i, len = TREE_VEC_LENGTH (values);
26782 
26783         for (i = 0; i < len; ++i)
26784           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
26785             return true;
26786 
26787         return false;
26788       }
26789 
26790     case TRAIT_EXPR:
26791       {
26792 	tree type2 = TRAIT_EXPR_TYPE2 (expression);
26793 
26794 	if (dependent_type_p (TRAIT_EXPR_TYPE1 (expression)))
26795 	  return true;
26796 
26797 	if (!type2)
26798 	  return false;
26799 
26800 	if (TREE_CODE (type2) != TREE_LIST)
26801 	  return dependent_type_p (type2);
26802 
26803 	for (; type2; type2 = TREE_CHAIN (type2))
26804 	  if (dependent_type_p (TREE_VALUE (type2)))
26805 	    return true;
26806 
26807 	return false;
26808       }
26809 
26810     case MODOP_EXPR:
26811       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
26812 	      || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
26813 
26814     case ARRAY_REF:
26815       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
26816 	      || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
26817 
26818     case ADDR_EXPR:
26819       {
26820 	tree op = TREE_OPERAND (expression, 0);
26821 	return (value_dependent_expression_p (op)
26822 		|| has_value_dependent_address (op));
26823       }
26824 
26825     case REQUIRES_EXPR:
26826       /* Treat all requires-expressions as value-dependent so
26827          we don't try to fold them.  */
26828       return true;
26829 
26830     case TYPE_REQ:
26831       return dependent_type_p (TREE_OPERAND (expression, 0));
26832 
26833     case CALL_EXPR:
26834       {
26835 	if (value_dependent_expression_p (CALL_EXPR_FN (expression)))
26836 	  return true;
26837 	tree fn = get_callee_fndecl (expression);
26838 	int i, nargs;
26839 	nargs = call_expr_nargs (expression);
26840 	for (i = 0; i < nargs; ++i)
26841 	  {
26842 	    tree op = CALL_EXPR_ARG (expression, i);
26843 	    /* In a call to a constexpr member function, look through the
26844 	       implicit ADDR_EXPR on the object argument so that it doesn't
26845 	       cause the call to be considered value-dependent.  We also
26846 	       look through it in potential_constant_expression.  */
26847 	    if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
26848 		&& DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
26849 		&& TREE_CODE (op) == ADDR_EXPR)
26850 	      op = TREE_OPERAND (op, 0);
26851 	    if (value_dependent_expression_p (op))
26852 	      return true;
26853 	  }
26854 	return false;
26855       }
26856 
26857     case TEMPLATE_ID_EXPR:
26858       return concept_definition_p (TREE_OPERAND (expression, 0));
26859 
26860     case CONSTRUCTOR:
26861       {
26862 	unsigned ix;
26863 	tree val;
26864 	if (dependent_type_p (TREE_TYPE (expression)))
26865 	  return true;
26866 	FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
26867 	  if (value_dependent_expression_p (val))
26868 	    return true;
26869 	return false;
26870       }
26871 
26872     case STMT_EXPR:
26873       /* Treat a GNU statement expression as dependent to avoid crashing
26874 	 under instantiate_non_dependent_expr; it can't be constant.  */
26875       return true;
26876 
26877     default:
26878       /* A constant expression is value-dependent if any subexpression is
26879 	 value-dependent.  */
26880       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
26881 	{
26882 	case tcc_reference:
26883 	case tcc_unary:
26884 	case tcc_comparison:
26885 	case tcc_binary:
26886 	case tcc_expression:
26887 	case tcc_vl_exp:
26888 	  {
26889 	    int i, len = cp_tree_operand_length (expression);
26890 
26891 	    for (i = 0; i < len; i++)
26892 	      {
26893 		tree t = TREE_OPERAND (expression, i);
26894 
26895 		/* In some cases, some of the operands may be missing.
26896 		   (For example, in the case of PREDECREMENT_EXPR, the
26897 		   amount to increment by may be missing.)  That doesn't
26898 		   make the expression dependent.  */
26899 		if (t && value_dependent_expression_p (t))
26900 		  return true;
26901 	      }
26902 	  }
26903 	  break;
26904 	default:
26905 	  break;
26906 	}
26907       break;
26908     }
26909 
26910   /* The expression is not value-dependent.  */
26911   return false;
26912 }
26913 
26914 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
26915    [temp.dep.expr].  Note that an expression with no type is
26916    considered dependent.  Other parts of the compiler arrange for an
26917    expression with type-dependent subexpressions to have no type, so
26918    this function doesn't have to be fully recursive.  */
26919 
26920 bool
type_dependent_expression_p(tree expression)26921 type_dependent_expression_p (tree expression)
26922 {
26923   if (!processing_template_decl)
26924     return false;
26925 
26926   if (expression == NULL_TREE || expression == error_mark_node)
26927     return false;
26928 
26929   STRIP_ANY_LOCATION_WRAPPER (expression);
26930 
26931   /* An unresolved name is always dependent.  */
26932   if (identifier_p (expression)
26933       || TREE_CODE (expression) == USING_DECL
26934       || TREE_CODE (expression) == WILDCARD_DECL)
26935     return true;
26936 
26937   /* A lambda-expression in template context is dependent.  dependent_type_p is
26938      true for a lambda in the scope of a class or function template, but that
26939      doesn't cover all template contexts, like a default template argument.  */
26940   if (TREE_CODE (expression) == LAMBDA_EXPR)
26941     return true;
26942 
26943   /* A fold expression is type-dependent. */
26944   if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
26945       || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
26946       || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
26947       || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
26948     return true;
26949 
26950   /* Some expression forms are never type-dependent.  */
26951   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
26952       || TREE_CODE (expression) == SIZEOF_EXPR
26953       || TREE_CODE (expression) == ALIGNOF_EXPR
26954       || TREE_CODE (expression) == AT_ENCODE_EXPR
26955       || TREE_CODE (expression) == NOEXCEPT_EXPR
26956       || TREE_CODE (expression) == TRAIT_EXPR
26957       || TREE_CODE (expression) == TYPEID_EXPR
26958       || TREE_CODE (expression) == DELETE_EXPR
26959       || TREE_CODE (expression) == VEC_DELETE_EXPR
26960       || TREE_CODE (expression) == THROW_EXPR
26961       || TREE_CODE (expression) == REQUIRES_EXPR)
26962     return false;
26963 
26964   /* The types of these expressions depends only on the type to which
26965      the cast occurs.  */
26966   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
26967       || TREE_CODE (expression) == STATIC_CAST_EXPR
26968       || TREE_CODE (expression) == CONST_CAST_EXPR
26969       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
26970       || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
26971       || TREE_CODE (expression) == CAST_EXPR)
26972     return dependent_type_p (TREE_TYPE (expression));
26973 
26974   /* The types of these expressions depends only on the type created
26975      by the expression.  */
26976   if (TREE_CODE (expression) == NEW_EXPR
26977       || TREE_CODE (expression) == VEC_NEW_EXPR)
26978     {
26979       /* For NEW_EXPR tree nodes created inside a template, either
26980 	 the object type itself or a TREE_LIST may appear as the
26981 	 operand 1.  */
26982       tree type = TREE_OPERAND (expression, 1);
26983       if (TREE_CODE (type) == TREE_LIST)
26984 	/* This is an array type.  We need to check array dimensions
26985 	   as well.  */
26986 	return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
26987 	       || value_dependent_expression_p
26988 		    (TREE_OPERAND (TREE_VALUE (type), 1));
26989       else
26990 	return dependent_type_p (type);
26991     }
26992 
26993   if (TREE_CODE (expression) == SCOPE_REF)
26994     {
26995       tree scope = TREE_OPERAND (expression, 0);
26996       tree name = TREE_OPERAND (expression, 1);
26997 
26998       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
26999 	 contains an identifier associated by name lookup with one or more
27000 	 declarations declared with a dependent type, or...a
27001 	 nested-name-specifier or qualified-id that names a member of an
27002 	 unknown specialization.  */
27003       return (type_dependent_expression_p (name)
27004 	      || dependent_scope_p (scope));
27005     }
27006 
27007   if (TREE_CODE (expression) == TEMPLATE_DECL
27008       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
27009     return uses_outer_template_parms (expression);
27010 
27011   if (TREE_CODE (expression) == STMT_EXPR)
27012     expression = stmt_expr_value_expr (expression);
27013 
27014   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
27015     {
27016       tree elt;
27017       unsigned i;
27018 
27019       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
27020 	{
27021 	  if (type_dependent_expression_p (elt))
27022 	    return true;
27023 	}
27024       return false;
27025     }
27026 
27027   /* A static data member of the current instantiation with incomplete
27028      array type is type-dependent, as the definition and specializations
27029      can have different bounds.  */
27030   if (VAR_P (expression)
27031       && DECL_CLASS_SCOPE_P (expression)
27032       && dependent_type_p (DECL_CONTEXT (expression))
27033       && VAR_HAD_UNKNOWN_BOUND (expression))
27034     return true;
27035 
27036   /* An array of unknown bound depending on a variadic parameter, eg:
27037 
27038      template<typename... Args>
27039        void foo (Args... args)
27040        {
27041          int arr[] = { args... };
27042        }
27043 
27044      template<int... vals>
27045        void bar ()
27046        {
27047          int arr[] = { vals... };
27048        }
27049 
27050      If the array has no length and has an initializer, it must be that
27051      we couldn't determine its length in cp_complete_array_type because
27052      it is dependent.  */
27053   if (VAR_P (expression)
27054       && TREE_TYPE (expression) != NULL_TREE
27055       && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
27056       && !TYPE_DOMAIN (TREE_TYPE (expression))
27057       && DECL_INITIAL (expression))
27058    return true;
27059 
27060   /* A function or variable template-id is type-dependent if it has any
27061      dependent template arguments.  */
27062   if (VAR_OR_FUNCTION_DECL_P (expression)
27063       && DECL_LANG_SPECIFIC (expression)
27064       && DECL_TEMPLATE_INFO (expression))
27065     {
27066       /* Consider the innermost template arguments, since those are the ones
27067 	 that come from the template-id; the template arguments for the
27068 	 enclosing class do not make it type-dependent unless they are used in
27069 	 the type of the decl.  */
27070       if (instantiates_primary_template_p (expression)
27071 	  && (any_dependent_template_arguments_p
27072 	      (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
27073 	return true;
27074     }
27075 
27076   /* Otherwise, if the function decl isn't from a dependent scope, it can't be
27077      type-dependent.  Checking this is important for functions with auto return
27078      type, which looks like a dependent type.  */
27079   if (TREE_CODE (expression) == FUNCTION_DECL
27080       && !(DECL_CLASS_SCOPE_P (expression)
27081 	   && dependent_type_p (DECL_CONTEXT (expression)))
27082       && !(DECL_LANG_SPECIFIC (expression)
27083 	   && DECL_FRIEND_P (expression)
27084 	   && (!DECL_FRIEND_CONTEXT (expression)
27085 	       || dependent_type_p (DECL_FRIEND_CONTEXT (expression))))
27086       && !DECL_LOCAL_FUNCTION_P (expression))
27087     {
27088       gcc_assert (!dependent_type_p (TREE_TYPE (expression))
27089 		  || undeduced_auto_decl (expression));
27090       return false;
27091     }
27092 
27093   /* Always dependent, on the number of arguments if nothing else.  */
27094   if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
27095     return true;
27096 
27097   if (TREE_TYPE (expression) == unknown_type_node)
27098     {
27099       if (TREE_CODE (expression) == ADDR_EXPR)
27100 	return type_dependent_expression_p (TREE_OPERAND (expression, 0));
27101       if (TREE_CODE (expression) == COMPONENT_REF
27102 	  || TREE_CODE (expression) == OFFSET_REF)
27103 	{
27104 	  if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
27105 	    return true;
27106 	  expression = TREE_OPERAND (expression, 1);
27107 	  if (identifier_p (expression))
27108 	    return false;
27109 	}
27110       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
27111       if (TREE_CODE (expression) == SCOPE_REF)
27112 	return false;
27113 
27114       /* CO_AWAIT/YIELD_EXPR with unknown type is always dependent.  */
27115       if (TREE_CODE (expression) == CO_AWAIT_EXPR
27116 	  || TREE_CODE (expression) == CO_YIELD_EXPR)
27117 	return true;
27118 
27119       if (BASELINK_P (expression))
27120 	{
27121 	  if (BASELINK_OPTYPE (expression)
27122 	      && dependent_type_p (BASELINK_OPTYPE (expression)))
27123 	    return true;
27124 	  expression = BASELINK_FUNCTIONS (expression);
27125 	}
27126 
27127       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
27128 	{
27129 	  if (any_dependent_template_arguments_p
27130 	      (TREE_OPERAND (expression, 1)))
27131 	    return true;
27132 	  expression = TREE_OPERAND (expression, 0);
27133 	  if (identifier_p (expression))
27134 	    return true;
27135 	}
27136 
27137       gcc_assert (OVL_P (expression));
27138 
27139       for (lkp_iterator iter (expression); iter; ++iter)
27140 	if (type_dependent_expression_p (*iter))
27141 	  return true;
27142 
27143       return false;
27144     }
27145 
27146   /* The type of a non-type template parm declared with a placeholder type
27147      depends on the corresponding template argument, even though
27148      placeholders are not normally considered dependent.  */
27149   if (TREE_CODE (expression) == TEMPLATE_PARM_INDEX
27150       && is_auto (TREE_TYPE (expression)))
27151     return true;
27152 
27153   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
27154 
27155   /* Dependent type attributes might not have made it from the decl to
27156      the type yet.  */
27157   if (DECL_P (expression)
27158       && any_dependent_type_attributes_p (DECL_ATTRIBUTES (expression)))
27159     return true;
27160 
27161   return (dependent_type_p (TREE_TYPE (expression)));
27162 }
27163 
27164 /* [temp.dep.expr]/5: A class member access expression (5.2.5) is
27165    type-dependent if the expression refers to a member of the current
27166    instantiation and the type of the referenced member is dependent, or the
27167    class member access expression refers to a member of an unknown
27168    specialization.
27169 
27170    This function returns true if the OBJECT in such a class member access
27171    expression is of an unknown specialization.  */
27172 
27173 bool
type_dependent_object_expression_p(tree object)27174 type_dependent_object_expression_p (tree object)
27175 {
27176   /* An IDENTIFIER_NODE can sometimes have a TREE_TYPE, but it's still
27177      dependent.  */
27178   if (TREE_CODE (object) == IDENTIFIER_NODE)
27179     return true;
27180   tree scope = TREE_TYPE (object);
27181   return (!scope || dependent_scope_p (scope));
27182 }
27183 
27184 /* walk_tree callback function for instantiation_dependent_expression_p,
27185    below.  Returns non-zero if a dependent subexpression is found.  */
27186 
27187 static tree
instantiation_dependent_r(tree * tp,int * walk_subtrees,void *)27188 instantiation_dependent_r (tree *tp, int *walk_subtrees,
27189 			   void * /*data*/)
27190 {
27191   if (TYPE_P (*tp))
27192     {
27193       /* We don't have to worry about decltype currently because decltype
27194 	 of an instantiation-dependent expr is a dependent type.  This
27195 	 might change depending on the resolution of DR 1172.  */
27196       *walk_subtrees = false;
27197       return NULL_TREE;
27198     }
27199   enum tree_code code = TREE_CODE (*tp);
27200   switch (code)
27201     {
27202       /* Don't treat an argument list as dependent just because it has no
27203 	 TREE_TYPE.  */
27204     case TREE_LIST:
27205     case TREE_VEC:
27206     case NONTYPE_ARGUMENT_PACK:
27207       return NULL_TREE;
27208 
27209     case TEMPLATE_PARM_INDEX:
27210       if (dependent_type_p (TREE_TYPE (*tp)))
27211 	return *tp;
27212       if (TEMPLATE_PARM_PARAMETER_PACK (*tp))
27213 	return *tp;
27214       /* We'll check value-dependence separately.  */
27215       return NULL_TREE;
27216 
27217       /* Handle expressions with type operands.  */
27218     case SIZEOF_EXPR:
27219     case ALIGNOF_EXPR:
27220     case TYPEID_EXPR:
27221     case AT_ENCODE_EXPR:
27222       {
27223 	tree op = TREE_OPERAND (*tp, 0);
27224 	if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
27225 	  op = TREE_TYPE (op);
27226 	if (TYPE_P (op))
27227 	  {
27228 	    if (dependent_type_p (op))
27229 	      return *tp;
27230 	    else
27231 	      {
27232 		*walk_subtrees = false;
27233 		return NULL_TREE;
27234 	      }
27235 	  }
27236 	break;
27237       }
27238 
27239     case COMPONENT_REF:
27240       if (identifier_p (TREE_OPERAND (*tp, 1)))
27241 	/* In a template, finish_class_member_access_expr creates a
27242 	   COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
27243 	   type-dependent, so that we can check access control at
27244 	   instantiation time (PR 42277).  See also Core issue 1273.  */
27245 	return *tp;
27246       break;
27247 
27248     case SCOPE_REF:
27249       if (instantiation_dependent_scope_ref_p (*tp))
27250 	return *tp;
27251       else
27252 	break;
27253 
27254       /* Treat statement-expressions as dependent.  */
27255     case BIND_EXPR:
27256       return *tp;
27257 
27258       /* Treat requires-expressions as dependent. */
27259     case REQUIRES_EXPR:
27260       return *tp;
27261 
27262     case CALL_EXPR:
27263       /* Treat concept checks as dependent. */
27264       if (concept_check_p (*tp))
27265         return *tp;
27266       break;
27267 
27268     case TEMPLATE_ID_EXPR:
27269       /* Treat concept checks as dependent.  */
27270       if (concept_check_p (*tp))
27271 	return *tp;
27272       break;
27273 
27274     case CONSTRUCTOR:
27275       if (CONSTRUCTOR_IS_DEPENDENT (*tp))
27276 	return *tp;
27277       break;
27278 
27279     default:
27280       break;
27281     }
27282 
27283   if (type_dependent_expression_p (*tp))
27284     return *tp;
27285   else
27286     return NULL_TREE;
27287 }
27288 
27289 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
27290    sense defined by the ABI:
27291 
27292    "An expression is instantiation-dependent if it is type-dependent
27293    or value-dependent, or it has a subexpression that is type-dependent
27294    or value-dependent."
27295 
27296    Except don't actually check value-dependence for unevaluated expressions,
27297    because in sizeof(i) we don't care about the value of i.  Checking
27298    type-dependence will in turn check value-dependence of array bounds/template
27299    arguments as needed.  */
27300 
27301 bool
instantiation_dependent_uneval_expression_p(tree expression)27302 instantiation_dependent_uneval_expression_p (tree expression)
27303 {
27304   tree result;
27305 
27306   if (!processing_template_decl)
27307     return false;
27308 
27309   if (expression == error_mark_node)
27310     return false;
27311 
27312   result = cp_walk_tree_without_duplicates (&expression,
27313 					    instantiation_dependent_r, NULL);
27314   return result != NULL_TREE;
27315 }
27316 
27317 /* As above, but also check value-dependence of the expression as a whole.  */
27318 
27319 bool
instantiation_dependent_expression_p(tree expression)27320 instantiation_dependent_expression_p (tree expression)
27321 {
27322   return (instantiation_dependent_uneval_expression_p (expression)
27323 	  || value_dependent_expression_p (expression));
27324 }
27325 
27326 /* Like type_dependent_expression_p, but it also works while not processing
27327    a template definition, i.e. during substitution or mangling.  */
27328 
27329 bool
type_dependent_expression_p_push(tree expr)27330 type_dependent_expression_p_push (tree expr)
27331 {
27332   bool b;
27333   ++processing_template_decl;
27334   b = type_dependent_expression_p (expr);
27335   --processing_template_decl;
27336   return b;
27337 }
27338 
27339 /* Returns TRUE if ARGS contains a type-dependent expression.  */
27340 
27341 bool
any_type_dependent_arguments_p(const vec<tree,va_gc> * args)27342 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
27343 {
27344   unsigned int i;
27345   tree arg;
27346 
27347   FOR_EACH_VEC_SAFE_ELT (args, i, arg)
27348     {
27349       if (type_dependent_expression_p (arg))
27350 	return true;
27351     }
27352   return false;
27353 }
27354 
27355 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
27356    expressions) contains any type-dependent expressions.  */
27357 
27358 bool
any_type_dependent_elements_p(const_tree list)27359 any_type_dependent_elements_p (const_tree list)
27360 {
27361   for (; list; list = TREE_CHAIN (list))
27362     if (type_dependent_expression_p (TREE_VALUE (list)))
27363       return true;
27364 
27365   return false;
27366 }
27367 
27368 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
27369    expressions) contains any value-dependent expressions.  */
27370 
27371 bool
any_value_dependent_elements_p(const_tree list)27372 any_value_dependent_elements_p (const_tree list)
27373 {
27374   for (; list; list = TREE_CHAIN (list))
27375     if (value_dependent_expression_p (TREE_VALUE (list)))
27376       return true;
27377 
27378   return false;
27379 }
27380 
27381 /* Returns TRUE if the ARG (a template argument) is dependent.  */
27382 
27383 bool
dependent_template_arg_p(tree arg)27384 dependent_template_arg_p (tree arg)
27385 {
27386   if (!processing_template_decl)
27387     return false;
27388 
27389   /* Assume a template argument that was wrongly written by the user
27390      is dependent. This is consistent with what
27391      any_dependent_template_arguments_p [that calls this function]
27392      does.  */
27393   if (!arg || arg == error_mark_node)
27394     return true;
27395 
27396   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
27397     arg = argument_pack_select_arg (arg);
27398 
27399   if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
27400     return true;
27401   if (TREE_CODE (arg) == TEMPLATE_DECL)
27402     {
27403       if (DECL_TEMPLATE_PARM_P (arg))
27404 	return true;
27405       /* A member template of a dependent class is not necessarily
27406 	 type-dependent, but it is a dependent template argument because it
27407 	 will be a member of an unknown specialization to that template.  */
27408       tree scope = CP_DECL_CONTEXT (arg);
27409       return TYPE_P (scope) && dependent_type_p (scope);
27410     }
27411   else if (ARGUMENT_PACK_P (arg))
27412     {
27413       tree args = ARGUMENT_PACK_ARGS (arg);
27414       int i, len = TREE_VEC_LENGTH (args);
27415       for (i = 0; i < len; ++i)
27416         {
27417           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
27418             return true;
27419         }
27420 
27421       return false;
27422     }
27423   else if (TYPE_P (arg))
27424     return dependent_type_p (arg);
27425   else
27426     return value_dependent_expression_p (arg);
27427 }
27428 
27429 /* Returns true if ARGS (a collection of template arguments) contains
27430    any types that require structural equality testing.  */
27431 
27432 bool
any_template_arguments_need_structural_equality_p(tree args)27433 any_template_arguments_need_structural_equality_p (tree args)
27434 {
27435   int i;
27436   int j;
27437 
27438   if (!args)
27439     return false;
27440   if (args == error_mark_node)
27441     return true;
27442 
27443   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
27444     {
27445       tree level = TMPL_ARGS_LEVEL (args, i + 1);
27446       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
27447 	{
27448 	  tree arg = TREE_VEC_ELT (level, j);
27449 	  tree packed_args = NULL_TREE;
27450 	  int k, len = 1;
27451 
27452 	  if (ARGUMENT_PACK_P (arg))
27453 	    {
27454 	      /* Look inside the argument pack.  */
27455 	      packed_args = ARGUMENT_PACK_ARGS (arg);
27456 	      len = TREE_VEC_LENGTH (packed_args);
27457 	    }
27458 
27459 	  for (k = 0; k < len; ++k)
27460 	    {
27461 	      if (packed_args)
27462 		arg = TREE_VEC_ELT (packed_args, k);
27463 
27464 	      if (error_operand_p (arg))
27465 		return true;
27466 	      else if (TREE_CODE (arg) == TEMPLATE_DECL)
27467 		continue;
27468 	      else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
27469 		return true;
27470 	      else if (!TYPE_P (arg) && TREE_TYPE (arg)
27471 		       && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
27472 		return true;
27473 	    }
27474 	}
27475     }
27476 
27477   return false;
27478 }
27479 
27480 /* Returns true if ARGS (a collection of template arguments) contains
27481    any dependent arguments.  */
27482 
27483 bool
any_dependent_template_arguments_p(const_tree args)27484 any_dependent_template_arguments_p (const_tree args)
27485 {
27486   int i;
27487   int j;
27488 
27489   if (!args)
27490     return false;
27491   if (args == error_mark_node)
27492     return true;
27493 
27494   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
27495     {
27496       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
27497       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
27498 	if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
27499 	  return true;
27500     }
27501 
27502   return false;
27503 }
27504 
27505 /* Returns true if ARGS contains any errors.  */
27506 
27507 bool
any_erroneous_template_args_p(const_tree args)27508 any_erroneous_template_args_p (const_tree args)
27509 {
27510   int i;
27511   int j;
27512 
27513   if (args == error_mark_node)
27514     return true;
27515 
27516   if (args && TREE_CODE (args) != TREE_VEC)
27517     {
27518       if (tree ti = get_template_info (args))
27519 	args = TI_ARGS (ti);
27520       else
27521 	args = NULL_TREE;
27522     }
27523 
27524   if (!args)
27525     return false;
27526 
27527   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
27528     {
27529       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
27530       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
27531 	if (error_operand_p (TREE_VEC_ELT (level, j)))
27532 	  return true;
27533     }
27534 
27535   return false;
27536 }
27537 
27538 /* Returns TRUE if the template TMPL is type-dependent.  */
27539 
27540 bool
dependent_template_p(tree tmpl)27541 dependent_template_p (tree tmpl)
27542 {
27543   if (TREE_CODE (tmpl) == OVERLOAD)
27544     {
27545       for (lkp_iterator iter (tmpl); iter; ++iter)
27546 	if (dependent_template_p (*iter))
27547 	  return true;
27548       return false;
27549     }
27550 
27551   /* Template template parameters are dependent.  */
27552   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
27553       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
27554     return true;
27555   /* So are names that have not been looked up.  */
27556   if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
27557     return true;
27558   return false;
27559 }
27560 
27561 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
27562 
27563 bool
dependent_template_id_p(tree tmpl,tree args)27564 dependent_template_id_p (tree tmpl, tree args)
27565 {
27566   return (dependent_template_p (tmpl)
27567 	  || any_dependent_template_arguments_p (args));
27568 }
27569 
27570 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
27571    are dependent.  */
27572 
27573 bool
dependent_omp_for_p(tree declv,tree initv,tree condv,tree incrv)27574 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
27575 {
27576   int i;
27577 
27578   if (!processing_template_decl)
27579     return false;
27580 
27581   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
27582     {
27583       tree decl = TREE_VEC_ELT (declv, i);
27584       tree init = TREE_VEC_ELT (initv, i);
27585       tree cond = TREE_VEC_ELT (condv, i);
27586       tree incr = TREE_VEC_ELT (incrv, i);
27587 
27588       if (type_dependent_expression_p (decl)
27589 	  || TREE_CODE (decl) == SCOPE_REF)
27590 	return true;
27591 
27592       if (init && type_dependent_expression_p (init))
27593 	return true;
27594 
27595       if (cond == global_namespace)
27596 	return true;
27597 
27598       if (type_dependent_expression_p (cond))
27599 	return true;
27600 
27601       if (COMPARISON_CLASS_P (cond)
27602 	  && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
27603 	      || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
27604 	return true;
27605 
27606       if (TREE_CODE (incr) == MODOP_EXPR)
27607 	{
27608 	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
27609 	      || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
27610 	    return true;
27611 	}
27612       else if (type_dependent_expression_p (incr))
27613 	return true;
27614       else if (TREE_CODE (incr) == MODIFY_EXPR)
27615 	{
27616 	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
27617 	    return true;
27618 	  else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
27619 	    {
27620 	      tree t = TREE_OPERAND (incr, 1);
27621 	      if (type_dependent_expression_p (TREE_OPERAND (t, 0))
27622 		  || type_dependent_expression_p (TREE_OPERAND (t, 1)))
27623 		return true;
27624 
27625 	      /* If this loop has a class iterator with != comparison
27626 		 with increment other than i++/++i/i--/--i, make sure the
27627 		 increment is constant.  */
27628 	      if (CLASS_TYPE_P (TREE_TYPE (decl))
27629 		  && TREE_CODE (cond) == NE_EXPR)
27630 		{
27631 		  if (TREE_OPERAND (t, 0) == decl)
27632 		    t = TREE_OPERAND (t, 1);
27633 		  else
27634 		    t = TREE_OPERAND (t, 0);
27635 		  if (TREE_CODE (t) != INTEGER_CST)
27636 		    return true;
27637 		}
27638 	    }
27639 	}
27640     }
27641 
27642   return false;
27643 }
27644 
27645 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
27646    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
27647    no such TYPE can be found.  Note that this function peers inside
27648    uninstantiated templates and therefore should be used only in
27649    extremely limited situations.  ONLY_CURRENT_P restricts this
27650    peering to the currently open classes hierarchy (which is required
27651    when comparing types).  */
27652 
27653 tree
resolve_typename_type(tree type,bool only_current_p)27654 resolve_typename_type (tree type, bool only_current_p)
27655 {
27656   tree scope;
27657   tree name;
27658   tree decl;
27659   int quals;
27660   tree pushed_scope;
27661   tree result;
27662 
27663   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
27664 
27665   scope = TYPE_CONTEXT (type);
27666   /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope.  */
27667   gcc_checking_assert (uses_template_parms (scope));
27668 
27669   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
27670      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
27671      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
27672      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
27673      identifier  of the TYPENAME_TYPE anymore.
27674      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
27675      TYPENAME_TYPE instead, we avoid messing up with a possible
27676      typedef variant case.  */
27677   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
27678 
27679   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
27680      it first before we can figure out what NAME refers to.  */
27681   if (TREE_CODE (scope) == TYPENAME_TYPE)
27682     {
27683       if (TYPENAME_IS_RESOLVING_P (scope))
27684 	/* Given a class template A with a dependent base with nested type C,
27685 	   typedef typename A::C::C C will land us here, as trying to resolve
27686 	   the initial A::C leads to the local C typedef, which leads back to
27687 	   A::C::C.  So we break the recursion now.  */
27688 	return type;
27689       else
27690 	scope = resolve_typename_type (scope, only_current_p);
27691     }
27692   /* If we don't know what SCOPE refers to, then we cannot resolve the
27693      TYPENAME_TYPE.  */
27694   if (!CLASS_TYPE_P (scope))
27695     return type;
27696   /* If this is a typedef, we don't want to look inside (c++/11987).  */
27697   if (typedef_variant_p (type))
27698     return type;
27699   /* If SCOPE isn't the template itself, it will not have a valid
27700      TYPE_FIELDS list.  */
27701   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
27702     /* scope is either the template itself or a compatible instantiation
27703        like X<T>, so look up the name in the original template.  */
27704     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
27705   /* If scope has no fields, it can't be a current instantiation.  Check this
27706      before currently_open_class to avoid infinite recursion (71515).  */
27707   if (!TYPE_FIELDS (scope))
27708     return type;
27709   /* If the SCOPE is not the current instantiation, there's no reason
27710      to look inside it.  */
27711   if (only_current_p && !currently_open_class (scope))
27712     return type;
27713   /* Enter the SCOPE so that name lookup will be resolved as if we
27714      were in the class definition.  In particular, SCOPE will no
27715      longer be considered a dependent type.  */
27716   pushed_scope = push_scope (scope);
27717   /* Look up the declaration.  */
27718   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
27719 			tf_warning_or_error);
27720 
27721   result = NULL_TREE;
27722 
27723   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
27724      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
27725   tree fullname = TYPENAME_TYPE_FULLNAME (type);
27726   if (!decl)
27727     /*nop*/;
27728   else if (identifier_p (fullname)
27729 	   && TREE_CODE (decl) == TYPE_DECL)
27730     {
27731       result = TREE_TYPE (decl);
27732       if (result == error_mark_node)
27733 	result = NULL_TREE;
27734     }
27735   else if (TREE_CODE (fullname) == TEMPLATE_ID_EXPR
27736 	   && DECL_CLASS_TEMPLATE_P (decl))
27737     {
27738       /* Obtain the template and the arguments.  */
27739       tree tmpl = TREE_OPERAND (fullname, 0);
27740       if (TREE_CODE (tmpl) == IDENTIFIER_NODE)
27741 	{
27742 	  /* We get here with a plain identifier because a previous tentative
27743 	     parse of the nested-name-specifier as part of a ptr-operator saw
27744 	     ::template X<A>.  The use of ::template is necessary in a
27745 	     ptr-operator, but wrong in a declarator-id.
27746 
27747 	     [temp.names]: In a qualified-id of a declarator-id, the keyword
27748 	     template shall not appear at the top level.  */
27749 	  pedwarn (cp_expr_loc_or_input_loc (fullname), OPT_Wpedantic,
27750 		   "keyword %<template%> not allowed in declarator-id");
27751 	  tmpl = decl;
27752 	}
27753       tree args = TREE_OPERAND (fullname, 1);
27754       /* Instantiate the template.  */
27755       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
27756 				      /*entering_scope=*/true,
27757 				      tf_error | tf_user);
27758       if (result == error_mark_node)
27759 	result = NULL_TREE;
27760     }
27761 
27762   /* Leave the SCOPE.  */
27763   if (pushed_scope)
27764     pop_scope (pushed_scope);
27765 
27766   /* If we failed to resolve it, return the original typename.  */
27767   if (!result)
27768     return type;
27769 
27770   /* If lookup found a typename type, resolve that too.  */
27771   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
27772     {
27773       /* Ill-formed programs can cause infinite recursion here, so we
27774 	 must catch that.  */
27775       TYPENAME_IS_RESOLVING_P (result) = 1;
27776       result = resolve_typename_type (result, only_current_p);
27777       TYPENAME_IS_RESOLVING_P (result) = 0;
27778     }
27779 
27780   /* Qualify the resulting type.  */
27781   quals = cp_type_quals (type);
27782   if (quals)
27783     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
27784 
27785   return result;
27786 }
27787 
27788 /* EXPR is an expression which is not type-dependent.  Return a proxy
27789    for EXPR that can be used to compute the types of larger
27790    expressions containing EXPR.  */
27791 
27792 tree
build_non_dependent_expr(tree expr)27793 build_non_dependent_expr (tree expr)
27794 {
27795   tree orig_expr = expr;
27796   tree inner_expr;
27797 
27798   /* When checking, try to get a constant value for all non-dependent
27799      expressions in order to expose bugs in *_dependent_expression_p
27800      and constexpr.  This can affect code generation, see PR70704, so
27801      only do this for -fchecking=2.  */
27802   if (flag_checking > 1
27803       && cxx_dialect >= cxx11
27804       /* Don't do this during nsdmi parsing as it can lead to
27805 	 unexpected recursive instantiations.  */
27806       && !parsing_nsdmi ()
27807       /* Don't do this during concept processing either and for
27808          the same reason.  */
27809       && !processing_constraint_expression_p ())
27810     fold_non_dependent_expr (expr, tf_none);
27811 
27812   STRIP_ANY_LOCATION_WRAPPER (expr);
27813 
27814   /* Preserve OVERLOADs; the functions must be available to resolve
27815      types.  */
27816   inner_expr = expr;
27817   if (TREE_CODE (inner_expr) == STMT_EXPR)
27818     inner_expr = stmt_expr_value_expr (inner_expr);
27819   if (TREE_CODE (inner_expr) == ADDR_EXPR)
27820     inner_expr = TREE_OPERAND (inner_expr, 0);
27821   if (TREE_CODE (inner_expr) == COMPONENT_REF)
27822     inner_expr = TREE_OPERAND (inner_expr, 1);
27823   if (is_overloaded_fn (inner_expr)
27824       || TREE_CODE (inner_expr) == OFFSET_REF)
27825     return orig_expr;
27826   /* There is no need to return a proxy for a variable or enumerator.  */
27827   if (VAR_P (expr) || TREE_CODE (expr) == CONST_DECL)
27828     return orig_expr;
27829   /* Preserve string constants; conversions from string constants to
27830      "char *" are allowed, even though normally a "const char *"
27831      cannot be used to initialize a "char *".  */
27832   if (TREE_CODE (expr) == STRING_CST)
27833     return orig_expr;
27834   /* Preserve void and arithmetic constants, as an optimization -- there is no
27835      reason to create a new node.  */
27836   if (TREE_CODE (expr) == VOID_CST
27837       || TREE_CODE (expr) == INTEGER_CST
27838       || TREE_CODE (expr) == REAL_CST)
27839     return orig_expr;
27840   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
27841      There is at least one place where we want to know that a
27842      particular expression is a throw-expression: when checking a ?:
27843      expression, there are special rules if the second or third
27844      argument is a throw-expression.  */
27845   if (TREE_CODE (expr) == THROW_EXPR)
27846     return orig_expr;
27847 
27848   /* Don't wrap an initializer list, we need to be able to look inside.  */
27849   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
27850     return orig_expr;
27851 
27852   /* Don't wrap a dummy object, we need to be able to test for it.  */
27853   if (is_dummy_object (expr))
27854     return orig_expr;
27855 
27856   if (TREE_CODE (expr) == COND_EXPR)
27857     return build3 (COND_EXPR,
27858 		   TREE_TYPE (expr),
27859 		   build_non_dependent_expr (TREE_OPERAND (expr, 0)),
27860 		   (TREE_OPERAND (expr, 1)
27861 		    ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
27862 		    : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
27863 		   build_non_dependent_expr (TREE_OPERAND (expr, 2)));
27864   if (TREE_CODE (expr) == COMPOUND_EXPR
27865       && !COMPOUND_EXPR_OVERLOADED (expr))
27866     return build2 (COMPOUND_EXPR,
27867 		   TREE_TYPE (expr),
27868 		   TREE_OPERAND (expr, 0),
27869 		   build_non_dependent_expr (TREE_OPERAND (expr, 1)));
27870 
27871   /* If the type is unknown, it can't really be non-dependent */
27872   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
27873 
27874   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
27875   return build1_loc (EXPR_LOCATION (orig_expr), NON_DEPENDENT_EXPR,
27876 		     TREE_TYPE (expr), expr);
27877 }
27878 
27879 /* ARGS is a vector of expressions as arguments to a function call.
27880    Replace the arguments with equivalent non-dependent expressions.
27881    This modifies ARGS in place.  */
27882 
27883 void
make_args_non_dependent(vec<tree,va_gc> * args)27884 make_args_non_dependent (vec<tree, va_gc> *args)
27885 {
27886   unsigned int ix;
27887   tree arg;
27888 
27889   FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
27890     {
27891       tree newarg = build_non_dependent_expr (arg);
27892       if (newarg != arg)
27893 	(*args)[ix] = newarg;
27894     }
27895 }
27896 
27897 /* Returns a type which represents 'auto' or 'decltype(auto)'.  We use a
27898    TEMPLATE_TYPE_PARM with a level one deeper than the actual template
27899    parms.  If set_canonical is true, we set TYPE_CANONICAL on it.  */
27900 
27901 static tree
make_auto_1(tree name,bool set_canonical)27902 make_auto_1 (tree name, bool set_canonical)
27903 {
27904   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
27905   TYPE_NAME (au) = build_decl (input_location, TYPE_DECL, name, au);
27906   TYPE_STUB_DECL (au) = TYPE_NAME (au);
27907   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
27908     (0, processing_template_decl + 1, processing_template_decl + 1,
27909      TYPE_NAME (au), NULL_TREE);
27910   if (set_canonical)
27911     TYPE_CANONICAL (au) = canonical_type_parameter (au);
27912   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
27913   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
27914   if (name == decltype_auto_identifier)
27915     AUTO_IS_DECLTYPE (au) = true;
27916 
27917   return au;
27918 }
27919 
27920 tree
make_decltype_auto(void)27921 make_decltype_auto (void)
27922 {
27923   return make_auto_1 (decltype_auto_identifier, true);
27924 }
27925 
27926 tree
make_auto(void)27927 make_auto (void)
27928 {
27929   return make_auto_1 (auto_identifier, true);
27930 }
27931 
27932 /* Return a C++17 deduction placeholder for class template TMPL.  */
27933 
27934 tree
make_template_placeholder(tree tmpl)27935 make_template_placeholder (tree tmpl)
27936 {
27937   tree t = make_auto_1 (auto_identifier, false);
27938   CLASS_PLACEHOLDER_TEMPLATE (t) = tmpl;
27939   /* Our canonical type depends on the placeholder.  */
27940   TYPE_CANONICAL (t) = canonical_type_parameter (t);
27941   return t;
27942 }
27943 
27944 /* True iff T is a C++17 class template deduction placeholder.  */
27945 
27946 bool
template_placeholder_p(tree t)27947 template_placeholder_p (tree t)
27948 {
27949   return is_auto (t) && CLASS_PLACEHOLDER_TEMPLATE (t);
27950 }
27951 
27952 /* Make a "constrained auto" type-specifier. This is an auto or
27953   decltype(auto) type with constraints that must be associated after
27954   deduction.  The constraint is formed from the given concept CON
27955   and its optional sequence of template arguments ARGS.
27956 
27957   TYPE must be the result of make_auto_type or make_decltype_auto_type. */
27958 
27959 static tree
make_constrained_placeholder_type(tree type,tree con,tree args)27960 make_constrained_placeholder_type (tree type, tree con, tree args)
27961 {
27962   /* Build the constraint. */
27963   tree tmpl = DECL_TI_TEMPLATE (con);
27964   tree expr = tmpl;
27965   if (TREE_CODE (con) == FUNCTION_DECL)
27966     expr = ovl_make (tmpl);
27967   expr = build_concept_check (expr, type, args, tf_warning_or_error);
27968 
27969   PLACEHOLDER_TYPE_CONSTRAINTS (type) = expr;
27970 
27971   /* Our canonical type depends on the constraint.  */
27972   TYPE_CANONICAL (type) = canonical_type_parameter (type);
27973 
27974   /* Attach the constraint to the type declaration. */
27975   return TYPE_NAME (type);
27976 }
27977 
27978 /* Make a "constrained auto" type-specifier.  */
27979 
27980 tree
make_constrained_auto(tree con,tree args)27981 make_constrained_auto (tree con, tree args)
27982 {
27983   tree type = make_auto_1 (auto_identifier, false);
27984   return make_constrained_placeholder_type (type, con, args);
27985 }
27986 
27987 /* Make a "constrained decltype(auto)" type-specifier.  */
27988 
27989 tree
make_constrained_decltype_auto(tree con,tree args)27990 make_constrained_decltype_auto (tree con, tree args)
27991 {
27992   tree type = make_auto_1 (decltype_auto_identifier, false);
27993   return make_constrained_placeholder_type (type, con, args);
27994 }
27995 
27996 /* Build and return a concept definition. Like other templates, the
27997    CONCEPT_DECL node is wrapped by a TEMPLATE_DECL.  This returns the
27998    the TEMPLATE_DECL. */
27999 
28000 tree
finish_concept_definition(cp_expr id,tree init)28001 finish_concept_definition (cp_expr id, tree init)
28002 {
28003   gcc_assert (identifier_p (id));
28004   gcc_assert (processing_template_decl);
28005 
28006   location_t loc = id.get_location();
28007 
28008   /* A concept-definition shall not have associated constraints.  */
28009   if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
28010     {
28011       error_at (loc, "a concept cannot be constrained");
28012       TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
28013     }
28014 
28015   /* A concept-definition shall appear in namespace scope.  Templates
28016      aren't allowed in block scope, so we only need to check for class
28017      scope.  */
28018   if (TYPE_P (current_scope()) || !DECL_NAMESPACE_SCOPE_P (current_scope ()))
28019     {
28020       error_at (loc, "concept %qE not in namespace scope", *id);
28021       return error_mark_node;
28022     }
28023 
28024   /* Initially build the concept declaration; it's type is bool.  */
28025   tree decl = build_lang_decl_loc (loc, CONCEPT_DECL, *id, boolean_type_node);
28026   DECL_CONTEXT (decl) = current_scope ();
28027   DECL_INITIAL (decl) = init;
28028 
28029   /* Push the enclosing template.  */
28030   return push_template_decl (decl);
28031 }
28032 
28033 /* Given type ARG, return std::initializer_list<ARG>.  */
28034 
28035 static tree
listify(tree arg)28036 listify (tree arg)
28037 {
28038   tree std_init_list = get_namespace_binding (std_node, init_list_identifier);
28039 
28040   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
28041     {
28042       gcc_rich_location richloc (input_location);
28043       maybe_add_include_fixit (&richloc, "<initializer_list>", false);
28044       error_at (&richloc,
28045 		"deducing from brace-enclosed initializer list"
28046 		" requires %<#include <initializer_list>%>");
28047 
28048       return error_mark_node;
28049     }
28050   tree argvec = make_tree_vec (1);
28051   TREE_VEC_ELT (argvec, 0) = arg;
28052 
28053   return lookup_template_class (std_init_list, argvec, NULL_TREE,
28054 				NULL_TREE, 0, tf_warning_or_error);
28055 }
28056 
28057 /* Replace auto in TYPE with std::initializer_list<auto>.  */
28058 
28059 static tree
listify_autos(tree type,tree auto_node)28060 listify_autos (tree type, tree auto_node)
28061 {
28062   tree init_auto = listify (strip_top_quals (auto_node));
28063   tree argvec = make_tree_vec (1);
28064   TREE_VEC_ELT (argvec, 0) = init_auto;
28065   if (processing_template_decl)
28066     argvec = add_to_template_args (current_template_args (), argvec);
28067   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
28068 }
28069 
28070 /* Hash traits for hashing possibly constrained 'auto'
28071    TEMPLATE_TYPE_PARMs for use by do_auto_deduction.  */
28072 
28073 struct auto_hash : default_hash_traits<tree>
28074 {
28075   static inline hashval_t hash (tree);
28076   static inline bool equal (tree, tree);
28077 };
28078 
28079 /* Hash the 'auto' T.  */
28080 
28081 inline hashval_t
hash(tree t)28082 auto_hash::hash (tree t)
28083 {
28084   if (tree c = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (t)))
28085     /* Matching constrained-type-specifiers denote the same template
28086        parameter, so hash the constraint.  */
28087     return hash_placeholder_constraint (c);
28088   else
28089     /* But unconstrained autos are all separate, so just hash the pointer.  */
28090     return iterative_hash_object (t, 0);
28091 }
28092 
28093 /* Compare two 'auto's.  */
28094 
28095 inline bool
equal(tree t1,tree t2)28096 auto_hash::equal (tree t1, tree t2)
28097 {
28098   if (t1 == t2)
28099     return true;
28100 
28101   tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
28102   tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
28103 
28104   /* Two unconstrained autos are distinct.  */
28105   if (!c1 || !c2)
28106     return false;
28107 
28108   return equivalent_placeholder_constraints (c1, c2);
28109 }
28110 
28111 /* for_each_template_parm callback for extract_autos: if t is a (possibly
28112    constrained) auto, add it to the vector.  */
28113 
28114 static int
extract_autos_r(tree t,void * data)28115 extract_autos_r (tree t, void *data)
28116 {
28117   hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
28118   if (is_auto (t))
28119     {
28120       /* All the autos were built with index 0; fix that up now.  */
28121       tree *p = hash.find_slot (t, INSERT);
28122       unsigned idx;
28123       if (*p)
28124 	/* If this is a repeated constrained-type-specifier, use the index we
28125 	   chose before.  */
28126 	idx = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (*p));
28127       else
28128 	{
28129 	  /* Otherwise this is new, so use the current count.  */
28130 	  *p = t;
28131 	  idx = hash.elements () - 1;
28132 	}
28133       TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (t)) = idx;
28134     }
28135 
28136   /* Always keep walking.  */
28137   return 0;
28138 }
28139 
28140 /* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
28141    says they can appear anywhere in the type.  */
28142 
28143 static tree
extract_autos(tree type)28144 extract_autos (tree type)
28145 {
28146   hash_set<tree> visited;
28147   hash_table<auto_hash> hash (2);
28148 
28149   for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
28150 
28151   tree tree_vec = make_tree_vec (hash.elements());
28152   for (hash_table<auto_hash>::iterator iter = hash.begin();
28153        iter != hash.end(); ++iter)
28154     {
28155       tree elt = *iter;
28156       unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
28157       TREE_VEC_ELT (tree_vec, i)
28158 	= build_tree_list (NULL_TREE, TYPE_NAME (elt));
28159     }
28160 
28161   return tree_vec;
28162 }
28163 
28164 /* The stem for deduction guide names.  */
28165 const char *const dguide_base = "__dguide_";
28166 
28167 /* Return the name for a deduction guide for class template TMPL.  */
28168 
28169 tree
dguide_name(tree tmpl)28170 dguide_name (tree tmpl)
28171 {
28172   tree type = (TYPE_P (tmpl) ? tmpl : TREE_TYPE (tmpl));
28173   tree tname = TYPE_IDENTIFIER (type);
28174   char *buf = (char *) alloca (1 + strlen (dguide_base)
28175 			       + IDENTIFIER_LENGTH (tname));
28176   memcpy (buf, dguide_base, strlen (dguide_base));
28177   memcpy (buf + strlen (dguide_base), IDENTIFIER_POINTER (tname),
28178 	  IDENTIFIER_LENGTH (tname) + 1);
28179   tree dname = get_identifier (buf);
28180   TREE_TYPE (dname) = type;
28181   return dname;
28182 }
28183 
28184 /* True if NAME is the name of a deduction guide.  */
28185 
28186 bool
dguide_name_p(tree name)28187 dguide_name_p (tree name)
28188 {
28189   return (TREE_CODE (name) == IDENTIFIER_NODE
28190 	  && TREE_TYPE (name)
28191 	  && !strncmp (IDENTIFIER_POINTER (name), dguide_base,
28192 		       strlen (dguide_base)));
28193 }
28194 
28195 /* True if FN is a deduction guide.  */
28196 
28197 bool
deduction_guide_p(const_tree fn)28198 deduction_guide_p (const_tree fn)
28199 {
28200   if (DECL_P (fn))
28201     if (tree name = DECL_NAME (fn))
28202       return dguide_name_p (name);
28203   return false;
28204 }
28205 
28206 /* True if FN is the copy deduction guide, i.e. A(A)->A.  */
28207 
28208 bool
copy_guide_p(const_tree fn)28209 copy_guide_p (const_tree fn)
28210 {
28211   gcc_assert (deduction_guide_p (fn));
28212   if (!DECL_ARTIFICIAL (fn))
28213     return false;
28214   tree parms = FUNCTION_FIRST_USER_PARMTYPE (DECL_TI_TEMPLATE (fn));
28215   return (TREE_CHAIN (parms) == void_list_node
28216 	  && same_type_p (TREE_VALUE (parms), TREE_TYPE (DECL_NAME (fn))));
28217 }
28218 
28219 /* True if FN is a guide generated from a constructor template.  */
28220 
28221 bool
template_guide_p(const_tree fn)28222 template_guide_p (const_tree fn)
28223 {
28224   gcc_assert (deduction_guide_p (fn));
28225   if (!DECL_ARTIFICIAL (fn))
28226     return false;
28227   tree tmpl = DECL_TI_TEMPLATE (fn);
28228   if (tree org = DECL_ABSTRACT_ORIGIN (tmpl))
28229     return PRIMARY_TEMPLATE_P (org);
28230   return false;
28231 }
28232 
28233 /* OLDDECL is a _DECL for a template parameter.  Return a similar parameter at
28234    LEVEL:INDEX, using tsubst_args and complain for substitution into non-type
28235    template parameter types.  Note that the handling of template template
28236    parameters relies on current_template_parms being set appropriately for the
28237    new template.  */
28238 
28239 static tree
rewrite_template_parm(tree olddecl,unsigned index,unsigned level,tree tsubst_args,tsubst_flags_t complain)28240 rewrite_template_parm (tree olddecl, unsigned index, unsigned level,
28241 		       tree tsubst_args, tsubst_flags_t complain)
28242 {
28243   if (olddecl == error_mark_node)
28244     return error_mark_node;
28245 
28246   tree oldidx = get_template_parm_index (olddecl);
28247 
28248   tree newtype;
28249   if (TREE_CODE (olddecl) == TYPE_DECL
28250       || TREE_CODE (olddecl) == TEMPLATE_DECL)
28251     {
28252       tree oldtype = TREE_TYPE (olddecl);
28253       newtype = cxx_make_type (TREE_CODE (oldtype));
28254       TYPE_MAIN_VARIANT (newtype) = newtype;
28255       if (TREE_CODE (oldtype) == TEMPLATE_TYPE_PARM)
28256 	TEMPLATE_TYPE_PARM_FOR_CLASS (newtype)
28257 	  = TEMPLATE_TYPE_PARM_FOR_CLASS (oldtype);
28258     }
28259   else
28260     {
28261       newtype = TREE_TYPE (olddecl);
28262       if (type_uses_auto (newtype))
28263 	{
28264 	  // Substitute once to fix references to other template parameters.
28265 	  newtype = tsubst (newtype, tsubst_args,
28266 			    complain|tf_partial, NULL_TREE);
28267 	  // Now substitute again to reduce the level of the auto.
28268 	  newtype = tsubst (newtype, current_template_args (),
28269 			    complain, NULL_TREE);
28270 	}
28271       else
28272 	newtype = tsubst (newtype, tsubst_args,
28273 			  complain, NULL_TREE);
28274     }
28275 
28276   tree newdecl
28277     = build_decl (DECL_SOURCE_LOCATION (olddecl), TREE_CODE (olddecl),
28278 		  DECL_NAME (olddecl), newtype);
28279   SET_DECL_TEMPLATE_PARM_P (newdecl);
28280 
28281   tree newidx;
28282   if (TREE_CODE (olddecl) == TYPE_DECL
28283       || TREE_CODE (olddecl) == TEMPLATE_DECL)
28284     {
28285       newidx = TEMPLATE_TYPE_PARM_INDEX (newtype)
28286 	= build_template_parm_index (index, level, level,
28287 				     newdecl, newtype);
28288       TEMPLATE_PARM_PARAMETER_PACK (newidx)
28289 	= TEMPLATE_PARM_PARAMETER_PACK (oldidx);
28290       TYPE_STUB_DECL (newtype) = TYPE_NAME (newtype) = newdecl;
28291       if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (olddecl)))
28292 	SET_TYPE_STRUCTURAL_EQUALITY (newtype);
28293       else
28294 	TYPE_CANONICAL (newtype) = canonical_type_parameter (newtype);
28295 
28296       if (TREE_CODE (olddecl) == TEMPLATE_DECL)
28297 	{
28298 	  DECL_TEMPLATE_RESULT (newdecl)
28299 	    = build_decl (DECL_SOURCE_LOCATION (olddecl), TYPE_DECL,
28300 			  DECL_NAME (olddecl), newtype);
28301 	  DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (newdecl)) = true;
28302 	  // First create a copy (ttargs) of tsubst_args with an
28303 	  // additional level for the template template parameter's own
28304 	  // template parameters (ttparms).
28305 	  tree ttparms = (INNERMOST_TEMPLATE_PARMS
28306 			  (DECL_TEMPLATE_PARMS (olddecl)));
28307 	  const int depth = TMPL_ARGS_DEPTH (tsubst_args);
28308 	  tree ttargs = make_tree_vec (depth + 1);
28309 	  for (int i = 0; i < depth; ++i)
28310 	    TREE_VEC_ELT (ttargs, i) = TREE_VEC_ELT (tsubst_args, i);
28311 	  TREE_VEC_ELT (ttargs, depth)
28312 	    = template_parms_level_to_args (ttparms);
28313 	  // Substitute ttargs into ttparms to fix references to
28314 	  // other template parameters.
28315 	  ttparms = tsubst_template_parms_level (ttparms, ttargs,
28316 						 complain|tf_partial);
28317 	  // Now substitute again with args based on tparms, to reduce
28318 	  // the level of the ttparms.
28319 	  ttargs = current_template_args ();
28320 	  ttparms = tsubst_template_parms_level (ttparms, ttargs,
28321 						 complain);
28322 	  // Finally, tack the adjusted parms onto tparms.
28323 	  ttparms = tree_cons (size_int (depth), ttparms,
28324 			       current_template_parms);
28325 	  DECL_TEMPLATE_PARMS (newdecl) = ttparms;
28326 	}
28327     }
28328   else
28329     {
28330       tree oldconst = TEMPLATE_PARM_DECL (oldidx);
28331       tree newconst
28332 	= build_decl (DECL_SOURCE_LOCATION (oldconst),
28333 		      TREE_CODE (oldconst),
28334 		      DECL_NAME (oldconst), newtype);
28335       TREE_CONSTANT (newconst) = TREE_CONSTANT (newdecl)
28336 	= TREE_READONLY (newconst) = TREE_READONLY (newdecl) = true;
28337       SET_DECL_TEMPLATE_PARM_P (newconst);
28338       newidx = build_template_parm_index (index, level, level,
28339 					  newconst, newtype);
28340       TEMPLATE_PARM_PARAMETER_PACK (newidx)
28341 	= TEMPLATE_PARM_PARAMETER_PACK (oldidx);
28342       DECL_INITIAL (newdecl) = DECL_INITIAL (newconst) = newidx;
28343     }
28344 
28345   return newdecl;
28346 }
28347 
28348 /* As rewrite_template_parm, but for the whole TREE_LIST representing a
28349    template parameter.  */
28350 
28351 static tree
rewrite_tparm_list(tree oldelt,unsigned index,unsigned level,tree targs,unsigned targs_index,tsubst_flags_t complain)28352 rewrite_tparm_list (tree oldelt, unsigned index, unsigned level,
28353 		    tree targs, unsigned targs_index, tsubst_flags_t complain)
28354 {
28355   tree olddecl = TREE_VALUE (oldelt);
28356   tree newdecl = rewrite_template_parm (olddecl, index, level,
28357 					targs, complain);
28358   if (newdecl == error_mark_node)
28359     return error_mark_node;
28360   tree newdef = tsubst_template_arg (TREE_PURPOSE (oldelt),
28361 				     targs, complain, NULL_TREE);
28362   tree list = build_tree_list (newdef, newdecl);
28363   TEMPLATE_PARM_CONSTRAINTS (list)
28364     = tsubst_constraint_info (TEMPLATE_PARM_CONSTRAINTS (oldelt),
28365 			      targs, complain, NULL_TREE);
28366   int depth = TMPL_ARGS_DEPTH (targs);
28367   TMPL_ARG (targs, depth, targs_index) = template_parm_to_arg (list);
28368   return list;
28369 }
28370 
28371 /* Returns a C++17 class deduction guide template based on the constructor
28372    CTOR.  As a special case, CTOR can be a RECORD_TYPE for an implicit default
28373    guide, REFERENCE_TYPE for an implicit copy/move guide, or TREE_LIST for an
28374    aggregate initialization guide.  */
28375 
28376 static tree
build_deduction_guide(tree type,tree ctor,tree outer_args,tsubst_flags_t complain)28377 build_deduction_guide (tree type, tree ctor, tree outer_args, tsubst_flags_t complain)
28378 {
28379   tree tparms, targs, fparms, fargs, ci;
28380   bool memtmpl = false;
28381   bool explicit_p;
28382   location_t loc;
28383   tree fn_tmpl = NULL_TREE;
28384 
28385   if (outer_args)
28386     {
28387       ++processing_template_decl;
28388       type = tsubst (type, outer_args, complain, CLASSTYPE_TI_TEMPLATE (type));
28389       --processing_template_decl;
28390     }
28391 
28392   if (!DECL_DECLARES_FUNCTION_P (ctor))
28393     {
28394       if (TYPE_P (ctor))
28395 	{
28396 	  bool copy_p = TYPE_REF_P (ctor);
28397 	  if (copy_p)
28398 	    fparms = tree_cons (NULL_TREE, type, void_list_node);
28399 	  else
28400 	    fparms = void_list_node;
28401 	}
28402       else if (TREE_CODE (ctor) == TREE_LIST)
28403 	fparms = ctor;
28404       else
28405 	gcc_unreachable ();
28406 
28407       tree ctmpl = CLASSTYPE_TI_TEMPLATE (type);
28408       tparms = DECL_TEMPLATE_PARMS (ctmpl);
28409       targs = CLASSTYPE_TI_ARGS (type);
28410       ci = NULL_TREE;
28411       fargs = NULL_TREE;
28412       loc = DECL_SOURCE_LOCATION (ctmpl);
28413       explicit_p = false;
28414     }
28415   else
28416     {
28417       ++processing_template_decl;
28418       bool ok = true;
28419 
28420       fn_tmpl
28421 	= (TREE_CODE (ctor) == TEMPLATE_DECL ? ctor
28422 	   : DECL_TI_TEMPLATE (ctor));
28423       if (outer_args)
28424 	fn_tmpl = tsubst (fn_tmpl, outer_args, complain, ctor);
28425       ctor = DECL_TEMPLATE_RESULT (fn_tmpl);
28426 
28427       tparms = DECL_TEMPLATE_PARMS (fn_tmpl);
28428       /* If type is a member class template, DECL_TI_ARGS (ctor) will have
28429 	 fully specialized args for the enclosing class.  Strip those off, as
28430 	 the deduction guide won't have those template parameters.  */
28431       targs = get_innermost_template_args (DECL_TI_ARGS (ctor),
28432 						TMPL_PARMS_DEPTH (tparms));
28433       /* Discard the 'this' parameter.  */
28434       fparms = FUNCTION_ARG_CHAIN (ctor);
28435       fargs = TREE_CHAIN (DECL_ARGUMENTS (ctor));
28436       ci = get_constraints (ctor);
28437       loc = DECL_SOURCE_LOCATION (ctor);
28438       explicit_p = DECL_NONCONVERTING_P (ctor);
28439 
28440       if (PRIMARY_TEMPLATE_P (fn_tmpl))
28441 	{
28442 	  memtmpl = true;
28443 
28444 	  /* For a member template constructor, we need to flatten the two
28445 	     template parameter lists into one, and then adjust the function
28446 	     signature accordingly.  This gets...complicated.  */
28447 	  tree save_parms = current_template_parms;
28448 
28449 	  /* For a member template we should have two levels of parms/args, one
28450 	     for the class and one for the constructor.  We stripped
28451 	     specialized args for further enclosing classes above.  */
28452 	  const int depth = 2;
28453 	  gcc_assert (TMPL_ARGS_DEPTH (targs) == depth);
28454 
28455 	  /* Template args for translating references to the two-level template
28456 	     parameters into references to the one-level template parameters we
28457 	     are creating.  */
28458 	  tree tsubst_args = copy_node (targs);
28459 	  TMPL_ARGS_LEVEL (tsubst_args, depth)
28460 	    = copy_node (TMPL_ARGS_LEVEL (tsubst_args, depth));
28461 
28462 	  /* Template parms for the constructor template.  */
28463 	  tree ftparms = TREE_VALUE (tparms);
28464 	  unsigned flen = TREE_VEC_LENGTH (ftparms);
28465 	  /* Template parms for the class template.  */
28466 	  tparms = TREE_CHAIN (tparms);
28467 	  tree ctparms = TREE_VALUE (tparms);
28468 	  unsigned clen = TREE_VEC_LENGTH (ctparms);
28469 	  /* Template parms for the deduction guide start as a copy of the
28470 	     template parms for the class.  We set current_template_parms for
28471 	     lookup_template_class_1.  */
28472 	  current_template_parms = tparms = copy_node (tparms);
28473 	  tree new_vec = TREE_VALUE (tparms) = make_tree_vec (flen + clen);
28474 	  for (unsigned i = 0; i < clen; ++i)
28475 	    TREE_VEC_ELT (new_vec, i) = TREE_VEC_ELT (ctparms, i);
28476 
28477 	  /* Now we need to rewrite the constructor parms to append them to the
28478 	     class parms.  */
28479 	  for (unsigned i = 0; i < flen; ++i)
28480 	    {
28481 	      unsigned index = i + clen;
28482 	      unsigned level = 1;
28483 	      tree oldelt = TREE_VEC_ELT (ftparms, i);
28484 	      tree newelt
28485 		= rewrite_tparm_list (oldelt, index, level,
28486 				      tsubst_args, i, complain);
28487 	      if (newelt == error_mark_node)
28488 		ok = false;
28489 	      TREE_VEC_ELT (new_vec, index) = newelt;
28490 	    }
28491 
28492 	  /* Now we have a final set of template parms to substitute into the
28493 	     function signature.  */
28494 	  targs = template_parms_to_args (tparms);
28495 	  fparms = tsubst_arg_types (fparms, tsubst_args, NULL_TREE,
28496 				     complain, ctor);
28497 	  if (fparms == error_mark_node)
28498 	    ok = false;
28499 	  if (ci)
28500 	    ci = tsubst_constraint_info (ci, tsubst_args, complain, ctor);
28501 
28502 	  /* Parms are to have DECL_CHAIN tsubsted, which would be skipped if
28503 	     cp_unevaluated_operand.  */
28504 	  cp_evaluated ev;
28505 	  fargs = tsubst (fargs, tsubst_args, complain, ctor);
28506 	  current_template_parms = save_parms;
28507 	}
28508 
28509       --processing_template_decl;
28510       if (!ok)
28511 	return error_mark_node;
28512     }
28513 
28514   if (!memtmpl)
28515     {
28516       /* Copy the parms so we can set DECL_PRIMARY_TEMPLATE.  */
28517       tparms = copy_node (tparms);
28518       INNERMOST_TEMPLATE_PARMS (tparms)
28519 	= copy_node (INNERMOST_TEMPLATE_PARMS (tparms));
28520     }
28521 
28522   tree fntype = build_function_type (type, fparms);
28523   tree ded_fn = build_lang_decl_loc (loc,
28524 				     FUNCTION_DECL,
28525 				     dguide_name (type), fntype);
28526   DECL_ARGUMENTS (ded_fn) = fargs;
28527   DECL_ARTIFICIAL (ded_fn) = true;
28528   DECL_NONCONVERTING_P (ded_fn) = explicit_p;
28529   tree ded_tmpl = build_template_decl (ded_fn, tparms, /*member*/false);
28530   DECL_ARTIFICIAL (ded_tmpl) = true;
28531   DECL_TEMPLATE_RESULT (ded_tmpl) = ded_fn;
28532   TREE_TYPE (ded_tmpl) = TREE_TYPE (ded_fn);
28533   DECL_TEMPLATE_INFO (ded_fn) = build_template_info (ded_tmpl, targs);
28534   DECL_PRIMARY_TEMPLATE (ded_tmpl) = ded_tmpl;
28535   if (DECL_P (ctor))
28536     DECL_ABSTRACT_ORIGIN (ded_tmpl) = fn_tmpl;
28537   if (ci)
28538     set_constraints (ded_tmpl, ci);
28539 
28540   return ded_tmpl;
28541 }
28542 
28543 /* Add to LIST the member types for the reshaped initializer CTOR.  */
28544 
28545 static tree
collect_ctor_idx_types(tree ctor,tree list)28546 collect_ctor_idx_types (tree ctor, tree list)
28547 {
28548   vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (ctor);
28549   tree idx, val; unsigned i;
28550   FOR_EACH_CONSTRUCTOR_ELT (v, i, idx, val)
28551     {
28552       if (BRACE_ENCLOSED_INITIALIZER_P (val)
28553 	  && CONSTRUCTOR_NELTS (val))
28554 	if (tree subidx = CONSTRUCTOR_ELT (val, 0)->index)
28555 	  if (TREE_CODE (subidx) == FIELD_DECL)
28556 	    {
28557 	      list = collect_ctor_idx_types (val, list);
28558 	      continue;
28559 	    }
28560       tree ftype = finish_decltype_type (idx, true, tf_none);
28561       list = tree_cons (NULL_TREE, ftype, list);
28562     }
28563 
28564   return list;
28565 }
28566 
28567 /* Return whether ETYPE is, or is derived from, a specialization of TMPL.  */
28568 
28569 static bool
is_spec_or_derived(tree etype,tree tmpl)28570 is_spec_or_derived (tree etype, tree tmpl)
28571 {
28572   if (!etype || !CLASS_TYPE_P (etype))
28573     return false;
28574 
28575   tree type = TREE_TYPE (tmpl);
28576   tree tparms = (INNERMOST_TEMPLATE_PARMS
28577 		 (DECL_TEMPLATE_PARMS (tmpl)));
28578   tree targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
28579   int err = unify (tparms, targs, type, etype,
28580 		   UNIFY_ALLOW_DERIVED, /*explain*/false);
28581   ggc_free (targs);
28582   return !err;
28583 }
28584 
28585 /* Return a C++20 aggregate deduction candidate for TYPE initialized from
28586    INIT.  */
28587 
28588 static tree
maybe_aggr_guide(tree tmpl,tree init,vec<tree,va_gc> * args)28589 maybe_aggr_guide (tree tmpl, tree init, vec<tree,va_gc> *args)
28590 {
28591   if (cxx_dialect < cxx2a)
28592     return NULL_TREE;
28593 
28594   if (init == NULL_TREE)
28595     return NULL_TREE;
28596 
28597   tree type = TREE_TYPE (tmpl);
28598   if (!CP_AGGREGATE_TYPE_P (type))
28599     return NULL_TREE;
28600 
28601   /* No aggregate candidate for copy-initialization.  */
28602   if (args->length() == 1)
28603     {
28604       tree val = (*args)[0];
28605       if (is_spec_or_derived (tmpl, TREE_TYPE (val)))
28606 	return NULL_TREE;
28607     }
28608 
28609   /* If we encounter a problem, we just won't add the candidate.  */
28610   tsubst_flags_t complain = tf_none;
28611 
28612   tree parms = NULL_TREE;
28613   if (BRACE_ENCLOSED_INITIALIZER_P (init))
28614     {
28615       init = reshape_init (type, init, complain);
28616       if (init == error_mark_node)
28617 	return NULL_TREE;
28618       parms = collect_ctor_idx_types (init, parms);
28619     }
28620   else if (TREE_CODE (init) == TREE_LIST)
28621     {
28622       int len = list_length (init);
28623       for (tree field = TYPE_FIELDS (type);
28624 	   len;
28625 	   --len, field = DECL_CHAIN (field))
28626 	{
28627 	  field = next_initializable_field (field);
28628 	  if (!field)
28629 	    return NULL_TREE;
28630 	  tree ftype = finish_decltype_type (field, true, complain);
28631 	  parms = tree_cons (NULL_TREE, ftype, parms);
28632 	}
28633     }
28634   else
28635     /* Aggregate initialization doesn't apply to an initializer expression.  */
28636     return NULL_TREE;
28637 
28638   if (parms)
28639     {
28640       tree last = parms;
28641       parms = nreverse (parms);
28642       TREE_CHAIN (last) = void_list_node;
28643       tree guide = build_deduction_guide (type, parms, NULL_TREE, complain);
28644       return guide;
28645     }
28646 
28647   return NULL_TREE;
28648 }
28649 
28650 /* UGUIDES are the deduction guides for the underlying template of alias
28651    template TMPL; adjust them to be deduction guides for TMPL.  */
28652 
28653 static tree
alias_ctad_tweaks(tree tmpl,tree uguides)28654 alias_ctad_tweaks (tree tmpl, tree uguides)
28655 {
28656   /* [over.match.class.deduct]: When resolving a placeholder for a deduced
28657      class type (9.2.8.2) where the template-name names an alias template A,
28658      the defining-type-id of A must be of the form
28659 
28660      typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
28661 
28662      as specified in 9.2.8.2. The guides of A are the set of functions or
28663      function templates formed as follows. For each function or function
28664      template f in the guides of the template named by the simple-template-id
28665      of the defining-type-id, the template arguments of the return type of f
28666      are deduced from the defining-type-id of A according to the process in
28667      13.10.2.5 with the exception that deduction does not fail if not all
28668      template arguments are deduced. Let g denote the result of substituting
28669      these deductions into f. If substitution succeeds, form a function or
28670      function template f' with the following properties and add it to the set
28671      of guides of A:
28672 
28673      * The function type of f' is the function type of g.
28674 
28675      * If f is a function template, f' is a function template whose template
28676      parameter list consists of all the template parameters of A (including
28677      their default template arguments) that appear in the above deductions or
28678      (recursively) in their default template arguments, followed by the
28679      template parameters of f that were not deduced (including their default
28680      template arguments), otherwise f' is not a function template.
28681 
28682      * The associated constraints (13.5.2) are the conjunction of the
28683      associated constraints of g and a constraint that is satisfied if and only
28684      if the arguments of A are deducible (see below) from the return type.
28685 
28686      * If f is a copy deduction candidate (12.4.1.8), then f' is considered to
28687      be so as well.
28688 
28689      * If f was generated from a deduction-guide (12.4.1.8), then f' is
28690      considered to be so as well.
28691 
28692      * The explicit-specifier of f' is the explicit-specifier of g (if
28693      any).  */
28694 
28695   /* This implementation differs from the above in two significant ways:
28696 
28697      1) We include all template parameters of A, not just some.
28698      2) The added constraint is same_type instead of deducible.
28699 
28700      I believe that while it's probably possible to construct a testcase that
28701      behaves differently with this simplification, it should have the same
28702      effect for real uses.  Including all template parameters means that we
28703      deduce all parameters of A when resolving the call, so when we're in the
28704      constraint we don't need to deduce them again, we can just check whether
28705      the deduction produced the desired result.  */
28706 
28707   tsubst_flags_t complain = tf_warning_or_error;
28708   tree atype = TREE_TYPE (tmpl);
28709   tree aguides = NULL_TREE;
28710   tree atparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
28711   unsigned natparms = TREE_VEC_LENGTH (atparms);
28712   tree utype = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
28713   for (ovl_iterator iter (uguides); iter; ++iter)
28714     {
28715       tree f = *iter;
28716       tree in_decl = f;
28717       location_t loc = DECL_SOURCE_LOCATION (f);
28718       tree ret = TREE_TYPE (TREE_TYPE (f));
28719       tree fprime = f;
28720       if (TREE_CODE (f) == TEMPLATE_DECL)
28721 	{
28722 	  processing_template_decl_sentinel ptds (/*reset*/false);
28723 	  ++processing_template_decl;
28724 
28725 	  /* Deduce template arguments for f from the type-id of A.  */
28726 	  tree ftparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (f));
28727 	  unsigned len = TREE_VEC_LENGTH (ftparms);
28728 	  tree targs = make_tree_vec (len);
28729 	  int err = unify (ftparms, targs, ret, utype, UNIFY_ALLOW_NONE, false);
28730 	  gcc_assert (!err);
28731 
28732 	  /* The number of parms for f' is the number of parms for A plus
28733 	     non-deduced parms of f.  */
28734 	  unsigned ndlen = 0;
28735 	  unsigned j;
28736 	  for (unsigned i = 0; i < len; ++i)
28737 	    if (TREE_VEC_ELT (targs, i) == NULL_TREE)
28738 	      ++ndlen;
28739 	  tree gtparms = make_tree_vec (natparms + ndlen);
28740 
28741 	  /* First copy over the parms of A.  */
28742 	  for (j = 0; j < natparms; ++j)
28743 	    TREE_VEC_ELT (gtparms, j) = TREE_VEC_ELT (atparms, j);
28744 	  /* Now rewrite the non-deduced parms of f.  */
28745 	  for (unsigned i = 0; ndlen && i < len; ++i)
28746 	    if (TREE_VEC_ELT (targs, i) == NULL_TREE)
28747 	      {
28748 		--ndlen;
28749 		unsigned index = j++;
28750 		unsigned level = 1;
28751 		tree oldlist = TREE_VEC_ELT (ftparms, i);
28752 		tree list = rewrite_tparm_list (oldlist, index, level,
28753 						targs, i, complain);
28754 		TREE_VEC_ELT (gtparms, index) = list;
28755 	      }
28756 	  gtparms = build_tree_list (size_one_node, gtparms);
28757 
28758 	  /* Substitute the deduced arguments plus the rewritten template
28759 	     parameters into f to get g.  This covers the type, copyness,
28760 	     guideness, and explicit-specifier.  */
28761 	  tree g = tsubst_decl (DECL_TEMPLATE_RESULT (f), targs, complain);
28762 	  if (g == error_mark_node)
28763 	    return error_mark_node;
28764 	  DECL_USE_TEMPLATE (g) = 0;
28765 	  fprime = build_template_decl (g, gtparms, false);
28766 	  DECL_TEMPLATE_RESULT (fprime) = g;
28767 	  TREE_TYPE (fprime) = TREE_TYPE (g);
28768 	  tree gtargs = template_parms_to_args (gtparms);
28769 	  DECL_TEMPLATE_INFO (g) = build_template_info (fprime, gtargs);
28770 	  DECL_PRIMARY_TEMPLATE (fprime) = fprime;
28771 
28772 	  /* Substitute the associated constraints.  */
28773 	  tree ci = get_constraints (f);
28774 	  if (ci)
28775 	    ci = tsubst_constraint_info (ci, targs, complain, in_decl);
28776 	  if (ci == error_mark_node)
28777 	    return error_mark_node;
28778 
28779 	  /* Add a constraint that the return type matches the instantiation of
28780 	     A with the same template arguments.  */
28781 	  ret = TREE_TYPE (TREE_TYPE (fprime));
28782 	  if (!same_type_p (atype, ret)
28783 	      /* FIXME this should mean they don't compare as equivalent.  */
28784 	      || dependent_alias_template_spec_p (atype, nt_opaque))
28785 	    {
28786 	      tree same = finish_trait_expr (loc, CPTK_IS_SAME_AS, atype, ret);
28787 	      ci = append_constraint (ci, same);
28788 	    }
28789 
28790 	  if (ci)
28791 	    set_constraints (fprime, ci);
28792 	}
28793       else
28794 	{
28795 	  /* For a non-template deduction guide, if the arguments of A aren't
28796 	     deducible from the return type, don't add the candidate.  */
28797 	  tree targs = make_tree_vec (natparms);
28798 	  int err = unify (atparms, targs, utype, ret, UNIFY_ALLOW_NONE, false);
28799 	  for (unsigned i = 0; !err && i < natparms; ++i)
28800 	    if (TREE_VEC_ELT (targs, i) == NULL_TREE)
28801 	      err = true;
28802 	  if (err)
28803 	    continue;
28804 	}
28805 
28806       aguides = lookup_add (fprime, aguides);
28807     }
28808 
28809   return aguides;
28810 }
28811 
28812 /* Return artificial deduction guides built from the constructors of class
28813    template TMPL.  */
28814 
28815 static tree
ctor_deduction_guides_for(tree tmpl,tsubst_flags_t complain)28816 ctor_deduction_guides_for (tree tmpl, tsubst_flags_t complain)
28817 {
28818   tree type = TREE_TYPE (tmpl);
28819   tree outer_args = NULL_TREE;
28820   if (DECL_CLASS_SCOPE_P (tmpl)
28821       && CLASSTYPE_TEMPLATE_INSTANTIATION (DECL_CONTEXT (tmpl)))
28822     {
28823       outer_args = CLASSTYPE_TI_ARGS (DECL_CONTEXT (tmpl));
28824       type = TREE_TYPE (most_general_template (tmpl));
28825     }
28826 
28827   tree cands = NULL_TREE;
28828 
28829   for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (type)); iter; ++iter)
28830     {
28831       /* Skip inherited constructors.  */
28832       if (iter.using_p ())
28833 	continue;
28834 
28835       tree guide = build_deduction_guide (type, *iter, outer_args, complain);
28836       cands = lookup_add (guide, cands);
28837     }
28838 
28839   /* Add implicit default constructor deduction guide.  */
28840   if (!TYPE_HAS_USER_CONSTRUCTOR (type))
28841     {
28842       tree guide = build_deduction_guide (type, type, outer_args,
28843 					  complain);
28844       cands = lookup_add (guide, cands);
28845     }
28846 
28847   /* Add copy guide.  */
28848   {
28849     tree gtype = build_reference_type (type);
28850     tree guide = build_deduction_guide (type, gtype, outer_args,
28851 					complain);
28852     cands = lookup_add (guide, cands);
28853   }
28854 
28855   return cands;
28856 }
28857 
28858 static GTY((deletable)) hash_map<tree, tree_pair_p> *dguide_cache;
28859 
28860 /* Return the non-aggregate deduction guides for deducible template TMPL.  The
28861    aggregate candidate is added separately because it depends on the
28862    initializer.  Set ANY_DGUIDES_P if we find a non-implicit deduction
28863    guide.  */
28864 
28865 static tree
deduction_guides_for(tree tmpl,bool & any_dguides_p,tsubst_flags_t complain)28866 deduction_guides_for (tree tmpl, bool &any_dguides_p, tsubst_flags_t complain)
28867 {
28868   tree guides = NULL_TREE;
28869   if (DECL_ALIAS_TEMPLATE_P (tmpl))
28870     {
28871       tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
28872       tree tinfo = get_template_info (under);
28873       guides = deduction_guides_for (TI_TEMPLATE (tinfo), any_dguides_p,
28874 				     complain);
28875     }
28876   else
28877     {
28878       guides = lookup_qualified_name (CP_DECL_CONTEXT (tmpl),
28879 				      dguide_name (tmpl),
28880 				      /*type*/false, /*complain*/false,
28881 				      /*hidden*/false);
28882       if (guides == error_mark_node)
28883 	guides = NULL_TREE;
28884       else
28885 	any_dguides_p = true;
28886     }
28887 
28888   /* Cache the deduction guides for a template.  We also remember the result of
28889      lookup, and rebuild everything if it changes; should be very rare.  */
28890   tree_pair_p cache = NULL;
28891   if (tree_pair_p &r
28892       = hash_map_safe_get_or_insert<hm_ggc> (dguide_cache, tmpl))
28893     {
28894       cache = r;
28895       if (cache->purpose == guides)
28896 	return cache->value;
28897     }
28898   else
28899     {
28900       r = cache = ggc_cleared_alloc<tree_pair_s> ();
28901       cache->purpose = guides;
28902     }
28903 
28904   tree cands = NULL_TREE;
28905   if (DECL_ALIAS_TEMPLATE_P (tmpl))
28906     cands = alias_ctad_tweaks (tmpl, guides);
28907   else
28908     {
28909       cands = ctor_deduction_guides_for (tmpl, complain);
28910       for (ovl_iterator it (guides); it; ++it)
28911 	cands = lookup_add (*it, cands);
28912     }
28913 
28914   cache->value = cands;
28915   return cands;
28916 }
28917 
28918 /* Return whether TMPL is a (class template argument-) deducible template.  */
28919 
28920 bool
ctad_template_p(tree tmpl)28921 ctad_template_p (tree tmpl)
28922 {
28923   /* A deducible template is either a class template or is an alias template
28924      whose defining-type-id is of the form
28925 
28926       typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
28927 
28928      where the nested-name-specifier (if any) is non-dependent and the
28929      template-name of the simple-template-id names a deducible template.  */
28930 
28931   if (DECL_CLASS_TEMPLATE_P (tmpl)
28932       || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
28933     return true;
28934   if (!DECL_ALIAS_TEMPLATE_P (tmpl))
28935     return false;
28936   tree orig = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
28937   if (tree tinfo = get_template_info (orig))
28938     return ctad_template_p (TI_TEMPLATE (tinfo));
28939   return false;
28940 }
28941 
28942 /* Deduce template arguments for the class template placeholder PTYPE for
28943    template TMPL based on the initializer INIT, and return the resulting
28944    type.  */
28945 
28946 static tree
do_class_deduction(tree ptype,tree tmpl,tree init,int flags,tsubst_flags_t complain)28947 do_class_deduction (tree ptype, tree tmpl, tree init,
28948 		    int flags, tsubst_flags_t complain)
28949 {
28950   /* We should have handled this in the caller.  */
28951   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
28952     return ptype;
28953 
28954   /* Initializing one placeholder from another.  */
28955   if (init && TREE_CODE (init) == TEMPLATE_PARM_INDEX
28956       && is_auto (TREE_TYPE (init))
28957       && CLASS_PLACEHOLDER_TEMPLATE (TREE_TYPE (init)) == tmpl)
28958     return cp_build_qualified_type (TREE_TYPE (init), cp_type_quals (ptype));
28959 
28960   /* Look through alias templates that just rename another template.  */
28961   tmpl = get_underlying_template (tmpl);
28962   if (!ctad_template_p (tmpl))
28963     {
28964       if (complain & tf_error)
28965 	error ("non-deducible template %qT used without template arguments", tmpl);
28966       return error_mark_node;
28967     }
28968   else if (cxx_dialect < cxx2a && DECL_ALIAS_TEMPLATE_P (tmpl))
28969     {
28970       /* This doesn't affect conforming C++17 code, so just pedwarn.  */
28971       if (complain & tf_warning_or_error)
28972 	pedwarn (input_location, 0, "alias template deduction only available "
28973 		 "with %<-std=c++2a%> or %<-std=gnu++2a%>");
28974     }
28975 
28976   tree type = TREE_TYPE (tmpl);
28977 
28978   bool try_list_ctor = false;
28979 
28980   releasing_vec rv_args = NULL;
28981   vec<tree,va_gc> *&args = *&rv_args;
28982   if (init == NULL_TREE)
28983     args = make_tree_vector ();
28984   else if (BRACE_ENCLOSED_INITIALIZER_P (init))
28985     {
28986       try_list_ctor = TYPE_HAS_LIST_CTOR (type);
28987       if (try_list_ctor && CONSTRUCTOR_NELTS (init) == 1)
28988 	{
28989 	  /* As an exception, the first phase in 16.3.1.7 (considering the
28990 	     initializer list as a single argument) is omitted if the
28991 	     initializer list consists of a single expression of type cv U,
28992 	     where U is a specialization of C or a class derived from a
28993 	     specialization of C.  */
28994 	  tree elt = CONSTRUCTOR_ELT (init, 0)->value;
28995 	  if (is_spec_or_derived (TREE_TYPE (elt), tmpl))
28996 	    try_list_ctor = false;
28997 	}
28998       if (try_list_ctor || is_std_init_list (type))
28999 	args = make_tree_vector_single (init);
29000       else
29001 	args = make_tree_vector_from_ctor (init);
29002     }
29003   else if (TREE_CODE (init) == TREE_LIST)
29004     args = make_tree_vector_from_list (init);
29005   else
29006     args = make_tree_vector_single (init);
29007 
29008   /* Do this now to avoid problems with erroneous args later on.  */
29009   args = resolve_args (args, complain);
29010   if (args == NULL)
29011     return error_mark_node;
29012 
29013   bool any_dguides_p = false;
29014   tree cands = deduction_guides_for (tmpl, any_dguides_p, complain);
29015   if (cands == error_mark_node)
29016     return error_mark_node;
29017 
29018   /* Prune explicit deduction guides in copy-initialization context.  */
29019   bool elided = false;
29020   if (flags & LOOKUP_ONLYCONVERTING)
29021     {
29022       for (lkp_iterator iter (cands); !elided && iter; ++iter)
29023 	if (DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
29024 	  elided = true;
29025 
29026       if (elided)
29027 	{
29028 	  /* Found a nonconverting guide, prune the candidates.  */
29029 	  tree pruned = NULL_TREE;
29030 	  for (lkp_iterator iter (cands); iter; ++iter)
29031 	    if (!DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
29032 	      pruned = lookup_add (*iter, pruned);
29033 
29034 	  cands = pruned;
29035 	}
29036     }
29037 
29038   if (!any_dguides_p)
29039     if (tree guide = maybe_aggr_guide (tmpl, init, args))
29040       cands = lookup_add (guide, cands);
29041 
29042   tree call = error_mark_node;
29043 
29044   /* If this is list-initialization and the class has a list constructor, first
29045      try deducing from the list as a single argument, as [over.match.list].  */
29046   tree list_cands = NULL_TREE;
29047   if (try_list_ctor && cands)
29048     for (lkp_iterator iter (cands); iter; ++iter)
29049       {
29050 	tree dg = *iter;
29051 	if (is_list_ctor (dg))
29052 	  list_cands = lookup_add (dg, list_cands);
29053       }
29054   if (list_cands)
29055     {
29056       ++cp_unevaluated_operand;
29057       call = build_new_function_call (list_cands, &args, tf_decltype);
29058       --cp_unevaluated_operand;
29059 
29060       if (call == error_mark_node)
29061 	{
29062 	  /* That didn't work, now try treating the list as a sequence of
29063 	     arguments.  */
29064 	  release_tree_vector (args);
29065 	  args = make_tree_vector_from_ctor (init);
29066 	}
29067     }
29068 
29069   if (elided && !cands)
29070     {
29071       error ("cannot deduce template arguments for copy-initialization"
29072 	     " of %qT, as it has no non-explicit deduction guides or "
29073 	     "user-declared constructors", type);
29074       return error_mark_node;
29075     }
29076   else if (!cands && call == error_mark_node)
29077     {
29078       error ("cannot deduce template arguments of %qT, as it has no viable "
29079 	     "deduction guides", type);
29080       return error_mark_node;
29081     }
29082 
29083   if (call == error_mark_node)
29084     {
29085       ++cp_unevaluated_operand;
29086       call = build_new_function_call (cands, &args, tf_decltype);
29087       --cp_unevaluated_operand;
29088     }
29089 
29090   if (call == error_mark_node
29091       && (complain & tf_warning_or_error))
29092     {
29093       error ("class template argument deduction failed:");
29094 
29095       ++cp_unevaluated_operand;
29096       call = build_new_function_call (cands, &args, complain | tf_decltype);
29097       --cp_unevaluated_operand;
29098 
29099       if (elided)
29100 	inform (input_location, "explicit deduction guides not considered "
29101 		"for copy-initialization");
29102     }
29103 
29104   return cp_build_qualified_type (TREE_TYPE (call), cp_type_quals (ptype));
29105 }
29106 
29107 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
29108    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
29109    The CONTEXT determines the context in which auto deduction is performed
29110    and is used to control error diagnostics.  FLAGS are the LOOKUP_* flags.
29111    OUTER_TARGS are used during template argument deduction
29112    (context == adc_unify) to properly substitute the result, and is ignored
29113    in other contexts.
29114 
29115    For partial-concept-ids, extra args may be appended to the list of deduced
29116    template arguments prior to determining constraint satisfaction.  */
29117 
29118 tree
do_auto_deduction(tree type,tree init,tree auto_node,tsubst_flags_t complain,auto_deduction_context context,tree outer_targs,int flags)29119 do_auto_deduction (tree type, tree init, tree auto_node,
29120                    tsubst_flags_t complain, auto_deduction_context context,
29121 		   tree outer_targs, int flags)
29122 {
29123   tree targs;
29124 
29125   if (init == error_mark_node)
29126     return error_mark_node;
29127 
29128   if (init && type_dependent_expression_p (init)
29129       && context != adc_unify)
29130     /* Defining a subset of type-dependent expressions that we can deduce
29131        from ahead of time isn't worth the trouble.  */
29132     return type;
29133 
29134   /* Similarly, we can't deduce from another undeduced decl.  */
29135   if (init && undeduced_auto_decl (init))
29136     return type;
29137 
29138   /* We may be doing a partial substitution, but we still want to replace
29139      auto_node.  */
29140   complain &= ~tf_partial;
29141 
29142   if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
29143     /* C++17 class template argument deduction.  */
29144     return do_class_deduction (type, tmpl, init, flags, complain);
29145 
29146   if (init == NULL_TREE || TREE_TYPE (init) == NULL_TREE)
29147     /* Nothing we can do with this, even in deduction context.  */
29148     return type;
29149 
29150   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
29151      with either a new invented type template parameter U or, if the
29152      initializer is a braced-init-list (8.5.4), with
29153      std::initializer_list<U>.  */
29154   if (BRACE_ENCLOSED_INITIALIZER_P (init))
29155     {
29156       if (!DIRECT_LIST_INIT_P (init))
29157 	type = listify_autos (type, auto_node);
29158       else if (CONSTRUCTOR_NELTS (init) == 1)
29159 	init = CONSTRUCTOR_ELT (init, 0)->value;
29160       else
29161 	{
29162           if (complain & tf_warning_or_error)
29163             {
29164 	      if (permerror (input_location, "direct-list-initialization of "
29165 			     "%<auto%> requires exactly one element"))
29166 	        inform (input_location,
29167 		        "for deduction to %<std::initializer_list%>, use copy-"
29168 		        "list-initialization (i.e. add %<=%> before the %<{%>)");
29169             }
29170 	  type = listify_autos (type, auto_node);
29171 	}
29172     }
29173 
29174   if (type == error_mark_node)
29175     return error_mark_node;
29176 
29177   init = resolve_nondeduced_context (init, complain);
29178 
29179   if (context == adc_decomp_type
29180       && auto_node == type
29181       && init != error_mark_node
29182       && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
29183     /* [dcl.decomp]/1 - if decomposition declaration has no ref-qualifiers
29184        and initializer has array type, deduce cv-qualified array type.  */
29185     return cp_build_qualified_type_real (TREE_TYPE (init), TYPE_QUALS (type),
29186 					 complain);
29187   else if (AUTO_IS_DECLTYPE (auto_node))
29188     {
29189       tree stripped_init = tree_strip_any_location_wrapper (init);
29190       bool id = (DECL_P (stripped_init)
29191 		 || ((TREE_CODE (init) == COMPONENT_REF
29192 		      || TREE_CODE (init) == SCOPE_REF)
29193 		     && !REF_PARENTHESIZED_P (init)));
29194       targs = make_tree_vec (1);
29195       TREE_VEC_ELT (targs, 0)
29196 	= finish_decltype_type (init, id, tf_warning_or_error);
29197       if (type != auto_node)
29198 	{
29199           if (complain & tf_error)
29200 	    error ("%qT as type rather than plain %<decltype(auto)%>", type);
29201 	  return error_mark_node;
29202 	}
29203     }
29204   else
29205     {
29206       if (error_operand_p (init))
29207 	return error_mark_node;
29208 
29209       tree parms = build_tree_list (NULL_TREE, type);
29210       tree tparms;
29211 
29212       if (flag_concepts)
29213 	tparms = extract_autos (type);
29214       else
29215 	{
29216 	  tparms = make_tree_vec (1);
29217 	  TREE_VEC_ELT (tparms, 0)
29218 	    = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
29219 	}
29220 
29221       targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
29222       int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
29223 				       DEDUCE_CALL,
29224 				       NULL, /*explain_p=*/false);
29225       if (val > 0)
29226 	{
29227 	  if (processing_template_decl)
29228 	    /* Try again at instantiation time.  */
29229 	    return type;
29230 	  if (type && type != error_mark_node
29231 	      && (complain & tf_error))
29232 	    /* If type is error_mark_node a diagnostic must have been
29233 	       emitted by now.  Also, having a mention to '<type error>'
29234 	       in the diagnostic is not really useful to the user.  */
29235 	    {
29236 	      if (cfun
29237 		  && FNDECL_USED_AUTO (current_function_decl)
29238 		  && (auto_node
29239 		      == DECL_SAVED_AUTO_RETURN_TYPE (current_function_decl))
29240 		  && LAMBDA_FUNCTION_P (current_function_decl))
29241 		error ("unable to deduce lambda return type from %qE", init);
29242 	      else
29243 		error ("unable to deduce %qT from %qE", type, init);
29244 	      type_unification_real (tparms, targs, parms, &init, 1, 0,
29245 				     DEDUCE_CALL,
29246 				     NULL, /*explain_p=*/true);
29247 	    }
29248 	  return error_mark_node;
29249 	}
29250     }
29251 
29252   /* Check any placeholder constraints against the deduced type. */
29253   if (flag_concepts && !processing_template_decl)
29254     if (tree check = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (auto_node)))
29255       {
29256         /* Use the deduced type to check the associated constraints. If we
29257            have a partial-concept-id, rebuild the argument list so that
29258            we check using the extra arguments. */
29259 	check = unpack_concept_check (check);
29260 	gcc_assert (TREE_CODE (check) == TEMPLATE_ID_EXPR);
29261 	tree cdecl = TREE_OPERAND (check, 0);
29262 	if (OVL_P (cdecl))
29263 	  cdecl = OVL_FIRST (cdecl);
29264         tree cargs = TREE_OPERAND (check, 1);
29265         if (TREE_VEC_LENGTH (cargs) > 1)
29266           {
29267             cargs = copy_node (cargs);
29268             TREE_VEC_ELT (cargs, 0) = TREE_VEC_ELT (targs, 0);
29269           }
29270         else
29271           cargs = targs;
29272 
29273 	/* Rebuild the check using the deduced arguments.  */
29274 	check = build_concept_check (cdecl, cargs, tf_none);
29275 
29276 	if (!constraints_satisfied_p (check))
29277           {
29278             if (complain & tf_warning_or_error)
29279               {
29280 		auto_diagnostic_group d;
29281                 switch (context)
29282                   {
29283                   case adc_unspecified:
29284 		  case adc_unify:
29285                     error("placeholder constraints not satisfied");
29286                     break;
29287                   case adc_variable_type:
29288 		  case adc_decomp_type:
29289                     error ("deduced initializer does not satisfy "
29290                            "placeholder constraints");
29291                     break;
29292                   case adc_return_type:
29293                     error ("deduced return type does not satisfy "
29294                            "placeholder constraints");
29295                     break;
29296                   case adc_requirement:
29297 		    error ("deduced expression type does not satisfy "
29298                            "placeholder constraints");
29299                     break;
29300                   }
29301 		diagnose_constraints (input_location, check, targs);
29302               }
29303             return error_mark_node;
29304           }
29305       }
29306 
29307   if (processing_template_decl && context != adc_unify)
29308     outer_targs = current_template_args ();
29309   targs = add_to_template_args (outer_targs, targs);
29310   return tsubst (type, targs, complain, NULL_TREE);
29311 }
29312 
29313 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
29314    result.  */
29315 
29316 tree
splice_late_return_type(tree type,tree late_return_type)29317 splice_late_return_type (tree type, tree late_return_type)
29318 {
29319   if (late_return_type)
29320     {
29321       gcc_assert (is_auto (type) || seen_error ());
29322       return late_return_type;
29323     }
29324 
29325   if (tree auto_node = find_type_usage (type, is_auto))
29326     if (TEMPLATE_TYPE_LEVEL (auto_node) <= processing_template_decl)
29327       {
29328 	/* In an abbreviated function template we didn't know we were dealing
29329 	   with a function template when we saw the auto return type, so rebuild
29330 	   the return type using an auto with the correct level.  */
29331 	tree new_auto = make_auto_1 (TYPE_IDENTIFIER (auto_node), false);
29332 	tree auto_vec = make_tree_vec (1);
29333 	TREE_VEC_ELT (auto_vec, 0) = new_auto;
29334 	tree targs = add_outermost_template_args (current_template_args (),
29335 						  auto_vec);
29336 	/* FIXME: We should also rebuild the constraint to refer to the new
29337 	   auto.  */
29338 	PLACEHOLDER_TYPE_CONSTRAINTS (new_auto)
29339 	  = PLACEHOLDER_TYPE_CONSTRAINTS (auto_node);
29340 	TYPE_CANONICAL (new_auto) = canonical_type_parameter (new_auto);
29341 	return tsubst (type, targs, tf_none, NULL_TREE);
29342       }
29343   return type;
29344 }
29345 
29346 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
29347    'decltype(auto)' or a deduced class template.  */
29348 
29349 bool
is_auto(const_tree type)29350 is_auto (const_tree type)
29351 {
29352   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
29353       && (TYPE_IDENTIFIER (type) == auto_identifier
29354 	  || TYPE_IDENTIFIER (type) == decltype_auto_identifier))
29355     return true;
29356   else
29357     return false;
29358 }
29359 
29360 /* for_each_template_parm callback for type_uses_auto.  */
29361 
29362 int
is_auto_r(tree tp,void *)29363 is_auto_r (tree tp, void */*data*/)
29364 {
29365   return is_auto (tp);
29366 }
29367 
29368 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
29369    a use of `auto'.  Returns NULL_TREE otherwise.  */
29370 
29371 tree
type_uses_auto(tree type)29372 type_uses_auto (tree type)
29373 {
29374   if (type == NULL_TREE)
29375     return NULL_TREE;
29376   else if (flag_concepts)
29377     {
29378       /* The Concepts TS allows multiple autos in one type-specifier; just
29379 	 return the first one we find, do_auto_deduction will collect all of
29380 	 them.  */
29381       if (uses_template_parms (type))
29382 	return for_each_template_parm (type, is_auto_r, /*data*/NULL,
29383 				       /*visited*/NULL, /*nondeduced*/false);
29384       else
29385 	return NULL_TREE;
29386     }
29387   else
29388     return find_type_usage (type, is_auto);
29389 }
29390 
29391 /* Report ill-formed occurrences of auto types in ARGUMENTS.  If
29392    concepts are enabled, auto is acceptable in template arguments, but
29393    only when TEMPL identifies a template class.  Return TRUE if any
29394    such errors were reported.  */
29395 
29396 bool
check_auto_in_tmpl_args(tree tmpl,tree args)29397 check_auto_in_tmpl_args (tree tmpl, tree args)
29398 {
29399   /* If there were previous errors, nevermind.  */
29400   if (!args || TREE_CODE (args) != TREE_VEC)
29401     return false;
29402 
29403   /* If TMPL is an identifier, we're parsing and we can't tell yet
29404      whether TMPL is supposed to be a type, a function or a variable.
29405      We'll only be able to tell during template substitution, so we
29406      expect to be called again then.  If concepts are enabled and we
29407      know we have a type, we're ok.  */
29408   if (flag_concepts
29409       && (identifier_p (tmpl)
29410 	  || (DECL_P (tmpl)
29411 	      &&  (DECL_TYPE_TEMPLATE_P (tmpl)
29412 		   || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)))))
29413     return false;
29414 
29415   /* Quickly search for any occurrences of auto; usually there won't
29416      be any, and then we'll avoid allocating the vector.  */
29417   if (!type_uses_auto (args))
29418     return false;
29419 
29420   bool errors = false;
29421 
29422   tree vec = extract_autos (args);
29423   for (int i = 0; i < TREE_VEC_LENGTH (vec); i++)
29424     {
29425       tree xauto = TREE_VALUE (TREE_VEC_ELT (vec, i));
29426       error_at (DECL_SOURCE_LOCATION (xauto),
29427 		"invalid use of %qT in template argument", xauto);
29428       errors = true;
29429     }
29430 
29431   return errors;
29432 }
29433 
29434 /* For a given template T, return the vector of typedefs referenced
29435    in T for which access check is needed at T instantiation time.
29436    T is either  a FUNCTION_DECL or a RECORD_TYPE.
29437    Those typedefs were added to T by the function
29438    append_type_to_template_for_access_check.  */
29439 
29440 vec<qualified_typedef_usage_t, va_gc> *
get_types_needing_access_check(tree t)29441 get_types_needing_access_check (tree t)
29442 {
29443   tree ti;
29444   vec<qualified_typedef_usage_t, va_gc> *result = NULL;
29445 
29446   if (!t || t == error_mark_node)
29447     return NULL;
29448 
29449   if (!(ti = get_template_info (t)))
29450     return NULL;
29451 
29452   if (CLASS_TYPE_P (t)
29453       || TREE_CODE (t) == FUNCTION_DECL)
29454     {
29455       if (!TI_TEMPLATE (ti))
29456 	return NULL;
29457 
29458       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
29459     }
29460 
29461   return result;
29462 }
29463 
29464 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
29465    tied to T. That list of typedefs will be access checked at
29466    T instantiation time.
29467    T is either a FUNCTION_DECL or a RECORD_TYPE.
29468    TYPE_DECL is a TYPE_DECL node representing a typedef.
29469    SCOPE is the scope through which TYPE_DECL is accessed.
29470    LOCATION is the location of the usage point of TYPE_DECL.
29471 
29472    This function is a subroutine of
29473    append_type_to_template_for_access_check.  */
29474 
29475 static void
append_type_to_template_for_access_check_1(tree t,tree type_decl,tree scope,location_t location)29476 append_type_to_template_for_access_check_1 (tree t,
29477 					    tree type_decl,
29478 					    tree scope,
29479 					    location_t location)
29480 {
29481   qualified_typedef_usage_t typedef_usage;
29482   tree ti;
29483 
29484   if (!t || t == error_mark_node)
29485     return;
29486 
29487   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
29488 	       || CLASS_TYPE_P (t))
29489 	      && type_decl
29490 	      && TREE_CODE (type_decl) == TYPE_DECL
29491 	      && scope);
29492 
29493   if (!(ti = get_template_info (t)))
29494     return;
29495 
29496   gcc_assert (TI_TEMPLATE (ti));
29497 
29498   typedef_usage.typedef_decl = type_decl;
29499   typedef_usage.context = scope;
29500   typedef_usage.locus = location;
29501 
29502   vec_safe_push (TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti), typedef_usage);
29503 }
29504 
29505 /* Append TYPE_DECL to the template TEMPL.
29506    TEMPL is either a class type, a FUNCTION_DECL or a TEMPLATE_DECL.
29507    At TEMPL instanciation time, TYPE_DECL will be checked to see
29508    if it can be accessed through SCOPE.
29509    LOCATION is the location of the usage point of TYPE_DECL.
29510 
29511    e.g. consider the following code snippet:
29512 
29513      class C
29514      {
29515        typedef int myint;
29516      };
29517 
29518      template<class U> struct S
29519      {
29520        C::myint mi; // <-- usage point of the typedef C::myint
29521      };
29522 
29523      S<char> s;
29524 
29525    At S<char> instantiation time, we need to check the access of C::myint
29526    In other words, we need to check the access of the myint typedef through
29527    the C scope. For that purpose, this function will add the myint typedef
29528    and the scope C through which its being accessed to a list of typedefs
29529    tied to the template S. That list will be walked at template instantiation
29530    time and access check performed on each typedefs it contains.
29531    Note that this particular code snippet should yield an error because
29532    myint is private to C.  */
29533 
29534 void
append_type_to_template_for_access_check(tree templ,tree type_decl,tree scope,location_t location)29535 append_type_to_template_for_access_check (tree templ,
29536                                           tree type_decl,
29537 					  tree scope,
29538 					  location_t location)
29539 {
29540   qualified_typedef_usage_t *iter;
29541   unsigned i;
29542 
29543   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
29544 
29545   /* Make sure we don't append the type to the template twice.  */
29546   FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (templ), i, iter)
29547     if (iter->typedef_decl == type_decl && scope == iter->context)
29548       return;
29549 
29550   append_type_to_template_for_access_check_1 (templ, type_decl,
29551 					      scope, location);
29552 }
29553 
29554 /* Recursively walk over && expressions searching for EXPR. Return a reference
29555    to that expression.  */
29556 
find_template_requirement(tree * t,tree key)29557 static tree *find_template_requirement (tree *t, tree key)
29558 {
29559   if (*t == key)
29560     return t;
29561   if (TREE_CODE (*t) == TRUTH_ANDIF_EXPR)
29562     {
29563       if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 0), key))
29564 	return p;
29565       if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 1), key))
29566 	return p;
29567     }
29568   return 0;
29569 }
29570 
29571 /* Convert the generic type parameters in PARM that match the types given in the
29572    range [START_IDX, END_IDX) from the current_template_parms into generic type
29573    packs.  */
29574 
29575 tree
convert_generic_types_to_packs(tree parm,int start_idx,int end_idx)29576 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
29577 {
29578   tree current = current_template_parms;
29579   int depth = TMPL_PARMS_DEPTH (current);
29580   current = INNERMOST_TEMPLATE_PARMS (current);
29581   tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
29582 
29583   for (int i = 0; i < start_idx; ++i)
29584     TREE_VEC_ELT (replacement, i)
29585       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
29586 
29587   for (int i = start_idx; i < end_idx; ++i)
29588     {
29589       /* Create a distinct parameter pack type from the current parm and add it
29590 	 to the replacement args to tsubst below into the generic function
29591 	 parameter.  */
29592       tree node = TREE_VEC_ELT (current, i);
29593       tree o = TREE_TYPE (TREE_VALUE (node));
29594       tree t = copy_type (o);
29595       TEMPLATE_TYPE_PARM_INDEX (t)
29596 	= reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
29597 				      t, 0, 0, tf_none);
29598       TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
29599       TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
29600       TYPE_MAIN_VARIANT (t) = t;
29601       TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
29602       TYPE_CANONICAL (t) = canonical_type_parameter (t);
29603       TREE_VEC_ELT (replacement, i) = t;
29604 
29605       /* Replace the current template parameter with new pack.  */
29606       TREE_VALUE (node) = TREE_CHAIN (t);
29607 
29608       /* Surgically adjust the associated constraint of adjusted parameter
29609          and it's corresponding contribution to the current template
29610          requirements.  */
29611       if (tree constr = TEMPLATE_PARM_CONSTRAINTS (node))
29612 	{
29613 	  tree id = unpack_concept_check (constr);
29614 	  TREE_VEC_ELT (TREE_OPERAND (id, 1), 0) = t;
29615 	  tree fold = finish_left_unary_fold_expr (constr, TRUTH_ANDIF_EXPR);
29616 	  TEMPLATE_PARM_CONSTRAINTS (node) = fold;
29617 
29618 	  /* If there was a constraint, we also need to replace that in
29619 	     the template requirements, which we've already built.  */
29620 	  tree *reqs = &TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
29621 	  reqs = find_template_requirement (reqs, constr);
29622 	  *reqs = fold;
29623 	}
29624     }
29625 
29626   for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
29627     TREE_VEC_ELT (replacement, i)
29628       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
29629 
29630   /* If there are more levels then build up the replacement with the outer
29631      template parms.  */
29632   if (depth > 1)
29633     replacement = add_to_template_args (template_parms_to_args
29634 					(TREE_CHAIN (current_template_parms)),
29635 					replacement);
29636 
29637   return tsubst (parm, replacement, tf_none, NULL_TREE);
29638 }
29639 
29640 /* __integer_pack(N) in a pack expansion expands to a sequence of numbers from
29641    0..N-1.  */
29642 
29643 void
declare_integer_pack(void)29644 declare_integer_pack (void)
29645 {
29646   tree ipfn = push_library_fn (get_identifier ("__integer_pack"),
29647 			       build_function_type_list (integer_type_node,
29648 							 integer_type_node,
29649 							 NULL_TREE),
29650 			       NULL_TREE, ECF_CONST);
29651   DECL_DECLARED_CONSTEXPR_P (ipfn) = true;
29652   set_decl_built_in_function (ipfn, BUILT_IN_FRONTEND,
29653 			      CP_BUILT_IN_INTEGER_PACK);
29654 }
29655 
29656 /* Set up the hash tables for template instantiations.  */
29657 
29658 void
init_template_processing(void)29659 init_template_processing (void)
29660 {
29661   /* FIXME: enable sanitization (PR87847) */
29662   decl_specializations = hash_table<spec_hasher>::create_ggc (37, false);
29663   type_specializations = hash_table<spec_hasher>::create_ggc (37, false);
29664 
29665   if (cxx_dialect >= cxx11)
29666     declare_integer_pack ();
29667 }
29668 
29669 /* Print stats about the template hash tables for -fstats.  */
29670 
29671 void
print_template_statistics(void)29672 print_template_statistics (void)
29673 {
29674   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
29675 	   "%f collisions\n", (long) decl_specializations->size (),
29676 	   (long) decl_specializations->elements (),
29677 	   decl_specializations->collisions ());
29678   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
29679 	   "%f collisions\n", (long) type_specializations->size (),
29680 	   (long) type_specializations->elements (),
29681 	   type_specializations->collisions ());
29682 }
29683 
29684 #if CHECKING_P
29685 
29686 namespace selftest {
29687 
29688 /* Verify that build_non_dependent_expr () works, for various expressions,
29689    and that location wrappers don't affect the results.  */
29690 
29691 static void
test_build_non_dependent_expr()29692 test_build_non_dependent_expr ()
29693 {
29694   location_t loc = BUILTINS_LOCATION;
29695 
29696   /* Verify constants, without and with location wrappers.  */
29697   tree int_cst = build_int_cst (integer_type_node, 42);
29698   ASSERT_EQ (int_cst, build_non_dependent_expr (int_cst));
29699 
29700   tree wrapped_int_cst = maybe_wrap_with_location (int_cst, loc);
29701   ASSERT_TRUE (location_wrapper_p (wrapped_int_cst));
29702   ASSERT_EQ (wrapped_int_cst, build_non_dependent_expr (wrapped_int_cst));
29703 
29704   tree string_lit = build_string (4, "foo");
29705   TREE_TYPE (string_lit) = char_array_type_node;
29706   string_lit = fix_string_type (string_lit);
29707   ASSERT_EQ (string_lit, build_non_dependent_expr (string_lit));
29708 
29709   tree wrapped_string_lit = maybe_wrap_with_location (string_lit, loc);
29710   ASSERT_TRUE (location_wrapper_p (wrapped_string_lit));
29711   ASSERT_EQ (wrapped_string_lit,
29712 	     build_non_dependent_expr (wrapped_string_lit));
29713 }
29714 
29715 /* Verify that type_dependent_expression_p () works correctly, even
29716    in the presence of location wrapper nodes.  */
29717 
29718 static void
test_type_dependent_expression_p()29719 test_type_dependent_expression_p ()
29720 {
29721   location_t loc = BUILTINS_LOCATION;
29722 
29723   tree name = get_identifier ("foo");
29724 
29725   /* If no templates are involved, nothing is type-dependent.  */
29726   gcc_assert (!processing_template_decl);
29727   ASSERT_FALSE (type_dependent_expression_p (name));
29728 
29729   ++processing_template_decl;
29730 
29731   /* Within a template, an unresolved name is always type-dependent.  */
29732   ASSERT_TRUE (type_dependent_expression_p (name));
29733 
29734   /* Ensure it copes with NULL_TREE and errors.  */
29735   ASSERT_FALSE (type_dependent_expression_p (NULL_TREE));
29736   ASSERT_FALSE (type_dependent_expression_p (error_mark_node));
29737 
29738   /* A USING_DECL in a template should be type-dependent, even if wrapped
29739      with a location wrapper (PR c++/83799).  */
29740   tree using_decl = build_lang_decl (USING_DECL, name, NULL_TREE);
29741   TREE_TYPE (using_decl) = integer_type_node;
29742   ASSERT_TRUE (type_dependent_expression_p (using_decl));
29743   tree wrapped_using_decl = maybe_wrap_with_location (using_decl, loc);
29744   ASSERT_TRUE (location_wrapper_p (wrapped_using_decl));
29745   ASSERT_TRUE (type_dependent_expression_p (wrapped_using_decl));
29746 
29747   --processing_template_decl;
29748 }
29749 
29750 /* Run all of the selftests within this file.  */
29751 
29752 void
cp_pt_c_tests()29753 cp_pt_c_tests ()
29754 {
29755   test_build_non_dependent_expr ();
29756   test_type_dependent_expression_p ();
29757 }
29758 
29759 } // namespace selftest
29760 
29761 #endif /* #if CHECKING_P */
29762 
29763 #include "gt-cp-pt.h"
29764