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_ARTIFICIAL (decl) = 1;
4457       SET_DECL_TEMPLATE_PARM_P (decl);
4458 
4459       tree tpi = build_template_parm_index (TEMPLATE_PARM_IDX (index),
4460 					    TEMPLATE_PARM_LEVEL (index) - levels,
4461 					    TEMPLATE_PARM_ORIG_LEVEL (index),
4462 					    decl, type);
4463       TEMPLATE_PARM_DESCENDANTS (index) = tpi;
4464       TEMPLATE_PARM_PARAMETER_PACK (tpi)
4465 	= TEMPLATE_PARM_PARAMETER_PACK (index);
4466 
4467 	/* Template template parameters need this.  */
4468       tree inner = decl;
4469       if (TREE_CODE (decl) == TEMPLATE_DECL)
4470 	{
4471 	  inner = build_decl (DECL_SOURCE_LOCATION (decl),
4472 			      TYPE_DECL, DECL_NAME (decl), type);
4473 	  DECL_TEMPLATE_RESULT (decl) = inner;
4474 	  DECL_ARTIFICIAL (inner) = true;
4475 	  DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
4476 	    (DECL_TEMPLATE_PARMS (orig_decl), args, complain);
4477 	}
4478 
4479       /* Attach the TPI to the decl.  */
4480       if (TREE_CODE (inner) == TYPE_DECL)
4481 	TEMPLATE_TYPE_PARM_INDEX (type) = tpi;
4482       else
4483 	DECL_INITIAL (decl) = tpi;
4484     }
4485 
4486   return TEMPLATE_PARM_DESCENDANTS (index);
4487 }
4488 
4489 /* Process information from new template parameter PARM and append it
4490    to the LIST being built.  This new parameter is a non-type
4491    parameter iff IS_NON_TYPE is true. This new parameter is a
4492    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
4493    is in PARM_LOC.  */
4494 
4495 tree
process_template_parm(tree list,location_t parm_loc,tree parm,bool is_non_type,bool is_parameter_pack)4496 process_template_parm (tree list, location_t parm_loc, tree parm,
4497 		       bool is_non_type, bool is_parameter_pack)
4498 {
4499   tree decl = 0;
4500   int idx = 0;
4501 
4502   gcc_assert (TREE_CODE (parm) == TREE_LIST);
4503   tree defval = TREE_PURPOSE (parm);
4504   tree constr = TREE_TYPE (parm);
4505 
4506   if (list)
4507     {
4508       tree p = tree_last (list);
4509 
4510       if (p && TREE_VALUE (p) != error_mark_node)
4511         {
4512           p = TREE_VALUE (p);
4513           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
4514             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
4515           else
4516             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
4517         }
4518 
4519       ++idx;
4520     }
4521 
4522   if (is_non_type)
4523     {
4524       parm = TREE_VALUE (parm);
4525 
4526       SET_DECL_TEMPLATE_PARM_P (parm);
4527 
4528       if (TREE_TYPE (parm) != error_mark_node)
4529 	{
4530 	  /* [temp.param]
4531 
4532 	     The top-level cv-qualifiers on the template-parameter are
4533 	     ignored when determining its type.  */
4534 	  TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
4535 	  if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
4536 	    TREE_TYPE (parm) = error_mark_node;
4537 	  else if (uses_parameter_packs (TREE_TYPE (parm))
4538 		   && !is_parameter_pack
4539 		   /* If we're in a nested template parameter list, the template
4540 		      template parameter could be a parameter pack.  */
4541 		   && processing_template_parmlist == 1)
4542 	    {
4543 	      /* This template parameter is not a parameter pack, but it
4544 		 should be. Complain about "bare" parameter packs.  */
4545 	      check_for_bare_parameter_packs (TREE_TYPE (parm));
4546 
4547 	      /* Recover by calling this a parameter pack.  */
4548 	      is_parameter_pack = true;
4549 	    }
4550 	}
4551 
4552       /* A template parameter is not modifiable.  */
4553       TREE_CONSTANT (parm) = 1;
4554       TREE_READONLY (parm) = 1;
4555       decl = build_decl (parm_loc,
4556 			 CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
4557       TREE_CONSTANT (decl) = 1;
4558       TREE_READONLY (decl) = 1;
4559       DECL_INITIAL (parm) = DECL_INITIAL (decl)
4560 	= build_template_parm_index (idx, processing_template_decl,
4561 				     processing_template_decl,
4562 				     decl, TREE_TYPE (parm));
4563 
4564       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4565 	= is_parameter_pack;
4566     }
4567   else
4568     {
4569       tree t;
4570       parm = TREE_VALUE (TREE_VALUE (parm));
4571 
4572       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
4573 	{
4574 	  t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
4575 	  /* This is for distinguishing between real templates and template
4576 	     template parameters */
4577 	  TREE_TYPE (parm) = t;
4578 
4579 	  /* any_template_parm_r expects to be able to get the targs of a
4580 	     DECL_TEMPLATE_RESULT.  */
4581 	  tree result = DECL_TEMPLATE_RESULT (parm);
4582 	  TREE_TYPE (result) = t;
4583 	  tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (parm));
4584 	  tree tinfo = build_template_info (parm, args);
4585 	  retrofit_lang_decl (result);
4586 	  DECL_TEMPLATE_INFO (result) = tinfo;
4587 
4588 	  decl = parm;
4589 	}
4590       else
4591 	{
4592 	  t = cxx_make_type (TEMPLATE_TYPE_PARM);
4593 	  /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
4594 	  decl = build_decl (parm_loc,
4595 			     TYPE_DECL, parm, t);
4596 	}
4597 
4598       TYPE_NAME (t) = decl;
4599       TYPE_STUB_DECL (t) = decl;
4600       parm = decl;
4601       TEMPLATE_TYPE_PARM_INDEX (t)
4602 	= build_template_parm_index (idx, processing_template_decl,
4603 				     processing_template_decl,
4604 				     decl, TREE_TYPE (parm));
4605       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
4606       if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
4607 	SET_TYPE_STRUCTURAL_EQUALITY (t);
4608       else
4609 	TYPE_CANONICAL (t) = canonical_type_parameter (t);
4610     }
4611   DECL_ARTIFICIAL (decl) = 1;
4612   SET_DECL_TEMPLATE_PARM_P (decl);
4613 
4614   /* Build requirements for the type/template parameter.
4615      This must be done after SET_DECL_TEMPLATE_PARM_P or
4616      process_template_parm could fail. */
4617   tree reqs = finish_shorthand_constraint (parm, constr);
4618 
4619   decl = pushdecl (decl);
4620   if (!is_non_type)
4621     parm = decl;
4622 
4623   /* Build the parameter node linking the parameter declaration,
4624      its default argument (if any), and its constraints (if any). */
4625   parm = build_tree_list (defval, parm);
4626   TEMPLATE_PARM_CONSTRAINTS (parm) = reqs;
4627 
4628   return chainon (list, parm);
4629 }
4630 
4631 /* The end of a template parameter list has been reached.  Process the
4632    tree list into a parameter vector, converting each parameter into a more
4633    useful form.	 Type parameters are saved as IDENTIFIER_NODEs, and others
4634    as PARM_DECLs.  */
4635 
4636 tree
end_template_parm_list(tree parms)4637 end_template_parm_list (tree parms)
4638 {
4639   int nparms;
4640   tree parm, next;
4641   tree saved_parmlist = make_tree_vec (list_length (parms));
4642 
4643   /* Pop the dummy parameter level and add the real one.  */
4644   current_template_parms = TREE_CHAIN (current_template_parms);
4645 
4646   current_template_parms
4647     = tree_cons (size_int (processing_template_decl),
4648 		 saved_parmlist, current_template_parms);
4649 
4650   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
4651     {
4652       next = TREE_CHAIN (parm);
4653       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
4654       TREE_CHAIN (parm) = NULL_TREE;
4655     }
4656 
4657   --processing_template_parmlist;
4658 
4659   return saved_parmlist;
4660 }
4661 
4662 // Explicitly indicate the end of the template parameter list. We assume
4663 // that the current template parameters have been constructed and/or
4664 // managed explicitly, as when creating new template template parameters
4665 // from a shorthand constraint.
4666 void
end_template_parm_list()4667 end_template_parm_list ()
4668 {
4669   --processing_template_parmlist;
4670 }
4671 
4672 /* end_template_decl is called after a template declaration is seen.  */
4673 
4674 void
end_template_decl(void)4675 end_template_decl (void)
4676 {
4677   reset_specialization ();
4678 
4679   if (! processing_template_decl)
4680     return;
4681 
4682   /* This matches the pushlevel in begin_template_parm_list.  */
4683   finish_scope ();
4684 
4685   --processing_template_decl;
4686   current_template_parms = TREE_CHAIN (current_template_parms);
4687 }
4688 
4689 /* Takes a TREE_LIST representing a template parameter and convert it
4690    into an argument suitable to be passed to the type substitution
4691    functions.  Note that If the TREE_LIST contains an error_mark
4692    node, the returned argument is error_mark_node.  */
4693 
4694 tree
template_parm_to_arg(tree t)4695 template_parm_to_arg (tree t)
4696 {
4697 
4698   if (t == NULL_TREE
4699       || TREE_CODE (t) != TREE_LIST)
4700     return t;
4701 
4702   if (error_operand_p (TREE_VALUE (t)))
4703     return error_mark_node;
4704 
4705   t = TREE_VALUE (t);
4706 
4707   if (TREE_CODE (t) == TYPE_DECL
4708       || TREE_CODE (t) == TEMPLATE_DECL)
4709     {
4710       t = TREE_TYPE (t);
4711 
4712       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
4713 	{
4714 	  /* Turn this argument into a TYPE_ARGUMENT_PACK
4715 	     with a single element, which expands T.  */
4716 	  tree vec = make_tree_vec (1);
4717 	  if (CHECKING_P)
4718 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4719 
4720 	  TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4721 
4722 	  t = cxx_make_type (TYPE_ARGUMENT_PACK);
4723 	  SET_ARGUMENT_PACK_ARGS (t, vec);
4724 	}
4725     }
4726   else
4727     {
4728       t = DECL_INITIAL (t);
4729 
4730       if (TEMPLATE_PARM_PARAMETER_PACK (t))
4731 	{
4732 	  /* Turn this argument into a NONTYPE_ARGUMENT_PACK
4733 	     with a single element, which expands T.  */
4734 	  tree vec = make_tree_vec (1);
4735 	  if (CHECKING_P)
4736 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4737 
4738 	  t = convert_from_reference (t);
4739 	  TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4740 
4741 	  t  = make_node (NONTYPE_ARGUMENT_PACK);
4742 	  SET_ARGUMENT_PACK_ARGS (t, vec);
4743 	}
4744       else
4745 	t = convert_from_reference (t);
4746     }
4747   return t;
4748 }
4749 
4750 /* Given a single level of template parameters (a TREE_VEC), return it
4751    as a set of template arguments.  */
4752 
4753 tree
template_parms_level_to_args(tree parms)4754 template_parms_level_to_args (tree parms)
4755 {
4756   tree a = copy_node (parms);
4757   TREE_TYPE (a) = NULL_TREE;
4758   for (int i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4759     TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4760 
4761   if (CHECKING_P)
4762     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4763 
4764   return a;
4765 }
4766 
4767 /* Given a set of template parameters, return them as a set of template
4768    arguments.  The template parameters are represented as a TREE_VEC, in
4769    the form documented in cp-tree.h for template arguments.  */
4770 
4771 tree
template_parms_to_args(tree parms)4772 template_parms_to_args (tree parms)
4773 {
4774   tree header;
4775   tree args = NULL_TREE;
4776   int length = TMPL_PARMS_DEPTH (parms);
4777   int l = length;
4778 
4779   /* If there is only one level of template parameters, we do not
4780      create a TREE_VEC of TREE_VECs.  Instead, we return a single
4781      TREE_VEC containing the arguments.  */
4782   if (length > 1)
4783     args = make_tree_vec (length);
4784 
4785   for (header = parms; header; header = TREE_CHAIN (header))
4786     {
4787       tree a = template_parms_level_to_args (TREE_VALUE (header));
4788 
4789       if (length > 1)
4790 	TREE_VEC_ELT (args, --l) = a;
4791       else
4792 	args = a;
4793     }
4794 
4795   return args;
4796 }
4797 
4798 /* Within the declaration of a template, return the currently active
4799    template parameters as an argument TREE_VEC.  */
4800 
4801 static tree
current_template_args(void)4802 current_template_args (void)
4803 {
4804   return template_parms_to_args (current_template_parms);
4805 }
4806 
4807 /* Return the fully generic arguments for of TMPL, i.e. what
4808    current_template_args would be while parsing it.  */
4809 
4810 tree
generic_targs_for(tree tmpl)4811 generic_targs_for (tree tmpl)
4812 {
4813   if (tmpl == NULL_TREE)
4814     return NULL_TREE;
4815   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
4816       || DECL_TEMPLATE_SPECIALIZATION (tmpl))
4817     /* DECL_TEMPLATE_RESULT doesn't have the arguments we want.  For a template
4818        template parameter, it has no TEMPLATE_INFO; for a partial
4819        specialization, it has the arguments for the primary template, and we
4820        want the arguments for the partial specialization.  */;
4821   else if (tree result = DECL_TEMPLATE_RESULT (tmpl))
4822     if (tree ti = get_template_info (result))
4823       return TI_ARGS (ti);
4824   return template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl));
4825 }
4826 
4827 /* Update the declared TYPE by doing any lookups which were thought to be
4828    dependent, but are not now that we know the SCOPE of the declarator.  */
4829 
4830 tree
maybe_update_decl_type(tree orig_type,tree scope)4831 maybe_update_decl_type (tree orig_type, tree scope)
4832 {
4833   tree type = orig_type;
4834 
4835   if (type == NULL_TREE)
4836     return type;
4837 
4838   if (TREE_CODE (orig_type) == TYPE_DECL)
4839     type = TREE_TYPE (type);
4840 
4841   if (scope && TYPE_P (scope) && dependent_type_p (scope)
4842       && dependent_type_p (type)
4843       /* Don't bother building up the args in this case.  */
4844       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4845     {
4846       /* tsubst in the args corresponding to the template parameters,
4847 	 including auto if present.  Most things will be unchanged, but
4848 	 make_typename_type and tsubst_qualified_id will resolve
4849 	 TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
4850       tree args = current_template_args ();
4851       tree auto_node = type_uses_auto (type);
4852       tree pushed;
4853       if (auto_node)
4854 	{
4855 	  tree auto_vec = make_tree_vec (1);
4856 	  TREE_VEC_ELT (auto_vec, 0) = auto_node;
4857 	  args = add_to_template_args (args, auto_vec);
4858 	}
4859       pushed = push_scope (scope);
4860       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4861       if (pushed)
4862 	pop_scope (scope);
4863     }
4864 
4865   if (type == error_mark_node)
4866     return orig_type;
4867 
4868   if (TREE_CODE (orig_type) == TYPE_DECL)
4869     {
4870       if (same_type_p (type, TREE_TYPE (orig_type)))
4871 	type = orig_type;
4872       else
4873 	type = TYPE_NAME (type);
4874     }
4875   return type;
4876 }
4877 
4878 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4879    template PARMS and constraints, CONSTR.  If MEMBER_TEMPLATE_P is true,
4880    the new  template is a member template. */
4881 
4882 static tree
build_template_decl(tree decl,tree parms,bool member_template_p)4883 build_template_decl (tree decl, tree parms, bool member_template_p)
4884 {
4885   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4886   SET_DECL_LANGUAGE (tmpl, DECL_LANGUAGE (decl));
4887   DECL_TEMPLATE_PARMS (tmpl) = parms;
4888   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4889   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
4890   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4891 
4892   return tmpl;
4893 }
4894 
4895 struct template_parm_data
4896 {
4897   /* The level of the template parameters we are currently
4898      processing.  */
4899   int level;
4900 
4901   /* The index of the specialization argument we are currently
4902      processing.  */
4903   int current_arg;
4904 
4905   /* An array whose size is the number of template parameters.  The
4906      elements are nonzero if the parameter has been used in any one
4907      of the arguments processed so far.  */
4908   int* parms;
4909 
4910   /* An array whose size is the number of template arguments.  The
4911      elements are nonzero if the argument makes use of template
4912      parameters of this level.  */
4913   int* arg_uses_template_parms;
4914 };
4915 
4916 /* Subroutine of push_template_decl used to see if each template
4917    parameter in a partial specialization is used in the explicit
4918    argument list.  If T is of the LEVEL given in DATA (which is
4919    treated as a template_parm_data*), then DATA->PARMS is marked
4920    appropriately.  */
4921 
4922 static int
mark_template_parm(tree t,void * data)4923 mark_template_parm (tree t, void* data)
4924 {
4925   int level;
4926   int idx;
4927   struct template_parm_data* tpd = (struct template_parm_data*) data;
4928 
4929   template_parm_level_and_index (t, &level, &idx);
4930 
4931   if (level == tpd->level)
4932     {
4933       tpd->parms[idx] = 1;
4934       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
4935     }
4936 
4937   /* In C++17 the type of a non-type argument is a deduced context.  */
4938   if (cxx_dialect >= cxx17
4939       && TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4940     for_each_template_parm (TREE_TYPE (t),
4941 			    &mark_template_parm,
4942 			    data,
4943 			    NULL,
4944 			    /*include_nondeduced_p=*/false);
4945 
4946   /* Return zero so that for_each_template_parm will continue the
4947      traversal of the tree; we want to mark *every* template parm.  */
4948   return 0;
4949 }
4950 
4951 /* Process the partial specialization DECL.  */
4952 
4953 static tree
process_partial_specialization(tree decl)4954 process_partial_specialization (tree decl)
4955 {
4956   tree type = TREE_TYPE (decl);
4957   tree tinfo = get_template_info (decl);
4958   tree maintmpl = TI_TEMPLATE (tinfo);
4959   tree specargs = TI_ARGS (tinfo);
4960   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
4961   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
4962   tree inner_parms;
4963   tree inst;
4964   int nargs = TREE_VEC_LENGTH (inner_args);
4965   int ntparms;
4966   int  i;
4967   bool did_error_intro = false;
4968   struct template_parm_data tpd;
4969   struct template_parm_data tpd2;
4970 
4971   gcc_assert (current_template_parms);
4972 
4973   /* A concept cannot be specialized.  */
4974   if (flag_concepts && variable_concept_p (maintmpl))
4975     {
4976       error ("specialization of variable concept %q#D", maintmpl);
4977       return error_mark_node;
4978     }
4979 
4980   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4981   ntparms = TREE_VEC_LENGTH (inner_parms);
4982 
4983   /* We check that each of the template parameters given in the
4984      partial specialization is used in the argument list to the
4985      specialization.  For example:
4986 
4987        template <class T> struct S;
4988        template <class T> struct S<T*>;
4989 
4990      The second declaration is OK because `T*' uses the template
4991      parameter T, whereas
4992 
4993        template <class T> struct S<int>;
4994 
4995      is no good.  Even trickier is:
4996 
4997        template <class T>
4998        struct S1
4999        {
5000 	  template <class U>
5001 	  struct S2;
5002 	  template <class U>
5003 	  struct S2<T>;
5004        };
5005 
5006      The S2<T> declaration is actually invalid; it is a
5007      full-specialization.  Of course,
5008 
5009 	  template <class U>
5010 	  struct S2<T (*)(U)>;
5011 
5012      or some such would have been OK.  */
5013   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
5014   tpd.parms = XALLOCAVEC (int, ntparms);
5015   memset (tpd.parms, 0, sizeof (int) * ntparms);
5016 
5017   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5018   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
5019   for (i = 0; i < nargs; ++i)
5020     {
5021       tpd.current_arg = i;
5022       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
5023 			      &mark_template_parm,
5024 			      &tpd,
5025 			      NULL,
5026 			      /*include_nondeduced_p=*/false);
5027     }
5028   for (i = 0; i < ntparms; ++i)
5029     if (tpd.parms[i] == 0)
5030       {
5031 	/* One of the template parms was not used in a deduced context in the
5032 	   specialization.  */
5033 	if (!did_error_intro)
5034 	  {
5035 	    error ("template parameters not deducible in "
5036 		   "partial specialization:");
5037 	    did_error_intro = true;
5038 	  }
5039 
5040 	inform (input_location, "        %qD",
5041 		TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
5042       }
5043 
5044   if (did_error_intro)
5045     return error_mark_node;
5046 
5047   /* [temp.class.spec]
5048 
5049      The argument list of the specialization shall not be identical to
5050      the implicit argument list of the primary template.  */
5051   tree main_args
5052     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
5053   if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args))
5054       && (!flag_concepts
5055 	  || !strictly_subsumes (current_template_constraints (),
5056 				 main_args, maintmpl)))
5057     {
5058       if (!flag_concepts)
5059         error ("partial specialization %q+D does not specialize "
5060 	       "any template arguments; to define the primary template, "
5061 	       "remove the template argument list", decl);
5062       else
5063         error ("partial specialization %q+D does not specialize any "
5064 	       "template arguments and is not more constrained than "
5065 	       "the primary template; to define the primary template, "
5066 	       "remove the template argument list", decl);
5067       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5068     }
5069 
5070   /* A partial specialization that replaces multiple parameters of the
5071      primary template with a pack expansion is less specialized for those
5072      parameters.  */
5073   if (nargs < DECL_NTPARMS (maintmpl))
5074     {
5075       error ("partial specialization is not more specialized than the "
5076 	     "primary template because it replaces multiple parameters "
5077 	     "with a pack expansion");
5078       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5079       /* Avoid crash in process_partial_specialization.  */
5080       return decl;
5081     }
5082 
5083   else if (nargs > DECL_NTPARMS (maintmpl))
5084     {
5085       error ("too many arguments for partial specialization %qT", type);
5086       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5087       /* Avoid crash below.  */
5088       return decl;
5089     }
5090 
5091   /* If we aren't in a dependent class, we can actually try deduction.  */
5092   else if (tpd.level == 1
5093 	   /* FIXME we should be able to handle a partial specialization of a
5094 	      partial instantiation, but currently we can't (c++/41727).  */
5095 	   && TMPL_ARGS_DEPTH (specargs) == 1
5096 	   && !get_partial_spec_bindings (maintmpl, maintmpl, specargs))
5097     {
5098       auto_diagnostic_group d;
5099       if (permerror (input_location, "partial specialization %qD is not "
5100 		     "more specialized than", decl))
5101 	inform (DECL_SOURCE_LOCATION (maintmpl), "primary template %qD",
5102 		maintmpl);
5103     }
5104 
5105   /* [temp.class.spec]
5106 
5107      A partially specialized non-type argument expression shall not
5108      involve template parameters of the partial specialization except
5109      when the argument expression is a simple identifier.
5110 
5111      The type of a template parameter corresponding to a specialized
5112      non-type argument shall not be dependent on a parameter of the
5113      specialization.
5114 
5115      Also, we verify that pack expansions only occur at the
5116      end of the argument list.  */
5117   tpd2.parms = 0;
5118   for (i = 0; i < nargs; ++i)
5119     {
5120       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
5121       tree arg = TREE_VEC_ELT (inner_args, i);
5122       tree packed_args = NULL_TREE;
5123       int j, len = 1;
5124 
5125       if (ARGUMENT_PACK_P (arg))
5126         {
5127           /* Extract the arguments from the argument pack. We'll be
5128              iterating over these in the following loop.  */
5129           packed_args = ARGUMENT_PACK_ARGS (arg);
5130           len = TREE_VEC_LENGTH (packed_args);
5131         }
5132 
5133       for (j = 0; j < len; j++)
5134         {
5135           if (packed_args)
5136             /* Get the Jth argument in the parameter pack.  */
5137             arg = TREE_VEC_ELT (packed_args, j);
5138 
5139           if (PACK_EXPANSION_P (arg))
5140             {
5141               /* Pack expansions must come at the end of the
5142                  argument list.  */
5143               if ((packed_args && j < len - 1)
5144                   || (!packed_args && i < nargs - 1))
5145                 {
5146                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5147                     error ("parameter pack argument %qE must be at the "
5148 			   "end of the template argument list", arg);
5149                   else
5150                     error ("parameter pack argument %qT must be at the "
5151 			   "end of the template argument list", arg);
5152                 }
5153             }
5154 
5155           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5156             /* We only care about the pattern.  */
5157             arg = PACK_EXPANSION_PATTERN (arg);
5158 
5159           if (/* These first two lines are the `non-type' bit.  */
5160               !TYPE_P (arg)
5161               && TREE_CODE (arg) != TEMPLATE_DECL
5162               /* This next two lines are the `argument expression is not just a
5163                  simple identifier' condition and also the `specialized
5164                  non-type argument' bit.  */
5165               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
5166 	      && !((REFERENCE_REF_P (arg)
5167 		    || TREE_CODE (arg) == VIEW_CONVERT_EXPR)
5168 		   && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
5169             {
5170               if ((!packed_args && tpd.arg_uses_template_parms[i])
5171                   || (packed_args && uses_template_parms (arg)))
5172 		error_at (cp_expr_loc_or_input_loc (arg),
5173 			  "template argument %qE involves template "
5174 			  "parameter(s)", arg);
5175               else
5176                 {
5177                   /* Look at the corresponding template parameter,
5178                      marking which template parameters its type depends
5179                      upon.  */
5180                   tree type = TREE_TYPE (parm);
5181 
5182                   if (!tpd2.parms)
5183                     {
5184                       /* We haven't yet initialized TPD2.  Do so now.  */
5185                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5186                       /* The number of parameters here is the number in the
5187                          main template, which, as checked in the assertion
5188                          above, is NARGS.  */
5189                       tpd2.parms = XALLOCAVEC (int, nargs);
5190                       tpd2.level =
5191                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
5192                     }
5193 
5194                   /* Mark the template parameters.  But this time, we're
5195                      looking for the template parameters of the main
5196                      template, not in the specialization.  */
5197                   tpd2.current_arg = i;
5198                   tpd2.arg_uses_template_parms[i] = 0;
5199                   memset (tpd2.parms, 0, sizeof (int) * nargs);
5200                   for_each_template_parm (type,
5201                                           &mark_template_parm,
5202                                           &tpd2,
5203                                           NULL,
5204 					  /*include_nondeduced_p=*/false);
5205 
5206                   if (tpd2.arg_uses_template_parms [i])
5207                     {
5208                       /* The type depended on some template parameters.
5209                          If they are fully specialized in the
5210                          specialization, that's OK.  */
5211                       int j;
5212                       int count = 0;
5213                       for (j = 0; j < nargs; ++j)
5214                         if (tpd2.parms[j] != 0
5215                             && tpd.arg_uses_template_parms [j])
5216                           ++count;
5217                       if (count != 0)
5218                         error_n (input_location, count,
5219                                  "type %qT of template argument %qE depends "
5220                                  "on a template parameter",
5221                                  "type %qT of template argument %qE depends "
5222                                  "on template parameters",
5223                                  type,
5224                                  arg);
5225                     }
5226                 }
5227             }
5228         }
5229     }
5230 
5231   /* We should only get here once.  */
5232   if (TREE_CODE (decl) == TYPE_DECL)
5233     gcc_assert (!COMPLETE_TYPE_P (type));
5234 
5235   // Build the template decl.
5236   tree tmpl = build_template_decl (decl, current_template_parms,
5237 				   DECL_MEMBER_TEMPLATE_P (maintmpl));
5238   TREE_TYPE (tmpl) = type;
5239   DECL_TEMPLATE_RESULT (tmpl) = decl;
5240   SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5241   DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
5242   DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
5243 
5244   /* Give template template parms a DECL_CONTEXT of the template
5245      for which they are a parameter.  */
5246   for (i = 0; i < ntparms; ++i)
5247     {
5248       tree parm = TREE_VALUE (TREE_VEC_ELT (inner_parms, i));
5249       if (TREE_CODE (parm) == TEMPLATE_DECL)
5250 	DECL_CONTEXT (parm) = tmpl;
5251     }
5252 
5253   if (VAR_P (decl))
5254     /* We didn't register this in check_explicit_specialization so we could
5255        wait until the constraints were set.  */
5256     decl = register_specialization (decl, maintmpl, specargs, false, 0);
5257   else
5258     associate_classtype_constraints (type);
5259 
5260   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
5261     = tree_cons (specargs, tmpl,
5262                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
5263   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
5264 
5265   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
5266        inst = TREE_CHAIN (inst))
5267     {
5268       tree instance = TREE_VALUE (inst);
5269       if (TYPE_P (instance)
5270 	  ? (COMPLETE_TYPE_P (instance)
5271 	     && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
5272 	  : DECL_TEMPLATE_INSTANTIATION (instance))
5273 	{
5274 	  tree spec = most_specialized_partial_spec (instance, tf_none);
5275 	  tree inst_decl = (DECL_P (instance)
5276 			    ? instance : TYPE_NAME (instance));
5277 	  if (!spec)
5278 	    /* OK */;
5279 	  else if (spec == error_mark_node)
5280 	    permerror (input_location,
5281 		       "declaration of %qD ambiguates earlier template "
5282 		       "instantiation for %qD", decl, inst_decl);
5283 	  else if (TREE_VALUE (spec) == tmpl)
5284 	    permerror (input_location,
5285 		       "partial specialization of %qD after instantiation "
5286 		       "of %qD", decl, inst_decl);
5287 	}
5288     }
5289 
5290   return decl;
5291 }
5292 
5293 /* PARM is a template parameter of some form; return the corresponding
5294    TEMPLATE_PARM_INDEX.  */
5295 
5296 static tree
get_template_parm_index(tree parm)5297 get_template_parm_index (tree parm)
5298 {
5299   if (TREE_CODE (parm) == PARM_DECL
5300       || TREE_CODE (parm) == CONST_DECL)
5301     parm = DECL_INITIAL (parm);
5302   else if (TREE_CODE (parm) == TYPE_DECL
5303 	   || TREE_CODE (parm) == TEMPLATE_DECL)
5304     parm = TREE_TYPE (parm);
5305   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
5306       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM
5307       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
5308     parm = TEMPLATE_TYPE_PARM_INDEX (parm);
5309   gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
5310   return parm;
5311 }
5312 
5313 /* Subroutine of fixed_parameter_pack_p below.  Look for any template
5314    parameter packs used by the template parameter PARM.  */
5315 
5316 static void
fixed_parameter_pack_p_1(tree parm,struct find_parameter_pack_data * ppd)5317 fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
5318 {
5319   /* A type parm can't refer to another parm.  */
5320   if (TREE_CODE (parm) == TYPE_DECL || parm == error_mark_node)
5321     return;
5322   else if (TREE_CODE (parm) == PARM_DECL)
5323     {
5324       cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
5325 		    ppd, ppd->visited);
5326       return;
5327     }
5328 
5329   gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
5330 
5331   tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
5332   for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
5333     {
5334       tree p = TREE_VALUE (TREE_VEC_ELT (vec, i));
5335       if (template_parameter_pack_p (p))
5336 	/* Any packs in the type are expanded by this parameter.  */;
5337       else
5338 	fixed_parameter_pack_p_1 (p, ppd);
5339     }
5340 }
5341 
5342 /* PARM is a template parameter pack.  Return any parameter packs used in
5343    its type or the type of any of its template parameters.  If there are
5344    any such packs, it will be instantiated into a fixed template parameter
5345    list by partial instantiation rather than be fully deduced.  */
5346 
5347 tree
fixed_parameter_pack_p(tree parm)5348 fixed_parameter_pack_p (tree parm)
5349 {
5350   /* This can only be true in a member template.  */
5351   if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
5352     return NULL_TREE;
5353   /* This can only be true for a parameter pack.  */
5354   if (!template_parameter_pack_p (parm))
5355     return NULL_TREE;
5356   /* A type parm can't refer to another parm.  */
5357   if (TREE_CODE (parm) == TYPE_DECL)
5358     return NULL_TREE;
5359 
5360   tree parameter_packs = NULL_TREE;
5361   struct find_parameter_pack_data ppd;
5362   ppd.parameter_packs = &parameter_packs;
5363   ppd.visited = new hash_set<tree>;
5364   ppd.type_pack_expansion_p = false;
5365 
5366   fixed_parameter_pack_p_1 (parm, &ppd);
5367 
5368   delete ppd.visited;
5369   return parameter_packs;
5370 }
5371 
5372 /* Check that a template declaration's use of default arguments and
5373    parameter packs is not invalid.  Here, PARMS are the template
5374    parameters.  IS_PRIMARY is true if DECL is the thing declared by
5375    a primary template.  IS_PARTIAL is true if DECL is a partial
5376    specialization.
5377 
5378    IS_FRIEND_DECL is nonzero if DECL is either a non-defining friend
5379    function template declaration or a friend class template
5380    declaration.  In the function case, 1 indicates a declaration, 2
5381    indicates a redeclaration.  When IS_FRIEND_DECL=2, no errors are
5382    emitted for extraneous default arguments.
5383 
5384    Returns TRUE if there were no errors found, FALSE otherwise. */
5385 
5386 bool
check_default_tmpl_args(tree decl,tree parms,bool is_primary,bool is_partial,int is_friend_decl)5387 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
5388                          bool is_partial, int is_friend_decl)
5389 {
5390   const char *msg;
5391   int last_level_to_check;
5392   tree parm_level;
5393   bool no_errors = true;
5394 
5395   /* [temp.param]
5396 
5397      A default template-argument shall not be specified in a
5398      function template declaration or a function template definition, nor
5399      in the template-parameter-list of the definition of a member of a
5400      class template.  */
5401 
5402   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
5403       || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_FUNCTION_P (decl)))
5404     /* You can't have a function template declaration in a local
5405        scope, nor you can you define a member of a class template in a
5406        local scope.  */
5407     return true;
5408 
5409   if ((TREE_CODE (decl) == TYPE_DECL
5410        && TREE_TYPE (decl)
5411        && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5412       || (TREE_CODE (decl) == FUNCTION_DECL
5413 	  && LAMBDA_FUNCTION_P (decl)))
5414     /* A lambda doesn't have an explicit declaration; don't complain
5415        about the parms of the enclosing class.  */
5416     return true;
5417 
5418   if (current_class_type
5419       && !TYPE_BEING_DEFINED (current_class_type)
5420       && DECL_LANG_SPECIFIC (decl)
5421       && DECL_DECLARES_FUNCTION_P (decl)
5422       /* If this is either a friend defined in the scope of the class
5423 	 or a member function.  */
5424       && (DECL_FUNCTION_MEMBER_P (decl)
5425 	  ? same_type_p (DECL_CONTEXT (decl), current_class_type)
5426 	  : DECL_FRIEND_CONTEXT (decl)
5427 	  ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
5428 	  : false)
5429       /* And, if it was a member function, it really was defined in
5430 	 the scope of the class.  */
5431       && (!DECL_FUNCTION_MEMBER_P (decl)
5432 	  || DECL_INITIALIZED_IN_CLASS_P (decl)))
5433     /* We already checked these parameters when the template was
5434        declared, so there's no need to do it again now.  This function
5435        was defined in class scope, but we're processing its body now
5436        that the class is complete.  */
5437     return true;
5438 
5439   /* Core issue 226 (C++0x only): the following only applies to class
5440      templates.  */
5441   if (is_primary
5442       && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
5443     {
5444       /* [temp.param]
5445 
5446          If a template-parameter has a default template-argument, all
5447          subsequent template-parameters shall have a default
5448          template-argument supplied.  */
5449       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
5450         {
5451           tree inner_parms = TREE_VALUE (parm_level);
5452           int ntparms = TREE_VEC_LENGTH (inner_parms);
5453           int seen_def_arg_p = 0;
5454           int i;
5455 
5456           for (i = 0; i < ntparms; ++i)
5457             {
5458               tree parm = TREE_VEC_ELT (inner_parms, i);
5459 
5460               if (parm == error_mark_node)
5461                 continue;
5462 
5463               if (TREE_PURPOSE (parm))
5464                 seen_def_arg_p = 1;
5465               else if (seen_def_arg_p
5466 		       && !template_parameter_pack_p (TREE_VALUE (parm)))
5467                 {
5468                   error ("no default argument for %qD", TREE_VALUE (parm));
5469                   /* For better subsequent error-recovery, we indicate that
5470                      there should have been a default argument.  */
5471                   TREE_PURPOSE (parm) = error_mark_node;
5472                   no_errors = false;
5473                 }
5474 	      else if (!is_partial
5475 		       && !is_friend_decl
5476 		       /* Don't complain about an enclosing partial
5477 			  specialization.  */
5478 		       && parm_level == parms
5479 		       && TREE_CODE (decl) == TYPE_DECL
5480 		       && i < ntparms - 1
5481 		       && template_parameter_pack_p (TREE_VALUE (parm))
5482 		       /* A fixed parameter pack will be partially
5483 			  instantiated into a fixed length list.  */
5484 		       && !fixed_parameter_pack_p (TREE_VALUE (parm)))
5485 		{
5486 		  /* A primary class template can only have one
5487 		     parameter pack, at the end of the template
5488 		     parameter list.  */
5489 
5490 		  error ("parameter pack %q+D must be at the end of the"
5491 			 " template parameter list", TREE_VALUE (parm));
5492 
5493 		  TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
5494 		    = error_mark_node;
5495 		  no_errors = false;
5496 		}
5497             }
5498         }
5499     }
5500 
5501   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
5502       || is_partial
5503       || !is_primary
5504       || is_friend_decl)
5505     /* For an ordinary class template, default template arguments are
5506        allowed at the innermost level, e.g.:
5507 	 template <class T = int>
5508 	 struct S {};
5509        but, in a partial specialization, they're not allowed even
5510        there, as we have in [temp.class.spec]:
5511 
5512 	 The template parameter list of a specialization shall not
5513 	 contain default template argument values.
5514 
5515        So, for a partial specialization, or for a function template
5516        (in C++98/C++03), we look at all of them.  */
5517     ;
5518   else
5519     /* But, for a primary class template that is not a partial
5520        specialization we look at all template parameters except the
5521        innermost ones.  */
5522     parms = TREE_CHAIN (parms);
5523 
5524   /* Figure out what error message to issue.  */
5525   if (is_friend_decl == 2)
5526     msg = G_("default template arguments may not be used in function template "
5527 	     "friend re-declaration");
5528   else if (is_friend_decl)
5529     msg = G_("default template arguments may not be used in template "
5530 	     "friend declarations");
5531   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
5532     msg = G_("default template arguments may not be used in function templates "
5533 	     "without %<-std=c++11%> or %<-std=gnu++11%>");
5534   else if (is_partial)
5535     msg = G_("default template arguments may not be used in "
5536 	     "partial specializations");
5537   else if (current_class_type && CLASSTYPE_IS_TEMPLATE (current_class_type))
5538     msg = G_("default argument for template parameter for class enclosing %qD");
5539   else
5540     /* Per [temp.param]/9, "A default template-argument shall not be
5541        specified in the template-parameter-lists of the definition of
5542        a member of a class template that appears outside of the member's
5543        class.", thus if we aren't handling a member of a class template
5544        there is no need to examine the parameters.  */
5545     return true;
5546 
5547   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
5548     /* If we're inside a class definition, there's no need to
5549        examine the parameters to the class itself.  On the one
5550        hand, they will be checked when the class is defined, and,
5551        on the other, default arguments are valid in things like:
5552 	 template <class T = double>
5553 	 struct S { template <class U> void f(U); };
5554        Here the default argument for `S' has no bearing on the
5555        declaration of `f'.  */
5556     last_level_to_check = template_class_depth (current_class_type) + 1;
5557   else
5558     /* Check everything.  */
5559     last_level_to_check = 0;
5560 
5561   for (parm_level = parms;
5562        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
5563        parm_level = TREE_CHAIN (parm_level))
5564     {
5565       tree inner_parms = TREE_VALUE (parm_level);
5566       int i;
5567       int ntparms;
5568 
5569       ntparms = TREE_VEC_LENGTH (inner_parms);
5570       for (i = 0; i < ntparms; ++i)
5571         {
5572           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
5573             continue;
5574 
5575 	  if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
5576 	    {
5577 	      if (msg)
5578 	        {
5579                   no_errors = false;
5580                   if (is_friend_decl == 2)
5581                     return no_errors;
5582 
5583 		  error (msg, decl);
5584 		  msg = 0;
5585 	        }
5586 
5587 	      /* Clear out the default argument so that we are not
5588 	         confused later.  */
5589 	      TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
5590 	    }
5591         }
5592 
5593       /* At this point, if we're still interested in issuing messages,
5594 	 they must apply to classes surrounding the object declared.  */
5595       if (msg)
5596 	msg = G_("default argument for template parameter for class "
5597 		 "enclosing %qD");
5598     }
5599 
5600   return no_errors;
5601 }
5602 
5603 /* Worker for push_template_decl_real, called via
5604    for_each_template_parm.  DATA is really an int, indicating the
5605    level of the parameters we are interested in.  If T is a template
5606    parameter of that level, return nonzero.  */
5607 
5608 static int
template_parm_this_level_p(tree t,void * data)5609 template_parm_this_level_p (tree t, void* data)
5610 {
5611   int this_level = *(int *)data;
5612   int level;
5613 
5614   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5615     level = TEMPLATE_PARM_LEVEL (t);
5616   else
5617     level = TEMPLATE_TYPE_LEVEL (t);
5618   return level == this_level;
5619 }
5620 
5621 /* Worker for uses_outer_template_parms, called via for_each_template_parm.
5622    DATA is really an int, indicating the innermost outer level of parameters.
5623    If T is a template parameter of that level or further out, return
5624    nonzero.  */
5625 
5626 static int
template_parm_outer_level(tree t,void * data)5627 template_parm_outer_level (tree t, void *data)
5628 {
5629   int this_level = *(int *)data;
5630   int level;
5631 
5632   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5633     level = TEMPLATE_PARM_LEVEL (t);
5634   else
5635     level = TEMPLATE_TYPE_LEVEL (t);
5636   return level <= this_level;
5637 }
5638 
5639 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
5640    parameters given by current_template_args, or reuses a
5641    previously existing one, if appropriate.  Returns the DECL, or an
5642    equivalent one, if it is replaced via a call to duplicate_decls.
5643 
5644    If IS_FRIEND is true, DECL is a friend declaration.  */
5645 
5646 tree
push_template_decl_real(tree decl,bool is_friend)5647 push_template_decl_real (tree decl, bool is_friend)
5648 {
5649   tree tmpl;
5650   tree args;
5651   tree info;
5652   tree ctx;
5653   bool is_primary;
5654   bool is_partial;
5655   int new_template_p = 0;
5656   /* True if the template is a member template, in the sense of
5657      [temp.mem].  */
5658   bool member_template_p = false;
5659 
5660   if (decl == error_mark_node || !current_template_parms)
5661     return error_mark_node;
5662 
5663   /* See if this is a partial specialization.  */
5664   is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
5665 		 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
5666 		 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
5667 		|| (VAR_P (decl)
5668 		    && DECL_LANG_SPECIFIC (decl)
5669 		    && DECL_TEMPLATE_SPECIALIZATION (decl)
5670 		    && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
5671 
5672   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
5673     is_friend = true;
5674 
5675   if (is_friend)
5676     /* For a friend, we want the context of the friend, not
5677        the type of which it is a friend.  */
5678     ctx = CP_DECL_CONTEXT (decl);
5679   else if (CP_DECL_CONTEXT (decl)
5680 	   && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
5681     /* In the case of a virtual function, we want the class in which
5682        it is defined.  */
5683     ctx = CP_DECL_CONTEXT (decl);
5684   else
5685     /* Otherwise, if we're currently defining some class, the DECL
5686        is assumed to be a member of the class.  */
5687     ctx = current_scope ();
5688 
5689   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
5690     ctx = NULL_TREE;
5691 
5692   if (!DECL_CONTEXT (decl))
5693     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5694 
5695   /* See if this is a primary template.  */
5696   if (is_friend && ctx
5697       && uses_template_parms_level (ctx, processing_template_decl))
5698     /* A friend template that specifies a class context, i.e.
5699          template <typename T> friend void A<T>::f();
5700        is not primary.  */
5701     is_primary = false;
5702   else if (TREE_CODE (decl) == TYPE_DECL
5703 	   && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5704     is_primary = false;
5705   else
5706     is_primary = template_parm_scope_p ();
5707 
5708   if (is_primary)
5709     {
5710       warning (OPT_Wtemplates, "template %qD declared", decl);
5711 
5712       if (DECL_CLASS_SCOPE_P (decl))
5713 	member_template_p = true;
5714       if (TREE_CODE (decl) == TYPE_DECL
5715 	  && IDENTIFIER_ANON_P (DECL_NAME (decl)))
5716 	{
5717 	  error ("template class without a name");
5718 	  return error_mark_node;
5719 	}
5720       else if (TREE_CODE (decl) == FUNCTION_DECL)
5721 	{
5722 	  if (member_template_p)
5723 	    {
5724 	      if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
5725 		error ("member template %qD may not have virt-specifiers", decl);
5726 	    }
5727 	  if (DECL_DESTRUCTOR_P (decl))
5728 	    {
5729 	      /* [temp.mem]
5730 
5731 		 A destructor shall not be a member template.  */
5732 	      error_at (DECL_SOURCE_LOCATION (decl),
5733 			"destructor %qD declared as member template", decl);
5734 	      return error_mark_node;
5735 	    }
5736 	  if (IDENTIFIER_NEWDEL_OP_P (DECL_NAME (decl))
5737 	      && (!prototype_p (TREE_TYPE (decl))
5738 		  || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
5739 		  || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5740 		  || (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5741 		      == void_list_node)))
5742 	    {
5743 	      /* [basic.stc.dynamic.allocation]
5744 
5745 		 An allocation function can be a function
5746 		 template. ... Template allocation functions shall
5747 		 have two or more parameters.  */
5748 	      error ("invalid template declaration of %qD", decl);
5749 	      return error_mark_node;
5750 	    }
5751 	}
5752       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5753 	       && CLASS_TYPE_P (TREE_TYPE (decl)))
5754 	{
5755 	  /* Class template, set TEMPLATE_TYPE_PARM_FOR_CLASS.  */
5756 	  tree parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
5757 	  for (int i = 0; i < TREE_VEC_LENGTH (parms); ++i)
5758 	    {
5759 	      tree t = TREE_VALUE (TREE_VEC_ELT (parms, i));
5760 	      if (TREE_CODE (t) == TYPE_DECL)
5761 		t = TREE_TYPE (t);
5762 	      if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
5763 		TEMPLATE_TYPE_PARM_FOR_CLASS (t) = true;
5764 	    }
5765 	}
5766       else if (TREE_CODE (decl) == TYPE_DECL
5767 	       && TYPE_DECL_ALIAS_P (decl))
5768 	/* alias-declaration */
5769 	gcc_assert (!DECL_ARTIFICIAL (decl));
5770       else if (VAR_P (decl))
5771 	/* C++14 variable template. */;
5772       else if (TREE_CODE (decl) == CONCEPT_DECL)
5773 	/* C++2a concept definitions.  */;
5774       else
5775 	{
5776 	  error ("template declaration of %q#D", decl);
5777 	  return error_mark_node;
5778 	}
5779     }
5780 
5781   /* Check to see that the rules regarding the use of default
5782      arguments are not being violated.  We check args for a friend
5783      functions when we know whether it's a definition, introducing
5784      declaration or re-declaration.  */
5785   if (!is_friend || TREE_CODE (decl) != FUNCTION_DECL)
5786     check_default_tmpl_args (decl, current_template_parms,
5787 			     is_primary, is_partial, is_friend);
5788 
5789   /* Ensure that there are no parameter packs in the type of this
5790      declaration that have not been expanded.  */
5791   if (TREE_CODE (decl) == FUNCTION_DECL)
5792     {
5793       /* Check each of the arguments individually to see if there are
5794          any bare parameter packs.  */
5795       tree type = TREE_TYPE (decl);
5796       tree arg = DECL_ARGUMENTS (decl);
5797       tree argtype = TYPE_ARG_TYPES (type);
5798 
5799       while (arg && argtype)
5800         {
5801           if (!DECL_PACK_P (arg)
5802               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
5803             {
5804             /* This is a PARM_DECL that contains unexpanded parameter
5805                packs. We have already complained about this in the
5806                check_for_bare_parameter_packs call, so just replace
5807                these types with ERROR_MARK_NODE.  */
5808               TREE_TYPE (arg) = error_mark_node;
5809               TREE_VALUE (argtype) = error_mark_node;
5810             }
5811 
5812           arg = DECL_CHAIN (arg);
5813           argtype = TREE_CHAIN (argtype);
5814         }
5815 
5816       /* Check for bare parameter packs in the return type and the
5817          exception specifiers.  */
5818       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
5819 	/* Errors were already issued, set return type to int
5820 	   as the frontend doesn't expect error_mark_node as
5821 	   the return type.  */
5822 	TREE_TYPE (type) = integer_type_node;
5823       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
5824 	TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
5825     }
5826   else if (check_for_bare_parameter_packs (is_typedef_decl (decl)
5827 					   ? DECL_ORIGINAL_TYPE (decl)
5828 					   : TREE_TYPE (decl)))
5829     {
5830       TREE_TYPE (decl) = error_mark_node;
5831       return error_mark_node;
5832     }
5833 
5834   if (is_partial)
5835     return process_partial_specialization (decl);
5836 
5837   args = current_template_args ();
5838 
5839   if (!ctx
5840       || TREE_CODE (ctx) == FUNCTION_DECL
5841       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
5842       || (TREE_CODE (decl) == TYPE_DECL
5843 	  && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5844       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
5845     {
5846       if (DECL_LANG_SPECIFIC (decl)
5847 	  && DECL_TEMPLATE_INFO (decl)
5848 	  && DECL_TI_TEMPLATE (decl))
5849 	tmpl = DECL_TI_TEMPLATE (decl);
5850       /* If DECL is a TYPE_DECL for a class-template, then there won't
5851 	 be DECL_LANG_SPECIFIC.  The information equivalent to
5852 	 DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
5853       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5854 	       && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
5855 	       && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
5856 	{
5857 	  /* Since a template declaration already existed for this
5858 	     class-type, we must be redeclaring it here.  Make sure
5859 	     that the redeclaration is valid.  */
5860 	  redeclare_class_template (TREE_TYPE (decl),
5861 				    current_template_parms,
5862 				    current_template_constraints ());
5863 	  /* We don't need to create a new TEMPLATE_DECL; just use the
5864 	     one we already had.  */
5865 	  tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
5866 	}
5867       else
5868 	{
5869 	  tmpl = build_template_decl (decl, current_template_parms,
5870 				      member_template_p);
5871 	  new_template_p = 1;
5872 
5873 	  if (DECL_LANG_SPECIFIC (decl)
5874 	      && DECL_TEMPLATE_SPECIALIZATION (decl))
5875 	    {
5876 	      /* A specialization of a member template of a template
5877 		 class.  */
5878 	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5879 	      DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
5880 	      DECL_TEMPLATE_INFO (decl) = NULL_TREE;
5881 	    }
5882 	}
5883     }
5884   else
5885     {
5886       tree a, t, current, parms;
5887       int i;
5888       tree tinfo = get_template_info (decl);
5889 
5890       if (!tinfo)
5891 	{
5892 	  error ("template definition of non-template %q#D", decl);
5893 	  return error_mark_node;
5894 	}
5895 
5896       tmpl = TI_TEMPLATE (tinfo);
5897 
5898       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
5899 	  && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
5900 	  && DECL_TEMPLATE_SPECIALIZATION (decl)
5901 	  && DECL_MEMBER_TEMPLATE_P (tmpl))
5902 	{
5903 	  tree new_tmpl;
5904 
5905 	  /* The declaration is a specialization of a member
5906 	     template, declared outside the class.  Therefore, the
5907 	     innermost template arguments will be NULL, so we
5908 	     replace them with the arguments determined by the
5909 	     earlier call to check_explicit_specialization.  */
5910 	  args = DECL_TI_ARGS (decl);
5911 
5912 	  new_tmpl
5913 	    = build_template_decl (decl, current_template_parms,
5914 				   member_template_p);
5915 	  DECL_TEMPLATE_RESULT (new_tmpl) = decl;
5916 	  TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
5917 	  DECL_TI_TEMPLATE (decl) = new_tmpl;
5918 	  SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
5919 	  DECL_TEMPLATE_INFO (new_tmpl)
5920 	    = build_template_info (tmpl, args);
5921 
5922 	  register_specialization (new_tmpl,
5923 				   most_general_template (tmpl),
5924 				   args,
5925 				   is_friend, 0);
5926 	  return decl;
5927 	}
5928 
5929       /* Make sure the template headers we got make sense.  */
5930 
5931       parms = DECL_TEMPLATE_PARMS (tmpl);
5932       i = TMPL_PARMS_DEPTH (parms);
5933       if (TMPL_ARGS_DEPTH (args) != i)
5934 	{
5935 	  error ("expected %d levels of template parms for %q#D, got %d",
5936 		 i, decl, TMPL_ARGS_DEPTH (args));
5937 	  DECL_INTERFACE_KNOWN (decl) = 1;
5938 	  return error_mark_node;
5939 	}
5940       else
5941 	for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
5942 	  {
5943 	    a = TMPL_ARGS_LEVEL (args, i);
5944 	    t = INNERMOST_TEMPLATE_PARMS (parms);
5945 
5946 	    if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
5947 	      {
5948 		if (current == decl)
5949 		  error ("got %d template parameters for %q#D",
5950 			 TREE_VEC_LENGTH (a), decl);
5951 		else
5952 		  error ("got %d template parameters for %q#T",
5953 			 TREE_VEC_LENGTH (a), current);
5954 		error ("  but %d required", TREE_VEC_LENGTH (t));
5955 		/* Avoid crash in import_export_decl.  */
5956 		DECL_INTERFACE_KNOWN (decl) = 1;
5957 		return error_mark_node;
5958 	      }
5959 
5960 	    if (current == decl)
5961 	      current = ctx;
5962 	    else if (current == NULL_TREE)
5963 	      /* Can happen in erroneous input.  */
5964 	      break;
5965 	    else
5966 	      current = get_containing_scope (current);
5967 	  }
5968 
5969       /* Check that the parms are used in the appropriate qualifying scopes
5970 	 in the declarator.  */
5971       if (!comp_template_args
5972 	  (TI_ARGS (tinfo),
5973 	   TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
5974 	{
5975 	  error ("template arguments to %qD do not match original "
5976 		 "template %qD", decl, DECL_TEMPLATE_RESULT (tmpl));
5977 	  if (!uses_template_parms (TI_ARGS (tinfo)))
5978 	    inform (input_location, "use %<template<>%> for"
5979 		    " an explicit specialization");
5980 	  /* Avoid crash in import_export_decl.  */
5981 	  DECL_INTERFACE_KNOWN (decl) = 1;
5982 	  return error_mark_node;
5983 	}
5984     }
5985 
5986   DECL_TEMPLATE_RESULT (tmpl) = decl;
5987   TREE_TYPE (tmpl) = TREE_TYPE (decl);
5988 
5989   /* Push template declarations for global functions and types.  Note
5990      that we do not try to push a global template friend declared in a
5991      template class; such a thing may well depend on the template
5992      parameters of the class.  */
5993   if (new_template_p && !ctx
5994       && !(is_friend && template_class_depth (current_class_type) > 0))
5995     {
5996       tmpl = pushdecl_namespace_level (tmpl, is_friend);
5997       if (tmpl == error_mark_node)
5998 	return error_mark_node;
5999 
6000       /* Hide template friend classes that haven't been declared yet.  */
6001       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
6002 	{
6003 	  DECL_ANTICIPATED (tmpl) = 1;
6004 	  DECL_FRIEND_P (tmpl) = 1;
6005 	}
6006     }
6007 
6008   if (is_primary)
6009     {
6010       tree parms = DECL_TEMPLATE_PARMS (tmpl);
6011 
6012       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6013 
6014       /* Give template template parms a DECL_CONTEXT of the template
6015 	 for which they are a parameter.  */
6016       parms = INNERMOST_TEMPLATE_PARMS (parms);
6017       for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
6018 	{
6019 	  tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6020 	  if (TREE_CODE (parm) == TEMPLATE_DECL)
6021 	    DECL_CONTEXT (parm) = tmpl;
6022 	}
6023 
6024       if (TREE_CODE (decl) == TYPE_DECL
6025 	  && TYPE_DECL_ALIAS_P (decl))
6026 	{
6027 	  if (tree constr
6028 	      = TEMPLATE_PARMS_CONSTRAINTS (DECL_TEMPLATE_PARMS (tmpl)))
6029 	    {
6030 	      /* ??? Why don't we do this here for all templates?  */
6031 	      constr = build_constraints (constr, NULL_TREE);
6032 	      set_constraints (decl, constr);
6033 	    }
6034 	  if (complex_alias_template_p (tmpl))
6035 	    TEMPLATE_DECL_COMPLEX_ALIAS_P (tmpl) = true;
6036 	}
6037     }
6038 
6039   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
6040      back to its most general template.  If TMPL is a specialization,
6041      ARGS may only have the innermost set of arguments.  Add the missing
6042      argument levels if necessary.  */
6043   if (DECL_TEMPLATE_INFO (tmpl))
6044     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
6045 
6046   info = build_template_info (tmpl, args);
6047 
6048   if (DECL_IMPLICIT_TYPEDEF_P (decl))
6049     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
6050   else
6051     {
6052       if (is_primary)
6053 	retrofit_lang_decl (decl);
6054       if (DECL_LANG_SPECIFIC (decl))
6055 	DECL_TEMPLATE_INFO (decl) = info;
6056     }
6057 
6058   if (flag_implicit_templates
6059       && !is_friend
6060       && TREE_PUBLIC (decl)
6061       && VAR_OR_FUNCTION_DECL_P (decl))
6062     /* Set DECL_COMDAT on template instantiations; if we force
6063        them to be emitted by explicit instantiation,
6064        mark_needed will tell cgraph to do the right thing.  */
6065     DECL_COMDAT (decl) = true;
6066 
6067   return DECL_TEMPLATE_RESULT (tmpl);
6068 }
6069 
6070 tree
push_template_decl(tree decl)6071 push_template_decl (tree decl)
6072 {
6073   return push_template_decl_real (decl, false);
6074 }
6075 
6076 /* FN is an inheriting constructor that inherits from the constructor
6077    template INHERITED; turn FN into a constructor template with a matching
6078    template header.  */
6079 
6080 tree
add_inherited_template_parms(tree fn,tree inherited)6081 add_inherited_template_parms (tree fn, tree inherited)
6082 {
6083   tree inner_parms
6084     = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
6085   inner_parms = copy_node (inner_parms);
6086   tree parms
6087     = tree_cons (size_int (processing_template_decl + 1),
6088 		 inner_parms, current_template_parms);
6089   tree tmpl = build_template_decl (fn, parms, /*member*/true);
6090   tree args = template_parms_to_args (parms);
6091   DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
6092   TREE_TYPE (tmpl) = TREE_TYPE (fn);
6093   DECL_TEMPLATE_RESULT (tmpl) = fn;
6094   DECL_ARTIFICIAL (tmpl) = true;
6095   DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6096   return tmpl;
6097 }
6098 
6099 /* Called when a class template TYPE is redeclared with the indicated
6100    template PARMS, e.g.:
6101 
6102      template <class T> struct S;
6103      template <class T> struct S {};  */
6104 
6105 bool
redeclare_class_template(tree type,tree parms,tree cons)6106 redeclare_class_template (tree type, tree parms, tree cons)
6107 {
6108   tree tmpl;
6109   tree tmpl_parms;
6110   int i;
6111 
6112   if (!TYPE_TEMPLATE_INFO (type))
6113     {
6114       error ("%qT is not a template type", type);
6115       return false;
6116     }
6117 
6118   tmpl = TYPE_TI_TEMPLATE (type);
6119   if (!PRIMARY_TEMPLATE_P (tmpl))
6120     /* The type is nested in some template class.  Nothing to worry
6121        about here; there are no new template parameters for the nested
6122        type.  */
6123     return true;
6124 
6125   if (!parms)
6126     {
6127       error ("template specifiers not specified in declaration of %qD",
6128 	     tmpl);
6129       return false;
6130     }
6131 
6132   parms = INNERMOST_TEMPLATE_PARMS (parms);
6133   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
6134 
6135   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
6136     {
6137       error_n (input_location, TREE_VEC_LENGTH (parms),
6138                "redeclared with %d template parameter",
6139                "redeclared with %d template parameters",
6140                TREE_VEC_LENGTH (parms));
6141       inform_n (DECL_SOURCE_LOCATION (tmpl), TREE_VEC_LENGTH (tmpl_parms),
6142                 "previous declaration %qD used %d template parameter",
6143                 "previous declaration %qD used %d template parameters",
6144                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
6145       return false;
6146     }
6147 
6148   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
6149     {
6150       tree tmpl_parm;
6151       tree parm;
6152       tree tmpl_default;
6153       tree parm_default;
6154 
6155       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
6156           || TREE_VEC_ELT (parms, i) == error_mark_node)
6157         continue;
6158 
6159       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
6160       if (error_operand_p (tmpl_parm))
6161 	return false;
6162 
6163       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6164       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
6165       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
6166 
6167       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
6168 	 TEMPLATE_DECL.  */
6169       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
6170 	  || (TREE_CODE (tmpl_parm) != TYPE_DECL
6171 	      && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
6172 	  || (TREE_CODE (tmpl_parm) != PARM_DECL
6173 	      && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
6174 		  != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
6175 	  || (TREE_CODE (tmpl_parm) == PARM_DECL
6176 	      && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
6177 		  != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
6178 	{
6179 	  auto_diagnostic_group d;
6180 	  error ("template parameter %q+#D", tmpl_parm);
6181 	  inform (input_location, "redeclared here as %q#D", parm);
6182 	  return false;
6183 	}
6184 
6185       /* The parameters can be declared to introduce different
6186 	 constraints.  */
6187       tree p1 = TREE_VEC_ELT (tmpl_parms, i);
6188       tree p2 = TREE_VEC_ELT (parms, i);
6189       if (!template_parameter_constraints_equivalent_p (p1, p2))
6190 	{
6191 	  auto_diagnostic_group d;
6192 	  error ("declaration of template parameter %q+#D with different "
6193 		 "constraints", parm);
6194 	  inform (DECL_SOURCE_LOCATION (tmpl_parm),
6195 		  "original declaration appeared here");
6196 	  return false;
6197 	}
6198 
6199       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
6200 	{
6201 	  /* We have in [temp.param]:
6202 
6203 	     A template-parameter may not be given default arguments
6204 	     by two different declarations in the same scope.  */
6205 	  auto_diagnostic_group d;
6206 	  error_at (input_location, "redefinition of default argument for %q#D", parm);
6207 	  inform (DECL_SOURCE_LOCATION (tmpl_parm),
6208 		  "original definition appeared here");
6209 	  return false;
6210 	}
6211 
6212       if (parm_default != NULL_TREE)
6213 	/* Update the previous template parameters (which are the ones
6214 	   that will really count) with the new default value.  */
6215 	TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
6216       else if (tmpl_default != NULL_TREE)
6217 	/* Update the new parameters, too; they'll be used as the
6218 	   parameters for any members.  */
6219 	TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
6220 
6221       /* Give each template template parm in this redeclaration a
6222 	 DECL_CONTEXT of the template for which they are a parameter.  */
6223       if (TREE_CODE (parm) == TEMPLATE_DECL)
6224 	{
6225 	  gcc_assert (DECL_CONTEXT (parm) == NULL_TREE);
6226 	  DECL_CONTEXT (parm) = tmpl;
6227 	}
6228 
6229       if (TREE_CODE (parm) == TYPE_DECL)
6230 	TEMPLATE_TYPE_PARM_FOR_CLASS (TREE_TYPE (parm)) = true;
6231     }
6232 
6233   tree ci = get_constraints (tmpl);
6234   tree req1 = ci ? CI_TEMPLATE_REQS (ci) : NULL_TREE;
6235   tree req2 = cons ? CI_TEMPLATE_REQS (cons) : NULL_TREE;
6236 
6237   /* Two classes with different constraints declare different entities.  */
6238   if (!cp_tree_equal (req1, req2))
6239     {
6240       auto_diagnostic_group d;
6241       error_at (input_location, "redeclaration %q#D with different "
6242                                 "constraints", tmpl);
6243       inform (DECL_SOURCE_LOCATION (tmpl),
6244               "original declaration appeared here");
6245       return false;
6246     }
6247 
6248     return true;
6249 }
6250 
6251 /* The actual substitution part of instantiate_non_dependent_expr_sfinae,
6252    to be used when the caller has already checked
6253    (processing_template_decl
6254     && !instantiation_dependent_expression_p (expr)
6255     && potential_constant_expression (expr))
6256    and cleared processing_template_decl.  */
6257 
6258 tree
instantiate_non_dependent_expr_internal(tree expr,tsubst_flags_t complain)6259 instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
6260 {
6261   return tsubst_copy_and_build (expr,
6262 				/*args=*/NULL_TREE,
6263 				complain,
6264 				/*in_decl=*/NULL_TREE,
6265 				/*function_p=*/false,
6266 				/*integral_constant_expression_p=*/true);
6267 }
6268 
6269 /* Simplify EXPR if it is a non-dependent expression.  Returns the
6270    (possibly simplified) expression.  */
6271 
6272 tree
instantiate_non_dependent_expr_sfinae(tree expr,tsubst_flags_t complain)6273 instantiate_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
6274 {
6275   if (expr == NULL_TREE)
6276     return NULL_TREE;
6277 
6278   /* If we're in a template, but EXPR isn't value dependent, simplify
6279      it.  We're supposed to treat:
6280 
6281        template <typename T> void f(T[1 + 1]);
6282        template <typename T> void f(T[2]);
6283 
6284      as two declarations of the same function, for example.  */
6285   if (processing_template_decl
6286       && is_nondependent_constant_expression (expr))
6287     {
6288       processing_template_decl_sentinel s;
6289       expr = instantiate_non_dependent_expr_internal (expr, complain);
6290     }
6291   return expr;
6292 }
6293 
6294 tree
instantiate_non_dependent_expr(tree expr)6295 instantiate_non_dependent_expr (tree expr)
6296 {
6297   return instantiate_non_dependent_expr_sfinae (expr, tf_error);
6298 }
6299 
6300 /* Like instantiate_non_dependent_expr, but return NULL_TREE rather than
6301    an uninstantiated expression.  */
6302 
6303 tree
instantiate_non_dependent_or_null(tree expr)6304 instantiate_non_dependent_or_null (tree expr)
6305 {
6306   if (expr == NULL_TREE)
6307     return NULL_TREE;
6308   if (processing_template_decl)
6309     {
6310       if (!is_nondependent_constant_expression (expr))
6311 	expr = NULL_TREE;
6312       else
6313 	{
6314 	  processing_template_decl_sentinel s;
6315 	  expr = instantiate_non_dependent_expr_internal (expr, tf_error);
6316 	}
6317     }
6318   return expr;
6319 }
6320 
6321 /* True iff T is a specialization of a variable template.  */
6322 
6323 bool
variable_template_specialization_p(tree t)6324 variable_template_specialization_p (tree t)
6325 {
6326   if (!VAR_P (t) || !DECL_LANG_SPECIFIC (t) || !DECL_TEMPLATE_INFO (t))
6327     return false;
6328   tree tmpl = DECL_TI_TEMPLATE (t);
6329   return variable_template_p (tmpl);
6330 }
6331 
6332 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
6333    template declaration, or a TYPE_DECL for an alias declaration.  */
6334 
6335 bool
alias_type_or_template_p(tree t)6336 alias_type_or_template_p (tree t)
6337 {
6338   if (t == NULL_TREE)
6339     return false;
6340   return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
6341 	  || (TYPE_P (t)
6342 	      && TYPE_NAME (t)
6343 	      && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
6344 	  || DECL_ALIAS_TEMPLATE_P (t));
6345 }
6346 
6347 /* If T is a specialization of an alias template, return it; otherwise return
6348    NULL_TREE.  If TRANSPARENT_TYPEDEFS is true, look through other aliases.  */
6349 
6350 tree
alias_template_specialization_p(const_tree t,bool transparent_typedefs)6351 alias_template_specialization_p (const_tree t,
6352 				 bool transparent_typedefs)
6353 {
6354   if (!TYPE_P (t))
6355     return NULL_TREE;
6356 
6357   /* It's an alias template specialization if it's an alias and its
6358      TYPE_NAME is a specialization of a primary template.  */
6359   if (typedef_variant_p (t))
6360     {
6361       if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
6362 	if (PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo)))
6363 	  return CONST_CAST_TREE (t);
6364       if (transparent_typedefs)
6365 	return alias_template_specialization_p (DECL_ORIGINAL_TYPE
6366 						(TYPE_NAME (t)),
6367 						transparent_typedefs);
6368     }
6369 
6370   return NULL_TREE;
6371 }
6372 
6373 /* An alias template is complex from a SFINAE perspective if a template-id
6374    using that alias can be ill-formed when the expansion is not, as with
6375    the void_t template.  We determine this by checking whether the
6376    expansion for the alias template uses all its template parameters.  */
6377 
6378 struct uses_all_template_parms_data
6379 {
6380   int level;
6381   bool *seen;
6382 };
6383 
6384 static int
uses_all_template_parms_r(tree t,void * data_)6385 uses_all_template_parms_r (tree t, void *data_)
6386 {
6387   struct uses_all_template_parms_data &data
6388     = *(struct uses_all_template_parms_data*)data_;
6389   tree idx = get_template_parm_index (t);
6390 
6391   if (TEMPLATE_PARM_LEVEL (idx) == data.level)
6392     data.seen[TEMPLATE_PARM_IDX (idx)] = true;
6393   return 0;
6394 }
6395 
6396 /* for_each_template_parm any_fn callback for complex_alias_template_p.  */
6397 
6398 static int
complex_pack_expansion_r(tree t,void * data_)6399 complex_pack_expansion_r (tree t, void *data_)
6400 {
6401   /* An alias template with a pack expansion that expands a pack from the
6402      enclosing class needs to be considered complex, to avoid confusion with
6403      the same pack being used as an argument to the alias's own template
6404      parameter (91966).  */
6405   if (!PACK_EXPANSION_P (t))
6406     return 0;
6407   struct uses_all_template_parms_data &data
6408     = *(struct uses_all_template_parms_data*)data_;
6409   for (tree pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
6410        pack = TREE_CHAIN (pack))
6411     {
6412       tree parm_pack = TREE_VALUE (pack);
6413       if (!TEMPLATE_PARM_P (parm_pack))
6414 	continue;
6415       int idx, level;
6416       template_parm_level_and_index (parm_pack, &level, &idx);
6417       if (level < data.level)
6418 	return 1;
6419     }
6420   return 0;
6421 }
6422 
6423 static bool
complex_alias_template_p(const_tree tmpl)6424 complex_alias_template_p (const_tree tmpl)
6425 {
6426   /* A renaming alias isn't complex.  */
6427   if (get_underlying_template (CONST_CAST_TREE (tmpl)) != tmpl)
6428     return false;
6429 
6430   /* Any other constrained alias is complex.  */
6431   if (get_constraints (tmpl))
6432     return true;
6433 
6434   struct uses_all_template_parms_data data;
6435   tree pat = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6436   tree parms = DECL_TEMPLATE_PARMS (tmpl);
6437   data.level = TMPL_PARMS_DEPTH (parms);
6438   int len = TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS (parms));
6439   data.seen = XALLOCAVEC (bool, len);
6440   for (int i = 0; i < len; ++i)
6441     data.seen[i] = false;
6442 
6443   if (for_each_template_parm (pat, uses_all_template_parms_r, &data,
6444 			      NULL, true, complex_pack_expansion_r))
6445     return true;
6446   for (int i = 0; i < len; ++i)
6447     if (!data.seen[i])
6448       return true;
6449   return false;
6450 }
6451 
6452 /* If T is a specialization of a complex alias template with dependent
6453    template-arguments, return it; otherwise return NULL_TREE.  If T is a
6454    typedef to such a specialization, return the specialization.  */
6455 
6456 tree
dependent_alias_template_spec_p(const_tree t,bool transparent_typedefs)6457 dependent_alias_template_spec_p (const_tree t, bool transparent_typedefs)
6458 {
6459   if (!TYPE_P (t) || !typedef_variant_p (t))
6460     return NULL_TREE;
6461 
6462   tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t);
6463   if (tinfo
6464       && TEMPLATE_DECL_COMPLEX_ALIAS_P (TI_TEMPLATE (tinfo))
6465       && (any_dependent_template_arguments_p
6466 	  (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)))))
6467     return CONST_CAST_TREE (t);
6468 
6469   if (transparent_typedefs)
6470     {
6471       tree utype = DECL_ORIGINAL_TYPE (TYPE_NAME (t));
6472       return dependent_alias_template_spec_p (utype, transparent_typedefs);
6473     }
6474 
6475   return NULL_TREE;
6476 }
6477 
6478 /* Return the number of innermost template parameters in TMPL.  */
6479 
6480 static int
num_innermost_template_parms(const_tree tmpl)6481 num_innermost_template_parms (const_tree tmpl)
6482 {
6483   tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6484   return TREE_VEC_LENGTH (parms);
6485 }
6486 
6487 /* Return either TMPL or another template that it is equivalent to under DR
6488    1286: An alias that just changes the name of a template is equivalent to
6489    the other template.  */
6490 
6491 static tree
get_underlying_template(tree tmpl)6492 get_underlying_template (tree tmpl)
6493 {
6494   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
6495   while (DECL_ALIAS_TEMPLATE_P (tmpl))
6496     {
6497       /* Determine if the alias is equivalent to an underlying template.  */
6498       tree orig_type = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6499       /* The underlying type may have been ill-formed. Don't proceed.  */
6500       if (!orig_type)
6501 	break;
6502       tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (orig_type);
6503       if (!tinfo)
6504 	break;
6505 
6506       tree underlying = TI_TEMPLATE (tinfo);
6507       if (!PRIMARY_TEMPLATE_P (underlying)
6508 	  || (num_innermost_template_parms (tmpl)
6509 	      != num_innermost_template_parms (underlying)))
6510 	break;
6511 
6512       tree alias_args = INNERMOST_TEMPLATE_ARGS (generic_targs_for (tmpl));
6513       if (!comp_template_args (TI_ARGS (tinfo), alias_args))
6514 	break;
6515 
6516       /* If TMPL adds or changes any constraints, it isn't equivalent.  I think
6517 	 it's appropriate to treat a less-constrained alias as equivalent.  */
6518       if (!at_least_as_constrained (underlying, tmpl))
6519 	break;
6520 
6521       /* Alias is equivalent.  Strip it and repeat.  */
6522       tmpl = underlying;
6523     }
6524 
6525   return tmpl;
6526 }
6527 
6528 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
6529    must be a reference-to-function or a pointer-to-function type, as specified
6530    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
6531    and check that the resulting function has external linkage.  */
6532 
6533 static tree
convert_nontype_argument_function(tree type,tree expr,tsubst_flags_t complain)6534 convert_nontype_argument_function (tree type, tree expr,
6535 				   tsubst_flags_t complain)
6536 {
6537   tree fns = expr;
6538   tree fn, fn_no_ptr;
6539   linkage_kind linkage;
6540 
6541   fn = instantiate_type (type, fns, tf_none);
6542   if (fn == error_mark_node)
6543     return error_mark_node;
6544 
6545   if (value_dependent_expression_p (fn))
6546     goto accept;
6547 
6548   fn_no_ptr = strip_fnptr_conv (fn);
6549   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
6550     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6551   if (BASELINK_P (fn_no_ptr))
6552     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
6553 
6554   /* [temp.arg.nontype]/1
6555 
6556      A template-argument for a non-type, non-template template-parameter
6557      shall be one of:
6558      [...]
6559      -- the address of an object or function with external [C++11: or
6560         internal] linkage.  */
6561 
6562   STRIP_ANY_LOCATION_WRAPPER (fn_no_ptr);
6563   if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
6564     {
6565       if (complain & tf_error)
6566 	{
6567 	  location_t loc = cp_expr_loc_or_input_loc (expr);
6568 	  error_at (loc, "%qE is not a valid template argument for type %qT",
6569 		    expr, type);
6570 	  if (TYPE_PTR_P (type))
6571 	    inform (loc, "it must be the address of a function "
6572 		    "with external linkage");
6573 	  else
6574 	    inform (loc, "it must be the name of a function with "
6575 		    "external linkage");
6576 	}
6577       return NULL_TREE;
6578     }
6579 
6580   linkage = decl_linkage (fn_no_ptr);
6581   if (cxx_dialect >= cxx11 ? linkage == lk_none : linkage != lk_external)
6582     {
6583       if (complain & tf_error)
6584 	{
6585 	  location_t loc = cp_expr_loc_or_input_loc (expr);
6586 	  if (cxx_dialect >= cxx11)
6587 	    error_at (loc, "%qE is not a valid template argument for type "
6588 		      "%qT because %qD has no linkage",
6589 		      expr, type, fn_no_ptr);
6590 	  else
6591 	    error_at (loc, "%qE is not a valid template argument for type "
6592 		      "%qT because %qD does not have external linkage",
6593 		      expr, type, fn_no_ptr);
6594 	}
6595       return NULL_TREE;
6596     }
6597 
6598  accept:
6599   if (TYPE_REF_P (type))
6600     {
6601       if (REFERENCE_REF_P (fn))
6602 	fn = TREE_OPERAND (fn, 0);
6603       else
6604 	fn = build_address (fn);
6605     }
6606   if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (fn)))
6607     fn = build_nop (type, fn);
6608 
6609   return fn;
6610 }
6611 
6612 /* Subroutine of convert_nontype_argument.
6613    Check if EXPR of type TYPE is a valid pointer-to-member constant.
6614    Emit an error otherwise.  */
6615 
6616 static bool
check_valid_ptrmem_cst_expr(tree type,tree expr,tsubst_flags_t complain)6617 check_valid_ptrmem_cst_expr (tree type, tree expr,
6618 			     tsubst_flags_t complain)
6619 {
6620   tree orig_expr = expr;
6621   STRIP_NOPS (expr);
6622   if (null_ptr_cst_p (expr))
6623     return true;
6624   if (TREE_CODE (expr) == PTRMEM_CST
6625       && same_type_p (TYPE_PTRMEM_CLASS_TYPE (type),
6626 		      PTRMEM_CST_CLASS (expr)))
6627     return true;
6628   if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
6629     return true;
6630   if (processing_template_decl
6631       && TREE_CODE (expr) == ADDR_EXPR
6632       && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
6633     return true;
6634   if (complain & tf_error)
6635     {
6636       location_t loc = cp_expr_loc_or_input_loc (orig_expr);
6637       error_at (loc, "%qE is not a valid template argument for type %qT",
6638 		orig_expr, type);
6639       if (TREE_CODE (expr) != PTRMEM_CST)
6640 	inform (loc, "it must be a pointer-to-member of the form %<&X::Y%>");
6641       else
6642 	inform (loc, "because it is a member of %qT", PTRMEM_CST_CLASS (expr));
6643     }
6644   return false;
6645 }
6646 
6647 /* Returns TRUE iff the address of OP is value-dependent.
6648 
6649    14.6.2.4 [temp.dep.temp]:
6650    A non-integral non-type template-argument is dependent if its type is
6651    dependent or it has either of the following forms
6652      qualified-id
6653      & qualified-id
6654    and contains a nested-name-specifier which specifies a class-name that
6655    names a dependent type.
6656 
6657    We generalize this to just say that the address of a member of a
6658    dependent class is value-dependent; the above doesn't cover the
6659    address of a static data member named with an unqualified-id.  */
6660 
6661 static bool
has_value_dependent_address(tree op)6662 has_value_dependent_address (tree op)
6663 {
6664   STRIP_ANY_LOCATION_WRAPPER (op);
6665 
6666   /* We could use get_inner_reference here, but there's no need;
6667      this is only relevant for template non-type arguments, which
6668      can only be expressed as &id-expression.  */
6669   if (DECL_P (op))
6670     {
6671       tree ctx = CP_DECL_CONTEXT (op);
6672       if (TYPE_P (ctx) && dependent_type_p (ctx))
6673 	return true;
6674     }
6675 
6676   return false;
6677 }
6678 
6679 /* The next set of functions are used for providing helpful explanatory
6680    diagnostics for failed overload resolution.  Their messages should be
6681    indented by two spaces for consistency with the messages in
6682    call.c  */
6683 
6684 static int
unify_success(bool)6685 unify_success (bool /*explain_p*/)
6686 {
6687   return 0;
6688 }
6689 
6690 /* Other failure functions should call this one, to provide a single function
6691    for setting a breakpoint on.  */
6692 
6693 static int
unify_invalid(bool)6694 unify_invalid (bool /*explain_p*/)
6695 {
6696   return 1;
6697 }
6698 
6699 static int
unify_parameter_deduction_failure(bool explain_p,tree parm)6700 unify_parameter_deduction_failure (bool explain_p, tree parm)
6701 {
6702   if (explain_p)
6703     inform (input_location,
6704 	    "  couldn%'t deduce template parameter %qD", parm);
6705   return unify_invalid (explain_p);
6706 }
6707 
6708 static int
unify_cv_qual_mismatch(bool explain_p,tree parm,tree arg)6709 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
6710 {
6711   if (explain_p)
6712     inform (input_location,
6713 	    "  types %qT and %qT have incompatible cv-qualifiers",
6714 	    parm, arg);
6715   return unify_invalid (explain_p);
6716 }
6717 
6718 static int
unify_type_mismatch(bool explain_p,tree parm,tree arg)6719 unify_type_mismatch (bool explain_p, tree parm, tree arg)
6720 {
6721   if (explain_p)
6722     inform (input_location, "  mismatched types %qT and %qT", parm, arg);
6723   return unify_invalid (explain_p);
6724 }
6725 
6726 static int
unify_parameter_pack_mismatch(bool explain_p,tree parm,tree arg)6727 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
6728 {
6729   if (explain_p)
6730     inform (input_location,
6731 	    "  template parameter %qD is not a parameter pack, but "
6732 	    "argument %qD is",
6733 	    parm, arg);
6734   return unify_invalid (explain_p);
6735 }
6736 
6737 static int
unify_ptrmem_cst_mismatch(bool explain_p,tree parm,tree arg)6738 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
6739 {
6740   if (explain_p)
6741     inform (input_location,
6742 	    "  template argument %qE does not match "
6743 	    "pointer-to-member constant %qE",
6744 	    arg, parm);
6745   return unify_invalid (explain_p);
6746 }
6747 
6748 static int
unify_expression_unequal(bool explain_p,tree parm,tree arg)6749 unify_expression_unequal (bool explain_p, tree parm, tree arg)
6750 {
6751   if (explain_p)
6752     inform (input_location, "  %qE is not equivalent to %qE", parm, arg);
6753   return unify_invalid (explain_p);
6754 }
6755 
6756 static int
unify_parameter_pack_inconsistent(bool explain_p,tree old_arg,tree new_arg)6757 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
6758 {
6759   if (explain_p)
6760     inform (input_location,
6761 	    "  inconsistent parameter pack deduction with %qT and %qT",
6762 	    old_arg, new_arg);
6763   return unify_invalid (explain_p);
6764 }
6765 
6766 static int
unify_inconsistency(bool explain_p,tree parm,tree first,tree second)6767 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
6768 {
6769   if (explain_p)
6770     {
6771       if (TYPE_P (parm))
6772 	inform (input_location,
6773 		"  deduced conflicting types for parameter %qT (%qT and %qT)",
6774 		parm, first, second);
6775       else
6776 	inform (input_location,
6777 		"  deduced conflicting values for non-type parameter "
6778 		"%qE (%qE and %qE)", parm, first, second);
6779     }
6780   return unify_invalid (explain_p);
6781 }
6782 
6783 static int
unify_vla_arg(bool explain_p,tree arg)6784 unify_vla_arg (bool explain_p, tree arg)
6785 {
6786   if (explain_p)
6787     inform (input_location,
6788 	    "  variable-sized array type %qT is not "
6789 	    "a valid template argument",
6790 	    arg);
6791   return unify_invalid (explain_p);
6792 }
6793 
6794 static int
unify_method_type_error(bool explain_p,tree arg)6795 unify_method_type_error (bool explain_p, tree arg)
6796 {
6797   if (explain_p)
6798     inform (input_location,
6799 	    "  member function type %qT is not a valid template argument",
6800 	    arg);
6801   return unify_invalid (explain_p);
6802 }
6803 
6804 static int
6805 unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
6806 {
6807   if (explain_p)
6808     {
6809       if (least_p)
6810 	inform_n (input_location, wanted,
6811 		  "  candidate expects at least %d argument, %d provided",
6812 		  "  candidate expects at least %d arguments, %d provided",
6813 		  wanted, have);
6814       else
6815 	inform_n (input_location, wanted,
6816 		  "  candidate expects %d argument, %d provided",
6817 		  "  candidate expects %d arguments, %d provided",
6818 		  wanted, have);
6819     }
6820   return unify_invalid (explain_p);
6821 }
6822 
6823 static int
unify_too_many_arguments(bool explain_p,int have,int wanted)6824 unify_too_many_arguments (bool explain_p, int have, int wanted)
6825 {
6826   return unify_arity (explain_p, have, wanted);
6827 }
6828 
6829 static int
6830 unify_too_few_arguments (bool explain_p, int have, int wanted,
6831 			 bool least_p = false)
6832 {
6833   return unify_arity (explain_p, have, wanted, least_p);
6834 }
6835 
6836 static int
unify_arg_conversion(bool explain_p,tree to_type,tree from_type,tree arg)6837 unify_arg_conversion (bool explain_p, tree to_type,
6838 		      tree from_type, tree arg)
6839 {
6840   if (explain_p)
6841     inform (cp_expr_loc_or_input_loc (arg),
6842 	    "  cannot convert %qE (type %qT) to type %qT",
6843 	    arg, from_type, to_type);
6844   return unify_invalid (explain_p);
6845 }
6846 
6847 static int
unify_no_common_base(bool explain_p,enum template_base_result r,tree parm,tree arg)6848 unify_no_common_base (bool explain_p, enum template_base_result r,
6849 		      tree parm, tree arg)
6850 {
6851   if (explain_p)
6852     switch (r)
6853       {
6854       case tbr_ambiguous_baseclass:
6855 	inform (input_location, "  %qT is an ambiguous base class of %qT",
6856 		parm, arg);
6857 	break;
6858       default:
6859 	inform (input_location, "  %qT is not derived from %qT", arg, parm);
6860 	break;
6861       }
6862   return unify_invalid (explain_p);
6863 }
6864 
6865 static int
unify_inconsistent_template_template_parameters(bool explain_p)6866 unify_inconsistent_template_template_parameters (bool explain_p)
6867 {
6868   if (explain_p)
6869     inform (input_location,
6870 	    "  template parameters of a template template argument are "
6871 	    "inconsistent with other deduced template arguments");
6872   return unify_invalid (explain_p);
6873 }
6874 
6875 static int
unify_template_deduction_failure(bool explain_p,tree parm,tree arg)6876 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
6877 {
6878   if (explain_p)
6879     inform (input_location,
6880 	    "  cannot deduce a template for %qT from non-template type %qT",
6881 	    parm, arg);
6882   return unify_invalid (explain_p);
6883 }
6884 
6885 static int
unify_template_argument_mismatch(bool explain_p,tree parm,tree arg)6886 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
6887 {
6888   if (explain_p)
6889     inform (input_location,
6890 	    "  template argument %qE does not match %qE", arg, parm);
6891   return unify_invalid (explain_p);
6892 }
6893 
6894 /* True if T is a C++20 template parameter object to store the argument for a
6895    template parameter of class type.  */
6896 
6897 bool
template_parm_object_p(const_tree t)6898 template_parm_object_p (const_tree t)
6899 {
6900   return (TREE_CODE (t) == VAR_DECL && DECL_ARTIFICIAL (t) && DECL_NAME (t)
6901 	  && !strncmp (IDENTIFIER_POINTER (DECL_NAME (t)), "_ZTA", 4));
6902 }
6903 
6904 /* Subroutine of convert_nontype_argument, to check whether EXPR, as an
6905    argument for TYPE, points to an unsuitable object.  */
6906 
6907 static bool
invalid_tparm_referent_p(tree type,tree expr,tsubst_flags_t complain)6908 invalid_tparm_referent_p (tree type, tree expr, tsubst_flags_t complain)
6909 {
6910   switch (TREE_CODE (expr))
6911     {
6912     CASE_CONVERT:
6913       return invalid_tparm_referent_p (type, TREE_OPERAND (expr, 0),
6914 				       complain);
6915 
6916     case TARGET_EXPR:
6917       return invalid_tparm_referent_p (type, TARGET_EXPR_INITIAL (expr),
6918 				       complain);
6919 
6920     case CONSTRUCTOR:
6921       {
6922 	unsigned i; tree elt;
6923 	FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expr), i, elt)
6924 	  if (invalid_tparm_referent_p (TREE_TYPE (elt), elt, complain))
6925 	    return true;
6926       }
6927       break;
6928 
6929     case ADDR_EXPR:
6930       {
6931 	tree decl = TREE_OPERAND (expr, 0);
6932 
6933 	if (!VAR_P (decl))
6934 	  {
6935 	    if (complain & tf_error)
6936 	      error_at (cp_expr_loc_or_input_loc (expr),
6937 			"%qE is not a valid template argument of type %qT "
6938 			"because %qE is not a variable", expr, type, decl);
6939 	    return true;
6940 	  }
6941 	else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
6942 	  {
6943 	    if (complain & tf_error)
6944 	      error_at (cp_expr_loc_or_input_loc (expr),
6945 			"%qE is not a valid template argument of type %qT "
6946 			"in C++98 because %qD does not have external linkage",
6947 			expr, type, decl);
6948 	    return true;
6949 	  }
6950 	else if ((cxx_dialect >= cxx11 && cxx_dialect < cxx17)
6951 		 && decl_linkage (decl) == lk_none)
6952 	  {
6953 	    if (complain & tf_error)
6954 	      error_at (cp_expr_loc_or_input_loc (expr),
6955 			"%qE is not a valid template argument of type %qT "
6956 			"because %qD has no linkage", expr, type, decl);
6957 	    return true;
6958 	  }
6959 	/* C++17: For a non-type template-parameter of reference or pointer
6960 	   type, the value of the constant expression shall not refer to (or
6961 	   for a pointer type, shall not be the address of):
6962 	   * a subobject (4.5),
6963 	   * a temporary object (15.2),
6964 	   * a string literal (5.13.5),
6965 	   * the result of a typeid expression (8.2.8), or
6966 	   * a predefined __func__ variable (11.4.1).  */
6967 	else if (DECL_ARTIFICIAL (decl))
6968 	  {
6969 	    if (complain & tf_error)
6970 	      error ("the address of %qD is not a valid template argument",
6971 		     decl);
6972 	    return true;
6973 	  }
6974 	else if (!same_type_ignoring_top_level_qualifiers_p
6975 		 (strip_array_types (TREE_TYPE (type)),
6976 		  strip_array_types (TREE_TYPE (decl))))
6977 	  {
6978 	    if (complain & tf_error)
6979 	      error ("the address of the %qT subobject of %qD is not a "
6980 		     "valid template argument", TREE_TYPE (type), decl);
6981 	    return true;
6982 	  }
6983 	else if (!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
6984 	  {
6985 	    if (complain & tf_error)
6986 	      error ("the address of %qD is not a valid template argument "
6987 		     "because it does not have static storage duration",
6988 		     decl);
6989 	    return true;
6990 	  }
6991       }
6992       break;
6993 
6994     default:
6995       if (!INDIRECT_TYPE_P (type))
6996 	/* We're only concerned about pointers and references here.  */;
6997       else if (cxx_dialect >= cxx11 && integer_zerop (expr))
6998 	/* Null pointer values are OK in C++11.  */;
6999       else
7000 	{
7001 	  if (VAR_P (expr))
7002 	    {
7003 	      if (complain & tf_error)
7004 		error ("%qD is not a valid template argument "
7005 		       "because %qD is a variable, not the address of "
7006 		       "a variable", expr, expr);
7007 	      return true;
7008 	    }
7009 	  else
7010 	    {
7011 	      if (complain & tf_error)
7012 		error ("%qE is not a valid template argument for %qT "
7013 		       "because it is not the address of a variable",
7014 		       expr, type);
7015 	      return true;
7016 	    }
7017 	}
7018     }
7019   return false;
7020 
7021 }
7022 
7023 /* The template arguments corresponding to template parameter objects of types
7024    that contain pointers to members.  */
7025 
7026 static GTY(()) hash_map<tree, tree> *tparm_obj_values;
7027 
7028 /* Return a VAR_DECL for the C++20 template parameter object corresponding to
7029    template argument EXPR.  */
7030 
7031 static tree
get_template_parm_object(tree expr,tsubst_flags_t complain)7032 get_template_parm_object (tree expr, tsubst_flags_t complain)
7033 {
7034   if (TREE_CODE (expr) == TARGET_EXPR)
7035     expr = TARGET_EXPR_INITIAL (expr);
7036 
7037   if (!TREE_CONSTANT (expr))
7038     {
7039       if ((complain & tf_error)
7040 	  && require_rvalue_constant_expression (expr))
7041 	cxx_constant_value (expr);
7042       return error_mark_node;
7043     }
7044   if (invalid_tparm_referent_p (TREE_TYPE (expr), expr, complain))
7045     return error_mark_node;
7046 
7047   tree name = mangle_template_parm_object (expr);
7048   tree decl = get_global_binding (name);
7049   if (decl)
7050     return decl;
7051 
7052   tree type = cp_build_qualified_type (TREE_TYPE (expr), TYPE_QUAL_CONST);
7053   decl = create_temporary_var (type);
7054   TREE_STATIC (decl) = true;
7055   DECL_DECLARED_CONSTEXPR_P (decl) = true;
7056   TREE_READONLY (decl) = true;
7057   DECL_NAME (decl) = name;
7058   SET_DECL_ASSEMBLER_NAME (decl, name);
7059   DECL_CONTEXT (decl) = global_namespace;
7060   comdat_linkage (decl);
7061 
7062   if (!zero_init_p (type))
7063     {
7064       /* If EXPR contains any PTRMEM_CST, they will get clobbered by
7065 	 lower_var_init before we're done mangling.  So store the original
7066 	 value elsewhere.  */
7067       tree copy = unshare_constructor (expr);
7068       hash_map_safe_put<hm_ggc> (tparm_obj_values, decl, copy);
7069     }
7070 
7071   pushdecl_top_level_and_finish (decl, expr);
7072 
7073   return decl;
7074 }
7075 
7076 /* Return the actual template argument corresponding to template parameter
7077    object VAR.  */
7078 
7079 tree
tparm_object_argument(tree var)7080 tparm_object_argument (tree var)
7081 {
7082   if (zero_init_p (TREE_TYPE (var)))
7083     return DECL_INITIAL (var);
7084   return *(tparm_obj_values->get (var));
7085 }
7086 
7087 /* Attempt to convert the non-type template parameter EXPR to the
7088    indicated TYPE.  If the conversion is successful, return the
7089    converted value.  If the conversion is unsuccessful, return
7090    NULL_TREE if we issued an error message, or error_mark_node if we
7091    did not.  We issue error messages for out-and-out bad template
7092    parameters, but not simply because the conversion failed, since we
7093    might be just trying to do argument deduction.  Both TYPE and EXPR
7094    must be non-dependent.
7095 
7096    The conversion follows the special rules described in
7097    [temp.arg.nontype], and it is much more strict than an implicit
7098    conversion.
7099 
7100    This function is called twice for each template argument (see
7101    lookup_template_class for a more accurate description of this
7102    problem). This means that we need to handle expressions which
7103    are not valid in a C++ source, but can be created from the
7104    first call (for instance, casts to perform conversions). These
7105    hacks can go away after we fix the double coercion problem.  */
7106 
7107 static tree
convert_nontype_argument(tree type,tree expr,tsubst_flags_t complain)7108 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
7109 {
7110   tree expr_type;
7111   location_t loc = cp_expr_loc_or_input_loc (expr);
7112 
7113   /* Detect immediately string literals as invalid non-type argument.
7114      This special-case is not needed for correctness (we would easily
7115      catch this later), but only to provide better diagnostic for this
7116      common user mistake. As suggested by DR 100, we do not mention
7117      linkage issues in the diagnostic as this is not the point.  */
7118   if (TREE_CODE (expr) == STRING_CST && !CLASS_TYPE_P (type))
7119     {
7120       if (complain & tf_error)
7121 	error ("%qE is not a valid template argument for type %qT "
7122 	       "because string literals can never be used in this context",
7123 	       expr, type);
7124       return NULL_TREE;
7125     }
7126 
7127   /* Add the ADDR_EXPR now for the benefit of
7128      value_dependent_expression_p.  */
7129   if (TYPE_PTROBV_P (type)
7130       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
7131     {
7132       expr = decay_conversion (expr, complain);
7133       if (expr == error_mark_node)
7134 	return error_mark_node;
7135     }
7136 
7137   /* If we are in a template, EXPR may be non-dependent, but still
7138      have a syntactic, rather than semantic, form.  For example, EXPR
7139      might be a SCOPE_REF, rather than the VAR_DECL to which the
7140      SCOPE_REF refers.  Preserving the qualifying scope is necessary
7141      so that access checking can be performed when the template is
7142      instantiated -- but here we need the resolved form so that we can
7143      convert the argument.  */
7144   bool non_dep = false;
7145   if (TYPE_REF_OBJ_P (type)
7146       && has_value_dependent_address (expr))
7147     /* If we want the address and it's value-dependent, don't fold.  */;
7148   else if (processing_template_decl
7149 	   && is_nondependent_constant_expression (expr))
7150     non_dep = true;
7151   if (error_operand_p (expr))
7152     return error_mark_node;
7153   expr_type = TREE_TYPE (expr);
7154 
7155   /* If the argument is non-dependent, perform any conversions in
7156      non-dependent context as well.  */
7157   processing_template_decl_sentinel s (non_dep);
7158   if (non_dep)
7159     expr = instantiate_non_dependent_expr_internal (expr, complain);
7160 
7161   const bool val_dep_p = value_dependent_expression_p (expr);
7162   if (val_dep_p)
7163     expr = canonicalize_expr_argument (expr, complain);
7164 
7165   /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
7166      to a non-type argument of "nullptr".  */
7167   if (NULLPTR_TYPE_P (expr_type) && TYPE_PTR_OR_PTRMEM_P (type))
7168     expr = fold_simple (convert (type, expr));
7169 
7170   /* In C++11, integral or enumeration non-type template arguments can be
7171      arbitrary constant expressions.  Pointer and pointer to
7172      member arguments can be general constant expressions that evaluate
7173      to a null value, but otherwise still need to be of a specific form.  */
7174   if (cxx_dialect >= cxx11)
7175     {
7176       if (TREE_CODE (expr) == PTRMEM_CST && TYPE_PTRMEM_P (type))
7177 	/* A PTRMEM_CST is already constant, and a valid template
7178 	   argument for a parameter of pointer to member type, we just want
7179 	   to leave it in that form rather than lower it to a
7180 	   CONSTRUCTOR.  */;
7181       else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7182 	       || cxx_dialect >= cxx17)
7183 	{
7184 	  /* C++17: A template-argument for a non-type template-parameter shall
7185 	     be a converted constant expression (8.20) of the type of the
7186 	     template-parameter.  */
7187 	  expr = build_converted_constant_expr (type, expr, complain);
7188 	  if (expr == error_mark_node)
7189 	    /* Make sure we return NULL_TREE only if we have really issued
7190 	       an error, as described above.  */
7191 	    return (complain & tf_error) ? NULL_TREE : error_mark_node;
7192 	  else if (TREE_CODE (expr) == IMPLICIT_CONV_EXPR)
7193 	    {
7194 	      IMPLICIT_CONV_EXPR_NONTYPE_ARG (expr) = true;
7195 	      return expr;
7196 	    }
7197 	  expr = maybe_constant_value (expr, NULL_TREE,
7198 				       /*manifestly_const_eval=*/true);
7199 	  expr = convert_from_reference (expr);
7200 	}
7201       else if (TYPE_PTR_OR_PTRMEM_P (type))
7202 	{
7203 	  tree folded = maybe_constant_value (expr, NULL_TREE,
7204 					      /*manifestly_const_eval=*/true);
7205 	  if (TYPE_PTR_P (type) ? integer_zerop (folded)
7206 	      : null_member_pointer_value_p (folded))
7207 	    expr = folded;
7208 	}
7209     }
7210 
7211   if (TYPE_REF_P (type))
7212     expr = mark_lvalue_use (expr);
7213   else
7214     expr = mark_rvalue_use (expr);
7215 
7216   /* HACK: Due to double coercion, we can get a
7217      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
7218      which is the tree that we built on the first call (see
7219      below when coercing to reference to object or to reference to
7220      function). We just strip everything and get to the arg.
7221      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
7222      for examples.  */
7223   if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
7224     {
7225       tree probe_type, probe = expr;
7226       if (REFERENCE_REF_P (probe))
7227 	probe = TREE_OPERAND (probe, 0);
7228       probe_type = TREE_TYPE (probe);
7229       if (TREE_CODE (probe) == NOP_EXPR)
7230 	{
7231 	  /* ??? Maybe we could use convert_from_reference here, but we
7232 	     would need to relax its constraints because the NOP_EXPR
7233 	     could actually change the type to something more cv-qualified,
7234 	     and this is not folded by convert_from_reference.  */
7235 	  tree addr = TREE_OPERAND (probe, 0);
7236 	  if (TYPE_REF_P (probe_type)
7237 	      && TREE_CODE (addr) == ADDR_EXPR
7238 	      && TYPE_PTR_P (TREE_TYPE (addr))
7239 	      && (same_type_ignoring_top_level_qualifiers_p
7240 		  (TREE_TYPE (probe_type),
7241 		   TREE_TYPE (TREE_TYPE (addr)))))
7242 	    {
7243 	      expr = TREE_OPERAND (addr, 0);
7244 	      expr_type = TREE_TYPE (probe_type);
7245 	    }
7246 	}
7247     }
7248 
7249   /* [temp.arg.nontype]/5, bullet 1
7250 
7251      For a non-type template-parameter of integral or enumeration type,
7252      integral promotions (_conv.prom_) and integral conversions
7253      (_conv.integral_) are applied.  */
7254   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
7255     {
7256       if (cxx_dialect < cxx11)
7257 	{
7258 	  tree t = build_converted_constant_expr (type, expr, complain);
7259 	  t = maybe_constant_value (t);
7260 	  if (t != error_mark_node)
7261 	    expr = t;
7262 	}
7263 
7264       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
7265 	return error_mark_node;
7266 
7267       /* Notice that there are constant expressions like '4 % 0' which
7268 	 do not fold into integer constants.  */
7269       if (TREE_CODE (expr) != INTEGER_CST && !val_dep_p)
7270 	{
7271 	  if (complain & tf_error)
7272 	    {
7273 	      int errs = errorcount, warns = warningcount + werrorcount;
7274 	      if (!require_potential_constant_expression (expr))
7275 		expr = error_mark_node;
7276 	      else
7277 		expr = cxx_constant_value (expr);
7278 	      if (errorcount > errs || warningcount + werrorcount > warns)
7279 		inform (loc, "in template argument for type %qT", type);
7280 	      if (expr == error_mark_node)
7281 		return NULL_TREE;
7282 	      /* else cxx_constant_value complained but gave us
7283 		 a real constant, so go ahead.  */
7284 	      if (TREE_CODE (expr) != INTEGER_CST)
7285 		{
7286 		  /* Some assemble time constant expressions like
7287 		     (intptr_t)&&lab1 - (intptr_t)&&lab2 or
7288 		     4 + (intptr_t)&&var satisfy reduced_constant_expression_p
7289 		     as we can emit them into .rodata initializers of
7290 		     variables, yet they can't fold into an INTEGER_CST at
7291 		     compile time.  Refuse them here.  */
7292 		  gcc_checking_assert (reduced_constant_expression_p (expr));
7293 		  error_at (loc, "template argument %qE for type %qT not "
7294 				 "a constant integer", expr, type);
7295 		  return NULL_TREE;
7296 		}
7297 	    }
7298 	  else
7299 	    return NULL_TREE;
7300 	}
7301 
7302       /* Avoid typedef problems.  */
7303       if (TREE_TYPE (expr) != type)
7304 	expr = fold_convert (type, expr);
7305     }
7306   /* [temp.arg.nontype]/5, bullet 2
7307 
7308      For a non-type template-parameter of type pointer to object,
7309      qualification conversions (_conv.qual_) and the array-to-pointer
7310      conversion (_conv.array_) are applied.  */
7311   else if (TYPE_PTROBV_P (type))
7312     {
7313       tree decayed = expr;
7314 
7315       /* Look through any NOP_EXPRs around an ADDR_EXPR, whether they come from
7316 	 decay_conversion or an explicit cast.  If it's a problematic cast,
7317 	 we'll complain about it below.  */
7318       if (TREE_CODE (expr) == NOP_EXPR)
7319 	{
7320 	  tree probe = expr;
7321 	  STRIP_NOPS (probe);
7322 	  if (TREE_CODE (probe) == ADDR_EXPR
7323 	      && TYPE_PTR_P (TREE_TYPE (probe)))
7324 	    {
7325 	      expr = probe;
7326 	      expr_type = TREE_TYPE (expr);
7327 	    }
7328 	}
7329 
7330       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
7331 
7332 	 A template-argument for a non-type, non-template template-parameter
7333 	 shall be one of: [...]
7334 
7335 	 -- the name of a non-type template-parameter;
7336 	 -- the address of an object or function with external linkage, [...]
7337 	    expressed as "& id-expression" where the & is optional if the name
7338 	    refers to a function or array, or if the corresponding
7339 	    template-parameter is a reference.
7340 
7341 	Here, we do not care about functions, as they are invalid anyway
7342 	for a parameter of type pointer-to-object.  */
7343 
7344       if (val_dep_p)
7345 	/* Non-type template parameters are OK.  */
7346 	;
7347       else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7348 	/* Null pointer values are OK in C++11.  */;
7349       else if (TREE_CODE (expr) != ADDR_EXPR
7350 	       && !INDIRECT_TYPE_P (expr_type))
7351 	/* Other values, like integer constants, might be valid
7352 	   non-type arguments of some other type.  */
7353 	return error_mark_node;
7354       else if (invalid_tparm_referent_p (type, expr, complain))
7355 	return NULL_TREE;
7356 
7357       expr = decayed;
7358 
7359       expr = perform_qualification_conversions (type, expr);
7360       if (expr == error_mark_node)
7361 	return error_mark_node;
7362     }
7363   /* [temp.arg.nontype]/5, bullet 3
7364 
7365      For a non-type template-parameter of type reference to object, no
7366      conversions apply. The type referred to by the reference may be more
7367      cv-qualified than the (otherwise identical) type of the
7368      template-argument. The template-parameter is bound directly to the
7369      template-argument, which must be an lvalue.  */
7370   else if (TYPE_REF_OBJ_P (type))
7371     {
7372       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
7373 						      expr_type))
7374 	return error_mark_node;
7375 
7376       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
7377 	{
7378 	  if (complain & tf_error)
7379 	    error ("%qE is not a valid template argument for type %qT "
7380 		   "because of conflicts in cv-qualification", expr, type);
7381 	  return NULL_TREE;
7382 	}
7383 
7384       if (!lvalue_p (expr))
7385 	{
7386 	  if (complain & tf_error)
7387 	    error ("%qE is not a valid template argument for type %qT "
7388 		   "because it is not an lvalue", expr, type);
7389 	  return NULL_TREE;
7390 	}
7391 
7392       /* [temp.arg.nontype]/1
7393 
7394 	 A template-argument for a non-type, non-template template-parameter
7395 	 shall be one of: [...]
7396 
7397 	 -- the address of an object or function with external linkage.  */
7398       if (INDIRECT_REF_P (expr)
7399 	  && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
7400 	{
7401 	  expr = TREE_OPERAND (expr, 0);
7402 	  if (DECL_P (expr))
7403 	    {
7404 	      if (complain & tf_error)
7405 		error ("%q#D is not a valid template argument for type %qT "
7406 		       "because a reference variable does not have a constant "
7407 		       "address", expr, type);
7408 	      return NULL_TREE;
7409 	    }
7410 	}
7411 
7412       if (TYPE_REF_OBJ_P (TREE_TYPE (expr)) && val_dep_p)
7413 	/* OK, dependent reference.  We don't want to ask whether a DECL is
7414 	   itself value-dependent, since what we want here is its address.  */;
7415       else
7416 	{
7417 	  expr = build_address (expr);
7418 
7419 	  if (invalid_tparm_referent_p (type, expr, complain))
7420 	    return NULL_TREE;
7421 	}
7422 
7423       if (!same_type_p (type, TREE_TYPE (expr)))
7424 	expr = build_nop (type, expr);
7425     }
7426   /* [temp.arg.nontype]/5, bullet 4
7427 
7428      For a non-type template-parameter of type pointer to function, only
7429      the function-to-pointer conversion (_conv.func_) is applied. If the
7430      template-argument represents a set of overloaded functions (or a
7431      pointer to such), the matching function is selected from the set
7432      (_over.over_).  */
7433   else if (TYPE_PTRFN_P (type))
7434     {
7435       /* If the argument is a template-id, we might not have enough
7436 	 context information to decay the pointer.  */
7437       if (!type_unknown_p (expr_type))
7438 	{
7439 	  expr = decay_conversion (expr, complain);
7440 	  if (expr == error_mark_node)
7441 	    return error_mark_node;
7442 	}
7443 
7444       if (cxx_dialect >= cxx11 && integer_zerop (expr))
7445 	/* Null pointer values are OK in C++11.  */
7446 	return perform_qualification_conversions (type, expr);
7447 
7448       expr = convert_nontype_argument_function (type, expr, complain);
7449       if (!expr || expr == error_mark_node)
7450 	return expr;
7451     }
7452   /* [temp.arg.nontype]/5, bullet 5
7453 
7454      For a non-type template-parameter of type reference to function, no
7455      conversions apply. If the template-argument represents a set of
7456      overloaded functions, the matching function is selected from the set
7457      (_over.over_).  */
7458   else if (TYPE_REFFN_P (type))
7459     {
7460       if (TREE_CODE (expr) == ADDR_EXPR)
7461 	{
7462 	  if (complain & tf_error)
7463 	    {
7464 	      error ("%qE is not a valid template argument for type %qT "
7465 		     "because it is a pointer", expr, type);
7466 	      inform (input_location, "try using %qE instead",
7467 		      TREE_OPERAND (expr, 0));
7468 	    }
7469 	  return NULL_TREE;
7470 	}
7471 
7472       expr = convert_nontype_argument_function (type, expr, complain);
7473       if (!expr || expr == error_mark_node)
7474 	return expr;
7475     }
7476   /* [temp.arg.nontype]/5, bullet 6
7477 
7478      For a non-type template-parameter of type pointer to member function,
7479      no conversions apply. If the template-argument represents a set of
7480      overloaded member functions, the matching member function is selected
7481      from the set (_over.over_).  */
7482   else if (TYPE_PTRMEMFUNC_P (type))
7483     {
7484       expr = instantiate_type (type, expr, tf_none);
7485       if (expr == error_mark_node)
7486 	return error_mark_node;
7487 
7488       /* [temp.arg.nontype] bullet 1 says the pointer to member
7489          expression must be a pointer-to-member constant.  */
7490       if (!val_dep_p
7491 	  && !check_valid_ptrmem_cst_expr (type, expr, complain))
7492 	return NULL_TREE;
7493 
7494       /* Repeated conversion can't deal with a conversion that turns PTRMEM_CST
7495 	 into a CONSTRUCTOR, so build up a new PTRMEM_CST instead.  */
7496       if (fnptr_conv_p (type, TREE_TYPE (expr)))
7497 	expr = make_ptrmem_cst (type, PTRMEM_CST_MEMBER (expr));
7498     }
7499   /* [temp.arg.nontype]/5, bullet 7
7500 
7501      For a non-type template-parameter of type pointer to data member,
7502      qualification conversions (_conv.qual_) are applied.  */
7503   else if (TYPE_PTRDATAMEM_P (type))
7504     {
7505       /* [temp.arg.nontype] bullet 1 says the pointer to member
7506          expression must be a pointer-to-member constant.  */
7507       if (!val_dep_p
7508 	  && !check_valid_ptrmem_cst_expr (type, expr, complain))
7509 	return NULL_TREE;
7510 
7511       expr = perform_qualification_conversions (type, expr);
7512       if (expr == error_mark_node)
7513 	return expr;
7514     }
7515   else if (NULLPTR_TYPE_P (type))
7516     {
7517       if (!NULLPTR_TYPE_P (TREE_TYPE (expr)))
7518 	{
7519 	  if (complain & tf_error)
7520 	    error ("%qE is not a valid template argument for type %qT "
7521 		   "because it is of type %qT", expr, type, TREE_TYPE (expr));
7522 	  return NULL_TREE;
7523 	}
7524       return expr;
7525     }
7526   else if (CLASS_TYPE_P (type))
7527     {
7528       /* Replace the argument with a reference to the corresponding template
7529 	 parameter object.  */
7530       if (!val_dep_p)
7531 	expr = get_template_parm_object (expr, complain);
7532       if (expr == error_mark_node)
7533 	return NULL_TREE;
7534     }
7535   /* A template non-type parameter must be one of the above.  */
7536   else
7537     gcc_unreachable ();
7538 
7539   /* Sanity check: did we actually convert the argument to the
7540      right type?  */
7541   gcc_assert (same_type_ignoring_top_level_qualifiers_p
7542 	      (type, TREE_TYPE (expr)));
7543   return convert_from_reference (expr);
7544 }
7545 
7546 /* Subroutine of coerce_template_template_parms, which returns 1 if
7547    PARM_PARM and ARG_PARM match using the rule for the template
7548    parameters of template template parameters. Both PARM and ARG are
7549    template parameters; the rest of the arguments are the same as for
7550    coerce_template_template_parms.
7551  */
7552 static int
coerce_template_template_parm(tree parm,tree arg,tsubst_flags_t complain,tree in_decl,tree outer_args)7553 coerce_template_template_parm (tree parm,
7554                               tree arg,
7555                               tsubst_flags_t complain,
7556                               tree in_decl,
7557                               tree outer_args)
7558 {
7559   if (arg == NULL_TREE || error_operand_p (arg)
7560       || parm == NULL_TREE || error_operand_p (parm))
7561     return 0;
7562 
7563   if (TREE_CODE (arg) != TREE_CODE (parm))
7564     return 0;
7565 
7566   switch (TREE_CODE (parm))
7567     {
7568     case TEMPLATE_DECL:
7569       /* We encounter instantiations of templates like
7570 	 template <template <template <class> class> class TT>
7571 	 class C;  */
7572       {
7573 	tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
7574 	tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
7575 
7576 	if (!coerce_template_template_parms
7577 	    (parmparm, argparm, complain, in_decl, outer_args))
7578 	  return 0;
7579       }
7580       /* Fall through.  */
7581 
7582     case TYPE_DECL:
7583       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
7584 	  && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7585 	/* Argument is a parameter pack but parameter is not.  */
7586 	return 0;
7587       break;
7588 
7589     case PARM_DECL:
7590       /* The tsubst call is used to handle cases such as
7591 
7592            template <int> class C {};
7593 	   template <class T, template <T> class TT> class D {};
7594 	   D<int, C> d;
7595 
7596 	 i.e. the parameter list of TT depends on earlier parameters.  */
7597       if (!uses_template_parms (TREE_TYPE (arg)))
7598 	{
7599 	  tree t = tsubst (TREE_TYPE (parm), outer_args, complain, in_decl);
7600 	  if (!uses_template_parms (t)
7601 	      && !same_type_p (t, TREE_TYPE (arg)))
7602 	    return 0;
7603 	}
7604 
7605       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
7606 	  && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7607 	/* Argument is a parameter pack but parameter is not.  */
7608 	return 0;
7609 
7610       break;
7611 
7612     default:
7613       gcc_unreachable ();
7614     }
7615 
7616   return 1;
7617 }
7618 
7619 /* Coerce template argument list ARGLIST for use with template
7620    template-parameter TEMPL.  */
7621 
7622 static tree
coerce_template_args_for_ttp(tree templ,tree arglist,tsubst_flags_t complain)7623 coerce_template_args_for_ttp (tree templ, tree arglist,
7624 			      tsubst_flags_t complain)
7625 {
7626   /* Consider an example where a template template parameter declared as
7627 
7628      template <class T, class U = std::allocator<T> > class TT
7629 
7630      The template parameter level of T and U are one level larger than
7631      of TT.  To proper process the default argument of U, say when an
7632      instantiation `TT<int>' is seen, we need to build the full
7633      arguments containing {int} as the innermost level.  Outer levels,
7634      available when not appearing as default template argument, can be
7635      obtained from the arguments of the enclosing template.
7636 
7637      Suppose that TT is later substituted with std::vector.  The above
7638      instantiation is `TT<int, std::allocator<T> >' with TT at
7639      level 1, and T at level 2, while the template arguments at level 1
7640      becomes {std::vector} and the inner level 2 is {int}.  */
7641 
7642   tree outer = DECL_CONTEXT (templ);
7643   if (outer)
7644     outer = generic_targs_for (outer);
7645   else if (current_template_parms)
7646     {
7647       /* This is an argument of the current template, so we haven't set
7648 	 DECL_CONTEXT yet.  */
7649       tree relevant_template_parms;
7650 
7651       /* Parameter levels that are greater than the level of the given
7652 	 template template parm are irrelevant.  */
7653       relevant_template_parms = current_template_parms;
7654       while (TMPL_PARMS_DEPTH (relevant_template_parms)
7655 	     != TEMPLATE_TYPE_LEVEL (TREE_TYPE (templ)))
7656 	relevant_template_parms = TREE_CHAIN (relevant_template_parms);
7657 
7658       outer = template_parms_to_args (relevant_template_parms);
7659     }
7660 
7661   if (outer)
7662     arglist = add_to_template_args (outer, arglist);
7663 
7664   tree parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7665   return coerce_template_parms (parmlist, arglist, templ,
7666 				complain,
7667 				/*require_all_args=*/true,
7668 				/*use_default_args=*/true);
7669 }
7670 
7671 /* A cache of template template parameters with match-all default
7672    arguments.  */
7673 static GTY((deletable)) hash_map<tree,tree> *defaulted_ttp_cache;
7674 
7675 /* T is a bound template template-parameter.  Copy its arguments into default
7676    arguments of the template template-parameter's template parameters.  */
7677 
7678 static tree
add_defaults_to_ttp(tree otmpl)7679 add_defaults_to_ttp (tree otmpl)
7680 {
7681   if (tree *c = hash_map_safe_get (defaulted_ttp_cache, otmpl))
7682     return *c;
7683 
7684   tree ntmpl = copy_node (otmpl);
7685 
7686   tree ntype = copy_node (TREE_TYPE (otmpl));
7687   TYPE_STUB_DECL (ntype) = TYPE_NAME (ntype) = ntmpl;
7688   TYPE_MAIN_VARIANT (ntype) = ntype;
7689   TYPE_POINTER_TO (ntype) = TYPE_REFERENCE_TO (ntype) = NULL_TREE;
7690   TYPE_NAME (ntype) = ntmpl;
7691   SET_TYPE_STRUCTURAL_EQUALITY (ntype);
7692 
7693   tree idx = TEMPLATE_TYPE_PARM_INDEX (ntype)
7694     = copy_node (TEMPLATE_TYPE_PARM_INDEX (ntype));
7695   TEMPLATE_PARM_DECL (idx) = ntmpl;
7696   TREE_TYPE (ntmpl) = TREE_TYPE (idx) = ntype;
7697 
7698   tree oparms = DECL_TEMPLATE_PARMS (otmpl);
7699   tree parms = DECL_TEMPLATE_PARMS (ntmpl) = copy_node (oparms);
7700   TREE_CHAIN (parms) = TREE_CHAIN (oparms);
7701   tree vec = TREE_VALUE (parms) = copy_node (TREE_VALUE (parms));
7702   for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
7703     {
7704       tree o = TREE_VEC_ELT (vec, i);
7705       if (!template_parameter_pack_p (TREE_VALUE (o)))
7706 	{
7707 	  tree n = TREE_VEC_ELT (vec, i) = copy_node (o);
7708 	  TREE_PURPOSE (n) = any_targ_node;
7709 	}
7710     }
7711 
7712   hash_map_safe_put<hm_ggc> (defaulted_ttp_cache, otmpl, ntmpl);
7713   return ntmpl;
7714 }
7715 
7716 /* ARG is a bound potential template template-argument, and PARGS is a list
7717    of arguments for the corresponding template template-parameter.  Adjust
7718    PARGS as appropriate for application to ARG's template, and if ARG is a
7719    BOUND_TEMPLATE_TEMPLATE_PARM, possibly adjust it to add default template
7720    arguments to the template template parameter.  */
7721 
7722 static tree
coerce_ttp_args_for_tta(tree & arg,tree pargs,tsubst_flags_t complain)7723 coerce_ttp_args_for_tta (tree& arg, tree pargs, tsubst_flags_t complain)
7724 {
7725   ++processing_template_decl;
7726   tree arg_tmpl = TYPE_TI_TEMPLATE (arg);
7727   if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
7728     {
7729       /* When comparing two template template-parameters in partial ordering,
7730 	 rewrite the one currently being used as an argument to have default
7731 	 arguments for all parameters.  */
7732       arg_tmpl = add_defaults_to_ttp (arg_tmpl);
7733       pargs = coerce_template_args_for_ttp (arg_tmpl, pargs, complain);
7734       if (pargs != error_mark_node)
7735 	arg = bind_template_template_parm (TREE_TYPE (arg_tmpl),
7736 					   TYPE_TI_ARGS (arg));
7737     }
7738   else
7739     {
7740       tree aparms
7741 	= INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (arg_tmpl));
7742       pargs = coerce_template_parms (aparms, pargs, arg_tmpl, complain,
7743 				       /*require_all*/true,
7744 				       /*use_default*/true);
7745     }
7746   --processing_template_decl;
7747   return pargs;
7748 }
7749 
7750 /* Subroutine of unify for the case when PARM is a
7751    BOUND_TEMPLATE_TEMPLATE_PARM.  */
7752 
7753 static int
unify_bound_ttp_args(tree tparms,tree targs,tree parm,tree & arg,bool explain_p)7754 unify_bound_ttp_args (tree tparms, tree targs, tree parm, tree& arg,
7755 		      bool explain_p)
7756 {
7757   tree parmvec = TYPE_TI_ARGS (parm);
7758   tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
7759 
7760   /* The template template parm might be variadic and the argument
7761      not, so flatten both argument lists.  */
7762   parmvec = expand_template_argument_pack (parmvec);
7763   argvec = expand_template_argument_pack (argvec);
7764 
7765   if (flag_new_ttp)
7766     {
7767       /* In keeping with P0522R0, adjust P's template arguments
7768 	 to apply to A's template; then flatten it again.  */
7769       tree nparmvec = coerce_ttp_args_for_tta (arg, parmvec, tf_none);
7770       nparmvec = expand_template_argument_pack (nparmvec);
7771 
7772       if (unify (tparms, targs, nparmvec, argvec,
7773 		 UNIFY_ALLOW_NONE, explain_p))
7774 	return 1;
7775 
7776       /* If the P0522 adjustment eliminated a pack expansion, deduce
7777 	 empty packs.  */
7778       if (flag_new_ttp
7779 	  && TREE_VEC_LENGTH (nparmvec) < TREE_VEC_LENGTH (parmvec)
7780 	  && unify_pack_expansion (tparms, targs, parmvec, argvec,
7781 				   DEDUCE_EXACT, /*sub*/true, explain_p))
7782 	return 1;
7783     }
7784   else
7785     {
7786       /* Deduce arguments T, i from TT<T> or TT<i>.
7787 	 We check each element of PARMVEC and ARGVEC individually
7788 	 rather than the whole TREE_VEC since they can have
7789 	 different number of elements, which is allowed under N2555.  */
7790 
7791       int len = TREE_VEC_LENGTH (parmvec);
7792 
7793       /* Check if the parameters end in a pack, making them
7794 	 variadic.  */
7795       int parm_variadic_p = 0;
7796       if (len > 0
7797 	  && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
7798 	parm_variadic_p = 1;
7799 
7800       for (int i = 0; i < len - parm_variadic_p; ++i)
7801 	/* If the template argument list of P contains a pack
7802 	   expansion that is not the last template argument, the
7803 	   entire template argument list is a non-deduced
7804 	   context.  */
7805 	if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
7806 	  return unify_success (explain_p);
7807 
7808       if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
7809 	return unify_too_few_arguments (explain_p,
7810 					TREE_VEC_LENGTH (argvec), len);
7811 
7812       for (int i = 0; i < len - parm_variadic_p; ++i)
7813 	if (unify (tparms, targs,
7814 		   TREE_VEC_ELT (parmvec, i),
7815 		   TREE_VEC_ELT (argvec, i),
7816 		   UNIFY_ALLOW_NONE, explain_p))
7817 	  return 1;
7818 
7819       if (parm_variadic_p
7820 	  && unify_pack_expansion (tparms, targs,
7821 				   parmvec, argvec,
7822 				   DEDUCE_EXACT,
7823 				   /*subr=*/true, explain_p))
7824 	return 1;
7825     }
7826 
7827   return 0;
7828 }
7829 
7830 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
7831    template template parameters.  Both PARM_PARMS and ARG_PARMS are
7832    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
7833    or PARM_DECL.
7834 
7835    Consider the example:
7836      template <class T> class A;
7837      template<template <class U> class TT> class B;
7838 
7839    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
7840    the parameters to A, and OUTER_ARGS contains A.  */
7841 
7842 static int
coerce_template_template_parms(tree parm_parms,tree arg_parms,tsubst_flags_t complain,tree in_decl,tree outer_args)7843 coerce_template_template_parms (tree parm_parms,
7844 				tree arg_parms,
7845 				tsubst_flags_t complain,
7846 				tree in_decl,
7847 				tree outer_args)
7848 {
7849   int nparms, nargs, i;
7850   tree parm, arg;
7851   int variadic_p = 0;
7852 
7853   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
7854   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
7855 
7856   nparms = TREE_VEC_LENGTH (parm_parms);
7857   nargs = TREE_VEC_LENGTH (arg_parms);
7858 
7859   if (flag_new_ttp)
7860     {
7861       /* P0522R0: A template template-parameter P is at least as specialized as
7862 	 a template template-argument A if, given the following rewrite to two
7863 	 function templates, the function template corresponding to P is at
7864 	 least as specialized as the function template corresponding to A
7865 	 according to the partial ordering rules for function templates
7866 	 ([temp.func.order]). Given an invented class template X with the
7867 	 template parameter list of A (including default arguments):
7868 
7869 	 * Each of the two function templates has the same template parameters,
7870 	 respectively, as P or A.
7871 
7872 	 * Each function template has a single function parameter whose type is
7873 	 a specialization of X with template arguments corresponding to the
7874 	 template parameters from the respective function template where, for
7875 	 each template parameter PP in the template parameter list of the
7876 	 function template, a corresponding template argument AA is formed. If
7877 	 PP declares a parameter pack, then AA is the pack expansion
7878 	 PP... ([temp.variadic]); otherwise, AA is the id-expression PP.
7879 
7880 	 If the rewrite produces an invalid type, then P is not at least as
7881 	 specialized as A.  */
7882 
7883       /* So coerce P's args to apply to A's parms, and then deduce between A's
7884 	 args and the converted args.  If that succeeds, A is at least as
7885 	 specialized as P, so they match.*/
7886       tree pargs = template_parms_level_to_args (parm_parms);
7887       pargs = add_outermost_template_args (outer_args, pargs);
7888       ++processing_template_decl;
7889       pargs = coerce_template_parms (arg_parms, pargs, NULL_TREE, tf_none,
7890 				     /*require_all*/true, /*use_default*/true);
7891       --processing_template_decl;
7892       if (pargs != error_mark_node)
7893 	{
7894 	  tree targs = make_tree_vec (nargs);
7895 	  tree aargs = template_parms_level_to_args (arg_parms);
7896 	  if (!unify (arg_parms, targs, aargs, pargs, UNIFY_ALLOW_NONE,
7897 		      /*explain*/false))
7898 	    return 1;
7899 	}
7900     }
7901 
7902   /* Determine whether we have a parameter pack at the end of the
7903      template template parameter's template parameter list.  */
7904   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
7905     {
7906       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
7907 
7908       if (error_operand_p (parm))
7909 	return 0;
7910 
7911       switch (TREE_CODE (parm))
7912         {
7913         case TEMPLATE_DECL:
7914         case TYPE_DECL:
7915           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7916             variadic_p = 1;
7917           break;
7918 
7919         case PARM_DECL:
7920           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7921             variadic_p = 1;
7922           break;
7923 
7924         default:
7925           gcc_unreachable ();
7926         }
7927     }
7928 
7929   if (nargs != nparms
7930       && !(variadic_p && nargs >= nparms - 1))
7931     return 0;
7932 
7933   /* Check all of the template parameters except the parameter pack at
7934      the end (if any).  */
7935   for (i = 0; i < nparms - variadic_p; ++i)
7936     {
7937       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
7938           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
7939         continue;
7940 
7941       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
7942       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
7943 
7944       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
7945                                           outer_args))
7946 	return 0;
7947 
7948     }
7949 
7950   if (variadic_p)
7951     {
7952       /* Check each of the template parameters in the template
7953 	 argument against the template parameter pack at the end of
7954 	 the template template parameter.  */
7955       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
7956 	return 0;
7957 
7958       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
7959 
7960       for (; i < nargs; ++i)
7961         {
7962           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
7963             continue;
7964 
7965           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
7966 
7967           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
7968                                               outer_args))
7969             return 0;
7970         }
7971     }
7972 
7973   return 1;
7974 }
7975 
7976 /* Verifies that the deduced template arguments (in TARGS) for the
7977    template template parameters (in TPARMS) represent valid bindings,
7978    by comparing the template parameter list of each template argument
7979    to the template parameter list of its corresponding template
7980    template parameter, in accordance with DR150. This
7981    routine can only be called after all template arguments have been
7982    deduced. It will return TRUE if all of the template template
7983    parameter bindings are okay, FALSE otherwise.  */
7984 bool
template_template_parm_bindings_ok_p(tree tparms,tree targs)7985 template_template_parm_bindings_ok_p (tree tparms, tree targs)
7986 {
7987   int i, ntparms = TREE_VEC_LENGTH (tparms);
7988   bool ret = true;
7989 
7990   /* We're dealing with template parms in this process.  */
7991   ++processing_template_decl;
7992 
7993   targs = INNERMOST_TEMPLATE_ARGS (targs);
7994 
7995   for (i = 0; i < ntparms; ++i)
7996     {
7997       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
7998       tree targ = TREE_VEC_ELT (targs, i);
7999 
8000       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
8001 	{
8002 	  tree packed_args = NULL_TREE;
8003 	  int idx, len = 1;
8004 
8005 	  if (ARGUMENT_PACK_P (targ))
8006 	    {
8007 	      /* Look inside the argument pack.  */
8008 	      packed_args = ARGUMENT_PACK_ARGS (targ);
8009 	      len = TREE_VEC_LENGTH (packed_args);
8010 	    }
8011 
8012 	  for (idx = 0; idx < len; ++idx)
8013 	    {
8014 	      tree targ_parms = NULL_TREE;
8015 
8016 	      if (packed_args)
8017 		/* Extract the next argument from the argument
8018 		   pack.  */
8019 		targ = TREE_VEC_ELT (packed_args, idx);
8020 
8021 	      if (PACK_EXPANSION_P (targ))
8022 		/* Look at the pattern of the pack expansion.  */
8023 		targ = PACK_EXPANSION_PATTERN (targ);
8024 
8025 	      /* Extract the template parameters from the template
8026 		 argument.  */
8027 	      if (TREE_CODE (targ) == TEMPLATE_DECL)
8028 		targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
8029 	      else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
8030 		targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
8031 
8032 	      /* Verify that we can coerce the template template
8033 		 parameters from the template argument to the template
8034 		 parameter.  This requires an exact match.  */
8035 	      if (targ_parms
8036 		  && !coerce_template_template_parms
8037 		       (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
8038 			targ_parms,
8039 			tf_none,
8040 			tparm,
8041 			targs))
8042 		{
8043 		  ret = false;
8044 		  goto out;
8045 		}
8046 	    }
8047 	}
8048     }
8049 
8050  out:
8051 
8052   --processing_template_decl;
8053   return ret;
8054 }
8055 
8056 /* Since type attributes aren't mangled, we need to strip them from
8057    template type arguments.  */
8058 
8059 tree
canonicalize_type_argument(tree arg,tsubst_flags_t complain)8060 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
8061 {
8062   if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
8063     return arg;
8064   bool removed_attributes = false;
8065   tree canon = strip_typedefs (arg, &removed_attributes);
8066   if (removed_attributes
8067       && (complain & tf_warning))
8068     warning (OPT_Wignored_attributes,
8069 	     "ignoring attributes on template argument %qT", arg);
8070   return canon;
8071 }
8072 
8073 /* And from inside dependent non-type arguments like sizeof(Type).  */
8074 
8075 static tree
canonicalize_expr_argument(tree arg,tsubst_flags_t complain)8076 canonicalize_expr_argument (tree arg, tsubst_flags_t complain)
8077 {
8078   if (!arg || arg == error_mark_node)
8079     return arg;
8080   bool removed_attributes = false;
8081   tree canon = strip_typedefs_expr (arg, &removed_attributes);
8082   if (removed_attributes
8083       && (complain & tf_warning))
8084     warning (OPT_Wignored_attributes,
8085 	     "ignoring attributes in template argument %qE", arg);
8086   return canon;
8087 }
8088 
8089 // A template declaration can be substituted for a constrained
8090 // template template parameter only when the argument is more
8091 // constrained than the parameter.
8092 static bool
is_compatible_template_arg(tree parm,tree arg)8093 is_compatible_template_arg (tree parm, tree arg)
8094 {
8095   tree parm_cons = get_constraints (parm);
8096 
8097   /* For now, allow constrained template template arguments
8098      and unconstrained template template parameters.  */
8099   if (parm_cons == NULL_TREE)
8100     return true;
8101 
8102   /* If the template parameter is constrained, we need to rewrite its
8103      constraints in terms of the ARG's template parameters. This ensures
8104      that all of the template parameter types will have the same depth.
8105 
8106      Note that this is only valid when coerce_template_template_parm is
8107      true for the innermost template parameters of PARM and ARG. In other
8108      words, because coercion is successful, this conversion will be valid.  */
8109   tree new_args = NULL_TREE;
8110   if (parm_cons)
8111     {
8112       tree aparms = DECL_INNERMOST_TEMPLATE_PARMS (arg);
8113       new_args = template_parms_level_to_args (aparms);
8114       parm_cons = tsubst_constraint_info (parm_cons, new_args,
8115 					  tf_none, NULL_TREE);
8116       if (parm_cons == error_mark_node)
8117         return false;
8118     }
8119 
8120   return weakly_subsumes (parm_cons, new_args, arg);
8121 }
8122 
8123 // Convert a placeholder argument into a binding to the original
8124 // parameter. The original parameter is saved as the TREE_TYPE of
8125 // ARG.
8126 static inline tree
convert_wildcard_argument(tree parm,tree arg)8127 convert_wildcard_argument (tree parm, tree arg)
8128 {
8129   TREE_TYPE (arg) = parm;
8130   return arg;
8131 }
8132 
8133 /* We can't fully resolve ARG given as a non-type template argument to TYPE,
8134    because one of them is dependent.  But we need to represent the
8135    conversion for the benefit of cp_tree_equal.  */
8136 
8137 static tree
maybe_convert_nontype_argument(tree type,tree arg)8138 maybe_convert_nontype_argument (tree type, tree arg)
8139 {
8140   /* Auto parms get no conversion.  */
8141   if (type_uses_auto (type))
8142     return arg;
8143   /* We don't need or want to add this conversion now if we're going to use the
8144      argument for deduction.  */
8145   if (value_dependent_expression_p (arg))
8146     return arg;
8147 
8148   type = cv_unqualified (type);
8149   tree argtype = TREE_TYPE (arg);
8150   if (same_type_p (type, argtype))
8151     return arg;
8152 
8153   arg = build1 (IMPLICIT_CONV_EXPR, type, arg);
8154   IMPLICIT_CONV_EXPR_NONTYPE_ARG (arg) = true;
8155   return arg;
8156 }
8157 
8158 /* Convert the indicated template ARG as necessary to match the
8159    indicated template PARM.  Returns the converted ARG, or
8160    error_mark_node if the conversion was unsuccessful.  Error and
8161    warning messages are issued under control of COMPLAIN.  This
8162    conversion is for the Ith parameter in the parameter list.  ARGS is
8163    the full set of template arguments deduced so far.  */
8164 
8165 static tree
convert_template_argument(tree parm,tree arg,tree args,tsubst_flags_t complain,int i,tree in_decl)8166 convert_template_argument (tree parm,
8167 			   tree arg,
8168 			   tree args,
8169 			   tsubst_flags_t complain,
8170 			   int i,
8171 			   tree in_decl)
8172 {
8173   tree orig_arg;
8174   tree val;
8175   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
8176 
8177   if (parm == error_mark_node || error_operand_p (arg))
8178     return error_mark_node;
8179 
8180   /* Trivially convert placeholders. */
8181   if (TREE_CODE (arg) == WILDCARD_DECL)
8182     return convert_wildcard_argument (parm, arg);
8183 
8184   if (arg == any_targ_node)
8185     return arg;
8186 
8187   if (TREE_CODE (arg) == TREE_LIST
8188       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
8189     {
8190       /* The template argument was the name of some
8191 	 member function.  That's usually
8192 	 invalid, but static members are OK.  In any
8193 	 case, grab the underlying fields/functions
8194 	 and issue an error later if required.  */
8195       TREE_TYPE (arg) = unknown_type_node;
8196     }
8197 
8198   orig_arg = arg;
8199 
8200   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
8201   requires_type = (TREE_CODE (parm) == TYPE_DECL
8202 		   || requires_tmpl_type);
8203 
8204   /* When determining whether an argument pack expansion is a template,
8205      look at the pattern.  */
8206   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
8207     arg = PACK_EXPANSION_PATTERN (arg);
8208 
8209   /* Deal with an injected-class-name used as a template template arg.  */
8210   if (requires_tmpl_type && CLASS_TYPE_P (arg))
8211     {
8212       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
8213       if (TREE_CODE (t) == TEMPLATE_DECL)
8214 	{
8215 	  if (cxx_dialect >= cxx11)
8216 	    /* OK under DR 1004.  */;
8217 	  else if (complain & tf_warning_or_error)
8218 	    pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
8219 		     " used as template template argument", TYPE_NAME (arg));
8220 	  else if (flag_pedantic_errors)
8221 	    t = arg;
8222 
8223 	  arg = t;
8224 	}
8225     }
8226 
8227   is_tmpl_type =
8228     ((TREE_CODE (arg) == TEMPLATE_DECL
8229       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
8230      || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
8231      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8232      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
8233 
8234   if (is_tmpl_type
8235       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8236 	  || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
8237     arg = TYPE_STUB_DECL (arg);
8238 
8239   is_type = TYPE_P (arg) || is_tmpl_type;
8240 
8241   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
8242       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
8243     {
8244       if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
8245 	{
8246 	  if (complain & tf_error)
8247 	    error ("invalid use of destructor %qE as a type", orig_arg);
8248 	  return error_mark_node;
8249 	}
8250 
8251       permerror (input_location,
8252 		 "to refer to a type member of a template parameter, "
8253 		 "use %<typename %E%>", orig_arg);
8254 
8255       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
8256 				     TREE_OPERAND (arg, 1),
8257 				     typename_type,
8258 				     complain);
8259       arg = orig_arg;
8260       is_type = 1;
8261     }
8262   if (is_type != requires_type)
8263     {
8264       if (in_decl)
8265 	{
8266 	  if (complain & tf_error)
8267 	    {
8268 	      error ("type/value mismatch at argument %d in template "
8269 		     "parameter list for %qD",
8270 		     i + 1, in_decl);
8271 	      if (is_type)
8272 		{
8273 		  /* The template argument is a type, but we're expecting
8274 		     an expression.  */
8275 		  inform (input_location,
8276 			  "  expected a constant of type %qT, got %qT",
8277 			  TREE_TYPE (parm),
8278 			  (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
8279 		  /* [temp.arg]/2: "In a template-argument, an ambiguity
8280 		     between a type-id and an expression is resolved to a
8281 		     type-id, regardless of the form of the corresponding
8282 		     template-parameter."  So give the user a clue.  */
8283 		  if (TREE_CODE (arg) == FUNCTION_TYPE)
8284 		    inform (input_location, "  ambiguous template argument "
8285 			    "for non-type template parameter is treated as "
8286 			    "function type");
8287 		}
8288 	      else if (requires_tmpl_type)
8289 		inform (input_location,
8290 			"  expected a class template, got %qE", orig_arg);
8291 	      else
8292 		inform (input_location,
8293 			"  expected a type, got %qE", orig_arg);
8294 	    }
8295 	}
8296       return error_mark_node;
8297     }
8298   if (is_tmpl_type ^ requires_tmpl_type)
8299     {
8300       if (in_decl && (complain & tf_error))
8301 	{
8302 	  error ("type/value mismatch at argument %d in template "
8303 		 "parameter list for %qD",
8304 		 i + 1, in_decl);
8305 	  if (is_tmpl_type)
8306 	    inform (input_location,
8307 		    "  expected a type, got %qT", DECL_NAME (arg));
8308 	  else
8309 	    inform (input_location,
8310 		    "  expected a class template, got %qT", orig_arg);
8311 	}
8312       return error_mark_node;
8313     }
8314 
8315   if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
8316     /* We already did the appropriate conversion when packing args.  */
8317     val = orig_arg;
8318   else if (is_type)
8319     {
8320       if (requires_tmpl_type)
8321 	{
8322 	  if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
8323 	    /* The number of argument required is not known yet.
8324 	       Just accept it for now.  */
8325 	    val = orig_arg;
8326 	  else
8327 	    {
8328 	      tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
8329 	      tree argparm;
8330 
8331 	      /* Strip alias templates that are equivalent to another
8332 		 template.  */
8333 	      arg = get_underlying_template (arg);
8334               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
8335 
8336 	      if (coerce_template_template_parms (parmparm, argparm,
8337 						  complain, in_decl,
8338 						  args))
8339 		{
8340 		  val = arg;
8341 
8342 		  /* TEMPLATE_TEMPLATE_PARM node is preferred over
8343 		     TEMPLATE_DECL.  */
8344 		  if (val != error_mark_node)
8345                     {
8346                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
8347                         val = TREE_TYPE (val);
8348 		      if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
8349 			val = make_pack_expansion (val, complain);
8350                     }
8351 		}
8352 	      else
8353 		{
8354 		  if (in_decl && (complain & tf_error))
8355 		    {
8356 		      error ("type/value mismatch at argument %d in "
8357 			     "template parameter list for %qD",
8358 			     i + 1, in_decl);
8359 		      inform (input_location,
8360 			      "  expected a template of type %qD, got %qT",
8361 			      parm, orig_arg);
8362 		    }
8363 
8364 		  val = error_mark_node;
8365 		}
8366 
8367               // Check that the constraints are compatible before allowing the
8368               // substitution.
8369               if (val != error_mark_node)
8370                 if (!is_compatible_template_arg (parm, arg))
8371                   {
8372 		    if (in_decl && (complain & tf_error))
8373                       {
8374                         error ("constraint mismatch at argument %d in "
8375                                "template parameter list for %qD",
8376                                i + 1, in_decl);
8377                         inform (input_location, "  expected %qD but got %qD",
8378                                 parm, arg);
8379                       }
8380 		    val = error_mark_node;
8381                   }
8382 	    }
8383 	}
8384       else
8385 	val = orig_arg;
8386       /* We only form one instance of each template specialization.
8387 	 Therefore, if we use a non-canonical variant (i.e., a
8388 	 typedef), any future messages referring to the type will use
8389 	 the typedef, which is confusing if those future uses do not
8390 	 themselves also use the typedef.  */
8391       if (TYPE_P (val))
8392 	val = canonicalize_type_argument (val, complain);
8393     }
8394   else
8395     {
8396       tree t = TREE_TYPE (parm);
8397 
8398       if (TEMPLATE_PARM_LEVEL (get_template_parm_index (parm))
8399 	  > TMPL_ARGS_DEPTH (args))
8400 	/* We don't have enough levels of args to do any substitution.  This
8401 	   can happen in the context of -fnew-ttp-matching.  */;
8402       else if (tree a = type_uses_auto (t))
8403 	{
8404 	  t = do_auto_deduction (t, arg, a, complain, adc_unify, args);
8405 	  if (t == error_mark_node)
8406 	    return error_mark_node;
8407 	}
8408       else
8409 	t = tsubst (t, args, complain, in_decl);
8410 
8411       if (invalid_nontype_parm_type_p (t, complain))
8412 	return error_mark_node;
8413 
8414       if (t != TREE_TYPE (parm))
8415 	t = canonicalize_type_argument (t, complain);
8416 
8417       if (!type_dependent_expression_p (orig_arg)
8418 	  && !uses_template_parms (t))
8419 	/* We used to call digest_init here.  However, digest_init
8420 	   will report errors, which we don't want when complain
8421 	   is zero.  More importantly, digest_init will try too
8422 	   hard to convert things: for example, `0' should not be
8423 	   converted to pointer type at this point according to
8424 	   the standard.  Accepting this is not merely an
8425 	   extension, since deciding whether or not these
8426 	   conversions can occur is part of determining which
8427 	   function template to call, or whether a given explicit
8428 	   argument specification is valid.  */
8429 	val = convert_nontype_argument (t, orig_arg, complain);
8430       else
8431 	{
8432 	  val = canonicalize_expr_argument (orig_arg, complain);
8433 	  val = maybe_convert_nontype_argument (t, val);
8434 	}
8435 
8436 
8437       if (val == NULL_TREE)
8438 	val = error_mark_node;
8439       else if (val == error_mark_node && (complain & tf_error))
8440 	error_at (cp_expr_loc_or_input_loc (orig_arg),
8441 		  "could not convert template argument %qE from %qT to %qT",
8442 		  orig_arg, TREE_TYPE (orig_arg), t);
8443 
8444       if (INDIRECT_REF_P (val))
8445         {
8446           /* Reject template arguments that are references to built-in
8447              functions with no library fallbacks.  */
8448           const_tree inner = TREE_OPERAND (val, 0);
8449 	  const_tree innertype = TREE_TYPE (inner);
8450 	  if (innertype
8451 	      && TYPE_REF_P (innertype)
8452 	      && TREE_CODE (TREE_TYPE (innertype)) == FUNCTION_TYPE
8453 	      && TREE_OPERAND_LENGTH (inner) > 0
8454               && reject_gcc_builtin (TREE_OPERAND (inner, 0)))
8455               return error_mark_node;
8456         }
8457 
8458       if (TREE_CODE (val) == SCOPE_REF)
8459 	{
8460 	  /* Strip typedefs from the SCOPE_REF.  */
8461 	  tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
8462 	  tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
8463 						   complain);
8464 	  val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
8465 				      QUALIFIED_NAME_IS_TEMPLATE (val));
8466 	}
8467     }
8468 
8469   return val;
8470 }
8471 
8472 /* Coerces the remaining template arguments in INNER_ARGS (from
8473    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
8474    Returns the coerced argument pack. PARM_IDX is the position of this
8475    parameter in the template parameter list. ARGS is the original
8476    template argument list.  */
8477 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)8478 coerce_template_parameter_pack (tree parms,
8479                                 int parm_idx,
8480                                 tree args,
8481                                 tree inner_args,
8482                                 int arg_idx,
8483                                 tree new_args,
8484                                 int* lost,
8485                                 tree in_decl,
8486                                 tsubst_flags_t complain)
8487 {
8488   tree parm = TREE_VEC_ELT (parms, parm_idx);
8489   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8490   tree packed_args;
8491   tree argument_pack;
8492   tree packed_parms = NULL_TREE;
8493 
8494   if (arg_idx > nargs)
8495     arg_idx = nargs;
8496 
8497   if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
8498     {
8499       /* When the template parameter is a non-type template parameter pack
8500          or template template parameter pack whose type or template
8501          parameters use parameter packs, we know exactly how many arguments
8502          we are looking for.  Build a vector of the instantiated decls for
8503          these template parameters in PACKED_PARMS.  */
8504       /* We can't use make_pack_expansion here because it would interpret a
8505 	 _DECL as a use rather than a declaration.  */
8506       tree decl = TREE_VALUE (parm);
8507       tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
8508       SET_PACK_EXPANSION_PATTERN (exp, decl);
8509       PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
8510       SET_TYPE_STRUCTURAL_EQUALITY (exp);
8511 
8512       TREE_VEC_LENGTH (args)--;
8513       packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
8514       TREE_VEC_LENGTH (args)++;
8515 
8516       if (packed_parms == error_mark_node)
8517         return error_mark_node;
8518 
8519       /* If we're doing a partial instantiation of a member template,
8520          verify that all of the types used for the non-type
8521          template parameter pack are, in fact, valid for non-type
8522          template parameters.  */
8523       if (arg_idx < nargs
8524           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
8525         {
8526           int j, len = TREE_VEC_LENGTH (packed_parms);
8527           for (j = 0; j < len; ++j)
8528             {
8529               tree t = TREE_VEC_ELT (packed_parms, j);
8530               if (TREE_CODE (t) == PARM_DECL
8531 		  && invalid_nontype_parm_type_p (TREE_TYPE (t), complain))
8532                 return error_mark_node;
8533             }
8534 	  /* We don't know how many args we have yet, just
8535 	     use the unconverted ones for now.  */
8536 	  return NULL_TREE;
8537         }
8538 
8539       packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
8540     }
8541   /* Check if we have a placeholder pack, which indicates we're
8542      in the context of a introduction list.  In that case we want
8543      to match this pack to the single placeholder.  */
8544   else if (arg_idx < nargs
8545            && TREE_CODE (TREE_VEC_ELT (inner_args, arg_idx)) == WILDCARD_DECL
8546            && WILDCARD_PACK_P (TREE_VEC_ELT (inner_args, arg_idx)))
8547     {
8548       nargs = arg_idx + 1;
8549       packed_args = make_tree_vec (1);
8550     }
8551   else
8552     packed_args = make_tree_vec (nargs - arg_idx);
8553 
8554   /* Convert the remaining arguments, which will be a part of the
8555      parameter pack "parm".  */
8556   int first_pack_arg = arg_idx;
8557   for (; arg_idx < nargs; ++arg_idx)
8558     {
8559       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
8560       tree actual_parm = TREE_VALUE (parm);
8561       int pack_idx = arg_idx - first_pack_arg;
8562 
8563       if (packed_parms)
8564         {
8565 	  /* Once we've packed as many args as we have types, stop.  */
8566 	  if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
8567 	    break;
8568 	  else if (PACK_EXPANSION_P (arg))
8569 	    /* We don't know how many args we have yet, just
8570 	       use the unconverted ones for now.  */
8571 	    return NULL_TREE;
8572 	  else
8573 	    actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
8574         }
8575 
8576       if (arg == error_mark_node)
8577 	{
8578 	  if (complain & tf_error)
8579 	    error ("template argument %d is invalid", arg_idx + 1);
8580 	}
8581       else
8582 	arg = convert_template_argument (actual_parm,
8583 					 arg, new_args, complain, parm_idx,
8584 					 in_decl);
8585       if (arg == error_mark_node)
8586         (*lost)++;
8587       TREE_VEC_ELT (packed_args, pack_idx) = arg;
8588     }
8589 
8590   if (arg_idx - first_pack_arg < TREE_VEC_LENGTH (packed_args)
8591       && TREE_VEC_LENGTH (packed_args) > 0)
8592     {
8593       if (complain & tf_error)
8594 	error ("wrong number of template arguments (%d, should be %d)",
8595 	       arg_idx - first_pack_arg, TREE_VEC_LENGTH (packed_args));
8596       return error_mark_node;
8597     }
8598 
8599   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
8600       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
8601     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
8602   else
8603     {
8604       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
8605       TREE_CONSTANT (argument_pack) = 1;
8606     }
8607 
8608   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
8609   if (CHECKING_P)
8610     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
8611 					 TREE_VEC_LENGTH (packed_args));
8612   return argument_pack;
8613 }
8614 
8615 /* Returns the number of pack expansions in the template argument vector
8616    ARGS.  */
8617 
8618 static int
pack_expansion_args_count(tree args)8619 pack_expansion_args_count (tree args)
8620 {
8621   int i;
8622   int count = 0;
8623   if (args)
8624     for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
8625       {
8626 	tree elt = TREE_VEC_ELT (args, i);
8627 	if (elt && PACK_EXPANSION_P (elt))
8628 	  ++count;
8629       }
8630   return count;
8631 }
8632 
8633 /* Convert all template arguments to their appropriate types, and
8634    return a vector containing the innermost resulting template
8635    arguments.  If any error occurs, return error_mark_node. Error and
8636    warning messages are issued under control of COMPLAIN.
8637 
8638    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
8639    for arguments not specified in ARGS.  Otherwise, if
8640    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
8641    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
8642    USE_DEFAULT_ARGS is false, then all arguments must be specified in
8643    ARGS.  */
8644 
8645 static tree
coerce_template_parms(tree parms,tree args,tree in_decl,tsubst_flags_t complain,bool require_all_args,bool use_default_args)8646 coerce_template_parms (tree parms,
8647 		       tree args,
8648 		       tree in_decl,
8649 		       tsubst_flags_t complain,
8650 		       bool require_all_args,
8651 		       bool use_default_args)
8652 {
8653   int nparms, nargs, parm_idx, arg_idx, lost = 0;
8654   tree orig_inner_args;
8655   tree inner_args;
8656   tree new_args;
8657   tree new_inner_args;
8658 
8659   /* When used as a boolean value, indicates whether this is a
8660      variadic template parameter list. Since it's an int, we can also
8661      subtract it from nparms to get the number of non-variadic
8662      parameters.  */
8663   int variadic_p = 0;
8664   int variadic_args_p = 0;
8665   int post_variadic_parms = 0;
8666 
8667   /* Adjustment to nparms for fixed parameter packs.  */
8668   int fixed_pack_adjust = 0;
8669   int fixed_packs = 0;
8670   int missing = 0;
8671 
8672   /* Likewise for parameters with default arguments.  */
8673   int default_p = 0;
8674 
8675   if (args == error_mark_node)
8676     return error_mark_node;
8677 
8678   nparms = TREE_VEC_LENGTH (parms);
8679 
8680   /* Determine if there are any parameter packs or default arguments.  */
8681   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
8682     {
8683       tree parm = TREE_VEC_ELT (parms, parm_idx);
8684       if (variadic_p)
8685 	++post_variadic_parms;
8686       if (template_parameter_pack_p (TREE_VALUE (parm)))
8687 	++variadic_p;
8688       if (TREE_PURPOSE (parm))
8689 	++default_p;
8690     }
8691 
8692   inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
8693   /* If there are no parameters that follow a parameter pack, we need to
8694      expand any argument packs so that we can deduce a parameter pack from
8695      some non-packed args followed by an argument pack, as in variadic85.C.
8696      If there are such parameters, we need to leave argument packs intact
8697      so the arguments are assigned properly.  This can happen when dealing
8698      with a nested class inside a partial specialization of a class
8699      template, as in variadic92.C, or when deducing a template parameter pack
8700      from a sub-declarator, as in variadic114.C.  */
8701   if (!post_variadic_parms)
8702     inner_args = expand_template_argument_pack (inner_args);
8703 
8704   /* Count any pack expansion args.  */
8705   variadic_args_p = pack_expansion_args_count (inner_args);
8706 
8707   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8708   if ((nargs - variadic_args_p > nparms && !variadic_p)
8709       || (nargs < nparms - variadic_p
8710 	  && require_all_args
8711 	  && !variadic_args_p
8712 	  && (!use_default_args
8713 	      || (TREE_VEC_ELT (parms, nargs) != error_mark_node
8714                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
8715     {
8716     bad_nargs:
8717       if (complain & tf_error)
8718 	{
8719           if (variadic_p || default_p)
8720             {
8721               nparms -= variadic_p + default_p;
8722 	      error ("wrong number of template arguments "
8723 		     "(%d, should be at least %d)", nargs, nparms);
8724             }
8725 	  else
8726 	     error ("wrong number of template arguments "
8727 		    "(%d, should be %d)", nargs, nparms);
8728 
8729 	  if (in_decl)
8730 	    inform (DECL_SOURCE_LOCATION (in_decl),
8731 		    "provided for %qD", in_decl);
8732 	}
8733 
8734       return error_mark_node;
8735     }
8736   /* We can't pass a pack expansion to a non-pack parameter of an alias
8737      template (DR 1430).  */
8738   else if (in_decl
8739 	   && (DECL_ALIAS_TEMPLATE_P (in_decl)
8740 	       || concept_definition_p (in_decl))
8741 	   && variadic_args_p
8742 	   && nargs - variadic_args_p < nparms - variadic_p)
8743     {
8744       if (complain & tf_error)
8745 	{
8746 	  for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
8747 	    {
8748 	      tree arg = TREE_VEC_ELT (inner_args, i);
8749 	      tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
8750 
8751 	      if (PACK_EXPANSION_P (arg)
8752 		  && !template_parameter_pack_p (parm))
8753 		{
8754 		  if (DECL_ALIAS_TEMPLATE_P (in_decl))
8755 		    error_at (location_of (arg),
8756 			      "pack expansion argument for non-pack parameter "
8757 			      "%qD of alias template %qD", parm, in_decl);
8758 		  else
8759 		    error_at (location_of (arg),
8760 			      "pack expansion argument for non-pack parameter "
8761 			      "%qD of concept %qD", parm, in_decl);
8762 		  inform (DECL_SOURCE_LOCATION (parm), "declared here");
8763 		  goto found;
8764 		}
8765 	    }
8766 	  gcc_unreachable ();
8767 	found:;
8768 	}
8769       return error_mark_node;
8770     }
8771 
8772   /* We need to evaluate the template arguments, even though this
8773      template-id may be nested within a "sizeof".  */
8774   cp_evaluated ev;
8775 
8776   new_inner_args = make_tree_vec (nparms);
8777   new_args = add_outermost_template_args (args, new_inner_args);
8778   int pack_adjust = 0;
8779   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
8780     {
8781       tree arg;
8782       tree parm;
8783 
8784       /* Get the Ith template parameter.  */
8785       parm = TREE_VEC_ELT (parms, parm_idx);
8786 
8787       if (parm == error_mark_node)
8788 	{
8789 	  TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
8790 	  continue;
8791 	}
8792 
8793       /* Calculate the next argument.  */
8794       if (arg_idx < nargs)
8795 	arg = TREE_VEC_ELT (inner_args, arg_idx);
8796       else
8797 	arg = NULL_TREE;
8798 
8799       if (template_parameter_pack_p (TREE_VALUE (parm))
8800 	  && (arg || require_all_args || !(complain & tf_partial))
8801 	  && !(arg && ARGUMENT_PACK_P (arg)))
8802         {
8803 	  /* Some arguments will be placed in the
8804 	     template parameter pack PARM.  */
8805 	  arg = coerce_template_parameter_pack (parms, parm_idx, args,
8806 						inner_args, arg_idx,
8807 						new_args, &lost,
8808 						in_decl, complain);
8809 
8810 	  if (arg == NULL_TREE)
8811 	    {
8812 	      /* We don't know how many args we have yet, just use the
8813 		 unconverted (and still packed) ones for now.  */
8814 	      new_inner_args = orig_inner_args;
8815 	      arg_idx = nargs;
8816 	      break;
8817 	    }
8818 
8819           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
8820 
8821           /* Store this argument.  */
8822           if (arg == error_mark_node)
8823 	    {
8824 	      lost++;
8825 	      /* We are done with all of the arguments.  */
8826 	      arg_idx = nargs;
8827 	      break;
8828 	    }
8829 	  else
8830 	    {
8831 	      pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
8832 	      arg_idx += pack_adjust;
8833 	      if (fixed_parameter_pack_p (TREE_VALUE (parm)))
8834 		{
8835 		  ++fixed_packs;
8836 		  fixed_pack_adjust += pack_adjust;
8837 		}
8838 	    }
8839 
8840           continue;
8841         }
8842       else if (arg)
8843 	{
8844           if (PACK_EXPANSION_P (arg))
8845             {
8846 	      /* "If every valid specialization of a variadic template
8847 		 requires an empty template parameter pack, the template is
8848 		 ill-formed, no diagnostic required."  So check that the
8849 		 pattern works with this parameter.  */
8850 	      tree pattern = PACK_EXPANSION_PATTERN (arg);
8851 	      tree conv = convert_template_argument (TREE_VALUE (parm),
8852 						     pattern, new_args,
8853 						     complain, parm_idx,
8854 						     in_decl);
8855 	      if (conv == error_mark_node)
8856 		{
8857 		  if (complain & tf_error)
8858 		    inform (input_location, "so any instantiation with a "
8859 			    "non-empty parameter pack would be ill-formed");
8860 		  ++lost;
8861 		}
8862 	      else if (TYPE_P (conv) && !TYPE_P (pattern))
8863 		/* Recover from missing typename.  */
8864 		TREE_VEC_ELT (inner_args, arg_idx)
8865 		  = make_pack_expansion (conv, complain);
8866 
8867               /* We don't know how many args we have yet, just
8868                  use the unconverted ones for now.  */
8869               new_inner_args = inner_args;
8870 	      arg_idx = nargs;
8871               break;
8872             }
8873         }
8874       else if (require_all_args)
8875 	{
8876 	  /* There must be a default arg in this case.  */
8877 	  arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
8878 				     complain, in_decl);
8879 	  /* The position of the first default template argument,
8880 	     is also the number of non-defaulted arguments in NEW_INNER_ARGS.
8881 	     Record that.  */
8882 	  if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
8883 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
8884 						 arg_idx - pack_adjust);
8885 	}
8886       else
8887 	break;
8888 
8889       if (arg == error_mark_node)
8890 	{
8891 	  if (complain & tf_error)
8892 	    error ("template argument %d is invalid", arg_idx + 1);
8893 	}
8894       else if (!arg)
8895 	{
8896 	  /* This can occur if there was an error in the template
8897 	     parameter list itself (which we would already have
8898 	     reported) that we are trying to recover from, e.g., a class
8899 	     template with a parameter list such as
8900 	     template<typename..., typename> (cpp0x/variadic150.C).  */
8901 	  ++lost;
8902 
8903 	  /* This can also happen with a fixed parameter pack (71834).  */
8904 	  if (arg_idx >= nargs)
8905 	    ++missing;
8906 	}
8907       else
8908 	arg = convert_template_argument (TREE_VALUE (parm),
8909 					 arg, new_args, complain,
8910                                          parm_idx, in_decl);
8911 
8912       if (arg == error_mark_node)
8913 	lost++;
8914 
8915       TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
8916     }
8917 
8918   if (missing || arg_idx < nargs - variadic_args_p)
8919     {
8920       /* If we had fixed parameter packs, we didn't know how many arguments we
8921 	 actually needed earlier; now we do.  */
8922       nparms += fixed_pack_adjust;
8923       variadic_p -= fixed_packs;
8924       goto bad_nargs;
8925     }
8926 
8927   if (arg_idx < nargs)
8928     {
8929       /* We had some pack expansion arguments that will only work if the packs
8930 	 are empty, but wait until instantiation time to complain.
8931 	 See variadic-ttp3.C.  */
8932 
8933       /* Except that we can't provide empty packs to alias templates or
8934          concepts when there are no corresponding parameters. Basically,
8935          we can get here with this:
8936 
8937              template<typename T> concept C = true;
8938 
8939              template<typename... Args>
8940 	       requires C<Args...>
8941              void f();
8942 
8943          When parsing C<Args...>, we try to form a concept check of
8944          C<?, Args...>. Without the extra check for substituting an empty
8945          pack past the last parameter, we can accept the check as valid.
8946 
8947          FIXME: This may be valid for alias templates (but I doubt it).
8948 
8949          FIXME: The error could be better also.   */
8950       if (in_decl && concept_definition_p (in_decl))
8951 	{
8952 	  if (complain & tf_error)
8953 	    error_at (location_of (TREE_VEC_ELT (args, arg_idx)),
8954 		      "too many arguments");
8955 	  return error_mark_node;
8956 	}
8957 
8958       int len = nparms + (nargs - arg_idx);
8959       tree args = make_tree_vec (len);
8960       int i = 0;
8961       for (; i < nparms; ++i)
8962 	TREE_VEC_ELT (args, i) = TREE_VEC_ELT (new_inner_args, i);
8963       for (; i < len; ++i, ++arg_idx)
8964 	TREE_VEC_ELT (args, i) = TREE_VEC_ELT (inner_args,
8965 					       arg_idx - pack_adjust);
8966       new_inner_args = args;
8967     }
8968 
8969   if (lost)
8970     {
8971       gcc_assert (!(complain & tf_error) || seen_error ());
8972       return error_mark_node;
8973     }
8974 
8975   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
8976     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
8977 					 TREE_VEC_LENGTH (new_inner_args));
8978 
8979   return new_inner_args;
8980 }
8981 
8982 /* Convert all template arguments to their appropriate types, and
8983    return a vector containing the innermost resulting template
8984    arguments.  If any error occurs, return error_mark_node. Error and
8985    warning messages are not issued.
8986 
8987    Note that no function argument deduction is performed, and default
8988    arguments are used to fill in unspecified arguments. */
8989 tree
coerce_template_parms(tree parms,tree args,tree in_decl)8990 coerce_template_parms (tree parms, tree args, tree in_decl)
8991 {
8992   return coerce_template_parms (parms, args, in_decl, tf_none, true, true);
8993 }
8994 
8995 /* Convert all template arguments to their appropriate type, and
8996    instantiate default arguments as needed. This returns a vector
8997    containing the innermost resulting template arguments, or
8998    error_mark_node if unsuccessful.  */
8999 tree
coerce_template_parms(tree parms,tree args,tree in_decl,tsubst_flags_t complain)9000 coerce_template_parms (tree parms, tree args, tree in_decl,
9001                        tsubst_flags_t complain)
9002 {
9003   return coerce_template_parms (parms, args, in_decl, complain, true, true);
9004 }
9005 
9006 /* Like coerce_template_parms.  If PARMS represents all template
9007    parameters levels, this function returns a vector of vectors
9008    representing all the resulting argument levels.  Note that in this
9009    case, only the innermost arguments are coerced because the
9010    outermost ones are supposed to have been coerced already.
9011 
9012    Otherwise, if PARMS represents only (the innermost) vector of
9013    parameters, this function returns a vector containing just the
9014    innermost resulting arguments.  */
9015 
9016 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)9017 coerce_innermost_template_parms (tree parms,
9018 				  tree args,
9019 				  tree in_decl,
9020 				  tsubst_flags_t complain,
9021 				  bool require_all_args,
9022 				  bool use_default_args)
9023 {
9024   int parms_depth = TMPL_PARMS_DEPTH (parms);
9025   int args_depth = TMPL_ARGS_DEPTH (args);
9026   tree coerced_args;
9027 
9028   if (parms_depth > 1)
9029     {
9030       coerced_args = make_tree_vec (parms_depth);
9031       tree level;
9032       int cur_depth;
9033 
9034       for (level = parms, cur_depth = parms_depth;
9035 	   parms_depth > 0 && level != NULL_TREE;
9036 	   level = TREE_CHAIN (level), --cur_depth)
9037 	{
9038 	  tree l;
9039 	  if (cur_depth == args_depth)
9040 	    l = coerce_template_parms (TREE_VALUE (level),
9041 				       args, in_decl, complain,
9042 				       require_all_args,
9043 				       use_default_args);
9044 	  else
9045 	    l = TMPL_ARGS_LEVEL (args, cur_depth);
9046 
9047 	  if (l == error_mark_node)
9048 	    return error_mark_node;
9049 
9050 	  SET_TMPL_ARGS_LEVEL (coerced_args, cur_depth, l);
9051 	}
9052     }
9053   else
9054     coerced_args = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parms),
9055 					  args, in_decl, complain,
9056 					  require_all_args,
9057 					  use_default_args);
9058   return coerced_args;
9059 }
9060 
9061 /* Returns true if T is a wrapper to make a C++20 template parameter
9062    object const.  */
9063 
9064 static bool
class_nttp_const_wrapper_p(tree t)9065 class_nttp_const_wrapper_p (tree t)
9066 {
9067   if (cxx_dialect < cxx2a)
9068     return false;
9069   return (TREE_CODE (t) == VIEW_CONVERT_EXPR
9070 	  && CP_TYPE_CONST_P (TREE_TYPE (t))
9071 	  && TREE_CODE (TREE_OPERAND (t, 0)) == TEMPLATE_PARM_INDEX);
9072 }
9073 
9074 /* Returns 1 if template args OT and NT are equivalent.  */
9075 
9076 int
template_args_equal(tree ot,tree nt,bool partial_order)9077 template_args_equal (tree ot, tree nt, bool partial_order /* = false */)
9078 {
9079   if (nt == ot)
9080     return 1;
9081   if (nt == NULL_TREE || ot == NULL_TREE)
9082     return false;
9083   if (nt == any_targ_node || ot == any_targ_node)
9084     return true;
9085 
9086   if (class_nttp_const_wrapper_p (nt))
9087     nt = TREE_OPERAND (nt, 0);
9088   if (class_nttp_const_wrapper_p (ot))
9089     ot = TREE_OPERAND (ot, 0);
9090 
9091   if (TREE_CODE (nt) == TREE_VEC)
9092     /* For member templates */
9093     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
9094   else if (PACK_EXPANSION_P (ot))
9095     return (PACK_EXPANSION_P (nt)
9096 	    && template_args_equal (PACK_EXPANSION_PATTERN (ot),
9097 				    PACK_EXPANSION_PATTERN (nt))
9098 	    && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
9099 				    PACK_EXPANSION_EXTRA_ARGS (nt)));
9100   else if (ARGUMENT_PACK_P (ot) || ARGUMENT_PACK_P (nt))
9101     return cp_tree_equal (ot, nt);
9102   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
9103     gcc_unreachable ();
9104   else if (TYPE_P (nt))
9105     {
9106       if (!TYPE_P (ot))
9107 	return false;
9108       /* Don't treat an alias template specialization with dependent
9109 	 arguments as equivalent to its underlying type when used as a
9110 	 template argument; we need them to be distinct so that we
9111 	 substitute into the specialization arguments at instantiation
9112 	 time.  And aliases can't be equivalent without being ==, so
9113 	 we don't need to look any deeper.
9114 
9115          During partial ordering, however, we need to treat them normally so
9116          that we can order uses of the same alias with different
9117          cv-qualification (79960).  */
9118       if (!partial_order
9119 	  && (TYPE_ALIAS_P (nt) || TYPE_ALIAS_P (ot)))
9120 	return false;
9121       else
9122 	return same_type_p (ot, nt);
9123     }
9124   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
9125     return 0;
9126   else
9127     {
9128       /* Try to treat a template non-type argument that has been converted
9129 	 to the parameter type as equivalent to one that hasn't yet.  */
9130       for (enum tree_code code1 = TREE_CODE (ot);
9131 	   CONVERT_EXPR_CODE_P (code1)
9132 	     || code1 == NON_LVALUE_EXPR;
9133 	   code1 = TREE_CODE (ot))
9134 	ot = TREE_OPERAND (ot, 0);
9135       for (enum tree_code code2 = TREE_CODE (nt);
9136 	   CONVERT_EXPR_CODE_P (code2)
9137 	     || code2 == NON_LVALUE_EXPR;
9138 	   code2 = TREE_CODE (nt))
9139 	nt = TREE_OPERAND (nt, 0);
9140 
9141       return cp_tree_equal (ot, nt);
9142     }
9143 }
9144 
9145 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
9146    template arguments.  Returns 0 otherwise, and updates OLDARG_PTR and
9147    NEWARG_PTR with the offending arguments if they are non-NULL.  */
9148 
9149 int
comp_template_args(tree oldargs,tree newargs,tree * oldarg_ptr,tree * newarg_ptr,bool partial_order)9150 comp_template_args (tree oldargs, tree newargs,
9151 		    tree *oldarg_ptr, tree *newarg_ptr,
9152 		    bool partial_order)
9153 {
9154   int i;
9155 
9156   if (oldargs == newargs)
9157     return 1;
9158 
9159   if (!oldargs || !newargs)
9160     return 0;
9161 
9162   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
9163     return 0;
9164 
9165   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
9166     {
9167       tree nt = TREE_VEC_ELT (newargs, i);
9168       tree ot = TREE_VEC_ELT (oldargs, i);
9169 
9170       if (! template_args_equal (ot, nt, partial_order))
9171 	{
9172 	  if (oldarg_ptr != NULL)
9173 	    *oldarg_ptr = ot;
9174 	  if (newarg_ptr != NULL)
9175 	    *newarg_ptr = nt;
9176 	  return 0;
9177 	}
9178     }
9179   return 1;
9180 }
9181 
9182 inline bool
comp_template_args_porder(tree oargs,tree nargs)9183 comp_template_args_porder (tree oargs, tree nargs)
9184 {
9185   return comp_template_args (oargs, nargs, NULL, NULL, true);
9186 }
9187 
9188 /* Implement a freelist interface for objects of type T.
9189 
9190    Head is a separate object, rather than a regular member, so that we
9191    can define it as a GTY deletable pointer, which is highly
9192    desirable.  A data member could be declared that way, but then the
9193    containing object would implicitly get GTY((user)), which would
9194    prevent us from instantiating freelists as global objects.
9195    Although this way we can create freelist global objects, they're
9196    such thin wrappers that instantiating temporaries at every use
9197    loses nothing and saves permanent storage for the freelist object.
9198 
9199    Member functions next, anew, poison and reinit have default
9200    implementations that work for most of the types we're interested
9201    in, but if they don't work for some type, they should be explicitly
9202    specialized.  See the comments before them for requirements, and
9203    the example specializations for the tree_list_freelist.  */
9204 template <typename T>
9205 class freelist
9206 {
9207   /* Return the next object in a chain.  We could just do type
9208      punning, but if we access the object with its underlying type, we
9209      avoid strict-aliasing trouble.  This needs only work between
9210      poison and reinit.  */
next(T * obj)9211   static T *&next (T *obj) { return obj->next; }
9212 
9213   /* Return a newly allocated, uninitialized or minimally-initialized
9214      object of type T.  Any initialization performed by anew should
9215      either remain across the life of the object and the execution of
9216      poison, or be redone by reinit.  */
anew()9217   static T *anew () { return ggc_alloc<T> (); }
9218 
9219   /* Optionally scribble all over the bits holding the object, so that
9220      they become (mostly?) uninitialized memory.  This is called while
9221      preparing to make the object part of the free list.  */
poison(T * obj)9222   static void poison (T *obj) {
9223     T *p ATTRIBUTE_UNUSED = obj;
9224     T **q ATTRIBUTE_UNUSED = &next (obj);
9225 
9226 #ifdef ENABLE_GC_CHECKING
9227     /* Poison the data, to indicate the data is garbage.  */
9228     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, sizeof (*p)));
9229     memset (p, 0xa5, sizeof (*p));
9230 #endif
9231     /* Let valgrind know the object is free.  */
9232     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, sizeof (*p)));
9233 
9234     /* Let valgrind know the next portion of the object is available,
9235        but uninitialized.  */
9236     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9237   }
9238 
9239   /* Bring an object that underwent at least one lifecycle after anew
9240      and before the most recent free and poison, back to a usable
9241      state, reinitializing whatever is needed for it to be
9242      functionally equivalent to an object just allocated and returned
9243      by anew.  This may poison or clear the next field, used by
9244      freelist housekeeping after poison was called.  */
reinit(T * obj)9245   static void reinit (T *obj) {
9246     T **q ATTRIBUTE_UNUSED = &next (obj);
9247 
9248 #ifdef ENABLE_GC_CHECKING
9249     memset (q, 0xa5, sizeof (*q));
9250 #endif
9251     /* Let valgrind know the entire object is available, but
9252        uninitialized.  */
9253     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (*obj)));
9254   }
9255 
9256   /* Reference a GTY-deletable pointer that points to the first object
9257      in the free list proper.  */
9258   T *&head;
9259 public:
9260   /* Construct a freelist object chaining objects off of HEAD.  */
freelist(T * & head)9261   freelist (T *&head) : head(head) {}
9262 
9263   /* Add OBJ to the free object list.  The former head becomes OBJ's
9264      successor.  */
free(T * obj)9265   void free (T *obj)
9266   {
9267     poison (obj);
9268     next (obj) = head;
9269     head = obj;
9270   }
9271 
9272   /* Take an object from the free list, if one is available, or
9273      allocate a new one.  Objects taken from the free list should be
9274      regarded as filled with garbage, except for bits that are
9275      configured to be preserved across free and alloc.  */
alloc()9276   T *alloc ()
9277   {
9278     if (head)
9279       {
9280 	T *obj = head;
9281 	head = next (head);
9282 	reinit (obj);
9283 	return obj;
9284       }
9285     else
9286       return anew ();
9287   }
9288 };
9289 
9290 /* Explicitly specialize the interfaces for freelist<tree_node>: we
9291    want to allocate a TREE_LIST using the usual interface, and ensure
9292    TREE_CHAIN remains functional.  Alas, we have to duplicate a bit of
9293    build_tree_list logic in reinit, so this could go out of sync.  */
9294 template <>
9295 inline tree &
next(tree obj)9296 freelist<tree_node>::next (tree obj)
9297 {
9298   return TREE_CHAIN (obj);
9299 }
9300 template <>
9301 inline tree
anew()9302 freelist<tree_node>::anew ()
9303 {
9304   return build_tree_list (NULL, NULL);
9305 }
9306 template <>
9307 inline void
poison(tree obj ATTRIBUTE_UNUSED)9308 freelist<tree_node>::poison (tree obj ATTRIBUTE_UNUSED)
9309 {
9310   int size ATTRIBUTE_UNUSED = sizeof (tree_list);
9311   tree p ATTRIBUTE_UNUSED = obj;
9312   tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9313   tree *q ATTRIBUTE_UNUSED = &next (obj);
9314 
9315 #ifdef ENABLE_GC_CHECKING
9316   gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9317 
9318   /* Poison the data, to indicate the data is garbage.  */
9319   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, size));
9320   memset (p, 0xa5, size);
9321 #endif
9322   /* Let valgrind know the object is free.  */
9323   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, size));
9324   /* But we still want to use the TREE_CODE and TREE_CHAIN parts.  */
9325   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9326   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9327 
9328 #ifdef ENABLE_GC_CHECKING
9329   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (b, sizeof (*b)));
9330   /* Keep TREE_CHAIN functional.  */
9331   TREE_SET_CODE (obj, TREE_LIST);
9332 #else
9333   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9334 #endif
9335 }
9336 template <>
9337 inline void
reinit(tree obj ATTRIBUTE_UNUSED)9338 freelist<tree_node>::reinit (tree obj ATTRIBUTE_UNUSED)
9339 {
9340   tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9341 
9342 #ifdef ENABLE_GC_CHECKING
9343   gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9344   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9345   memset (obj, 0, sizeof (tree_list));
9346 #endif
9347 
9348   /* Let valgrind know the entire object is available, but
9349      uninitialized.  */
9350   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9351 
9352 #ifdef ENABLE_GC_CHECKING
9353   TREE_SET_CODE (obj, TREE_LIST);
9354 #else
9355   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9356 #endif
9357 }
9358 
9359 /* Point to the first object in the TREE_LIST freelist.  */
9360 static GTY((deletable)) tree tree_list_freelist_head;
9361 /* Return the/an actual TREE_LIST freelist.  */
9362 static inline freelist<tree_node>
tree_list_freelist()9363 tree_list_freelist ()
9364 {
9365   return tree_list_freelist_head;
9366 }
9367 
9368 /* Point to the first object in the tinst_level freelist.  */
9369 static GTY((deletable)) tinst_level *tinst_level_freelist_head;
9370 /* Return the/an actual tinst_level freelist.  */
9371 static inline freelist<tinst_level>
tinst_level_freelist()9372 tinst_level_freelist ()
9373 {
9374   return tinst_level_freelist_head;
9375 }
9376 
9377 /* Point to the first object in the pending_template freelist.  */
9378 static GTY((deletable)) pending_template *pending_template_freelist_head;
9379 /* Return the/an actual pending_template freelist.  */
9380 static inline freelist<pending_template>
pending_template_freelist()9381 pending_template_freelist ()
9382 {
9383   return pending_template_freelist_head;
9384 }
9385 
9386 /* Build the TREE_LIST object out of a split list, store it
9387    permanently, and return it.  */
9388 tree
to_list()9389 tinst_level::to_list ()
9390 {
9391   gcc_assert (split_list_p ());
9392   tree ret = tree_list_freelist ().alloc ();
9393   TREE_PURPOSE (ret) = tldcl;
9394   TREE_VALUE (ret) = targs;
9395   tldcl = ret;
9396   targs = NULL;
9397   gcc_assert (tree_list_p ());
9398   return ret;
9399 }
9400 
9401 const unsigned short tinst_level::refcount_infinity;
9402 
9403 /* Increment OBJ's refcount unless it is already infinite.  */
9404 static tinst_level *
inc_refcount_use(tinst_level * obj)9405 inc_refcount_use (tinst_level *obj)
9406 {
9407   if (obj && obj->refcount != tinst_level::refcount_infinity)
9408     ++obj->refcount;
9409   return obj;
9410 }
9411 
9412 /* Release storage for OBJ and node, if it's a TREE_LIST.  */
9413 void
free(tinst_level * obj)9414 tinst_level::free (tinst_level *obj)
9415 {
9416   if (obj->tree_list_p ())
9417     tree_list_freelist ().free (obj->get_node ());
9418   tinst_level_freelist ().free (obj);
9419 }
9420 
9421 /* Decrement OBJ's refcount if not infinite.  If it reaches zero, release
9422    OBJ's DECL and OBJ, and start over with the tinst_level object that
9423    used to be referenced by OBJ's NEXT.  */
9424 static void
dec_refcount_use(tinst_level * obj)9425 dec_refcount_use (tinst_level *obj)
9426 {
9427   while (obj
9428 	 && obj->refcount != tinst_level::refcount_infinity
9429 	 && !--obj->refcount)
9430     {
9431       tinst_level *next = obj->next;
9432       tinst_level::free (obj);
9433       obj = next;
9434     }
9435 }
9436 
9437 /* Modify PTR so that it points to OBJ, adjusting the refcounts of OBJ
9438    and of the former PTR.  Omitting the second argument is equivalent
9439    to passing (T*)NULL; this is allowed because passing the
9440    zero-valued integral constant NULL confuses type deduction and/or
9441    overload resolution.  */
9442 template <typename T>
9443 static void
9444 set_refcount_ptr (T *& ptr, T *obj = NULL)
9445 {
9446   T *save = ptr;
9447   ptr = inc_refcount_use (obj);
9448   dec_refcount_use (save);
9449 }
9450 
9451 static void
add_pending_template(tree d)9452 add_pending_template (tree d)
9453 {
9454   tree ti = (TYPE_P (d)
9455 	     ? CLASSTYPE_TEMPLATE_INFO (d)
9456 	     : DECL_TEMPLATE_INFO (d));
9457   struct pending_template *pt;
9458   int level;
9459 
9460   if (TI_PENDING_TEMPLATE_FLAG (ti))
9461     return;
9462 
9463   /* We are called both from instantiate_decl, where we've already had a
9464      tinst_level pushed, and instantiate_template, where we haven't.
9465      Compensate.  */
9466   gcc_assert (TREE_CODE (d) != TREE_LIST);
9467   level = !current_tinst_level
9468     || current_tinst_level->maybe_get_node () != d;
9469 
9470   if (level)
9471     push_tinst_level (d);
9472 
9473   pt = pending_template_freelist ().alloc ();
9474   pt->next = NULL;
9475   pt->tinst = NULL;
9476   set_refcount_ptr (pt->tinst, current_tinst_level);
9477   if (last_pending_template)
9478     last_pending_template->next = pt;
9479   else
9480     pending_templates = pt;
9481 
9482   last_pending_template = pt;
9483 
9484   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
9485 
9486   if (level)
9487     pop_tinst_level ();
9488 }
9489 
9490 
9491 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
9492    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
9493    documentation for TEMPLATE_ID_EXPR.  */
9494 
9495 tree
lookup_template_function(tree fns,tree arglist)9496 lookup_template_function (tree fns, tree arglist)
9497 {
9498   if (fns == error_mark_node || arglist == error_mark_node)
9499     return error_mark_node;
9500 
9501   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
9502 
9503   if (!is_overloaded_fn (fns) && !identifier_p (fns))
9504     {
9505       error ("%q#D is not a function template", fns);
9506       return error_mark_node;
9507     }
9508 
9509   if (BASELINK_P (fns))
9510     {
9511       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
9512 					 unknown_type_node,
9513 					 BASELINK_FUNCTIONS (fns),
9514 					 arglist);
9515       return fns;
9516     }
9517 
9518   return build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, arglist);
9519 }
9520 
9521 /* Within the scope of a template class S<T>, the name S gets bound
9522    (in build_self_reference) to a TYPE_DECL for the class, not a
9523    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
9524    or one of its enclosing classes, and that type is a template,
9525    return the associated TEMPLATE_DECL.  Otherwise, the original
9526    DECL is returned.
9527 
9528    Also handle the case when DECL is a TREE_LIST of ambiguous
9529    injected-class-names from different bases.  */
9530 
9531 tree
maybe_get_template_decl_from_type_decl(tree decl)9532 maybe_get_template_decl_from_type_decl (tree decl)
9533 {
9534   if (decl == NULL_TREE)
9535     return decl;
9536 
9537   /* DR 176: A lookup that finds an injected-class-name (10.2
9538      [class.member.lookup]) can result in an ambiguity in certain cases
9539      (for example, if it is found in more than one base class). If all of
9540      the injected-class-names that are found refer to specializations of
9541      the same class template, and if the name is followed by a
9542      template-argument-list, the reference refers to the class template
9543      itself and not a specialization thereof, and is not ambiguous.  */
9544   if (TREE_CODE (decl) == TREE_LIST)
9545     {
9546       tree t, tmpl = NULL_TREE;
9547       for (t = decl; t; t = TREE_CHAIN (t))
9548 	{
9549 	  tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
9550 	  if (!tmpl)
9551 	    tmpl = elt;
9552 	  else if (tmpl != elt)
9553 	    break;
9554 	}
9555       if (tmpl && t == NULL_TREE)
9556 	return tmpl;
9557       else
9558 	return decl;
9559     }
9560 
9561   return (decl != NULL_TREE
9562 	  && DECL_SELF_REFERENCE_P (decl)
9563 	  && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
9564     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
9565 }
9566 
9567 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
9568    parameters, find the desired type.
9569 
9570    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
9571 
9572    IN_DECL, if non-NULL, is the template declaration we are trying to
9573    instantiate.
9574 
9575    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
9576    the class we are looking up.
9577 
9578    Issue error and warning messages under control of COMPLAIN.
9579 
9580    If the template class is really a local class in a template
9581    function, then the FUNCTION_CONTEXT is the function in which it is
9582    being instantiated.
9583 
9584    ??? Note that this function is currently called *twice* for each
9585    template-id: the first time from the parser, while creating the
9586    incomplete type (finish_template_type), and the second type during the
9587    real instantiation (instantiate_template_class). This is surely something
9588    that we want to avoid. It also causes some problems with argument
9589    coercion (see convert_nontype_argument for more information on this).  */
9590 
9591 static tree
lookup_template_class_1(tree d1,tree arglist,tree in_decl,tree context,int entering_scope,tsubst_flags_t complain)9592 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
9593 			 int entering_scope, tsubst_flags_t complain)
9594 {
9595   tree templ = NULL_TREE, parmlist;
9596   tree t;
9597   spec_entry **slot;
9598   spec_entry *entry;
9599   spec_entry elt;
9600   hashval_t hash;
9601 
9602   if (identifier_p (d1))
9603     {
9604       tree value = innermost_non_namespace_value (d1);
9605       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
9606 	templ = value;
9607       else
9608 	{
9609 	  if (context)
9610 	    push_decl_namespace (context);
9611 	  templ = lookup_name (d1);
9612 	  templ = maybe_get_template_decl_from_type_decl (templ);
9613 	  if (context)
9614 	    pop_decl_namespace ();
9615 	}
9616       if (templ)
9617 	context = DECL_CONTEXT (templ);
9618     }
9619   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
9620     {
9621       tree type = TREE_TYPE (d1);
9622 
9623       /* If we are declaring a constructor, say A<T>::A<T>, we will get
9624 	 an implicit typename for the second A.  Deal with it.  */
9625       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
9626 	type = TREE_TYPE (type);
9627 
9628       if (CLASSTYPE_TEMPLATE_INFO (type))
9629 	{
9630 	  templ = CLASSTYPE_TI_TEMPLATE (type);
9631 	  d1 = DECL_NAME (templ);
9632 	}
9633     }
9634   else if (TREE_CODE (d1) == ENUMERAL_TYPE
9635 	   || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
9636     {
9637       templ = TYPE_TI_TEMPLATE (d1);
9638       d1 = DECL_NAME (templ);
9639     }
9640   else if (DECL_TYPE_TEMPLATE_P (d1))
9641     {
9642       templ = d1;
9643       d1 = DECL_NAME (templ);
9644       context = DECL_CONTEXT (templ);
9645     }
9646   else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
9647     {
9648       templ = d1;
9649       d1 = DECL_NAME (templ);
9650     }
9651 
9652   /* Issue an error message if we didn't find a template.  */
9653   if (! templ)
9654     {
9655       if (complain & tf_error)
9656 	error ("%qT is not a template", d1);
9657       return error_mark_node;
9658     }
9659 
9660   if (TREE_CODE (templ) != TEMPLATE_DECL
9661 	 /* Make sure it's a user visible template, if it was named by
9662 	    the user.  */
9663       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
9664 	  && !PRIMARY_TEMPLATE_P (templ)))
9665     {
9666       if (complain & tf_error)
9667 	{
9668 	  error ("non-template type %qT used as a template", d1);
9669 	  if (in_decl)
9670 	    error ("for template declaration %q+D", in_decl);
9671 	}
9672       return error_mark_node;
9673     }
9674 
9675   complain &= ~tf_user;
9676 
9677   /* An alias that just changes the name of a template is equivalent to the
9678      other template, so if any of the arguments are pack expansions, strip
9679      the alias to avoid problems with a pack expansion passed to a non-pack
9680      alias template parameter (DR 1430).  */
9681   if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
9682     templ = get_underlying_template (templ);
9683 
9684   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
9685     {
9686       tree parm;
9687       tree arglist2 = coerce_template_args_for_ttp (templ, arglist, complain);
9688       if (arglist2 == error_mark_node
9689 	  || (!uses_template_parms (arglist2)
9690 	      && check_instantiated_args (templ, arglist2, complain)))
9691 	return error_mark_node;
9692 
9693       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
9694       return parm;
9695     }
9696   else
9697     {
9698       tree template_type = TREE_TYPE (templ);
9699       tree gen_tmpl;
9700       tree type_decl;
9701       tree found = NULL_TREE;
9702       int arg_depth;
9703       int parm_depth;
9704       int is_dependent_type;
9705       int use_partial_inst_tmpl = false;
9706 
9707       if (template_type == error_mark_node)
9708 	/* An error occurred while building the template TEMPL, and a
9709 	   diagnostic has most certainly been emitted for that
9710 	   already.  Let's propagate that error.  */
9711 	return error_mark_node;
9712 
9713       gen_tmpl = most_general_template (templ);
9714       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
9715       parm_depth = TMPL_PARMS_DEPTH (parmlist);
9716       arg_depth = TMPL_ARGS_DEPTH (arglist);
9717 
9718       if (arg_depth == 1 && parm_depth > 1)
9719 	{
9720 	  /* We've been given an incomplete set of template arguments.
9721 	     For example, given:
9722 
9723 	       template <class T> struct S1 {
9724 		 template <class U> struct S2 {};
9725 		 template <class U> struct S2<U*> {};
9726 		};
9727 
9728 	     we will be called with an ARGLIST of `U*', but the
9729 	     TEMPLATE will be `template <class T> template
9730 	     <class U> struct S1<T>::S2'.  We must fill in the missing
9731 	     arguments.  */
9732 	  tree ti = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (templ));
9733 	  arglist = add_outermost_template_args (TI_ARGS (ti), arglist);
9734 	  arg_depth = TMPL_ARGS_DEPTH (arglist);
9735 	}
9736 
9737       /* Now we should have enough arguments.  */
9738       gcc_assert (parm_depth == arg_depth);
9739 
9740       /* From here on, we're only interested in the most general
9741 	 template.  */
9742 
9743       /* Calculate the BOUND_ARGS.  These will be the args that are
9744 	 actually tsubst'd into the definition to create the
9745 	 instantiation.  */
9746       arglist = coerce_innermost_template_parms (parmlist, arglist, gen_tmpl,
9747 						 complain,
9748 						 /*require_all_args=*/true,
9749 						 /*use_default_args=*/true);
9750 
9751       if (arglist == error_mark_node)
9752 	/* We were unable to bind the arguments.  */
9753 	return error_mark_node;
9754 
9755       /* In the scope of a template class, explicit references to the
9756 	 template class refer to the type of the template, not any
9757 	 instantiation of it.  For example, in:
9758 
9759 	   template <class T> class C { void f(C<T>); }
9760 
9761 	 the `C<T>' is just the same as `C'.  Outside of the
9762 	 class, however, such a reference is an instantiation.  */
9763       if (entering_scope
9764 	  || !PRIMARY_TEMPLATE_P (gen_tmpl)
9765 	  || currently_open_class (template_type))
9766 	{
9767 	  tree tinfo = TYPE_TEMPLATE_INFO (template_type);
9768 
9769 	  if (tinfo && comp_template_args (TI_ARGS (tinfo), arglist))
9770 	    return template_type;
9771 	}
9772 
9773       /* If we already have this specialization, return it.  */
9774       elt.tmpl = gen_tmpl;
9775       elt.args = arglist;
9776       elt.spec = NULL_TREE;
9777       hash = spec_hasher::hash (&elt);
9778       entry = type_specializations->find_with_hash (&elt, hash);
9779 
9780       if (entry)
9781 	return entry->spec;
9782 
9783       /* If the template's constraints are not satisfied,
9784          then we cannot form a valid type.
9785 
9786          Note that the check is deferred until after the hash
9787          lookup. This prevents redundant checks on previously
9788          instantiated specializations. */
9789       if (flag_concepts
9790 	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl)
9791 	  && !constraints_satisfied_p (gen_tmpl, arglist))
9792         {
9793           if (complain & tf_error)
9794             {
9795 	      auto_diagnostic_group d;
9796               error ("template constraint failure for %qD", gen_tmpl);
9797               diagnose_constraints (input_location, gen_tmpl, arglist);
9798             }
9799           return error_mark_node;
9800         }
9801 
9802       is_dependent_type = uses_template_parms (arglist);
9803 
9804       /* If the deduced arguments are invalid, then the binding
9805 	 failed.  */
9806       if (!is_dependent_type
9807 	  && check_instantiated_args (gen_tmpl,
9808 				      INNERMOST_TEMPLATE_ARGS (arglist),
9809 				      complain))
9810 	return error_mark_node;
9811 
9812       if (!is_dependent_type
9813 	  && !PRIMARY_TEMPLATE_P (gen_tmpl)
9814 	  && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
9815 	  && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
9816 	{
9817 	  found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
9818 				      DECL_NAME (gen_tmpl),
9819 				      /*tag_scope=*/ts_global);
9820 	  return found;
9821 	}
9822 
9823       context = DECL_CONTEXT (gen_tmpl);
9824       if (context && TYPE_P (context))
9825 	{
9826 	  context = tsubst_aggr_type (context, arglist, complain, in_decl, true);
9827 	  context = complete_type (context);
9828 	}
9829       else
9830 	context = tsubst (context, arglist, complain, in_decl);
9831 
9832       if (context == error_mark_node)
9833 	return error_mark_node;
9834 
9835       if (!context)
9836 	context = global_namespace;
9837 
9838       /* Create the type.  */
9839       if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9840 	{
9841 	  /* The user referred to a specialization of an alias
9842 	    template represented by GEN_TMPL.
9843 
9844 	    [temp.alias]/2 says:
9845 
9846 	        When a template-id refers to the specialization of an
9847 		alias template, it is equivalent to the associated
9848 		type obtained by substitution of its
9849 		template-arguments for the template-parameters in the
9850 		type-id of the alias template.  */
9851 
9852 	  t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
9853 	  /* Note that the call above (by indirectly calling
9854 	     register_specialization in tsubst_decl) registers the
9855 	     TYPE_DECL representing the specialization of the alias
9856 	     template.  So next time someone substitutes ARGLIST for
9857 	     the template parms into the alias template (GEN_TMPL),
9858 	     she'll get that TYPE_DECL back.  */
9859 
9860 	  if (t == error_mark_node)
9861 	    return t;
9862 	}
9863       else if (TREE_CODE (template_type) == ENUMERAL_TYPE)
9864 	{
9865 	  if (!is_dependent_type)
9866 	    {
9867 	      set_current_access_from_decl (TYPE_NAME (template_type));
9868 	      t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
9869 			      tsubst (ENUM_UNDERLYING_TYPE (template_type),
9870 				      arglist, complain, in_decl),
9871 			      tsubst_attributes (TYPE_ATTRIBUTES (template_type),
9872 						 arglist, complain, in_decl),
9873 			      SCOPED_ENUM_P (template_type), NULL);
9874 
9875 	      if (t == error_mark_node)
9876 		return t;
9877 	    }
9878 	  else
9879             {
9880               /* We don't want to call start_enum for this type, since
9881                  the values for the enumeration constants may involve
9882                  template parameters.  And, no one should be interested
9883                  in the enumeration constants for such a type.  */
9884               t = cxx_make_type (ENUMERAL_TYPE);
9885               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
9886             }
9887           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
9888 	  ENUM_FIXED_UNDERLYING_TYPE_P (t)
9889 	    = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
9890 	}
9891       else if (CLASS_TYPE_P (template_type))
9892 	{
9893 	  /* Lambda closures are regenerated in tsubst_lambda_expr, not
9894 	     instantiated here.  */
9895 	  gcc_assert (!LAMBDA_TYPE_P (template_type));
9896 
9897 	  t = make_class_type (TREE_CODE (template_type));
9898 	  CLASSTYPE_DECLARED_CLASS (t)
9899 	    = CLASSTYPE_DECLARED_CLASS (template_type);
9900 	  SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
9901 
9902 	  /* A local class.  Make sure the decl gets registered properly.  */
9903 	  if (context == current_function_decl)
9904 	    if (pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current)
9905 		== error_mark_node)
9906 	      return error_mark_node;
9907 
9908 	  if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
9909 	    /* This instantiation is another name for the primary
9910 	       template type. Set the TYPE_CANONICAL field
9911 	       appropriately. */
9912 	    TYPE_CANONICAL (t) = template_type;
9913 	  else if (any_template_arguments_need_structural_equality_p (arglist))
9914 	    /* Some of the template arguments require structural
9915 	       equality testing, so this template class requires
9916 	       structural equality testing. */
9917 	    SET_TYPE_STRUCTURAL_EQUALITY (t);
9918 	}
9919       else
9920 	gcc_unreachable ();
9921 
9922       /* If we called start_enum or pushtag above, this information
9923 	 will already be set up.  */
9924       if (!TYPE_NAME (t))
9925 	{
9926 	  TYPE_CONTEXT (t) = FROB_CONTEXT (context);
9927 
9928 	  type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
9929 	  DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
9930 	  DECL_SOURCE_LOCATION (type_decl)
9931 	    = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
9932 	}
9933       else
9934 	type_decl = TYPE_NAME (t);
9935 
9936       if (CLASS_TYPE_P (template_type))
9937 	{
9938 	  TREE_PRIVATE (type_decl)
9939 	    = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
9940 	  TREE_PROTECTED (type_decl)
9941 	    = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
9942 	  if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
9943 	    {
9944 	      DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
9945 	      DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
9946 	    }
9947 	}
9948 
9949       if (OVERLOAD_TYPE_P (t)
9950 	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9951 	{
9952 	  static const char *tags[] = {"abi_tag", "may_alias"};
9953 
9954 	  for (unsigned ix = 0; ix != 2; ix++)
9955 	    {
9956 	      tree attributes
9957 		= lookup_attribute (tags[ix], TYPE_ATTRIBUTES (template_type));
9958 
9959 	      if (attributes)
9960 		TYPE_ATTRIBUTES (t)
9961 		  = tree_cons (TREE_PURPOSE (attributes),
9962 			       TREE_VALUE (attributes),
9963 			       TYPE_ATTRIBUTES (t));
9964 	    }
9965 	}
9966 
9967       /* Let's consider the explicit specialization of a member
9968          of a class template specialization that is implicitly instantiated,
9969 	 e.g.:
9970 	     template<class T>
9971 	     struct S
9972 	     {
9973 	       template<class U> struct M {}; //#0
9974 	     };
9975 
9976 	     template<>
9977 	     template<>
9978 	     struct S<int>::M<char> //#1
9979 	     {
9980 	       int i;
9981 	     };
9982 	[temp.expl.spec]/4 says this is valid.
9983 
9984 	In this case, when we write:
9985 	S<int>::M<char> m;
9986 
9987 	M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
9988 	the one of #0.
9989 
9990 	When we encounter #1, we want to store the partial instantiation
9991 	of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
9992 
9993 	For all cases other than this "explicit specialization of member of a
9994 	class template", we just want to store the most general template into
9995 	the CLASSTYPE_TI_TEMPLATE of M.
9996 
9997 	This case of "explicit specialization of member of a class template"
9998 	only happens when:
9999 	1/ the enclosing class is an instantiation of, and therefore not
10000 	the same as, the context of the most general template, and
10001 	2/ we aren't looking at the partial instantiation itself, i.e.
10002 	the innermost arguments are not the same as the innermost parms of
10003 	the most general template.
10004 
10005 	So it's only when 1/ and 2/ happens that we want to use the partial
10006 	instantiation of the member template in lieu of its most general
10007 	template.  */
10008 
10009       if (PRIMARY_TEMPLATE_P (gen_tmpl)
10010 	  && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
10011 	  /* the enclosing class must be an instantiation...  */
10012 	  && CLASS_TYPE_P (context)
10013 	  && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
10014 	{
10015 	  TREE_VEC_LENGTH (arglist)--;
10016 	  ++processing_template_decl;
10017 	  tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (gen_tmpl));
10018 	  tree partial_inst_args =
10019 	    tsubst (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)),
10020 		    arglist, complain, NULL_TREE);
10021 	  --processing_template_decl;
10022 	  TREE_VEC_LENGTH (arglist)++;
10023 	  if (partial_inst_args == error_mark_node)
10024 	    return error_mark_node;
10025 	  use_partial_inst_tmpl =
10026 	    /*...and we must not be looking at the partial instantiation
10027 	     itself. */
10028 	    !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
10029 				 partial_inst_args);
10030 	}
10031 
10032       if (!use_partial_inst_tmpl)
10033 	/* This case is easy; there are no member templates involved.  */
10034 	found = gen_tmpl;
10035       else
10036 	{
10037 	  /* This is a full instantiation of a member template.  Find
10038 	     the partial instantiation of which this is an instance.  */
10039 
10040 	  /* Temporarily reduce by one the number of levels in the ARGLIST
10041 	     so as to avoid comparing the last set of arguments.  */
10042 	  TREE_VEC_LENGTH (arglist)--;
10043 	  found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
10044 	  TREE_VEC_LENGTH (arglist)++;
10045 	  /* FOUND is either a proper class type, or an alias
10046 	     template specialization.  In the later case, it's a
10047 	     TYPE_DECL, resulting from the substituting of arguments
10048 	     for parameters in the TYPE_DECL of the alias template
10049 	     done earlier.  So be careful while getting the template
10050 	     of FOUND.  */
10051 	  found = (TREE_CODE (found) == TEMPLATE_DECL
10052 		   ? found
10053 		   : (TREE_CODE (found) == TYPE_DECL
10054 		      ? DECL_TI_TEMPLATE (found)
10055 		      : CLASSTYPE_TI_TEMPLATE (found)));
10056 
10057 	  if (DECL_CLASS_TEMPLATE_P (found)
10058 	      && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (found)))
10059 	    {
10060 	      /* If this partial instantiation is specialized, we want to
10061 		 use it for hash table lookup.  */
10062 	      elt.tmpl = found;
10063 	      elt.args = arglist = INNERMOST_TEMPLATE_ARGS (arglist);
10064 	      hash = spec_hasher::hash (&elt);
10065 	    }
10066 	}
10067 
10068       // Build template info for the new specialization.
10069       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
10070 
10071       elt.spec = t;
10072       slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
10073       gcc_checking_assert (*slot == NULL);
10074       entry = ggc_alloc<spec_entry> ();
10075       *entry = elt;
10076       *slot = entry;
10077 
10078       /* Note this use of the partial instantiation so we can check it
10079 	 later in maybe_process_partial_specialization.  */
10080       DECL_TEMPLATE_INSTANTIATIONS (found)
10081 	= tree_cons (arglist, t,
10082 		     DECL_TEMPLATE_INSTANTIATIONS (found));
10083 
10084       if (TREE_CODE (template_type) == ENUMERAL_TYPE && !is_dependent_type
10085 	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10086 	/* Now that the type has been registered on the instantiations
10087 	   list, we set up the enumerators.  Because the enumeration
10088 	   constants may involve the enumeration type itself, we make
10089 	   sure to register the type first, and then create the
10090 	   constants.  That way, doing tsubst_expr for the enumeration
10091 	   constants won't result in recursive calls here; we'll find
10092 	   the instantiation and exit above.  */
10093 	tsubst_enum (template_type, t, arglist);
10094 
10095       if (CLASS_TYPE_P (template_type) && is_dependent_type)
10096 	/* If the type makes use of template parameters, the
10097 	   code that generates debugging information will crash.  */
10098 	DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
10099 
10100       /* Possibly limit visibility based on template args.  */
10101       TREE_PUBLIC (type_decl) = 1;
10102       determine_visibility (type_decl);
10103 
10104       inherit_targ_abi_tags (t);
10105 
10106       return t;
10107     }
10108 }
10109 
10110 /* Wrapper for lookup_template_class_1.  */
10111 
10112 tree
lookup_template_class(tree d1,tree arglist,tree in_decl,tree context,int entering_scope,tsubst_flags_t complain)10113 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
10114                        int entering_scope, tsubst_flags_t complain)
10115 {
10116   tree ret;
10117   timevar_push (TV_TEMPLATE_INST);
10118   ret = lookup_template_class_1 (d1, arglist, in_decl, context,
10119                                  entering_scope, complain);
10120   timevar_pop (TV_TEMPLATE_INST);
10121   return ret;
10122 }
10123 
10124 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST.  */
10125 
10126 tree
lookup_template_variable(tree templ,tree arglist)10127 lookup_template_variable (tree templ, tree arglist)
10128 {
10129   if (flag_concepts && variable_concept_p (templ))
10130     return build_concept_check (templ, arglist, tf_none);
10131 
10132   /* The type of the expression is NULL_TREE since the template-id could refer
10133      to an explicit or partial specialization. */
10134   return build2 (TEMPLATE_ID_EXPR, NULL_TREE, templ, arglist);
10135 }
10136 
10137 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR for use. */
10138 
10139 tree
finish_template_variable(tree var,tsubst_flags_t complain)10140 finish_template_variable (tree var, tsubst_flags_t complain)
10141 {
10142   tree templ = TREE_OPERAND (var, 0);
10143   tree arglist = TREE_OPERAND (var, 1);
10144 
10145   tree tmpl_args = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (templ));
10146   arglist = add_outermost_template_args (tmpl_args, arglist);
10147 
10148   templ = most_general_template (templ);
10149   tree parms = DECL_TEMPLATE_PARMS (templ);
10150   arglist = coerce_innermost_template_parms (parms, arglist, templ, complain,
10151 					     /*req_all*/true,
10152 					     /*use_default*/true);
10153 
10154   if (flag_concepts && !constraints_satisfied_p (templ, arglist))
10155     {
10156       if (complain & tf_error)
10157 	{
10158 	  auto_diagnostic_group d;
10159 	  error ("use of invalid variable template %qE", var);
10160 	  diagnose_constraints (location_of (var), templ, arglist);
10161 	}
10162       return error_mark_node;
10163     }
10164 
10165   return instantiate_template (templ, arglist, complain);
10166 }
10167 
10168 /* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
10169    TARGS template args, and instantiate it if it's not dependent.  */
10170 
10171 tree
lookup_and_finish_template_variable(tree templ,tree targs,tsubst_flags_t complain)10172 lookup_and_finish_template_variable (tree templ, tree targs,
10173 				     tsubst_flags_t complain)
10174 {
10175   templ = lookup_template_variable (templ, targs);
10176   if (!any_dependent_template_arguments_p (targs))
10177     {
10178       templ = finish_template_variable (templ, complain);
10179       mark_used (templ);
10180     }
10181 
10182   return convert_from_reference (templ);
10183 }
10184 
10185 
10186 struct pair_fn_data
10187 {
10188   tree_fn_t fn;
10189   tree_fn_t any_fn;
10190   void *data;
10191   /* True when we should also visit template parameters that occur in
10192      non-deduced contexts.  */
10193   bool include_nondeduced_p;
10194   hash_set<tree> *visited;
10195 };
10196 
10197 /* Called from for_each_template_parm via walk_tree.  */
10198 
10199 static tree
for_each_template_parm_r(tree * tp,int * walk_subtrees,void * d)10200 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
10201 {
10202   tree t = *tp;
10203   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
10204   tree_fn_t fn = pfd->fn;
10205   void *data = pfd->data;
10206   tree result = NULL_TREE;
10207 
10208 #define WALK_SUBTREE(NODE)						\
10209   do									\
10210     {									\
10211       result = for_each_template_parm (NODE, fn, data, pfd->visited,	\
10212 				       pfd->include_nondeduced_p,	\
10213 				       pfd->any_fn);			\
10214       if (result) goto out;						\
10215     }									\
10216   while (0)
10217 
10218   if (pfd->any_fn && (*pfd->any_fn)(t, data))
10219     return t;
10220 
10221   if (TYPE_P (t)
10222       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
10223     WALK_SUBTREE (TYPE_CONTEXT (t));
10224 
10225   switch (TREE_CODE (t))
10226     {
10227     case RECORD_TYPE:
10228       if (TYPE_PTRMEMFUNC_P (t))
10229 	break;
10230       /* Fall through.  */
10231 
10232     case UNION_TYPE:
10233     case ENUMERAL_TYPE:
10234       if (!TYPE_TEMPLATE_INFO (t))
10235 	*walk_subtrees = 0;
10236       else
10237 	WALK_SUBTREE (TYPE_TI_ARGS (t));
10238       break;
10239 
10240     case INTEGER_TYPE:
10241       WALK_SUBTREE (TYPE_MIN_VALUE (t));
10242       WALK_SUBTREE (TYPE_MAX_VALUE (t));
10243       break;
10244 
10245     case METHOD_TYPE:
10246       /* Since we're not going to walk subtrees, we have to do this
10247 	 explicitly here.  */
10248       WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
10249       /* Fall through.  */
10250 
10251     case FUNCTION_TYPE:
10252       /* Check the return type.  */
10253       WALK_SUBTREE (TREE_TYPE (t));
10254 
10255       /* Check the parameter types.  Since default arguments are not
10256 	 instantiated until they are needed, the TYPE_ARG_TYPES may
10257 	 contain expressions that involve template parameters.  But,
10258 	 no-one should be looking at them yet.  And, once they're
10259 	 instantiated, they don't contain template parameters, so
10260 	 there's no point in looking at them then, either.  */
10261       {
10262 	tree parm;
10263 
10264 	for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
10265 	  WALK_SUBTREE (TREE_VALUE (parm));
10266 
10267 	/* Since we've already handled the TYPE_ARG_TYPES, we don't
10268 	   want walk_tree walking into them itself.  */
10269 	*walk_subtrees = 0;
10270       }
10271 
10272       if (flag_noexcept_type)
10273 	{
10274 	  tree spec = TYPE_RAISES_EXCEPTIONS (t);
10275 	  if (spec)
10276 	    WALK_SUBTREE (TREE_PURPOSE (spec));
10277 	}
10278       break;
10279 
10280     case TYPEOF_TYPE:
10281     case DECLTYPE_TYPE:
10282     case UNDERLYING_TYPE:
10283       if (pfd->include_nondeduced_p
10284 	  && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
10285 				     pfd->visited,
10286 				     pfd->include_nondeduced_p,
10287 				     pfd->any_fn))
10288 	return error_mark_node;
10289       *walk_subtrees = false;
10290       break;
10291 
10292     case FUNCTION_DECL:
10293     case VAR_DECL:
10294       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10295 	WALK_SUBTREE (DECL_TI_ARGS (t));
10296       /* Fall through.  */
10297 
10298     case PARM_DECL:
10299     case CONST_DECL:
10300       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t))
10301 	WALK_SUBTREE (DECL_INITIAL (t));
10302       if (DECL_CONTEXT (t)
10303 	  && pfd->include_nondeduced_p)
10304 	WALK_SUBTREE (DECL_CONTEXT (t));
10305       break;
10306 
10307     case BOUND_TEMPLATE_TEMPLATE_PARM:
10308       /* Record template parameters such as `T' inside `TT<T>'.  */
10309       WALK_SUBTREE (TYPE_TI_ARGS (t));
10310       /* Fall through.  */
10311 
10312     case TEMPLATE_TEMPLATE_PARM:
10313     case TEMPLATE_TYPE_PARM:
10314     case TEMPLATE_PARM_INDEX:
10315       if (fn && (*fn)(t, data))
10316 	return t;
10317       else if (!fn)
10318 	return t;
10319       break;
10320 
10321     case TEMPLATE_DECL:
10322       /* A template template parameter is encountered.  */
10323       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10324 	WALK_SUBTREE (TREE_TYPE (t));
10325 
10326       /* Already substituted template template parameter */
10327       *walk_subtrees = 0;
10328       break;
10329 
10330     case TYPENAME_TYPE:
10331       /* A template-id in a TYPENAME_TYPE might be a deduced context after
10332 	 partial instantiation.  */
10333       WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
10334       break;
10335 
10336     case CONSTRUCTOR:
10337       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
10338 	  && pfd->include_nondeduced_p)
10339 	WALK_SUBTREE (TYPE_PTRMEMFUNC_FN_TYPE (TREE_TYPE (t)));
10340       break;
10341 
10342     case INDIRECT_REF:
10343     case COMPONENT_REF:
10344       /* If there's no type, then this thing must be some expression
10345 	 involving template parameters.  */
10346       if (!fn && !TREE_TYPE (t))
10347 	return error_mark_node;
10348       break;
10349 
10350     case MODOP_EXPR:
10351     case CAST_EXPR:
10352     case IMPLICIT_CONV_EXPR:
10353     case REINTERPRET_CAST_EXPR:
10354     case CONST_CAST_EXPR:
10355     case STATIC_CAST_EXPR:
10356     case DYNAMIC_CAST_EXPR:
10357     case ARROW_EXPR:
10358     case DOTSTAR_EXPR:
10359     case TYPEID_EXPR:
10360     case PSEUDO_DTOR_EXPR:
10361       if (!fn)
10362 	return error_mark_node;
10363       break;
10364 
10365     case SCOPE_REF:
10366       if (pfd->include_nondeduced_p)
10367 	WALK_SUBTREE (TREE_OPERAND (t, 0));
10368       break;
10369 
10370     case REQUIRES_EXPR:
10371       {
10372 	if (!fn)
10373 	  return error_mark_node;
10374 
10375 	/* Recursively walk the type of each constraint variable.  */
10376 	tree p = TREE_OPERAND (t, 0);
10377 	while (p)
10378 	  {
10379 	    WALK_SUBTREE (TREE_TYPE (p));
10380 	    p = TREE_CHAIN (p);
10381 	  }
10382       }
10383       break;
10384 
10385     default:
10386       break;
10387     }
10388 
10389   #undef WALK_SUBTREE
10390 
10391   /* We didn't find any template parameters we liked.  */
10392  out:
10393   return result;
10394 }
10395 
10396 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
10397    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
10398    call FN with the parameter and the DATA.
10399    If FN returns nonzero, the iteration is terminated, and
10400    for_each_template_parm returns 1.  Otherwise, the iteration
10401    continues.  If FN never returns a nonzero value, the value
10402    returned by for_each_template_parm is 0.  If FN is NULL, it is
10403    considered to be the function which always returns 1.
10404 
10405    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
10406    parameters that occur in non-deduced contexts.  When false, only
10407    visits those template parameters that can be deduced.  */
10408 
10409 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)10410 for_each_template_parm (tree t, tree_fn_t fn, void* data,
10411 			hash_set<tree> *visited,
10412 			bool include_nondeduced_p,
10413 			tree_fn_t any_fn)
10414 {
10415   struct pair_fn_data pfd;
10416   tree result;
10417 
10418   /* Set up.  */
10419   pfd.fn = fn;
10420   pfd.any_fn = any_fn;
10421   pfd.data = data;
10422   pfd.include_nondeduced_p = include_nondeduced_p;
10423 
10424   /* Walk the tree.  (Conceptually, we would like to walk without
10425      duplicates, but for_each_template_parm_r recursively calls
10426      for_each_template_parm, so we would need to reorganize a fair
10427      bit to use walk_tree_without_duplicates, so we keep our own
10428      visited list.)  */
10429   if (visited)
10430     pfd.visited = visited;
10431   else
10432     pfd.visited = new hash_set<tree>;
10433   result = cp_walk_tree (&t,
10434 		         for_each_template_parm_r,
10435 		         &pfd,
10436 		         pfd.visited);
10437 
10438   /* Clean up.  */
10439   if (!visited)
10440     {
10441       delete pfd.visited;
10442       pfd.visited = 0;
10443     }
10444 
10445   return result;
10446 }
10447 
10448 struct find_template_parameter_info
10449 {
find_template_parameter_infofind_template_parameter_info10450   explicit find_template_parameter_info (tree ctx_parms)
10451     : parm_list (NULL_TREE),
10452       ctx_parms (ctx_parms),
10453       max_depth (TMPL_PARMS_DEPTH (ctx_parms))
10454   {}
10455 
10456   hash_set<tree> visited;
10457   hash_set<tree> parms;
10458   tree parm_list;
10459   tree ctx_parms;
10460   int max_depth;
10461 };
10462 
10463 /* Appends the declaration of T to the list in DATA.  */
10464 
10465 static int
keep_template_parm(tree t,void * data)10466 keep_template_parm (tree t, void* data)
10467 {
10468   find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10469 
10470   /* Template parameters declared within the expression are not part of
10471      the parameter mapping. For example, in this concept:
10472 
10473        template<typename T>
10474        concept C = requires { <expr> } -> same_as<int>;
10475 
10476      the return specifier same_as<int> declares a new decltype parameter
10477      that must not be part of the parameter mapping. The same is true
10478      for generic lambda parameters, lambda template parameters, etc.  */
10479   int level;
10480   int index;
10481   template_parm_level_and_index (t, &level, &index);
10482   if (level > ftpi->max_depth)
10483     return 0;
10484 
10485   /* Arguments like const T yield parameters like const T. This means that
10486      a template-id like X<T, const T> would yield two distinct parameters:
10487      T and const T. Adjust types to their unqualified versions.  */
10488   if (TYPE_P (t))
10489     t = TYPE_MAIN_VARIANT (t);
10490   if (!ftpi->parms.add (t))
10491     ftpi->parm_list = tree_cons (NULL_TREE, t, ftpi->parm_list);
10492 
10493   return 0;
10494 }
10495 
10496 /* Ensure that we recursively examine certain terms that are not normally
10497    visited in for_each_template_parm_r.  */
10498 
10499 static int
any_template_parm_r(tree t,void * data)10500 any_template_parm_r (tree t, void *data)
10501 {
10502   find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10503 
10504 #define WALK_SUBTREE(NODE)						\
10505   do									\
10506     {									\
10507       for_each_template_parm (NODE, keep_template_parm, data,		\
10508 			      &ftpi->visited, true,			\
10509 			      any_template_parm_r);			\
10510     }									\
10511   while (0)
10512 
10513   /* A mention of a member alias/typedef is a use of all of its template
10514      arguments, including those from the enclosing class, so we don't use
10515      alias_template_specialization_p here.  */
10516   if (TYPE_P (t) && typedef_variant_p (t))
10517     if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
10518       WALK_SUBTREE (TI_ARGS (tinfo));
10519 
10520   switch (TREE_CODE (t))
10521     {
10522     case TEMPLATE_TYPE_PARM:
10523       /* Type constraints of a placeholder type may contain parameters.  */
10524       if (is_auto (t))
10525 	if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
10526 	  WALK_SUBTREE (constr);
10527       break;
10528 
10529     case TEMPLATE_ID_EXPR:
10530       /* Search through references to variable templates.  */
10531       WALK_SUBTREE (TREE_OPERAND (t, 0));
10532       WALK_SUBTREE (TREE_OPERAND (t, 1));
10533       break;
10534 
10535     case TEMPLATE_PARM_INDEX:
10536     case PARM_DECL:
10537       /* A parameter or constraint variable may also depend on a template
10538 	 parameter without explicitly naming it.  */
10539       WALK_SUBTREE (TREE_TYPE (t));
10540       break;
10541 
10542     case TEMPLATE_DECL:
10543       {
10544 	/* If T is a member template that shares template parameters with
10545 	   ctx_parms, we need to mark all those parameters for mapping.  */
10546 	tree dparms = DECL_TEMPLATE_PARMS (t);
10547 	tree cparms = ftpi->ctx_parms;
10548 	while (TMPL_PARMS_DEPTH (dparms) > ftpi->max_depth)
10549 	  dparms = TREE_CHAIN (dparms);
10550 	while (TMPL_PARMS_DEPTH (cparms) > TMPL_PARMS_DEPTH (dparms))
10551 	  cparms = TREE_CHAIN (cparms);
10552 	while (dparms
10553 	       && (TREE_TYPE (TREE_VALUE (dparms))
10554 		   != TREE_TYPE (TREE_VALUE (cparms))))
10555 	  dparms = TREE_CHAIN (dparms),
10556 	    cparms = TREE_CHAIN (cparms);
10557 	if (dparms)
10558 	  {
10559 	    int ddepth = TMPL_PARMS_DEPTH (dparms);
10560 	    tree dargs = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (t)));
10561 	    for (int i = 0; i < ddepth; ++i)
10562 	      WALK_SUBTREE (TMPL_ARGS_LEVEL (dargs, i+1));
10563 	  }
10564       }
10565       break;
10566 
10567     case LAMBDA_EXPR:
10568       {
10569 	/* Look in the parms and body.  */
10570 	tree fn = lambda_function (t);
10571 	WALK_SUBTREE (TREE_TYPE (fn));
10572 	WALK_SUBTREE (DECL_SAVED_TREE (fn));
10573       }
10574       break;
10575 
10576     case IDENTIFIER_NODE:
10577       if (IDENTIFIER_CONV_OP_P (t))
10578 	/* The conversion-type-id of a conversion operator may be dependent.  */
10579 	WALK_SUBTREE (TREE_TYPE (t));
10580       break;
10581 
10582     default:
10583       break;
10584     }
10585 
10586   /* Keep walking.  */
10587   return 0;
10588 }
10589 
10590 /* Returns a list of unique template parameters found within T, where CTX_PARMS
10591    are the template parameters in scope.  */
10592 
10593 tree
find_template_parameters(tree t,tree ctx_parms)10594 find_template_parameters (tree t, tree ctx_parms)
10595 {
10596   if (!ctx_parms)
10597     return NULL_TREE;
10598 
10599   find_template_parameter_info ftpi (ctx_parms);
10600   for_each_template_parm (t, keep_template_parm, &ftpi, &ftpi.visited,
10601 			  /*include_nondeduced*/true, any_template_parm_r);
10602   return ftpi.parm_list;
10603 }
10604 
10605 /* Returns true if T depends on any template parameter.  */
10606 
10607 int
uses_template_parms(tree t)10608 uses_template_parms (tree t)
10609 {
10610   if (t == NULL_TREE)
10611     return false;
10612 
10613   bool dependent_p;
10614   int saved_processing_template_decl;
10615 
10616   saved_processing_template_decl = processing_template_decl;
10617   if (!saved_processing_template_decl)
10618     processing_template_decl = 1;
10619   if (TYPE_P (t))
10620     dependent_p = dependent_type_p (t);
10621   else if (TREE_CODE (t) == TREE_VEC)
10622     dependent_p = any_dependent_template_arguments_p (t);
10623   else if (TREE_CODE (t) == TREE_LIST)
10624     dependent_p = (uses_template_parms (TREE_VALUE (t))
10625 		   || uses_template_parms (TREE_CHAIN (t)));
10626   else if (TREE_CODE (t) == TYPE_DECL)
10627     dependent_p = dependent_type_p (TREE_TYPE (t));
10628   else if (t == error_mark_node)
10629     dependent_p = false;
10630   else
10631     dependent_p = value_dependent_expression_p (t);
10632 
10633   processing_template_decl = saved_processing_template_decl;
10634 
10635   return dependent_p;
10636 }
10637 
10638 /* Returns true iff current_function_decl is an incompletely instantiated
10639    template.  Useful instead of processing_template_decl because the latter
10640    is set to 0 during instantiate_non_dependent_expr.  */
10641 
10642 bool
in_template_function(void)10643 in_template_function (void)
10644 {
10645   tree fn = current_function_decl;
10646   bool ret;
10647   ++processing_template_decl;
10648   ret = (fn && DECL_LANG_SPECIFIC (fn)
10649 	 && DECL_TEMPLATE_INFO (fn)
10650 	 && any_dependent_template_arguments_p (DECL_TI_ARGS (fn)));
10651   --processing_template_decl;
10652   return ret;
10653 }
10654 
10655 /* Returns true if T depends on any template parameter with level LEVEL.  */
10656 
10657 bool
uses_template_parms_level(tree t,int level)10658 uses_template_parms_level (tree t, int level)
10659 {
10660   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
10661 				 /*include_nondeduced_p=*/true);
10662 }
10663 
10664 /* Returns true if the signature of DECL depends on any template parameter from
10665    its enclosing class.  */
10666 
10667 bool
uses_outer_template_parms(tree decl)10668 uses_outer_template_parms (tree decl)
10669 {
10670   int depth = template_class_depth (CP_DECL_CONTEXT (decl));
10671   if (depth == 0)
10672     return false;
10673   if (for_each_template_parm (TREE_TYPE (decl), template_parm_outer_level,
10674 			      &depth, NULL, /*include_nondeduced_p=*/true))
10675     return true;
10676   if (PRIMARY_TEMPLATE_P (decl)
10677       && for_each_template_parm (INNERMOST_TEMPLATE_PARMS
10678 				 (DECL_TEMPLATE_PARMS (decl)),
10679 				 template_parm_outer_level,
10680 				 &depth, NULL, /*include_nondeduced_p=*/true))
10681     return true;
10682   tree ci = get_constraints (decl);
10683   if (ci)
10684     ci = CI_ASSOCIATED_CONSTRAINTS (ci);
10685   if (ci && for_each_template_parm (ci, template_parm_outer_level,
10686 				    &depth, NULL, /*nondeduced*/true))
10687     return true;
10688   return false;
10689 }
10690 
10691 /* Returns TRUE iff INST is an instantiation we don't need to do in an
10692    ill-formed translation unit, i.e. a variable or function that isn't
10693    usable in a constant expression.  */
10694 
10695 static inline bool
neglectable_inst_p(tree d)10696 neglectable_inst_p (tree d)
10697 {
10698   return (d && DECL_P (d)
10699 	  && !undeduced_auto_decl (d)
10700 	  && !(TREE_CODE (d) == FUNCTION_DECL ? DECL_DECLARED_CONSTEXPR_P (d)
10701 	       : decl_maybe_constant_var_p (d)));
10702 }
10703 
10704 /* Returns TRUE iff we should refuse to instantiate DECL because it's
10705    neglectable and instantiated from within an erroneous instantiation.  */
10706 
10707 static bool
limit_bad_template_recursion(tree decl)10708 limit_bad_template_recursion (tree decl)
10709 {
10710   struct tinst_level *lev = current_tinst_level;
10711   int errs = errorcount + sorrycount;
10712   if (lev == NULL || errs == 0 || !neglectable_inst_p (decl))
10713     return false;
10714 
10715   for (; lev; lev = lev->next)
10716     if (neglectable_inst_p (lev->maybe_get_node ()))
10717       break;
10718 
10719   return (lev && errs > lev->errors);
10720 }
10721 
10722 static int tinst_depth;
10723 extern int max_tinst_depth;
10724 int depth_reached;
10725 
10726 static GTY(()) struct tinst_level *last_error_tinst_level;
10727 
10728 /* We're starting to instantiate D; record the template instantiation context
10729    at LOC for diagnostics and to restore it later.  */
10730 
10731 static bool
push_tinst_level_loc(tree tldcl,tree targs,location_t loc)10732 push_tinst_level_loc (tree tldcl, tree targs, location_t loc)
10733 {
10734   struct tinst_level *new_level;
10735 
10736   if (tinst_depth >= max_tinst_depth)
10737     {
10738       /* Tell error.c not to try to instantiate any templates.  */
10739       at_eof = 2;
10740       fatal_error (input_location,
10741 		   "template instantiation depth exceeds maximum of %d"
10742 		   " (use %<-ftemplate-depth=%> to increase the maximum)",
10743                    max_tinst_depth);
10744       return false;
10745     }
10746 
10747   /* If the current instantiation caused problems, don't let it instantiate
10748      anything else.  Do allow deduction substitution and decls usable in
10749      constant expressions.  */
10750   if (!targs && limit_bad_template_recursion (tldcl))
10751     {
10752       /* Avoid no_linkage_errors and unused function warnings for this
10753 	 decl.  */
10754       TREE_NO_WARNING (tldcl) = 1;
10755       return false;
10756     }
10757 
10758   /* When not -quiet, dump template instantiations other than functions, since
10759      announce_function will take care of those.  */
10760   if (!quiet_flag && !targs
10761       && TREE_CODE (tldcl) != TREE_LIST
10762       && TREE_CODE (tldcl) != FUNCTION_DECL)
10763     fprintf (stderr, " %s", decl_as_string (tldcl, TFF_DECL_SPECIFIERS));
10764 
10765   new_level = tinst_level_freelist ().alloc ();
10766   new_level->tldcl = tldcl;
10767   new_level->targs = targs;
10768   new_level->locus = loc;
10769   new_level->errors = errorcount + sorrycount;
10770   new_level->next = NULL;
10771   new_level->refcount = 0;
10772   set_refcount_ptr (new_level->next, current_tinst_level);
10773   set_refcount_ptr (current_tinst_level, new_level);
10774 
10775   ++tinst_depth;
10776   if (GATHER_STATISTICS && (tinst_depth > depth_reached))
10777     depth_reached = tinst_depth;
10778 
10779   return true;
10780 }
10781 
10782 /* We're starting substitution of TMPL<ARGS>; record the template
10783    substitution context for diagnostics and to restore it later.  */
10784 
10785 static bool
push_tinst_level(tree tmpl,tree args)10786 push_tinst_level (tree tmpl, tree args)
10787 {
10788   return push_tinst_level_loc (tmpl, args, input_location);
10789 }
10790 
10791 /* We're starting to instantiate D; record INPUT_LOCATION and the
10792    template instantiation context for diagnostics and to restore it
10793    later.  */
10794 
10795 bool
push_tinst_level(tree d)10796 push_tinst_level (tree d)
10797 {
10798   return push_tinst_level_loc (d, input_location);
10799 }
10800 
10801 /* Likewise, but record LOC as the program location.  */
10802 
10803 bool
push_tinst_level_loc(tree d,location_t loc)10804 push_tinst_level_loc (tree d, location_t loc)
10805 {
10806   gcc_assert (TREE_CODE (d) != TREE_LIST);
10807   return push_tinst_level_loc (d, NULL, loc);
10808 }
10809 
10810 /* We're done instantiating this template; return to the instantiation
10811    context.  */
10812 
10813 void
pop_tinst_level(void)10814 pop_tinst_level (void)
10815 {
10816   /* Restore the filename and line number stashed away when we started
10817      this instantiation.  */
10818   input_location = current_tinst_level->locus;
10819   set_refcount_ptr (current_tinst_level, current_tinst_level->next);
10820   --tinst_depth;
10821 }
10822 
10823 /* We're instantiating a deferred template; restore the template
10824    instantiation context in which the instantiation was requested, which
10825    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
10826 
10827 static tree
reopen_tinst_level(struct tinst_level * level)10828 reopen_tinst_level (struct tinst_level *level)
10829 {
10830   struct tinst_level *t;
10831 
10832   tinst_depth = 0;
10833   for (t = level; t; t = t->next)
10834     ++tinst_depth;
10835 
10836   set_refcount_ptr (current_tinst_level, level);
10837   pop_tinst_level ();
10838   if (current_tinst_level)
10839     current_tinst_level->errors = errorcount+sorrycount;
10840   return level->maybe_get_node ();
10841 }
10842 
10843 /* Returns the TINST_LEVEL which gives the original instantiation
10844    context.  */
10845 
10846 struct tinst_level *
outermost_tinst_level(void)10847 outermost_tinst_level (void)
10848 {
10849   struct tinst_level *level = current_tinst_level;
10850   if (level)
10851     while (level->next)
10852       level = level->next;
10853   return level;
10854 }
10855 
10856 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
10857    vector of template arguments, as for tsubst.
10858 
10859    Returns an appropriate tsubst'd friend declaration.  */
10860 
10861 static tree
tsubst_friend_function(tree decl,tree args)10862 tsubst_friend_function (tree decl, tree args)
10863 {
10864   tree new_friend;
10865 
10866   if (TREE_CODE (decl) == FUNCTION_DECL
10867       && DECL_TEMPLATE_INSTANTIATION (decl)
10868       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
10869     /* This was a friend declared with an explicit template
10870        argument list, e.g.:
10871 
10872        friend void f<>(T);
10873 
10874        to indicate that f was a template instantiation, not a new
10875        function declaration.  Now, we have to figure out what
10876        instantiation of what template.  */
10877     {
10878       tree template_id, arglist, fns;
10879       tree new_args;
10880       tree tmpl;
10881       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
10882 
10883       /* Friend functions are looked up in the containing namespace scope.
10884 	 We must enter that scope, to avoid finding member functions of the
10885 	 current class with same name.  */
10886       push_nested_namespace (ns);
10887       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
10888 			 tf_warning_or_error, NULL_TREE,
10889 			 /*integral_constant_expression_p=*/false);
10890       pop_nested_namespace (ns);
10891       arglist = tsubst (DECL_TI_ARGS (decl), args,
10892 			tf_warning_or_error, NULL_TREE);
10893       template_id = lookup_template_function (fns, arglist);
10894 
10895       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
10896       tmpl = determine_specialization (template_id, new_friend,
10897 				       &new_args,
10898 				       /*need_member_template=*/0,
10899 				       TREE_VEC_LENGTH (args),
10900 				       tsk_none);
10901       return instantiate_template (tmpl, new_args, tf_error);
10902     }
10903 
10904   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
10905 
10906   /* The NEW_FRIEND will look like an instantiation, to the
10907      compiler, but is not an instantiation from the point of view of
10908      the language.  For example, we might have had:
10909 
10910      template <class T> struct S {
10911        template <class U> friend void f(T, U);
10912      };
10913 
10914      Then, in S<int>, template <class U> void f(int, U) is not an
10915      instantiation of anything.  */
10916   if (new_friend == error_mark_node)
10917     return error_mark_node;
10918 
10919   DECL_USE_TEMPLATE (new_friend) = 0;
10920   if (TREE_CODE (decl) == TEMPLATE_DECL)
10921     {
10922       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
10923       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
10924 	= DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
10925 
10926       /* Substitute TEMPLATE_PARMS_CONSTRAINTS so that parameter levels will
10927 	 match in decls_match.  */
10928       tree parms = DECL_TEMPLATE_PARMS (new_friend);
10929       tree treqs = TEMPLATE_PARMS_CONSTRAINTS (parms);
10930       treqs = maybe_substitute_reqs_for (treqs, new_friend);
10931       TEMPLATE_PARMS_CONSTRAINTS (parms) = treqs;
10932     }
10933 
10934   /* The mangled name for the NEW_FRIEND is incorrect.  The function
10935      is not a template instantiation and should not be mangled like
10936      one.  Therefore, we forget the mangling here; we'll recompute it
10937      later if we need it.  */
10938   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
10939     {
10940       SET_DECL_RTL (new_friend, NULL);
10941       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
10942     }
10943 
10944   if (DECL_NAMESPACE_SCOPE_P (new_friend))
10945     {
10946       tree old_decl;
10947       tree new_friend_template_info;
10948       tree new_friend_result_template_info;
10949       tree ns;
10950       int  new_friend_is_defn;
10951 
10952       /* We must save some information from NEW_FRIEND before calling
10953 	 duplicate decls since that function will free NEW_FRIEND if
10954 	 possible.  */
10955       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
10956       new_friend_is_defn =
10957 	    (DECL_INITIAL (DECL_TEMPLATE_RESULT
10958 			   (template_for_substitution (new_friend)))
10959 	     != NULL_TREE);
10960       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
10961 	{
10962 	  /* This declaration is a `primary' template.  */
10963 	  DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
10964 
10965 	  new_friend_result_template_info
10966 	    = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
10967 	}
10968       else
10969 	new_friend_result_template_info = NULL_TREE;
10970 
10971       /* Inside pushdecl_namespace_level, we will push into the
10972 	 current namespace. However, the friend function should go
10973 	 into the namespace of the template.  */
10974       ns = decl_namespace_context (new_friend);
10975       push_nested_namespace (ns);
10976       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
10977       pop_nested_namespace (ns);
10978 
10979       if (old_decl == error_mark_node)
10980 	return error_mark_node;
10981 
10982       if (old_decl != new_friend)
10983 	{
10984 	  /* This new friend declaration matched an existing
10985 	     declaration.  For example, given:
10986 
10987 	       template <class T> void f(T);
10988 	       template <class U> class C {
10989 		 template <class T> friend void f(T) {}
10990 	       };
10991 
10992 	     the friend declaration actually provides the definition
10993 	     of `f', once C has been instantiated for some type.  So,
10994 	     old_decl will be the out-of-class template declaration,
10995 	     while new_friend is the in-class definition.
10996 
10997 	     But, if `f' was called before this point, the
10998 	     instantiation of `f' will have DECL_TI_ARGS corresponding
10999 	     to `T' but not to `U', references to which might appear
11000 	     in the definition of `f'.  Previously, the most general
11001 	     template for an instantiation of `f' was the out-of-class
11002 	     version; now it is the in-class version.  Therefore, we
11003 	     run through all specialization of `f', adding to their
11004 	     DECL_TI_ARGS appropriately.  In particular, they need a
11005 	     new set of outer arguments, corresponding to the
11006 	     arguments for this class instantiation.
11007 
11008 	     The same situation can arise with something like this:
11009 
11010 	       friend void f(int);
11011 	       template <class T> class C {
11012 		 friend void f(T) {}
11013 	       };
11014 
11015 	     when `C<int>' is instantiated.  Now, `f(int)' is defined
11016 	     in the class.  */
11017 
11018 	  if (!new_friend_is_defn)
11019 	    /* On the other hand, if the in-class declaration does
11020 	       *not* provide a definition, then we don't want to alter
11021 	       existing definitions.  We can just leave everything
11022 	       alone.  */
11023 	    ;
11024 	  else
11025 	    {
11026 	      tree new_template = TI_TEMPLATE (new_friend_template_info);
11027 	      tree new_args = TI_ARGS (new_friend_template_info);
11028 
11029 	      /* Overwrite whatever template info was there before, if
11030 		 any, with the new template information pertaining to
11031 		 the declaration.  */
11032 	      DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
11033 
11034 	      if (TREE_CODE (old_decl) != TEMPLATE_DECL)
11035 		{
11036 		  /* We should have called reregister_specialization in
11037 		     duplicate_decls.  */
11038 		  gcc_assert (retrieve_specialization (new_template,
11039 						       new_args, 0)
11040 			      == old_decl);
11041 
11042 		  /* Instantiate it if the global has already been used.  */
11043 		  if (DECL_ODR_USED (old_decl))
11044 		    instantiate_decl (old_decl, /*defer_ok=*/true,
11045 				      /*expl_inst_class_mem_p=*/false);
11046 		}
11047 	      else
11048 		{
11049 		  tree t;
11050 
11051 		  /* Indicate that the old function template is a partial
11052 		     instantiation.  */
11053 		  DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
11054 		    = new_friend_result_template_info;
11055 
11056 		  gcc_assert (new_template
11057 			      == most_general_template (new_template));
11058 		  gcc_assert (new_template != old_decl);
11059 
11060 		  /* Reassign any specializations already in the hash table
11061 		     to the new more general template, and add the
11062 		     additional template args.  */
11063 		  for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
11064 		       t != NULL_TREE;
11065 		       t = TREE_CHAIN (t))
11066 		    {
11067 		      tree spec = TREE_VALUE (t);
11068 		      spec_entry elt;
11069 
11070 		      elt.tmpl = old_decl;
11071 		      elt.args = DECL_TI_ARGS (spec);
11072 		      elt.spec = NULL_TREE;
11073 
11074 		      decl_specializations->remove_elt (&elt);
11075 
11076 		      DECL_TI_ARGS (spec)
11077 			= add_outermost_template_args (new_args,
11078 						       DECL_TI_ARGS (spec));
11079 
11080 		      register_specialization
11081 			(spec, new_template, DECL_TI_ARGS (spec), true, 0);
11082 
11083 		    }
11084 		  DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
11085 		}
11086 	    }
11087 
11088 	  /* The information from NEW_FRIEND has been merged into OLD_DECL
11089 	     by duplicate_decls.  */
11090 	  new_friend = old_decl;
11091 	}
11092     }
11093   else
11094     {
11095       tree context = DECL_CONTEXT (new_friend);
11096       bool dependent_p;
11097 
11098       /* In the code
11099 	   template <class T> class C {
11100 	     template <class U> friend void C1<U>::f (); // case 1
11101 	     friend void C2<T>::f ();			 // case 2
11102 	   };
11103 	 we only need to make sure CONTEXT is a complete type for
11104 	 case 2.  To distinguish between the two cases, we note that
11105 	 CONTEXT of case 1 remains dependent type after tsubst while
11106 	 this isn't true for case 2.  */
11107       ++processing_template_decl;
11108       dependent_p = dependent_type_p (context);
11109       --processing_template_decl;
11110 
11111       if (!dependent_p
11112 	  && !complete_type_or_else (context, NULL_TREE))
11113 	return error_mark_node;
11114 
11115       if (COMPLETE_TYPE_P (context))
11116 	{
11117 	  tree fn = new_friend;
11118 	  /* do_friend adds the TEMPLATE_DECL for any member friend
11119 	     template even if it isn't a member template, i.e.
11120 	       template <class T> friend A<T>::f();
11121 	     Look through it in that case.  */
11122 	  if (TREE_CODE (fn) == TEMPLATE_DECL
11123 	      && !PRIMARY_TEMPLATE_P (fn))
11124 	    fn = DECL_TEMPLATE_RESULT (fn);
11125 	  /* Check to see that the declaration is really present, and,
11126 	     possibly obtain an improved declaration.  */
11127 	  fn = check_classfn (context, fn, NULL_TREE);
11128 
11129 	  if (fn)
11130 	    new_friend = fn;
11131 	}
11132     }
11133 
11134   return new_friend;
11135 }
11136 
11137 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
11138    template arguments, as for tsubst.
11139 
11140    Returns an appropriate tsubst'd friend type or error_mark_node on
11141    failure.  */
11142 
11143 static tree
tsubst_friend_class(tree friend_tmpl,tree args)11144 tsubst_friend_class (tree friend_tmpl, tree args)
11145 {
11146   tree tmpl;
11147 
11148   if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
11149     {
11150       tmpl = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
11151       return TREE_TYPE (tmpl);
11152     }
11153 
11154   tree context = CP_DECL_CONTEXT (friend_tmpl);
11155   if (TREE_CODE (context) == NAMESPACE_DECL)
11156     push_nested_namespace (context);
11157   else
11158     {
11159       context = tsubst (context, args, tf_error, NULL_TREE);
11160       push_nested_class (context);
11161     }
11162 
11163   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), /*prefer_type=*/false,
11164 			   /*non_class=*/false, /*block_p=*/false,
11165 			   /*namespaces_only=*/false, LOOKUP_HIDDEN);
11166 
11167   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
11168     {
11169       /* The friend template has already been declared.  Just
11170 	 check to see that the declarations match, and install any new
11171 	 default parameters.  We must tsubst the default parameters,
11172 	 of course.  We only need the innermost template parameters
11173 	 because that is all that redeclare_class_template will look
11174 	 at.  */
11175       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
11176 	  > TMPL_ARGS_DEPTH (args))
11177 	{
11178 	  tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
11179 					      args, tf_warning_or_error);
11180           location_t saved_input_location = input_location;
11181           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
11182           tree cons = get_constraints (tmpl);
11183           redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
11184           input_location = saved_input_location;
11185 	}
11186     }
11187   else
11188     {
11189       /* The friend template has not already been declared.  In this
11190 	 case, the instantiation of the template class will cause the
11191 	 injection of this template into the namespace scope.  */
11192       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
11193 
11194       if (tmpl != error_mark_node)
11195 	{
11196 	  /* The new TMPL is not an instantiation of anything, so we
11197 	     forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE
11198 	     for the new type because that is supposed to be the
11199 	     corresponding template decl, i.e., TMPL.  */
11200 	  DECL_USE_TEMPLATE (tmpl) = 0;
11201 	  DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
11202 	  CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
11203 	  CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
11204 	    = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
11205 
11206 	  /* It is hidden.  */
11207 	  retrofit_lang_decl (DECL_TEMPLATE_RESULT (tmpl));
11208 	  DECL_ANTICIPATED (tmpl)
11209 	    = DECL_ANTICIPATED (DECL_TEMPLATE_RESULT (tmpl)) = true;
11210 
11211 	  /* Substitute into and set the constraints on the new declaration.  */
11212 	  if (tree ci = get_constraints (friend_tmpl))
11213 	    {
11214 	      ++processing_template_decl;
11215 	      ci = tsubst_constraint_info (ci, args, tf_warning_or_error,
11216 					   DECL_FRIEND_CONTEXT (friend_tmpl));
11217 	      --processing_template_decl;
11218 	      set_constraints (tmpl, ci);
11219 	    }
11220 
11221 	  /* Inject this template into the enclosing namspace scope.  */
11222 	  tmpl = pushdecl_namespace_level (tmpl, true);
11223 	}
11224     }
11225 
11226   if (TREE_CODE (context) == NAMESPACE_DECL)
11227     pop_nested_namespace (context);
11228   else
11229     pop_nested_class ();
11230 
11231   return TREE_TYPE (tmpl);
11232 }
11233 
11234 /* Returns zero if TYPE cannot be completed later due to circularity.
11235    Otherwise returns one.  */
11236 
11237 static int
can_complete_type_without_circularity(tree type)11238 can_complete_type_without_circularity (tree type)
11239 {
11240   if (type == NULL_TREE || type == error_mark_node)
11241     return 0;
11242   else if (COMPLETE_TYPE_P (type))
11243     return 1;
11244   else if (TREE_CODE (type) == ARRAY_TYPE)
11245     return can_complete_type_without_circularity (TREE_TYPE (type));
11246   else if (CLASS_TYPE_P (type)
11247 	   && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
11248     return 0;
11249   else
11250     return 1;
11251 }
11252 
11253 static tree tsubst_omp_clauses (tree, enum c_omp_region_type, tree,
11254 				tsubst_flags_t, tree);
11255 
11256 /* Instantiate a single dependent attribute T (a TREE_LIST), and return either
11257    T or a new TREE_LIST, possibly a chain in the case of a pack expansion.  */
11258 
11259 static tree
tsubst_attribute(tree t,tree * decl_p,tree args,tsubst_flags_t complain,tree in_decl)11260 tsubst_attribute (tree t, tree *decl_p, tree args,
11261 		  tsubst_flags_t complain, tree in_decl)
11262 {
11263   gcc_assert (ATTR_IS_DEPENDENT (t));
11264 
11265   tree val = TREE_VALUE (t);
11266   if (val == NULL_TREE)
11267     /* Nothing to do.  */;
11268   else if ((flag_openmp || flag_openmp_simd)
11269 	   && is_attribute_p ("omp declare simd",
11270 			      get_attribute_name (t)))
11271     {
11272       tree clauses = TREE_VALUE (val);
11273       clauses = tsubst_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD, args,
11274 				    complain, in_decl);
11275       c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11276       clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11277       tree parms = DECL_ARGUMENTS (*decl_p);
11278       clauses
11279 	= c_omp_declare_simd_clauses_to_numbers (parms, clauses);
11280       if (clauses)
11281 	val = build_tree_list (NULL_TREE, clauses);
11282       else
11283 	val = NULL_TREE;
11284     }
11285   else if (flag_openmp
11286 	   && is_attribute_p ("omp declare variant base",
11287 			      get_attribute_name (t)))
11288     {
11289       ++cp_unevaluated_operand;
11290       tree varid
11291 	= tsubst_expr (TREE_PURPOSE (val), args, complain,
11292 		       in_decl, /*integral_constant_expression_p=*/false);
11293       --cp_unevaluated_operand;
11294       tree chain = TREE_CHAIN (val);
11295       location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
11296       tree ctx = copy_list (TREE_VALUE (val));
11297       tree simd = get_identifier ("simd");
11298       tree score = get_identifier (" score");
11299       tree condition = get_identifier ("condition");
11300       for (tree t1 = ctx; t1; t1 = TREE_CHAIN (t1))
11301 	{
11302 	  const char *set = IDENTIFIER_POINTER (TREE_PURPOSE (t1));
11303 	  TREE_VALUE (t1) = copy_list (TREE_VALUE (t1));
11304 	  for (tree t2 = TREE_VALUE (t1); t2; t2 = TREE_CHAIN (t2))
11305 	    {
11306 	      if (TREE_PURPOSE (t2) == simd && set[0] == 'c')
11307 		{
11308 		  tree clauses = TREE_VALUE (t2);
11309 		  clauses = tsubst_omp_clauses (clauses,
11310 						C_ORT_OMP_DECLARE_SIMD, args,
11311 						complain, in_decl);
11312 		  c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11313 		  clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11314 		  TREE_VALUE (t2) = clauses;
11315 		}
11316 	      else
11317 		{
11318 		  TREE_VALUE (t2) = copy_list (TREE_VALUE (t2));
11319 		  for (tree t3 = TREE_VALUE (t2); t3; t3 = TREE_CHAIN (t3))
11320 		    if (TREE_VALUE (t3))
11321 		      {
11322 			bool allow_string
11323 			  = ((TREE_PURPOSE (t2) != condition || set[0] != 'u')
11324 			     && TREE_PURPOSE (t3) != score);
11325 			tree v = TREE_VALUE (t3);
11326 			if (TREE_CODE (v) == STRING_CST && allow_string)
11327 			  continue;
11328 			v = tsubst_expr (v, args, complain, in_decl, true);
11329 			v = fold_non_dependent_expr (v);
11330 			if (!INTEGRAL_TYPE_P (TREE_TYPE (v))
11331 			    || (TREE_PURPOSE (t3) == score
11332 				? TREE_CODE (v) != INTEGER_CST
11333 				: !tree_fits_shwi_p (v)))
11334 			  {
11335 			    location_t loc
11336 			      = cp_expr_loc_or_loc (TREE_VALUE (t3),
11337 						    match_loc);
11338 			    if (TREE_PURPOSE (t3) == score)
11339 			      error_at (loc, "score argument must be "
11340 					     "constant integer expression");
11341 			    else if (allow_string)
11342 			      error_at (loc, "property must be constant "
11343 					     "integer expression or string "
11344 					     "literal");
11345 			    else
11346 			      error_at (loc, "property must be constant "
11347 					     "integer expression");
11348 			    return NULL_TREE;
11349 			  }
11350 			else if (TREE_PURPOSE (t3) == score
11351 				 && tree_int_cst_sgn (v) < 0)
11352 			  {
11353 			    location_t loc
11354 			      = cp_expr_loc_or_loc (TREE_VALUE (t3),
11355 						    match_loc);
11356 			    error_at (loc, "score argument must be "
11357 					   "non-negative");
11358 			    return NULL_TREE;
11359 			  }
11360 			TREE_VALUE (t3) = v;
11361 		      }
11362 		}
11363 	    }
11364 	}
11365       val = tree_cons (varid, ctx, chain);
11366     }
11367   /* If the first attribute argument is an identifier, don't
11368      pass it through tsubst.  Attributes like mode, format,
11369      cleanup and several target specific attributes expect it
11370      unmodified.  */
11371   else if (attribute_takes_identifier_p (get_attribute_name (t)))
11372     {
11373       tree chain
11374 	= tsubst_expr (TREE_CHAIN (val), args, complain, in_decl,
11375 		       /*integral_constant_expression_p=*/false);
11376       if (chain != TREE_CHAIN (val))
11377 	val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
11378     }
11379   else if (PACK_EXPANSION_P (val))
11380     {
11381       /* An attribute pack expansion.  */
11382       tree purp = TREE_PURPOSE (t);
11383       tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
11384       if (pack == error_mark_node)
11385 	return error_mark_node;
11386       int len = TREE_VEC_LENGTH (pack);
11387       tree list = NULL_TREE;
11388       tree *q = &list;
11389       for (int i = 0; i < len; ++i)
11390 	{
11391 	  tree elt = TREE_VEC_ELT (pack, i);
11392 	  *q = build_tree_list (purp, elt);
11393 	  q = &TREE_CHAIN (*q);
11394 	}
11395       return list;
11396     }
11397   else
11398     val = tsubst_expr (val, args, complain, in_decl,
11399 		       /*integral_constant_expression_p=*/false);
11400 
11401   if (val != TREE_VALUE (t))
11402     return build_tree_list (TREE_PURPOSE (t), val);
11403   return t;
11404 }
11405 
11406 /* Instantiate any dependent attributes in ATTRIBUTES, returning either it
11407    unchanged or a new TREE_LIST chain.  */
11408 
11409 static tree
tsubst_attributes(tree attributes,tree args,tsubst_flags_t complain,tree in_decl)11410 tsubst_attributes (tree attributes, tree args,
11411 		   tsubst_flags_t complain, tree in_decl)
11412 {
11413   tree last_dep = NULL_TREE;
11414 
11415   for (tree t = attributes; t; t = TREE_CHAIN (t))
11416     if (ATTR_IS_DEPENDENT (t))
11417       {
11418 	last_dep = t;
11419 	attributes = copy_list (attributes);
11420 	break;
11421       }
11422 
11423   if (last_dep)
11424     for (tree *p = &attributes; *p; )
11425       {
11426 	tree t = *p;
11427 	if (ATTR_IS_DEPENDENT (t))
11428 	  {
11429 	    tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
11430 	    if (subst != t)
11431 	      {
11432 		*p = subst;
11433 		while (*p)
11434 		  p = &TREE_CHAIN (*p);
11435 		*p = TREE_CHAIN (t);
11436 		continue;
11437 	      }
11438 	  }
11439 	p = &TREE_CHAIN (*p);
11440       }
11441 
11442   return attributes;
11443 }
11444 
11445 /* Apply any attributes which had to be deferred until instantiation
11446    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
11447    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
11448 
11449 static void
apply_late_template_attributes(tree * decl_p,tree attributes,int attr_flags,tree args,tsubst_flags_t complain,tree in_decl)11450 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
11451 				tree args, tsubst_flags_t complain, tree in_decl)
11452 {
11453   tree last_dep = NULL_TREE;
11454   tree t;
11455   tree *p;
11456 
11457   if (attributes == NULL_TREE)
11458     return;
11459 
11460   if (DECL_P (*decl_p))
11461     {
11462       if (TREE_TYPE (*decl_p) == error_mark_node)
11463 	return;
11464       p = &DECL_ATTRIBUTES (*decl_p);
11465       /* DECL_ATTRIBUTES comes from copy_node in tsubst_decl, and is identical
11466          to our attributes parameter.  */
11467       gcc_assert (*p == attributes);
11468     }
11469   else
11470     {
11471       p = &TYPE_ATTRIBUTES (*decl_p);
11472       /* TYPE_ATTRIBUTES was set up (with abi_tag and may_alias) in
11473 	 lookup_template_class_1, and should be preserved.  */
11474       gcc_assert (*p != attributes);
11475       while (*p)
11476 	p = &TREE_CHAIN (*p);
11477     }
11478 
11479   for (t = attributes; t; t = TREE_CHAIN (t))
11480     if (ATTR_IS_DEPENDENT (t))
11481       {
11482 	last_dep = t;
11483 	attributes = copy_list (attributes);
11484 	break;
11485       }
11486 
11487   *p = attributes;
11488   if (last_dep)
11489     {
11490       tree late_attrs = NULL_TREE;
11491       tree *q = &late_attrs;
11492 
11493       for (; *p; )
11494 	{
11495 	  t = *p;
11496 	  if (ATTR_IS_DEPENDENT (t))
11497 	    {
11498 	      *p = TREE_CHAIN (t);
11499 	      TREE_CHAIN (t) = NULL_TREE;
11500 	      *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
11501 	      while (*q)
11502 		q = &TREE_CHAIN (*q);
11503 	    }
11504 	  else
11505 	    p = &TREE_CHAIN (t);
11506 	}
11507 
11508       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
11509     }
11510 }
11511 
11512 /* Perform (or defer) access check for typedefs that were referenced
11513    from within the template TMPL code.
11514    This is a subroutine of instantiate_decl and instantiate_class_template.
11515    TMPL is the template to consider and TARGS is the list of arguments of
11516    that template.  */
11517 
11518 static void
perform_typedefs_access_check(tree tmpl,tree targs)11519 perform_typedefs_access_check (tree tmpl, tree targs)
11520 {
11521   unsigned i;
11522   qualified_typedef_usage_t *iter;
11523 
11524   if (!tmpl
11525       || (!CLASS_TYPE_P (tmpl)
11526 	  && TREE_CODE (tmpl) != FUNCTION_DECL))
11527     return;
11528 
11529   FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (tmpl), i, iter)
11530     {
11531       tree type_decl = iter->typedef_decl;
11532       tree type_scope = iter->context;
11533 
11534       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
11535 	continue;
11536 
11537       if (uses_template_parms (type_decl))
11538 	type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
11539       if (uses_template_parms (type_scope))
11540 	type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
11541 
11542       /* Make access check error messages point to the location
11543          of the use of the typedef.  */
11544       iloc_sentinel ils (iter->locus);
11545       perform_or_defer_access_check (TYPE_BINFO (type_scope),
11546 				     type_decl, type_decl,
11547 				     tf_warning_or_error);
11548     }
11549 }
11550 
11551 static tree
instantiate_class_template_1(tree type)11552 instantiate_class_template_1 (tree type)
11553 {
11554   tree templ, args, pattern, t, member;
11555   tree typedecl;
11556   tree pbinfo;
11557   tree base_list;
11558   unsigned int saved_maximum_field_alignment;
11559   tree fn_context;
11560 
11561   if (type == error_mark_node)
11562     return error_mark_node;
11563 
11564   if (COMPLETE_OR_OPEN_TYPE_P (type)
11565       || uses_template_parms (type))
11566     return type;
11567 
11568   /* Figure out which template is being instantiated.  */
11569   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
11570   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
11571 
11572   /* Mark the type as in the process of being defined.  */
11573   TYPE_BEING_DEFINED (type) = 1;
11574 
11575   /* We may be in the middle of deferred access check.  Disable
11576      it now.  */
11577   deferring_access_check_sentinel acs (dk_no_deferred);
11578 
11579   /* Determine what specialization of the original template to
11580      instantiate.  */
11581   t = most_specialized_partial_spec (type, tf_warning_or_error);
11582   if (t == error_mark_node)
11583     return error_mark_node;
11584   else if (t)
11585     {
11586       /* This TYPE is actually an instantiation of a partial
11587 	 specialization.  We replace the innermost set of ARGS with
11588 	 the arguments appropriate for substitution.  For example,
11589 	 given:
11590 
11591 	   template <class T> struct S {};
11592 	   template <class T> struct S<T*> {};
11593 
11594 	 and supposing that we are instantiating S<int*>, ARGS will
11595 	 presently be {int*} -- but we need {int}.  */
11596       pattern = TREE_TYPE (t);
11597       args = TREE_PURPOSE (t);
11598     }
11599   else
11600     {
11601       pattern = TREE_TYPE (templ);
11602       args = CLASSTYPE_TI_ARGS (type);
11603     }
11604 
11605   /* If the template we're instantiating is incomplete, then clearly
11606      there's nothing we can do.  */
11607   if (!COMPLETE_TYPE_P (pattern))
11608     {
11609       /* We can try again later.  */
11610       TYPE_BEING_DEFINED (type) = 0;
11611       return type;
11612     }
11613 
11614   /* If we've recursively instantiated too many templates, stop.  */
11615   if (! push_tinst_level (type))
11616     return type;
11617 
11618   int saved_unevaluated_operand = cp_unevaluated_operand;
11619   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
11620 
11621   fn_context = decl_function_context (TYPE_MAIN_DECL (type));
11622   /* Also avoid push_to_top_level for a lambda in an NSDMI.  */
11623   if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
11624     fn_context = error_mark_node;
11625   if (!fn_context)
11626     push_to_top_level ();
11627   else
11628     {
11629       cp_unevaluated_operand = 0;
11630       c_inhibit_evaluation_warnings = 0;
11631     }
11632   /* Use #pragma pack from the template context.  */
11633   saved_maximum_field_alignment = maximum_field_alignment;
11634   maximum_field_alignment = TYPE_PRECISION (pattern);
11635 
11636   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
11637 
11638   /* Set the input location to the most specialized template definition.
11639      This is needed if tsubsting causes an error.  */
11640   typedecl = TYPE_MAIN_DECL (pattern);
11641   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
11642     DECL_SOURCE_LOCATION (typedecl);
11643 
11644   TYPE_PACKED (type) = TYPE_PACKED (pattern);
11645   SET_TYPE_ALIGN (type, TYPE_ALIGN (pattern));
11646   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
11647   CLASSTYPE_NON_AGGREGATE (type) = CLASSTYPE_NON_AGGREGATE (pattern);
11648   if (ANON_AGGR_TYPE_P (pattern))
11649     SET_ANON_AGGR_TYPE_P (type);
11650   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
11651     {
11652       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
11653       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
11654       /* Adjust visibility for template arguments.  */
11655       determine_visibility (TYPE_MAIN_DECL (type));
11656     }
11657   if (CLASS_TYPE_P (type))
11658     CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
11659 
11660   pbinfo = TYPE_BINFO (pattern);
11661 
11662   /* We should never instantiate a nested class before its enclosing
11663      class; we need to look up the nested class by name before we can
11664      instantiate it, and that lookup should instantiate the enclosing
11665      class.  */
11666   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
11667 	      || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
11668 
11669   base_list = NULL_TREE;
11670   if (BINFO_N_BASE_BINFOS (pbinfo))
11671     {
11672       tree pbase_binfo;
11673       tree pushed_scope;
11674       int i;
11675 
11676       /* We must enter the scope containing the type, as that is where
11677 	 the accessibility of types named in dependent bases are
11678 	 looked up from.  */
11679       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
11680 
11681       /* Substitute into each of the bases to determine the actual
11682 	 basetypes.  */
11683       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
11684 	{
11685 	  tree base;
11686 	  tree access = BINFO_BASE_ACCESS (pbinfo, i);
11687           tree expanded_bases = NULL_TREE;
11688           int idx, len = 1;
11689 
11690           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
11691             {
11692               expanded_bases =
11693 		tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
11694 				       args, tf_error, NULL_TREE);
11695               if (expanded_bases == error_mark_node)
11696                 continue;
11697 
11698               len = TREE_VEC_LENGTH (expanded_bases);
11699             }
11700 
11701           for (idx = 0; idx < len; idx++)
11702             {
11703               if (expanded_bases)
11704                 /* Extract the already-expanded base class.  */
11705                 base = TREE_VEC_ELT (expanded_bases, idx);
11706               else
11707                 /* Substitute to figure out the base class.  */
11708                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
11709                                NULL_TREE);
11710 
11711               if (base == error_mark_node)
11712                 continue;
11713 
11714               base_list = tree_cons (access, base, base_list);
11715               if (BINFO_VIRTUAL_P (pbase_binfo))
11716                 TREE_TYPE (base_list) = integer_type_node;
11717             }
11718 	}
11719 
11720       /* The list is now in reverse order; correct that.  */
11721       base_list = nreverse (base_list);
11722 
11723       if (pushed_scope)
11724 	pop_scope (pushed_scope);
11725     }
11726   /* Now call xref_basetypes to set up all the base-class
11727      information.  */
11728   xref_basetypes (type, base_list);
11729 
11730   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
11731 				  (int) ATTR_FLAG_TYPE_IN_PLACE,
11732 				  args, tf_error, NULL_TREE);
11733   fixup_attribute_variants (type);
11734 
11735   /* Now that our base classes are set up, enter the scope of the
11736      class, so that name lookups into base classes, etc. will work
11737      correctly.  This is precisely analogous to what we do in
11738      begin_class_definition when defining an ordinary non-template
11739      class, except we also need to push the enclosing classes.  */
11740   push_nested_class (type);
11741 
11742   /* Now members are processed in the order of declaration.  */
11743   for (member = CLASSTYPE_DECL_LIST (pattern);
11744        member; member = TREE_CHAIN (member))
11745     {
11746       tree t = TREE_VALUE (member);
11747 
11748       if (TREE_PURPOSE (member))
11749 	{
11750 	  if (TYPE_P (t))
11751 	    {
11752 	      if (LAMBDA_TYPE_P (t))
11753 		/* A closure type for a lambda in an NSDMI or default argument.
11754 		   Ignore it; it will be regenerated when needed.  */
11755 		continue;
11756 
11757 	      /* Build new CLASSTYPE_NESTED_UTDS.  */
11758 
11759 	      tree newtag;
11760 	      bool class_template_p;
11761 
11762 	      class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
11763 				  && TYPE_LANG_SPECIFIC (t)
11764 				  && CLASSTYPE_IS_TEMPLATE (t));
11765 	      /* If the member is a class template, then -- even after
11766 		 substitution -- there may be dependent types in the
11767 		 template argument list for the class.  We increment
11768 		 PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
11769 		 that function will assume that no types are dependent
11770 		 when outside of a template.  */
11771 	      if (class_template_p)
11772 		++processing_template_decl;
11773 	      newtag = tsubst (t, args, tf_error, NULL_TREE);
11774 	      if (class_template_p)
11775 		--processing_template_decl;
11776 	      if (newtag == error_mark_node)
11777 		continue;
11778 
11779 	      if (TREE_CODE (newtag) != ENUMERAL_TYPE)
11780 		{
11781 		  tree name = TYPE_IDENTIFIER (t);
11782 
11783 		  if (class_template_p)
11784 		    /* Unfortunately, lookup_template_class sets
11785 		       CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
11786 		       instantiation (i.e., for the type of a member
11787 		       template class nested within a template class.)
11788 		       This behavior is required for
11789 		       maybe_process_partial_specialization to work
11790 		       correctly, but is not accurate in this case;
11791 		       the TAG is not an instantiation of anything.
11792 		       (The corresponding TEMPLATE_DECL is an
11793 		       instantiation, but the TYPE is not.) */
11794 		    CLASSTYPE_USE_TEMPLATE (newtag) = 0;
11795 
11796 		  /* Now, we call pushtag to put this NEWTAG into the scope of
11797 		     TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
11798 		     pushtag calling push_template_decl.  We don't have to do
11799 		     this for enums because it will already have been done in
11800 		     tsubst_enum.  */
11801 		  if (name)
11802 		    SET_IDENTIFIER_TYPE_VALUE (name, newtag);
11803 		  pushtag (name, newtag, /*tag_scope=*/ts_current);
11804 		}
11805 	    }
11806 	  else if (DECL_DECLARES_FUNCTION_P (t))
11807 	    {
11808 	      tree r;
11809 
11810 	      if (TREE_CODE (t) == TEMPLATE_DECL)
11811 		++processing_template_decl;
11812 	      r = tsubst (t, args, tf_error, NULL_TREE);
11813 	      if (TREE_CODE (t) == TEMPLATE_DECL)
11814 		--processing_template_decl;
11815 	      set_current_access_from_decl (r);
11816 	      finish_member_declaration (r);
11817 	      /* Instantiate members marked with attribute used.  */
11818 	      if (r != error_mark_node && DECL_PRESERVE_P (r))
11819 		mark_used (r);
11820 	      if (TREE_CODE (r) == FUNCTION_DECL
11821 		  && DECL_OMP_DECLARE_REDUCTION_P (r))
11822 		cp_check_omp_declare_reduction (r);
11823 	    }
11824 	  else if ((DECL_CLASS_TEMPLATE_P (t) || DECL_IMPLICIT_TYPEDEF_P (t))
11825 		   && LAMBDA_TYPE_P (TREE_TYPE (t)))
11826 	    /* A closure type for a lambda in an NSDMI or default argument.
11827 	       Ignore it; it will be regenerated when needed.  */;
11828 	  else
11829 	    {
11830 	      /* Build new TYPE_FIELDS.  */
11831               if (TREE_CODE (t) == STATIC_ASSERT)
11832                 {
11833                   tree condition;
11834 
11835 		  ++c_inhibit_evaluation_warnings;
11836 		  condition =
11837 		    tsubst_expr (STATIC_ASSERT_CONDITION (t), args,
11838 				 tf_warning_or_error, NULL_TREE,
11839 				 /*integral_constant_expression_p=*/true);
11840 		  --c_inhibit_evaluation_warnings;
11841 
11842                   finish_static_assert (condition,
11843                                         STATIC_ASSERT_MESSAGE (t),
11844                                         STATIC_ASSERT_SOURCE_LOCATION (t),
11845                                         /*member_p=*/true);
11846                 }
11847 	      else if (TREE_CODE (t) != CONST_DECL)
11848 		{
11849 		  tree r;
11850 		  tree vec = NULL_TREE;
11851 		  int len = 1;
11852 
11853 		  /* The file and line for this declaration, to
11854 		     assist in error message reporting.  Since we
11855 		     called push_tinst_level above, we don't need to
11856 		     restore these.  */
11857 		  input_location = DECL_SOURCE_LOCATION (t);
11858 
11859 		  if (TREE_CODE (t) == TEMPLATE_DECL)
11860 		    ++processing_template_decl;
11861 		  r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
11862 		  if (TREE_CODE (t) == TEMPLATE_DECL)
11863 		    --processing_template_decl;
11864 
11865 		  if (TREE_CODE (r) == TREE_VEC)
11866 		    {
11867 		      /* A capture pack became multiple fields.  */
11868 		      vec = r;
11869 		      len = TREE_VEC_LENGTH (vec);
11870 		    }
11871 
11872 		  for (int i = 0; i < len; ++i)
11873 		    {
11874 		      if (vec)
11875 			r = TREE_VEC_ELT (vec, i);
11876 		      if (VAR_P (r))
11877 			{
11878 			  /* In [temp.inst]:
11879 
11880 			     [t]he initialization (and any associated
11881 			     side-effects) of a static data member does
11882 			     not occur unless the static data member is
11883 			     itself used in a way that requires the
11884 			     definition of the static data member to
11885 			     exist.
11886 
11887 			     Therefore, we do not substitute into the
11888 			     initialized for the static data member here.  */
11889 			  finish_static_data_member_decl
11890 			    (r,
11891 			     /*init=*/NULL_TREE,
11892 			     /*init_const_expr_p=*/false,
11893 			     /*asmspec_tree=*/NULL_TREE,
11894 			     /*flags=*/0);
11895 			  /* Instantiate members marked with attribute used. */
11896 			  if (r != error_mark_node && DECL_PRESERVE_P (r))
11897 			    mark_used (r);
11898 			}
11899 		      else if (TREE_CODE (r) == FIELD_DECL)
11900 			{
11901 			  /* Determine whether R has a valid type and can be
11902 			     completed later.  If R is invalid, then its type
11903 			     is replaced by error_mark_node.  */
11904 			  tree rtype = TREE_TYPE (r);
11905 			  if (can_complete_type_without_circularity (rtype))
11906 			    complete_type (rtype);
11907 
11908 			  if (!complete_or_array_type_p (rtype))
11909 			    {
11910 			      /* If R's type couldn't be completed and
11911 				 it isn't a flexible array member (whose
11912 				 type is incomplete by definition) give
11913 				 an error.  */
11914 			      cxx_incomplete_type_error (r, rtype);
11915 			      TREE_TYPE (r) = error_mark_node;
11916 			    }
11917 			  else if (TREE_CODE (rtype) == ARRAY_TYPE
11918 				   && TYPE_DOMAIN (rtype) == NULL_TREE
11919 				   && (TREE_CODE (type) == UNION_TYPE
11920 				       || TREE_CODE (type) == QUAL_UNION_TYPE))
11921 			    {
11922 			      error ("flexible array member %qD in union", r);
11923 			      TREE_TYPE (r) = error_mark_node;
11924 			    }
11925 			  else if (!verify_type_context (input_location,
11926 							 TCTX_FIELD, rtype))
11927 			    TREE_TYPE (r) = error_mark_node;
11928 			}
11929 
11930 		      /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
11931 			 such a thing will already have been added to the field
11932 			 list by tsubst_enum in finish_member_declaration in the
11933 			 CLASSTYPE_NESTED_UTDS case above.  */
11934 		      if (!(TREE_CODE (r) == TYPE_DECL
11935 			    && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
11936 			    && DECL_ARTIFICIAL (r)))
11937 			{
11938 			  set_current_access_from_decl (r);
11939 			  finish_member_declaration (r);
11940 			}
11941 		    }
11942 		}
11943 	    }
11944 	}
11945       else
11946 	{
11947 	  if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
11948 	      || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11949 	    {
11950 	      /* Build new CLASSTYPE_FRIEND_CLASSES.  */
11951 
11952 	      tree friend_type = t;
11953 	      bool adjust_processing_template_decl = false;
11954 
11955 	      if (TREE_CODE (friend_type) == TEMPLATE_DECL)
11956 		{
11957 		  /* template <class T> friend class C;  */
11958 		  friend_type = tsubst_friend_class (friend_type, args);
11959 		  adjust_processing_template_decl = true;
11960 		}
11961 	      else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
11962 		{
11963 		  /* template <class T> friend class C::D;  */
11964 		  friend_type = tsubst (friend_type, args,
11965 					tf_warning_or_error, NULL_TREE);
11966 		  if (TREE_CODE (friend_type) == TEMPLATE_DECL)
11967 		    friend_type = TREE_TYPE (friend_type);
11968 		  adjust_processing_template_decl = true;
11969 		}
11970 	      else if (TREE_CODE (friend_type) == TYPENAME_TYPE
11971 		       || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
11972 		{
11973 		  /* This could be either
11974 
11975 		       friend class T::C;
11976 
11977 		     when dependent_type_p is false or
11978 
11979 		       template <class U> friend class T::C;
11980 
11981 		     otherwise.  */
11982 		  /* Bump processing_template_decl in case this is something like
11983 		     template <class T> friend struct A<T>::B.  */
11984 		  ++processing_template_decl;
11985 		  friend_type = tsubst (friend_type, args,
11986 					tf_warning_or_error, NULL_TREE);
11987 		  if (dependent_type_p (friend_type))
11988 		    adjust_processing_template_decl = true;
11989 		  --processing_template_decl;
11990 		}
11991 	      else if (TREE_CODE (friend_type) != BOUND_TEMPLATE_TEMPLATE_PARM
11992 		       && !CLASSTYPE_USE_TEMPLATE (friend_type)
11993 		       && TYPE_HIDDEN_P (friend_type))
11994 		{
11995 		  /* friend class C;
11996 
11997 		     where C hasn't been declared yet.  Let's lookup name
11998 		     from namespace scope directly, bypassing any name that
11999 		     come from dependent base class.  */
12000 		  tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
12001 
12002 		  /* The call to xref_tag_from_type does injection for friend
12003 		     classes.  */
12004 		  push_nested_namespace (ns);
12005 		  friend_type =
12006 		    xref_tag_from_type (friend_type, NULL_TREE,
12007 					/*tag_scope=*/ts_current);
12008 		  pop_nested_namespace (ns);
12009 		}
12010 	      else if (uses_template_parms (friend_type))
12011 		/* friend class C<T>;  */
12012 		friend_type = tsubst (friend_type, args,
12013 				      tf_warning_or_error, NULL_TREE);
12014 	      /* Otherwise it's
12015 
12016 		   friend class C;
12017 
12018 		 where C is already declared or
12019 
12020 		   friend class C<int>;
12021 
12022 		 We don't have to do anything in these cases.  */
12023 
12024 	      if (adjust_processing_template_decl)
12025 		/* Trick make_friend_class into realizing that the friend
12026 		   we're adding is a template, not an ordinary class.  It's
12027 		   important that we use make_friend_class since it will
12028 		   perform some error-checking and output cross-reference
12029 		   information.  */
12030 		++processing_template_decl;
12031 
12032 	      if (friend_type != error_mark_node)
12033 		make_friend_class (type, friend_type, /*complain=*/false);
12034 
12035 	      if (adjust_processing_template_decl)
12036 		--processing_template_decl;
12037 	    }
12038 	  else
12039 	    {
12040 	      /* Build new DECL_FRIENDLIST.  */
12041 	      tree r;
12042 
12043 	      /* The file and line for this declaration, to
12044 		 assist in error message reporting.  Since we
12045 		 called push_tinst_level above, we don't need to
12046 		 restore these.  */
12047 	      input_location = DECL_SOURCE_LOCATION (t);
12048 
12049 	      if (TREE_CODE (t) == TEMPLATE_DECL)
12050 		{
12051 		  ++processing_template_decl;
12052 		  push_deferring_access_checks (dk_no_check);
12053 		}
12054 
12055 	      r = tsubst_friend_function (t, args);
12056 	      add_friend (type, r, /*complain=*/false);
12057 	      if (TREE_CODE (t) == TEMPLATE_DECL)
12058 		{
12059 		  pop_deferring_access_checks ();
12060 		  --processing_template_decl;
12061 		}
12062 	    }
12063 	}
12064     }
12065 
12066   if (fn_context)
12067     {
12068       /* Restore these before substituting into the lambda capture
12069 	 initializers.  */
12070       cp_unevaluated_operand = saved_unevaluated_operand;
12071       c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
12072     }
12073 
12074   /* Set the file and line number information to whatever is given for
12075      the class itself.  This puts error messages involving generated
12076      implicit functions at a predictable point, and the same point
12077      that would be used for non-template classes.  */
12078   input_location = DECL_SOURCE_LOCATION (typedecl);
12079 
12080   unreverse_member_declarations (type);
12081   finish_struct_1 (type);
12082   TYPE_BEING_DEFINED (type) = 0;
12083 
12084   /* We don't instantiate default arguments for member functions.  14.7.1:
12085 
12086      The implicit instantiation of a class template specialization causes
12087      the implicit instantiation of the declarations, but not of the
12088      definitions or default arguments, of the class member functions,
12089      member classes, static data members and member templates....  */
12090 
12091   /* Some typedefs referenced from within the template code need to be access
12092      checked at template instantiation time, i.e now. These types were
12093      added to the template at parsing time. Let's get those and perform
12094      the access checks then.  */
12095   perform_typedefs_access_check (pattern, args);
12096   perform_deferred_access_checks (tf_warning_or_error);
12097   pop_nested_class ();
12098   maximum_field_alignment = saved_maximum_field_alignment;
12099   if (!fn_context)
12100     pop_from_top_level ();
12101   pop_tinst_level ();
12102 
12103   /* The vtable for a template class can be emitted in any translation
12104      unit in which the class is instantiated.  When there is no key
12105      method, however, finish_struct_1 will already have added TYPE to
12106      the keyed_classes.  */
12107   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
12108     vec_safe_push (keyed_classes, type);
12109 
12110   return type;
12111 }
12112 
12113 /* Wrapper for instantiate_class_template_1.  */
12114 
12115 tree
instantiate_class_template(tree type)12116 instantiate_class_template (tree type)
12117 {
12118   tree ret;
12119   timevar_push (TV_TEMPLATE_INST);
12120   ret = instantiate_class_template_1 (type);
12121   timevar_pop (TV_TEMPLATE_INST);
12122   return ret;
12123 }
12124 
12125 tree
tsubst_template_arg(tree t,tree args,tsubst_flags_t complain,tree in_decl)12126 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12127 {
12128   tree r;
12129 
12130   if (!t)
12131     r = t;
12132   else if (TYPE_P (t))
12133     r = tsubst (t, args, complain, in_decl);
12134   else
12135     {
12136       if (!(complain & tf_warning))
12137 	++c_inhibit_evaluation_warnings;
12138       r = tsubst_expr (t, args, complain, in_decl,
12139 		       /*integral_constant_expression_p=*/true);
12140       if (!(complain & tf_warning))
12141 	--c_inhibit_evaluation_warnings;
12142     }
12143 
12144   return r;
12145 }
12146 
12147 /* Given a function parameter pack TMPL_PARM and some function parameters
12148    instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
12149    and set *SPEC_P to point at the next point in the list.  */
12150 
12151 tree
extract_fnparm_pack(tree tmpl_parm,tree * spec_p)12152 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
12153 {
12154   /* Collect all of the extra "packed" parameters into an
12155      argument pack.  */
12156   tree parmvec;
12157   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
12158   tree spec_parm = *spec_p;
12159   int i, len;
12160 
12161   for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
12162     if (tmpl_parm
12163 	&& !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
12164       break;
12165 
12166   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
12167   parmvec = make_tree_vec (len);
12168   spec_parm = *spec_p;
12169   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
12170     {
12171       tree elt = spec_parm;
12172       if (DECL_PACK_P (elt))
12173 	elt = make_pack_expansion (elt);
12174       TREE_VEC_ELT (parmvec, i) = elt;
12175     }
12176 
12177   /* Build the argument packs.  */
12178   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
12179   *spec_p = spec_parm;
12180 
12181   return argpack;
12182 }
12183 
12184 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
12185    NONTYPE_ARGUMENT_PACK.  */
12186 
12187 static tree
make_fnparm_pack(tree spec_parm)12188 make_fnparm_pack (tree spec_parm)
12189 {
12190   return extract_fnparm_pack (NULL_TREE, &spec_parm);
12191 }
12192 
12193 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
12194    pack expansion with no extra args, 2 if it has extra args, or 0
12195    if it is not a pack expansion.  */
12196 
12197 static int
argument_pack_element_is_expansion_p(tree arg_pack,int i)12198 argument_pack_element_is_expansion_p (tree arg_pack, int i)
12199 {
12200   if (TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12201     /* We're being called before this happens in tsubst_pack_expansion.  */
12202     arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12203   tree vec = ARGUMENT_PACK_ARGS (arg_pack);
12204   if (i >= TREE_VEC_LENGTH (vec))
12205     return 0;
12206   tree elt = TREE_VEC_ELT (vec, i);
12207   if (DECL_P (elt))
12208     /* A decl pack is itself an expansion.  */
12209     elt = TREE_TYPE (elt);
12210   if (!PACK_EXPANSION_P (elt))
12211     return 0;
12212   if (PACK_EXPANSION_EXTRA_ARGS (elt))
12213     return 2;
12214   return 1;
12215 }
12216 
12217 
12218 /* Creates and return an ARGUMENT_PACK_SELECT tree node.  */
12219 
12220 static tree
make_argument_pack_select(tree arg_pack,unsigned index)12221 make_argument_pack_select (tree arg_pack, unsigned index)
12222 {
12223   tree aps = make_node (ARGUMENT_PACK_SELECT);
12224 
12225   ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
12226   ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12227 
12228   return aps;
12229 }
12230 
12231 /*  This is a subroutine of tsubst_pack_expansion.
12232 
12233     It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
12234     mechanism to store the (non complete list of) arguments of the
12235     substitution and return a non substituted pack expansion, in order
12236     to wait for when we have enough arguments to really perform the
12237     substitution.  */
12238 
12239 static bool
use_pack_expansion_extra_args_p(tree parm_packs,int arg_pack_len,bool has_empty_arg)12240 use_pack_expansion_extra_args_p (tree parm_packs,
12241 				 int arg_pack_len,
12242 				 bool has_empty_arg)
12243 {
12244   /* If one pack has an expansion and another pack has a normal
12245      argument or if one pack has an empty argument and an another
12246      one hasn't then tsubst_pack_expansion cannot perform the
12247      substitution and need to fall back on the
12248      PACK_EXPANSION_EXTRA mechanism.  */
12249   if (parm_packs == NULL_TREE)
12250     return false;
12251   else if (has_empty_arg)
12252     {
12253       /* If all the actual packs are pack expansions, we can still
12254 	 subsitute directly.  */
12255       for (tree p = parm_packs; p; p = TREE_CHAIN (p))
12256 	{
12257 	  tree a = TREE_VALUE (p);
12258 	  if (TREE_CODE (a) == ARGUMENT_PACK_SELECT)
12259 	    a = ARGUMENT_PACK_SELECT_FROM_PACK (a);
12260 	  a = ARGUMENT_PACK_ARGS (a);
12261 	  if (TREE_VEC_LENGTH (a) == 1)
12262 	    a = TREE_VEC_ELT (a, 0);
12263 	  if (PACK_EXPANSION_P (a))
12264 	    continue;
12265 	  return true;
12266 	}
12267       return false;
12268     }
12269 
12270   bool has_expansion_arg = false;
12271   for (int i = 0 ; i < arg_pack_len; ++i)
12272     {
12273       bool has_non_expansion_arg = false;
12274       for (tree parm_pack = parm_packs;
12275 	   parm_pack;
12276 	   parm_pack = TREE_CHAIN (parm_pack))
12277 	{
12278 	  tree arg = TREE_VALUE (parm_pack);
12279 
12280 	  int exp = argument_pack_element_is_expansion_p (arg, i);
12281 	  if (exp == 2)
12282 	    /* We can't substitute a pack expansion with extra args into
12283 	       our pattern.  */
12284 	    return true;
12285 	  else if (exp)
12286 	    has_expansion_arg = true;
12287 	  else
12288 	    has_non_expansion_arg = true;
12289 	}
12290 
12291       if (has_expansion_arg && has_non_expansion_arg)
12292 	return true;
12293     }
12294   return false;
12295 }
12296 
12297 /* [temp.variadic]/6 says that:
12298 
12299        The instantiation of a pack expansion [...]
12300        produces a list E1,E2, ..., En, where N is the number of elements
12301        in the pack expansion parameters.
12302 
12303    This subroutine of tsubst_pack_expansion produces one of these Ei.
12304 
12305    PATTERN is the pattern of the pack expansion.  PARM_PACKS is a
12306    TREE_LIST in which each TREE_PURPOSE is a parameter pack of
12307    PATTERN, and each TREE_VALUE is its corresponding argument pack.
12308    INDEX is the index 'i' of the element Ei to produce.  ARGS,
12309    COMPLAIN, and IN_DECL are the same parameters as for the
12310    tsubst_pack_expansion function.
12311 
12312    The function returns the resulting Ei upon successful completion,
12313    or error_mark_node.
12314 
12315    Note that this function possibly modifies the ARGS parameter, so
12316    it's the responsibility of the caller to restore it.  */
12317 
12318 static tree
gen_elem_of_pack_expansion_instantiation(tree pattern,tree parm_packs,unsigned index,tree args,tsubst_flags_t complain,tree in_decl)12319 gen_elem_of_pack_expansion_instantiation (tree pattern,
12320 					  tree parm_packs,
12321 					  unsigned index,
12322 					  tree args /* This parm gets
12323 						       modified.  */,
12324 					  tsubst_flags_t complain,
12325 					  tree in_decl)
12326 {
12327   tree t;
12328   bool ith_elem_is_expansion = false;
12329 
12330   /* For each parameter pack, change the substitution of the parameter
12331      pack to the ith argument in its argument pack, then expand the
12332      pattern.  */
12333   for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
12334     {
12335       tree parm = TREE_PURPOSE (pack);
12336       tree arg_pack = TREE_VALUE (pack);
12337       tree aps;			/* instance of ARGUMENT_PACK_SELECT.  */
12338 
12339       ith_elem_is_expansion |=
12340 	argument_pack_element_is_expansion_p (arg_pack, index);
12341 
12342       /* Select the Ith argument from the pack.  */
12343       if (TREE_CODE (parm) == PARM_DECL
12344 	  || VAR_P (parm)
12345 	  || TREE_CODE (parm) == FIELD_DECL)
12346 	{
12347 	  if (index == 0)
12348 	    {
12349 	      aps = make_argument_pack_select (arg_pack, index);
12350 	      if (!mark_used (parm, complain) && !(complain & tf_error))
12351 		return error_mark_node;
12352 	      register_local_specialization (aps, parm);
12353 	    }
12354 	  else
12355 	    aps = retrieve_local_specialization (parm);
12356 	}
12357       else
12358 	{
12359 	  int idx, level;
12360 	  template_parm_level_and_index (parm, &level, &idx);
12361 
12362 	  if (index == 0)
12363 	    {
12364 	      aps = make_argument_pack_select (arg_pack, index);
12365 	      /* Update the corresponding argument.  */
12366 	      TMPL_ARG (args, level, idx) = aps;
12367 	    }
12368 	  else
12369 	    /* Re-use the ARGUMENT_PACK_SELECT.  */
12370 	    aps = TMPL_ARG (args, level, idx);
12371 	}
12372       ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12373     }
12374 
12375   /* Substitute into the PATTERN with the (possibly altered)
12376      arguments.  */
12377   if (pattern == in_decl)
12378     /* Expanding a fixed parameter pack from
12379        coerce_template_parameter_pack.  */
12380     t = tsubst_decl (pattern, args, complain);
12381   else if (pattern == error_mark_node)
12382     t = error_mark_node;
12383   else if (!TYPE_P (pattern))
12384     t = tsubst_expr (pattern, args, complain, in_decl,
12385 		     /*integral_constant_expression_p=*/false);
12386   else
12387     t = tsubst (pattern, args, complain, in_decl);
12388 
12389   /*  If the Ith argument pack element is a pack expansion, then
12390       the Ith element resulting from the substituting is going to
12391       be a pack expansion as well.  */
12392   if (ith_elem_is_expansion)
12393     t = make_pack_expansion (t, complain);
12394 
12395   return t;
12396 }
12397 
12398 /* When the unexpanded parameter pack in a fold expression expands to an empty
12399    sequence, the value of the expression is as follows; the program is
12400    ill-formed if the operator is not listed in this table.
12401 
12402    &&	true
12403    ||	false
12404    ,	void()  */
12405 
12406 tree
expand_empty_fold(tree t,tsubst_flags_t complain)12407 expand_empty_fold (tree t, tsubst_flags_t complain)
12408 {
12409   tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
12410   if (!FOLD_EXPR_MODIFY_P (t))
12411     switch (code)
12412       {
12413       case TRUTH_ANDIF_EXPR:
12414 	return boolean_true_node;
12415       case TRUTH_ORIF_EXPR:
12416 	return boolean_false_node;
12417       case COMPOUND_EXPR:
12418 	return void_node;
12419       default:
12420 	break;
12421       }
12422 
12423   if (complain & tf_error)
12424     error_at (location_of (t),
12425 	      "fold of empty expansion over %O", code);
12426   return error_mark_node;
12427 }
12428 
12429 /* Given a fold-expression T and a current LEFT and RIGHT operand,
12430    form an expression that combines the two terms using the
12431    operator of T. */
12432 
12433 static tree
fold_expression(tree t,tree left,tree right,tsubst_flags_t complain)12434 fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
12435 {
12436   tree op = FOLD_EXPR_OP (t);
12437   tree_code code = (tree_code)TREE_INT_CST_LOW (op);
12438 
12439   // Handle compound assignment operators.
12440   if (FOLD_EXPR_MODIFY_P (t))
12441     return build_x_modify_expr (input_location, left, code, right, complain);
12442 
12443   warning_sentinel s(warn_parentheses);
12444   switch (code)
12445     {
12446     case COMPOUND_EXPR:
12447       return build_x_compound_expr (input_location, left, right, complain);
12448     default:
12449       return build_x_binary_op (input_location, code,
12450                                 left, TREE_CODE (left),
12451                                 right, TREE_CODE (right),
12452                                 /*overload=*/NULL,
12453                                 complain);
12454     }
12455 }
12456 
12457 /* Substitute ARGS into the pack of a fold expression T. */
12458 
12459 static inline tree
tsubst_fold_expr_pack(tree t,tree args,tsubst_flags_t complain,tree in_decl)12460 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12461 {
12462   return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
12463 }
12464 
12465 /* Substitute ARGS into the pack of a fold expression T. */
12466 
12467 static inline tree
tsubst_fold_expr_init(tree t,tree args,tsubst_flags_t complain,tree in_decl)12468 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12469 {
12470   return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl, false);
12471 }
12472 
12473 /* Expand a PACK of arguments into a grouped as left fold.
12474    Given a pack containing elements A0, A1, ..., An and an
12475    operator @, this builds the expression:
12476 
12477       ((A0 @ A1) @ A2) ... @ An
12478 
12479    Note that PACK must not be empty.
12480 
12481    The operator is defined by the original fold expression T. */
12482 
12483 static tree
expand_left_fold(tree t,tree pack,tsubst_flags_t complain)12484 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
12485 {
12486   tree left = TREE_VEC_ELT (pack, 0);
12487   for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
12488     {
12489       tree right = TREE_VEC_ELT (pack, i);
12490       left = fold_expression (t, left, right, complain);
12491     }
12492   return left;
12493 }
12494 
12495 /* Substitute into a unary left fold expression. */
12496 
12497 static tree
tsubst_unary_left_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)12498 tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
12499                         tree in_decl)
12500 {
12501   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12502   if (pack == error_mark_node)
12503     return error_mark_node;
12504   if (PACK_EXPANSION_P (pack))
12505     {
12506       tree r = copy_node (t);
12507       FOLD_EXPR_PACK (r) = pack;
12508       return r;
12509     }
12510   if (TREE_VEC_LENGTH (pack) == 0)
12511     return expand_empty_fold (t, complain);
12512   else
12513     return expand_left_fold (t, pack, complain);
12514 }
12515 
12516 /* Substitute into a binary left fold expression.
12517 
12518    Do ths by building a single (non-empty) vector of argumnts and
12519    building the expression from those elements. */
12520 
12521 static tree
tsubst_binary_left_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)12522 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
12523                          tree in_decl)
12524 {
12525   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12526   if (pack == error_mark_node)
12527     return error_mark_node;
12528   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
12529   if (init == error_mark_node)
12530     return error_mark_node;
12531 
12532   if (PACK_EXPANSION_P (pack))
12533     {
12534       tree r = copy_node (t);
12535       FOLD_EXPR_PACK (r) = pack;
12536       FOLD_EXPR_INIT (r) = init;
12537       return r;
12538     }
12539 
12540   tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
12541   TREE_VEC_ELT (vec, 0) = init;
12542   for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
12543     TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
12544 
12545   return expand_left_fold (t, vec, complain);
12546 }
12547 
12548 /* Expand a PACK of arguments into a grouped as right fold.
12549    Given a pack containing elementns A0, A1, ..., and an
12550    operator @, this builds the expression:
12551 
12552       A0@ ... (An-2 @ (An-1 @ An))
12553 
12554    Note that PACK must not be empty.
12555 
12556    The operator is defined by the original fold expression T. */
12557 
12558 tree
expand_right_fold(tree t,tree pack,tsubst_flags_t complain)12559 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
12560 {
12561   // Build the expression.
12562   int n = TREE_VEC_LENGTH (pack);
12563   tree right = TREE_VEC_ELT (pack, n - 1);
12564   for (--n; n != 0; --n)
12565     {
12566       tree left = TREE_VEC_ELT (pack, n - 1);
12567       right = fold_expression (t, left, right, complain);
12568     }
12569   return right;
12570 }
12571 
12572 /* Substitute into a unary right fold expression. */
12573 
12574 static tree
tsubst_unary_right_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)12575 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
12576                          tree in_decl)
12577 {
12578   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12579   if (pack == error_mark_node)
12580     return error_mark_node;
12581   if (PACK_EXPANSION_P (pack))
12582     {
12583       tree r = copy_node (t);
12584       FOLD_EXPR_PACK (r) = pack;
12585       return r;
12586     }
12587   if (TREE_VEC_LENGTH (pack) == 0)
12588     return expand_empty_fold (t, complain);
12589   else
12590     return expand_right_fold (t, pack, complain);
12591 }
12592 
12593 /* Substitute into a binary right fold expression.
12594 
12595    Do ths by building a single (non-empty) vector of arguments and
12596    building the expression from those elements. */
12597 
12598 static tree
tsubst_binary_right_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)12599 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
12600                          tree in_decl)
12601 {
12602   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12603   if (pack == error_mark_node)
12604     return error_mark_node;
12605   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
12606   if (init == error_mark_node)
12607     return error_mark_node;
12608 
12609   if (PACK_EXPANSION_P (pack))
12610     {
12611       tree r = copy_node (t);
12612       FOLD_EXPR_PACK (r) = pack;
12613       FOLD_EXPR_INIT (r) = init;
12614       return r;
12615     }
12616 
12617   int n = TREE_VEC_LENGTH (pack);
12618   tree vec = make_tree_vec (n + 1);
12619   for (int i = 0; i < n; ++i)
12620     TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
12621   TREE_VEC_ELT (vec, n) = init;
12622 
12623   return expand_right_fold (t, vec, complain);
12624 }
12625 
12626 /* Walk through the pattern of a pack expansion, adding everything in
12627    local_specializations to a list.  */
12628 
12629 class el_data
12630 {
12631 public:
12632   hash_set<tree> internal;
12633   tree extra;
12634   tsubst_flags_t complain;
12635 
el_data(tsubst_flags_t c)12636   el_data (tsubst_flags_t c)
12637     : extra (NULL_TREE), complain (c) {}
12638 };
12639 static tree
extract_locals_r(tree * tp,int *,void * data_)12640 extract_locals_r (tree *tp, int */*walk_subtrees*/, void *data_)
12641 {
12642   el_data &data = *reinterpret_cast<el_data*>(data_);
12643   tree *extra = &data.extra;
12644   tsubst_flags_t complain = data.complain;
12645 
12646   if (TYPE_P (*tp) && typedef_variant_p (*tp))
12647     /* Remember local typedefs (85214).  */
12648     tp = &TYPE_NAME (*tp);
12649 
12650   if (TREE_CODE (*tp) == DECL_EXPR)
12651     data.internal.add (DECL_EXPR_DECL (*tp));
12652   else if (tree spec = retrieve_local_specialization (*tp))
12653     {
12654       if (data.internal.contains (*tp))
12655 	/* Don't mess with variables declared within the pattern.  */
12656 	return NULL_TREE;
12657       if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
12658 	{
12659 	  /* Maybe pull out the PARM_DECL for a partial instantiation.  */
12660 	  tree args = ARGUMENT_PACK_ARGS (spec);
12661 	  if (TREE_VEC_LENGTH (args) == 1)
12662 	    {
12663 	      tree elt = TREE_VEC_ELT (args, 0);
12664 	      if (PACK_EXPANSION_P (elt))
12665 		elt = PACK_EXPANSION_PATTERN (elt);
12666 	      if (DECL_PACK_P (elt))
12667 		spec = elt;
12668 	    }
12669 	  if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
12670 	    {
12671 	      /* Handle lambda capture here, since we aren't doing any
12672 		 substitution now, and so tsubst_copy won't call
12673 		 process_outer_var_ref.  */
12674 	      tree args = ARGUMENT_PACK_ARGS (spec);
12675 	      int len = TREE_VEC_LENGTH (args);
12676 	      for (int i = 0; i < len; ++i)
12677 		{
12678 		  tree arg = TREE_VEC_ELT (args, i);
12679 		  tree carg = arg;
12680 		  if (outer_automatic_var_p (arg))
12681 		    carg = process_outer_var_ref (arg, complain);
12682 		  if (carg != arg)
12683 		    {
12684 		      /* Make a new NONTYPE_ARGUMENT_PACK of the capture
12685 			 proxies.  */
12686 		      if (i == 0)
12687 			{
12688 			  spec = copy_node (spec);
12689 			  args = copy_node (args);
12690 			  SET_ARGUMENT_PACK_ARGS (spec, args);
12691 			  register_local_specialization (spec, *tp);
12692 			}
12693 		      TREE_VEC_ELT (args, i) = carg;
12694 		    }
12695 		}
12696 	    }
12697 	}
12698       if (outer_automatic_var_p (spec))
12699 	spec = process_outer_var_ref (spec, complain);
12700       *extra = tree_cons (*tp, spec, *extra);
12701     }
12702   return NULL_TREE;
12703 }
12704 static tree
extract_local_specs(tree pattern,tsubst_flags_t complain)12705 extract_local_specs (tree pattern, tsubst_flags_t complain)
12706 {
12707   el_data data (complain);
12708   cp_walk_tree_without_duplicates (&pattern, extract_locals_r, &data);
12709   return data.extra;
12710 }
12711 
12712 /* Extract any uses of local_specializations from PATTERN and add them to ARGS
12713    for use in PACK_EXPANSION_EXTRA_ARGS.  */
12714 
12715 tree
build_extra_args(tree pattern,tree args,tsubst_flags_t complain)12716 build_extra_args (tree pattern, tree args, tsubst_flags_t complain)
12717 {
12718   tree extra = args;
12719   if (local_specializations)
12720     if (tree locals = extract_local_specs (pattern, complain))
12721       extra = tree_cons (NULL_TREE, extra, locals);
12722   return extra;
12723 }
12724 
12725 /* Apply any local specializations from PACK_EXPANSION_EXTRA_ARGS and add the
12726    normal template args to ARGS.  */
12727 
12728 tree
add_extra_args(tree extra,tree args)12729 add_extra_args (tree extra, tree args)
12730 {
12731   if (extra && TREE_CODE (extra) == TREE_LIST)
12732     {
12733       for (tree elt = TREE_CHAIN (extra); elt; elt = TREE_CHAIN (elt))
12734 	{
12735 	  /* The partial instantiation involved local declarations collected in
12736 	     extract_local_specs; map from the general template to our local
12737 	     context.  */
12738 	  tree gen = TREE_PURPOSE (elt);
12739 	  tree inst = TREE_VALUE (elt);
12740 	  if (DECL_P (inst))
12741 	    if (tree local = retrieve_local_specialization (inst))
12742 	      inst = local;
12743 	  /* else inst is already a full instantiation of the pack.  */
12744 	  register_local_specialization (inst, gen);
12745 	}
12746       gcc_assert (!TREE_PURPOSE (extra));
12747       extra = TREE_VALUE (extra);
12748     }
12749 #if 1
12750   /* I think we should always be able to substitute dependent args into the
12751      pattern.  If that turns out to be incorrect in some cases, enable the
12752      alternate code (and add complain/in_decl parms to this function).  */
12753   gcc_checking_assert (!uses_template_parms (extra));
12754 #else
12755   if (!uses_template_parms (extra))
12756     {
12757       gcc_unreachable ();
12758       extra = tsubst_template_args (extra, args, complain, in_decl);
12759       args = add_outermost_template_args (args, extra);
12760     }
12761   else
12762 #endif
12763     args = add_to_template_args (extra, args);
12764   return args;
12765 }
12766 
12767 /* Substitute ARGS into T, which is an pack expansion
12768    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
12769    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
12770    (if only a partial substitution could be performed) or
12771    ERROR_MARK_NODE if there was an error.  */
12772 tree
tsubst_pack_expansion(tree t,tree args,tsubst_flags_t complain,tree in_decl)12773 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
12774 		       tree in_decl)
12775 {
12776   tree pattern;
12777   tree pack, packs = NULL_TREE;
12778   bool unsubstituted_packs = false;
12779   int i, len = -1;
12780   tree result;
12781   bool need_local_specializations = false;
12782   int levels;
12783 
12784   gcc_assert (PACK_EXPANSION_P (t));
12785   pattern = PACK_EXPANSION_PATTERN (t);
12786 
12787   /* Add in any args remembered from an earlier partial instantiation.  */
12788   args = add_extra_args (PACK_EXPANSION_EXTRA_ARGS (t), args);
12789 
12790   levels = TMPL_ARGS_DEPTH (args);
12791 
12792   /* Determine the argument packs that will instantiate the parameter
12793      packs used in the expansion expression. While we're at it,
12794      compute the number of arguments to be expanded and make sure it
12795      is consistent.  */
12796   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
12797        pack = TREE_CHAIN (pack))
12798     {
12799       tree parm_pack = TREE_VALUE (pack);
12800       tree arg_pack = NULL_TREE;
12801       tree orig_arg = NULL_TREE;
12802       int level = 0;
12803 
12804       if (TREE_CODE (parm_pack) == BASES)
12805 	{
12806 	  gcc_assert (parm_pack == pattern);
12807 	  if (BASES_DIRECT (parm_pack))
12808 	    return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
12809 							args, complain,
12810 							in_decl, false),
12811 					   complain);
12812 	  else
12813 	    return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
12814 						 args, complain, in_decl,
12815 						 false), complain);
12816 	}
12817       else if (builtin_pack_call_p (parm_pack))
12818 	{
12819 	  if (parm_pack != pattern)
12820 	    {
12821 	      if (complain & tf_error)
12822 		sorry ("%qE is not the entire pattern of the pack expansion",
12823 		       parm_pack);
12824 	      return error_mark_node;
12825 	    }
12826 	  return expand_builtin_pack_call (parm_pack, args,
12827 					   complain, in_decl);
12828 	}
12829       else if (TREE_CODE (parm_pack) == PARM_DECL)
12830 	{
12831 	  /* We know we have correct local_specializations if this
12832 	     expansion is at function scope, or if we're dealing with a
12833 	     local parameter in a requires expression; for the latter,
12834 	     tsubst_requires_expr set it up appropriately.  */
12835 	  if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
12836 	    arg_pack = retrieve_local_specialization (parm_pack);
12837 	  else
12838 	    /* We can't rely on local_specializations for a parameter
12839 	       name used later in a function declaration (such as in a
12840 	       late-specified return type).  Even if it exists, it might
12841 	       have the wrong value for a recursive call.  */
12842 	    need_local_specializations = true;
12843 
12844 	  if (!arg_pack)
12845 	    {
12846 	      /* This parameter pack was used in an unevaluated context.  Just
12847 		 make a dummy decl, since it's only used for its type.  */
12848 	      ++cp_unevaluated_operand;
12849 	      arg_pack = tsubst_decl (parm_pack, args, complain);
12850 	      --cp_unevaluated_operand;
12851 	      if (arg_pack && DECL_PACK_P (arg_pack))
12852 		/* Partial instantiation of the parm_pack, we can't build
12853 		   up an argument pack yet.  */
12854 		arg_pack = NULL_TREE;
12855 	      else
12856 		arg_pack = make_fnparm_pack (arg_pack);
12857 	    }
12858 	  else if (DECL_PACK_P (arg_pack))
12859 	    /* This argument pack isn't fully instantiated yet.  */
12860 	    arg_pack = NULL_TREE;
12861 	}
12862       else if (is_capture_proxy (parm_pack))
12863 	{
12864 	  arg_pack = retrieve_local_specialization (parm_pack);
12865 	  if (DECL_PACK_P (arg_pack))
12866 	    arg_pack = NULL_TREE;
12867 	}
12868       else
12869         {
12870 	  int idx;
12871           template_parm_level_and_index (parm_pack, &level, &idx);
12872           if (level <= levels)
12873             arg_pack = TMPL_ARG (args, level, idx);
12874 
12875 	  if (arg_pack && TREE_CODE (arg_pack) == TEMPLATE_TYPE_PARM
12876 	      && TEMPLATE_TYPE_PARAMETER_PACK (arg_pack))
12877 	    arg_pack = NULL_TREE;
12878         }
12879 
12880       orig_arg = arg_pack;
12881       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12882 	arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12883 
12884       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
12885 	/* This can only happen if we forget to expand an argument
12886 	   pack somewhere else. Just return an error, silently.  */
12887 	{
12888 	  result = make_tree_vec (1);
12889 	  TREE_VEC_ELT (result, 0) = error_mark_node;
12890 	  return result;
12891 	}
12892 
12893       if (arg_pack)
12894         {
12895           int my_len =
12896             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
12897 
12898 	  /* Don't bother trying to do a partial substitution with
12899 	     incomplete packs; we'll try again after deduction.  */
12900           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
12901             return t;
12902 
12903           if (len < 0)
12904 	    len = my_len;
12905 	  else if (len != my_len)
12906             {
12907 	      if (!(complain & tf_error))
12908 		/* Fail quietly.  */;
12909               else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
12910                 error ("mismatched argument pack lengths while expanding %qT",
12911                        pattern);
12912               else
12913                 error ("mismatched argument pack lengths while expanding %qE",
12914                        pattern);
12915               return error_mark_node;
12916             }
12917 
12918           /* Keep track of the parameter packs and their corresponding
12919              argument packs.  */
12920           packs = tree_cons (parm_pack, arg_pack, packs);
12921           TREE_TYPE (packs) = orig_arg;
12922         }
12923       else
12924 	{
12925 	  /* We can't substitute for this parameter pack.  We use a flag as
12926 	     well as the missing_level counter because function parameter
12927 	     packs don't have a level.  */
12928 	  gcc_assert (processing_template_decl || is_auto (parm_pack));
12929 	  unsubstituted_packs = true;
12930 	}
12931     }
12932 
12933   /* If the expansion is just T..., return the matching argument pack, unless
12934      we need to call convert_from_reference on all the elements.  This is an
12935      important optimization; see c++/68422.  */
12936   if (!unsubstituted_packs
12937       && TREE_PURPOSE (packs) == pattern)
12938     {
12939       tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
12940 
12941       /* If the argument pack is a single pack expansion, pull it out.  */
12942       if (TREE_VEC_LENGTH (args) == 1
12943 	  && pack_expansion_args_count (args))
12944 	return TREE_VEC_ELT (args, 0);
12945 
12946       /* Types need no adjustment, nor does sizeof..., and if we still have
12947 	 some pack expansion args we won't do anything yet.  */
12948       if (TREE_CODE (t) == TYPE_PACK_EXPANSION
12949 	  || PACK_EXPANSION_SIZEOF_P (t)
12950 	  || pack_expansion_args_count (args))
12951 	return args;
12952       /* Also optimize expression pack expansions if we can tell that the
12953 	 elements won't have reference type.  */
12954       tree type = TREE_TYPE (pattern);
12955       if (type && !TYPE_REF_P (type)
12956 	  && !PACK_EXPANSION_P (type)
12957 	  && !WILDCARD_TYPE_P (type))
12958 	return args;
12959       /* Otherwise use the normal path so we get convert_from_reference.  */
12960     }
12961 
12962   /* We cannot expand this expansion expression, because we don't have
12963      all of the argument packs we need.  */
12964   if (use_pack_expansion_extra_args_p (packs, len, unsubstituted_packs))
12965     {
12966       /* We got some full packs, but we can't substitute them in until we
12967 	 have values for all the packs.  So remember these until then.  */
12968 
12969       t = make_pack_expansion (pattern, complain);
12970       PACK_EXPANSION_EXTRA_ARGS (t)
12971 	= build_extra_args (pattern, args, complain);
12972       return t;
12973     }
12974 
12975   /* If NEED_LOCAL_SPECIALIZATIONS then we're in a late-specified return
12976      type, so create our own local specializations map; the current map is
12977      either NULL or (in the case of recursive unification) might have
12978      bindings that we don't want to use or alter.  */
12979   local_specialization_stack lss (need_local_specializations
12980 				  ? lss_blank : lss_nop);
12981 
12982   if (unsubstituted_packs)
12983     {
12984       /* There were no real arguments, we're just replacing a parameter
12985 	 pack with another version of itself. Substitute into the
12986 	 pattern and return a PACK_EXPANSION_*. The caller will need to
12987 	 deal with that.  */
12988       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
12989 	t = tsubst_expr (pattern, args, complain, in_decl,
12990 			 /*integral_constant_expression_p=*/false);
12991       else
12992 	t = tsubst (pattern, args, complain, in_decl);
12993       t = make_pack_expansion (t, complain);
12994       return t;
12995     }
12996 
12997   gcc_assert (len >= 0);
12998 
12999   /* For each argument in each argument pack, substitute into the
13000      pattern.  */
13001   result = make_tree_vec (len);
13002   tree elem_args = copy_template_args (args);
13003   for (i = 0; i < len; ++i)
13004     {
13005       t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
13006 						    i,
13007 						    elem_args, complain,
13008 						    in_decl);
13009       TREE_VEC_ELT (result, i) = t;
13010       if (t == error_mark_node)
13011 	{
13012 	  result = error_mark_node;
13013 	  break;
13014 	}
13015     }
13016 
13017   /* Update ARGS to restore the substitution from parameter packs to
13018      their argument packs.  */
13019   for (pack = packs; pack; pack = TREE_CHAIN (pack))
13020     {
13021       tree parm = TREE_PURPOSE (pack);
13022 
13023       if (TREE_CODE (parm) == PARM_DECL
13024 	  || VAR_P (parm)
13025 	  || TREE_CODE (parm) == FIELD_DECL)
13026         register_local_specialization (TREE_TYPE (pack), parm);
13027       else
13028         {
13029           int idx, level;
13030 
13031 	  if (TREE_VALUE (pack) == NULL_TREE)
13032 	    continue;
13033 
13034           template_parm_level_and_index (parm, &level, &idx);
13035 
13036           /* Update the corresponding argument.  */
13037           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
13038             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
13039               TREE_TYPE (pack);
13040           else
13041             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
13042         }
13043     }
13044 
13045   /* If the dependent pack arguments were such that we end up with only a
13046      single pack expansion again, there's no need to keep it in a TREE_VEC.  */
13047   if (len == 1 && TREE_CODE (result) == TREE_VEC
13048       && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
13049     return TREE_VEC_ELT (result, 0);
13050 
13051   return result;
13052 }
13053 
13054 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
13055    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
13056    parameter packs; all parms generated from a function parameter pack will
13057    have the same DECL_PARM_INDEX.  */
13058 
13059 tree
get_pattern_parm(tree parm,tree tmpl)13060 get_pattern_parm (tree parm, tree tmpl)
13061 {
13062   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
13063   tree patparm;
13064 
13065   if (DECL_ARTIFICIAL (parm))
13066     {
13067       for (patparm = DECL_ARGUMENTS (pattern);
13068 	   patparm; patparm = DECL_CHAIN (patparm))
13069 	if (DECL_ARTIFICIAL (patparm)
13070 	    && DECL_NAME (parm) == DECL_NAME (patparm))
13071 	  break;
13072     }
13073   else
13074     {
13075       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
13076       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
13077       gcc_assert (DECL_PARM_INDEX (patparm)
13078 		  == DECL_PARM_INDEX (parm));
13079     }
13080 
13081   return patparm;
13082 }
13083 
13084 /* Make an argument pack out of the TREE_VEC VEC.  */
13085 
13086 static tree
make_argument_pack(tree vec)13087 make_argument_pack (tree vec)
13088 {
13089   tree pack;
13090   tree elt = TREE_VEC_ELT (vec, 0);
13091   if (TYPE_P (elt))
13092     pack = cxx_make_type (TYPE_ARGUMENT_PACK);
13093   else
13094     {
13095       pack = make_node (NONTYPE_ARGUMENT_PACK);
13096       TREE_CONSTANT (pack) = 1;
13097     }
13098   SET_ARGUMENT_PACK_ARGS (pack, vec);
13099   return pack;
13100 }
13101 
13102 /* Return an exact copy of template args T that can be modified
13103    independently.  */
13104 
13105 static tree
copy_template_args(tree t)13106 copy_template_args (tree t)
13107 {
13108   if (t == error_mark_node)
13109     return t;
13110 
13111   int len = TREE_VEC_LENGTH (t);
13112   tree new_vec = make_tree_vec (len);
13113 
13114   for (int i = 0; i < len; ++i)
13115     {
13116       tree elt = TREE_VEC_ELT (t, i);
13117       if (elt && TREE_CODE (elt) == TREE_VEC)
13118 	elt = copy_template_args (elt);
13119       TREE_VEC_ELT (new_vec, i) = elt;
13120     }
13121 
13122   NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
13123     = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13124 
13125   return new_vec;
13126 }
13127 
13128 /* Substitute ARGS into the *_ARGUMENT_PACK orig_arg.  */
13129 
13130 tree
tsubst_argument_pack(tree orig_arg,tree args,tsubst_flags_t complain,tree in_decl)13131 tsubst_argument_pack (tree orig_arg, tree args, tsubst_flags_t complain,
13132 		      tree in_decl)
13133 {
13134   /* Substitute into each of the arguments.  */
13135   tree new_arg = TYPE_P (orig_arg)
13136     ? cxx_make_type (TREE_CODE (orig_arg))
13137     : make_node (TREE_CODE (orig_arg));
13138 
13139   tree pack_args = tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
13140 					 args, complain, in_decl);
13141   if (pack_args == error_mark_node)
13142     new_arg = error_mark_node;
13143   else
13144     SET_ARGUMENT_PACK_ARGS (new_arg, pack_args);
13145 
13146   if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK)
13147     TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
13148 
13149   return new_arg;
13150 }
13151 
13152 /* Substitute ARGS into the vector or list of template arguments T.  */
13153 
13154 tree
tsubst_template_args(tree t,tree args,tsubst_flags_t complain,tree in_decl)13155 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
13156 {
13157   tree orig_t = t;
13158   int len, need_new = 0, i, expanded_len_adjust = 0, out;
13159   tree *elts;
13160 
13161   if (t == error_mark_node)
13162     return error_mark_node;
13163 
13164   len = TREE_VEC_LENGTH (t);
13165   elts = XALLOCAVEC (tree, len);
13166 
13167   for (i = 0; i < len; i++)
13168     {
13169       tree orig_arg = TREE_VEC_ELT (t, i);
13170       tree new_arg;
13171 
13172       if (TREE_CODE (orig_arg) == TREE_VEC)
13173 	new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
13174       else if (PACK_EXPANSION_P (orig_arg))
13175         {
13176           /* Substitute into an expansion expression.  */
13177           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
13178 
13179           if (TREE_CODE (new_arg) == TREE_VEC)
13180             /* Add to the expanded length adjustment the number of
13181                expanded arguments. We subtract one from this
13182                measurement, because the argument pack expression
13183                itself is already counted as 1 in
13184                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
13185                the argument pack is empty.  */
13186             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
13187         }
13188       else if (ARGUMENT_PACK_P (orig_arg))
13189 	new_arg = tsubst_argument_pack (orig_arg, args, complain, in_decl);
13190       else
13191 	new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
13192 
13193       if (new_arg == error_mark_node)
13194 	return error_mark_node;
13195 
13196       elts[i] = new_arg;
13197       if (new_arg != orig_arg)
13198 	need_new = 1;
13199     }
13200 
13201   if (!need_new)
13202     return t;
13203 
13204   /* Make space for the expanded arguments coming from template
13205      argument packs.  */
13206   t = make_tree_vec (len + expanded_len_adjust);
13207   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
13208      arguments for a member template.
13209      In that case each TREE_VEC in ORIG_T represents a level of template
13210      arguments, and ORIG_T won't carry any non defaulted argument count.
13211      It will rather be the nested TREE_VECs that will carry one.
13212      In other words, ORIG_T carries a non defaulted argument count only
13213      if it doesn't contain any nested TREE_VEC.  */
13214   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
13215     {
13216       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
13217       count += expanded_len_adjust;
13218       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
13219     }
13220   for (i = 0, out = 0; i < len; i++)
13221     {
13222       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
13223            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
13224           && TREE_CODE (elts[i]) == TREE_VEC)
13225         {
13226           int idx;
13227 
13228           /* Now expand the template argument pack "in place".  */
13229           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
13230             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
13231         }
13232       else
13233         {
13234           TREE_VEC_ELT (t, out) = elts[i];
13235           out++;
13236         }
13237     }
13238 
13239   return t;
13240 }
13241 
13242 /* Substitute ARGS into one level PARMS of template parameters.  */
13243 
13244 static tree
tsubst_template_parms_level(tree parms,tree args,tsubst_flags_t complain)13245 tsubst_template_parms_level (tree parms, tree args, tsubst_flags_t complain)
13246 {
13247   if (parms == error_mark_node)
13248     return error_mark_node;
13249 
13250   tree new_vec = make_tree_vec (TREE_VEC_LENGTH (parms));
13251 
13252   for (int i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
13253     {
13254       tree tuple = TREE_VEC_ELT (parms, i);
13255 
13256       if (tuple == error_mark_node)
13257 	continue;
13258 
13259       TREE_VEC_ELT (new_vec, i) =
13260 	tsubst_template_parm (tuple, args, complain);
13261     }
13262 
13263   return new_vec;
13264 }
13265 
13266 /* Return the result of substituting ARGS into the template parameters
13267    given by PARMS.  If there are m levels of ARGS and m + n levels of
13268    PARMS, then the result will contain n levels of PARMS.  For
13269    example, if PARMS is `template <class T> template <class U>
13270    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
13271    result will be `template <int*, double, class V>'.  */
13272 
13273 static tree
tsubst_template_parms(tree parms,tree args,tsubst_flags_t complain)13274 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
13275 {
13276   tree r = NULL_TREE;
13277   tree* new_parms;
13278 
13279   /* When substituting into a template, we must set
13280      PROCESSING_TEMPLATE_DECL as the template parameters may be
13281      dependent if they are based on one-another, and the dependency
13282      predicates are short-circuit outside of templates.  */
13283   ++processing_template_decl;
13284 
13285   for (new_parms = &r;
13286        parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
13287        new_parms = &(TREE_CHAIN (*new_parms)),
13288 	 parms = TREE_CHAIN (parms))
13289     {
13290       tree new_vec = tsubst_template_parms_level (TREE_VALUE (parms),
13291 						  args, complain);
13292       *new_parms =
13293 	tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
13294 			     - TMPL_ARGS_DEPTH (args)),
13295 		   new_vec, NULL_TREE);
13296       TEMPLATE_PARMS_CONSTRAINTS (*new_parms)
13297 	= TEMPLATE_PARMS_CONSTRAINTS (parms);
13298     }
13299 
13300   --processing_template_decl;
13301 
13302   return r;
13303 }
13304 
13305 /* Return the result of substituting ARGS into one template parameter
13306    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
13307    parameter and which TREE_PURPOSE is the default argument of the
13308    template parameter.  */
13309 
13310 static tree
tsubst_template_parm(tree t,tree args,tsubst_flags_t complain)13311 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
13312 {
13313   tree default_value, parm_decl;
13314 
13315   if (args == NULL_TREE
13316       || t == NULL_TREE
13317       || t == error_mark_node)
13318     return t;
13319 
13320   gcc_assert (TREE_CODE (t) == TREE_LIST);
13321 
13322   default_value = TREE_PURPOSE (t);
13323   parm_decl = TREE_VALUE (t);
13324   tree constraint = TEMPLATE_PARM_CONSTRAINTS (t);
13325 
13326   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
13327   if (TREE_CODE (parm_decl) == PARM_DECL
13328       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
13329     parm_decl = error_mark_node;
13330   default_value = tsubst_template_arg (default_value, args,
13331 				       complain, NULL_TREE);
13332   constraint = tsubst_constraint (constraint, args, complain, NULL_TREE);
13333 
13334   tree r = build_tree_list (default_value, parm_decl);
13335   TEMPLATE_PARM_CONSTRAINTS (r) = constraint;
13336   return r;
13337 }
13338 
13339 /* Substitute the ARGS into the indicated aggregate (or enumeration)
13340    type T.  If T is not an aggregate or enumeration type, it is
13341    handled as if by tsubst.  IN_DECL is as for tsubst.  If
13342    ENTERING_SCOPE is nonzero, T is the context for a template which
13343    we are presently tsubst'ing.  Return the substituted value.  */
13344 
13345 static tree
tsubst_aggr_type(tree t,tree args,tsubst_flags_t complain,tree in_decl,int entering_scope)13346 tsubst_aggr_type (tree t,
13347 		  tree args,
13348 		  tsubst_flags_t complain,
13349 		  tree in_decl,
13350 		  int entering_scope)
13351 {
13352   if (t == NULL_TREE)
13353     return NULL_TREE;
13354 
13355   switch (TREE_CODE (t))
13356     {
13357     case RECORD_TYPE:
13358       if (TYPE_PTRMEMFUNC_P (t))
13359 	return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
13360 
13361       /* Fall through.  */
13362     case ENUMERAL_TYPE:
13363     case UNION_TYPE:
13364       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
13365 	{
13366 	  tree argvec;
13367 	  tree context;
13368 	  tree r;
13369 
13370 	  /* In "sizeof(X<I>)" we need to evaluate "I".  */
13371 	  cp_evaluated ev;
13372 
13373 	  /* First, determine the context for the type we are looking
13374 	     up.  */
13375 	  context = TYPE_CONTEXT (t);
13376 	  if (context && TYPE_P (context))
13377 	    {
13378 	      context = tsubst_aggr_type (context, args, complain,
13379 					  in_decl, /*entering_scope=*/1);
13380 	      /* If context is a nested class inside a class template,
13381 	         it may still need to be instantiated (c++/33959).  */
13382 	      context = complete_type (context);
13383 	    }
13384 
13385 	  /* Then, figure out what arguments are appropriate for the
13386 	     type we are trying to find.  For example, given:
13387 
13388 	       template <class T> struct S;
13389 	       template <class T, class U> void f(T, U) { S<U> su; }
13390 
13391 	     and supposing that we are instantiating f<int, double>,
13392 	     then our ARGS will be {int, double}, but, when looking up
13393 	     S we only want {double}.  */
13394 	  argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
13395 					 complain, in_decl);
13396 	  if (argvec == error_mark_node)
13397 	    r = error_mark_node;
13398 	  else
13399 	    {
13400 	      r = lookup_template_class (t, argvec, in_decl, context,
13401 					 entering_scope, complain);
13402 	      r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
13403 	    }
13404 
13405 	  return r;
13406 	}
13407       else
13408 	/* This is not a template type, so there's nothing to do.  */
13409 	return t;
13410 
13411     default:
13412       return tsubst (t, args, complain, in_decl);
13413     }
13414 }
13415 
13416 static GTY((cache)) decl_tree_cache_map *defarg_inst;
13417 
13418 /* Substitute into the default argument ARG (a default argument for
13419    FN), which has the indicated TYPE.  */
13420 
13421 tree
tsubst_default_argument(tree fn,int parmnum,tree type,tree arg,tsubst_flags_t complain)13422 tsubst_default_argument (tree fn, int parmnum, tree type, tree arg,
13423 			 tsubst_flags_t complain)
13424 {
13425   int errs = errorcount + sorrycount;
13426 
13427   /* This can happen in invalid code.  */
13428   if (TREE_CODE (arg) == DEFERRED_PARSE)
13429     return arg;
13430 
13431   tree parm = FUNCTION_FIRST_USER_PARM (fn);
13432   parm = chain_index (parmnum, parm);
13433   tree parmtype = TREE_TYPE (parm);
13434   if (DECL_BY_REFERENCE (parm))
13435     parmtype = TREE_TYPE (parmtype);
13436   if (parmtype == error_mark_node)
13437     return error_mark_node;
13438 
13439   gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, parmtype));
13440 
13441   tree *slot;
13442   if (defarg_inst && (slot = defarg_inst->get (parm)))
13443     return *slot;
13444 
13445   /* This default argument came from a template.  Instantiate the
13446      default argument here, not in tsubst.  In the case of
13447      something like:
13448 
13449        template <class T>
13450        struct S {
13451 	 static T t();
13452 	 void f(T = t());
13453        };
13454 
13455      we must be careful to do name lookup in the scope of S<T>,
13456      rather than in the current class.  */
13457   push_to_top_level ();
13458   push_access_scope (fn);
13459   push_deferring_access_checks (dk_no_deferred);
13460   start_lambda_scope (parm);
13461 
13462   /* The default argument expression may cause implicitly defined
13463      member functions to be synthesized, which will result in garbage
13464      collection.  We must treat this situation as if we were within
13465      the body of function so as to avoid collecting live data on the
13466      stack.  */
13467   ++function_depth;
13468   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
13469 		     complain, NULL_TREE,
13470 		     /*integral_constant_expression_p=*/false);
13471   --function_depth;
13472 
13473   finish_lambda_scope ();
13474 
13475   /* Make sure the default argument is reasonable.  */
13476   arg = check_default_argument (type, arg, complain);
13477 
13478   if (errorcount+sorrycount > errs
13479       && (complain & tf_warning_or_error))
13480     inform (input_location,
13481 	    "  when instantiating default argument for call to %qD", fn);
13482 
13483   pop_deferring_access_checks ();
13484   pop_access_scope (fn);
13485   pop_from_top_level ();
13486 
13487   if (arg != error_mark_node && !cp_unevaluated_operand)
13488     {
13489       if (!defarg_inst)
13490 	defarg_inst = decl_tree_cache_map::create_ggc (37);
13491       defarg_inst->put (parm, arg);
13492     }
13493 
13494   return arg;
13495 }
13496 
13497 /* Substitute into all the default arguments for FN.  */
13498 
13499 static void
tsubst_default_arguments(tree fn,tsubst_flags_t complain)13500 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
13501 {
13502   tree arg;
13503   tree tmpl_args;
13504 
13505   tmpl_args = DECL_TI_ARGS (fn);
13506 
13507   /* If this function is not yet instantiated, we certainly don't need
13508      its default arguments.  */
13509   if (uses_template_parms (tmpl_args))
13510     return;
13511   /* Don't do this again for clones.  */
13512   if (DECL_CLONED_FUNCTION_P (fn))
13513     return;
13514 
13515   int i = 0;
13516   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
13517        arg;
13518        arg = TREE_CHAIN (arg), ++i)
13519     if (TREE_PURPOSE (arg))
13520       TREE_PURPOSE (arg) = tsubst_default_argument (fn, i,
13521 						    TREE_VALUE (arg),
13522 						    TREE_PURPOSE (arg),
13523 						    complain);
13524 }
13525 
13526 /* Hash table mapping a FUNCTION_DECL to its dependent explicit-specifier.  */
13527 static GTY((cache)) decl_tree_cache_map *explicit_specifier_map;
13528 
13529 /* Store a pair to EXPLICIT_SPECIFIER_MAP.  */
13530 
13531 void
store_explicit_specifier(tree v,tree t)13532 store_explicit_specifier (tree v, tree t)
13533 {
13534   if (!explicit_specifier_map)
13535     explicit_specifier_map = decl_tree_cache_map::create_ggc (37);
13536   DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (v) = true;
13537   explicit_specifier_map->put (v, t);
13538 }
13539 
13540 /* Lookup an element in EXPLICIT_SPECIFIER_MAP.  */
13541 
13542 static tree
lookup_explicit_specifier(tree v)13543 lookup_explicit_specifier (tree v)
13544 {
13545   return *explicit_specifier_map->get (v);
13546 }
13547 
13548 /* Given T, a FUNCTION_TYPE or METHOD_TYPE, construct and return a corresponding
13549    FUNCTION_TYPE or METHOD_TYPE whose return type is RETURN_TYPE, argument types
13550    are ARG_TYPES, and exception specification is RAISES, and otherwise is
13551    identical to T.  */
13552 
13553 static tree
rebuild_function_or_method_type(tree t,tree return_type,tree arg_types,tree raises,tsubst_flags_t complain)13554 rebuild_function_or_method_type (tree t, tree return_type, tree arg_types,
13555 				 tree raises, tsubst_flags_t complain)
13556 {
13557   gcc_assert (FUNC_OR_METHOD_TYPE_P (t));
13558 
13559   tree new_type;
13560   if (TREE_CODE (t) == FUNCTION_TYPE)
13561     {
13562       new_type = build_function_type (return_type, arg_types);
13563       new_type = apply_memfn_quals (new_type, type_memfn_quals (t));
13564     }
13565   else
13566     {
13567       tree r = TREE_TYPE (TREE_VALUE (arg_types));
13568       /* Don't pick up extra function qualifiers from the basetype.  */
13569       r = cp_build_qualified_type_real (r, type_memfn_quals (t), complain);
13570       if (! MAYBE_CLASS_TYPE_P (r))
13571 	{
13572 	  /* [temp.deduct]
13573 
13574 	     Type deduction may fail for any of the following
13575 	     reasons:
13576 
13577 	     -- Attempting to create "pointer to member of T" when T
13578 	     is not a class type.  */
13579 	  if (complain & tf_error)
13580 	    error ("creating pointer to member function of non-class type %qT",
13581 		   r);
13582 	  return error_mark_node;
13583 	}
13584 
13585       new_type = build_method_type_directly (r, return_type,
13586 					     TREE_CHAIN (arg_types));
13587     }
13588   new_type = cp_build_type_attribute_variant (new_type, TYPE_ATTRIBUTES (t));
13589 
13590   cp_ref_qualifier rqual = type_memfn_rqual (t);
13591   bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
13592   return build_cp_fntype_variant (new_type, rqual, raises, late_return_type_p);
13593 }
13594 
13595 /* Check if the function type of DECL, a FUNCTION_DECL, agrees with the type of
13596    each of its formal parameters.  If there is a disagreement then rebuild
13597    DECL's function type according to its formal parameter types, as part of a
13598    resolution for Core issues 1001/1322.  */
13599 
13600 static void
maybe_rebuild_function_decl_type(tree decl)13601 maybe_rebuild_function_decl_type (tree decl)
13602 {
13603   bool function_type_needs_rebuilding = false;
13604   if (tree parm_list = FUNCTION_FIRST_USER_PARM (decl))
13605     {
13606       tree parm_type_list = FUNCTION_FIRST_USER_PARMTYPE (decl);
13607       while (parm_type_list && parm_type_list != void_list_node)
13608 	{
13609 	  tree parm_type = TREE_VALUE (parm_type_list);
13610 	  tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
13611 	  if (!same_type_p (parm_type, formal_parm_type_unqual))
13612 	    {
13613 	      function_type_needs_rebuilding = true;
13614 	      break;
13615 	    }
13616 
13617 	  parm_list = DECL_CHAIN (parm_list);
13618 	  parm_type_list = TREE_CHAIN (parm_type_list);
13619 	}
13620     }
13621 
13622   if (!function_type_needs_rebuilding)
13623     return;
13624 
13625   const tree fntype = TREE_TYPE (decl);
13626   tree parm_list = DECL_ARGUMENTS (decl);
13627   tree old_parm_type_list = TYPE_ARG_TYPES (fntype);
13628   tree new_parm_type_list = NULL_TREE;
13629   tree *q = &new_parm_type_list;
13630   for (int skip = num_artificial_parms_for (decl); skip > 0; skip--)
13631     {
13632       *q = copy_node (old_parm_type_list);
13633       parm_list = DECL_CHAIN (parm_list);
13634       old_parm_type_list = TREE_CHAIN (old_parm_type_list);
13635       q = &TREE_CHAIN (*q);
13636     }
13637   while (old_parm_type_list && old_parm_type_list != void_list_node)
13638     {
13639       *q = copy_node (old_parm_type_list);
13640       tree *new_parm_type = &TREE_VALUE (*q);
13641       tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
13642       if (!same_type_p (*new_parm_type, formal_parm_type_unqual))
13643 	*new_parm_type = formal_parm_type_unqual;
13644 
13645       parm_list = DECL_CHAIN (parm_list);
13646       old_parm_type_list = TREE_CHAIN (old_parm_type_list);
13647       q = &TREE_CHAIN (*q);
13648     }
13649   if (old_parm_type_list == void_list_node)
13650     *q = void_list_node;
13651 
13652   TREE_TYPE (decl)
13653     = rebuild_function_or_method_type (fntype,
13654 				       TREE_TYPE (fntype), new_parm_type_list,
13655 				       TYPE_RAISES_EXCEPTIONS (fntype), tf_none);
13656 }
13657 
13658 /* Subroutine of tsubst_decl for the case when T is a FUNCTION_DECL.  */
13659 
13660 static tree
tsubst_function_decl(tree t,tree args,tsubst_flags_t complain,tree lambda_fntype)13661 tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
13662 		      tree lambda_fntype)
13663 {
13664   tree gen_tmpl, argvec;
13665   hashval_t hash = 0;
13666   tree in_decl = t;
13667 
13668   /* Nobody should be tsubst'ing into non-template functions.  */
13669   gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
13670 
13671   if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
13672     {
13673       /* If T is not dependent, just return it.  */
13674       if (!uses_template_parms (DECL_TI_ARGS (t))
13675 	  && !LAMBDA_FUNCTION_P (t))
13676 	return t;
13677 
13678       /* Calculate the most general template of which R is a
13679 	 specialization.  */
13680       gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
13681 
13682       /* We're substituting a lambda function under tsubst_lambda_expr but not
13683 	 directly from it; find the matching function we're already inside.
13684 	 But don't do this if T is a generic lambda with a single level of
13685 	 template parms, as in that case we're doing a normal instantiation. */
13686       if (LAMBDA_FUNCTION_P (t) && !lambda_fntype
13687 	  && (!generic_lambda_fn_p (t)
13688 	      || TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)) > 1))
13689 	return enclosing_instantiation_of (t);
13690 
13691       /* Calculate the complete set of arguments used to
13692 	 specialize R.  */
13693       argvec = tsubst_template_args (DECL_TI_ARGS
13694 				     (DECL_TEMPLATE_RESULT
13695 				      (DECL_TI_TEMPLATE (t))),
13696 				     args, complain, in_decl);
13697       if (argvec == error_mark_node)
13698 	return error_mark_node;
13699 
13700       /* Check to see if we already have this specialization.  */
13701       if (!lambda_fntype)
13702 	{
13703 	  hash = hash_tmpl_and_args (gen_tmpl, argvec);
13704 	  if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
13705 	    return spec;
13706 	}
13707 
13708       /* We can see more levels of arguments than parameters if
13709 	 there was a specialization of a member template, like
13710 	 this:
13711 
13712 	 template <class T> struct S { template <class U> void f(); }
13713 	 template <> template <class U> void S<int>::f(U);
13714 
13715 	 Here, we'll be substituting into the specialization,
13716 	 because that's where we can find the code we actually
13717 	 want to generate, but we'll have enough arguments for
13718 	 the most general template.
13719 
13720 	 We also deal with the peculiar case:
13721 
13722 	 template <class T> struct S {
13723 	   template <class U> friend void f();
13724 	 };
13725 	 template <class U> void f() {}
13726 	 template S<int>;
13727 	 template void f<double>();
13728 
13729 	 Here, the ARGS for the instantiation of will be {int,
13730 	 double}.  But, we only need as many ARGS as there are
13731 	 levels of template parameters in CODE_PATTERN.  We are
13732 	 careful not to get fooled into reducing the ARGS in
13733 	 situations like:
13734 
13735 	 template <class T> struct S { template <class U> void f(U); }
13736 	 template <class T> template <> void S<T>::f(int) {}
13737 
13738 	 which we can spot because the pattern will be a
13739 	 specialization in this case.  */
13740       int args_depth = TMPL_ARGS_DEPTH (args);
13741       int parms_depth =
13742 	TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
13743 
13744       if (args_depth > parms_depth && !DECL_TEMPLATE_SPECIALIZATION (t))
13745 	args = get_innermost_template_args (args, parms_depth);
13746     }
13747   else
13748     {
13749       /* This special case arises when we have something like this:
13750 
13751 	 template <class T> struct S {
13752 	 friend void f<int>(int, double);
13753 	 };
13754 
13755 	 Here, the DECL_TI_TEMPLATE for the friend declaration
13756 	 will be an IDENTIFIER_NODE.  We are being called from
13757 	 tsubst_friend_function, and we want only to create a
13758 	 new decl (R) with appropriate types so that we can call
13759 	 determine_specialization.  */
13760       gen_tmpl = NULL_TREE;
13761       argvec = NULL_TREE;
13762     }
13763 
13764   tree closure = (lambda_fntype ? TYPE_METHOD_BASETYPE (lambda_fntype)
13765 		  : NULL_TREE);
13766   tree ctx = closure ? closure : DECL_CONTEXT (t);
13767   bool member = ctx && TYPE_P (ctx);
13768 
13769   if (member && !closure)
13770     ctx = tsubst_aggr_type (ctx, args,
13771 			    complain, t, /*entering_scope=*/1);
13772 
13773   tree type = (lambda_fntype ? lambda_fntype
13774 	       : tsubst (TREE_TYPE (t), args,
13775 			 complain | tf_fndecl_type, in_decl));
13776   if (type == error_mark_node)
13777     return error_mark_node;
13778 
13779   /* If we hit excessive deduction depth, the type is bogus even if
13780      it isn't error_mark_node, so don't build a decl.  */
13781   if (excessive_deduction_depth)
13782     return error_mark_node;
13783 
13784   /* We do NOT check for matching decls pushed separately at this
13785      point, as they may not represent instantiations of this
13786      template, and in any case are considered separate under the
13787      discrete model.  */
13788   tree r = copy_decl (t);
13789   DECL_USE_TEMPLATE (r) = 0;
13790   TREE_TYPE (r) = type;
13791   /* Clear out the mangled name and RTL for the instantiation.  */
13792   SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
13793   SET_DECL_RTL (r, NULL);
13794   /* Leave DECL_INITIAL set on deleted instantiations.  */
13795   if (!DECL_DELETED_FN (r))
13796     DECL_INITIAL (r) = NULL_TREE;
13797   DECL_CONTEXT (r) = ctx;
13798 
13799   /* Handle explicit(dependent-expr).  */
13800   if (DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (t))
13801     {
13802       tree spec = lookup_explicit_specifier (t);
13803       spec = tsubst_copy_and_build (spec, args, complain, in_decl,
13804 				    /*function_p=*/false,
13805 				    /*i_c_e_p=*/true);
13806       spec = build_explicit_specifier (spec, complain);
13807       DECL_NONCONVERTING_P (r) = (spec == boolean_true_node);
13808     }
13809 
13810   /* OpenMP UDRs have the only argument a reference to the declared
13811      type.  We want to diagnose if the declared type is a reference,
13812      which is invalid, but as references to references are usually
13813      quietly merged, diagnose it here.  */
13814   if (DECL_OMP_DECLARE_REDUCTION_P (t))
13815     {
13816       tree argtype
13817 	= TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
13818       argtype = tsubst (argtype, args, complain, in_decl);
13819       if (TYPE_REF_P (argtype))
13820 	error_at (DECL_SOURCE_LOCATION (t),
13821 		  "reference type %qT in "
13822 		  "%<#pragma omp declare reduction%>", argtype);
13823       if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
13824 	DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
13825 					  argtype);
13826     }
13827 
13828   if (member && DECL_CONV_FN_P (r))
13829     /* Type-conversion operator.  Reconstruct the name, in
13830        case it's the name of one of the template's parameters.  */
13831     DECL_NAME (r) = make_conv_op_name (TREE_TYPE (type));
13832 
13833   tree parms = DECL_ARGUMENTS (t);
13834   if (closure)
13835     parms = DECL_CHAIN (parms);
13836   parms = tsubst (parms, args, complain, t);
13837   for (tree parm = parms; parm; parm = DECL_CHAIN (parm))
13838     DECL_CONTEXT (parm) = r;
13839   if (closure)
13840     {
13841       tree tparm = build_this_parm (r, closure, type_memfn_quals (type));
13842       DECL_CHAIN (tparm) = parms;
13843       parms = tparm;
13844     }
13845   DECL_ARGUMENTS (r) = parms;
13846   DECL_RESULT (r) = NULL_TREE;
13847 
13848   maybe_rebuild_function_decl_type (r);
13849 
13850   TREE_STATIC (r) = 0;
13851   TREE_PUBLIC (r) = TREE_PUBLIC (t);
13852   DECL_EXTERNAL (r) = 1;
13853   /* If this is an instantiation of a function with internal
13854      linkage, we already know what object file linkage will be
13855      assigned to the instantiation.  */
13856   DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
13857   DECL_DEFER_OUTPUT (r) = 0;
13858   DECL_CHAIN (r) = NULL_TREE;
13859   DECL_PENDING_INLINE_INFO (r) = 0;
13860   DECL_PENDING_INLINE_P (r) = 0;
13861   DECL_SAVED_TREE (r) = NULL_TREE;
13862   DECL_STRUCT_FUNCTION (r) = NULL;
13863   TREE_USED (r) = 0;
13864   /* We'll re-clone as appropriate in instantiate_template.  */
13865   DECL_CLONED_FUNCTION (r) = NULL_TREE;
13866 
13867   /* If we aren't complaining now, return on error before we register
13868      the specialization so that we'll complain eventually.  */
13869   if ((complain & tf_error) == 0
13870       && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
13871       && !grok_op_properties (r, /*complain=*/false))
13872     return error_mark_node;
13873 
13874   /* Associate the constraints directly with the instantiation. We
13875      don't substitute through the constraints; that's only done when
13876      they are checked.  */
13877   if (tree ci = get_constraints (t))
13878     /* Unless we're regenerating a lambda, in which case we'll set the
13879        lambda's constraints in tsubst_lambda_expr.  */
13880     if (!lambda_fntype)
13881       set_constraints (r, ci);
13882 
13883   if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
13884     SET_DECL_FRIEND_CONTEXT (r,
13885 			     tsubst (DECL_FRIEND_CONTEXT (t),
13886 				     args, complain, in_decl));
13887 
13888   /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
13889      this in the special friend case mentioned above where
13890      GEN_TMPL is NULL.  */
13891   if (gen_tmpl && !closure)
13892     {
13893       DECL_TEMPLATE_INFO (r)
13894 	= build_template_info (gen_tmpl, argvec);
13895       SET_DECL_IMPLICIT_INSTANTIATION (r);
13896 
13897       tree new_r
13898 	= register_specialization (r, gen_tmpl, argvec, false, hash);
13899       if (new_r != r)
13900 	/* We instantiated this while substituting into
13901 	   the type earlier (template/friend54.C).  */
13902 	return new_r;
13903 
13904       /* We're not supposed to instantiate default arguments
13905 	 until they are called, for a template.  But, for a
13906 	 declaration like:
13907 
13908 	 template <class T> void f ()
13909 	 { extern void g(int i = T()); }
13910 
13911 	 we should do the substitution when the template is
13912 	 instantiated.  We handle the member function case in
13913 	 instantiate_class_template since the default arguments
13914 	 might refer to other members of the class.  */
13915       if (!member
13916 	  && !PRIMARY_TEMPLATE_P (gen_tmpl)
13917 	  && !uses_template_parms (argvec))
13918 	tsubst_default_arguments (r, complain);
13919     }
13920   else
13921     DECL_TEMPLATE_INFO (r) = NULL_TREE;
13922 
13923   /* Copy the list of befriending classes.  */
13924   for (tree *friends = &DECL_BEFRIENDING_CLASSES (r);
13925        *friends;
13926        friends = &TREE_CHAIN (*friends))
13927     {
13928       *friends = copy_node (*friends);
13929       TREE_VALUE (*friends)
13930 	= tsubst (TREE_VALUE (*friends), args, complain, in_decl);
13931     }
13932 
13933   if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
13934     {
13935       maybe_retrofit_in_chrg (r);
13936       if (DECL_CONSTRUCTOR_P (r) && !grok_ctor_properties (ctx, r))
13937 	return error_mark_node;
13938       /* If this is an instantiation of a member template, clone it.
13939 	 If it isn't, that'll be handled by
13940 	 clone_constructors_and_destructors.  */
13941       if (PRIMARY_TEMPLATE_P (gen_tmpl))
13942 	clone_function_decl (r, /*update_methods=*/false);
13943     }
13944   else if ((complain & tf_error) != 0
13945 	   && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
13946 	   && !grok_op_properties (r, /*complain=*/true))
13947     return error_mark_node;
13948 
13949   /* Possibly limit visibility based on template args.  */
13950   DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
13951   if (DECL_VISIBILITY_SPECIFIED (t))
13952     {
13953       DECL_VISIBILITY_SPECIFIED (r) = 0;
13954       DECL_ATTRIBUTES (r)
13955 	= remove_attribute ("visibility", DECL_ATTRIBUTES (r));
13956     }
13957   determine_visibility (r);
13958   if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
13959       && !processing_template_decl)
13960     defaulted_late_check (r);
13961 
13962   apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
13963 				  args, complain, in_decl);
13964   if (flag_openmp)
13965     if (tree attr = lookup_attribute ("omp declare variant base",
13966 				      DECL_ATTRIBUTES (r)))
13967       omp_declare_variant_finalize (r, attr);
13968 
13969   return r;
13970 }
13971 
13972 /* Subroutine of tsubst_decl for the case when T is a TEMPLATE_DECL.  */
13973 
13974 static tree
tsubst_template_decl(tree t,tree args,tsubst_flags_t complain,tree lambda_fntype)13975 tsubst_template_decl (tree t, tree args, tsubst_flags_t complain,
13976 		      tree lambda_fntype)
13977 {
13978   /* We can get here when processing a member function template,
13979      member class template, or template template parameter.  */
13980   tree decl = DECL_TEMPLATE_RESULT (t);
13981   tree in_decl = t;
13982   tree spec;
13983   tree tmpl_args;
13984   tree full_args;
13985   tree r;
13986   hashval_t hash = 0;
13987 
13988   if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
13989     {
13990       /* Template template parameter is treated here.  */
13991       tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13992       if (new_type == error_mark_node)
13993 	r = error_mark_node;
13994       /* If we get a real template back, return it.  This can happen in
13995 	 the context of most_specialized_partial_spec.  */
13996       else if (TREE_CODE (new_type) == TEMPLATE_DECL)
13997 	r = new_type;
13998       else
13999 	/* The new TEMPLATE_DECL was built in
14000 	   reduce_template_parm_level.  */
14001 	r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
14002       return r;
14003     }
14004 
14005   if (!lambda_fntype)
14006     {
14007       /* We might already have an instance of this template.
14008 	 The ARGS are for the surrounding class type, so the
14009 	 full args contain the tsubst'd args for the context,
14010 	 plus the innermost args from the template decl.  */
14011       tmpl_args = DECL_CLASS_TEMPLATE_P (t)
14012 	? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
14013 	: DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
14014       /* Because this is a template, the arguments will still be
14015 	 dependent, even after substitution.  If
14016 	 PROCESSING_TEMPLATE_DECL is not set, the dependency
14017 	 predicates will short-circuit.  */
14018       ++processing_template_decl;
14019       full_args = tsubst_template_args (tmpl_args, args,
14020 					complain, in_decl);
14021       --processing_template_decl;
14022       if (full_args == error_mark_node)
14023 	return error_mark_node;
14024 
14025       /* If this is a default template template argument,
14026 	 tsubst might not have changed anything.  */
14027       if (full_args == tmpl_args)
14028 	return t;
14029 
14030       hash = hash_tmpl_and_args (t, full_args);
14031       spec = retrieve_specialization (t, full_args, hash);
14032       if (spec != NULL_TREE)
14033 	{
14034 	  if (TYPE_P (spec))
14035 	    /* Type partial instantiations are stored as the type by
14036 	       lookup_template_class_1, not here as the template.  */
14037 	    spec = CLASSTYPE_TI_TEMPLATE (spec);
14038 	  return spec;
14039 	}
14040     }
14041 
14042   /* Make a new template decl.  It will be similar to the
14043      original, but will record the current template arguments.
14044      We also create a new function declaration, which is just
14045      like the old one, but points to this new template, rather
14046      than the old one.  */
14047   r = copy_decl (t);
14048   gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
14049   DECL_CHAIN (r) = NULL_TREE;
14050 
14051   // Build new template info linking to the original template decl.
14052   if (!lambda_fntype)
14053     {
14054       DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
14055       SET_DECL_IMPLICIT_INSTANTIATION (r);
14056     }
14057   else
14058     DECL_TEMPLATE_INFO (r) = NULL_TREE;
14059 
14060   /* The template parameters for this new template are all the
14061      template parameters for the old template, except the
14062      outermost level of parameters.  */
14063   DECL_TEMPLATE_PARMS (r)
14064     = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
14065 			     complain);
14066 
14067   if (TREE_CODE (decl) == TYPE_DECL
14068       && !TYPE_DECL_ALIAS_P (decl))
14069     {
14070       tree new_type;
14071       ++processing_template_decl;
14072       new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14073       --processing_template_decl;
14074       if (new_type == error_mark_node)
14075 	return error_mark_node;
14076 
14077       TREE_TYPE (r) = new_type;
14078       /* For a partial specialization, we need to keep pointing to
14079 	 the primary template.  */
14080       if (!DECL_TEMPLATE_SPECIALIZATION (t))
14081 	CLASSTYPE_TI_TEMPLATE (new_type) = r;
14082       DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
14083       DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
14084       DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
14085     }
14086   else
14087     {
14088       tree new_decl;
14089       ++processing_template_decl;
14090       if (TREE_CODE (decl) == FUNCTION_DECL)
14091 	new_decl = tsubst_function_decl (decl, args, complain, lambda_fntype);
14092       else
14093 	new_decl = tsubst (decl, args, complain, in_decl);
14094       --processing_template_decl;
14095       if (new_decl == error_mark_node)
14096 	return error_mark_node;
14097 
14098       DECL_TEMPLATE_RESULT (r) = new_decl;
14099       TREE_TYPE (r) = TREE_TYPE (new_decl);
14100       DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
14101       if (lambda_fntype)
14102 	{
14103 	  tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (r));
14104 	  DECL_TEMPLATE_INFO (new_decl) = build_template_info (r, args);
14105 	}
14106       else
14107 	{
14108 	  DECL_TI_TEMPLATE (new_decl) = r;
14109 	  DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
14110 	}
14111     }
14112 
14113   DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
14114   DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
14115 
14116   if (PRIMARY_TEMPLATE_P (t))
14117     DECL_PRIMARY_TEMPLATE (r) = r;
14118 
14119   if (TREE_CODE (decl) != TYPE_DECL && !VAR_P (decl)
14120       && !lambda_fntype)
14121     /* Record this non-type partial instantiation.  */
14122     register_specialization (r, t,
14123 			     DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
14124 			     false, hash);
14125 
14126   return r;
14127 }
14128 
14129 /* True if FN is the op() for a lambda in an uninstantiated template.  */
14130 
14131 bool
lambda_fn_in_template_p(tree fn)14132 lambda_fn_in_template_p (tree fn)
14133 {
14134   if (!fn || !LAMBDA_FUNCTION_P (fn))
14135     return false;
14136   tree closure = DECL_CONTEXT (fn);
14137   return CLASSTYPE_TEMPLATE_INFO (closure) != NULL_TREE;
14138 }
14139 
14140 /* True if FN is the substitution (via tsubst_lambda_expr) of a function for
14141    which the above is true.  */
14142 
14143 bool
instantiated_lambda_fn_p(tree fn)14144 instantiated_lambda_fn_p (tree fn)
14145 {
14146   if (!fn || !LAMBDA_FUNCTION_P (fn))
14147     return false;
14148   tree closure = DECL_CONTEXT (fn);
14149   tree lam = CLASSTYPE_LAMBDA_EXPR (closure);
14150   return LAMBDA_EXPR_INSTANTIATED (lam);
14151 }
14152 
14153 /* We're instantiating a variable from template function TCTX.  Return the
14154    corresponding current enclosing scope.  This gets complicated because lambda
14155    functions in templates are regenerated rather than instantiated, but generic
14156    lambda functions are subsequently instantiated.  */
14157 
14158 static tree
enclosing_instantiation_of(tree otctx)14159 enclosing_instantiation_of (tree otctx)
14160 {
14161   tree tctx = otctx;
14162   tree fn = current_function_decl;
14163   int lambda_count = 0;
14164 
14165   for (; tctx && (lambda_fn_in_template_p (tctx)
14166 		  || instantiated_lambda_fn_p (tctx));
14167        tctx = decl_function_context (tctx))
14168     ++lambda_count;
14169   for (; fn; fn = decl_function_context (fn))
14170     {
14171       tree ofn = fn;
14172       int flambda_count = 0;
14173       for (; fn && instantiated_lambda_fn_p (fn);
14174 	   fn = decl_function_context (fn))
14175 	++flambda_count;
14176       if ((fn && DECL_TEMPLATE_INFO (fn))
14177 	  ? most_general_template (fn) != most_general_template (tctx)
14178 	  : fn != tctx)
14179 	continue;
14180       if (flambda_count != lambda_count)
14181 	{
14182 	  gcc_assert (flambda_count > lambda_count);
14183 	  for (; flambda_count > lambda_count; --flambda_count)
14184 	    ofn = decl_function_context (ofn);
14185 	}
14186       gcc_assert (DECL_NAME (ofn) == DECL_NAME (otctx)
14187 		  || DECL_CONV_FN_P (ofn));
14188       return ofn;
14189     }
14190   gcc_unreachable ();
14191 }
14192 
14193 /* Substitute the ARGS into the T, which is a _DECL.  Return the
14194    result of the substitution.  Issue error and warning messages under
14195    control of COMPLAIN.  */
14196 
14197 static tree
tsubst_decl(tree t,tree args,tsubst_flags_t complain)14198 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
14199 {
14200 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
14201   location_t saved_loc;
14202   tree r = NULL_TREE;
14203   tree in_decl = t;
14204   hashval_t hash = 0;
14205 
14206   /* Set the filename and linenumber to improve error-reporting.  */
14207   saved_loc = input_location;
14208   input_location = DECL_SOURCE_LOCATION (t);
14209 
14210   switch (TREE_CODE (t))
14211     {
14212     case TEMPLATE_DECL:
14213       r = tsubst_template_decl (t, args, complain, /*lambda*/NULL_TREE);
14214       break;
14215 
14216     case FUNCTION_DECL:
14217       r = tsubst_function_decl (t, args, complain, /*lambda*/NULL_TREE);
14218       break;
14219 
14220     case PARM_DECL:
14221       {
14222 	tree type = NULL_TREE;
14223         int i, len = 1;
14224         tree expanded_types = NULL_TREE;
14225         tree prev_r = NULL_TREE;
14226         tree first_r = NULL_TREE;
14227 
14228         if (DECL_PACK_P (t))
14229           {
14230             /* If there is a local specialization that isn't a
14231                parameter pack, it means that we're doing a "simple"
14232                substitution from inside tsubst_pack_expansion. Just
14233                return the local specialization (which will be a single
14234                parm).  */
14235             tree spec = retrieve_local_specialization (t);
14236             if (spec
14237                 && TREE_CODE (spec) == PARM_DECL
14238                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
14239               RETURN (spec);
14240 
14241             /* Expand the TYPE_PACK_EXPANSION that provides the types for
14242                the parameters in this function parameter pack.  */
14243             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
14244 						    complain, in_decl);
14245             if (TREE_CODE (expanded_types) == TREE_VEC)
14246               {
14247                 len = TREE_VEC_LENGTH (expanded_types);
14248 
14249                 /* Zero-length parameter packs are boring. Just substitute
14250                    into the chain.  */
14251 		if (len == 0 && !cp_unevaluated_operand)
14252                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
14253 				  TREE_CHAIN (t)));
14254               }
14255             else
14256               {
14257                 /* All we did was update the type. Make a note of that.  */
14258                 type = expanded_types;
14259                 expanded_types = NULL_TREE;
14260               }
14261           }
14262 
14263         /* Loop through all of the parameters we'll build. When T is
14264            a function parameter pack, LEN is the number of expanded
14265            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
14266         r = NULL_TREE;
14267         for (i = 0; i < len; ++i)
14268           {
14269             prev_r = r;
14270             r = copy_node (t);
14271             if (DECL_TEMPLATE_PARM_P (t))
14272               SET_DECL_TEMPLATE_PARM_P (r);
14273 
14274             if (expanded_types)
14275               /* We're on the Ith parameter of the function parameter
14276                  pack.  */
14277               {
14278                 /* Get the Ith type.  */
14279                 type = TREE_VEC_ELT (expanded_types, i);
14280 
14281 		/* Rename the parameter to include the index.  */
14282 		DECL_NAME (r)
14283 		  = make_ith_pack_parameter_name (DECL_NAME (r), i);
14284               }
14285             else if (!type)
14286               /* We're dealing with a normal parameter.  */
14287               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14288 
14289             type = type_decays_to (type);
14290             TREE_TYPE (r) = type;
14291             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14292 
14293             if (DECL_INITIAL (r))
14294               {
14295                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
14296                   DECL_INITIAL (r) = TREE_TYPE (r);
14297                 else
14298                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
14299                                              complain, in_decl);
14300               }
14301 
14302             DECL_CONTEXT (r) = NULL_TREE;
14303 
14304             if (!DECL_TEMPLATE_PARM_P (r))
14305               DECL_ARG_TYPE (r) = type_passed_as (type);
14306 
14307 	    apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14308 					    args, complain, in_decl);
14309 
14310             /* Keep track of the first new parameter we
14311                generate. That's what will be returned to the
14312                caller.  */
14313             if (!first_r)
14314               first_r = r;
14315 
14316             /* Build a proper chain of parameters when substituting
14317                into a function parameter pack.  */
14318             if (prev_r)
14319               DECL_CHAIN (prev_r) = r;
14320           }
14321 
14322 	/* If cp_unevaluated_operand is set, we're just looking for a
14323 	   single dummy parameter, so don't keep going.  */
14324 	if (DECL_CHAIN (t) && !cp_unevaluated_operand)
14325 	  DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
14326 				   complain, DECL_CHAIN (t));
14327 
14328         /* FIRST_R contains the start of the chain we've built.  */
14329         r = first_r;
14330       }
14331       break;
14332 
14333     case FIELD_DECL:
14334       {
14335 	tree type = NULL_TREE;
14336 	tree vec = NULL_TREE;
14337 	tree expanded_types = NULL_TREE;
14338 	int len = 1;
14339 
14340 	if (PACK_EXPANSION_P (TREE_TYPE (t)))
14341 	  {
14342 	    /* This field is a lambda capture pack.  Return a TREE_VEC of
14343 	       the expanded fields to instantiate_class_template_1.  */
14344             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
14345 						    complain, in_decl);
14346             if (TREE_CODE (expanded_types) == TREE_VEC)
14347               {
14348                 len = TREE_VEC_LENGTH (expanded_types);
14349 		vec = make_tree_vec (len);
14350               }
14351             else
14352               {
14353                 /* All we did was update the type. Make a note of that.  */
14354                 type = expanded_types;
14355                 expanded_types = NULL_TREE;
14356               }
14357 	  }
14358 
14359 	for (int i = 0; i < len; ++i)
14360 	  {
14361 	    r = copy_decl (t);
14362 	    if (expanded_types)
14363 	      {
14364 		type = TREE_VEC_ELT (expanded_types, i);
14365 		DECL_NAME (r)
14366 		  = make_ith_pack_parameter_name (DECL_NAME (r), i);
14367 	      }
14368             else if (!type)
14369               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14370 
14371 	    if (type == error_mark_node)
14372 	      RETURN (error_mark_node);
14373 	    TREE_TYPE (r) = type;
14374 	    cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14375 
14376 	    if (DECL_C_BIT_FIELD (r))
14377 	      /* For bit-fields, DECL_BIT_FIELD_REPRESENTATIVE gives the
14378 		 number of bits.  */
14379 	      DECL_BIT_FIELD_REPRESENTATIVE (r)
14380 		= tsubst_expr (DECL_BIT_FIELD_REPRESENTATIVE (t), args,
14381 			       complain, in_decl,
14382 			       /*integral_constant_expression_p=*/true);
14383 	    if (DECL_INITIAL (t))
14384 	      {
14385 		/* Set up DECL_TEMPLATE_INFO so that we can get at the
14386 		   NSDMI in perform_member_init.  Still set DECL_INITIAL
14387 		   so that we know there is one.  */
14388 		DECL_INITIAL (r) = void_node;
14389 		gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
14390 		retrofit_lang_decl (r);
14391 		DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
14392 	      }
14393 	    /* We don't have to set DECL_CONTEXT here; it is set by
14394 	       finish_member_declaration.  */
14395 	    DECL_CHAIN (r) = NULL_TREE;
14396 
14397 	    apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14398 					    args, complain, in_decl);
14399 
14400 	    if (vec)
14401 	      TREE_VEC_ELT (vec, i) = r;
14402 	  }
14403 
14404 	if (vec)
14405 	  r = vec;
14406       }
14407       break;
14408 
14409     case USING_DECL:
14410       /* We reach here only for member using decls.  We also need to check
14411 	 uses_template_parms because DECL_DEPENDENT_P is not set for a
14412 	 using-declaration that designates a member of the current
14413 	 instantiation (c++/53549).  */
14414       if (DECL_DEPENDENT_P (t)
14415 	  || uses_template_parms (USING_DECL_SCOPE (t)))
14416 	{
14417 	  tree scope = USING_DECL_SCOPE (t);
14418 	  tree name = tsubst_copy (DECL_NAME (t), args, complain, in_decl);
14419 	  if (PACK_EXPANSION_P (scope))
14420 	    {
14421 	      tree vec = tsubst_pack_expansion (scope, args, complain, in_decl);
14422 	      int len = TREE_VEC_LENGTH (vec);
14423 	      r = make_tree_vec (len);
14424 	      for (int i = 0; i < len; ++i)
14425 		{
14426 		  tree escope = TREE_VEC_ELT (vec, i);
14427 		  tree elt = do_class_using_decl (escope, name);
14428 		  if (!elt)
14429 		    {
14430 		      r = error_mark_node;
14431 		      break;
14432 		    }
14433 		  else
14434 		    {
14435 		      TREE_PROTECTED (elt) = TREE_PROTECTED (t);
14436 		      TREE_PRIVATE (elt) = TREE_PRIVATE (t);
14437 		    }
14438 		  TREE_VEC_ELT (r, i) = elt;
14439 		}
14440 	    }
14441 	  else
14442 	    {
14443 	      tree inst_scope = tsubst_copy (USING_DECL_SCOPE (t), args,
14444 					     complain, in_decl);
14445 	      r = do_class_using_decl (inst_scope, name);
14446 	      if (!r)
14447 		r = error_mark_node;
14448 	      else
14449 		{
14450 		  TREE_PROTECTED (r) = TREE_PROTECTED (t);
14451 		  TREE_PRIVATE (r) = TREE_PRIVATE (t);
14452 		}
14453 	    }
14454 	}
14455       else
14456 	{
14457 	  r = copy_node (t);
14458 	  DECL_CHAIN (r) = NULL_TREE;
14459 	}
14460       break;
14461 
14462     case TYPE_DECL:
14463     case VAR_DECL:
14464       {
14465 	tree argvec = NULL_TREE;
14466 	tree gen_tmpl = NULL_TREE;
14467 	tree spec;
14468 	tree tmpl = NULL_TREE;
14469 	tree ctx;
14470 	tree type = NULL_TREE;
14471 	bool local_p;
14472 
14473 	if (TREE_TYPE (t) == error_mark_node)
14474 	  RETURN (error_mark_node);
14475 
14476 	if (TREE_CODE (t) == TYPE_DECL
14477 	    && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
14478 	  {
14479 	    /* If this is the canonical decl, we don't have to
14480 	       mess with instantiations, and often we can't (for
14481 	       typename, template type parms and such).  Note that
14482 	       TYPE_NAME is not correct for the above test if
14483 	       we've copied the type for a typedef.  */
14484 	    type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14485 	    if (type == error_mark_node)
14486 	      RETURN (error_mark_node);
14487 	    r = TYPE_NAME (type);
14488 	    break;
14489 	  }
14490 
14491 	/* Check to see if we already have the specialization we
14492 	   need.  */
14493 	spec = NULL_TREE;
14494 	if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
14495 	  {
14496 	    /* T is a static data member or namespace-scope entity.
14497 	       We have to substitute into namespace-scope variables
14498 	       (not just variable templates) because of cases like:
14499 
14500 	         template <class T> void f() { extern T t; }
14501 
14502 	       where the entity referenced is not known until
14503 	       instantiation time.  */
14504 	    local_p = false;
14505 	    ctx = DECL_CONTEXT (t);
14506 	    if (DECL_CLASS_SCOPE_P (t))
14507 	      {
14508 		ctx = tsubst_aggr_type (ctx, args,
14509 					complain,
14510 					in_decl, /*entering_scope=*/1);
14511 		/* If CTX is unchanged, then T is in fact the
14512 		   specialization we want.  That situation occurs when
14513 		   referencing a static data member within in its own
14514 		   class.  We can use pointer equality, rather than
14515 		   same_type_p, because DECL_CONTEXT is always
14516 		   canonical...  */
14517 		if (ctx == DECL_CONTEXT (t)
14518 		    /* ... unless T is a member template; in which
14519 		       case our caller can be willing to create a
14520 		       specialization of that template represented
14521 		       by T.  */
14522 		    && !(DECL_TI_TEMPLATE (t)
14523 			 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
14524 		  spec = t;
14525 	      }
14526 
14527 	    if (!spec)
14528 	      {
14529 		tmpl = DECL_TI_TEMPLATE (t);
14530 		gen_tmpl = most_general_template (tmpl);
14531 		argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
14532 		if (argvec != error_mark_node)
14533 		  argvec = (coerce_innermost_template_parms
14534 			    (DECL_TEMPLATE_PARMS (gen_tmpl),
14535 			     argvec, t, complain,
14536 			     /*all*/true, /*defarg*/true));
14537 		if (argvec == error_mark_node)
14538 		  RETURN (error_mark_node);
14539 		hash = hash_tmpl_and_args (gen_tmpl, argvec);
14540 		spec = retrieve_specialization (gen_tmpl, argvec, hash);
14541 	      }
14542 	  }
14543 	else
14544 	  {
14545 	    /* A local variable.  */
14546 	    local_p = true;
14547 	    /* Subsequent calls to pushdecl will fill this in.  */
14548 	    ctx = NULL_TREE;
14549 	    /* Unless this is a reference to a static variable from an
14550 	       enclosing function, in which case we need to fill it in now.  */
14551 	    if (TREE_STATIC (t))
14552 	      {
14553 		tree fn = enclosing_instantiation_of (DECL_CONTEXT (t));
14554 		if (fn != current_function_decl)
14555 		  ctx = fn;
14556 	      }
14557 	    spec = retrieve_local_specialization (t);
14558 	  }
14559 	/* If we already have the specialization we need, there is
14560 	   nothing more to do.  */
14561 	if (spec)
14562 	  {
14563 	    r = spec;
14564 	    break;
14565 	  }
14566 
14567 	/* Create a new node for the specialization we need.  */
14568 	if (type == NULL_TREE)
14569 	  {
14570 	    if (is_typedef_decl (t))
14571 	      type = DECL_ORIGINAL_TYPE (t);
14572 	    else
14573 	      type = TREE_TYPE (t);
14574 	    if (VAR_P (t)
14575 		&& VAR_HAD_UNKNOWN_BOUND (t)
14576 		&& type != error_mark_node)
14577 	      type = strip_array_domain (type);
14578 	    tree sub_args = args;
14579 	    if (tree auto_node = type_uses_auto (type))
14580 	      {
14581 		/* Mask off any template args past the variable's context so we
14582 		   don't replace the auto with an unrelated argument.  */
14583 		int nouter = TEMPLATE_TYPE_LEVEL (auto_node) - 1;
14584 		int extra = TMPL_ARGS_DEPTH (args) - nouter;
14585 		if (extra > 0)
14586 		  /* This should never happen with the new lambda instantiation
14587 		     model, but keep the handling just in case.  */
14588 		  gcc_assert (!CHECKING_P),
14589 		  sub_args = strip_innermost_template_args (args, extra);
14590 	      }
14591 	    type = tsubst (type, sub_args, complain, in_decl);
14592 	    /* Substituting the type might have recursively instantiated this
14593 	       same alias (c++/86171).  */
14594 	    if (gen_tmpl && DECL_ALIAS_TEMPLATE_P (gen_tmpl)
14595 		&& (spec = retrieve_specialization (gen_tmpl, argvec, hash)))
14596 	      {
14597 		r = spec;
14598 		break;
14599 	      }
14600 	  }
14601 	r = copy_decl (t);
14602 	if (VAR_P (r))
14603 	  {
14604 	    DECL_INITIALIZED_P (r) = 0;
14605 	    DECL_TEMPLATE_INSTANTIATED (r) = 0;
14606 	    if (type == error_mark_node)
14607 	      RETURN (error_mark_node);
14608 	    if (TREE_CODE (type) == FUNCTION_TYPE)
14609 	      {
14610 		/* It may seem that this case cannot occur, since:
14611 
14612 		   typedef void f();
14613 		   void g() { f x; }
14614 
14615 		   declares a function, not a variable.  However:
14616 
14617 		   typedef void f();
14618 		   template <typename T> void g() { T t; }
14619 		   template void g<f>();
14620 
14621 		   is an attempt to declare a variable with function
14622 		   type.  */
14623 		error ("variable %qD has function type",
14624 		       /* R is not yet sufficiently initialized, so we
14625 			  just use its name.  */
14626 		       DECL_NAME (r));
14627 		RETURN (error_mark_node);
14628 	      }
14629 	    type = complete_type (type);
14630 	    /* Wait until cp_finish_decl to set this again, to handle
14631 	       circular dependency (template/instantiate6.C). */
14632 	    DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
14633 	    type = check_var_type (DECL_NAME (r), type,
14634 				   DECL_SOURCE_LOCATION (r));
14635 	    if (DECL_HAS_VALUE_EXPR_P (t))
14636 	      {
14637 		tree ve = DECL_VALUE_EXPR (t);
14638 		/* If the DECL_VALUE_EXPR is converted to the declared type,
14639 		   preserve the identity so that gimplify_type_sizes works.  */
14640 		bool nop = (TREE_CODE (ve) == NOP_EXPR);
14641 		if (nop)
14642 		  ve = TREE_OPERAND (ve, 0);
14643 		ve = tsubst_expr (ve, args, complain, in_decl,
14644 				  /*constant_expression_p=*/false);
14645 		if (REFERENCE_REF_P (ve))
14646 		  {
14647 		    gcc_assert (TYPE_REF_P (type));
14648 		    ve = TREE_OPERAND (ve, 0);
14649 		  }
14650 		if (nop)
14651 		  ve = build_nop (type, ve);
14652 		else
14653 		  gcc_checking_assert (TREE_TYPE (ve) == type);
14654 		SET_DECL_VALUE_EXPR (r, ve);
14655 	      }
14656 	    if (CP_DECL_THREAD_LOCAL_P (r)
14657 		&& !processing_template_decl)
14658 	      set_decl_tls_model (r, decl_default_tls_model (r));
14659 	  }
14660 	else if (DECL_SELF_REFERENCE_P (t))
14661 	  SET_DECL_SELF_REFERENCE_P (r);
14662 	TREE_TYPE (r) = type;
14663 	cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14664 	DECL_CONTEXT (r) = ctx;
14665 	/* Clear out the mangled name and RTL for the instantiation.  */
14666 	SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
14667 	if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
14668 	  SET_DECL_RTL (r, NULL);
14669 	/* The initializer must not be expanded until it is required;
14670 	   see [temp.inst].  */
14671 	DECL_INITIAL (r) = NULL_TREE;
14672 	DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
14673 	if (VAR_P (r))
14674 	  {
14675 	    if (DECL_LANG_SPECIFIC (r))
14676 	      SET_DECL_DEPENDENT_INIT_P (r, false);
14677 
14678 	    SET_DECL_MODE (r, VOIDmode);
14679 
14680 	    /* Possibly limit visibility based on template args.  */
14681 	    DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
14682 	    if (DECL_VISIBILITY_SPECIFIED (t))
14683 	      {
14684 		DECL_VISIBILITY_SPECIFIED (r) = 0;
14685 		DECL_ATTRIBUTES (r)
14686 		  = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
14687 	      }
14688 	    determine_visibility (r);
14689 	  }
14690 
14691 	if (!local_p)
14692 	  {
14693 	    /* A static data member declaration is always marked
14694 	       external when it is declared in-class, even if an
14695 	       initializer is present.  We mimic the non-template
14696 	       processing here.  */
14697 	    DECL_EXTERNAL (r) = 1;
14698 	    if (DECL_NAMESPACE_SCOPE_P (t))
14699 	      DECL_NOT_REALLY_EXTERN (r) = 1;
14700 
14701 	    DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
14702 	    SET_DECL_IMPLICIT_INSTANTIATION (r);
14703 	    /* Remember whether we require constant initialization of
14704 	       a non-constant template variable.  */
14705 	    TINFO_VAR_DECLARED_CONSTINIT (DECL_TEMPLATE_INFO (r))
14706 	      = TINFO_VAR_DECLARED_CONSTINIT (DECL_TEMPLATE_INFO (t));
14707 	    if (!error_operand_p (r) || (complain & tf_error))
14708 	      register_specialization (r, gen_tmpl, argvec, false, hash);
14709 	  }
14710 	else
14711 	  {
14712 	    if (DECL_LANG_SPECIFIC (r))
14713 	      DECL_TEMPLATE_INFO (r) = NULL_TREE;
14714 	    if (!cp_unevaluated_operand)
14715 	      register_local_specialization (r, t);
14716 	  }
14717 
14718 	DECL_CHAIN (r) = NULL_TREE;
14719 
14720 	apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
14721 					/*flags=*/0,
14722 					args, complain, in_decl);
14723 
14724 	/* Preserve a typedef that names a type.  */
14725 	if (is_typedef_decl (r) && type != error_mark_node)
14726 	  {
14727 	    DECL_ORIGINAL_TYPE (r) = NULL_TREE;
14728 	    set_underlying_type (r);
14729 	    if (TYPE_DECL_ALIAS_P (r))
14730 	      /* An alias template specialization can be dependent
14731 		 even if its underlying type is not.  */
14732 	      TYPE_DEPENDENT_P_VALID (TREE_TYPE (r)) = false;
14733 	  }
14734 
14735 	layout_decl (r, 0);
14736       }
14737       break;
14738 
14739     default:
14740       gcc_unreachable ();
14741     }
14742 #undef RETURN
14743 
14744  out:
14745   /* Restore the file and line information.  */
14746   input_location = saved_loc;
14747 
14748   return r;
14749 }
14750 
14751 /* Substitute into the complete parameter type list PARMS.  */
14752 
14753 tree
tsubst_function_parms(tree parms,tree args,tsubst_flags_t complain,tree in_decl)14754 tsubst_function_parms (tree parms,
14755 		       tree args,
14756 		       tsubst_flags_t complain,
14757 		       tree in_decl)
14758 {
14759   return tsubst_arg_types (parms, args, NULL_TREE, complain, in_decl);
14760 }
14761 
14762 /* Substitute into the ARG_TYPES of a function type.
14763    If END is a TREE_CHAIN, leave it and any following types
14764    un-substituted.  */
14765 
14766 static tree
tsubst_arg_types(tree arg_types,tree args,tree end,tsubst_flags_t complain,tree in_decl)14767 tsubst_arg_types (tree arg_types,
14768 		  tree args,
14769 		  tree end,
14770 		  tsubst_flags_t complain,
14771 		  tree in_decl)
14772 {
14773   tree remaining_arg_types;
14774   tree type = NULL_TREE;
14775   int i = 1;
14776   tree expanded_args = NULL_TREE;
14777   tree default_arg;
14778 
14779   if (!arg_types || arg_types == void_list_node || arg_types == end)
14780     return arg_types;
14781 
14782   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
14783 					  args, end, complain, in_decl);
14784   if (remaining_arg_types == error_mark_node)
14785     return error_mark_node;
14786 
14787   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
14788     {
14789       /* For a pack expansion, perform substitution on the
14790          entire expression. Later on, we'll handle the arguments
14791          one-by-one.  */
14792       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
14793                                             args, complain, in_decl);
14794 
14795       if (TREE_CODE (expanded_args) == TREE_VEC)
14796         /* So that we'll spin through the parameters, one by one.  */
14797         i = TREE_VEC_LENGTH (expanded_args);
14798       else
14799         {
14800           /* We only partially substituted into the parameter
14801              pack. Our type is TYPE_PACK_EXPANSION.  */
14802           type = expanded_args;
14803           expanded_args = NULL_TREE;
14804         }
14805     }
14806 
14807   while (i > 0) {
14808     --i;
14809 
14810     if (expanded_args)
14811       type = TREE_VEC_ELT (expanded_args, i);
14812     else if (!type)
14813       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
14814 
14815     if (type == error_mark_node)
14816       return error_mark_node;
14817     if (VOID_TYPE_P (type))
14818       {
14819         if (complain & tf_error)
14820           {
14821             error ("invalid parameter type %qT", type);
14822             if (in_decl)
14823               error ("in declaration %q+D", in_decl);
14824           }
14825         return error_mark_node;
14826     }
14827     /* DR 657. */
14828     if (abstract_virtuals_error_sfinae (ACU_PARM, type, complain))
14829       return error_mark_node;
14830 
14831     /* Do array-to-pointer, function-to-pointer conversion, and ignore
14832        top-level qualifiers as required.  */
14833     type = cv_unqualified (type_decays_to (type));
14834 
14835     /* We do not substitute into default arguments here.  The standard
14836        mandates that they be instantiated only when needed, which is
14837        done in build_over_call.  */
14838     default_arg = TREE_PURPOSE (arg_types);
14839 
14840     /* Except that we do substitute default arguments under tsubst_lambda_expr,
14841        since the new op() won't have any associated template arguments for us
14842        to refer to later.  */
14843     if (lambda_fn_in_template_p (in_decl))
14844       default_arg = tsubst_copy_and_build (default_arg, args, complain, in_decl,
14845 					   false/*fn*/, false/*constexpr*/);
14846 
14847     if (default_arg && TREE_CODE (default_arg) == DEFERRED_PARSE)
14848       {
14849         /* We've instantiated a template before its default arguments
14850            have been parsed.  This can happen for a nested template
14851            class, and is not an error unless we require the default
14852            argument in a call of this function.  */
14853         remaining_arg_types =
14854           tree_cons (default_arg, type, remaining_arg_types);
14855 	vec_safe_push (DEFPARSE_INSTANTIATIONS (default_arg),
14856 		       remaining_arg_types);
14857       }
14858     else
14859       remaining_arg_types =
14860         hash_tree_cons (default_arg, type, remaining_arg_types);
14861   }
14862 
14863   return remaining_arg_types;
14864 }
14865 
14866 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
14867    *not* handle the exception-specification for FNTYPE, because the
14868    initial substitution of explicitly provided template parameters
14869    during argument deduction forbids substitution into the
14870    exception-specification:
14871 
14872      [temp.deduct]
14873 
14874      All references in the function type of the function template to  the
14875      corresponding template parameters are replaced by the specified tem-
14876      plate argument values.  If a substitution in a template parameter or
14877      in  the function type of the function template results in an invalid
14878      type, type deduction fails.  [Note: The equivalent  substitution  in
14879      exception specifications is done only when the function is instanti-
14880      ated, at which point a program is  ill-formed  if  the  substitution
14881      results in an invalid type.]  */
14882 
14883 static tree
tsubst_function_type(tree t,tree args,tsubst_flags_t complain,tree in_decl)14884 tsubst_function_type (tree t,
14885 		      tree args,
14886 		      tsubst_flags_t complain,
14887 		      tree in_decl)
14888 {
14889   tree return_type;
14890   tree arg_types = NULL_TREE;
14891 
14892   /* The TYPE_CONTEXT is not used for function/method types.  */
14893   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
14894 
14895   /* DR 1227: Mixing immediate and non-immediate contexts in deduction
14896      failure.  */
14897   bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
14898 
14899   if (late_return_type_p)
14900     {
14901       /* Substitute the argument types.  */
14902       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
14903 				    complain, in_decl);
14904       if (arg_types == error_mark_node)
14905 	return error_mark_node;
14906 
14907       tree save_ccp = current_class_ptr;
14908       tree save_ccr = current_class_ref;
14909       tree this_type = (TREE_CODE (t) == METHOD_TYPE
14910 			? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
14911       bool do_inject = this_type && CLASS_TYPE_P (this_type);
14912       if (do_inject)
14913 	{
14914 	  /* DR 1207: 'this' is in scope in the trailing return type.  */
14915 	  inject_this_parameter (this_type, cp_type_quals (this_type));
14916 	}
14917 
14918       /* Substitute the return type.  */
14919       return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14920 
14921       if (do_inject)
14922 	{
14923 	  current_class_ptr = save_ccp;
14924 	  current_class_ref = save_ccr;
14925 	}
14926     }
14927   else
14928     /* Substitute the return type.  */
14929     return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14930 
14931   if (return_type == error_mark_node)
14932     return error_mark_node;
14933   /* DR 486 clarifies that creation of a function type with an
14934      invalid return type is a deduction failure.  */
14935   if (TREE_CODE (return_type) == ARRAY_TYPE
14936       || TREE_CODE (return_type) == FUNCTION_TYPE)
14937     {
14938       if (complain & tf_error)
14939 	{
14940 	  if (TREE_CODE (return_type) == ARRAY_TYPE)
14941 	    error ("function returning an array");
14942 	  else
14943 	    error ("function returning a function");
14944 	}
14945       return error_mark_node;
14946     }
14947   /* And DR 657. */
14948   if (abstract_virtuals_error_sfinae (ACU_RETURN, return_type, complain))
14949     return error_mark_node;
14950 
14951   if (!late_return_type_p)
14952     {
14953       /* Substitute the argument types.  */
14954       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
14955 				    complain, in_decl);
14956       if (arg_types == error_mark_node)
14957 	return error_mark_node;
14958     }
14959 
14960   /* Construct a new type node and return it.  */
14961   return rebuild_function_or_method_type (t, return_type, arg_types,
14962 					  /*raises=*/NULL_TREE, complain);
14963 }
14964 
14965 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
14966    ARGS into that specification, and return the substituted
14967    specification.  If there is no specification, return NULL_TREE.  */
14968 
14969 static tree
tsubst_exception_specification(tree fntype,tree args,tsubst_flags_t complain,tree in_decl,bool defer_ok)14970 tsubst_exception_specification (tree fntype,
14971 				tree args,
14972 				tsubst_flags_t complain,
14973 				tree in_decl,
14974 				bool defer_ok)
14975 {
14976   tree specs;
14977   tree new_specs;
14978 
14979   specs = TYPE_RAISES_EXCEPTIONS (fntype);
14980   new_specs = NULL_TREE;
14981   if (specs && TREE_PURPOSE (specs))
14982     {
14983       /* A noexcept-specifier.  */
14984       tree expr = TREE_PURPOSE (specs);
14985       if (TREE_CODE (expr) == INTEGER_CST)
14986 	new_specs = expr;
14987       else if (defer_ok)
14988 	{
14989 	  /* Defer instantiation of noexcept-specifiers to avoid
14990 	     excessive instantiations (c++/49107).  */
14991 	  new_specs = make_node (DEFERRED_NOEXCEPT);
14992 	  if (DEFERRED_NOEXCEPT_SPEC_P (specs))
14993 	    {
14994 	      /* We already partially instantiated this member template,
14995 		 so combine the new args with the old.  */
14996 	      DEFERRED_NOEXCEPT_PATTERN (new_specs)
14997 		= DEFERRED_NOEXCEPT_PATTERN (expr);
14998 	      DEFERRED_NOEXCEPT_ARGS (new_specs)
14999 		= add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
15000 	    }
15001 	  else
15002 	    {
15003 	      DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
15004 	      DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
15005 	    }
15006 	}
15007       else
15008 	{
15009 	  if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15010 	    {
15011 	      args = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr),
15012 					   args);
15013 	      expr = DEFERRED_NOEXCEPT_PATTERN (expr);
15014 	    }
15015 	  new_specs = tsubst_copy_and_build
15016 	    (expr, args, complain, in_decl, /*function_p=*/false,
15017 	     /*integral_constant_expression_p=*/true);
15018 	}
15019       new_specs = build_noexcept_spec (new_specs, complain);
15020     }
15021   else if (specs)
15022     {
15023       if (! TREE_VALUE (specs))
15024 	new_specs = specs;
15025       else
15026 	while (specs)
15027 	  {
15028 	    tree spec;
15029             int i, len = 1;
15030             tree expanded_specs = NULL_TREE;
15031 
15032             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
15033               {
15034                 /* Expand the pack expansion type.  */
15035                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
15036                                                        args, complain,
15037                                                        in_decl);
15038 
15039 		if (expanded_specs == error_mark_node)
15040 		  return error_mark_node;
15041 		else if (TREE_CODE (expanded_specs) == TREE_VEC)
15042 		  len = TREE_VEC_LENGTH (expanded_specs);
15043 		else
15044 		  {
15045 		    /* We're substituting into a member template, so
15046 		       we got a TYPE_PACK_EXPANSION back.  Add that
15047 		       expansion and move on.  */
15048 		    gcc_assert (TREE_CODE (expanded_specs)
15049 				== TYPE_PACK_EXPANSION);
15050 		    new_specs = add_exception_specifier (new_specs,
15051 							 expanded_specs,
15052 							 complain);
15053 		    specs = TREE_CHAIN (specs);
15054 		    continue;
15055 		  }
15056               }
15057 
15058             for (i = 0; i < len; ++i)
15059               {
15060                 if (expanded_specs)
15061                   spec = TREE_VEC_ELT (expanded_specs, i);
15062                 else
15063                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
15064                 if (spec == error_mark_node)
15065                   return spec;
15066                 new_specs = add_exception_specifier (new_specs, spec,
15067                                                      complain);
15068               }
15069 
15070             specs = TREE_CHAIN (specs);
15071 	  }
15072     }
15073   return new_specs;
15074 }
15075 
15076 /* Take the tree structure T and replace template parameters used
15077    therein with the argument vector ARGS.  IN_DECL is an associated
15078    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
15079    Issue error and warning messages under control of COMPLAIN.  Note
15080    that we must be relatively non-tolerant of extensions here, in
15081    order to preserve conformance; if we allow substitutions that
15082    should not be allowed, we may allow argument deductions that should
15083    not succeed, and therefore report ambiguous overload situations
15084    where there are none.  In theory, we could allow the substitution,
15085    but indicate that it should have failed, and allow our caller to
15086    make sure that the right thing happens, but we don't try to do this
15087    yet.
15088 
15089    This function is used for dealing with types, decls and the like;
15090    for expressions, use tsubst_expr or tsubst_copy.  */
15091 
15092 tree
tsubst(tree t,tree args,tsubst_flags_t complain,tree in_decl)15093 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15094 {
15095   enum tree_code code;
15096   tree type, r = NULL_TREE;
15097 
15098   if (t == NULL_TREE || t == error_mark_node
15099       || t == integer_type_node
15100       || t == void_type_node
15101       || t == char_type_node
15102       || t == unknown_type_node
15103       || TREE_CODE (t) == NAMESPACE_DECL
15104       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
15105     return t;
15106 
15107   if (DECL_P (t))
15108     return tsubst_decl (t, args, complain);
15109 
15110   if (args == NULL_TREE)
15111     return t;
15112 
15113   code = TREE_CODE (t);
15114 
15115   if (code == IDENTIFIER_NODE)
15116     type = IDENTIFIER_TYPE_VALUE (t);
15117   else
15118     type = TREE_TYPE (t);
15119 
15120   gcc_assert (type != unknown_type_node);
15121 
15122   /* Reuse typedefs.  We need to do this to handle dependent attributes,
15123      such as attribute aligned.  */
15124   if (TYPE_P (t)
15125       && typedef_variant_p (t))
15126     {
15127       tree decl = TYPE_NAME (t);
15128 
15129       if (alias_template_specialization_p (t, nt_opaque))
15130 	{
15131 	  /* DECL represents an alias template and we want to
15132 	     instantiate it.  */
15133 	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15134 	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15135 	  r = instantiate_alias_template (tmpl, gen_args, complain);
15136 	}
15137       else if (DECL_CLASS_SCOPE_P (decl)
15138 	       && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
15139 	       && uses_template_parms (DECL_CONTEXT (decl)))
15140 	{
15141 	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15142 	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15143 	  r = retrieve_specialization (tmpl, gen_args, 0);
15144 	}
15145       else if (DECL_FUNCTION_SCOPE_P (decl)
15146 	       && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
15147 	       && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
15148 	r = retrieve_local_specialization (decl);
15149       else
15150 	/* The typedef is from a non-template context.  */
15151 	return t;
15152 
15153       if (r)
15154 	{
15155 	  r = TREE_TYPE (r);
15156 	  r = cp_build_qualified_type_real
15157 	    (r, cp_type_quals (t) | cp_type_quals (r),
15158 	     complain | tf_ignore_bad_quals);
15159 	  return r;
15160 	}
15161       else
15162 	{
15163 	  /* We don't have an instantiation yet, so drop the typedef.  */
15164 	  int quals = cp_type_quals (t);
15165 	  t = DECL_ORIGINAL_TYPE (decl);
15166 	  t = cp_build_qualified_type_real (t, quals,
15167 					    complain | tf_ignore_bad_quals);
15168 	}
15169     }
15170 
15171   bool fndecl_type = (complain & tf_fndecl_type);
15172   complain &= ~tf_fndecl_type;
15173 
15174   if (type
15175       && code != TYPENAME_TYPE
15176       && code != TEMPLATE_TYPE_PARM
15177       && code != TEMPLATE_PARM_INDEX
15178       && code != IDENTIFIER_NODE
15179       && code != FUNCTION_TYPE
15180       && code != METHOD_TYPE)
15181     type = tsubst (type, args, complain, in_decl);
15182   if (type == error_mark_node)
15183     return error_mark_node;
15184 
15185   switch (code)
15186     {
15187     case RECORD_TYPE:
15188     case UNION_TYPE:
15189     case ENUMERAL_TYPE:
15190       return tsubst_aggr_type (t, args, complain, in_decl,
15191 			       /*entering_scope=*/0);
15192 
15193     case ERROR_MARK:
15194     case IDENTIFIER_NODE:
15195     case VOID_TYPE:
15196     case REAL_TYPE:
15197     case COMPLEX_TYPE:
15198     case VECTOR_TYPE:
15199     case BOOLEAN_TYPE:
15200     case NULLPTR_TYPE:
15201     case LANG_TYPE:
15202       return t;
15203 
15204     case INTEGER_TYPE:
15205       if (t == integer_type_node)
15206 	return t;
15207 
15208       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
15209           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
15210         return t;
15211 
15212       {
15213 	tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
15214 
15215 	max = tsubst_expr (omax, args, complain, in_decl,
15216 			   /*integral_constant_expression_p=*/false);
15217 
15218 	/* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
15219 	   needed.  */
15220 	if (TREE_CODE (max) == NOP_EXPR
15221 	    && TREE_SIDE_EFFECTS (omax)
15222 	    && !TREE_TYPE (max))
15223 	  TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
15224 
15225 	/* If we're in a partial instantiation, preserve the magic NOP_EXPR
15226 	   with TREE_SIDE_EFFECTS that indicates this is not an integral
15227 	   constant expression.  */
15228 	if (processing_template_decl
15229 	    && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
15230 	  {
15231 	    gcc_assert (TREE_CODE (max) == NOP_EXPR);
15232 	    TREE_SIDE_EFFECTS (max) = 1;
15233 	  }
15234 
15235 	return compute_array_index_type (NULL_TREE, max, complain);
15236       }
15237 
15238     case TEMPLATE_TYPE_PARM:
15239     case TEMPLATE_TEMPLATE_PARM:
15240     case BOUND_TEMPLATE_TEMPLATE_PARM:
15241     case TEMPLATE_PARM_INDEX:
15242       {
15243 	int idx;
15244 	int level;
15245 	int levels;
15246 	tree arg = NULL_TREE;
15247 
15248 	r = NULL_TREE;
15249 
15250 	gcc_assert (TREE_VEC_LENGTH (args) > 0);
15251 	template_parm_level_and_index (t, &level, &idx);
15252 
15253 	levels = TMPL_ARGS_DEPTH (args);
15254 	if (level <= levels
15255 	    && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
15256 	  {
15257 	    arg = TMPL_ARG (args, level, idx);
15258 
15259 	    /* See through ARGUMENT_PACK_SELECT arguments. */
15260 	    if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
15261 	      arg = argument_pack_select_arg (arg);
15262 	  }
15263 
15264 	if (arg == error_mark_node)
15265 	  return error_mark_node;
15266 	else if (arg != NULL_TREE)
15267 	  {
15268 	    if (ARGUMENT_PACK_P (arg))
15269 	      /* If ARG is an argument pack, we don't actually want to
15270 		 perform a substitution here, because substitutions
15271 		 for argument packs are only done
15272 		 element-by-element. We can get to this point when
15273 		 substituting the type of a non-type template
15274 		 parameter pack, when that type actually contains
15275 		 template parameter packs from an outer template, e.g.,
15276 
15277 	         template<typename... Types> struct A {
15278 		   template<Types... Values> struct B { };
15279                  };  */
15280 	      return t;
15281 
15282 	    if (code == TEMPLATE_TYPE_PARM)
15283 	      {
15284 		int quals;
15285 
15286 		/* When building concept checks for the purpose of
15287 		   deducing placeholders, we can end up with wildcards
15288 		   where types are expected. Adjust this to the deduced
15289 		   value.  */
15290 		if (TREE_CODE (arg) == WILDCARD_DECL)
15291 		  arg = TREE_TYPE (TREE_TYPE (arg));
15292 
15293 		gcc_assert (TYPE_P (arg));
15294 
15295 		quals = cp_type_quals (arg) | cp_type_quals (t);
15296 
15297 		return cp_build_qualified_type_real
15298 		  (arg, quals, complain | tf_ignore_bad_quals);
15299 	      }
15300 	    else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
15301 	      {
15302 		/* We are processing a type constructed from a
15303 		   template template parameter.  */
15304 		tree argvec = tsubst (TYPE_TI_ARGS (t),
15305 				      args, complain, in_decl);
15306 		if (argvec == error_mark_node)
15307 		  return error_mark_node;
15308 
15309 		gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
15310 			    || TREE_CODE (arg) == TEMPLATE_DECL
15311 			    || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
15312 
15313 		if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
15314 		  /* Consider this code:
15315 
15316 			template <template <class> class Template>
15317 			struct Internal {
15318 			template <class Arg> using Bind = Template<Arg>;
15319 			};
15320 
15321 			template <template <class> class Template, class Arg>
15322 			using Instantiate = Template<Arg>; //#0
15323 
15324 			template <template <class> class Template,
15325                                   class Argument>
15326 			using Bind =
15327 			  Instantiate<Internal<Template>::template Bind,
15328 				      Argument>; //#1
15329 
15330 		     When #1 is parsed, the
15331 		     BOUND_TEMPLATE_TEMPLATE_PARM representing the
15332 		     parameter `Template' in #0 matches the
15333 		     UNBOUND_CLASS_TEMPLATE representing the argument
15334 		     `Internal<Template>::template Bind'; We then want
15335 		     to assemble the type `Bind<Argument>' that can't
15336 		     be fully created right now, because
15337 		     `Internal<Template>' not being complete, the Bind
15338 		     template cannot be looked up in that context.  So
15339 		     we need to "store" `Bind<Argument>' for later
15340 		     when the context of Bind becomes complete.  Let's
15341 		     store that in a TYPENAME_TYPE.  */
15342 		  return make_typename_type (TYPE_CONTEXT (arg),
15343 					     build_nt (TEMPLATE_ID_EXPR,
15344 						       TYPE_IDENTIFIER (arg),
15345 						       argvec),
15346 					     typename_type,
15347 					     complain);
15348 
15349 		/* We can get a TEMPLATE_TEMPLATE_PARM here when we
15350 		   are resolving nested-types in the signature of a
15351 		   member function templates.  Otherwise ARG is a
15352 		   TEMPLATE_DECL and is the real template to be
15353 		   instantiated.  */
15354 		if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
15355 		  arg = TYPE_NAME (arg);
15356 
15357 		r = lookup_template_class (arg,
15358 					   argvec, in_decl,
15359 					   DECL_CONTEXT (arg),
15360 					    /*entering_scope=*/0,
15361 					   complain);
15362 		return cp_build_qualified_type_real
15363 		  (r, cp_type_quals (t) | cp_type_quals (r), complain);
15364 	      }
15365 	    else if (code == TEMPLATE_TEMPLATE_PARM)
15366 	      return arg;
15367 	    else
15368 	      /* TEMPLATE_PARM_INDEX.  */
15369 	      return convert_from_reference (unshare_expr (arg));
15370 	  }
15371 
15372 	if (level == 1)
15373 	  /* This can happen during the attempted tsubst'ing in
15374 	     unify.  This means that we don't yet have any information
15375 	     about the template parameter in question.  */
15376 	  return t;
15377 
15378 	/* Early in template argument deduction substitution, we don't
15379 	   want to reduce the level of 'auto', or it will be confused
15380 	   with a normal template parm in subsequent deduction.
15381 	   Similarly, don't reduce the level of template parameters to
15382 	   avoid mismatches when deducing their types.  */
15383 	if (complain & tf_partial)
15384 	  return t;
15385 
15386 	/* If we get here, we must have been looking at a parm for a
15387 	   more deeply nested template.  Make a new version of this
15388 	   template parameter, but with a lower level.  */
15389 	switch (code)
15390 	  {
15391 	  case TEMPLATE_TYPE_PARM:
15392 	  case TEMPLATE_TEMPLATE_PARM:
15393 	  case BOUND_TEMPLATE_TEMPLATE_PARM:
15394 	    if (cp_type_quals (t))
15395 	      {
15396 		r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
15397 		r = cp_build_qualified_type_real
15398 		  (r, cp_type_quals (t),
15399 		   complain | (code == TEMPLATE_TYPE_PARM
15400 			       ? tf_ignore_bad_quals : 0));
15401 	      }
15402 	    else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
15403 		     && PLACEHOLDER_TYPE_CONSTRAINTS (t)
15404 		     && (r = (TEMPLATE_PARM_DESCENDANTS
15405 			      (TEMPLATE_TYPE_PARM_INDEX (t))))
15406 		     && (r = TREE_TYPE (r))
15407 		     && !PLACEHOLDER_TYPE_CONSTRAINTS (r))
15408 	      /* Break infinite recursion when substituting the constraints
15409 		 of a constrained placeholder.  */;
15410 	    else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
15411 		     && !PLACEHOLDER_TYPE_CONSTRAINTS (t)
15412 		     && !CLASS_PLACEHOLDER_TEMPLATE (t)
15413 		     && (arg = TEMPLATE_TYPE_PARM_INDEX (t),
15414 			 r = TEMPLATE_PARM_DESCENDANTS (arg))
15415 		     && (TEMPLATE_PARM_LEVEL (r)
15416 			 == TEMPLATE_PARM_LEVEL (arg) - levels))
15417 		/* Cache the simple case of lowering a type parameter.  */
15418 	      r = TREE_TYPE (r);
15419 	    else
15420 	      {
15421 		r = copy_type (t);
15422 		TEMPLATE_TYPE_PARM_INDEX (r)
15423 		  = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
15424 						r, levels, args, complain);
15425 		TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
15426 		TYPE_MAIN_VARIANT (r) = r;
15427 		TYPE_POINTER_TO (r) = NULL_TREE;
15428 		TYPE_REFERENCE_TO (r) = NULL_TREE;
15429 
15430                 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
15431 		  {
15432 		    /* Propagate constraints on placeholders since they are
15433 		       only instantiated during satisfaction.  */
15434 		    if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
15435 		      PLACEHOLDER_TYPE_CONSTRAINTS (r) = constr;
15436 		    else if (tree pl = CLASS_PLACEHOLDER_TEMPLATE (t))
15437 		      {
15438 			pl = tsubst_copy (pl, args, complain, in_decl);
15439 			CLASS_PLACEHOLDER_TEMPLATE (r) = pl;
15440 		      }
15441 		  }
15442 
15443 		if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
15444 		  /* We have reduced the level of the template
15445 		     template parameter, but not the levels of its
15446 		     template parameters, so canonical_type_parameter
15447 		     will not be able to find the canonical template
15448 		     template parameter for this level. Thus, we
15449 		     require structural equality checking to compare
15450 		     TEMPLATE_TEMPLATE_PARMs. */
15451 		  SET_TYPE_STRUCTURAL_EQUALITY (r);
15452 		else if (TYPE_STRUCTURAL_EQUALITY_P (t))
15453 		  SET_TYPE_STRUCTURAL_EQUALITY (r);
15454 		else
15455 		  TYPE_CANONICAL (r) = canonical_type_parameter (r);
15456 
15457 		if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
15458 		  {
15459 		    tree tinfo = TYPE_TEMPLATE_INFO (t);
15460 		    /* We might need to substitute into the types of non-type
15461 		       template parameters.  */
15462 		    tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
15463 					complain, in_decl);
15464 		    if (tmpl == error_mark_node)
15465 		      return error_mark_node;
15466 		    tree argvec = tsubst (TI_ARGS (tinfo), args,
15467 					  complain, in_decl);
15468 		    if (argvec == error_mark_node)
15469 		      return error_mark_node;
15470 
15471 		    TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
15472 		      = build_template_info (tmpl, argvec);
15473 		  }
15474 	      }
15475 	    break;
15476 
15477 	  case TEMPLATE_PARM_INDEX:
15478 	    /* OK, now substitute the type of the non-type parameter.  We
15479 	       couldn't do it earlier because it might be an auto parameter,
15480 	       and we wouldn't need to if we had an argument.  */
15481 	    type = tsubst (type, args, complain, in_decl);
15482 	    if (type == error_mark_node)
15483 	      return error_mark_node;
15484 	    r = reduce_template_parm_level (t, type, levels, args, complain);
15485 	    break;
15486 
15487 	  default:
15488 	    gcc_unreachable ();
15489 	  }
15490 
15491 	return r;
15492       }
15493 
15494     case TREE_LIST:
15495       {
15496 	tree purpose, value, chain;
15497 
15498 	if (t == void_list_node)
15499 	  return t;
15500 
15501 	if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
15502 	    || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
15503 	  {
15504 	    /* We have pack expansions, so expand those and
15505 	       create a new list out of it.  */
15506 
15507 	    /* Expand the argument expressions.  */
15508 	    tree purposevec = NULL_TREE;
15509 	    if (TREE_PURPOSE (t))
15510 	      purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
15511 						  complain, in_decl);
15512 	    if (purposevec == error_mark_node)
15513 	      return error_mark_node;
15514 
15515 	    tree valuevec = NULL_TREE;
15516 	    if (TREE_VALUE (t))
15517 	      valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
15518 						complain, in_decl);
15519 	    if (valuevec == error_mark_node)
15520 	      return error_mark_node;
15521 
15522 	    /* Build the rest of the list.  */
15523 	    tree chain = TREE_CHAIN (t);
15524 	    if (chain && chain != void_type_node)
15525 	      chain = tsubst (chain, args, complain, in_decl);
15526 	    if (chain == error_mark_node)
15527 	      return error_mark_node;
15528 
15529 	    /* Determine the number of arguments.  */
15530 	    int len = -1;
15531 	    if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
15532 	      {
15533 		len = TREE_VEC_LENGTH (purposevec);
15534 		gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
15535 	      }
15536 	    else if (TREE_CODE (valuevec) == TREE_VEC)
15537 	      len = TREE_VEC_LENGTH (valuevec);
15538 	    else
15539 	      {
15540 		/* Since we only performed a partial substitution into
15541 		   the argument pack, we only RETURN (a single list
15542 		   node.  */
15543 		if (purposevec == TREE_PURPOSE (t)
15544 		    && valuevec == TREE_VALUE (t)
15545 		    && chain == TREE_CHAIN (t))
15546 		  return t;
15547 
15548 		return tree_cons (purposevec, valuevec, chain);
15549 	      }
15550 
15551 	    /* Convert the argument vectors into a TREE_LIST.  */
15552 	    for (int i = len; i-- > 0; )
15553 	      {
15554 		purpose = (purposevec ? TREE_VEC_ELT (purposevec, i)
15555 			   : NULL_TREE);
15556 		value = (valuevec ? TREE_VEC_ELT (valuevec, i)
15557 			 : NULL_TREE);
15558 
15559 		/* Build the list (backwards).  */
15560 		chain = hash_tree_cons (purpose, value, chain);
15561 	      }
15562 
15563 	    return chain;
15564 	  }
15565 
15566 	purpose = TREE_PURPOSE (t);
15567 	if (purpose)
15568 	  {
15569 	    purpose = tsubst (purpose, args, complain, in_decl);
15570 	    if (purpose == error_mark_node)
15571 	      return error_mark_node;
15572 	  }
15573 	value = TREE_VALUE (t);
15574 	if (value)
15575 	  {
15576 	    value = tsubst (value, args, complain, in_decl);
15577 	    if (value == error_mark_node)
15578 	      return error_mark_node;
15579 	  }
15580 	chain = TREE_CHAIN (t);
15581 	if (chain && chain != void_type_node)
15582 	  {
15583 	    chain = tsubst (chain, args, complain, in_decl);
15584 	    if (chain == error_mark_node)
15585 	      return error_mark_node;
15586 	  }
15587 	if (purpose == TREE_PURPOSE (t)
15588 	    && value == TREE_VALUE (t)
15589 	    && chain == TREE_CHAIN (t))
15590 	  return t;
15591 	return hash_tree_cons (purpose, value, chain);
15592       }
15593 
15594     case TREE_BINFO:
15595       /* We should never be tsubsting a binfo.  */
15596       gcc_unreachable ();
15597 
15598     case TREE_VEC:
15599       /* A vector of template arguments.  */
15600       gcc_assert (!type);
15601       return tsubst_template_args (t, args, complain, in_decl);
15602 
15603     case POINTER_TYPE:
15604     case REFERENCE_TYPE:
15605       {
15606 	if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
15607 	  return t;
15608 
15609 	/* [temp.deduct]
15610 
15611 	   Type deduction may fail for any of the following
15612 	   reasons:
15613 
15614 	   -- Attempting to create a pointer to reference type.
15615 	   -- Attempting to create a reference to a reference type or
15616 	      a reference to void.
15617 
15618 	  Core issue 106 says that creating a reference to a reference
15619 	  during instantiation is no longer a cause for failure. We
15620 	  only enforce this check in strict C++98 mode.  */
15621 	if ((TYPE_REF_P (type)
15622 	     && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
15623 	    || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
15624 	  {
15625 	    static location_t last_loc;
15626 
15627 	    /* We keep track of the last time we issued this error
15628 	       message to avoid spewing a ton of messages during a
15629 	       single bad template instantiation.  */
15630 	    if (complain & tf_error
15631 		&& last_loc != input_location)
15632 	      {
15633 		if (VOID_TYPE_P (type))
15634 		  error ("forming reference to void");
15635                else if (code == POINTER_TYPE)
15636                  error ("forming pointer to reference type %qT", type);
15637                else
15638 		  error ("forming reference to reference type %qT", type);
15639 		last_loc = input_location;
15640 	      }
15641 
15642 	    return error_mark_node;
15643 	  }
15644 	else if (TREE_CODE (type) == FUNCTION_TYPE
15645 		 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
15646 		     || type_memfn_rqual (type) != REF_QUAL_NONE))
15647 	  {
15648 	    if (complain & tf_error)
15649 	      {
15650 		if (code == POINTER_TYPE)
15651 		  error ("forming pointer to qualified function type %qT",
15652 			 type);
15653 		else
15654 		  error ("forming reference to qualified function type %qT",
15655 			 type);
15656 	      }
15657 	    return error_mark_node;
15658 	  }
15659 	else if (code == POINTER_TYPE)
15660 	  {
15661 	    r = build_pointer_type (type);
15662 	    if (TREE_CODE (type) == METHOD_TYPE)
15663 	      r = build_ptrmemfunc_type (r);
15664 	  }
15665 	else if (TYPE_REF_P (type))
15666 	  /* In C++0x, during template argument substitution, when there is an
15667 	     attempt to create a reference to a reference type, reference
15668 	     collapsing is applied as described in [14.3.1/4 temp.arg.type]:
15669 
15670 	     "If a template-argument for a template-parameter T names a type
15671 	     that is a reference to a type A, an attempt to create the type
15672 	     'lvalue reference to cv T' creates the type 'lvalue reference to
15673 	     A,' while an attempt to create the type type rvalue reference to
15674 	     cv T' creates the type T"
15675 	  */
15676 	  r = cp_build_reference_type
15677 	      (TREE_TYPE (type),
15678 	       TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
15679 	else
15680 	  r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
15681 	r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
15682 
15683 	if (r != error_mark_node)
15684 	  /* Will this ever be needed for TYPE_..._TO values?  */
15685 	  layout_type (r);
15686 
15687 	return r;
15688       }
15689     case OFFSET_TYPE:
15690       {
15691 	r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
15692 	if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
15693 	  {
15694 	    /* [temp.deduct]
15695 
15696 	       Type deduction may fail for any of the following
15697 	       reasons:
15698 
15699 	       -- Attempting to create "pointer to member of T" when T
15700 		  is not a class type.  */
15701 	    if (complain & tf_error)
15702 	      error ("creating pointer to member of non-class type %qT", r);
15703 	    return error_mark_node;
15704 	  }
15705 	if (TYPE_REF_P (type))
15706 	  {
15707 	    if (complain & tf_error)
15708 	      error ("creating pointer to member reference type %qT", type);
15709 	    return error_mark_node;
15710 	  }
15711 	if (VOID_TYPE_P (type))
15712 	  {
15713 	    if (complain & tf_error)
15714 	      error ("creating pointer to member of type void");
15715 	    return error_mark_node;
15716 	  }
15717 	gcc_assert (TREE_CODE (type) != METHOD_TYPE);
15718 	if (TREE_CODE (type) == FUNCTION_TYPE)
15719 	  {
15720 	    /* The type of the implicit object parameter gets its
15721 	       cv-qualifiers from the FUNCTION_TYPE. */
15722 	    tree memptr;
15723 	    tree method_type
15724 	      = build_memfn_type (type, r, type_memfn_quals (type),
15725 				  type_memfn_rqual (type));
15726 	    memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
15727 	    return cp_build_qualified_type_real (memptr, cp_type_quals (t),
15728 						 complain);
15729 	  }
15730 	else
15731 	  return cp_build_qualified_type_real (build_ptrmem_type (r, type),
15732 					       cp_type_quals (t),
15733 					       complain);
15734       }
15735     case FUNCTION_TYPE:
15736     case METHOD_TYPE:
15737       {
15738 	tree fntype;
15739 	tree specs;
15740 	fntype = tsubst_function_type (t, args, complain, in_decl);
15741 	if (fntype == error_mark_node)
15742 	  return error_mark_node;
15743 
15744 	/* Substitute the exception specification.  */
15745 	specs = tsubst_exception_specification (t, args, complain, in_decl,
15746 						/*defer_ok*/fndecl_type);
15747 	if (specs == error_mark_node)
15748 	  return error_mark_node;
15749 	if (specs)
15750 	  fntype = build_exception_variant (fntype, specs);
15751 	return fntype;
15752       }
15753     case ARRAY_TYPE:
15754       {
15755 	tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
15756 	if (domain == error_mark_node)
15757 	  return error_mark_node;
15758 
15759 	/* As an optimization, we avoid regenerating the array type if
15760 	   it will obviously be the same as T.  */
15761 	if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
15762 	  return t;
15763 
15764 	/* These checks should match the ones in create_array_type_for_decl.
15765 
15766 	   [temp.deduct]
15767 
15768 	   The deduction may fail for any of the following reasons:
15769 
15770 	   -- Attempting to create an array with an element type that
15771 	      is void, a function type, or a reference type, or [DR337]
15772 	      an abstract class type.  */
15773 	if (VOID_TYPE_P (type)
15774 	    || TREE_CODE (type) == FUNCTION_TYPE
15775 	    || (TREE_CODE (type) == ARRAY_TYPE
15776 		&& TYPE_DOMAIN (type) == NULL_TREE)
15777 	    || TYPE_REF_P (type))
15778 	  {
15779 	    if (complain & tf_error)
15780 	      error ("creating array of %qT", type);
15781 	    return error_mark_node;
15782 	  }
15783 
15784 	if (abstract_virtuals_error_sfinae (ACU_ARRAY, type, complain))
15785 	  return error_mark_node;
15786 
15787 	r = build_cplus_array_type (type, domain);
15788 
15789 	if (!valid_array_size_p (input_location, r, in_decl,
15790 				 (complain & tf_error)))
15791 	  return error_mark_node;
15792 
15793 	if (TYPE_USER_ALIGN (t))
15794 	  {
15795 	    SET_TYPE_ALIGN (r, TYPE_ALIGN (t));
15796 	    TYPE_USER_ALIGN (r) = 1;
15797 	  }
15798 
15799 	return r;
15800       }
15801 
15802     case TYPENAME_TYPE:
15803       {
15804 	tree ctx = TYPE_CONTEXT (t);
15805 	if (TREE_CODE (ctx) == TYPE_PACK_EXPANSION)
15806 	  {
15807 	    ctx = tsubst_pack_expansion (ctx, args, complain, in_decl);
15808 	    if (ctx == error_mark_node
15809 		|| TREE_VEC_LENGTH (ctx) > 1)
15810 	      return error_mark_node;
15811 	    if (TREE_VEC_LENGTH (ctx) == 0)
15812 	      {
15813 		if (complain & tf_error)
15814 		  error ("%qD is instantiated for an empty pack",
15815 			 TYPENAME_TYPE_FULLNAME (t));
15816 		return error_mark_node;
15817 	      }
15818 	    ctx = TREE_VEC_ELT (ctx, 0);
15819 	  }
15820 	else
15821 	  ctx = tsubst_aggr_type (ctx, args, complain, in_decl,
15822 				  /*entering_scope=*/1);
15823 	if (ctx == error_mark_node)
15824 	  return error_mark_node;
15825 
15826 	tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
15827 			      complain, in_decl);
15828 	if (f == error_mark_node)
15829 	  return error_mark_node;
15830 
15831 	if (!MAYBE_CLASS_TYPE_P (ctx))
15832 	  {
15833 	    if (complain & tf_error)
15834 	      error ("%qT is not a class, struct, or union type", ctx);
15835 	    return error_mark_node;
15836 	  }
15837 	else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
15838 	  {
15839 	    /* Normally, make_typename_type does not require that the CTX
15840 	       have complete type in order to allow things like:
15841 
15842 		 template <class T> struct S { typename S<T>::X Y; };
15843 
15844 	       But, such constructs have already been resolved by this
15845 	       point, so here CTX really should have complete type, unless
15846 	       it's a partial instantiation.  */
15847 	    ctx = complete_type (ctx);
15848 	    if (!COMPLETE_TYPE_P (ctx))
15849 	      {
15850 		if (complain & tf_error)
15851 		  cxx_incomplete_type_error (NULL_TREE, ctx);
15852 		return error_mark_node;
15853 	      }
15854 	  }
15855 
15856 	f = make_typename_type (ctx, f, typename_type,
15857 				complain | tf_keep_type_decl);
15858 	if (f == error_mark_node)
15859 	  return f;
15860 	if (TREE_CODE (f) == TYPE_DECL)
15861 	  {
15862 	    complain |= tf_ignore_bad_quals;
15863 	    f = TREE_TYPE (f);
15864 	  }
15865 
15866 	if (TREE_CODE (f) != TYPENAME_TYPE)
15867 	  {
15868 	    if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
15869 	      {
15870 		if (complain & tf_error)
15871 		  error ("%qT resolves to %qT, which is not an enumeration type",
15872 			 t, f);
15873 		else
15874 		  return error_mark_node;
15875 	      }
15876 	    else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
15877 	      {
15878 		if (complain & tf_error)
15879 		  error ("%qT resolves to %qT, which is not a class type",
15880 			 t, f);
15881 		else
15882 		  return error_mark_node;
15883 	      }
15884 	  }
15885 
15886 	return cp_build_qualified_type_real
15887 	  (f, cp_type_quals (f) | cp_type_quals (t), complain);
15888       }
15889 
15890     case UNBOUND_CLASS_TEMPLATE:
15891       {
15892 	tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
15893 				     in_decl, /*entering_scope=*/1);
15894 	tree name = TYPE_IDENTIFIER (t);
15895 	tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
15896 
15897 	if (ctx == error_mark_node || name == error_mark_node)
15898 	  return error_mark_node;
15899 
15900 	if (parm_list)
15901 	  parm_list = tsubst_template_parms (parm_list, args, complain);
15902 	return make_unbound_class_template (ctx, name, parm_list, complain);
15903       }
15904 
15905     case TYPEOF_TYPE:
15906       {
15907 	tree type;
15908 
15909 	++cp_unevaluated_operand;
15910 	++c_inhibit_evaluation_warnings;
15911 
15912 	type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
15913 			    complain, in_decl,
15914 			    /*integral_constant_expression_p=*/false);
15915 
15916 	--cp_unevaluated_operand;
15917 	--c_inhibit_evaluation_warnings;
15918 
15919 	type = finish_typeof (type);
15920 	return cp_build_qualified_type_real (type,
15921 					     cp_type_quals (t)
15922 					     | cp_type_quals (type),
15923 					     complain);
15924       }
15925 
15926     case DECLTYPE_TYPE:
15927       {
15928 	tree type;
15929 
15930 	++cp_unevaluated_operand;
15931 	++c_inhibit_evaluation_warnings;
15932 
15933 	type = tsubst_copy_and_build (DECLTYPE_TYPE_EXPR (t), args,
15934 				      complain|tf_decltype, in_decl,
15935 				      /*function_p*/false,
15936 				      /*integral_constant_expression*/false);
15937 
15938 	--cp_unevaluated_operand;
15939 	--c_inhibit_evaluation_warnings;
15940 
15941 	if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
15942 	  type = lambda_capture_field_type (type,
15943 					    false /*explicit_init*/,
15944 					    DECLTYPE_FOR_REF_CAPTURE (t));
15945 	else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
15946 	  type = lambda_proxy_type (type);
15947 	else
15948 	  {
15949 	    bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
15950 	    if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
15951 		&& EXPR_P (type))
15952 	      /* In a template ~id could be either a complement expression
15953 		 or an unqualified-id naming a destructor; if instantiating
15954 		 it produces an expression, it's not an id-expression or
15955 		 member access.  */
15956 	      id = false;
15957 	    type = finish_decltype_type (type, id, complain);
15958 	  }
15959 	return cp_build_qualified_type_real (type,
15960 					     cp_type_quals (t)
15961 					     | cp_type_quals (type),
15962 					     complain | tf_ignore_bad_quals);
15963       }
15964 
15965     case UNDERLYING_TYPE:
15966       {
15967 	tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
15968 			    complain, in_decl);
15969 	return finish_underlying_type (type);
15970       }
15971 
15972     case TYPE_ARGUMENT_PACK:
15973     case NONTYPE_ARGUMENT_PACK:
15974       {
15975         tree r;
15976 
15977 	if (code == NONTYPE_ARGUMENT_PACK)
15978 	  r = make_node (code);
15979 	else
15980 	  r = cxx_make_type (code);
15981 
15982 	tree pack_args = ARGUMENT_PACK_ARGS (t);
15983 	pack_args = tsubst_template_args (pack_args, args, complain, in_decl);
15984 	SET_ARGUMENT_PACK_ARGS (r, pack_args);
15985 
15986 	return r;
15987       }
15988 
15989     case VOID_CST:
15990     case INTEGER_CST:
15991     case REAL_CST:
15992     case STRING_CST:
15993     case PLUS_EXPR:
15994     case MINUS_EXPR:
15995     case NEGATE_EXPR:
15996     case NOP_EXPR:
15997     case INDIRECT_REF:
15998     case ADDR_EXPR:
15999     case CALL_EXPR:
16000     case ARRAY_REF:
16001     case SCOPE_REF:
16002       /* We should use one of the expression tsubsts for these codes.  */
16003       gcc_unreachable ();
16004 
16005     default:
16006       sorry ("use of %qs in template", get_tree_code_name (code));
16007       return error_mark_node;
16008     }
16009 }
16010 
16011 /* tsubst a BASELINK.  OBJECT_TYPE, if non-NULL, is the type of the
16012    expression on the left-hand side of the "." or "->" operator.  We
16013    only do the lookup if we had a dependent BASELINK.  Otherwise we
16014    adjust it onto the instantiated heirarchy.  */
16015 
16016 static tree
tsubst_baselink(tree baselink,tree object_type,tree args,tsubst_flags_t complain,tree in_decl)16017 tsubst_baselink (tree baselink, tree object_type,
16018 		 tree args, tsubst_flags_t complain, tree in_decl)
16019 {
16020   bool qualified_p = BASELINK_QUALIFIED_P (baselink);
16021   tree qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
16022   qualifying_scope = tsubst (qualifying_scope, args, complain, in_decl);
16023 
16024   tree optype = BASELINK_OPTYPE (baselink);
16025   optype = tsubst (optype, args, complain, in_decl);
16026 
16027   tree template_args = NULL_TREE;
16028   bool template_id_p = false;
16029   tree fns = BASELINK_FUNCTIONS (baselink);
16030   if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
16031     {
16032       template_id_p = true;
16033       template_args = TREE_OPERAND (fns, 1);
16034       fns = TREE_OPERAND (fns, 0);
16035       if (template_args)
16036 	template_args = tsubst_template_args (template_args, args,
16037 					      complain, in_decl);
16038     }
16039 
16040   tree binfo_type = BINFO_TYPE (BASELINK_BINFO (baselink));
16041   binfo_type = tsubst (binfo_type, args, complain, in_decl);
16042   bool dependent_p = binfo_type != BINFO_TYPE (BASELINK_BINFO (baselink));
16043 
16044   if (dependent_p)
16045     {
16046       tree name = OVL_NAME (fns);
16047       if (IDENTIFIER_CONV_OP_P (name))
16048 	name = make_conv_op_name (optype);
16049 
16050       if (name == complete_dtor_identifier)
16051 	/* Treat as-if non-dependent below.  */
16052 	dependent_p = false;
16053 
16054       baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
16055       if (!baselink)
16056 	{
16057 	  if ((complain & tf_error)
16058 	      && constructor_name_p (name, qualifying_scope))
16059 	    error ("cannot call constructor %<%T::%D%> directly",
16060 		   qualifying_scope, name);
16061 	  return error_mark_node;
16062 	}
16063 
16064       if (BASELINK_P (baselink))
16065 	fns = BASELINK_FUNCTIONS (baselink);
16066     }
16067   else
16068     /* We're going to overwrite pieces below, make a duplicate.  */
16069     baselink = copy_node (baselink);
16070 
16071   /* If lookup found a single function, mark it as used at this point.
16072      (If lookup found multiple functions the one selected later by
16073      overload resolution will be marked as used at that point.)  */
16074   if (!template_id_p && !really_overloaded_fn (fns))
16075     {
16076       tree fn = OVL_FIRST (fns);
16077       bool ok = mark_used (fn, complain);
16078       if (!ok && !(complain & tf_error))
16079 	return error_mark_node;
16080       if (ok && BASELINK_P (baselink))
16081 	/* We might have instantiated an auto function.  */
16082 	TREE_TYPE (baselink) = TREE_TYPE (fn);
16083     }
16084 
16085   if (BASELINK_P (baselink))
16086     {
16087       /* Add back the template arguments, if present.  */
16088       if (template_id_p)
16089 	BASELINK_FUNCTIONS (baselink)
16090 	  = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, template_args);
16091 
16092       /* Update the conversion operator type.  */
16093       BASELINK_OPTYPE (baselink) = optype;
16094     }
16095 
16096   if (!object_type)
16097     object_type = current_class_type;
16098 
16099   if (qualified_p || !dependent_p)
16100     {
16101       baselink = adjust_result_of_qualified_name_lookup (baselink,
16102 							 qualifying_scope,
16103 							 object_type);
16104       if (!qualified_p)
16105 	/* We need to call adjust_result_of_qualified_name_lookup in case the
16106 	   destructor names a base class, but we unset BASELINK_QUALIFIED_P
16107 	   so that we still get virtual function binding.  */
16108 	BASELINK_QUALIFIED_P (baselink) = false;
16109     }
16110 
16111   return baselink;
16112 }
16113 
16114 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
16115    true if the qualified-id will be a postfix-expression in-and-of
16116    itself; false if more of the postfix-expression follows the
16117    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
16118    of "&".  */
16119 
16120 static tree
tsubst_qualified_id(tree qualified_id,tree args,tsubst_flags_t complain,tree in_decl,bool done,bool address_p)16121 tsubst_qualified_id (tree qualified_id, tree args,
16122 		     tsubst_flags_t complain, tree in_decl,
16123 		     bool done, bool address_p)
16124 {
16125   tree expr;
16126   tree scope;
16127   tree name;
16128   bool is_template;
16129   tree template_args;
16130   location_t loc = UNKNOWN_LOCATION;
16131 
16132   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
16133 
16134   /* Figure out what name to look up.  */
16135   name = TREE_OPERAND (qualified_id, 1);
16136   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
16137     {
16138       is_template = true;
16139       loc = EXPR_LOCATION (name);
16140       template_args = TREE_OPERAND (name, 1);
16141       if (template_args)
16142 	template_args = tsubst_template_args (template_args, args,
16143 					      complain, in_decl);
16144       if (template_args == error_mark_node)
16145 	return error_mark_node;
16146       name = TREE_OPERAND (name, 0);
16147     }
16148   else
16149     {
16150       is_template = false;
16151       template_args = NULL_TREE;
16152     }
16153 
16154   /* Substitute into the qualifying scope.  When there are no ARGS, we
16155      are just trying to simplify a non-dependent expression.  In that
16156      case the qualifying scope may be dependent, and, in any case,
16157      substituting will not help.  */
16158   scope = TREE_OPERAND (qualified_id, 0);
16159   if (args)
16160     {
16161       scope = tsubst (scope, args, complain, in_decl);
16162       expr = tsubst_copy (name, args, complain, in_decl);
16163     }
16164   else
16165     expr = name;
16166 
16167   if (dependent_scope_p (scope))
16168     {
16169       if (is_template)
16170 	expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr, template_args);
16171       tree r = build_qualified_name (NULL_TREE, scope, expr,
16172 				     QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
16173       REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (qualified_id);
16174       return r;
16175     }
16176 
16177   if (!BASELINK_P (name) && !DECL_P (expr))
16178     {
16179       if (TREE_CODE (expr) == BIT_NOT_EXPR)
16180 	{
16181 	  /* A BIT_NOT_EXPR is used to represent a destructor.  */
16182 	  if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
16183 	    {
16184 	      error ("qualifying type %qT does not match destructor name ~%qT",
16185 		     scope, TREE_OPERAND (expr, 0));
16186 	      expr = error_mark_node;
16187 	    }
16188 	  else
16189 	    expr = lookup_qualified_name (scope, complete_dtor_identifier,
16190 					  /*is_type_p=*/0, false);
16191 	}
16192       else
16193 	expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
16194       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
16195 		     ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
16196 	{
16197 	  if (complain & tf_error)
16198 	    {
16199 	      error ("dependent-name %qE is parsed as a non-type, but "
16200 		     "instantiation yields a type", qualified_id);
16201 	      inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
16202 	    }
16203 	  return error_mark_node;
16204 	}
16205     }
16206 
16207   if (DECL_P (expr))
16208     {
16209       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
16210 					   scope);
16211       /* Remember that there was a reference to this entity.  */
16212       if (!mark_used (expr, complain) && !(complain & tf_error))
16213 	return error_mark_node;
16214     }
16215 
16216   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
16217     {
16218       if (complain & tf_error)
16219 	qualified_name_lookup_error (scope,
16220 				     TREE_OPERAND (qualified_id, 1),
16221 				     expr, input_location);
16222       return error_mark_node;
16223     }
16224 
16225   if (is_template)
16226     {
16227       /* We may be repeating a check already done during parsing, but
16228 	 if it was well-formed and passed then, it will pass again
16229 	 now, and if it didn't, we wouldn't have got here.  The case
16230 	 we want to catch is when we couldn't tell then, and can now,
16231 	 namely when templ prior to substitution was an
16232 	 identifier.  */
16233       if (flag_concepts && check_auto_in_tmpl_args (expr, template_args))
16234 	return error_mark_node;
16235 
16236       if (variable_template_p (expr))
16237 	expr = lookup_and_finish_template_variable (expr, template_args,
16238 						    complain);
16239       else
16240 	expr = lookup_template_function (expr, template_args);
16241     }
16242 
16243   if (expr == error_mark_node && complain & tf_error)
16244     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
16245 				 expr, input_location);
16246   else if (TYPE_P (scope))
16247     {
16248       expr = (adjust_result_of_qualified_name_lookup
16249 	      (expr, scope, current_nonlambda_class_type ()));
16250       expr = (finish_qualified_id_expr
16251 	      (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
16252 	       QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
16253 	       /*template_arg_p=*/false, complain));
16254     }
16255 
16256   /* Expressions do not generally have reference type.  */
16257   if (TREE_CODE (expr) != SCOPE_REF
16258       /* However, if we're about to form a pointer-to-member, we just
16259 	 want the referenced member referenced.  */
16260       && TREE_CODE (expr) != OFFSET_REF)
16261     expr = convert_from_reference (expr);
16262 
16263   if (REF_PARENTHESIZED_P (qualified_id))
16264     expr = force_paren_expr (expr);
16265 
16266   return expr;
16267 }
16268 
16269 /* tsubst the initializer for a VAR_DECL.  INIT is the unsubstituted
16270    initializer, DECL is the substituted VAR_DECL.  Other arguments are as
16271    for tsubst.  */
16272 
16273 static tree
tsubst_init(tree init,tree decl,tree args,tsubst_flags_t complain,tree in_decl)16274 tsubst_init (tree init, tree decl, tree args,
16275 	     tsubst_flags_t complain, tree in_decl)
16276 {
16277   if (!init)
16278     return NULL_TREE;
16279 
16280   init = tsubst_expr (init, args, complain, in_decl, false);
16281 
16282   tree type = TREE_TYPE (decl);
16283 
16284   if (!init && type != error_mark_node)
16285     {
16286       if (tree auto_node = type_uses_auto (type))
16287 	{
16288 	  if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
16289 	    {
16290 	      if (complain & tf_error)
16291 		error ("initializer for %q#D expands to an empty list "
16292 		       "of expressions", decl);
16293 	      return error_mark_node;
16294 	    }
16295 	}
16296       else if (!dependent_type_p (type))
16297 	{
16298 	  /* If we had an initializer but it
16299 	     instantiated to nothing,
16300 	     value-initialize the object.  This will
16301 	     only occur when the initializer was a
16302 	     pack expansion where the parameter packs
16303 	     used in that expansion were of length
16304 	     zero.  */
16305 	  init = build_value_init (type, complain);
16306 	  if (TREE_CODE (init) == AGGR_INIT_EXPR)
16307 	    init = get_target_expr_sfinae (init, complain);
16308 	  if (TREE_CODE (init) == TARGET_EXPR)
16309 	    TARGET_EXPR_DIRECT_INIT_P (init) = true;
16310 	}
16311     }
16312 
16313   return init;
16314 }
16315 
16316 /* Like tsubst, but deals with expressions.  This function just replaces
16317    template parms; to finish processing the resultant expression, use
16318    tsubst_copy_and_build or tsubst_expr.  */
16319 
16320 static tree
tsubst_copy(tree t,tree args,tsubst_flags_t complain,tree in_decl)16321 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
16322 {
16323   enum tree_code code;
16324   tree r;
16325 
16326   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
16327     return t;
16328 
16329   code = TREE_CODE (t);
16330 
16331   switch (code)
16332     {
16333     case PARM_DECL:
16334       r = retrieve_local_specialization (t);
16335 
16336       if (r == NULL_TREE)
16337 	{
16338 	  /* We get here for a use of 'this' in an NSDMI.  */
16339 	  if (DECL_NAME (t) == this_identifier && current_class_ptr)
16340 	    return current_class_ptr;
16341 
16342 	  /* This can happen for a parameter name used later in a function
16343 	     declaration (such as in a late-specified return type).  Just
16344 	     make a dummy decl, since it's only used for its type.  */
16345 	  gcc_assert (cp_unevaluated_operand != 0);
16346 	  r = tsubst_decl (t, args, complain);
16347 	  /* Give it the template pattern as its context; its true context
16348 	     hasn't been instantiated yet and this is good enough for
16349 	     mangling.  */
16350 	  DECL_CONTEXT (r) = DECL_CONTEXT (t);
16351 	}
16352 
16353       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
16354 	r = argument_pack_select_arg (r);
16355       if (!mark_used (r, complain) && !(complain & tf_error))
16356 	return error_mark_node;
16357       return r;
16358 
16359     case CONST_DECL:
16360       {
16361 	tree enum_type;
16362 	tree v;
16363 
16364 	if (DECL_TEMPLATE_PARM_P (t))
16365 	  return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
16366 	/* There is no need to substitute into namespace-scope
16367 	   enumerators.  */
16368 	if (DECL_NAMESPACE_SCOPE_P (t))
16369 	  return t;
16370 	/* If ARGS is NULL, then T is known to be non-dependent.  */
16371 	if (args == NULL_TREE)
16372 	  return scalar_constant_value (t);
16373 
16374 	/* Unfortunately, we cannot just call lookup_name here.
16375 	   Consider:
16376 
16377 	     template <int I> int f() {
16378 	     enum E { a = I };
16379 	     struct S { void g() { E e = a; } };
16380 	     };
16381 
16382 	   When we instantiate f<7>::S::g(), say, lookup_name is not
16383 	   clever enough to find f<7>::a.  */
16384 	enum_type
16385 	  = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
16386 			      /*entering_scope=*/0);
16387 
16388 	for (v = TYPE_VALUES (enum_type);
16389 	     v != NULL_TREE;
16390 	     v = TREE_CHAIN (v))
16391 	  if (TREE_PURPOSE (v) == DECL_NAME (t))
16392 	    return TREE_VALUE (v);
16393 
16394 	  /* We didn't find the name.  That should never happen; if
16395 	     name-lookup found it during preliminary parsing, we
16396 	     should find it again here during instantiation.  */
16397 	gcc_unreachable ();
16398       }
16399       return t;
16400 
16401     case FIELD_DECL:
16402       if (DECL_CONTEXT (t))
16403 	{
16404 	  tree ctx;
16405 
16406 	  ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
16407 				  /*entering_scope=*/1);
16408 	  if (ctx != DECL_CONTEXT (t))
16409 	    {
16410 	      tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
16411 	      if (!r)
16412 		{
16413 		  if (complain & tf_error)
16414 		    error ("using invalid field %qD", t);
16415 		  return error_mark_node;
16416 		}
16417 	      return r;
16418 	    }
16419 	}
16420 
16421       return t;
16422 
16423     case VAR_DECL:
16424     case FUNCTION_DECL:
16425       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
16426 	r = tsubst (t, args, complain, in_decl);
16427       else if (local_variable_p (t)
16428 	       && uses_template_parms (DECL_CONTEXT (t)))
16429 	{
16430 	  r = retrieve_local_specialization (t);
16431 	  if (r == NULL_TREE)
16432 	    {
16433 	      /* First try name lookup to find the instantiation.  */
16434 	      r = lookup_name (DECL_NAME (t));
16435 	      if (r)
16436 		{
16437 		  if (!VAR_P (r))
16438 		    {
16439 		      /* During error-recovery we may find a non-variable,
16440 			 even an OVERLOAD: just bail out and avoid ICEs and
16441 			 duplicate diagnostics (c++/62207).  */
16442 		      gcc_assert (seen_error ());
16443 		      return error_mark_node;
16444 		    }
16445 		  if (!is_capture_proxy (r))
16446 		    {
16447 		      /* Make sure the one we found is the one we want.  */
16448 		      tree ctx = enclosing_instantiation_of (DECL_CONTEXT (t));
16449 		      if (ctx != DECL_CONTEXT (r))
16450 			r = NULL_TREE;
16451 		    }
16452 		}
16453 
16454 	      if (r)
16455 		/* OK */;
16456 	      else
16457 		{
16458 		  /* This can happen for a variable used in a
16459 		     late-specified return type of a local lambda, or for a
16460 		     local static or constant.  Building a new VAR_DECL
16461 		     should be OK in all those cases.  */
16462 		  r = tsubst_decl (t, args, complain);
16463 		  if (local_specializations)
16464 		    /* Avoid infinite recursion (79640).  */
16465 		    register_local_specialization (r, t);
16466 		  if (decl_maybe_constant_var_p (r))
16467 		    {
16468 		      /* We can't call cp_finish_decl, so handle the
16469 			 initializer by hand.  */
16470 		      tree init = tsubst_init (DECL_INITIAL (t), r, args,
16471 					       complain, in_decl);
16472 		      if (!processing_template_decl)
16473 			init = maybe_constant_init (init);
16474 		      if (processing_template_decl
16475 			  ? potential_constant_expression (init)
16476 			  : reduced_constant_expression_p (init))
16477 			DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
16478 			  = TREE_CONSTANT (r) = true;
16479 		      DECL_INITIAL (r) = init;
16480 		      if (tree auto_node = type_uses_auto (TREE_TYPE (r)))
16481 			TREE_TYPE (r)
16482 			  = do_auto_deduction (TREE_TYPE (r), init, auto_node,
16483 					       complain, adc_variable_type);
16484 		    }
16485 		  gcc_assert (cp_unevaluated_operand || TREE_STATIC (r)
16486 			      || decl_constant_var_p (r)
16487 			      || seen_error ());
16488 		  if (!processing_template_decl
16489 		      && !TREE_STATIC (r))
16490 		    r = process_outer_var_ref (r, complain);
16491 		}
16492 	      /* Remember this for subsequent uses.  */
16493 	      if (local_specializations)
16494 		register_local_specialization (r, t);
16495 	    }
16496 	  if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
16497 	    r = argument_pack_select_arg (r);
16498 	}
16499       else
16500 	r = t;
16501       if (!mark_used (r, complain))
16502 	return error_mark_node;
16503       return r;
16504 
16505     case NAMESPACE_DECL:
16506       return t;
16507 
16508     case OVERLOAD:
16509       return t;
16510 
16511     case BASELINK:
16512       return tsubst_baselink (t, current_nonlambda_class_type (),
16513 			      args, complain, in_decl);
16514 
16515     case TEMPLATE_DECL:
16516       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
16517 	return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
16518 		       args, complain, in_decl);
16519       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
16520 	return tsubst (t, args, complain, in_decl);
16521       else if (DECL_CLASS_SCOPE_P (t)
16522 	       && uses_template_parms (DECL_CONTEXT (t)))
16523 	{
16524 	  /* Template template argument like the following example need
16525 	     special treatment:
16526 
16527 	       template <template <class> class TT> struct C {};
16528 	       template <class T> struct D {
16529 		 template <class U> struct E {};
16530 		 C<E> c;				// #1
16531 	       };
16532 	       D<int> d;				// #2
16533 
16534 	     We are processing the template argument `E' in #1 for
16535 	     the template instantiation #2.  Originally, `E' is a
16536 	     TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
16537 	     have to substitute this with one having context `D<int>'.  */
16538 
16539 	  tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
16540 	  if (dependent_scope_p (context))
16541 	    {
16542 	      /* When rewriting a constructor into a deduction guide, a
16543 		 non-dependent name can become dependent, so memtmpl<args>
16544 		 becomes context::template memtmpl<args>.  */
16545 	      tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16546 	      return build_qualified_name (type, context, DECL_NAME (t),
16547 					   /*template*/true);
16548 	    }
16549 	  return lookup_field (context, DECL_NAME(t), 0, false);
16550 	}
16551       else
16552 	/* Ordinary template template argument.  */
16553 	return t;
16554 
16555     case NON_LVALUE_EXPR:
16556     case VIEW_CONVERT_EXPR:
16557 	{
16558 	  /* Handle location wrappers by substituting the wrapped node
16559 	     first, *then* reusing the resulting type.  Doing the type
16560 	     first ensures that we handle template parameters and
16561 	     parameter pack expansions.  */
16562 	  if (location_wrapper_p (t))
16563 	    {
16564 	      tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args,
16565 				      complain, in_decl);
16566 	      return maybe_wrap_with_location (op0, EXPR_LOCATION (t));
16567 	    }
16568 	  tree op = TREE_OPERAND (t, 0);
16569 	  if (code == VIEW_CONVERT_EXPR
16570 	      && TREE_CODE (op) == TEMPLATE_PARM_INDEX)
16571 	    {
16572 	      /* Wrapper to make a C++20 template parameter object const.  */
16573 	      op = tsubst_copy (op, args, complain, in_decl);
16574 	      if (TREE_CODE (op) == TEMPLATE_PARM_INDEX)
16575 		{
16576 		  tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16577 		  return build1 (code, type, op);
16578 		}
16579 	      else
16580 		{
16581 		  gcc_assert (CP_TYPE_CONST_P (TREE_TYPE (op))
16582 			      || (TREE_CODE (op) == IMPLICIT_CONV_EXPR
16583 				  && IMPLICIT_CONV_EXPR_NONTYPE_ARG (op)));
16584 		  return op;
16585 		}
16586 	    }
16587 	  /* force_paren_expr can also create a VIEW_CONVERT_EXPR.  */
16588 	  else if (code == VIEW_CONVERT_EXPR && REF_PARENTHESIZED_P (t))
16589 	    {
16590 	      op = tsubst_copy (op, args, complain, in_decl);
16591 	      op = build1 (code, TREE_TYPE (op), op);
16592 	      REF_PARENTHESIZED_P (op) = true;
16593 	      return op;
16594 	    }
16595 	  /* We shouldn't see any other uses of these in templates.  */
16596 	  gcc_unreachable ();
16597 	}
16598 
16599     case CAST_EXPR:
16600     case REINTERPRET_CAST_EXPR:
16601     case CONST_CAST_EXPR:
16602     case STATIC_CAST_EXPR:
16603     case DYNAMIC_CAST_EXPR:
16604     case IMPLICIT_CONV_EXPR:
16605     case CONVERT_EXPR:
16606     case NOP_EXPR:
16607       {
16608 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16609 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16610 	return build1 (code, type, op0);
16611       }
16612 
16613     case SIZEOF_EXPR:
16614       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
16615 	  || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
16616         {
16617           tree expanded, op = TREE_OPERAND (t, 0);
16618 	  int len = 0;
16619 
16620 	  if (SIZEOF_EXPR_TYPE_P (t))
16621 	    op = TREE_TYPE (op);
16622 
16623 	  ++cp_unevaluated_operand;
16624 	  ++c_inhibit_evaluation_warnings;
16625 	  /* We only want to compute the number of arguments.  */
16626 	  if (PACK_EXPANSION_P (op))
16627 	    expanded = tsubst_pack_expansion (op, args, complain, in_decl);
16628 	  else
16629 	    expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
16630 					     args, complain, in_decl);
16631 	  --cp_unevaluated_operand;
16632 	  --c_inhibit_evaluation_warnings;
16633 
16634 	  if (TREE_CODE (expanded) == TREE_VEC)
16635 	    {
16636 	      len = TREE_VEC_LENGTH (expanded);
16637 	      /* Set TREE_USED for the benefit of -Wunused.  */
16638 	      for (int i = 0; i < len; i++)
16639 		if (DECL_P (TREE_VEC_ELT (expanded, i)))
16640 		  TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
16641 	    }
16642 
16643 	  if (expanded == error_mark_node)
16644 	    return error_mark_node;
16645 	  else if (PACK_EXPANSION_P (expanded)
16646 		   || (TREE_CODE (expanded) == TREE_VEC
16647 		       && pack_expansion_args_count (expanded)))
16648 
16649 	    {
16650 	      if (PACK_EXPANSION_P (expanded))
16651 		/* OK.  */;
16652 	      else if (TREE_VEC_LENGTH (expanded) == 1)
16653 		expanded = TREE_VEC_ELT (expanded, 0);
16654 	      else
16655 		expanded = make_argument_pack (expanded);
16656 
16657 	      if (TYPE_P (expanded))
16658 		return cxx_sizeof_or_alignof_type (input_location,
16659 						   expanded, SIZEOF_EXPR,
16660 						   false,
16661 						   complain & tf_error);
16662 	      else
16663 		return cxx_sizeof_or_alignof_expr (input_location,
16664 						   expanded, SIZEOF_EXPR,
16665                                                    complain & tf_error);
16666 	    }
16667 	  else
16668 	    return build_int_cst (size_type_node, len);
16669         }
16670       if (SIZEOF_EXPR_TYPE_P (t))
16671 	{
16672 	  r = tsubst (TREE_TYPE (TREE_OPERAND (t, 0)),
16673 		      args, complain, in_decl);
16674 	  r = build1 (NOP_EXPR, r, error_mark_node);
16675 	  r = build1 (SIZEOF_EXPR,
16676 		      tsubst (TREE_TYPE (t), args, complain, in_decl), r);
16677 	  SIZEOF_EXPR_TYPE_P (r) = 1;
16678 	  return r;
16679 	}
16680       /* Fall through */
16681 
16682     case INDIRECT_REF:
16683     case NEGATE_EXPR:
16684     case TRUTH_NOT_EXPR:
16685     case BIT_NOT_EXPR:
16686     case ADDR_EXPR:
16687     case UNARY_PLUS_EXPR:      /* Unary + */
16688     case ALIGNOF_EXPR:
16689     case AT_ENCODE_EXPR:
16690     case ARROW_EXPR:
16691     case THROW_EXPR:
16692     case TYPEID_EXPR:
16693     case REALPART_EXPR:
16694     case IMAGPART_EXPR:
16695     case PAREN_EXPR:
16696       {
16697 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16698 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16699 	r = build1 (code, type, op0);
16700 	if (code == ALIGNOF_EXPR)
16701 	  ALIGNOF_EXPR_STD_P (r) = ALIGNOF_EXPR_STD_P (t);
16702 	return r;
16703       }
16704 
16705     case COMPONENT_REF:
16706       {
16707 	tree object;
16708 	tree name;
16709 
16710 	object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16711 	name = TREE_OPERAND (t, 1);
16712 	if (TREE_CODE (name) == BIT_NOT_EXPR)
16713 	  {
16714 	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
16715 				complain, in_decl);
16716 	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
16717 	  }
16718 	else if (TREE_CODE (name) == SCOPE_REF
16719 		 && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
16720 	  {
16721 	    tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
16722 				     complain, in_decl);
16723 	    name = TREE_OPERAND (name, 1);
16724 	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
16725 				complain, in_decl);
16726 	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
16727 	    name = build_qualified_name (/*type=*/NULL_TREE,
16728 					 base, name,
16729 					 /*template_p=*/false);
16730 	  }
16731 	else if (BASELINK_P (name))
16732 	  name = tsubst_baselink (name,
16733 				  non_reference (TREE_TYPE (object)),
16734 				  args, complain,
16735 				  in_decl);
16736 	else
16737 	  name = tsubst_copy (name, args, complain, in_decl);
16738 	return build_nt (COMPONENT_REF, object, name, NULL_TREE);
16739       }
16740 
16741     case PLUS_EXPR:
16742     case MINUS_EXPR:
16743     case MULT_EXPR:
16744     case TRUNC_DIV_EXPR:
16745     case CEIL_DIV_EXPR:
16746     case FLOOR_DIV_EXPR:
16747     case ROUND_DIV_EXPR:
16748     case EXACT_DIV_EXPR:
16749     case BIT_AND_EXPR:
16750     case BIT_IOR_EXPR:
16751     case BIT_XOR_EXPR:
16752     case TRUNC_MOD_EXPR:
16753     case FLOOR_MOD_EXPR:
16754     case TRUTH_ANDIF_EXPR:
16755     case TRUTH_ORIF_EXPR:
16756     case TRUTH_AND_EXPR:
16757     case TRUTH_OR_EXPR:
16758     case RSHIFT_EXPR:
16759     case LSHIFT_EXPR:
16760     case EQ_EXPR:
16761     case NE_EXPR:
16762     case MAX_EXPR:
16763     case MIN_EXPR:
16764     case LE_EXPR:
16765     case GE_EXPR:
16766     case LT_EXPR:
16767     case GT_EXPR:
16768     case COMPOUND_EXPR:
16769     case DOTSTAR_EXPR:
16770     case MEMBER_REF:
16771     case PREDECREMENT_EXPR:
16772     case PREINCREMENT_EXPR:
16773     case POSTDECREMENT_EXPR:
16774     case POSTINCREMENT_EXPR:
16775       {
16776 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16777 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16778 	return build_nt (code, op0, op1);
16779       }
16780 
16781     case SCOPE_REF:
16782       {
16783 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16784 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16785 	return build_qualified_name (/*type=*/NULL_TREE, op0, op1,
16786 				     QUALIFIED_NAME_IS_TEMPLATE (t));
16787       }
16788 
16789     case ARRAY_REF:
16790       {
16791 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16792 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16793 	return build_nt (ARRAY_REF, op0, op1, NULL_TREE, NULL_TREE);
16794       }
16795 
16796     case CALL_EXPR:
16797       {
16798 	int n = VL_EXP_OPERAND_LENGTH (t);
16799 	tree result = build_vl_exp (CALL_EXPR, n);
16800 	int i;
16801 	for (i = 0; i < n; i++)
16802 	  TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
16803 					     complain, in_decl);
16804 	return result;
16805       }
16806 
16807     case COND_EXPR:
16808     case MODOP_EXPR:
16809     case PSEUDO_DTOR_EXPR:
16810     case VEC_PERM_EXPR:
16811       {
16812 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16813 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16814 	tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
16815 	r = build_nt (code, op0, op1, op2);
16816 	TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
16817 	return r;
16818       }
16819 
16820     case NEW_EXPR:
16821       {
16822 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16823 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16824 	tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
16825 	r = build_nt (code, op0, op1, op2);
16826 	NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
16827 	return r;
16828       }
16829 
16830     case DELETE_EXPR:
16831       {
16832 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16833 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16834 	r = build_nt (code, op0, op1);
16835 	DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
16836 	DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
16837 	return r;
16838       }
16839 
16840     case TEMPLATE_ID_EXPR:
16841       {
16842 	/* Substituted template arguments */
16843 	tree fn = TREE_OPERAND (t, 0);
16844 	tree targs = TREE_OPERAND (t, 1);
16845 
16846 	fn = tsubst_copy (fn, args, complain, in_decl);
16847 	if (targs)
16848 	  targs = tsubst_template_args (targs, args, complain, in_decl);
16849 
16850 	return lookup_template_function (fn, targs);
16851       }
16852 
16853     case TREE_LIST:
16854       {
16855 	tree purpose, value, chain;
16856 
16857 	if (t == void_list_node)
16858 	  return t;
16859 
16860 	purpose = TREE_PURPOSE (t);
16861 	if (purpose)
16862 	  purpose = tsubst_copy (purpose, args, complain, in_decl);
16863 	value = TREE_VALUE (t);
16864 	if (value)
16865 	  value = tsubst_copy (value, args, complain, in_decl);
16866 	chain = TREE_CHAIN (t);
16867 	if (chain && chain != void_type_node)
16868 	  chain = tsubst_copy (chain, args, complain, in_decl);
16869 	if (purpose == TREE_PURPOSE (t)
16870 	    && value == TREE_VALUE (t)
16871 	    && chain == TREE_CHAIN (t))
16872 	  return t;
16873 	return tree_cons (purpose, value, chain);
16874       }
16875 
16876     case RECORD_TYPE:
16877     case UNION_TYPE:
16878     case ENUMERAL_TYPE:
16879     case INTEGER_TYPE:
16880     case TEMPLATE_TYPE_PARM:
16881     case TEMPLATE_TEMPLATE_PARM:
16882     case BOUND_TEMPLATE_TEMPLATE_PARM:
16883     case TEMPLATE_PARM_INDEX:
16884     case POINTER_TYPE:
16885     case REFERENCE_TYPE:
16886     case OFFSET_TYPE:
16887     case FUNCTION_TYPE:
16888     case METHOD_TYPE:
16889     case ARRAY_TYPE:
16890     case TYPENAME_TYPE:
16891     case UNBOUND_CLASS_TEMPLATE:
16892     case TYPEOF_TYPE:
16893     case DECLTYPE_TYPE:
16894     case TYPE_DECL:
16895       return tsubst (t, args, complain, in_decl);
16896 
16897     case USING_DECL:
16898       t = DECL_NAME (t);
16899       /* Fall through.  */
16900     case IDENTIFIER_NODE:
16901       if (IDENTIFIER_CONV_OP_P (t))
16902 	{
16903 	  tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16904 	  return make_conv_op_name (new_type);
16905 	}
16906       else
16907 	return t;
16908 
16909     case CONSTRUCTOR:
16910       /* This is handled by tsubst_copy_and_build.  */
16911       gcc_unreachable ();
16912 
16913     case VA_ARG_EXPR:
16914       {
16915 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16916 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16917 	return build_x_va_arg (EXPR_LOCATION (t), op0, type);
16918       }
16919 
16920     case CLEANUP_POINT_EXPR:
16921       /* We shouldn't have built any of these during initial template
16922 	 generation.  Instead, they should be built during instantiation
16923 	 in response to the saved STMT_IS_FULL_EXPR_P setting.  */
16924       gcc_unreachable ();
16925 
16926     case OFFSET_REF:
16927       {
16928 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16929 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16930 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16931 	r = build2 (code, type, op0, op1);
16932 	PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
16933 	if (!mark_used (TREE_OPERAND (r, 1), complain)
16934 	    && !(complain & tf_error))
16935 	  return error_mark_node;
16936 	return r;
16937       }
16938 
16939     case EXPR_PACK_EXPANSION:
16940       error ("invalid use of pack expansion expression");
16941       return error_mark_node;
16942 
16943     case NONTYPE_ARGUMENT_PACK:
16944       error ("use %<...%> to expand argument pack");
16945       return error_mark_node;
16946 
16947     case VOID_CST:
16948       gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
16949       return t;
16950 
16951     case INTEGER_CST:
16952     case REAL_CST:
16953     case COMPLEX_CST:
16954       {
16955 	/* Instantiate any typedefs in the type.  */
16956 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16957 	r = fold_convert (type, t);
16958 	gcc_assert (TREE_CODE (r) == code);
16959 	return r;
16960       }
16961 
16962     case STRING_CST:
16963       {
16964 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16965 	r = t;
16966 	if (type != TREE_TYPE (t))
16967 	  {
16968 	    r = copy_node (t);
16969 	    TREE_TYPE (r) = type;
16970 	  }
16971 	return r;
16972       }
16973 
16974     case PTRMEM_CST:
16975       /* These can sometimes show up in a partial instantiation, but never
16976 	 involve template parms.  */
16977       gcc_assert (!uses_template_parms (t));
16978       return t;
16979 
16980     case UNARY_LEFT_FOLD_EXPR:
16981       return tsubst_unary_left_fold (t, args, complain, in_decl);
16982     case UNARY_RIGHT_FOLD_EXPR:
16983       return tsubst_unary_right_fold (t, args, complain, in_decl);
16984     case BINARY_LEFT_FOLD_EXPR:
16985       return tsubst_binary_left_fold (t, args, complain, in_decl);
16986     case BINARY_RIGHT_FOLD_EXPR:
16987       return tsubst_binary_right_fold (t, args, complain, in_decl);
16988     case PREDICT_EXPR:
16989       return t;
16990 
16991     case DEBUG_BEGIN_STMT:
16992       /* ??? There's no point in copying it for now, but maybe some
16993 	 day it will contain more information, such as a pointer back
16994 	 to the containing function, inlined copy or so.  */
16995       return t;
16996 
16997     case CO_AWAIT_EXPR:
16998       return tsubst_expr (t, args, complain, in_decl,
16999 			  /*integral_constant_expression_p=*/false);
17000       break;
17001 
17002     default:
17003       /* We shouldn't get here, but keep going if !flag_checking.  */
17004       if (flag_checking)
17005 	gcc_unreachable ();
17006       return t;
17007     }
17008 }
17009 
17010 /* Helper function for tsubst_omp_clauses, used for instantiation of
17011    OMP_CLAUSE_DECL of clauses.  */
17012 
17013 static tree
tsubst_omp_clause_decl(tree decl,tree args,tsubst_flags_t complain,tree in_decl,tree * iterator_cache)17014 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
17015 			tree in_decl, tree *iterator_cache)
17016 {
17017   if (decl == NULL_TREE)
17018     return NULL_TREE;
17019 
17020   /* Handle OpenMP iterators.  */
17021   if (TREE_CODE (decl) == TREE_LIST
17022       && TREE_PURPOSE (decl)
17023       && TREE_CODE (TREE_PURPOSE (decl)) == TREE_VEC)
17024     {
17025       tree ret;
17026       if (iterator_cache[0] == TREE_PURPOSE (decl))
17027 	ret = iterator_cache[1];
17028       else
17029 	{
17030 	  tree *tp = &ret;
17031 	  begin_scope (sk_omp, NULL);
17032 	  for (tree it = TREE_PURPOSE (decl); it; it = TREE_CHAIN (it))
17033 	    {
17034 	      *tp = copy_node (it);
17035 	      TREE_VEC_ELT (*tp, 0)
17036 		= tsubst_decl (TREE_VEC_ELT (it, 0), args, complain);
17037 	      TREE_VEC_ELT (*tp, 1)
17038 		= tsubst_expr (TREE_VEC_ELT (it, 1), args, complain, in_decl,
17039 			       /*integral_constant_expression_p=*/false);
17040 	      TREE_VEC_ELT (*tp, 2)
17041 		= tsubst_expr (TREE_VEC_ELT (it, 2), args, complain, in_decl,
17042 			       /*integral_constant_expression_p=*/false);
17043 	      TREE_VEC_ELT (*tp, 3)
17044 		= tsubst_expr (TREE_VEC_ELT (it, 3), args, complain, in_decl,
17045 			       /*integral_constant_expression_p=*/false);
17046 	      TREE_CHAIN (*tp) = NULL_TREE;
17047 	      tp = &TREE_CHAIN (*tp);
17048 	    }
17049 	  TREE_VEC_ELT (ret, 5) = poplevel (1, 1, 0);
17050 	  iterator_cache[0] = TREE_PURPOSE (decl);
17051 	  iterator_cache[1] = ret;
17052 	}
17053       return build_tree_list (ret, tsubst_omp_clause_decl (TREE_VALUE (decl),
17054 							   args, complain,
17055 							   in_decl, NULL));
17056     }
17057 
17058   /* Handle an OpenMP array section represented as a TREE_LIST (or
17059      OMP_CLAUSE_DEPEND_KIND).  An OMP_CLAUSE_DEPEND (with a depend
17060      kind of OMP_CLAUSE_DEPEND_SINK) can also be represented as a
17061      TREE_LIST.  We can handle it exactly the same as an array section
17062      (purpose, value, and a chain), even though the nomenclature
17063      (low_bound, length, etc) is different.  */
17064   if (TREE_CODE (decl) == TREE_LIST)
17065     {
17066       tree low_bound
17067 	= tsubst_expr (TREE_PURPOSE (decl), args, complain, in_decl,
17068 		       /*integral_constant_expression_p=*/false);
17069       tree length = tsubst_expr (TREE_VALUE (decl), args, complain, in_decl,
17070 				 /*integral_constant_expression_p=*/false);
17071       tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
17072 					   in_decl, NULL);
17073       if (TREE_PURPOSE (decl) == low_bound
17074 	  && TREE_VALUE (decl) == length
17075 	  && TREE_CHAIN (decl) == chain)
17076 	return decl;
17077       tree ret = tree_cons (low_bound, length, chain);
17078       OMP_CLAUSE_DEPEND_SINK_NEGATIVE (ret)
17079 	= OMP_CLAUSE_DEPEND_SINK_NEGATIVE (decl);
17080       return ret;
17081     }
17082   tree ret = tsubst_expr (decl, args, complain, in_decl,
17083 			  /*integral_constant_expression_p=*/false);
17084   /* Undo convert_from_reference tsubst_expr could have called.  */
17085   if (decl
17086       && REFERENCE_REF_P (ret)
17087       && !REFERENCE_REF_P (decl))
17088     ret = TREE_OPERAND (ret, 0);
17089   return ret;
17090 }
17091 
17092 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
17093 
17094 static tree
tsubst_omp_clauses(tree clauses,enum c_omp_region_type ort,tree args,tsubst_flags_t complain,tree in_decl)17095 tsubst_omp_clauses (tree clauses, enum c_omp_region_type ort,
17096 		    tree args, tsubst_flags_t complain, tree in_decl)
17097 {
17098   tree new_clauses = NULL_TREE, nc, oc;
17099   tree linear_no_step = NULL_TREE;
17100   tree iterator_cache[2] = { NULL_TREE, NULL_TREE };
17101 
17102   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
17103     {
17104       nc = copy_node (oc);
17105       OMP_CLAUSE_CHAIN (nc) = new_clauses;
17106       new_clauses = nc;
17107 
17108       switch (OMP_CLAUSE_CODE (nc))
17109 	{
17110 	case OMP_CLAUSE_LASTPRIVATE:
17111 	  if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
17112 	    {
17113 	      OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
17114 	      tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
17115 			   in_decl, /*integral_constant_expression_p=*/false);
17116 	      OMP_CLAUSE_LASTPRIVATE_STMT (nc)
17117 		= pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
17118 	    }
17119 	  /* FALLTHRU */
17120 	case OMP_CLAUSE_PRIVATE:
17121 	case OMP_CLAUSE_SHARED:
17122 	case OMP_CLAUSE_FIRSTPRIVATE:
17123 	case OMP_CLAUSE_COPYIN:
17124 	case OMP_CLAUSE_COPYPRIVATE:
17125 	case OMP_CLAUSE_UNIFORM:
17126 	case OMP_CLAUSE_DEPEND:
17127 	case OMP_CLAUSE_FROM:
17128 	case OMP_CLAUSE_TO:
17129 	case OMP_CLAUSE_MAP:
17130 	case OMP_CLAUSE_NONTEMPORAL:
17131 	case OMP_CLAUSE_USE_DEVICE_PTR:
17132 	case OMP_CLAUSE_USE_DEVICE_ADDR:
17133 	case OMP_CLAUSE_IS_DEVICE_PTR:
17134 	case OMP_CLAUSE_INCLUSIVE:
17135 	case OMP_CLAUSE_EXCLUSIVE:
17136 	  OMP_CLAUSE_DECL (nc)
17137 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17138 				      in_decl, iterator_cache);
17139 	  break;
17140 	case OMP_CLAUSE_TILE:
17141 	case OMP_CLAUSE_IF:
17142 	case OMP_CLAUSE_NUM_THREADS:
17143 	case OMP_CLAUSE_SCHEDULE:
17144 	case OMP_CLAUSE_COLLAPSE:
17145 	case OMP_CLAUSE_FINAL:
17146 	case OMP_CLAUSE_DEVICE:
17147 	case OMP_CLAUSE_DIST_SCHEDULE:
17148 	case OMP_CLAUSE_NUM_TEAMS:
17149 	case OMP_CLAUSE_THREAD_LIMIT:
17150 	case OMP_CLAUSE_SAFELEN:
17151 	case OMP_CLAUSE_SIMDLEN:
17152 	case OMP_CLAUSE_NUM_TASKS:
17153 	case OMP_CLAUSE_GRAINSIZE:
17154 	case OMP_CLAUSE_PRIORITY:
17155 	case OMP_CLAUSE_ORDERED:
17156 	case OMP_CLAUSE_HINT:
17157 	case OMP_CLAUSE_NUM_GANGS:
17158 	case OMP_CLAUSE_NUM_WORKERS:
17159 	case OMP_CLAUSE_VECTOR_LENGTH:
17160 	case OMP_CLAUSE_WORKER:
17161 	case OMP_CLAUSE_VECTOR:
17162 	case OMP_CLAUSE_ASYNC:
17163 	case OMP_CLAUSE_WAIT:
17164 	  OMP_CLAUSE_OPERAND (nc, 0)
17165 	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain,
17166 			   in_decl, /*integral_constant_expression_p=*/false);
17167 	  break;
17168 	case OMP_CLAUSE_REDUCTION:
17169 	case OMP_CLAUSE_IN_REDUCTION:
17170 	case OMP_CLAUSE_TASK_REDUCTION:
17171 	  if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
17172 	    {
17173 	      tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
17174 	      if (TREE_CODE (placeholder) == SCOPE_REF)
17175 		{
17176 		  tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
17177 				       complain, in_decl);
17178 		  OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
17179 		    = build_qualified_name (NULL_TREE, scope,
17180 					    TREE_OPERAND (placeholder, 1),
17181 					    false);
17182 		}
17183 	      else
17184 		gcc_assert (identifier_p (placeholder));
17185 	    }
17186 	  OMP_CLAUSE_DECL (nc)
17187 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17188 				      in_decl, NULL);
17189 	  break;
17190 	case OMP_CLAUSE_GANG:
17191 	case OMP_CLAUSE_ALIGNED:
17192 	  OMP_CLAUSE_DECL (nc)
17193 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17194 				      in_decl, NULL);
17195 	  OMP_CLAUSE_OPERAND (nc, 1)
17196 	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain,
17197 			   in_decl, /*integral_constant_expression_p=*/false);
17198 	  break;
17199 	case OMP_CLAUSE_LINEAR:
17200 	  OMP_CLAUSE_DECL (nc)
17201 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17202 				      in_decl, NULL);
17203 	  if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
17204 	    {
17205 	      gcc_assert (!linear_no_step);
17206 	      linear_no_step = nc;
17207 	    }
17208 	  else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
17209 	    OMP_CLAUSE_LINEAR_STEP (nc)
17210 	      = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
17211 					complain, in_decl, NULL);
17212 	  else
17213 	    OMP_CLAUSE_LINEAR_STEP (nc)
17214 	      = tsubst_expr (OMP_CLAUSE_LINEAR_STEP (oc), args, complain,
17215 			     in_decl,
17216 			     /*integral_constant_expression_p=*/false);
17217 	  break;
17218 	case OMP_CLAUSE_NOWAIT:
17219 	case OMP_CLAUSE_DEFAULT:
17220 	case OMP_CLAUSE_UNTIED:
17221 	case OMP_CLAUSE_MERGEABLE:
17222 	case OMP_CLAUSE_INBRANCH:
17223 	case OMP_CLAUSE_NOTINBRANCH:
17224 	case OMP_CLAUSE_PROC_BIND:
17225 	case OMP_CLAUSE_FOR:
17226 	case OMP_CLAUSE_PARALLEL:
17227 	case OMP_CLAUSE_SECTIONS:
17228 	case OMP_CLAUSE_TASKGROUP:
17229 	case OMP_CLAUSE_NOGROUP:
17230 	case OMP_CLAUSE_THREADS:
17231 	case OMP_CLAUSE_SIMD:
17232 	case OMP_CLAUSE_DEFAULTMAP:
17233 	case OMP_CLAUSE_ORDER:
17234 	case OMP_CLAUSE_BIND:
17235 	case OMP_CLAUSE_INDEPENDENT:
17236 	case OMP_CLAUSE_AUTO:
17237 	case OMP_CLAUSE_SEQ:
17238 	case OMP_CLAUSE_IF_PRESENT:
17239 	case OMP_CLAUSE_FINALIZE:
17240 	  break;
17241 	default:
17242 	  gcc_unreachable ();
17243 	}
17244       if ((ort & C_ORT_OMP_DECLARE_SIMD) == C_ORT_OMP)
17245 	switch (OMP_CLAUSE_CODE (nc))
17246 	  {
17247 	  case OMP_CLAUSE_SHARED:
17248 	  case OMP_CLAUSE_PRIVATE:
17249 	  case OMP_CLAUSE_FIRSTPRIVATE:
17250 	  case OMP_CLAUSE_LASTPRIVATE:
17251 	  case OMP_CLAUSE_COPYPRIVATE:
17252 	  case OMP_CLAUSE_LINEAR:
17253 	  case OMP_CLAUSE_REDUCTION:
17254 	  case OMP_CLAUSE_IN_REDUCTION:
17255 	  case OMP_CLAUSE_TASK_REDUCTION:
17256 	  case OMP_CLAUSE_USE_DEVICE_PTR:
17257 	  case OMP_CLAUSE_USE_DEVICE_ADDR:
17258 	  case OMP_CLAUSE_IS_DEVICE_PTR:
17259 	  case OMP_CLAUSE_INCLUSIVE:
17260 	  case OMP_CLAUSE_EXCLUSIVE:
17261 	    /* tsubst_expr on SCOPE_REF results in returning
17262 	       finish_non_static_data_member result.  Undo that here.  */
17263 	    if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
17264 		&& (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
17265 		    == IDENTIFIER_NODE))
17266 	      {
17267 		tree t = OMP_CLAUSE_DECL (nc);
17268 		tree v = t;
17269 		while (v)
17270 		  switch (TREE_CODE (v))
17271 		    {
17272 		    case COMPONENT_REF:
17273 		    case MEM_REF:
17274 		    case INDIRECT_REF:
17275 		    CASE_CONVERT:
17276 		    case POINTER_PLUS_EXPR:
17277 		      v = TREE_OPERAND (v, 0);
17278 		      continue;
17279 		    case PARM_DECL:
17280 		      if (DECL_CONTEXT (v) == current_function_decl
17281 			  && DECL_ARTIFICIAL (v)
17282 			  && DECL_NAME (v) == this_identifier)
17283 			OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
17284 		      /* FALLTHRU */
17285 		    default:
17286 		      v = NULL_TREE;
17287 		      break;
17288 		    }
17289 	      }
17290 	    else if (VAR_P (OMP_CLAUSE_DECL (oc))
17291 		     && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
17292 		     && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
17293 		     && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
17294 		     && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
17295 	      {
17296 		tree decl = OMP_CLAUSE_DECL (nc);
17297 		if (VAR_P (decl))
17298 		  {
17299 		    retrofit_lang_decl (decl);
17300 		    DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
17301 		  }
17302 	      }
17303 	    break;
17304 	  default:
17305 	    break;
17306 	  }
17307     }
17308 
17309   new_clauses = nreverse (new_clauses);
17310   if (ort != C_ORT_OMP_DECLARE_SIMD)
17311     {
17312       new_clauses = finish_omp_clauses (new_clauses, ort);
17313       if (linear_no_step)
17314 	for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
17315 	  if (nc == linear_no_step)
17316 	    {
17317 	      OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
17318 	      break;
17319 	    }
17320     }
17321   return new_clauses;
17322 }
17323 
17324 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
17325 
17326 static tree
tsubst_copy_asm_operands(tree t,tree args,tsubst_flags_t complain,tree in_decl)17327 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
17328 			  tree in_decl)
17329 {
17330 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
17331 
17332   tree purpose, value, chain;
17333 
17334   if (t == NULL)
17335     return t;
17336 
17337   if (TREE_CODE (t) != TREE_LIST)
17338     return tsubst_copy_and_build (t, args, complain, in_decl,
17339 				  /*function_p=*/false,
17340 				  /*integral_constant_expression_p=*/false);
17341 
17342   if (t == void_list_node)
17343     return t;
17344 
17345   purpose = TREE_PURPOSE (t);
17346   if (purpose)
17347     purpose = RECUR (purpose);
17348   value = TREE_VALUE (t);
17349   if (value)
17350     {
17351       if (TREE_CODE (value) != LABEL_DECL)
17352 	value = RECUR (value);
17353       else
17354 	{
17355 	  value = lookup_label (DECL_NAME (value));
17356 	  gcc_assert (TREE_CODE (value) == LABEL_DECL);
17357 	  TREE_USED (value) = 1;
17358 	}
17359     }
17360   chain = TREE_CHAIN (t);
17361   if (chain && chain != void_type_node)
17362     chain = RECUR (chain);
17363   return tree_cons (purpose, value, chain);
17364 #undef RECUR
17365 }
17366 
17367 /* Used to temporarily communicate the list of #pragma omp parallel
17368    clauses to #pragma omp for instantiation if they are combined
17369    together.  */
17370 
17371 static tree *omp_parallel_combined_clauses;
17372 
17373 static tree tsubst_decomp_names (tree, tree, tree, tsubst_flags_t, tree,
17374 				 tree *, unsigned int *);
17375 
17376 /* Substitute one OMP_FOR iterator.  */
17377 
17378 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)17379 tsubst_omp_for_iterator (tree t, int i, tree declv, tree &orig_declv,
17380 			 tree initv, tree condv, tree incrv, tree *clauses,
17381 			 tree args, tsubst_flags_t complain, tree in_decl,
17382 			 bool integral_constant_expression_p)
17383 {
17384 #define RECUR(NODE)				\
17385   tsubst_expr ((NODE), args, complain, in_decl,	\
17386 	       integral_constant_expression_p)
17387   tree decl, init, cond = NULL_TREE, incr = NULL_TREE;
17388   bool ret = false;
17389 
17390   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
17391   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
17392 
17393   decl = TREE_OPERAND (init, 0);
17394   init = TREE_OPERAND (init, 1);
17395   tree decl_expr = NULL_TREE;
17396   bool range_for = TREE_VEC_ELT (OMP_FOR_COND (t), i) == global_namespace;
17397   if (range_for)
17398     {
17399       bool decomp = false;
17400       if (decl != error_mark_node && DECL_HAS_VALUE_EXPR_P (decl))
17401 	{
17402 	  tree v = DECL_VALUE_EXPR (decl);
17403 	  if (TREE_CODE (v) == ARRAY_REF
17404 	      && VAR_P (TREE_OPERAND (v, 0))
17405 	      && DECL_DECOMPOSITION_P (TREE_OPERAND (v, 0)))
17406 	    {
17407 	      tree decomp_first = NULL_TREE;
17408 	      unsigned decomp_cnt = 0;
17409 	      tree d = tsubst_decl (TREE_OPERAND (v, 0), args, complain);
17410 	      maybe_push_decl (d);
17411 	      d = tsubst_decomp_names (d, TREE_OPERAND (v, 0), args, complain,
17412 				       in_decl, &decomp_first, &decomp_cnt);
17413 	      decomp = true;
17414 	      if (d == error_mark_node)
17415 		decl = error_mark_node;
17416 	      else
17417 		for (unsigned int i = 0; i < decomp_cnt; i++)
17418 		  {
17419 		    if (!DECL_HAS_VALUE_EXPR_P (decomp_first))
17420 		      {
17421 			tree v = build_nt (ARRAY_REF, d,
17422 					   size_int (decomp_cnt - i - 1),
17423 					   NULL_TREE, NULL_TREE);
17424 			SET_DECL_VALUE_EXPR (decomp_first, v);
17425 			DECL_HAS_VALUE_EXPR_P (decomp_first) = 1;
17426 		      }
17427 		    fit_decomposition_lang_decl (decomp_first, d);
17428 		    decomp_first = DECL_CHAIN (decomp_first);
17429 		  }
17430 	    }
17431 	}
17432       decl = tsubst_decl (decl, args, complain);
17433       if (!decomp)
17434 	maybe_push_decl (decl);
17435     }
17436   else if (init && TREE_CODE (init) == DECL_EXPR)
17437     {
17438       /* We need to jump through some hoops to handle declarations in the
17439 	 init-statement, since we might need to handle auto deduction,
17440 	 but we need to keep control of initialization.  */
17441       decl_expr = init;
17442       init = DECL_INITIAL (DECL_EXPR_DECL (init));
17443       decl = tsubst_decl (decl, args, complain);
17444     }
17445   else
17446     {
17447       if (TREE_CODE (decl) == SCOPE_REF)
17448 	{
17449 	  decl = RECUR (decl);
17450 	  if (TREE_CODE (decl) == COMPONENT_REF)
17451 	    {
17452 	      tree v = decl;
17453 	      while (v)
17454 		switch (TREE_CODE (v))
17455 		  {
17456 		  case COMPONENT_REF:
17457 		  case MEM_REF:
17458 		  case INDIRECT_REF:
17459 		  CASE_CONVERT:
17460 		  case POINTER_PLUS_EXPR:
17461 		    v = TREE_OPERAND (v, 0);
17462 		    continue;
17463 		  case PARM_DECL:
17464 		    if (DECL_CONTEXT (v) == current_function_decl
17465 			&& DECL_ARTIFICIAL (v)
17466 			&& DECL_NAME (v) == this_identifier)
17467 		      {
17468 			decl = TREE_OPERAND (decl, 1);
17469 			decl = omp_privatize_field (decl, false);
17470 		      }
17471 		    /* FALLTHRU */
17472 		  default:
17473 		    v = NULL_TREE;
17474 		    break;
17475 		  }
17476 	    }
17477 	}
17478       else
17479 	decl = RECUR (decl);
17480     }
17481   init = RECUR (init);
17482 
17483   if (orig_declv && OMP_FOR_ORIG_DECLS (t))
17484     {
17485       tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
17486       if (TREE_CODE (o) == TREE_LIST)
17487 	TREE_VEC_ELT (orig_declv, i)
17488 	  = tree_cons (RECUR (TREE_PURPOSE (o)),
17489 		       RECUR (TREE_VALUE (o)),
17490 		       NULL_TREE);
17491       else
17492 	TREE_VEC_ELT (orig_declv, i) = RECUR (o);
17493     }
17494 
17495   if (range_for)
17496     {
17497       tree this_pre_body = NULL_TREE;
17498       tree orig_init = NULL_TREE;
17499       tree orig_decl = NULL_TREE;
17500       cp_convert_omp_range_for (this_pre_body, NULL, decl, orig_decl, init,
17501 				orig_init, cond, incr);
17502       if (orig_decl)
17503 	{
17504 	  if (orig_declv == NULL_TREE)
17505 	    orig_declv = copy_node (declv);
17506 	  TREE_VEC_ELT (orig_declv, i) = orig_decl;
17507 	  ret = true;
17508 	}
17509       else if (orig_declv)
17510 	TREE_VEC_ELT (orig_declv, i) = decl;
17511     }
17512 
17513   tree auto_node = type_uses_auto (TREE_TYPE (decl));
17514   if (!range_for && auto_node && init)
17515     TREE_TYPE (decl)
17516       = do_auto_deduction (TREE_TYPE (decl), init, auto_node, complain);
17517 
17518   gcc_assert (!type_dependent_expression_p (decl));
17519 
17520   if (!CLASS_TYPE_P (TREE_TYPE (decl)) || range_for)
17521     {
17522       if (decl_expr)
17523 	{
17524 	  /* Declare the variable, but don't let that initialize it.  */
17525 	  tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
17526 	  DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
17527 	  RECUR (decl_expr);
17528 	  DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
17529 	}
17530 
17531       if (!range_for)
17532 	{
17533 	  cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
17534 	  incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
17535 	  if (TREE_CODE (incr) == MODIFY_EXPR)
17536 	    {
17537 	      tree lhs = RECUR (TREE_OPERAND (incr, 0));
17538 	      tree rhs = RECUR (TREE_OPERAND (incr, 1));
17539 	      incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
17540 					  NOP_EXPR, rhs, complain);
17541 	    }
17542 	  else
17543 	    incr = RECUR (incr);
17544 	  if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
17545 	    TREE_VEC_ELT (orig_declv, i) = decl;
17546 	}
17547       TREE_VEC_ELT (declv, i) = decl;
17548       TREE_VEC_ELT (initv, i) = init;
17549       TREE_VEC_ELT (condv, i) = cond;
17550       TREE_VEC_ELT (incrv, i) = incr;
17551       return ret;
17552     }
17553 
17554   if (decl_expr)
17555     {
17556       /* Declare and initialize the variable.  */
17557       RECUR (decl_expr);
17558       init = NULL_TREE;
17559     }
17560   else if (init)
17561     {
17562       tree *pc;
17563       int j;
17564       for (j = ((omp_parallel_combined_clauses == NULL
17565 		|| TREE_CODE (t) == OMP_LOOP) ? 1 : 0); j < 2; j++)
17566 	{
17567 	  for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
17568 	    {
17569 	      if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
17570 		  && OMP_CLAUSE_DECL (*pc) == decl)
17571 		break;
17572 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
17573 		       && OMP_CLAUSE_DECL (*pc) == decl)
17574 		{
17575 		  if (j)
17576 		    break;
17577 		  /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES.  */
17578 		  tree c = *pc;
17579 		  *pc = OMP_CLAUSE_CHAIN (c);
17580 		  OMP_CLAUSE_CHAIN (c) = *clauses;
17581 		  *clauses = c;
17582 		}
17583 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
17584 		       && OMP_CLAUSE_DECL (*pc) == decl)
17585 		{
17586 		  error ("iteration variable %qD should not be firstprivate",
17587 			 decl);
17588 		  *pc = OMP_CLAUSE_CHAIN (*pc);
17589 		}
17590 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
17591 		       && OMP_CLAUSE_DECL (*pc) == decl)
17592 		{
17593 		  error ("iteration variable %qD should not be reduction",
17594 			 decl);
17595 		  *pc = OMP_CLAUSE_CHAIN (*pc);
17596 		}
17597 	      else
17598 		pc = &OMP_CLAUSE_CHAIN (*pc);
17599 	    }
17600 	  if (*pc)
17601 	    break;
17602 	}
17603       if (*pc == NULL_TREE)
17604 	{
17605 	  tree c = build_omp_clause (input_location,
17606 				     TREE_CODE (t) == OMP_LOOP
17607 				     ? OMP_CLAUSE_LASTPRIVATE
17608 				     : OMP_CLAUSE_PRIVATE);
17609 	  OMP_CLAUSE_DECL (c) = decl;
17610 	  c = finish_omp_clauses (c, C_ORT_OMP);
17611 	  if (c)
17612 	    {
17613 	      OMP_CLAUSE_CHAIN (c) = *clauses;
17614 	      *clauses = c;
17615 	    }
17616 	}
17617     }
17618   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
17619   if (COMPARISON_CLASS_P (cond))
17620     {
17621       tree op0 = RECUR (TREE_OPERAND (cond, 0));
17622       tree op1 = RECUR (TREE_OPERAND (cond, 1));
17623       cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
17624     }
17625   else
17626     cond = RECUR (cond);
17627   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
17628   switch (TREE_CODE (incr))
17629     {
17630     case PREINCREMENT_EXPR:
17631     case PREDECREMENT_EXPR:
17632     case POSTINCREMENT_EXPR:
17633     case POSTDECREMENT_EXPR:
17634       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
17635 		     RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
17636       break;
17637     case MODIFY_EXPR:
17638       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
17639 	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
17640 	{
17641 	  tree rhs = TREE_OPERAND (incr, 1);
17642 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
17643 	  tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
17644 	  tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
17645 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
17646 			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
17647 				 rhs0, rhs1));
17648 	}
17649       else
17650 	incr = RECUR (incr);
17651       break;
17652     case MODOP_EXPR:
17653       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
17654 	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
17655 	{
17656 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
17657 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
17658 			 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
17659 				 TREE_TYPE (decl), lhs,
17660 				 RECUR (TREE_OPERAND (incr, 2))));
17661 	}
17662       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
17663 	       && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
17664 		   || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
17665 	{
17666 	  tree rhs = TREE_OPERAND (incr, 2);
17667 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
17668 	  tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
17669 	  tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
17670 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
17671 			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
17672 				 rhs0, rhs1));
17673 	}
17674       else
17675 	incr = RECUR (incr);
17676       break;
17677     default:
17678       incr = RECUR (incr);
17679       break;
17680     }
17681 
17682   if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
17683     TREE_VEC_ELT (orig_declv, i) = decl;
17684   TREE_VEC_ELT (declv, i) = decl;
17685   TREE_VEC_ELT (initv, i) = init;
17686   TREE_VEC_ELT (condv, i) = cond;
17687   TREE_VEC_ELT (incrv, i) = incr;
17688   return false;
17689 #undef RECUR
17690 }
17691 
17692 /* Helper function of tsubst_expr, find OMP_TEAMS inside
17693    of OMP_TARGET's body.  */
17694 
17695 static tree
tsubst_find_omp_teams(tree * tp,int * walk_subtrees,void *)17696 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
17697 {
17698   *walk_subtrees = 0;
17699   switch (TREE_CODE (*tp))
17700     {
17701     case OMP_TEAMS:
17702       return *tp;
17703     case BIND_EXPR:
17704     case STATEMENT_LIST:
17705       *walk_subtrees = 1;
17706       break;
17707     default:
17708       break;
17709     }
17710   return NULL_TREE;
17711 }
17712 
17713 /* Helper function for tsubst_expr.  For decomposition declaration
17714    artificial base DECL, which is tsubsted PATTERN_DECL, tsubst
17715    also the corresponding decls representing the identifiers
17716    of the decomposition declaration.  Return DECL if successful
17717    or error_mark_node otherwise, set *FIRST to the first decl
17718    in the list chained through DECL_CHAIN and *CNT to the number
17719    of such decls.  */
17720 
17721 static tree
tsubst_decomp_names(tree decl,tree pattern_decl,tree args,tsubst_flags_t complain,tree in_decl,tree * first,unsigned int * cnt)17722 tsubst_decomp_names (tree decl, tree pattern_decl, tree args,
17723 		     tsubst_flags_t complain, tree in_decl, tree *first,
17724 		     unsigned int *cnt)
17725 {
17726   tree decl2, decl3, prev = decl;
17727   *cnt = 0;
17728   gcc_assert (DECL_NAME (decl) == NULL_TREE);
17729   for (decl2 = DECL_CHAIN (pattern_decl);
17730        decl2
17731        && VAR_P (decl2)
17732        && DECL_DECOMPOSITION_P (decl2)
17733        && DECL_NAME (decl2);
17734        decl2 = DECL_CHAIN (decl2))
17735     {
17736       if (TREE_TYPE (decl2) == error_mark_node && *cnt == 0)
17737 	{
17738 	  gcc_assert (errorcount);
17739 	  return error_mark_node;
17740 	}
17741       (*cnt)++;
17742       gcc_assert (DECL_DECOMP_BASE (decl2) == pattern_decl);
17743       gcc_assert (DECL_HAS_VALUE_EXPR_P (decl2));
17744       tree v = DECL_VALUE_EXPR (decl2);
17745       DECL_HAS_VALUE_EXPR_P (decl2) = 0;
17746       SET_DECL_VALUE_EXPR (decl2, NULL_TREE);
17747       decl3 = tsubst (decl2, args, complain, in_decl);
17748       SET_DECL_VALUE_EXPR (decl2, v);
17749       DECL_HAS_VALUE_EXPR_P (decl2) = 1;
17750       if (VAR_P (decl3))
17751 	DECL_TEMPLATE_INSTANTIATED (decl3) = 1;
17752       else
17753 	{
17754 	  gcc_assert (errorcount);
17755 	  decl = error_mark_node;
17756 	  continue;
17757 	}
17758       maybe_push_decl (decl3);
17759       if (error_operand_p (decl3))
17760 	decl = error_mark_node;
17761       else if (decl != error_mark_node
17762 	       && DECL_CHAIN (decl3) != prev
17763 	       && decl != prev)
17764 	{
17765 	  gcc_assert (errorcount);
17766 	  decl = error_mark_node;
17767 	}
17768       else
17769 	prev = decl3;
17770     }
17771   *first = prev;
17772   return decl;
17773 }
17774 
17775 /* Return the proper local_specialization for init-capture pack DECL.  */
17776 
17777 static tree
lookup_init_capture_pack(tree decl)17778 lookup_init_capture_pack (tree decl)
17779 {
17780   /* We handle normal pack captures by forwarding to the specialization of the
17781      captured parameter.  We can't do that for pack init-captures; we need them
17782      to have their own local_specialization.  We created the individual
17783      VAR_DECLs (if any) under build_capture_proxy, and we need to collect them
17784      when we process the DECL_EXPR for the pack init-capture in the template.
17785      So, how do we find them?  We don't know the capture proxy pack when
17786      building the individual resulting proxies, and we don't know the
17787      individual proxies when instantiating the pack.  What we have in common is
17788      the FIELD_DECL.
17789 
17790      So...when we instantiate the FIELD_DECL, we stick the result in
17791      local_specializations.  Then at the DECL_EXPR we look up that result, see
17792      how many elements it has, synthesize the names, and look them up.  */
17793 
17794   tree cname = DECL_NAME (decl);
17795   tree val = DECL_VALUE_EXPR (decl);
17796   tree field = TREE_OPERAND (val, 1);
17797   gcc_assert (TREE_CODE (field) == FIELD_DECL);
17798   tree fpack = retrieve_local_specialization (field);
17799   if (fpack == error_mark_node)
17800     return error_mark_node;
17801 
17802   int len = 1;
17803   tree vec = NULL_TREE;
17804   tree r = NULL_TREE;
17805   if (TREE_CODE (fpack) == TREE_VEC)
17806     {
17807       len = TREE_VEC_LENGTH (fpack);
17808       vec = make_tree_vec (len);
17809       r = make_node (NONTYPE_ARGUMENT_PACK);
17810       SET_ARGUMENT_PACK_ARGS (r, vec);
17811     }
17812   for (int i = 0; i < len; ++i)
17813     {
17814       tree ename = vec ? make_ith_pack_parameter_name (cname, i) : cname;
17815       tree elt = lookup_name_real (ename, 0, 0, true, 0, LOOKUP_NORMAL);
17816       if (vec)
17817 	TREE_VEC_ELT (vec, i) = elt;
17818       else
17819 	r = elt;
17820     }
17821   return r;
17822 }
17823 
17824 /* Like tsubst_copy for expressions, etc. but also does semantic
17825    processing.  */
17826 
17827 tree
tsubst_expr(tree t,tree args,tsubst_flags_t complain,tree in_decl,bool integral_constant_expression_p)17828 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
17829 	     bool integral_constant_expression_p)
17830 {
17831 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
17832 #define RECUR(NODE)				\
17833   tsubst_expr ((NODE), args, complain, in_decl,	\
17834 	       integral_constant_expression_p)
17835 
17836   tree stmt, tmp;
17837   tree r;
17838   location_t loc;
17839 
17840   if (t == NULL_TREE || t == error_mark_node)
17841     return t;
17842 
17843   loc = input_location;
17844   if (location_t eloc = cp_expr_location (t))
17845     input_location = eloc;
17846   if (STATEMENT_CODE_P (TREE_CODE (t)))
17847     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
17848 
17849   switch (TREE_CODE (t))
17850     {
17851     case STATEMENT_LIST:
17852       {
17853 	tree_stmt_iterator i;
17854 	for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
17855 	  RECUR (tsi_stmt (i));
17856 	break;
17857       }
17858 
17859     case CTOR_INITIALIZER:
17860       finish_mem_initializers (tsubst_initializer_list
17861 			       (TREE_OPERAND (t, 0), args));
17862       break;
17863 
17864     case RETURN_EXPR:
17865       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
17866       break;
17867 
17868     case CO_RETURN_EXPR:
17869       finish_co_return_stmt (input_location, RECUR (TREE_OPERAND (t, 0)));
17870       break;
17871 
17872     case CO_YIELD_EXPR:
17873       stmt = finish_co_yield_expr (input_location,
17874 				   RECUR (TREE_OPERAND (t, 0)));
17875       RETURN (stmt);
17876       break;
17877 
17878     case CO_AWAIT_EXPR:
17879       stmt = finish_co_await_expr (input_location,
17880 				   RECUR (TREE_OPERAND (t, 0)));
17881       RETURN (stmt);
17882       break;
17883 
17884     case EXPR_STMT:
17885       tmp = RECUR (EXPR_STMT_EXPR (t));
17886       if (EXPR_STMT_STMT_EXPR_RESULT (t))
17887 	finish_stmt_expr_expr (tmp, cur_stmt_expr);
17888       else
17889 	finish_expr_stmt (tmp);
17890       break;
17891 
17892     case USING_STMT:
17893       finish_using_directive (USING_STMT_NAMESPACE (t), /*attribs=*/NULL_TREE);
17894       break;
17895 
17896     case DECL_EXPR:
17897       {
17898 	tree decl, pattern_decl;
17899 	tree init;
17900 
17901 	pattern_decl = decl = DECL_EXPR_DECL (t);
17902 	if (TREE_CODE (decl) == LABEL_DECL)
17903 	  finish_label_decl (DECL_NAME (decl));
17904 	else if (TREE_CODE (decl) == USING_DECL)
17905 	  {
17906 	    tree scope = USING_DECL_SCOPE (decl);
17907 	    tree name = DECL_NAME (decl);
17908 
17909 	    scope = tsubst (scope, args, complain, in_decl);
17910 	    finish_nonmember_using_decl (scope, name);
17911 	  }
17912 	else if (is_capture_proxy (decl)
17913 		 && !DECL_TEMPLATE_INSTANTIATION (current_function_decl))
17914 	  {
17915 	    /* We're in tsubst_lambda_expr, we've already inserted a new
17916 	       capture proxy, so look it up and register it.  */
17917 	    tree inst;
17918 	    if (!DECL_PACK_P (decl))
17919 	      {
17920 		inst = lookup_name_real (DECL_NAME (decl), /*prefer_type*/0,
17921 					 /*nonclass*/1, /*block_p=*/true,
17922 					 /*ns_only*/0, LOOKUP_HIDDEN);
17923 		gcc_assert (inst != decl && is_capture_proxy (inst));
17924 	      }
17925 	    else if (is_normal_capture_proxy (decl))
17926 	      {
17927 		inst = (retrieve_local_specialization
17928 			(DECL_CAPTURED_VARIABLE (decl)));
17929 		gcc_assert (TREE_CODE (inst) == NONTYPE_ARGUMENT_PACK
17930 			    || DECL_PACK_P (inst));
17931 	      }
17932 	    else
17933 	      inst = lookup_init_capture_pack (decl);
17934 
17935 	    register_local_specialization (inst, decl);
17936 	    break;
17937 	  }
17938 	else if (DECL_PRETTY_FUNCTION_P (decl))
17939 	  decl = make_fname_decl (DECL_SOURCE_LOCATION (decl),
17940 				  DECL_NAME (decl),
17941 				  true/*DECL_PRETTY_FUNCTION_P (decl)*/);
17942 	else if (DECL_IMPLICIT_TYPEDEF_P (decl)
17943 		 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
17944 	  /* Don't copy the old closure; we'll create a new one in
17945 	     tsubst_lambda_expr.  */
17946 	  break;
17947 	else
17948 	  {
17949 	    init = DECL_INITIAL (decl);
17950 	    /* The following tsubst call will clear the DECL_TEMPLATE_INFO
17951 	       for local variables, so save if DECL was declared constinit.  */
17952 	    const bool constinit_p
17953 	      = (VAR_P (decl)
17954 		 && DECL_LANG_SPECIFIC (decl)
17955 		 && DECL_TEMPLATE_INFO (decl)
17956 		 && TINFO_VAR_DECLARED_CONSTINIT (DECL_TEMPLATE_INFO (decl)));
17957 	    decl = tsubst (decl, args, complain, in_decl);
17958 	    if (decl != error_mark_node)
17959 	      {
17960 		/* By marking the declaration as instantiated, we avoid
17961 		   trying to instantiate it.  Since instantiate_decl can't
17962 		   handle local variables, and since we've already done
17963 		   all that needs to be done, that's the right thing to
17964 		   do.  */
17965 		if (VAR_P (decl))
17966 		  DECL_TEMPLATE_INSTANTIATED (decl) = 1;
17967 		if (VAR_P (decl) && !DECL_NAME (decl)
17968 		    && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
17969 		  /* Anonymous aggregates are a special case.  */
17970 		  finish_anon_union (decl);
17971 		else if (is_capture_proxy (DECL_EXPR_DECL (t)))
17972 		  {
17973 		    DECL_CONTEXT (decl) = current_function_decl;
17974 		    if (DECL_NAME (decl) == this_identifier)
17975 		      {
17976 			tree lam = DECL_CONTEXT (current_function_decl);
17977 			lam = CLASSTYPE_LAMBDA_EXPR (lam);
17978 			LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
17979 		      }
17980 		    insert_capture_proxy (decl);
17981 		  }
17982 		else if (DECL_IMPLICIT_TYPEDEF_P (t))
17983 		  /* We already did a pushtag.  */;
17984 		else if (TREE_CODE (decl) == FUNCTION_DECL
17985 			 && DECL_OMP_DECLARE_REDUCTION_P (decl)
17986 			 && DECL_FUNCTION_SCOPE_P (pattern_decl))
17987 		  {
17988 		    DECL_CONTEXT (decl) = NULL_TREE;
17989 		    pushdecl (decl);
17990 		    DECL_CONTEXT (decl) = current_function_decl;
17991 		    cp_check_omp_declare_reduction (decl);
17992 		  }
17993 		else
17994 		  {
17995 		    bool const_init = false;
17996 		    unsigned int cnt = 0;
17997 		    tree first = NULL_TREE, ndecl = error_mark_node;
17998 		    maybe_push_decl (decl);
17999 
18000 		    if (VAR_P (decl)
18001 			&& DECL_DECOMPOSITION_P (decl)
18002 			&& TREE_TYPE (pattern_decl) != error_mark_node)
18003 		      ndecl = tsubst_decomp_names (decl, pattern_decl, args,
18004 						   complain, in_decl, &first,
18005 						   &cnt);
18006 
18007 		    init = tsubst_init (init, decl, args, complain, in_decl);
18008 
18009 		    if (VAR_P (decl))
18010 		      const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
18011 				    (pattern_decl));
18012 
18013 		    if (ndecl != error_mark_node)
18014 		      cp_maybe_mangle_decomp (ndecl, first, cnt);
18015 
18016 		    cp_finish_decl (decl, init, const_init, NULL_TREE,
18017 				    constinit_p ? LOOKUP_CONSTINIT : 0);
18018 
18019 		    if (ndecl != error_mark_node)
18020 		      cp_finish_decomp (ndecl, first, cnt);
18021 		  }
18022 	      }
18023 	  }
18024 
18025 	break;
18026       }
18027 
18028     case FOR_STMT:
18029       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
18030       RECUR (FOR_INIT_STMT (t));
18031       finish_init_stmt (stmt);
18032       tmp = RECUR (FOR_COND (t));
18033       finish_for_cond (tmp, stmt, false, 0);
18034       tmp = RECUR (FOR_EXPR (t));
18035       finish_for_expr (tmp, stmt);
18036       {
18037 	bool prev = note_iteration_stmt_body_start ();
18038 	RECUR (FOR_BODY (t));
18039 	note_iteration_stmt_body_end (prev);
18040       }
18041       finish_for_stmt (stmt);
18042       break;
18043 
18044     case RANGE_FOR_STMT:
18045       {
18046 	/* Construct another range_for, if this is not a final
18047 	   substitution (for inside a generic lambda of a
18048 	   template).  Otherwise convert to a regular for.  */
18049         tree decl, expr;
18050         stmt = (processing_template_decl
18051 		? begin_range_for_stmt (NULL_TREE, NULL_TREE)
18052 		: begin_for_stmt (NULL_TREE, NULL_TREE));
18053 	RECUR (RANGE_FOR_INIT_STMT (t));
18054         decl = RANGE_FOR_DECL (t);
18055         decl = tsubst (decl, args, complain, in_decl);
18056         maybe_push_decl (decl);
18057         expr = RECUR (RANGE_FOR_EXPR (t));
18058 
18059 	tree decomp_first = NULL_TREE;
18060 	unsigned decomp_cnt = 0;
18061 	if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
18062 	  decl = tsubst_decomp_names (decl, RANGE_FOR_DECL (t), args,
18063 				      complain, in_decl,
18064 				      &decomp_first, &decomp_cnt);
18065 
18066 	if (processing_template_decl)
18067 	  {
18068 	    RANGE_FOR_IVDEP (stmt) = RANGE_FOR_IVDEP (t);
18069 	    RANGE_FOR_UNROLL (stmt) = RANGE_FOR_UNROLL (t);
18070 	    finish_range_for_decl (stmt, decl, expr);
18071 	    if (decomp_first && decl != error_mark_node)
18072 	      cp_finish_decomp (decl, decomp_first, decomp_cnt);
18073 	  }
18074 	else
18075 	  {
18076 	    unsigned short unroll = (RANGE_FOR_UNROLL (t)
18077 				     ? tree_to_uhwi (RANGE_FOR_UNROLL (t)) : 0);
18078 	    stmt = cp_convert_range_for (stmt, decl, expr,
18079 					 decomp_first, decomp_cnt,
18080 					 RANGE_FOR_IVDEP (t), unroll);
18081 	  }
18082 
18083 	bool prev = note_iteration_stmt_body_start ();
18084         RECUR (RANGE_FOR_BODY (t));
18085 	note_iteration_stmt_body_end (prev);
18086         finish_for_stmt (stmt);
18087       }
18088       break;
18089 
18090     case WHILE_STMT:
18091       stmt = begin_while_stmt ();
18092       tmp = RECUR (WHILE_COND (t));
18093       finish_while_stmt_cond (tmp, stmt, false, 0);
18094       {
18095 	bool prev = note_iteration_stmt_body_start ();
18096 	RECUR (WHILE_BODY (t));
18097 	note_iteration_stmt_body_end (prev);
18098       }
18099       finish_while_stmt (stmt);
18100       break;
18101 
18102     case DO_STMT:
18103       stmt = begin_do_stmt ();
18104       {
18105 	bool prev = note_iteration_stmt_body_start ();
18106 	RECUR (DO_BODY (t));
18107 	note_iteration_stmt_body_end (prev);
18108       }
18109       finish_do_body (stmt);
18110       tmp = RECUR (DO_COND (t));
18111       finish_do_stmt (tmp, stmt, false, 0);
18112       break;
18113 
18114     case IF_STMT:
18115       stmt = begin_if_stmt ();
18116       IF_STMT_CONSTEXPR_P (stmt) = IF_STMT_CONSTEXPR_P (t);
18117       if (IF_STMT_CONSTEXPR_P (t))
18118 	args = add_extra_args (IF_STMT_EXTRA_ARGS (t), args);
18119       tmp = RECUR (IF_COND (t));
18120       tmp = finish_if_stmt_cond (tmp, stmt);
18121       if (IF_STMT_CONSTEXPR_P (t)
18122 	  && instantiation_dependent_expression_p (tmp))
18123 	{
18124 	  /* We're partially instantiating a generic lambda, but the condition
18125 	     of the constexpr if is still dependent.  Don't substitute into the
18126 	     branches now, just remember the template arguments.  */
18127 	  do_poplevel (IF_SCOPE (stmt));
18128 	  IF_COND (stmt) = IF_COND (t);
18129 	  THEN_CLAUSE (stmt) = THEN_CLAUSE (t);
18130 	  ELSE_CLAUSE (stmt) = ELSE_CLAUSE (t);
18131 	  IF_STMT_EXTRA_ARGS (stmt) = build_extra_args (t, args, complain);
18132 	  add_stmt (stmt);
18133 	  break;
18134 	}
18135       if (IF_STMT_CONSTEXPR_P (t) && integer_zerop (tmp))
18136 	/* Don't instantiate the THEN_CLAUSE. */;
18137       else
18138 	{
18139 	  tree folded = fold_non_dependent_expr (tmp, complain);
18140 	  bool inhibit = integer_zerop (folded);
18141 	  if (inhibit)
18142 	    ++c_inhibit_evaluation_warnings;
18143 	  RECUR (THEN_CLAUSE (t));
18144 	  if (inhibit)
18145 	    --c_inhibit_evaluation_warnings;
18146 	}
18147       finish_then_clause (stmt);
18148 
18149       if (IF_STMT_CONSTEXPR_P (t) && integer_nonzerop (tmp))
18150 	/* Don't instantiate the ELSE_CLAUSE. */;
18151       else if (ELSE_CLAUSE (t))
18152 	{
18153 	  tree folded = fold_non_dependent_expr (tmp, complain);
18154 	  bool inhibit = integer_nonzerop (folded);
18155 	  begin_else_clause (stmt);
18156 	  if (inhibit)
18157 	    ++c_inhibit_evaluation_warnings;
18158 	  RECUR (ELSE_CLAUSE (t));
18159 	  if (inhibit)
18160 	    --c_inhibit_evaluation_warnings;
18161 	  finish_else_clause (stmt);
18162 	}
18163 
18164       finish_if_stmt (stmt);
18165       break;
18166 
18167     case BIND_EXPR:
18168       if (BIND_EXPR_BODY_BLOCK (t))
18169 	stmt = begin_function_body ();
18170       else
18171 	stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
18172 				    ? BCS_TRY_BLOCK : 0);
18173 
18174       RECUR (BIND_EXPR_BODY (t));
18175 
18176       if (BIND_EXPR_BODY_BLOCK (t))
18177 	finish_function_body (stmt);
18178       else
18179 	finish_compound_stmt (stmt);
18180       break;
18181 
18182     case BREAK_STMT:
18183       finish_break_stmt ();
18184       break;
18185 
18186     case CONTINUE_STMT:
18187       finish_continue_stmt ();
18188       break;
18189 
18190     case SWITCH_STMT:
18191       stmt = begin_switch_stmt ();
18192       tmp = RECUR (SWITCH_STMT_COND (t));
18193       finish_switch_cond (tmp, stmt);
18194       RECUR (SWITCH_STMT_BODY (t));
18195       finish_switch_stmt (stmt);
18196       break;
18197 
18198     case CASE_LABEL_EXPR:
18199       {
18200 	tree decl = CASE_LABEL (t);
18201 	tree low = RECUR (CASE_LOW (t));
18202 	tree high = RECUR (CASE_HIGH (t));
18203 	tree l = finish_case_label (EXPR_LOCATION (t), low, high);
18204 	if (l && TREE_CODE (l) == CASE_LABEL_EXPR)
18205 	  {
18206 	    tree label = CASE_LABEL (l);
18207 	    FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
18208 	    if (DECL_ATTRIBUTES (decl) != NULL_TREE)
18209 	      cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
18210 	  }
18211       }
18212       break;
18213 
18214     case LABEL_EXPR:
18215       {
18216 	tree decl = LABEL_EXPR_LABEL (t);
18217 	tree label;
18218 
18219 	label = finish_label_stmt (DECL_NAME (decl));
18220 	if (TREE_CODE (label) == LABEL_DECL)
18221 	  FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
18222 	if (DECL_ATTRIBUTES (decl) != NULL_TREE)
18223 	  cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
18224       }
18225       break;
18226 
18227     case GOTO_EXPR:
18228       tmp = GOTO_DESTINATION (t);
18229       if (TREE_CODE (tmp) != LABEL_DECL)
18230 	/* Computed goto's must be tsubst'd into.  On the other hand,
18231 	   non-computed gotos must not be; the identifier in question
18232 	   will have no binding.  */
18233 	tmp = RECUR (tmp);
18234       else
18235 	tmp = DECL_NAME (tmp);
18236       finish_goto_stmt (tmp);
18237       break;
18238 
18239     case ASM_EXPR:
18240       {
18241 	tree string = RECUR (ASM_STRING (t));
18242 	tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
18243 						 complain, in_decl);
18244 	tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
18245 						complain, in_decl);
18246 	tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
18247 	 					  complain, in_decl);
18248 	tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
18249 						complain, in_decl);
18250 	tmp = finish_asm_stmt (EXPR_LOCATION (t), ASM_VOLATILE_P (t), string,
18251 			       outputs, inputs, clobbers, labels,
18252 			       ASM_INLINE_P (t));
18253 	tree asm_expr = tmp;
18254 	if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
18255 	  asm_expr = TREE_OPERAND (asm_expr, 0);
18256 	ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
18257       }
18258       break;
18259 
18260     case TRY_BLOCK:
18261       if (CLEANUP_P (t))
18262 	{
18263 	  stmt = begin_try_block ();
18264 	  RECUR (TRY_STMTS (t));
18265 	  finish_cleanup_try_block (stmt);
18266 	  finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
18267 	}
18268       else
18269 	{
18270 	  tree compound_stmt = NULL_TREE;
18271 
18272 	  if (FN_TRY_BLOCK_P (t))
18273 	    stmt = begin_function_try_block (&compound_stmt);
18274 	  else
18275 	    stmt = begin_try_block ();
18276 
18277 	  RECUR (TRY_STMTS (t));
18278 
18279 	  if (FN_TRY_BLOCK_P (t))
18280 	    finish_function_try_block (stmt);
18281 	  else
18282 	    finish_try_block (stmt);
18283 
18284 	  RECUR (TRY_HANDLERS (t));
18285 	  if (FN_TRY_BLOCK_P (t))
18286 	    finish_function_handler_sequence (stmt, compound_stmt);
18287 	  else
18288 	    finish_handler_sequence (stmt);
18289 	}
18290       break;
18291 
18292     case HANDLER:
18293       {
18294 	tree decl = HANDLER_PARMS (t);
18295 
18296 	if (decl)
18297 	  {
18298 	    decl = tsubst (decl, args, complain, in_decl);
18299 	    /* Prevent instantiate_decl from trying to instantiate
18300 	       this variable.  We've already done all that needs to be
18301 	       done.  */
18302 	    if (decl != error_mark_node)
18303 	      DECL_TEMPLATE_INSTANTIATED (decl) = 1;
18304 	  }
18305 	stmt = begin_handler ();
18306 	finish_handler_parms (decl, stmt);
18307 	RECUR (HANDLER_BODY (t));
18308 	finish_handler (stmt);
18309       }
18310       break;
18311 
18312     case TAG_DEFN:
18313       tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
18314       if (CLASS_TYPE_P (tmp))
18315 	{
18316 	  /* Local classes are not independent templates; they are
18317 	     instantiated along with their containing function.  And this
18318 	     way we don't have to deal with pushing out of one local class
18319 	     to instantiate a member of another local class.  */
18320 	  /* Closures are handled by the LAMBDA_EXPR.  */
18321 	  gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
18322 	  complete_type (tmp);
18323 	  for (tree fld = TYPE_FIELDS (tmp); fld; fld = DECL_CHAIN (fld))
18324 	    if ((VAR_P (fld)
18325 		 || (TREE_CODE (fld) == FUNCTION_DECL
18326 		     && !DECL_ARTIFICIAL (fld)))
18327 		&& DECL_TEMPLATE_INSTANTIATION (fld))
18328 	      instantiate_decl (fld, /*defer_ok=*/false,
18329 				/*expl_inst_class=*/false);
18330 	}
18331       break;
18332 
18333     case STATIC_ASSERT:
18334       {
18335 	tree condition;
18336 
18337 	++c_inhibit_evaluation_warnings;
18338         condition =
18339           tsubst_expr (STATIC_ASSERT_CONDITION (t),
18340                        args,
18341                        complain, in_decl,
18342                        /*integral_constant_expression_p=*/true);
18343 	--c_inhibit_evaluation_warnings;
18344 
18345         finish_static_assert (condition,
18346                               STATIC_ASSERT_MESSAGE (t),
18347                               STATIC_ASSERT_SOURCE_LOCATION (t),
18348                               /*member_p=*/false);
18349       }
18350       break;
18351 
18352     case OACC_KERNELS:
18353     case OACC_PARALLEL:
18354     case OACC_SERIAL:
18355       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_ACC, args, complain,
18356 				in_decl);
18357       stmt = begin_omp_parallel ();
18358       RECUR (OMP_BODY (t));
18359       finish_omp_construct (TREE_CODE (t), stmt, tmp);
18360       break;
18361 
18362     case OMP_PARALLEL:
18363       r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
18364       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), C_ORT_OMP, args,
18365 				complain, in_decl);
18366       if (OMP_PARALLEL_COMBINED (t))
18367 	omp_parallel_combined_clauses = &tmp;
18368       stmt = begin_omp_parallel ();
18369       RECUR (OMP_PARALLEL_BODY (t));
18370       gcc_assert (omp_parallel_combined_clauses == NULL);
18371       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
18372 	= OMP_PARALLEL_COMBINED (t);
18373       pop_omp_privatization_clauses (r);
18374       break;
18375 
18376     case OMP_TASK:
18377       if (OMP_TASK_BODY (t) == NULL_TREE)
18378 	{
18379 	  tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
18380 				    complain, in_decl);
18381 	  t = copy_node (t);
18382 	  OMP_TASK_CLAUSES (t) = tmp;
18383 	  add_stmt (t);
18384 	  break;
18385 	}
18386       r = push_omp_privatization_clauses (false);
18387       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
18388 				complain, in_decl);
18389       stmt = begin_omp_task ();
18390       RECUR (OMP_TASK_BODY (t));
18391       finish_omp_task (tmp, stmt);
18392       pop_omp_privatization_clauses (r);
18393       break;
18394 
18395     case OMP_FOR:
18396     case OMP_LOOP:
18397     case OMP_SIMD:
18398     case OMP_DISTRIBUTE:
18399     case OMP_TASKLOOP:
18400     case OACC_LOOP:
18401       {
18402 	tree clauses, body, pre_body;
18403 	tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
18404 	tree orig_declv = NULL_TREE;
18405 	tree incrv = NULL_TREE;
18406 	enum c_omp_region_type ort = C_ORT_OMP;
18407 	bool any_range_for = false;
18408 	int i;
18409 
18410 	if (TREE_CODE (t) == OACC_LOOP)
18411 	  ort = C_ORT_ACC;
18412 
18413 	r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
18414 	clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), ort, args, complain,
18415 				      in_decl);
18416 	if (OMP_FOR_INIT (t) != NULL_TREE)
18417 	  {
18418 	    declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18419 	    if (OMP_FOR_ORIG_DECLS (t))
18420 	      orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18421 	    initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18422 	    condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18423 	    incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18424 	  }
18425 
18426 	keep_next_level (true);
18427 	stmt = begin_omp_structured_block ();
18428 
18429 	pre_body = push_stmt_list ();
18430 	RECUR (OMP_FOR_PRE_BODY (t));
18431 	pre_body = pop_stmt_list (pre_body);
18432 
18433 	if (OMP_FOR_INIT (t) != NULL_TREE)
18434 	  for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
18435 	    any_range_for
18436 	      |= tsubst_omp_for_iterator (t, i, declv, orig_declv, initv,
18437 					  condv, incrv, &clauses, args,
18438 					  complain, in_decl,
18439 					  integral_constant_expression_p);
18440 	omp_parallel_combined_clauses = NULL;
18441 
18442 	if (any_range_for)
18443 	  {
18444 	    gcc_assert (orig_declv);
18445 	    body = begin_omp_structured_block ();
18446 	    for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
18447 	      if (TREE_VEC_ELT (orig_declv, i) != TREE_VEC_ELT (declv, i)
18448 		  && TREE_CODE (TREE_VEC_ELT (orig_declv, i)) == TREE_LIST
18449 		  && TREE_CHAIN (TREE_VEC_ELT (orig_declv, i)))
18450 		cp_finish_omp_range_for (TREE_VEC_ELT (orig_declv, i),
18451 					 TREE_VEC_ELT (declv, i));
18452 	  }
18453 	else
18454 	  body = push_stmt_list ();
18455 	RECUR (OMP_FOR_BODY (t));
18456 	if (any_range_for)
18457 	  body = finish_omp_structured_block (body);
18458 	else
18459 	  body = pop_stmt_list (body);
18460 
18461 	if (OMP_FOR_INIT (t) != NULL_TREE)
18462 	  t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
18463 			      orig_declv, initv, condv, incrv, body, pre_body,
18464 			      NULL, clauses);
18465 	else
18466 	  {
18467 	    t = make_node (TREE_CODE (t));
18468 	    TREE_TYPE (t) = void_type_node;
18469 	    OMP_FOR_BODY (t) = body;
18470 	    OMP_FOR_PRE_BODY (t) = pre_body;
18471 	    OMP_FOR_CLAUSES (t) = clauses;
18472 	    SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
18473 	    add_stmt (t);
18474 	  }
18475 
18476 	add_stmt (finish_omp_for_block (finish_omp_structured_block (stmt),
18477 					t));
18478 	pop_omp_privatization_clauses (r);
18479       }
18480       break;
18481 
18482     case OMP_SECTIONS:
18483       omp_parallel_combined_clauses = NULL;
18484       /* FALLTHRU */
18485     case OMP_SINGLE:
18486     case OMP_TEAMS:
18487     case OMP_CRITICAL:
18488     case OMP_TASKGROUP:
18489     case OMP_SCAN:
18490       r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
18491 					  && OMP_TEAMS_COMBINED (t));
18492       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_OMP, args, complain,
18493 				in_decl);
18494       if (TREE_CODE (t) == OMP_TEAMS)
18495 	{
18496 	  keep_next_level (true);
18497 	  stmt = begin_omp_structured_block ();
18498 	  RECUR (OMP_BODY (t));
18499 	  stmt = finish_omp_structured_block (stmt);
18500 	}
18501       else
18502 	{
18503 	  stmt = push_stmt_list ();
18504 	  RECUR (OMP_BODY (t));
18505 	  stmt = pop_stmt_list (stmt);
18506 	}
18507 
18508       t = copy_node (t);
18509       OMP_BODY (t) = stmt;
18510       OMP_CLAUSES (t) = tmp;
18511       add_stmt (t);
18512       pop_omp_privatization_clauses (r);
18513       break;
18514 
18515     case OMP_DEPOBJ:
18516       r = RECUR (OMP_DEPOBJ_DEPOBJ (t));
18517       if (OMP_DEPOBJ_CLAUSES (t) && OMP_DEPOBJ_CLAUSES (t) != error_mark_node)
18518 	{
18519 	  enum omp_clause_depend_kind kind = OMP_CLAUSE_DEPEND_SOURCE;
18520 	  if (TREE_CODE (OMP_DEPOBJ_CLAUSES (t)) == OMP_CLAUSE)
18521 	    {
18522 	      tmp = tsubst_omp_clauses (OMP_DEPOBJ_CLAUSES (t), C_ORT_OMP,
18523 					args, complain, in_decl);
18524 	      if (tmp == NULL_TREE)
18525 		tmp = error_mark_node;
18526 	    }
18527 	  else
18528 	    {
18529 	      kind = (enum omp_clause_depend_kind)
18530 		     tree_to_uhwi (OMP_DEPOBJ_CLAUSES (t));
18531 	      tmp = NULL_TREE;
18532 	    }
18533 	  finish_omp_depobj (EXPR_LOCATION (t), r, kind, tmp);
18534 	}
18535       else
18536 	finish_omp_depobj (EXPR_LOCATION (t), r,
18537 			   OMP_CLAUSE_DEPEND_SOURCE,
18538 			   OMP_DEPOBJ_CLAUSES (t));
18539       break;
18540 
18541     case OACC_DATA:
18542     case OMP_TARGET_DATA:
18543     case OMP_TARGET:
18544       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), (TREE_CODE (t) == OACC_DATA)
18545 				? C_ORT_ACC : C_ORT_OMP, args, complain,
18546 				in_decl);
18547       keep_next_level (true);
18548       stmt = begin_omp_structured_block ();
18549 
18550       RECUR (OMP_BODY (t));
18551       stmt = finish_omp_structured_block (stmt);
18552 
18553       t = copy_node (t);
18554       OMP_BODY (t) = stmt;
18555       OMP_CLAUSES (t) = tmp;
18556       if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
18557 	{
18558 	  tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
18559 	  if (teams)
18560 	    {
18561 	      /* For combined target teams, ensure the num_teams and
18562 		 thread_limit clause expressions are evaluated on the host,
18563 		 before entering the target construct.  */
18564 	      tree c;
18565 	      for (c = OMP_TEAMS_CLAUSES (teams);
18566 		   c; c = OMP_CLAUSE_CHAIN (c))
18567 		if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
18568 		     || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
18569 		    && TREE_CODE (OMP_CLAUSE_OPERAND (c, 0)) != INTEGER_CST)
18570 		  {
18571 		    tree expr = OMP_CLAUSE_OPERAND (c, 0);
18572 		    expr = force_target_expr (TREE_TYPE (expr), expr, tf_none);
18573 		    if (expr == error_mark_node)
18574 		      continue;
18575 		    tmp = TARGET_EXPR_SLOT (expr);
18576 		    add_stmt (expr);
18577 		    OMP_CLAUSE_OPERAND (c, 0) = expr;
18578 		    tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
18579 						OMP_CLAUSE_FIRSTPRIVATE);
18580 		    OMP_CLAUSE_DECL (tc) = tmp;
18581 		    OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
18582 		    OMP_TARGET_CLAUSES (t) = tc;
18583 		  }
18584 	    }
18585 	}
18586       add_stmt (t);
18587       break;
18588 
18589     case OACC_DECLARE:
18590       t = copy_node (t);
18591       tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), C_ORT_ACC, args,
18592 				complain, in_decl);
18593       OACC_DECLARE_CLAUSES (t) = tmp;
18594       add_stmt (t);
18595       break;
18596 
18597     case OMP_TARGET_UPDATE:
18598     case OMP_TARGET_ENTER_DATA:
18599     case OMP_TARGET_EXIT_DATA:
18600       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_OMP, args,
18601 				complain, in_decl);
18602       t = copy_node (t);
18603       OMP_STANDALONE_CLAUSES (t) = tmp;
18604       add_stmt (t);
18605       break;
18606 
18607     case OACC_ENTER_DATA:
18608     case OACC_EXIT_DATA:
18609     case OACC_UPDATE:
18610       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_ACC, args,
18611 				complain, in_decl);
18612       t = copy_node (t);
18613       OMP_STANDALONE_CLAUSES (t) = tmp;
18614       add_stmt (t);
18615       break;
18616 
18617     case OMP_ORDERED:
18618       tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), C_ORT_OMP, args,
18619 				complain, in_decl);
18620       stmt = push_stmt_list ();
18621       RECUR (OMP_BODY (t));
18622       stmt = pop_stmt_list (stmt);
18623 
18624       t = copy_node (t);
18625       OMP_BODY (t) = stmt;
18626       OMP_ORDERED_CLAUSES (t) = tmp;
18627       add_stmt (t);
18628       break;
18629 
18630     case OMP_MASTER:
18631       omp_parallel_combined_clauses = NULL;
18632       /* FALLTHRU */
18633     case OMP_SECTION:
18634       stmt = push_stmt_list ();
18635       RECUR (OMP_BODY (t));
18636       stmt = pop_stmt_list (stmt);
18637 
18638       t = copy_node (t);
18639       OMP_BODY (t) = stmt;
18640       add_stmt (t);
18641       break;
18642 
18643     case OMP_ATOMIC:
18644       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
18645       tmp = NULL_TREE;
18646       if (TREE_CODE (TREE_OPERAND (t, 0)) == OMP_CLAUSE)
18647 	tmp = tsubst_omp_clauses (TREE_OPERAND (t, 0), C_ORT_OMP, args,
18648 				  complain, in_decl);
18649       if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
18650 	{
18651 	  tree op1 = TREE_OPERAND (t, 1);
18652 	  tree rhs1 = NULL_TREE;
18653 	  tree lhs, rhs;
18654 	  if (TREE_CODE (op1) == COMPOUND_EXPR)
18655 	    {
18656 	      rhs1 = RECUR (TREE_OPERAND (op1, 0));
18657 	      op1 = TREE_OPERAND (op1, 1);
18658 	    }
18659 	  lhs = RECUR (TREE_OPERAND (op1, 0));
18660 	  rhs = RECUR (TREE_OPERAND (op1, 1));
18661 	  finish_omp_atomic (EXPR_LOCATION (t), OMP_ATOMIC, TREE_CODE (op1),
18662 			     lhs, rhs, NULL_TREE, NULL_TREE, rhs1, tmp,
18663 			     OMP_ATOMIC_MEMORY_ORDER (t));
18664 	}
18665       else
18666 	{
18667 	  tree op1 = TREE_OPERAND (t, 1);
18668 	  tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
18669 	  tree rhs1 = NULL_TREE;
18670 	  enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
18671 	  enum tree_code opcode = NOP_EXPR;
18672 	  if (code == OMP_ATOMIC_READ)
18673 	    {
18674 	      v = RECUR (TREE_OPERAND (op1, 0));
18675 	      lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
18676 	    }
18677 	  else if (code == OMP_ATOMIC_CAPTURE_OLD
18678 		   || code == OMP_ATOMIC_CAPTURE_NEW)
18679 	    {
18680 	      tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
18681 	      v = RECUR (TREE_OPERAND (op1, 0));
18682 	      lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
18683 	      if (TREE_CODE (op11) == COMPOUND_EXPR)
18684 		{
18685 		  rhs1 = RECUR (TREE_OPERAND (op11, 0));
18686 		  op11 = TREE_OPERAND (op11, 1);
18687 		}
18688 	      lhs = RECUR (TREE_OPERAND (op11, 0));
18689 	      rhs = RECUR (TREE_OPERAND (op11, 1));
18690 	      opcode = TREE_CODE (op11);
18691 	      if (opcode == MODIFY_EXPR)
18692 		opcode = NOP_EXPR;
18693 	    }
18694 	  else
18695 	    {
18696 	      code = OMP_ATOMIC;
18697 	      lhs = RECUR (TREE_OPERAND (op1, 0));
18698 	      rhs = RECUR (TREE_OPERAND (op1, 1));
18699 	    }
18700 	  finish_omp_atomic (EXPR_LOCATION (t), code, opcode, lhs, rhs, v,
18701 			     lhs1, rhs1, tmp, OMP_ATOMIC_MEMORY_ORDER (t));
18702 	}
18703       break;
18704 
18705     case TRANSACTION_EXPR:
18706       {
18707 	int flags = 0;
18708 	flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
18709 	flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
18710 
18711         if (TRANSACTION_EXPR_IS_STMT (t))
18712           {
18713 	    tree body = TRANSACTION_EXPR_BODY (t);
18714 	    tree noex = NULL_TREE;
18715 	    if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
18716 	      {
18717 		noex = MUST_NOT_THROW_COND (body);
18718 		if (noex == NULL_TREE)
18719 		  noex = boolean_true_node;
18720 		body = TREE_OPERAND (body, 0);
18721 	      }
18722             stmt = begin_transaction_stmt (input_location, NULL, flags);
18723             RECUR (body);
18724             finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
18725           }
18726         else
18727           {
18728             stmt = build_transaction_expr (EXPR_LOCATION (t),
18729 					   RECUR (TRANSACTION_EXPR_BODY (t)),
18730 					   flags, NULL_TREE);
18731             RETURN (stmt);
18732           }
18733       }
18734       break;
18735 
18736     case MUST_NOT_THROW_EXPR:
18737       {
18738 	tree op0 = RECUR (TREE_OPERAND (t, 0));
18739 	tree cond = RECUR (MUST_NOT_THROW_COND (t));
18740 	RETURN (build_must_not_throw_expr (op0, cond));
18741       }
18742 
18743     case EXPR_PACK_EXPANSION:
18744       error ("invalid use of pack expansion expression");
18745       RETURN (error_mark_node);
18746 
18747     case NONTYPE_ARGUMENT_PACK:
18748       error ("use %<...%> to expand argument pack");
18749       RETURN (error_mark_node);
18750 
18751     case COMPOUND_EXPR:
18752       tmp = RECUR (TREE_OPERAND (t, 0));
18753       if (tmp == NULL_TREE)
18754 	/* If the first operand was a statement, we're done with it.  */
18755 	RETURN (RECUR (TREE_OPERAND (t, 1)));
18756       RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
18757 				    RECUR (TREE_OPERAND (t, 1)),
18758 				    complain));
18759 
18760     case ANNOTATE_EXPR:
18761       tmp = RECUR (TREE_OPERAND (t, 0));
18762       RETURN (build3_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
18763 			  TREE_TYPE (tmp), tmp,
18764 			  RECUR (TREE_OPERAND (t, 1)),
18765 			  RECUR (TREE_OPERAND (t, 2))));
18766 
18767     case PREDICT_EXPR:
18768       RETURN (add_stmt (copy_node (t)));
18769 
18770     default:
18771       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
18772 
18773       RETURN (tsubst_copy_and_build (t, args, complain, in_decl,
18774 				    /*function_p=*/false,
18775 				    integral_constant_expression_p));
18776     }
18777 
18778   RETURN (NULL_TREE);
18779  out:
18780   input_location = loc;
18781   return r;
18782 #undef RECUR
18783 #undef RETURN
18784 }
18785 
18786 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
18787    function.  For description of the body see comment above
18788    cp_parser_omp_declare_reduction_exprs.  */
18789 
18790 static void
tsubst_omp_udr(tree t,tree args,tsubst_flags_t complain,tree in_decl)18791 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
18792 {
18793   if (t == NULL_TREE || t == error_mark_node)
18794     return;
18795 
18796   gcc_assert (TREE_CODE (t) == STATEMENT_LIST);
18797 
18798   tree_stmt_iterator tsi;
18799   int i;
18800   tree stmts[7];
18801   memset (stmts, 0, sizeof stmts);
18802   for (i = 0, tsi = tsi_start (t);
18803        i < 7 && !tsi_end_p (tsi);
18804        i++, tsi_next (&tsi))
18805     stmts[i] = tsi_stmt (tsi);
18806   gcc_assert (tsi_end_p (tsi));
18807 
18808   if (i >= 3)
18809     {
18810       gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
18811 		  && TREE_CODE (stmts[1]) == DECL_EXPR);
18812       tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
18813 			     args, complain, in_decl);
18814       tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
18815 			    args, complain, in_decl);
18816       DECL_CONTEXT (omp_out) = current_function_decl;
18817       DECL_CONTEXT (omp_in) = current_function_decl;
18818       keep_next_level (true);
18819       tree block = begin_omp_structured_block ();
18820       tsubst_expr (stmts[2], args, complain, in_decl, false);
18821       block = finish_omp_structured_block (block);
18822       block = maybe_cleanup_point_expr_void (block);
18823       add_decl_expr (omp_out);
18824       if (TREE_NO_WARNING (DECL_EXPR_DECL (stmts[0])))
18825 	TREE_NO_WARNING (omp_out) = 1;
18826       add_decl_expr (omp_in);
18827       finish_expr_stmt (block);
18828     }
18829   if (i >= 6)
18830     {
18831       gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
18832 		  && TREE_CODE (stmts[4]) == DECL_EXPR);
18833       tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
18834 			      args, complain, in_decl);
18835       tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
18836 			      args, complain, in_decl);
18837       DECL_CONTEXT (omp_priv) = current_function_decl;
18838       DECL_CONTEXT (omp_orig) = current_function_decl;
18839       keep_next_level (true);
18840       tree block = begin_omp_structured_block ();
18841       tsubst_expr (stmts[5], args, complain, in_decl, false);
18842       block = finish_omp_structured_block (block);
18843       block = maybe_cleanup_point_expr_void (block);
18844       cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
18845       add_decl_expr (omp_priv);
18846       add_decl_expr (omp_orig);
18847       finish_expr_stmt (block);
18848       if (i == 7)
18849 	add_decl_expr (omp_orig);
18850     }
18851 }
18852 
18853 /* T is a postfix-expression that is not being used in a function
18854    call.  Return the substituted version of T.  */
18855 
18856 static tree
tsubst_non_call_postfix_expression(tree t,tree args,tsubst_flags_t complain,tree in_decl)18857 tsubst_non_call_postfix_expression (tree t, tree args,
18858 				    tsubst_flags_t complain,
18859 				    tree in_decl)
18860 {
18861   if (TREE_CODE (t) == SCOPE_REF)
18862     t = tsubst_qualified_id (t, args, complain, in_decl,
18863 			     /*done=*/false, /*address_p=*/false);
18864   else
18865     t = tsubst_copy_and_build (t, args, complain, in_decl,
18866 			       /*function_p=*/false,
18867 			       /*integral_constant_expression_p=*/false);
18868 
18869   return t;
18870 }
18871 
18872 /* Subroutine of tsubst_lambda_expr: add the FIELD/INIT capture pair to the
18873    LAMBDA_EXPR_CAPTURE_LIST passed in LIST.  Do deduction for a previously
18874    dependent init-capture.  */
18875 
18876 static void
prepend_one_capture(tree field,tree init,tree & list,tsubst_flags_t complain)18877 prepend_one_capture (tree field, tree init, tree &list,
18878 		     tsubst_flags_t complain)
18879 {
18880   if (tree auto_node = type_uses_auto (TREE_TYPE (field)))
18881     {
18882       tree type = NULL_TREE;
18883       if (!init)
18884 	{
18885 	  if (complain & tf_error)
18886 	    error ("empty initializer in lambda init-capture");
18887 	  init = error_mark_node;
18888 	}
18889       else if (TREE_CODE (init) == TREE_LIST)
18890 	init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
18891       if (!type)
18892 	type = do_auto_deduction (TREE_TYPE (field), init, auto_node, complain);
18893       TREE_TYPE (field) = type;
18894       cp_apply_type_quals_to_decl (cp_type_quals (type), field);
18895     }
18896   list = tree_cons (field, init, list);
18897 }
18898 
18899 /* T is a LAMBDA_EXPR.  Generate a new LAMBDA_EXPR for the current
18900    instantiation context.  Instantiating a pack expansion containing a lambda
18901    might result in multiple lambdas all based on the same lambda in the
18902    template.  */
18903 
18904 tree
tsubst_lambda_expr(tree t,tree args,tsubst_flags_t complain,tree in_decl)18905 tsubst_lambda_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
18906 {
18907   tree oldfn = lambda_function (t);
18908   in_decl = oldfn;
18909 
18910   tree r = build_lambda_expr ();
18911 
18912   LAMBDA_EXPR_LOCATION (r)
18913     = LAMBDA_EXPR_LOCATION (t);
18914   LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
18915     = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
18916   LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
18917   LAMBDA_EXPR_INSTANTIATED (r) = true;
18918 
18919   if (LAMBDA_EXPR_EXTRA_SCOPE (t) == NULL_TREE)
18920     /* A lambda in a default argument outside a class gets no
18921        LAMBDA_EXPR_EXTRA_SCOPE, as specified by the ABI.  But
18922        tsubst_default_argument calls start_lambda_scope, so we need to
18923        specifically ignore it here, and use the global scope.  */
18924     record_null_lambda_scope (r);
18925   else
18926     record_lambda_scope (r);
18927 
18928   gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
18929 	      && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
18930 
18931   vec<tree,va_gc>* field_packs = NULL;
18932 
18933   for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t); cap;
18934        cap = TREE_CHAIN (cap))
18935     {
18936       tree ofield = TREE_PURPOSE (cap);
18937       tree init = TREE_VALUE (cap);
18938       if (PACK_EXPANSION_P (init))
18939 	init = tsubst_pack_expansion (init, args, complain, in_decl);
18940       else
18941 	init = tsubst_copy_and_build (init, args, complain, in_decl,
18942 				      /*fn*/false, /*constexpr*/false);
18943 
18944       if (init == error_mark_node)
18945 	return error_mark_node;
18946 
18947       if (init && TREE_CODE (init) == TREE_LIST)
18948 	init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
18949 
18950       if (!processing_template_decl
18951 	  && init && TREE_CODE (init) != TREE_VEC
18952 	  && variably_modified_type_p (TREE_TYPE (init), NULL_TREE))
18953 	{
18954 	  /* For a VLA, simply tsubsting the field type won't work, we need to
18955 	     go through add_capture again.  XXX do we want to do this for all
18956 	     captures?  */
18957 	  tree name = (get_identifier
18958 		       (IDENTIFIER_POINTER (DECL_NAME (ofield)) + 2));
18959 	  tree ftype = TREE_TYPE (ofield);
18960 	  bool by_ref = (TYPE_REF_P (ftype)
18961 			 || (TREE_CODE (ftype) == DECLTYPE_TYPE
18962 			     && DECLTYPE_FOR_REF_CAPTURE (ftype)));
18963 	  add_capture (r, name, init, by_ref, !DECL_NORMAL_CAPTURE_P (ofield));
18964 	  continue;
18965 	}
18966 
18967       if (PACK_EXPANSION_P (ofield))
18968 	ofield = PACK_EXPANSION_PATTERN (ofield);
18969       tree field = tsubst_decl (ofield, args, complain);
18970 
18971       if (DECL_PACK_P (ofield) && !DECL_NORMAL_CAPTURE_P (ofield))
18972 	{
18973 	  /* Remember these for when we've pushed local_specializations.  */
18974 	  vec_safe_push (field_packs, ofield);
18975 	  vec_safe_push (field_packs, field);
18976 	}
18977 
18978       if (field == error_mark_node)
18979 	return error_mark_node;
18980 
18981       if (TREE_CODE (field) == TREE_VEC)
18982 	{
18983 	  int len = TREE_VEC_LENGTH (field);
18984 	  gcc_assert (TREE_CODE (init) == TREE_VEC
18985 		      && TREE_VEC_LENGTH (init) == len);
18986 	  for (int i = 0; i < len; ++i)
18987 	    prepend_one_capture (TREE_VEC_ELT (field, i),
18988 				 TREE_VEC_ELT (init, i),
18989 				 LAMBDA_EXPR_CAPTURE_LIST (r),
18990 				 complain);
18991 	}
18992       else
18993 	{
18994 	  prepend_one_capture (field, init, LAMBDA_EXPR_CAPTURE_LIST (r),
18995 			       complain);
18996 
18997 	  if (id_equal (DECL_NAME (field), "__this"))
18998 	    LAMBDA_EXPR_THIS_CAPTURE (r) = field;
18999 	}
19000     }
19001 
19002   tree type = begin_lambda_type (r);
19003   if (type == error_mark_node)
19004     return error_mark_node;
19005 
19006   /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
19007   determine_visibility (TYPE_NAME (type));
19008 
19009   register_capture_members (LAMBDA_EXPR_CAPTURE_LIST (r));
19010 
19011   tree oldtmpl = (generic_lambda_fn_p (oldfn)
19012 		  ? DECL_TI_TEMPLATE (oldfn)
19013 		  : NULL_TREE);
19014 
19015   tree fntype = static_fn_type (oldfn);
19016   if (oldtmpl)
19017     ++processing_template_decl;
19018   fntype = tsubst (fntype, args, complain, in_decl);
19019   if (oldtmpl)
19020     --processing_template_decl;
19021 
19022   if (fntype == error_mark_node)
19023     r = error_mark_node;
19024   else
19025     {
19026       /* The body of a lambda-expression is not a subexpression of the
19027 	 enclosing expression.  Parms are to have DECL_CHAIN tsubsted,
19028 	 which would be skipped if cp_unevaluated_operand.  */
19029       cp_evaluated ev;
19030 
19031       /* Fix the type of 'this'.  */
19032       fntype = build_memfn_type (fntype, type,
19033 				 type_memfn_quals (fntype),
19034 				 type_memfn_rqual (fntype));
19035       tree fn, tmpl;
19036       if (oldtmpl)
19037 	{
19038 	  tmpl = tsubst_template_decl (oldtmpl, args, complain, fntype);
19039 	  if (tmpl == error_mark_node)
19040 	    {
19041 	      r = error_mark_node;
19042 	      goto out;
19043 	    }
19044 	  fn = DECL_TEMPLATE_RESULT (tmpl);
19045 	  finish_member_declaration (tmpl);
19046 	}
19047       else
19048 	{
19049 	  tmpl = NULL_TREE;
19050 	  fn = tsubst_function_decl (oldfn, args, complain, fntype);
19051 	  if (fn == error_mark_node)
19052 	    {
19053 	      r = error_mark_node;
19054 	      goto out;
19055 	    }
19056 	  finish_member_declaration (fn);
19057 	}
19058 
19059       if (tree ci = get_constraints (oldfn))
19060 	{
19061 	  /* Substitute into the lambda's constraints.  */
19062 	  if (oldtmpl)
19063 	    ++processing_template_decl;
19064 	  ci = tsubst_constraint_info (ci, args, complain, in_decl);
19065 	  if (oldtmpl)
19066 	    --processing_template_decl;
19067 	  set_constraints (fn, ci);
19068 	}
19069 
19070       /* Let finish_function set this.  */
19071       DECL_DECLARED_CONSTEXPR_P (fn) = false;
19072 
19073       bool nested = cfun;
19074       if (nested)
19075 	push_function_context ();
19076       else
19077 	/* Still increment function_depth so that we don't GC in the
19078 	   middle of an expression.  */
19079 	++function_depth;
19080 
19081       local_specialization_stack s (lss_copy);
19082 
19083       tree body = start_lambda_function (fn, r);
19084 
19085       /* Now record them for lookup_init_capture_pack.  */
19086       int fplen = vec_safe_length (field_packs);
19087       for (int i = 0; i < fplen; )
19088 	{
19089 	  tree pack = (*field_packs)[i++];
19090 	  tree inst = (*field_packs)[i++];
19091 	  register_local_specialization (inst, pack);
19092 	}
19093       release_tree_vector (field_packs);
19094 
19095       register_parameter_specializations (oldfn, fn);
19096 
19097       if (oldtmpl)
19098 	{
19099 	  /* We might not partially instantiate some parts of the function, so
19100 	     copy these flags from the original template.  */
19101 	  language_function *ol = DECL_STRUCT_FUNCTION (oldfn)->language;
19102 	  current_function_returns_value = ol->returns_value;
19103 	  current_function_returns_null = ol->returns_null;
19104 	  current_function_returns_abnormally = ol->returns_abnormally;
19105 	  current_function_infinite_loop = ol->infinite_loop;
19106 	}
19107 
19108       /* [temp.deduct] A lambda-expression appearing in a function type or a
19109 	 template parameter is not considered part of the immediate context for
19110 	 the purposes of template argument deduction. */
19111       complain = tf_warning_or_error;
19112 
19113       tsubst_expr (DECL_SAVED_TREE (oldfn), args, complain, r,
19114 		   /*constexpr*/false);
19115 
19116       finish_lambda_function (body);
19117 
19118       if (nested)
19119 	pop_function_context ();
19120       else
19121 	--function_depth;
19122 
19123       /* The capture list was built up in reverse order; fix that now.  */
19124       LAMBDA_EXPR_CAPTURE_LIST (r)
19125 	= nreverse (LAMBDA_EXPR_CAPTURE_LIST (r));
19126 
19127       LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
19128 
19129       maybe_add_lambda_conv_op (type);
19130     }
19131 
19132 out:
19133   finish_struct (type, /*attr*/NULL_TREE);
19134 
19135   insert_pending_capture_proxies ();
19136 
19137   return r;
19138 }
19139 
19140 /* Like tsubst but deals with expressions and performs semantic
19141    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
19142 
19143 tree
tsubst_copy_and_build(tree t,tree args,tsubst_flags_t complain,tree in_decl,bool function_p,bool integral_constant_expression_p)19144 tsubst_copy_and_build (tree t,
19145 		       tree args,
19146 		       tsubst_flags_t complain,
19147 		       tree in_decl,
19148 		       bool function_p,
19149 		       bool integral_constant_expression_p)
19150 {
19151 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
19152 #define RECUR(NODE)						\
19153   tsubst_copy_and_build (NODE, args, complain, in_decl, 	\
19154 			 /*function_p=*/false,			\
19155 			 integral_constant_expression_p)
19156 
19157   tree retval, op1;
19158   location_t save_loc;
19159 
19160   if (t == NULL_TREE || t == error_mark_node)
19161     return t;
19162 
19163   save_loc = input_location;
19164   if (location_t eloc = cp_expr_location (t))
19165     input_location = eloc;
19166 
19167   /* N3276 decltype magic only applies to calls at the top level or on the
19168      right side of a comma.  */
19169   tsubst_flags_t decltype_flag = (complain & tf_decltype);
19170   complain &= ~tf_decltype;
19171 
19172   switch (TREE_CODE (t))
19173     {
19174     case USING_DECL:
19175       t = DECL_NAME (t);
19176       /* Fall through.  */
19177     case IDENTIFIER_NODE:
19178       {
19179 	tree decl;
19180 	cp_id_kind idk;
19181 	bool non_integral_constant_expression_p;
19182 	const char *error_msg;
19183 
19184 	if (IDENTIFIER_CONV_OP_P (t))
19185 	  {
19186 	    tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19187 	    t = make_conv_op_name (new_type);
19188 	  }
19189 
19190 	/* Look up the name.  */
19191 	decl = lookup_name (t);
19192 
19193 	/* By convention, expressions use ERROR_MARK_NODE to indicate
19194 	   failure, not NULL_TREE.  */
19195 	if (decl == NULL_TREE)
19196 	  decl = error_mark_node;
19197 
19198 	decl = finish_id_expression (t, decl, NULL_TREE,
19199 				     &idk,
19200 				     integral_constant_expression_p,
19201           /*allow_non_integral_constant_expression_p=*/(cxx_dialect >= cxx11),
19202 				     &non_integral_constant_expression_p,
19203 				     /*template_p=*/false,
19204 				     /*done=*/true,
19205 				     /*address_p=*/false,
19206 				     /*template_arg_p=*/false,
19207 				     &error_msg,
19208 				     input_location);
19209 	if (error_msg)
19210 	  error (error_msg);
19211 	if (!function_p && identifier_p (decl))
19212 	  {
19213 	    if (complain & tf_error)
19214 	      unqualified_name_lookup_error (decl);
19215 	    decl = error_mark_node;
19216 	  }
19217 	RETURN (decl);
19218       }
19219 
19220     case TEMPLATE_ID_EXPR:
19221       {
19222 	tree object;
19223 	tree templ = RECUR (TREE_OPERAND (t, 0));
19224 	tree targs = TREE_OPERAND (t, 1);
19225 
19226 	if (targs)
19227 	  targs = tsubst_template_args (targs, args, complain, in_decl);
19228 	if (targs == error_mark_node)
19229 	  RETURN (error_mark_node);
19230 
19231 	if (TREE_CODE (templ) == SCOPE_REF)
19232 	  {
19233 	    tree name = TREE_OPERAND (templ, 1);
19234 	    tree tid = lookup_template_function (name, targs);
19235 	    TREE_OPERAND (templ, 1) = tid;
19236 	    RETURN (templ);
19237 	  }
19238 
19239 	if (concept_definition_p (templ))
19240 	  {
19241 	    tree check = build_concept_check (templ, targs, complain);
19242 	    if (check == error_mark_node)
19243 	      RETURN (error_mark_node);
19244 
19245 	    tree id = unpack_concept_check (check);
19246 
19247 	    /* If we built a function concept check, return the underlying
19248 	       template-id. So we can evaluate it as a function call.  */
19249 	    if (function_concept_p (TREE_OPERAND (id, 0)))
19250 	      RETURN (id);
19251 
19252 	    RETURN (check);
19253 	  }
19254 
19255 	if (variable_template_p (templ))
19256 	  {
19257 	    tree r = lookup_and_finish_template_variable (templ, targs,
19258 							  complain);
19259 	    r = maybe_wrap_with_location (r, EXPR_LOCATION (t));
19260 	    RETURN (r);
19261 	  }
19262 
19263 	if (TREE_CODE (templ) == COMPONENT_REF)
19264 	  {
19265 	    object = TREE_OPERAND (templ, 0);
19266 	    templ = TREE_OPERAND (templ, 1);
19267 	  }
19268 	else
19269 	  object = NULL_TREE;
19270 	templ = lookup_template_function (templ, targs);
19271 
19272 	if (object)
19273 	  RETURN (build3 (COMPONENT_REF, TREE_TYPE (templ),
19274 			 object, templ, NULL_TREE));
19275 	else
19276 	  RETURN (baselink_for_fns (templ));
19277       }
19278 
19279     case INDIRECT_REF:
19280       {
19281 	tree r = RECUR (TREE_OPERAND (t, 0));
19282 
19283 	if (REFERENCE_REF_P (t))
19284 	  {
19285 	    /* A type conversion to reference type will be enclosed in
19286 	       such an indirect ref, but the substitution of the cast
19287 	       will have also added such an indirect ref.  */
19288 	    r = convert_from_reference (r);
19289 	  }
19290 	else
19291 	  r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
19292 				    complain|decltype_flag);
19293 
19294 	if (REF_PARENTHESIZED_P (t))
19295 	  r = force_paren_expr (r);
19296 
19297 	RETURN (r);
19298       }
19299 
19300     case NOP_EXPR:
19301       {
19302 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19303 	tree op0 = RECUR (TREE_OPERAND (t, 0));
19304 	RETURN (build_nop (type, op0));
19305       }
19306 
19307     case IMPLICIT_CONV_EXPR:
19308       {
19309 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19310 	tree expr = RECUR (TREE_OPERAND (t, 0));
19311 	if (dependent_type_p (type) || type_dependent_expression_p (expr))
19312 	  {
19313 	    retval = copy_node (t);
19314 	    TREE_TYPE (retval) = type;
19315 	    TREE_OPERAND (retval, 0) = expr;
19316 	    RETURN (retval);
19317 	  }
19318 	if (IMPLICIT_CONV_EXPR_NONTYPE_ARG (t))
19319 	  /* We'll pass this to convert_nontype_argument again, we don't need
19320 	     to actually perform any conversion here.  */
19321 	  RETURN (expr);
19322 	int flags = LOOKUP_IMPLICIT;
19323 	if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
19324 	  flags = LOOKUP_NORMAL;
19325 	if (IMPLICIT_CONV_EXPR_BRACED_INIT (t))
19326 	  flags |= LOOKUP_NO_NARROWING;
19327 	RETURN (perform_implicit_conversion_flags (type, expr, complain,
19328 						  flags));
19329       }
19330 
19331     case CONVERT_EXPR:
19332       {
19333 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19334 	tree op0 = RECUR (TREE_OPERAND (t, 0));
19335 	if (op0 == error_mark_node)
19336 	  RETURN (error_mark_node);
19337 	RETURN (build1 (CONVERT_EXPR, type, op0));
19338       }
19339 
19340     case CAST_EXPR:
19341     case REINTERPRET_CAST_EXPR:
19342     case CONST_CAST_EXPR:
19343     case DYNAMIC_CAST_EXPR:
19344     case STATIC_CAST_EXPR:
19345       {
19346 	tree type;
19347 	tree op, r = NULL_TREE;
19348 
19349 	type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19350 	if (integral_constant_expression_p
19351 	    && !cast_valid_in_integral_constant_expression_p (type))
19352 	  {
19353             if (complain & tf_error)
19354               error ("a cast to a type other than an integral or "
19355                      "enumeration type cannot appear in a constant-expression");
19356 	    RETURN (error_mark_node);
19357 	  }
19358 
19359 	op = RECUR (TREE_OPERAND (t, 0));
19360 
19361 	warning_sentinel s(warn_useless_cast);
19362 	warning_sentinel s2(warn_ignored_qualifiers);
19363 	switch (TREE_CODE (t))
19364 	  {
19365 	  case CAST_EXPR:
19366 	    r = build_functional_cast (input_location, type, op, complain);
19367 	    break;
19368 	  case REINTERPRET_CAST_EXPR:
19369 	    r = build_reinterpret_cast (input_location, type, op, complain);
19370 	    break;
19371 	  case CONST_CAST_EXPR:
19372 	    r = build_const_cast (input_location, type, op, complain);
19373 	    break;
19374 	  case DYNAMIC_CAST_EXPR:
19375 	    r = build_dynamic_cast (input_location, type, op, complain);
19376 	    break;
19377 	  case STATIC_CAST_EXPR:
19378 	    r = build_static_cast (input_location, type, op, complain);
19379 	    break;
19380 	  default:
19381 	    gcc_unreachable ();
19382 	  }
19383 
19384 	RETURN (r);
19385       }
19386 
19387     case POSTDECREMENT_EXPR:
19388     case POSTINCREMENT_EXPR:
19389       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
19390 						args, complain, in_decl);
19391       RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
19392 				complain|decltype_flag));
19393 
19394     case PREDECREMENT_EXPR:
19395     case PREINCREMENT_EXPR:
19396     case NEGATE_EXPR:
19397     case BIT_NOT_EXPR:
19398     case ABS_EXPR:
19399     case TRUTH_NOT_EXPR:
19400     case UNARY_PLUS_EXPR:  /* Unary + */
19401     case REALPART_EXPR:
19402     case IMAGPART_EXPR:
19403       RETURN (build_x_unary_op (input_location, TREE_CODE (t),
19404 				RECUR (TREE_OPERAND (t, 0)),
19405 				complain|decltype_flag));
19406 
19407     case FIX_TRUNC_EXPR:
19408       gcc_unreachable ();
19409 
19410     case ADDR_EXPR:
19411       op1 = TREE_OPERAND (t, 0);
19412       if (TREE_CODE (op1) == LABEL_DECL)
19413 	RETURN (finish_label_address_expr (DECL_NAME (op1),
19414 					  EXPR_LOCATION (op1)));
19415       if (TREE_CODE (op1) == SCOPE_REF)
19416 	op1 = tsubst_qualified_id (op1, args, complain, in_decl,
19417 				   /*done=*/true, /*address_p=*/true);
19418       else
19419 	op1 = tsubst_non_call_postfix_expression (op1, args, complain,
19420 						  in_decl);
19421       RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
19422 				complain|decltype_flag));
19423 
19424     case PLUS_EXPR:
19425     case MINUS_EXPR:
19426     case MULT_EXPR:
19427     case TRUNC_DIV_EXPR:
19428     case CEIL_DIV_EXPR:
19429     case FLOOR_DIV_EXPR:
19430     case ROUND_DIV_EXPR:
19431     case EXACT_DIV_EXPR:
19432     case BIT_AND_EXPR:
19433     case BIT_IOR_EXPR:
19434     case BIT_XOR_EXPR:
19435     case TRUNC_MOD_EXPR:
19436     case FLOOR_MOD_EXPR:
19437     case TRUTH_ANDIF_EXPR:
19438     case TRUTH_ORIF_EXPR:
19439     case TRUTH_AND_EXPR:
19440     case TRUTH_OR_EXPR:
19441     case RSHIFT_EXPR:
19442     case LSHIFT_EXPR:
19443     case EQ_EXPR:
19444     case NE_EXPR:
19445     case MAX_EXPR:
19446     case MIN_EXPR:
19447     case LE_EXPR:
19448     case GE_EXPR:
19449     case LT_EXPR:
19450     case GT_EXPR:
19451     case SPACESHIP_EXPR:
19452     case MEMBER_REF:
19453     case DOTSTAR_EXPR:
19454       {
19455 	/* If T was type-dependent, suppress warnings that depend on the range
19456 	   of the types involved.  */
19457 	bool was_dep = type_dependent_expression_p_push (t);
19458 
19459 	tree op0 = RECUR (TREE_OPERAND (t, 0));
19460 	tree op1 = RECUR (TREE_OPERAND (t, 1));
19461 
19462 	warning_sentinel s1(warn_type_limits, was_dep);
19463 	warning_sentinel s2(warn_div_by_zero, was_dep);
19464 	warning_sentinel s3(warn_logical_op, was_dep);
19465 	warning_sentinel s4(warn_tautological_compare, was_dep);
19466 
19467 	tree r = build_x_binary_op
19468 	  (input_location, TREE_CODE (t),
19469 	   op0,
19470 	   (TREE_NO_WARNING (TREE_OPERAND (t, 0))
19471 	    ? ERROR_MARK
19472 	    : TREE_CODE (TREE_OPERAND (t, 0))),
19473 	   op1,
19474 	   (TREE_NO_WARNING (TREE_OPERAND (t, 1))
19475 	    ? ERROR_MARK
19476 	    : TREE_CODE (TREE_OPERAND (t, 1))),
19477 	   /*overload=*/NULL,
19478 	   complain|decltype_flag);
19479 	if (EXPR_P (r) && TREE_NO_WARNING (t))
19480 	  TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
19481 
19482 	RETURN (r);
19483       }
19484 
19485     case POINTER_PLUS_EXPR:
19486       {
19487 	tree op0 = RECUR (TREE_OPERAND (t, 0));
19488 	if (op0 == error_mark_node)
19489 	  RETURN (error_mark_node);
19490 	tree op1 = RECUR (TREE_OPERAND (t, 1));
19491 	if (op1 == error_mark_node)
19492 	  RETURN (error_mark_node);
19493 	RETURN (fold_build_pointer_plus (op0, op1));
19494       }
19495 
19496     case SCOPE_REF:
19497       RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
19498 				  /*address_p=*/false));
19499     case ARRAY_REF:
19500       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
19501 						args, complain, in_decl);
19502       RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
19503 				 RECUR (TREE_OPERAND (t, 1)),
19504 				 complain|decltype_flag));
19505 
19506     case SIZEOF_EXPR:
19507       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
19508 	  || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
19509 	RETURN (tsubst_copy (t, args, complain, in_decl));
19510       /* Fall through */
19511 
19512     case ALIGNOF_EXPR:
19513       {
19514 	tree r;
19515 
19516 	op1 = TREE_OPERAND (t, 0);
19517 	if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
19518 	  op1 = TREE_TYPE (op1);
19519 	bool std_alignof = (TREE_CODE (t) == ALIGNOF_EXPR
19520 			    && ALIGNOF_EXPR_STD_P (t));
19521         if (!args)
19522 	  {
19523 	    /* When there are no ARGS, we are trying to evaluate a
19524 	       non-dependent expression from the parser.  Trying to do
19525 	       the substitutions may not work.  */
19526 	    if (!TYPE_P (op1))
19527 	      op1 = TREE_TYPE (op1);
19528 	  }
19529 	else
19530 	  {
19531 	    ++cp_unevaluated_operand;
19532 	    ++c_inhibit_evaluation_warnings;
19533 	    if (TYPE_P (op1))
19534 	      op1 = tsubst (op1, args, complain, in_decl);
19535 	    else
19536 	      op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
19537 					   /*function_p=*/false,
19538 					   /*integral_constant_expression_p=*/
19539 					   false);
19540 	    --cp_unevaluated_operand;
19541 	    --c_inhibit_evaluation_warnings;
19542 	  }
19543         if (TYPE_P (op1))
19544 	  r = cxx_sizeof_or_alignof_type (input_location,
19545 					  op1, TREE_CODE (t), std_alignof,
19546 					  complain & tf_error);
19547 	else
19548 	  r = cxx_sizeof_or_alignof_expr (input_location,
19549 					  op1, TREE_CODE (t),
19550 					  complain & tf_error);
19551 	if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
19552 	  {
19553 	    if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
19554 	      {
19555 		if (!processing_template_decl && TYPE_P (op1))
19556 		  {
19557 		    r = build_min (SIZEOF_EXPR, size_type_node,
19558 				   build1 (NOP_EXPR, op1, error_mark_node));
19559 		    SIZEOF_EXPR_TYPE_P (r) = 1;
19560 		  }
19561 		else
19562 		  r = build_min (SIZEOF_EXPR, size_type_node, op1);
19563 		TREE_SIDE_EFFECTS (r) = 0;
19564 		TREE_READONLY (r) = 1;
19565 	      }
19566 	    SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
19567 	  }
19568 	RETURN (r);
19569       }
19570 
19571     case AT_ENCODE_EXPR:
19572       {
19573 	op1 = TREE_OPERAND (t, 0);
19574 	++cp_unevaluated_operand;
19575 	++c_inhibit_evaluation_warnings;
19576 	op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
19577 				     /*function_p=*/false,
19578 				     /*integral_constant_expression_p=*/false);
19579 	--cp_unevaluated_operand;
19580 	--c_inhibit_evaluation_warnings;
19581 	RETURN (objc_build_encode_expr (op1));
19582       }
19583 
19584     case NOEXCEPT_EXPR:
19585       op1 = TREE_OPERAND (t, 0);
19586       ++cp_unevaluated_operand;
19587       ++c_inhibit_evaluation_warnings;
19588       ++cp_noexcept_operand;
19589       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
19590 				   /*function_p=*/false,
19591 				   /*integral_constant_expression_p=*/false);
19592       --cp_unevaluated_operand;
19593       --c_inhibit_evaluation_warnings;
19594       --cp_noexcept_operand;
19595       RETURN (finish_noexcept_expr (op1, complain));
19596 
19597     case MODOP_EXPR:
19598       {
19599 	warning_sentinel s(warn_div_by_zero);
19600 	tree lhs = RECUR (TREE_OPERAND (t, 0));
19601 	tree rhs = RECUR (TREE_OPERAND (t, 2));
19602 	tree r = build_x_modify_expr
19603 	  (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
19604 	   complain|decltype_flag);
19605 	/* TREE_NO_WARNING must be set if either the expression was
19606 	   parenthesized or it uses an operator such as >>= rather
19607 	   than plain assignment.  In the former case, it was already
19608 	   set and must be copied.  In the latter case,
19609 	   build_x_modify_expr sets it and it must not be reset
19610 	   here.  */
19611 	if (TREE_NO_WARNING (t))
19612 	  TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
19613 
19614 	RETURN (r);
19615       }
19616 
19617     case ARROW_EXPR:
19618       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
19619 						args, complain, in_decl);
19620       /* Remember that there was a reference to this entity.  */
19621       if (DECL_P (op1)
19622 	  && !mark_used (op1, complain) && !(complain & tf_error))
19623 	RETURN (error_mark_node);
19624       RETURN (build_x_arrow (input_location, op1, complain));
19625 
19626     case NEW_EXPR:
19627       {
19628 	tree placement = RECUR (TREE_OPERAND (t, 0));
19629 	tree init = RECUR (TREE_OPERAND (t, 3));
19630 	vec<tree, va_gc> *placement_vec;
19631 	vec<tree, va_gc> *init_vec;
19632 	tree ret;
19633 	location_t loc = EXPR_LOCATION (t);
19634 
19635 	if (placement == NULL_TREE)
19636 	  placement_vec = NULL;
19637 	else
19638 	  {
19639 	    placement_vec = make_tree_vector ();
19640 	    for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
19641 	      vec_safe_push (placement_vec, TREE_VALUE (placement));
19642 	  }
19643 
19644 	/* If there was an initializer in the original tree, but it
19645 	   instantiated to an empty list, then we should pass a
19646 	   non-NULL empty vector to tell build_new that it was an
19647 	   empty initializer() rather than no initializer.  This can
19648 	   only happen when the initializer is a pack expansion whose
19649 	   parameter packs are of length zero.  */
19650 	if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
19651 	  init_vec = NULL;
19652 	else
19653 	  {
19654 	    init_vec = make_tree_vector ();
19655 	    if (init == void_node)
19656 	      gcc_assert (init_vec != NULL);
19657 	    else
19658 	      {
19659 		for (; init != NULL_TREE; init = TREE_CHAIN (init))
19660 		  vec_safe_push (init_vec, TREE_VALUE (init));
19661 	      }
19662 	  }
19663 
19664 	/* Avoid passing an enclosing decl to valid_array_size_p.  */
19665 	in_decl = NULL_TREE;
19666 
19667 	tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
19668 	tree op2 = RECUR (TREE_OPERAND (t, 2));
19669 	ret = build_new (loc, &placement_vec, op1, op2,
19670 			 &init_vec, NEW_EXPR_USE_GLOBAL (t),
19671 			 complain);
19672 
19673 	if (placement_vec != NULL)
19674 	  release_tree_vector (placement_vec);
19675 	if (init_vec != NULL)
19676 	  release_tree_vector (init_vec);
19677 
19678 	RETURN (ret);
19679       }
19680 
19681     case DELETE_EXPR:
19682       {
19683 	tree op0 = RECUR (TREE_OPERAND (t, 0));
19684 	tree op1 = RECUR (TREE_OPERAND (t, 1));
19685 	RETURN (delete_sanity (input_location, op0, op1,
19686 			       DELETE_EXPR_USE_VEC (t),
19687 			       DELETE_EXPR_USE_GLOBAL (t),
19688 			       complain));
19689       }
19690 
19691     case COMPOUND_EXPR:
19692       {
19693 	tree op0 = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
19694 					  complain & ~tf_decltype, in_decl,
19695 					  /*function_p=*/false,
19696 					  integral_constant_expression_p);
19697 	RETURN (build_x_compound_expr (EXPR_LOCATION (t),
19698 				       op0,
19699 				       RECUR (TREE_OPERAND (t, 1)),
19700 				       complain|decltype_flag));
19701       }
19702 
19703     case CALL_EXPR:
19704       {
19705 	tree function;
19706 	unsigned int nargs, i;
19707 	bool qualified_p;
19708 	bool koenig_p;
19709 	tree ret;
19710 
19711 	function = CALL_EXPR_FN (t);
19712 	/* Internal function with no arguments.  */
19713 	if (function == NULL_TREE && call_expr_nargs (t) == 0)
19714 	  RETURN (t);
19715 
19716 	/* When we parsed the expression, we determined whether or
19717 	   not Koenig lookup should be performed.  */
19718 	koenig_p = KOENIG_LOOKUP_P (t);
19719 	if (function == NULL_TREE)
19720 	  {
19721 	    koenig_p = false;
19722 	    qualified_p = false;
19723 	  }
19724 	else if (TREE_CODE (function) == SCOPE_REF)
19725 	  {
19726 	    qualified_p = true;
19727 	    function = tsubst_qualified_id (function, args, complain, in_decl,
19728 					    /*done=*/false,
19729 					    /*address_p=*/false);
19730 	  }
19731 	else if (koenig_p && identifier_p (function))
19732 	  {
19733 	    /* Do nothing; calling tsubst_copy_and_build on an identifier
19734 	       would incorrectly perform unqualified lookup again.
19735 
19736 	       Note that we can also have an IDENTIFIER_NODE if the earlier
19737 	       unqualified lookup found a member function; in that case
19738 	       koenig_p will be false and we do want to do the lookup
19739 	       again to find the instantiated member function.
19740 
19741 	       FIXME but doing that causes c++/15272, so we need to stop
19742 	       using IDENTIFIER_NODE in that situation.  */
19743 	    qualified_p = false;
19744 	  }
19745 	else
19746 	  {
19747 	    if (TREE_CODE (function) == COMPONENT_REF)
19748 	      {
19749 		tree op = TREE_OPERAND (function, 1);
19750 
19751 		qualified_p = (TREE_CODE (op) == SCOPE_REF
19752 			       || (BASELINK_P (op)
19753 				   && BASELINK_QUALIFIED_P (op)));
19754 	      }
19755 	    else
19756 	      qualified_p = false;
19757 
19758 	    if (TREE_CODE (function) == ADDR_EXPR
19759 		&& TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
19760 	      /* Avoid error about taking the address of a constructor.  */
19761 	      function = TREE_OPERAND (function, 0);
19762 
19763 	    function = tsubst_copy_and_build (function, args, complain,
19764 					      in_decl,
19765 					      !qualified_p,
19766 					      integral_constant_expression_p);
19767 
19768 	    if (BASELINK_P (function))
19769 	      qualified_p = true;
19770 	  }
19771 
19772 	nargs = call_expr_nargs (t);
19773 	releasing_vec call_args;
19774 	for (i = 0; i < nargs; ++i)
19775 	  {
19776 	    tree arg = CALL_EXPR_ARG (t, i);
19777 
19778 	    if (!PACK_EXPANSION_P (arg))
19779 	      vec_safe_push (call_args, RECUR (CALL_EXPR_ARG (t, i)));
19780 	    else
19781 	      {
19782 		/* Expand the pack expansion and push each entry onto
19783 		   CALL_ARGS.  */
19784 		arg = tsubst_pack_expansion (arg, args, complain, in_decl);
19785 		if (TREE_CODE (arg) == TREE_VEC)
19786 		  {
19787 		    unsigned int len, j;
19788 
19789 		    len = TREE_VEC_LENGTH (arg);
19790 		    for (j = 0; j < len; ++j)
19791 		      {
19792 			tree value = TREE_VEC_ELT (arg, j);
19793 			if (value != NULL_TREE)
19794 			  value = convert_from_reference (value);
19795 			vec_safe_push (call_args, value);
19796 		      }
19797 		  }
19798 		else
19799 		  {
19800 		    /* A partial substitution.  Add one entry.  */
19801 		    vec_safe_push (call_args, arg);
19802 		  }
19803 	      }
19804 	  }
19805 
19806 	/* Stripped-down processing for a call in a thunk.  Specifically, in
19807 	   the thunk template for a generic lambda.  */
19808 	if (CALL_FROM_THUNK_P (t))
19809 	  {
19810 	    /* Now that we've expanded any packs, the number of call args
19811 	       might be different.  */
19812 	    unsigned int cargs = call_args->length ();
19813 	    tree thisarg = NULL_TREE;
19814 	    if (TREE_CODE (function) == COMPONENT_REF)
19815 	      {
19816 		thisarg = TREE_OPERAND (function, 0);
19817 		if (TREE_CODE (thisarg) == INDIRECT_REF)
19818 		  thisarg = TREE_OPERAND (thisarg, 0);
19819 		function = TREE_OPERAND (function, 1);
19820 		if (TREE_CODE (function) == BASELINK)
19821 		  function = BASELINK_FUNCTIONS (function);
19822 	      }
19823 	    /* We aren't going to do normal overload resolution, so force the
19824 	       template-id to resolve.  */
19825 	    function = resolve_nondeduced_context (function, complain);
19826 	    for (unsigned i = 0; i < cargs; ++i)
19827 	      {
19828 		/* In a thunk, pass through args directly, without any
19829 		   conversions.  */
19830 		tree arg = (*call_args)[i];
19831 		while (TREE_CODE (arg) != PARM_DECL)
19832 		  arg = TREE_OPERAND (arg, 0);
19833 		(*call_args)[i] = arg;
19834 	      }
19835 	    if (thisarg)
19836 	      {
19837 		/* If there are no other args, just push 'this'.  */
19838 		if (cargs == 0)
19839 		  vec_safe_push (call_args, thisarg);
19840 		else
19841 		  {
19842 		    /* Otherwise, shift the other args over to make room.  */
19843 		    tree last = (*call_args)[cargs - 1];
19844 		    vec_safe_push (call_args, last);
19845 		    for (int i = cargs - 1; i > 0; --i)
19846 		      (*call_args)[i] = (*call_args)[i - 1];
19847 		    (*call_args)[0] = thisarg;
19848 		  }
19849 	      }
19850 	    ret = build_call_a (function, call_args->length (),
19851 				call_args->address ());
19852 	    /* The thunk location is not interesting.  */
19853 	    SET_EXPR_LOCATION (ret, UNKNOWN_LOCATION);
19854 	    CALL_FROM_THUNK_P (ret) = true;
19855 	    if (CLASS_TYPE_P (TREE_TYPE (ret)))
19856 	      CALL_EXPR_RETURN_SLOT_OPT (ret) = true;
19857 
19858 	    RETURN (ret);
19859 	  }
19860 
19861 	/* We do not perform argument-dependent lookup if normal
19862 	   lookup finds a non-function, in accordance with the
19863 	   expected resolution of DR 218.  */
19864 	if (koenig_p
19865 	    && ((is_overloaded_fn (function)
19866 		 /* If lookup found a member function, the Koenig lookup is
19867 		    not appropriate, even if an unqualified-name was used
19868 		    to denote the function.  */
19869 		 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
19870 		|| identifier_p (function))
19871 	    /* Only do this when substitution turns a dependent call
19872 	       into a non-dependent call.  */
19873 	    && type_dependent_expression_p_push (t)
19874 	    && !any_type_dependent_arguments_p (call_args))
19875 	  function = perform_koenig_lookup (function, call_args, tf_none);
19876 
19877 	if (function != NULL_TREE
19878 	    && identifier_p (function)
19879 	    && !any_type_dependent_arguments_p (call_args))
19880 	  {
19881 	    if (koenig_p && (complain & tf_warning_or_error))
19882 	      {
19883 		/* For backwards compatibility and good diagnostics, try
19884 		   the unqualified lookup again if we aren't in SFINAE
19885 		   context.  */
19886 		tree unq = (tsubst_copy_and_build
19887 			    (function, args, complain, in_decl, true,
19888 			     integral_constant_expression_p));
19889 		if (unq == error_mark_node)
19890 		  RETURN (error_mark_node);
19891 
19892 		if (unq != function)
19893 		  {
19894 		    /* In a lambda fn, we have to be careful to not
19895 		       introduce new this captures.  Legacy code can't
19896 		       be using lambdas anyway, so it's ok to be
19897 		       stricter.  */
19898 		    bool in_lambda = (current_class_type
19899 				      && LAMBDA_TYPE_P (current_class_type));
19900 		    char const *const msg
19901 		      = G_("%qD was not declared in this scope, "
19902 			   "and no declarations were found by "
19903 			   "argument-dependent lookup at the point "
19904 			   "of instantiation");
19905 
19906 		    bool diag = true;
19907 		    if (in_lambda)
19908 		      error_at (cp_expr_loc_or_input_loc (t),
19909 				msg, function);
19910 		    else
19911 		      diag = permerror (cp_expr_loc_or_input_loc (t),
19912 					msg, function);
19913 		    if (diag)
19914 		      {
19915 			tree fn = unq;
19916 
19917 			if (INDIRECT_REF_P (fn))
19918 			  fn = TREE_OPERAND (fn, 0);
19919 			if (is_overloaded_fn (fn))
19920 			  fn = get_first_fn (fn);
19921 
19922 			if (!DECL_P (fn))
19923 			  /* Can't say anything more.  */;
19924 			else if (DECL_CLASS_SCOPE_P (fn))
19925 			  {
19926 			    location_t loc = cp_expr_loc_or_input_loc (t);
19927 			    inform (loc,
19928 				    "declarations in dependent base %qT are "
19929 				    "not found by unqualified lookup",
19930 				    DECL_CLASS_CONTEXT (fn));
19931 			    if (current_class_ptr)
19932 			      inform (loc,
19933 				      "use %<this->%D%> instead", function);
19934 			    else
19935 			      inform (loc,
19936 				      "use %<%T::%D%> instead",
19937 				      current_class_name, function);
19938 			  }
19939 			else
19940 			  inform (DECL_SOURCE_LOCATION (fn),
19941 				  "%qD declared here, later in the "
19942 				  "translation unit", fn);
19943 			if (in_lambda)
19944 			  RETURN (error_mark_node);
19945 		      }
19946 
19947 		    function = unq;
19948 		  }
19949 	      }
19950 	    if (identifier_p (function))
19951 	      {
19952 		if (complain & tf_error)
19953 		  unqualified_name_lookup_error (function);
19954 		RETURN (error_mark_node);
19955 	      }
19956 	  }
19957 
19958 	/* Remember that there was a reference to this entity.  */
19959 	if (function != NULL_TREE
19960 	    && DECL_P (function)
19961 	    && !mark_used (function, complain) && !(complain & tf_error))
19962 	  RETURN (error_mark_node);
19963 
19964 	/* Put back tf_decltype for the actual call.  */
19965 	complain |= decltype_flag;
19966 
19967 	if (function == NULL_TREE)
19968 	  switch (CALL_EXPR_IFN (t))
19969 	    {
19970 	    case IFN_LAUNDER:
19971 	      gcc_assert (nargs == 1);
19972 	      if (vec_safe_length (call_args) != 1)
19973 		{
19974 		  error_at (cp_expr_loc_or_input_loc (t),
19975 			    "wrong number of arguments to "
19976 			    "%<__builtin_launder%>");
19977 		  ret = error_mark_node;
19978 		}
19979 	      else
19980 		ret = finish_builtin_launder (cp_expr_loc_or_input_loc (t),
19981 					      (*call_args)[0], complain);
19982 	      break;
19983 
19984 	    case IFN_VEC_CONVERT:
19985 	      gcc_assert (nargs == 1);
19986 	      if (vec_safe_length (call_args) != 1)
19987 		{
19988 		  error_at (cp_expr_loc_or_input_loc (t),
19989 			    "wrong number of arguments to "
19990 			    "%<__builtin_convertvector%>");
19991 		  ret = error_mark_node;
19992 		  break;
19993 		}
19994 	      ret = cp_build_vec_convert ((*call_args)[0], input_location,
19995 					  tsubst (TREE_TYPE (t), args,
19996 						  complain, in_decl),
19997 					  complain);
19998 	      if (TREE_CODE (ret) == VIEW_CONVERT_EXPR)
19999 		RETURN (ret);
20000 	      break;
20001 
20002 	    default:
20003 	      /* Unsupported internal function with arguments.  */
20004 	      gcc_unreachable ();
20005 	    }
20006 	else if (TREE_CODE (function) == OFFSET_REF
20007 		 || TREE_CODE (function) == DOTSTAR_EXPR
20008 		 || TREE_CODE (function) == MEMBER_REF)
20009 	  ret = build_offset_ref_call_from_tree (function, &call_args,
20010 						 complain);
20011 	else if (TREE_CODE (function) == COMPONENT_REF)
20012 	  {
20013 	    tree instance = TREE_OPERAND (function, 0);
20014 	    tree fn = TREE_OPERAND (function, 1);
20015 
20016 	    if (processing_template_decl
20017 		&& (type_dependent_expression_p (instance)
20018 		    || (!BASELINK_P (fn)
20019 			&& TREE_CODE (fn) != FIELD_DECL)
20020 		    || type_dependent_expression_p (fn)
20021 		    || any_type_dependent_arguments_p (call_args)))
20022 	      ret = build_min_nt_call_vec (function, call_args);
20023 	    else if (!BASELINK_P (fn))
20024 	      ret = finish_call_expr (function, &call_args,
20025 				       /*disallow_virtual=*/false,
20026 				       /*koenig_p=*/false,
20027 				       complain);
20028 	    else
20029 	      ret = (build_new_method_call
20030 		      (instance, fn,
20031 		       &call_args, NULL_TREE,
20032 		       qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
20033 		       /*fn_p=*/NULL,
20034 		       complain));
20035 	  }
20036 	else if (concept_check_p (function))
20037 	  {
20038 	    /* FUNCTION is a template-id referring to a concept definition.  */
20039 	    tree id = unpack_concept_check (function);
20040 	    tree tmpl = TREE_OPERAND (id, 0);
20041 	    tree args = TREE_OPERAND (id, 1);
20042 
20043 	    /* Calls to standard and variable concepts should have been
20044 	       previously diagnosed.  */
20045 	    gcc_assert (function_concept_p (tmpl));
20046 
20047 	    /* Ensure the result is wrapped as a call expression.  */
20048 	    ret = build_concept_check (tmpl, args, tf_warning_or_error);
20049 	  }
20050 	else
20051 	  ret = finish_call_expr (function, &call_args,
20052 				  /*disallow_virtual=*/qualified_p,
20053 				  koenig_p,
20054 				  complain);
20055 
20056 	if (ret != error_mark_node)
20057 	  {
20058 	    bool op = CALL_EXPR_OPERATOR_SYNTAX (t);
20059 	    bool ord = CALL_EXPR_ORDERED_ARGS (t);
20060 	    bool rev = CALL_EXPR_REVERSE_ARGS (t);
20061 	    if (op || ord || rev)
20062 	      {
20063 		function = extract_call_expr (ret);
20064 		CALL_EXPR_OPERATOR_SYNTAX (function) = op;
20065 		CALL_EXPR_ORDERED_ARGS (function) = ord;
20066 		CALL_EXPR_REVERSE_ARGS (function) = rev;
20067 	      }
20068 	  }
20069 
20070 	RETURN (ret);
20071       }
20072 
20073     case COND_EXPR:
20074       {
20075 	tree cond = RECUR (TREE_OPERAND (t, 0));
20076 	cond = mark_rvalue_use (cond);
20077 	tree folded_cond = fold_non_dependent_expr (cond, complain);
20078 	tree exp1, exp2;
20079 
20080 	if (TREE_CODE (folded_cond) == INTEGER_CST)
20081 	  {
20082 	    if (integer_zerop (folded_cond))
20083 	      {
20084 		++c_inhibit_evaluation_warnings;
20085 		exp1 = RECUR (TREE_OPERAND (t, 1));
20086 		--c_inhibit_evaluation_warnings;
20087 		exp2 = RECUR (TREE_OPERAND (t, 2));
20088 	      }
20089 	    else
20090 	      {
20091 		exp1 = RECUR (TREE_OPERAND (t, 1));
20092 		++c_inhibit_evaluation_warnings;
20093 		exp2 = RECUR (TREE_OPERAND (t, 2));
20094 		--c_inhibit_evaluation_warnings;
20095 	      }
20096 	    cond = folded_cond;
20097 	  }
20098 	else
20099 	  {
20100 	    exp1 = RECUR (TREE_OPERAND (t, 1));
20101 	    exp2 = RECUR (TREE_OPERAND (t, 2));
20102 	  }
20103 
20104 	warning_sentinel s(warn_duplicated_branches);
20105 	RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
20106 					 cond, exp1, exp2, complain));
20107       }
20108 
20109     case PSEUDO_DTOR_EXPR:
20110       {
20111 	tree op0 = RECUR (TREE_OPERAND (t, 0));
20112 	tree op1 = RECUR (TREE_OPERAND (t, 1));
20113 	tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
20114 	RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
20115 					       input_location));
20116       }
20117 
20118     case TREE_LIST:
20119       {
20120 	tree purpose, value, chain;
20121 
20122 	if (t == void_list_node)
20123 	  RETURN (t);
20124 
20125         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
20126             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
20127           {
20128             /* We have pack expansions, so expand those and
20129                create a new list out of it.  */
20130             tree purposevec = NULL_TREE;
20131             tree valuevec = NULL_TREE;
20132             tree chain;
20133             int i, len = -1;
20134 
20135             /* Expand the argument expressions.  */
20136             if (TREE_PURPOSE (t))
20137               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
20138                                                  complain, in_decl);
20139             if (TREE_VALUE (t))
20140               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
20141                                                complain, in_decl);
20142 
20143             /* Build the rest of the list.  */
20144             chain = TREE_CHAIN (t);
20145             if (chain && chain != void_type_node)
20146               chain = RECUR (chain);
20147 
20148             /* Determine the number of arguments.  */
20149             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
20150               {
20151                 len = TREE_VEC_LENGTH (purposevec);
20152                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
20153               }
20154             else if (TREE_CODE (valuevec) == TREE_VEC)
20155               len = TREE_VEC_LENGTH (valuevec);
20156             else
20157               {
20158                 /* Since we only performed a partial substitution into
20159                    the argument pack, we only RETURN (a single list
20160                    node.  */
20161                 if (purposevec == TREE_PURPOSE (t)
20162                     && valuevec == TREE_VALUE (t)
20163                     && chain == TREE_CHAIN (t))
20164                   RETURN (t);
20165 
20166                 RETURN (tree_cons (purposevec, valuevec, chain));
20167               }
20168 
20169             /* Convert the argument vectors into a TREE_LIST */
20170             i = len;
20171             while (i > 0)
20172               {
20173                 /* Grab the Ith values.  */
20174                 i--;
20175                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i)
20176 		                     : NULL_TREE;
20177                 value
20178 		  = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i))
20179                              : NULL_TREE;
20180 
20181                 /* Build the list (backwards).  */
20182                 chain = tree_cons (purpose, value, chain);
20183               }
20184 
20185             RETURN (chain);
20186           }
20187 
20188 	purpose = TREE_PURPOSE (t);
20189 	if (purpose)
20190 	  purpose = RECUR (purpose);
20191 	value = TREE_VALUE (t);
20192 	if (value)
20193 	  value = RECUR (value);
20194 	chain = TREE_CHAIN (t);
20195 	if (chain && chain != void_type_node)
20196 	  chain = RECUR (chain);
20197 	if (purpose == TREE_PURPOSE (t)
20198 	    && value == TREE_VALUE (t)
20199 	    && chain == TREE_CHAIN (t))
20200 	  RETURN (t);
20201 	RETURN (tree_cons (purpose, value, chain));
20202       }
20203 
20204     case COMPONENT_REF:
20205       {
20206 	tree object;
20207 	tree object_type;
20208 	tree member;
20209 	tree r;
20210 
20211 	object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20212 						     args, complain, in_decl);
20213 	/* Remember that there was a reference to this entity.  */
20214 	if (DECL_P (object)
20215 	    && !mark_used (object, complain) && !(complain & tf_error))
20216 	  RETURN (error_mark_node);
20217 	object_type = TREE_TYPE (object);
20218 
20219 	member = TREE_OPERAND (t, 1);
20220 	if (BASELINK_P (member))
20221 	  member = tsubst_baselink (member,
20222 				    non_reference (TREE_TYPE (object)),
20223 				    args, complain, in_decl);
20224 	else
20225 	  member = tsubst_copy (member, args, complain, in_decl);
20226 	if (member == error_mark_node)
20227 	  RETURN (error_mark_node);
20228 
20229 	if (TREE_CODE (member) == FIELD_DECL)
20230 	  {
20231 	    r = finish_non_static_data_member (member, object, NULL_TREE);
20232 	    if (TREE_CODE (r) == COMPONENT_REF)
20233 	      REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
20234 	    RETURN (r);
20235 	  }
20236 	else if (type_dependent_expression_p (object))
20237 	  /* We can't do much here.  */;
20238 	else if (!CLASS_TYPE_P (object_type))
20239 	  {
20240 	    if (scalarish_type_p (object_type))
20241 	      {
20242 		tree s = NULL_TREE;
20243 		tree dtor = member;
20244 
20245 		if (TREE_CODE (dtor) == SCOPE_REF)
20246 		  {
20247 		    s = TREE_OPERAND (dtor, 0);
20248 		    dtor = TREE_OPERAND (dtor, 1);
20249 		  }
20250 		if (TREE_CODE (dtor) == BIT_NOT_EXPR)
20251 		  {
20252 		    dtor = TREE_OPERAND (dtor, 0);
20253 		    if (TYPE_P (dtor))
20254 		      RETURN (finish_pseudo_destructor_expr
20255 			      (object, s, dtor, input_location));
20256 		  }
20257 	      }
20258 	  }
20259 	else if (TREE_CODE (member) == SCOPE_REF
20260 		 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
20261 	  {
20262 	    /* Lookup the template functions now that we know what the
20263 	       scope is.  */
20264 	    tree scope = TREE_OPERAND (member, 0);
20265 	    tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
20266 	    tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
20267 	    member = lookup_qualified_name (scope, tmpl,
20268 					    /*is_type_p=*/false,
20269 					    /*complain=*/false);
20270 	    if (BASELINK_P (member))
20271 	      {
20272 		BASELINK_FUNCTIONS (member)
20273 		  = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
20274 			      args);
20275 		member = (adjust_result_of_qualified_name_lookup
20276 			  (member, BINFO_TYPE (BASELINK_BINFO (member)),
20277 			   object_type));
20278 	      }
20279 	    else
20280 	      {
20281 		qualified_name_lookup_error (scope, tmpl, member,
20282 					     input_location);
20283 		RETURN (error_mark_node);
20284 	      }
20285 	  }
20286 	else if (TREE_CODE (member) == SCOPE_REF
20287 		 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
20288 		 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
20289 	  {
20290 	    if (complain & tf_error)
20291 	      {
20292 		if (TYPE_P (TREE_OPERAND (member, 0)))
20293 		  error ("%qT is not a class or namespace",
20294 			 TREE_OPERAND (member, 0));
20295 		else
20296 		  error ("%qD is not a class or namespace",
20297 			 TREE_OPERAND (member, 0));
20298 	      }
20299 	    RETURN (error_mark_node);
20300 	  }
20301 
20302 	r = finish_class_member_access_expr (object, member,
20303 					     /*template_p=*/false,
20304 					     complain);
20305 	if (TREE_CODE (r) == COMPONENT_REF)
20306 	  REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
20307 	RETURN (r);
20308       }
20309 
20310     case THROW_EXPR:
20311       RETURN (build_throw
20312        (input_location, RECUR (TREE_OPERAND (t, 0))));
20313 
20314     case CONSTRUCTOR:
20315       {
20316 	vec<constructor_elt, va_gc> *n;
20317 	constructor_elt *ce;
20318 	unsigned HOST_WIDE_INT idx;
20319 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20320 	bool process_index_p;
20321         int newlen;
20322         bool need_copy_p = false;
20323 	tree r;
20324 
20325 	if (type == error_mark_node)
20326 	  RETURN (error_mark_node);
20327 
20328 	/* We do not want to process the index of aggregate
20329 	   initializers as they are identifier nodes which will be
20330 	   looked up by digest_init.  */
20331 	process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
20332 
20333 	if (null_member_pointer_value_p (t))
20334 	  {
20335 	    gcc_assert (same_type_p (type, TREE_TYPE (t)));
20336 	    RETURN (t);
20337 	  }
20338 
20339 	n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
20340         newlen = vec_safe_length (n);
20341 	FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
20342 	  {
20343 	    if (ce->index && process_index_p
20344 		/* An identifier index is looked up in the type
20345 		   being initialized, not the current scope.  */
20346 		&& TREE_CODE (ce->index) != IDENTIFIER_NODE)
20347 	      ce->index = RECUR (ce->index);
20348 
20349             if (PACK_EXPANSION_P (ce->value))
20350               {
20351                 /* Substitute into the pack expansion.  */
20352                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
20353                                                   in_decl);
20354 
20355 		if (ce->value == error_mark_node
20356 		    || PACK_EXPANSION_P (ce->value))
20357 		  ;
20358 		else if (TREE_VEC_LENGTH (ce->value) == 1)
20359                   /* Just move the argument into place.  */
20360                   ce->value = TREE_VEC_ELT (ce->value, 0);
20361                 else
20362                   {
20363                     /* Update the length of the final CONSTRUCTOR
20364                        arguments vector, and note that we will need to
20365                        copy.*/
20366                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
20367                     need_copy_p = true;
20368                   }
20369               }
20370             else
20371               ce->value = RECUR (ce->value);
20372 	  }
20373 
20374         if (need_copy_p)
20375           {
20376             vec<constructor_elt, va_gc> *old_n = n;
20377 
20378             vec_alloc (n, newlen);
20379             FOR_EACH_VEC_ELT (*old_n, idx, ce)
20380               {
20381                 if (TREE_CODE (ce->value) == TREE_VEC)
20382                   {
20383                     int i, len = TREE_VEC_LENGTH (ce->value);
20384                     for (i = 0; i < len; ++i)
20385                       CONSTRUCTOR_APPEND_ELT (n, 0,
20386                                               TREE_VEC_ELT (ce->value, i));
20387                   }
20388                 else
20389                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
20390               }
20391           }
20392 
20393 	r = build_constructor (init_list_type_node, n);
20394 	CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
20395 	CONSTRUCTOR_IS_DESIGNATED_INIT (r)
20396 	  = CONSTRUCTOR_IS_DESIGNATED_INIT (t);
20397 
20398 	if (TREE_HAS_CONSTRUCTOR (t))
20399 	  {
20400 	    fcl_t cl = fcl_functional;
20401 	    if (CONSTRUCTOR_C99_COMPOUND_LITERAL (t))
20402 	      cl = fcl_c99;
20403 	    RETURN (finish_compound_literal (type, r, complain, cl));
20404 	  }
20405 
20406 	TREE_TYPE (r) = type;
20407 	RETURN (r);
20408       }
20409 
20410     case TYPEID_EXPR:
20411       {
20412 	tree operand_0 = TREE_OPERAND (t, 0);
20413 	if (TYPE_P (operand_0))
20414 	  {
20415 	    operand_0 = tsubst (operand_0, args, complain, in_decl);
20416 	    RETURN (get_typeid (operand_0, complain));
20417 	  }
20418 	else
20419 	  {
20420 	    operand_0 = RECUR (operand_0);
20421 	    RETURN (build_typeid (operand_0, complain));
20422 	  }
20423       }
20424 
20425     case VAR_DECL:
20426       if (!args)
20427 	RETURN (t);
20428       /* Fall through */
20429 
20430     case PARM_DECL:
20431       {
20432 	tree r = tsubst_copy (t, args, complain, in_decl);
20433 	/* ??? We're doing a subset of finish_id_expression here.  */
20434 	if (tree wrap = maybe_get_tls_wrapper_call (r))
20435 	  /* Replace an evaluated use of the thread_local variable with
20436 	     a call to its wrapper.  */
20437 	  r = wrap;
20438 	else if (outer_automatic_var_p (r))
20439 	  r = process_outer_var_ref (r, complain);
20440 
20441 	if (!TYPE_REF_P (TREE_TYPE (t)))
20442 	  /* If the original type was a reference, we'll be wrapped in
20443 	     the appropriate INDIRECT_REF.  */
20444 	  r = convert_from_reference (r);
20445 	RETURN (r);
20446       }
20447 
20448     case VA_ARG_EXPR:
20449       {
20450 	tree op0 = RECUR (TREE_OPERAND (t, 0));
20451 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20452 	RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
20453       }
20454 
20455     case OFFSETOF_EXPR:
20456       {
20457 	tree object_ptr
20458 	  = tsubst_copy_and_build (TREE_OPERAND (t, 1), args, complain,
20459 				   in_decl, /*function_p=*/false,
20460 				   /*integral_constant_expression_p=*/false);
20461 	RETURN (finish_offsetof (object_ptr,
20462 				 RECUR (TREE_OPERAND (t, 0)),
20463 				 EXPR_LOCATION (t)));
20464       }
20465 
20466     case ADDRESSOF_EXPR:
20467       RETURN (cp_build_addressof (EXPR_LOCATION (t),
20468 				  RECUR (TREE_OPERAND (t, 0)), complain));
20469 
20470     case TRAIT_EXPR:
20471       {
20472 	tree type1 = tsubst (TRAIT_EXPR_TYPE1 (t), args,
20473 			     complain, in_decl);
20474 	tree type2 = tsubst (TRAIT_EXPR_TYPE2 (t), args,
20475 			     complain, in_decl);
20476 	RETURN (finish_trait_expr (TRAIT_EXPR_LOCATION (t),
20477 				   TRAIT_EXPR_KIND (t), type1, type2));
20478       }
20479 
20480     case STMT_EXPR:
20481       {
20482 	tree old_stmt_expr = cur_stmt_expr;
20483 	tree stmt_expr = begin_stmt_expr ();
20484 
20485 	cur_stmt_expr = stmt_expr;
20486 	tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
20487 		     integral_constant_expression_p);
20488 	stmt_expr = finish_stmt_expr (stmt_expr, false);
20489 	cur_stmt_expr = old_stmt_expr;
20490 
20491 	/* If the resulting list of expression statement is empty,
20492 	   fold it further into void_node.  */
20493 	if (empty_expr_stmt_p (stmt_expr))
20494 	  stmt_expr = void_node;
20495 
20496 	RETURN (stmt_expr);
20497       }
20498 
20499     case LAMBDA_EXPR:
20500       {
20501 	if (complain & tf_partial)
20502 	  {
20503 	    /* We don't have a full set of template arguments yet; don't touch
20504 	       the lambda at all.  */
20505 	    gcc_assert (processing_template_decl);
20506 	    return t;
20507 	  }
20508 	tree r = tsubst_lambda_expr (t, args, complain, in_decl);
20509 
20510 	RETURN (build_lambda_object (r));
20511       }
20512 
20513     case TARGET_EXPR:
20514       /* We can get here for a constant initializer of non-dependent type.
20515          FIXME stop folding in cp_parser_initializer_clause.  */
20516       {
20517 	tree r = get_target_expr_sfinae (RECUR (TARGET_EXPR_INITIAL (t)),
20518 					 complain);
20519 	RETURN (r);
20520       }
20521 
20522     case TRANSACTION_EXPR:
20523       RETURN (tsubst_expr(t, args, complain, in_decl,
20524 	     integral_constant_expression_p));
20525 
20526     case PAREN_EXPR:
20527       RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
20528 
20529     case VEC_PERM_EXPR:
20530       {
20531 	tree op0 = RECUR (TREE_OPERAND (t, 0));
20532 	tree op1 = RECUR (TREE_OPERAND (t, 1));
20533 	tree op2 = RECUR (TREE_OPERAND (t, 2));
20534 	RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
20535 				       complain));
20536       }
20537 
20538     case REQUIRES_EXPR:
20539       {
20540 	tree r = tsubst_requires_expr (t, args, tf_none, in_decl);
20541 	RETURN (r);
20542       }
20543 
20544     case RANGE_EXPR:
20545       /* No need to substitute further, a RANGE_EXPR will always be built
20546 	 with constant operands.  */
20547       RETURN (t);
20548 
20549     case NON_LVALUE_EXPR:
20550     case VIEW_CONVERT_EXPR:
20551       if (location_wrapper_p (t))
20552 	/* We need to do this here as well as in tsubst_copy so we get the
20553 	   other tsubst_copy_and_build semantics for a PARM_DECL operand.  */
20554 	RETURN (maybe_wrap_with_location (RECUR (TREE_OPERAND (t, 0)),
20555 					  EXPR_LOCATION (t)));
20556       /* fallthrough.  */
20557 
20558     default:
20559       /* Handle Objective-C++ constructs, if appropriate.  */
20560       {
20561 	tree subst
20562 	  = objcp_tsubst_copy_and_build (t, args, complain,
20563 					 in_decl, /*function_p=*/false);
20564 	if (subst)
20565 	  RETURN (subst);
20566       }
20567       RETURN (tsubst_copy (t, args, complain, in_decl));
20568     }
20569 
20570 #undef RECUR
20571 #undef RETURN
20572  out:
20573   input_location = save_loc;
20574   return retval;
20575 }
20576 
20577 /* Verify that the instantiated ARGS are valid. For type arguments,
20578    make sure that the type's linkage is ok. For non-type arguments,
20579    make sure they are constants if they are integral or enumerations.
20580    Emit an error under control of COMPLAIN, and return TRUE on error.  */
20581 
20582 static bool
check_instantiated_arg(tree tmpl,tree t,tsubst_flags_t complain)20583 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
20584 {
20585   if (dependent_template_arg_p (t))
20586     return false;
20587   if (ARGUMENT_PACK_P (t))
20588     {
20589       tree vec = ARGUMENT_PACK_ARGS (t);
20590       int len = TREE_VEC_LENGTH (vec);
20591       bool result = false;
20592       int i;
20593 
20594       for (i = 0; i < len; ++i)
20595 	if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
20596 	  result = true;
20597       return result;
20598     }
20599   else if (TYPE_P (t))
20600     {
20601       /* [basic.link]: A name with no linkage (notably, the name
20602 	 of a class or enumeration declared in a local scope)
20603 	 shall not be used to declare an entity with linkage.
20604 	 This implies that names with no linkage cannot be used as
20605 	 template arguments
20606 
20607 	 DR 757 relaxes this restriction for C++0x.  */
20608       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
20609 		 : no_linkage_check (t, /*relaxed_p=*/false));
20610 
20611       if (nt)
20612 	{
20613 	  /* DR 488 makes use of a type with no linkage cause
20614 	     type deduction to fail.  */
20615 	  if (complain & tf_error)
20616 	    {
20617 	      if (TYPE_UNNAMED_P (nt))
20618 		error ("%qT is/uses unnamed type", t);
20619 	      else
20620 		error ("template argument for %qD uses local type %qT",
20621 		       tmpl, t);
20622 	    }
20623 	  return true;
20624 	}
20625       /* In order to avoid all sorts of complications, we do not
20626 	 allow variably-modified types as template arguments.  */
20627       else if (variably_modified_type_p (t, NULL_TREE))
20628 	{
20629 	  if (complain & tf_error)
20630 	    error ("%qT is a variably modified type", t);
20631 	  return true;
20632 	}
20633     }
20634   /* Class template and alias template arguments should be OK.  */
20635   else if (DECL_TYPE_TEMPLATE_P (t))
20636     ;
20637   /* A non-type argument of integral or enumerated type must be a
20638      constant.  */
20639   else if (TREE_TYPE (t)
20640 	   && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
20641 	   && !REFERENCE_REF_P (t)
20642 	   && !TREE_CONSTANT (t))
20643     {
20644       if (complain & tf_error)
20645 	error ("integral expression %qE is not constant", t);
20646       return true;
20647     }
20648   return false;
20649 }
20650 
20651 static bool
check_instantiated_args(tree tmpl,tree args,tsubst_flags_t complain)20652 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
20653 {
20654   int ix, len = DECL_NTPARMS (tmpl);
20655   bool result = false;
20656 
20657   for (ix = 0; ix != len; ix++)
20658     {
20659       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
20660 	result = true;
20661     }
20662   if (result && (complain & tf_error))
20663     error ("  trying to instantiate %qD", tmpl);
20664   return result;
20665 }
20666 
20667 /* We're out of SFINAE context now, so generate diagnostics for the access
20668    errors we saw earlier when instantiating D from TMPL and ARGS.  */
20669 
20670 static void
recheck_decl_substitution(tree d,tree tmpl,tree args)20671 recheck_decl_substitution (tree d, tree tmpl, tree args)
20672 {
20673   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
20674   tree type = TREE_TYPE (pattern);
20675   location_t loc = input_location;
20676 
20677   push_access_scope (d);
20678   push_deferring_access_checks (dk_no_deferred);
20679   input_location = DECL_SOURCE_LOCATION (pattern);
20680   tsubst (type, args, tf_warning_or_error, d);
20681   input_location = loc;
20682   pop_deferring_access_checks ();
20683   pop_access_scope (d);
20684 }
20685 
20686 /* Instantiate the indicated variable, function, or alias template TMPL with
20687    the template arguments in TARG_PTR.  */
20688 
20689 static tree
instantiate_template_1(tree tmpl,tree orig_args,tsubst_flags_t complain)20690 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
20691 {
20692   tree targ_ptr = orig_args;
20693   tree fndecl;
20694   tree gen_tmpl;
20695   tree spec;
20696   bool access_ok = true;
20697 
20698   if (tmpl == error_mark_node)
20699     return error_mark_node;
20700 
20701   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
20702 
20703   /* If this function is a clone, handle it specially.  */
20704   if (DECL_CLONED_FUNCTION_P (tmpl))
20705     {
20706       tree spec;
20707       tree clone;
20708 
20709       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
20710 	 DECL_CLONED_FUNCTION.  */
20711       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
20712 				   targ_ptr, complain);
20713       if (spec == error_mark_node)
20714 	return error_mark_node;
20715 
20716       /* Look for the clone.  */
20717       FOR_EACH_CLONE (clone, spec)
20718 	if (DECL_NAME (clone) == DECL_NAME (tmpl))
20719 	  return clone;
20720       /* We should always have found the clone by now.  */
20721       gcc_unreachable ();
20722       return NULL_TREE;
20723     }
20724 
20725   if (targ_ptr == error_mark_node)
20726     return error_mark_node;
20727 
20728   /* Check to see if we already have this specialization.  */
20729   gen_tmpl = most_general_template (tmpl);
20730   if (TMPL_ARGS_DEPTH (targ_ptr)
20731       < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)))
20732     /* targ_ptr only has the innermost template args, so add the outer ones
20733        from tmpl, which could be either a partial instantiation or gen_tmpl (in
20734        the case of a non-dependent call within a template definition).  */
20735     targ_ptr = (add_outermost_template_args
20736 		(DECL_TI_ARGS (DECL_TEMPLATE_RESULT (tmpl)),
20737 		 targ_ptr));
20738 
20739   /* It would be nice to avoid hashing here and then again in tsubst_decl,
20740      but it doesn't seem to be on the hot path.  */
20741   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
20742 
20743   gcc_assert (tmpl == gen_tmpl
20744 	      || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
20745 		  == spec)
20746 	      || fndecl == NULL_TREE);
20747 
20748   if (spec != NULL_TREE)
20749     {
20750       if (FNDECL_HAS_ACCESS_ERRORS (spec))
20751 	{
20752 	  if (complain & tf_error)
20753 	    recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
20754 	  return error_mark_node;
20755 	}
20756       return spec;
20757     }
20758 
20759   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
20760 			       complain))
20761     return error_mark_node;
20762 
20763   /* We are building a FUNCTION_DECL, during which the access of its
20764      parameters and return types have to be checked.  However this
20765      FUNCTION_DECL which is the desired context for access checking
20766      is not built yet.  We solve this chicken-and-egg problem by
20767      deferring all checks until we have the FUNCTION_DECL.  */
20768   push_deferring_access_checks (dk_deferred);
20769 
20770   /* Instantiation of the function happens in the context of the function
20771      template, not the context of the overload resolution we're doing.  */
20772   push_to_top_level ();
20773   /* If there are dependent arguments, e.g. because we're doing partial
20774      ordering, make sure processing_template_decl stays set.  */
20775   if (uses_template_parms (targ_ptr))
20776     ++processing_template_decl;
20777   if (DECL_CLASS_SCOPE_P (gen_tmpl))
20778     {
20779       tree ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
20780 				   complain, gen_tmpl, true);
20781       push_nested_class (ctx);
20782     }
20783 
20784   tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
20785 
20786   fndecl = NULL_TREE;
20787   if (VAR_P (pattern))
20788     {
20789       /* We need to determine if we're using a partial or explicit
20790 	 specialization now, because the type of the variable could be
20791 	 different.  */
20792       tree tid = lookup_template_variable (gen_tmpl, targ_ptr);
20793       tree elt = most_specialized_partial_spec (tid, complain);
20794       if (elt == error_mark_node)
20795 	pattern = error_mark_node;
20796       else if (elt)
20797 	{
20798 	  tree partial_tmpl = TREE_VALUE (elt);
20799 	  tree partial_args = TREE_PURPOSE (elt);
20800 	  tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
20801 	  fndecl = tsubst (partial_pat, partial_args, complain, gen_tmpl);
20802 	}
20803     }
20804 
20805   /* Substitute template parameters to obtain the specialization.  */
20806   if (fndecl == NULL_TREE)
20807     fndecl = tsubst (pattern, targ_ptr, complain, gen_tmpl);
20808   if (DECL_CLASS_SCOPE_P (gen_tmpl))
20809     pop_nested_class ();
20810   pop_from_top_level ();
20811 
20812   if (fndecl == error_mark_node)
20813     {
20814       pop_deferring_access_checks ();
20815       return error_mark_node;
20816     }
20817 
20818   /* The DECL_TI_TEMPLATE should always be the immediate parent
20819      template, not the most general template.  */
20820   DECL_TI_TEMPLATE (fndecl) = tmpl;
20821   DECL_TI_ARGS (fndecl) = targ_ptr;
20822 
20823   /* Now we know the specialization, compute access previously
20824      deferred.  Do no access control for inheriting constructors,
20825      as we already checked access for the inherited constructor.  */
20826   if (!(flag_new_inheriting_ctors
20827 	&& DECL_INHERITED_CTOR (fndecl)))
20828     {
20829       push_access_scope (fndecl);
20830       if (!perform_deferred_access_checks (complain))
20831 	access_ok = false;
20832       pop_access_scope (fndecl);
20833     }
20834   pop_deferring_access_checks ();
20835 
20836   /* If we've just instantiated the main entry point for a function,
20837      instantiate all the alternate entry points as well.  We do this
20838      by cloning the instantiation of the main entry point, not by
20839      instantiating the template clones.  */
20840   if (tree chain = DECL_CHAIN (gen_tmpl))
20841     if (DECL_P (chain) && DECL_CLONED_FUNCTION_P (chain))
20842       clone_function_decl (fndecl, /*update_methods=*/false);
20843 
20844   if (!access_ok)
20845     {
20846       if (!(complain & tf_error))
20847 	{
20848 	  /* Remember to reinstantiate when we're out of SFINAE so the user
20849 	     can see the errors.  */
20850 	  FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
20851 	}
20852       return error_mark_node;
20853     }
20854   return fndecl;
20855 }
20856 
20857 /* Wrapper for instantiate_template_1.  */
20858 
20859 tree
instantiate_template(tree tmpl,tree orig_args,tsubst_flags_t complain)20860 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
20861 {
20862   tree ret;
20863   timevar_push (TV_TEMPLATE_INST);
20864   ret = instantiate_template_1 (tmpl, orig_args,  complain);
20865   timevar_pop (TV_TEMPLATE_INST);
20866   return ret;
20867 }
20868 
20869 /* Instantiate the alias template TMPL with ARGS.  Also push a template
20870    instantiation level, which instantiate_template doesn't do because
20871    functions and variables have sufficient context established by the
20872    callers.  */
20873 
20874 static tree
instantiate_alias_template(tree tmpl,tree args,tsubst_flags_t complain)20875 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
20876 {
20877   if (tmpl == error_mark_node || args == error_mark_node)
20878     return error_mark_node;
20879 
20880   args =
20881     coerce_innermost_template_parms (DECL_TEMPLATE_PARMS (tmpl),
20882 				     args, tmpl, complain,
20883 				     /*require_all_args=*/true,
20884 				     /*use_default_args=*/true);
20885 
20886   /* FIXME check for satisfaction in check_instantiated_args.  */
20887   if (flag_concepts
20888       && !any_dependent_template_arguments_p (args)
20889       && !constraints_satisfied_p (tmpl, args))
20890     {
20891       if (complain & tf_error)
20892 	{
20893 	  auto_diagnostic_group d;
20894 	  error ("template constraint failure for %qD", tmpl);
20895 	  diagnose_constraints (input_location, tmpl, args);
20896 	}
20897       return error_mark_node;
20898     }
20899 
20900   if (!push_tinst_level (tmpl, args))
20901     return error_mark_node;
20902   tree r = instantiate_template (tmpl, args, complain);
20903   pop_tinst_level ();
20904 
20905   return r;
20906 }
20907 
20908 /* PARM is a template parameter pack for FN.  Returns true iff
20909    PARM is used in a deducible way in the argument list of FN.  */
20910 
20911 static bool
pack_deducible_p(tree parm,tree fn)20912 pack_deducible_p (tree parm, tree fn)
20913 {
20914   tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
20915   for (; t; t = TREE_CHAIN (t))
20916     {
20917       tree type = TREE_VALUE (t);
20918       tree packs;
20919       if (!PACK_EXPANSION_P (type))
20920 	continue;
20921       for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
20922 	   packs; packs = TREE_CHAIN (packs))
20923 	if (template_args_equal (TREE_VALUE (packs), parm))
20924 	  {
20925 	    /* The template parameter pack is used in a function parameter
20926 	       pack.  If this is the end of the parameter list, the
20927 	       template parameter pack is deducible.  */
20928 	    if (TREE_CHAIN (t) == void_list_node)
20929 	      return true;
20930 	    else
20931 	      /* Otherwise, not.  Well, it could be deduced from
20932 		 a non-pack parameter, but doing so would end up with
20933 		 a deduction mismatch, so don't bother.  */
20934 	      return false;
20935 	  }
20936     }
20937   /* The template parameter pack isn't used in any function parameter
20938      packs, but it might be used deeper, e.g. tuple<Args...>.  */
20939   return true;
20940 }
20941 
20942 /* Subroutine of fn_type_unification: check non-dependent parms for
20943    convertibility.  */
20944 
20945 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)20946 check_non_deducible_conversions (tree parms, const tree *args, unsigned nargs,
20947 				 tree fn, unification_kind_t strict, int flags,
20948 				 struct conversion **convs, bool explain_p)
20949 {
20950   /* Non-constructor methods need to leave a conversion for 'this', which
20951      isn't included in nargs here.  */
20952   unsigned offset = (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
20953 		     && !DECL_CONSTRUCTOR_P (fn));
20954 
20955   for (unsigned ia = 0;
20956        parms && parms != void_list_node && ia < nargs; )
20957     {
20958       tree parm = TREE_VALUE (parms);
20959 
20960       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
20961 	  && (!TREE_CHAIN (parms)
20962 	      || TREE_CHAIN (parms) == void_list_node))
20963 	/* For a function parameter pack that occurs at the end of the
20964 	   parameter-declaration-list, the type A of each remaining
20965 	   argument of the call is compared with the type P of the
20966 	   declarator-id of the function parameter pack.  */
20967 	break;
20968 
20969       parms = TREE_CHAIN (parms);
20970 
20971       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
20972 	/* For a function parameter pack that does not occur at the
20973 	   end of the parameter-declaration-list, the type of the
20974 	   parameter pack is a non-deduced context.  */
20975 	continue;
20976 
20977       if (!uses_template_parms (parm))
20978 	{
20979 	  tree arg = args[ia];
20980 	  conversion **conv_p = convs ? &convs[ia+offset] : NULL;
20981 	  int lflags = conv_flags (ia, nargs, fn, arg, flags);
20982 
20983 	  if (check_non_deducible_conversion (parm, arg, strict, lflags,
20984 					      conv_p, explain_p))
20985 	    return 1;
20986 	}
20987 
20988       ++ia;
20989     }
20990 
20991   return 0;
20992 }
20993 
20994 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
20995    NARGS elements of the arguments that are being used when calling
20996    it.  TARGS is a vector into which the deduced template arguments
20997    are placed.
20998 
20999    Returns either a FUNCTION_DECL for the matching specialization of FN or
21000    NULL_TREE if no suitable specialization can be found.  If EXPLAIN_P is
21001    true, diagnostics will be printed to explain why it failed.
21002 
21003    If FN is a conversion operator, or we are trying to produce a specific
21004    specialization, RETURN_TYPE is the return type desired.
21005 
21006    The EXPLICIT_TARGS are explicit template arguments provided via a
21007    template-id.
21008 
21009    The parameter STRICT is one of:
21010 
21011    DEDUCE_CALL:
21012      We are deducing arguments for a function call, as in
21013      [temp.deduct.call].  If RETURN_TYPE is non-null, we are
21014      deducing arguments for a call to the result of a conversion
21015      function template, as in [over.call.object].
21016 
21017    DEDUCE_CONV:
21018      We are deducing arguments for a conversion function, as in
21019      [temp.deduct.conv].
21020 
21021    DEDUCE_EXACT:
21022      We are deducing arguments when doing an explicit instantiation
21023      as in [temp.explicit], when determining an explicit specialization
21024      as in [temp.expl.spec], or when taking the address of a function
21025      template, as in [temp.deduct.funcaddr].  */
21026 
21027 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)21028 fn_type_unification (tree fn,
21029 		     tree explicit_targs,
21030 		     tree targs,
21031 		     const tree *args,
21032 		     unsigned int nargs,
21033 		     tree return_type,
21034 		     unification_kind_t strict,
21035 		     int flags,
21036 		     struct conversion **convs,
21037 		     bool explain_p,
21038 		     bool decltype_p)
21039 {
21040   tree parms;
21041   tree fntype;
21042   tree decl = NULL_TREE;
21043   tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
21044   bool ok;
21045   static int deduction_depth;
21046   /* type_unification_real will pass back any access checks from default
21047      template argument substitution.  */
21048   vec<deferred_access_check, va_gc> *checks = NULL;
21049   /* We don't have all the template args yet.  */
21050   bool incomplete = true;
21051 
21052   tree orig_fn = fn;
21053   if (flag_new_inheriting_ctors)
21054     fn = strip_inheriting_ctors (fn);
21055 
21056   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
21057   tree r = error_mark_node;
21058 
21059   tree full_targs = targs;
21060   if (TMPL_ARGS_DEPTH (targs)
21061       < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (fn)))
21062     full_targs = (add_outermost_template_args
21063 		  (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (fn)),
21064 		   targs));
21065 
21066   if (decltype_p)
21067     complain |= tf_decltype;
21068 
21069   /* In C++0x, it's possible to have a function template whose type depends
21070      on itself recursively.  This is most obvious with decltype, but can also
21071      occur with enumeration scope (c++/48969).  So we need to catch infinite
21072      recursion and reject the substitution at deduction time; this function
21073      will return error_mark_node for any repeated substitution.
21074 
21075      This also catches excessive recursion such as when f<N> depends on
21076      f<N-1> across all integers, and returns error_mark_node for all the
21077      substitutions back up to the initial one.
21078 
21079      This is, of course, not reentrant.  */
21080   if (excessive_deduction_depth)
21081     return error_mark_node;
21082   ++deduction_depth;
21083 
21084   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
21085 
21086   fntype = TREE_TYPE (fn);
21087   if (explicit_targs)
21088     {
21089       /* [temp.deduct]
21090 
21091 	 The specified template arguments must match the template
21092 	 parameters in kind (i.e., type, nontype, template), and there
21093 	 must not be more arguments than there are parameters;
21094 	 otherwise type deduction fails.
21095 
21096 	 Nontype arguments must match the types of the corresponding
21097 	 nontype template parameters, or must be convertible to the
21098 	 types of the corresponding nontype parameters as specified in
21099 	 _temp.arg.nontype_, otherwise type deduction fails.
21100 
21101 	 All references in the function type of the function template
21102 	 to the corresponding template parameters are replaced by the
21103 	 specified template argument values.  If a substitution in a
21104 	 template parameter or in the function type of the function
21105 	 template results in an invalid type, type deduction fails.  */
21106       int i, len = TREE_VEC_LENGTH (tparms);
21107       location_t loc = input_location;
21108       incomplete = false;
21109 
21110       if (explicit_targs == error_mark_node)
21111 	goto fail;
21112 
21113       if (TMPL_ARGS_DEPTH (explicit_targs)
21114 	  < TMPL_ARGS_DEPTH (full_targs))
21115 	explicit_targs = add_outermost_template_args (full_targs,
21116 						      explicit_targs);
21117 
21118       /* Adjust any explicit template arguments before entering the
21119 	 substitution context.  */
21120       explicit_targs
21121 	= (coerce_template_parms (tparms, explicit_targs, NULL_TREE,
21122 				  complain|tf_partial,
21123 				  /*require_all_args=*/false,
21124 				  /*use_default_args=*/false));
21125       if (explicit_targs == error_mark_node)
21126 	goto fail;
21127 
21128       /* Substitute the explicit args into the function type.  This is
21129 	 necessary so that, for instance, explicitly declared function
21130 	 arguments can match null pointed constants.  If we were given
21131 	 an incomplete set of explicit args, we must not do semantic
21132 	 processing during substitution as we could create partial
21133 	 instantiations.  */
21134       for (i = 0; i < len; i++)
21135         {
21136           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
21137           bool parameter_pack = false;
21138 	  tree targ = TREE_VEC_ELT (explicit_targs, i);
21139 
21140           /* Dig out the actual parm.  */
21141           if (TREE_CODE (parm) == TYPE_DECL
21142               || TREE_CODE (parm) == TEMPLATE_DECL)
21143             {
21144               parm = TREE_TYPE (parm);
21145               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
21146             }
21147           else if (TREE_CODE (parm) == PARM_DECL)
21148             {
21149               parm = DECL_INITIAL (parm);
21150               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
21151             }
21152 
21153 	  if (targ == NULL_TREE)
21154 	    /* No explicit argument for this template parameter.  */
21155 	    incomplete = true;
21156 	  else if (parameter_pack && pack_deducible_p (parm, fn))
21157             {
21158               /* Mark the argument pack as "incomplete". We could
21159                  still deduce more arguments during unification.
21160 	         We remove this mark in type_unification_real.  */
21161 	      ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
21162 	      ARGUMENT_PACK_EXPLICIT_ARGS (targ)
21163 		= ARGUMENT_PACK_ARGS (targ);
21164 
21165               /* We have some incomplete argument packs.  */
21166               incomplete = true;
21167             }
21168         }
21169 
21170       if (incomplete)
21171 	{
21172 	  if (!push_tinst_level (fn, explicit_targs))
21173 	    {
21174 	      excessive_deduction_depth = true;
21175 	      goto fail;
21176 	    }
21177 	  ++processing_template_decl;
21178 	  input_location = DECL_SOURCE_LOCATION (fn);
21179 	  /* Ignore any access checks; we'll see them again in
21180 	     instantiate_template and they might have the wrong
21181 	     access path at this point.  */
21182 	  push_deferring_access_checks (dk_deferred);
21183 	  tsubst_flags_t ecomplain = complain | tf_partial | tf_fndecl_type;
21184 	  fntype = tsubst (TREE_TYPE (fn), explicit_targs, ecomplain, NULL_TREE);
21185 	  pop_deferring_access_checks ();
21186 	  input_location = loc;
21187 	  --processing_template_decl;
21188 	  pop_tinst_level ();
21189 
21190 	  if (fntype == error_mark_node)
21191 	    goto fail;
21192 	}
21193 
21194       /* Place the explicitly specified arguments in TARGS.  */
21195       explicit_targs = INNERMOST_TEMPLATE_ARGS (explicit_targs);
21196       for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
21197 	TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
21198       if (!incomplete && CHECKING_P
21199 	  && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
21200 	SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
21201 	  (targs, NUM_TMPL_ARGS (explicit_targs));
21202     }
21203 
21204   if (return_type && strict != DEDUCE_CALL)
21205     {
21206       tree *new_args = XALLOCAVEC (tree, nargs + 1);
21207       new_args[0] = return_type;
21208       memcpy (new_args + 1, args, nargs * sizeof (tree));
21209       args = new_args;
21210       ++nargs;
21211     }
21212 
21213   if (!incomplete)
21214     goto deduced;
21215 
21216   /* Never do unification on the 'this' parameter.  */
21217   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
21218 
21219   if (return_type && strict == DEDUCE_CALL)
21220     {
21221       /* We're deducing for a call to the result of a template conversion
21222          function.  The parms we really want are in return_type.  */
21223       if (INDIRECT_TYPE_P (return_type))
21224 	return_type = TREE_TYPE (return_type);
21225       parms = TYPE_ARG_TYPES (return_type);
21226     }
21227   else if (return_type)
21228     {
21229       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
21230     }
21231 
21232   /* We allow incomplete unification without an error message here
21233      because the standard doesn't seem to explicitly prohibit it.  Our
21234      callers must be ready to deal with unification failures in any
21235      event.  */
21236 
21237   /* If we aren't explaining yet, push tinst context so we can see where
21238      any errors (e.g. from class instantiations triggered by instantiation
21239      of default template arguments) come from.  If we are explaining, this
21240      context is redundant.  */
21241   if (!explain_p && !push_tinst_level (fn, targs))
21242     {
21243       excessive_deduction_depth = true;
21244       goto fail;
21245     }
21246 
21247   ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
21248 			       full_targs, parms, args, nargs, /*subr=*/0,
21249 			       strict, &checks, explain_p);
21250   if (!explain_p)
21251     pop_tinst_level ();
21252   if (!ok)
21253     goto fail;
21254 
21255   /* Now that we have bindings for all of the template arguments,
21256      ensure that the arguments deduced for the template template
21257      parameters have compatible template parameter lists.  We cannot
21258      check this property before we have deduced all template
21259      arguments, because the template parameter types of a template
21260      template parameter might depend on prior template parameters
21261      deduced after the template template parameter.  The following
21262      ill-formed example illustrates this issue:
21263 
21264        template<typename T, template<T> class C> void f(C<5>, T);
21265 
21266        template<int N> struct X {};
21267 
21268        void g() {
21269          f(X<5>(), 5l); // error: template argument deduction fails
21270        }
21271 
21272      The template parameter list of 'C' depends on the template type
21273      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
21274      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
21275      time that we deduce 'C'.  */
21276   if (!template_template_parm_bindings_ok_p
21277            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
21278     {
21279       unify_inconsistent_template_template_parameters (explain_p);
21280       goto fail;
21281     }
21282 
21283   /* DR 1391: All parameters have args, now check non-dependent parms for
21284      convertibility.  */
21285   if (check_non_deducible_conversions (parms, args, nargs, fn, strict, flags,
21286 				       convs, explain_p))
21287     goto fail;
21288 
21289  deduced:
21290   /* All is well so far.  Now, check:
21291 
21292      [temp.deduct]
21293 
21294      When all template arguments have been deduced, all uses of
21295      template parameters in nondeduced contexts are replaced with
21296      the corresponding deduced argument values.  If the
21297      substitution results in an invalid type, as described above,
21298      type deduction fails.  */
21299   if (!push_tinst_level (fn, targs))
21300     {
21301       excessive_deduction_depth = true;
21302       goto fail;
21303     }
21304 
21305   /* Also collect access checks from the instantiation.  */
21306   reopen_deferring_access_checks (checks);
21307 
21308   decl = instantiate_template (fn, targs, complain);
21309 
21310   checks = get_deferred_access_checks ();
21311   pop_deferring_access_checks ();
21312 
21313   pop_tinst_level ();
21314 
21315   if (decl == error_mark_node)
21316     goto fail;
21317 
21318   /* Now perform any access checks encountered during substitution.  */
21319   push_access_scope (decl);
21320   ok = perform_access_checks (checks, complain);
21321   pop_access_scope (decl);
21322   if (!ok)
21323     goto fail;
21324 
21325   /* If we're looking for an exact match, check that what we got
21326      is indeed an exact match.  It might not be if some template
21327      parameters are used in non-deduced contexts.  But don't check
21328      for an exact match if we have dependent template arguments;
21329      in that case we're doing partial ordering, and we already know
21330      that we have two candidates that will provide the actual type.  */
21331   if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
21332     {
21333       tree substed = TREE_TYPE (decl);
21334       unsigned int i;
21335 
21336       tree sarg
21337 	= skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
21338       if (return_type)
21339 	sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
21340       for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
21341 	if (!same_type_p (args[i], TREE_VALUE (sarg)))
21342 	  {
21343 	    unify_type_mismatch (explain_p, args[i],
21344 				 TREE_VALUE (sarg));
21345 	    goto fail;
21346 	  }
21347     }
21348 
21349   /* After doing deduction with the inherited constructor, actually return an
21350      instantiation of the inheriting constructor.  */
21351   if (orig_fn != fn)
21352     decl = instantiate_template (orig_fn, targs, complain);
21353 
21354   r = decl;
21355 
21356  fail:
21357   --deduction_depth;
21358   if (excessive_deduction_depth)
21359     {
21360       if (deduction_depth == 0)
21361 	/* Reset once we're all the way out.  */
21362 	excessive_deduction_depth = false;
21363     }
21364 
21365   return r;
21366 }
21367 
21368 /* Adjust types before performing type deduction, as described in
21369    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
21370    sections are symmetric.  PARM is the type of a function parameter
21371    or the return type of the conversion function.  ARG is the type of
21372    the argument passed to the call, or the type of the value
21373    initialized with the result of the conversion function.
21374    ARG_EXPR is the original argument expression, which may be null.  */
21375 
21376 static int
maybe_adjust_types_for_deduction(unification_kind_t strict,tree * parm,tree * arg,tree arg_expr)21377 maybe_adjust_types_for_deduction (unification_kind_t strict,
21378 				  tree* parm,
21379 				  tree* arg,
21380 				  tree arg_expr)
21381 {
21382   int result = 0;
21383 
21384   switch (strict)
21385     {
21386     case DEDUCE_CALL:
21387       break;
21388 
21389     case DEDUCE_CONV:
21390       /* Swap PARM and ARG throughout the remainder of this
21391 	 function; the handling is precisely symmetric since PARM
21392 	 will initialize ARG rather than vice versa.  */
21393       std::swap (parm, arg);
21394       break;
21395 
21396     case DEDUCE_EXACT:
21397       /* Core issue #873: Do the DR606 thing (see below) for these cases,
21398 	 too, but here handle it by stripping the reference from PARM
21399 	 rather than by adding it to ARG.  */
21400       if (TYPE_REF_P (*parm)
21401 	  && TYPE_REF_IS_RVALUE (*parm)
21402 	  && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
21403 	  && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
21404 	  && TYPE_REF_P (*arg)
21405 	  && !TYPE_REF_IS_RVALUE (*arg))
21406 	*parm = TREE_TYPE (*parm);
21407       /* Nothing else to do in this case.  */
21408       return 0;
21409 
21410     default:
21411       gcc_unreachable ();
21412     }
21413 
21414   if (!TYPE_REF_P (*parm))
21415     {
21416       /* [temp.deduct.call]
21417 
21418 	 If P is not a reference type:
21419 
21420 	 --If A is an array type, the pointer type produced by the
21421 	 array-to-pointer standard conversion (_conv.array_) is
21422 	 used in place of A for type deduction; otherwise,
21423 
21424 	 --If A is a function type, the pointer type produced by
21425 	 the function-to-pointer standard conversion
21426 	 (_conv.func_) is used in place of A for type deduction;
21427 	 otherwise,
21428 
21429 	 --If A is a cv-qualified type, the top level
21430 	 cv-qualifiers of A's type are ignored for type
21431 	 deduction.  */
21432       if (TREE_CODE (*arg) == ARRAY_TYPE)
21433 	*arg = build_pointer_type (TREE_TYPE (*arg));
21434       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
21435 	*arg = build_pointer_type (*arg);
21436       else
21437 	*arg = TYPE_MAIN_VARIANT (*arg);
21438     }
21439 
21440   /* [14.8.2.1/3 temp.deduct.call], "A forwarding reference is an rvalue
21441      reference to a cv-unqualified template parameter that does not represent a
21442      template parameter of a class template (during class template argument
21443      deduction (13.3.1.8)). If P is a forwarding reference and the argument is
21444      an lvalue, the type "lvalue reference to A" is used in place of A for type
21445      deduction. */
21446   if (TYPE_REF_P (*parm)
21447       && TYPE_REF_IS_RVALUE (*parm)
21448       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
21449       && !TEMPLATE_TYPE_PARM_FOR_CLASS (TREE_TYPE (*parm))
21450       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
21451       && (arg_expr ? lvalue_p (arg_expr)
21452 	  /* try_one_overload doesn't provide an arg_expr, but
21453 	     functions are always lvalues.  */
21454 	  : TREE_CODE (*arg) == FUNCTION_TYPE))
21455     *arg = build_reference_type (*arg);
21456 
21457   /* [temp.deduct.call]
21458 
21459      If P is a cv-qualified type, the top level cv-qualifiers
21460      of P's type are ignored for type deduction.  If P is a
21461      reference type, the type referred to by P is used for
21462      type deduction.  */
21463   *parm = TYPE_MAIN_VARIANT (*parm);
21464   if (TYPE_REF_P (*parm))
21465     {
21466       *parm = TREE_TYPE (*parm);
21467       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
21468     }
21469 
21470   /* DR 322. For conversion deduction, remove a reference type on parm
21471      too (which has been swapped into ARG).  */
21472   if (strict == DEDUCE_CONV && TYPE_REF_P (*arg))
21473     *arg = TREE_TYPE (*arg);
21474 
21475   return result;
21476 }
21477 
21478 /* Subroutine of fn_type_unification.  PARM is a function parameter of a
21479    template which doesn't contain any deducible template parameters; check if
21480    ARG is a suitable match for it.  STRICT, FLAGS and EXPLAIN_P are as in
21481    unify_one_argument.  */
21482 
21483 static int
check_non_deducible_conversion(tree parm,tree arg,int strict,int flags,struct conversion ** conv_p,bool explain_p)21484 check_non_deducible_conversion (tree parm, tree arg, int strict,
21485 				int flags, struct conversion **conv_p,
21486 				bool explain_p)
21487 {
21488   tree type;
21489 
21490   if (!TYPE_P (arg))
21491     type = TREE_TYPE (arg);
21492   else
21493     type = arg;
21494 
21495   if (same_type_p (parm, type))
21496     return unify_success (explain_p);
21497 
21498   tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
21499   if (strict == DEDUCE_CONV)
21500     {
21501       if (can_convert_arg (type, parm, NULL_TREE, flags, complain))
21502 	return unify_success (explain_p);
21503     }
21504   else if (strict != DEDUCE_EXACT)
21505     {
21506       bool ok = false;
21507       tree conv_arg = TYPE_P (arg) ? NULL_TREE : arg;
21508       if (conv_p)
21509 	/* Avoid recalculating this in add_function_candidate.  */
21510 	ok = (*conv_p
21511 	      = good_conversion (parm, type, conv_arg, flags, complain));
21512       else
21513 	ok = can_convert_arg (parm, type, conv_arg, flags, complain);
21514       if (ok)
21515 	return unify_success (explain_p);
21516     }
21517 
21518   if (strict == DEDUCE_EXACT)
21519     return unify_type_mismatch (explain_p, parm, arg);
21520   else
21521     return unify_arg_conversion (explain_p, parm, type, arg);
21522 }
21523 
21524 static bool uses_deducible_template_parms (tree type);
21525 
21526 /* Returns true iff the expression EXPR is one from which a template
21527    argument can be deduced.  In other words, if it's an undecorated
21528    use of a template non-type parameter.  */
21529 
21530 static bool
deducible_expression(tree expr)21531 deducible_expression (tree expr)
21532 {
21533   /* Strip implicit conversions.  */
21534   while (CONVERT_EXPR_P (expr) || TREE_CODE (expr) == VIEW_CONVERT_EXPR)
21535     expr = TREE_OPERAND (expr, 0);
21536   return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
21537 }
21538 
21539 /* Returns true iff the array domain DOMAIN uses a template parameter in a
21540    deducible way; that is, if it has a max value of <PARM> - 1.  */
21541 
21542 static bool
deducible_array_bound(tree domain)21543 deducible_array_bound (tree domain)
21544 {
21545   if (domain == NULL_TREE)
21546     return false;
21547 
21548   tree max = TYPE_MAX_VALUE (domain);
21549   if (TREE_CODE (max) != MINUS_EXPR)
21550     return false;
21551 
21552   return deducible_expression (TREE_OPERAND (max, 0));
21553 }
21554 
21555 /* Returns true iff the template arguments ARGS use a template parameter
21556    in a deducible way.  */
21557 
21558 static bool
deducible_template_args(tree args)21559 deducible_template_args (tree args)
21560 {
21561   for (int i = 0; i < TREE_VEC_LENGTH (args); ++i)
21562     {
21563       bool deducible;
21564       tree elt = TREE_VEC_ELT (args, i);
21565       if (ARGUMENT_PACK_P (elt))
21566 	deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
21567       else
21568 	{
21569 	  if (PACK_EXPANSION_P (elt))
21570 	    elt = PACK_EXPANSION_PATTERN (elt);
21571 	  if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
21572 	    deducible = true;
21573 	  else if (TYPE_P (elt))
21574 	    deducible = uses_deducible_template_parms (elt);
21575 	  else
21576 	    deducible = deducible_expression (elt);
21577 	}
21578       if (deducible)
21579 	return true;
21580     }
21581   return false;
21582 }
21583 
21584 /* Returns true iff TYPE contains any deducible references to template
21585    parameters, as per 14.8.2.5.  */
21586 
21587 static bool
uses_deducible_template_parms(tree type)21588 uses_deducible_template_parms (tree type)
21589 {
21590   if (PACK_EXPANSION_P (type))
21591     type = PACK_EXPANSION_PATTERN (type);
21592 
21593   /* T
21594      cv-list T
21595      TT<T>
21596      TT<i>
21597      TT<> */
21598   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
21599       || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
21600     return true;
21601 
21602   /* T*
21603      T&
21604      T&&  */
21605   if (INDIRECT_TYPE_P (type))
21606     return uses_deducible_template_parms (TREE_TYPE (type));
21607 
21608   /* T[integer-constant ]
21609      type [i]  */
21610   if (TREE_CODE (type) == ARRAY_TYPE)
21611     return (uses_deducible_template_parms (TREE_TYPE (type))
21612 	    || deducible_array_bound (TYPE_DOMAIN (type)));
21613 
21614   /* T type ::*
21615      type T::*
21616      T T::*
21617      T (type ::*)()
21618      type (T::*)()
21619      type (type ::*)(T)
21620      type (T::*)(T)
21621      T (type ::*)(T)
21622      T (T::*)()
21623      T (T::*)(T) */
21624   if (TYPE_PTRMEM_P (type))
21625     return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
21626 	    || (uses_deducible_template_parms
21627 		(TYPE_PTRMEM_POINTED_TO_TYPE (type))));
21628 
21629   /* template-name <T> (where template-name refers to a class template)
21630      template-name <i> (where template-name refers to a class template) */
21631   if (CLASS_TYPE_P (type)
21632       && CLASSTYPE_TEMPLATE_INFO (type)
21633       && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
21634     return deducible_template_args (INNERMOST_TEMPLATE_ARGS
21635 				    (CLASSTYPE_TI_ARGS (type)));
21636 
21637   /* type (T)
21638      T()
21639      T(T)  */
21640   if (FUNC_OR_METHOD_TYPE_P (type))
21641     {
21642       if (uses_deducible_template_parms (TREE_TYPE (type)))
21643 	return true;
21644       tree parm = TYPE_ARG_TYPES (type);
21645       if (TREE_CODE (type) == METHOD_TYPE)
21646 	parm = TREE_CHAIN (parm);
21647       for (; parm; parm = TREE_CHAIN (parm))
21648 	if (uses_deducible_template_parms (TREE_VALUE (parm)))
21649 	  return true;
21650     }
21651 
21652   return false;
21653 }
21654 
21655 /* Subroutine of type_unification_real and unify_pack_expansion to
21656    handle unification of a single P/A pair.  Parameters are as
21657    for those functions.  */
21658 
21659 static int
unify_one_argument(tree tparms,tree targs,tree parm,tree arg,int subr,unification_kind_t strict,bool explain_p)21660 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
21661 		    int subr, unification_kind_t strict,
21662 		    bool explain_p)
21663 {
21664   tree arg_expr = NULL_TREE;
21665   int arg_strict;
21666 
21667   if (arg == error_mark_node || parm == error_mark_node)
21668     return unify_invalid (explain_p);
21669   if (arg == unknown_type_node)
21670     /* We can't deduce anything from this, but we might get all the
21671        template args from other function args.  */
21672     return unify_success (explain_p);
21673 
21674   /* Implicit conversions (Clause 4) will be performed on a function
21675      argument to convert it to the type of the corresponding function
21676      parameter if the parameter type contains no template-parameters that
21677      participate in template argument deduction.  */
21678   if (strict != DEDUCE_EXACT
21679       && TYPE_P (parm) && !uses_deducible_template_parms (parm))
21680     /* For function parameters with no deducible template parameters,
21681        just return.  We'll check non-dependent conversions later.  */
21682     return unify_success (explain_p);
21683 
21684   switch (strict)
21685     {
21686     case DEDUCE_CALL:
21687       arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
21688 		    | UNIFY_ALLOW_MORE_CV_QUAL
21689 		    | UNIFY_ALLOW_DERIVED);
21690       break;
21691 
21692     case DEDUCE_CONV:
21693       arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
21694       break;
21695 
21696     case DEDUCE_EXACT:
21697       arg_strict = UNIFY_ALLOW_NONE;
21698       break;
21699 
21700     default:
21701       gcc_unreachable ();
21702     }
21703 
21704   /* We only do these transformations if this is the top-level
21705      parameter_type_list in a call or declaration matching; in other
21706      situations (nested function declarators, template argument lists) we
21707      won't be comparing a type to an expression, and we don't do any type
21708      adjustments.  */
21709   if (!subr)
21710     {
21711       if (!TYPE_P (arg))
21712 	{
21713 	  gcc_assert (TREE_TYPE (arg) != NULL_TREE);
21714 	  if (type_unknown_p (arg))
21715 	    {
21716 	      /* [temp.deduct.type] A template-argument can be
21717 		 deduced from a pointer to function or pointer
21718 		 to member function argument if the set of
21719 		 overloaded functions does not contain function
21720 		 templates and at most one of a set of
21721 		 overloaded functions provides a unique
21722 		 match.  */
21723 	      resolve_overloaded_unification (tparms, targs, parm,
21724 					      arg, strict,
21725 					      arg_strict, explain_p);
21726 	      /* If a unique match was not found, this is a
21727 	         non-deduced context, so we still succeed. */
21728 	      return unify_success (explain_p);
21729 	    }
21730 
21731 	  arg_expr = arg;
21732 	  arg = unlowered_expr_type (arg);
21733 	  if (arg == error_mark_node)
21734 	    return unify_invalid (explain_p);
21735 	}
21736 
21737       arg_strict |=
21738 	maybe_adjust_types_for_deduction (strict, &parm, &arg, arg_expr);
21739     }
21740   else
21741     if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
21742 	!= (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
21743       return unify_template_argument_mismatch (explain_p, parm, arg);
21744 
21745   /* For deduction from an init-list we need the actual list.  */
21746   if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
21747     arg = arg_expr;
21748   return unify (tparms, targs, parm, arg, arg_strict, explain_p);
21749 }
21750 
21751 /* for_each_template_parm callback that always returns 0.  */
21752 
21753 static int
zero_r(tree,void *)21754 zero_r (tree, void *)
21755 {
21756   return 0;
21757 }
21758 
21759 /* for_each_template_parm any_fn callback to handle deduction of a template
21760    type argument from the type of an array bound.  */
21761 
21762 static int
array_deduction_r(tree t,void * data)21763 array_deduction_r (tree t, void *data)
21764 {
21765   tree_pair_p d = (tree_pair_p)data;
21766   tree &tparms = d->purpose;
21767   tree &targs = d->value;
21768 
21769   if (TREE_CODE (t) == ARRAY_TYPE)
21770     if (tree dom = TYPE_DOMAIN (t))
21771       if (tree max = TYPE_MAX_VALUE (dom))
21772 	{
21773 	  if (TREE_CODE (max) == MINUS_EXPR)
21774 	    max = TREE_OPERAND (max, 0);
21775 	  if (TREE_CODE (max) == TEMPLATE_PARM_INDEX)
21776 	    unify (tparms, targs, TREE_TYPE (max), size_type_node,
21777 		   UNIFY_ALLOW_NONE, /*explain*/false);
21778 	}
21779 
21780   /* Keep walking.  */
21781   return 0;
21782 }
21783 
21784 /* Try to deduce any not-yet-deduced template type arguments from the type of
21785    an array bound.  This is handled separately from unify because 14.8.2.5 says
21786    "The type of a type parameter is only deduced from an array bound if it is
21787    not otherwise deduced."  */
21788 
21789 static void
try_array_deduction(tree tparms,tree targs,tree parm)21790 try_array_deduction (tree tparms, tree targs, tree parm)
21791 {
21792   tree_pair_s data = { tparms, targs };
21793   hash_set<tree> visited;
21794   for_each_template_parm (parm, zero_r, &data, &visited,
21795 			  /*nondeduced*/false, array_deduction_r);
21796 }
21797 
21798 /* Most parms like fn_type_unification.
21799 
21800    If SUBR is 1, we're being called recursively (to unify the
21801    arguments of a function or method parameter of a function
21802    template).
21803 
21804    CHECKS is a pointer to a vector of access checks encountered while
21805    substituting default template arguments.  */
21806 
21807 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)21808 type_unification_real (tree tparms,
21809 		       tree full_targs,
21810 		       tree xparms,
21811 		       const tree *xargs,
21812 		       unsigned int xnargs,
21813 		       int subr,
21814 		       unification_kind_t strict,
21815 		       vec<deferred_access_check, va_gc> **checks,
21816 		       bool explain_p)
21817 {
21818   tree parm, arg;
21819   int i;
21820   int ntparms = TREE_VEC_LENGTH (tparms);
21821   int saw_undeduced = 0;
21822   tree parms;
21823   const tree *args;
21824   unsigned int nargs;
21825   unsigned int ia;
21826 
21827   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
21828   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
21829   gcc_assert (ntparms > 0);
21830 
21831   tree targs = INNERMOST_TEMPLATE_ARGS (full_targs);
21832 
21833   /* Reset the number of non-defaulted template arguments contained
21834      in TARGS.  */
21835   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
21836 
21837  again:
21838   parms = xparms;
21839   args = xargs;
21840   nargs = xnargs;
21841 
21842   ia = 0;
21843   while (parms && parms != void_list_node
21844 	 && ia < nargs)
21845     {
21846       parm = TREE_VALUE (parms);
21847 
21848       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
21849 	  && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
21850 	/* For a function parameter pack that occurs at the end of the
21851 	   parameter-declaration-list, the type A of each remaining
21852 	   argument of the call is compared with the type P of the
21853 	   declarator-id of the function parameter pack.  */
21854 	break;
21855 
21856       parms = TREE_CHAIN (parms);
21857 
21858       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
21859 	/* For a function parameter pack that does not occur at the
21860 	   end of the parameter-declaration-list, the type of the
21861 	   parameter pack is a non-deduced context.  */
21862 	continue;
21863 
21864       arg = args[ia];
21865       ++ia;
21866 
21867       if (unify_one_argument (tparms, full_targs, parm, arg, subr, strict,
21868 			      explain_p))
21869 	return 1;
21870     }
21871 
21872   if (parms
21873       && parms != void_list_node
21874       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
21875     {
21876       /* Unify the remaining arguments with the pack expansion type.  */
21877       tree argvec;
21878       tree parmvec = make_tree_vec (1);
21879 
21880       /* Allocate a TREE_VEC and copy in all of the arguments */
21881       argvec = make_tree_vec (nargs - ia);
21882       for (i = 0; ia < nargs; ++ia, ++i)
21883 	TREE_VEC_ELT (argvec, i) = args[ia];
21884 
21885       /* Copy the parameter into parmvec.  */
21886       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
21887       if (unify_pack_expansion (tparms, full_targs, parmvec, argvec, strict,
21888                                 /*subr=*/subr, explain_p))
21889         return 1;
21890 
21891       /* Advance to the end of the list of parameters.  */
21892       parms = TREE_CHAIN (parms);
21893     }
21894 
21895   /* Fail if we've reached the end of the parm list, and more args
21896      are present, and the parm list isn't variadic.  */
21897   if (ia < nargs && parms == void_list_node)
21898     return unify_too_many_arguments (explain_p, nargs, ia);
21899   /* Fail if parms are left and they don't have default values and
21900      they aren't all deduced as empty packs (c++/57397).  This is
21901      consistent with sufficient_parms_p.  */
21902   if (parms && parms != void_list_node
21903       && TREE_PURPOSE (parms) == NULL_TREE)
21904     {
21905       unsigned int count = nargs;
21906       tree p = parms;
21907       bool type_pack_p;
21908       do
21909 	{
21910 	  type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
21911 	  if (!type_pack_p)
21912 	    count++;
21913 	  p = TREE_CHAIN (p);
21914 	}
21915       while (p && p != void_list_node);
21916       if (count != nargs)
21917 	return unify_too_few_arguments (explain_p, ia, count,
21918 					type_pack_p);
21919     }
21920 
21921   if (!subr)
21922     {
21923       tsubst_flags_t complain = (explain_p
21924 				 ? tf_warning_or_error
21925 				 : tf_none);
21926       bool tried_array_deduction = (cxx_dialect < cxx17);
21927 
21928       for (i = 0; i < ntparms; i++)
21929 	{
21930 	  tree targ = TREE_VEC_ELT (targs, i);
21931 	  tree tparm = TREE_VEC_ELT (tparms, i);
21932 
21933 	  /* Clear the "incomplete" flags on all argument packs now so that
21934 	     substituting them into later default arguments works.  */
21935 	  if (targ && ARGUMENT_PACK_P (targ))
21936             {
21937               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
21938               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
21939             }
21940 
21941 	  if (targ || tparm == error_mark_node)
21942 	    continue;
21943 	  tparm = TREE_VALUE (tparm);
21944 
21945 	  if (TREE_CODE (tparm) == TYPE_DECL
21946 	      && !tried_array_deduction)
21947 	    {
21948 	      try_array_deduction (tparms, targs, xparms);
21949 	      tried_array_deduction = true;
21950 	      if (TREE_VEC_ELT (targs, i))
21951 		continue;
21952 	    }
21953 
21954 	  /* If this is an undeduced nontype parameter that depends on
21955 	     a type parameter, try another pass; its type may have been
21956 	     deduced from a later argument than the one from which
21957 	     this parameter can be deduced.  */
21958 	  if (TREE_CODE (tparm) == PARM_DECL
21959 	      && uses_template_parms (TREE_TYPE (tparm))
21960 	      && saw_undeduced < 2)
21961 	    {
21962 	      saw_undeduced = 1;
21963 	      continue;
21964 	    }
21965 
21966 	  /* Core issue #226 (C++0x) [temp.deduct]:
21967 
21968 	     If a template argument has not been deduced, its
21969 	     default template argument, if any, is used.
21970 
21971 	     When we are in C++98 mode, TREE_PURPOSE will either
21972 	     be NULL_TREE or ERROR_MARK_NODE, so we do not need
21973 	     to explicitly check cxx_dialect here.  */
21974 	  if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
21975 	    /* OK, there is a default argument.  Wait until after the
21976 	       conversion check to do substitution.  */
21977 	    continue;
21978 
21979 	  /* If the type parameter is a parameter pack, then it will
21980 	     be deduced to an empty parameter pack.  */
21981 	  if (template_parameter_pack_p (tparm))
21982 	    {
21983 	      tree arg;
21984 
21985 	      if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
21986 		{
21987 		  arg = make_node (NONTYPE_ARGUMENT_PACK);
21988 		  TREE_CONSTANT (arg) = 1;
21989 		}
21990 	      else
21991 		arg = cxx_make_type (TYPE_ARGUMENT_PACK);
21992 
21993 	      SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
21994 
21995 	      TREE_VEC_ELT (targs, i) = arg;
21996 	      continue;
21997 	    }
21998 
21999 	  return unify_parameter_deduction_failure (explain_p, tparm);
22000 	}
22001 
22002       /* Now substitute into the default template arguments.  */
22003       for (i = 0; i < ntparms; i++)
22004 	{
22005 	  tree targ = TREE_VEC_ELT (targs, i);
22006 	  tree tparm = TREE_VEC_ELT (tparms, i);
22007 
22008 	  if (targ || tparm == error_mark_node)
22009 	    continue;
22010 	  tree parm = TREE_VALUE (tparm);
22011 	  tree arg = TREE_PURPOSE (tparm);
22012 	  reopen_deferring_access_checks (*checks);
22013 	  location_t save_loc = input_location;
22014 	  if (DECL_P (parm))
22015 	    input_location = DECL_SOURCE_LOCATION (parm);
22016 
22017 	  if (saw_undeduced == 1
22018 	      && TREE_CODE (parm) == PARM_DECL
22019 	      && uses_template_parms (TREE_TYPE (parm)))
22020 	    {
22021 	      /* The type of this non-type parameter depends on undeduced
22022 		 parameters.  Don't try to use its default argument yet,
22023 		 since we might deduce an argument for it on the next pass,
22024 		 but do check whether the arguments we already have cause
22025 		 substitution failure, so that that happens before we try
22026 		 later default arguments (78489).  */
22027 	      ++processing_template_decl;
22028 	      tree type = tsubst (TREE_TYPE (parm), full_targs, complain,
22029 				  NULL_TREE);
22030 	      --processing_template_decl;
22031 	      if (type == error_mark_node)
22032 		arg = error_mark_node;
22033 	      else
22034 		arg = NULL_TREE;
22035 	    }
22036 	  else
22037 	    {
22038 	      /* Even if the call is happening in template context, getting
22039 		 here means it's non-dependent, and a default argument is
22040 		 considered a separate definition under [temp.decls], so we can
22041 		 do this substitution without processing_template_decl.  This
22042 		 is important if the default argument contains something that
22043 		 might be instantiation-dependent like access (87480).  */
22044 	      processing_template_decl_sentinel s;
22045 	      tree substed = NULL_TREE;
22046 	      if (saw_undeduced == 1)
22047 		{
22048 		  /* First instatiate in template context, in case we still
22049 		     depend on undeduced template parameters.  */
22050 		  ++processing_template_decl;
22051 		  substed = tsubst_template_arg (arg, full_targs, complain,
22052 						 NULL_TREE);
22053 		  --processing_template_decl;
22054 		  if (substed != error_mark_node
22055 		      && !uses_template_parms (substed))
22056 		    /* We replaced all the tparms, substitute again out of
22057 		       template context.  */
22058 		    substed = NULL_TREE;
22059 		}
22060 	      if (!substed)
22061 		substed = tsubst_template_arg (arg, full_targs, complain,
22062 					       NULL_TREE);
22063 
22064 	      if (!uses_template_parms (substed))
22065 		arg = convert_template_argument (parm, substed, full_targs,
22066 						 complain, i, NULL_TREE);
22067 	      else if (saw_undeduced == 1)
22068 		arg = NULL_TREE;
22069 	      else
22070 		arg = error_mark_node;
22071 	    }
22072 
22073 	  input_location = save_loc;
22074 	  *checks = get_deferred_access_checks ();
22075 	  pop_deferring_access_checks ();
22076 
22077 	  if (arg == error_mark_node)
22078 	    return 1;
22079 	  else if (arg)
22080 	    {
22081 	      TREE_VEC_ELT (targs, i) = arg;
22082 	      /* The position of the first default template argument,
22083 		 is also the number of non-defaulted arguments in TARGS.
22084 		 Record that.  */
22085 	      if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
22086 		SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
22087 	    }
22088 	}
22089 
22090       if (saw_undeduced++ == 1)
22091 	goto again;
22092     }
22093 
22094   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
22095     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
22096 
22097   return unify_success (explain_p);
22098 }
22099 
22100 /* Subroutine of type_unification_real.  Args are like the variables
22101    at the call site.  ARG is an overloaded function (or template-id);
22102    we try deducing template args from each of the overloads, and if
22103    only one succeeds, we go with that.  Modifies TARGS and returns
22104    true on success.  */
22105 
22106 static bool
resolve_overloaded_unification(tree tparms,tree targs,tree parm,tree arg,unification_kind_t strict,int sub_strict,bool explain_p)22107 resolve_overloaded_unification (tree tparms,
22108 				tree targs,
22109 				tree parm,
22110 				tree arg,
22111 				unification_kind_t strict,
22112 				int sub_strict,
22113 			        bool explain_p)
22114 {
22115   tree tempargs = copy_node (targs);
22116   int good = 0;
22117   tree goodfn = NULL_TREE;
22118   bool addr_p;
22119 
22120   if (TREE_CODE (arg) == ADDR_EXPR)
22121     {
22122       arg = TREE_OPERAND (arg, 0);
22123       addr_p = true;
22124     }
22125   else
22126     addr_p = false;
22127 
22128   if (TREE_CODE (arg) == COMPONENT_REF)
22129     /* Handle `&x' where `x' is some static or non-static member
22130        function name.  */
22131     arg = TREE_OPERAND (arg, 1);
22132 
22133   if (TREE_CODE (arg) == OFFSET_REF)
22134     arg = TREE_OPERAND (arg, 1);
22135 
22136   /* Strip baselink information.  */
22137   if (BASELINK_P (arg))
22138     arg = BASELINK_FUNCTIONS (arg);
22139 
22140   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
22141     {
22142       /* If we got some explicit template args, we need to plug them into
22143 	 the affected templates before we try to unify, in case the
22144 	 explicit args will completely resolve the templates in question.  */
22145 
22146       int ok = 0;
22147       tree expl_subargs = TREE_OPERAND (arg, 1);
22148       arg = TREE_OPERAND (arg, 0);
22149 
22150       for (lkp_iterator iter (arg); iter; ++iter)
22151 	{
22152 	  tree fn = *iter;
22153 	  tree subargs, elem;
22154 
22155 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
22156 	    continue;
22157 
22158 	  subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
22159 					   expl_subargs, NULL_TREE, tf_none,
22160 					   /*require_all_args=*/true,
22161 					   /*use_default_args=*/true);
22162 	  if (subargs != error_mark_node
22163 	      && !any_dependent_template_arguments_p (subargs))
22164 	    {
22165 	      elem = TREE_TYPE (instantiate_template (fn, subargs, tf_none));
22166 	      if (try_one_overload (tparms, targs, tempargs, parm,
22167 				    elem, strict, sub_strict, addr_p, explain_p)
22168 		  && (!goodfn || !same_type_p (goodfn, elem)))
22169 		{
22170 		  goodfn = elem;
22171 		  ++good;
22172 		}
22173 	    }
22174 	  else if (subargs)
22175 	    ++ok;
22176 	}
22177       /* If no templates (or more than one) are fully resolved by the
22178 	 explicit arguments, this template-id is a non-deduced context; it
22179 	 could still be OK if we deduce all template arguments for the
22180 	 enclosing call through other arguments.  */
22181       if (good != 1)
22182 	good = ok;
22183     }
22184   else if (!OVL_P (arg))
22185     /* If ARG is, for example, "(0, &f)" then its type will be unknown
22186        -- but the deduction does not succeed because the expression is
22187        not just the function on its own.  */
22188     return false;
22189   else
22190     for (lkp_iterator iter (arg); iter; ++iter)
22191       {
22192 	tree fn = *iter;
22193 	if (try_one_overload (tparms, targs, tempargs, parm, TREE_TYPE (fn),
22194 			      strict, sub_strict, addr_p, explain_p)
22195 	    && (!goodfn || !decls_match (goodfn, fn)))
22196 	  {
22197 	    goodfn = fn;
22198 	    ++good;
22199 	  }
22200       }
22201 
22202   /* [temp.deduct.type] A template-argument can be deduced from a pointer
22203      to function or pointer to member function argument if the set of
22204      overloaded functions does not contain function templates and at most
22205      one of a set of overloaded functions provides a unique match.
22206 
22207      So if we found multiple possibilities, we return success but don't
22208      deduce anything.  */
22209 
22210   if (good == 1)
22211     {
22212       int i = TREE_VEC_LENGTH (targs);
22213       for (; i--; )
22214 	if (TREE_VEC_ELT (tempargs, i))
22215 	  {
22216 	    tree old = TREE_VEC_ELT (targs, i);
22217 	    tree new_ = TREE_VEC_ELT (tempargs, i);
22218 	    if (new_ && old && ARGUMENT_PACK_P (old)
22219 		&& ARGUMENT_PACK_EXPLICIT_ARGS (old))
22220 	      /* Don't forget explicit template arguments in a pack.  */
22221 	      ARGUMENT_PACK_EXPLICIT_ARGS (new_)
22222 		= ARGUMENT_PACK_EXPLICIT_ARGS (old);
22223 	    TREE_VEC_ELT (targs, i) = new_;
22224 	  }
22225     }
22226   if (good)
22227     return true;
22228 
22229   return false;
22230 }
22231 
22232 /* Core DR 115: In contexts where deduction is done and fails, or in
22233    contexts where deduction is not done, if a template argument list is
22234    specified and it, along with any default template arguments, identifies
22235    a single function template specialization, then the template-id is an
22236    lvalue for the function template specialization.  */
22237 
22238 tree
resolve_nondeduced_context(tree orig_expr,tsubst_flags_t complain)22239 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
22240 {
22241   tree expr, offset, baselink;
22242   bool addr;
22243 
22244   if (!type_unknown_p (orig_expr))
22245     return orig_expr;
22246 
22247   expr = orig_expr;
22248   addr = false;
22249   offset = NULL_TREE;
22250   baselink = NULL_TREE;
22251 
22252   if (TREE_CODE (expr) == ADDR_EXPR)
22253     {
22254       expr = TREE_OPERAND (expr, 0);
22255       addr = true;
22256     }
22257   if (TREE_CODE (expr) == OFFSET_REF)
22258     {
22259       offset = expr;
22260       expr = TREE_OPERAND (expr, 1);
22261     }
22262   if (BASELINK_P (expr))
22263     {
22264       baselink = expr;
22265       expr = BASELINK_FUNCTIONS (expr);
22266     }
22267 
22268   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
22269     {
22270       int good = 0;
22271       tree goodfn = NULL_TREE;
22272 
22273       /* If we got some explicit template args, we need to plug them into
22274 	 the affected templates before we try to unify, in case the
22275 	 explicit args will completely resolve the templates in question.  */
22276 
22277       tree expl_subargs = TREE_OPERAND (expr, 1);
22278       tree arg = TREE_OPERAND (expr, 0);
22279       tree badfn = NULL_TREE;
22280       tree badargs = NULL_TREE;
22281 
22282       for (lkp_iterator iter (arg); iter; ++iter)
22283 	{
22284 	  tree fn = *iter;
22285 	  tree subargs, elem;
22286 
22287 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
22288 	    continue;
22289 
22290 	  subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
22291 					   expl_subargs, NULL_TREE, tf_none,
22292 					   /*require_all_args=*/true,
22293 					   /*use_default_args=*/true);
22294 	  if (subargs != error_mark_node
22295 	      && !any_dependent_template_arguments_p (subargs))
22296 	    {
22297 	      elem = instantiate_template (fn, subargs, tf_none);
22298 	      if (elem == error_mark_node)
22299 		{
22300 		  badfn = fn;
22301 		  badargs = subargs;
22302 		}
22303 	      else if (elem && (!goodfn || !decls_match (goodfn, elem)))
22304 		{
22305 		  goodfn = elem;
22306 		  ++good;
22307 		}
22308 	    }
22309 	}
22310       if (good == 1)
22311 	{
22312 	  mark_used (goodfn);
22313 	  expr = goodfn;
22314 	  if (baselink)
22315 	    expr = build_baselink (BASELINK_BINFO (baselink),
22316 				   BASELINK_ACCESS_BINFO (baselink),
22317 				   expr, BASELINK_OPTYPE (baselink));
22318 	  if (offset)
22319 	    {
22320 	      tree base
22321 		= TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
22322 	      expr = build_offset_ref (base, expr, addr, complain);
22323 	    }
22324 	  if (addr)
22325 	    expr = cp_build_addr_expr (expr, complain);
22326 	  return expr;
22327 	}
22328       else if (good == 0 && badargs && (complain & tf_error))
22329 	/* There were no good options and at least one bad one, so let the
22330 	   user know what the problem is.  */
22331 	instantiate_template (badfn, badargs, complain);
22332     }
22333   return orig_expr;
22334 }
22335 
22336 /* As above, but error out if the expression remains overloaded.  */
22337 
22338 tree
resolve_nondeduced_context_or_error(tree exp,tsubst_flags_t complain)22339 resolve_nondeduced_context_or_error (tree exp, tsubst_flags_t complain)
22340 {
22341   exp = resolve_nondeduced_context (exp, complain);
22342   if (type_unknown_p (exp))
22343     {
22344       if (complain & tf_error)
22345 	cxx_incomplete_type_error (exp, TREE_TYPE (exp));
22346       return error_mark_node;
22347     }
22348   return exp;
22349 }
22350 
22351 /* Subroutine of resolve_overloaded_unification; does deduction for a single
22352    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
22353    different overloads deduce different arguments for a given parm.
22354    ADDR_P is true if the expression for which deduction is being
22355    performed was of the form "& fn" rather than simply "fn".
22356 
22357    Returns 1 on success.  */
22358 
22359 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)22360 try_one_overload (tree tparms,
22361 		  tree orig_targs,
22362 		  tree targs,
22363 		  tree parm,
22364 		  tree arg,
22365 		  unification_kind_t strict,
22366 		  int sub_strict,
22367 		  bool addr_p,
22368 		  bool explain_p)
22369 {
22370   int nargs;
22371   tree tempargs;
22372   int i;
22373 
22374   if (arg == error_mark_node)
22375     return 0;
22376 
22377   /* [temp.deduct.type] A template-argument can be deduced from a pointer
22378      to function or pointer to member function argument if the set of
22379      overloaded functions does not contain function templates and at most
22380      one of a set of overloaded functions provides a unique match.
22381 
22382      So if this is a template, just return success.  */
22383 
22384   if (uses_template_parms (arg))
22385     return 1;
22386 
22387   if (TREE_CODE (arg) == METHOD_TYPE)
22388     arg = build_ptrmemfunc_type (build_pointer_type (arg));
22389   else if (addr_p)
22390     arg = build_pointer_type (arg);
22391 
22392   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
22393 
22394   /* We don't copy orig_targs for this because if we have already deduced
22395      some template args from previous args, unify would complain when we
22396      try to deduce a template parameter for the same argument, even though
22397      there isn't really a conflict.  */
22398   nargs = TREE_VEC_LENGTH (targs);
22399   tempargs = make_tree_vec (nargs);
22400 
22401   if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
22402     return 0;
22403 
22404   /* First make sure we didn't deduce anything that conflicts with
22405      explicitly specified args.  */
22406   for (i = nargs; i--; )
22407     {
22408       tree elt = TREE_VEC_ELT (tempargs, i);
22409       tree oldelt = TREE_VEC_ELT (orig_targs, i);
22410 
22411       if (!elt)
22412 	/*NOP*/;
22413       else if (uses_template_parms (elt))
22414 	/* Since we're unifying against ourselves, we will fill in
22415 	   template args used in the function parm list with our own
22416 	   template parms.  Discard them.  */
22417 	TREE_VEC_ELT (tempargs, i) = NULL_TREE;
22418       else if (oldelt && ARGUMENT_PACK_P (oldelt))
22419 	{
22420 	  /* Check that the argument at each index of the deduced argument pack
22421 	     is equivalent to the corresponding explicitly specified argument.
22422 	     We may have deduced more arguments than were explicitly specified,
22423 	     and that's OK.  */
22424 
22425 	  /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
22426 	     that's wrong if we deduce the same argument pack from multiple
22427 	     function arguments: it's only incomplete the first time.  */
22428 
22429 	  tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
22430 	  tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
22431 
22432 	  if (TREE_VEC_LENGTH (deduced_pack)
22433 	      < TREE_VEC_LENGTH (explicit_pack))
22434 	    return 0;
22435 
22436 	  for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
22437 	    if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
22438 				      TREE_VEC_ELT (deduced_pack, j)))
22439 	      return 0;
22440 	}
22441       else if (oldelt && !template_args_equal (oldelt, elt))
22442 	return 0;
22443     }
22444 
22445   for (i = nargs; i--; )
22446     {
22447       tree elt = TREE_VEC_ELT (tempargs, i);
22448 
22449       if (elt)
22450 	TREE_VEC_ELT (targs, i) = elt;
22451     }
22452 
22453   return 1;
22454 }
22455 
22456 /* PARM is a template class (perhaps with unbound template
22457    parameters).  ARG is a fully instantiated type.  If ARG can be
22458    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
22459    TARGS are as for unify.  */
22460 
22461 static tree
try_class_unification(tree tparms,tree targs,tree parm,tree arg,bool explain_p)22462 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
22463 		       bool explain_p)
22464 {
22465   tree copy_of_targs;
22466 
22467   if (!CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
22468     return NULL_TREE;
22469   else if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
22470     /* Matches anything.  */;
22471   else if (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
22472 	   != most_general_template (CLASSTYPE_TI_TEMPLATE (parm)))
22473     return NULL_TREE;
22474 
22475   /* We need to make a new template argument vector for the call to
22476      unify.  If we used TARGS, we'd clutter it up with the result of
22477      the attempted unification, even if this class didn't work out.
22478      We also don't want to commit ourselves to all the unifications
22479      we've already done, since unification is supposed to be done on
22480      an argument-by-argument basis.  In other words, consider the
22481      following pathological case:
22482 
22483        template <int I, int J, int K>
22484        struct S {};
22485 
22486        template <int I, int J>
22487        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
22488 
22489        template <int I, int J, int K>
22490        void f(S<I, J, K>, S<I, I, I>);
22491 
22492        void g() {
22493 	 S<0, 0, 0> s0;
22494 	 S<0, 1, 2> s2;
22495 
22496 	 f(s0, s2);
22497        }
22498 
22499      Now, by the time we consider the unification involving `s2', we
22500      already know that we must have `f<0, 0, 0>'.  But, even though
22501      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
22502      because there are two ways to unify base classes of S<0, 1, 2>
22503      with S<I, I, I>.  If we kept the already deduced knowledge, we
22504      would reject the possibility I=1.  */
22505   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
22506 
22507   if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
22508     {
22509       if (unify_bound_ttp_args (tparms, copy_of_targs, parm, arg, explain_p))
22510 	return NULL_TREE;
22511       return arg;
22512     }
22513 
22514   /* If unification failed, we're done.  */
22515   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
22516 	     CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
22517     return NULL_TREE;
22518 
22519   return arg;
22520 }
22521 
22522 /* Given a template type PARM and a class type ARG, find the unique
22523    base type in ARG that is an instance of PARM.  We do not examine
22524    ARG itself; only its base-classes.  If there is not exactly one
22525    appropriate base class, return NULL_TREE.  PARM may be the type of
22526    a partial specialization, as well as a plain template type.  Used
22527    by unify.  */
22528 
22529 static enum template_base_result
get_template_base(tree tparms,tree targs,tree parm,tree arg,bool explain_p,tree * result)22530 get_template_base (tree tparms, tree targs, tree parm, tree arg,
22531 		   bool explain_p, tree *result)
22532 {
22533   tree rval = NULL_TREE;
22534   tree binfo;
22535 
22536   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
22537 
22538   binfo = TYPE_BINFO (complete_type (arg));
22539   if (!binfo)
22540     {
22541       /* The type could not be completed.  */
22542       *result = NULL_TREE;
22543       return tbr_incomplete_type;
22544     }
22545 
22546   /* Walk in inheritance graph order.  The search order is not
22547      important, and this avoids multiple walks of virtual bases.  */
22548   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
22549     {
22550       tree r = try_class_unification (tparms, targs, parm,
22551 				      BINFO_TYPE (binfo), explain_p);
22552 
22553       if (r)
22554 	{
22555 	  /* If there is more than one satisfactory baseclass, then:
22556 
22557 	       [temp.deduct.call]
22558 
22559 	      If they yield more than one possible deduced A, the type
22560 	      deduction fails.
22561 
22562 	     applies.  */
22563 	  if (rval && !same_type_p (r, rval))
22564 	    {
22565 	      *result = NULL_TREE;
22566 	      return tbr_ambiguous_baseclass;
22567 	    }
22568 
22569 	  rval = r;
22570 	}
22571     }
22572 
22573   *result = rval;
22574   return tbr_success;
22575 }
22576 
22577 /* Returns the level of DECL, which declares a template parameter.  */
22578 
22579 static int
template_decl_level(tree decl)22580 template_decl_level (tree decl)
22581 {
22582   switch (TREE_CODE (decl))
22583     {
22584     case TYPE_DECL:
22585     case TEMPLATE_DECL:
22586       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
22587 
22588     case PARM_DECL:
22589       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
22590 
22591     default:
22592       gcc_unreachable ();
22593     }
22594   return 0;
22595 }
22596 
22597 /* Decide whether ARG can be unified with PARM, considering only the
22598    cv-qualifiers of each type, given STRICT as documented for unify.
22599    Returns nonzero iff the unification is OK on that basis.  */
22600 
22601 static int
check_cv_quals_for_unify(int strict,tree arg,tree parm)22602 check_cv_quals_for_unify (int strict, tree arg, tree parm)
22603 {
22604   int arg_quals = cp_type_quals (arg);
22605   int parm_quals = cp_type_quals (parm);
22606 
22607   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
22608       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
22609     {
22610       /*  Although a CVR qualifier is ignored when being applied to a
22611 	  substituted template parameter ([8.3.2]/1 for example), that
22612 	  does not allow us to unify "const T" with "int&" because both
22613 	  types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
22614 	  It is ok when we're allowing additional CV qualifiers
22615 	  at the outer level [14.8.2.1]/3,1st bullet.  */
22616       if ((TYPE_REF_P (arg)
22617 	   || FUNC_OR_METHOD_TYPE_P (arg))
22618 	  && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
22619 	return 0;
22620 
22621       if ((!INDIRECT_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
22622 	  && (parm_quals & TYPE_QUAL_RESTRICT))
22623 	return 0;
22624     }
22625 
22626   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
22627       && (arg_quals & parm_quals) != parm_quals)
22628     return 0;
22629 
22630   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
22631       && (parm_quals & arg_quals) != arg_quals)
22632     return 0;
22633 
22634   return 1;
22635 }
22636 
22637 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
22638 void
template_parm_level_and_index(tree parm,int * level,int * index)22639 template_parm_level_and_index (tree parm, int* level, int* index)
22640 {
22641   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
22642       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
22643       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
22644     {
22645       *index = TEMPLATE_TYPE_IDX (parm);
22646       *level = TEMPLATE_TYPE_LEVEL (parm);
22647     }
22648   else
22649     {
22650       *index = TEMPLATE_PARM_IDX (parm);
22651       *level = TEMPLATE_PARM_LEVEL (parm);
22652     }
22653 }
22654 
22655 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)			\
22656   do {									\
22657     if (unify (TP, TA, P, A, S, EP))					\
22658       return 1;								\
22659   } while (0)
22660 
22661 /* Unifies the remaining arguments in PACKED_ARGS with the pack
22662    expansion at the end of PACKED_PARMS. Returns 0 if the type
22663    deduction succeeds, 1 otherwise. STRICT is the same as in
22664    fn_type_unification. CALL_ARGS_P is true iff PACKED_ARGS is actually a
22665    function call argument list. We'll need to adjust the arguments to make them
22666    types. SUBR tells us if this is from a recursive call to
22667    type_unification_real, or for comparing two template argument
22668    lists. */
22669 
22670 static int
unify_pack_expansion(tree tparms,tree targs,tree packed_parms,tree packed_args,unification_kind_t strict,bool subr,bool explain_p)22671 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
22672                       tree packed_args, unification_kind_t strict,
22673                       bool subr, bool explain_p)
22674 {
22675   tree parm
22676     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
22677   tree pattern = PACK_EXPANSION_PATTERN (parm);
22678   tree pack, packs = NULL_TREE;
22679   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
22680 
22681   /* Add in any args remembered from an earlier partial instantiation.  */
22682   targs = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (parm), targs);
22683   int levels = TMPL_ARGS_DEPTH (targs);
22684 
22685   packed_args = expand_template_argument_pack (packed_args);
22686 
22687   int len = TREE_VEC_LENGTH (packed_args);
22688 
22689   /* Determine the parameter packs we will be deducing from the
22690      pattern, and record their current deductions.  */
22691   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
22692        pack; pack = TREE_CHAIN (pack))
22693     {
22694       tree parm_pack = TREE_VALUE (pack);
22695       int idx, level;
22696 
22697       /* Only template parameter packs can be deduced, not e.g. function
22698 	 parameter packs or __bases or __integer_pack.  */
22699       if (!TEMPLATE_PARM_P (parm_pack))
22700 	continue;
22701 
22702       /* Determine the index and level of this parameter pack.  */
22703       template_parm_level_and_index (parm_pack, &level, &idx);
22704       if (level < levels)
22705 	continue;
22706 
22707       /* Keep track of the parameter packs and their corresponding
22708          argument packs.  */
22709       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
22710       TREE_TYPE (packs) = make_tree_vec (len - start);
22711     }
22712 
22713   /* Loop through all of the arguments that have not yet been
22714      unified and unify each with the pattern.  */
22715   for (i = start; i < len; i++)
22716     {
22717       tree parm;
22718       bool any_explicit = false;
22719       tree arg = TREE_VEC_ELT (packed_args, i);
22720 
22721       /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
22722 	 or the element of its argument pack at the current index if
22723 	 this argument was explicitly specified.  */
22724       for (pack = packs; pack; pack = TREE_CHAIN (pack))
22725         {
22726           int idx, level;
22727           tree arg, pargs;
22728           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
22729 
22730           arg = NULL_TREE;
22731           if (TREE_VALUE (pack)
22732               && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
22733               && (i - start < TREE_VEC_LENGTH (pargs)))
22734             {
22735               any_explicit = true;
22736               arg = TREE_VEC_ELT (pargs, i - start);
22737             }
22738           TMPL_ARG (targs, level, idx) = arg;
22739         }
22740 
22741       /* If we had explicit template arguments, substitute them into the
22742 	 pattern before deduction.  */
22743       if (any_explicit)
22744 	{
22745 	  /* Some arguments might still be unspecified or dependent.  */
22746 	  bool dependent;
22747 	  ++processing_template_decl;
22748 	  dependent = any_dependent_template_arguments_p (targs);
22749 	  if (!dependent)
22750 	    --processing_template_decl;
22751 	  parm = tsubst (pattern, targs,
22752 			 explain_p ? tf_warning_or_error : tf_none,
22753 			 NULL_TREE);
22754 	  if (dependent)
22755 	    --processing_template_decl;
22756 	  if (parm == error_mark_node)
22757 	    return 1;
22758 	}
22759       else
22760 	parm = pattern;
22761 
22762       /* Unify the pattern with the current argument.  */
22763       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
22764 			      explain_p))
22765 	return 1;
22766 
22767       /* For each parameter pack, collect the deduced value.  */
22768       for (pack = packs; pack; pack = TREE_CHAIN (pack))
22769         {
22770           int idx, level;
22771           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
22772 
22773           TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
22774             TMPL_ARG (targs, level, idx);
22775         }
22776     }
22777 
22778   /* Verify that the results of unification with the parameter packs
22779      produce results consistent with what we've seen before, and make
22780      the deduced argument packs available.  */
22781   for (pack = packs; pack; pack = TREE_CHAIN (pack))
22782     {
22783       tree old_pack = TREE_VALUE (pack);
22784       tree new_args = TREE_TYPE (pack);
22785       int i, len = TREE_VEC_LENGTH (new_args);
22786       int idx, level;
22787       bool nondeduced_p = false;
22788 
22789       /* By default keep the original deduced argument pack.
22790 	 If necessary, more specific code is going to update the
22791 	 resulting deduced argument later down in this function.  */
22792       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
22793       TMPL_ARG (targs, level, idx) = old_pack;
22794 
22795       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
22796 	 actually deduce anything.  */
22797       for (i = 0; i < len && !nondeduced_p; ++i)
22798 	if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
22799 	  nondeduced_p = true;
22800       if (nondeduced_p)
22801 	continue;
22802 
22803       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
22804         {
22805           /* If we had fewer function args than explicit template args,
22806              just use the explicits.  */
22807           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
22808           int explicit_len = TREE_VEC_LENGTH (explicit_args);
22809           if (len < explicit_len)
22810             new_args = explicit_args;
22811         }
22812 
22813       if (!old_pack)
22814         {
22815           tree result;
22816           /* Build the deduced *_ARGUMENT_PACK.  */
22817           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
22818             {
22819               result = make_node (NONTYPE_ARGUMENT_PACK);
22820               TREE_CONSTANT (result) = 1;
22821             }
22822           else
22823             result = cxx_make_type (TYPE_ARGUMENT_PACK);
22824 
22825           SET_ARGUMENT_PACK_ARGS (result, new_args);
22826 
22827           /* Note the deduced argument packs for this parameter
22828              pack.  */
22829           TMPL_ARG (targs, level, idx) = result;
22830         }
22831       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
22832                && (ARGUMENT_PACK_ARGS (old_pack)
22833                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
22834         {
22835           /* We only had the explicitly-provided arguments before, but
22836              now we have a complete set of arguments.  */
22837           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
22838 
22839           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
22840           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
22841           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
22842         }
22843       else
22844 	{
22845 	  tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
22846 	  tree old_args = ARGUMENT_PACK_ARGS (old_pack);
22847 
22848 	  if (!comp_template_args (old_args, new_args,
22849 				   &bad_old_arg, &bad_new_arg))
22850 	    /* Inconsistent unification of this parameter pack.  */
22851 	    return unify_parameter_pack_inconsistent (explain_p,
22852 						      bad_old_arg,
22853 						      bad_new_arg);
22854 	}
22855     }
22856 
22857   return unify_success (explain_p);
22858 }
22859 
22860 /* Handle unification of the domain of an array.  PARM_DOM and ARG_DOM are
22861    INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs.  The other
22862    parameters and return value are as for unify.  */
22863 
22864 static int
unify_array_domain(tree tparms,tree targs,tree parm_dom,tree arg_dom,bool explain_p)22865 unify_array_domain (tree tparms, tree targs,
22866 		    tree parm_dom, tree arg_dom,
22867 		    bool explain_p)
22868 {
22869   tree parm_max;
22870   tree arg_max;
22871   bool parm_cst;
22872   bool arg_cst;
22873 
22874   /* Our representation of array types uses "N - 1" as the
22875      TYPE_MAX_VALUE for an array with "N" elements, if "N" is
22876      not an integer constant.  We cannot unify arbitrarily
22877      complex expressions, so we eliminate the MINUS_EXPRs
22878      here.  */
22879   parm_max = TYPE_MAX_VALUE (parm_dom);
22880   parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
22881   if (!parm_cst)
22882     {
22883       gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
22884       parm_max = TREE_OPERAND (parm_max, 0);
22885     }
22886   arg_max = TYPE_MAX_VALUE (arg_dom);
22887   arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
22888   if (!arg_cst)
22889     {
22890       /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
22891 	 trying to unify the type of a variable with the type
22892 	 of a template parameter.  For example:
22893 
22894 	   template <unsigned int N>
22895 	   void f (char (&) [N]);
22896 	   int g();
22897 	   void h(int i) {
22898 	     char a[g(i)];
22899 	     f(a);
22900 	   }
22901 
22902 	 Here, the type of the ARG will be "int [g(i)]", and
22903 	 may be a SAVE_EXPR, etc.  */
22904       if (TREE_CODE (arg_max) != MINUS_EXPR)
22905 	return unify_vla_arg (explain_p, arg_dom);
22906       arg_max = TREE_OPERAND (arg_max, 0);
22907     }
22908 
22909   /* If only one of the bounds used a MINUS_EXPR, compensate
22910      by adding one to the other bound.  */
22911   if (parm_cst && !arg_cst)
22912     parm_max = fold_build2_loc (input_location, PLUS_EXPR,
22913 				integer_type_node,
22914 				parm_max,
22915 				integer_one_node);
22916   else if (arg_cst && !parm_cst)
22917     arg_max = fold_build2_loc (input_location, PLUS_EXPR,
22918 			       integer_type_node,
22919 			       arg_max,
22920 			       integer_one_node);
22921 
22922   return unify (tparms, targs, parm_max, arg_max,
22923 		UNIFY_ALLOW_INTEGER, explain_p);
22924 }
22925 
22926 /* Returns whether T, a P or A in unify, is a type, template or expression.  */
22927 
22928 enum pa_kind_t { pa_type, pa_tmpl, pa_expr };
22929 
22930 static pa_kind_t
pa_kind(tree t)22931 pa_kind (tree t)
22932 {
22933   if (PACK_EXPANSION_P (t))
22934     t = PACK_EXPANSION_PATTERN (t);
22935   if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
22936       || TREE_CODE (t) == UNBOUND_CLASS_TEMPLATE
22937       || DECL_TYPE_TEMPLATE_P (t))
22938     return pa_tmpl;
22939   else if (TYPE_P (t))
22940     return pa_type;
22941   else
22942     return pa_expr;
22943 }
22944 
22945 /* Deduce the value of template parameters.  TPARMS is the (innermost)
22946    set of template parameters to a template.  TARGS is the bindings
22947    for those template parameters, as determined thus far; TARGS may
22948    include template arguments for outer levels of template parameters
22949    as well.  PARM is a parameter to a template function, or a
22950    subcomponent of that parameter; ARG is the corresponding argument.
22951    This function attempts to match PARM with ARG in a manner
22952    consistent with the existing assignments in TARGS.  If more values
22953    are deduced, then TARGS is updated.
22954 
22955    Returns 0 if the type deduction succeeds, 1 otherwise.  The
22956    parameter STRICT is a bitwise or of the following flags:
22957 
22958      UNIFY_ALLOW_NONE:
22959        Require an exact match between PARM and ARG.
22960      UNIFY_ALLOW_MORE_CV_QUAL:
22961        Allow the deduced ARG to be more cv-qualified (by qualification
22962        conversion) than ARG.
22963      UNIFY_ALLOW_LESS_CV_QUAL:
22964        Allow the deduced ARG to be less cv-qualified than ARG.
22965      UNIFY_ALLOW_DERIVED:
22966        Allow the deduced ARG to be a template base class of ARG,
22967        or a pointer to a template base class of the type pointed to by
22968        ARG.
22969      UNIFY_ALLOW_INTEGER:
22970        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
22971        case for more information.
22972      UNIFY_ALLOW_OUTER_LEVEL:
22973        This is the outermost level of a deduction. Used to determine validity
22974        of qualification conversions. A valid qualification conversion must
22975        have const qualified pointers leading up to the inner type which
22976        requires additional CV quals, except at the outer level, where const
22977        is not required [conv.qual]. It would be normal to set this flag in
22978        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
22979      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
22980        This is the outermost level of a deduction, and PARM can be more CV
22981        qualified at this point.
22982      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
22983        This is the outermost level of a deduction, and PARM can be less CV
22984        qualified at this point.  */
22985 
22986 static int
unify(tree tparms,tree targs,tree parm,tree arg,int strict,bool explain_p)22987 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
22988        bool explain_p)
22989 {
22990   int idx;
22991   tree targ;
22992   tree tparm;
22993   int strict_in = strict;
22994   tsubst_flags_t complain = (explain_p
22995 			     ? tf_warning_or_error
22996 			     : tf_none);
22997 
22998   /* I don't think this will do the right thing with respect to types.
22999      But the only case I've seen it in so far has been array bounds, where
23000      signedness is the only information lost, and I think that will be
23001      okay.  VIEW_CONVERT_EXPR can appear with class NTTP, thanks to
23002      finish_id_expression_1, and are also OK.  */
23003   while (CONVERT_EXPR_P (parm) || TREE_CODE (parm) == VIEW_CONVERT_EXPR)
23004     parm = TREE_OPERAND (parm, 0);
23005 
23006   if (arg == error_mark_node)
23007     return unify_invalid (explain_p);
23008   if (arg == unknown_type_node
23009       || arg == init_list_type_node)
23010     /* We can't deduce anything from this, but we might get all the
23011        template args from other function args.  */
23012     return unify_success (explain_p);
23013 
23014   if (parm == any_targ_node || arg == any_targ_node)
23015     return unify_success (explain_p);
23016 
23017   /* If PARM uses template parameters, then we can't bail out here,
23018      even if ARG == PARM, since we won't record unifications for the
23019      template parameters.  We might need them if we're trying to
23020      figure out which of two things is more specialized.  */
23021   if (arg == parm && !uses_template_parms (parm))
23022     return unify_success (explain_p);
23023 
23024   /* Handle init lists early, so the rest of the function can assume
23025      we're dealing with a type. */
23026   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
23027     {
23028       tree elt, elttype;
23029       unsigned i;
23030       tree orig_parm = parm;
23031 
23032       if (!is_std_init_list (parm)
23033 	  && TREE_CODE (parm) != ARRAY_TYPE)
23034 	/* We can only deduce from an initializer list argument if the
23035 	   parameter is std::initializer_list or an array; otherwise this
23036 	   is a non-deduced context. */
23037 	return unify_success (explain_p);
23038 
23039       if (TREE_CODE (parm) == ARRAY_TYPE)
23040 	elttype = TREE_TYPE (parm);
23041       else
23042 	{
23043 	  elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
23044 	  /* Deduction is defined in terms of a single type, so just punt
23045 	     on the (bizarre) std::initializer_list<T...>.  */
23046 	  if (PACK_EXPANSION_P (elttype))
23047 	    return unify_success (explain_p);
23048 	}
23049 
23050       if (strict != DEDUCE_EXACT
23051 	  && TYPE_P (elttype)
23052 	  && !uses_deducible_template_parms (elttype))
23053 	/* If ELTTYPE has no deducible template parms, skip deduction from
23054 	   the list elements.  */;
23055       else
23056 	FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
23057 	  {
23058 	    int elt_strict = strict;
23059 
23060 	    if (elt == error_mark_node)
23061 	      return unify_invalid (explain_p);
23062 
23063 	    if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
23064 	      {
23065 		tree type = TREE_TYPE (elt);
23066 		if (type == error_mark_node)
23067 		  return unify_invalid (explain_p);
23068 		/* It should only be possible to get here for a call.  */
23069 		gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
23070 		elt_strict |= maybe_adjust_types_for_deduction
23071 		  (DEDUCE_CALL, &elttype, &type, elt);
23072 		elt = type;
23073 	      }
23074 
23075 	  RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
23076 				   explain_p);
23077 	}
23078 
23079       if (TREE_CODE (parm) == ARRAY_TYPE
23080 	  && deducible_array_bound (TYPE_DOMAIN (parm)))
23081 	{
23082 	  /* Also deduce from the length of the initializer list.  */
23083 	  tree max = size_int (CONSTRUCTOR_NELTS (arg));
23084 	  tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
23085 	  if (idx == error_mark_node)
23086 	    return unify_invalid (explain_p);
23087 	  return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
23088 				     idx, explain_p);
23089 	}
23090 
23091       /* If the std::initializer_list<T> deduction worked, replace the
23092 	 deduced A with std::initializer_list<A>.  */
23093       if (orig_parm != parm)
23094 	{
23095 	  idx = TEMPLATE_TYPE_IDX (orig_parm);
23096 	  targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
23097 	  targ = listify (targ);
23098 	  TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
23099 	}
23100       return unify_success (explain_p);
23101     }
23102 
23103   /* If parm and arg aren't the same kind of thing (template, type, or
23104      expression), fail early.  */
23105   if (pa_kind (parm) != pa_kind (arg))
23106     return unify_invalid (explain_p);
23107 
23108   /* Immediately reject some pairs that won't unify because of
23109      cv-qualification mismatches.  */
23110   if (TREE_CODE (arg) == TREE_CODE (parm)
23111       && TYPE_P (arg)
23112       /* It is the elements of the array which hold the cv quals of an array
23113 	 type, and the elements might be template type parms. We'll check
23114 	 when we recurse.  */
23115       && TREE_CODE (arg) != ARRAY_TYPE
23116       /* We check the cv-qualifiers when unifying with template type
23117 	 parameters below.  We want to allow ARG `const T' to unify with
23118 	 PARM `T' for example, when computing which of two templates
23119 	 is more specialized, for example.  */
23120       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
23121       && !check_cv_quals_for_unify (strict_in, arg, parm))
23122     return unify_cv_qual_mismatch (explain_p, parm, arg);
23123 
23124   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
23125       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
23126     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
23127   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
23128   strict &= ~UNIFY_ALLOW_DERIVED;
23129   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
23130   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
23131 
23132   switch (TREE_CODE (parm))
23133     {
23134     case TYPENAME_TYPE:
23135     case SCOPE_REF:
23136     case UNBOUND_CLASS_TEMPLATE:
23137       /* In a type which contains a nested-name-specifier, template
23138 	 argument values cannot be deduced for template parameters used
23139 	 within the nested-name-specifier.  */
23140       return unify_success (explain_p);
23141 
23142     case TEMPLATE_TYPE_PARM:
23143     case TEMPLATE_TEMPLATE_PARM:
23144     case BOUND_TEMPLATE_TEMPLATE_PARM:
23145       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
23146       if (error_operand_p (tparm))
23147 	return unify_invalid (explain_p);
23148 
23149       if (TEMPLATE_TYPE_LEVEL (parm)
23150 	  != template_decl_level (tparm))
23151 	/* The PARM is not one we're trying to unify.  Just check
23152 	   to see if it matches ARG.  */
23153 	{
23154 	  if (TREE_CODE (arg) == TREE_CODE (parm)
23155 	      && (is_auto (parm) ? is_auto (arg)
23156 		  : same_type_p (parm, arg)))
23157 	    return unify_success (explain_p);
23158 	  else
23159 	    return unify_type_mismatch (explain_p, parm, arg);
23160 	}
23161       idx = TEMPLATE_TYPE_IDX (parm);
23162       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
23163       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
23164       if (error_operand_p (tparm))
23165 	return unify_invalid (explain_p);
23166 
23167       /* Check for mixed types and values.  */
23168       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
23169 	   && TREE_CODE (tparm) != TYPE_DECL)
23170 	  || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
23171 	      && TREE_CODE (tparm) != TEMPLATE_DECL))
23172 	gcc_unreachable ();
23173 
23174       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23175 	{
23176 	  if ((strict_in & UNIFY_ALLOW_DERIVED)
23177 	      && CLASS_TYPE_P (arg))
23178 	    {
23179 	      /* First try to match ARG directly.  */
23180 	      tree t = try_class_unification (tparms, targs, parm, arg,
23181 					      explain_p);
23182 	      if (!t)
23183 		{
23184 		  /* Otherwise, look for a suitable base of ARG, as below.  */
23185 		  enum template_base_result r;
23186 		  r = get_template_base (tparms, targs, parm, arg,
23187 					 explain_p, &t);
23188 		  if (!t)
23189 		    return unify_no_common_base (explain_p, r, parm, arg);
23190 		  arg = t;
23191 		}
23192 	    }
23193 	  /* ARG must be constructed from a template class or a template
23194 	     template parameter.  */
23195 	  else if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
23196 		   && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
23197 	    return unify_template_deduction_failure (explain_p, parm, arg);
23198 
23199 	  /* Deduce arguments T, i from TT<T> or TT<i>.  */
23200 	  if (unify_bound_ttp_args (tparms, targs, parm, arg, explain_p))
23201 	    return 1;
23202 
23203 	  arg = TYPE_TI_TEMPLATE (arg);
23204 
23205 	  /* Fall through to deduce template name.  */
23206 	}
23207 
23208       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
23209 	  || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23210 	{
23211 	  /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
23212 
23213 	  /* Simple cases: Value already set, does match or doesn't.  */
23214 	  if (targ != NULL_TREE && template_args_equal (targ, arg))
23215 	    return unify_success (explain_p);
23216 	  else if (targ)
23217 	    return unify_inconsistency (explain_p, parm, targ, arg);
23218 	}
23219       else
23220 	{
23221 	  /* If PARM is `const T' and ARG is only `int', we don't have
23222 	     a match unless we are allowing additional qualification.
23223 	     If ARG is `const int' and PARM is just `T' that's OK;
23224 	     that binds `const int' to `T'.  */
23225 	  if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
23226 					 arg, parm))
23227 	    return unify_cv_qual_mismatch (explain_p, parm, arg);
23228 
23229 	  /* Consider the case where ARG is `const volatile int' and
23230 	     PARM is `const T'.  Then, T should be `volatile int'.  */
23231 	  arg = cp_build_qualified_type_real
23232 	    (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
23233 	  if (arg == error_mark_node)
23234 	    return unify_invalid (explain_p);
23235 
23236 	  /* Simple cases: Value already set, does match or doesn't.  */
23237 	  if (targ != NULL_TREE && same_type_p (targ, arg))
23238 	    return unify_success (explain_p);
23239 	  else if (targ)
23240 	    return unify_inconsistency (explain_p, parm, targ, arg);
23241 
23242 	  /* Make sure that ARG is not a variable-sized array.  (Note
23243 	     that were talking about variable-sized arrays (like
23244 	     `int[n]'), rather than arrays of unknown size (like
23245 	     `int[]').)  We'll get very confused by such a type since
23246 	     the bound of the array is not constant, and therefore
23247 	     not mangleable.  Besides, such types are not allowed in
23248 	     ISO C++, so we can do as we please here.  We do allow
23249 	     them for 'auto' deduction, since that isn't ABI-exposed.  */
23250 	  if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
23251 	    return unify_vla_arg (explain_p, arg);
23252 
23253 	  /* Strip typedefs as in convert_template_argument.  */
23254 	  arg = canonicalize_type_argument (arg, tf_none);
23255 	}
23256 
23257       /* If ARG is a parameter pack or an expansion, we cannot unify
23258 	 against it unless PARM is also a parameter pack.  */
23259       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
23260 	  && !template_parameter_pack_p (parm))
23261 	return unify_parameter_pack_mismatch (explain_p, parm, arg);
23262 
23263       /* If the argument deduction results is a METHOD_TYPE,
23264          then there is a problem.
23265          METHOD_TYPE doesn't map to any real C++ type the result of
23266 	 the deduction cannot be of that type.  */
23267       if (TREE_CODE (arg) == METHOD_TYPE)
23268 	return unify_method_type_error (explain_p, arg);
23269 
23270       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
23271       return unify_success (explain_p);
23272 
23273     case TEMPLATE_PARM_INDEX:
23274       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
23275       if (error_operand_p (tparm))
23276 	return unify_invalid (explain_p);
23277 
23278       if (TEMPLATE_PARM_LEVEL (parm)
23279 	  != template_decl_level (tparm))
23280 	{
23281 	  /* The PARM is not one we're trying to unify.  Just check
23282 	     to see if it matches ARG.  */
23283 	  int result = !(TREE_CODE (arg) == TREE_CODE (parm)
23284 			 && cp_tree_equal (parm, arg));
23285 	  if (result)
23286 	    unify_expression_unequal (explain_p, parm, arg);
23287 	  return result;
23288 	}
23289 
23290       idx = TEMPLATE_PARM_IDX (parm);
23291       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
23292 
23293       if (targ)
23294 	{
23295 	  if ((strict & UNIFY_ALLOW_INTEGER)
23296 	      && TREE_TYPE (targ) && TREE_TYPE (arg)
23297 	      && CP_INTEGRAL_TYPE_P (TREE_TYPE (targ)))
23298 	    /* We're deducing from an array bound, the type doesn't matter.  */
23299 	    arg = fold_convert (TREE_TYPE (targ), arg);
23300 	  int x = !cp_tree_equal (targ, arg);
23301 	  if (x)
23302 	    unify_inconsistency (explain_p, parm, targ, arg);
23303 	  return x;
23304 	}
23305 
23306       /* [temp.deduct.type] If, in the declaration of a function template
23307 	 with a non-type template-parameter, the non-type
23308 	 template-parameter is used in an expression in the function
23309 	 parameter-list and, if the corresponding template-argument is
23310 	 deduced, the template-argument type shall match the type of the
23311 	 template-parameter exactly, except that a template-argument
23312 	 deduced from an array bound may be of any integral type.
23313 	 The non-type parameter might use already deduced type parameters.  */
23314       tparm = TREE_TYPE (parm);
23315       if (TEMPLATE_PARM_LEVEL (parm) > TMPL_ARGS_DEPTH (targs))
23316 	/* We don't have enough levels of args to do any substitution.  This
23317 	   can happen in the context of -fnew-ttp-matching.  */;
23318       else
23319 	{
23320 	  ++processing_template_decl;
23321 	  tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
23322 	  --processing_template_decl;
23323 
23324 	  if (tree a = type_uses_auto (tparm))
23325 	    {
23326 	      tparm = do_auto_deduction (tparm, arg, a, complain, adc_unify);
23327 	      if (tparm == error_mark_node)
23328 		return 1;
23329 	    }
23330 	}
23331 
23332       if (!TREE_TYPE (arg))
23333 	/* Template-parameter dependent expression.  Just accept it for now.
23334 	   It will later be processed in convert_template_argument.  */
23335 	;
23336       else if (same_type_ignoring_top_level_qualifiers_p
23337 	       (non_reference (TREE_TYPE (arg)),
23338 		non_reference (tparm)))
23339 	/* OK.  Ignore top-level quals here because a class-type template
23340 	   parameter object is const.  */;
23341       else if ((strict & UNIFY_ALLOW_INTEGER)
23342 	       && CP_INTEGRAL_TYPE_P (tparm))
23343 	/* Convert the ARG to the type of PARM; the deduced non-type
23344 	   template argument must exactly match the types of the
23345 	   corresponding parameter.  */
23346 	arg = fold (build_nop (tparm, arg));
23347       else if (uses_template_parms (tparm))
23348 	{
23349 	  /* We haven't deduced the type of this parameter yet.  */
23350 	  if (cxx_dialect >= cxx17
23351 	      /* We deduce from array bounds in try_array_deduction.  */
23352 	      && !(strict & UNIFY_ALLOW_INTEGER))
23353 	    {
23354 	      /* Deduce it from the non-type argument.  */
23355 	      tree atype = TREE_TYPE (arg);
23356 	      RECUR_AND_CHECK_FAILURE (tparms, targs,
23357 				       tparm, atype,
23358 				       UNIFY_ALLOW_NONE, explain_p);
23359 	    }
23360 	  else
23361 	    /* Try again later.  */
23362 	    return unify_success (explain_p);
23363 	}
23364       else
23365 	return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
23366 
23367       /* If ARG is a parameter pack or an expansion, we cannot unify
23368 	 against it unless PARM is also a parameter pack.  */
23369       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
23370 	  && !TEMPLATE_PARM_PARAMETER_PACK (parm))
23371 	return unify_parameter_pack_mismatch (explain_p, parm, arg);
23372 
23373       {
23374 	bool removed_attr = false;
23375 	arg = strip_typedefs_expr (arg, &removed_attr);
23376       }
23377       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
23378       return unify_success (explain_p);
23379 
23380     case PTRMEM_CST:
23381      {
23382 	/* A pointer-to-member constant can be unified only with
23383 	 another constant.  */
23384       if (TREE_CODE (arg) != PTRMEM_CST)
23385 	return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
23386 
23387       /* Just unify the class member. It would be useless (and possibly
23388 	 wrong, depending on the strict flags) to unify also
23389 	 PTRMEM_CST_CLASS, because we want to be sure that both parm and
23390 	 arg refer to the same variable, even if through different
23391 	 classes. For instance:
23392 
23393 	 struct A { int x; };
23394 	 struct B : A { };
23395 
23396 	 Unification of &A::x and &B::x must succeed.  */
23397       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
23398 		    PTRMEM_CST_MEMBER (arg), strict, explain_p);
23399      }
23400 
23401     case POINTER_TYPE:
23402       {
23403 	if (!TYPE_PTR_P (arg))
23404 	  return unify_type_mismatch (explain_p, parm, arg);
23405 
23406 	/* [temp.deduct.call]
23407 
23408 	   A can be another pointer or pointer to member type that can
23409 	   be converted to the deduced A via a qualification
23410 	   conversion (_conv.qual_).
23411 
23412 	   We pass down STRICT here rather than UNIFY_ALLOW_NONE.
23413 	   This will allow for additional cv-qualification of the
23414 	   pointed-to types if appropriate.  */
23415 
23416 	if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
23417 	  /* The derived-to-base conversion only persists through one
23418 	     level of pointers.  */
23419 	  strict |= (strict_in & UNIFY_ALLOW_DERIVED);
23420 
23421 	return unify (tparms, targs, TREE_TYPE (parm),
23422 		      TREE_TYPE (arg), strict, explain_p);
23423       }
23424 
23425     case REFERENCE_TYPE:
23426       if (!TYPE_REF_P (arg))
23427 	return unify_type_mismatch (explain_p, parm, arg);
23428       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
23429 		    strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
23430 
23431     case ARRAY_TYPE:
23432       if (TREE_CODE (arg) != ARRAY_TYPE)
23433 	return unify_type_mismatch (explain_p, parm, arg);
23434       if ((TYPE_DOMAIN (parm) == NULL_TREE)
23435 	  != (TYPE_DOMAIN (arg) == NULL_TREE))
23436 	return unify_type_mismatch (explain_p, parm, arg);
23437       RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
23438 			       strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
23439       if (TYPE_DOMAIN (parm) != NULL_TREE)
23440 	return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
23441 				   TYPE_DOMAIN (arg), explain_p);
23442       return unify_success (explain_p);
23443 
23444     case REAL_TYPE:
23445     case COMPLEX_TYPE:
23446     case VECTOR_TYPE:
23447     case INTEGER_TYPE:
23448     case BOOLEAN_TYPE:
23449     case ENUMERAL_TYPE:
23450     case VOID_TYPE:
23451     case NULLPTR_TYPE:
23452       if (TREE_CODE (arg) != TREE_CODE (parm))
23453 	return unify_type_mismatch (explain_p, parm, arg);
23454 
23455       /* We have already checked cv-qualification at the top of the
23456 	 function.  */
23457       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
23458 	return unify_type_mismatch (explain_p, parm, arg);
23459 
23460       /* As far as unification is concerned, this wins.	 Later checks
23461 	 will invalidate it if necessary.  */
23462       return unify_success (explain_p);
23463 
23464       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
23465       /* Type INTEGER_CST can come from ordinary constant template args.  */
23466     case INTEGER_CST:
23467       while (CONVERT_EXPR_P (arg))
23468 	arg = TREE_OPERAND (arg, 0);
23469 
23470       if (TREE_CODE (arg) != INTEGER_CST)
23471 	return unify_template_argument_mismatch (explain_p, parm, arg);
23472       return (tree_int_cst_equal (parm, arg)
23473 	      ? unify_success (explain_p)
23474 	      : unify_template_argument_mismatch (explain_p, parm, arg));
23475 
23476     case TREE_VEC:
23477       {
23478 	int i, len, argslen;
23479 	int parm_variadic_p = 0;
23480 
23481 	if (TREE_CODE (arg) != TREE_VEC)
23482 	  return unify_template_argument_mismatch (explain_p, parm, arg);
23483 
23484 	len = TREE_VEC_LENGTH (parm);
23485 	argslen = TREE_VEC_LENGTH (arg);
23486 
23487 	/* Check for pack expansions in the parameters.  */
23488 	for (i = 0; i < len; ++i)
23489 	  {
23490 	    if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
23491 	      {
23492 		if (i == len - 1)
23493 		  /* We can unify against something with a trailing
23494 		     parameter pack.  */
23495 		  parm_variadic_p = 1;
23496 		else
23497 		  /* [temp.deduct.type]/9: If the template argument list of
23498 		     P contains a pack expansion that is not the last
23499 		     template argument, the entire template argument list
23500 		     is a non-deduced context.  */
23501 		  return unify_success (explain_p);
23502 	      }
23503 	  }
23504 
23505         /* If we don't have enough arguments to satisfy the parameters
23506            (not counting the pack expression at the end), or we have
23507            too many arguments for a parameter list that doesn't end in
23508            a pack expression, we can't unify.  */
23509 	if (parm_variadic_p
23510 	    ? argslen < len - parm_variadic_p
23511 	    : argslen != len)
23512 	  return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
23513 
23514 	/* Unify all of the parameters that precede the (optional)
23515 	   pack expression.  */
23516 	for (i = 0; i < len - parm_variadic_p; ++i)
23517 	  {
23518 	    RECUR_AND_CHECK_FAILURE (tparms, targs,
23519 				     TREE_VEC_ELT (parm, i),
23520 				     TREE_VEC_ELT (arg, i),
23521 				     UNIFY_ALLOW_NONE, explain_p);
23522 	  }
23523 	if (parm_variadic_p)
23524 	  return unify_pack_expansion (tparms, targs, parm, arg,
23525 				       DEDUCE_EXACT,
23526 				       /*subr=*/true, explain_p);
23527 	return unify_success (explain_p);
23528       }
23529 
23530     case RECORD_TYPE:
23531     case UNION_TYPE:
23532       if (TREE_CODE (arg) != TREE_CODE (parm))
23533 	return unify_type_mismatch (explain_p, parm, arg);
23534 
23535       if (TYPE_PTRMEMFUNC_P (parm))
23536 	{
23537 	  if (!TYPE_PTRMEMFUNC_P (arg))
23538 	    return unify_type_mismatch (explain_p, parm, arg);
23539 
23540 	  return unify (tparms, targs,
23541 			TYPE_PTRMEMFUNC_FN_TYPE (parm),
23542 			TYPE_PTRMEMFUNC_FN_TYPE (arg),
23543 			strict, explain_p);
23544 	}
23545       else if (TYPE_PTRMEMFUNC_P (arg))
23546 	return unify_type_mismatch (explain_p, parm, arg);
23547 
23548       if (CLASSTYPE_TEMPLATE_INFO (parm))
23549 	{
23550 	  tree t = NULL_TREE;
23551 
23552 	  if (strict_in & UNIFY_ALLOW_DERIVED)
23553 	    {
23554 	      /* First, we try to unify the PARM and ARG directly.  */
23555 	      t = try_class_unification (tparms, targs,
23556 					 parm, arg, explain_p);
23557 
23558 	      if (!t)
23559 		{
23560 		  /* Fallback to the special case allowed in
23561 		     [temp.deduct.call]:
23562 
23563 		       If P is a class, and P has the form
23564 		       template-id, then A can be a derived class of
23565 		       the deduced A.  Likewise, if P is a pointer to
23566 		       a class of the form template-id, A can be a
23567 		       pointer to a derived class pointed to by the
23568 		       deduced A.  */
23569 		  enum template_base_result r;
23570 		  r = get_template_base (tparms, targs, parm, arg,
23571 					 explain_p, &t);
23572 
23573 		  if (!t)
23574 		    {
23575 		      /* Don't give the derived diagnostic if we're
23576 			 already dealing with the same template.  */
23577 		      bool same_template
23578 			= (CLASSTYPE_TEMPLATE_INFO (arg)
23579 			   && (CLASSTYPE_TI_TEMPLATE (parm)
23580 			       == CLASSTYPE_TI_TEMPLATE (arg)));
23581 		      return unify_no_common_base (explain_p && !same_template,
23582 						   r, parm, arg);
23583 		    }
23584 		}
23585 	    }
23586 	  else if (CLASSTYPE_TEMPLATE_INFO (arg)
23587 		   && (CLASSTYPE_TI_TEMPLATE (parm)
23588 		       == CLASSTYPE_TI_TEMPLATE (arg)))
23589 	    /* Perhaps PARM is something like S<U> and ARG is S<int>.
23590 	       Then, we should unify `int' and `U'.  */
23591 	    t = arg;
23592 	  else
23593 	    /* There's no chance of unification succeeding.  */
23594 	    return unify_type_mismatch (explain_p, parm, arg);
23595 
23596 	  return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
23597 			CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
23598 	}
23599       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
23600 	return unify_type_mismatch (explain_p, parm, arg);
23601       return unify_success (explain_p);
23602 
23603     case METHOD_TYPE:
23604     case FUNCTION_TYPE:
23605       {
23606 	unsigned int nargs;
23607 	tree *args;
23608 	tree a;
23609 	unsigned int i;
23610 
23611 	if (TREE_CODE (arg) != TREE_CODE (parm))
23612 	  return unify_type_mismatch (explain_p, parm, arg);
23613 
23614 	/* CV qualifications for methods can never be deduced, they must
23615 	   match exactly.  We need to check them explicitly here,
23616 	   because type_unification_real treats them as any other
23617 	   cv-qualified parameter.  */
23618 	if (TREE_CODE (parm) == METHOD_TYPE
23619 	    && (!check_cv_quals_for_unify
23620 		(UNIFY_ALLOW_NONE,
23621 		 class_of_this_parm (arg),
23622 		 class_of_this_parm (parm))))
23623 	  return unify_cv_qual_mismatch (explain_p, parm, arg);
23624 	if (TREE_CODE (arg) == FUNCTION_TYPE
23625 	    && type_memfn_quals (parm) != type_memfn_quals (arg))
23626 	  return unify_cv_qual_mismatch (explain_p, parm, arg);
23627 	if (type_memfn_rqual (parm) != type_memfn_rqual (arg))
23628 	  return unify_type_mismatch (explain_p, parm, arg);
23629 
23630 	RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
23631 				 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
23632 
23633 	nargs = list_length (TYPE_ARG_TYPES (arg));
23634 	args = XALLOCAVEC (tree, nargs);
23635 	for (a = TYPE_ARG_TYPES (arg), i = 0;
23636 	     a != NULL_TREE && a != void_list_node;
23637 	     a = TREE_CHAIN (a), ++i)
23638 	  args[i] = TREE_VALUE (a);
23639 	nargs = i;
23640 
23641 	if (type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
23642 				   args, nargs, 1, DEDUCE_EXACT,
23643 				   NULL, explain_p))
23644 	  return 1;
23645 
23646 	if (flag_noexcept_type)
23647 	  {
23648 	    tree pspec = TYPE_RAISES_EXCEPTIONS (parm);
23649 	    tree aspec = canonical_eh_spec (TYPE_RAISES_EXCEPTIONS (arg));
23650 	    if (pspec == NULL_TREE) pspec = noexcept_false_spec;
23651 	    if (aspec == NULL_TREE) aspec = noexcept_false_spec;
23652 	    if (TREE_PURPOSE (pspec) && TREE_PURPOSE (aspec)
23653 		&& uses_template_parms (TREE_PURPOSE (pspec)))
23654 	      RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_PURPOSE (pspec),
23655 				       TREE_PURPOSE (aspec),
23656 				       UNIFY_ALLOW_NONE, explain_p);
23657 	    else if (nothrow_spec_p (pspec) && !nothrow_spec_p (aspec))
23658 	      return unify_type_mismatch (explain_p, parm, arg);
23659 	  }
23660 
23661 	return 0;
23662       }
23663 
23664     case OFFSET_TYPE:
23665       /* Unify a pointer to member with a pointer to member function, which
23666 	 deduces the type of the member as a function type. */
23667       if (TYPE_PTRMEMFUNC_P (arg))
23668 	{
23669 	  /* Check top-level cv qualifiers */
23670 	  if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
23671 	    return unify_cv_qual_mismatch (explain_p, parm, arg);
23672 
23673 	  RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
23674 				   TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
23675 				   UNIFY_ALLOW_NONE, explain_p);
23676 
23677 	  /* Determine the type of the function we are unifying against. */
23678 	  tree fntype = static_fn_type (arg);
23679 
23680 	  return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
23681 	}
23682 
23683       if (TREE_CODE (arg) != OFFSET_TYPE)
23684 	return unify_type_mismatch (explain_p, parm, arg);
23685       RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
23686 			       TYPE_OFFSET_BASETYPE (arg),
23687 			       UNIFY_ALLOW_NONE, explain_p);
23688       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
23689 		    strict, explain_p);
23690 
23691     case CONST_DECL:
23692       if (DECL_TEMPLATE_PARM_P (parm))
23693 	return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
23694       if (arg != scalar_constant_value (parm))
23695 	return unify_template_argument_mismatch (explain_p, parm, arg);
23696       return unify_success (explain_p);
23697 
23698     case FIELD_DECL:
23699     case TEMPLATE_DECL:
23700       /* Matched cases are handled by the ARG == PARM test above.  */
23701       return unify_template_argument_mismatch (explain_p, parm, arg);
23702 
23703     case VAR_DECL:
23704       /* We might get a variable as a non-type template argument in parm if the
23705 	 corresponding parameter is type-dependent.  Make any necessary
23706 	 adjustments based on whether arg is a reference.  */
23707       if (CONSTANT_CLASS_P (arg))
23708 	parm = fold_non_dependent_expr (parm, complain);
23709       else if (REFERENCE_REF_P (arg))
23710 	{
23711 	  tree sub = TREE_OPERAND (arg, 0);
23712 	  STRIP_NOPS (sub);
23713 	  if (TREE_CODE (sub) == ADDR_EXPR)
23714 	    arg = TREE_OPERAND (sub, 0);
23715 	}
23716       /* Now use the normal expression code to check whether they match.  */
23717       goto expr;
23718 
23719     case TYPE_ARGUMENT_PACK:
23720     case NONTYPE_ARGUMENT_PACK:
23721       return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
23722 		    ARGUMENT_PACK_ARGS (arg), strict, explain_p);
23723 
23724     case TYPEOF_TYPE:
23725     case DECLTYPE_TYPE:
23726     case UNDERLYING_TYPE:
23727       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
23728 	 or UNDERLYING_TYPE nodes.  */
23729       return unify_success (explain_p);
23730 
23731     case ERROR_MARK:
23732       /* Unification fails if we hit an error node.  */
23733       return unify_invalid (explain_p);
23734 
23735     case INDIRECT_REF:
23736       if (REFERENCE_REF_P (parm))
23737 	{
23738 	  bool pexp = PACK_EXPANSION_P (arg);
23739 	  if (pexp)
23740 	    arg = PACK_EXPANSION_PATTERN (arg);
23741 	  if (REFERENCE_REF_P (arg))
23742 	    arg = TREE_OPERAND (arg, 0);
23743 	  if (pexp)
23744 	    arg = make_pack_expansion (arg, complain);
23745 	  return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
23746 			strict, explain_p);
23747 	}
23748       /* FALLTHRU */
23749 
23750     default:
23751       /* An unresolved overload is a nondeduced context.  */
23752       if (is_overloaded_fn (parm) || type_unknown_p (parm))
23753 	return unify_success (explain_p);
23754       gcc_assert (EXPR_P (parm)
23755 		  || COMPOUND_LITERAL_P (parm)
23756 		  || TREE_CODE (parm) == TRAIT_EXPR);
23757     expr:
23758       /* We must be looking at an expression.  This can happen with
23759 	 something like:
23760 
23761 	   template <int I>
23762 	   void foo(S<I>, S<I + 2>);
23763 
23764 	 or
23765 
23766 	   template<typename T>
23767 	   void foo(A<T, T{}>);
23768 
23769 	 This is a "non-deduced context":
23770 
23771 	   [deduct.type]
23772 
23773 	   The non-deduced contexts are:
23774 
23775 	   --A non-type template argument or an array bound in which
23776 	     a subexpression references a template parameter.
23777 
23778 	 In these cases, we assume deduction succeeded, but don't
23779 	 actually infer any unifications.  */
23780 
23781       if (!uses_template_parms (parm)
23782 	  && !template_args_equal (parm, arg))
23783 	return unify_expression_unequal (explain_p, parm, arg);
23784       else
23785 	return unify_success (explain_p);
23786     }
23787 }
23788 #undef RECUR_AND_CHECK_FAILURE
23789 
23790 /* Note that DECL can be defined in this translation unit, if
23791    required.  */
23792 
23793 static void
mark_definable(tree decl)23794 mark_definable (tree decl)
23795 {
23796   tree clone;
23797   DECL_NOT_REALLY_EXTERN (decl) = 1;
23798   FOR_EACH_CLONE (clone, decl)
23799     DECL_NOT_REALLY_EXTERN (clone) = 1;
23800 }
23801 
23802 /* Called if RESULT is explicitly instantiated, or is a member of an
23803    explicitly instantiated class.  */
23804 
23805 void
mark_decl_instantiated(tree result,int extern_p)23806 mark_decl_instantiated (tree result, int extern_p)
23807 {
23808   SET_DECL_EXPLICIT_INSTANTIATION (result);
23809 
23810   /* If this entity has already been written out, it's too late to
23811      make any modifications.  */
23812   if (TREE_ASM_WRITTEN (result))
23813     return;
23814 
23815   /* For anonymous namespace we don't need to do anything.  */
23816   if (decl_anon_ns_mem_p (result))
23817     {
23818       gcc_assert (!TREE_PUBLIC (result));
23819       return;
23820     }
23821 
23822   if (TREE_CODE (result) != FUNCTION_DECL)
23823     /* The TREE_PUBLIC flag for function declarations will have been
23824        set correctly by tsubst.  */
23825     TREE_PUBLIC (result) = 1;
23826 
23827   /* This might have been set by an earlier implicit instantiation.  */
23828   DECL_COMDAT (result) = 0;
23829 
23830   if (extern_p)
23831     DECL_NOT_REALLY_EXTERN (result) = 0;
23832   else
23833     {
23834       mark_definable (result);
23835       mark_needed (result);
23836       /* Always make artificials weak.  */
23837       if (DECL_ARTIFICIAL (result) && flag_weak)
23838 	comdat_linkage (result);
23839       /* For WIN32 we also want to put explicit instantiations in
23840 	 linkonce sections.  */
23841       else if (TREE_PUBLIC (result))
23842 	maybe_make_one_only (result);
23843       if (TREE_CODE (result) == FUNCTION_DECL
23844 	  && DECL_TEMPLATE_INSTANTIATED (result))
23845 	/* If the function has already been instantiated, clear DECL_EXTERNAL,
23846 	   since start_preparsed_function wouldn't have if we had an earlier
23847 	   extern explicit instantiation.  */
23848 	DECL_EXTERNAL (result) = 0;
23849     }
23850 
23851   /* If EXTERN_P, then this function will not be emitted -- unless
23852      followed by an explicit instantiation, at which point its linkage
23853      will be adjusted.  If !EXTERN_P, then this function will be
23854      emitted here.  In neither circumstance do we want
23855      import_export_decl to adjust the linkage.  */
23856   DECL_INTERFACE_KNOWN (result) = 1;
23857 }
23858 
23859 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
23860    important template arguments.  If any are missing, we check whether
23861    they're important by using error_mark_node for substituting into any
23862    args that were used for partial ordering (the ones between ARGS and END)
23863    and seeing if it bubbles up.  */
23864 
23865 static bool
check_undeduced_parms(tree targs,tree args,tree end)23866 check_undeduced_parms (tree targs, tree args, tree end)
23867 {
23868   bool found = false;
23869   int i;
23870   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
23871     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
23872       {
23873 	found = true;
23874 	TREE_VEC_ELT (targs, i) = error_mark_node;
23875       }
23876   if (found)
23877     {
23878       tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
23879       if (substed == error_mark_node)
23880 	return true;
23881     }
23882   return false;
23883 }
23884 
23885 /* Given two function templates PAT1 and PAT2, return:
23886 
23887    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
23888    -1 if PAT2 is more specialized than PAT1.
23889    0 if neither is more specialized.
23890 
23891    LEN indicates the number of parameters we should consider
23892    (defaulted parameters should not be considered).
23893 
23894    The 1998 std underspecified function template partial ordering, and
23895    DR214 addresses the issue.  We take pairs of arguments, one from
23896    each of the templates, and deduce them against each other.  One of
23897    the templates will be more specialized if all the *other*
23898    template's arguments deduce against its arguments and at least one
23899    of its arguments *does* *not* deduce against the other template's
23900    corresponding argument.  Deduction is done as for class templates.
23901    The arguments used in deduction have reference and top level cv
23902    qualifiers removed.  Iff both arguments were originally reference
23903    types *and* deduction succeeds in both directions, an lvalue reference
23904    wins against an rvalue reference and otherwise the template
23905    with the more cv-qualified argument wins for that pairing (if
23906    neither is more cv-qualified, they both are equal).  Unlike regular
23907    deduction, after all the arguments have been deduced in this way,
23908    we do *not* verify the deduced template argument values can be
23909    substituted into non-deduced contexts.
23910 
23911    The logic can be a bit confusing here, because we look at deduce1 and
23912    targs1 to see if pat2 is at least as specialized, and vice versa; if we
23913    can find template arguments for pat1 to make arg1 look like arg2, that
23914    means that arg2 is at least as specialized as arg1.  */
23915 
23916 int
more_specialized_fn(tree pat1,tree pat2,int len)23917 more_specialized_fn (tree pat1, tree pat2, int len)
23918 {
23919   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
23920   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
23921   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
23922   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
23923   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
23924   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
23925   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
23926   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
23927   tree origs1, origs2;
23928   bool lose1 = false;
23929   bool lose2 = false;
23930 
23931   /* Remove the this parameter from non-static member functions.  If
23932      one is a non-static member function and the other is not a static
23933      member function, remove the first parameter from that function
23934      also.  This situation occurs for operator functions where we
23935      locate both a member function (with this pointer) and non-member
23936      operator (with explicit first operand).  */
23937   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
23938     {
23939       len--; /* LEN is the number of significant arguments for DECL1 */
23940       args1 = TREE_CHAIN (args1);
23941       if (!DECL_STATIC_FUNCTION_P (decl2))
23942 	args2 = TREE_CHAIN (args2);
23943     }
23944   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
23945     {
23946       args2 = TREE_CHAIN (args2);
23947       if (!DECL_STATIC_FUNCTION_P (decl1))
23948 	{
23949 	  len--;
23950 	  args1 = TREE_CHAIN (args1);
23951 	}
23952     }
23953 
23954   /* If only one is a conversion operator, they are unordered.  */
23955   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
23956     return 0;
23957 
23958   /* Consider the return type for a conversion function */
23959   if (DECL_CONV_FN_P (decl1))
23960     {
23961       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
23962       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
23963       len++;
23964     }
23965 
23966   processing_template_decl++;
23967 
23968   origs1 = args1;
23969   origs2 = args2;
23970 
23971   while (len--
23972 	 /* Stop when an ellipsis is seen.  */
23973 	 && args1 != NULL_TREE && args2 != NULL_TREE)
23974     {
23975       tree arg1 = TREE_VALUE (args1);
23976       tree arg2 = TREE_VALUE (args2);
23977       int deduce1, deduce2;
23978       int quals1 = -1;
23979       int quals2 = -1;
23980       int ref1 = 0;
23981       int ref2 = 0;
23982 
23983       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
23984           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
23985         {
23986           /* When both arguments are pack expansions, we need only
23987              unify the patterns themselves.  */
23988           arg1 = PACK_EXPANSION_PATTERN (arg1);
23989           arg2 = PACK_EXPANSION_PATTERN (arg2);
23990 
23991           /* This is the last comparison we need to do.  */
23992           len = 0;
23993         }
23994 
23995       /* DR 1847: If a particular P contains no template-parameters that
23996 	 participate in template argument deduction, that P is not used to
23997 	 determine the ordering.  */
23998       if (!uses_deducible_template_parms (arg1)
23999 	  && !uses_deducible_template_parms (arg2))
24000 	goto next;
24001 
24002       if (TYPE_REF_P (arg1))
24003 	{
24004 	  ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
24005 	  arg1 = TREE_TYPE (arg1);
24006 	  quals1 = cp_type_quals (arg1);
24007 	}
24008 
24009       if (TYPE_REF_P (arg2))
24010 	{
24011 	  ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
24012 	  arg2 = TREE_TYPE (arg2);
24013 	  quals2 = cp_type_quals (arg2);
24014 	}
24015 
24016       arg1 = TYPE_MAIN_VARIANT (arg1);
24017       arg2 = TYPE_MAIN_VARIANT (arg2);
24018 
24019       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
24020         {
24021           int i, len2 = remaining_arguments (args2);
24022           tree parmvec = make_tree_vec (1);
24023           tree argvec = make_tree_vec (len2);
24024           tree ta = args2;
24025 
24026           /* Setup the parameter vector, which contains only ARG1.  */
24027           TREE_VEC_ELT (parmvec, 0) = arg1;
24028 
24029           /* Setup the argument vector, which contains the remaining
24030              arguments.  */
24031           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
24032             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
24033 
24034           deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
24035 					   argvec, DEDUCE_EXACT,
24036 					   /*subr=*/true, /*explain_p=*/false)
24037 		     == 0);
24038 
24039           /* We cannot deduce in the other direction, because ARG1 is
24040              a pack expansion but ARG2 is not.  */
24041           deduce2 = 0;
24042         }
24043       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
24044         {
24045           int i, len1 = remaining_arguments (args1);
24046           tree parmvec = make_tree_vec (1);
24047           tree argvec = make_tree_vec (len1);
24048           tree ta = args1;
24049 
24050           /* Setup the parameter vector, which contains only ARG1.  */
24051           TREE_VEC_ELT (parmvec, 0) = arg2;
24052 
24053           /* Setup the argument vector, which contains the remaining
24054              arguments.  */
24055           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
24056             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
24057 
24058           deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
24059 					   argvec, DEDUCE_EXACT,
24060 					   /*subr=*/true, /*explain_p=*/false)
24061 		     == 0);
24062 
24063           /* We cannot deduce in the other direction, because ARG2 is
24064              a pack expansion but ARG1 is not.*/
24065           deduce1 = 0;
24066         }
24067 
24068       else
24069         {
24070           /* The normal case, where neither argument is a pack
24071              expansion.  */
24072           deduce1 = (unify (tparms1, targs1, arg1, arg2,
24073 			    UNIFY_ALLOW_NONE, /*explain_p=*/false)
24074 		     == 0);
24075           deduce2 = (unify (tparms2, targs2, arg2, arg1,
24076 			    UNIFY_ALLOW_NONE, /*explain_p=*/false)
24077 		     == 0);
24078         }
24079 
24080       /* If we couldn't deduce arguments for tparms1 to make arg1 match
24081 	 arg2, then arg2 is not as specialized as arg1.  */
24082       if (!deduce1)
24083 	lose2 = true;
24084       if (!deduce2)
24085 	lose1 = true;
24086 
24087       /* "If, for a given type, deduction succeeds in both directions
24088 	 (i.e., the types are identical after the transformations above)
24089 	 and both P and A were reference types (before being replaced with
24090 	 the type referred to above):
24091 	 - if the type from the argument template was an lvalue reference and
24092 	 the type from the parameter template was not, the argument type is
24093 	 considered to be more specialized than the other; otherwise,
24094 	 - if the type from the argument template is more cv-qualified
24095 	 than the type from the parameter template (as described above),
24096 	 the argument type is considered to be more specialized than the other;
24097 	 otherwise,
24098 	 - neither type is more specialized than the other."  */
24099 
24100       if (deduce1 && deduce2)
24101 	{
24102 	  if (ref1 && ref2 && ref1 != ref2)
24103 	    {
24104 	      if (ref1 > ref2)
24105 		lose1 = true;
24106 	      else
24107 		lose2 = true;
24108 	    }
24109 	  else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
24110 	    {
24111 	      if ((quals1 & quals2) == quals2)
24112 		lose2 = true;
24113 	      if ((quals1 & quals2) == quals1)
24114 		lose1 = true;
24115 	    }
24116 	}
24117 
24118       if (lose1 && lose2)
24119 	/* We've failed to deduce something in either direction.
24120 	   These must be unordered.  */
24121 	break;
24122 
24123     next:
24124 
24125       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
24126           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
24127         /* We have already processed all of the arguments in our
24128            handing of the pack expansion type.  */
24129         len = 0;
24130 
24131       args1 = TREE_CHAIN (args1);
24132       args2 = TREE_CHAIN (args2);
24133     }
24134 
24135   /* "In most cases, all template parameters must have values in order for
24136      deduction to succeed, but for partial ordering purposes a template
24137      parameter may remain without a value provided it is not used in the
24138      types being used for partial ordering."
24139 
24140      Thus, if we are missing any of the targs1 we need to substitute into
24141      origs1, then pat2 is not as specialized as pat1.  This can happen when
24142      there is a nondeduced context.  */
24143   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
24144     lose2 = true;
24145   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
24146     lose1 = true;
24147 
24148   processing_template_decl--;
24149 
24150   /* If both deductions succeed, the partial ordering selects the more
24151      constrained template.  */
24152   /* P2113: If the corresponding template-parameters of the
24153      template-parameter-lists are not equivalent ([temp.over.link]) or if
24154      the function parameters that positionally correspond between the two
24155      templates are not of the same type, neither template is more
24156      specialized than the other.  */
24157   if (!lose1 && !lose2
24158       && comp_template_parms (DECL_TEMPLATE_PARMS (pat1),
24159 			      DECL_TEMPLATE_PARMS (pat2))
24160       && compparms (origs1, origs2))
24161     {
24162       int winner = more_constrained (decl1, decl2);
24163       if (winner > 0)
24164 	lose2 = true;
24165       else if (winner < 0)
24166 	lose1 = true;
24167     }
24168 
24169   /* All things being equal, if the next argument is a pack expansion
24170      for one function but not for the other, prefer the
24171      non-variadic function.  FIXME this is bogus; see c++/41958.  */
24172   if (lose1 == lose2
24173       && args1 && TREE_VALUE (args1)
24174       && args2 && TREE_VALUE (args2))
24175     {
24176       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
24177       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
24178     }
24179 
24180   if (lose1 == lose2)
24181     return 0;
24182   else if (!lose1)
24183     return 1;
24184   else
24185     return -1;
24186 }
24187 
24188 /* Determine which of two partial specializations of TMPL is more
24189    specialized.
24190 
24191    PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
24192    to the first partial specialization.  The TREE_PURPOSE is the
24193    innermost set of template parameters for the partial
24194    specialization.  PAT2 is similar, but for the second template.
24195 
24196    Return 1 if the first partial specialization is more specialized;
24197    -1 if the second is more specialized; 0 if neither is more
24198    specialized.
24199 
24200    See [temp.class.order] for information about determining which of
24201    two templates is more specialized.  */
24202 
24203 static int
more_specialized_partial_spec(tree tmpl,tree pat1,tree pat2)24204 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
24205 {
24206   tree targs;
24207   int winner = 0;
24208   bool any_deductions = false;
24209 
24210   tree tmpl1 = TREE_VALUE (pat1);
24211   tree tmpl2 = TREE_VALUE (pat2);
24212   tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
24213   tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
24214 
24215   /* Just like what happens for functions, if we are ordering between
24216      different template specializations, we may encounter dependent
24217      types in the arguments, and we need our dependency check functions
24218      to behave correctly.  */
24219   ++processing_template_decl;
24220   targs = get_partial_spec_bindings (tmpl, tmpl1, specargs2);
24221   if (targs)
24222     {
24223       --winner;
24224       any_deductions = true;
24225     }
24226 
24227   targs = get_partial_spec_bindings (tmpl, tmpl2, specargs1);
24228   if (targs)
24229     {
24230       ++winner;
24231       any_deductions = true;
24232     }
24233   --processing_template_decl;
24234 
24235   /* If both deductions succeed, the partial ordering selects the more
24236      constrained template.  */
24237   if (!winner && any_deductions)
24238     winner = more_constrained (tmpl1, tmpl2);
24239 
24240   /* In the case of a tie where at least one of the templates
24241      has a parameter pack at the end, the template with the most
24242      non-packed parameters wins.  */
24243   if (winner == 0
24244       && any_deductions
24245       && (template_args_variadic_p (TREE_PURPOSE (pat1))
24246           || template_args_variadic_p (TREE_PURPOSE (pat2))))
24247     {
24248       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
24249       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
24250       int len1 = TREE_VEC_LENGTH (args1);
24251       int len2 = TREE_VEC_LENGTH (args2);
24252 
24253       /* We don't count the pack expansion at the end.  */
24254       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
24255         --len1;
24256       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
24257         --len2;
24258 
24259       if (len1 > len2)
24260         return 1;
24261       else if (len1 < len2)
24262         return -1;
24263     }
24264 
24265   return winner;
24266 }
24267 
24268 /* Return the template arguments that will produce the function signature
24269    DECL from the function template FN, with the explicit template
24270    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
24271    also match.  Return NULL_TREE if no satisfactory arguments could be
24272    found.  */
24273 
24274 static tree
get_bindings(tree fn,tree decl,tree explicit_args,bool check_rettype)24275 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
24276 {
24277   int ntparms = DECL_NTPARMS (fn);
24278   tree targs = make_tree_vec (ntparms);
24279   tree decl_type = TREE_TYPE (decl);
24280   tree decl_arg_types;
24281   tree *args;
24282   unsigned int nargs, ix;
24283   tree arg;
24284 
24285   gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
24286 
24287   /* Never do unification on the 'this' parameter.  */
24288   decl_arg_types = skip_artificial_parms_for (decl,
24289 					      TYPE_ARG_TYPES (decl_type));
24290 
24291   nargs = list_length (decl_arg_types);
24292   args = XALLOCAVEC (tree, nargs);
24293   for (arg = decl_arg_types, ix = 0;
24294        arg != NULL_TREE && arg != void_list_node;
24295        arg = TREE_CHAIN (arg), ++ix)
24296     args[ix] = TREE_VALUE (arg);
24297 
24298   if (fn_type_unification (fn, explicit_args, targs,
24299 			   args, ix,
24300 			   (check_rettype || DECL_CONV_FN_P (fn)
24301 			    ? TREE_TYPE (decl_type) : NULL_TREE),
24302 			   DEDUCE_EXACT, LOOKUP_NORMAL, NULL,
24303 			   /*explain_p=*/false,
24304 			   /*decltype*/false)
24305       == error_mark_node)
24306     return NULL_TREE;
24307 
24308   return targs;
24309 }
24310 
24311 /* Return the innermost template arguments that, when applied to a partial
24312    specialization SPEC_TMPL of TMPL, yield the ARGS.
24313 
24314    For example, suppose we have:
24315 
24316      template <class T, class U> struct S {};
24317      template <class T> struct S<T*, int> {};
24318 
24319    Then, suppose we want to get `S<double*, int>'.  SPEC_TMPL will be the
24320    partial specialization and the ARGS will be {double*, int}.  The resulting
24321    vector will be {double}, indicating that `T' is bound to `double'.  */
24322 
24323 static tree
get_partial_spec_bindings(tree tmpl,tree spec_tmpl,tree args)24324 get_partial_spec_bindings (tree tmpl, tree spec_tmpl, tree args)
24325 {
24326   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
24327   tree spec_args
24328     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (spec_tmpl)));
24329   int i, ntparms = TREE_VEC_LENGTH (tparms);
24330   tree deduced_args;
24331   tree innermost_deduced_args;
24332 
24333   innermost_deduced_args = make_tree_vec (ntparms);
24334   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
24335     {
24336       deduced_args = copy_node (args);
24337       SET_TMPL_ARGS_LEVEL (deduced_args,
24338 			   TMPL_ARGS_DEPTH (deduced_args),
24339 			   innermost_deduced_args);
24340     }
24341   else
24342     deduced_args = innermost_deduced_args;
24343 
24344   bool tried_array_deduction = (cxx_dialect < cxx17);
24345  again:
24346   if (unify (tparms, deduced_args,
24347 	     INNERMOST_TEMPLATE_ARGS (spec_args),
24348 	     INNERMOST_TEMPLATE_ARGS (args),
24349 	     UNIFY_ALLOW_NONE, /*explain_p=*/false))
24350     return NULL_TREE;
24351 
24352   for (i =  0; i < ntparms; ++i)
24353     if (! TREE_VEC_ELT (innermost_deduced_args, i))
24354       {
24355 	if (!tried_array_deduction)
24356 	  {
24357 	    try_array_deduction (tparms, innermost_deduced_args,
24358 				 INNERMOST_TEMPLATE_ARGS (spec_args));
24359 	    tried_array_deduction = true;
24360 	    if (TREE_VEC_ELT (innermost_deduced_args, i))
24361 	      goto again;
24362 	  }
24363 	return NULL_TREE;
24364       }
24365 
24366   if (!push_tinst_level (spec_tmpl, deduced_args))
24367     {
24368       excessive_deduction_depth = true;
24369       return NULL_TREE;
24370     }
24371 
24372   /* Verify that nondeduced template arguments agree with the type
24373      obtained from argument deduction.
24374 
24375      For example:
24376 
24377        struct A { typedef int X; };
24378        template <class T, class U> struct C {};
24379        template <class T> struct C<T, typename T::X> {};
24380 
24381      Then with the instantiation `C<A, int>', we can deduce that
24382      `T' is `A' but unify () does not check whether `typename T::X'
24383      is `int'.  */
24384   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
24385 
24386   if (spec_args != error_mark_node)
24387     spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
24388 				       INNERMOST_TEMPLATE_ARGS (spec_args),
24389 				       tmpl, tf_none, false, false);
24390 
24391   pop_tinst_level ();
24392 
24393   if (spec_args == error_mark_node
24394       /* We only need to check the innermost arguments; the other
24395 	 arguments will always agree.  */
24396       || !comp_template_args_porder (INNERMOST_TEMPLATE_ARGS (spec_args),
24397 				     INNERMOST_TEMPLATE_ARGS (args)))
24398     return NULL_TREE;
24399 
24400   /* Now that we have bindings for all of the template arguments,
24401      ensure that the arguments deduced for the template template
24402      parameters have compatible template parameter lists.  See the use
24403      of template_template_parm_bindings_ok_p in fn_type_unification
24404      for more information.  */
24405   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
24406     return NULL_TREE;
24407 
24408   return deduced_args;
24409 }
24410 
24411 // Compare two function templates T1 and T2 by deducing bindings
24412 // from one against the other. If both deductions succeed, compare
24413 // constraints to see which is more constrained.
24414 static int
more_specialized_inst(tree t1,tree t2)24415 more_specialized_inst (tree t1, tree t2)
24416 {
24417   int fate = 0;
24418   int count = 0;
24419 
24420   if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
24421     {
24422       --fate;
24423       ++count;
24424     }
24425 
24426   if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
24427     {
24428       ++fate;
24429       ++count;
24430     }
24431 
24432   // If both deductions succeed, then one may be more constrained.
24433   if (count == 2 && fate == 0)
24434     fate = more_constrained (t1, t2);
24435 
24436   return fate;
24437 }
24438 
24439 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
24440    Return the TREE_LIST node with the most specialized template, if
24441    any.  If there is no most specialized template, the error_mark_node
24442    is returned.
24443 
24444    Note that this function does not look at, or modify, the
24445    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
24446    returned is one of the elements of INSTANTIATIONS, callers may
24447    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
24448    and retrieve it from the value returned.  */
24449 
24450 tree
most_specialized_instantiation(tree templates)24451 most_specialized_instantiation (tree templates)
24452 {
24453   tree fn, champ;
24454 
24455   ++processing_template_decl;
24456 
24457   champ = templates;
24458   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
24459     {
24460       gcc_assert (TREE_VALUE (champ) != TREE_VALUE (fn));
24461       int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
24462       if (fate == -1)
24463 	champ = fn;
24464       else if (!fate)
24465 	{
24466 	  /* Equally specialized, move to next function.  If there
24467 	     is no next function, nothing's most specialized.  */
24468 	  fn = TREE_CHAIN (fn);
24469 	  champ = fn;
24470 	  if (!fn)
24471 	    break;
24472 	}
24473     }
24474 
24475   if (champ)
24476     /* Now verify that champ is better than everything earlier in the
24477        instantiation list.  */
24478     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
24479       if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
24480       {
24481         champ = NULL_TREE;
24482         break;
24483       }
24484     }
24485 
24486   processing_template_decl--;
24487 
24488   if (!champ)
24489     return error_mark_node;
24490 
24491   return champ;
24492 }
24493 
24494 /* If DECL is a specialization of some template, return the most
24495    general such template.  Otherwise, returns NULL_TREE.
24496 
24497    For example, given:
24498 
24499      template <class T> struct S { template <class U> void f(U); };
24500 
24501    if TMPL is `template <class U> void S<int>::f(U)' this will return
24502    the full template.  This function will not trace past partial
24503    specializations, however.  For example, given in addition:
24504 
24505      template <class T> struct S<T*> { template <class U> void f(U); };
24506 
24507    if TMPL is `template <class U> void S<int*>::f(U)' this will return
24508    `template <class T> template <class U> S<T*>::f(U)'.  */
24509 
24510 tree
most_general_template(tree decl)24511 most_general_template (tree decl)
24512 {
24513   if (TREE_CODE (decl) != TEMPLATE_DECL)
24514     {
24515       if (tree tinfo = get_template_info (decl))
24516 	decl = TI_TEMPLATE (tinfo);
24517       /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
24518 	 template friend, or a FIELD_DECL for a capture pack.  */
24519       if (TREE_CODE (decl) != TEMPLATE_DECL)
24520 	return NULL_TREE;
24521     }
24522 
24523   /* Look for more and more general templates.  */
24524   while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
24525     {
24526       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
24527 	 (See cp-tree.h for details.)  */
24528       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
24529 	break;
24530 
24531       if (CLASS_TYPE_P (TREE_TYPE (decl))
24532 	  && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
24533 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
24534 	break;
24535 
24536       /* Stop if we run into an explicitly specialized class template.  */
24537       if (!DECL_NAMESPACE_SCOPE_P (decl)
24538 	  && DECL_CONTEXT (decl)
24539 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
24540 	break;
24541 
24542       decl = DECL_TI_TEMPLATE (decl);
24543     }
24544 
24545   return decl;
24546 }
24547 
24548 /* Return the most specialized of the template partial specializations
24549    which can produce TARGET, a specialization of some class or variable
24550    template.  The value returned is actually a TREE_LIST; the TREE_VALUE is
24551    a TEMPLATE_DECL node corresponding to the partial specialization, while
24552    the TREE_PURPOSE is the set of template arguments that must be
24553    substituted into the template pattern in order to generate TARGET.
24554 
24555    If the choice of partial specialization is ambiguous, a diagnostic
24556    is issued, and the error_mark_node is returned.  If there are no
24557    partial specializations matching TARGET, then NULL_TREE is
24558    returned, indicating that the primary template should be used.  */
24559 
24560 tree
most_specialized_partial_spec(tree target,tsubst_flags_t complain)24561 most_specialized_partial_spec (tree target, tsubst_flags_t complain)
24562 {
24563   tree list = NULL_TREE;
24564   tree t;
24565   tree champ;
24566   int fate;
24567   bool ambiguous_p;
24568   tree outer_args = NULL_TREE;
24569   tree tmpl, args;
24570 
24571   if (TYPE_P (target))
24572     {
24573       tree tinfo = CLASSTYPE_TEMPLATE_INFO (target);
24574       tmpl = TI_TEMPLATE (tinfo);
24575       args = TI_ARGS (tinfo);
24576     }
24577   else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
24578     {
24579       tmpl = TREE_OPERAND (target, 0);
24580       args = TREE_OPERAND (target, 1);
24581     }
24582   else if (VAR_P (target))
24583     {
24584       tree tinfo = DECL_TEMPLATE_INFO (target);
24585       tmpl = TI_TEMPLATE (tinfo);
24586       args = TI_ARGS (tinfo);
24587     }
24588   else
24589     gcc_unreachable ();
24590 
24591   tree main_tmpl = most_general_template (tmpl);
24592 
24593   /* For determining which partial specialization to use, only the
24594      innermost args are interesting.  */
24595   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
24596     {
24597       outer_args = strip_innermost_template_args (args, 1);
24598       args = INNERMOST_TEMPLATE_ARGS (args);
24599     }
24600 
24601   /* The caller hasn't called push_to_top_level yet, but we need
24602      get_partial_spec_bindings to be done in non-template context so that we'll
24603      fully resolve everything.  */
24604   processing_template_decl_sentinel ptds;
24605 
24606   for (t = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl); t; t = TREE_CHAIN (t))
24607     {
24608       const tree ospec_tmpl = TREE_VALUE (t);
24609 
24610       tree spec_tmpl;
24611       if (outer_args)
24612 	{
24613 	  /* Substitute in the template args from the enclosing class.  */
24614 	  ++processing_template_decl;
24615 	  spec_tmpl = tsubst (ospec_tmpl, outer_args, tf_none, NULL_TREE);
24616 	  --processing_template_decl;
24617 	  if (spec_tmpl == error_mark_node)
24618 	    return error_mark_node;
24619 	}
24620       else
24621 	spec_tmpl = ospec_tmpl;
24622 
24623       tree spec_args = get_partial_spec_bindings (tmpl, spec_tmpl, args);
24624       if (spec_args)
24625 	{
24626 	  if (outer_args)
24627 	    spec_args = add_to_template_args (outer_args, spec_args);
24628 
24629           /* Keep the candidate only if the constraints are satisfied,
24630              or if we're not compiling with concepts.  */
24631           if (!flag_concepts
24632 	      || constraints_satisfied_p (ospec_tmpl, spec_args))
24633             {
24634 	      list = tree_cons (spec_args, ospec_tmpl, list);
24635               TREE_TYPE (list) = TREE_TYPE (t);
24636             }
24637 	}
24638     }
24639 
24640   if (! list)
24641     return NULL_TREE;
24642 
24643   ambiguous_p = false;
24644   t = list;
24645   champ = t;
24646   t = TREE_CHAIN (t);
24647   for (; t; t = TREE_CHAIN (t))
24648     {
24649       fate = more_specialized_partial_spec (tmpl, champ, t);
24650       if (fate == 1)
24651 	;
24652       else
24653 	{
24654 	  if (fate == 0)
24655 	    {
24656 	      t = TREE_CHAIN (t);
24657 	      if (! t)
24658 		{
24659 		  ambiguous_p = true;
24660 		  break;
24661 		}
24662 	    }
24663 	  champ = t;
24664 	}
24665     }
24666 
24667   if (!ambiguous_p)
24668     for (t = list; t && t != champ; t = TREE_CHAIN (t))
24669       {
24670 	fate = more_specialized_partial_spec (tmpl, champ, t);
24671 	if (fate != 1)
24672 	  {
24673 	    ambiguous_p = true;
24674 	    break;
24675 	  }
24676       }
24677 
24678   if (ambiguous_p)
24679     {
24680       const char *str;
24681       char *spaces = NULL;
24682       if (!(complain & tf_error))
24683 	return error_mark_node;
24684       if (TYPE_P (target))
24685 	error ("ambiguous template instantiation for %q#T", target);
24686       else
24687 	error ("ambiguous template instantiation for %q#D", target);
24688       str = ngettext ("candidate is:", "candidates are:", list_length (list));
24689       for (t = list; t; t = TREE_CHAIN (t))
24690         {
24691 	  tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
24692           inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
24693 		  "%s %#qS", spaces ? spaces : str, subst);
24694           spaces = spaces ? spaces : get_spaces (str);
24695         }
24696       free (spaces);
24697       return error_mark_node;
24698     }
24699 
24700   return champ;
24701 }
24702 
24703 /* Explicitly instantiate DECL.  */
24704 
24705 void
do_decl_instantiation(tree decl,tree storage)24706 do_decl_instantiation (tree decl, tree storage)
24707 {
24708   tree result = NULL_TREE;
24709   int extern_p = 0;
24710 
24711   if (!decl || decl == error_mark_node)
24712     /* An error occurred, for which grokdeclarator has already issued
24713        an appropriate message.  */
24714     return;
24715   else if (! DECL_LANG_SPECIFIC (decl))
24716     {
24717       error ("explicit instantiation of non-template %q#D", decl);
24718       return;
24719     }
24720   else if (DECL_DECLARED_CONCEPT_P (decl))
24721     {
24722       if (VAR_P (decl))
24723 	error ("explicit instantiation of variable concept %q#D", decl);
24724       else
24725 	error ("explicit instantiation of function concept %q#D", decl);
24726       return;
24727     }
24728 
24729   bool var_templ = (DECL_TEMPLATE_INFO (decl)
24730                     && variable_template_p (DECL_TI_TEMPLATE (decl)));
24731 
24732   if (VAR_P (decl) && !var_templ)
24733     {
24734       /* There is an asymmetry here in the way VAR_DECLs and
24735 	 FUNCTION_DECLs are handled by grokdeclarator.  In the case of
24736 	 the latter, the DECL we get back will be marked as a
24737 	 template instantiation, and the appropriate
24738 	 DECL_TEMPLATE_INFO will be set up.  This does not happen for
24739 	 VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
24740 	 should handle VAR_DECLs as it currently handles
24741 	 FUNCTION_DECLs.  */
24742       if (!DECL_CLASS_SCOPE_P (decl))
24743 	{
24744 	  error ("%qD is not a static data member of a class template", decl);
24745 	  return;
24746 	}
24747       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
24748       if (!result || !VAR_P (result))
24749 	{
24750 	  error ("no matching template for %qD found", decl);
24751 	  return;
24752 	}
24753       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
24754 	{
24755 	  error ("type %qT for explicit instantiation %qD does not match "
24756 		 "declared type %qT", TREE_TYPE (result), decl,
24757 		 TREE_TYPE (decl));
24758 	  return;
24759 	}
24760     }
24761   else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
24762     {
24763       error ("explicit instantiation of %q#D", decl);
24764       return;
24765     }
24766   else
24767     result = decl;
24768 
24769   /* Check for various error cases.  Note that if the explicit
24770      instantiation is valid the RESULT will currently be marked as an
24771      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
24772      until we get here.  */
24773 
24774   if (DECL_TEMPLATE_SPECIALIZATION (result))
24775     {
24776       /* DR 259 [temp.spec].
24777 
24778 	 Both an explicit instantiation and a declaration of an explicit
24779 	 specialization shall not appear in a program unless the explicit
24780 	 instantiation follows a declaration of the explicit specialization.
24781 
24782 	 For a given set of template parameters, if an explicit
24783 	 instantiation of a template appears after a declaration of an
24784 	 explicit specialization for that template, the explicit
24785 	 instantiation has no effect.  */
24786       return;
24787     }
24788   else if (DECL_EXPLICIT_INSTANTIATION (result))
24789     {
24790       /* [temp.spec]
24791 
24792 	 No program shall explicitly instantiate any template more
24793 	 than once.
24794 
24795 	 We check DECL_NOT_REALLY_EXTERN so as not to complain when
24796 	 the first instantiation was `extern' and the second is not,
24797 	 and EXTERN_P for the opposite case.  */
24798       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
24799 	permerror (input_location, "duplicate explicit instantiation of %q#D", result);
24800       /* If an "extern" explicit instantiation follows an ordinary
24801 	 explicit instantiation, the template is instantiated.  */
24802       if (extern_p)
24803 	return;
24804     }
24805   else if (!DECL_IMPLICIT_INSTANTIATION (result))
24806     {
24807       error ("no matching template for %qD found", result);
24808       return;
24809     }
24810   else if (!DECL_TEMPLATE_INFO (result))
24811     {
24812       permerror (input_location, "explicit instantiation of non-template %q#D", result);
24813       return;
24814     }
24815 
24816   if (storage == NULL_TREE)
24817     ;
24818   else if (storage == ridpointers[(int) RID_EXTERN])
24819     {
24820       if (cxx_dialect == cxx98)
24821 	pedwarn (input_location, OPT_Wpedantic,
24822 		 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
24823 		 "instantiations");
24824       extern_p = 1;
24825     }
24826   else
24827     error ("storage class %qD applied to template instantiation", storage);
24828 
24829   check_explicit_instantiation_namespace (result);
24830   mark_decl_instantiated (result, extern_p);
24831   if (! extern_p)
24832     instantiate_decl (result, /*defer_ok=*/true,
24833 		      /*expl_inst_class_mem_p=*/false);
24834 }
24835 
24836 static void
mark_class_instantiated(tree t,int extern_p)24837 mark_class_instantiated (tree t, int extern_p)
24838 {
24839   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
24840   SET_CLASSTYPE_INTERFACE_KNOWN (t);
24841   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
24842   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
24843   if (! extern_p)
24844     {
24845       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
24846       rest_of_type_compilation (t, 1);
24847     }
24848 }
24849 
24850 /* Called from do_type_instantiation through binding_table_foreach to
24851    do recursive instantiation for the type bound in ENTRY.  */
24852 static void
bt_instantiate_type_proc(binding_entry entry,void * data)24853 bt_instantiate_type_proc (binding_entry entry, void *data)
24854 {
24855   tree storage = *(tree *) data;
24856 
24857   if (MAYBE_CLASS_TYPE_P (entry->type)
24858       && CLASSTYPE_TEMPLATE_INFO (entry->type)
24859       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
24860     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
24861 }
24862 
24863 /* Perform an explicit instantiation of template class T.  STORAGE, if
24864    non-null, is the RID for extern, inline or static.  COMPLAIN is
24865    nonzero if this is called from the parser, zero if called recursively,
24866    since the standard is unclear (as detailed below).  */
24867 
24868 void
do_type_instantiation(tree t,tree storage,tsubst_flags_t complain)24869 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
24870 {
24871   int extern_p = 0;
24872   int nomem_p = 0;
24873   int static_p = 0;
24874   int previous_instantiation_extern_p = 0;
24875 
24876   if (TREE_CODE (t) == TYPE_DECL)
24877     t = TREE_TYPE (t);
24878 
24879   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
24880     {
24881       tree tmpl =
24882 	(TYPE_TEMPLATE_INFO (t)) ? TYPE_TI_TEMPLATE (t) : NULL;
24883       if (tmpl)
24884 	error ("explicit instantiation of non-class template %qD", tmpl);
24885       else
24886 	error ("explicit instantiation of non-template type %qT", t);
24887       return;
24888     }
24889 
24890   complete_type (t);
24891 
24892   if (!COMPLETE_TYPE_P (t))
24893     {
24894       if (complain & tf_error)
24895 	error ("explicit instantiation of %q#T before definition of template",
24896 	       t);
24897       return;
24898     }
24899 
24900   if (storage != NULL_TREE)
24901     {
24902       if (storage == ridpointers[(int) RID_EXTERN])
24903 	{
24904 	  if (cxx_dialect == cxx98)
24905 	    pedwarn (input_location, OPT_Wpedantic,
24906 		     "ISO C++ 1998 forbids the use of %<extern%> on "
24907 		     "explicit instantiations");
24908 	}
24909       else
24910 	pedwarn (input_location, OPT_Wpedantic,
24911 		 "ISO C++ forbids the use of %qE"
24912 		 " on explicit instantiations", storage);
24913 
24914       if (storage == ridpointers[(int) RID_INLINE])
24915 	nomem_p = 1;
24916       else if (storage == ridpointers[(int) RID_EXTERN])
24917 	extern_p = 1;
24918       else if (storage == ridpointers[(int) RID_STATIC])
24919 	static_p = 1;
24920       else
24921 	{
24922 	  error ("storage class %qD applied to template instantiation",
24923 		 storage);
24924 	  extern_p = 0;
24925 	}
24926     }
24927 
24928   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
24929     {
24930       /* DR 259 [temp.spec].
24931 
24932 	 Both an explicit instantiation and a declaration of an explicit
24933 	 specialization shall not appear in a program unless the explicit
24934 	 instantiation follows a declaration of the explicit specialization.
24935 
24936 	 For a given set of template parameters, if an explicit
24937 	 instantiation of a template appears after a declaration of an
24938 	 explicit specialization for that template, the explicit
24939 	 instantiation has no effect.  */
24940       return;
24941     }
24942   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
24943     {
24944       /* [temp.spec]
24945 
24946 	 No program shall explicitly instantiate any template more
24947 	 than once.
24948 
24949 	 If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
24950 	 instantiation was `extern'.  If EXTERN_P then the second is.
24951 	 These cases are OK.  */
24952       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
24953 
24954       if (!previous_instantiation_extern_p && !extern_p
24955 	  && (complain & tf_error))
24956 	permerror (input_location, "duplicate explicit instantiation of %q#T", t);
24957 
24958       /* If we've already instantiated the template, just return now.  */
24959       if (!CLASSTYPE_INTERFACE_ONLY (t))
24960 	return;
24961     }
24962 
24963   check_explicit_instantiation_namespace (TYPE_NAME (t));
24964   mark_class_instantiated (t, extern_p);
24965 
24966   if (nomem_p)
24967     return;
24968 
24969   /* In contrast to implicit instantiation, where only the
24970      declarations, and not the definitions, of members are
24971      instantiated, we have here:
24972 
24973 	 [temp.explicit]
24974 
24975 	 The explicit instantiation of a class template specialization
24976 	 implies the instantiation of all of its members not
24977 	 previously explicitly specialized in the translation unit
24978 	 containing the explicit instantiation.
24979 
24980      Of course, we can't instantiate member template classes, since we
24981      don't have any arguments for them.  Note that the standard is
24982      unclear on whether the instantiation of the members are
24983      *explicit* instantiations or not.  However, the most natural
24984      interpretation is that it should be an explicit
24985      instantiation.  */
24986   for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
24987     if ((VAR_P (fld)
24988 	 || (TREE_CODE (fld) == FUNCTION_DECL
24989 	     && !static_p
24990 	     && user_provided_p (fld)))
24991 	&& DECL_TEMPLATE_INSTANTIATION (fld))
24992       {
24993 	mark_decl_instantiated (fld, extern_p);
24994 	if (! extern_p)
24995 	  instantiate_decl (fld, /*defer_ok=*/true,
24996 			    /*expl_inst_class_mem_p=*/true);
24997       }
24998 
24999   if (CLASSTYPE_NESTED_UTDS (t))
25000     binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
25001 			   bt_instantiate_type_proc, &storage);
25002 }
25003 
25004 /* Given a function DECL, which is a specialization of TMPL, modify
25005    DECL to be a re-instantiation of TMPL with the same template
25006    arguments.  TMPL should be the template into which tsubst'ing
25007    should occur for DECL, not the most general template.
25008 
25009    One reason for doing this is a scenario like this:
25010 
25011      template <class T>
25012      void f(const T&, int i);
25013 
25014      void g() { f(3, 7); }
25015 
25016      template <class T>
25017      void f(const T& t, const int i) { }
25018 
25019    Note that when the template is first instantiated, with
25020    instantiate_template, the resulting DECL will have no name for the
25021    first parameter, and the wrong type for the second.  So, when we go
25022    to instantiate the DECL, we regenerate it.  */
25023 
25024 static void
regenerate_decl_from_template(tree decl,tree tmpl,tree args)25025 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
25026 {
25027   /* The arguments used to instantiate DECL, from the most general
25028      template.  */
25029   tree code_pattern;
25030 
25031   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
25032 
25033   /* Make sure that we can see identifiers, and compute access
25034      correctly.  */
25035   push_access_scope (decl);
25036 
25037   if (TREE_CODE (decl) == FUNCTION_DECL)
25038     {
25039       tree decl_parm;
25040       tree pattern_parm;
25041       tree specs;
25042       int args_depth;
25043       int parms_depth;
25044 
25045       args_depth = TMPL_ARGS_DEPTH (args);
25046       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
25047       if (args_depth > parms_depth)
25048 	args = get_innermost_template_args (args, parms_depth);
25049 
25050       /* Instantiate a dynamic exception-specification.  noexcept will be
25051 	 handled below.  */
25052       if (tree raises = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (code_pattern)))
25053 	if (TREE_VALUE (raises))
25054 	  {
25055 	    specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
25056 						    args, tf_error, NULL_TREE,
25057 						    /*defer_ok*/false);
25058 	    if (specs && specs != error_mark_node)
25059 	      TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
25060 							  specs);
25061 	  }
25062 
25063       /* Merge parameter declarations.  */
25064       decl_parm = skip_artificial_parms_for (decl,
25065 					     DECL_ARGUMENTS (decl));
25066       pattern_parm
25067 	= skip_artificial_parms_for (code_pattern,
25068 				     DECL_ARGUMENTS (code_pattern));
25069       while (decl_parm && !DECL_PACK_P (pattern_parm))
25070 	{
25071 	  tree parm_type;
25072 	  tree attributes;
25073 
25074 	  if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
25075 	    DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
25076 	  parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
25077 			      NULL_TREE);
25078 	  parm_type = type_decays_to (parm_type);
25079 	  if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
25080 	    TREE_TYPE (decl_parm) = parm_type;
25081 	  attributes = DECL_ATTRIBUTES (pattern_parm);
25082 	  if (DECL_ATTRIBUTES (decl_parm) != attributes)
25083 	    {
25084 	      DECL_ATTRIBUTES (decl_parm) = attributes;
25085 	      cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
25086 	    }
25087 	  decl_parm = DECL_CHAIN (decl_parm);
25088 	  pattern_parm = DECL_CHAIN (pattern_parm);
25089 	}
25090       /* Merge any parameters that match with the function parameter
25091          pack.  */
25092       if (pattern_parm && DECL_PACK_P (pattern_parm))
25093         {
25094           int i, len;
25095           tree expanded_types;
25096           /* Expand the TYPE_PACK_EXPANSION that provides the types for
25097              the parameters in this function parameter pack.  */
25098           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm),
25099                                                  args, tf_error, NULL_TREE);
25100           len = TREE_VEC_LENGTH (expanded_types);
25101           for (i = 0; i < len; i++)
25102             {
25103               tree parm_type;
25104               tree attributes;
25105 
25106               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
25107                 /* Rename the parameter to include the index.  */
25108                 DECL_NAME (decl_parm) =
25109                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
25110               parm_type = TREE_VEC_ELT (expanded_types, i);
25111               parm_type = type_decays_to (parm_type);
25112               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
25113                 TREE_TYPE (decl_parm) = parm_type;
25114               attributes = DECL_ATTRIBUTES (pattern_parm);
25115               if (DECL_ATTRIBUTES (decl_parm) != attributes)
25116                 {
25117                   DECL_ATTRIBUTES (decl_parm) = attributes;
25118                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
25119                 }
25120               decl_parm = DECL_CHAIN (decl_parm);
25121             }
25122         }
25123       /* Merge additional specifiers from the CODE_PATTERN.  */
25124       if (DECL_DECLARED_INLINE_P (code_pattern)
25125 	  && !DECL_DECLARED_INLINE_P (decl))
25126 	DECL_DECLARED_INLINE_P (decl) = 1;
25127 
25128       maybe_instantiate_noexcept (decl, tf_error);
25129     }
25130   else if (VAR_P (decl))
25131     {
25132       start_lambda_scope (decl);
25133       DECL_INITIAL (decl) =
25134 	tsubst_init (DECL_INITIAL (code_pattern), decl, args,
25135 		     tf_error, DECL_TI_TEMPLATE (decl));
25136       finish_lambda_scope ();
25137       if (VAR_HAD_UNKNOWN_BOUND (decl))
25138 	TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
25139 				   tf_error, DECL_TI_TEMPLATE (decl));
25140     }
25141   else
25142     gcc_unreachable ();
25143 
25144   pop_access_scope (decl);
25145 }
25146 
25147 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
25148    substituted to get DECL.  */
25149 
25150 tree
template_for_substitution(tree decl)25151 template_for_substitution (tree decl)
25152 {
25153   tree tmpl = DECL_TI_TEMPLATE (decl);
25154 
25155   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
25156      for the instantiation.  This is not always the most general
25157      template.  Consider, for example:
25158 
25159 	template <class T>
25160 	struct S { template <class U> void f();
25161 		   template <> void f<int>(); };
25162 
25163      and an instantiation of S<double>::f<int>.  We want TD to be the
25164      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
25165   while (/* An instantiation cannot have a definition, so we need a
25166 	    more general template.  */
25167 	 DECL_TEMPLATE_INSTANTIATION (tmpl)
25168 	   /* We must also deal with friend templates.  Given:
25169 
25170 		template <class T> struct S {
25171 		  template <class U> friend void f() {};
25172 		};
25173 
25174 	      S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
25175 	      so far as the language is concerned, but that's still
25176 	      where we get the pattern for the instantiation from.  On
25177 	      other hand, if the definition comes outside the class, say:
25178 
25179 		template <class T> struct S {
25180 		  template <class U> friend void f();
25181 		};
25182 		template <class U> friend void f() {}
25183 
25184 	      we don't need to look any further.  That's what the check for
25185 	      DECL_INITIAL is for.  */
25186 	  || (TREE_CODE (decl) == FUNCTION_DECL
25187 	      && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
25188 	      && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
25189     {
25190       /* The present template, TD, should not be a definition.  If it
25191 	 were a definition, we should be using it!  Note that we
25192 	 cannot restructure the loop to just keep going until we find
25193 	 a template with a definition, since that might go too far if
25194 	 a specialization was declared, but not defined.  */
25195 
25196       /* Fetch the more general template.  */
25197       tmpl = DECL_TI_TEMPLATE (tmpl);
25198     }
25199 
25200   return tmpl;
25201 }
25202 
25203 /* Returns true if we need to instantiate this template instance even if we
25204    know we aren't going to emit it.  */
25205 
25206 bool
always_instantiate_p(tree decl)25207 always_instantiate_p (tree decl)
25208 {
25209   /* We always instantiate inline functions so that we can inline them.  An
25210      explicit instantiation declaration prohibits implicit instantiation of
25211      non-inline functions.  With high levels of optimization, we would
25212      normally inline non-inline functions -- but we're not allowed to do
25213      that for "extern template" functions.  Therefore, we check
25214      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
25215   return ((TREE_CODE (decl) == FUNCTION_DECL
25216 	   && (DECL_DECLARED_INLINE_P (decl)
25217 	       || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
25218 	  /* And we need to instantiate static data members so that
25219 	     their initializers are available in integral constant
25220 	     expressions.  */
25221 	  || (VAR_P (decl)
25222 	      && decl_maybe_constant_var_p (decl)));
25223 }
25224 
25225 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
25226    instantiate it now, modifying TREE_TYPE (fn).  Returns false on
25227    error, true otherwise.  */
25228 
25229 bool
maybe_instantiate_noexcept(tree fn,tsubst_flags_t complain)25230 maybe_instantiate_noexcept (tree fn, tsubst_flags_t complain)
25231 {
25232   tree fntype, spec, noex, clone;
25233 
25234   /* Don't instantiate a noexcept-specification from template context.  */
25235   if (processing_template_decl
25236       && (!flag_noexcept_type || type_dependent_expression_p (fn)))
25237     return true;
25238 
25239   if (DECL_MAYBE_DELETED (fn))
25240     {
25241       if (fn == current_function_decl)
25242 	/* We're in start_preparsed_function, keep going.  */
25243 	return true;
25244 
25245       ++function_depth;
25246       synthesize_method (fn);
25247       --function_depth;
25248       return !DECL_MAYBE_DELETED (fn);
25249     }
25250 
25251   if (DECL_CLONED_FUNCTION_P (fn))
25252     fn = DECL_CLONED_FUNCTION (fn);
25253 
25254   tree orig_fn = NULL_TREE;
25255   /* For a member friend template we can get a TEMPLATE_DECL.  Let's use
25256      its FUNCTION_DECL for the rest of this function -- push_access_scope
25257      doesn't accept TEMPLATE_DECLs.  */
25258   if (DECL_FUNCTION_TEMPLATE_P (fn))
25259     {
25260       orig_fn = fn;
25261       fn = DECL_TEMPLATE_RESULT (fn);
25262     }
25263 
25264   fntype = TREE_TYPE (fn);
25265   spec = TYPE_RAISES_EXCEPTIONS (fntype);
25266 
25267   if (!spec || !TREE_PURPOSE (spec))
25268     return true;
25269 
25270   noex = TREE_PURPOSE (spec);
25271 
25272   if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
25273     {
25274       static hash_set<tree>* fns = new hash_set<tree>;
25275       bool added = false;
25276       if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
25277 	{
25278 	  spec = get_defaulted_eh_spec (fn, complain);
25279 	  if (spec == error_mark_node)
25280 	    /* This might have failed because of an unparsed DMI, so
25281 	       let's try again later.  */
25282 	    return false;
25283 	}
25284       else if (!(added = !fns->add (fn)))
25285 	{
25286 	  /* If hash_set::add returns true, the element was already there.  */
25287 	  location_t loc = cp_expr_loc_or_loc (DEFERRED_NOEXCEPT_PATTERN (noex),
25288 					    DECL_SOURCE_LOCATION (fn));
25289 	  error_at (loc,
25290 		    "exception specification of %qD depends on itself",
25291 		    fn);
25292 	  spec = noexcept_false_spec;
25293 	}
25294       else if (push_tinst_level (fn))
25295 	{
25296 	  push_to_top_level ();
25297 	  push_access_scope (fn);
25298 	  push_deferring_access_checks (dk_no_deferred);
25299 	  input_location = DECL_SOURCE_LOCATION (fn);
25300 
25301 	  /* If needed, set current_class_ptr for the benefit of
25302 	     tsubst_copy/PARM_DECL.  */
25303 	  tree tdecl = DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (fn));
25304 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (tdecl))
25305 	    {
25306 	      tree this_parm = DECL_ARGUMENTS (tdecl);
25307 	      current_class_ptr = NULL_TREE;
25308 	      current_class_ref = cp_build_fold_indirect_ref (this_parm);
25309 	      current_class_ptr = this_parm;
25310 	    }
25311 
25312 	  /* If this function is represented by a TEMPLATE_DECL, then
25313 	     the deferred noexcept-specification might still contain
25314 	     dependent types, even after substitution.  And we need the
25315 	     dependency check functions to work in build_noexcept_spec.  */
25316 	  if (orig_fn)
25317 	    ++processing_template_decl;
25318 
25319 	  /* Do deferred instantiation of the noexcept-specifier.  */
25320 	  noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
25321 					DEFERRED_NOEXCEPT_ARGS (noex),
25322 					tf_warning_or_error, fn,
25323 					/*function_p=*/false,
25324 					/*i_c_e_p=*/true);
25325 
25326 	  /* Build up the noexcept-specification.  */
25327 	  spec = build_noexcept_spec (noex, tf_warning_or_error);
25328 
25329 	  if (orig_fn)
25330 	    --processing_template_decl;
25331 
25332 	  pop_deferring_access_checks ();
25333 	  pop_access_scope (fn);
25334 	  pop_tinst_level ();
25335 	  pop_from_top_level ();
25336 	}
25337       else
25338 	spec = noexcept_false_spec;
25339 
25340       if (added)
25341 	fns->remove (fn);
25342 
25343       if (spec == error_mark_node)
25344 	{
25345 	  /* This failed with a hard error, so let's go with false.  */
25346 	  gcc_assert (seen_error ());
25347 	  spec = noexcept_false_spec;
25348 	}
25349 
25350       TREE_TYPE (fn) = build_exception_variant (fntype, spec);
25351       if (orig_fn)
25352 	TREE_TYPE (orig_fn) = TREE_TYPE (fn);
25353     }
25354 
25355   FOR_EACH_CLONE (clone, fn)
25356     {
25357       if (TREE_TYPE (clone) == fntype)
25358 	TREE_TYPE (clone) = TREE_TYPE (fn);
25359       else
25360 	TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone), spec);
25361     }
25362 
25363   return true;
25364 }
25365 
25366 /* We're starting to process the function INST, an instantiation of PATTERN;
25367    add their parameters to local_specializations.  */
25368 
25369 static void
register_parameter_specializations(tree pattern,tree inst)25370 register_parameter_specializations (tree pattern, tree inst)
25371 {
25372   tree tmpl_parm = DECL_ARGUMENTS (pattern);
25373   tree spec_parm = DECL_ARGUMENTS (inst);
25374   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (inst))
25375     {
25376       register_local_specialization (spec_parm, tmpl_parm);
25377       spec_parm = skip_artificial_parms_for (inst, spec_parm);
25378       tmpl_parm = skip_artificial_parms_for (pattern, tmpl_parm);
25379     }
25380   for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
25381     {
25382       if (!DECL_PACK_P (tmpl_parm)
25383 	  || (spec_parm && DECL_PACK_P (spec_parm)))
25384 	{
25385 	  register_local_specialization (spec_parm, tmpl_parm);
25386 	  spec_parm = DECL_CHAIN (spec_parm);
25387 	}
25388       else
25389 	{
25390 	  /* Register the (value) argument pack as a specialization of
25391 	     TMPL_PARM, then move on.  */
25392 	  tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
25393 	  register_local_specialization (argpack, tmpl_parm);
25394 	}
25395     }
25396   gcc_assert (!spec_parm);
25397 }
25398 
25399 /* Produce the definition of D, a _DECL generated from a template.  If
25400    DEFER_OK is true, then we don't have to actually do the
25401    instantiation now; we just have to do it sometime.  Normally it is
25402    an error if this is an explicit instantiation but D is undefined.
25403    EXPL_INST_CLASS_MEM_P is true iff D is a member of an explicitly
25404    instantiated class template.  */
25405 
25406 tree
instantiate_decl(tree d,bool defer_ok,bool expl_inst_class_mem_p)25407 instantiate_decl (tree d, bool defer_ok, bool expl_inst_class_mem_p)
25408 {
25409   tree tmpl = DECL_TI_TEMPLATE (d);
25410   tree gen_args;
25411   tree args;
25412   tree td;
25413   tree code_pattern;
25414   tree spec;
25415   tree gen_tmpl;
25416   bool pattern_defined;
25417   location_t saved_loc = input_location;
25418   int saved_unevaluated_operand = cp_unevaluated_operand;
25419   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
25420   bool external_p;
25421   bool deleted_p;
25422 
25423   /* This function should only be used to instantiate templates for
25424      functions and static member variables.  */
25425   gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
25426 
25427   /* A concept is never instantiated. */
25428   gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
25429 
25430   /* Variables are never deferred; if instantiation is required, they
25431      are instantiated right away.  That allows for better code in the
25432      case that an expression refers to the value of the variable --
25433      if the variable has a constant value the referring expression can
25434      take advantage of that fact.  */
25435   if (VAR_P (d))
25436     defer_ok = false;
25437 
25438   /* Don't instantiate cloned functions.  Instead, instantiate the
25439      functions they cloned.  */
25440   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
25441     d = DECL_CLONED_FUNCTION (d);
25442 
25443   if (DECL_TEMPLATE_INSTANTIATED (d)
25444       || (TREE_CODE (d) == FUNCTION_DECL
25445 	  && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
25446       || DECL_TEMPLATE_SPECIALIZATION (d))
25447     /* D has already been instantiated or explicitly specialized, so
25448        there's nothing for us to do here.
25449 
25450        It might seem reasonable to check whether or not D is an explicit
25451        instantiation, and, if so, stop here.  But when an explicit
25452        instantiation is deferred until the end of the compilation,
25453        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
25454        the instantiation.  */
25455     return d;
25456 
25457   /* Check to see whether we know that this template will be
25458      instantiated in some other file, as with "extern template"
25459      extension.  */
25460   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
25461 
25462   /* In general, we do not instantiate such templates.  */
25463   if (external_p && !always_instantiate_p (d))
25464     return d;
25465 
25466   gen_tmpl = most_general_template (tmpl);
25467   gen_args = DECL_TI_ARGS (d);
25468 
25469   if (tmpl != gen_tmpl)
25470     /* We should already have the extra args.  */
25471     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
25472 		== TMPL_ARGS_DEPTH (gen_args));
25473   /* And what's in the hash table should match D.  */
25474   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
25475 	      || spec == NULL_TREE);
25476 
25477   /* This needs to happen before any tsubsting.  */
25478   if (! push_tinst_level (d))
25479     return d;
25480 
25481   timevar_push (TV_TEMPLATE_INST);
25482 
25483   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
25484      for the instantiation.  */
25485   td = template_for_substitution (d);
25486   args = gen_args;
25487 
25488   if (VAR_P (d))
25489     {
25490       /* Look up an explicit specialization, if any.  */
25491       tree tid = lookup_template_variable (gen_tmpl, gen_args);
25492       tree elt = most_specialized_partial_spec (tid, tf_warning_or_error);
25493       if (elt && elt != error_mark_node)
25494 	{
25495 	  td = TREE_VALUE (elt);
25496 	  args = TREE_PURPOSE (elt);
25497 	}
25498     }
25499 
25500   code_pattern = DECL_TEMPLATE_RESULT (td);
25501 
25502   /* We should never be trying to instantiate a member of a class
25503      template or partial specialization.  */
25504   gcc_assert (d != code_pattern);
25505 
25506   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
25507       || DECL_TEMPLATE_SPECIALIZATION (td))
25508     /* In the case of a friend template whose definition is provided
25509        outside the class, we may have too many arguments.  Drop the
25510        ones we don't need.  The same is true for specializations.  */
25511     args = get_innermost_template_args
25512       (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
25513 
25514   if (TREE_CODE (d) == FUNCTION_DECL)
25515     {
25516       deleted_p = DECL_DELETED_FN (code_pattern);
25517       pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
25518 			  && DECL_INITIAL (code_pattern) != error_mark_node)
25519 			 || DECL_DEFAULTED_FN (code_pattern)
25520 			 || deleted_p);
25521     }
25522   else
25523     {
25524       deleted_p = false;
25525       if (DECL_CLASS_SCOPE_P (code_pattern))
25526 	pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
25527       else
25528 	pattern_defined = ! DECL_EXTERNAL (code_pattern);
25529     }
25530 
25531   /* We may be in the middle of deferred access check.  Disable it now.  */
25532   push_deferring_access_checks (dk_no_deferred);
25533 
25534   /* Unless an explicit instantiation directive has already determined
25535      the linkage of D, remember that a definition is available for
25536      this entity.  */
25537   if (pattern_defined
25538       && !DECL_INTERFACE_KNOWN (d)
25539       && !DECL_NOT_REALLY_EXTERN (d))
25540     mark_definable (d);
25541 
25542   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
25543   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
25544   input_location = DECL_SOURCE_LOCATION (d);
25545 
25546   /* If D is a member of an explicitly instantiated class template,
25547      and no definition is available, treat it like an implicit
25548      instantiation.  */
25549   if (!pattern_defined && expl_inst_class_mem_p
25550       && DECL_EXPLICIT_INSTANTIATION (d))
25551     {
25552       /* Leave linkage flags alone on instantiations with anonymous
25553 	 visibility.  */
25554       if (TREE_PUBLIC (d))
25555 	{
25556 	  DECL_NOT_REALLY_EXTERN (d) = 0;
25557 	  DECL_INTERFACE_KNOWN (d) = 0;
25558 	}
25559       SET_DECL_IMPLICIT_INSTANTIATION (d);
25560     }
25561 
25562   /* Defer all other templates, unless we have been explicitly
25563      forbidden from doing so.  */
25564   if (/* If there is no definition, we cannot instantiate the
25565 	 template.  */
25566       ! pattern_defined
25567       /* If it's OK to postpone instantiation, do so.  */
25568       || defer_ok
25569       /* If this is a static data member that will be defined
25570 	 elsewhere, we don't want to instantiate the entire data
25571 	 member, but we do want to instantiate the initializer so that
25572 	 we can substitute that elsewhere.  */
25573       || (external_p && VAR_P (d))
25574       /* Handle here a deleted function too, avoid generating
25575 	 its body (c++/61080).  */
25576       || deleted_p)
25577     {
25578       /* The definition of the static data member is now required so
25579 	 we must substitute the initializer.  */
25580       if (VAR_P (d)
25581 	  && !DECL_INITIAL (d)
25582 	  && DECL_INITIAL (code_pattern))
25583 	{
25584 	  tree ns;
25585 	  tree init;
25586 	  bool const_init = false;
25587 	  bool enter_context = DECL_CLASS_SCOPE_P (d);
25588 
25589 	  ns = decl_namespace_context (d);
25590 	  push_nested_namespace (ns);
25591 	  if (enter_context)
25592 	    push_nested_class (DECL_CONTEXT (d));
25593 	  init = tsubst_expr (DECL_INITIAL (code_pattern),
25594 			      args,
25595 			      tf_warning_or_error, NULL_TREE,
25596 			      /*integral_constant_expression_p=*/false);
25597 	  /* If instantiating the initializer involved instantiating this
25598 	     again, don't call cp_finish_decl twice.  */
25599 	  if (!DECL_INITIAL (d))
25600 	    {
25601 	      /* Make sure the initializer is still constant, in case of
25602 		 circular dependency (template/instantiate6.C). */
25603 	      const_init
25604 		= DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
25605 	      cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
25606 			      /*asmspec_tree=*/NULL_TREE,
25607 			      LOOKUP_ONLYCONVERTING);
25608 	    }
25609 	  if (enter_context)
25610 	    pop_nested_class ();
25611 	  pop_nested_namespace (ns);
25612 	}
25613 
25614       /* We restore the source position here because it's used by
25615 	 add_pending_template.  */
25616       input_location = saved_loc;
25617 
25618       if (at_eof && !pattern_defined
25619 	  && DECL_EXPLICIT_INSTANTIATION (d)
25620 	  && DECL_NOT_REALLY_EXTERN (d))
25621 	/* [temp.explicit]
25622 
25623 	   The definition of a non-exported function template, a
25624 	   non-exported member function template, or a non-exported
25625 	   member function or static data member of a class template
25626 	   shall be present in every translation unit in which it is
25627 	   explicitly instantiated.  */
25628 	permerror (input_location,  "explicit instantiation of %qD "
25629 		   "but no definition available", d);
25630 
25631       /* If we're in unevaluated context, we just wanted to get the
25632 	 constant value; this isn't an odr use, so don't queue
25633 	 a full instantiation.  */
25634       if (cp_unevaluated_operand != 0)
25635 	goto out;
25636       /* ??? Historically, we have instantiated inline functions, even
25637 	 when marked as "extern template".  */
25638       if (!(external_p && VAR_P (d)))
25639 	add_pending_template (d);
25640       goto out;
25641     }
25642 
25643   bool push_to_top, nested;
25644   tree fn_context;
25645   fn_context = decl_function_context (d);
25646   if (LAMBDA_FUNCTION_P (d))
25647     /* tsubst_lambda_expr resolved any references to enclosing functions.  */
25648     fn_context = NULL_TREE;
25649   nested = current_function_decl != NULL_TREE;
25650   push_to_top = !(nested && fn_context == current_function_decl);
25651 
25652   vec<tree> omp_privatization_save;
25653   if (nested)
25654     save_omp_privatization_clauses (omp_privatization_save);
25655 
25656   if (push_to_top)
25657     push_to_top_level ();
25658   else
25659     {
25660       gcc_assert (!processing_template_decl);
25661       push_function_context ();
25662       cp_unevaluated_operand = 0;
25663       c_inhibit_evaluation_warnings = 0;
25664     }
25665 
25666   if (VAR_P (d))
25667     {
25668       /* The variable might be a lambda's extra scope, and that
25669 	 lambda's visibility depends on D's.  */
25670       maybe_commonize_var (d);
25671       determine_visibility (d);
25672     }
25673 
25674   /* Mark D as instantiated so that recursive calls to
25675      instantiate_decl do not try to instantiate it again.  */
25676   DECL_TEMPLATE_INSTANTIATED (d) = 1;
25677 
25678   /* Regenerate the declaration in case the template has been modified
25679      by a subsequent redeclaration.  */
25680   regenerate_decl_from_template (d, td, args);
25681 
25682   /* We already set the file and line above.  Reset them now in case
25683      they changed as a result of calling regenerate_decl_from_template.  */
25684   input_location = DECL_SOURCE_LOCATION (d);
25685 
25686   if (VAR_P (d))
25687     {
25688       tree init;
25689       bool const_init = false;
25690 
25691       /* Clear out DECL_RTL; whatever was there before may not be right
25692 	 since we've reset the type of the declaration.  */
25693       SET_DECL_RTL (d, NULL);
25694       DECL_IN_AGGR_P (d) = 0;
25695 
25696       /* The initializer is placed in DECL_INITIAL by
25697 	 regenerate_decl_from_template so we don't need to
25698 	 push/pop_access_scope again here.  Pull it out so that
25699 	 cp_finish_decl can process it.  */
25700       init = DECL_INITIAL (d);
25701       DECL_INITIAL (d) = NULL_TREE;
25702       DECL_INITIALIZED_P (d) = 0;
25703 
25704       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
25705 	 initializer.  That function will defer actual emission until
25706 	 we have a chance to determine linkage.  */
25707       DECL_EXTERNAL (d) = 0;
25708 
25709       /* Enter the scope of D so that access-checking works correctly.  */
25710       bool enter_context = DECL_CLASS_SCOPE_P (d);
25711       if (enter_context)
25712         push_nested_class (DECL_CONTEXT (d));
25713 
25714       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
25715       int flags = (TINFO_VAR_DECLARED_CONSTINIT (DECL_TEMPLATE_INFO (d))
25716 		   ? LOOKUP_CONSTINIT : 0);
25717       cp_finish_decl (d, init, const_init, NULL_TREE, flags);
25718 
25719       if (enter_context)
25720         pop_nested_class ();
25721 
25722       if (variable_template_p (gen_tmpl))
25723 	note_variable_template_instantiation (d);
25724     }
25725   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
25726     synthesize_method (d);
25727   else if (TREE_CODE (d) == FUNCTION_DECL)
25728     {
25729       /* Set up the list of local specializations.  */
25730       local_specialization_stack lss (push_to_top ? lss_blank : lss_copy);
25731       tree block = NULL_TREE;
25732 
25733       /* Set up context.  */
25734       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
25735 	  && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
25736 	block = push_stmt_list ();
25737       else
25738 	start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
25739 
25740       /* Some typedefs referenced from within the template code need to be
25741 	 access checked at template instantiation time, i.e now. These
25742 	 types were added to the template at parsing time. Let's get those
25743 	 and perform the access checks then.  */
25744       perform_typedefs_access_check (DECL_TEMPLATE_RESULT (td),
25745 				     args);
25746 
25747       /* Create substitution entries for the parameters.  */
25748       register_parameter_specializations (code_pattern, d);
25749 
25750       /* Substitute into the body of the function.  */
25751       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
25752 	tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
25753 			tf_warning_or_error, tmpl);
25754       else
25755 	{
25756 	  tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
25757 		       tf_warning_or_error, tmpl,
25758 		       /*integral_constant_expression_p=*/false);
25759 
25760 	  /* Set the current input_location to the end of the function
25761 	     so that finish_function knows where we are.  */
25762 	  input_location
25763 	    = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
25764 
25765 	  /* Remember if we saw an infinite loop in the template.  */
25766 	  current_function_infinite_loop
25767 	    = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
25768 	}
25769 
25770       /* Finish the function.  */
25771       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
25772 	  && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
25773 	DECL_SAVED_TREE (d) = pop_stmt_list (block);
25774       else
25775 	{
25776 	  d = finish_function (/*inline_p=*/false);
25777 	  expand_or_defer_fn (d);
25778 	}
25779 
25780       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
25781 	cp_check_omp_declare_reduction (d);
25782     }
25783 
25784   /* We're not deferring instantiation any more.  */
25785   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
25786 
25787   if (push_to_top)
25788     pop_from_top_level ();
25789   else
25790     pop_function_context ();
25791 
25792   if (nested)
25793     restore_omp_privatization_clauses (omp_privatization_save);
25794 
25795 out:
25796   pop_deferring_access_checks ();
25797   timevar_pop (TV_TEMPLATE_INST);
25798   pop_tinst_level ();
25799   input_location = saved_loc;
25800   cp_unevaluated_operand = saved_unevaluated_operand;
25801   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
25802 
25803   return d;
25804 }
25805 
25806 /* Run through the list of templates that we wish we could
25807    instantiate, and instantiate any we can.  RETRIES is the
25808    number of times we retry pending template instantiation.  */
25809 
25810 void
instantiate_pending_templates(int retries)25811 instantiate_pending_templates (int retries)
25812 {
25813   int reconsider;
25814   location_t saved_loc = input_location;
25815 
25816   /* Instantiating templates may trigger vtable generation.  This in turn
25817      may require further template instantiations.  We place a limit here
25818      to avoid infinite loop.  */
25819   if (pending_templates && retries >= max_tinst_depth)
25820     {
25821       tree decl = pending_templates->tinst->maybe_get_node ();
25822 
25823       fatal_error (input_location,
25824 		   "template instantiation depth exceeds maximum of %d"
25825 		   " instantiating %q+D, possibly from virtual table generation"
25826 		   " (use %<-ftemplate-depth=%> to increase the maximum)",
25827 		   max_tinst_depth, decl);
25828       if (TREE_CODE (decl) == FUNCTION_DECL)
25829 	/* Pretend that we defined it.  */
25830 	DECL_INITIAL (decl) = error_mark_node;
25831       return;
25832     }
25833 
25834   do
25835     {
25836       struct pending_template **t = &pending_templates;
25837       struct pending_template *last = NULL;
25838       reconsider = 0;
25839       while (*t)
25840 	{
25841 	  tree instantiation = reopen_tinst_level ((*t)->tinst);
25842 	  bool complete = false;
25843 
25844 	  if (TYPE_P (instantiation))
25845 	    {
25846 	      if (!COMPLETE_TYPE_P (instantiation))
25847 		{
25848 		  instantiate_class_template (instantiation);
25849 		  if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
25850 		    for (tree fld = TYPE_FIELDS (instantiation);
25851 			 fld; fld = TREE_CHAIN (fld))
25852 		      if ((VAR_P (fld)
25853 			   || (TREE_CODE (fld) == FUNCTION_DECL
25854 			       && !DECL_ARTIFICIAL (fld)))
25855 			  && DECL_TEMPLATE_INSTANTIATION (fld))
25856 			instantiate_decl (fld,
25857 					  /*defer_ok=*/false,
25858 					  /*expl_inst_class_mem_p=*/false);
25859 
25860 		  if (COMPLETE_TYPE_P (instantiation))
25861 		    reconsider = 1;
25862 		}
25863 
25864 	      complete = COMPLETE_TYPE_P (instantiation);
25865 	    }
25866 	  else
25867 	    {
25868 	      if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
25869 		  && !DECL_TEMPLATE_INSTANTIATED (instantiation))
25870 		{
25871 		  instantiation
25872 		    = instantiate_decl (instantiation,
25873 					/*defer_ok=*/false,
25874 					/*expl_inst_class_mem_p=*/false);
25875 		  if (DECL_TEMPLATE_INSTANTIATED (instantiation))
25876 		    reconsider = 1;
25877 		}
25878 
25879 	      complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
25880 			  || DECL_TEMPLATE_INSTANTIATED (instantiation));
25881 	    }
25882 
25883 	  if (complete)
25884 	    {
25885 	      /* If INSTANTIATION has been instantiated, then we don't
25886 		 need to consider it again in the future.  */
25887 	      struct pending_template *drop = *t;
25888 	      *t = (*t)->next;
25889 	      set_refcount_ptr (drop->tinst);
25890 	      pending_template_freelist ().free (drop);
25891 	    }
25892 	  else
25893 	    {
25894 	      last = *t;
25895 	      t = &(*t)->next;
25896 	    }
25897 	  tinst_depth = 0;
25898 	  set_refcount_ptr (current_tinst_level);
25899 	}
25900       last_pending_template = last;
25901     }
25902   while (reconsider);
25903 
25904   input_location = saved_loc;
25905 }
25906 
25907 /* Substitute ARGVEC into T, which is a list of initializers for
25908    either base class or a non-static data member.  The TREE_PURPOSEs
25909    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
25910    instantiate_decl.  */
25911 
25912 static tree
tsubst_initializer_list(tree t,tree argvec)25913 tsubst_initializer_list (tree t, tree argvec)
25914 {
25915   tree inits = NULL_TREE;
25916   tree target_ctor = error_mark_node;
25917 
25918   for (; t; t = TREE_CHAIN (t))
25919     {
25920       tree decl;
25921       tree init;
25922       tree expanded_bases = NULL_TREE;
25923       tree expanded_arguments = NULL_TREE;
25924       int i, len = 1;
25925 
25926       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
25927         {
25928           tree expr;
25929           tree arg;
25930 
25931           /* Expand the base class expansion type into separate base
25932              classes.  */
25933           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
25934                                                  tf_warning_or_error,
25935                                                  NULL_TREE);
25936           if (expanded_bases == error_mark_node)
25937             continue;
25938 
25939           /* We'll be building separate TREE_LISTs of arguments for
25940              each base.  */
25941           len = TREE_VEC_LENGTH (expanded_bases);
25942           expanded_arguments = make_tree_vec (len);
25943           for (i = 0; i < len; i++)
25944             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
25945 
25946           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
25947              expand each argument in the TREE_VALUE of t.  */
25948           expr = make_node (EXPR_PACK_EXPANSION);
25949 	  PACK_EXPANSION_LOCAL_P (expr) = true;
25950           PACK_EXPANSION_PARAMETER_PACKS (expr) =
25951             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
25952 
25953 	  if (TREE_VALUE (t) == void_type_node)
25954 	    /* VOID_TYPE_NODE is used to indicate
25955 	       value-initialization.  */
25956 	    {
25957 	      for (i = 0; i < len; i++)
25958 		TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
25959 	    }
25960 	  else
25961 	    {
25962 	      /* Substitute parameter packs into each argument in the
25963 		 TREE_LIST.  */
25964 	      in_base_initializer = 1;
25965 	      for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
25966 		{
25967 		  tree expanded_exprs;
25968 
25969 		  /* Expand the argument.  */
25970 		  SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
25971 		  expanded_exprs
25972 		    = tsubst_pack_expansion (expr, argvec,
25973 					     tf_warning_or_error,
25974 					     NULL_TREE);
25975 		  if (expanded_exprs == error_mark_node)
25976 		    continue;
25977 
25978 		  /* Prepend each of the expanded expressions to the
25979 		     corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
25980 		  for (i = 0; i < len; i++)
25981 		    {
25982 		      TREE_VEC_ELT (expanded_arguments, i) =
25983 			tree_cons (NULL_TREE,
25984 				   TREE_VEC_ELT (expanded_exprs, i),
25985 				   TREE_VEC_ELT (expanded_arguments, i));
25986 		    }
25987 		}
25988 	      in_base_initializer = 0;
25989 
25990 	      /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
25991 		 since we built them backwards.  */
25992 	      for (i = 0; i < len; i++)
25993 		{
25994 		  TREE_VEC_ELT (expanded_arguments, i) =
25995 		    nreverse (TREE_VEC_ELT (expanded_arguments, i));
25996 		}
25997 	    }
25998         }
25999 
26000       for (i = 0; i < len; ++i)
26001         {
26002           if (expanded_bases)
26003             {
26004               decl = TREE_VEC_ELT (expanded_bases, i);
26005               decl = expand_member_init (decl);
26006               init = TREE_VEC_ELT (expanded_arguments, i);
26007             }
26008           else
26009             {
26010 	      tree tmp;
26011               decl = tsubst_copy (TREE_PURPOSE (t), argvec,
26012                                   tf_warning_or_error, NULL_TREE);
26013 
26014               decl = expand_member_init (decl);
26015               if (decl && !DECL_P (decl))
26016                 in_base_initializer = 1;
26017 
26018 	      init = TREE_VALUE (t);
26019 	      tmp = init;
26020 	      if (init != void_type_node)
26021 		init = tsubst_expr (init, argvec,
26022 				    tf_warning_or_error, NULL_TREE,
26023 				    /*integral_constant_expression_p=*/false);
26024 	      if (init == NULL_TREE && tmp != NULL_TREE)
26025 		/* If we had an initializer but it instantiated to nothing,
26026 		   value-initialize the object.  This will only occur when
26027 		   the initializer was a pack expansion where the parameter
26028 		   packs used in that expansion were of length zero.  */
26029 		init = void_type_node;
26030               in_base_initializer = 0;
26031             }
26032 
26033 	  if (target_ctor != error_mark_node
26034 	      && init != error_mark_node)
26035 	    {
26036 	      error ("mem-initializer for %qD follows constructor delegation",
26037 		     decl);
26038 	      return inits;
26039 	    }
26040 	  /* Look for a target constructor. */
26041 	  if (init != error_mark_node
26042 	      && decl && CLASS_TYPE_P (decl)
26043 	      && same_type_p (decl, current_class_type))
26044 	    {
26045 	      maybe_warn_cpp0x (CPP0X_DELEGATING_CTORS);
26046 	      if (inits)
26047 		{
26048 		  error ("constructor delegation follows mem-initializer for %qD",
26049 			 TREE_PURPOSE (inits));
26050 		  continue;
26051 		}
26052 	      target_ctor = init;
26053 	    }
26054 
26055           if (decl)
26056             {
26057               init = build_tree_list (decl, init);
26058               TREE_CHAIN (init) = inits;
26059               inits = init;
26060             }
26061         }
26062     }
26063   return inits;
26064 }
26065 
26066 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
26067 
26068 static void
set_current_access_from_decl(tree decl)26069 set_current_access_from_decl (tree decl)
26070 {
26071   if (TREE_PRIVATE (decl))
26072     current_access_specifier = access_private_node;
26073   else if (TREE_PROTECTED (decl))
26074     current_access_specifier = access_protected_node;
26075   else
26076     current_access_specifier = access_public_node;
26077 }
26078 
26079 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
26080    is the instantiation (which should have been created with
26081    start_enum) and ARGS are the template arguments to use.  */
26082 
26083 static void
tsubst_enum(tree tag,tree newtag,tree args)26084 tsubst_enum (tree tag, tree newtag, tree args)
26085 {
26086   tree e;
26087 
26088   if (SCOPED_ENUM_P (newtag))
26089     begin_scope (sk_scoped_enum, newtag);
26090 
26091   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
26092     {
26093       tree value;
26094       tree decl;
26095 
26096       decl = TREE_VALUE (e);
26097       /* Note that in a template enum, the TREE_VALUE is the
26098 	 CONST_DECL, not the corresponding INTEGER_CST.  */
26099       value = tsubst_expr (DECL_INITIAL (decl),
26100 			   args, tf_warning_or_error, NULL_TREE,
26101 			   /*integral_constant_expression_p=*/true);
26102 
26103       /* Give this enumeration constant the correct access.  */
26104       set_current_access_from_decl (decl);
26105 
26106       /* Actually build the enumerator itself.  Here we're assuming that
26107 	 enumerators can't have dependent attributes.  */
26108       build_enumerator (DECL_NAME (decl), value, newtag,
26109 			DECL_ATTRIBUTES (decl), DECL_SOURCE_LOCATION (decl));
26110     }
26111 
26112   if (SCOPED_ENUM_P (newtag))
26113     finish_scope ();
26114 
26115   finish_enum_value_list (newtag);
26116   finish_enum (newtag);
26117 
26118   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
26119     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
26120 }
26121 
26122 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
26123    its type -- but without substituting the innermost set of template
26124    arguments.  So, innermost set of template parameters will appear in
26125    the type.  */
26126 
26127 tree
get_mostly_instantiated_function_type(tree decl)26128 get_mostly_instantiated_function_type (tree decl)
26129 {
26130   /* For a function, DECL_TI_TEMPLATE is partially instantiated.  */
26131   return TREE_TYPE (DECL_TI_TEMPLATE (decl));
26132 }
26133 
26134 /* Return truthvalue if we're processing a template different from
26135    the last one involved in diagnostics.  */
26136 bool
problematic_instantiation_changed(void)26137 problematic_instantiation_changed (void)
26138 {
26139   return current_tinst_level != last_error_tinst_level;
26140 }
26141 
26142 /* Remember current template involved in diagnostics.  */
26143 void
record_last_problematic_instantiation(void)26144 record_last_problematic_instantiation (void)
26145 {
26146   set_refcount_ptr (last_error_tinst_level, current_tinst_level);
26147 }
26148 
26149 struct tinst_level *
current_instantiation(void)26150 current_instantiation (void)
26151 {
26152   return current_tinst_level;
26153 }
26154 
26155 /* Return TRUE if current_function_decl is being instantiated, false
26156    otherwise.  */
26157 
26158 bool
instantiating_current_function_p(void)26159 instantiating_current_function_p (void)
26160 {
26161   return (current_instantiation ()
26162 	  && (current_instantiation ()->maybe_get_node ()
26163 	      == current_function_decl));
26164 }
26165 
26166 /* [temp.param] Check that template non-type parm TYPE is of an allowable
26167    type.  Return false for ok, true for disallowed.  Issue error and
26168    inform messages under control of COMPLAIN.  */
26169 
26170 static bool
invalid_nontype_parm_type_p(tree type,tsubst_flags_t complain)26171 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
26172 {
26173   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
26174     return false;
26175   else if (TYPE_PTR_P (type))
26176     return false;
26177   else if (TYPE_REF_P (type)
26178 	   && !TYPE_REF_IS_RVALUE (type))
26179     return false;
26180   else if (TYPE_PTRMEM_P (type))
26181     return false;
26182   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
26183     {
26184       if (CLASS_PLACEHOLDER_TEMPLATE (type) && cxx_dialect < cxx2a)
26185 	{
26186 	  if (complain & tf_error)
26187 	    error ("non-type template parameters of deduced class type only "
26188 		   "available with %<-std=c++2a%> or %<-std=gnu++2a%>");
26189 	  return true;
26190 	}
26191       return false;
26192     }
26193   else if (TREE_CODE (type) == TYPENAME_TYPE)
26194     return false;
26195   else if (TREE_CODE (type) == DECLTYPE_TYPE)
26196     return false;
26197   else if (TREE_CODE (type) == NULLPTR_TYPE)
26198     return false;
26199   /* A bound template template parm could later be instantiated to have a valid
26200      nontype parm type via an alias template.  */
26201   else if (cxx_dialect >= cxx11
26202 	   && TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
26203     return false;
26204   else if (CLASS_TYPE_P (type))
26205     {
26206       if (cxx_dialect < cxx2a)
26207 	{
26208 	  if (complain & tf_error)
26209 	    error ("non-type template parameters of class type only available "
26210 		   "with %<-std=c++2a%> or %<-std=gnu++2a%>");
26211 	  return true;
26212 	}
26213       if (dependent_type_p (type))
26214 	return false;
26215       if (!complete_type_or_else (type, NULL_TREE))
26216 	return true;
26217       if (!structural_type_p (type))
26218 	{
26219 	  if (complain & tf_error)
26220 	    {
26221 	      auto_diagnostic_group d;
26222 	      error ("%qT is not a valid type for a template non-type "
26223 		     "parameter because it is not structural", type);
26224 	      structural_type_p (type, true);
26225 	    }
26226 	  return true;
26227 	}
26228       return false;
26229     }
26230 
26231   if (complain & tf_error)
26232     {
26233       if (type == error_mark_node)
26234 	inform (input_location, "invalid template non-type parameter");
26235       else
26236 	error ("%q#T is not a valid type for a template non-type parameter",
26237 	       type);
26238     }
26239   return true;
26240 }
26241 
26242 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
26243    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
26244 
26245 static bool
dependent_type_p_r(tree type)26246 dependent_type_p_r (tree type)
26247 {
26248   tree scope;
26249 
26250   /* [temp.dep.type]
26251 
26252      A type is dependent if it is:
26253 
26254      -- a template parameter. Template template parameters are types
26255 	for us (since TYPE_P holds true for them) so we handle
26256 	them here.  */
26257   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
26258       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
26259     return true;
26260   /* -- a qualified-id with a nested-name-specifier which contains a
26261 	class-name that names a dependent type or whose unqualified-id
26262 	names a dependent type.  */
26263   if (TREE_CODE (type) == TYPENAME_TYPE)
26264     return true;
26265 
26266   /* An alias template specialization can be dependent even if the
26267      resulting type is not.  */
26268   if (dependent_alias_template_spec_p (type, nt_transparent))
26269     return true;
26270 
26271   /* -- a cv-qualified type where the cv-unqualified type is
26272 	dependent.
26273      No code is necessary for this bullet; the code below handles
26274      cv-qualified types, and we don't want to strip aliases with
26275      TYPE_MAIN_VARIANT because of DR 1558.  */
26276   /* -- a compound type constructed from any dependent type.  */
26277   if (TYPE_PTRMEM_P (type))
26278     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
26279 	    || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
26280 					   (type)));
26281   else if (INDIRECT_TYPE_P (type))
26282     return dependent_type_p (TREE_TYPE (type));
26283   else if (FUNC_OR_METHOD_TYPE_P (type))
26284     {
26285       tree arg_type;
26286 
26287       if (dependent_type_p (TREE_TYPE (type)))
26288 	return true;
26289       for (arg_type = TYPE_ARG_TYPES (type);
26290 	   arg_type;
26291 	   arg_type = TREE_CHAIN (arg_type))
26292 	if (dependent_type_p (TREE_VALUE (arg_type)))
26293 	  return true;
26294       if (cxx_dialect >= cxx17)
26295 	/* A value-dependent noexcept-specifier makes the type dependent.  */
26296 	if (tree spec = TYPE_RAISES_EXCEPTIONS (type))
26297 	  if (tree noex = TREE_PURPOSE (spec))
26298 	    /* Treat DEFERRED_NOEXCEPT as non-dependent, since it doesn't
26299 	       affect overload resolution and treating it as dependent breaks
26300 	       things.  Same for an unparsed noexcept expression.  */
26301 	    if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
26302 		&& TREE_CODE (noex) != DEFERRED_PARSE
26303 		&& value_dependent_expression_p (noex))
26304 	      return true;
26305       return false;
26306     }
26307   /* -- an array type constructed from any dependent type or whose
26308 	size is specified by a constant expression that is
26309 	value-dependent.
26310 
26311         We checked for type- and value-dependence of the bounds in
26312         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
26313   if (TREE_CODE (type) == ARRAY_TYPE)
26314     {
26315       if (TYPE_DOMAIN (type)
26316 	  && dependent_type_p (TYPE_DOMAIN (type)))
26317 	return true;
26318       return dependent_type_p (TREE_TYPE (type));
26319     }
26320 
26321   /* -- a template-id in which either the template name is a template
26322      parameter ...  */
26323   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
26324     return true;
26325   /* ... or any of the template arguments is a dependent type or
26326 	an expression that is type-dependent or value-dependent.  */
26327   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
26328 	   && (any_dependent_template_arguments_p
26329 	       (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
26330     return true;
26331 
26332   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
26333      dependent; if the argument of the `typeof' expression is not
26334      type-dependent, then it should already been have resolved.  */
26335   if (TREE_CODE (type) == TYPEOF_TYPE
26336       || TREE_CODE (type) == DECLTYPE_TYPE
26337       || TREE_CODE (type) == UNDERLYING_TYPE)
26338     return true;
26339 
26340   /* A template argument pack is dependent if any of its packed
26341      arguments are.  */
26342   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
26343     {
26344       tree args = ARGUMENT_PACK_ARGS (type);
26345       int i, len = TREE_VEC_LENGTH (args);
26346       for (i = 0; i < len; ++i)
26347         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
26348           return true;
26349     }
26350 
26351   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
26352      be template parameters.  */
26353   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
26354     return true;
26355 
26356   if (any_dependent_type_attributes_p (TYPE_ATTRIBUTES (type)))
26357     return true;
26358 
26359   /* The standard does not specifically mention types that are local
26360      to template functions or local classes, but they should be
26361      considered dependent too.  For example:
26362 
26363        template <int I> void f() {
26364 	 enum E { a = I };
26365 	 S<sizeof (E)> s;
26366        }
26367 
26368      The size of `E' cannot be known until the value of `I' has been
26369      determined.  Therefore, `E' must be considered dependent.  */
26370   scope = TYPE_CONTEXT (type);
26371   if (scope && TYPE_P (scope))
26372     return dependent_type_p (scope);
26373   /* Don't use type_dependent_expression_p here, as it can lead
26374      to infinite recursion trying to determine whether a lambda
26375      nested in a lambda is dependent (c++/47687).  */
26376   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
26377 	   && DECL_LANG_SPECIFIC (scope)
26378 	   && DECL_TEMPLATE_INFO (scope)
26379 	   && (any_dependent_template_arguments_p
26380 	       (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
26381     return true;
26382 
26383   /* Other types are non-dependent.  */
26384   return false;
26385 }
26386 
26387 /* Returns TRUE if TYPE is dependent, in the sense of
26388    [temp.dep.type].  Note that a NULL type is considered dependent.  */
26389 
26390 bool
dependent_type_p(tree type)26391 dependent_type_p (tree type)
26392 {
26393   /* If there are no template parameters in scope, then there can't be
26394      any dependent types.  */
26395   if (!processing_template_decl)
26396     {
26397       /* If we are not processing a template, then nobody should be
26398 	 providing us with a dependent type.  */
26399       gcc_assert (type);
26400       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
26401       return false;
26402     }
26403 
26404   /* If the type is NULL, we have not computed a type for the entity
26405      in question; in that case, the type is dependent.  */
26406   if (!type)
26407     return true;
26408 
26409   /* Erroneous types can be considered non-dependent.  */
26410   if (type == error_mark_node)
26411     return false;
26412 
26413   /* Getting here with global_type_node means we improperly called this
26414      function on the TREE_TYPE of an IDENTIFIER_NODE.  */
26415   gcc_checking_assert (type != global_type_node);
26416 
26417   /* If we have not already computed the appropriate value for TYPE,
26418      do so now.  */
26419   if (!TYPE_DEPENDENT_P_VALID (type))
26420     {
26421       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
26422       TYPE_DEPENDENT_P_VALID (type) = 1;
26423     }
26424 
26425   return TYPE_DEPENDENT_P (type);
26426 }
26427 
26428 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
26429    lookup.  In other words, a dependent type that is not the current
26430    instantiation.  */
26431 
26432 bool
dependent_scope_p(tree scope)26433 dependent_scope_p (tree scope)
26434 {
26435   return (scope && TYPE_P (scope) && dependent_type_p (scope)
26436 	  && !currently_open_class (scope));
26437 }
26438 
26439 /* T is a SCOPE_REF.  Return whether it represents a non-static member of
26440    an unknown base of 'this' (and is therefore instantiation-dependent).  */
26441 
26442 static bool
unknown_base_ref_p(tree t)26443 unknown_base_ref_p (tree t)
26444 {
26445   if (!current_class_ptr)
26446     return false;
26447 
26448   tree mem = TREE_OPERAND (t, 1);
26449   if (shared_member_p (mem))
26450     return false;
26451 
26452   tree cur = current_nonlambda_class_type ();
26453   if (!any_dependent_bases_p (cur))
26454     return false;
26455 
26456   tree ctx = TREE_OPERAND (t, 0);
26457   if (DERIVED_FROM_P (ctx, cur))
26458     return false;
26459 
26460   return true;
26461 }
26462 
26463 /* T is a SCOPE_REF; return whether we need to consider it
26464     instantiation-dependent so that we can check access at instantiation
26465     time even though we know which member it resolves to.  */
26466 
26467 static bool
instantiation_dependent_scope_ref_p(tree t)26468 instantiation_dependent_scope_ref_p (tree t)
26469 {
26470   if (DECL_P (TREE_OPERAND (t, 1))
26471       && CLASS_TYPE_P (TREE_OPERAND (t, 0))
26472       && !unknown_base_ref_p (t)
26473       && accessible_in_template_p (TREE_OPERAND (t, 0),
26474 				   TREE_OPERAND (t, 1)))
26475     return false;
26476   else
26477     return true;
26478 }
26479 
26480 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
26481    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
26482    expression.  */
26483 
26484 /* Note that this predicate is not appropriate for general expressions;
26485    only constant expressions (that satisfy potential_constant_expression)
26486    can be tested for value dependence.  */
26487 
26488 bool
value_dependent_expression_p(tree expression)26489 value_dependent_expression_p (tree expression)
26490 {
26491   if (!processing_template_decl || expression == NULL_TREE)
26492     return false;
26493 
26494   /* A type-dependent expression is also value-dependent.  */
26495   if (type_dependent_expression_p (expression))
26496     return true;
26497 
26498   switch (TREE_CODE (expression))
26499     {
26500     case BASELINK:
26501       /* A dependent member function of the current instantiation.  */
26502       return dependent_type_p (BINFO_TYPE (BASELINK_BINFO (expression)));
26503 
26504     case FUNCTION_DECL:
26505       /* A dependent member function of the current instantiation.  */
26506       if (DECL_CLASS_SCOPE_P (expression)
26507 	  && dependent_type_p (DECL_CONTEXT (expression)))
26508 	return true;
26509       break;
26510 
26511     case IDENTIFIER_NODE:
26512       /* A name that has not been looked up -- must be dependent.  */
26513       return true;
26514 
26515     case TEMPLATE_PARM_INDEX:
26516       /* A non-type template parm.  */
26517       return true;
26518 
26519     case CONST_DECL:
26520       /* A non-type template parm.  */
26521       if (DECL_TEMPLATE_PARM_P (expression))
26522 	return true;
26523       return value_dependent_expression_p (DECL_INITIAL (expression));
26524 
26525     case VAR_DECL:
26526        /* A constant with literal type and is initialized
26527 	  with an expression that is value-dependent.  */
26528       if (DECL_DEPENDENT_INIT_P (expression)
26529 	  /* FIXME cp_finish_decl doesn't fold reference initializers.  */
26530 	  || TYPE_REF_P (TREE_TYPE (expression)))
26531 	return true;
26532       if (DECL_HAS_VALUE_EXPR_P (expression))
26533 	{
26534 	  tree value_expr = DECL_VALUE_EXPR (expression);
26535 	  if (value_dependent_expression_p (value_expr)
26536 	      /* __PRETTY_FUNCTION__ inside a template function is dependent
26537 		 on the name of the function.  */
26538 	      || (DECL_PRETTY_FUNCTION_P (expression)
26539 		  /* It might be used in a template, but not a template
26540 		     function, in which case its DECL_VALUE_EXPR will be
26541 		     "top level".  */
26542 		  && value_expr == error_mark_node))
26543 	    return true;
26544 	}
26545       return false;
26546 
26547     case DYNAMIC_CAST_EXPR:
26548     case STATIC_CAST_EXPR:
26549     case CONST_CAST_EXPR:
26550     case REINTERPRET_CAST_EXPR:
26551     case CAST_EXPR:
26552     case IMPLICIT_CONV_EXPR:
26553       /* These expressions are value-dependent if the type to which
26554 	 the cast occurs is dependent or the expression being casted
26555 	 is value-dependent.  */
26556       {
26557 	tree type = TREE_TYPE (expression);
26558 
26559 	if (dependent_type_p (type))
26560 	  return true;
26561 
26562 	/* A functional cast has a list of operands.  */
26563 	expression = TREE_OPERAND (expression, 0);
26564 	if (!expression)
26565 	  {
26566 	    /* If there are no operands, it must be an expression such
26567 	       as "int()". This should not happen for aggregate types
26568 	       because it would form non-constant expressions.  */
26569 	    gcc_assert (cxx_dialect >= cxx11
26570 			|| INTEGRAL_OR_ENUMERATION_TYPE_P (type));
26571 
26572 	    return false;
26573 	  }
26574 
26575 	if (TREE_CODE (expression) == TREE_LIST)
26576 	  return any_value_dependent_elements_p (expression);
26577 
26578 	return value_dependent_expression_p (expression);
26579       }
26580 
26581     case SIZEOF_EXPR:
26582       if (SIZEOF_EXPR_TYPE_P (expression))
26583 	return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
26584       /* FALLTHRU */
26585     case ALIGNOF_EXPR:
26586     case TYPEID_EXPR:
26587       /* A `sizeof' expression is value-dependent if the operand is
26588 	 type-dependent or is a pack expansion.  */
26589       expression = TREE_OPERAND (expression, 0);
26590       if (PACK_EXPANSION_P (expression))
26591         return true;
26592       else if (TYPE_P (expression))
26593 	return dependent_type_p (expression);
26594       return instantiation_dependent_uneval_expression_p (expression);
26595 
26596     case AT_ENCODE_EXPR:
26597       /* An 'encode' expression is value-dependent if the operand is
26598 	 type-dependent.  */
26599       expression = TREE_OPERAND (expression, 0);
26600       return dependent_type_p (expression);
26601 
26602     case NOEXCEPT_EXPR:
26603       expression = TREE_OPERAND (expression, 0);
26604       return instantiation_dependent_uneval_expression_p (expression);
26605 
26606     case SCOPE_REF:
26607       /* All instantiation-dependent expressions should also be considered
26608 	 value-dependent.  */
26609       return instantiation_dependent_scope_ref_p (expression);
26610 
26611     case COMPONENT_REF:
26612       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
26613 	      || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
26614 
26615     case NONTYPE_ARGUMENT_PACK:
26616       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
26617          is value-dependent.  */
26618       {
26619         tree values = ARGUMENT_PACK_ARGS (expression);
26620         int i, len = TREE_VEC_LENGTH (values);
26621 
26622         for (i = 0; i < len; ++i)
26623           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
26624             return true;
26625 
26626         return false;
26627       }
26628 
26629     case TRAIT_EXPR:
26630       {
26631 	tree type2 = TRAIT_EXPR_TYPE2 (expression);
26632 
26633 	if (dependent_type_p (TRAIT_EXPR_TYPE1 (expression)))
26634 	  return true;
26635 
26636 	if (!type2)
26637 	  return false;
26638 
26639 	if (TREE_CODE (type2) != TREE_LIST)
26640 	  return dependent_type_p (type2);
26641 
26642 	for (; type2; type2 = TREE_CHAIN (type2))
26643 	  if (dependent_type_p (TREE_VALUE (type2)))
26644 	    return true;
26645 
26646 	return false;
26647       }
26648 
26649     case MODOP_EXPR:
26650       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
26651 	      || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
26652 
26653     case ARRAY_REF:
26654       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
26655 	      || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
26656 
26657     case ADDR_EXPR:
26658       {
26659 	tree op = TREE_OPERAND (expression, 0);
26660 	return (value_dependent_expression_p (op)
26661 		|| has_value_dependent_address (op));
26662       }
26663 
26664     case REQUIRES_EXPR:
26665       /* Treat all requires-expressions as value-dependent so
26666          we don't try to fold them.  */
26667       return true;
26668 
26669     case TYPE_REQ:
26670       return dependent_type_p (TREE_OPERAND (expression, 0));
26671 
26672     case CALL_EXPR:
26673       {
26674 	if (value_dependent_expression_p (CALL_EXPR_FN (expression)))
26675 	  return true;
26676 	tree fn = get_callee_fndecl (expression);
26677 	int i, nargs;
26678 	nargs = call_expr_nargs (expression);
26679 	for (i = 0; i < nargs; ++i)
26680 	  {
26681 	    tree op = CALL_EXPR_ARG (expression, i);
26682 	    /* In a call to a constexpr member function, look through the
26683 	       implicit ADDR_EXPR on the object argument so that it doesn't
26684 	       cause the call to be considered value-dependent.  We also
26685 	       look through it in potential_constant_expression.  */
26686 	    if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
26687 		&& DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
26688 		&& TREE_CODE (op) == ADDR_EXPR)
26689 	      op = TREE_OPERAND (op, 0);
26690 	    if (value_dependent_expression_p (op))
26691 	      return true;
26692 	  }
26693 	return false;
26694       }
26695 
26696     case TEMPLATE_ID_EXPR:
26697       return concept_definition_p (TREE_OPERAND (expression, 0));
26698 
26699     case CONSTRUCTOR:
26700       {
26701 	unsigned ix;
26702 	tree val;
26703 	if (dependent_type_p (TREE_TYPE (expression)))
26704 	  return true;
26705 	FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
26706 	  if (value_dependent_expression_p (val))
26707 	    return true;
26708 	return false;
26709       }
26710 
26711     case STMT_EXPR:
26712       /* Treat a GNU statement expression as dependent to avoid crashing
26713 	 under instantiate_non_dependent_expr; it can't be constant.  */
26714       return true;
26715 
26716     default:
26717       /* A constant expression is value-dependent if any subexpression is
26718 	 value-dependent.  */
26719       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
26720 	{
26721 	case tcc_reference:
26722 	case tcc_unary:
26723 	case tcc_comparison:
26724 	case tcc_binary:
26725 	case tcc_expression:
26726 	case tcc_vl_exp:
26727 	  {
26728 	    int i, len = cp_tree_operand_length (expression);
26729 
26730 	    for (i = 0; i < len; i++)
26731 	      {
26732 		tree t = TREE_OPERAND (expression, i);
26733 
26734 		/* In some cases, some of the operands may be missing.
26735 		   (For example, in the case of PREDECREMENT_EXPR, the
26736 		   amount to increment by may be missing.)  That doesn't
26737 		   make the expression dependent.  */
26738 		if (t && value_dependent_expression_p (t))
26739 		  return true;
26740 	      }
26741 	  }
26742 	  break;
26743 	default:
26744 	  break;
26745 	}
26746       break;
26747     }
26748 
26749   /* The expression is not value-dependent.  */
26750   return false;
26751 }
26752 
26753 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
26754    [temp.dep.expr].  Note that an expression with no type is
26755    considered dependent.  Other parts of the compiler arrange for an
26756    expression with type-dependent subexpressions to have no type, so
26757    this function doesn't have to be fully recursive.  */
26758 
26759 bool
type_dependent_expression_p(tree expression)26760 type_dependent_expression_p (tree expression)
26761 {
26762   if (!processing_template_decl)
26763     return false;
26764 
26765   if (expression == NULL_TREE || expression == error_mark_node)
26766     return false;
26767 
26768   STRIP_ANY_LOCATION_WRAPPER (expression);
26769 
26770   /* An unresolved name is always dependent.  */
26771   if (identifier_p (expression)
26772       || TREE_CODE (expression) == USING_DECL
26773       || TREE_CODE (expression) == WILDCARD_DECL)
26774     return true;
26775 
26776   /* A lambda-expression in template context is dependent.  dependent_type_p is
26777      true for a lambda in the scope of a class or function template, but that
26778      doesn't cover all template contexts, like a default template argument.  */
26779   if (TREE_CODE (expression) == LAMBDA_EXPR)
26780     return true;
26781 
26782   /* A fold expression is type-dependent. */
26783   if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
26784       || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
26785       || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
26786       || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
26787     return true;
26788 
26789   /* Some expression forms are never type-dependent.  */
26790   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
26791       || TREE_CODE (expression) == SIZEOF_EXPR
26792       || TREE_CODE (expression) == ALIGNOF_EXPR
26793       || TREE_CODE (expression) == AT_ENCODE_EXPR
26794       || TREE_CODE (expression) == NOEXCEPT_EXPR
26795       || TREE_CODE (expression) == TRAIT_EXPR
26796       || TREE_CODE (expression) == TYPEID_EXPR
26797       || TREE_CODE (expression) == DELETE_EXPR
26798       || TREE_CODE (expression) == VEC_DELETE_EXPR
26799       || TREE_CODE (expression) == THROW_EXPR
26800       || TREE_CODE (expression) == REQUIRES_EXPR)
26801     return false;
26802 
26803   /* The types of these expressions depends only on the type to which
26804      the cast occurs.  */
26805   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
26806       || TREE_CODE (expression) == STATIC_CAST_EXPR
26807       || TREE_CODE (expression) == CONST_CAST_EXPR
26808       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
26809       || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
26810       || TREE_CODE (expression) == CAST_EXPR)
26811     return dependent_type_p (TREE_TYPE (expression));
26812 
26813   /* The types of these expressions depends only on the type created
26814      by the expression.  */
26815   if (TREE_CODE (expression) == NEW_EXPR
26816       || TREE_CODE (expression) == VEC_NEW_EXPR)
26817     {
26818       /* For NEW_EXPR tree nodes created inside a template, either
26819 	 the object type itself or a TREE_LIST may appear as the
26820 	 operand 1.  */
26821       tree type = TREE_OPERAND (expression, 1);
26822       if (TREE_CODE (type) == TREE_LIST)
26823 	/* This is an array type.  We need to check array dimensions
26824 	   as well.  */
26825 	return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
26826 	       || value_dependent_expression_p
26827 		    (TREE_OPERAND (TREE_VALUE (type), 1));
26828       else
26829 	return dependent_type_p (type);
26830     }
26831 
26832   if (TREE_CODE (expression) == SCOPE_REF)
26833     {
26834       tree scope = TREE_OPERAND (expression, 0);
26835       tree name = TREE_OPERAND (expression, 1);
26836 
26837       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
26838 	 contains an identifier associated by name lookup with one or more
26839 	 declarations declared with a dependent type, or...a
26840 	 nested-name-specifier or qualified-id that names a member of an
26841 	 unknown specialization.  */
26842       return (type_dependent_expression_p (name)
26843 	      || dependent_scope_p (scope));
26844     }
26845 
26846   if (TREE_CODE (expression) == TEMPLATE_DECL
26847       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
26848     return uses_outer_template_parms (expression);
26849 
26850   if (TREE_CODE (expression) == STMT_EXPR)
26851     expression = stmt_expr_value_expr (expression);
26852 
26853   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
26854     {
26855       tree elt;
26856       unsigned i;
26857 
26858       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
26859 	{
26860 	  if (type_dependent_expression_p (elt))
26861 	    return true;
26862 	}
26863       return false;
26864     }
26865 
26866   /* A static data member of the current instantiation with incomplete
26867      array type is type-dependent, as the definition and specializations
26868      can have different bounds.  */
26869   if (VAR_P (expression)
26870       && DECL_CLASS_SCOPE_P (expression)
26871       && dependent_type_p (DECL_CONTEXT (expression))
26872       && VAR_HAD_UNKNOWN_BOUND (expression))
26873     return true;
26874 
26875   /* An array of unknown bound depending on a variadic parameter, eg:
26876 
26877      template<typename... Args>
26878        void foo (Args... args)
26879        {
26880          int arr[] = { args... };
26881        }
26882 
26883      template<int... vals>
26884        void bar ()
26885        {
26886          int arr[] = { vals... };
26887        }
26888 
26889      If the array has no length and has an initializer, it must be that
26890      we couldn't determine its length in cp_complete_array_type because
26891      it is dependent.  */
26892   if (VAR_P (expression)
26893       && TREE_TYPE (expression) != NULL_TREE
26894       && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
26895       && !TYPE_DOMAIN (TREE_TYPE (expression))
26896       && DECL_INITIAL (expression))
26897    return true;
26898 
26899   /* A function or variable template-id is type-dependent if it has any
26900      dependent template arguments.  */
26901   if (VAR_OR_FUNCTION_DECL_P (expression)
26902       && DECL_LANG_SPECIFIC (expression)
26903       && DECL_TEMPLATE_INFO (expression))
26904     {
26905       /* Consider the innermost template arguments, since those are the ones
26906 	 that come from the template-id; the template arguments for the
26907 	 enclosing class do not make it type-dependent unless they are used in
26908 	 the type of the decl.  */
26909       if (instantiates_primary_template_p (expression)
26910 	  && (any_dependent_template_arguments_p
26911 	      (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
26912 	return true;
26913     }
26914 
26915   /* Otherwise, if the function decl isn't from a dependent scope, it can't be
26916      type-dependent.  Checking this is important for functions with auto return
26917      type, which looks like a dependent type.  */
26918   if (TREE_CODE (expression) == FUNCTION_DECL
26919       && !(DECL_CLASS_SCOPE_P (expression)
26920 	   && dependent_type_p (DECL_CONTEXT (expression)))
26921       && !(DECL_LANG_SPECIFIC (expression)
26922 	   && DECL_FRIEND_P (expression)
26923 	   && (!DECL_FRIEND_CONTEXT (expression)
26924 	       || dependent_type_p (DECL_FRIEND_CONTEXT (expression))))
26925       && !DECL_LOCAL_FUNCTION_P (expression))
26926     {
26927       gcc_assert (!dependent_type_p (TREE_TYPE (expression))
26928 		  || undeduced_auto_decl (expression));
26929       return false;
26930     }
26931 
26932   /* Always dependent, on the number of arguments if nothing else.  */
26933   if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
26934     return true;
26935 
26936   if (TREE_TYPE (expression) == unknown_type_node)
26937     {
26938       if (TREE_CODE (expression) == ADDR_EXPR)
26939 	return type_dependent_expression_p (TREE_OPERAND (expression, 0));
26940       if (TREE_CODE (expression) == COMPONENT_REF
26941 	  || TREE_CODE (expression) == OFFSET_REF)
26942 	{
26943 	  if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
26944 	    return true;
26945 	  expression = TREE_OPERAND (expression, 1);
26946 	  if (identifier_p (expression))
26947 	    return false;
26948 	}
26949       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
26950       if (TREE_CODE (expression) == SCOPE_REF)
26951 	return false;
26952 
26953       /* CO_AWAIT/YIELD_EXPR with unknown type is always dependent.  */
26954       if (TREE_CODE (expression) == CO_AWAIT_EXPR
26955 	  || TREE_CODE (expression) == CO_YIELD_EXPR)
26956 	return true;
26957 
26958       if (BASELINK_P (expression))
26959 	{
26960 	  if (BASELINK_OPTYPE (expression)
26961 	      && dependent_type_p (BASELINK_OPTYPE (expression)))
26962 	    return true;
26963 	  expression = BASELINK_FUNCTIONS (expression);
26964 	}
26965 
26966       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
26967 	{
26968 	  if (any_dependent_template_arguments_p
26969 	      (TREE_OPERAND (expression, 1)))
26970 	    return true;
26971 	  expression = TREE_OPERAND (expression, 0);
26972 	  if (identifier_p (expression))
26973 	    return true;
26974 	}
26975 
26976       gcc_assert (OVL_P (expression));
26977 
26978       for (lkp_iterator iter (expression); iter; ++iter)
26979 	if (type_dependent_expression_p (*iter))
26980 	  return true;
26981 
26982       return false;
26983     }
26984 
26985   /* The type of a non-type template parm declared with a placeholder type
26986      depends on the corresponding template argument, even though
26987      placeholders are not normally considered dependent.  */
26988   if (TREE_CODE (expression) == TEMPLATE_PARM_INDEX
26989       && is_auto (TREE_TYPE (expression)))
26990     return true;
26991 
26992   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
26993 
26994   /* Dependent type attributes might not have made it from the decl to
26995      the type yet.  */
26996   if (DECL_P (expression)
26997       && any_dependent_type_attributes_p (DECL_ATTRIBUTES (expression)))
26998     return true;
26999 
27000   return (dependent_type_p (TREE_TYPE (expression)));
27001 }
27002 
27003 /* [temp.dep.expr]/5: A class member access expression (5.2.5) is
27004    type-dependent if the expression refers to a member of the current
27005    instantiation and the type of the referenced member is dependent, or the
27006    class member access expression refers to a member of an unknown
27007    specialization.
27008 
27009    This function returns true if the OBJECT in such a class member access
27010    expression is of an unknown specialization.  */
27011 
27012 bool
type_dependent_object_expression_p(tree object)27013 type_dependent_object_expression_p (tree object)
27014 {
27015   /* An IDENTIFIER_NODE can sometimes have a TREE_TYPE, but it's still
27016      dependent.  */
27017   if (TREE_CODE (object) == IDENTIFIER_NODE)
27018     return true;
27019   tree scope = TREE_TYPE (object);
27020   return (!scope || dependent_scope_p (scope));
27021 }
27022 
27023 /* walk_tree callback function for instantiation_dependent_expression_p,
27024    below.  Returns non-zero if a dependent subexpression is found.  */
27025 
27026 static tree
instantiation_dependent_r(tree * tp,int * walk_subtrees,void *)27027 instantiation_dependent_r (tree *tp, int *walk_subtrees,
27028 			   void * /*data*/)
27029 {
27030   if (TYPE_P (*tp))
27031     {
27032       /* We don't have to worry about decltype currently because decltype
27033 	 of an instantiation-dependent expr is a dependent type.  This
27034 	 might change depending on the resolution of DR 1172.  */
27035       *walk_subtrees = false;
27036       return NULL_TREE;
27037     }
27038   enum tree_code code = TREE_CODE (*tp);
27039   switch (code)
27040     {
27041       /* Don't treat an argument list as dependent just because it has no
27042 	 TREE_TYPE.  */
27043     case TREE_LIST:
27044     case TREE_VEC:
27045     case NONTYPE_ARGUMENT_PACK:
27046       return NULL_TREE;
27047 
27048     case TEMPLATE_PARM_INDEX:
27049       if (dependent_type_p (TREE_TYPE (*tp)))
27050 	return *tp;
27051       if (TEMPLATE_PARM_PARAMETER_PACK (*tp))
27052 	return *tp;
27053       /* We'll check value-dependence separately.  */
27054       return NULL_TREE;
27055 
27056       /* Handle expressions with type operands.  */
27057     case SIZEOF_EXPR:
27058     case ALIGNOF_EXPR:
27059     case TYPEID_EXPR:
27060     case AT_ENCODE_EXPR:
27061       {
27062 	tree op = TREE_OPERAND (*tp, 0);
27063 	if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
27064 	  op = TREE_TYPE (op);
27065 	if (TYPE_P (op))
27066 	  {
27067 	    if (dependent_type_p (op))
27068 	      return *tp;
27069 	    else
27070 	      {
27071 		*walk_subtrees = false;
27072 		return NULL_TREE;
27073 	      }
27074 	  }
27075 	break;
27076       }
27077 
27078     case COMPONENT_REF:
27079       if (identifier_p (TREE_OPERAND (*tp, 1)))
27080 	/* In a template, finish_class_member_access_expr creates a
27081 	   COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
27082 	   type-dependent, so that we can check access control at
27083 	   instantiation time (PR 42277).  See also Core issue 1273.  */
27084 	return *tp;
27085       break;
27086 
27087     case SCOPE_REF:
27088       if (instantiation_dependent_scope_ref_p (*tp))
27089 	return *tp;
27090       else
27091 	break;
27092 
27093       /* Treat statement-expressions as dependent.  */
27094     case BIND_EXPR:
27095       return *tp;
27096 
27097       /* Treat requires-expressions as dependent. */
27098     case REQUIRES_EXPR:
27099       return *tp;
27100 
27101     case CALL_EXPR:
27102       /* Treat concept checks as dependent. */
27103       if (concept_check_p (*tp))
27104         return *tp;
27105       break;
27106 
27107     case TEMPLATE_ID_EXPR:
27108       /* Treat concept checks as dependent.  */
27109       if (concept_check_p (*tp))
27110 	return *tp;
27111       break;
27112 
27113     case CONSTRUCTOR:
27114       if (CONSTRUCTOR_IS_DEPENDENT (*tp))
27115 	return *tp;
27116       break;
27117 
27118     default:
27119       break;
27120     }
27121 
27122   if (type_dependent_expression_p (*tp))
27123     return *tp;
27124   else
27125     return NULL_TREE;
27126 }
27127 
27128 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
27129    sense defined by the ABI:
27130 
27131    "An expression is instantiation-dependent if it is type-dependent
27132    or value-dependent, or it has a subexpression that is type-dependent
27133    or value-dependent."
27134 
27135    Except don't actually check value-dependence for unevaluated expressions,
27136    because in sizeof(i) we don't care about the value of i.  Checking
27137    type-dependence will in turn check value-dependence of array bounds/template
27138    arguments as needed.  */
27139 
27140 bool
instantiation_dependent_uneval_expression_p(tree expression)27141 instantiation_dependent_uneval_expression_p (tree expression)
27142 {
27143   tree result;
27144 
27145   if (!processing_template_decl)
27146     return false;
27147 
27148   if (expression == error_mark_node)
27149     return false;
27150 
27151   result = cp_walk_tree_without_duplicates (&expression,
27152 					    instantiation_dependent_r, NULL);
27153   return result != NULL_TREE;
27154 }
27155 
27156 /* As above, but also check value-dependence of the expression as a whole.  */
27157 
27158 bool
instantiation_dependent_expression_p(tree expression)27159 instantiation_dependent_expression_p (tree expression)
27160 {
27161   return (instantiation_dependent_uneval_expression_p (expression)
27162 	  || value_dependent_expression_p (expression));
27163 }
27164 
27165 /* Like type_dependent_expression_p, but it also works while not processing
27166    a template definition, i.e. during substitution or mangling.  */
27167 
27168 bool
type_dependent_expression_p_push(tree expr)27169 type_dependent_expression_p_push (tree expr)
27170 {
27171   bool b;
27172   ++processing_template_decl;
27173   b = type_dependent_expression_p (expr);
27174   --processing_template_decl;
27175   return b;
27176 }
27177 
27178 /* Returns TRUE if ARGS contains a type-dependent expression.  */
27179 
27180 bool
any_type_dependent_arguments_p(const vec<tree,va_gc> * args)27181 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
27182 {
27183   unsigned int i;
27184   tree arg;
27185 
27186   FOR_EACH_VEC_SAFE_ELT (args, i, arg)
27187     {
27188       if (type_dependent_expression_p (arg))
27189 	return true;
27190     }
27191   return false;
27192 }
27193 
27194 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
27195    expressions) contains any type-dependent expressions.  */
27196 
27197 bool
any_type_dependent_elements_p(const_tree list)27198 any_type_dependent_elements_p (const_tree list)
27199 {
27200   for (; list; list = TREE_CHAIN (list))
27201     if (type_dependent_expression_p (TREE_VALUE (list)))
27202       return true;
27203 
27204   return false;
27205 }
27206 
27207 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
27208    expressions) contains any value-dependent expressions.  */
27209 
27210 bool
any_value_dependent_elements_p(const_tree list)27211 any_value_dependent_elements_p (const_tree list)
27212 {
27213   for (; list; list = TREE_CHAIN (list))
27214     if (value_dependent_expression_p (TREE_VALUE (list)))
27215       return true;
27216 
27217   return false;
27218 }
27219 
27220 /* Returns TRUE if the ARG (a template argument) is dependent.  */
27221 
27222 bool
dependent_template_arg_p(tree arg)27223 dependent_template_arg_p (tree arg)
27224 {
27225   if (!processing_template_decl)
27226     return false;
27227 
27228   /* Assume a template argument that was wrongly written by the user
27229      is dependent. This is consistent with what
27230      any_dependent_template_arguments_p [that calls this function]
27231      does.  */
27232   if (!arg || arg == error_mark_node)
27233     return true;
27234 
27235   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
27236     arg = argument_pack_select_arg (arg);
27237 
27238   if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
27239     return true;
27240   if (TREE_CODE (arg) == TEMPLATE_DECL)
27241     {
27242       if (DECL_TEMPLATE_PARM_P (arg))
27243 	return true;
27244       /* A member template of a dependent class is not necessarily
27245 	 type-dependent, but it is a dependent template argument because it
27246 	 will be a member of an unknown specialization to that template.  */
27247       tree scope = CP_DECL_CONTEXT (arg);
27248       return TYPE_P (scope) && dependent_type_p (scope);
27249     }
27250   else if (ARGUMENT_PACK_P (arg))
27251     {
27252       tree args = ARGUMENT_PACK_ARGS (arg);
27253       int i, len = TREE_VEC_LENGTH (args);
27254       for (i = 0; i < len; ++i)
27255         {
27256           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
27257             return true;
27258         }
27259 
27260       return false;
27261     }
27262   else if (TYPE_P (arg))
27263     return dependent_type_p (arg);
27264   else
27265     return value_dependent_expression_p (arg);
27266 }
27267 
27268 /* Returns true if ARGS (a collection of template arguments) contains
27269    any types that require structural equality testing.  */
27270 
27271 bool
any_template_arguments_need_structural_equality_p(tree args)27272 any_template_arguments_need_structural_equality_p (tree args)
27273 {
27274   int i;
27275   int j;
27276 
27277   if (!args)
27278     return false;
27279   if (args == error_mark_node)
27280     return true;
27281 
27282   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
27283     {
27284       tree level = TMPL_ARGS_LEVEL (args, i + 1);
27285       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
27286 	{
27287 	  tree arg = TREE_VEC_ELT (level, j);
27288 	  tree packed_args = NULL_TREE;
27289 	  int k, len = 1;
27290 
27291 	  if (ARGUMENT_PACK_P (arg))
27292 	    {
27293 	      /* Look inside the argument pack.  */
27294 	      packed_args = ARGUMENT_PACK_ARGS (arg);
27295 	      len = TREE_VEC_LENGTH (packed_args);
27296 	    }
27297 
27298 	  for (k = 0; k < len; ++k)
27299 	    {
27300 	      if (packed_args)
27301 		arg = TREE_VEC_ELT (packed_args, k);
27302 
27303 	      if (error_operand_p (arg))
27304 		return true;
27305 	      else if (TREE_CODE (arg) == TEMPLATE_DECL)
27306 		continue;
27307 	      else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
27308 		return true;
27309 	      else if (!TYPE_P (arg) && TREE_TYPE (arg)
27310 		       && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
27311 		return true;
27312 	    }
27313 	}
27314     }
27315 
27316   return false;
27317 }
27318 
27319 /* Returns true if ARGS (a collection of template arguments) contains
27320    any dependent arguments.  */
27321 
27322 bool
any_dependent_template_arguments_p(const_tree args)27323 any_dependent_template_arguments_p (const_tree args)
27324 {
27325   int i;
27326   int j;
27327 
27328   if (!args)
27329     return false;
27330   if (args == error_mark_node)
27331     return true;
27332 
27333   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
27334     {
27335       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
27336       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
27337 	if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
27338 	  return true;
27339     }
27340 
27341   return false;
27342 }
27343 
27344 /* Returns true if ARGS contains any errors.  */
27345 
27346 bool
any_erroneous_template_args_p(const_tree args)27347 any_erroneous_template_args_p (const_tree args)
27348 {
27349   int i;
27350   int j;
27351 
27352   if (args == error_mark_node)
27353     return true;
27354 
27355   if (args && TREE_CODE (args) != TREE_VEC)
27356     {
27357       if (tree ti = get_template_info (args))
27358 	args = TI_ARGS (ti);
27359       else
27360 	args = NULL_TREE;
27361     }
27362 
27363   if (!args)
27364     return false;
27365 
27366   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
27367     {
27368       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
27369       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
27370 	if (error_operand_p (TREE_VEC_ELT (level, j)))
27371 	  return true;
27372     }
27373 
27374   return false;
27375 }
27376 
27377 /* Returns TRUE if the template TMPL is type-dependent.  */
27378 
27379 bool
dependent_template_p(tree tmpl)27380 dependent_template_p (tree tmpl)
27381 {
27382   if (TREE_CODE (tmpl) == OVERLOAD)
27383     {
27384       for (lkp_iterator iter (tmpl); iter; ++iter)
27385 	if (dependent_template_p (*iter))
27386 	  return true;
27387       return false;
27388     }
27389 
27390   /* Template template parameters are dependent.  */
27391   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
27392       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
27393     return true;
27394   /* So are names that have not been looked up.  */
27395   if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
27396     return true;
27397   return false;
27398 }
27399 
27400 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
27401 
27402 bool
dependent_template_id_p(tree tmpl,tree args)27403 dependent_template_id_p (tree tmpl, tree args)
27404 {
27405   return (dependent_template_p (tmpl)
27406 	  || any_dependent_template_arguments_p (args));
27407 }
27408 
27409 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
27410    are dependent.  */
27411 
27412 bool
dependent_omp_for_p(tree declv,tree initv,tree condv,tree incrv)27413 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
27414 {
27415   int i;
27416 
27417   if (!processing_template_decl)
27418     return false;
27419 
27420   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
27421     {
27422       tree decl = TREE_VEC_ELT (declv, i);
27423       tree init = TREE_VEC_ELT (initv, i);
27424       tree cond = TREE_VEC_ELT (condv, i);
27425       tree incr = TREE_VEC_ELT (incrv, i);
27426 
27427       if (type_dependent_expression_p (decl)
27428 	  || TREE_CODE (decl) == SCOPE_REF)
27429 	return true;
27430 
27431       if (init && type_dependent_expression_p (init))
27432 	return true;
27433 
27434       if (cond == global_namespace)
27435 	return true;
27436 
27437       if (type_dependent_expression_p (cond))
27438 	return true;
27439 
27440       if (COMPARISON_CLASS_P (cond)
27441 	  && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
27442 	      || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
27443 	return true;
27444 
27445       if (TREE_CODE (incr) == MODOP_EXPR)
27446 	{
27447 	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
27448 	      || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
27449 	    return true;
27450 	}
27451       else if (type_dependent_expression_p (incr))
27452 	return true;
27453       else if (TREE_CODE (incr) == MODIFY_EXPR)
27454 	{
27455 	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
27456 	    return true;
27457 	  else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
27458 	    {
27459 	      tree t = TREE_OPERAND (incr, 1);
27460 	      if (type_dependent_expression_p (TREE_OPERAND (t, 0))
27461 		  || type_dependent_expression_p (TREE_OPERAND (t, 1)))
27462 		return true;
27463 
27464 	      /* If this loop has a class iterator with != comparison
27465 		 with increment other than i++/++i/i--/--i, make sure the
27466 		 increment is constant.  */
27467 	      if (CLASS_TYPE_P (TREE_TYPE (decl))
27468 		  && TREE_CODE (cond) == NE_EXPR)
27469 		{
27470 		  if (TREE_OPERAND (t, 0) == decl)
27471 		    t = TREE_OPERAND (t, 1);
27472 		  else
27473 		    t = TREE_OPERAND (t, 0);
27474 		  if (TREE_CODE (t) != INTEGER_CST)
27475 		    return true;
27476 		}
27477 	    }
27478 	}
27479     }
27480 
27481   return false;
27482 }
27483 
27484 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
27485    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
27486    no such TYPE can be found.  Note that this function peers inside
27487    uninstantiated templates and therefore should be used only in
27488    extremely limited situations.  ONLY_CURRENT_P restricts this
27489    peering to the currently open classes hierarchy (which is required
27490    when comparing types).  */
27491 
27492 tree
resolve_typename_type(tree type,bool only_current_p)27493 resolve_typename_type (tree type, bool only_current_p)
27494 {
27495   tree scope;
27496   tree name;
27497   tree decl;
27498   int quals;
27499   tree pushed_scope;
27500   tree result;
27501 
27502   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
27503 
27504   scope = TYPE_CONTEXT (type);
27505   /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope.  */
27506   gcc_checking_assert (uses_template_parms (scope));
27507 
27508   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
27509      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
27510      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
27511      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
27512      identifier  of the TYPENAME_TYPE anymore.
27513      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
27514      TYPENAME_TYPE instead, we avoid messing up with a possible
27515      typedef variant case.  */
27516   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
27517 
27518   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
27519      it first before we can figure out what NAME refers to.  */
27520   if (TREE_CODE (scope) == TYPENAME_TYPE)
27521     {
27522       if (TYPENAME_IS_RESOLVING_P (scope))
27523 	/* Given a class template A with a dependent base with nested type C,
27524 	   typedef typename A::C::C C will land us here, as trying to resolve
27525 	   the initial A::C leads to the local C typedef, which leads back to
27526 	   A::C::C.  So we break the recursion now.  */
27527 	return type;
27528       else
27529 	scope = resolve_typename_type (scope, only_current_p);
27530     }
27531   /* If we don't know what SCOPE refers to, then we cannot resolve the
27532      TYPENAME_TYPE.  */
27533   if (!CLASS_TYPE_P (scope))
27534     return type;
27535   /* If this is a typedef, we don't want to look inside (c++/11987).  */
27536   if (typedef_variant_p (type))
27537     return type;
27538   /* If SCOPE isn't the template itself, it will not have a valid
27539      TYPE_FIELDS list.  */
27540   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
27541     /* scope is either the template itself or a compatible instantiation
27542        like X<T>, so look up the name in the original template.  */
27543     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
27544   /* If scope has no fields, it can't be a current instantiation.  Check this
27545      before currently_open_class to avoid infinite recursion (71515).  */
27546   if (!TYPE_FIELDS (scope))
27547     return type;
27548   /* If the SCOPE is not the current instantiation, there's no reason
27549      to look inside it.  */
27550   if (only_current_p && !currently_open_class (scope))
27551     return type;
27552   /* Enter the SCOPE so that name lookup will be resolved as if we
27553      were in the class definition.  In particular, SCOPE will no
27554      longer be considered a dependent type.  */
27555   pushed_scope = push_scope (scope);
27556   /* Look up the declaration.  */
27557   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
27558 			tf_warning_or_error);
27559 
27560   result = NULL_TREE;
27561 
27562   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
27563      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
27564   tree fullname = TYPENAME_TYPE_FULLNAME (type);
27565   if (!decl)
27566     /*nop*/;
27567   else if (identifier_p (fullname)
27568 	   && TREE_CODE (decl) == TYPE_DECL)
27569     {
27570       result = TREE_TYPE (decl);
27571       if (result == error_mark_node)
27572 	result = NULL_TREE;
27573     }
27574   else if (TREE_CODE (fullname) == TEMPLATE_ID_EXPR
27575 	   && DECL_CLASS_TEMPLATE_P (decl))
27576     {
27577       /* Obtain the template and the arguments.  */
27578       tree tmpl = TREE_OPERAND (fullname, 0);
27579       if (TREE_CODE (tmpl) == IDENTIFIER_NODE)
27580 	{
27581 	  /* We get here with a plain identifier because a previous tentative
27582 	     parse of the nested-name-specifier as part of a ptr-operator saw
27583 	     ::template X<A>.  The use of ::template is necessary in a
27584 	     ptr-operator, but wrong in a declarator-id.
27585 
27586 	     [temp.names]: In a qualified-id of a declarator-id, the keyword
27587 	     template shall not appear at the top level.  */
27588 	  pedwarn (cp_expr_loc_or_input_loc (fullname), OPT_Wpedantic,
27589 		   "keyword %<template%> not allowed in declarator-id");
27590 	  tmpl = decl;
27591 	}
27592       tree args = TREE_OPERAND (fullname, 1);
27593       /* Instantiate the template.  */
27594       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
27595 				      /*entering_scope=*/true,
27596 				      tf_error | tf_user);
27597       if (result == error_mark_node)
27598 	result = NULL_TREE;
27599     }
27600 
27601   /* Leave the SCOPE.  */
27602   if (pushed_scope)
27603     pop_scope (pushed_scope);
27604 
27605   /* If we failed to resolve it, return the original typename.  */
27606   if (!result)
27607     return type;
27608 
27609   /* If lookup found a typename type, resolve that too.  */
27610   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
27611     {
27612       /* Ill-formed programs can cause infinite recursion here, so we
27613 	 must catch that.  */
27614       TYPENAME_IS_RESOLVING_P (result) = 1;
27615       result = resolve_typename_type (result, only_current_p);
27616       TYPENAME_IS_RESOLVING_P (result) = 0;
27617     }
27618 
27619   /* Qualify the resulting type.  */
27620   quals = cp_type_quals (type);
27621   if (quals)
27622     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
27623 
27624   return result;
27625 }
27626 
27627 /* EXPR is an expression which is not type-dependent.  Return a proxy
27628    for EXPR that can be used to compute the types of larger
27629    expressions containing EXPR.  */
27630 
27631 tree
build_non_dependent_expr(tree expr)27632 build_non_dependent_expr (tree expr)
27633 {
27634   tree orig_expr = expr;
27635   tree inner_expr;
27636 
27637   /* When checking, try to get a constant value for all non-dependent
27638      expressions in order to expose bugs in *_dependent_expression_p
27639      and constexpr.  This can affect code generation, see PR70704, so
27640      only do this for -fchecking=2.  */
27641   if (flag_checking > 1
27642       && cxx_dialect >= cxx11
27643       /* Don't do this during nsdmi parsing as it can lead to
27644 	 unexpected recursive instantiations.  */
27645       && !parsing_nsdmi ()
27646       /* Don't do this during concept processing either and for
27647          the same reason.  */
27648       && !processing_constraint_expression_p ())
27649     fold_non_dependent_expr (expr, tf_none);
27650 
27651   STRIP_ANY_LOCATION_WRAPPER (expr);
27652 
27653   /* Preserve OVERLOADs; the functions must be available to resolve
27654      types.  */
27655   inner_expr = expr;
27656   if (TREE_CODE (inner_expr) == STMT_EXPR)
27657     inner_expr = stmt_expr_value_expr (inner_expr);
27658   if (TREE_CODE (inner_expr) == ADDR_EXPR)
27659     inner_expr = TREE_OPERAND (inner_expr, 0);
27660   if (TREE_CODE (inner_expr) == COMPONENT_REF)
27661     inner_expr = TREE_OPERAND (inner_expr, 1);
27662   if (is_overloaded_fn (inner_expr)
27663       || TREE_CODE (inner_expr) == OFFSET_REF)
27664     return orig_expr;
27665   /* There is no need to return a proxy for a variable or enumerator.  */
27666   if (VAR_P (expr) || TREE_CODE (expr) == CONST_DECL)
27667     return orig_expr;
27668   /* Preserve string constants; conversions from string constants to
27669      "char *" are allowed, even though normally a "const char *"
27670      cannot be used to initialize a "char *".  */
27671   if (TREE_CODE (expr) == STRING_CST)
27672     return orig_expr;
27673   /* Preserve void and arithmetic constants, as an optimization -- there is no
27674      reason to create a new node.  */
27675   if (TREE_CODE (expr) == VOID_CST
27676       || TREE_CODE (expr) == INTEGER_CST
27677       || TREE_CODE (expr) == REAL_CST)
27678     return orig_expr;
27679   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
27680      There is at least one place where we want to know that a
27681      particular expression is a throw-expression: when checking a ?:
27682      expression, there are special rules if the second or third
27683      argument is a throw-expression.  */
27684   if (TREE_CODE (expr) == THROW_EXPR)
27685     return orig_expr;
27686 
27687   /* Don't wrap an initializer list, we need to be able to look inside.  */
27688   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
27689     return orig_expr;
27690 
27691   /* Don't wrap a dummy object, we need to be able to test for it.  */
27692   if (is_dummy_object (expr))
27693     return orig_expr;
27694 
27695   if (TREE_CODE (expr) == COND_EXPR)
27696     return build3 (COND_EXPR,
27697 		   TREE_TYPE (expr),
27698 		   build_non_dependent_expr (TREE_OPERAND (expr, 0)),
27699 		   (TREE_OPERAND (expr, 1)
27700 		    ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
27701 		    : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
27702 		   build_non_dependent_expr (TREE_OPERAND (expr, 2)));
27703   if (TREE_CODE (expr) == COMPOUND_EXPR
27704       && !COMPOUND_EXPR_OVERLOADED (expr))
27705     return build2 (COMPOUND_EXPR,
27706 		   TREE_TYPE (expr),
27707 		   TREE_OPERAND (expr, 0),
27708 		   build_non_dependent_expr (TREE_OPERAND (expr, 1)));
27709 
27710   /* If the type is unknown, it can't really be non-dependent */
27711   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
27712 
27713   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
27714   return build1_loc (EXPR_LOCATION (orig_expr), NON_DEPENDENT_EXPR,
27715 		     TREE_TYPE (expr), expr);
27716 }
27717 
27718 /* ARGS is a vector of expressions as arguments to a function call.
27719    Replace the arguments with equivalent non-dependent expressions.
27720    This modifies ARGS in place.  */
27721 
27722 void
make_args_non_dependent(vec<tree,va_gc> * args)27723 make_args_non_dependent (vec<tree, va_gc> *args)
27724 {
27725   unsigned int ix;
27726   tree arg;
27727 
27728   FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
27729     {
27730       tree newarg = build_non_dependent_expr (arg);
27731       if (newarg != arg)
27732 	(*args)[ix] = newarg;
27733     }
27734 }
27735 
27736 /* Returns a type which represents 'auto' or 'decltype(auto)'.  We use a
27737    TEMPLATE_TYPE_PARM with a level one deeper than the actual template
27738    parms.  If set_canonical is true, we set TYPE_CANONICAL on it.  */
27739 
27740 static tree
make_auto_1(tree name,bool set_canonical)27741 make_auto_1 (tree name, bool set_canonical)
27742 {
27743   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
27744   TYPE_NAME (au) = build_decl (input_location, TYPE_DECL, name, au);
27745   TYPE_STUB_DECL (au) = TYPE_NAME (au);
27746   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
27747     (0, processing_template_decl + 1, processing_template_decl + 1,
27748      TYPE_NAME (au), NULL_TREE);
27749   if (set_canonical)
27750     TYPE_CANONICAL (au) = canonical_type_parameter (au);
27751   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
27752   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
27753   if (name == decltype_auto_identifier)
27754     AUTO_IS_DECLTYPE (au) = true;
27755 
27756   return au;
27757 }
27758 
27759 tree
make_decltype_auto(void)27760 make_decltype_auto (void)
27761 {
27762   return make_auto_1 (decltype_auto_identifier, true);
27763 }
27764 
27765 tree
make_auto(void)27766 make_auto (void)
27767 {
27768   return make_auto_1 (auto_identifier, true);
27769 }
27770 
27771 /* Return a C++17 deduction placeholder for class template TMPL.  */
27772 
27773 tree
make_template_placeholder(tree tmpl)27774 make_template_placeholder (tree tmpl)
27775 {
27776   tree t = make_auto_1 (auto_identifier, false);
27777   CLASS_PLACEHOLDER_TEMPLATE (t) = tmpl;
27778   /* Our canonical type depends on the placeholder.  */
27779   TYPE_CANONICAL (t) = canonical_type_parameter (t);
27780   return t;
27781 }
27782 
27783 /* True iff T is a C++17 class template deduction placeholder.  */
27784 
27785 bool
template_placeholder_p(tree t)27786 template_placeholder_p (tree t)
27787 {
27788   return is_auto (t) && CLASS_PLACEHOLDER_TEMPLATE (t);
27789 }
27790 
27791 /* Make a "constrained auto" type-specifier. This is an auto or
27792   decltype(auto) type with constraints that must be associated after
27793   deduction.  The constraint is formed from the given concept CON
27794   and its optional sequence of template arguments ARGS.
27795 
27796   TYPE must be the result of make_auto_type or make_decltype_auto_type. */
27797 
27798 static tree
make_constrained_placeholder_type(tree type,tree con,tree args)27799 make_constrained_placeholder_type (tree type, tree con, tree args)
27800 {
27801   /* Build the constraint. */
27802   tree tmpl = DECL_TI_TEMPLATE (con);
27803   tree expr = tmpl;
27804   if (TREE_CODE (con) == FUNCTION_DECL)
27805     expr = ovl_make (tmpl);
27806   expr = build_concept_check (expr, type, args, tf_warning_or_error);
27807 
27808   PLACEHOLDER_TYPE_CONSTRAINTS (type) = expr;
27809 
27810   /* Our canonical type depends on the constraint.  */
27811   TYPE_CANONICAL (type) = canonical_type_parameter (type);
27812 
27813   /* Attach the constraint to the type declaration. */
27814   return TYPE_NAME (type);
27815 }
27816 
27817 /* Make a "constrained auto" type-specifier.  */
27818 
27819 tree
make_constrained_auto(tree con,tree args)27820 make_constrained_auto (tree con, tree args)
27821 {
27822   tree type = make_auto_1 (auto_identifier, false);
27823   return make_constrained_placeholder_type (type, con, args);
27824 }
27825 
27826 /* Make a "constrained decltype(auto)" type-specifier.  */
27827 
27828 tree
make_constrained_decltype_auto(tree con,tree args)27829 make_constrained_decltype_auto (tree con, tree args)
27830 {
27831   tree type = make_auto_1 (decltype_auto_identifier, false);
27832   return make_constrained_placeholder_type (type, con, args);
27833 }
27834 
27835 /* Build and return a concept definition. Like other templates, the
27836    CONCEPT_DECL node is wrapped by a TEMPLATE_DECL.  This returns the
27837    the TEMPLATE_DECL. */
27838 
27839 tree
finish_concept_definition(cp_expr id,tree init)27840 finish_concept_definition (cp_expr id, tree init)
27841 {
27842   gcc_assert (identifier_p (id));
27843   gcc_assert (processing_template_decl);
27844 
27845   location_t loc = id.get_location();
27846 
27847   /* A concept-definition shall not have associated constraints.  */
27848   if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
27849     {
27850       error_at (loc, "a concept cannot be constrained");
27851       TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
27852     }
27853 
27854   /* A concept-definition shall appear in namespace scope.  Templates
27855      aren't allowed in block scope, so we only need to check for class
27856      scope.  */
27857   if (TYPE_P (current_scope()) || !DECL_NAMESPACE_SCOPE_P (current_scope ()))
27858     {
27859       error_at (loc, "concept %qE not in namespace scope", *id);
27860       return error_mark_node;
27861     }
27862 
27863   /* Initially build the concept declaration; it's type is bool.  */
27864   tree decl = build_lang_decl_loc (loc, CONCEPT_DECL, *id, boolean_type_node);
27865   DECL_CONTEXT (decl) = current_scope ();
27866   DECL_INITIAL (decl) = init;
27867 
27868   /* Push the enclosing template.  */
27869   return push_template_decl (decl);
27870 }
27871 
27872 /* Given type ARG, return std::initializer_list<ARG>.  */
27873 
27874 static tree
listify(tree arg)27875 listify (tree arg)
27876 {
27877   tree std_init_list = get_namespace_binding (std_node, init_list_identifier);
27878 
27879   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
27880     {
27881       gcc_rich_location richloc (input_location);
27882       maybe_add_include_fixit (&richloc, "<initializer_list>", false);
27883       error_at (&richloc,
27884 		"deducing from brace-enclosed initializer list"
27885 		" requires %<#include <initializer_list>%>");
27886 
27887       return error_mark_node;
27888     }
27889   tree argvec = make_tree_vec (1);
27890   TREE_VEC_ELT (argvec, 0) = arg;
27891 
27892   return lookup_template_class (std_init_list, argvec, NULL_TREE,
27893 				NULL_TREE, 0, tf_warning_or_error);
27894 }
27895 
27896 /* Replace auto in TYPE with std::initializer_list<auto>.  */
27897 
27898 static tree
listify_autos(tree type,tree auto_node)27899 listify_autos (tree type, tree auto_node)
27900 {
27901   tree init_auto = listify (strip_top_quals (auto_node));
27902   tree argvec = make_tree_vec (1);
27903   TREE_VEC_ELT (argvec, 0) = init_auto;
27904   if (processing_template_decl)
27905     argvec = add_to_template_args (current_template_args (), argvec);
27906   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
27907 }
27908 
27909 /* Hash traits for hashing possibly constrained 'auto'
27910    TEMPLATE_TYPE_PARMs for use by do_auto_deduction.  */
27911 
27912 struct auto_hash : default_hash_traits<tree>
27913 {
27914   static inline hashval_t hash (tree);
27915   static inline bool equal (tree, tree);
27916 };
27917 
27918 /* Hash the 'auto' T.  */
27919 
27920 inline hashval_t
hash(tree t)27921 auto_hash::hash (tree t)
27922 {
27923   if (tree c = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (t)))
27924     /* Matching constrained-type-specifiers denote the same template
27925        parameter, so hash the constraint.  */
27926     return hash_placeholder_constraint (c);
27927   else
27928     /* But unconstrained autos are all separate, so just hash the pointer.  */
27929     return iterative_hash_object (t, 0);
27930 }
27931 
27932 /* Compare two 'auto's.  */
27933 
27934 inline bool
equal(tree t1,tree t2)27935 auto_hash::equal (tree t1, tree t2)
27936 {
27937   if (t1 == t2)
27938     return true;
27939 
27940   tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
27941   tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
27942 
27943   /* Two unconstrained autos are distinct.  */
27944   if (!c1 || !c2)
27945     return false;
27946 
27947   return equivalent_placeholder_constraints (c1, c2);
27948 }
27949 
27950 /* for_each_template_parm callback for extract_autos: if t is a (possibly
27951    constrained) auto, add it to the vector.  */
27952 
27953 static int
extract_autos_r(tree t,void * data)27954 extract_autos_r (tree t, void *data)
27955 {
27956   hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
27957   if (is_auto (t))
27958     {
27959       /* All the autos were built with index 0; fix that up now.  */
27960       tree *p = hash.find_slot (t, INSERT);
27961       unsigned idx;
27962       if (*p)
27963 	/* If this is a repeated constrained-type-specifier, use the index we
27964 	   chose before.  */
27965 	idx = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (*p));
27966       else
27967 	{
27968 	  /* Otherwise this is new, so use the current count.  */
27969 	  *p = t;
27970 	  idx = hash.elements () - 1;
27971 	}
27972       TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (t)) = idx;
27973     }
27974 
27975   /* Always keep walking.  */
27976   return 0;
27977 }
27978 
27979 /* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
27980    says they can appear anywhere in the type.  */
27981 
27982 static tree
extract_autos(tree type)27983 extract_autos (tree type)
27984 {
27985   hash_set<tree> visited;
27986   hash_table<auto_hash> hash (2);
27987 
27988   for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
27989 
27990   tree tree_vec = make_tree_vec (hash.elements());
27991   for (hash_table<auto_hash>::iterator iter = hash.begin();
27992        iter != hash.end(); ++iter)
27993     {
27994       tree elt = *iter;
27995       unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
27996       TREE_VEC_ELT (tree_vec, i)
27997 	= build_tree_list (NULL_TREE, TYPE_NAME (elt));
27998     }
27999 
28000   return tree_vec;
28001 }
28002 
28003 /* The stem for deduction guide names.  */
28004 const char *const dguide_base = "__dguide_";
28005 
28006 /* Return the name for a deduction guide for class template TMPL.  */
28007 
28008 tree
dguide_name(tree tmpl)28009 dguide_name (tree tmpl)
28010 {
28011   tree type = (TYPE_P (tmpl) ? tmpl : TREE_TYPE (tmpl));
28012   tree tname = TYPE_IDENTIFIER (type);
28013   char *buf = (char *) alloca (1 + strlen (dguide_base)
28014 			       + IDENTIFIER_LENGTH (tname));
28015   memcpy (buf, dguide_base, strlen (dguide_base));
28016   memcpy (buf + strlen (dguide_base), IDENTIFIER_POINTER (tname),
28017 	  IDENTIFIER_LENGTH (tname) + 1);
28018   tree dname = get_identifier (buf);
28019   TREE_TYPE (dname) = type;
28020   return dname;
28021 }
28022 
28023 /* True if NAME is the name of a deduction guide.  */
28024 
28025 bool
dguide_name_p(tree name)28026 dguide_name_p (tree name)
28027 {
28028   return (TREE_CODE (name) == IDENTIFIER_NODE
28029 	  && TREE_TYPE (name)
28030 	  && !strncmp (IDENTIFIER_POINTER (name), dguide_base,
28031 		       strlen (dguide_base)));
28032 }
28033 
28034 /* True if FN is a deduction guide.  */
28035 
28036 bool
deduction_guide_p(const_tree fn)28037 deduction_guide_p (const_tree fn)
28038 {
28039   if (DECL_P (fn))
28040     if (tree name = DECL_NAME (fn))
28041       return dguide_name_p (name);
28042   return false;
28043 }
28044 
28045 /* True if FN is the copy deduction guide, i.e. A(A)->A.  */
28046 
28047 bool
copy_guide_p(const_tree fn)28048 copy_guide_p (const_tree fn)
28049 {
28050   gcc_assert (deduction_guide_p (fn));
28051   if (!DECL_ARTIFICIAL (fn))
28052     return false;
28053   tree parms = FUNCTION_FIRST_USER_PARMTYPE (DECL_TI_TEMPLATE (fn));
28054   return (TREE_CHAIN (parms) == void_list_node
28055 	  && same_type_p (TREE_VALUE (parms), TREE_TYPE (DECL_NAME (fn))));
28056 }
28057 
28058 /* True if FN is a guide generated from a constructor template.  */
28059 
28060 bool
template_guide_p(const_tree fn)28061 template_guide_p (const_tree fn)
28062 {
28063   gcc_assert (deduction_guide_p (fn));
28064   if (!DECL_ARTIFICIAL (fn))
28065     return false;
28066   tree tmpl = DECL_TI_TEMPLATE (fn);
28067   if (tree org = DECL_ABSTRACT_ORIGIN (tmpl))
28068     return PRIMARY_TEMPLATE_P (org);
28069   return false;
28070 }
28071 
28072 /* OLDDECL is a _DECL for a template parameter.  Return a similar parameter at
28073    LEVEL:INDEX, using tsubst_args and complain for substitution into non-type
28074    template parameter types.  Note that the handling of template template
28075    parameters relies on current_template_parms being set appropriately for the
28076    new template.  */
28077 
28078 static tree
rewrite_template_parm(tree olddecl,unsigned index,unsigned level,tree tsubst_args,tsubst_flags_t complain)28079 rewrite_template_parm (tree olddecl, unsigned index, unsigned level,
28080 		       tree tsubst_args, tsubst_flags_t complain)
28081 {
28082   if (olddecl == error_mark_node)
28083     return error_mark_node;
28084 
28085   tree oldidx = get_template_parm_index (olddecl);
28086 
28087   tree newtype;
28088   if (TREE_CODE (olddecl) == TYPE_DECL
28089       || TREE_CODE (olddecl) == TEMPLATE_DECL)
28090     {
28091       tree oldtype = TREE_TYPE (olddecl);
28092       newtype = cxx_make_type (TREE_CODE (oldtype));
28093       TYPE_MAIN_VARIANT (newtype) = newtype;
28094       if (TREE_CODE (oldtype) == TEMPLATE_TYPE_PARM)
28095 	TEMPLATE_TYPE_PARM_FOR_CLASS (newtype)
28096 	  = TEMPLATE_TYPE_PARM_FOR_CLASS (oldtype);
28097     }
28098   else
28099     {
28100       newtype = TREE_TYPE (olddecl);
28101       if (type_uses_auto (newtype))
28102 	{
28103 	  // Substitute once to fix references to other template parameters.
28104 	  newtype = tsubst (newtype, tsubst_args,
28105 			    complain|tf_partial, NULL_TREE);
28106 	  // Now substitute again to reduce the level of the auto.
28107 	  newtype = tsubst (newtype, current_template_args (),
28108 			    complain, NULL_TREE);
28109 	}
28110       else
28111 	newtype = tsubst (newtype, tsubst_args,
28112 			  complain, NULL_TREE);
28113     }
28114 
28115   tree newdecl
28116     = build_decl (DECL_SOURCE_LOCATION (olddecl), TREE_CODE (olddecl),
28117 		  DECL_NAME (olddecl), newtype);
28118   SET_DECL_TEMPLATE_PARM_P (newdecl);
28119 
28120   tree newidx;
28121   if (TREE_CODE (olddecl) == TYPE_DECL
28122       || TREE_CODE (olddecl) == TEMPLATE_DECL)
28123     {
28124       newidx = TEMPLATE_TYPE_PARM_INDEX (newtype)
28125 	= build_template_parm_index (index, level, level,
28126 				     newdecl, newtype);
28127       TEMPLATE_PARM_PARAMETER_PACK (newidx)
28128 	= TEMPLATE_PARM_PARAMETER_PACK (oldidx);
28129       TYPE_STUB_DECL (newtype) = TYPE_NAME (newtype) = newdecl;
28130       if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (olddecl)))
28131 	SET_TYPE_STRUCTURAL_EQUALITY (newtype);
28132       else
28133 	TYPE_CANONICAL (newtype) = canonical_type_parameter (newtype);
28134 
28135       if (TREE_CODE (olddecl) == TEMPLATE_DECL)
28136 	{
28137 	  DECL_TEMPLATE_RESULT (newdecl)
28138 	    = build_decl (DECL_SOURCE_LOCATION (olddecl), TYPE_DECL,
28139 			  DECL_NAME (olddecl), newtype);
28140 	  DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (newdecl)) = true;
28141 	  // First create a copy (ttargs) of tsubst_args with an
28142 	  // additional level for the template template parameter's own
28143 	  // template parameters (ttparms).
28144 	  tree ttparms = (INNERMOST_TEMPLATE_PARMS
28145 			  (DECL_TEMPLATE_PARMS (olddecl)));
28146 	  const int depth = TMPL_ARGS_DEPTH (tsubst_args);
28147 	  tree ttargs = make_tree_vec (depth + 1);
28148 	  for (int i = 0; i < depth; ++i)
28149 	    TREE_VEC_ELT (ttargs, i) = TREE_VEC_ELT (tsubst_args, i);
28150 	  TREE_VEC_ELT (ttargs, depth)
28151 	    = template_parms_level_to_args (ttparms);
28152 	  // Substitute ttargs into ttparms to fix references to
28153 	  // other template parameters.
28154 	  ttparms = tsubst_template_parms_level (ttparms, ttargs,
28155 						 complain|tf_partial);
28156 	  // Now substitute again with args based on tparms, to reduce
28157 	  // the level of the ttparms.
28158 	  ttargs = current_template_args ();
28159 	  ttparms = tsubst_template_parms_level (ttparms, ttargs,
28160 						 complain);
28161 	  // Finally, tack the adjusted parms onto tparms.
28162 	  ttparms = tree_cons (size_int (depth), ttparms,
28163 			       current_template_parms);
28164 	  DECL_TEMPLATE_PARMS (newdecl) = ttparms;
28165 	}
28166     }
28167   else
28168     {
28169       tree oldconst = TEMPLATE_PARM_DECL (oldidx);
28170       tree newconst
28171 	= build_decl (DECL_SOURCE_LOCATION (oldconst),
28172 		      TREE_CODE (oldconst),
28173 		      DECL_NAME (oldconst), newtype);
28174       TREE_CONSTANT (newconst) = TREE_CONSTANT (newdecl)
28175 	= TREE_READONLY (newconst) = TREE_READONLY (newdecl) = true;
28176       SET_DECL_TEMPLATE_PARM_P (newconst);
28177       newidx = build_template_parm_index (index, level, level,
28178 					  newconst, newtype);
28179       TEMPLATE_PARM_PARAMETER_PACK (newidx)
28180 	= TEMPLATE_PARM_PARAMETER_PACK (oldidx);
28181       DECL_INITIAL (newdecl) = DECL_INITIAL (newconst) = newidx;
28182     }
28183 
28184   return newdecl;
28185 }
28186 
28187 /* As rewrite_template_parm, but for the whole TREE_LIST representing a
28188    template parameter.  */
28189 
28190 static tree
rewrite_tparm_list(tree oldelt,unsigned index,unsigned level,tree targs,unsigned targs_index,tsubst_flags_t complain)28191 rewrite_tparm_list (tree oldelt, unsigned index, unsigned level,
28192 		    tree targs, unsigned targs_index, tsubst_flags_t complain)
28193 {
28194   tree olddecl = TREE_VALUE (oldelt);
28195   tree newdecl = rewrite_template_parm (olddecl, index, level,
28196 					targs, complain);
28197   if (newdecl == error_mark_node)
28198     return error_mark_node;
28199   tree newdef = tsubst_template_arg (TREE_PURPOSE (oldelt),
28200 				     targs, complain, NULL_TREE);
28201   tree list = build_tree_list (newdef, newdecl);
28202   TEMPLATE_PARM_CONSTRAINTS (list)
28203     = tsubst_constraint_info (TEMPLATE_PARM_CONSTRAINTS (oldelt),
28204 			      targs, complain, NULL_TREE);
28205   int depth = TMPL_ARGS_DEPTH (targs);
28206   TMPL_ARG (targs, depth, targs_index) = template_parm_to_arg (list);
28207   return list;
28208 }
28209 
28210 /* Returns a C++17 class deduction guide template based on the constructor
28211    CTOR.  As a special case, CTOR can be a RECORD_TYPE for an implicit default
28212    guide, REFERENCE_TYPE for an implicit copy/move guide, or TREE_LIST for an
28213    aggregate initialization guide.  */
28214 
28215 static tree
build_deduction_guide(tree type,tree ctor,tree outer_args,tsubst_flags_t complain)28216 build_deduction_guide (tree type, tree ctor, tree outer_args, tsubst_flags_t complain)
28217 {
28218   tree tparms, targs, fparms, fargs, ci;
28219   bool memtmpl = false;
28220   bool explicit_p;
28221   location_t loc;
28222   tree fn_tmpl = NULL_TREE;
28223 
28224   if (outer_args)
28225     {
28226       ++processing_template_decl;
28227       type = tsubst (type, outer_args, complain, CLASSTYPE_TI_TEMPLATE (type));
28228       --processing_template_decl;
28229     }
28230 
28231   if (!DECL_DECLARES_FUNCTION_P (ctor))
28232     {
28233       if (TYPE_P (ctor))
28234 	{
28235 	  bool copy_p = TYPE_REF_P (ctor);
28236 	  if (copy_p)
28237 	    fparms = tree_cons (NULL_TREE, type, void_list_node);
28238 	  else
28239 	    fparms = void_list_node;
28240 	}
28241       else if (TREE_CODE (ctor) == TREE_LIST)
28242 	fparms = ctor;
28243       else
28244 	gcc_unreachable ();
28245 
28246       tree ctmpl = CLASSTYPE_TI_TEMPLATE (type);
28247       tparms = DECL_TEMPLATE_PARMS (ctmpl);
28248       targs = CLASSTYPE_TI_ARGS (type);
28249       ci = NULL_TREE;
28250       fargs = NULL_TREE;
28251       loc = DECL_SOURCE_LOCATION (ctmpl);
28252       explicit_p = false;
28253     }
28254   else
28255     {
28256       ++processing_template_decl;
28257       bool ok = true;
28258 
28259       fn_tmpl
28260 	= (TREE_CODE (ctor) == TEMPLATE_DECL ? ctor
28261 	   : DECL_TI_TEMPLATE (ctor));
28262       if (outer_args)
28263 	fn_tmpl = tsubst (fn_tmpl, outer_args, complain, ctor);
28264       ctor = DECL_TEMPLATE_RESULT (fn_tmpl);
28265 
28266       tparms = DECL_TEMPLATE_PARMS (fn_tmpl);
28267       /* If type is a member class template, DECL_TI_ARGS (ctor) will have
28268 	 fully specialized args for the enclosing class.  Strip those off, as
28269 	 the deduction guide won't have those template parameters.  */
28270       targs = get_innermost_template_args (DECL_TI_ARGS (ctor),
28271 						TMPL_PARMS_DEPTH (tparms));
28272       /* Discard the 'this' parameter.  */
28273       fparms = FUNCTION_ARG_CHAIN (ctor);
28274       fargs = TREE_CHAIN (DECL_ARGUMENTS (ctor));
28275       ci = get_constraints (ctor);
28276       loc = DECL_SOURCE_LOCATION (ctor);
28277       explicit_p = DECL_NONCONVERTING_P (ctor);
28278 
28279       if (PRIMARY_TEMPLATE_P (fn_tmpl))
28280 	{
28281 	  memtmpl = true;
28282 
28283 	  /* For a member template constructor, we need to flatten the two
28284 	     template parameter lists into one, and then adjust the function
28285 	     signature accordingly.  This gets...complicated.  */
28286 	  tree save_parms = current_template_parms;
28287 
28288 	  /* For a member template we should have two levels of parms/args, one
28289 	     for the class and one for the constructor.  We stripped
28290 	     specialized args for further enclosing classes above.  */
28291 	  const int depth = 2;
28292 	  gcc_assert (TMPL_ARGS_DEPTH (targs) == depth);
28293 
28294 	  /* Template args for translating references to the two-level template
28295 	     parameters into references to the one-level template parameters we
28296 	     are creating.  */
28297 	  tree tsubst_args = copy_node (targs);
28298 	  TMPL_ARGS_LEVEL (tsubst_args, depth)
28299 	    = copy_node (TMPL_ARGS_LEVEL (tsubst_args, depth));
28300 
28301 	  /* Template parms for the constructor template.  */
28302 	  tree ftparms = TREE_VALUE (tparms);
28303 	  unsigned flen = TREE_VEC_LENGTH (ftparms);
28304 	  /* Template parms for the class template.  */
28305 	  tparms = TREE_CHAIN (tparms);
28306 	  tree ctparms = TREE_VALUE (tparms);
28307 	  unsigned clen = TREE_VEC_LENGTH (ctparms);
28308 	  /* Template parms for the deduction guide start as a copy of the
28309 	     template parms for the class.  We set current_template_parms for
28310 	     lookup_template_class_1.  */
28311 	  current_template_parms = tparms = copy_node (tparms);
28312 	  tree new_vec = TREE_VALUE (tparms) = make_tree_vec (flen + clen);
28313 	  for (unsigned i = 0; i < clen; ++i)
28314 	    TREE_VEC_ELT (new_vec, i) = TREE_VEC_ELT (ctparms, i);
28315 
28316 	  /* Now we need to rewrite the constructor parms to append them to the
28317 	     class parms.  */
28318 	  for (unsigned i = 0; i < flen; ++i)
28319 	    {
28320 	      unsigned index = i + clen;
28321 	      unsigned level = 1;
28322 	      tree oldelt = TREE_VEC_ELT (ftparms, i);
28323 	      tree newelt
28324 		= rewrite_tparm_list (oldelt, index, level,
28325 				      tsubst_args, i, complain);
28326 	      if (newelt == error_mark_node)
28327 		ok = false;
28328 	      TREE_VEC_ELT (new_vec, index) = newelt;
28329 	    }
28330 
28331 	  /* Now we have a final set of template parms to substitute into the
28332 	     function signature.  */
28333 	  targs = template_parms_to_args (tparms);
28334 	  fparms = tsubst_arg_types (fparms, tsubst_args, NULL_TREE,
28335 				     complain, ctor);
28336 	  if (fparms == error_mark_node)
28337 	    ok = false;
28338 	  if (ci)
28339 	    ci = tsubst_constraint_info (ci, tsubst_args, complain, ctor);
28340 
28341 	  /* Parms are to have DECL_CHAIN tsubsted, which would be skipped if
28342 	     cp_unevaluated_operand.  */
28343 	  cp_evaluated ev;
28344 	  fargs = tsubst (fargs, tsubst_args, complain, ctor);
28345 	  current_template_parms = save_parms;
28346 	}
28347 
28348       --processing_template_decl;
28349       if (!ok)
28350 	return error_mark_node;
28351     }
28352 
28353   if (!memtmpl)
28354     {
28355       /* Copy the parms so we can set DECL_PRIMARY_TEMPLATE.  */
28356       tparms = copy_node (tparms);
28357       INNERMOST_TEMPLATE_PARMS (tparms)
28358 	= copy_node (INNERMOST_TEMPLATE_PARMS (tparms));
28359     }
28360 
28361   tree fntype = build_function_type (type, fparms);
28362   tree ded_fn = build_lang_decl_loc (loc,
28363 				     FUNCTION_DECL,
28364 				     dguide_name (type), fntype);
28365   DECL_ARGUMENTS (ded_fn) = fargs;
28366   DECL_ARTIFICIAL (ded_fn) = true;
28367   DECL_NONCONVERTING_P (ded_fn) = explicit_p;
28368   tree ded_tmpl = build_template_decl (ded_fn, tparms, /*member*/false);
28369   DECL_ARTIFICIAL (ded_tmpl) = true;
28370   DECL_TEMPLATE_RESULT (ded_tmpl) = ded_fn;
28371   TREE_TYPE (ded_tmpl) = TREE_TYPE (ded_fn);
28372   DECL_TEMPLATE_INFO (ded_fn) = build_template_info (ded_tmpl, targs);
28373   DECL_PRIMARY_TEMPLATE (ded_tmpl) = ded_tmpl;
28374   if (DECL_P (ctor))
28375     DECL_ABSTRACT_ORIGIN (ded_tmpl) = fn_tmpl;
28376   if (ci)
28377     set_constraints (ded_tmpl, ci);
28378 
28379   return ded_tmpl;
28380 }
28381 
28382 /* Add to LIST the member types for the reshaped initializer CTOR.  */
28383 
28384 static tree
collect_ctor_idx_types(tree ctor,tree list)28385 collect_ctor_idx_types (tree ctor, tree list)
28386 {
28387   vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (ctor);
28388   tree idx, val; unsigned i;
28389   FOR_EACH_CONSTRUCTOR_ELT (v, i, idx, val)
28390     {
28391       if (BRACE_ENCLOSED_INITIALIZER_P (val)
28392 	  && CONSTRUCTOR_NELTS (val))
28393 	if (tree subidx = CONSTRUCTOR_ELT (val, 0)->index)
28394 	  if (TREE_CODE (subidx) == FIELD_DECL)
28395 	    {
28396 	      list = collect_ctor_idx_types (val, list);
28397 	      continue;
28398 	    }
28399       tree ftype = finish_decltype_type (idx, true, tf_none);
28400       list = tree_cons (NULL_TREE, ftype, list);
28401     }
28402 
28403   return list;
28404 }
28405 
28406 /* Return whether ETYPE is, or is derived from, a specialization of TMPL.  */
28407 
28408 static bool
is_spec_or_derived(tree etype,tree tmpl)28409 is_spec_or_derived (tree etype, tree tmpl)
28410 {
28411   if (!etype || !CLASS_TYPE_P (etype))
28412     return false;
28413 
28414   tree type = TREE_TYPE (tmpl);
28415   tree tparms = (INNERMOST_TEMPLATE_PARMS
28416 		 (DECL_TEMPLATE_PARMS (tmpl)));
28417   tree targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
28418   int err = unify (tparms, targs, type, etype,
28419 		   UNIFY_ALLOW_DERIVED, /*explain*/false);
28420   ggc_free (targs);
28421   return !err;
28422 }
28423 
28424 /* Return a C++20 aggregate deduction candidate for TYPE initialized from
28425    INIT.  */
28426 
28427 static tree
maybe_aggr_guide(tree tmpl,tree init,vec<tree,va_gc> * args)28428 maybe_aggr_guide (tree tmpl, tree init, vec<tree,va_gc> *args)
28429 {
28430   if (cxx_dialect < cxx2a)
28431     return NULL_TREE;
28432 
28433   if (init == NULL_TREE)
28434     return NULL_TREE;
28435 
28436   tree type = TREE_TYPE (tmpl);
28437   if (!CP_AGGREGATE_TYPE_P (type))
28438     return NULL_TREE;
28439 
28440   /* No aggregate candidate for copy-initialization.  */
28441   if (args->length() == 1)
28442     {
28443       tree val = (*args)[0];
28444       if (is_spec_or_derived (tmpl, TREE_TYPE (val)))
28445 	return NULL_TREE;
28446     }
28447 
28448   /* If we encounter a problem, we just won't add the candidate.  */
28449   tsubst_flags_t complain = tf_none;
28450 
28451   tree parms = NULL_TREE;
28452   if (BRACE_ENCLOSED_INITIALIZER_P (init))
28453     {
28454       init = reshape_init (type, init, complain);
28455       if (init == error_mark_node)
28456 	return NULL_TREE;
28457       parms = collect_ctor_idx_types (init, parms);
28458     }
28459   else if (TREE_CODE (init) == TREE_LIST)
28460     {
28461       int len = list_length (init);
28462       for (tree field = TYPE_FIELDS (type);
28463 	   len;
28464 	   --len, field = DECL_CHAIN (field))
28465 	{
28466 	  field = next_initializable_field (field);
28467 	  if (!field)
28468 	    return NULL_TREE;
28469 	  tree ftype = finish_decltype_type (field, true, complain);
28470 	  parms = tree_cons (NULL_TREE, ftype, parms);
28471 	}
28472     }
28473   else
28474     /* Aggregate initialization doesn't apply to an initializer expression.  */
28475     return NULL_TREE;
28476 
28477   if (parms)
28478     {
28479       tree last = parms;
28480       parms = nreverse (parms);
28481       TREE_CHAIN (last) = void_list_node;
28482       tree guide = build_deduction_guide (type, parms, NULL_TREE, complain);
28483       return guide;
28484     }
28485 
28486   return NULL_TREE;
28487 }
28488 
28489 /* UGUIDES are the deduction guides for the underlying template of alias
28490    template TMPL; adjust them to be deduction guides for TMPL.  */
28491 
28492 static tree
alias_ctad_tweaks(tree tmpl,tree uguides)28493 alias_ctad_tweaks (tree tmpl, tree uguides)
28494 {
28495   /* [over.match.class.deduct]: When resolving a placeholder for a deduced
28496      class type (9.2.8.2) where the template-name names an alias template A,
28497      the defining-type-id of A must be of the form
28498 
28499      typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
28500 
28501      as specified in 9.2.8.2. The guides of A are the set of functions or
28502      function templates formed as follows. For each function or function
28503      template f in the guides of the template named by the simple-template-id
28504      of the defining-type-id, the template arguments of the return type of f
28505      are deduced from the defining-type-id of A according to the process in
28506      13.10.2.5 with the exception that deduction does not fail if not all
28507      template arguments are deduced. Let g denote the result of substituting
28508      these deductions into f. If substitution succeeds, form a function or
28509      function template f' with the following properties and add it to the set
28510      of guides of A:
28511 
28512      * The function type of f' is the function type of g.
28513 
28514      * If f is a function template, f' is a function template whose template
28515      parameter list consists of all the template parameters of A (including
28516      their default template arguments) that appear in the above deductions or
28517      (recursively) in their default template arguments, followed by the
28518      template parameters of f that were not deduced (including their default
28519      template arguments), otherwise f' is not a function template.
28520 
28521      * The associated constraints (13.5.2) are the conjunction of the
28522      associated constraints of g and a constraint that is satisfied if and only
28523      if the arguments of A are deducible (see below) from the return type.
28524 
28525      * If f is a copy deduction candidate (12.4.1.8), then f' is considered to
28526      be so as well.
28527 
28528      * If f was generated from a deduction-guide (12.4.1.8), then f' is
28529      considered to be so as well.
28530 
28531      * The explicit-specifier of f' is the explicit-specifier of g (if
28532      any).  */
28533 
28534   /* This implementation differs from the above in two significant ways:
28535 
28536      1) We include all template parameters of A, not just some.
28537      2) The added constraint is same_type instead of deducible.
28538 
28539      I believe that while it's probably possible to construct a testcase that
28540      behaves differently with this simplification, it should have the same
28541      effect for real uses.  Including all template parameters means that we
28542      deduce all parameters of A when resolving the call, so when we're in the
28543      constraint we don't need to deduce them again, we can just check whether
28544      the deduction produced the desired result.  */
28545 
28546   tsubst_flags_t complain = tf_warning_or_error;
28547   tree atype = TREE_TYPE (tmpl);
28548   tree aguides = NULL_TREE;
28549   tree atparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
28550   unsigned natparms = TREE_VEC_LENGTH (atparms);
28551   tree utype = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
28552   for (ovl_iterator iter (uguides); iter; ++iter)
28553     {
28554       tree f = *iter;
28555       tree in_decl = f;
28556       location_t loc = DECL_SOURCE_LOCATION (f);
28557       tree ret = TREE_TYPE (TREE_TYPE (f));
28558       tree fprime = f;
28559       if (TREE_CODE (f) == TEMPLATE_DECL)
28560 	{
28561 	  processing_template_decl_sentinel ptds (/*reset*/false);
28562 	  ++processing_template_decl;
28563 
28564 	  /* Deduce template arguments for f from the type-id of A.  */
28565 	  tree ftparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (f));
28566 	  unsigned len = TREE_VEC_LENGTH (ftparms);
28567 	  tree targs = make_tree_vec (len);
28568 	  int err = unify (ftparms, targs, ret, utype, UNIFY_ALLOW_NONE, false);
28569 	  gcc_assert (!err);
28570 
28571 	  /* The number of parms for f' is the number of parms for A plus
28572 	     non-deduced parms of f.  */
28573 	  unsigned ndlen = 0;
28574 	  unsigned j;
28575 	  for (unsigned i = 0; i < len; ++i)
28576 	    if (TREE_VEC_ELT (targs, i) == NULL_TREE)
28577 	      ++ndlen;
28578 	  tree gtparms = make_tree_vec (natparms + ndlen);
28579 
28580 	  /* First copy over the parms of A.  */
28581 	  for (j = 0; j < natparms; ++j)
28582 	    TREE_VEC_ELT (gtparms, j) = TREE_VEC_ELT (atparms, j);
28583 	  /* Now rewrite the non-deduced parms of f.  */
28584 	  for (unsigned i = 0; ndlen && i < len; ++i)
28585 	    if (TREE_VEC_ELT (targs, i) == NULL_TREE)
28586 	      {
28587 		--ndlen;
28588 		unsigned index = j++;
28589 		unsigned level = 1;
28590 		tree oldlist = TREE_VEC_ELT (ftparms, i);
28591 		tree list = rewrite_tparm_list (oldlist, index, level,
28592 						targs, i, complain);
28593 		TREE_VEC_ELT (gtparms, index) = list;
28594 	      }
28595 	  gtparms = build_tree_list (size_one_node, gtparms);
28596 
28597 	  /* Substitute the deduced arguments plus the rewritten template
28598 	     parameters into f to get g.  This covers the type, copyness,
28599 	     guideness, and explicit-specifier.  */
28600 	  tree g = tsubst_decl (DECL_TEMPLATE_RESULT (f), targs, complain);
28601 	  if (g == error_mark_node)
28602 	    return error_mark_node;
28603 	  DECL_USE_TEMPLATE (g) = 0;
28604 	  fprime = build_template_decl (g, gtparms, false);
28605 	  DECL_TEMPLATE_RESULT (fprime) = g;
28606 	  TREE_TYPE (fprime) = TREE_TYPE (g);
28607 	  tree gtargs = template_parms_to_args (gtparms);
28608 	  DECL_TEMPLATE_INFO (g) = build_template_info (fprime, gtargs);
28609 	  DECL_PRIMARY_TEMPLATE (fprime) = fprime;
28610 
28611 	  /* Substitute the associated constraints.  */
28612 	  tree ci = get_constraints (f);
28613 	  if (ci)
28614 	    ci = tsubst_constraint_info (ci, targs, complain, in_decl);
28615 	  if (ci == error_mark_node)
28616 	    return error_mark_node;
28617 
28618 	  /* Add a constraint that the return type matches the instantiation of
28619 	     A with the same template arguments.  */
28620 	  ret = TREE_TYPE (TREE_TYPE (fprime));
28621 	  if (!same_type_p (atype, ret)
28622 	      /* FIXME this should mean they don't compare as equivalent.  */
28623 	      || dependent_alias_template_spec_p (atype, nt_opaque))
28624 	    {
28625 	      tree same = finish_trait_expr (loc, CPTK_IS_SAME_AS, atype, ret);
28626 	      ci = append_constraint (ci, same);
28627 	    }
28628 
28629 	  if (ci)
28630 	    set_constraints (fprime, ci);
28631 	}
28632       else
28633 	{
28634 	  /* For a non-template deduction guide, if the arguments of A aren't
28635 	     deducible from the return type, don't add the candidate.  */
28636 	  tree targs = make_tree_vec (natparms);
28637 	  int err = unify (atparms, targs, utype, ret, UNIFY_ALLOW_NONE, false);
28638 	  for (unsigned i = 0; !err && i < natparms; ++i)
28639 	    if (TREE_VEC_ELT (targs, i) == NULL_TREE)
28640 	      err = true;
28641 	  if (err)
28642 	    continue;
28643 	}
28644 
28645       aguides = lookup_add (fprime, aguides);
28646     }
28647 
28648   return aguides;
28649 }
28650 
28651 /* Return artificial deduction guides built from the constructors of class
28652    template TMPL.  */
28653 
28654 static tree
ctor_deduction_guides_for(tree tmpl,tsubst_flags_t complain)28655 ctor_deduction_guides_for (tree tmpl, tsubst_flags_t complain)
28656 {
28657   tree type = TREE_TYPE (tmpl);
28658   tree outer_args = NULL_TREE;
28659   if (DECL_CLASS_SCOPE_P (tmpl)
28660       && CLASSTYPE_TEMPLATE_INSTANTIATION (DECL_CONTEXT (tmpl)))
28661     {
28662       outer_args = CLASSTYPE_TI_ARGS (DECL_CONTEXT (tmpl));
28663       type = TREE_TYPE (most_general_template (tmpl));
28664     }
28665 
28666   tree cands = NULL_TREE;
28667 
28668   for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (type)); iter; ++iter)
28669     {
28670       /* Skip inherited constructors.  */
28671       if (iter.using_p ())
28672 	continue;
28673 
28674       tree guide = build_deduction_guide (type, *iter, outer_args, complain);
28675       cands = lookup_add (guide, cands);
28676     }
28677 
28678   /* Add implicit default constructor deduction guide.  */
28679   if (!TYPE_HAS_USER_CONSTRUCTOR (type))
28680     {
28681       tree guide = build_deduction_guide (type, type, outer_args,
28682 					  complain);
28683       cands = lookup_add (guide, cands);
28684     }
28685 
28686   /* Add copy guide.  */
28687   {
28688     tree gtype = build_reference_type (type);
28689     tree guide = build_deduction_guide (type, gtype, outer_args,
28690 					complain);
28691     cands = lookup_add (guide, cands);
28692   }
28693 
28694   return cands;
28695 }
28696 
28697 static GTY((deletable)) hash_map<tree, tree_pair_p> *dguide_cache;
28698 
28699 /* Return the non-aggregate deduction guides for deducible template TMPL.  The
28700    aggregate candidate is added separately because it depends on the
28701    initializer.  */
28702 
28703 static tree
deduction_guides_for(tree tmpl,tsubst_flags_t complain)28704 deduction_guides_for (tree tmpl, tsubst_flags_t complain)
28705 {
28706   tree guides = NULL_TREE;
28707   if (DECL_ALIAS_TEMPLATE_P (tmpl))
28708     {
28709       tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
28710       tree tinfo = get_template_info (under);
28711       guides = deduction_guides_for (TI_TEMPLATE (tinfo), complain);
28712     }
28713   else
28714     {
28715       guides = lookup_qualified_name (CP_DECL_CONTEXT (tmpl),
28716 				      dguide_name (tmpl),
28717 				      /*type*/false, /*complain*/false,
28718 				      /*hidden*/false);
28719       if (guides == error_mark_node)
28720 	guides = NULL_TREE;
28721     }
28722 
28723   /* Cache the deduction guides for a template.  We also remember the result of
28724      lookup, and rebuild everything if it changes; should be very rare.  */
28725   tree_pair_p cache = NULL;
28726   if (tree_pair_p &r
28727       = hash_map_safe_get_or_insert<hm_ggc> (dguide_cache, tmpl))
28728     {
28729       cache = r;
28730       if (cache->purpose == guides)
28731 	return cache->value;
28732     }
28733   else
28734     {
28735       r = cache = ggc_cleared_alloc<tree_pair_s> ();
28736       cache->purpose = guides;
28737     }
28738 
28739   tree cands = NULL_TREE;
28740   if (DECL_ALIAS_TEMPLATE_P (tmpl))
28741     cands = alias_ctad_tweaks (tmpl, guides);
28742   else
28743     {
28744       cands = ctor_deduction_guides_for (tmpl, complain);
28745       for (ovl_iterator it (guides); it; ++it)
28746 	cands = lookup_add (*it, cands);
28747     }
28748 
28749   cache->value = cands;
28750   return cands;
28751 }
28752 
28753 /* Return whether TMPL is a (class template argument-) deducible template.  */
28754 
28755 bool
ctad_template_p(tree tmpl)28756 ctad_template_p (tree tmpl)
28757 {
28758   /* A deducible template is either a class template or is an alias template
28759      whose defining-type-id is of the form
28760 
28761       typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
28762 
28763      where the nested-name-specifier (if any) is non-dependent and the
28764      template-name of the simple-template-id names a deducible template.  */
28765 
28766   if (DECL_CLASS_TEMPLATE_P (tmpl)
28767       || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
28768     return true;
28769   if (!DECL_ALIAS_TEMPLATE_P (tmpl))
28770     return false;
28771   tree orig = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
28772   if (tree tinfo = get_template_info (orig))
28773     return ctad_template_p (TI_TEMPLATE (tinfo));
28774   return false;
28775 }
28776 
28777 /* Deduce template arguments for the class template placeholder PTYPE for
28778    template TMPL based on the initializer INIT, and return the resulting
28779    type.  */
28780 
28781 static tree
do_class_deduction(tree ptype,tree tmpl,tree init,int flags,tsubst_flags_t complain)28782 do_class_deduction (tree ptype, tree tmpl, tree init,
28783 		    int flags, tsubst_flags_t complain)
28784 {
28785   /* We should have handled this in the caller.  */
28786   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
28787     return ptype;
28788 
28789   /* Look through alias templates that just rename another template.  */
28790   tmpl = get_underlying_template (tmpl);
28791   if (!ctad_template_p (tmpl))
28792     {
28793       if (complain & tf_error)
28794 	error ("non-deducible template %qT used without template arguments", tmpl);
28795       return error_mark_node;
28796     }
28797   else if (cxx_dialect < cxx2a && DECL_ALIAS_TEMPLATE_P (tmpl))
28798     {
28799       /* This doesn't affect conforming C++17 code, so just pedwarn.  */
28800       if (complain & tf_warning_or_error)
28801 	pedwarn (input_location, 0, "alias template deduction only available "
28802 		 "with %<-std=c++2a%> or %<-std=gnu++2a%>");
28803     }
28804 
28805   if (init && TREE_TYPE (init) == ptype)
28806     /* Using the template parm as its own argument.  */
28807     return ptype;
28808 
28809   tree type = TREE_TYPE (tmpl);
28810 
28811   bool try_list_ctor = false;
28812 
28813   releasing_vec rv_args = NULL;
28814   vec<tree,va_gc> *&args = *&rv_args;
28815   if (init == NULL_TREE)
28816     args = make_tree_vector ();
28817   else if (BRACE_ENCLOSED_INITIALIZER_P (init))
28818     {
28819       try_list_ctor = TYPE_HAS_LIST_CTOR (type);
28820       if (try_list_ctor && CONSTRUCTOR_NELTS (init) == 1)
28821 	{
28822 	  /* As an exception, the first phase in 16.3.1.7 (considering the
28823 	     initializer list as a single argument) is omitted if the
28824 	     initializer list consists of a single expression of type cv U,
28825 	     where U is a specialization of C or a class derived from a
28826 	     specialization of C.  */
28827 	  tree elt = CONSTRUCTOR_ELT (init, 0)->value;
28828 	  if (is_spec_or_derived (TREE_TYPE (elt), tmpl))
28829 	    try_list_ctor = false;
28830 	}
28831       if (try_list_ctor || is_std_init_list (type))
28832 	args = make_tree_vector_single (init);
28833       else
28834 	args = make_tree_vector_from_ctor (init);
28835     }
28836   else if (TREE_CODE (init) == TREE_LIST)
28837     args = make_tree_vector_from_list (init);
28838   else
28839     args = make_tree_vector_single (init);
28840 
28841   /* Do this now to avoid problems with erroneous args later on.  */
28842   args = resolve_args (args, complain);
28843   if (args == NULL)
28844     return error_mark_node;
28845 
28846   tree cands = deduction_guides_for (tmpl, complain);
28847   if (cands == error_mark_node)
28848     return error_mark_node;
28849 
28850   /* Prune explicit deduction guides in copy-initialization context.  */
28851   bool elided = false;
28852   if (flags & LOOKUP_ONLYCONVERTING)
28853     {
28854       for (lkp_iterator iter (cands); !elided && iter; ++iter)
28855 	if (DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
28856 	  elided = true;
28857 
28858       if (elided)
28859 	{
28860 	  /* Found a nonconverting guide, prune the candidates.  */
28861 	  tree pruned = NULL_TREE;
28862 	  for (lkp_iterator iter (cands); iter; ++iter)
28863 	    if (!DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
28864 	      pruned = lookup_add (*iter, pruned);
28865 
28866 	  cands = pruned;
28867 	}
28868     }
28869 
28870   if (tree guide = maybe_aggr_guide (tmpl, init, args))
28871     cands = lookup_add (guide, cands);
28872 
28873   tree call = error_mark_node;
28874 
28875   /* If this is list-initialization and the class has a list constructor, first
28876      try deducing from the list as a single argument, as [over.match.list].  */
28877   tree list_cands = NULL_TREE;
28878   if (try_list_ctor && cands)
28879     for (lkp_iterator iter (cands); iter; ++iter)
28880       {
28881 	tree dg = *iter;
28882 	if (is_list_ctor (dg))
28883 	  list_cands = lookup_add (dg, list_cands);
28884       }
28885   if (list_cands)
28886     {
28887       ++cp_unevaluated_operand;
28888       call = build_new_function_call (list_cands, &args, tf_decltype);
28889       --cp_unevaluated_operand;
28890 
28891       if (call == error_mark_node)
28892 	{
28893 	  /* That didn't work, now try treating the list as a sequence of
28894 	     arguments.  */
28895 	  release_tree_vector (args);
28896 	  args = make_tree_vector_from_ctor (init);
28897 	}
28898     }
28899 
28900   if (elided && !cands)
28901     {
28902       error ("cannot deduce template arguments for copy-initialization"
28903 	     " of %qT, as it has no non-explicit deduction guides or "
28904 	     "user-declared constructors", type);
28905       return error_mark_node;
28906     }
28907   else if (!cands && call == error_mark_node)
28908     {
28909       error ("cannot deduce template arguments of %qT, as it has no viable "
28910 	     "deduction guides", type);
28911       return error_mark_node;
28912     }
28913 
28914   if (call == error_mark_node)
28915     {
28916       ++cp_unevaluated_operand;
28917       call = build_new_function_call (cands, &args, tf_decltype);
28918       --cp_unevaluated_operand;
28919     }
28920 
28921   if (call == error_mark_node
28922       && (complain & tf_warning_or_error))
28923     {
28924       error ("class template argument deduction failed:");
28925 
28926       ++cp_unevaluated_operand;
28927       call = build_new_function_call (cands, &args, complain | tf_decltype);
28928       --cp_unevaluated_operand;
28929 
28930       if (elided)
28931 	inform (input_location, "explicit deduction guides not considered "
28932 		"for copy-initialization");
28933     }
28934 
28935   return cp_build_qualified_type (TREE_TYPE (call), cp_type_quals (ptype));
28936 }
28937 
28938 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
28939    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
28940    The CONTEXT determines the context in which auto deduction is performed
28941    and is used to control error diagnostics.  FLAGS are the LOOKUP_* flags.
28942    OUTER_TARGS are used during template argument deduction
28943    (context == adc_unify) to properly substitute the result, and is ignored
28944    in other contexts.
28945 
28946    For partial-concept-ids, extra args may be appended to the list of deduced
28947    template arguments prior to determining constraint satisfaction.  */
28948 
28949 tree
do_auto_deduction(tree type,tree init,tree auto_node,tsubst_flags_t complain,auto_deduction_context context,tree outer_targs,int flags)28950 do_auto_deduction (tree type, tree init, tree auto_node,
28951                    tsubst_flags_t complain, auto_deduction_context context,
28952 		   tree outer_targs, int flags)
28953 {
28954   tree targs;
28955 
28956   if (init == error_mark_node)
28957     return error_mark_node;
28958 
28959   if (init && type_dependent_expression_p (init)
28960       && context != adc_unify)
28961     /* Defining a subset of type-dependent expressions that we can deduce
28962        from ahead of time isn't worth the trouble.  */
28963     return type;
28964 
28965   /* Similarly, we can't deduce from another undeduced decl.  */
28966   if (init && undeduced_auto_decl (init))
28967     return type;
28968 
28969   /* We may be doing a partial substitution, but we still want to replace
28970      auto_node.  */
28971   complain &= ~tf_partial;
28972 
28973   if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
28974     /* C++17 class template argument deduction.  */
28975     return do_class_deduction (type, tmpl, init, flags, complain);
28976 
28977   if (init == NULL_TREE || TREE_TYPE (init) == NULL_TREE)
28978     /* Nothing we can do with this, even in deduction context.  */
28979     return type;
28980 
28981   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
28982      with either a new invented type template parameter U or, if the
28983      initializer is a braced-init-list (8.5.4), with
28984      std::initializer_list<U>.  */
28985   if (BRACE_ENCLOSED_INITIALIZER_P (init))
28986     {
28987       if (!DIRECT_LIST_INIT_P (init))
28988 	type = listify_autos (type, auto_node);
28989       else if (CONSTRUCTOR_NELTS (init) == 1)
28990 	init = CONSTRUCTOR_ELT (init, 0)->value;
28991       else
28992 	{
28993           if (complain & tf_warning_or_error)
28994             {
28995 	      if (permerror (input_location, "direct-list-initialization of "
28996 			     "%<auto%> requires exactly one element"))
28997 	        inform (input_location,
28998 		        "for deduction to %<std::initializer_list%>, use copy-"
28999 		        "list-initialization (i.e. add %<=%> before the %<{%>)");
29000             }
29001 	  type = listify_autos (type, auto_node);
29002 	}
29003     }
29004 
29005   if (type == error_mark_node)
29006     return error_mark_node;
29007 
29008   init = resolve_nondeduced_context (init, complain);
29009 
29010   if (context == adc_decomp_type
29011       && auto_node == type
29012       && init != error_mark_node
29013       && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
29014     /* [dcl.decomp]/1 - if decomposition declaration has no ref-qualifiers
29015        and initializer has array type, deduce cv-qualified array type.  */
29016     return cp_build_qualified_type_real (TREE_TYPE (init), TYPE_QUALS (type),
29017 					 complain);
29018   else if (AUTO_IS_DECLTYPE (auto_node))
29019     {
29020       tree stripped_init = tree_strip_any_location_wrapper (init);
29021       bool id = (DECL_P (stripped_init)
29022 		 || ((TREE_CODE (init) == COMPONENT_REF
29023 		      || TREE_CODE (init) == SCOPE_REF)
29024 		     && !REF_PARENTHESIZED_P (init)));
29025       targs = make_tree_vec (1);
29026       TREE_VEC_ELT (targs, 0)
29027 	= finish_decltype_type (init, id, tf_warning_or_error);
29028       if (type != auto_node)
29029 	{
29030           if (complain & tf_error)
29031 	    error ("%qT as type rather than plain %<decltype(auto)%>", type);
29032 	  return error_mark_node;
29033 	}
29034     }
29035   else
29036     {
29037       if (error_operand_p (init))
29038 	return error_mark_node;
29039 
29040       tree parms = build_tree_list (NULL_TREE, type);
29041       tree tparms;
29042 
29043       if (flag_concepts)
29044 	tparms = extract_autos (type);
29045       else
29046 	{
29047 	  tparms = make_tree_vec (1);
29048 	  TREE_VEC_ELT (tparms, 0)
29049 	    = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
29050 	}
29051 
29052       targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
29053       int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
29054 				       DEDUCE_CALL,
29055 				       NULL, /*explain_p=*/false);
29056       if (val > 0)
29057 	{
29058 	  if (processing_template_decl)
29059 	    /* Try again at instantiation time.  */
29060 	    return type;
29061 	  if (type && type != error_mark_node
29062 	      && (complain & tf_error))
29063 	    /* If type is error_mark_node a diagnostic must have been
29064 	       emitted by now.  Also, having a mention to '<type error>'
29065 	       in the diagnostic is not really useful to the user.  */
29066 	    {
29067 	      if (cfun
29068 		  && FNDECL_USED_AUTO (current_function_decl)
29069 		  && (auto_node
29070 		      == DECL_SAVED_AUTO_RETURN_TYPE (current_function_decl))
29071 		  && LAMBDA_FUNCTION_P (current_function_decl))
29072 		error ("unable to deduce lambda return type from %qE", init);
29073 	      else
29074 		error ("unable to deduce %qT from %qE", type, init);
29075 	      type_unification_real (tparms, targs, parms, &init, 1, 0,
29076 				     DEDUCE_CALL,
29077 				     NULL, /*explain_p=*/true);
29078 	    }
29079 	  return error_mark_node;
29080 	}
29081     }
29082 
29083   /* Check any placeholder constraints against the deduced type. */
29084   if (flag_concepts && !processing_template_decl)
29085     if (tree check = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (auto_node)))
29086       {
29087         /* Use the deduced type to check the associated constraints. If we
29088            have a partial-concept-id, rebuild the argument list so that
29089            we check using the extra arguments. */
29090 	check = unpack_concept_check (check);
29091 	gcc_assert (TREE_CODE (check) == TEMPLATE_ID_EXPR);
29092 	tree cdecl = TREE_OPERAND (check, 0);
29093 	if (OVL_P (cdecl))
29094 	  cdecl = OVL_FIRST (cdecl);
29095         tree cargs = TREE_OPERAND (check, 1);
29096         if (TREE_VEC_LENGTH (cargs) > 1)
29097           {
29098             cargs = copy_node (cargs);
29099             TREE_VEC_ELT (cargs, 0) = TREE_VEC_ELT (targs, 0);
29100           }
29101         else
29102           cargs = targs;
29103 
29104 	/* Rebuild the check using the deduced arguments.  */
29105 	check = build_concept_check (cdecl, cargs, tf_none);
29106 
29107 	if (!constraints_satisfied_p (check))
29108           {
29109             if (complain & tf_warning_or_error)
29110               {
29111 		auto_diagnostic_group d;
29112                 switch (context)
29113                   {
29114                   case adc_unspecified:
29115 		  case adc_unify:
29116                     error("placeholder constraints not satisfied");
29117                     break;
29118                   case adc_variable_type:
29119 		  case adc_decomp_type:
29120                     error ("deduced initializer does not satisfy "
29121                            "placeholder constraints");
29122                     break;
29123                   case adc_return_type:
29124                     error ("deduced return type does not satisfy "
29125                            "placeholder constraints");
29126                     break;
29127                   case adc_requirement:
29128 		    error ("deduced expression type does not satisfy "
29129                            "placeholder constraints");
29130                     break;
29131                   }
29132 		diagnose_constraints (input_location, check, targs);
29133               }
29134             return error_mark_node;
29135           }
29136       }
29137 
29138   if (processing_template_decl && context != adc_unify)
29139     outer_targs = current_template_args ();
29140   targs = add_to_template_args (outer_targs, targs);
29141   return tsubst (type, targs, complain, NULL_TREE);
29142 }
29143 
29144 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
29145    result.  */
29146 
29147 tree
splice_late_return_type(tree type,tree late_return_type)29148 splice_late_return_type (tree type, tree late_return_type)
29149 {
29150   if (late_return_type)
29151     {
29152       gcc_assert (is_auto (type) || seen_error ());
29153       return late_return_type;
29154     }
29155 
29156   if (tree *auto_node = find_type_usage (&type, is_auto))
29157     {
29158       tree idx = get_template_parm_index (*auto_node);
29159       if (TEMPLATE_PARM_LEVEL (idx) <= processing_template_decl)
29160 	{
29161 	  /* In an abbreviated function template we didn't know we were dealing
29162 	     with a function template when we saw the auto return type, so update
29163 	     it to have the correct level.  */
29164 	  tree new_auto = make_auto_1 (TYPE_IDENTIFIER (*auto_node), false);
29165 	  PLACEHOLDER_TYPE_CONSTRAINTS (new_auto)
29166 	    = PLACEHOLDER_TYPE_CONSTRAINTS (*auto_node);
29167 	  TYPE_CANONICAL (new_auto) = canonical_type_parameter (new_auto);
29168 	  new_auto = cp_build_qualified_type (new_auto, TYPE_QUALS (*auto_node));
29169 	  *auto_node = new_auto;
29170 	}
29171     }
29172   return type;
29173 }
29174 
29175 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
29176    'decltype(auto)' or a deduced class template.  */
29177 
29178 bool
is_auto(const_tree type)29179 is_auto (const_tree type)
29180 {
29181   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
29182       && (TYPE_IDENTIFIER (type) == auto_identifier
29183 	  || TYPE_IDENTIFIER (type) == decltype_auto_identifier))
29184     return true;
29185   else
29186     return false;
29187 }
29188 
29189 /* for_each_template_parm callback for type_uses_auto.  */
29190 
29191 int
is_auto_r(tree tp,void *)29192 is_auto_r (tree tp, void */*data*/)
29193 {
29194   return is_auto (tp);
29195 }
29196 
29197 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
29198    a use of `auto'.  Returns NULL_TREE otherwise.  */
29199 
29200 tree
type_uses_auto(tree type)29201 type_uses_auto (tree type)
29202 {
29203   if (type == NULL_TREE)
29204     return NULL_TREE;
29205   else if (flag_concepts)
29206     {
29207       /* The Concepts TS allows multiple autos in one type-specifier; just
29208 	 return the first one we find, do_auto_deduction will collect all of
29209 	 them.  */
29210       if (uses_template_parms (type))
29211 	return for_each_template_parm (type, is_auto_r, /*data*/NULL,
29212 				       /*visited*/NULL, /*nondeduced*/false);
29213       else
29214 	return NULL_TREE;
29215     }
29216   else if (tree *tp = find_type_usage (&type, is_auto))
29217     return *tp;
29218   else
29219     return NULL_TREE;
29220 }
29221 
29222 /* Report ill-formed occurrences of auto types in ARGUMENTS.  If
29223    concepts are enabled, auto is acceptable in template arguments, but
29224    only when TEMPL identifies a template class.  Return TRUE if any
29225    such errors were reported.  */
29226 
29227 bool
check_auto_in_tmpl_args(tree tmpl,tree args)29228 check_auto_in_tmpl_args (tree tmpl, tree args)
29229 {
29230   /* If there were previous errors, nevermind.  */
29231   if (!args || TREE_CODE (args) != TREE_VEC)
29232     return false;
29233 
29234   /* If TMPL is an identifier, we're parsing and we can't tell yet
29235      whether TMPL is supposed to be a type, a function or a variable.
29236      We'll only be able to tell during template substitution, so we
29237      expect to be called again then.  If concepts are enabled and we
29238      know we have a type, we're ok.  */
29239   if (flag_concepts
29240       && (identifier_p (tmpl)
29241 	  || (DECL_P (tmpl)
29242 	      &&  (DECL_TYPE_TEMPLATE_P (tmpl)
29243 		   || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)))))
29244     return false;
29245 
29246   /* Quickly search for any occurrences of auto; usually there won't
29247      be any, and then we'll avoid allocating the vector.  */
29248   if (!type_uses_auto (args))
29249     return false;
29250 
29251   bool errors = false;
29252 
29253   tree vec = extract_autos (args);
29254   for (int i = 0; i < TREE_VEC_LENGTH (vec); i++)
29255     {
29256       tree xauto = TREE_VALUE (TREE_VEC_ELT (vec, i));
29257       error_at (DECL_SOURCE_LOCATION (xauto),
29258 		"invalid use of %qT in template argument", xauto);
29259       errors = true;
29260     }
29261 
29262   return errors;
29263 }
29264 
29265 /* For a given template T, return the vector of typedefs referenced
29266    in T for which access check is needed at T instantiation time.
29267    T is either  a FUNCTION_DECL or a RECORD_TYPE.
29268    Those typedefs were added to T by the function
29269    append_type_to_template_for_access_check.  */
29270 
29271 vec<qualified_typedef_usage_t, va_gc> *
get_types_needing_access_check(tree t)29272 get_types_needing_access_check (tree t)
29273 {
29274   tree ti;
29275   vec<qualified_typedef_usage_t, va_gc> *result = NULL;
29276 
29277   if (!t || t == error_mark_node)
29278     return NULL;
29279 
29280   if (!(ti = get_template_info (t)))
29281     return NULL;
29282 
29283   if (CLASS_TYPE_P (t)
29284       || TREE_CODE (t) == FUNCTION_DECL)
29285     {
29286       if (!TI_TEMPLATE (ti))
29287 	return NULL;
29288 
29289       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
29290     }
29291 
29292   return result;
29293 }
29294 
29295 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
29296    tied to T. That list of typedefs will be access checked at
29297    T instantiation time.
29298    T is either a FUNCTION_DECL or a RECORD_TYPE.
29299    TYPE_DECL is a TYPE_DECL node representing a typedef.
29300    SCOPE is the scope through which TYPE_DECL is accessed.
29301    LOCATION is the location of the usage point of TYPE_DECL.
29302 
29303    This function is a subroutine of
29304    append_type_to_template_for_access_check.  */
29305 
29306 static void
append_type_to_template_for_access_check_1(tree t,tree type_decl,tree scope,location_t location)29307 append_type_to_template_for_access_check_1 (tree t,
29308 					    tree type_decl,
29309 					    tree scope,
29310 					    location_t location)
29311 {
29312   qualified_typedef_usage_t typedef_usage;
29313   tree ti;
29314 
29315   if (!t || t == error_mark_node)
29316     return;
29317 
29318   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
29319 	       || CLASS_TYPE_P (t))
29320 	      && type_decl
29321 	      && TREE_CODE (type_decl) == TYPE_DECL
29322 	      && scope);
29323 
29324   if (!(ti = get_template_info (t)))
29325     return;
29326 
29327   gcc_assert (TI_TEMPLATE (ti));
29328 
29329   typedef_usage.typedef_decl = type_decl;
29330   typedef_usage.context = scope;
29331   typedef_usage.locus = location;
29332 
29333   vec_safe_push (TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti), typedef_usage);
29334 }
29335 
29336 /* Append TYPE_DECL to the template TEMPL.
29337    TEMPL is either a class type, a FUNCTION_DECL or a TEMPLATE_DECL.
29338    At TEMPL instanciation time, TYPE_DECL will be checked to see
29339    if it can be accessed through SCOPE.
29340    LOCATION is the location of the usage point of TYPE_DECL.
29341 
29342    e.g. consider the following code snippet:
29343 
29344      class C
29345      {
29346        typedef int myint;
29347      };
29348 
29349      template<class U> struct S
29350      {
29351        C::myint mi; // <-- usage point of the typedef C::myint
29352      };
29353 
29354      S<char> s;
29355 
29356    At S<char> instantiation time, we need to check the access of C::myint
29357    In other words, we need to check the access of the myint typedef through
29358    the C scope. For that purpose, this function will add the myint typedef
29359    and the scope C through which its being accessed to a list of typedefs
29360    tied to the template S. That list will be walked at template instantiation
29361    time and access check performed on each typedefs it contains.
29362    Note that this particular code snippet should yield an error because
29363    myint is private to C.  */
29364 
29365 void
append_type_to_template_for_access_check(tree templ,tree type_decl,tree scope,location_t location)29366 append_type_to_template_for_access_check (tree templ,
29367                                           tree type_decl,
29368 					  tree scope,
29369 					  location_t location)
29370 {
29371   qualified_typedef_usage_t *iter;
29372   unsigned i;
29373 
29374   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
29375 
29376   /* Make sure we don't append the type to the template twice.  */
29377   FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (templ), i, iter)
29378     if (iter->typedef_decl == type_decl && scope == iter->context)
29379       return;
29380 
29381   append_type_to_template_for_access_check_1 (templ, type_decl,
29382 					      scope, location);
29383 }
29384 
29385 /* Recursively walk over && expressions searching for EXPR. Return a reference
29386    to that expression.  */
29387 
find_template_requirement(tree * t,tree key)29388 static tree *find_template_requirement (tree *t, tree key)
29389 {
29390   if (*t == key)
29391     return t;
29392   if (TREE_CODE (*t) == TRUTH_ANDIF_EXPR)
29393     {
29394       if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 0), key))
29395 	return p;
29396       if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 1), key))
29397 	return p;
29398     }
29399   return 0;
29400 }
29401 
29402 /* Convert the generic type parameters in PARM that match the types given in the
29403    range [START_IDX, END_IDX) from the current_template_parms into generic type
29404    packs.  */
29405 
29406 tree
convert_generic_types_to_packs(tree parm,int start_idx,int end_idx)29407 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
29408 {
29409   tree current = current_template_parms;
29410   int depth = TMPL_PARMS_DEPTH (current);
29411   current = INNERMOST_TEMPLATE_PARMS (current);
29412   tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
29413 
29414   for (int i = 0; i < start_idx; ++i)
29415     TREE_VEC_ELT (replacement, i)
29416       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
29417 
29418   for (int i = start_idx; i < end_idx; ++i)
29419     {
29420       /* Create a distinct parameter pack type from the current parm and add it
29421 	 to the replacement args to tsubst below into the generic function
29422 	 parameter.  */
29423       tree node = TREE_VEC_ELT (current, i);
29424       tree o = TREE_TYPE (TREE_VALUE (node));
29425       tree t = copy_type (o);
29426       TEMPLATE_TYPE_PARM_INDEX (t)
29427 	= reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
29428 				      t, 0, 0, tf_none);
29429       TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
29430       TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
29431       TYPE_MAIN_VARIANT (t) = t;
29432       TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
29433       TYPE_CANONICAL (t) = canonical_type_parameter (t);
29434       TREE_VEC_ELT (replacement, i) = t;
29435 
29436       /* Replace the current template parameter with new pack.  */
29437       TREE_VALUE (node) = TREE_CHAIN (t);
29438 
29439       /* Surgically adjust the associated constraint of adjusted parameter
29440          and it's corresponding contribution to the current template
29441          requirements.  */
29442       if (tree constr = TEMPLATE_PARM_CONSTRAINTS (node))
29443 	{
29444 	  tree id = unpack_concept_check (constr);
29445 	  TREE_VEC_ELT (TREE_OPERAND (id, 1), 0) = template_parm_to_arg (t);
29446 	  tree fold = finish_left_unary_fold_expr (constr, TRUTH_ANDIF_EXPR);
29447 	  TEMPLATE_PARM_CONSTRAINTS (node) = fold;
29448 
29449 	  /* If there was a constraint, we also need to replace that in
29450 	     the template requirements, which we've already built.  */
29451 	  tree *reqs = &TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
29452 	  reqs = find_template_requirement (reqs, constr);
29453 	  *reqs = fold;
29454 	}
29455     }
29456 
29457   for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
29458     TREE_VEC_ELT (replacement, i)
29459       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
29460 
29461   /* If there are more levels then build up the replacement with the outer
29462      template parms.  */
29463   if (depth > 1)
29464     replacement = add_to_template_args (template_parms_to_args
29465 					(TREE_CHAIN (current_template_parms)),
29466 					replacement);
29467 
29468   return tsubst (parm, replacement, tf_none, NULL_TREE);
29469 }
29470 
29471 /* __integer_pack(N) in a pack expansion expands to a sequence of numbers from
29472    0..N-1.  */
29473 
29474 void
declare_integer_pack(void)29475 declare_integer_pack (void)
29476 {
29477   tree ipfn = push_library_fn (get_identifier ("__integer_pack"),
29478 			       build_function_type_list (integer_type_node,
29479 							 integer_type_node,
29480 							 NULL_TREE),
29481 			       NULL_TREE, ECF_CONST);
29482   DECL_DECLARED_CONSTEXPR_P (ipfn) = true;
29483   set_decl_built_in_function (ipfn, BUILT_IN_FRONTEND,
29484 			      CP_BUILT_IN_INTEGER_PACK);
29485 }
29486 
29487 /* Set up the hash tables for template instantiations.  */
29488 
29489 void
init_template_processing(void)29490 init_template_processing (void)
29491 {
29492   /* FIXME: enable sanitization (PR87847) */
29493   decl_specializations = hash_table<spec_hasher>::create_ggc (37, false);
29494   type_specializations = hash_table<spec_hasher>::create_ggc (37, false);
29495 
29496   if (cxx_dialect >= cxx11)
29497     declare_integer_pack ();
29498 }
29499 
29500 /* Print stats about the template hash tables for -fstats.  */
29501 
29502 void
print_template_statistics(void)29503 print_template_statistics (void)
29504 {
29505   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
29506 	   "%f collisions\n", (long) decl_specializations->size (),
29507 	   (long) decl_specializations->elements (),
29508 	   decl_specializations->collisions ());
29509   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
29510 	   "%f collisions\n", (long) type_specializations->size (),
29511 	   (long) type_specializations->elements (),
29512 	   type_specializations->collisions ());
29513 }
29514 
29515 #if CHECKING_P
29516 
29517 namespace selftest {
29518 
29519 /* Verify that build_non_dependent_expr () works, for various expressions,
29520    and that location wrappers don't affect the results.  */
29521 
29522 static void
test_build_non_dependent_expr()29523 test_build_non_dependent_expr ()
29524 {
29525   location_t loc = BUILTINS_LOCATION;
29526 
29527   /* Verify constants, without and with location wrappers.  */
29528   tree int_cst = build_int_cst (integer_type_node, 42);
29529   ASSERT_EQ (int_cst, build_non_dependent_expr (int_cst));
29530 
29531   tree wrapped_int_cst = maybe_wrap_with_location (int_cst, loc);
29532   ASSERT_TRUE (location_wrapper_p (wrapped_int_cst));
29533   ASSERT_EQ (wrapped_int_cst, build_non_dependent_expr (wrapped_int_cst));
29534 
29535   tree string_lit = build_string (4, "foo");
29536   TREE_TYPE (string_lit) = char_array_type_node;
29537   string_lit = fix_string_type (string_lit);
29538   ASSERT_EQ (string_lit, build_non_dependent_expr (string_lit));
29539 
29540   tree wrapped_string_lit = maybe_wrap_with_location (string_lit, loc);
29541   ASSERT_TRUE (location_wrapper_p (wrapped_string_lit));
29542   ASSERT_EQ (wrapped_string_lit,
29543 	     build_non_dependent_expr (wrapped_string_lit));
29544 }
29545 
29546 /* Verify that type_dependent_expression_p () works correctly, even
29547    in the presence of location wrapper nodes.  */
29548 
29549 static void
test_type_dependent_expression_p()29550 test_type_dependent_expression_p ()
29551 {
29552   location_t loc = BUILTINS_LOCATION;
29553 
29554   tree name = get_identifier ("foo");
29555 
29556   /* If no templates are involved, nothing is type-dependent.  */
29557   gcc_assert (!processing_template_decl);
29558   ASSERT_FALSE (type_dependent_expression_p (name));
29559 
29560   ++processing_template_decl;
29561 
29562   /* Within a template, an unresolved name is always type-dependent.  */
29563   ASSERT_TRUE (type_dependent_expression_p (name));
29564 
29565   /* Ensure it copes with NULL_TREE and errors.  */
29566   ASSERT_FALSE (type_dependent_expression_p (NULL_TREE));
29567   ASSERT_FALSE (type_dependent_expression_p (error_mark_node));
29568 
29569   /* A USING_DECL in a template should be type-dependent, even if wrapped
29570      with a location wrapper (PR c++/83799).  */
29571   tree using_decl = build_lang_decl (USING_DECL, name, NULL_TREE);
29572   TREE_TYPE (using_decl) = integer_type_node;
29573   ASSERT_TRUE (type_dependent_expression_p (using_decl));
29574   tree wrapped_using_decl = maybe_wrap_with_location (using_decl, loc);
29575   ASSERT_TRUE (location_wrapper_p (wrapped_using_decl));
29576   ASSERT_TRUE (type_dependent_expression_p (wrapped_using_decl));
29577 
29578   --processing_template_decl;
29579 }
29580 
29581 /* Run all of the selftests within this file.  */
29582 
29583 void
cp_pt_c_tests()29584 cp_pt_c_tests ()
29585 {
29586   test_build_non_dependent_expr ();
29587   test_type_dependent_expression_p ();
29588 }
29589 
29590 } // namespace selftest
29591 
29592 #endif /* #if CHECKING_P */
29593 
29594 #include "gt-cp-pt.h"
29595