1 /* Handle parameterized types (templates) for GNU -*- C++ -*-.
2    Copyright (C) 1992-2018 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 
46 /* The type of functions taking a tree, and some additional data, and
47    returning an int.  */
48 typedef int (*tree_fn_t) (tree, void*);
49 
50 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
51    instantiations have been deferred, either because their definitions
52    were not yet available, or because we were putting off doing the work.  */
53 struct GTY ((chain_next ("%h.next"))) pending_template
54 {
55   struct pending_template *next;
56   struct tinst_level *tinst;
57 };
58 
59 static GTY(()) struct pending_template *pending_templates;
60 static GTY(()) struct pending_template *last_pending_template;
61 
62 int processing_template_parmlist;
63 static int template_header_count;
64 
65 static GTY(()) tree saved_trees;
66 static vec<int> inline_parm_levels;
67 
68 static GTY(()) struct tinst_level *current_tinst_level;
69 
70 static GTY(()) tree saved_access_scope;
71 
72 /* Live only within one (recursive) call to tsubst_expr.  We use
73    this to pass the statement expression node from the STMT_EXPR
74    to the EXPR_STMT that is its result.  */
75 static tree cur_stmt_expr;
76 
77 // -------------------------------------------------------------------------- //
78 // Local Specialization Stack
79 //
80 // Implementation of the RAII helper for creating new local
81 // specializations.
local_specialization_stack(lss_policy policy)82 local_specialization_stack::local_specialization_stack (lss_policy policy)
83   : saved (local_specializations)
84 {
85   if (policy == lss_blank || !saved)
86     local_specializations = new hash_map<tree, tree>;
87   else
88     local_specializations = new hash_map<tree, tree>(*saved);
89 }
90 
~local_specialization_stack()91 local_specialization_stack::~local_specialization_stack ()
92 {
93   delete local_specializations;
94   local_specializations = saved;
95 }
96 
97 /* True if we've recursed into fn_type_unification too many times.  */
98 static bool excessive_deduction_depth;
99 
100 struct GTY((for_user)) spec_entry
101 {
102   tree tmpl;
103   tree args;
104   tree spec;
105 };
106 
107 struct spec_hasher : ggc_ptr_hash<spec_entry>
108 {
109   static hashval_t hash (spec_entry *);
110   static bool equal (spec_entry *, spec_entry *);
111 };
112 
113 static GTY (()) hash_table<spec_hasher> *decl_specializations;
114 
115 static GTY (()) hash_table<spec_hasher> *type_specializations;
116 
117 /* Contains canonical template parameter types. The vector is indexed by
118    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
119    TREE_LIST, whose TREE_VALUEs contain the canonical template
120    parameters of various types and levels.  */
121 static GTY(()) vec<tree, va_gc> *canonical_template_parms;
122 
123 #define UNIFY_ALLOW_NONE 0
124 #define UNIFY_ALLOW_MORE_CV_QUAL 1
125 #define UNIFY_ALLOW_LESS_CV_QUAL 2
126 #define UNIFY_ALLOW_DERIVED 4
127 #define UNIFY_ALLOW_INTEGER 8
128 #define UNIFY_ALLOW_OUTER_LEVEL 16
129 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
130 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
131 
132 enum template_base_result {
133   tbr_incomplete_type,
134   tbr_ambiguous_baseclass,
135   tbr_success
136 };
137 
138 static void push_access_scope (tree);
139 static void pop_access_scope (tree);
140 static bool resolve_overloaded_unification (tree, tree, tree, tree,
141 					    unification_kind_t, int,
142 					    bool);
143 static int try_one_overload (tree, tree, tree, tree, tree,
144 			     unification_kind_t, int, bool, bool);
145 static int unify (tree, tree, tree, tree, int, bool);
146 static void add_pending_template (tree);
147 static tree reopen_tinst_level (struct tinst_level *);
148 static tree tsubst_initializer_list (tree, tree);
149 static tree get_partial_spec_bindings (tree, tree, tree);
150 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
151 				   bool, bool);
152 static tree coerce_innermost_template_parms (tree, tree, tree, tsubst_flags_t,
153 					      bool, bool);
154 static void tsubst_enum	(tree, tree, tree);
155 static tree add_to_template_args (tree, tree);
156 static tree add_outermost_template_args (tree, tree);
157 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
158 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
159 					     tree);
160 static int type_unification_real (tree, tree, tree, const tree *,
161 				  unsigned int, int, unification_kind_t, int,
162 				  vec<deferred_access_check, va_gc> **,
163 				  bool);
164 static void note_template_header (int);
165 static tree convert_nontype_argument_function (tree, tree, tsubst_flags_t);
166 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
167 static tree convert_template_argument (tree, tree, tree,
168 				       tsubst_flags_t, int, tree);
169 static tree for_each_template_parm (tree, tree_fn_t, void*,
170 				    hash_set<tree> *, bool, tree_fn_t = NULL);
171 static tree expand_template_argument_pack (tree);
172 static tree build_template_parm_index (int, int, int, tree, tree);
173 static bool inline_needs_template_parms (tree, bool);
174 static void push_inline_template_parms_recursive (tree, int);
175 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
176 static int mark_template_parm (tree, void *);
177 static int template_parm_this_level_p (tree, void *);
178 static tree tsubst_friend_function (tree, tree);
179 static tree tsubst_friend_class (tree, tree);
180 static int can_complete_type_without_circularity (tree);
181 static tree get_bindings (tree, tree, tree, bool);
182 static int template_decl_level (tree);
183 static int check_cv_quals_for_unify (int, tree, tree);
184 static void template_parm_level_and_index (tree, int*, int*);
185 static int unify_pack_expansion (tree, tree, tree,
186 				 tree, unification_kind_t, bool, bool);
187 static tree copy_template_args (tree);
188 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
189 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
190 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
191 static tree most_specialized_partial_spec (tree, tsubst_flags_t);
192 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
193 static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
194 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
195 static bool check_specialization_scope (void);
196 static tree process_partial_specialization (tree);
197 static void set_current_access_from_decl (tree);
198 static enum template_base_result get_template_base (tree, tree, tree, tree,
199 						    bool , tree *);
200 static tree try_class_unification (tree, tree, tree, tree, bool);
201 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
202 					   tree, tree);
203 static bool template_template_parm_bindings_ok_p (tree, tree);
204 static void tsubst_default_arguments (tree, tsubst_flags_t);
205 static tree for_each_template_parm_r (tree *, int *, void *);
206 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
207 static void copy_default_args_to_explicit_spec (tree);
208 static bool invalid_nontype_parm_type_p (tree, tsubst_flags_t);
209 static bool dependent_template_arg_p (tree);
210 static bool any_template_arguments_need_structural_equality_p (tree);
211 static bool dependent_type_p_r (tree);
212 static tree tsubst_copy	(tree, tree, tsubst_flags_t, tree);
213 static tree tsubst_decl (tree, tree, tsubst_flags_t);
214 static void perform_typedefs_access_check (tree tmpl, tree targs);
215 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
216 							location_t);
217 static tree listify (tree);
218 static tree listify_autos (tree, tree);
219 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
220 static tree instantiate_alias_template (tree, tree, tsubst_flags_t);
221 static bool complex_alias_template_p (const_tree tmpl);
222 static tree tsubst_attributes (tree, tree, tsubst_flags_t, tree);
223 static tree canonicalize_expr_argument (tree, tsubst_flags_t);
224 static tree make_argument_pack (tree);
225 static void register_parameter_specializations (tree, tree);
226 static tree enclosing_instantiation_of (tree tctx);
227 
228 /* Make the current scope suitable for access checking when we are
229    processing T.  T can be FUNCTION_DECL for instantiated function
230    template, VAR_DECL for static member variable, or TYPE_DECL for
231    alias template (needed by instantiate_decl).  */
232 
233 static void
push_access_scope(tree t)234 push_access_scope (tree t)
235 {
236   gcc_assert (VAR_OR_FUNCTION_DECL_P (t)
237 	      || TREE_CODE (t) == TYPE_DECL);
238 
239   if (DECL_FRIEND_CONTEXT (t))
240     push_nested_class (DECL_FRIEND_CONTEXT (t));
241   else if (DECL_CLASS_SCOPE_P (t))
242     push_nested_class (DECL_CONTEXT (t));
243   else
244     push_to_top_level ();
245 
246   if (TREE_CODE (t) == FUNCTION_DECL)
247     {
248       saved_access_scope = tree_cons
249 	(NULL_TREE, current_function_decl, saved_access_scope);
250       current_function_decl = t;
251     }
252 }
253 
254 /* Restore the scope set up by push_access_scope.  T is the node we
255    are processing.  */
256 
257 static void
pop_access_scope(tree t)258 pop_access_scope (tree t)
259 {
260   if (TREE_CODE (t) == FUNCTION_DECL)
261     {
262       current_function_decl = TREE_VALUE (saved_access_scope);
263       saved_access_scope = TREE_CHAIN (saved_access_scope);
264     }
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 ("data member %qD cannot be a member template", decl);
304   else if (DECL_TEMPLATE_INFO (decl))
305     {
306       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
307 	{
308 	  check_member_template (DECL_TI_TEMPLATE (decl));
309 	  return DECL_TI_TEMPLATE (decl);
310 	}
311       else
312 	return decl;
313     }
314   else
315     error ("invalid member template declaration %qD", decl);
316 
317   return error_mark_node;
318 }
319 
320 /* Create a template info node.  */
321 
322 tree
build_template_info(tree template_decl,tree template_args)323 build_template_info (tree template_decl, tree template_args)
324 {
325   tree result = make_node (TEMPLATE_INFO);
326   TI_TEMPLATE (result) = template_decl;
327   TI_ARGS (result) = template_args;
328   return result;
329 }
330 
331 /* Return the template info node corresponding to T, whatever T is.  */
332 
333 tree
get_template_info(const_tree t)334 get_template_info (const_tree t)
335 {
336   tree tinfo = NULL_TREE;
337 
338   if (!t || t == error_mark_node)
339     return NULL;
340 
341   if (TREE_CODE (t) == NAMESPACE_DECL
342       || TREE_CODE (t) == PARM_DECL)
343     return NULL;
344 
345   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
346     tinfo = DECL_TEMPLATE_INFO (t);
347 
348   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
349     t = TREE_TYPE (t);
350 
351   if (OVERLOAD_TYPE_P (t))
352     tinfo = TYPE_TEMPLATE_INFO (t);
353   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
354     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
355 
356   return tinfo;
357 }
358 
359 /* Returns the template nesting level of the indicated class TYPE.
360 
361    For example, in:
362      template <class T>
363      struct A
364      {
365        template <class U>
366        struct B {};
367      };
368 
369    A<T>::B<U> has depth two, while A<T> has depth one.
370    Both A<T>::B<int> and A<int>::B<U> have depth one, if
371    they are instantiations, not specializations.
372 
373    This function is guaranteed to return 0 if passed NULL_TREE so
374    that, for example, `template_class_depth (current_class_type)' is
375    always safe.  */
376 
377 int
template_class_depth(tree type)378 template_class_depth (tree type)
379 {
380   int depth;
381 
382   for (depth = 0; type && TREE_CODE (type) != NAMESPACE_DECL; )
383     {
384       tree tinfo = get_template_info (type);
385 
386       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
387 	  && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
388 	++depth;
389 
390       if (DECL_P (type))
391 	type = CP_DECL_CONTEXT (type);
392       else if (LAMBDA_TYPE_P (type))
393 	type = LAMBDA_TYPE_EXTRA_SCOPE (type);
394       else
395 	type = CP_TYPE_CONTEXT (type);
396     }
397 
398   return depth;
399 }
400 
401 /* Return TRUE if NODE instantiates a template that has arguments of
402    its own, be it directly a primary template or indirectly through a
403    partial specializations.  */
404 static bool
instantiates_primary_template_p(tree node)405 instantiates_primary_template_p (tree node)
406 {
407   tree tinfo = get_template_info (node);
408   if (!tinfo)
409     return false;
410 
411   tree tmpl = TI_TEMPLATE (tinfo);
412   if (PRIMARY_TEMPLATE_P (tmpl))
413     return true;
414 
415   if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
416     return false;
417 
418   /* So now we know we have a specialization, but it could be a full
419      or a partial specialization.  To tell which, compare the depth of
420      its template arguments with those of its context.  */
421 
422   tree ctxt = DECL_CONTEXT (tmpl);
423   tree ctinfo = get_template_info (ctxt);
424   if (!ctinfo)
425     return true;
426 
427   return (TMPL_ARGS_DEPTH (TI_ARGS (tinfo))
428 	  > TMPL_ARGS_DEPTH (TI_ARGS (ctinfo)));
429 }
430 
431 /* Subroutine of maybe_begin_member_template_processing.
432    Returns true if processing DECL needs us to push template parms.  */
433 
434 static bool
inline_needs_template_parms(tree decl,bool nsdmi)435 inline_needs_template_parms (tree decl, bool nsdmi)
436 {
437   if (!decl || (!nsdmi && ! DECL_TEMPLATE_INFO (decl)))
438     return false;
439 
440   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
441 	  > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
442 }
443 
444 /* Subroutine of maybe_begin_member_template_processing.
445    Push the template parms in PARMS, starting from LEVELS steps into the
446    chain, and ending at the beginning, since template parms are listed
447    innermost first.  */
448 
449 static void
push_inline_template_parms_recursive(tree parmlist,int levels)450 push_inline_template_parms_recursive (tree parmlist, int levels)
451 {
452   tree parms = TREE_VALUE (parmlist);
453   int i;
454 
455   if (levels > 1)
456     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
457 
458   ++processing_template_decl;
459   current_template_parms
460     = tree_cons (size_int (processing_template_decl),
461 		 parms, current_template_parms);
462   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
463 
464   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
465 	       NULL);
466   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
467     {
468       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
469 
470       if (error_operand_p (parm))
471 	continue;
472 
473       gcc_assert (DECL_P (parm));
474 
475       switch (TREE_CODE (parm))
476 	{
477 	case TYPE_DECL:
478 	case TEMPLATE_DECL:
479 	  pushdecl (parm);
480 	  break;
481 
482 	case PARM_DECL:
483 	  /* Push the CONST_DECL.  */
484 	  pushdecl (TEMPLATE_PARM_DECL (DECL_INITIAL (parm)));
485 	  break;
486 
487 	default:
488 	  gcc_unreachable ();
489 	}
490     }
491 }
492 
493 /* Restore the template parameter context for a member template, a
494    friend template defined in a class definition, or a non-template
495    member of template class.  */
496 
497 void
maybe_begin_member_template_processing(tree decl)498 maybe_begin_member_template_processing (tree decl)
499 {
500   tree parms;
501   int levels = 0;
502   bool nsdmi = TREE_CODE (decl) == FIELD_DECL;
503 
504   if (nsdmi)
505     {
506       tree ctx = DECL_CONTEXT (decl);
507       decl = (CLASSTYPE_TEMPLATE_INFO (ctx)
508 	      /* Disregard full specializations (c++/60999).  */
509 	      && uses_template_parms (ctx)
510 	      ? CLASSTYPE_TI_TEMPLATE (ctx) : NULL_TREE);
511     }
512 
513   if (inline_needs_template_parms (decl, nsdmi))
514     {
515       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
516       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
517 
518       if (DECL_TEMPLATE_SPECIALIZATION (decl))
519 	{
520 	  --levels;
521 	  parms = TREE_CHAIN (parms);
522 	}
523 
524       push_inline_template_parms_recursive (parms, levels);
525     }
526 
527   /* Remember how many levels of template parameters we pushed so that
528      we can pop them later.  */
529   inline_parm_levels.safe_push (levels);
530 }
531 
532 /* Undo the effects of maybe_begin_member_template_processing.  */
533 
534 void
maybe_end_member_template_processing(void)535 maybe_end_member_template_processing (void)
536 {
537   int i;
538   int last;
539 
540   if (inline_parm_levels.length () == 0)
541     return;
542 
543   last = inline_parm_levels.pop ();
544   for (i = 0; i < last; ++i)
545     {
546       --processing_template_decl;
547       current_template_parms = TREE_CHAIN (current_template_parms);
548       poplevel (0, 0, 0);
549     }
550 }
551 
552 /* Return a new template argument vector which contains all of ARGS,
553    but has as its innermost set of arguments the EXTRA_ARGS.  */
554 
555 static tree
add_to_template_args(tree args,tree extra_args)556 add_to_template_args (tree args, tree extra_args)
557 {
558   tree new_args;
559   int extra_depth;
560   int i;
561   int j;
562 
563   if (args == NULL_TREE || extra_args == error_mark_node)
564     return extra_args;
565 
566   extra_depth = TMPL_ARGS_DEPTH (extra_args);
567   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
568 
569   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
570     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
571 
572   for (j = 1; j <= extra_depth; ++j, ++i)
573     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
574 
575   return new_args;
576 }
577 
578 /* Like add_to_template_args, but only the outermost ARGS are added to
579    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
580    (EXTRA_ARGS) levels are added.  This function is used to combine
581    the template arguments from a partial instantiation with the
582    template arguments used to attain the full instantiation from the
583    partial instantiation.  */
584 
585 static tree
add_outermost_template_args(tree args,tree extra_args)586 add_outermost_template_args (tree args, tree extra_args)
587 {
588   tree new_args;
589 
590   /* If there are more levels of EXTRA_ARGS than there are ARGS,
591      something very fishy is going on.  */
592   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
593 
594   /* If *all* the new arguments will be the EXTRA_ARGS, just return
595      them.  */
596   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
597     return extra_args;
598 
599   /* For the moment, we make ARGS look like it contains fewer levels.  */
600   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
601 
602   new_args = add_to_template_args (args, extra_args);
603 
604   /* Now, we restore ARGS to its full dimensions.  */
605   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
606 
607   return new_args;
608 }
609 
610 /* Return the N levels of innermost template arguments from the ARGS.  */
611 
612 tree
get_innermost_template_args(tree args,int n)613 get_innermost_template_args (tree args, int n)
614 {
615   tree new_args;
616   int extra_levels;
617   int i;
618 
619   gcc_assert (n >= 0);
620 
621   /* If N is 1, just return the innermost set of template arguments.  */
622   if (n == 1)
623     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
624 
625   /* If we're not removing anything, just return the arguments we were
626      given.  */
627   extra_levels = TMPL_ARGS_DEPTH (args) - n;
628   gcc_assert (extra_levels >= 0);
629   if (extra_levels == 0)
630     return args;
631 
632   /* Make a new set of arguments, not containing the outer arguments.  */
633   new_args = make_tree_vec (n);
634   for (i = 1; i <= n; ++i)
635     SET_TMPL_ARGS_LEVEL (new_args, i,
636 			 TMPL_ARGS_LEVEL (args, i + extra_levels));
637 
638   return new_args;
639 }
640 
641 /* The inverse of get_innermost_template_args: Return all but the innermost
642    EXTRA_LEVELS levels of template arguments from the ARGS.  */
643 
644 static tree
strip_innermost_template_args(tree args,int extra_levels)645 strip_innermost_template_args (tree args, int extra_levels)
646 {
647   tree new_args;
648   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
649   int i;
650 
651   gcc_assert (n >= 0);
652 
653   /* If N is 1, just return the outermost set of template arguments.  */
654   if (n == 1)
655     return TMPL_ARGS_LEVEL (args, 1);
656 
657   /* If we're not removing anything, just return the arguments we were
658      given.  */
659   gcc_assert (extra_levels >= 0);
660   if (extra_levels == 0)
661     return args;
662 
663   /* Make a new set of arguments, not containing the inner arguments.  */
664   new_args = make_tree_vec (n);
665   for (i = 1; i <= n; ++i)
666     SET_TMPL_ARGS_LEVEL (new_args, i,
667 			 TMPL_ARGS_LEVEL (args, i));
668 
669   return new_args;
670 }
671 
672 /* We've got a template header coming up; push to a new level for storing
673    the parms.  */
674 
675 void
begin_template_parm_list(void)676 begin_template_parm_list (void)
677 {
678   /* We use a non-tag-transparent scope here, which causes pushtag to
679      put tags in this scope, rather than in the enclosing class or
680      namespace scope.  This is the right thing, since we want
681      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
682      global template class, push_template_decl handles putting the
683      TEMPLATE_DECL into top-level scope.  For a nested template class,
684      e.g.:
685 
686        template <class T> struct S1 {
687 	 template <class T> struct S2 {};
688        };
689 
690      pushtag contains special code to insert the TEMPLATE_DECL for S2
691      at the right scope.  */
692   begin_scope (sk_template_parms, NULL);
693   ++processing_template_decl;
694   ++processing_template_parmlist;
695   note_template_header (0);
696 
697   /* Add a dummy parameter level while we process the parameter list.  */
698   current_template_parms
699     = tree_cons (size_int (processing_template_decl),
700 		 make_tree_vec (0),
701 		 current_template_parms);
702 }
703 
704 /* This routine is called when a specialization is declared.  If it is
705    invalid to declare a specialization here, an error is reported and
706    false is returned, otherwise this routine will return true.  */
707 
708 static bool
check_specialization_scope(void)709 check_specialization_scope (void)
710 {
711   tree scope = current_scope ();
712 
713   /* [temp.expl.spec]
714 
715      An explicit specialization shall be declared in the namespace of
716      which the template is a member, or, for member templates, in the
717      namespace of which the enclosing class or enclosing class
718      template is a member.  An explicit specialization of a member
719      function, member class or static data member of a class template
720      shall be declared in the namespace of which the class template
721      is a member.  */
722   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
723     {
724       error ("explicit specialization in non-namespace scope %qD", scope);
725       return false;
726     }
727 
728   /* [temp.expl.spec]
729 
730      In an explicit specialization declaration for a member of a class
731      template or a member template that appears in namespace scope,
732      the member template and some of its enclosing class templates may
733      remain unspecialized, except that the declaration shall not
734      explicitly specialize a class member template if its enclosing
735      class templates are not explicitly specialized as well.  */
736   if (current_template_parms)
737     {
738       error ("enclosing class templates are not explicitly specialized");
739       return false;
740     }
741 
742   return true;
743 }
744 
745 /* We've just seen template <>.  */
746 
747 bool
begin_specialization(void)748 begin_specialization (void)
749 {
750   begin_scope (sk_template_spec, NULL);
751   note_template_header (1);
752   return check_specialization_scope ();
753 }
754 
755 /* Called at then end of processing a declaration preceded by
756    template<>.  */
757 
758 void
end_specialization(void)759 end_specialization (void)
760 {
761   finish_scope ();
762   reset_specialization ();
763 }
764 
765 /* Any template <>'s that we have seen thus far are not referring to a
766    function specialization.  */
767 
768 void
reset_specialization(void)769 reset_specialization (void)
770 {
771   processing_specialization = 0;
772   template_header_count = 0;
773 }
774 
775 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
776    it was of the form template <>.  */
777 
778 static void
note_template_header(int specialization)779 note_template_header (int specialization)
780 {
781   processing_specialization = specialization;
782   template_header_count++;
783 }
784 
785 /* We're beginning an explicit instantiation.  */
786 
787 void
begin_explicit_instantiation(void)788 begin_explicit_instantiation (void)
789 {
790   gcc_assert (!processing_explicit_instantiation);
791   processing_explicit_instantiation = true;
792 }
793 
794 
795 void
end_explicit_instantiation(void)796 end_explicit_instantiation (void)
797 {
798   gcc_assert (processing_explicit_instantiation);
799   processing_explicit_instantiation = false;
800 }
801 
802 /* An explicit specialization or partial specialization of TMPL is being
803    declared.  Check that the namespace in which the specialization is
804    occurring is permissible.  Returns false iff it is invalid to
805    specialize TMPL in the current namespace.  */
806 
807 static bool
check_specialization_namespace(tree tmpl)808 check_specialization_namespace (tree tmpl)
809 {
810   tree tpl_ns = decl_namespace_context (tmpl);
811 
812   /* [tmpl.expl.spec]
813 
814      An explicit specialization shall be declared in a namespace enclosing the
815      specialized template. An explicit specialization whose declarator-id is
816      not qualified shall be declared in the nearest enclosing namespace of the
817      template, or, if the namespace is inline (7.3.1), any namespace from its
818      enclosing namespace set.  */
819   if (current_scope() != DECL_CONTEXT (tmpl)
820       && !at_namespace_scope_p ())
821     {
822       error ("specialization of %qD must appear at namespace scope", tmpl);
823       return false;
824     }
825 
826   if (is_nested_namespace (current_namespace, tpl_ns, cxx_dialect < cxx11))
827     /* Same or enclosing namespace.  */
828     return true;
829   else
830     {
831       permerror (input_location,
832 		 "specialization of %qD in different namespace", tmpl);
833       inform (DECL_SOURCE_LOCATION (tmpl),
834 	      "  from definition of %q#D", tmpl);
835       return false;
836     }
837 }
838 
839 /* SPEC is an explicit instantiation.  Check that it is valid to
840    perform this explicit instantiation in the current namespace.  */
841 
842 static void
check_explicit_instantiation_namespace(tree spec)843 check_explicit_instantiation_namespace (tree spec)
844 {
845   tree ns;
846 
847   /* DR 275: An explicit instantiation shall appear in an enclosing
848      namespace of its template.  */
849   ns = decl_namespace_context (spec);
850   if (!is_nested_namespace (current_namespace, ns))
851     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
852 	       "(which does not enclose namespace %qD)",
853 	       spec, current_namespace, ns);
854 }
855 
856 // Returns the type of a template specialization only if that
857 // specialization needs to be defined. Otherwise (e.g., if the type has
858 // already been defined), the function returns NULL_TREE.
859 static tree
maybe_new_partial_specialization(tree type)860 maybe_new_partial_specialization (tree type)
861 {
862   // An implicit instantiation of an incomplete type implies
863   // the definition of a new class template.
864   //
865   //    template<typename T>
866   //      struct S;
867   //
868   //    template<typename T>
869   //      struct S<T*>;
870   //
871   // Here, S<T*> is an implicit instantiation of S whose type
872   // is incomplete.
873   if (CLASSTYPE_IMPLICIT_INSTANTIATION (type) && !COMPLETE_TYPE_P (type))
874     return type;
875 
876   // It can also be the case that TYPE is a completed specialization.
877   // Continuing the previous example, suppose we also declare:
878   //
879   //    template<typename T>
880   //      requires Integral<T>
881   //        struct S<T*>;
882   //
883   // Here, S<T*> refers to the specialization S<T*> defined
884   // above. However, we need to differentiate definitions because
885   // we intend to define a new partial specialization. In this case,
886   // we rely on the fact that the constraints are different for
887   // this declaration than that above.
888   //
889   // Note that we also get here for injected class names and
890   // late-parsed template definitions. We must ensure that we
891   // do not create new type declarations for those cases.
892   if (flag_concepts && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
893     {
894       tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
895       tree args = CLASSTYPE_TI_ARGS (type);
896 
897       // If there are no template parameters, this cannot be a new
898       // partial template specializtion?
899       if (!current_template_parms)
900         return NULL_TREE;
901 
902       // The injected-class-name is not a new partial specialization.
903       if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
904 	return NULL_TREE;
905 
906       // If the constraints are not the same as those of the primary
907       // then, we can probably create a new specialization.
908       tree type_constr = current_template_constraints ();
909 
910       if (type == TREE_TYPE (tmpl))
911 	{
912 	  tree main_constr = get_constraints (tmpl);
913 	  if (equivalent_constraints (type_constr, main_constr))
914 	    return NULL_TREE;
915 	}
916 
917       // Also, if there's a pre-existing specialization with matching
918       // constraints, then this also isn't new.
919       tree specs = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
920       while (specs)
921         {
922           tree spec_tmpl = TREE_VALUE (specs);
923           tree spec_args = TREE_PURPOSE (specs);
924           tree spec_constr = get_constraints (spec_tmpl);
925           if (comp_template_args (args, spec_args)
926 	      && equivalent_constraints (type_constr, spec_constr))
927             return NULL_TREE;
928           specs = TREE_CHAIN (specs);
929         }
930 
931       // Create a new type node (and corresponding type decl)
932       // for the newly declared specialization.
933       tree t = make_class_type (TREE_CODE (type));
934       CLASSTYPE_DECLARED_CLASS (t) = CLASSTYPE_DECLARED_CLASS (type);
935       SET_TYPE_TEMPLATE_INFO (t, build_template_info (tmpl, args));
936 
937       /* We only need a separate type node for storing the definition of this
938 	 partial specialization; uses of S<T*> are unconstrained, so all are
939 	 equivalent.  So keep TYPE_CANONICAL the same.  */
940       TYPE_CANONICAL (t) = TYPE_CANONICAL (type);
941 
942       // Build the corresponding type decl.
943       tree d = create_implicit_typedef (DECL_NAME (tmpl), t);
944       DECL_CONTEXT (d) = TYPE_CONTEXT (t);
945       DECL_SOURCE_LOCATION (d) = input_location;
946 
947       return t;
948     }
949 
950   return NULL_TREE;
951 }
952 
953 /* The TYPE is being declared.  If it is a template type, that means it
954    is a partial specialization.  Do appropriate error-checking.  */
955 
956 tree
maybe_process_partial_specialization(tree type)957 maybe_process_partial_specialization (tree type)
958 {
959   tree context;
960 
961   if (type == error_mark_node)
962     return error_mark_node;
963 
964   /* A lambda that appears in specialization context is not itself a
965      specialization.  */
966   if (CLASS_TYPE_P (type) && CLASSTYPE_LAMBDA_EXPR (type))
967     return type;
968 
969   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
970     {
971       error ("name of class shadows template template parameter %qD",
972 	     TYPE_NAME (type));
973       return error_mark_node;
974     }
975 
976   context = TYPE_CONTEXT (type);
977 
978   if (TYPE_ALIAS_P (type))
979     {
980       tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (type);
981 
982       if (tinfo && DECL_ALIAS_TEMPLATE_P (TI_TEMPLATE (tinfo)))
983 	error ("specialization of alias template %qD",
984 	       TI_TEMPLATE (tinfo));
985       else
986 	error ("explicit specialization of non-template %qT", type);
987       return error_mark_node;
988     }
989   else if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
990     {
991       /* This is for ordinary explicit specialization and partial
992 	 specialization of a template class such as:
993 
994 	   template <> class C<int>;
995 
996 	 or:
997 
998 	   template <class T> class C<T*>;
999 
1000 	 Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
1001 
1002       if (tree t = maybe_new_partial_specialization (type))
1003 	{
1004 	  if (!check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (t))
1005 	      && !at_namespace_scope_p ())
1006 	    return error_mark_node;
1007 	  SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (t);
1008 	  DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (t)) = input_location;
1009 	  if (processing_template_decl)
1010 	    {
1011 	      tree decl = push_template_decl (TYPE_MAIN_DECL (t));
1012 	      if (decl == error_mark_node)
1013 		return error_mark_node;
1014 	      return TREE_TYPE (decl);
1015 	    }
1016 	}
1017       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
1018 	error ("specialization of %qT after instantiation", type);
1019       else if (errorcount && !processing_specialization
1020 	        && CLASSTYPE_TEMPLATE_SPECIALIZATION (type)
1021 	       && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
1022 	/* Trying to define a specialization either without a template<> header
1023 	   or in an inappropriate place.  We've already given an error, so just
1024 	   bail now so we don't actually define the specialization.  */
1025 	return error_mark_node;
1026     }
1027   else if (CLASS_TYPE_P (type)
1028 	   && !CLASSTYPE_USE_TEMPLATE (type)
1029 	   && CLASSTYPE_TEMPLATE_INFO (type)
1030 	   && context && CLASS_TYPE_P (context)
1031 	   && CLASSTYPE_TEMPLATE_INFO (context))
1032     {
1033       /* This is for an explicit specialization of member class
1034 	 template according to [temp.expl.spec/18]:
1035 
1036 	   template <> template <class U> class C<int>::D;
1037 
1038 	 The context `C<int>' must be an implicit instantiation.
1039 	 Otherwise this is just a member class template declared
1040 	 earlier like:
1041 
1042 	   template <> class C<int> { template <class U> class D; };
1043 	   template <> template <class U> class C<int>::D;
1044 
1045 	 In the first case, `C<int>::D' is a specialization of `C<T>::D'
1046 	 while in the second case, `C<int>::D' is a primary template
1047 	 and `C<T>::D' may not exist.  */
1048 
1049       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
1050 	  && !COMPLETE_TYPE_P (type))
1051 	{
1052 	  tree t;
1053 	  tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
1054 
1055 	  if (current_namespace
1056 	      != decl_namespace_context (tmpl))
1057 	    {
1058 	      permerror (input_location,
1059 			 "specializing %q#T in different namespace", type);
1060 	      permerror (DECL_SOURCE_LOCATION (tmpl),
1061 			 "  from definition of %q#D", tmpl);
1062 	    }
1063 
1064 	  /* Check for invalid specialization after instantiation:
1065 
1066 	       template <> template <> class C<int>::D<int>;
1067 	       template <> template <class U> class C<int>::D;  */
1068 
1069 	  for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
1070 	       t; t = TREE_CHAIN (t))
1071 	    {
1072 	      tree inst = TREE_VALUE (t);
1073 	      if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst)
1074 		  || !COMPLETE_OR_OPEN_TYPE_P (inst))
1075 		{
1076 		  /* We already have a full specialization of this partial
1077 		     instantiation, or a full specialization has been
1078 		     looked up but not instantiated.  Reassign it to the
1079 		     new member specialization template.  */
1080 		  spec_entry elt;
1081 		  spec_entry *entry;
1082 
1083 		  elt.tmpl = most_general_template (tmpl);
1084 		  elt.args = CLASSTYPE_TI_ARGS (inst);
1085 		  elt.spec = inst;
1086 
1087 		  type_specializations->remove_elt (&elt);
1088 
1089 		  elt.tmpl = tmpl;
1090 		  elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
1091 
1092 		  spec_entry **slot
1093 		    = type_specializations->find_slot (&elt, INSERT);
1094 		  entry = ggc_alloc<spec_entry> ();
1095 		  *entry = elt;
1096 		  *slot = entry;
1097 		}
1098 	      else
1099 		/* But if we've had an implicit instantiation, that's a
1100 		   problem ([temp.expl.spec]/6).  */
1101 		error ("specialization %qT after instantiation %qT",
1102 		       type, inst);
1103 	    }
1104 
1105 	  /* Mark TYPE as a specialization.  And as a result, we only
1106 	     have one level of template argument for the innermost
1107 	     class template.  */
1108 	  SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1109 	  DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1110 	  CLASSTYPE_TI_ARGS (type)
1111 	    = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
1112 	}
1113     }
1114   else if (processing_specialization)
1115     {
1116        /* Someday C++0x may allow for enum template specialization.  */
1117       if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
1118 	  && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
1119 	pedwarn (input_location, OPT_Wpedantic, "template specialization "
1120 		 "of %qD not allowed by ISO C++", type);
1121       else
1122 	{
1123 	  error ("explicit specialization of non-template %qT", type);
1124 	  return error_mark_node;
1125 	}
1126     }
1127 
1128   return type;
1129 }
1130 
1131 /* Returns nonzero if we can optimize the retrieval of specializations
1132    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
1133    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
1134 
1135 static inline bool
optimize_specialization_lookup_p(tree tmpl)1136 optimize_specialization_lookup_p (tree tmpl)
1137 {
1138   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
1139 	  && DECL_CLASS_SCOPE_P (tmpl)
1140 	  /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
1141 	     parameter.  */
1142 	  && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
1143 	  /* The optimized lookup depends on the fact that the
1144 	     template arguments for the member function template apply
1145 	     purely to the containing class, which is not true if the
1146 	     containing class is an explicit or partial
1147 	     specialization.  */
1148 	  && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
1149 	  && !DECL_MEMBER_TEMPLATE_P (tmpl)
1150 	  && !DECL_CONV_FN_P (tmpl)
1151 	  /* It is possible to have a template that is not a member
1152 	     template and is not a member of a template class:
1153 
1154 	     template <typename T>
1155 	     struct S { friend A::f(); };
1156 
1157 	     Here, the friend function is a template, but the context does
1158 	     not have template information.  The optimized lookup relies
1159 	     on having ARGS be the template arguments for both the class
1160 	     and the function template.  */
1161 	  && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
1162 }
1163 
1164 /* Make sure ARGS doesn't use any inappropriate typedefs; we should have
1165    gone through coerce_template_parms by now.  */
1166 
1167 static void
verify_unstripped_args_1(tree inner)1168 verify_unstripped_args_1 (tree inner)
1169 {
1170   for (int i = 0; i < TREE_VEC_LENGTH (inner); ++i)
1171     {
1172       tree arg = TREE_VEC_ELT (inner, i);
1173       if (TREE_CODE (arg) == TEMPLATE_DECL)
1174 	/* OK */;
1175       else if (TYPE_P (arg))
1176 	gcc_assert (strip_typedefs (arg, NULL) == arg);
1177       else if (ARGUMENT_PACK_P (arg))
1178 	verify_unstripped_args_1 (ARGUMENT_PACK_ARGS (arg));
1179       else if (strip_typedefs (TREE_TYPE (arg), NULL) != TREE_TYPE (arg))
1180 	/* Allow typedefs on the type of a non-type argument, since a
1181 	   parameter can have them.  */;
1182       else
1183 	gcc_assert (strip_typedefs_expr (arg, NULL) == arg);
1184     }
1185 }
1186 
1187 static void
verify_unstripped_args(tree args)1188 verify_unstripped_args (tree args)
1189 {
1190   ++processing_template_decl;
1191   if (!any_dependent_template_arguments_p (args))
1192     verify_unstripped_args_1 (INNERMOST_TEMPLATE_ARGS (args));
1193   --processing_template_decl;
1194 }
1195 
1196 /* Retrieve the specialization (in the sense of [temp.spec] - a
1197    specialization is either an instantiation or an explicit
1198    specialization) of TMPL for the given template ARGS.  If there is
1199    no such specialization, return NULL_TREE.  The ARGS are a vector of
1200    arguments, or a vector of vectors of arguments, in the case of
1201    templates with more than one level of parameters.
1202 
1203    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
1204    then we search for a partial specialization matching ARGS.  This
1205    parameter is ignored if TMPL is not a class template.
1206 
1207    We can also look up a FIELD_DECL, if it is a lambda capture pack; the
1208    result is a NONTYPE_ARGUMENT_PACK.  */
1209 
1210 static tree
retrieve_specialization(tree tmpl,tree args,hashval_t hash)1211 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1212 {
1213   if (tmpl == NULL_TREE)
1214     return NULL_TREE;
1215 
1216   if (args == error_mark_node)
1217     return NULL_TREE;
1218 
1219   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL
1220 	      || TREE_CODE (tmpl) == FIELD_DECL);
1221 
1222   /* There should be as many levels of arguments as there are
1223      levels of parameters.  */
1224   gcc_assert (TMPL_ARGS_DEPTH (args)
1225 	      == (TREE_CODE (tmpl) == TEMPLATE_DECL
1226 		  ? TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl))
1227 		  : template_class_depth (DECL_CONTEXT (tmpl))));
1228 
1229   if (flag_checking)
1230     verify_unstripped_args (args);
1231 
1232   /* Lambda functions in templates aren't instantiated normally, but through
1233      tsubst_lambda_expr.  */
1234   if (lambda_fn_in_template_p (tmpl))
1235     return NULL_TREE;
1236 
1237   if (optimize_specialization_lookup_p (tmpl))
1238     {
1239       /* The template arguments actually apply to the containing
1240 	 class.  Find the class specialization with those
1241 	 arguments.  */
1242       tree class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
1243       tree class_specialization
1244 	= retrieve_specialization (class_template, args, 0);
1245       if (!class_specialization)
1246 	return NULL_TREE;
1247 
1248       /* Find the instance of TMPL.  */
1249       tree fns = get_class_binding (class_specialization, DECL_NAME (tmpl));
1250       for (ovl_iterator iter (fns); iter; ++iter)
1251 	{
1252 	  tree fn = *iter;
1253 	  if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1254 	      /* using-declarations can add base methods to the method vec,
1255 		 and we don't want those here.  */
1256 	      && DECL_CONTEXT (fn) == class_specialization)
1257 	    return fn;
1258 	}
1259       return NULL_TREE;
1260     }
1261   else
1262     {
1263       spec_entry *found;
1264       spec_entry elt;
1265       hash_table<spec_hasher> *specializations;
1266 
1267       elt.tmpl = tmpl;
1268       elt.args = args;
1269       elt.spec = NULL_TREE;
1270 
1271       if (DECL_CLASS_TEMPLATE_P (tmpl))
1272 	specializations = type_specializations;
1273       else
1274 	specializations = decl_specializations;
1275 
1276       if (hash == 0)
1277 	hash = spec_hasher::hash (&elt);
1278       found = specializations->find_with_hash (&elt, hash);
1279       if (found)
1280 	return found->spec;
1281     }
1282 
1283   return NULL_TREE;
1284 }
1285 
1286 /* Like retrieve_specialization, but for local declarations.  */
1287 
1288 tree
retrieve_local_specialization(tree tmpl)1289 retrieve_local_specialization (tree tmpl)
1290 {
1291   if (local_specializations == NULL)
1292     return NULL_TREE;
1293 
1294   tree *slot = local_specializations->get (tmpl);
1295   return slot ? *slot : NULL_TREE;
1296 }
1297 
1298 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1299 
1300 int
is_specialization_of(tree decl,tree tmpl)1301 is_specialization_of (tree decl, tree tmpl)
1302 {
1303   tree t;
1304 
1305   if (TREE_CODE (decl) == FUNCTION_DECL)
1306     {
1307       for (t = decl;
1308 	   t != NULL_TREE;
1309 	   t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1310 	if (t == tmpl)
1311 	  return 1;
1312     }
1313   else
1314     {
1315       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1316 
1317       for (t = TREE_TYPE (decl);
1318 	   t != NULL_TREE;
1319 	   t = CLASSTYPE_USE_TEMPLATE (t)
1320 	     ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1321 	if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1322 	  return 1;
1323     }
1324 
1325   return 0;
1326 }
1327 
1328 /* Returns nonzero iff DECL is a specialization of friend declaration
1329    FRIEND_DECL according to [temp.friend].  */
1330 
1331 bool
is_specialization_of_friend(tree decl,tree friend_decl)1332 is_specialization_of_friend (tree decl, tree friend_decl)
1333 {
1334   bool need_template = true;
1335   int template_depth;
1336 
1337   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1338 	      || TREE_CODE (decl) == TYPE_DECL);
1339 
1340   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1341      of a template class, we want to check if DECL is a specialization
1342      if this.  */
1343   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1344       && DECL_TEMPLATE_INFO (friend_decl)
1345       && !DECL_USE_TEMPLATE (friend_decl))
1346     {
1347       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1348       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1349       need_template = false;
1350     }
1351   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1352 	   && !PRIMARY_TEMPLATE_P (friend_decl))
1353     need_template = false;
1354 
1355   /* There is nothing to do if this is not a template friend.  */
1356   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1357     return false;
1358 
1359   if (is_specialization_of (decl, friend_decl))
1360     return true;
1361 
1362   /* [temp.friend/6]
1363      A member of a class template may be declared to be a friend of a
1364      non-template class.  In this case, the corresponding member of
1365      every specialization of the class template is a friend of the
1366      class granting friendship.
1367 
1368      For example, given a template friend declaration
1369 
1370        template <class T> friend void A<T>::f();
1371 
1372      the member function below is considered a friend
1373 
1374        template <> struct A<int> {
1375 	 void f();
1376        };
1377 
1378      For this type of template friend, TEMPLATE_DEPTH below will be
1379      nonzero.  To determine if DECL is a friend of FRIEND, we first
1380      check if the enclosing class is a specialization of another.  */
1381 
1382   template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1383   if (template_depth
1384       && DECL_CLASS_SCOPE_P (decl)
1385       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1386 			       CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1387     {
1388       /* Next, we check the members themselves.  In order to handle
1389 	 a few tricky cases, such as when FRIEND_DECL's are
1390 
1391 	   template <class T> friend void A<T>::g(T t);
1392 	   template <class T> template <T t> friend void A<T>::h();
1393 
1394 	 and DECL's are
1395 
1396 	   void A<int>::g(int);
1397 	   template <int> void A<int>::h();
1398 
1399 	 we need to figure out ARGS, the template arguments from
1400 	 the context of DECL.  This is required for template substitution
1401 	 of `T' in the function parameter of `g' and template parameter
1402 	 of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1403 
1404       tree context = DECL_CONTEXT (decl);
1405       tree args = NULL_TREE;
1406       int current_depth = 0;
1407 
1408       while (current_depth < template_depth)
1409 	{
1410 	  if (CLASSTYPE_TEMPLATE_INFO (context))
1411 	    {
1412 	      if (current_depth == 0)
1413 		args = TYPE_TI_ARGS (context);
1414 	      else
1415 		args = add_to_template_args (TYPE_TI_ARGS (context), args);
1416 	      current_depth++;
1417 	    }
1418 	  context = TYPE_CONTEXT (context);
1419 	}
1420 
1421       if (TREE_CODE (decl) == FUNCTION_DECL)
1422 	{
1423 	  bool is_template;
1424 	  tree friend_type;
1425 	  tree decl_type;
1426 	  tree friend_args_type;
1427 	  tree decl_args_type;
1428 
1429 	  /* Make sure that both DECL and FRIEND_DECL are templates or
1430 	     non-templates.  */
1431 	  is_template = DECL_TEMPLATE_INFO (decl)
1432 			&& PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1433 	  if (need_template ^ is_template)
1434 	    return false;
1435 	  else if (is_template)
1436 	    {
1437 	      /* If both are templates, check template parameter list.  */
1438 	      tree friend_parms
1439 		= tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1440 					 args, tf_none);
1441 	      if (!comp_template_parms
1442 		     (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1443 		      friend_parms))
1444 		return false;
1445 
1446 	      decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1447 	    }
1448 	  else
1449 	    decl_type = TREE_TYPE (decl);
1450 
1451 	  friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1452 					      tf_none, NULL_TREE);
1453 	  if (friend_type == error_mark_node)
1454 	    return false;
1455 
1456 	  /* Check if return types match.  */
1457 	  if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1458 	    return false;
1459 
1460 	  /* Check if function parameter types match, ignoring the
1461 	     `this' parameter.  */
1462 	  friend_args_type = TYPE_ARG_TYPES (friend_type);
1463 	  decl_args_type = TYPE_ARG_TYPES (decl_type);
1464 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1465 	    friend_args_type = TREE_CHAIN (friend_args_type);
1466 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1467 	    decl_args_type = TREE_CHAIN (decl_args_type);
1468 
1469 	  return compparms (decl_args_type, friend_args_type);
1470 	}
1471       else
1472 	{
1473 	  /* DECL is a TYPE_DECL */
1474 	  bool is_template;
1475 	  tree decl_type = TREE_TYPE (decl);
1476 
1477 	  /* Make sure that both DECL and FRIEND_DECL are templates or
1478 	     non-templates.  */
1479 	  is_template
1480 	    = CLASSTYPE_TEMPLATE_INFO (decl_type)
1481 	      && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1482 
1483 	  if (need_template ^ is_template)
1484 	    return false;
1485 	  else if (is_template)
1486 	    {
1487 	      tree friend_parms;
1488 	      /* If both are templates, check the name of the two
1489 		 TEMPLATE_DECL's first because is_friend didn't.  */
1490 	      if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1491 		  != DECL_NAME (friend_decl))
1492 		return false;
1493 
1494 	      /* Now check template parameter list.  */
1495 	      friend_parms
1496 		= tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1497 					 args, tf_none);
1498 	      return comp_template_parms
1499 		(DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1500 		 friend_parms);
1501 	    }
1502 	  else
1503 	    return (DECL_NAME (decl)
1504 		    == DECL_NAME (friend_decl));
1505 	}
1506     }
1507   return false;
1508 }
1509 
1510 /* Register the specialization SPEC as a specialization of TMPL with
1511    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1512    is actually just a friend declaration.  ATTRLIST is the list of
1513    attributes that the specialization is declared with or NULL when
1514    it isn't.  Returns SPEC, or an equivalent prior declaration, if
1515    available.
1516 
1517    We also store instantiations of field packs in the hash table, even
1518    though they are not themselves templates, to make lookup easier.  */
1519 
1520 static tree
register_specialization(tree spec,tree tmpl,tree args,bool is_friend,hashval_t hash)1521 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1522 			 hashval_t hash)
1523 {
1524   tree fn;
1525   spec_entry **slot = NULL;
1526   spec_entry elt;
1527 
1528   gcc_assert ((TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec))
1529 	      || (TREE_CODE (tmpl) == FIELD_DECL
1530 		  && TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK));
1531 
1532   if (TREE_CODE (spec) == FUNCTION_DECL
1533       && uses_template_parms (DECL_TI_ARGS (spec)))
1534     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1535        register it; we want the corresponding TEMPLATE_DECL instead.
1536        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1537        the more obvious `uses_template_parms (spec)' to avoid problems
1538        with default function arguments.  In particular, given
1539        something like this:
1540 
1541 	  template <class T> void f(T t1, T t = T())
1542 
1543        the default argument expression is not substituted for in an
1544        instantiation unless and until it is actually needed.  */
1545     return spec;
1546 
1547   if (optimize_specialization_lookup_p (tmpl))
1548     /* We don't put these specializations in the hash table, but we might
1549        want to give an error about a mismatch.  */
1550     fn = retrieve_specialization (tmpl, args, 0);
1551   else
1552     {
1553       elt.tmpl = tmpl;
1554       elt.args = args;
1555       elt.spec = spec;
1556 
1557       if (hash == 0)
1558 	hash = spec_hasher::hash (&elt);
1559 
1560       slot =
1561 	decl_specializations->find_slot_with_hash (&elt, hash, INSERT);
1562       if (*slot)
1563 	fn = ((spec_entry *) *slot)->spec;
1564       else
1565 	fn = NULL_TREE;
1566     }
1567 
1568   /* We can sometimes try to re-register a specialization that we've
1569      already got.  In particular, regenerate_decl_from_template calls
1570      duplicate_decls which will update the specialization list.  But,
1571      we'll still get called again here anyhow.  It's more convenient
1572      to simply allow this than to try to prevent it.  */
1573   if (fn == spec)
1574     return spec;
1575   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1576     {
1577       if (DECL_TEMPLATE_INSTANTIATION (fn))
1578 	{
1579 	  if (DECL_ODR_USED (fn)
1580 	      || DECL_EXPLICIT_INSTANTIATION (fn))
1581 	    {
1582 	      error ("specialization of %qD after instantiation",
1583 		     fn);
1584 	      return error_mark_node;
1585 	    }
1586 	  else
1587 	    {
1588 	      tree clone;
1589 	      /* This situation should occur only if the first
1590 		 specialization is an implicit instantiation, the
1591 		 second is an explicit specialization, and the
1592 		 implicit instantiation has not yet been used.  That
1593 		 situation can occur if we have implicitly
1594 		 instantiated a member function and then specialized
1595 		 it later.
1596 
1597 		 We can also wind up here if a friend declaration that
1598 		 looked like an instantiation turns out to be a
1599 		 specialization:
1600 
1601 		   template <class T> void foo(T);
1602 		   class S { friend void foo<>(int) };
1603 		   template <> void foo(int);
1604 
1605 		 We transform the existing DECL in place so that any
1606 		 pointers to it become pointers to the updated
1607 		 declaration.
1608 
1609 		 If there was a definition for the template, but not
1610 		 for the specialization, we want this to look as if
1611 		 there were no definition, and vice versa.  */
1612 	      DECL_INITIAL (fn) = NULL_TREE;
1613 	      duplicate_decls (spec, fn, is_friend);
1614 	      /* The call to duplicate_decls will have applied
1615 		 [temp.expl.spec]:
1616 
1617 		   An explicit specialization of a function template
1618 		   is inline only if it is explicitly declared to be,
1619 		   and independently of whether its function template
1620 		   is.
1621 
1622 		to the primary function; now copy the inline bits to
1623 		the various clones.  */
1624 	      FOR_EACH_CLONE (clone, fn)
1625 		{
1626 		  DECL_DECLARED_INLINE_P (clone)
1627 		    = DECL_DECLARED_INLINE_P (fn);
1628 		  DECL_SOURCE_LOCATION (clone)
1629 		    = DECL_SOURCE_LOCATION (fn);
1630 		  DECL_DELETED_FN (clone)
1631 		    = DECL_DELETED_FN (fn);
1632 		}
1633 	      check_specialization_namespace (tmpl);
1634 
1635 	      return fn;
1636 	    }
1637 	}
1638       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1639 	{
1640 	  tree dd = duplicate_decls (spec, fn, is_friend);
1641 	  if (dd == error_mark_node)
1642 	    /* We've already complained in duplicate_decls.  */
1643 	    return error_mark_node;
1644 
1645 	  if (dd == NULL_TREE && DECL_INITIAL (spec))
1646 	    /* Dup decl failed, but this is a new definition. Set the
1647 	       line number so any errors match this new
1648 	       definition.  */
1649 	    DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1650 
1651 	  return fn;
1652 	}
1653     }
1654   else if (fn)
1655     return duplicate_decls (spec, fn, is_friend);
1656 
1657   /* A specialization must be declared in the same namespace as the
1658      template it is specializing.  */
1659   if (DECL_P (spec) && DECL_TEMPLATE_SPECIALIZATION (spec)
1660       && !check_specialization_namespace (tmpl))
1661     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1662 
1663   if (slot != NULL /* !optimize_specialization_lookup_p (tmpl) */)
1664     {
1665       spec_entry *entry = ggc_alloc<spec_entry> ();
1666       gcc_assert (tmpl && args && spec);
1667       *entry = elt;
1668       *slot = entry;
1669       if ((TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1670 	   && PRIMARY_TEMPLATE_P (tmpl)
1671 	   && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1672 	  || variable_template_p (tmpl))
1673 	/* If TMPL is a forward declaration of a template function, keep a list
1674 	   of all specializations in case we need to reassign them to a friend
1675 	   template later in tsubst_friend_function.
1676 
1677 	   Also keep a list of all variable template instantiations so that
1678 	   process_partial_specialization can check whether a later partial
1679 	   specialization would have used it.  */
1680 	DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1681 	  = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1682     }
1683 
1684   return spec;
1685 }
1686 
1687 /* Returns true iff two spec_entry nodes are equivalent.  */
1688 
1689 int comparing_specializations;
1690 
1691 bool
equal(spec_entry * e1,spec_entry * e2)1692 spec_hasher::equal (spec_entry *e1, spec_entry *e2)
1693 {
1694   int equal;
1695 
1696   ++comparing_specializations;
1697   equal = (e1->tmpl == e2->tmpl
1698 	   && comp_template_args (e1->args, e2->args));
1699   if (equal && flag_concepts
1700       /* tmpl could be a FIELD_DECL for a capture pack.  */
1701       && TREE_CODE (e1->tmpl) == TEMPLATE_DECL
1702       && VAR_P (DECL_TEMPLATE_RESULT (e1->tmpl))
1703       && uses_template_parms (e1->args))
1704     {
1705       /* Partial specializations of a variable template can be distinguished by
1706 	 constraints.  */
1707       tree c1 = e1->spec ? get_constraints (e1->spec) : NULL_TREE;
1708       tree c2 = e2->spec ? get_constraints (e2->spec) : NULL_TREE;
1709       equal = equivalent_constraints (c1, c2);
1710     }
1711   --comparing_specializations;
1712 
1713   return equal;
1714 }
1715 
1716 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1717 
1718 static hashval_t
hash_tmpl_and_args(tree tmpl,tree args)1719 hash_tmpl_and_args (tree tmpl, tree args)
1720 {
1721   hashval_t val = iterative_hash_object (DECL_UID (tmpl), 0);
1722   return iterative_hash_template_arg (args, val);
1723 }
1724 
1725 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1726    ignoring SPEC.  */
1727 
1728 hashval_t
hash(spec_entry * e)1729 spec_hasher::hash (spec_entry *e)
1730 {
1731   return hash_tmpl_and_args (e->tmpl, e->args);
1732 }
1733 
1734 /* Recursively calculate a hash value for a template argument ARG, for use
1735    in the hash tables of template specializations.  */
1736 
1737 hashval_t
iterative_hash_template_arg(tree arg,hashval_t val)1738 iterative_hash_template_arg (tree arg, hashval_t val)
1739 {
1740   unsigned HOST_WIDE_INT i;
1741   enum tree_code code;
1742   char tclass;
1743 
1744   if (arg == NULL_TREE)
1745     return iterative_hash_object (arg, val);
1746 
1747   if (!TYPE_P (arg))
1748     STRIP_NOPS (arg);
1749 
1750   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1751     gcc_unreachable ();
1752 
1753   code = TREE_CODE (arg);
1754   tclass = TREE_CODE_CLASS (code);
1755 
1756   val = iterative_hash_object (code, val);
1757 
1758   switch (code)
1759     {
1760     case ERROR_MARK:
1761       return val;
1762 
1763     case IDENTIFIER_NODE:
1764       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1765 
1766     case TREE_VEC:
1767       {
1768 	int i, len = TREE_VEC_LENGTH (arg);
1769 	for (i = 0; i < len; ++i)
1770 	  val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1771 	return val;
1772       }
1773 
1774     case TYPE_PACK_EXPANSION:
1775     case EXPR_PACK_EXPANSION:
1776       val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1777       return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1778 
1779     case TYPE_ARGUMENT_PACK:
1780     case NONTYPE_ARGUMENT_PACK:
1781       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1782 
1783     case TREE_LIST:
1784       for (; arg; arg = TREE_CHAIN (arg))
1785 	val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1786       return val;
1787 
1788     case OVERLOAD:
1789       for (lkp_iterator iter (arg); iter; ++iter)
1790 	val = iterative_hash_template_arg (*iter, val);
1791       return val;
1792 
1793     case CONSTRUCTOR:
1794       {
1795 	tree field, value;
1796 	iterative_hash_template_arg (TREE_TYPE (arg), val);
1797 	FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1798 	  {
1799 	    val = iterative_hash_template_arg (field, val);
1800 	    val = iterative_hash_template_arg (value, val);
1801 	  }
1802 	return val;
1803       }
1804 
1805     case PARM_DECL:
1806       if (!DECL_ARTIFICIAL (arg))
1807 	{
1808 	  val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1809 	  val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1810 	}
1811       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1812 
1813     case TARGET_EXPR:
1814       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1815 
1816     case PTRMEM_CST:
1817       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1818       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1819 
1820     case TEMPLATE_PARM_INDEX:
1821       val = iterative_hash_template_arg
1822 	(TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1823       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1824       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1825 
1826     case TRAIT_EXPR:
1827       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1828       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1829       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1830 
1831     case BASELINK:
1832       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1833 					 val);
1834       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1835 					  val);
1836 
1837     case MODOP_EXPR:
1838       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1839       code = TREE_CODE (TREE_OPERAND (arg, 1));
1840       val = iterative_hash_object (code, val);
1841       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1842 
1843     case LAMBDA_EXPR:
1844       /* A lambda can't appear in a template arg, but don't crash on
1845 	 erroneous input.  */
1846       gcc_assert (seen_error ());
1847       return val;
1848 
1849     case CAST_EXPR:
1850     case IMPLICIT_CONV_EXPR:
1851     case STATIC_CAST_EXPR:
1852     case REINTERPRET_CAST_EXPR:
1853     case CONST_CAST_EXPR:
1854     case DYNAMIC_CAST_EXPR:
1855     case NEW_EXPR:
1856       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1857       /* Now hash operands as usual.  */
1858       break;
1859 
1860     default:
1861       break;
1862     }
1863 
1864   switch (tclass)
1865     {
1866     case tcc_type:
1867       if (alias_template_specialization_p (arg))
1868 	{
1869 	  // We want an alias specialization that survived strip_typedefs
1870 	  // to hash differently from its TYPE_CANONICAL, to avoid hash
1871 	  // collisions that compare as different in template_args_equal.
1872 	  // These could be dependent specializations that strip_typedefs
1873 	  // left alone, or untouched specializations because
1874 	  // coerce_template_parms returns the unconverted template
1875 	  // arguments if it sees incomplete argument packs.
1876 	  tree ti = TYPE_ALIAS_TEMPLATE_INFO (arg);
1877 	  return hash_tmpl_and_args (TI_TEMPLATE (ti), TI_ARGS (ti));
1878 	}
1879       if (TYPE_CANONICAL (arg))
1880 	return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1881 				      val);
1882       else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1883 	return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1884       /* Otherwise just compare the types during lookup.  */
1885       return val;
1886 
1887     case tcc_declaration:
1888     case tcc_constant:
1889       return iterative_hash_expr (arg, val);
1890 
1891     default:
1892       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1893       {
1894 	unsigned n = cp_tree_operand_length (arg);
1895 	for (i = 0; i < n; ++i)
1896 	  val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1897 	return val;
1898       }
1899     }
1900   gcc_unreachable ();
1901   return 0;
1902 }
1903 
1904 /* Unregister the specialization SPEC as a specialization of TMPL.
1905    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1906    if the SPEC was listed as a specialization of TMPL.
1907 
1908    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1909 
1910 bool
reregister_specialization(tree spec,tree tinfo,tree new_spec)1911 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1912 {
1913   spec_entry *entry;
1914   spec_entry elt;
1915 
1916   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1917   elt.args = TI_ARGS (tinfo);
1918   elt.spec = NULL_TREE;
1919 
1920   entry = decl_specializations->find (&elt);
1921   if (entry != NULL)
1922     {
1923       gcc_assert (entry->spec == spec || entry->spec == new_spec);
1924       gcc_assert (new_spec != NULL_TREE);
1925       entry->spec = new_spec;
1926       return 1;
1927     }
1928 
1929   return 0;
1930 }
1931 
1932 /* Like register_specialization, but for local declarations.  We are
1933    registering SPEC, an instantiation of TMPL.  */
1934 
1935 void
register_local_specialization(tree spec,tree tmpl)1936 register_local_specialization (tree spec, tree tmpl)
1937 {
1938   gcc_assert (tmpl != spec);
1939   local_specializations->put (tmpl, spec);
1940 }
1941 
1942 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1943    specialized class.  */
1944 
1945 bool
explicit_class_specialization_p(tree type)1946 explicit_class_specialization_p (tree type)
1947 {
1948   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1949     return false;
1950   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1951 }
1952 
1953 /* Print the list of functions at FNS, going through all the overloads
1954    for each element of the list.  Alternatively, FNS can not be a
1955    TREE_LIST, in which case it will be printed together with all the
1956    overloads.
1957 
1958    MORE and *STR should respectively be FALSE and NULL when the function
1959    is called from the outside.  They are used internally on recursive
1960    calls.  print_candidates manages the two parameters and leaves NULL
1961    in *STR when it ends.  */
1962 
1963 static void
1964 print_candidates_1 (tree fns, char **str, bool more = false)
1965 {
1966   if (TREE_CODE (fns) == TREE_LIST)
1967     for (; fns; fns = TREE_CHAIN (fns))
1968       print_candidates_1 (TREE_VALUE (fns), str, more || TREE_CHAIN (fns));
1969   else
1970     for (lkp_iterator iter (fns); iter;)
1971       {
1972 	tree cand = *iter;
1973 	++iter;
1974 
1975 	const char *pfx = *str;
1976 	if (!pfx)
1977 	  {
1978 	    if (more || iter)
1979 	      pfx = _("candidates are:");
1980 	    else
1981 	      pfx = _("candidate is:");
1982 	    *str = get_spaces (pfx);
1983 	  }
1984 	inform (DECL_SOURCE_LOCATION (cand), "%s %#qD", pfx, cand);
1985       }
1986 }
1987 
1988 /* Print the list of candidate FNS in an error message.  FNS can also
1989    be a TREE_LIST of non-functions in the case of an ambiguous lookup.  */
1990 
1991 void
print_candidates(tree fns)1992 print_candidates (tree fns)
1993 {
1994   char *str = NULL;
1995   print_candidates_1 (fns, &str);
1996   free (str);
1997 }
1998 
1999 /* Get a (possibly) constrained template declaration for the
2000    purpose of ordering candidates.  */
2001 static tree
get_template_for_ordering(tree list)2002 get_template_for_ordering (tree list)
2003 {
2004   gcc_assert (TREE_CODE (list) == TREE_LIST);
2005   tree f = TREE_VALUE (list);
2006   if (tree ti = DECL_TEMPLATE_INFO (f))
2007     return TI_TEMPLATE (ti);
2008   return f;
2009 }
2010 
2011 /* Among candidates having the same signature, return the
2012    most constrained or NULL_TREE if there is no best candidate.
2013    If the signatures of candidates vary (e.g., template
2014    specialization vs. member function), then there can be no
2015    most constrained.
2016 
2017    Note that we don't compare constraints on the functions
2018    themselves, but rather those of their templates. */
2019 static tree
most_constrained_function(tree candidates)2020 most_constrained_function (tree candidates)
2021 {
2022   // Try to find the best candidate in a first pass.
2023   tree champ = candidates;
2024   for (tree c = TREE_CHAIN (champ); c; c = TREE_CHAIN (c))
2025     {
2026       int winner = more_constrained (get_template_for_ordering (champ),
2027                                      get_template_for_ordering (c));
2028       if (winner == -1)
2029         champ = c; // The candidate is more constrained
2030       else if (winner == 0)
2031         return NULL_TREE; // Neither is more constrained
2032     }
2033 
2034   // Verify that the champ is better than previous candidates.
2035   for (tree c = candidates; c != champ; c = TREE_CHAIN (c)) {
2036     if (!more_constrained (get_template_for_ordering (champ),
2037                            get_template_for_ordering (c)))
2038       return NULL_TREE;
2039   }
2040 
2041   return champ;
2042 }
2043 
2044 
2045 /* Returns the template (one of the functions given by TEMPLATE_ID)
2046    which can be specialized to match the indicated DECL with the
2047    explicit template args given in TEMPLATE_ID.  The DECL may be
2048    NULL_TREE if none is available.  In that case, the functions in
2049    TEMPLATE_ID are non-members.
2050 
2051    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
2052    specialization of a member template.
2053 
2054    The TEMPLATE_COUNT is the number of references to qualifying
2055    template classes that appeared in the name of the function. See
2056    check_explicit_specialization for a more accurate description.
2057 
2058    TSK indicates what kind of template declaration (if any) is being
2059    declared.  TSK_TEMPLATE indicates that the declaration given by
2060    DECL, though a FUNCTION_DECL, has template parameters, and is
2061    therefore a template function.
2062 
2063    The template args (those explicitly specified and those deduced)
2064    are output in a newly created vector *TARGS_OUT.
2065 
2066    If it is impossible to determine the result, an error message is
2067    issued.  The error_mark_node is returned to indicate failure.  */
2068 
2069 static tree
determine_specialization(tree template_id,tree decl,tree * targs_out,int need_member_template,int template_count,tmpl_spec_kind tsk)2070 determine_specialization (tree template_id,
2071 			  tree decl,
2072 			  tree* targs_out,
2073 			  int need_member_template,
2074 			  int template_count,
2075 			  tmpl_spec_kind tsk)
2076 {
2077   tree fns;
2078   tree targs;
2079   tree explicit_targs;
2080   tree candidates = NULL_TREE;
2081 
2082   /* A TREE_LIST of templates of which DECL may be a specialization.
2083      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
2084      corresponding TREE_PURPOSE is the set of template arguments that,
2085      when used to instantiate the template, would produce a function
2086      with the signature of DECL.  */
2087   tree templates = NULL_TREE;
2088   int header_count;
2089   cp_binding_level *b;
2090 
2091   *targs_out = NULL_TREE;
2092 
2093   if (template_id == error_mark_node || decl == error_mark_node)
2094     return error_mark_node;
2095 
2096   /* We shouldn't be specializing a member template of an
2097      unspecialized class template; we already gave an error in
2098      check_specialization_scope, now avoid crashing.  */
2099   if (!VAR_P (decl)
2100       && template_count && DECL_CLASS_SCOPE_P (decl)
2101       && template_class_depth (DECL_CONTEXT (decl)) > 0)
2102     {
2103       gcc_assert (errorcount);
2104       return error_mark_node;
2105     }
2106 
2107   fns = TREE_OPERAND (template_id, 0);
2108   explicit_targs = TREE_OPERAND (template_id, 1);
2109 
2110   if (fns == error_mark_node)
2111     return error_mark_node;
2112 
2113   /* Check for baselinks.  */
2114   if (BASELINK_P (fns))
2115     fns = BASELINK_FUNCTIONS (fns);
2116 
2117   if (TREE_CODE (decl) == FUNCTION_DECL && !is_overloaded_fn (fns))
2118     {
2119       error ("%qD is not a function template", fns);
2120       return error_mark_node;
2121     }
2122   else if (VAR_P (decl) && !variable_template_p (fns))
2123     {
2124       error ("%qD is not a variable template", fns);
2125       return error_mark_node;
2126     }
2127 
2128   /* Count the number of template headers specified for this
2129      specialization.  */
2130   header_count = 0;
2131   for (b = current_binding_level;
2132        b->kind == sk_template_parms;
2133        b = b->level_chain)
2134     ++header_count;
2135 
2136   tree orig_fns = fns;
2137 
2138   if (variable_template_p (fns))
2139     {
2140       tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (fns));
2141       targs = coerce_template_parms (parms, explicit_targs, fns,
2142 				     tf_warning_or_error,
2143 				     /*req_all*/true, /*use_defarg*/true);
2144       if (targs != error_mark_node)
2145         templates = tree_cons (targs, fns, templates);
2146     }
2147   else for (lkp_iterator iter (fns); iter; ++iter)
2148     {
2149       tree fn = *iter;
2150 
2151       if (TREE_CODE (fn) == TEMPLATE_DECL)
2152 	{
2153 	  tree decl_arg_types;
2154 	  tree fn_arg_types;
2155 	  tree insttype;
2156 
2157 	  /* In case of explicit specialization, we need to check if
2158 	     the number of template headers appearing in the specialization
2159 	     is correct. This is usually done in check_explicit_specialization,
2160 	     but the check done there cannot be exhaustive when specializing
2161 	     member functions. Consider the following code:
2162 
2163 	     template <> void A<int>::f(int);
2164 	     template <> template <> void A<int>::f(int);
2165 
2166 	     Assuming that A<int> is not itself an explicit specialization
2167 	     already, the first line specializes "f" which is a non-template
2168 	     member function, whilst the second line specializes "f" which
2169 	     is a template member function. So both lines are syntactically
2170 	     correct, and check_explicit_specialization does not reject
2171 	     them.
2172 
2173 	     Here, we can do better, as we are matching the specialization
2174 	     against the declarations. We count the number of template
2175 	     headers, and we check if they match TEMPLATE_COUNT + 1
2176 	     (TEMPLATE_COUNT is the number of qualifying template classes,
2177 	     plus there must be another header for the member template
2178 	     itself).
2179 
2180 	     Notice that if header_count is zero, this is not a
2181 	     specialization but rather a template instantiation, so there
2182 	     is no check we can perform here.  */
2183 	  if (header_count && header_count != template_count + 1)
2184 	    continue;
2185 
2186 	  /* Check that the number of template arguments at the
2187 	     innermost level for DECL is the same as for FN.  */
2188 	  if (current_binding_level->kind == sk_template_parms
2189 	      && !current_binding_level->explicit_spec_p
2190 	      && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
2191 		  != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
2192 				      (current_template_parms))))
2193 	    continue;
2194 
2195 	  /* DECL might be a specialization of FN.  */
2196 	  decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2197 	  fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
2198 
2199 	  /* For a non-static member function, we need to make sure
2200 	     that the const qualification is the same.  Since
2201 	     get_bindings does not try to merge the "this" parameter,
2202 	     we must do the comparison explicitly.  */
2203 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
2204 	    {
2205 	      if (!same_type_p (TREE_VALUE (fn_arg_types),
2206 				TREE_VALUE (decl_arg_types)))
2207 		continue;
2208 
2209 	      /* And the ref-qualification.  */
2210 	      if (type_memfn_rqual (TREE_TYPE (decl))
2211 		  != type_memfn_rqual (TREE_TYPE (fn)))
2212 		continue;
2213 	    }
2214 
2215 	  /* Skip the "this" parameter and, for constructors of
2216 	     classes with virtual bases, the VTT parameter.  A
2217 	     full specialization of a constructor will have a VTT
2218 	     parameter, but a template never will.  */
2219 	  decl_arg_types
2220 	    = skip_artificial_parms_for (decl, decl_arg_types);
2221 	  fn_arg_types
2222 	    = skip_artificial_parms_for (fn, fn_arg_types);
2223 
2224 	  /* Function templates cannot be specializations; there are
2225 	     no partial specializations of functions.  Therefore, if
2226 	     the type of DECL does not match FN, there is no
2227 	     match.
2228 
2229              Note that it should never be the case that we have both
2230              candidates added here, and for regular member functions
2231              below. */
2232 	  if (tsk == tsk_template)
2233 	    {
2234 	      if (compparms (fn_arg_types, decl_arg_types))
2235 		candidates = tree_cons (NULL_TREE, fn, candidates);
2236 	      continue;
2237 	    }
2238 
2239 	  /* See whether this function might be a specialization of this
2240 	     template.  Suppress access control because we might be trying
2241 	     to make this specialization a friend, and we have already done
2242 	     access control for the declaration of the specialization.  */
2243 	  push_deferring_access_checks (dk_no_check);
2244 	  targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
2245 	  pop_deferring_access_checks ();
2246 
2247 	  if (!targs)
2248 	    /* We cannot deduce template arguments that when used to
2249 	       specialize TMPL will produce DECL.  */
2250 	    continue;
2251 
2252 	  if (uses_template_parms (targs))
2253 	    /* We deduced something involving 'auto', which isn't a valid
2254 	       template argument.  */
2255 	    continue;
2256 
2257           /* Remove, from the set of candidates, all those functions
2258              whose constraints are not satisfied. */
2259           if (flag_concepts && !constraints_satisfied_p (fn, targs))
2260             continue;
2261 
2262           // Then, try to form the new function type.
2263 	  insttype = tsubst (TREE_TYPE (fn), targs, tf_fndecl_type, NULL_TREE);
2264 	  if (insttype == error_mark_node)
2265 	    continue;
2266 	  fn_arg_types
2267 	    = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (insttype));
2268 	  if (!compparms (fn_arg_types, decl_arg_types))
2269 	    continue;
2270 
2271 	  /* Save this template, and the arguments deduced.  */
2272 	  templates = tree_cons (targs, fn, templates);
2273 	}
2274       else if (need_member_template)
2275 	/* FN is an ordinary member function, and we need a
2276 	   specialization of a member template.  */
2277 	;
2278       else if (TREE_CODE (fn) != FUNCTION_DECL)
2279 	/* We can get IDENTIFIER_NODEs here in certain erroneous
2280 	   cases.  */
2281 	;
2282       else if (!DECL_FUNCTION_MEMBER_P (fn))
2283 	/* This is just an ordinary non-member function.  Nothing can
2284 	   be a specialization of that.  */
2285 	;
2286       else if (DECL_ARTIFICIAL (fn))
2287 	/* Cannot specialize functions that are created implicitly.  */
2288 	;
2289       else
2290 	{
2291 	  tree decl_arg_types;
2292 
2293 	  /* This is an ordinary member function.  However, since
2294 	     we're here, we can assume its enclosing class is a
2295 	     template class.  For example,
2296 
2297 	       template <typename T> struct S { void f(); };
2298 	       template <> void S<int>::f() {}
2299 
2300 	     Here, S<int>::f is a non-template, but S<int> is a
2301 	     template class.  If FN has the same type as DECL, we
2302 	     might be in business.  */
2303 
2304 	  if (!DECL_TEMPLATE_INFO (fn))
2305 	    /* Its enclosing class is an explicit specialization
2306 	       of a template class.  This is not a candidate.  */
2307 	    continue;
2308 
2309 	  if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2310 			    TREE_TYPE (TREE_TYPE (fn))))
2311 	    /* The return types differ.  */
2312 	    continue;
2313 
2314 	  /* Adjust the type of DECL in case FN is a static member.  */
2315 	  decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2316 	  if (DECL_STATIC_FUNCTION_P (fn)
2317 	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2318 	    decl_arg_types = TREE_CHAIN (decl_arg_types);
2319 
2320 	  if (!compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2321 			 decl_arg_types))
2322             continue;
2323 
2324 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2325 	      && (type_memfn_rqual (TREE_TYPE (decl))
2326 		  != type_memfn_rqual (TREE_TYPE (fn))))
2327 	    continue;
2328 
2329           // If the deduced arguments do not satisfy the constraints,
2330           // this is not a candidate.
2331           if (flag_concepts && !constraints_satisfied_p (fn))
2332             continue;
2333 
2334           // Add the candidate.
2335           candidates = tree_cons (NULL_TREE, fn, candidates);
2336 	}
2337     }
2338 
2339   if (templates && TREE_CHAIN (templates))
2340     {
2341       /* We have:
2342 
2343 	   [temp.expl.spec]
2344 
2345 	   It is possible for a specialization with a given function
2346 	   signature to be instantiated from more than one function
2347 	   template.  In such cases, explicit specification of the
2348 	   template arguments must be used to uniquely identify the
2349 	   function template specialization being specialized.
2350 
2351 	 Note that here, there's no suggestion that we're supposed to
2352 	 determine which of the candidate templates is most
2353 	 specialized.  However, we, also have:
2354 
2355 	   [temp.func.order]
2356 
2357 	   Partial ordering of overloaded function template
2358 	   declarations is used in the following contexts to select
2359 	   the function template to which a function template
2360 	   specialization refers:
2361 
2362 	   -- when an explicit specialization refers to a function
2363 	      template.
2364 
2365 	 So, we do use the partial ordering rules, at least for now.
2366 	 This extension can only serve to make invalid programs valid,
2367 	 so it's safe.  And, there is strong anecdotal evidence that
2368 	 the committee intended the partial ordering rules to apply;
2369 	 the EDG front end has that behavior, and John Spicer claims
2370 	 that the committee simply forgot to delete the wording in
2371 	 [temp.expl.spec].  */
2372       tree tmpl = most_specialized_instantiation (templates);
2373       if (tmpl != error_mark_node)
2374 	{
2375 	  templates = tmpl;
2376 	  TREE_CHAIN (templates) = NULL_TREE;
2377 	}
2378     }
2379 
2380   // Concepts allows multiple declarations of member functions
2381   // with the same signature. Like above, we need to rely on
2382   // on the partial ordering of those candidates to determine which
2383   // is the best.
2384   if (flag_concepts && candidates && TREE_CHAIN (candidates))
2385     {
2386       if (tree cand = most_constrained_function (candidates))
2387         {
2388           candidates = cand;
2389           TREE_CHAIN (cand) = NULL_TREE;
2390         }
2391     }
2392 
2393   if (templates == NULL_TREE && candidates == NULL_TREE)
2394     {
2395       error ("template-id %qD for %q+D does not match any template "
2396 	     "declaration", template_id, decl);
2397       if (header_count && header_count != template_count + 1)
2398 	inform (input_location, "saw %d %<template<>%>, need %d for "
2399 		"specializing a member function template",
2400 		header_count, template_count + 1);
2401       else
2402 	print_candidates (orig_fns);
2403       return error_mark_node;
2404     }
2405   else if ((templates && TREE_CHAIN (templates))
2406 	   || (candidates && TREE_CHAIN (candidates))
2407 	   || (templates && candidates))
2408     {
2409       error ("ambiguous template specialization %qD for %q+D",
2410 	     template_id, decl);
2411       candidates = chainon (candidates, templates);
2412       print_candidates (candidates);
2413       return error_mark_node;
2414     }
2415 
2416   /* We have one, and exactly one, match.  */
2417   if (candidates)
2418     {
2419       tree fn = TREE_VALUE (candidates);
2420       *targs_out = copy_node (DECL_TI_ARGS (fn));
2421 
2422       // Propagate the candidate's constraints to the declaration.
2423       set_constraints (decl, get_constraints (fn));
2424 
2425       /* DECL is a re-declaration or partial instantiation of a template
2426 	 function.  */
2427       if (TREE_CODE (fn) == TEMPLATE_DECL)
2428 	return fn;
2429       /* It was a specialization of an ordinary member function in a
2430 	 template class.  */
2431       return DECL_TI_TEMPLATE (fn);
2432     }
2433 
2434   /* It was a specialization of a template.  */
2435   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2436   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2437     {
2438       *targs_out = copy_node (targs);
2439       SET_TMPL_ARGS_LEVEL (*targs_out,
2440 			   TMPL_ARGS_DEPTH (*targs_out),
2441 			   TREE_PURPOSE (templates));
2442     }
2443   else
2444     *targs_out = TREE_PURPOSE (templates);
2445   return TREE_VALUE (templates);
2446 }
2447 
2448 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2449    but with the default argument values filled in from those in the
2450    TMPL_TYPES.  */
2451 
2452 static tree
copy_default_args_to_explicit_spec_1(tree spec_types,tree tmpl_types)2453 copy_default_args_to_explicit_spec_1 (tree spec_types,
2454 				      tree tmpl_types)
2455 {
2456   tree new_spec_types;
2457 
2458   if (!spec_types)
2459     return NULL_TREE;
2460 
2461   if (spec_types == void_list_node)
2462     return void_list_node;
2463 
2464   /* Substitute into the rest of the list.  */
2465   new_spec_types =
2466     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2467 					  TREE_CHAIN (tmpl_types));
2468 
2469   /* Add the default argument for this parameter.  */
2470   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2471 			 TREE_VALUE (spec_types),
2472 			 new_spec_types);
2473 }
2474 
2475 /* DECL is an explicit specialization.  Replicate default arguments
2476    from the template it specializes.  (That way, code like:
2477 
2478      template <class T> void f(T = 3);
2479      template <> void f(double);
2480      void g () { f (); }
2481 
2482    works, as required.)  An alternative approach would be to look up
2483    the correct default arguments at the call-site, but this approach
2484    is consistent with how implicit instantiations are handled.  */
2485 
2486 static void
copy_default_args_to_explicit_spec(tree decl)2487 copy_default_args_to_explicit_spec (tree decl)
2488 {
2489   tree tmpl;
2490   tree spec_types;
2491   tree tmpl_types;
2492   tree new_spec_types;
2493   tree old_type;
2494   tree new_type;
2495   tree t;
2496   tree object_type = NULL_TREE;
2497   tree in_charge = NULL_TREE;
2498   tree vtt = NULL_TREE;
2499 
2500   /* See if there's anything we need to do.  */
2501   tmpl = DECL_TI_TEMPLATE (decl);
2502   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2503   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2504     if (TREE_PURPOSE (t))
2505       break;
2506   if (!t)
2507     return;
2508 
2509   old_type = TREE_TYPE (decl);
2510   spec_types = TYPE_ARG_TYPES (old_type);
2511 
2512   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2513     {
2514       /* Remove the this pointer, but remember the object's type for
2515 	 CV quals.  */
2516       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2517       spec_types = TREE_CHAIN (spec_types);
2518       tmpl_types = TREE_CHAIN (tmpl_types);
2519 
2520       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2521 	{
2522 	  /* DECL may contain more parameters than TMPL due to the extra
2523 	     in-charge parameter in constructors and destructors.  */
2524 	  in_charge = spec_types;
2525 	  spec_types = TREE_CHAIN (spec_types);
2526 	}
2527       if (DECL_HAS_VTT_PARM_P (decl))
2528 	{
2529 	  vtt = spec_types;
2530 	  spec_types = TREE_CHAIN (spec_types);
2531 	}
2532     }
2533 
2534   /* Compute the merged default arguments.  */
2535   new_spec_types =
2536     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2537 
2538   /* Compute the new FUNCTION_TYPE.  */
2539   if (object_type)
2540     {
2541       if (vtt)
2542 	new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2543 					 TREE_VALUE (vtt),
2544 					 new_spec_types);
2545 
2546       if (in_charge)
2547 	/* Put the in-charge parameter back.  */
2548 	new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2549 					 TREE_VALUE (in_charge),
2550 					 new_spec_types);
2551 
2552       new_type = build_method_type_directly (object_type,
2553 					     TREE_TYPE (old_type),
2554 					     new_spec_types);
2555     }
2556   else
2557     new_type = build_function_type (TREE_TYPE (old_type),
2558 				    new_spec_types);
2559   new_type = cp_build_type_attribute_variant (new_type,
2560 					      TYPE_ATTRIBUTES (old_type));
2561   new_type = build_exception_variant (new_type,
2562 				      TYPE_RAISES_EXCEPTIONS (old_type));
2563 
2564   if (TYPE_HAS_LATE_RETURN_TYPE (old_type))
2565     TYPE_HAS_LATE_RETURN_TYPE (new_type) = 1;
2566 
2567   TREE_TYPE (decl) = new_type;
2568 }
2569 
2570 /* Return the number of template headers we expect to see for a definition
2571    or specialization of CTYPE or one of its non-template members.  */
2572 
2573 int
num_template_headers_for_class(tree ctype)2574 num_template_headers_for_class (tree ctype)
2575 {
2576   int num_templates = 0;
2577 
2578   while (ctype && CLASS_TYPE_P (ctype))
2579     {
2580       /* You're supposed to have one `template <...>' for every
2581 	 template class, but you don't need one for a full
2582 	 specialization.  For example:
2583 
2584 	 template <class T> struct S{};
2585 	 template <> struct S<int> { void f(); };
2586 	 void S<int>::f () {}
2587 
2588 	 is correct; there shouldn't be a `template <>' for the
2589 	 definition of `S<int>::f'.  */
2590       if (!CLASSTYPE_TEMPLATE_INFO (ctype))
2591 	/* If CTYPE does not have template information of any
2592 	   kind,  then it is not a template, nor is it nested
2593 	   within a template.  */
2594 	break;
2595       if (explicit_class_specialization_p (ctype))
2596 	break;
2597       if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (ctype)))
2598 	++num_templates;
2599 
2600       ctype = TYPE_CONTEXT (ctype);
2601     }
2602 
2603   return num_templates;
2604 }
2605 
2606 /* Do a simple sanity check on the template headers that precede the
2607    variable declaration DECL.  */
2608 
2609 void
check_template_variable(tree decl)2610 check_template_variable (tree decl)
2611 {
2612   tree ctx = CP_DECL_CONTEXT (decl);
2613   int wanted = num_template_headers_for_class (ctx);
2614   if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
2615       && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
2616     {
2617       if (cxx_dialect < cxx14)
2618         pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2619                  "variable templates only available with "
2620                  "-std=c++14 or -std=gnu++14");
2621 
2622       // Namespace-scope variable templates should have a template header.
2623       ++wanted;
2624     }
2625   if (template_header_count > wanted)
2626     {
2627       bool warned = pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2628 			     "too many template headers for %qD "
2629 	                     "(should be %d)",
2630 			     decl, wanted);
2631       if (warned && CLASS_TYPE_P (ctx)
2632 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (ctx))
2633 	inform (DECL_SOURCE_LOCATION (decl),
2634 		"members of an explicitly specialized class are defined "
2635 		"without a template header");
2636     }
2637 }
2638 
2639 /* An explicit specialization whose declarator-id or class-head-name is not
2640    qualified shall be declared in the nearest enclosing namespace of the
2641    template, or, if the namespace is inline (7.3.1), any namespace from its
2642    enclosing namespace set.
2643 
2644    If the name declared in the explicit instantiation is an unqualified name,
2645    the explicit instantiation shall appear in the namespace where its template
2646    is declared or, if that namespace is inline (7.3.1), any namespace from its
2647    enclosing namespace set.  */
2648 
2649 void
check_unqualified_spec_or_inst(tree t,location_t loc)2650 check_unqualified_spec_or_inst (tree t, location_t loc)
2651 {
2652   tree tmpl = most_general_template (t);
2653   if (DECL_NAMESPACE_SCOPE_P (tmpl)
2654       && !is_nested_namespace (current_namespace,
2655 			       CP_DECL_CONTEXT (tmpl), true))
2656     {
2657       if (processing_specialization)
2658 	permerror (loc, "explicit specialization of %qD outside its "
2659 		   "namespace must use a nested-name-specifier", tmpl);
2660       else if (processing_explicit_instantiation
2661 	       && cxx_dialect >= cxx11)
2662 	/* This was allowed in C++98, so only pedwarn.  */
2663 	pedwarn (loc, OPT_Wpedantic, "explicit instantiation of %qD "
2664 		 "outside its namespace must use a nested-name-"
2665 		 "specifier", tmpl);
2666     }
2667 }
2668 
2669 /* Warn for a template specialization SPEC that is missing some of a set
2670    of function or type attributes that the template TEMPL is declared with.
2671    ATTRLIST is a list of additional attributes that SPEC should be taken
2672    to ultimately be declared with.  */
2673 
2674 static void
warn_spec_missing_attributes(tree tmpl,tree spec,tree attrlist)2675 warn_spec_missing_attributes (tree tmpl, tree spec, tree attrlist)
2676 {
2677   if (DECL_FUNCTION_TEMPLATE_P (tmpl))
2678     tmpl = DECL_TEMPLATE_RESULT (tmpl);
2679 
2680   if (TREE_CODE (tmpl) != FUNCTION_DECL)
2681     return;
2682 
2683   /* Avoid warning if either declaration or its type is deprecated.  */
2684   if (TREE_DEPRECATED (tmpl)
2685       || TREE_DEPRECATED (spec))
2686     return;
2687 
2688   tree tmpl_type = TREE_TYPE (tmpl);
2689   tree spec_type = TREE_TYPE (spec);
2690 
2691   if (TREE_DEPRECATED (tmpl_type)
2692       || TREE_DEPRECATED (spec_type)
2693       || TREE_DEPRECATED (TREE_TYPE (tmpl_type))
2694       || TREE_DEPRECATED (TREE_TYPE (spec_type)))
2695     return;
2696 
2697   tree tmpl_attrs[] = { DECL_ATTRIBUTES (tmpl), TYPE_ATTRIBUTES (tmpl_type) };
2698   tree spec_attrs[] = { DECL_ATTRIBUTES (spec), TYPE_ATTRIBUTES (spec_type) };
2699 
2700   if (!spec_attrs[0])
2701     spec_attrs[0] = attrlist;
2702   else if (!spec_attrs[1])
2703     spec_attrs[1] = attrlist;
2704 
2705   /* Avoid warning if the primary has no attributes.  */
2706   if (!tmpl_attrs[0] && !tmpl_attrs[1])
2707     return;
2708 
2709   /* Avoid warning if either declaration contains an attribute on
2710      the white list below.  */
2711   const char* const whitelist[] = {
2712     "error", "warning"
2713   };
2714 
2715   for (unsigned i = 0; i != 2; ++i)
2716     for (unsigned j = 0; j != sizeof whitelist / sizeof *whitelist; ++j)
2717       if (lookup_attribute (whitelist[j], tmpl_attrs[i])
2718 	  || lookup_attribute (whitelist[j], spec_attrs[i]))
2719 	return;
2720 
2721   /* Avoid warning if the difference between the primary and
2722      the specialization is not in one of the attributes below.  */
2723   const char* const blacklist[] = {
2724     "alloc_align", "alloc_size", "assume_aligned", "format",
2725     "format_arg", "malloc", "nonnull"
2726   };
2727 
2728   /* Put together a list of the black listed attributes that the primary
2729      template is declared with that the specialization is not, in case
2730      it's not apparent from the most recent declaration of the primary.  */
2731   unsigned nattrs = 0;
2732   pretty_printer str;
2733 
2734   for (unsigned i = 0; i != sizeof blacklist / sizeof *blacklist; ++i)
2735     {
2736       for (unsigned j = 0; j != 2; ++j)
2737 	{
2738 	  if (!lookup_attribute (blacklist[i], tmpl_attrs[j]))
2739 	    continue;
2740 
2741 	  for (unsigned k = 0; k != 1 + !!spec_attrs[1]; ++k)
2742 	    {
2743 	      if (lookup_attribute (blacklist[i], spec_attrs[k]))
2744 		break;
2745 
2746 	      if (nattrs)
2747 		pp_string (&str, ", ");
2748 	      pp_begin_quote (&str, pp_show_color (global_dc->printer));
2749 	      pp_string (&str, blacklist[i]);
2750 	      pp_end_quote (&str, pp_show_color (global_dc->printer));
2751 	      ++nattrs;
2752 	    }
2753 	}
2754     }
2755 
2756   if (!nattrs)
2757     return;
2758 
2759   if (warning_at (DECL_SOURCE_LOCATION (spec), OPT_Wmissing_attributes,
2760 		  "explicit specialization %q#D may be missing attributes",
2761 		  spec))
2762     inform (DECL_SOURCE_LOCATION (tmpl),
2763 	    nattrs > 1
2764 	    ? G_("missing primary template attributes %s")
2765 	    : G_("missing primary template attribute %s"),
2766 	    pp_formatted_text (&str));
2767 }
2768 
2769 /* Check to see if the function just declared, as indicated in
2770    DECLARATOR, and in DECL, is a specialization of a function
2771    template.  We may also discover that the declaration is an explicit
2772    instantiation at this point.
2773 
2774    Returns DECL, or an equivalent declaration that should be used
2775    instead if all goes well.  Issues an error message if something is
2776    amiss.  Returns error_mark_node if the error is not easily
2777    recoverable.
2778 
2779    FLAGS is a bitmask consisting of the following flags:
2780 
2781    2: The function has a definition.
2782    4: The function is a friend.
2783 
2784    The TEMPLATE_COUNT is the number of references to qualifying
2785    template classes that appeared in the name of the function.  For
2786    example, in
2787 
2788      template <class T> struct S { void f(); };
2789      void S<int>::f();
2790 
2791    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2792    classes are not counted in the TEMPLATE_COUNT, so that in
2793 
2794      template <class T> struct S {};
2795      template <> struct S<int> { void f(); }
2796      template <> void S<int>::f();
2797 
2798    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2799    invalid; there should be no template <>.)
2800 
2801    If the function is a specialization, it is marked as such via
2802    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2803    is set up correctly, and it is added to the list of specializations
2804    for that template.  */
2805 
2806 tree
check_explicit_specialization(tree declarator,tree decl,int template_count,int flags,tree attrlist)2807 check_explicit_specialization (tree declarator,
2808 			       tree decl,
2809 			       int template_count,
2810 			       int flags,
2811 			       tree attrlist)
2812 {
2813   int have_def = flags & 2;
2814   int is_friend = flags & 4;
2815   bool is_concept = flags & 8;
2816   int specialization = 0;
2817   int explicit_instantiation = 0;
2818   int member_specialization = 0;
2819   tree ctype = DECL_CLASS_CONTEXT (decl);
2820   tree dname = DECL_NAME (decl);
2821   tmpl_spec_kind tsk;
2822 
2823   if (is_friend)
2824     {
2825       if (!processing_specialization)
2826 	tsk = tsk_none;
2827       else
2828 	tsk = tsk_excessive_parms;
2829     }
2830   else
2831     tsk = current_tmpl_spec_kind (template_count);
2832 
2833   switch (tsk)
2834     {
2835     case tsk_none:
2836       if (processing_specialization && !VAR_P (decl))
2837 	{
2838 	  specialization = 1;
2839 	  SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2840 	}
2841       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2842 	{
2843 	  if (is_friend)
2844 	    /* This could be something like:
2845 
2846 	       template <class T> void f(T);
2847 	       class S { friend void f<>(int); }  */
2848 	    specialization = 1;
2849 	  else
2850 	    {
2851 	      /* This case handles bogus declarations like template <>
2852 		 template <class T> void f<int>(); */
2853 
2854 	      error ("template-id %qD in declaration of primary template",
2855 		     declarator);
2856 	      return decl;
2857 	    }
2858 	}
2859       break;
2860 
2861     case tsk_invalid_member_spec:
2862       /* The error has already been reported in
2863 	 check_specialization_scope.  */
2864       return error_mark_node;
2865 
2866     case tsk_invalid_expl_inst:
2867       error ("template parameter list used in explicit instantiation");
2868 
2869       /* Fall through.  */
2870 
2871     case tsk_expl_inst:
2872       if (have_def)
2873 	error ("definition provided for explicit instantiation");
2874 
2875       explicit_instantiation = 1;
2876       break;
2877 
2878     case tsk_excessive_parms:
2879     case tsk_insufficient_parms:
2880       if (tsk == tsk_excessive_parms)
2881 	error ("too many template parameter lists in declaration of %qD",
2882 	       decl);
2883       else if (template_header_count)
2884 	error("too few template parameter lists in declaration of %qD", decl);
2885       else
2886 	error("explicit specialization of %qD must be introduced by "
2887 	      "%<template <>%>", decl);
2888 
2889       /* Fall through.  */
2890     case tsk_expl_spec:
2891       if (is_concept)
2892         error ("explicit specialization declared %<concept%>");
2893 
2894       if (VAR_P (decl) && TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2895 	/* In cases like template<> constexpr bool v = true;
2896 	   We'll give an error in check_template_variable.  */
2897 	break;
2898 
2899       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2900       if (ctype)
2901 	member_specialization = 1;
2902       else
2903 	specialization = 1;
2904       break;
2905 
2906     case tsk_template:
2907       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2908 	{
2909 	  /* This case handles bogus declarations like template <>
2910 	     template <class T> void f<int>(); */
2911 
2912 	  if (!uses_template_parms (declarator))
2913 	    error ("template-id %qD in declaration of primary template",
2914 		   declarator);
2915 	  else if (variable_template_p (TREE_OPERAND (declarator, 0)))
2916 	    {
2917 	      /* Partial specialization of variable template.  */
2918 	      SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2919 	      specialization = 1;
2920 	      goto ok;
2921 	    }
2922 	  else if (cxx_dialect < cxx14)
2923 	    error ("non-type partial specialization %qD "
2924 		   "is not allowed", declarator);
2925 	  else
2926 	    error ("non-class, non-variable partial specialization %qD "
2927 		   "is not allowed", declarator);
2928 	  return decl;
2929 	ok:;
2930 	}
2931 
2932       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2933 	/* This is a specialization of a member template, without
2934 	   specialization the containing class.  Something like:
2935 
2936 	     template <class T> struct S {
2937 	       template <class U> void f (U);
2938 	     };
2939 	     template <> template <class U> void S<int>::f(U) {}
2940 
2941 	   That's a specialization -- but of the entire template.  */
2942 	specialization = 1;
2943       break;
2944 
2945     default:
2946       gcc_unreachable ();
2947     }
2948 
2949   if ((specialization || member_specialization)
2950       /* This doesn't apply to variable templates.  */
2951       && (TREE_CODE (TREE_TYPE (decl)) == FUNCTION_TYPE
2952           || TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE))
2953     {
2954       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2955       for (; t; t = TREE_CHAIN (t))
2956 	if (TREE_PURPOSE (t))
2957 	  {
2958 	    permerror (input_location,
2959 		       "default argument specified in explicit specialization");
2960 	    break;
2961 	  }
2962     }
2963 
2964   if (specialization || member_specialization || explicit_instantiation)
2965     {
2966       tree tmpl = NULL_TREE;
2967       tree targs = NULL_TREE;
2968       bool was_template_id = (TREE_CODE (declarator) == TEMPLATE_ID_EXPR);
2969 
2970       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2971       if (!was_template_id)
2972 	{
2973 	  tree fns;
2974 
2975 	  gcc_assert (identifier_p (declarator));
2976 	  if (ctype)
2977 	    fns = dname;
2978 	  else
2979 	    {
2980 	      /* If there is no class context, the explicit instantiation
2981 		 must be at namespace scope.  */
2982 	      gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2983 
2984 	      /* Find the namespace binding, using the declaration
2985 		 context.  */
2986 	      fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2987 					   false, true);
2988 	      if (fns == error_mark_node)
2989 		/* If lookup fails, look for a friend declaration so we can
2990 		   give a better diagnostic.  */
2991 		fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2992 					     /*type*/false, /*complain*/true,
2993 					     /*hidden*/true);
2994 
2995 	      if (fns == error_mark_node || !is_overloaded_fn (fns))
2996 		{
2997 		  error ("%qD is not a template function", dname);
2998 		  fns = error_mark_node;
2999 		}
3000 	    }
3001 
3002 	  declarator = lookup_template_function (fns, NULL_TREE);
3003 	}
3004 
3005       if (declarator == error_mark_node)
3006 	return error_mark_node;
3007 
3008       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
3009 	{
3010 	  if (!explicit_instantiation)
3011 	    /* A specialization in class scope.  This is invalid,
3012 	       but the error will already have been flagged by
3013 	       check_specialization_scope.  */
3014 	    return error_mark_node;
3015 	  else
3016 	    {
3017 	      /* It's not valid to write an explicit instantiation in
3018 		 class scope, e.g.:
3019 
3020 		   class C { template void f(); }
3021 
3022 		   This case is caught by the parser.  However, on
3023 		   something like:
3024 
3025 		   template class C { void f(); };
3026 
3027 		   (which is invalid) we can get here.  The error will be
3028 		   issued later.  */
3029 	      ;
3030 	    }
3031 
3032 	  return decl;
3033 	}
3034       else if (ctype != NULL_TREE
3035 	       && (identifier_p (TREE_OPERAND (declarator, 0))))
3036 	{
3037 	  // We'll match variable templates in start_decl.
3038 	  if (VAR_P (decl))
3039 	    return decl;
3040 
3041 	  /* Find the list of functions in ctype that have the same
3042 	     name as the declared function.  */
3043 	  tree name = TREE_OPERAND (declarator, 0);
3044 
3045 	  if (constructor_name_p (name, ctype))
3046 	    {
3047 	      if (DECL_CONSTRUCTOR_P (decl)
3048 		  ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
3049 		  : !CLASSTYPE_DESTRUCTOR (ctype))
3050 		{
3051 		  /* From [temp.expl.spec]:
3052 
3053 		     If such an explicit specialization for the member
3054 		     of a class template names an implicitly-declared
3055 		     special member function (clause _special_), the
3056 		     program is ill-formed.
3057 
3058 		     Similar language is found in [temp.explicit].  */
3059 		  error ("specialization of implicitly-declared special member function");
3060 		  return error_mark_node;
3061 		}
3062 
3063 	      name = DECL_NAME (decl);
3064 	    }
3065 
3066 	  /* For a type-conversion operator, We might be looking for
3067 	     `operator int' which will be a specialization of
3068 	     `operator T'.  Grab all the conversion operators, and
3069 	     then select from them.  */
3070 	  tree fns = get_class_binding (ctype, IDENTIFIER_CONV_OP_P (name)
3071 				      ? conv_op_identifier : name);
3072 
3073 	  if (fns == NULL_TREE)
3074 	    {
3075 	      error ("no member function %qD declared in %qT", name, ctype);
3076 	      return error_mark_node;
3077 	    }
3078 	  else
3079 	    TREE_OPERAND (declarator, 0) = fns;
3080 	}
3081 
3082       /* Figure out what exactly is being specialized at this point.
3083 	 Note that for an explicit instantiation, even one for a
3084 	 member function, we cannot tell a priori whether the
3085 	 instantiation is for a member template, or just a member
3086 	 function of a template class.  Even if a member template is
3087 	 being instantiated, the member template arguments may be
3088 	 elided if they can be deduced from the rest of the
3089 	 declaration.  */
3090       tmpl = determine_specialization (declarator, decl,
3091 				       &targs,
3092 				       member_specialization,
3093 				       template_count,
3094 				       tsk);
3095 
3096       if (!tmpl || tmpl == error_mark_node)
3097 	/* We couldn't figure out what this declaration was
3098 	   specializing.  */
3099 	return error_mark_node;
3100       else
3101 	{
3102 	  if (TREE_CODE (decl) == FUNCTION_DECL
3103 	      && DECL_HIDDEN_FRIEND_P (tmpl))
3104 	    {
3105 	      if (pedwarn (DECL_SOURCE_LOCATION (decl), 0,
3106 			   "friend declaration %qD is not visible to "
3107 			   "explicit specialization", tmpl))
3108 		inform (DECL_SOURCE_LOCATION (tmpl),
3109 			"friend declaration here");
3110 	    }
3111 	  else if (!ctype && !is_friend
3112 		   && CP_DECL_CONTEXT (decl) == current_namespace)
3113 	    check_unqualified_spec_or_inst (tmpl, DECL_SOURCE_LOCATION (decl));
3114 
3115 	  tree gen_tmpl = most_general_template (tmpl);
3116 
3117 	  if (explicit_instantiation)
3118 	    {
3119 	      /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
3120 		 is done by do_decl_instantiation later.  */
3121 
3122 	      int arg_depth = TMPL_ARGS_DEPTH (targs);
3123 	      int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
3124 
3125 	      if (arg_depth > parm_depth)
3126 		{
3127 		  /* If TMPL is not the most general template (for
3128 		     example, if TMPL is a friend template that is
3129 		     injected into namespace scope), then there will
3130 		     be too many levels of TARGS.  Remove some of them
3131 		     here.  */
3132 		  int i;
3133 		  tree new_targs;
3134 
3135 		  new_targs = make_tree_vec (parm_depth);
3136 		  for (i = arg_depth - parm_depth; i < arg_depth; ++i)
3137 		    TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
3138 		      = TREE_VEC_ELT (targs, i);
3139 		  targs = new_targs;
3140 		}
3141 
3142 	      return instantiate_template (tmpl, targs, tf_error);
3143 	    }
3144 
3145 	  /* If we thought that the DECL was a member function, but it
3146 	     turns out to be specializing a static member function,
3147 	     make DECL a static member function as well.  */
3148 	  if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3149 	      && DECL_STATIC_FUNCTION_P (tmpl)
3150 	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
3151 	    revert_static_member_fn (decl);
3152 
3153 	  /* If this is a specialization of a member template of a
3154 	     template class, we want to return the TEMPLATE_DECL, not
3155 	     the specialization of it.  */
3156 	  if (tsk == tsk_template && !was_template_id)
3157 	    {
3158 	      tree result = DECL_TEMPLATE_RESULT (tmpl);
3159 	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3160 	      DECL_INITIAL (result) = NULL_TREE;
3161 	      if (have_def)
3162 		{
3163 		  tree parm;
3164 		  DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
3165 		  DECL_SOURCE_LOCATION (result)
3166 		    = DECL_SOURCE_LOCATION (decl);
3167 		  /* We want to use the argument list specified in the
3168 		     definition, not in the original declaration.  */
3169 		  DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
3170 		  for (parm = DECL_ARGUMENTS (result); parm;
3171 		       parm = DECL_CHAIN (parm))
3172 		    DECL_CONTEXT (parm) = result;
3173 		}
3174 	      return register_specialization (tmpl, gen_tmpl, targs,
3175 					      is_friend, 0);
3176 	    }
3177 
3178 	  /* Set up the DECL_TEMPLATE_INFO for DECL.  */
3179 	  DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
3180 
3181 	  if (was_template_id)
3182 	    TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl)) = true;
3183 
3184 	  /* Inherit default function arguments from the template
3185 	     DECL is specializing.  */
3186 	  if (DECL_FUNCTION_TEMPLATE_P (tmpl))
3187 	    copy_default_args_to_explicit_spec (decl);
3188 
3189 	  /* This specialization has the same protection as the
3190 	     template it specializes.  */
3191 	  TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
3192 	  TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
3193 
3194           /* 7.1.1-1 [dcl.stc]
3195 
3196              A storage-class-specifier shall not be specified in an
3197              explicit specialization...
3198 
3199              The parser rejects these, so unless action is taken here,
3200              explicit function specializations will always appear with
3201              global linkage.
3202 
3203              The action recommended by the C++ CWG in response to C++
3204              defect report 605 is to make the storage class and linkage
3205              of the explicit specialization match the templated function:
3206 
3207              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
3208            */
3209           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
3210             {
3211               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
3212               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
3213 
3214               /* A concept cannot be specialized.  */
3215               if (DECL_DECLARED_CONCEPT_P (tmpl_func))
3216                 {
3217                   error ("explicit specialization of function concept %qD",
3218                          gen_tmpl);
3219                   return error_mark_node;
3220                 }
3221 
3222               /* This specialization has the same linkage and visibility as
3223                  the function template it specializes.  */
3224               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
3225 	      if (! TREE_PUBLIC (decl))
3226 		{
3227 		  DECL_INTERFACE_KNOWN (decl) = 1;
3228 		  DECL_NOT_REALLY_EXTERN (decl) = 1;
3229 		}
3230               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
3231               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
3232                 {
3233                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
3234                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
3235                 }
3236             }
3237 
3238 	  /* If DECL is a friend declaration, declared using an
3239 	     unqualified name, the namespace associated with DECL may
3240 	     have been set incorrectly.  For example, in:
3241 
3242 	       template <typename T> void f(T);
3243 	       namespace N {
3244 		 struct S { friend void f<int>(int); }
3245 	       }
3246 
3247 	     we will have set the DECL_CONTEXT for the friend
3248 	     declaration to N, rather than to the global namespace.  */
3249 	  if (DECL_NAMESPACE_SCOPE_P (decl))
3250 	    DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
3251 
3252 	  if (is_friend && !have_def)
3253 	    /* This is not really a declaration of a specialization.
3254 	       It's just the name of an instantiation.  But, it's not
3255 	       a request for an instantiation, either.  */
3256 	    SET_DECL_IMPLICIT_INSTANTIATION (decl);
3257 	  else if (TREE_CODE (decl) == FUNCTION_DECL)
3258 	    /* A specialization is not necessarily COMDAT.  */
3259 	    DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
3260 				  && DECL_DECLARED_INLINE_P (decl));
3261 	  else if (VAR_P (decl))
3262 	    DECL_COMDAT (decl) = false;
3263 
3264 	  /* If this is a full specialization, register it so that we can find
3265 	     it again.  Partial specializations will be registered in
3266 	     process_partial_specialization.  */
3267 	  if (!processing_template_decl)
3268 	    {
3269 	      warn_spec_missing_attributes (gen_tmpl, decl, attrlist);
3270 
3271 	      decl = register_specialization (decl, gen_tmpl, targs,
3272 					      is_friend, 0);
3273 	    }
3274 
3275 
3276 	  /* A 'structor should already have clones.  */
3277 	  gcc_assert (decl == error_mark_node
3278 		      || variable_template_p (tmpl)
3279 		      || !(DECL_CONSTRUCTOR_P (decl)
3280 			   || DECL_DESTRUCTOR_P (decl))
3281 		      || DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
3282 	}
3283     }
3284 
3285   return decl;
3286 }
3287 
3288 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
3289    parameters.  These are represented in the same format used for
3290    DECL_TEMPLATE_PARMS.  */
3291 
3292 int
comp_template_parms(const_tree parms1,const_tree parms2)3293 comp_template_parms (const_tree parms1, const_tree parms2)
3294 {
3295   const_tree p1;
3296   const_tree p2;
3297 
3298   if (parms1 == parms2)
3299     return 1;
3300 
3301   for (p1 = parms1, p2 = parms2;
3302        p1 != NULL_TREE && p2 != NULL_TREE;
3303        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
3304     {
3305       tree t1 = TREE_VALUE (p1);
3306       tree t2 = TREE_VALUE (p2);
3307       int i;
3308 
3309       gcc_assert (TREE_CODE (t1) == TREE_VEC);
3310       gcc_assert (TREE_CODE (t2) == TREE_VEC);
3311 
3312       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
3313 	return 0;
3314 
3315       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
3316 	{
3317           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
3318           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
3319 
3320           /* If either of the template parameters are invalid, assume
3321              they match for the sake of error recovery. */
3322           if (error_operand_p (parm1) || error_operand_p (parm2))
3323             return 1;
3324 
3325 	  if (TREE_CODE (parm1) != TREE_CODE (parm2))
3326 	    return 0;
3327 
3328 	  if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
3329               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
3330                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
3331 	    continue;
3332 	  else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
3333 	    return 0;
3334 	}
3335     }
3336 
3337   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3338     /* One set of parameters has more parameters lists than the
3339        other.  */
3340     return 0;
3341 
3342   return 1;
3343 }
3344 
3345 /* Determine whether PARM is a parameter pack.  */
3346 
3347 bool
template_parameter_pack_p(const_tree parm)3348 template_parameter_pack_p (const_tree parm)
3349 {
3350   /* Determine if we have a non-type template parameter pack.  */
3351   if (TREE_CODE (parm) == PARM_DECL)
3352     return (DECL_TEMPLATE_PARM_P (parm)
3353             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
3354   if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
3355     return TEMPLATE_PARM_PARAMETER_PACK (parm);
3356 
3357   /* If this is a list of template parameters, we could get a
3358      TYPE_DECL or a TEMPLATE_DECL.  */
3359   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
3360     parm = TREE_TYPE (parm);
3361 
3362   /* Otherwise it must be a type template parameter.  */
3363   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
3364 	   || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
3365 	  && TEMPLATE_TYPE_PARAMETER_PACK (parm));
3366 }
3367 
3368 /* Determine if T is a function parameter pack.  */
3369 
3370 bool
function_parameter_pack_p(const_tree t)3371 function_parameter_pack_p (const_tree t)
3372 {
3373   if (t && TREE_CODE (t) == PARM_DECL)
3374     return DECL_PACK_P (t);
3375   return false;
3376 }
3377 
3378 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
3379    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
3380 
3381 tree
get_function_template_decl(const_tree primary_func_tmpl_inst)3382 get_function_template_decl (const_tree primary_func_tmpl_inst)
3383 {
3384   if (! primary_func_tmpl_inst
3385       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
3386       || ! primary_template_specialization_p (primary_func_tmpl_inst))
3387     return NULL;
3388 
3389   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
3390 }
3391 
3392 /* Return true iff the function parameter PARAM_DECL was expanded
3393    from the function parameter pack PACK.  */
3394 
3395 bool
function_parameter_expanded_from_pack_p(tree param_decl,tree pack)3396 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
3397 {
3398   if (DECL_ARTIFICIAL (param_decl)
3399       || !function_parameter_pack_p (pack))
3400     return false;
3401 
3402   /* The parameter pack and its pack arguments have the same
3403      DECL_PARM_INDEX.  */
3404   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
3405 }
3406 
3407 /* Determine whether ARGS describes a variadic template args list,
3408    i.e., one that is terminated by a template argument pack.  */
3409 
3410 static bool
template_args_variadic_p(tree args)3411 template_args_variadic_p (tree args)
3412 {
3413   int nargs;
3414   tree last_parm;
3415 
3416   if (args == NULL_TREE)
3417     return false;
3418 
3419   args = INNERMOST_TEMPLATE_ARGS (args);
3420   nargs = TREE_VEC_LENGTH (args);
3421 
3422   if (nargs == 0)
3423     return false;
3424 
3425   last_parm = TREE_VEC_ELT (args, nargs - 1);
3426 
3427   return ARGUMENT_PACK_P (last_parm);
3428 }
3429 
3430 /* Generate a new name for the parameter pack name NAME (an
3431    IDENTIFIER_NODE) that incorporates its */
3432 
3433 static tree
make_ith_pack_parameter_name(tree name,int i)3434 make_ith_pack_parameter_name (tree name, int i)
3435 {
3436   /* Munge the name to include the parameter index.  */
3437 #define NUMBUF_LEN 128
3438   char numbuf[NUMBUF_LEN];
3439   char* newname;
3440   int newname_len;
3441 
3442   if (name == NULL_TREE)
3443     return name;
3444   snprintf (numbuf, NUMBUF_LEN, "%i", i);
3445   newname_len = IDENTIFIER_LENGTH (name)
3446 	        + strlen (numbuf) + 2;
3447   newname = (char*)alloca (newname_len);
3448   snprintf (newname, newname_len,
3449 	    "%s#%i", IDENTIFIER_POINTER (name), i);
3450   return get_identifier (newname);
3451 }
3452 
3453 /* Return true if T is a primary function, class or alias template
3454    specialization, not including the template pattern.  */
3455 
3456 bool
primary_template_specialization_p(const_tree t)3457 primary_template_specialization_p (const_tree t)
3458 {
3459   if (!t)
3460     return false;
3461 
3462   if (TREE_CODE (t) == FUNCTION_DECL || VAR_P (t))
3463     return (DECL_LANG_SPECIFIC (t)
3464 	    && DECL_USE_TEMPLATE (t)
3465 	    && DECL_TEMPLATE_INFO (t)
3466 	    && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t)));
3467   else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
3468     return (CLASSTYPE_TEMPLATE_INFO (t)
3469 	    && CLASSTYPE_USE_TEMPLATE (t)
3470 	    && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)));
3471   else if (alias_template_specialization_p (t))
3472     return true;
3473   return false;
3474 }
3475 
3476 /* Return true if PARM is a template template parameter.  */
3477 
3478 bool
template_template_parameter_p(const_tree parm)3479 template_template_parameter_p (const_tree parm)
3480 {
3481   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
3482 }
3483 
3484 /* Return true iff PARM is a DECL representing a type template
3485    parameter.  */
3486 
3487 bool
template_type_parameter_p(const_tree parm)3488 template_type_parameter_p (const_tree parm)
3489 {
3490   return (parm
3491 	  && (TREE_CODE (parm) == TYPE_DECL
3492 	      || TREE_CODE (parm) == TEMPLATE_DECL)
3493 	  && DECL_TEMPLATE_PARM_P (parm));
3494 }
3495 
3496 /* Return the template parameters of T if T is a
3497    primary template instantiation, NULL otherwise.  */
3498 
3499 tree
get_primary_template_innermost_parameters(const_tree t)3500 get_primary_template_innermost_parameters (const_tree t)
3501 {
3502   tree parms = NULL, template_info = NULL;
3503 
3504   if ((template_info = get_template_info (t))
3505       && primary_template_specialization_p (t))
3506     parms = INNERMOST_TEMPLATE_PARMS
3507 	(DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
3508 
3509   return parms;
3510 }
3511 
3512 /* Return the template parameters of the LEVELth level from the full list
3513    of template parameters PARMS.  */
3514 
3515 tree
get_template_parms_at_level(tree parms,int level)3516 get_template_parms_at_level (tree parms, int level)
3517 {
3518   tree p;
3519   if (!parms
3520       || TREE_CODE (parms) != TREE_LIST
3521       || level > TMPL_PARMS_DEPTH (parms))
3522     return NULL_TREE;
3523 
3524   for (p = parms; p; p = TREE_CHAIN (p))
3525     if (TMPL_PARMS_DEPTH (p) == level)
3526       return p;
3527 
3528   return NULL_TREE;
3529 }
3530 
3531 /* Returns the template arguments of T if T is a template instantiation,
3532    NULL otherwise.  */
3533 
3534 tree
get_template_innermost_arguments(const_tree t)3535 get_template_innermost_arguments (const_tree t)
3536 {
3537   tree args = NULL, template_info = NULL;
3538 
3539   if ((template_info = get_template_info (t))
3540       && TI_ARGS (template_info))
3541     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
3542 
3543   return args;
3544 }
3545 
3546 /* Return the argument pack elements of T if T is a template argument pack,
3547    NULL otherwise.  */
3548 
3549 tree
get_template_argument_pack_elems(const_tree t)3550 get_template_argument_pack_elems (const_tree t)
3551 {
3552   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
3553       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
3554     return NULL;
3555 
3556   return ARGUMENT_PACK_ARGS (t);
3557 }
3558 
3559 /* In an ARGUMENT_PACK_SELECT, the actual underlying argument that the
3560    ARGUMENT_PACK_SELECT represents. */
3561 
3562 static tree
argument_pack_select_arg(tree t)3563 argument_pack_select_arg (tree t)
3564 {
3565   tree args = ARGUMENT_PACK_ARGS (ARGUMENT_PACK_SELECT_FROM_PACK (t));
3566   tree arg = TREE_VEC_ELT (args, ARGUMENT_PACK_SELECT_INDEX (t));
3567 
3568   /* If the selected argument is an expansion E, that most likely means we were
3569      called from gen_elem_of_pack_expansion_instantiation during the
3570      substituting of an argument pack (of which the Ith element is a pack
3571      expansion, where I is ARGUMENT_PACK_SELECT_INDEX) into a pack expansion.
3572      In this case, the Ith element resulting from this substituting is going to
3573      be a pack expansion, which pattern is the pattern of E.  Let's return the
3574      pattern of E, and gen_elem_of_pack_expansion_instantiation will build the
3575      resulting pack expansion from it.  */
3576   if (PACK_EXPANSION_P (arg))
3577     {
3578       /* Make sure we aren't throwing away arg info.  */
3579       gcc_assert (!PACK_EXPANSION_EXTRA_ARGS (arg));
3580       arg = PACK_EXPANSION_PATTERN (arg);
3581     }
3582 
3583   return arg;
3584 }
3585 
3586 
3587 /* True iff FN is a function representing a built-in variadic parameter
3588    pack.  */
3589 
3590 bool
builtin_pack_fn_p(tree fn)3591 builtin_pack_fn_p (tree fn)
3592 {
3593   if (!fn
3594       || TREE_CODE (fn) != FUNCTION_DECL
3595       || !DECL_IS_BUILTIN (fn))
3596     return false;
3597 
3598   if (id_equal (DECL_NAME (fn), "__integer_pack"))
3599     return true;
3600 
3601   return false;
3602 }
3603 
3604 /* True iff CALL is a call to a function representing a built-in variadic
3605    parameter pack.  */
3606 
3607 static bool
builtin_pack_call_p(tree call)3608 builtin_pack_call_p (tree call)
3609 {
3610   if (TREE_CODE (call) != CALL_EXPR)
3611     return false;
3612   return builtin_pack_fn_p (CALL_EXPR_FN (call));
3613 }
3614 
3615 /* Return a TREE_VEC for the expansion of __integer_pack(HI).  */
3616 
3617 static tree
expand_integer_pack(tree call,tree args,tsubst_flags_t complain,tree in_decl)3618 expand_integer_pack (tree call, tree args, tsubst_flags_t complain,
3619 		     tree in_decl)
3620 {
3621   tree ohi = CALL_EXPR_ARG (call, 0);
3622   tree hi = tsubst_copy_and_build (ohi, args, complain, in_decl,
3623 				   false/*fn*/, true/*int_cst*/);
3624 
3625   if (value_dependent_expression_p (hi))
3626     {
3627       if (hi != ohi)
3628 	{
3629 	  call = copy_node (call);
3630 	  CALL_EXPR_ARG (call, 0) = hi;
3631 	}
3632       tree ex = make_pack_expansion (call, complain);
3633       tree vec = make_tree_vec (1);
3634       TREE_VEC_ELT (vec, 0) = ex;
3635       return vec;
3636     }
3637   else
3638     {
3639       hi = cxx_constant_value (hi);
3640       int len = valid_constant_size_p (hi) ? tree_to_shwi (hi) : -1;
3641 
3642       /* Calculate the largest value of len that won't make the size of the vec
3643 	 overflow an int.  The compiler will exceed resource limits long before
3644 	 this, but it seems a decent place to diagnose.  */
3645       int max = ((INT_MAX - sizeof (tree_vec)) / sizeof (tree)) + 1;
3646 
3647       if (len < 0 || len > max)
3648 	{
3649 	  if ((complain & tf_error)
3650 	      && hi != error_mark_node)
3651 	    error ("argument to __integer_pack must be between 0 and %d", max);
3652 	  return error_mark_node;
3653 	}
3654 
3655       tree vec = make_tree_vec (len);
3656 
3657       for (int i = 0; i < len; ++i)
3658 	TREE_VEC_ELT (vec, i) = size_int (i);
3659 
3660       return vec;
3661     }
3662 }
3663 
3664 /* Return a TREE_VEC for the expansion of built-in template parameter pack
3665    CALL.  */
3666 
3667 static tree
expand_builtin_pack_call(tree call,tree args,tsubst_flags_t complain,tree in_decl)3668 expand_builtin_pack_call (tree call, tree args, tsubst_flags_t complain,
3669 			  tree in_decl)
3670 {
3671   if (!builtin_pack_call_p (call))
3672     return NULL_TREE;
3673 
3674   tree fn = CALL_EXPR_FN (call);
3675 
3676   if (id_equal (DECL_NAME (fn), "__integer_pack"))
3677     return expand_integer_pack (call, args, complain, in_decl);
3678 
3679   return NULL_TREE;
3680 }
3681 
3682 /* Structure used to track the progress of find_parameter_packs_r.  */
3683 struct find_parameter_pack_data
3684 {
3685   /* TREE_LIST that will contain all of the parameter packs found by
3686      the traversal.  */
3687   tree* parameter_packs;
3688 
3689   /* Set of AST nodes that have been visited by the traversal.  */
3690   hash_set<tree> *visited;
3691 
3692   /* True iff we're making a type pack expansion.  */
3693   bool type_pack_expansion_p;
3694 };
3695 
3696 /* Identifies all of the argument packs that occur in a template
3697    argument and appends them to the TREE_LIST inside DATA, which is a
3698    find_parameter_pack_data structure. This is a subroutine of
3699    make_pack_expansion and uses_parameter_packs.  */
3700 static tree
find_parameter_packs_r(tree * tp,int * walk_subtrees,void * data)3701 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
3702 {
3703   tree t = *tp;
3704   struct find_parameter_pack_data* ppd =
3705     (struct find_parameter_pack_data*)data;
3706   bool parameter_pack_p = false;
3707 
3708   /* Handle type aliases/typedefs.  */
3709   if (TYPE_ALIAS_P (t))
3710     {
3711       if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
3712 	cp_walk_tree (&TI_ARGS (tinfo),
3713 		      &find_parameter_packs_r,
3714 		      ppd, ppd->visited);
3715       *walk_subtrees = 0;
3716       return NULL_TREE;
3717     }
3718 
3719   /* Identify whether this is a parameter pack or not.  */
3720   switch (TREE_CODE (t))
3721     {
3722     case TEMPLATE_PARM_INDEX:
3723       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3724         parameter_pack_p = true;
3725       break;
3726 
3727     case TEMPLATE_TYPE_PARM:
3728       t = TYPE_MAIN_VARIANT (t);
3729       /* FALLTHRU */
3730     case TEMPLATE_TEMPLATE_PARM:
3731       /* If the placeholder appears in the decl-specifier-seq of a function
3732 	 parameter pack (14.6.3), or the type-specifier-seq of a type-id that
3733 	 is a pack expansion, the invented template parameter is a template
3734 	 parameter pack.  */
3735       if (ppd->type_pack_expansion_p && is_auto (t))
3736 	TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
3737       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3738         parameter_pack_p = true;
3739       break;
3740 
3741     case FIELD_DECL:
3742     case PARM_DECL:
3743       if (DECL_PACK_P (t))
3744         {
3745           /* We don't want to walk into the type of a PARM_DECL,
3746              because we don't want to see the type parameter pack.  */
3747           *walk_subtrees = 0;
3748 	  parameter_pack_p = true;
3749         }
3750       break;
3751 
3752     case VAR_DECL:
3753       if (DECL_PACK_P (t))
3754         {
3755           /* We don't want to walk into the type of a variadic capture proxy,
3756              because we don't want to see the type parameter pack.  */
3757           *walk_subtrees = 0;
3758 	  parameter_pack_p = true;
3759         }
3760       else if (variable_template_specialization_p (t))
3761 	{
3762 	  cp_walk_tree (&DECL_TI_ARGS (t),
3763 			find_parameter_packs_r,
3764 			ppd, ppd->visited);
3765 	  *walk_subtrees = 0;
3766 	}
3767       break;
3768 
3769     case CALL_EXPR:
3770       if (builtin_pack_call_p (t))
3771 	parameter_pack_p = true;
3772       break;
3773 
3774     case BASES:
3775       parameter_pack_p = true;
3776       break;
3777     default:
3778       /* Not a parameter pack.  */
3779       break;
3780     }
3781 
3782   if (parameter_pack_p)
3783     {
3784       /* Add this parameter pack to the list.  */
3785       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
3786     }
3787 
3788   if (TYPE_P (t))
3789     cp_walk_tree (&TYPE_CONTEXT (t),
3790 		  &find_parameter_packs_r, ppd, ppd->visited);
3791 
3792   /* This switch statement will return immediately if we don't find a
3793      parameter pack.  */
3794   switch (TREE_CODE (t))
3795     {
3796     case TEMPLATE_PARM_INDEX:
3797       return NULL_TREE;
3798 
3799     case BOUND_TEMPLATE_TEMPLATE_PARM:
3800       /* Check the template itself.  */
3801       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)),
3802 		    &find_parameter_packs_r, ppd, ppd->visited);
3803       /* Check the template arguments.  */
3804       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd,
3805 		    ppd->visited);
3806       *walk_subtrees = 0;
3807       return NULL_TREE;
3808 
3809     case TEMPLATE_TYPE_PARM:
3810     case TEMPLATE_TEMPLATE_PARM:
3811       return NULL_TREE;
3812 
3813     case PARM_DECL:
3814       return NULL_TREE;
3815 
3816     case DECL_EXPR:
3817       {
3818 	tree decl = DECL_EXPR_DECL (t);
3819 	/* Ignore the declaration of a capture proxy for a parameter pack.  */
3820 	if (is_capture_proxy (decl))
3821 	  *walk_subtrees = 0;
3822 	if (is_typedef_decl (decl) && TYPE_ALIAS_P (TREE_TYPE (decl)))
3823 	  /* Since we stop at aliases above, we need to look through them at
3824 	     the point of the DECL_EXPR.  */
3825 	  cp_walk_tree (&DECL_ORIGINAL_TYPE (decl),
3826 			&find_parameter_packs_r, ppd, ppd->visited);
3827 	return NULL_TREE;
3828       }
3829 
3830     case RECORD_TYPE:
3831       if (TYPE_PTRMEMFUNC_P (t))
3832 	return NULL_TREE;
3833       /* Fall through.  */
3834 
3835     case UNION_TYPE:
3836     case ENUMERAL_TYPE:
3837       if (TYPE_TEMPLATE_INFO (t))
3838 	cp_walk_tree (&TYPE_TI_ARGS (t),
3839 		      &find_parameter_packs_r, ppd, ppd->visited);
3840 
3841       *walk_subtrees = 0;
3842       return NULL_TREE;
3843 
3844     case TEMPLATE_DECL:
3845       if (!DECL_TEMPLATE_TEMPLATE_PARM_P (t))
3846 	return NULL_TREE;
3847       gcc_fallthrough();
3848 
3849     case CONSTRUCTOR:
3850       cp_walk_tree (&TREE_TYPE (t),
3851 		    &find_parameter_packs_r, ppd, ppd->visited);
3852       return NULL_TREE;
3853 
3854     case TYPENAME_TYPE:
3855       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3856                    ppd, ppd->visited);
3857       *walk_subtrees = 0;
3858       return NULL_TREE;
3859 
3860     case TYPE_PACK_EXPANSION:
3861     case EXPR_PACK_EXPANSION:
3862       *walk_subtrees = 0;
3863       return NULL_TREE;
3864 
3865     case INTEGER_TYPE:
3866       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r,
3867 		    ppd, ppd->visited);
3868       *walk_subtrees = 0;
3869       return NULL_TREE;
3870 
3871     case IDENTIFIER_NODE:
3872       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd,
3873 		    ppd->visited);
3874       *walk_subtrees = 0;
3875       return NULL_TREE;
3876 
3877     case LAMBDA_EXPR:
3878       {
3879 	/* Look at explicit captures.  */
3880 	for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t);
3881 	     cap; cap = TREE_CHAIN (cap))
3882 	  cp_walk_tree (&TREE_VALUE (cap), &find_parameter_packs_r, ppd,
3883 			ppd->visited);
3884 	/* Since we defer implicit capture, look in the parms and body.  */
3885 	tree fn = lambda_function (t);
3886 	cp_walk_tree (&TREE_TYPE (fn), &find_parameter_packs_r, ppd,
3887 		      ppd->visited);
3888 	cp_walk_tree (&DECL_SAVED_TREE (fn), &find_parameter_packs_r, ppd,
3889 		      ppd->visited);
3890 	*walk_subtrees = 0;
3891 	return NULL_TREE;
3892       }
3893 
3894     case DECLTYPE_TYPE:
3895       {
3896 	/* When traversing a DECLTYPE_TYPE_EXPR, we need to set
3897 	   type_pack_expansion_p to false so that any placeholders
3898 	   within the expression don't get marked as parameter packs.  */
3899 	bool type_pack_expansion_p = ppd->type_pack_expansion_p;
3900 	ppd->type_pack_expansion_p = false;
3901 	cp_walk_tree (&DECLTYPE_TYPE_EXPR (t), &find_parameter_packs_r,
3902 		      ppd, ppd->visited);
3903 	ppd->type_pack_expansion_p = type_pack_expansion_p;
3904 	*walk_subtrees = 0;
3905 	return NULL_TREE;
3906       }
3907 
3908     case IF_STMT:
3909       cp_walk_tree (&IF_COND (t), &find_parameter_packs_r,
3910 		    ppd, ppd->visited);
3911       cp_walk_tree (&THEN_CLAUSE (t), &find_parameter_packs_r,
3912 		    ppd, ppd->visited);
3913       cp_walk_tree (&ELSE_CLAUSE (t), &find_parameter_packs_r,
3914 		    ppd, ppd->visited);
3915       /* Don't walk into IF_STMT_EXTRA_ARGS.  */
3916       *walk_subtrees = 0;
3917       return NULL_TREE;
3918 
3919     default:
3920       return NULL_TREE;
3921     }
3922 
3923   return NULL_TREE;
3924 }
3925 
3926 /* Determines if the expression or type T uses any parameter packs.  */
3927 bool
uses_parameter_packs(tree t)3928 uses_parameter_packs (tree t)
3929 {
3930   tree parameter_packs = NULL_TREE;
3931   struct find_parameter_pack_data ppd;
3932   ppd.parameter_packs = &parameter_packs;
3933   ppd.visited = new hash_set<tree>;
3934   ppd.type_pack_expansion_p = false;
3935   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3936   delete ppd.visited;
3937   return parameter_packs != NULL_TREE;
3938 }
3939 
3940 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3941    representation a base-class initializer into a parameter pack
3942    expansion. If all goes well, the resulting node will be an
3943    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3944    respectively.  */
3945 tree
make_pack_expansion(tree arg,tsubst_flags_t complain)3946 make_pack_expansion (tree arg, tsubst_flags_t complain)
3947 {
3948   tree result;
3949   tree parameter_packs = NULL_TREE;
3950   bool for_types = false;
3951   struct find_parameter_pack_data ppd;
3952 
3953   if (!arg || arg == error_mark_node)
3954     return arg;
3955 
3956   if (TREE_CODE (arg) == TREE_LIST && TREE_PURPOSE (arg))
3957     {
3958       /* A TREE_LIST with a non-null TREE_PURPOSE is for a base
3959          class initializer.  In this case, the TREE_PURPOSE will be a
3960          _TYPE node (representing the base class expansion we're
3961          initializing) and the TREE_VALUE will be a TREE_LIST
3962          containing the initialization arguments.
3963 
3964          The resulting expansion looks somewhat different from most
3965          expansions. Rather than returning just one _EXPANSION, we
3966          return a TREE_LIST whose TREE_PURPOSE is a
3967          TYPE_PACK_EXPANSION containing the bases that will be
3968          initialized.  The TREE_VALUE will be identical to the
3969          original TREE_VALUE, which is a list of arguments that will
3970          be passed to each base.  We do not introduce any new pack
3971          expansion nodes into the TREE_VALUE (although it is possible
3972          that some already exist), because the TREE_PURPOSE and
3973          TREE_VALUE all need to be expanded together with the same
3974          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3975          resulting TREE_PURPOSE will mention the parameter packs in
3976          both the bases and the arguments to the bases.  */
3977       tree purpose;
3978       tree value;
3979       tree parameter_packs = NULL_TREE;
3980 
3981       /* Determine which parameter packs will be used by the base
3982          class expansion.  */
3983       ppd.visited = new hash_set<tree>;
3984       ppd.parameter_packs = &parameter_packs;
3985       ppd.type_pack_expansion_p = false;
3986       gcc_assert (TYPE_P (TREE_PURPOSE (arg)));
3987       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r,
3988                     &ppd, ppd.visited);
3989 
3990       if (parameter_packs == NULL_TREE)
3991         {
3992 	  if (complain & tf_error)
3993 	    error ("base initializer expansion %qT contains no parameter packs",
3994 		   arg);
3995           delete ppd.visited;
3996           return error_mark_node;
3997         }
3998 
3999       if (TREE_VALUE (arg) != void_type_node)
4000         {
4001           /* Collect the sets of parameter packs used in each of the
4002              initialization arguments.  */
4003           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
4004             {
4005               /* Determine which parameter packs will be expanded in this
4006                  argument.  */
4007               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r,
4008                             &ppd, ppd.visited);
4009             }
4010         }
4011 
4012       delete ppd.visited;
4013 
4014       /* Create the pack expansion type for the base type.  */
4015       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
4016       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
4017       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
4018       PACK_EXPANSION_LOCAL_P (purpose) = at_function_scope_p ();
4019 
4020       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4021 	 they will rarely be compared to anything.  */
4022       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
4023 
4024       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
4025     }
4026 
4027   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
4028     for_types = true;
4029 
4030   /* Build the PACK_EXPANSION_* node.  */
4031   result = for_types
4032      ? cxx_make_type (TYPE_PACK_EXPANSION)
4033      : make_node (EXPR_PACK_EXPANSION);
4034   SET_PACK_EXPANSION_PATTERN (result, arg);
4035   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
4036     {
4037       /* Propagate type and const-expression information.  */
4038       TREE_TYPE (result) = TREE_TYPE (arg);
4039       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
4040       /* Mark this read now, since the expansion might be length 0.  */
4041       mark_exp_read (arg);
4042     }
4043   else
4044     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4045        they will rarely be compared to anything.  */
4046     SET_TYPE_STRUCTURAL_EQUALITY (result);
4047 
4048   /* Determine which parameter packs will be expanded.  */
4049   ppd.parameter_packs = &parameter_packs;
4050   ppd.visited = new hash_set<tree>;
4051   ppd.type_pack_expansion_p = TYPE_P (arg);
4052   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
4053   delete ppd.visited;
4054 
4055   /* Make sure we found some parameter packs.  */
4056   if (parameter_packs == NULL_TREE)
4057     {
4058       if (complain & tf_error)
4059 	{
4060 	  if (TYPE_P (arg))
4061 	    error ("expansion pattern %qT contains no argument packs", arg);
4062 	  else
4063 	    error ("expansion pattern %qE contains no argument packs", arg);
4064 	}
4065       return error_mark_node;
4066     }
4067   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
4068 
4069   PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
4070 
4071   return result;
4072 }
4073 
4074 /* Checks T for any "bare" parameter packs, which have not yet been
4075    expanded, and issues an error if any are found. This operation can
4076    only be done on full expressions or types (e.g., an expression
4077    statement, "if" condition, etc.), because we could have expressions like:
4078 
4079      foo(f(g(h(args)))...)
4080 
4081    where "args" is a parameter pack. check_for_bare_parameter_packs
4082    should not be called for the subexpressions args, h(args),
4083    g(h(args)), or f(g(h(args))), because we would produce erroneous
4084    error messages.
4085 
4086    Returns TRUE and emits an error if there were bare parameter packs,
4087    returns FALSE otherwise.  */
4088 bool
check_for_bare_parameter_packs(tree t,location_t loc)4089 check_for_bare_parameter_packs (tree t, location_t loc /* = UNKNOWN_LOCATION */)
4090 {
4091   tree parameter_packs = NULL_TREE;
4092   struct find_parameter_pack_data ppd;
4093 
4094   if (!processing_template_decl || !t || t == error_mark_node)
4095     return false;
4096 
4097   /* A lambda might use a parameter pack from the containing context.  */
4098   if (current_class_type && LAMBDA_TYPE_P (current_class_type)
4099       && CLASSTYPE_TEMPLATE_INFO (current_class_type))
4100     return false;
4101 
4102   if (TREE_CODE (t) == TYPE_DECL)
4103     t = TREE_TYPE (t);
4104 
4105   ppd.parameter_packs = &parameter_packs;
4106   ppd.visited = new hash_set<tree>;
4107   ppd.type_pack_expansion_p = false;
4108   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4109   delete ppd.visited;
4110 
4111   if (parameter_packs)
4112     {
4113       if (loc == UNKNOWN_LOCATION)
4114 	loc = EXPR_LOC_OR_LOC (t, input_location);
4115       error_at (loc, "parameter packs not expanded with %<...%>:");
4116       while (parameter_packs)
4117         {
4118           tree pack = TREE_VALUE (parameter_packs);
4119           tree name = NULL_TREE;
4120 
4121           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
4122               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
4123             name = TYPE_NAME (pack);
4124           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
4125             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
4126 	  else if (TREE_CODE (pack) == CALL_EXPR)
4127 	    name = DECL_NAME (CALL_EXPR_FN (pack));
4128           else
4129             name = DECL_NAME (pack);
4130 
4131 	  if (name)
4132 	    inform (loc, "        %qD", name);
4133 	  else
4134 	    inform (loc, "        <anonymous>");
4135 
4136           parameter_packs = TREE_CHAIN (parameter_packs);
4137         }
4138 
4139       return true;
4140     }
4141 
4142   return false;
4143 }
4144 
4145 /* Expand any parameter packs that occur in the template arguments in
4146    ARGS.  */
4147 tree
expand_template_argument_pack(tree args)4148 expand_template_argument_pack (tree args)
4149 {
4150   if (args == error_mark_node)
4151     return error_mark_node;
4152 
4153   tree result_args = NULL_TREE;
4154   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
4155   int num_result_args = -1;
4156   int non_default_args_count = -1;
4157 
4158   /* First, determine if we need to expand anything, and the number of
4159      slots we'll need.  */
4160   for (in_arg = 0; in_arg < nargs; ++in_arg)
4161     {
4162       tree arg = TREE_VEC_ELT (args, in_arg);
4163       if (arg == NULL_TREE)
4164 	return args;
4165       if (ARGUMENT_PACK_P (arg))
4166         {
4167           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
4168           if (num_result_args < 0)
4169             num_result_args = in_arg + num_packed;
4170           else
4171             num_result_args += num_packed;
4172         }
4173       else
4174         {
4175           if (num_result_args >= 0)
4176             num_result_args++;
4177         }
4178     }
4179 
4180   /* If no expansion is necessary, we're done.  */
4181   if (num_result_args < 0)
4182     return args;
4183 
4184   /* Expand arguments.  */
4185   result_args = make_tree_vec (num_result_args);
4186   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
4187     non_default_args_count =
4188       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
4189   for (in_arg = 0; in_arg < nargs; ++in_arg)
4190     {
4191       tree arg = TREE_VEC_ELT (args, in_arg);
4192       if (ARGUMENT_PACK_P (arg))
4193         {
4194           tree packed = ARGUMENT_PACK_ARGS (arg);
4195           int i, num_packed = TREE_VEC_LENGTH (packed);
4196           for (i = 0; i < num_packed; ++i, ++out_arg)
4197             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
4198 	  if (non_default_args_count > 0)
4199 	    non_default_args_count += num_packed - 1;
4200         }
4201       else
4202         {
4203           TREE_VEC_ELT (result_args, out_arg) = arg;
4204           ++out_arg;
4205         }
4206     }
4207   if (non_default_args_count >= 0)
4208     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
4209   return result_args;
4210 }
4211 
4212 /* Checks if DECL shadows a template parameter.
4213 
4214    [temp.local]: A template-parameter shall not be redeclared within its
4215    scope (including nested scopes).
4216 
4217    Emits an error and returns TRUE if the DECL shadows a parameter,
4218    returns FALSE otherwise.  */
4219 
4220 bool
check_template_shadow(tree decl)4221 check_template_shadow (tree decl)
4222 {
4223   tree olddecl;
4224 
4225   /* If we're not in a template, we can't possibly shadow a template
4226      parameter.  */
4227   if (!current_template_parms)
4228     return true;
4229 
4230   /* Figure out what we're shadowing.  */
4231   decl = OVL_FIRST (decl);
4232   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
4233 
4234   /* If there's no previous binding for this name, we're not shadowing
4235      anything, let alone a template parameter.  */
4236   if (!olddecl)
4237     return true;
4238 
4239   /* If we're not shadowing a template parameter, we're done.  Note
4240      that OLDDECL might be an OVERLOAD (or perhaps even an
4241      ERROR_MARK), so we can't just blithely assume it to be a _DECL
4242      node.  */
4243   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
4244     return true;
4245 
4246   /* We check for decl != olddecl to avoid bogus errors for using a
4247      name inside a class.  We check TPFI to avoid duplicate errors for
4248      inline member templates.  */
4249   if (decl == olddecl
4250       || (DECL_TEMPLATE_PARM_P (decl)
4251 	  && TEMPLATE_PARMS_FOR_INLINE (current_template_parms)))
4252     return true;
4253 
4254   /* Don't complain about the injected class name, as we've already
4255      complained about the class itself.  */
4256   if (DECL_SELF_REFERENCE_P (decl))
4257     return false;
4258 
4259   if (DECL_TEMPLATE_PARM_P (decl))
4260     error ("declaration of template parameter %q+D shadows "
4261 	   "template parameter", decl);
4262   else
4263     error ("declaration of %q+#D shadows template parameter", decl);
4264   inform (DECL_SOURCE_LOCATION (olddecl),
4265 	  "template parameter %qD declared here", olddecl);
4266   return false;
4267 }
4268 
4269 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
4270    ORIG_LEVEL, DECL, and TYPE.  */
4271 
4272 static tree
build_template_parm_index(int index,int level,int orig_level,tree decl,tree type)4273 build_template_parm_index (int index,
4274 			   int level,
4275 			   int orig_level,
4276 			   tree decl,
4277 			   tree type)
4278 {
4279   tree t = make_node (TEMPLATE_PARM_INDEX);
4280   TEMPLATE_PARM_IDX (t) = index;
4281   TEMPLATE_PARM_LEVEL (t) = level;
4282   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
4283   TEMPLATE_PARM_DECL (t) = decl;
4284   TREE_TYPE (t) = type;
4285   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
4286   TREE_READONLY (t) = TREE_READONLY (decl);
4287 
4288   return t;
4289 }
4290 
4291 /* Find the canonical type parameter for the given template type
4292    parameter.  Returns the canonical type parameter, which may be TYPE
4293    if no such parameter existed.  */
4294 
4295 static tree
canonical_type_parameter(tree type)4296 canonical_type_parameter (tree type)
4297 {
4298   tree list;
4299   int idx = TEMPLATE_TYPE_IDX (type);
4300   if (!canonical_template_parms)
4301     vec_alloc (canonical_template_parms, idx + 1);
4302 
4303   if (canonical_template_parms->length () <= (unsigned) idx)
4304     vec_safe_grow_cleared (canonical_template_parms, idx + 1);
4305 
4306   list = (*canonical_template_parms)[idx];
4307   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
4308     list = TREE_CHAIN (list);
4309 
4310   if (list)
4311     return TREE_VALUE (list);
4312   else
4313     {
4314       (*canonical_template_parms)[idx]
4315 	= tree_cons (NULL_TREE, type, (*canonical_template_parms)[idx]);
4316       return type;
4317     }
4318 }
4319 
4320 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
4321    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
4322    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
4323    new one is created.  */
4324 
4325 static tree
reduce_template_parm_level(tree index,tree type,int levels,tree args,tsubst_flags_t complain)4326 reduce_template_parm_level (tree index, tree type, int levels, tree args,
4327 			    tsubst_flags_t complain)
4328 {
4329   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
4330       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
4331 	  != TEMPLATE_PARM_LEVEL (index) - levels)
4332       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
4333     {
4334       tree orig_decl = TEMPLATE_PARM_DECL (index);
4335       tree decl, t;
4336 
4337       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
4338 			 TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
4339       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
4340       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
4341       DECL_ARTIFICIAL (decl) = 1;
4342       SET_DECL_TEMPLATE_PARM_P (decl);
4343 
4344       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
4345 				     TEMPLATE_PARM_LEVEL (index) - levels,
4346 				     TEMPLATE_PARM_ORIG_LEVEL (index),
4347 				     decl, type);
4348       TEMPLATE_PARM_DESCENDANTS (index) = t;
4349       TEMPLATE_PARM_PARAMETER_PACK (t)
4350 	= TEMPLATE_PARM_PARAMETER_PACK (index);
4351 
4352 	/* Template template parameters need this.  */
4353       if (TREE_CODE (decl) == TEMPLATE_DECL)
4354 	{
4355 	  DECL_TEMPLATE_RESULT (decl)
4356 	    = build_decl (DECL_SOURCE_LOCATION (decl),
4357 			  TYPE_DECL, DECL_NAME (decl), type);
4358 	  DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (decl)) = true;
4359 	  DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
4360 	    (DECL_TEMPLATE_PARMS (orig_decl), args, complain);
4361 	}
4362     }
4363 
4364   return TEMPLATE_PARM_DESCENDANTS (index);
4365 }
4366 
4367 /* Process information from new template parameter PARM and append it
4368    to the LIST being built.  This new parameter is a non-type
4369    parameter iff IS_NON_TYPE is true. This new parameter is a
4370    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
4371    is in PARM_LOC.  */
4372 
4373 tree
process_template_parm(tree list,location_t parm_loc,tree parm,bool is_non_type,bool is_parameter_pack)4374 process_template_parm (tree list, location_t parm_loc, tree parm,
4375 		       bool is_non_type, bool is_parameter_pack)
4376 {
4377   tree decl = 0;
4378   int idx = 0;
4379 
4380   gcc_assert (TREE_CODE (parm) == TREE_LIST);
4381   tree defval = TREE_PURPOSE (parm);
4382   tree constr = TREE_TYPE (parm);
4383 
4384   if (list)
4385     {
4386       tree p = tree_last (list);
4387 
4388       if (p && TREE_VALUE (p) != error_mark_node)
4389         {
4390           p = TREE_VALUE (p);
4391           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
4392             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
4393           else
4394             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
4395         }
4396 
4397       ++idx;
4398     }
4399 
4400   if (is_non_type)
4401     {
4402       parm = TREE_VALUE (parm);
4403 
4404       SET_DECL_TEMPLATE_PARM_P (parm);
4405 
4406       if (TREE_TYPE (parm) != error_mark_node)
4407 	{
4408 	  /* [temp.param]
4409 
4410 	     The top-level cv-qualifiers on the template-parameter are
4411 	     ignored when determining its type.  */
4412 	  TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
4413 	  if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
4414 	    TREE_TYPE (parm) = error_mark_node;
4415 	  else if (uses_parameter_packs (TREE_TYPE (parm))
4416 		   && !is_parameter_pack
4417 		   /* If we're in a nested template parameter list, the template
4418 		      template parameter could be a parameter pack.  */
4419 		   && processing_template_parmlist == 1)
4420 	    {
4421 	      /* This template parameter is not a parameter pack, but it
4422 		 should be. Complain about "bare" parameter packs.  */
4423 	      check_for_bare_parameter_packs (TREE_TYPE (parm));
4424 
4425 	      /* Recover by calling this a parameter pack.  */
4426 	      is_parameter_pack = true;
4427 	    }
4428 	}
4429 
4430       /* A template parameter is not modifiable.  */
4431       TREE_CONSTANT (parm) = 1;
4432       TREE_READONLY (parm) = 1;
4433       decl = build_decl (parm_loc,
4434 			 CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
4435       TREE_CONSTANT (decl) = 1;
4436       TREE_READONLY (decl) = 1;
4437       DECL_INITIAL (parm) = DECL_INITIAL (decl)
4438 	= build_template_parm_index (idx, processing_template_decl,
4439 				     processing_template_decl,
4440 				     decl, TREE_TYPE (parm));
4441 
4442       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4443 	= is_parameter_pack;
4444     }
4445   else
4446     {
4447       tree t;
4448       parm = TREE_VALUE (TREE_VALUE (parm));
4449 
4450       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
4451 	{
4452 	  t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
4453 	  /* This is for distinguishing between real templates and template
4454 	     template parameters */
4455 	  TREE_TYPE (parm) = t;
4456 	  TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
4457 	  decl = parm;
4458 	}
4459       else
4460 	{
4461 	  t = cxx_make_type (TEMPLATE_TYPE_PARM);
4462 	  /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
4463 	  decl = build_decl (parm_loc,
4464 			     TYPE_DECL, parm, t);
4465 	}
4466 
4467       TYPE_NAME (t) = decl;
4468       TYPE_STUB_DECL (t) = decl;
4469       parm = decl;
4470       TEMPLATE_TYPE_PARM_INDEX (t)
4471 	= build_template_parm_index (idx, processing_template_decl,
4472 				     processing_template_decl,
4473 				     decl, TREE_TYPE (parm));
4474       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
4475       TYPE_CANONICAL (t) = canonical_type_parameter (t);
4476     }
4477   DECL_ARTIFICIAL (decl) = 1;
4478   SET_DECL_TEMPLATE_PARM_P (decl);
4479 
4480   /* Build requirements for the type/template parameter.
4481      This must be done after SET_DECL_TEMPLATE_PARM_P or
4482      process_template_parm could fail. */
4483   tree reqs = finish_shorthand_constraint (parm, constr);
4484 
4485   pushdecl (decl);
4486 
4487   if (defval && TREE_CODE (defval) == OVERLOAD)
4488     lookup_keep (defval, true);
4489 
4490   /* Build the parameter node linking the parameter declaration,
4491      its default argument (if any), and its constraints (if any). */
4492   parm = build_tree_list (defval, parm);
4493   TEMPLATE_PARM_CONSTRAINTS (parm) = reqs;
4494 
4495   return chainon (list, parm);
4496 }
4497 
4498 /* The end of a template parameter list has been reached.  Process the
4499    tree list into a parameter vector, converting each parameter into a more
4500    useful form.	 Type parameters are saved as IDENTIFIER_NODEs, and others
4501    as PARM_DECLs.  */
4502 
4503 tree
end_template_parm_list(tree parms)4504 end_template_parm_list (tree parms)
4505 {
4506   int nparms;
4507   tree parm, next;
4508   tree saved_parmlist = make_tree_vec (list_length (parms));
4509 
4510   /* Pop the dummy parameter level and add the real one.  */
4511   current_template_parms = TREE_CHAIN (current_template_parms);
4512 
4513   current_template_parms
4514     = tree_cons (size_int (processing_template_decl),
4515 		 saved_parmlist, current_template_parms);
4516 
4517   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
4518     {
4519       next = TREE_CHAIN (parm);
4520       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
4521       TREE_CHAIN (parm) = NULL_TREE;
4522     }
4523 
4524   --processing_template_parmlist;
4525 
4526   return saved_parmlist;
4527 }
4528 
4529 // Explicitly indicate the end of the template parameter list. We assume
4530 // that the current template parameters have been constructed and/or
4531 // managed explicitly, as when creating new template template parameters
4532 // from a shorthand constraint.
4533 void
end_template_parm_list()4534 end_template_parm_list ()
4535 {
4536   --processing_template_parmlist;
4537 }
4538 
4539 /* end_template_decl is called after a template declaration is seen.  */
4540 
4541 void
end_template_decl(void)4542 end_template_decl (void)
4543 {
4544   reset_specialization ();
4545 
4546   if (! processing_template_decl)
4547     return;
4548 
4549   /* This matches the pushlevel in begin_template_parm_list.  */
4550   finish_scope ();
4551 
4552   --processing_template_decl;
4553   current_template_parms = TREE_CHAIN (current_template_parms);
4554 }
4555 
4556 /* Takes a TREE_LIST representing a template parameter and convert it
4557    into an argument suitable to be passed to the type substitution
4558    functions.  Note that If the TREE_LIST contains an error_mark
4559    node, the returned argument is error_mark_node.  */
4560 
4561 tree
template_parm_to_arg(tree t)4562 template_parm_to_arg (tree t)
4563 {
4564 
4565   if (t == NULL_TREE
4566       || TREE_CODE (t) != TREE_LIST)
4567     return t;
4568 
4569   if (error_operand_p (TREE_VALUE (t)))
4570     return error_mark_node;
4571 
4572   t = TREE_VALUE (t);
4573 
4574   if (TREE_CODE (t) == TYPE_DECL
4575       || TREE_CODE (t) == TEMPLATE_DECL)
4576     {
4577       t = TREE_TYPE (t);
4578 
4579       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
4580 	{
4581 	  /* Turn this argument into a TYPE_ARGUMENT_PACK
4582 	     with a single element, which expands T.  */
4583 	  tree vec = make_tree_vec (1);
4584 	  if (CHECKING_P)
4585 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4586 
4587 	  TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4588 
4589 	  t = cxx_make_type (TYPE_ARGUMENT_PACK);
4590 	  SET_ARGUMENT_PACK_ARGS (t, vec);
4591 	}
4592     }
4593   else
4594     {
4595       t = DECL_INITIAL (t);
4596 
4597       if (TEMPLATE_PARM_PARAMETER_PACK (t))
4598 	{
4599 	  /* Turn this argument into a NONTYPE_ARGUMENT_PACK
4600 	     with a single element, which expands T.  */
4601 	  tree vec = make_tree_vec (1);
4602 	  if (CHECKING_P)
4603 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4604 
4605 	  t = convert_from_reference (t);
4606 	  TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4607 
4608 	  t  = make_node (NONTYPE_ARGUMENT_PACK);
4609 	  SET_ARGUMENT_PACK_ARGS (t, vec);
4610 	}
4611       else
4612 	t = convert_from_reference (t);
4613     }
4614   return t;
4615 }
4616 
4617 /* Given a single level of template parameters (a TREE_VEC), return it
4618    as a set of template arguments.  */
4619 
4620 static tree
template_parms_level_to_args(tree parms)4621 template_parms_level_to_args (tree parms)
4622 {
4623   tree a = copy_node (parms);
4624   TREE_TYPE (a) = NULL_TREE;
4625   for (int i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4626     TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4627 
4628   if (CHECKING_P)
4629     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4630 
4631   return a;
4632 }
4633 
4634 /* Given a set of template parameters, return them as a set of template
4635    arguments.  The template parameters are represented as a TREE_VEC, in
4636    the form documented in cp-tree.h for template arguments.  */
4637 
4638 static tree
template_parms_to_args(tree parms)4639 template_parms_to_args (tree parms)
4640 {
4641   tree header;
4642   tree args = NULL_TREE;
4643   int length = TMPL_PARMS_DEPTH (parms);
4644   int l = length;
4645 
4646   /* If there is only one level of template parameters, we do not
4647      create a TREE_VEC of TREE_VECs.  Instead, we return a single
4648      TREE_VEC containing the arguments.  */
4649   if (length > 1)
4650     args = make_tree_vec (length);
4651 
4652   for (header = parms; header; header = TREE_CHAIN (header))
4653     {
4654       tree a = template_parms_level_to_args (TREE_VALUE (header));
4655 
4656       if (length > 1)
4657 	TREE_VEC_ELT (args, --l) = a;
4658       else
4659 	args = a;
4660     }
4661 
4662   return args;
4663 }
4664 
4665 /* Within the declaration of a template, return the currently active
4666    template parameters as an argument TREE_VEC.  */
4667 
4668 static tree
current_template_args(void)4669 current_template_args (void)
4670 {
4671   return template_parms_to_args (current_template_parms);
4672 }
4673 
4674 /* Update the declared TYPE by doing any lookups which were thought to be
4675    dependent, but are not now that we know the SCOPE of the declarator.  */
4676 
4677 tree
maybe_update_decl_type(tree orig_type,tree scope)4678 maybe_update_decl_type (tree orig_type, tree scope)
4679 {
4680   tree type = orig_type;
4681 
4682   if (type == NULL_TREE)
4683     return type;
4684 
4685   if (TREE_CODE (orig_type) == TYPE_DECL)
4686     type = TREE_TYPE (type);
4687 
4688   if (scope && TYPE_P (scope) && dependent_type_p (scope)
4689       && dependent_type_p (type)
4690       /* Don't bother building up the args in this case.  */
4691       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4692     {
4693       /* tsubst in the args corresponding to the template parameters,
4694 	 including auto if present.  Most things will be unchanged, but
4695 	 make_typename_type and tsubst_qualified_id will resolve
4696 	 TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
4697       tree args = current_template_args ();
4698       tree auto_node = type_uses_auto (type);
4699       tree pushed;
4700       if (auto_node)
4701 	{
4702 	  tree auto_vec = make_tree_vec (1);
4703 	  TREE_VEC_ELT (auto_vec, 0) = auto_node;
4704 	  args = add_to_template_args (args, auto_vec);
4705 	}
4706       pushed = push_scope (scope);
4707       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4708       if (pushed)
4709 	pop_scope (scope);
4710     }
4711 
4712   if (type == error_mark_node)
4713     return orig_type;
4714 
4715   if (TREE_CODE (orig_type) == TYPE_DECL)
4716     {
4717       if (same_type_p (type, TREE_TYPE (orig_type)))
4718 	type = orig_type;
4719       else
4720 	type = TYPE_NAME (type);
4721     }
4722   return type;
4723 }
4724 
4725 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4726    template PARMS and constraints, CONSTR.  If MEMBER_TEMPLATE_P is true,
4727    the new  template is a member template. */
4728 
4729 tree
build_template_decl(tree decl,tree parms,bool member_template_p)4730 build_template_decl (tree decl, tree parms, bool member_template_p)
4731 {
4732   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4733   SET_DECL_LANGUAGE (tmpl, DECL_LANGUAGE (decl));
4734   DECL_TEMPLATE_PARMS (tmpl) = parms;
4735   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4736   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
4737   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4738 
4739   return tmpl;
4740 }
4741 
4742 struct template_parm_data
4743 {
4744   /* The level of the template parameters we are currently
4745      processing.  */
4746   int level;
4747 
4748   /* The index of the specialization argument we are currently
4749      processing.  */
4750   int current_arg;
4751 
4752   /* An array whose size is the number of template parameters.  The
4753      elements are nonzero if the parameter has been used in any one
4754      of the arguments processed so far.  */
4755   int* parms;
4756 
4757   /* An array whose size is the number of template arguments.  The
4758      elements are nonzero if the argument makes use of template
4759      parameters of this level.  */
4760   int* arg_uses_template_parms;
4761 };
4762 
4763 /* Subroutine of push_template_decl used to see if each template
4764    parameter in a partial specialization is used in the explicit
4765    argument list.  If T is of the LEVEL given in DATA (which is
4766    treated as a template_parm_data*), then DATA->PARMS is marked
4767    appropriately.  */
4768 
4769 static int
mark_template_parm(tree t,void * data)4770 mark_template_parm (tree t, void* data)
4771 {
4772   int level;
4773   int idx;
4774   struct template_parm_data* tpd = (struct template_parm_data*) data;
4775 
4776   template_parm_level_and_index (t, &level, &idx);
4777 
4778   if (level == tpd->level)
4779     {
4780       tpd->parms[idx] = 1;
4781       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
4782     }
4783 
4784   /* In C++17 the type of a non-type argument is a deduced context.  */
4785   if (cxx_dialect >= cxx17
4786       && TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4787     for_each_template_parm (TREE_TYPE (t),
4788 			    &mark_template_parm,
4789 			    data,
4790 			    NULL,
4791 			    /*include_nondeduced_p=*/false);
4792 
4793   /* Return zero so that for_each_template_parm will continue the
4794      traversal of the tree; we want to mark *every* template parm.  */
4795   return 0;
4796 }
4797 
4798 /* Process the partial specialization DECL.  */
4799 
4800 static tree
process_partial_specialization(tree decl)4801 process_partial_specialization (tree decl)
4802 {
4803   tree type = TREE_TYPE (decl);
4804   tree tinfo = get_template_info (decl);
4805   tree maintmpl = TI_TEMPLATE (tinfo);
4806   tree specargs = TI_ARGS (tinfo);
4807   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
4808   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
4809   tree inner_parms;
4810   tree inst;
4811   int nargs = TREE_VEC_LENGTH (inner_args);
4812   int ntparms;
4813   int  i;
4814   bool did_error_intro = false;
4815   struct template_parm_data tpd;
4816   struct template_parm_data tpd2;
4817 
4818   gcc_assert (current_template_parms);
4819 
4820   /* A concept cannot be specialized.  */
4821   if (flag_concepts && variable_concept_p (maintmpl))
4822     {
4823       error ("specialization of variable concept %q#D", maintmpl);
4824       return error_mark_node;
4825     }
4826 
4827   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4828   ntparms = TREE_VEC_LENGTH (inner_parms);
4829 
4830   /* We check that each of the template parameters given in the
4831      partial specialization is used in the argument list to the
4832      specialization.  For example:
4833 
4834        template <class T> struct S;
4835        template <class T> struct S<T*>;
4836 
4837      The second declaration is OK because `T*' uses the template
4838      parameter T, whereas
4839 
4840        template <class T> struct S<int>;
4841 
4842      is no good.  Even trickier is:
4843 
4844        template <class T>
4845        struct S1
4846        {
4847 	  template <class U>
4848 	  struct S2;
4849 	  template <class U>
4850 	  struct S2<T>;
4851        };
4852 
4853      The S2<T> declaration is actually invalid; it is a
4854      full-specialization.  Of course,
4855 
4856 	  template <class U>
4857 	  struct S2<T (*)(U)>;
4858 
4859      or some such would have been OK.  */
4860   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
4861   tpd.parms = XALLOCAVEC (int, ntparms);
4862   memset (tpd.parms, 0, sizeof (int) * ntparms);
4863 
4864   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4865   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
4866   for (i = 0; i < nargs; ++i)
4867     {
4868       tpd.current_arg = i;
4869       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
4870 			      &mark_template_parm,
4871 			      &tpd,
4872 			      NULL,
4873 			      /*include_nondeduced_p=*/false);
4874     }
4875   for (i = 0; i < ntparms; ++i)
4876     if (tpd.parms[i] == 0)
4877       {
4878 	/* One of the template parms was not used in a deduced context in the
4879 	   specialization.  */
4880 	if (!did_error_intro)
4881 	  {
4882 	    error ("template parameters not deducible in "
4883 		   "partial specialization:");
4884 	    did_error_intro = true;
4885 	  }
4886 
4887 	inform (input_location, "        %qD",
4888 		TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
4889       }
4890 
4891   if (did_error_intro)
4892     return error_mark_node;
4893 
4894   /* [temp.class.spec]
4895 
4896      The argument list of the specialization shall not be identical to
4897      the implicit argument list of the primary template.  */
4898   tree main_args
4899     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
4900   if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args))
4901       && (!flag_concepts
4902 	  || !strictly_subsumes (current_template_constraints (),
4903 				 get_constraints (maintmpl))))
4904     {
4905       if (!flag_concepts)
4906         error ("partial specialization %q+D does not specialize "
4907 	       "any template arguments; to define the primary template, "
4908 	       "remove the template argument list", decl);
4909       else
4910         error ("partial specialization %q+D does not specialize any "
4911 	       "template arguments and is not more constrained than "
4912 	       "the primary template; to define the primary template, "
4913 	       "remove the template argument list", decl);
4914       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
4915     }
4916 
4917   /* A partial specialization that replaces multiple parameters of the
4918      primary template with a pack expansion is less specialized for those
4919      parameters.  */
4920   if (nargs < DECL_NTPARMS (maintmpl))
4921     {
4922       error ("partial specialization is not more specialized than the "
4923 	     "primary template because it replaces multiple parameters "
4924 	     "with a pack expansion");
4925       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
4926       /* Avoid crash in process_partial_specialization.  */
4927       return decl;
4928     }
4929 
4930   else if (nargs > DECL_NTPARMS (maintmpl))
4931     {
4932       error ("too many arguments for partial specialization %qT", type);
4933       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
4934       /* Avoid crash below.  */
4935       return decl;
4936     }
4937 
4938   /* If we aren't in a dependent class, we can actually try deduction.  */
4939   else if (tpd.level == 1
4940 	   /* FIXME we should be able to handle a partial specialization of a
4941 	      partial instantiation, but currently we can't (c++/41727).  */
4942 	   && TMPL_ARGS_DEPTH (specargs) == 1
4943 	   && !get_partial_spec_bindings (maintmpl, maintmpl, specargs))
4944     {
4945       if (permerror (input_location, "partial specialization %qD is not "
4946 		     "more specialized than", decl))
4947 	inform (DECL_SOURCE_LOCATION (maintmpl), "primary template %qD",
4948 		maintmpl);
4949     }
4950 
4951   /* [temp.class.spec]
4952 
4953      A partially specialized non-type argument expression shall not
4954      involve template parameters of the partial specialization except
4955      when the argument expression is a simple identifier.
4956 
4957      The type of a template parameter corresponding to a specialized
4958      non-type argument shall not be dependent on a parameter of the
4959      specialization.
4960 
4961      Also, we verify that pack expansions only occur at the
4962      end of the argument list.  */
4963   tpd2.parms = 0;
4964   for (i = 0; i < nargs; ++i)
4965     {
4966       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
4967       tree arg = TREE_VEC_ELT (inner_args, i);
4968       tree packed_args = NULL_TREE;
4969       int j, len = 1;
4970 
4971       if (ARGUMENT_PACK_P (arg))
4972         {
4973           /* Extract the arguments from the argument pack. We'll be
4974              iterating over these in the following loop.  */
4975           packed_args = ARGUMENT_PACK_ARGS (arg);
4976           len = TREE_VEC_LENGTH (packed_args);
4977         }
4978 
4979       for (j = 0; j < len; j++)
4980         {
4981           if (packed_args)
4982             /* Get the Jth argument in the parameter pack.  */
4983             arg = TREE_VEC_ELT (packed_args, j);
4984 
4985           if (PACK_EXPANSION_P (arg))
4986             {
4987               /* Pack expansions must come at the end of the
4988                  argument list.  */
4989               if ((packed_args && j < len - 1)
4990                   || (!packed_args && i < nargs - 1))
4991                 {
4992                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4993                     error ("parameter pack argument %qE must be at the "
4994 			   "end of the template argument list", arg);
4995                   else
4996                     error ("parameter pack argument %qT must be at the "
4997 			   "end of the template argument list", arg);
4998                 }
4999             }
5000 
5001           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5002             /* We only care about the pattern.  */
5003             arg = PACK_EXPANSION_PATTERN (arg);
5004 
5005           if (/* These first two lines are the `non-type' bit.  */
5006               !TYPE_P (arg)
5007               && TREE_CODE (arg) != TEMPLATE_DECL
5008               /* This next two lines are the `argument expression is not just a
5009                  simple identifier' condition and also the `specialized
5010                  non-type argument' bit.  */
5011               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
5012 	      && !(REFERENCE_REF_P (arg)
5013 		   && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
5014             {
5015               if ((!packed_args && tpd.arg_uses_template_parms[i])
5016                   || (packed_args && uses_template_parms (arg)))
5017                 error ("template argument %qE involves template parameter(s)",
5018                        arg);
5019               else
5020                 {
5021                   /* Look at the corresponding template parameter,
5022                      marking which template parameters its type depends
5023                      upon.  */
5024                   tree type = TREE_TYPE (parm);
5025 
5026                   if (!tpd2.parms)
5027                     {
5028                       /* We haven't yet initialized TPD2.  Do so now.  */
5029                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5030                       /* The number of parameters here is the number in the
5031                          main template, which, as checked in the assertion
5032                          above, is NARGS.  */
5033                       tpd2.parms = XALLOCAVEC (int, nargs);
5034                       tpd2.level =
5035                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
5036                     }
5037 
5038                   /* Mark the template parameters.  But this time, we're
5039                      looking for the template parameters of the main
5040                      template, not in the specialization.  */
5041                   tpd2.current_arg = i;
5042                   tpd2.arg_uses_template_parms[i] = 0;
5043                   memset (tpd2.parms, 0, sizeof (int) * nargs);
5044                   for_each_template_parm (type,
5045                                           &mark_template_parm,
5046                                           &tpd2,
5047                                           NULL,
5048 					  /*include_nondeduced_p=*/false);
5049 
5050                   if (tpd2.arg_uses_template_parms [i])
5051                     {
5052                       /* The type depended on some template parameters.
5053                          If they are fully specialized in the
5054                          specialization, that's OK.  */
5055                       int j;
5056                       int count = 0;
5057                       for (j = 0; j < nargs; ++j)
5058                         if (tpd2.parms[j] != 0
5059                             && tpd.arg_uses_template_parms [j])
5060                           ++count;
5061                       if (count != 0)
5062                         error_n (input_location, count,
5063                                  "type %qT of template argument %qE depends "
5064                                  "on a template parameter",
5065                                  "type %qT of template argument %qE depends "
5066                                  "on template parameters",
5067                                  type,
5068                                  arg);
5069                     }
5070                 }
5071             }
5072         }
5073     }
5074 
5075   /* We should only get here once.  */
5076   if (TREE_CODE (decl) == TYPE_DECL)
5077     gcc_assert (!COMPLETE_TYPE_P (type));
5078 
5079   // Build the template decl.
5080   tree tmpl = build_template_decl (decl, current_template_parms,
5081 				   DECL_MEMBER_TEMPLATE_P (maintmpl));
5082   TREE_TYPE (tmpl) = type;
5083   DECL_TEMPLATE_RESULT (tmpl) = decl;
5084   SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5085   DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
5086   DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
5087 
5088   /* Give template template parms a DECL_CONTEXT of the template
5089      for which they are a parameter.  */
5090   for (i = 0; i < ntparms; ++i)
5091     {
5092       tree parm = TREE_VALUE (TREE_VEC_ELT (inner_parms, i));
5093       if (TREE_CODE (parm) == TEMPLATE_DECL)
5094 	DECL_CONTEXT (parm) = tmpl;
5095     }
5096 
5097   if (VAR_P (decl))
5098     /* We didn't register this in check_explicit_specialization so we could
5099        wait until the constraints were set.  */
5100     decl = register_specialization (decl, maintmpl, specargs, false, 0);
5101   else
5102     associate_classtype_constraints (type);
5103 
5104   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
5105     = tree_cons (specargs, tmpl,
5106                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
5107   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
5108 
5109   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
5110        inst = TREE_CHAIN (inst))
5111     {
5112       tree instance = TREE_VALUE (inst);
5113       if (TYPE_P (instance)
5114 	  ? (COMPLETE_TYPE_P (instance)
5115 	     && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
5116 	  : DECL_TEMPLATE_INSTANTIATION (instance))
5117 	{
5118 	  tree spec = most_specialized_partial_spec (instance, tf_none);
5119 	  tree inst_decl = (DECL_P (instance)
5120 			    ? instance : TYPE_NAME (instance));
5121 	  if (!spec)
5122 	    /* OK */;
5123 	  else if (spec == error_mark_node)
5124 	    permerror (input_location,
5125 		       "declaration of %qD ambiguates earlier template "
5126 		       "instantiation for %qD", decl, inst_decl);
5127 	  else if (TREE_VALUE (spec) == tmpl)
5128 	    permerror (input_location,
5129 		       "partial specialization of %qD after instantiation "
5130 		       "of %qD", decl, inst_decl);
5131 	}
5132     }
5133 
5134   return decl;
5135 }
5136 
5137 /* PARM is a template parameter of some form; return the corresponding
5138    TEMPLATE_PARM_INDEX.  */
5139 
5140 static tree
get_template_parm_index(tree parm)5141 get_template_parm_index (tree parm)
5142 {
5143   if (TREE_CODE (parm) == PARM_DECL
5144       || TREE_CODE (parm) == CONST_DECL)
5145     parm = DECL_INITIAL (parm);
5146   else if (TREE_CODE (parm) == TYPE_DECL
5147 	   || TREE_CODE (parm) == TEMPLATE_DECL)
5148     parm = TREE_TYPE (parm);
5149   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
5150       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM
5151       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
5152     parm = TEMPLATE_TYPE_PARM_INDEX (parm);
5153   gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
5154   return parm;
5155 }
5156 
5157 /* Subroutine of fixed_parameter_pack_p below.  Look for any template
5158    parameter packs used by the template parameter PARM.  */
5159 
5160 static void
fixed_parameter_pack_p_1(tree parm,struct find_parameter_pack_data * ppd)5161 fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
5162 {
5163   /* A type parm can't refer to another parm.  */
5164   if (TREE_CODE (parm) == TYPE_DECL || parm == error_mark_node)
5165     return;
5166   else if (TREE_CODE (parm) == PARM_DECL)
5167     {
5168       cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
5169 		    ppd, ppd->visited);
5170       return;
5171     }
5172 
5173   gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
5174 
5175   tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
5176   for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
5177     fixed_parameter_pack_p_1 (TREE_VALUE (TREE_VEC_ELT (vec, i)), ppd);
5178 }
5179 
5180 /* PARM is a template parameter pack.  Return any parameter packs used in
5181    its type or the type of any of its template parameters.  If there are
5182    any such packs, it will be instantiated into a fixed template parameter
5183    list by partial instantiation rather than be fully deduced.  */
5184 
5185 tree
fixed_parameter_pack_p(tree parm)5186 fixed_parameter_pack_p (tree parm)
5187 {
5188   /* This can only be true in a member template.  */
5189   if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
5190     return NULL_TREE;
5191   /* This can only be true for a parameter pack.  */
5192   if (!template_parameter_pack_p (parm))
5193     return NULL_TREE;
5194   /* A type parm can't refer to another parm.  */
5195   if (TREE_CODE (parm) == TYPE_DECL)
5196     return NULL_TREE;
5197 
5198   tree parameter_packs = NULL_TREE;
5199   struct find_parameter_pack_data ppd;
5200   ppd.parameter_packs = &parameter_packs;
5201   ppd.visited = new hash_set<tree>;
5202   ppd.type_pack_expansion_p = false;
5203 
5204   fixed_parameter_pack_p_1 (parm, &ppd);
5205 
5206   delete ppd.visited;
5207   return parameter_packs;
5208 }
5209 
5210 /* Check that a template declaration's use of default arguments and
5211    parameter packs is not invalid.  Here, PARMS are the template
5212    parameters.  IS_PRIMARY is true if DECL is the thing declared by
5213    a primary template.  IS_PARTIAL is true if DECL is a partial
5214    specialization.
5215 
5216    IS_FRIEND_DECL is nonzero if DECL is either a non-defining friend
5217    function template declaration or a friend class template
5218    declaration.  In the function case, 1 indicates a declaration, 2
5219    indicates a redeclaration.  When IS_FRIEND_DECL=2, no errors are
5220    emitted for extraneous default arguments.
5221 
5222    Returns TRUE if there were no errors found, FALSE otherwise. */
5223 
5224 bool
check_default_tmpl_args(tree decl,tree parms,bool is_primary,bool is_partial,int is_friend_decl)5225 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
5226                          bool is_partial, int is_friend_decl)
5227 {
5228   const char *msg;
5229   int last_level_to_check;
5230   tree parm_level;
5231   bool no_errors = true;
5232 
5233   /* [temp.param]
5234 
5235      A default template-argument shall not be specified in a
5236      function template declaration or a function template definition, nor
5237      in the template-parameter-list of the definition of a member of a
5238      class template.  */
5239 
5240   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
5241       || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_FUNCTION_P (decl)))
5242     /* You can't have a function template declaration in a local
5243        scope, nor you can you define a member of a class template in a
5244        local scope.  */
5245     return true;
5246 
5247   if ((TREE_CODE (decl) == TYPE_DECL
5248        && TREE_TYPE (decl)
5249        && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5250       || (TREE_CODE (decl) == FUNCTION_DECL
5251 	  && LAMBDA_FUNCTION_P (decl)))
5252     /* A lambda doesn't have an explicit declaration; don't complain
5253        about the parms of the enclosing class.  */
5254     return true;
5255 
5256   if (current_class_type
5257       && !TYPE_BEING_DEFINED (current_class_type)
5258       && DECL_LANG_SPECIFIC (decl)
5259       && DECL_DECLARES_FUNCTION_P (decl)
5260       /* If this is either a friend defined in the scope of the class
5261 	 or a member function.  */
5262       && (DECL_FUNCTION_MEMBER_P (decl)
5263 	  ? same_type_p (DECL_CONTEXT (decl), current_class_type)
5264 	  : DECL_FRIEND_CONTEXT (decl)
5265 	  ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
5266 	  : false)
5267       /* And, if it was a member function, it really was defined in
5268 	 the scope of the class.  */
5269       && (!DECL_FUNCTION_MEMBER_P (decl)
5270 	  || DECL_INITIALIZED_IN_CLASS_P (decl)))
5271     /* We already checked these parameters when the template was
5272        declared, so there's no need to do it again now.  This function
5273        was defined in class scope, but we're processing its body now
5274        that the class is complete.  */
5275     return true;
5276 
5277   /* Core issue 226 (C++0x only): the following only applies to class
5278      templates.  */
5279   if (is_primary
5280       && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
5281     {
5282       /* [temp.param]
5283 
5284          If a template-parameter has a default template-argument, all
5285          subsequent template-parameters shall have a default
5286          template-argument supplied.  */
5287       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
5288         {
5289           tree inner_parms = TREE_VALUE (parm_level);
5290           int ntparms = TREE_VEC_LENGTH (inner_parms);
5291           int seen_def_arg_p = 0;
5292           int i;
5293 
5294           for (i = 0; i < ntparms; ++i)
5295             {
5296               tree parm = TREE_VEC_ELT (inner_parms, i);
5297 
5298               if (parm == error_mark_node)
5299                 continue;
5300 
5301               if (TREE_PURPOSE (parm))
5302                 seen_def_arg_p = 1;
5303               else if (seen_def_arg_p
5304 		       && !template_parameter_pack_p (TREE_VALUE (parm)))
5305                 {
5306                   error ("no default argument for %qD", TREE_VALUE (parm));
5307                   /* For better subsequent error-recovery, we indicate that
5308                      there should have been a default argument.  */
5309                   TREE_PURPOSE (parm) = error_mark_node;
5310                   no_errors = false;
5311                 }
5312 	      else if (!is_partial
5313 		       && !is_friend_decl
5314 		       /* Don't complain about an enclosing partial
5315 			  specialization.  */
5316 		       && parm_level == parms
5317 		       && TREE_CODE (decl) == TYPE_DECL
5318 		       && i < ntparms - 1
5319 		       && template_parameter_pack_p (TREE_VALUE (parm))
5320 		       /* A fixed parameter pack will be partially
5321 			  instantiated into a fixed length list.  */
5322 		       && !fixed_parameter_pack_p (TREE_VALUE (parm)))
5323 		{
5324 		  /* A primary class template can only have one
5325 		     parameter pack, at the end of the template
5326 		     parameter list.  */
5327 
5328 		  error ("parameter pack %q+D must be at the end of the"
5329 			 " template parameter list", TREE_VALUE (parm));
5330 
5331 		  TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
5332 		    = error_mark_node;
5333 		  no_errors = false;
5334 		}
5335             }
5336         }
5337     }
5338 
5339   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
5340       || is_partial
5341       || !is_primary
5342       || is_friend_decl)
5343     /* For an ordinary class template, default template arguments are
5344        allowed at the innermost level, e.g.:
5345 	 template <class T = int>
5346 	 struct S {};
5347        but, in a partial specialization, they're not allowed even
5348        there, as we have in [temp.class.spec]:
5349 
5350 	 The template parameter list of a specialization shall not
5351 	 contain default template argument values.
5352 
5353        So, for a partial specialization, or for a function template
5354        (in C++98/C++03), we look at all of them.  */
5355     ;
5356   else
5357     /* But, for a primary class template that is not a partial
5358        specialization we look at all template parameters except the
5359        innermost ones.  */
5360     parms = TREE_CHAIN (parms);
5361 
5362   /* Figure out what error message to issue.  */
5363   if (is_friend_decl == 2)
5364     msg = G_("default template arguments may not be used in function template "
5365 	     "friend re-declaration");
5366   else if (is_friend_decl)
5367     msg = G_("default template arguments may not be used in template "
5368 	     "friend declarations");
5369   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
5370     msg = G_("default template arguments may not be used in function templates "
5371 	     "without -std=c++11 or -std=gnu++11");
5372   else if (is_partial)
5373     msg = G_("default template arguments may not be used in "
5374 	     "partial specializations");
5375   else if (current_class_type && CLASSTYPE_IS_TEMPLATE (current_class_type))
5376     msg = G_("default argument for template parameter for class enclosing %qD");
5377   else
5378     /* Per [temp.param]/9, "A default template-argument shall not be
5379        specified in the template-parameter-lists of the definition of
5380        a member of a class template that appears outside of the member's
5381        class.", thus if we aren't handling a member of a class template
5382        there is no need to examine the parameters.  */
5383     return true;
5384 
5385   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
5386     /* If we're inside a class definition, there's no need to
5387        examine the parameters to the class itself.  On the one
5388        hand, they will be checked when the class is defined, and,
5389        on the other, default arguments are valid in things like:
5390 	 template <class T = double>
5391 	 struct S { template <class U> void f(U); };
5392        Here the default argument for `S' has no bearing on the
5393        declaration of `f'.  */
5394     last_level_to_check = template_class_depth (current_class_type) + 1;
5395   else
5396     /* Check everything.  */
5397     last_level_to_check = 0;
5398 
5399   for (parm_level = parms;
5400        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
5401        parm_level = TREE_CHAIN (parm_level))
5402     {
5403       tree inner_parms = TREE_VALUE (parm_level);
5404       int i;
5405       int ntparms;
5406 
5407       ntparms = TREE_VEC_LENGTH (inner_parms);
5408       for (i = 0; i < ntparms; ++i)
5409         {
5410           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
5411             continue;
5412 
5413 	  if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
5414 	    {
5415 	      if (msg)
5416 	        {
5417                   no_errors = false;
5418                   if (is_friend_decl == 2)
5419                     return no_errors;
5420 
5421 		  error (msg, decl);
5422 		  msg = 0;
5423 	        }
5424 
5425 	      /* Clear out the default argument so that we are not
5426 	         confused later.  */
5427 	      TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
5428 	    }
5429         }
5430 
5431       /* At this point, if we're still interested in issuing messages,
5432 	 they must apply to classes surrounding the object declared.  */
5433       if (msg)
5434 	msg = G_("default argument for template parameter for class "
5435 		 "enclosing %qD");
5436     }
5437 
5438   return no_errors;
5439 }
5440 
5441 /* Worker for push_template_decl_real, called via
5442    for_each_template_parm.  DATA is really an int, indicating the
5443    level of the parameters we are interested in.  If T is a template
5444    parameter of that level, return nonzero.  */
5445 
5446 static int
template_parm_this_level_p(tree t,void * data)5447 template_parm_this_level_p (tree t, void* data)
5448 {
5449   int this_level = *(int *)data;
5450   int level;
5451 
5452   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5453     level = TEMPLATE_PARM_LEVEL (t);
5454   else
5455     level = TEMPLATE_TYPE_LEVEL (t);
5456   return level == this_level;
5457 }
5458 
5459 /* Worker for uses_outer_template_parms, called via for_each_template_parm.
5460    DATA is really an int, indicating the innermost outer level of parameters.
5461    If T is a template parameter of that level or further out, return
5462    nonzero.  */
5463 
5464 static int
template_parm_outer_level(tree t,void * data)5465 template_parm_outer_level (tree t, void *data)
5466 {
5467   int this_level = *(int *)data;
5468   int level;
5469 
5470   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5471     level = TEMPLATE_PARM_LEVEL (t);
5472   else
5473     level = TEMPLATE_TYPE_LEVEL (t);
5474   return level <= this_level;
5475 }
5476 
5477 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
5478    parameters given by current_template_args, or reuses a
5479    previously existing one, if appropriate.  Returns the DECL, or an
5480    equivalent one, if it is replaced via a call to duplicate_decls.
5481 
5482    If IS_FRIEND is true, DECL is a friend declaration.  */
5483 
5484 tree
push_template_decl_real(tree decl,bool is_friend)5485 push_template_decl_real (tree decl, bool is_friend)
5486 {
5487   tree tmpl;
5488   tree args;
5489   tree info;
5490   tree ctx;
5491   bool is_primary;
5492   bool is_partial;
5493   int new_template_p = 0;
5494   /* True if the template is a member template, in the sense of
5495      [temp.mem].  */
5496   bool member_template_p = false;
5497 
5498   if (decl == error_mark_node || !current_template_parms)
5499     return error_mark_node;
5500 
5501   /* See if this is a partial specialization.  */
5502   is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
5503 		 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
5504 		 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
5505 		|| (VAR_P (decl)
5506 		    && DECL_LANG_SPECIFIC (decl)
5507 		    && DECL_TEMPLATE_SPECIALIZATION (decl)
5508 		    && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
5509 
5510   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
5511     is_friend = true;
5512 
5513   if (is_friend)
5514     /* For a friend, we want the context of the friend, not
5515        the type of which it is a friend.  */
5516     ctx = CP_DECL_CONTEXT (decl);
5517   else if (CP_DECL_CONTEXT (decl)
5518 	   && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
5519     /* In the case of a virtual function, we want the class in which
5520        it is defined.  */
5521     ctx = CP_DECL_CONTEXT (decl);
5522   else
5523     /* Otherwise, if we're currently defining some class, the DECL
5524        is assumed to be a member of the class.  */
5525     ctx = current_scope ();
5526 
5527   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
5528     ctx = NULL_TREE;
5529 
5530   if (!DECL_CONTEXT (decl))
5531     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5532 
5533   /* See if this is a primary template.  */
5534   if (is_friend && ctx
5535       && uses_template_parms_level (ctx, processing_template_decl))
5536     /* A friend template that specifies a class context, i.e.
5537          template <typename T> friend void A<T>::f();
5538        is not primary.  */
5539     is_primary = false;
5540   else if (TREE_CODE (decl) == TYPE_DECL
5541 	   && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5542     is_primary = false;
5543   else
5544     is_primary = template_parm_scope_p ();
5545 
5546   if (is_primary)
5547     {
5548       warning (OPT_Wtemplates, "template %qD declared", decl);
5549 
5550       if (DECL_CLASS_SCOPE_P (decl))
5551 	member_template_p = true;
5552       if (TREE_CODE (decl) == TYPE_DECL
5553 	  && anon_aggrname_p (DECL_NAME (decl)))
5554 	{
5555 	  error ("template class without a name");
5556 	  return error_mark_node;
5557 	}
5558       else if (TREE_CODE (decl) == FUNCTION_DECL)
5559 	{
5560 	  if (member_template_p)
5561 	    {
5562 	      if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
5563 		error ("member template %qD may not have virt-specifiers", decl);
5564 	    }
5565 	  if (DECL_DESTRUCTOR_P (decl))
5566 	    {
5567 	      /* [temp.mem]
5568 
5569 		 A destructor shall not be a member template.  */
5570 	      error ("destructor %qD declared as member template", decl);
5571 	      return error_mark_node;
5572 	    }
5573 	  if (IDENTIFIER_NEWDEL_OP_P (DECL_NAME (decl))
5574 	      && (!prototype_p (TREE_TYPE (decl))
5575 		  || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
5576 		  || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5577 		  || (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5578 		      == void_list_node)))
5579 	    {
5580 	      /* [basic.stc.dynamic.allocation]
5581 
5582 		 An allocation function can be a function
5583 		 template. ... Template allocation functions shall
5584 		 have two or more parameters.  */
5585 	      error ("invalid template declaration of %qD", decl);
5586 	      return error_mark_node;
5587 	    }
5588 	}
5589       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5590 	       && CLASS_TYPE_P (TREE_TYPE (decl)))
5591 	{
5592 	  /* Class template, set TEMPLATE_TYPE_PARM_FOR_CLASS.  */
5593 	  tree parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
5594 	  for (int i = 0; i < TREE_VEC_LENGTH (parms); ++i)
5595 	    {
5596 	      tree t = TREE_VALUE (TREE_VEC_ELT (parms, i));
5597 	      if (TREE_CODE (t) == TYPE_DECL)
5598 		t = TREE_TYPE (t);
5599 	      if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
5600 		TEMPLATE_TYPE_PARM_FOR_CLASS (t) = true;
5601 	    }
5602 	}
5603       else if (TREE_CODE (decl) == TYPE_DECL
5604 	       && TYPE_DECL_ALIAS_P (decl))
5605 	/* alias-declaration */
5606 	gcc_assert (!DECL_ARTIFICIAL (decl));
5607       else if (VAR_P (decl))
5608 	/* C++14 variable template. */;
5609       else
5610 	{
5611 	  error ("template declaration of %q#D", decl);
5612 	  return error_mark_node;
5613 	}
5614     }
5615 
5616   /* Check to see that the rules regarding the use of default
5617      arguments are not being violated.  We check args for a friend
5618      functions when we know whether it's a definition, introducing
5619      declaration or re-declaration.  */
5620   if (!is_friend || TREE_CODE (decl) != FUNCTION_DECL)
5621     check_default_tmpl_args (decl, current_template_parms,
5622 			     is_primary, is_partial, is_friend);
5623 
5624   /* Ensure that there are no parameter packs in the type of this
5625      declaration that have not been expanded.  */
5626   if (TREE_CODE (decl) == FUNCTION_DECL)
5627     {
5628       /* Check each of the arguments individually to see if there are
5629          any bare parameter packs.  */
5630       tree type = TREE_TYPE (decl);
5631       tree arg = DECL_ARGUMENTS (decl);
5632       tree argtype = TYPE_ARG_TYPES (type);
5633 
5634       while (arg && argtype)
5635         {
5636           if (!DECL_PACK_P (arg)
5637               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
5638             {
5639             /* This is a PARM_DECL that contains unexpanded parameter
5640                packs. We have already complained about this in the
5641                check_for_bare_parameter_packs call, so just replace
5642                these types with ERROR_MARK_NODE.  */
5643               TREE_TYPE (arg) = error_mark_node;
5644               TREE_VALUE (argtype) = error_mark_node;
5645             }
5646 
5647           arg = DECL_CHAIN (arg);
5648           argtype = TREE_CHAIN (argtype);
5649         }
5650 
5651       /* Check for bare parameter packs in the return type and the
5652          exception specifiers.  */
5653       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
5654 	/* Errors were already issued, set return type to int
5655 	   as the frontend doesn't expect error_mark_node as
5656 	   the return type.  */
5657 	TREE_TYPE (type) = integer_type_node;
5658       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
5659 	TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
5660     }
5661   else if (check_for_bare_parameter_packs ((TREE_CODE (decl) == TYPE_DECL
5662 					    && TYPE_DECL_ALIAS_P (decl))
5663 					   ? DECL_ORIGINAL_TYPE (decl)
5664 					   : TREE_TYPE (decl)))
5665     {
5666       TREE_TYPE (decl) = error_mark_node;
5667       return error_mark_node;
5668     }
5669 
5670   if (is_partial)
5671     return process_partial_specialization (decl);
5672 
5673   args = current_template_args ();
5674 
5675   if (!ctx
5676       || TREE_CODE (ctx) == FUNCTION_DECL
5677       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
5678       || (TREE_CODE (decl) == TYPE_DECL
5679 	  && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5680       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
5681     {
5682       if (DECL_LANG_SPECIFIC (decl)
5683 	  && DECL_TEMPLATE_INFO (decl)
5684 	  && DECL_TI_TEMPLATE (decl))
5685 	tmpl = DECL_TI_TEMPLATE (decl);
5686       /* If DECL is a TYPE_DECL for a class-template, then there won't
5687 	 be DECL_LANG_SPECIFIC.  The information equivalent to
5688 	 DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
5689       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5690 	       && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
5691 	       && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
5692 	{
5693 	  /* Since a template declaration already existed for this
5694 	     class-type, we must be redeclaring it here.  Make sure
5695 	     that the redeclaration is valid.  */
5696 	  redeclare_class_template (TREE_TYPE (decl),
5697 				    current_template_parms,
5698 				    current_template_constraints ());
5699 	  /* We don't need to create a new TEMPLATE_DECL; just use the
5700 	     one we already had.  */
5701 	  tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
5702 	}
5703       else
5704 	{
5705 	  tmpl = build_template_decl (decl, current_template_parms,
5706 				      member_template_p);
5707 	  new_template_p = 1;
5708 
5709 	  if (DECL_LANG_SPECIFIC (decl)
5710 	      && DECL_TEMPLATE_SPECIALIZATION (decl))
5711 	    {
5712 	      /* A specialization of a member template of a template
5713 		 class.  */
5714 	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5715 	      DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
5716 	      DECL_TEMPLATE_INFO (decl) = NULL_TREE;
5717 	    }
5718 	}
5719     }
5720   else
5721     {
5722       tree a, t, current, parms;
5723       int i;
5724       tree tinfo = get_template_info (decl);
5725 
5726       if (!tinfo)
5727 	{
5728 	  error ("template definition of non-template %q#D", decl);
5729 	  return error_mark_node;
5730 	}
5731 
5732       tmpl = TI_TEMPLATE (tinfo);
5733 
5734       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
5735 	  && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
5736 	  && DECL_TEMPLATE_SPECIALIZATION (decl)
5737 	  && DECL_MEMBER_TEMPLATE_P (tmpl))
5738 	{
5739 	  tree new_tmpl;
5740 
5741 	  /* The declaration is a specialization of a member
5742 	     template, declared outside the class.  Therefore, the
5743 	     innermost template arguments will be NULL, so we
5744 	     replace them with the arguments determined by the
5745 	     earlier call to check_explicit_specialization.  */
5746 	  args = DECL_TI_ARGS (decl);
5747 
5748 	  new_tmpl
5749 	    = build_template_decl (decl, current_template_parms,
5750 				   member_template_p);
5751 	  DECL_TEMPLATE_RESULT (new_tmpl) = decl;
5752 	  TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
5753 	  DECL_TI_TEMPLATE (decl) = new_tmpl;
5754 	  SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
5755 	  DECL_TEMPLATE_INFO (new_tmpl)
5756 	    = build_template_info (tmpl, args);
5757 
5758 	  register_specialization (new_tmpl,
5759 				   most_general_template (tmpl),
5760 				   args,
5761 				   is_friend, 0);
5762 	  return decl;
5763 	}
5764 
5765       /* Make sure the template headers we got make sense.  */
5766 
5767       parms = DECL_TEMPLATE_PARMS (tmpl);
5768       i = TMPL_PARMS_DEPTH (parms);
5769       if (TMPL_ARGS_DEPTH (args) != i)
5770 	{
5771 	  error ("expected %d levels of template parms for %q#D, got %d",
5772 		 i, decl, TMPL_ARGS_DEPTH (args));
5773 	  DECL_INTERFACE_KNOWN (decl) = 1;
5774 	  return error_mark_node;
5775 	}
5776       else
5777 	for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
5778 	  {
5779 	    a = TMPL_ARGS_LEVEL (args, i);
5780 	    t = INNERMOST_TEMPLATE_PARMS (parms);
5781 
5782 	    if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
5783 	      {
5784 		if (current == decl)
5785 		  error ("got %d template parameters for %q#D",
5786 			 TREE_VEC_LENGTH (a), decl);
5787 		else
5788 		  error ("got %d template parameters for %q#T",
5789 			 TREE_VEC_LENGTH (a), current);
5790 		error ("  but %d required", TREE_VEC_LENGTH (t));
5791 		/* Avoid crash in import_export_decl.  */
5792 		DECL_INTERFACE_KNOWN (decl) = 1;
5793 		return error_mark_node;
5794 	      }
5795 
5796 	    if (current == decl)
5797 	      current = ctx;
5798 	    else if (current == NULL_TREE)
5799 	      /* Can happen in erroneous input.  */
5800 	      break;
5801 	    else
5802 	      current = get_containing_scope (current);
5803 	  }
5804 
5805       /* Check that the parms are used in the appropriate qualifying scopes
5806 	 in the declarator.  */
5807       if (!comp_template_args
5808 	  (TI_ARGS (tinfo),
5809 	   TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
5810 	{
5811 	  error ("template arguments to %qD do not match original "
5812 		 "template %qD", decl, DECL_TEMPLATE_RESULT (tmpl));
5813 	  if (!uses_template_parms (TI_ARGS (tinfo)))
5814 	    inform (input_location, "use %<template<>%> for"
5815 		    " an explicit specialization");
5816 	  /* Avoid crash in import_export_decl.  */
5817 	  DECL_INTERFACE_KNOWN (decl) = 1;
5818 	  return error_mark_node;
5819 	}
5820     }
5821 
5822   DECL_TEMPLATE_RESULT (tmpl) = decl;
5823   TREE_TYPE (tmpl) = TREE_TYPE (decl);
5824 
5825   /* Push template declarations for global functions and types.  Note
5826      that we do not try to push a global template friend declared in a
5827      template class; such a thing may well depend on the template
5828      parameters of the class.  */
5829   if (new_template_p && !ctx
5830       && !(is_friend && template_class_depth (current_class_type) > 0))
5831     {
5832       tmpl = pushdecl_namespace_level (tmpl, is_friend);
5833       if (tmpl == error_mark_node)
5834 	return error_mark_node;
5835 
5836       /* Hide template friend classes that haven't been declared yet.  */
5837       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
5838 	{
5839 	  DECL_ANTICIPATED (tmpl) = 1;
5840 	  DECL_FRIEND_P (tmpl) = 1;
5841 	}
5842     }
5843 
5844   if (is_primary)
5845     {
5846       tree parms = DECL_TEMPLATE_PARMS (tmpl);
5847 
5848       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
5849 
5850       /* Give template template parms a DECL_CONTEXT of the template
5851 	 for which they are a parameter.  */
5852       parms = INNERMOST_TEMPLATE_PARMS (parms);
5853       for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
5854 	{
5855 	  tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5856 	  if (TREE_CODE (parm) == TEMPLATE_DECL)
5857 	    DECL_CONTEXT (parm) = tmpl;
5858 	}
5859 
5860       if (TREE_CODE (decl) == TYPE_DECL
5861 	  && TYPE_DECL_ALIAS_P (decl)
5862 	  && complex_alias_template_p (tmpl))
5863 	TEMPLATE_DECL_COMPLEX_ALIAS_P (tmpl) = true;
5864     }
5865 
5866   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
5867      back to its most general template.  If TMPL is a specialization,
5868      ARGS may only have the innermost set of arguments.  Add the missing
5869      argument levels if necessary.  */
5870   if (DECL_TEMPLATE_INFO (tmpl))
5871     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
5872 
5873   info = build_template_info (tmpl, args);
5874 
5875   if (DECL_IMPLICIT_TYPEDEF_P (decl))
5876     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
5877   else
5878     {
5879       if (is_primary)
5880 	retrofit_lang_decl (decl);
5881       if (DECL_LANG_SPECIFIC (decl))
5882 	DECL_TEMPLATE_INFO (decl) = info;
5883     }
5884 
5885   if (flag_implicit_templates
5886       && !is_friend
5887       && TREE_PUBLIC (decl)
5888       && VAR_OR_FUNCTION_DECL_P (decl))
5889     /* Set DECL_COMDAT on template instantiations; if we force
5890        them to be emitted by explicit instantiation or -frepo,
5891        mark_needed will tell cgraph to do the right thing.  */
5892     DECL_COMDAT (decl) = true;
5893 
5894   return DECL_TEMPLATE_RESULT (tmpl);
5895 }
5896 
5897 tree
push_template_decl(tree decl)5898 push_template_decl (tree decl)
5899 {
5900   return push_template_decl_real (decl, false);
5901 }
5902 
5903 /* FN is an inheriting constructor that inherits from the constructor
5904    template INHERITED; turn FN into a constructor template with a matching
5905    template header.  */
5906 
5907 tree
add_inherited_template_parms(tree fn,tree inherited)5908 add_inherited_template_parms (tree fn, tree inherited)
5909 {
5910   tree inner_parms
5911     = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
5912   inner_parms = copy_node (inner_parms);
5913   tree parms
5914     = tree_cons (size_int (processing_template_decl + 1),
5915 		 inner_parms, current_template_parms);
5916   tree tmpl = build_template_decl (fn, parms, /*member*/true);
5917   tree args = template_parms_to_args (parms);
5918   DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
5919   TREE_TYPE (tmpl) = TREE_TYPE (fn);
5920   DECL_TEMPLATE_RESULT (tmpl) = fn;
5921   DECL_ARTIFICIAL (tmpl) = true;
5922   DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
5923   return tmpl;
5924 }
5925 
5926 /* Called when a class template TYPE is redeclared with the indicated
5927    template PARMS, e.g.:
5928 
5929      template <class T> struct S;
5930      template <class T> struct S {};  */
5931 
5932 bool
redeclare_class_template(tree type,tree parms,tree cons)5933 redeclare_class_template (tree type, tree parms, tree cons)
5934 {
5935   tree tmpl;
5936   tree tmpl_parms;
5937   int i;
5938 
5939   if (!TYPE_TEMPLATE_INFO (type))
5940     {
5941       error ("%qT is not a template type", type);
5942       return false;
5943     }
5944 
5945   tmpl = TYPE_TI_TEMPLATE (type);
5946   if (!PRIMARY_TEMPLATE_P (tmpl))
5947     /* The type is nested in some template class.  Nothing to worry
5948        about here; there are no new template parameters for the nested
5949        type.  */
5950     return true;
5951 
5952   if (!parms)
5953     {
5954       error ("template specifiers not specified in declaration of %qD",
5955 	     tmpl);
5956       return false;
5957     }
5958 
5959   parms = INNERMOST_TEMPLATE_PARMS (parms);
5960   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
5961 
5962   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
5963     {
5964       error_n (input_location, TREE_VEC_LENGTH (parms),
5965                "redeclared with %d template parameter",
5966                "redeclared with %d template parameters",
5967                TREE_VEC_LENGTH (parms));
5968       inform_n (DECL_SOURCE_LOCATION (tmpl), TREE_VEC_LENGTH (tmpl_parms),
5969                 "previous declaration %qD used %d template parameter",
5970                 "previous declaration %qD used %d template parameters",
5971                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
5972       return false;
5973     }
5974 
5975   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
5976     {
5977       tree tmpl_parm;
5978       tree parm;
5979       tree tmpl_default;
5980       tree parm_default;
5981 
5982       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
5983           || TREE_VEC_ELT (parms, i) == error_mark_node)
5984         continue;
5985 
5986       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
5987       if (error_operand_p (tmpl_parm))
5988 	return false;
5989 
5990       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5991       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
5992       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
5993 
5994       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
5995 	 TEMPLATE_DECL.  */
5996       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
5997 	  || (TREE_CODE (tmpl_parm) != TYPE_DECL
5998 	      && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
5999 	  || (TREE_CODE (tmpl_parm) != PARM_DECL
6000 	      && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
6001 		  != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
6002 	  || (TREE_CODE (tmpl_parm) == PARM_DECL
6003 	      && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
6004 		  != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
6005 	{
6006 	  error ("template parameter %q+#D", tmpl_parm);
6007 	  error ("redeclared here as %q#D", parm);
6008 	  return false;
6009 	}
6010 
6011       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
6012 	{
6013 	  /* We have in [temp.param]:
6014 
6015 	     A template-parameter may not be given default arguments
6016 	     by two different declarations in the same scope.  */
6017 	  error_at (input_location, "redefinition of default argument for %q#D", parm);
6018 	  inform (DECL_SOURCE_LOCATION (tmpl_parm),
6019 		  "original definition appeared here");
6020 	  return false;
6021 	}
6022 
6023       if (parm_default != NULL_TREE)
6024 	/* Update the previous template parameters (which are the ones
6025 	   that will really count) with the new default value.  */
6026 	TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
6027       else if (tmpl_default != NULL_TREE)
6028 	/* Update the new parameters, too; they'll be used as the
6029 	   parameters for any members.  */
6030 	TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
6031 
6032       /* Give each template template parm in this redeclaration a
6033 	 DECL_CONTEXT of the template for which they are a parameter.  */
6034       if (TREE_CODE (parm) == TEMPLATE_DECL)
6035 	{
6036 	  gcc_assert (DECL_CONTEXT (parm) == NULL_TREE);
6037 	  DECL_CONTEXT (parm) = tmpl;
6038 	}
6039 
6040       if (TREE_CODE (parm) == TYPE_DECL)
6041 	TEMPLATE_TYPE_PARM_FOR_CLASS (TREE_TYPE (parm)) = true;
6042     }
6043 
6044   // Cannot redeclare a class template with a different set of constraints.
6045   if (!equivalent_constraints (get_constraints (tmpl), cons))
6046     {
6047       error_at (input_location, "redeclaration %q#D with different "
6048                                 "constraints", tmpl);
6049       inform (DECL_SOURCE_LOCATION (tmpl),
6050               "original declaration appeared here");
6051     }
6052 
6053     return true;
6054 }
6055 
6056 /* The actual substitution part of instantiate_non_dependent_expr_sfinae,
6057    to be used when the caller has already checked
6058    (processing_template_decl
6059     && !instantiation_dependent_expression_p (expr)
6060     && potential_constant_expression (expr))
6061    and cleared processing_template_decl.  */
6062 
6063 tree
instantiate_non_dependent_expr_internal(tree expr,tsubst_flags_t complain)6064 instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
6065 {
6066   return tsubst_copy_and_build (expr,
6067 				/*args=*/NULL_TREE,
6068 				complain,
6069 				/*in_decl=*/NULL_TREE,
6070 				/*function_p=*/false,
6071 				/*integral_constant_expression_p=*/true);
6072 }
6073 
6074 /* Simplify EXPR if it is a non-dependent expression.  Returns the
6075    (possibly simplified) expression.  */
6076 
6077 tree
instantiate_non_dependent_expr_sfinae(tree expr,tsubst_flags_t complain)6078 instantiate_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
6079 {
6080   if (expr == NULL_TREE)
6081     return NULL_TREE;
6082 
6083   /* If we're in a template, but EXPR isn't value dependent, simplify
6084      it.  We're supposed to treat:
6085 
6086        template <typename T> void f(T[1 + 1]);
6087        template <typename T> void f(T[2]);
6088 
6089      as two declarations of the same function, for example.  */
6090   if (processing_template_decl
6091       && is_nondependent_constant_expression (expr))
6092     {
6093       processing_template_decl_sentinel s;
6094       expr = instantiate_non_dependent_expr_internal (expr, complain);
6095     }
6096   return expr;
6097 }
6098 
6099 tree
instantiate_non_dependent_expr(tree expr)6100 instantiate_non_dependent_expr (tree expr)
6101 {
6102   return instantiate_non_dependent_expr_sfinae (expr, tf_error);
6103 }
6104 
6105 /* Like instantiate_non_dependent_expr, but return NULL_TREE rather than
6106    an uninstantiated expression.  */
6107 
6108 tree
instantiate_non_dependent_or_null(tree expr)6109 instantiate_non_dependent_or_null (tree expr)
6110 {
6111   if (expr == NULL_TREE)
6112     return NULL_TREE;
6113   if (processing_template_decl)
6114     {
6115       if (!is_nondependent_constant_expression (expr))
6116 	expr = NULL_TREE;
6117       else
6118 	{
6119 	  processing_template_decl_sentinel s;
6120 	  expr = instantiate_non_dependent_expr_internal (expr, tf_error);
6121 	}
6122     }
6123   return expr;
6124 }
6125 
6126 /* True iff T is a specialization of a variable template.  */
6127 
6128 bool
variable_template_specialization_p(tree t)6129 variable_template_specialization_p (tree t)
6130 {
6131   if (!VAR_P (t) || !DECL_LANG_SPECIFIC (t) || !DECL_TEMPLATE_INFO (t))
6132     return false;
6133   tree tmpl = DECL_TI_TEMPLATE (t);
6134   return variable_template_p (tmpl);
6135 }
6136 
6137 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
6138    template declaration, or a TYPE_DECL for an alias declaration.  */
6139 
6140 bool
alias_type_or_template_p(tree t)6141 alias_type_or_template_p (tree t)
6142 {
6143   if (t == NULL_TREE)
6144     return false;
6145   return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
6146 	  || (TYPE_P (t)
6147 	      && TYPE_NAME (t)
6148 	      && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
6149 	  || DECL_ALIAS_TEMPLATE_P (t));
6150 }
6151 
6152 /* Return TRUE iff T is a specialization of an alias template.  */
6153 
6154 bool
alias_template_specialization_p(const_tree t)6155 alias_template_specialization_p (const_tree t)
6156 {
6157   /* It's an alias template specialization if it's an alias and its
6158      TYPE_NAME is a specialization of a primary template.  */
6159   if (TYPE_ALIAS_P (t))
6160     if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
6161       return PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo));
6162 
6163   return false;
6164 }
6165 
6166 /* An alias template is complex from a SFINAE perspective if a template-id
6167    using that alias can be ill-formed when the expansion is not, as with
6168    the void_t template.  We determine this by checking whether the
6169    expansion for the alias template uses all its template parameters.  */
6170 
6171 struct uses_all_template_parms_data
6172 {
6173   int level;
6174   bool *seen;
6175 };
6176 
6177 static int
uses_all_template_parms_r(tree t,void * data_)6178 uses_all_template_parms_r (tree t, void *data_)
6179 {
6180   struct uses_all_template_parms_data &data
6181     = *(struct uses_all_template_parms_data*)data_;
6182   tree idx = get_template_parm_index (t);
6183 
6184   if (TEMPLATE_PARM_LEVEL (idx) == data.level)
6185     data.seen[TEMPLATE_PARM_IDX (idx)] = true;
6186   return 0;
6187 }
6188 
6189 /* for_each_template_parm any_fn callback for complex_alias_template_p.  */
6190 
6191 static int
complex_pack_expansion_r(tree t,void * data_)6192 complex_pack_expansion_r (tree t, void *data_)
6193 {
6194   /* An alias template with a pack expansion that expands a pack from the
6195      enclosing class needs to be considered complex, to avoid confusion with
6196      the same pack being used as an argument to the alias's own template
6197      parameter (91966).  */
6198   if (!PACK_EXPANSION_P (t))
6199     return 0;
6200   struct uses_all_template_parms_data &data
6201     = *(struct uses_all_template_parms_data*)data_;
6202   for (tree pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
6203        pack = TREE_CHAIN (pack))
6204     {
6205       tree parm_pack = TREE_VALUE (pack);
6206       if (!TEMPLATE_PARM_P (parm_pack))
6207 	continue;
6208       int idx, level;
6209       template_parm_level_and_index (parm_pack, &level, &idx);
6210       if (level < data.level)
6211 	return 1;
6212     }
6213   return 0;
6214 }
6215 
6216 static bool
complex_alias_template_p(const_tree tmpl)6217 complex_alias_template_p (const_tree tmpl)
6218 {
6219   struct uses_all_template_parms_data data;
6220   tree pat = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6221   tree parms = DECL_TEMPLATE_PARMS (tmpl);
6222   data.level = TMPL_PARMS_DEPTH (parms);
6223   int len = TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS (parms));
6224   data.seen = XALLOCAVEC (bool, len);
6225   for (int i = 0; i < len; ++i)
6226     data.seen[i] = false;
6227 
6228   if (for_each_template_parm (pat, uses_all_template_parms_r, &data,
6229 			      NULL, true, complex_pack_expansion_r))
6230     return true;
6231   for (int i = 0; i < len; ++i)
6232     if (!data.seen[i])
6233       return true;
6234   return false;
6235 }
6236 
6237 /* Return TRUE iff T is a specialization of a complex alias template with
6238    dependent template-arguments.  */
6239 
6240 bool
dependent_alias_template_spec_p(const_tree t)6241 dependent_alias_template_spec_p (const_tree t)
6242 {
6243   if (!alias_template_specialization_p (t))
6244     return false;
6245 
6246   tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t);
6247   if (!TEMPLATE_DECL_COMPLEX_ALIAS_P (TI_TEMPLATE (tinfo)))
6248     return false;
6249 
6250   tree args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo));
6251   if (!any_dependent_template_arguments_p (args))
6252     return false;
6253 
6254   return true;
6255 }
6256 
6257 /* Return the number of innermost template parameters in TMPL.  */
6258 
6259 static int
num_innermost_template_parms(tree tmpl)6260 num_innermost_template_parms (tree tmpl)
6261 {
6262   tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6263   return TREE_VEC_LENGTH (parms);
6264 }
6265 
6266 /* Return either TMPL or another template that it is equivalent to under DR
6267    1286: An alias that just changes the name of a template is equivalent to
6268    the other template.  */
6269 
6270 static tree
get_underlying_template(tree tmpl)6271 get_underlying_template (tree tmpl)
6272 {
6273   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
6274   while (DECL_ALIAS_TEMPLATE_P (tmpl))
6275     {
6276       /* Determine if the alias is equivalent to an underlying template.  */
6277       tree orig_type = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6278       tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (orig_type);
6279       if (!tinfo)
6280 	break;
6281 
6282       tree underlying = TI_TEMPLATE (tinfo);
6283       if (!PRIMARY_TEMPLATE_P (underlying)
6284 	  || (num_innermost_template_parms (tmpl)
6285 	      != num_innermost_template_parms (underlying)))
6286 	break;
6287 
6288       tree alias_args = INNERMOST_TEMPLATE_ARGS
6289 	(template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl)));
6290       if (!comp_template_args (TI_ARGS (tinfo), alias_args))
6291 	break;
6292 
6293       /* Alias is equivalent.  Strip it and repeat.  */
6294       tmpl = underlying;
6295     }
6296 
6297   return tmpl;
6298 }
6299 
6300 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
6301    must be a reference-to-function or a pointer-to-function type, as specified
6302    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
6303    and check that the resulting function has external linkage.  */
6304 
6305 static tree
convert_nontype_argument_function(tree type,tree expr,tsubst_flags_t complain)6306 convert_nontype_argument_function (tree type, tree expr,
6307 				   tsubst_flags_t complain)
6308 {
6309   tree fns = expr;
6310   tree fn, fn_no_ptr;
6311   linkage_kind linkage;
6312 
6313   fn = instantiate_type (type, fns, tf_none);
6314   if (fn == error_mark_node)
6315     return error_mark_node;
6316 
6317   if (value_dependent_expression_p (fn))
6318     goto accept;
6319 
6320   fn_no_ptr = strip_fnptr_conv (fn);
6321   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
6322     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6323   if (BASELINK_P (fn_no_ptr))
6324     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
6325 
6326   /* [temp.arg.nontype]/1
6327 
6328      A template-argument for a non-type, non-template template-parameter
6329      shall be one of:
6330      [...]
6331      -- the address of an object or function with external [C++11: or
6332         internal] linkage.  */
6333 
6334   if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
6335     {
6336       if (complain & tf_error)
6337 	{
6338 	  error ("%qE is not a valid template argument for type %qT",
6339 		 expr, type);
6340 	  if (TYPE_PTR_P (type))
6341 	    inform (input_location, "it must be the address of a function "
6342 		    "with external linkage");
6343 	  else
6344 	    inform (input_location, "it must be the name of a function with "
6345 		    "external linkage");
6346 	}
6347       return NULL_TREE;
6348     }
6349 
6350   linkage = decl_linkage (fn_no_ptr);
6351   if (cxx_dialect >= cxx11 ? linkage == lk_none : linkage != lk_external)
6352     {
6353       if (complain & tf_error)
6354 	{
6355 	  if (cxx_dialect >= cxx11)
6356 	    error ("%qE is not a valid template argument for type %qT "
6357 		   "because %qD has no linkage",
6358 		   expr, type, fn_no_ptr);
6359 	  else
6360 	    error ("%qE is not a valid template argument for type %qT "
6361 		   "because %qD does not have external linkage",
6362 		   expr, type, fn_no_ptr);
6363 	}
6364       return NULL_TREE;
6365     }
6366 
6367  accept:
6368   if (TREE_CODE (type) == REFERENCE_TYPE)
6369     {
6370       if (REFERENCE_REF_P (fn))
6371 	fn = TREE_OPERAND (fn, 0);
6372       else
6373 	fn = build_address (fn);
6374     }
6375   if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (fn)))
6376     fn = build_nop (type, fn);
6377 
6378   return fn;
6379 }
6380 
6381 /* Subroutine of convert_nontype_argument.
6382    Check if EXPR of type TYPE is a valid pointer-to-member constant.
6383    Emit an error otherwise.  */
6384 
6385 static bool
check_valid_ptrmem_cst_expr(tree type,tree expr,tsubst_flags_t complain)6386 check_valid_ptrmem_cst_expr (tree type, tree expr,
6387 			     tsubst_flags_t complain)
6388 {
6389   location_t loc = EXPR_LOC_OR_LOC (expr, input_location);
6390   tree orig_expr = expr;
6391   STRIP_NOPS (expr);
6392   if (null_ptr_cst_p (expr))
6393     return true;
6394   if (TREE_CODE (expr) == PTRMEM_CST
6395       && same_type_p (TYPE_PTRMEM_CLASS_TYPE (type),
6396 		      PTRMEM_CST_CLASS (expr)))
6397     return true;
6398   if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
6399     return true;
6400   if (processing_template_decl
6401       && TREE_CODE (expr) == ADDR_EXPR
6402       && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
6403     return true;
6404   if (complain & tf_error)
6405     {
6406       error_at (loc, "%qE is not a valid template argument for type %qT",
6407 		orig_expr, type);
6408       if (TREE_CODE (expr) != PTRMEM_CST)
6409 	inform (loc, "it must be a pointer-to-member of the form %<&X::Y%>");
6410       else
6411 	inform (loc, "because it is a member of %qT", PTRMEM_CST_CLASS (expr));
6412     }
6413   return false;
6414 }
6415 
6416 /* Returns TRUE iff the address of OP is value-dependent.
6417 
6418    14.6.2.4 [temp.dep.temp]:
6419    A non-integral non-type template-argument is dependent if its type is
6420    dependent or it has either of the following forms
6421      qualified-id
6422      & qualified-id
6423    and contains a nested-name-specifier which specifies a class-name that
6424    names a dependent type.
6425 
6426    We generalize this to just say that the address of a member of a
6427    dependent class is value-dependent; the above doesn't cover the
6428    address of a static data member named with an unqualified-id.  */
6429 
6430 static bool
has_value_dependent_address(tree op)6431 has_value_dependent_address (tree op)
6432 {
6433   /* We could use get_inner_reference here, but there's no need;
6434      this is only relevant for template non-type arguments, which
6435      can only be expressed as &id-expression.  */
6436   if (DECL_P (op))
6437     {
6438       tree ctx = CP_DECL_CONTEXT (op);
6439       if (TYPE_P (ctx) && dependent_type_p (ctx))
6440 	return true;
6441     }
6442 
6443   return false;
6444 }
6445 
6446 /* The next set of functions are used for providing helpful explanatory
6447    diagnostics for failed overload resolution.  Their messages should be
6448    indented by two spaces for consistency with the messages in
6449    call.c  */
6450 
6451 static int
unify_success(bool)6452 unify_success (bool /*explain_p*/)
6453 {
6454   return 0;
6455 }
6456 
6457 /* Other failure functions should call this one, to provide a single function
6458    for setting a breakpoint on.  */
6459 
6460 static int
unify_invalid(bool)6461 unify_invalid (bool /*explain_p*/)
6462 {
6463   return 1;
6464 }
6465 
6466 static int
unify_parameter_deduction_failure(bool explain_p,tree parm)6467 unify_parameter_deduction_failure (bool explain_p, tree parm)
6468 {
6469   if (explain_p)
6470     inform (input_location,
6471 	    "  couldn't deduce template parameter %qD", parm);
6472   return unify_invalid (explain_p);
6473 }
6474 
6475 static int
unify_cv_qual_mismatch(bool explain_p,tree parm,tree arg)6476 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
6477 {
6478   if (explain_p)
6479     inform (input_location,
6480 	    "  types %qT and %qT have incompatible cv-qualifiers",
6481 	    parm, arg);
6482   return unify_invalid (explain_p);
6483 }
6484 
6485 static int
unify_type_mismatch(bool explain_p,tree parm,tree arg)6486 unify_type_mismatch (bool explain_p, tree parm, tree arg)
6487 {
6488   if (explain_p)
6489     inform (input_location, "  mismatched types %qT and %qT", parm, arg);
6490   return unify_invalid (explain_p);
6491 }
6492 
6493 static int
unify_parameter_pack_mismatch(bool explain_p,tree parm,tree arg)6494 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
6495 {
6496   if (explain_p)
6497     inform (input_location,
6498 	    "  template parameter %qD is not a parameter pack, but "
6499 	    "argument %qD is",
6500 	    parm, arg);
6501   return unify_invalid (explain_p);
6502 }
6503 
6504 static int
unify_ptrmem_cst_mismatch(bool explain_p,tree parm,tree arg)6505 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
6506 {
6507   if (explain_p)
6508     inform (input_location,
6509 	    "  template argument %qE does not match "
6510 	    "pointer-to-member constant %qE",
6511 	    arg, parm);
6512   return unify_invalid (explain_p);
6513 }
6514 
6515 static int
unify_expression_unequal(bool explain_p,tree parm,tree arg)6516 unify_expression_unequal (bool explain_p, tree parm, tree arg)
6517 {
6518   if (explain_p)
6519     inform (input_location, "  %qE is not equivalent to %qE", parm, arg);
6520   return unify_invalid (explain_p);
6521 }
6522 
6523 static int
unify_parameter_pack_inconsistent(bool explain_p,tree old_arg,tree new_arg)6524 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
6525 {
6526   if (explain_p)
6527     inform (input_location,
6528 	    "  inconsistent parameter pack deduction with %qT and %qT",
6529 	    old_arg, new_arg);
6530   return unify_invalid (explain_p);
6531 }
6532 
6533 static int
unify_inconsistency(bool explain_p,tree parm,tree first,tree second)6534 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
6535 {
6536   if (explain_p)
6537     {
6538       if (TYPE_P (parm))
6539 	inform (input_location,
6540 		"  deduced conflicting types for parameter %qT (%qT and %qT)",
6541 		parm, first, second);
6542       else
6543 	inform (input_location,
6544 		"  deduced conflicting values for non-type parameter "
6545 		"%qE (%qE and %qE)", parm, first, second);
6546     }
6547   return unify_invalid (explain_p);
6548 }
6549 
6550 static int
unify_vla_arg(bool explain_p,tree arg)6551 unify_vla_arg (bool explain_p, tree arg)
6552 {
6553   if (explain_p)
6554     inform (input_location,
6555 	    "  variable-sized array type %qT is not "
6556 	    "a valid template argument",
6557 	    arg);
6558   return unify_invalid (explain_p);
6559 }
6560 
6561 static int
unify_method_type_error(bool explain_p,tree arg)6562 unify_method_type_error (bool explain_p, tree arg)
6563 {
6564   if (explain_p)
6565     inform (input_location,
6566 	    "  member function type %qT is not a valid template argument",
6567 	    arg);
6568   return unify_invalid (explain_p);
6569 }
6570 
6571 static int
6572 unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
6573 {
6574   if (explain_p)
6575     {
6576       if (least_p)
6577 	inform_n (input_location, wanted,
6578 		  "  candidate expects at least %d argument, %d provided",
6579 		  "  candidate expects at least %d arguments, %d provided",
6580 		  wanted, have);
6581       else
6582 	inform_n (input_location, wanted,
6583 		  "  candidate expects %d argument, %d provided",
6584 		  "  candidate expects %d arguments, %d provided",
6585 		  wanted, have);
6586     }
6587   return unify_invalid (explain_p);
6588 }
6589 
6590 static int
unify_too_many_arguments(bool explain_p,int have,int wanted)6591 unify_too_many_arguments (bool explain_p, int have, int wanted)
6592 {
6593   return unify_arity (explain_p, have, wanted);
6594 }
6595 
6596 static int
6597 unify_too_few_arguments (bool explain_p, int have, int wanted,
6598 			 bool least_p = false)
6599 {
6600   return unify_arity (explain_p, have, wanted, least_p);
6601 }
6602 
6603 static int
unify_arg_conversion(bool explain_p,tree to_type,tree from_type,tree arg)6604 unify_arg_conversion (bool explain_p, tree to_type,
6605 		      tree from_type, tree arg)
6606 {
6607   if (explain_p)
6608     inform (EXPR_LOC_OR_LOC (arg, input_location),
6609 	    "  cannot convert %qE (type %qT) to type %qT",
6610 	    arg, from_type, to_type);
6611   return unify_invalid (explain_p);
6612 }
6613 
6614 static int
unify_no_common_base(bool explain_p,enum template_base_result r,tree parm,tree arg)6615 unify_no_common_base (bool explain_p, enum template_base_result r,
6616 		      tree parm, tree arg)
6617 {
6618   if (explain_p)
6619     switch (r)
6620       {
6621       case tbr_ambiguous_baseclass:
6622 	inform (input_location, "  %qT is an ambiguous base class of %qT",
6623 		parm, arg);
6624 	break;
6625       default:
6626 	inform (input_location, "  %qT is not derived from %qT", arg, parm);
6627 	break;
6628       }
6629   return unify_invalid (explain_p);
6630 }
6631 
6632 static int
unify_inconsistent_template_template_parameters(bool explain_p)6633 unify_inconsistent_template_template_parameters (bool explain_p)
6634 {
6635   if (explain_p)
6636     inform (input_location,
6637 	    "  template parameters of a template template argument are "
6638 	    "inconsistent with other deduced template arguments");
6639   return unify_invalid (explain_p);
6640 }
6641 
6642 static int
unify_template_deduction_failure(bool explain_p,tree parm,tree arg)6643 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
6644 {
6645   if (explain_p)
6646     inform (input_location,
6647 	    "  can't deduce a template for %qT from non-template type %qT",
6648 	    parm, arg);
6649   return unify_invalid (explain_p);
6650 }
6651 
6652 static int
unify_template_argument_mismatch(bool explain_p,tree parm,tree arg)6653 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
6654 {
6655   if (explain_p)
6656     inform (input_location,
6657 	    "  template argument %qE does not match %qE", arg, parm);
6658   return unify_invalid (explain_p);
6659 }
6660 
6661 /* Attempt to convert the non-type template parameter EXPR to the
6662    indicated TYPE.  If the conversion is successful, return the
6663    converted value.  If the conversion is unsuccessful, return
6664    NULL_TREE if we issued an error message, or error_mark_node if we
6665    did not.  We issue error messages for out-and-out bad template
6666    parameters, but not simply because the conversion failed, since we
6667    might be just trying to do argument deduction.  Both TYPE and EXPR
6668    must be non-dependent.
6669 
6670    The conversion follows the special rules described in
6671    [temp.arg.nontype], and it is much more strict than an implicit
6672    conversion.
6673 
6674    This function is called twice for each template argument (see
6675    lookup_template_class for a more accurate description of this
6676    problem). This means that we need to handle expressions which
6677    are not valid in a C++ source, but can be created from the
6678    first call (for instance, casts to perform conversions). These
6679    hacks can go away after we fix the double coercion problem.  */
6680 
6681 static tree
convert_nontype_argument(tree type,tree expr,tsubst_flags_t complain)6682 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
6683 {
6684   tree expr_type;
6685   location_t loc = EXPR_LOC_OR_LOC (expr, input_location);
6686   tree orig_expr = expr;
6687 
6688   /* Detect immediately string literals as invalid non-type argument.
6689      This special-case is not needed for correctness (we would easily
6690      catch this later), but only to provide better diagnostic for this
6691      common user mistake. As suggested by DR 100, we do not mention
6692      linkage issues in the diagnostic as this is not the point.  */
6693   /* FIXME we're making this OK.  */
6694   if (TREE_CODE (expr) == STRING_CST)
6695     {
6696       if (complain & tf_error)
6697 	error ("%qE is not a valid template argument for type %qT "
6698 	       "because string literals can never be used in this context",
6699 	       expr, type);
6700       return NULL_TREE;
6701     }
6702 
6703   /* Add the ADDR_EXPR now for the benefit of
6704      value_dependent_expression_p.  */
6705   if (TYPE_PTROBV_P (type)
6706       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
6707     {
6708       expr = decay_conversion (expr, complain);
6709       if (expr == error_mark_node)
6710 	return error_mark_node;
6711     }
6712 
6713   /* If we are in a template, EXPR may be non-dependent, but still
6714      have a syntactic, rather than semantic, form.  For example, EXPR
6715      might be a SCOPE_REF, rather than the VAR_DECL to which the
6716      SCOPE_REF refers.  Preserving the qualifying scope is necessary
6717      so that access checking can be performed when the template is
6718      instantiated -- but here we need the resolved form so that we can
6719      convert the argument.  */
6720   bool non_dep = false;
6721   if (TYPE_REF_OBJ_P (type)
6722       && has_value_dependent_address (expr))
6723     /* If we want the address and it's value-dependent, don't fold.  */;
6724   else if (processing_template_decl
6725 	   && is_nondependent_constant_expression (expr))
6726     non_dep = true;
6727   if (error_operand_p (expr))
6728     return error_mark_node;
6729   expr_type = TREE_TYPE (expr);
6730 
6731   /* If the argument is non-dependent, perform any conversions in
6732      non-dependent context as well.  */
6733   processing_template_decl_sentinel s (non_dep);
6734   if (non_dep)
6735     expr = instantiate_non_dependent_expr_internal (expr, complain);
6736 
6737   if (value_dependent_expression_p (expr))
6738     expr = canonicalize_expr_argument (expr, complain);
6739 
6740   /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
6741      to a non-type argument of "nullptr".  */
6742   if (NULLPTR_TYPE_P (expr_type) && TYPE_PTR_OR_PTRMEM_P (type))
6743     expr = fold_simple (convert (type, expr));
6744 
6745   /* In C++11, integral or enumeration non-type template arguments can be
6746      arbitrary constant expressions.  Pointer and pointer to
6747      member arguments can be general constant expressions that evaluate
6748      to a null value, but otherwise still need to be of a specific form.  */
6749   if (cxx_dialect >= cxx11)
6750     {
6751       if (TREE_CODE (expr) == PTRMEM_CST)
6752 	/* A PTRMEM_CST is already constant, and a valid template
6753 	   argument for a parameter of pointer to member type, we just want
6754 	   to leave it in that form rather than lower it to a
6755 	   CONSTRUCTOR.  */;
6756       else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
6757 	       || cxx_dialect >= cxx17)
6758 	{
6759 	  /* C++17: A template-argument for a non-type template-parameter shall
6760 	     be a converted constant expression (8.20) of the type of the
6761 	     template-parameter.  */
6762 	  expr = build_converted_constant_expr (type, expr, complain);
6763 	  if (expr == error_mark_node)
6764 	    return error_mark_node;
6765 	  expr = maybe_constant_value (expr);
6766 	  expr = convert_from_reference (expr);
6767 	}
6768       else if (TYPE_PTR_OR_PTRMEM_P (type))
6769 	{
6770 	  tree folded = maybe_constant_value (expr);
6771 	  if (TYPE_PTR_P (type) ? integer_zerop (folded)
6772 	      : null_member_pointer_value_p (folded))
6773 	    expr = folded;
6774 	}
6775     }
6776 
6777   if (TREE_CODE (type) == REFERENCE_TYPE)
6778     expr = mark_lvalue_use (expr);
6779   else
6780     expr = mark_rvalue_use (expr);
6781 
6782   /* HACK: Due to double coercion, we can get a
6783      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
6784      which is the tree that we built on the first call (see
6785      below when coercing to reference to object or to reference to
6786      function). We just strip everything and get to the arg.
6787      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
6788      for examples.  */
6789   if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
6790     {
6791       tree probe_type, probe = expr;
6792       if (REFERENCE_REF_P (probe))
6793 	probe = TREE_OPERAND (probe, 0);
6794       probe_type = TREE_TYPE (probe);
6795       if (TREE_CODE (probe) == NOP_EXPR)
6796 	{
6797 	  /* ??? Maybe we could use convert_from_reference here, but we
6798 	     would need to relax its constraints because the NOP_EXPR
6799 	     could actually change the type to something more cv-qualified,
6800 	     and this is not folded by convert_from_reference.  */
6801 	  tree addr = TREE_OPERAND (probe, 0);
6802 	  if (TREE_CODE (probe_type) == REFERENCE_TYPE
6803 	      && TREE_CODE (addr) == ADDR_EXPR
6804 	      && TYPE_PTR_P (TREE_TYPE (addr))
6805 	      && (same_type_ignoring_top_level_qualifiers_p
6806 		  (TREE_TYPE (probe_type),
6807 		   TREE_TYPE (TREE_TYPE (addr)))))
6808 	    {
6809 	      expr = TREE_OPERAND (addr, 0);
6810 	      expr_type = TREE_TYPE (probe_type);
6811 	    }
6812 	}
6813     }
6814 
6815   /* [temp.arg.nontype]/5, bullet 1
6816 
6817      For a non-type template-parameter of integral or enumeration type,
6818      integral promotions (_conv.prom_) and integral conversions
6819      (_conv.integral_) are applied.  */
6820   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
6821     {
6822       if (cxx_dialect < cxx11)
6823 	{
6824 	  tree t = build_converted_constant_expr (type, expr, complain);
6825 	  t = maybe_constant_value (t);
6826 	  if (t != error_mark_node)
6827 	    expr = t;
6828 	}
6829 
6830       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
6831 	return error_mark_node;
6832 
6833       /* Notice that there are constant expressions like '4 % 0' which
6834 	 do not fold into integer constants.  */
6835       if (TREE_CODE (expr) != INTEGER_CST
6836 	  && !value_dependent_expression_p (expr))
6837 	{
6838 	  if (complain & tf_error)
6839 	    {
6840 	      int errs = errorcount, warns = warningcount + werrorcount;
6841 	      if (!require_potential_constant_expression (expr))
6842 		expr = error_mark_node;
6843 	      else
6844 		expr = cxx_constant_value (expr);
6845 	      if (errorcount > errs || warningcount + werrorcount > warns)
6846 		inform (loc, "in template argument for type %qT", type);
6847 	      if (expr == error_mark_node)
6848 		return NULL_TREE;
6849 	      /* else cxx_constant_value complained but gave us
6850 		 a real constant, so go ahead.  */
6851 	      if (TREE_CODE (expr) != INTEGER_CST)
6852 		{
6853 		  /* Some assemble time constant expressions like
6854 		     (intptr_t)&&lab1 - (intptr_t)&&lab2 or
6855 		     4 + (intptr_t)&&var satisfy reduced_constant_expression_p
6856 		     as we can emit them into .rodata initializers of
6857 		     variables, yet they can't fold into an INTEGER_CST at
6858 		     compile time.  Refuse them here.  */
6859 		  gcc_checking_assert (reduced_constant_expression_p (expr));
6860 		  error_at (loc, "template argument %qE for type %qT not "
6861 				 "a constant integer", expr, type);
6862 		  return NULL_TREE;
6863 		}
6864 	    }
6865 	  else
6866 	    return NULL_TREE;
6867 	}
6868 
6869       /* Avoid typedef problems.  */
6870       if (TREE_TYPE (expr) != type)
6871 	expr = fold_convert (type, expr);
6872     }
6873   /* [temp.arg.nontype]/5, bullet 2
6874 
6875      For a non-type template-parameter of type pointer to object,
6876      qualification conversions (_conv.qual_) and the array-to-pointer
6877      conversion (_conv.array_) are applied.  */
6878   else if (TYPE_PTROBV_P (type))
6879     {
6880       tree decayed = expr;
6881 
6882       /* Look through any NOP_EXPRs around an ADDR_EXPR, whether they come from
6883 	 decay_conversion or an explicit cast.  If it's a problematic cast,
6884 	 we'll complain about it below.  */
6885       if (TREE_CODE (expr) == NOP_EXPR)
6886 	{
6887 	  tree probe = expr;
6888 	  STRIP_NOPS (probe);
6889 	  if (TREE_CODE (probe) == ADDR_EXPR
6890 	      && TYPE_PTR_P (TREE_TYPE (probe)))
6891 	    {
6892 	      expr = probe;
6893 	      expr_type = TREE_TYPE (expr);
6894 	    }
6895 	}
6896 
6897       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
6898 
6899 	 A template-argument for a non-type, non-template template-parameter
6900 	 shall be one of: [...]
6901 
6902 	 -- the name of a non-type template-parameter;
6903 	 -- the address of an object or function with external linkage, [...]
6904 	    expressed as "& id-expression" where the & is optional if the name
6905 	    refers to a function or array, or if the corresponding
6906 	    template-parameter is a reference.
6907 
6908 	Here, we do not care about functions, as they are invalid anyway
6909 	for a parameter of type pointer-to-object.  */
6910 
6911       if (value_dependent_expression_p (expr))
6912 	/* Non-type template parameters are OK.  */
6913 	;
6914       else if (cxx_dialect >= cxx11 && integer_zerop (expr))
6915 	/* Null pointer values are OK in C++11.  */;
6916       else if (TREE_CODE (expr) != ADDR_EXPR)
6917 	{
6918 	  if (VAR_P (expr))
6919 	    {
6920 	      if (complain & tf_error)
6921 		error ("%qD is not a valid template argument "
6922 		       "because %qD is a variable, not the address of "
6923 		       "a variable", orig_expr, expr);
6924 	      return NULL_TREE;
6925 	    }
6926 	  if (POINTER_TYPE_P (expr_type))
6927 	    {
6928 	      if (complain & tf_error)
6929 		error ("%qE is not a valid template argument for %qT "
6930 		       "because it is not the address of a variable",
6931 		       orig_expr, type);
6932 	      return NULL_TREE;
6933 	    }
6934 	  /* Other values, like integer constants, might be valid
6935 	     non-type arguments of some other type.  */
6936 	  return error_mark_node;
6937 	}
6938       else
6939 	{
6940 	  tree decl = TREE_OPERAND (expr, 0);
6941 
6942 	  if (!VAR_P (decl))
6943 	    {
6944 	      if (complain & tf_error)
6945 		error ("%qE is not a valid template argument of type %qT "
6946 		       "because %qE is not a variable", orig_expr, type, decl);
6947 	      return NULL_TREE;
6948 	    }
6949 	  else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
6950 	    {
6951 	      if (complain & tf_error)
6952 		error ("%qE is not a valid template argument of type %qT "
6953 		       "because %qD does not have external linkage",
6954 		       orig_expr, type, decl);
6955 	      return NULL_TREE;
6956 	    }
6957 	  else if ((cxx_dialect >= cxx11 && cxx_dialect < cxx17)
6958 		   && decl_linkage (decl) == lk_none)
6959 	    {
6960 	      if (complain & tf_error)
6961 		error ("%qE is not a valid template argument of type %qT "
6962 		       "because %qD has no linkage", orig_expr, type, decl);
6963 	      return NULL_TREE;
6964 	    }
6965 	  /* C++17: For a non-type template-parameter of reference or pointer
6966 	     type, the value of the constant expression shall not refer to (or
6967 	     for a pointer type, shall not be the address of):
6968 	       * a subobject (4.5),
6969 	       * a temporary object (15.2),
6970 	       * a string literal (5.13.5),
6971 	       * the result of a typeid expression (8.2.8), or
6972 	       * a predefined __func__ variable (11.4.1).  */
6973 	  else if (DECL_ARTIFICIAL (decl))
6974 	    {
6975 	      if (complain & tf_error)
6976 		error ("the address of %qD is not a valid template argument",
6977 		       decl);
6978 	      return NULL_TREE;
6979 	    }
6980 	  else if (!same_type_ignoring_top_level_qualifiers_p
6981 		   (strip_array_types (TREE_TYPE (type)),
6982 		    strip_array_types (TREE_TYPE (decl))))
6983 	    {
6984 	      if (complain & tf_error)
6985 		error ("the address of the %qT subobject of %qD is not a "
6986 		       "valid template argument", TREE_TYPE (type), decl);
6987 	      return NULL_TREE;
6988 	    }
6989 	  else if (!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
6990 	    {
6991 	      if (complain & tf_error)
6992 		error ("the address of %qD is not a valid template argument "
6993 		       "because it does not have static storage duration",
6994 		       decl);
6995 	      return NULL_TREE;
6996 	    }
6997 	}
6998 
6999       expr = decayed;
7000 
7001       expr = perform_qualification_conversions (type, expr);
7002       if (expr == error_mark_node)
7003 	return error_mark_node;
7004     }
7005   /* [temp.arg.nontype]/5, bullet 3
7006 
7007      For a non-type template-parameter of type reference to object, no
7008      conversions apply. The type referred to by the reference may be more
7009      cv-qualified than the (otherwise identical) type of the
7010      template-argument. The template-parameter is bound directly to the
7011      template-argument, which must be an lvalue.  */
7012   else if (TYPE_REF_OBJ_P (type))
7013     {
7014       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
7015 						      expr_type))
7016 	return error_mark_node;
7017 
7018       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
7019 	{
7020 	  if (complain & tf_error)
7021 	    error ("%qE is not a valid template argument for type %qT "
7022 		   "because of conflicts in cv-qualification", expr, type);
7023 	  return NULL_TREE;
7024 	}
7025 
7026       if (!lvalue_p (expr))
7027 	{
7028 	  if (complain & tf_error)
7029 	    error ("%qE is not a valid template argument for type %qT "
7030 		   "because it is not an lvalue", expr, type);
7031 	  return NULL_TREE;
7032 	}
7033 
7034       /* [temp.arg.nontype]/1
7035 
7036 	 A template-argument for a non-type, non-template template-parameter
7037 	 shall be one of: [...]
7038 
7039 	 -- the address of an object or function with external linkage.  */
7040       if (INDIRECT_REF_P (expr)
7041 	  && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
7042 	{
7043 	  expr = TREE_OPERAND (expr, 0);
7044 	  if (DECL_P (expr))
7045 	    {
7046 	      if (complain & tf_error)
7047 		error ("%q#D is not a valid template argument for type %qT "
7048 		       "because a reference variable does not have a constant "
7049 		       "address", expr, type);
7050 	      return NULL_TREE;
7051 	    }
7052 	}
7053 
7054       if (TYPE_REF_OBJ_P (TREE_TYPE (expr))
7055 	  && value_dependent_expression_p (expr))
7056 	/* OK, dependent reference.  We don't want to ask whether a DECL is
7057 	   itself value-dependent, since what we want here is its address.  */;
7058       else
7059 	{
7060 	  if (!DECL_P (expr))
7061 	    {
7062 	      if (complain & tf_error)
7063 		error ("%qE is not a valid template argument for type %qT "
7064 		       "because it is not an object with linkage",
7065 		       expr, type);
7066 	      return NULL_TREE;
7067 	    }
7068 
7069 	  /* DR 1155 allows internal linkage in C++11 and up.  */
7070 	  linkage_kind linkage = decl_linkage (expr);
7071 	  if (linkage < (cxx_dialect >= cxx11 ? lk_internal : lk_external))
7072 	    {
7073 	      if (complain & tf_error)
7074 		error ("%qE is not a valid template argument for type %qT "
7075 		       "because object %qD does not have linkage",
7076 		       expr, type, expr);
7077 	      return NULL_TREE;
7078 	    }
7079 
7080 	  expr = build_address (expr);
7081 	}
7082 
7083       if (!same_type_p (type, TREE_TYPE (expr)))
7084 	expr = build_nop (type, expr);
7085     }
7086   /* [temp.arg.nontype]/5, bullet 4
7087 
7088      For a non-type template-parameter of type pointer to function, only
7089      the function-to-pointer conversion (_conv.func_) is applied. If the
7090      template-argument represents a set of overloaded functions (or a
7091      pointer to such), the matching function is selected from the set
7092      (_over.over_).  */
7093   else if (TYPE_PTRFN_P (type))
7094     {
7095       /* If the argument is a template-id, we might not have enough
7096 	 context information to decay the pointer.  */
7097       if (!type_unknown_p (expr_type))
7098 	{
7099 	  expr = decay_conversion (expr, complain);
7100 	  if (expr == error_mark_node)
7101 	    return error_mark_node;
7102 	}
7103 
7104       if (cxx_dialect >= cxx11 && integer_zerop (expr))
7105 	/* Null pointer values are OK in C++11.  */
7106 	return perform_qualification_conversions (type, expr);
7107 
7108       expr = convert_nontype_argument_function (type, expr, complain);
7109       if (!expr || expr == error_mark_node)
7110 	return expr;
7111     }
7112   /* [temp.arg.nontype]/5, bullet 5
7113 
7114      For a non-type template-parameter of type reference to function, no
7115      conversions apply. If the template-argument represents a set of
7116      overloaded functions, the matching function is selected from the set
7117      (_over.over_).  */
7118   else if (TYPE_REFFN_P (type))
7119     {
7120       if (TREE_CODE (expr) == ADDR_EXPR)
7121 	{
7122 	  if (complain & tf_error)
7123 	    {
7124 	      error ("%qE is not a valid template argument for type %qT "
7125 		     "because it is a pointer", expr, type);
7126 	      inform (input_location, "try using %qE instead",
7127 		      TREE_OPERAND (expr, 0));
7128 	    }
7129 	  return NULL_TREE;
7130 	}
7131 
7132       expr = convert_nontype_argument_function (type, expr, complain);
7133       if (!expr || expr == error_mark_node)
7134 	return expr;
7135     }
7136   /* [temp.arg.nontype]/5, bullet 6
7137 
7138      For a non-type template-parameter of type pointer to member function,
7139      no conversions apply. If the template-argument represents a set of
7140      overloaded member functions, the matching member function is selected
7141      from the set (_over.over_).  */
7142   else if (TYPE_PTRMEMFUNC_P (type))
7143     {
7144       expr = instantiate_type (type, expr, tf_none);
7145       if (expr == error_mark_node)
7146 	return error_mark_node;
7147 
7148       /* [temp.arg.nontype] bullet 1 says the pointer to member
7149          expression must be a pointer-to-member constant.  */
7150       if (!value_dependent_expression_p (expr)
7151 	  && !check_valid_ptrmem_cst_expr (type, expr, complain))
7152 	return NULL_TREE;
7153 
7154       /* Repeated conversion can't deal with a conversion that turns PTRMEM_CST
7155 	 into a CONSTRUCTOR, so build up a new PTRMEM_CST instead.  */
7156       if (fnptr_conv_p (type, TREE_TYPE (expr)))
7157 	expr = make_ptrmem_cst (type, PTRMEM_CST_MEMBER (expr));
7158     }
7159   /* [temp.arg.nontype]/5, bullet 7
7160 
7161      For a non-type template-parameter of type pointer to data member,
7162      qualification conversions (_conv.qual_) are applied.  */
7163   else if (TYPE_PTRDATAMEM_P (type))
7164     {
7165       /* [temp.arg.nontype] bullet 1 says the pointer to member
7166          expression must be a pointer-to-member constant.  */
7167       if (!value_dependent_expression_p (expr)
7168 	  && !check_valid_ptrmem_cst_expr (type, expr, complain))
7169 	return NULL_TREE;
7170 
7171       expr = perform_qualification_conversions (type, expr);
7172       if (expr == error_mark_node)
7173 	return expr;
7174     }
7175   else if (NULLPTR_TYPE_P (type))
7176     {
7177       if (!NULLPTR_TYPE_P (TREE_TYPE (expr)))
7178 	{
7179 	  if (complain & tf_error)
7180 	    error ("%qE is not a valid template argument for type %qT "
7181 		   "because it is of type %qT", expr, type, TREE_TYPE (expr));
7182 	  return NULL_TREE;
7183 	}
7184       return expr;
7185     }
7186   /* A template non-type parameter must be one of the above.  */
7187   else
7188     gcc_unreachable ();
7189 
7190   /* Sanity check: did we actually convert the argument to the
7191      right type?  */
7192   gcc_assert (same_type_ignoring_top_level_qualifiers_p
7193 	      (type, TREE_TYPE (expr)));
7194   return convert_from_reference (expr);
7195 }
7196 
7197 /* Subroutine of coerce_template_template_parms, which returns 1 if
7198    PARM_PARM and ARG_PARM match using the rule for the template
7199    parameters of template template parameters. Both PARM and ARG are
7200    template parameters; the rest of the arguments are the same as for
7201    coerce_template_template_parms.
7202  */
7203 static int
coerce_template_template_parm(tree parm,tree arg,tsubst_flags_t complain,tree in_decl,tree outer_args)7204 coerce_template_template_parm (tree parm,
7205                               tree arg,
7206                               tsubst_flags_t complain,
7207                               tree in_decl,
7208                               tree outer_args)
7209 {
7210   if (arg == NULL_TREE || error_operand_p (arg)
7211       || parm == NULL_TREE || error_operand_p (parm))
7212     return 0;
7213 
7214   if (TREE_CODE (arg) != TREE_CODE (parm))
7215     return 0;
7216 
7217   switch (TREE_CODE (parm))
7218     {
7219     case TEMPLATE_DECL:
7220       /* We encounter instantiations of templates like
7221 	 template <template <template <class> class> class TT>
7222 	 class C;  */
7223       {
7224 	tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
7225 	tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
7226 
7227 	if (!coerce_template_template_parms
7228 	    (parmparm, argparm, complain, in_decl, outer_args))
7229 	  return 0;
7230       }
7231       /* Fall through.  */
7232 
7233     case TYPE_DECL:
7234       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
7235 	  && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7236 	/* Argument is a parameter pack but parameter is not.  */
7237 	return 0;
7238       break;
7239 
7240     case PARM_DECL:
7241       /* The tsubst call is used to handle cases such as
7242 
7243            template <int> class C {};
7244 	   template <class T, template <T> class TT> class D {};
7245 	   D<int, C> d;
7246 
7247 	 i.e. the parameter list of TT depends on earlier parameters.  */
7248       if (!uses_template_parms (TREE_TYPE (arg)))
7249 	{
7250 	  tree t = tsubst (TREE_TYPE (parm), outer_args, complain, in_decl);
7251 	  if (!uses_template_parms (t)
7252 	      && !same_type_p (t, TREE_TYPE (arg)))
7253 	    return 0;
7254 	}
7255 
7256       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
7257 	  && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7258 	/* Argument is a parameter pack but parameter is not.  */
7259 	return 0;
7260 
7261       break;
7262 
7263     default:
7264       gcc_unreachable ();
7265     }
7266 
7267   return 1;
7268 }
7269 
7270 /* Coerce template argument list ARGLIST for use with template
7271    template-parameter TEMPL.  */
7272 
7273 static tree
coerce_template_args_for_ttp(tree templ,tree arglist,tsubst_flags_t complain)7274 coerce_template_args_for_ttp (tree templ, tree arglist,
7275 			      tsubst_flags_t complain)
7276 {
7277   /* Consider an example where a template template parameter declared as
7278 
7279      template <class T, class U = std::allocator<T> > class TT
7280 
7281      The template parameter level of T and U are one level larger than
7282      of TT.  To proper process the default argument of U, say when an
7283      instantiation `TT<int>' is seen, we need to build the full
7284      arguments containing {int} as the innermost level.  Outer levels,
7285      available when not appearing as default template argument, can be
7286      obtained from the arguments of the enclosing template.
7287 
7288      Suppose that TT is later substituted with std::vector.  The above
7289      instantiation is `TT<int, std::allocator<T> >' with TT at
7290      level 1, and T at level 2, while the template arguments at level 1
7291      becomes {std::vector} and the inner level 2 is {int}.  */
7292 
7293   tree outer = DECL_CONTEXT (templ);
7294   if (outer)
7295     {
7296       if (DECL_TEMPLATE_SPECIALIZATION (outer))
7297 	/* We want arguments for the partial specialization, not arguments for
7298 	   the primary template.  */
7299 	outer = template_parms_to_args (DECL_TEMPLATE_PARMS (outer));
7300       else
7301 	outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
7302     }
7303   else if (current_template_parms)
7304     {
7305       /* This is an argument of the current template, so we haven't set
7306 	 DECL_CONTEXT yet.  */
7307       tree relevant_template_parms;
7308 
7309       /* Parameter levels that are greater than the level of the given
7310 	 template template parm are irrelevant.  */
7311       relevant_template_parms = current_template_parms;
7312       while (TMPL_PARMS_DEPTH (relevant_template_parms)
7313 	     != TEMPLATE_TYPE_LEVEL (TREE_TYPE (templ)))
7314 	relevant_template_parms = TREE_CHAIN (relevant_template_parms);
7315 
7316       outer = template_parms_to_args (relevant_template_parms);
7317     }
7318 
7319   if (outer)
7320     arglist = add_to_template_args (outer, arglist);
7321 
7322   tree parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7323   return coerce_template_parms (parmlist, arglist, templ,
7324 				complain,
7325 				/*require_all_args=*/true,
7326 				/*use_default_args=*/true);
7327 }
7328 
7329 /* A cache of template template parameters with match-all default
7330    arguments.  */
7331 static GTY((deletable)) hash_map<tree,tree> *defaulted_ttp_cache;
7332 static void
store_defaulted_ttp(tree v,tree t)7333 store_defaulted_ttp (tree v, tree t)
7334 {
7335   if (!defaulted_ttp_cache)
7336     defaulted_ttp_cache = hash_map<tree,tree>::create_ggc (13);
7337   defaulted_ttp_cache->put (v, t);
7338 }
7339 static tree
lookup_defaulted_ttp(tree v)7340 lookup_defaulted_ttp (tree v)
7341 {
7342   if (defaulted_ttp_cache)
7343     if (tree *p = defaulted_ttp_cache->get (v))
7344       return *p;
7345   return NULL_TREE;
7346 }
7347 
7348 /* T is a bound template template-parameter.  Copy its arguments into default
7349    arguments of the template template-parameter's template parameters.  */
7350 
7351 static tree
add_defaults_to_ttp(tree otmpl)7352 add_defaults_to_ttp (tree otmpl)
7353 {
7354   if (tree c = lookup_defaulted_ttp (otmpl))
7355     return c;
7356 
7357   tree ntmpl = copy_node (otmpl);
7358 
7359   tree ntype = copy_node (TREE_TYPE (otmpl));
7360   TYPE_STUB_DECL (ntype) = TYPE_NAME (ntype) = ntmpl;
7361   TYPE_MAIN_VARIANT (ntype) = ntype;
7362   TYPE_POINTER_TO (ntype) = TYPE_REFERENCE_TO (ntype) = NULL_TREE;
7363   TYPE_NAME (ntype) = ntmpl;
7364   SET_TYPE_STRUCTURAL_EQUALITY (ntype);
7365 
7366   tree idx = TEMPLATE_TYPE_PARM_INDEX (ntype)
7367     = copy_node (TEMPLATE_TYPE_PARM_INDEX (ntype));
7368   TEMPLATE_PARM_DECL (idx) = ntmpl;
7369   TREE_TYPE (ntmpl) = TREE_TYPE (idx) = ntype;
7370 
7371   tree oparms = DECL_TEMPLATE_PARMS (otmpl);
7372   tree parms = DECL_TEMPLATE_PARMS (ntmpl) = copy_node (oparms);
7373   TREE_CHAIN (parms) = TREE_CHAIN (oparms);
7374   tree vec = TREE_VALUE (parms) = copy_node (TREE_VALUE (parms));
7375   for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
7376     {
7377       tree o = TREE_VEC_ELT (vec, i);
7378       if (!template_parameter_pack_p (TREE_VALUE (o)))
7379 	{
7380 	  tree n = TREE_VEC_ELT (vec, i) = copy_node (o);
7381 	  TREE_PURPOSE (n) = any_targ_node;
7382 	}
7383     }
7384 
7385   store_defaulted_ttp (otmpl, ntmpl);
7386   return ntmpl;
7387 }
7388 
7389 /* ARG is a bound potential template template-argument, and PARGS is a list
7390    of arguments for the corresponding template template-parameter.  Adjust
7391    PARGS as appropriate for application to ARG's template, and if ARG is a
7392    BOUND_TEMPLATE_TEMPLATE_PARM, possibly adjust it to add default template
7393    arguments to the template template parameter.  */
7394 
7395 static tree
coerce_ttp_args_for_tta(tree & arg,tree pargs,tsubst_flags_t complain)7396 coerce_ttp_args_for_tta (tree& arg, tree pargs, tsubst_flags_t complain)
7397 {
7398   ++processing_template_decl;
7399   tree arg_tmpl = TYPE_TI_TEMPLATE (arg);
7400   if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
7401     {
7402       /* When comparing two template template-parameters in partial ordering,
7403 	 rewrite the one currently being used as an argument to have default
7404 	 arguments for all parameters.  */
7405       arg_tmpl = add_defaults_to_ttp (arg_tmpl);
7406       pargs = coerce_template_args_for_ttp (arg_tmpl, pargs, complain);
7407       if (pargs != error_mark_node)
7408 	arg = bind_template_template_parm (TREE_TYPE (arg_tmpl),
7409 					   TYPE_TI_ARGS (arg));
7410     }
7411   else
7412     {
7413       tree aparms
7414 	= INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (arg_tmpl));
7415       pargs = coerce_template_parms (aparms, pargs, arg_tmpl, complain,
7416 				       /*require_all*/true,
7417 				       /*use_default*/true);
7418     }
7419   --processing_template_decl;
7420   return pargs;
7421 }
7422 
7423 /* Subroutine of unify for the case when PARM is a
7424    BOUND_TEMPLATE_TEMPLATE_PARM.  */
7425 
7426 static int
unify_bound_ttp_args(tree tparms,tree targs,tree parm,tree & arg,bool explain_p)7427 unify_bound_ttp_args (tree tparms, tree targs, tree parm, tree& arg,
7428 		      bool explain_p)
7429 {
7430   tree parmvec = TYPE_TI_ARGS (parm);
7431   tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
7432 
7433   /* The template template parm might be variadic and the argument
7434      not, so flatten both argument lists.  */
7435   parmvec = expand_template_argument_pack (parmvec);
7436   argvec = expand_template_argument_pack (argvec);
7437 
7438   if (flag_new_ttp)
7439     {
7440       /* In keeping with P0522R0, adjust P's template arguments
7441 	 to apply to A's template; then flatten it again.  */
7442       tree nparmvec = parmvec;
7443       nparmvec = coerce_ttp_args_for_tta (arg, parmvec, tf_none);
7444       nparmvec = expand_template_argument_pack (nparmvec);
7445 
7446       if (unify (tparms, targs, nparmvec, argvec,
7447 		 UNIFY_ALLOW_NONE, explain_p))
7448 	return 1;
7449 
7450       /* If the P0522 adjustment eliminated a pack expansion, deduce
7451 	 empty packs.  */
7452       if (flag_new_ttp
7453 	  && TREE_VEC_LENGTH (nparmvec) < TREE_VEC_LENGTH (parmvec)
7454 	  && unify_pack_expansion (tparms, targs, parmvec, argvec,
7455 				   DEDUCE_EXACT, /*sub*/true, explain_p))
7456 	return 1;
7457     }
7458   else
7459     {
7460       /* Deduce arguments T, i from TT<T> or TT<i>.
7461 	 We check each element of PARMVEC and ARGVEC individually
7462 	 rather than the whole TREE_VEC since they can have
7463 	 different number of elements, which is allowed under N2555.  */
7464 
7465       int len = TREE_VEC_LENGTH (parmvec);
7466 
7467       /* Check if the parameters end in a pack, making them
7468 	 variadic.  */
7469       int parm_variadic_p = 0;
7470       if (len > 0
7471 	  && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
7472 	parm_variadic_p = 1;
7473 
7474       for (int i = 0; i < len - parm_variadic_p; ++i)
7475 	/* If the template argument list of P contains a pack
7476 	   expansion that is not the last template argument, the
7477 	   entire template argument list is a non-deduced
7478 	   context.  */
7479 	if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
7480 	  return unify_success (explain_p);
7481 
7482       if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
7483 	return unify_too_few_arguments (explain_p,
7484 					TREE_VEC_LENGTH (argvec), len);
7485 
7486       for (int i = 0; i < len - parm_variadic_p; ++i)
7487 	if (unify (tparms, targs,
7488 		   TREE_VEC_ELT (parmvec, i),
7489 		   TREE_VEC_ELT (argvec, i),
7490 		   UNIFY_ALLOW_NONE, explain_p))
7491 	  return 1;
7492 
7493       if (parm_variadic_p
7494 	  && unify_pack_expansion (tparms, targs,
7495 				   parmvec, argvec,
7496 				   DEDUCE_EXACT,
7497 				   /*subr=*/true, explain_p))
7498 	return 1;
7499     }
7500 
7501   return 0;
7502 }
7503 
7504 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
7505    template template parameters.  Both PARM_PARMS and ARG_PARMS are
7506    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
7507    or PARM_DECL.
7508 
7509    Consider the example:
7510      template <class T> class A;
7511      template<template <class U> class TT> class B;
7512 
7513    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
7514    the parameters to A, and OUTER_ARGS contains A.  */
7515 
7516 static int
coerce_template_template_parms(tree parm_parms,tree arg_parms,tsubst_flags_t complain,tree in_decl,tree outer_args)7517 coerce_template_template_parms (tree parm_parms,
7518 				tree arg_parms,
7519 				tsubst_flags_t complain,
7520 				tree in_decl,
7521 				tree outer_args)
7522 {
7523   int nparms, nargs, i;
7524   tree parm, arg;
7525   int variadic_p = 0;
7526 
7527   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
7528   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
7529 
7530   nparms = TREE_VEC_LENGTH (parm_parms);
7531   nargs = TREE_VEC_LENGTH (arg_parms);
7532 
7533   if (flag_new_ttp)
7534     {
7535       /* P0522R0: A template template-parameter P is at least as specialized as
7536 	 a template template-argument A if, given the following rewrite to two
7537 	 function templates, the function template corresponding to P is at
7538 	 least as specialized as the function template corresponding to A
7539 	 according to the partial ordering rules for function templates
7540 	 ([temp.func.order]). Given an invented class template X with the
7541 	 template parameter list of A (including default arguments):
7542 
7543 	 * Each of the two function templates has the same template parameters,
7544 	 respectively, as P or A.
7545 
7546 	 * Each function template has a single function parameter whose type is
7547 	 a specialization of X with template arguments corresponding to the
7548 	 template parameters from the respective function template where, for
7549 	 each template parameter PP in the template parameter list of the
7550 	 function template, a corresponding template argument AA is formed. If
7551 	 PP declares a parameter pack, then AA is the pack expansion
7552 	 PP... ([temp.variadic]); otherwise, AA is the id-expression PP.
7553 
7554 	 If the rewrite produces an invalid type, then P is not at least as
7555 	 specialized as A.  */
7556 
7557       /* So coerce P's args to apply to A's parms, and then deduce between A's
7558 	 args and the converted args.  If that succeeds, A is at least as
7559 	 specialized as P, so they match.*/
7560       tree pargs = template_parms_level_to_args (parm_parms);
7561       ++processing_template_decl;
7562       pargs = coerce_template_parms (arg_parms, pargs, NULL_TREE, tf_none,
7563 				     /*require_all*/true, /*use_default*/true);
7564       --processing_template_decl;
7565       if (pargs != error_mark_node)
7566 	{
7567 	  tree targs = make_tree_vec (nargs);
7568 	  tree aargs = template_parms_level_to_args (arg_parms);
7569 	  if (!unify (arg_parms, targs, aargs, pargs, UNIFY_ALLOW_NONE,
7570 		      /*explain*/false))
7571 	    return 1;
7572 	}
7573     }
7574 
7575   /* Determine whether we have a parameter pack at the end of the
7576      template template parameter's template parameter list.  */
7577   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
7578     {
7579       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
7580 
7581       if (error_operand_p (parm))
7582 	return 0;
7583 
7584       switch (TREE_CODE (parm))
7585         {
7586         case TEMPLATE_DECL:
7587         case TYPE_DECL:
7588           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7589             variadic_p = 1;
7590           break;
7591 
7592         case PARM_DECL:
7593           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7594             variadic_p = 1;
7595           break;
7596 
7597         default:
7598           gcc_unreachable ();
7599         }
7600     }
7601 
7602   if (nargs != nparms
7603       && !(variadic_p && nargs >= nparms - 1))
7604     return 0;
7605 
7606   /* Check all of the template parameters except the parameter pack at
7607      the end (if any).  */
7608   for (i = 0; i < nparms - variadic_p; ++i)
7609     {
7610       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
7611           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
7612         continue;
7613 
7614       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
7615       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
7616 
7617       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
7618                                           outer_args))
7619 	return 0;
7620 
7621     }
7622 
7623   if (variadic_p)
7624     {
7625       /* Check each of the template parameters in the template
7626 	 argument against the template parameter pack at the end of
7627 	 the template template parameter.  */
7628       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
7629 	return 0;
7630 
7631       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
7632 
7633       for (; i < nargs; ++i)
7634         {
7635           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
7636             continue;
7637 
7638           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
7639 
7640           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
7641                                               outer_args))
7642             return 0;
7643         }
7644     }
7645 
7646   return 1;
7647 }
7648 
7649 /* Verifies that the deduced template arguments (in TARGS) for the
7650    template template parameters (in TPARMS) represent valid bindings,
7651    by comparing the template parameter list of each template argument
7652    to the template parameter list of its corresponding template
7653    template parameter, in accordance with DR150. This
7654    routine can only be called after all template arguments have been
7655    deduced. It will return TRUE if all of the template template
7656    parameter bindings are okay, FALSE otherwise.  */
7657 bool
template_template_parm_bindings_ok_p(tree tparms,tree targs)7658 template_template_parm_bindings_ok_p (tree tparms, tree targs)
7659 {
7660   int i, ntparms = TREE_VEC_LENGTH (tparms);
7661   bool ret = true;
7662 
7663   /* We're dealing with template parms in this process.  */
7664   ++processing_template_decl;
7665 
7666   targs = INNERMOST_TEMPLATE_ARGS (targs);
7667 
7668   for (i = 0; i < ntparms; ++i)
7669     {
7670       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
7671       tree targ = TREE_VEC_ELT (targs, i);
7672 
7673       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
7674 	{
7675 	  tree packed_args = NULL_TREE;
7676 	  int idx, len = 1;
7677 
7678 	  if (ARGUMENT_PACK_P (targ))
7679 	    {
7680 	      /* Look inside the argument pack.  */
7681 	      packed_args = ARGUMENT_PACK_ARGS (targ);
7682 	      len = TREE_VEC_LENGTH (packed_args);
7683 	    }
7684 
7685 	  for (idx = 0; idx < len; ++idx)
7686 	    {
7687 	      tree targ_parms = NULL_TREE;
7688 
7689 	      if (packed_args)
7690 		/* Extract the next argument from the argument
7691 		   pack.  */
7692 		targ = TREE_VEC_ELT (packed_args, idx);
7693 
7694 	      if (PACK_EXPANSION_P (targ))
7695 		/* Look at the pattern of the pack expansion.  */
7696 		targ = PACK_EXPANSION_PATTERN (targ);
7697 
7698 	      /* Extract the template parameters from the template
7699 		 argument.  */
7700 	      if (TREE_CODE (targ) == TEMPLATE_DECL)
7701 		targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
7702 	      else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
7703 		targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
7704 
7705 	      /* Verify that we can coerce the template template
7706 		 parameters from the template argument to the template
7707 		 parameter.  This requires an exact match.  */
7708 	      if (targ_parms
7709 		  && !coerce_template_template_parms
7710 		       (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
7711 			targ_parms,
7712 			tf_none,
7713 			tparm,
7714 			targs))
7715 		{
7716 		  ret = false;
7717 		  goto out;
7718 		}
7719 	    }
7720 	}
7721     }
7722 
7723  out:
7724 
7725   --processing_template_decl;
7726   return ret;
7727 }
7728 
7729 /* Since type attributes aren't mangled, we need to strip them from
7730    template type arguments.  */
7731 
7732 static tree
canonicalize_type_argument(tree arg,tsubst_flags_t complain)7733 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
7734 {
7735   if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
7736     return arg;
7737   bool removed_attributes = false;
7738   tree canon = strip_typedefs (arg, &removed_attributes);
7739   if (removed_attributes
7740       && (complain & tf_warning))
7741     warning (OPT_Wignored_attributes,
7742 	     "ignoring attributes on template argument %qT", arg);
7743   return canon;
7744 }
7745 
7746 /* And from inside dependent non-type arguments like sizeof(Type).  */
7747 
7748 static tree
canonicalize_expr_argument(tree arg,tsubst_flags_t complain)7749 canonicalize_expr_argument (tree arg, tsubst_flags_t complain)
7750 {
7751   if (!arg || arg == error_mark_node)
7752     return arg;
7753   bool removed_attributes = false;
7754   tree canon = strip_typedefs_expr (arg, &removed_attributes);
7755   if (removed_attributes
7756       && (complain & tf_warning))
7757     warning (OPT_Wignored_attributes,
7758 	     "ignoring attributes in template argument %qE", arg);
7759   return canon;
7760 }
7761 
7762 // A template declaration can be substituted for a constrained
7763 // template template parameter only when the argument is more
7764 // constrained than the parameter.
7765 static bool
is_compatible_template_arg(tree parm,tree arg)7766 is_compatible_template_arg (tree parm, tree arg)
7767 {
7768   tree parm_cons = get_constraints (parm);
7769 
7770   /* For now, allow constrained template template arguments
7771      and unconstrained template template parameters.  */
7772   if (parm_cons == NULL_TREE)
7773     return true;
7774 
7775   tree arg_cons = get_constraints (arg);
7776 
7777   // If the template parameter is constrained, we need to rewrite its
7778   // constraints in terms of the ARG's template parameters. This ensures
7779   // that all of the template parameter types will have the same depth.
7780   //
7781   // Note that this is only valid when coerce_template_template_parm is
7782   // true for the innermost template parameters of PARM and ARG. In other
7783   // words, because coercion is successful, this conversion will be valid.
7784   if (parm_cons)
7785     {
7786       tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (arg));
7787       parm_cons = tsubst_constraint_info (parm_cons,
7788 					  INNERMOST_TEMPLATE_ARGS (args),
7789 					  tf_none, NULL_TREE);
7790       if (parm_cons == error_mark_node)
7791         return false;
7792     }
7793 
7794   return subsumes (parm_cons, arg_cons);
7795 }
7796 
7797 // Convert a placeholder argument into a binding to the original
7798 // parameter. The original parameter is saved as the TREE_TYPE of
7799 // ARG.
7800 static inline tree
convert_wildcard_argument(tree parm,tree arg)7801 convert_wildcard_argument (tree parm, tree arg)
7802 {
7803   TREE_TYPE (arg) = parm;
7804   return arg;
7805 }
7806 
7807 /* We can't fully resolve ARG given as a non-type template argument to TYPE,
7808    because one of them is dependent.  But we need to represent the
7809    conversion for the benefit of cp_tree_equal.  */
7810 
7811 static tree
maybe_convert_nontype_argument(tree type,tree arg)7812 maybe_convert_nontype_argument (tree type, tree arg)
7813 {
7814   /* Auto parms get no conversion.  */
7815   if (type_uses_auto (type))
7816     return arg;
7817   /* We don't need or want to add this conversion now if we're going to use the
7818      argument for deduction.  */
7819   if (value_dependent_expression_p (arg))
7820     return arg;
7821 
7822   type = cv_unqualified (type);
7823   tree argtype = TREE_TYPE (arg);
7824   if (same_type_p (type, argtype))
7825     return arg;
7826 
7827   arg = build1 (IMPLICIT_CONV_EXPR, type, arg);
7828   IMPLICIT_CONV_EXPR_NONTYPE_ARG (arg) = true;
7829   return arg;
7830 }
7831 
7832 /* Convert the indicated template ARG as necessary to match the
7833    indicated template PARM.  Returns the converted ARG, or
7834    error_mark_node if the conversion was unsuccessful.  Error and
7835    warning messages are issued under control of COMPLAIN.  This
7836    conversion is for the Ith parameter in the parameter list.  ARGS is
7837    the full set of template arguments deduced so far.  */
7838 
7839 static tree
convert_template_argument(tree parm,tree arg,tree args,tsubst_flags_t complain,int i,tree in_decl)7840 convert_template_argument (tree parm,
7841 			   tree arg,
7842 			   tree args,
7843 			   tsubst_flags_t complain,
7844 			   int i,
7845 			   tree in_decl)
7846 {
7847   tree orig_arg;
7848   tree val;
7849   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
7850 
7851   if (parm == error_mark_node)
7852     return error_mark_node;
7853 
7854   /* Trivially convert placeholders. */
7855   if (TREE_CODE (arg) == WILDCARD_DECL)
7856     return convert_wildcard_argument (parm, arg);
7857 
7858   if (arg == any_targ_node)
7859     return arg;
7860 
7861   if (TREE_CODE (arg) == TREE_LIST
7862       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
7863     {
7864       /* The template argument was the name of some
7865 	 member function.  That's usually
7866 	 invalid, but static members are OK.  In any
7867 	 case, grab the underlying fields/functions
7868 	 and issue an error later if required.  */
7869       orig_arg = TREE_VALUE (arg);
7870       TREE_TYPE (arg) = unknown_type_node;
7871     }
7872 
7873   orig_arg = arg;
7874 
7875   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
7876   requires_type = (TREE_CODE (parm) == TYPE_DECL
7877 		   || requires_tmpl_type);
7878 
7879   /* When determining whether an argument pack expansion is a template,
7880      look at the pattern.  */
7881   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
7882     arg = PACK_EXPANSION_PATTERN (arg);
7883 
7884   /* Deal with an injected-class-name used as a template template arg.  */
7885   if (requires_tmpl_type && CLASS_TYPE_P (arg))
7886     {
7887       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
7888       if (TREE_CODE (t) == TEMPLATE_DECL)
7889 	{
7890 	  if (cxx_dialect >= cxx11)
7891 	    /* OK under DR 1004.  */;
7892 	  else if (complain & tf_warning_or_error)
7893 	    pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
7894 		     " used as template template argument", TYPE_NAME (arg));
7895 	  else if (flag_pedantic_errors)
7896 	    t = arg;
7897 
7898 	  arg = t;
7899 	}
7900     }
7901 
7902   is_tmpl_type =
7903     ((TREE_CODE (arg) == TEMPLATE_DECL
7904       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
7905      || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
7906      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
7907      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
7908 
7909   if (is_tmpl_type
7910       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
7911 	  || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
7912     arg = TYPE_STUB_DECL (arg);
7913 
7914   is_type = TYPE_P (arg) || is_tmpl_type;
7915 
7916   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
7917       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
7918     {
7919       if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
7920 	{
7921 	  if (complain & tf_error)
7922 	    error ("invalid use of destructor %qE as a type", orig_arg);
7923 	  return error_mark_node;
7924 	}
7925 
7926       permerror (input_location,
7927 		 "to refer to a type member of a template parameter, "
7928 		 "use %<typename %E%>", orig_arg);
7929 
7930       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
7931 				     TREE_OPERAND (arg, 1),
7932 				     typename_type,
7933 				     complain);
7934       arg = orig_arg;
7935       is_type = 1;
7936     }
7937   if (is_type != requires_type)
7938     {
7939       if (in_decl)
7940 	{
7941 	  if (complain & tf_error)
7942 	    {
7943 	      error ("type/value mismatch at argument %d in template "
7944 		     "parameter list for %qD",
7945 		     i + 1, in_decl);
7946 	      if (is_type)
7947 		inform (input_location,
7948 			"  expected a constant of type %qT, got %qT",
7949 			TREE_TYPE (parm),
7950 			(DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
7951 	      else if (requires_tmpl_type)
7952 		inform (input_location,
7953 			"  expected a class template, got %qE", orig_arg);
7954 	      else
7955 		inform (input_location,
7956 			"  expected a type, got %qE", orig_arg);
7957 	    }
7958 	}
7959       return error_mark_node;
7960     }
7961   if (is_tmpl_type ^ requires_tmpl_type)
7962     {
7963       if (in_decl && (complain & tf_error))
7964 	{
7965 	  error ("type/value mismatch at argument %d in template "
7966 		 "parameter list for %qD",
7967 		 i + 1, in_decl);
7968 	  if (is_tmpl_type)
7969 	    inform (input_location,
7970 		    "  expected a type, got %qT", DECL_NAME (arg));
7971 	  else
7972 	    inform (input_location,
7973 		    "  expected a class template, got %qT", orig_arg);
7974 	}
7975       return error_mark_node;
7976     }
7977 
7978   if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
7979     /* We already did the appropriate conversion when packing args.  */
7980     val = orig_arg;
7981   else if (is_type)
7982     {
7983       if (requires_tmpl_type)
7984 	{
7985 	  if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
7986 	    /* The number of argument required is not known yet.
7987 	       Just accept it for now.  */
7988 	    val = orig_arg;
7989 	  else
7990 	    {
7991 	      tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
7992 	      tree argparm;
7993 
7994 	      /* Strip alias templates that are equivalent to another
7995 		 template.  */
7996 	      arg = get_underlying_template (arg);
7997               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
7998 
7999 	      if (coerce_template_template_parms (parmparm, argparm,
8000 						  complain, in_decl,
8001 						  args))
8002 		{
8003 		  val = arg;
8004 
8005 		  /* TEMPLATE_TEMPLATE_PARM node is preferred over
8006 		     TEMPLATE_DECL.  */
8007 		  if (val != error_mark_node)
8008                     {
8009                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
8010                         val = TREE_TYPE (val);
8011 		      if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
8012 			val = make_pack_expansion (val, complain);
8013                     }
8014 		}
8015 	      else
8016 		{
8017 		  if (in_decl && (complain & tf_error))
8018 		    {
8019 		      error ("type/value mismatch at argument %d in "
8020 			     "template parameter list for %qD",
8021 			     i + 1, in_decl);
8022 		      inform (input_location,
8023 			      "  expected a template of type %qD, got %qT",
8024 			      parm, orig_arg);
8025 		    }
8026 
8027 		  val = error_mark_node;
8028 		}
8029 
8030               // Check that the constraints are compatible before allowing the
8031               // substitution.
8032               if (val != error_mark_node)
8033                 if (!is_compatible_template_arg (parm, arg))
8034                   {
8035 		    if (in_decl && (complain & tf_error))
8036                       {
8037                         error ("constraint mismatch at argument %d in "
8038                                "template parameter list for %qD",
8039                                i + 1, in_decl);
8040                         inform (input_location, "  expected %qD but got %qD",
8041                                 parm, arg);
8042                       }
8043 		    val = error_mark_node;
8044                   }
8045 	    }
8046 	}
8047       else
8048 	val = orig_arg;
8049       /* We only form one instance of each template specialization.
8050 	 Therefore, if we use a non-canonical variant (i.e., a
8051 	 typedef), any future messages referring to the type will use
8052 	 the typedef, which is confusing if those future uses do not
8053 	 themselves also use the typedef.  */
8054       if (TYPE_P (val))
8055 	val = canonicalize_type_argument (val, complain);
8056     }
8057   else
8058     {
8059       tree t = TREE_TYPE (parm);
8060 
8061       if (TEMPLATE_PARM_LEVEL (get_template_parm_index (parm))
8062 	  > TMPL_ARGS_DEPTH (args))
8063 	/* We don't have enough levels of args to do any substitution.  This
8064 	   can happen in the context of -fnew-ttp-matching.  */;
8065       else if (tree a = type_uses_auto (t))
8066 	{
8067 	  t = do_auto_deduction (t, arg, a, complain, adc_unify, args);
8068 	  if (t == error_mark_node)
8069 	    return error_mark_node;
8070 	}
8071       else
8072 	t = tsubst (t, args, complain, in_decl);
8073 
8074       if (invalid_nontype_parm_type_p (t, complain))
8075 	return error_mark_node;
8076 
8077       if (!type_dependent_expression_p (orig_arg)
8078 	  && !uses_template_parms (t))
8079 	/* We used to call digest_init here.  However, digest_init
8080 	   will report errors, which we don't want when complain
8081 	   is zero.  More importantly, digest_init will try too
8082 	   hard to convert things: for example, `0' should not be
8083 	   converted to pointer type at this point according to
8084 	   the standard.  Accepting this is not merely an
8085 	   extension, since deciding whether or not these
8086 	   conversions can occur is part of determining which
8087 	   function template to call, or whether a given explicit
8088 	   argument specification is valid.  */
8089 	val = convert_nontype_argument (t, orig_arg, complain);
8090       else
8091 	{
8092 	  val = canonicalize_expr_argument (orig_arg, complain);
8093 	  val = maybe_convert_nontype_argument (t, val);
8094 	}
8095 
8096 
8097       if (val == NULL_TREE)
8098 	val = error_mark_node;
8099       else if (val == error_mark_node && (complain & tf_error))
8100 	error ("could not convert template argument %qE from %qT to %qT",
8101 	       orig_arg, TREE_TYPE (orig_arg), t);
8102 
8103       if (INDIRECT_REF_P (val))
8104         {
8105           /* Reject template arguments that are references to built-in
8106              functions with no library fallbacks.  */
8107           const_tree inner = TREE_OPERAND (val, 0);
8108 	  const_tree innertype = TREE_TYPE (inner);
8109 	  if (innertype
8110 	      && TREE_CODE (innertype) == REFERENCE_TYPE
8111 	      && TREE_CODE (TREE_TYPE (innertype)) == FUNCTION_TYPE
8112 	      && TREE_OPERAND_LENGTH (inner) > 0
8113               && reject_gcc_builtin (TREE_OPERAND (inner, 0)))
8114               return error_mark_node;
8115         }
8116 
8117       if (TREE_CODE (val) == SCOPE_REF)
8118 	{
8119 	  /* Strip typedefs from the SCOPE_REF.  */
8120 	  tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
8121 	  tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
8122 						   complain);
8123 	  val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
8124 				      QUALIFIED_NAME_IS_TEMPLATE (val));
8125 	}
8126     }
8127 
8128   return val;
8129 }
8130 
8131 /* Coerces the remaining template arguments in INNER_ARGS (from
8132    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
8133    Returns the coerced argument pack. PARM_IDX is the position of this
8134    parameter in the template parameter list. ARGS is the original
8135    template argument list.  */
8136 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)8137 coerce_template_parameter_pack (tree parms,
8138                                 int parm_idx,
8139                                 tree args,
8140                                 tree inner_args,
8141                                 int arg_idx,
8142                                 tree new_args,
8143                                 int* lost,
8144                                 tree in_decl,
8145                                 tsubst_flags_t complain)
8146 {
8147   tree parm = TREE_VEC_ELT (parms, parm_idx);
8148   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8149   tree packed_args;
8150   tree argument_pack;
8151   tree packed_parms = NULL_TREE;
8152 
8153   if (arg_idx > nargs)
8154     arg_idx = nargs;
8155 
8156   if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
8157     {
8158       /* When the template parameter is a non-type template parameter pack
8159          or template template parameter pack whose type or template
8160          parameters use parameter packs, we know exactly how many arguments
8161          we are looking for.  Build a vector of the instantiated decls for
8162          these template parameters in PACKED_PARMS.  */
8163       /* We can't use make_pack_expansion here because it would interpret a
8164 	 _DECL as a use rather than a declaration.  */
8165       tree decl = TREE_VALUE (parm);
8166       tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
8167       SET_PACK_EXPANSION_PATTERN (exp, decl);
8168       PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
8169       SET_TYPE_STRUCTURAL_EQUALITY (exp);
8170 
8171       TREE_VEC_LENGTH (args)--;
8172       packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
8173       TREE_VEC_LENGTH (args)++;
8174 
8175       if (packed_parms == error_mark_node)
8176         return error_mark_node;
8177 
8178       /* If we're doing a partial instantiation of a member template,
8179          verify that all of the types used for the non-type
8180          template parameter pack are, in fact, valid for non-type
8181          template parameters.  */
8182       if (arg_idx < nargs
8183           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
8184         {
8185           int j, len = TREE_VEC_LENGTH (packed_parms);
8186           for (j = 0; j < len; ++j)
8187             {
8188               tree t = TREE_TYPE (TREE_VEC_ELT (packed_parms, j));
8189               if (invalid_nontype_parm_type_p (t, complain))
8190                 return error_mark_node;
8191             }
8192 	  /* We don't know how many args we have yet, just
8193 	     use the unconverted ones for now.  */
8194 	  return NULL_TREE;
8195         }
8196 
8197       packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
8198     }
8199   /* Check if we have a placeholder pack, which indicates we're
8200      in the context of a introduction list.  In that case we want
8201      to match this pack to the single placeholder.  */
8202   else if (arg_idx < nargs
8203            && TREE_CODE (TREE_VEC_ELT (inner_args, arg_idx)) == WILDCARD_DECL
8204            && WILDCARD_PACK_P (TREE_VEC_ELT (inner_args, arg_idx)))
8205     {
8206       nargs = arg_idx + 1;
8207       packed_args = make_tree_vec (1);
8208     }
8209   else
8210     packed_args = make_tree_vec (nargs - arg_idx);
8211 
8212   /* Convert the remaining arguments, which will be a part of the
8213      parameter pack "parm".  */
8214   int first_pack_arg = arg_idx;
8215   for (; arg_idx < nargs; ++arg_idx)
8216     {
8217       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
8218       tree actual_parm = TREE_VALUE (parm);
8219       int pack_idx = arg_idx - first_pack_arg;
8220 
8221       if (packed_parms)
8222         {
8223 	  /* Once we've packed as many args as we have types, stop.  */
8224 	  if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
8225 	    break;
8226 	  else if (PACK_EXPANSION_P (arg))
8227 	    /* We don't know how many args we have yet, just
8228 	       use the unconverted ones for now.  */
8229 	    return NULL_TREE;
8230 	  else
8231 	    actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
8232         }
8233 
8234       if (arg == error_mark_node)
8235 	{
8236 	  if (complain & tf_error)
8237 	    error ("template argument %d is invalid", arg_idx + 1);
8238 	}
8239       else
8240 	arg = convert_template_argument (actual_parm,
8241 					 arg, new_args, complain, parm_idx,
8242 					 in_decl);
8243       if (arg == error_mark_node)
8244         (*lost)++;
8245       TREE_VEC_ELT (packed_args, pack_idx) = arg;
8246     }
8247 
8248   if (arg_idx - first_pack_arg < TREE_VEC_LENGTH (packed_args)
8249       && TREE_VEC_LENGTH (packed_args) > 0)
8250     {
8251       if (complain & tf_error)
8252 	error ("wrong number of template arguments (%d, should be %d)",
8253 	       arg_idx - first_pack_arg, TREE_VEC_LENGTH (packed_args));
8254       return error_mark_node;
8255     }
8256 
8257   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
8258       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
8259     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
8260   else
8261     {
8262       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
8263       TREE_CONSTANT (argument_pack) = 1;
8264     }
8265 
8266   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
8267   if (CHECKING_P)
8268     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
8269 					 TREE_VEC_LENGTH (packed_args));
8270   return argument_pack;
8271 }
8272 
8273 /* Returns the number of pack expansions in the template argument vector
8274    ARGS.  */
8275 
8276 static int
pack_expansion_args_count(tree args)8277 pack_expansion_args_count (tree args)
8278 {
8279   int i;
8280   int count = 0;
8281   if (args)
8282     for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
8283       {
8284 	tree elt = TREE_VEC_ELT (args, i);
8285 	if (elt && PACK_EXPANSION_P (elt))
8286 	  ++count;
8287       }
8288   return count;
8289 }
8290 
8291 /* Convert all template arguments to their appropriate types, and
8292    return a vector containing the innermost resulting template
8293    arguments.  If any error occurs, return error_mark_node. Error and
8294    warning messages are issued under control of COMPLAIN.
8295 
8296    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
8297    for arguments not specified in ARGS.  Otherwise, if
8298    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
8299    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
8300    USE_DEFAULT_ARGS is false, then all arguments must be specified in
8301    ARGS.  */
8302 
8303 static tree
coerce_template_parms(tree parms,tree args,tree in_decl,tsubst_flags_t complain,bool require_all_args,bool use_default_args)8304 coerce_template_parms (tree parms,
8305 		       tree args,
8306 		       tree in_decl,
8307 		       tsubst_flags_t complain,
8308 		       bool require_all_args,
8309 		       bool use_default_args)
8310 {
8311   int nparms, nargs, parm_idx, arg_idx, lost = 0;
8312   tree orig_inner_args;
8313   tree inner_args;
8314   tree new_args;
8315   tree new_inner_args;
8316   int saved_unevaluated_operand;
8317   int saved_inhibit_evaluation_warnings;
8318 
8319   /* When used as a boolean value, indicates whether this is a
8320      variadic template parameter list. Since it's an int, we can also
8321      subtract it from nparms to get the number of non-variadic
8322      parameters.  */
8323   int variadic_p = 0;
8324   int variadic_args_p = 0;
8325   int post_variadic_parms = 0;
8326 
8327   /* Adjustment to nparms for fixed parameter packs.  */
8328   int fixed_pack_adjust = 0;
8329   int fixed_packs = 0;
8330   int missing = 0;
8331 
8332   /* Likewise for parameters with default arguments.  */
8333   int default_p = 0;
8334 
8335   if (args == error_mark_node)
8336     return error_mark_node;
8337 
8338   nparms = TREE_VEC_LENGTH (parms);
8339 
8340   /* Determine if there are any parameter packs or default arguments.  */
8341   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
8342     {
8343       tree parm = TREE_VEC_ELT (parms, parm_idx);
8344       if (variadic_p)
8345 	++post_variadic_parms;
8346       if (template_parameter_pack_p (TREE_VALUE (parm)))
8347 	++variadic_p;
8348       if (TREE_PURPOSE (parm))
8349 	++default_p;
8350     }
8351 
8352   inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
8353   /* If there are no parameters that follow a parameter pack, we need to
8354      expand any argument packs so that we can deduce a parameter pack from
8355      some non-packed args followed by an argument pack, as in variadic85.C.
8356      If there are such parameters, we need to leave argument packs intact
8357      so the arguments are assigned properly.  This can happen when dealing
8358      with a nested class inside a partial specialization of a class
8359      template, as in variadic92.C, or when deducing a template parameter pack
8360      from a sub-declarator, as in variadic114.C.  */
8361   if (!post_variadic_parms)
8362     inner_args = expand_template_argument_pack (inner_args);
8363 
8364   /* Count any pack expansion args.  */
8365   variadic_args_p = pack_expansion_args_count (inner_args);
8366 
8367   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8368   if ((nargs - variadic_args_p > nparms && !variadic_p)
8369       || (nargs < nparms - variadic_p
8370 	  && require_all_args
8371 	  && !variadic_args_p
8372 	  && (!use_default_args
8373 	      || (TREE_VEC_ELT (parms, nargs) != error_mark_node
8374                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
8375     {
8376     bad_nargs:
8377       if (complain & tf_error)
8378 	{
8379           if (variadic_p || default_p)
8380             {
8381               nparms -= variadic_p + default_p;
8382 	      error ("wrong number of template arguments "
8383 		     "(%d, should be at least %d)", nargs, nparms);
8384             }
8385 	  else
8386 	     error ("wrong number of template arguments "
8387 		    "(%d, should be %d)", nargs, nparms);
8388 
8389 	  if (in_decl)
8390 	    inform (DECL_SOURCE_LOCATION (in_decl),
8391 		    "provided for %qD", in_decl);
8392 	}
8393 
8394       return error_mark_node;
8395     }
8396   /* We can't pass a pack expansion to a non-pack parameter of an alias
8397      template (DR 1430).  */
8398   else if (in_decl
8399 	   && (DECL_ALIAS_TEMPLATE_P (in_decl)
8400 	       || concept_template_p (in_decl))
8401 	   && variadic_args_p
8402 	   && nargs - variadic_args_p < nparms - variadic_p)
8403     {
8404       if (complain & tf_error)
8405 	{
8406 	  for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
8407 	    {
8408 	      tree arg = TREE_VEC_ELT (inner_args, i);
8409 	      tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
8410 
8411 	      if (PACK_EXPANSION_P (arg)
8412 		  && !template_parameter_pack_p (parm))
8413 		{
8414 		  if (DECL_ALIAS_TEMPLATE_P (in_decl))
8415 		    error_at (location_of (arg),
8416 			      "pack expansion argument for non-pack parameter "
8417 			      "%qD of alias template %qD", parm, in_decl);
8418 		  else
8419 		    error_at (location_of (arg),
8420 			      "pack expansion argument for non-pack parameter "
8421 			      "%qD of concept %qD", parm, in_decl);
8422 		  inform (DECL_SOURCE_LOCATION (parm), "declared here");
8423 		  goto found;
8424 		}
8425 	    }
8426 	  gcc_unreachable ();
8427 	found:;
8428 	}
8429       return error_mark_node;
8430     }
8431 
8432   /* We need to evaluate the template arguments, even though this
8433      template-id may be nested within a "sizeof".  */
8434   saved_unevaluated_operand = cp_unevaluated_operand;
8435   cp_unevaluated_operand = 0;
8436   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
8437   c_inhibit_evaluation_warnings = 0;
8438   new_inner_args = make_tree_vec (nparms);
8439   new_args = add_outermost_template_args (args, new_inner_args);
8440   int pack_adjust = 0;
8441   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
8442     {
8443       tree arg;
8444       tree parm;
8445 
8446       /* Get the Ith template parameter.  */
8447       parm = TREE_VEC_ELT (parms, parm_idx);
8448 
8449       if (parm == error_mark_node)
8450 	{
8451 	  TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
8452 	  continue;
8453 	}
8454 
8455       /* Calculate the next argument.  */
8456       if (arg_idx < nargs)
8457 	arg = TREE_VEC_ELT (inner_args, arg_idx);
8458       else
8459 	arg = NULL_TREE;
8460 
8461       if (template_parameter_pack_p (TREE_VALUE (parm))
8462 	  && !(arg && ARGUMENT_PACK_P (arg)))
8463         {
8464 	  /* Some arguments will be placed in the
8465 	     template parameter pack PARM.  */
8466 	  arg = coerce_template_parameter_pack (parms, parm_idx, args,
8467 						inner_args, arg_idx,
8468 						new_args, &lost,
8469 						in_decl, complain);
8470 
8471 	  if (arg == NULL_TREE)
8472 	    {
8473 	      /* We don't know how many args we have yet, just use the
8474 		 unconverted (and still packed) ones for now.  */
8475 	      new_inner_args = orig_inner_args;
8476 	      arg_idx = nargs;
8477 	      break;
8478 	    }
8479 
8480           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
8481 
8482           /* Store this argument.  */
8483           if (arg == error_mark_node)
8484 	    {
8485 	      lost++;
8486 	      /* We are done with all of the arguments.  */
8487 	      arg_idx = nargs;
8488 	      break;
8489 	    }
8490 	  else
8491 	    {
8492 	      pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
8493 	      arg_idx += pack_adjust;
8494 	      if (fixed_parameter_pack_p (TREE_VALUE (parm)))
8495 		{
8496 		  ++fixed_packs;
8497 		  fixed_pack_adjust += pack_adjust;
8498 		}
8499 	    }
8500 
8501           continue;
8502         }
8503       else if (arg)
8504 	{
8505           if (PACK_EXPANSION_P (arg))
8506             {
8507 	      /* "If every valid specialization of a variadic template
8508 		 requires an empty template parameter pack, the template is
8509 		 ill-formed, no diagnostic required."  So check that the
8510 		 pattern works with this parameter.  */
8511 	      tree pattern = PACK_EXPANSION_PATTERN (arg);
8512 	      tree conv = convert_template_argument (TREE_VALUE (parm),
8513 						     pattern, new_args,
8514 						     complain, parm_idx,
8515 						     in_decl);
8516 	      if (conv == error_mark_node)
8517 		{
8518 		  if (complain & tf_error)
8519 		    inform (input_location, "so any instantiation with a "
8520 			    "non-empty parameter pack would be ill-formed");
8521 		  ++lost;
8522 		}
8523 	      else if (TYPE_P (conv) && !TYPE_P (pattern))
8524 		/* Recover from missing typename.  */
8525 		TREE_VEC_ELT (inner_args, arg_idx)
8526 		  = make_pack_expansion (conv, complain);
8527 
8528               /* We don't know how many args we have yet, just
8529                  use the unconverted ones for now.  */
8530               new_inner_args = inner_args;
8531 	      arg_idx = nargs;
8532               break;
8533             }
8534         }
8535       else if (require_all_args)
8536 	{
8537 	  /* There must be a default arg in this case.  */
8538 	  arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
8539 				     complain, in_decl);
8540 	  /* The position of the first default template argument,
8541 	     is also the number of non-defaulted arguments in NEW_INNER_ARGS.
8542 	     Record that.  */
8543 	  if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
8544 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
8545 						 arg_idx - pack_adjust);
8546 	}
8547       else
8548 	break;
8549 
8550       if (arg == error_mark_node)
8551 	{
8552 	  if (complain & tf_error)
8553 	    error ("template argument %d is invalid", arg_idx + 1);
8554 	}
8555       else if (!arg)
8556 	{
8557 	  /* This can occur if there was an error in the template
8558 	     parameter list itself (which we would already have
8559 	     reported) that we are trying to recover from, e.g., a class
8560 	     template with a parameter list such as
8561 	     template<typename..., typename> (cpp0x/variadic150.C).  */
8562 	  ++lost;
8563 
8564 	  /* This can also happen with a fixed parameter pack (71834).  */
8565 	  if (arg_idx >= nargs)
8566 	    ++missing;
8567 	}
8568       else
8569 	arg = convert_template_argument (TREE_VALUE (parm),
8570 					 arg, new_args, complain,
8571                                          parm_idx, in_decl);
8572 
8573       if (arg == error_mark_node)
8574 	lost++;
8575       TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
8576     }
8577   cp_unevaluated_operand = saved_unevaluated_operand;
8578   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
8579 
8580   if (missing || arg_idx < nargs - variadic_args_p)
8581     {
8582       /* If we had fixed parameter packs, we didn't know how many arguments we
8583 	 actually needed earlier; now we do.  */
8584       nparms += fixed_pack_adjust;
8585       variadic_p -= fixed_packs;
8586       goto bad_nargs;
8587     }
8588 
8589   if (arg_idx < nargs)
8590     {
8591       /* We had some pack expansion arguments that will only work if the packs
8592 	 are empty, but wait until instantiation time to complain.
8593 	 See variadic-ttp3.C.  */
8594       int len = nparms + (nargs - arg_idx);
8595       tree args = make_tree_vec (len);
8596       int i = 0;
8597       for (; i < nparms; ++i)
8598 	TREE_VEC_ELT (args, i) = TREE_VEC_ELT (new_inner_args, i);
8599       for (; i < len; ++i, ++arg_idx)
8600 	TREE_VEC_ELT (args, i) = TREE_VEC_ELT (inner_args,
8601 					       arg_idx - pack_adjust);
8602       new_inner_args = args;
8603     }
8604 
8605   if (lost)
8606     {
8607       gcc_assert (!(complain & tf_error) || seen_error ());
8608       return error_mark_node;
8609     }
8610 
8611   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
8612     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
8613 					 TREE_VEC_LENGTH (new_inner_args));
8614 
8615   return new_inner_args;
8616 }
8617 
8618 /* Convert all template arguments to their appropriate types, and
8619    return a vector containing the innermost resulting template
8620    arguments.  If any error occurs, return error_mark_node. Error and
8621    warning messages are not issued.
8622 
8623    Note that no function argument deduction is performed, and default
8624    arguments are used to fill in unspecified arguments. */
8625 tree
coerce_template_parms(tree parms,tree args,tree in_decl)8626 coerce_template_parms (tree parms, tree args, tree in_decl)
8627 {
8628   return coerce_template_parms (parms, args, in_decl, tf_none, true, true);
8629 }
8630 
8631 /* Convert all template arguments to their appropriate type, and
8632    instantiate default arguments as needed. This returns a vector
8633    containing the innermost resulting template arguments, or
8634    error_mark_node if unsuccessful.  */
8635 tree
coerce_template_parms(tree parms,tree args,tree in_decl,tsubst_flags_t complain)8636 coerce_template_parms (tree parms, tree args, tree in_decl,
8637                        tsubst_flags_t complain)
8638 {
8639   return coerce_template_parms (parms, args, in_decl, complain, true, true);
8640 }
8641 
8642 /* Like coerce_template_parms.  If PARMS represents all template
8643    parameters levels, this function returns a vector of vectors
8644    representing all the resulting argument levels.  Note that in this
8645    case, only the innermost arguments are coerced because the
8646    outermost ones are supposed to have been coerced already.
8647 
8648    Otherwise, if PARMS represents only (the innermost) vector of
8649    parameters, this function returns a vector containing just the
8650    innermost resulting arguments.  */
8651 
8652 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)8653 coerce_innermost_template_parms (tree parms,
8654 				  tree args,
8655 				  tree in_decl,
8656 				  tsubst_flags_t complain,
8657 				  bool require_all_args,
8658 				  bool use_default_args)
8659 {
8660   int parms_depth = TMPL_PARMS_DEPTH (parms);
8661   int args_depth = TMPL_ARGS_DEPTH (args);
8662   tree coerced_args;
8663 
8664   if (parms_depth > 1)
8665     {
8666       coerced_args = make_tree_vec (parms_depth);
8667       tree level;
8668       int cur_depth;
8669 
8670       for (level = parms, cur_depth = parms_depth;
8671 	   parms_depth > 0 && level != NULL_TREE;
8672 	   level = TREE_CHAIN (level), --cur_depth)
8673 	{
8674 	  tree l;
8675 	  if (cur_depth == args_depth)
8676 	    l = coerce_template_parms (TREE_VALUE (level),
8677 				       args, in_decl, complain,
8678 				       require_all_args,
8679 				       use_default_args);
8680 	  else
8681 	    l = TMPL_ARGS_LEVEL (args, cur_depth);
8682 
8683 	  if (l == error_mark_node)
8684 	    return error_mark_node;
8685 
8686 	  SET_TMPL_ARGS_LEVEL (coerced_args, cur_depth, l);
8687 	}
8688     }
8689   else
8690     coerced_args = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parms),
8691 					  args, in_decl, complain,
8692 					  require_all_args,
8693 					  use_default_args);
8694   return coerced_args;
8695 }
8696 
8697 /* Returns 1 if template args OT and NT are equivalent.  */
8698 
8699 int
template_args_equal(tree ot,tree nt,bool partial_order)8700 template_args_equal (tree ot, tree nt, bool partial_order /* = false */)
8701 {
8702   if (nt == ot)
8703     return 1;
8704   if (nt == NULL_TREE || ot == NULL_TREE)
8705     return false;
8706   if (nt == any_targ_node || ot == any_targ_node)
8707     return true;
8708 
8709   if (TREE_CODE (nt) == TREE_VEC)
8710     /* For member templates */
8711     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
8712   else if (PACK_EXPANSION_P (ot))
8713     return (PACK_EXPANSION_P (nt)
8714 	    && template_args_equal (PACK_EXPANSION_PATTERN (ot),
8715 				    PACK_EXPANSION_PATTERN (nt))
8716 	    && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
8717 				    PACK_EXPANSION_EXTRA_ARGS (nt)));
8718   else if (ARGUMENT_PACK_P (ot))
8719     {
8720       int i, len;
8721       tree opack, npack;
8722 
8723       if (!ARGUMENT_PACK_P (nt))
8724 	return 0;
8725 
8726       opack = ARGUMENT_PACK_ARGS (ot);
8727       npack = ARGUMENT_PACK_ARGS (nt);
8728       len = TREE_VEC_LENGTH (opack);
8729       if (TREE_VEC_LENGTH (npack) != len)
8730 	return 0;
8731       for (i = 0; i < len; ++i)
8732 	if (!template_args_equal (TREE_VEC_ELT (opack, i),
8733 				  TREE_VEC_ELT (npack, i)))
8734 	  return 0;
8735       return 1;
8736     }
8737   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
8738     gcc_unreachable ();
8739   else if (TYPE_P (nt))
8740     {
8741       if (!TYPE_P (ot))
8742 	return false;
8743       /* Don't treat an alias template specialization with dependent
8744 	 arguments as equivalent to its underlying type when used as a
8745 	 template argument; we need them to be distinct so that we
8746 	 substitute into the specialization arguments at instantiation
8747 	 time.  And aliases can't be equivalent without being ==, so
8748 	 we don't need to look any deeper.
8749 
8750          During partial ordering, however, we need to treat them normally so
8751          that we can order uses of the same alias with different
8752          cv-qualification (79960).  */
8753       if (!partial_order
8754 	  && (TYPE_ALIAS_P (nt) || TYPE_ALIAS_P (ot)))
8755 	return false;
8756       else
8757 	return same_type_p (ot, nt);
8758     }
8759   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
8760     return 0;
8761   else
8762     {
8763       /* Try to treat a template non-type argument that has been converted
8764 	 to the parameter type as equivalent to one that hasn't yet.  */
8765       for (enum tree_code code1 = TREE_CODE (ot);
8766 	   CONVERT_EXPR_CODE_P (code1)
8767 	     || code1 == NON_LVALUE_EXPR;
8768 	   code1 = TREE_CODE (ot))
8769 	ot = TREE_OPERAND (ot, 0);
8770       for (enum tree_code code2 = TREE_CODE (nt);
8771 	   CONVERT_EXPR_CODE_P (code2)
8772 	     || code2 == NON_LVALUE_EXPR;
8773 	   code2 = TREE_CODE (nt))
8774 	nt = TREE_OPERAND (nt, 0);
8775 
8776       return cp_tree_equal (ot, nt);
8777     }
8778 }
8779 
8780 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
8781    template arguments.  Returns 0 otherwise, and updates OLDARG_PTR and
8782    NEWARG_PTR with the offending arguments if they are non-NULL.  */
8783 
8784 int
comp_template_args(tree oldargs,tree newargs,tree * oldarg_ptr,tree * newarg_ptr,bool partial_order)8785 comp_template_args (tree oldargs, tree newargs,
8786 		    tree *oldarg_ptr, tree *newarg_ptr,
8787 		    bool partial_order)
8788 {
8789   int i;
8790 
8791   if (oldargs == newargs)
8792     return 1;
8793 
8794   if (!oldargs || !newargs)
8795     return 0;
8796 
8797   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
8798     return 0;
8799 
8800   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
8801     {
8802       tree nt = TREE_VEC_ELT (newargs, i);
8803       tree ot = TREE_VEC_ELT (oldargs, i);
8804 
8805       if (! template_args_equal (ot, nt, partial_order))
8806 	{
8807 	  if (oldarg_ptr != NULL)
8808 	    *oldarg_ptr = ot;
8809 	  if (newarg_ptr != NULL)
8810 	    *newarg_ptr = nt;
8811 	  return 0;
8812 	}
8813     }
8814   return 1;
8815 }
8816 
8817 inline bool
comp_template_args_porder(tree oargs,tree nargs)8818 comp_template_args_porder (tree oargs, tree nargs)
8819 {
8820   return comp_template_args (oargs, nargs, NULL, NULL, true);
8821 }
8822 
8823 /* Implement a freelist interface for objects of type T.
8824 
8825    Head is a separate object, rather than a regular member, so that we
8826    can define it as a GTY deletable pointer, which is highly
8827    desirable.  A data member could be declared that way, but then the
8828    containing object would implicitly get GTY((user)), which would
8829    prevent us from instantiating freelists as global objects.
8830    Although this way we can create freelist global objects, they're
8831    such thin wrappers that instantiating temporaries at every use
8832    loses nothing and saves permanent storage for the freelist object.
8833 
8834    Member functions next, anew, poison and reinit have default
8835    implementations that work for most of the types we're interested
8836    in, but if they don't work for some type, they should be explicitly
8837    specialized.  See the comments before them for requirements, and
8838    the example specializations for the tree_list_freelist.  */
8839 template <typename T>
8840 class freelist
8841 {
8842   /* Return the next object in a chain.  We could just do type
8843      punning, but if we access the object with its underlying type, we
8844      avoid strict-aliasing trouble.  This needs only work between
8845      poison and reinit.  */
next(T * obj)8846   static T *&next (T *obj) { return obj->next; }
8847 
8848   /* Return a newly allocated, uninitialized or minimally-initialized
8849      object of type T.  Any initialization performed by anew should
8850      either remain across the life of the object and the execution of
8851      poison, or be redone by reinit.  */
anew()8852   static T *anew () { return ggc_alloc<T> (); }
8853 
8854   /* Optionally scribble all over the bits holding the object, so that
8855      they become (mostly?) uninitialized memory.  This is called while
8856      preparing to make the object part of the free list.  */
poison(T * obj)8857   static void poison (T *obj) {
8858     T *p ATTRIBUTE_UNUSED = obj;
8859     T **q ATTRIBUTE_UNUSED = &next (obj);
8860 
8861 #ifdef ENABLE_GC_CHECKING
8862     /* Poison the data, to indicate the data is garbage.  */
8863     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, sizeof (*p)));
8864     memset (p, 0xa5, sizeof (*p));
8865 #endif
8866     /* Let valgrind know the object is free.  */
8867     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, sizeof (*p)));
8868 
8869     /* Let valgrind know the next portion of the object is available,
8870        but uninitialized.  */
8871     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
8872   }
8873 
8874   /* Bring an object that underwent at least one lifecycle after anew
8875      and before the most recent free and poison, back to a usable
8876      state, reinitializing whatever is needed for it to be
8877      functionally equivalent to an object just allocated and returned
8878      by anew.  This may poison or clear the next field, used by
8879      freelist housekeeping after poison was called.  */
reinit(T * obj)8880   static void reinit (T *obj) {
8881     T **q ATTRIBUTE_UNUSED = &next (obj);
8882 
8883 #ifdef ENABLE_GC_CHECKING
8884     memset (q, 0xa5, sizeof (*q));
8885 #endif
8886     /* Let valgrind know the entire object is available, but
8887        uninitialized.  */
8888     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (*obj)));
8889   }
8890 
8891   /* Reference a GTY-deletable pointer that points to the first object
8892      in the free list proper.  */
8893   T *&head;
8894 public:
8895   /* Construct a freelist object chaining objects off of HEAD.  */
freelist(T * & head)8896   freelist (T *&head) : head(head) {}
8897 
8898   /* Add OBJ to the free object list.  The former head becomes OBJ's
8899      successor.  */
free(T * obj)8900   void free (T *obj)
8901   {
8902     poison (obj);
8903     next (obj) = head;
8904     head = obj;
8905   }
8906 
8907   /* Take an object from the free list, if one is available, or
8908      allocate a new one.  Objects taken from the free list should be
8909      regarded as filled with garbage, except for bits that are
8910      configured to be preserved across free and alloc.  */
alloc()8911   T *alloc ()
8912   {
8913     if (head)
8914       {
8915 	T *obj = head;
8916 	head = next (head);
8917 	reinit (obj);
8918 	return obj;
8919       }
8920     else
8921       return anew ();
8922   }
8923 };
8924 
8925 /* Explicitly specialize the interfaces for freelist<tree_node>: we
8926    want to allocate a TREE_LIST using the usual interface, and ensure
8927    TREE_CHAIN remains functional.  Alas, we have to duplicate a bit of
8928    build_tree_list logic in reinit, so this could go out of sync.  */
8929 template <>
8930 inline tree &
next(tree obj)8931 freelist<tree_node>::next (tree obj)
8932 {
8933   return TREE_CHAIN (obj);
8934 }
8935 template <>
8936 inline tree
anew()8937 freelist<tree_node>::anew ()
8938 {
8939   return build_tree_list (NULL, NULL);
8940 }
8941 template <>
8942 inline void
poison(tree obj ATTRIBUTE_UNUSED)8943 freelist<tree_node>::poison (tree obj ATTRIBUTE_UNUSED)
8944 {
8945   int size ATTRIBUTE_UNUSED = sizeof (tree_list);
8946   tree p ATTRIBUTE_UNUSED = obj;
8947   tree_base *b ATTRIBUTE_UNUSED = &obj->base;
8948   tree *q ATTRIBUTE_UNUSED = &next (obj);
8949 
8950 #ifdef ENABLE_GC_CHECKING
8951   gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
8952 
8953   /* Poison the data, to indicate the data is garbage.  */
8954   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, size));
8955   memset (p, 0xa5, size);
8956 #endif
8957   /* Let valgrind know the object is free.  */
8958   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, size));
8959   /* But we still want to use the TREE_CODE and TREE_CHAIN parts.  */
8960   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
8961   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
8962 
8963 #ifdef ENABLE_GC_CHECKING
8964   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (b, sizeof (*b)));
8965   /* Keep TREE_CHAIN functional.  */
8966   TREE_SET_CODE (obj, TREE_LIST);
8967 #else
8968   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
8969 #endif
8970 }
8971 template <>
8972 inline void
reinit(tree obj ATTRIBUTE_UNUSED)8973 freelist<tree_node>::reinit (tree obj ATTRIBUTE_UNUSED)
8974 {
8975   tree_base *b ATTRIBUTE_UNUSED = &obj->base;
8976 
8977 #ifdef ENABLE_GC_CHECKING
8978   gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
8979   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
8980   memset (obj, 0, sizeof (tree_list));
8981 #endif
8982 
8983   /* Let valgrind know the entire object is available, but
8984      uninitialized.  */
8985   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
8986 
8987 #ifdef ENABLE_GC_CHECKING
8988   TREE_SET_CODE (obj, TREE_LIST);
8989 #else
8990   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
8991 #endif
8992 }
8993 
8994 /* Point to the first object in the TREE_LIST freelist.  */
8995 static GTY((deletable)) tree tree_list_freelist_head;
8996 /* Return the/an actual TREE_LIST freelist.  */
8997 static inline freelist<tree_node>
tree_list_freelist()8998 tree_list_freelist ()
8999 {
9000   return tree_list_freelist_head;
9001 }
9002 
9003 /* Point to the first object in the tinst_level freelist.  */
9004 static GTY((deletable)) tinst_level *tinst_level_freelist_head;
9005 /* Return the/an actual tinst_level freelist.  */
9006 static inline freelist<tinst_level>
tinst_level_freelist()9007 tinst_level_freelist ()
9008 {
9009   return tinst_level_freelist_head;
9010 }
9011 
9012 /* Point to the first object in the pending_template freelist.  */
9013 static GTY((deletable)) pending_template *pending_template_freelist_head;
9014 /* Return the/an actual pending_template freelist.  */
9015 static inline freelist<pending_template>
pending_template_freelist()9016 pending_template_freelist ()
9017 {
9018   return pending_template_freelist_head;
9019 }
9020 
9021 /* Build the TREE_LIST object out of a split list, store it
9022    permanently, and return it.  */
9023 tree
to_list()9024 tinst_level::to_list ()
9025 {
9026   gcc_assert (split_list_p ());
9027   tree ret = tree_list_freelist ().alloc ();
9028   TREE_PURPOSE (ret) = tldcl;
9029   TREE_VALUE (ret) = targs;
9030   tldcl = ret;
9031   targs = NULL;
9032   gcc_assert (tree_list_p ());
9033   return ret;
9034 }
9035 
9036 const unsigned short tinst_level::refcount_infinity;
9037 
9038 /* Increment OBJ's refcount unless it is already infinite.  */
9039 static tinst_level *
inc_refcount_use(tinst_level * obj)9040 inc_refcount_use (tinst_level *obj)
9041 {
9042   if (obj && obj->refcount != tinst_level::refcount_infinity)
9043     ++obj->refcount;
9044   return obj;
9045 }
9046 
9047 /* Release storage for OBJ and node, if it's a TREE_LIST.  */
9048 void
free(tinst_level * obj)9049 tinst_level::free (tinst_level *obj)
9050 {
9051   if (obj->tree_list_p ())
9052     tree_list_freelist ().free (obj->get_node ());
9053   tinst_level_freelist ().free (obj);
9054 }
9055 
9056 /* Decrement OBJ's refcount if not infinite.  If it reaches zero, release
9057    OBJ's DECL and OBJ, and start over with the tinst_level object that
9058    used to be referenced by OBJ's NEXT.  */
9059 static void
dec_refcount_use(tinst_level * obj)9060 dec_refcount_use (tinst_level *obj)
9061 {
9062   while (obj
9063 	 && obj->refcount != tinst_level::refcount_infinity
9064 	 && !--obj->refcount)
9065     {
9066       tinst_level *next = obj->next;
9067       tinst_level::free (obj);
9068       obj = next;
9069     }
9070 }
9071 
9072 /* Modify PTR so that it points to OBJ, adjusting the refcounts of OBJ
9073    and of the former PTR.  Omitting the second argument is equivalent
9074    to passing (T*)NULL; this is allowed because passing the
9075    zero-valued integral constant NULL confuses type deduction and/or
9076    overload resolution.  */
9077 template <typename T>
9078 static void
9079 set_refcount_ptr (T *& ptr, T *obj = NULL)
9080 {
9081   T *save = ptr;
9082   ptr = inc_refcount_use (obj);
9083   dec_refcount_use (save);
9084 }
9085 
9086 static void
add_pending_template(tree d)9087 add_pending_template (tree d)
9088 {
9089   tree ti = (TYPE_P (d)
9090 	     ? CLASSTYPE_TEMPLATE_INFO (d)
9091 	     : DECL_TEMPLATE_INFO (d));
9092   struct pending_template *pt;
9093   int level;
9094 
9095   if (TI_PENDING_TEMPLATE_FLAG (ti))
9096     return;
9097 
9098   /* We are called both from instantiate_decl, where we've already had a
9099      tinst_level pushed, and instantiate_template, where we haven't.
9100      Compensate.  */
9101   gcc_assert (TREE_CODE (d) != TREE_LIST);
9102   level = !current_tinst_level
9103     || current_tinst_level->maybe_get_node () != d;
9104 
9105   if (level)
9106     push_tinst_level (d);
9107 
9108   pt = pending_template_freelist ().alloc ();
9109   pt->next = NULL;
9110   pt->tinst = NULL;
9111   set_refcount_ptr (pt->tinst, current_tinst_level);
9112   if (last_pending_template)
9113     last_pending_template->next = pt;
9114   else
9115     pending_templates = pt;
9116 
9117   last_pending_template = pt;
9118 
9119   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
9120 
9121   if (level)
9122     pop_tinst_level ();
9123 }
9124 
9125 
9126 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
9127    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
9128    documentation for TEMPLATE_ID_EXPR.  */
9129 
9130 tree
lookup_template_function(tree fns,tree arglist)9131 lookup_template_function (tree fns, tree arglist)
9132 {
9133   tree type;
9134 
9135   if (fns == error_mark_node || arglist == error_mark_node)
9136     return error_mark_node;
9137 
9138   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
9139 
9140   if (!is_overloaded_fn (fns) && !identifier_p (fns))
9141     {
9142       error ("%q#D is not a function template", fns);
9143       return error_mark_node;
9144     }
9145 
9146   if (BASELINK_P (fns))
9147     {
9148       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
9149 					 unknown_type_node,
9150 					 BASELINK_FUNCTIONS (fns),
9151 					 arglist);
9152       return fns;
9153     }
9154 
9155   type = TREE_TYPE (fns);
9156   if (TREE_CODE (fns) == OVERLOAD || !type)
9157     type = unknown_type_node;
9158 
9159   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
9160 }
9161 
9162 /* Within the scope of a template class S<T>, the name S gets bound
9163    (in build_self_reference) to a TYPE_DECL for the class, not a
9164    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
9165    or one of its enclosing classes, and that type is a template,
9166    return the associated TEMPLATE_DECL.  Otherwise, the original
9167    DECL is returned.
9168 
9169    Also handle the case when DECL is a TREE_LIST of ambiguous
9170    injected-class-names from different bases.  */
9171 
9172 tree
maybe_get_template_decl_from_type_decl(tree decl)9173 maybe_get_template_decl_from_type_decl (tree decl)
9174 {
9175   if (decl == NULL_TREE)
9176     return decl;
9177 
9178   /* DR 176: A lookup that finds an injected-class-name (10.2
9179      [class.member.lookup]) can result in an ambiguity in certain cases
9180      (for example, if it is found in more than one base class). If all of
9181      the injected-class-names that are found refer to specializations of
9182      the same class template, and if the name is followed by a
9183      template-argument-list, the reference refers to the class template
9184      itself and not a specialization thereof, and is not ambiguous.  */
9185   if (TREE_CODE (decl) == TREE_LIST)
9186     {
9187       tree t, tmpl = NULL_TREE;
9188       for (t = decl; t; t = TREE_CHAIN (t))
9189 	{
9190 	  tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
9191 	  if (!tmpl)
9192 	    tmpl = elt;
9193 	  else if (tmpl != elt)
9194 	    break;
9195 	}
9196       if (tmpl && t == NULL_TREE)
9197 	return tmpl;
9198       else
9199 	return decl;
9200     }
9201 
9202   return (decl != NULL_TREE
9203 	  && DECL_SELF_REFERENCE_P (decl)
9204 	  && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
9205     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
9206 }
9207 
9208 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
9209    parameters, find the desired type.
9210 
9211    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
9212 
9213    IN_DECL, if non-NULL, is the template declaration we are trying to
9214    instantiate.
9215 
9216    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
9217    the class we are looking up.
9218 
9219    Issue error and warning messages under control of COMPLAIN.
9220 
9221    If the template class is really a local class in a template
9222    function, then the FUNCTION_CONTEXT is the function in which it is
9223    being instantiated.
9224 
9225    ??? Note that this function is currently called *twice* for each
9226    template-id: the first time from the parser, while creating the
9227    incomplete type (finish_template_type), and the second type during the
9228    real instantiation (instantiate_template_class). This is surely something
9229    that we want to avoid. It also causes some problems with argument
9230    coercion (see convert_nontype_argument for more information on this).  */
9231 
9232 static tree
lookup_template_class_1(tree d1,tree arglist,tree in_decl,tree context,int entering_scope,tsubst_flags_t complain)9233 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
9234 			 int entering_scope, tsubst_flags_t complain)
9235 {
9236   tree templ = NULL_TREE, parmlist;
9237   tree t;
9238   spec_entry **slot;
9239   spec_entry *entry;
9240   spec_entry elt;
9241   hashval_t hash;
9242 
9243   if (identifier_p (d1))
9244     {
9245       tree value = innermost_non_namespace_value (d1);
9246       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
9247 	templ = value;
9248       else
9249 	{
9250 	  if (context)
9251 	    push_decl_namespace (context);
9252 	  templ = lookup_name (d1);
9253 	  templ = maybe_get_template_decl_from_type_decl (templ);
9254 	  if (context)
9255 	    pop_decl_namespace ();
9256 	}
9257       if (templ)
9258 	context = DECL_CONTEXT (templ);
9259     }
9260   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
9261     {
9262       tree type = TREE_TYPE (d1);
9263 
9264       /* If we are declaring a constructor, say A<T>::A<T>, we will get
9265 	 an implicit typename for the second A.  Deal with it.  */
9266       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
9267 	type = TREE_TYPE (type);
9268 
9269       if (CLASSTYPE_TEMPLATE_INFO (type))
9270 	{
9271 	  templ = CLASSTYPE_TI_TEMPLATE (type);
9272 	  d1 = DECL_NAME (templ);
9273 	}
9274     }
9275   else if (TREE_CODE (d1) == ENUMERAL_TYPE
9276 	   || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
9277     {
9278       templ = TYPE_TI_TEMPLATE (d1);
9279       d1 = DECL_NAME (templ);
9280     }
9281   else if (DECL_TYPE_TEMPLATE_P (d1))
9282     {
9283       templ = d1;
9284       d1 = DECL_NAME (templ);
9285       context = DECL_CONTEXT (templ);
9286     }
9287   else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
9288     {
9289       templ = d1;
9290       d1 = DECL_NAME (templ);
9291     }
9292 
9293   /* Issue an error message if we didn't find a template.  */
9294   if (! templ)
9295     {
9296       if (complain & tf_error)
9297 	error ("%qT is not a template", d1);
9298       return error_mark_node;
9299     }
9300 
9301   if (TREE_CODE (templ) != TEMPLATE_DECL
9302 	 /* Make sure it's a user visible template, if it was named by
9303 	    the user.  */
9304       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
9305 	  && !PRIMARY_TEMPLATE_P (templ)))
9306     {
9307       if (complain & tf_error)
9308 	{
9309 	  error ("non-template type %qT used as a template", d1);
9310 	  if (in_decl)
9311 	    error ("for template declaration %q+D", in_decl);
9312 	}
9313       return error_mark_node;
9314     }
9315 
9316   complain &= ~tf_user;
9317 
9318   /* An alias that just changes the name of a template is equivalent to the
9319      other template, so if any of the arguments are pack expansions, strip
9320      the alias to avoid problems with a pack expansion passed to a non-pack
9321      alias template parameter (DR 1430).  */
9322   if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
9323     templ = get_underlying_template (templ);
9324 
9325   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
9326     {
9327       tree parm;
9328       tree arglist2 = coerce_template_args_for_ttp (templ, arglist, complain);
9329       if (arglist2 == error_mark_node
9330 	  || (!uses_template_parms (arglist2)
9331 	      && check_instantiated_args (templ, arglist2, complain)))
9332 	return error_mark_node;
9333 
9334       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
9335       return parm;
9336     }
9337   else
9338     {
9339       tree template_type = TREE_TYPE (templ);
9340       tree gen_tmpl;
9341       tree type_decl;
9342       tree found = NULL_TREE;
9343       int arg_depth;
9344       int parm_depth;
9345       int is_dependent_type;
9346       int use_partial_inst_tmpl = false;
9347 
9348       if (template_type == error_mark_node)
9349 	/* An error occurred while building the template TEMPL, and a
9350 	   diagnostic has most certainly been emitted for that
9351 	   already.  Let's propagate that error.  */
9352 	return error_mark_node;
9353 
9354       gen_tmpl = most_general_template (templ);
9355       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
9356       parm_depth = TMPL_PARMS_DEPTH (parmlist);
9357       arg_depth = TMPL_ARGS_DEPTH (arglist);
9358 
9359       if (arg_depth == 1 && parm_depth > 1)
9360 	{
9361 	  /* We've been given an incomplete set of template arguments.
9362 	     For example, given:
9363 
9364 	       template <class T> struct S1 {
9365 		 template <class U> struct S2 {};
9366 		 template <class U> struct S2<U*> {};
9367 		};
9368 
9369 	     we will be called with an ARGLIST of `U*', but the
9370 	     TEMPLATE will be `template <class T> template
9371 	     <class U> struct S1<T>::S2'.  We must fill in the missing
9372 	     arguments.  */
9373 	  tree ti = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (templ));
9374 	  arglist = add_outermost_template_args (TI_ARGS (ti), arglist);
9375 	  arg_depth = TMPL_ARGS_DEPTH (arglist);
9376 	}
9377 
9378       /* Now we should have enough arguments.  */
9379       gcc_assert (parm_depth == arg_depth);
9380 
9381       /* From here on, we're only interested in the most general
9382 	 template.  */
9383 
9384       /* Calculate the BOUND_ARGS.  These will be the args that are
9385 	 actually tsubst'd into the definition to create the
9386 	 instantiation.  */
9387       arglist = coerce_innermost_template_parms (parmlist, arglist, gen_tmpl,
9388 						 complain,
9389 						 /*require_all_args=*/true,
9390 						 /*use_default_args=*/true);
9391 
9392       if (arglist == error_mark_node)
9393 	/* We were unable to bind the arguments.  */
9394 	return error_mark_node;
9395 
9396       /* In the scope of a template class, explicit references to the
9397 	 template class refer to the type of the template, not any
9398 	 instantiation of it.  For example, in:
9399 
9400 	   template <class T> class C { void f(C<T>); }
9401 
9402 	 the `C<T>' is just the same as `C'.  Outside of the
9403 	 class, however, such a reference is an instantiation.  */
9404       if (entering_scope
9405 	  || !PRIMARY_TEMPLATE_P (gen_tmpl)
9406 	  || currently_open_class (template_type))
9407 	{
9408 	  tree tinfo = TYPE_TEMPLATE_INFO (template_type);
9409 
9410 	  if (tinfo && comp_template_args (TI_ARGS (tinfo), arglist))
9411 	    return template_type;
9412 	}
9413 
9414       /* If we already have this specialization, return it.  */
9415       elt.tmpl = gen_tmpl;
9416       elt.args = arglist;
9417       elt.spec = NULL_TREE;
9418       hash = spec_hasher::hash (&elt);
9419       entry = type_specializations->find_with_hash (&elt, hash);
9420 
9421       if (entry)
9422 	return entry->spec;
9423 
9424       /* If the the template's constraints are not satisfied,
9425          then we cannot form a valid type.
9426 
9427          Note that the check is deferred until after the hash
9428          lookup. This prevents redundant checks on previously
9429          instantiated specializations. */
9430       if (flag_concepts && !constraints_satisfied_p (gen_tmpl, arglist))
9431         {
9432           if (complain & tf_error)
9433             {
9434               error ("template constraint failure");
9435               diagnose_constraints (input_location, gen_tmpl, arglist);
9436             }
9437           return error_mark_node;
9438         }
9439 
9440       is_dependent_type = uses_template_parms (arglist);
9441 
9442       /* If the deduced arguments are invalid, then the binding
9443 	 failed.  */
9444       if (!is_dependent_type
9445 	  && check_instantiated_args (gen_tmpl,
9446 				      INNERMOST_TEMPLATE_ARGS (arglist),
9447 				      complain))
9448 	return error_mark_node;
9449 
9450       if (!is_dependent_type
9451 	  && !PRIMARY_TEMPLATE_P (gen_tmpl)
9452 	  && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
9453 	  && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
9454 	{
9455 	  found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
9456 				      DECL_NAME (gen_tmpl),
9457 				      /*tag_scope=*/ts_global);
9458 	  return found;
9459 	}
9460 
9461       context = DECL_CONTEXT (gen_tmpl);
9462       if (context && TYPE_P (context))
9463 	{
9464 	  context = tsubst_aggr_type (context, arglist, complain, in_decl, true);
9465 	  context = complete_type (context);
9466 	}
9467       else
9468 	context = tsubst (context, arglist, complain, in_decl);
9469 
9470       if (context == error_mark_node)
9471 	return error_mark_node;
9472 
9473       if (!context)
9474 	context = global_namespace;
9475 
9476       /* Create the type.  */
9477       if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9478 	{
9479 	  /* The user referred to a specialization of an alias
9480 	    template represented by GEN_TMPL.
9481 
9482 	    [temp.alias]/2 says:
9483 
9484 	        When a template-id refers to the specialization of an
9485 		alias template, it is equivalent to the associated
9486 		type obtained by substitution of its
9487 		template-arguments for the template-parameters in the
9488 		type-id of the alias template.  */
9489 
9490 	  t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
9491 	  /* Note that the call above (by indirectly calling
9492 	     register_specialization in tsubst_decl) registers the
9493 	     TYPE_DECL representing the specialization of the alias
9494 	     template.  So next time someone substitutes ARGLIST for
9495 	     the template parms into the alias template (GEN_TMPL),
9496 	     she'll get that TYPE_DECL back.  */
9497 
9498 	  if (t == error_mark_node)
9499 	    return t;
9500 	}
9501       else if (TREE_CODE (template_type) == ENUMERAL_TYPE)
9502 	{
9503 	  if (!is_dependent_type)
9504 	    {
9505 	      set_current_access_from_decl (TYPE_NAME (template_type));
9506 	      t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
9507 			      tsubst (ENUM_UNDERLYING_TYPE (template_type),
9508 				      arglist, complain, in_decl),
9509 			      tsubst_attributes (TYPE_ATTRIBUTES (template_type),
9510 						 arglist, complain, in_decl),
9511 			      SCOPED_ENUM_P (template_type), NULL);
9512 
9513 	      if (t == error_mark_node)
9514 		return t;
9515 	    }
9516 	  else
9517             {
9518               /* We don't want to call start_enum for this type, since
9519                  the values for the enumeration constants may involve
9520                  template parameters.  And, no one should be interested
9521                  in the enumeration constants for such a type.  */
9522               t = cxx_make_type (ENUMERAL_TYPE);
9523               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
9524             }
9525           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
9526 	  ENUM_FIXED_UNDERLYING_TYPE_P (t)
9527 	    = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
9528 	}
9529       else if (CLASS_TYPE_P (template_type))
9530 	{
9531 	  /* Lambda closures are regenerated in tsubst_lambda_expr, not
9532 	     instantiated here.  */
9533 	  gcc_assert (!LAMBDA_TYPE_P (template_type));
9534 
9535 	  t = make_class_type (TREE_CODE (template_type));
9536 	  CLASSTYPE_DECLARED_CLASS (t)
9537 	    = CLASSTYPE_DECLARED_CLASS (template_type);
9538 	  SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
9539 
9540 	  /* A local class.  Make sure the decl gets registered properly.  */
9541 	  if (context == current_function_decl)
9542 	    if (pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current)
9543 		== error_mark_node)
9544 	      return error_mark_node;
9545 
9546 	  if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
9547 	    /* This instantiation is another name for the primary
9548 	       template type. Set the TYPE_CANONICAL field
9549 	       appropriately. */
9550 	    TYPE_CANONICAL (t) = template_type;
9551 	  else if (any_template_arguments_need_structural_equality_p (arglist))
9552 	    /* Some of the template arguments require structural
9553 	       equality testing, so this template class requires
9554 	       structural equality testing. */
9555 	    SET_TYPE_STRUCTURAL_EQUALITY (t);
9556 	}
9557       else
9558 	gcc_unreachable ();
9559 
9560       /* If we called start_enum or pushtag above, this information
9561 	 will already be set up.  */
9562       if (!TYPE_NAME (t))
9563 	{
9564 	  TYPE_CONTEXT (t) = FROB_CONTEXT (context);
9565 
9566 	  type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
9567 	  DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
9568 	  DECL_SOURCE_LOCATION (type_decl)
9569 	    = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
9570 	}
9571       else
9572 	type_decl = TYPE_NAME (t);
9573 
9574       if (CLASS_TYPE_P (template_type))
9575 	{
9576 	  TREE_PRIVATE (type_decl)
9577 	    = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
9578 	  TREE_PROTECTED (type_decl)
9579 	    = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
9580 	  if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
9581 	    {
9582 	      DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
9583 	      DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
9584 	    }
9585 	}
9586 
9587       if (OVERLOAD_TYPE_P (t)
9588 	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9589 	{
9590 	  static const char *tags[] = {"abi_tag", "may_alias"};
9591 
9592 	  for (unsigned ix = 0; ix != 2; ix++)
9593 	    {
9594 	      tree attributes
9595 		= lookup_attribute (tags[ix], TYPE_ATTRIBUTES (template_type));
9596 
9597 	      if (attributes)
9598 		TYPE_ATTRIBUTES (t)
9599 		  = tree_cons (TREE_PURPOSE (attributes),
9600 			       TREE_VALUE (attributes),
9601 			       TYPE_ATTRIBUTES (t));
9602 	    }
9603 	}
9604 
9605       /* Let's consider the explicit specialization of a member
9606          of a class template specialization that is implicitly instantiated,
9607 	 e.g.:
9608 	     template<class T>
9609 	     struct S
9610 	     {
9611 	       template<class U> struct M {}; //#0
9612 	     };
9613 
9614 	     template<>
9615 	     template<>
9616 	     struct S<int>::M<char> //#1
9617 	     {
9618 	       int i;
9619 	     };
9620 	[temp.expl.spec]/4 says this is valid.
9621 
9622 	In this case, when we write:
9623 	S<int>::M<char> m;
9624 
9625 	M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
9626 	the one of #0.
9627 
9628 	When we encounter #1, we want to store the partial instantiation
9629 	of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
9630 
9631 	For all cases other than this "explicit specialization of member of a
9632 	class template", we just want to store the most general template into
9633 	the CLASSTYPE_TI_TEMPLATE of M.
9634 
9635 	This case of "explicit specialization of member of a class template"
9636 	only happens when:
9637 	1/ the enclosing class is an instantiation of, and therefore not
9638 	the same as, the context of the most general template, and
9639 	2/ we aren't looking at the partial instantiation itself, i.e.
9640 	the innermost arguments are not the same as the innermost parms of
9641 	the most general template.
9642 
9643 	So it's only when 1/ and 2/ happens that we want to use the partial
9644 	instantiation of the member template in lieu of its most general
9645 	template.  */
9646 
9647       if (PRIMARY_TEMPLATE_P (gen_tmpl)
9648 	  && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
9649 	  /* the enclosing class must be an instantiation...  */
9650 	  && CLASS_TYPE_P (context)
9651 	  && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
9652 	{
9653 	  TREE_VEC_LENGTH (arglist)--;
9654 	  ++processing_template_decl;
9655 	  tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (gen_tmpl));
9656 	  tree partial_inst_args =
9657 	    tsubst (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)),
9658 		    arglist, complain, NULL_TREE);
9659 	  --processing_template_decl;
9660 	  TREE_VEC_LENGTH (arglist)++;
9661 	  if (partial_inst_args == error_mark_node)
9662 	    return error_mark_node;
9663 	  use_partial_inst_tmpl =
9664 	    /*...and we must not be looking at the partial instantiation
9665 	     itself. */
9666 	    !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
9667 				 partial_inst_args);
9668 	}
9669 
9670       if (!use_partial_inst_tmpl)
9671 	/* This case is easy; there are no member templates involved.  */
9672 	found = gen_tmpl;
9673       else
9674 	{
9675 	  /* This is a full instantiation of a member template.  Find
9676 	     the partial instantiation of which this is an instance.  */
9677 
9678 	  /* Temporarily reduce by one the number of levels in the ARGLIST
9679 	     so as to avoid comparing the last set of arguments.  */
9680 	  TREE_VEC_LENGTH (arglist)--;
9681 	  found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
9682 	  TREE_VEC_LENGTH (arglist)++;
9683 	  /* FOUND is either a proper class type, or an alias
9684 	     template specialization.  In the later case, it's a
9685 	     TYPE_DECL, resulting from the substituting of arguments
9686 	     for parameters in the TYPE_DECL of the alias template
9687 	     done earlier.  So be careful while getting the template
9688 	     of FOUND.  */
9689 	  found = (TREE_CODE (found) == TEMPLATE_DECL
9690 		   ? found
9691 		   : (TREE_CODE (found) == TYPE_DECL
9692 		      ? DECL_TI_TEMPLATE (found)
9693 		      : CLASSTYPE_TI_TEMPLATE (found)));
9694 	}
9695 
9696       // Build template info for the new specialization.
9697       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
9698 
9699       elt.spec = t;
9700       slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
9701       entry = ggc_alloc<spec_entry> ();
9702       *entry = elt;
9703       *slot = entry;
9704 
9705       /* Note this use of the partial instantiation so we can check it
9706 	 later in maybe_process_partial_specialization.  */
9707       DECL_TEMPLATE_INSTANTIATIONS (found)
9708 	= tree_cons (arglist, t,
9709 		     DECL_TEMPLATE_INSTANTIATIONS (found));
9710 
9711       if (TREE_CODE (template_type) == ENUMERAL_TYPE && !is_dependent_type
9712 	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9713 	/* Now that the type has been registered on the instantiations
9714 	   list, we set up the enumerators.  Because the enumeration
9715 	   constants may involve the enumeration type itself, we make
9716 	   sure to register the type first, and then create the
9717 	   constants.  That way, doing tsubst_expr for the enumeration
9718 	   constants won't result in recursive calls here; we'll find
9719 	   the instantiation and exit above.  */
9720 	tsubst_enum (template_type, t, arglist);
9721 
9722       if (CLASS_TYPE_P (template_type) && is_dependent_type)
9723 	/* If the type makes use of template parameters, the
9724 	   code that generates debugging information will crash.  */
9725 	DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
9726 
9727       /* Possibly limit visibility based on template args.  */
9728       TREE_PUBLIC (type_decl) = 1;
9729       determine_visibility (type_decl);
9730 
9731       inherit_targ_abi_tags (t);
9732 
9733       return t;
9734     }
9735 }
9736 
9737 /* Wrapper for lookup_template_class_1.  */
9738 
9739 tree
lookup_template_class(tree d1,tree arglist,tree in_decl,tree context,int entering_scope,tsubst_flags_t complain)9740 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
9741                        int entering_scope, tsubst_flags_t complain)
9742 {
9743   tree ret;
9744   timevar_push (TV_TEMPLATE_INST);
9745   ret = lookup_template_class_1 (d1, arglist, in_decl, context,
9746                                  entering_scope, complain);
9747   timevar_pop (TV_TEMPLATE_INST);
9748   return ret;
9749 }
9750 
9751 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST.  */
9752 
9753 tree
lookup_template_variable(tree templ,tree arglist)9754 lookup_template_variable (tree templ, tree arglist)
9755 {
9756   /* The type of the expression is NULL_TREE since the template-id could refer
9757      to an explicit or partial specialization. */
9758   tree type = NULL_TREE;
9759   if (flag_concepts && variable_concept_p (templ))
9760     /* Except that concepts are always bool.  */
9761     type = boolean_type_node;
9762   return build2 (TEMPLATE_ID_EXPR, type, templ, arglist);
9763 }
9764 
9765 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR for use. */
9766 
9767 tree
finish_template_variable(tree var,tsubst_flags_t complain)9768 finish_template_variable (tree var, tsubst_flags_t complain)
9769 {
9770   tree templ = TREE_OPERAND (var, 0);
9771   tree arglist = TREE_OPERAND (var, 1);
9772 
9773   /* We never want to return a VAR_DECL for a variable concept, since they
9774      aren't instantiated.  In a template, leave the TEMPLATE_ID_EXPR alone.  */
9775   bool concept_p = flag_concepts && variable_concept_p (templ);
9776   if (concept_p && processing_template_decl)
9777     return var;
9778 
9779   tree tmpl_args = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (templ));
9780   arglist = add_outermost_template_args (tmpl_args, arglist);
9781 
9782   templ = most_general_template (templ);
9783   tree parms = DECL_TEMPLATE_PARMS (templ);
9784   arglist = coerce_innermost_template_parms (parms, arglist, templ, complain,
9785 					     /*req_all*/true,
9786 					     /*use_default*/true);
9787 
9788   if (flag_concepts && !constraints_satisfied_p (templ, arglist))
9789     {
9790       if (complain & tf_error)
9791 	{
9792 	  error ("use of invalid variable template %qE", var);
9793 	  diagnose_constraints (location_of (var), templ, arglist);
9794 	}
9795       return error_mark_node;
9796     }
9797 
9798   /* If a template-id refers to a specialization of a variable
9799      concept, then the expression is true if and only if the
9800      concept's constraints are satisfied by the given template
9801      arguments.
9802 
9803      NOTE: This is an extension of Concepts Lite TS that
9804      allows constraints to be used in expressions. */
9805   if (concept_p)
9806     {
9807       tree decl = DECL_TEMPLATE_RESULT (templ);
9808       return evaluate_variable_concept (decl, arglist);
9809     }
9810 
9811   return instantiate_template (templ, arglist, complain);
9812 }
9813 
9814 /* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
9815    TARGS template args, and instantiate it if it's not dependent.  */
9816 
9817 tree
lookup_and_finish_template_variable(tree templ,tree targs,tsubst_flags_t complain)9818 lookup_and_finish_template_variable (tree templ, tree targs,
9819 				     tsubst_flags_t complain)
9820 {
9821   templ = lookup_template_variable (templ, targs);
9822   if (!any_dependent_template_arguments_p (targs))
9823     {
9824       templ = finish_template_variable (templ, complain);
9825       mark_used (templ);
9826     }
9827 
9828   return convert_from_reference (templ);
9829 }
9830 
9831 
9832 struct pair_fn_data
9833 {
9834   tree_fn_t fn;
9835   tree_fn_t any_fn;
9836   void *data;
9837   /* True when we should also visit template parameters that occur in
9838      non-deduced contexts.  */
9839   bool include_nondeduced_p;
9840   hash_set<tree> *visited;
9841 };
9842 
9843 /* Called from for_each_template_parm via walk_tree.  */
9844 
9845 static tree
for_each_template_parm_r(tree * tp,int * walk_subtrees,void * d)9846 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
9847 {
9848   tree t = *tp;
9849   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
9850   tree_fn_t fn = pfd->fn;
9851   void *data = pfd->data;
9852   tree result = NULL_TREE;
9853 
9854 #define WALK_SUBTREE(NODE)						\
9855   do									\
9856     {									\
9857       result = for_each_template_parm (NODE, fn, data, pfd->visited,	\
9858 				       pfd->include_nondeduced_p,	\
9859 				       pfd->any_fn);			\
9860       if (result) goto out;						\
9861     }									\
9862   while (0)
9863 
9864   if (pfd->any_fn && (*pfd->any_fn)(t, data))
9865     return t;
9866 
9867   if (TYPE_P (t)
9868       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
9869     WALK_SUBTREE (TYPE_CONTEXT (t));
9870 
9871   switch (TREE_CODE (t))
9872     {
9873     case RECORD_TYPE:
9874       if (TYPE_PTRMEMFUNC_P (t))
9875 	break;
9876       /* Fall through.  */
9877 
9878     case UNION_TYPE:
9879     case ENUMERAL_TYPE:
9880       if (!TYPE_TEMPLATE_INFO (t))
9881 	*walk_subtrees = 0;
9882       else
9883 	WALK_SUBTREE (TYPE_TI_ARGS (t));
9884       break;
9885 
9886     case INTEGER_TYPE:
9887       WALK_SUBTREE (TYPE_MIN_VALUE (t));
9888       WALK_SUBTREE (TYPE_MAX_VALUE (t));
9889       break;
9890 
9891     case METHOD_TYPE:
9892       /* Since we're not going to walk subtrees, we have to do this
9893 	 explicitly here.  */
9894       WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
9895       /* Fall through.  */
9896 
9897     case FUNCTION_TYPE:
9898       /* Check the return type.  */
9899       WALK_SUBTREE (TREE_TYPE (t));
9900 
9901       /* Check the parameter types.  Since default arguments are not
9902 	 instantiated until they are needed, the TYPE_ARG_TYPES may
9903 	 contain expressions that involve template parameters.  But,
9904 	 no-one should be looking at them yet.  And, once they're
9905 	 instantiated, they don't contain template parameters, so
9906 	 there's no point in looking at them then, either.  */
9907       {
9908 	tree parm;
9909 
9910 	for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
9911 	  WALK_SUBTREE (TREE_VALUE (parm));
9912 
9913 	/* Since we've already handled the TYPE_ARG_TYPES, we don't
9914 	   want walk_tree walking into them itself.  */
9915 	*walk_subtrees = 0;
9916       }
9917 
9918       if (flag_noexcept_type)
9919 	{
9920 	  tree spec = TYPE_RAISES_EXCEPTIONS (t);
9921 	  if (spec)
9922 	    WALK_SUBTREE (TREE_PURPOSE (spec));
9923 	}
9924       break;
9925 
9926     case TYPEOF_TYPE:
9927     case DECLTYPE_TYPE:
9928     case UNDERLYING_TYPE:
9929       if (pfd->include_nondeduced_p
9930 	  && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
9931 				     pfd->visited,
9932 				     pfd->include_nondeduced_p,
9933 				     pfd->any_fn))
9934 	return error_mark_node;
9935       *walk_subtrees = false;
9936       break;
9937 
9938     case FUNCTION_DECL:
9939     case VAR_DECL:
9940       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
9941 	WALK_SUBTREE (DECL_TI_ARGS (t));
9942       /* Fall through.  */
9943 
9944     case PARM_DECL:
9945     case CONST_DECL:
9946       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t))
9947 	WALK_SUBTREE (DECL_INITIAL (t));
9948       if (DECL_CONTEXT (t)
9949 	  && pfd->include_nondeduced_p)
9950 	WALK_SUBTREE (DECL_CONTEXT (t));
9951       break;
9952 
9953     case BOUND_TEMPLATE_TEMPLATE_PARM:
9954       /* Record template parameters such as `T' inside `TT<T>'.  */
9955       WALK_SUBTREE (TYPE_TI_ARGS (t));
9956       /* Fall through.  */
9957 
9958     case TEMPLATE_TEMPLATE_PARM:
9959     case TEMPLATE_TYPE_PARM:
9960     case TEMPLATE_PARM_INDEX:
9961       if (fn && (*fn)(t, data))
9962 	return t;
9963       else if (!fn)
9964 	return t;
9965       break;
9966 
9967     case TEMPLATE_DECL:
9968       /* A template template parameter is encountered.  */
9969       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9970 	WALK_SUBTREE (TREE_TYPE (t));
9971 
9972       /* Already substituted template template parameter */
9973       *walk_subtrees = 0;
9974       break;
9975 
9976     case TYPENAME_TYPE:
9977       /* A template-id in a TYPENAME_TYPE might be a deduced context after
9978 	 partial instantiation.  */
9979       WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
9980       break;
9981 
9982     case CONSTRUCTOR:
9983       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
9984 	  && pfd->include_nondeduced_p)
9985 	WALK_SUBTREE (TYPE_PTRMEMFUNC_FN_TYPE (TREE_TYPE (t)));
9986       break;
9987 
9988     case INDIRECT_REF:
9989     case COMPONENT_REF:
9990       /* If there's no type, then this thing must be some expression
9991 	 involving template parameters.  */
9992       if (!fn && !TREE_TYPE (t))
9993 	return error_mark_node;
9994       break;
9995 
9996     case MODOP_EXPR:
9997     case CAST_EXPR:
9998     case IMPLICIT_CONV_EXPR:
9999     case REINTERPRET_CAST_EXPR:
10000     case CONST_CAST_EXPR:
10001     case STATIC_CAST_EXPR:
10002     case DYNAMIC_CAST_EXPR:
10003     case ARROW_EXPR:
10004     case DOTSTAR_EXPR:
10005     case TYPEID_EXPR:
10006     case PSEUDO_DTOR_EXPR:
10007       if (!fn)
10008 	return error_mark_node;
10009       break;
10010 
10011     default:
10012       break;
10013     }
10014 
10015   #undef WALK_SUBTREE
10016 
10017   /* We didn't find any template parameters we liked.  */
10018  out:
10019   return result;
10020 }
10021 
10022 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
10023    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
10024    call FN with the parameter and the DATA.
10025    If FN returns nonzero, the iteration is terminated, and
10026    for_each_template_parm returns 1.  Otherwise, the iteration
10027    continues.  If FN never returns a nonzero value, the value
10028    returned by for_each_template_parm is 0.  If FN is NULL, it is
10029    considered to be the function which always returns 1.
10030 
10031    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
10032    parameters that occur in non-deduced contexts.  When false, only
10033    visits those template parameters that can be deduced.  */
10034 
10035 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)10036 for_each_template_parm (tree t, tree_fn_t fn, void* data,
10037 			hash_set<tree> *visited,
10038 			bool include_nondeduced_p,
10039 			tree_fn_t any_fn)
10040 {
10041   struct pair_fn_data pfd;
10042   tree result;
10043 
10044   /* Set up.  */
10045   pfd.fn = fn;
10046   pfd.any_fn = any_fn;
10047   pfd.data = data;
10048   pfd.include_nondeduced_p = include_nondeduced_p;
10049 
10050   /* Walk the tree.  (Conceptually, we would like to walk without
10051      duplicates, but for_each_template_parm_r recursively calls
10052      for_each_template_parm, so we would need to reorganize a fair
10053      bit to use walk_tree_without_duplicates, so we keep our own
10054      visited list.)  */
10055   if (visited)
10056     pfd.visited = visited;
10057   else
10058     pfd.visited = new hash_set<tree>;
10059   result = cp_walk_tree (&t,
10060 		         for_each_template_parm_r,
10061 		         &pfd,
10062 		         pfd.visited);
10063 
10064   /* Clean up.  */
10065   if (!visited)
10066     {
10067       delete pfd.visited;
10068       pfd.visited = 0;
10069     }
10070 
10071   return result;
10072 }
10073 
10074 /* Returns true if T depends on any template parameter.  */
10075 
10076 int
uses_template_parms(tree t)10077 uses_template_parms (tree t)
10078 {
10079   if (t == NULL_TREE)
10080     return false;
10081 
10082   bool dependent_p;
10083   int saved_processing_template_decl;
10084 
10085   saved_processing_template_decl = processing_template_decl;
10086   if (!saved_processing_template_decl)
10087     processing_template_decl = 1;
10088   if (TYPE_P (t))
10089     dependent_p = dependent_type_p (t);
10090   else if (TREE_CODE (t) == TREE_VEC)
10091     dependent_p = any_dependent_template_arguments_p (t);
10092   else if (TREE_CODE (t) == TREE_LIST)
10093     dependent_p = (uses_template_parms (TREE_VALUE (t))
10094 		   || uses_template_parms (TREE_CHAIN (t)));
10095   else if (TREE_CODE (t) == TYPE_DECL)
10096     dependent_p = dependent_type_p (TREE_TYPE (t));
10097   else if (DECL_P (t)
10098 	   || EXPR_P (t)
10099 	   || TREE_CODE (t) == TEMPLATE_PARM_INDEX
10100 	   || TREE_CODE (t) == OVERLOAD
10101 	   || BASELINK_P (t)
10102 	   || identifier_p (t)
10103 	   || TREE_CODE (t) == TRAIT_EXPR
10104 	   || TREE_CODE (t) == CONSTRUCTOR
10105 	   || CONSTANT_CLASS_P (t))
10106     dependent_p = (type_dependent_expression_p (t)
10107 		   || value_dependent_expression_p (t));
10108   else
10109     {
10110       gcc_assert (t == error_mark_node);
10111       dependent_p = false;
10112     }
10113 
10114   processing_template_decl = saved_processing_template_decl;
10115 
10116   return dependent_p;
10117 }
10118 
10119 /* Returns true iff current_function_decl is an incompletely instantiated
10120    template.  Useful instead of processing_template_decl because the latter
10121    is set to 0 during instantiate_non_dependent_expr.  */
10122 
10123 bool
in_template_function(void)10124 in_template_function (void)
10125 {
10126   tree fn = current_function_decl;
10127   bool ret;
10128   ++processing_template_decl;
10129   ret = (fn && DECL_LANG_SPECIFIC (fn)
10130 	 && DECL_TEMPLATE_INFO (fn)
10131 	 && any_dependent_template_arguments_p (DECL_TI_ARGS (fn)));
10132   --processing_template_decl;
10133   return ret;
10134 }
10135 
10136 /* Returns true if T depends on any template parameter with level LEVEL.  */
10137 
10138 bool
uses_template_parms_level(tree t,int level)10139 uses_template_parms_level (tree t, int level)
10140 {
10141   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
10142 				 /*include_nondeduced_p=*/true);
10143 }
10144 
10145 /* Returns true if the signature of DECL depends on any template parameter from
10146    its enclosing class.  */
10147 
10148 bool
uses_outer_template_parms(tree decl)10149 uses_outer_template_parms (tree decl)
10150 {
10151   int depth = template_class_depth (CP_DECL_CONTEXT (decl));
10152   if (depth == 0)
10153     return false;
10154   if (for_each_template_parm (TREE_TYPE (decl), template_parm_outer_level,
10155 			      &depth, NULL, /*include_nondeduced_p=*/true))
10156     return true;
10157   if (PRIMARY_TEMPLATE_P (decl)
10158       && for_each_template_parm (INNERMOST_TEMPLATE_PARMS
10159 				 (DECL_TEMPLATE_PARMS (decl)),
10160 				 template_parm_outer_level,
10161 				 &depth, NULL, /*include_nondeduced_p=*/true))
10162     return true;
10163   tree ci = get_constraints (decl);
10164   if (ci)
10165     ci = CI_ASSOCIATED_CONSTRAINTS (ci);
10166   if (ci && for_each_template_parm (ci, template_parm_outer_level,
10167 				    &depth, NULL, /*nondeduced*/true))
10168     return true;
10169   return false;
10170 }
10171 
10172 /* Returns TRUE iff INST is an instantiation we don't need to do in an
10173    ill-formed translation unit, i.e. a variable or function that isn't
10174    usable in a constant expression.  */
10175 
10176 static inline bool
neglectable_inst_p(tree d)10177 neglectable_inst_p (tree d)
10178 {
10179   return (d && DECL_P (d)
10180 	  && !undeduced_auto_decl (d)
10181 	  && !(TREE_CODE (d) == FUNCTION_DECL ? DECL_DECLARED_CONSTEXPR_P (d)
10182 	       : decl_maybe_constant_var_p (d)));
10183 }
10184 
10185 /* Returns TRUE iff we should refuse to instantiate DECL because it's
10186    neglectable and instantiated from within an erroneous instantiation.  */
10187 
10188 static bool
limit_bad_template_recursion(tree decl)10189 limit_bad_template_recursion (tree decl)
10190 {
10191   struct tinst_level *lev = current_tinst_level;
10192   int errs = errorcount + sorrycount;
10193   if (lev == NULL || errs == 0 || !neglectable_inst_p (decl))
10194     return false;
10195 
10196   for (; lev; lev = lev->next)
10197     if (neglectable_inst_p (lev->maybe_get_node ()))
10198       break;
10199 
10200   return (lev && errs > lev->errors);
10201 }
10202 
10203 static int tinst_depth;
10204 extern int max_tinst_depth;
10205 int depth_reached;
10206 
10207 static GTY(()) struct tinst_level *last_error_tinst_level;
10208 
10209 /* We're starting to instantiate D; record the template instantiation context
10210    at LOC for diagnostics and to restore it later.  */
10211 
10212 static bool
push_tinst_level_loc(tree tldcl,tree targs,location_t loc)10213 push_tinst_level_loc (tree tldcl, tree targs, location_t loc)
10214 {
10215   struct tinst_level *new_level;
10216 
10217   if (tinst_depth >= max_tinst_depth)
10218     {
10219       /* Tell error.c not to try to instantiate any templates.  */
10220       at_eof = 2;
10221       fatal_error (input_location,
10222 		   "template instantiation depth exceeds maximum of %d"
10223                    " (use -ftemplate-depth= to increase the maximum)",
10224                    max_tinst_depth);
10225       return false;
10226     }
10227 
10228   /* If the current instantiation caused problems, don't let it instantiate
10229      anything else.  Do allow deduction substitution and decls usable in
10230      constant expressions.  */
10231   if (!targs && limit_bad_template_recursion (tldcl))
10232     return false;
10233 
10234   /* When not -quiet, dump template instantiations other than functions, since
10235      announce_function will take care of those.  */
10236   if (!quiet_flag && !targs
10237       && TREE_CODE (tldcl) != TREE_LIST
10238       && TREE_CODE (tldcl) != FUNCTION_DECL)
10239     fprintf (stderr, " %s", decl_as_string (tldcl, TFF_DECL_SPECIFIERS));
10240 
10241   new_level = tinst_level_freelist ().alloc ();
10242   new_level->tldcl = tldcl;
10243   new_level->targs = targs;
10244   new_level->locus = loc;
10245   new_level->errors = errorcount + sorrycount;
10246   new_level->next = NULL;
10247   new_level->refcount = 0;
10248   set_refcount_ptr (new_level->next, current_tinst_level);
10249   set_refcount_ptr (current_tinst_level, new_level);
10250 
10251   ++tinst_depth;
10252   if (GATHER_STATISTICS && (tinst_depth > depth_reached))
10253     depth_reached = tinst_depth;
10254 
10255   return true;
10256 }
10257 
10258 /* We're starting substitution of TMPL<ARGS>; record the template
10259    substitution context for diagnostics and to restore it later.  */
10260 
10261 static bool
push_tinst_level(tree tmpl,tree args)10262 push_tinst_level (tree tmpl, tree args)
10263 {
10264   return push_tinst_level_loc (tmpl, args, input_location);
10265 }
10266 
10267 /* We're starting to instantiate D; record INPUT_LOCATION and the
10268    template instantiation context for diagnostics and to restore it
10269    later.  */
10270 
10271 bool
push_tinst_level(tree d)10272 push_tinst_level (tree d)
10273 {
10274   return push_tinst_level_loc (d, input_location);
10275 }
10276 
10277 /* Likewise, but record LOC as the program location.  */
10278 
10279 bool
push_tinst_level_loc(tree d,location_t loc)10280 push_tinst_level_loc (tree d, location_t loc)
10281 {
10282   gcc_assert (TREE_CODE (d) != TREE_LIST);
10283   return push_tinst_level_loc (d, NULL, loc);
10284 }
10285 
10286 /* We're done instantiating this template; return to the instantiation
10287    context.  */
10288 
10289 void
pop_tinst_level(void)10290 pop_tinst_level (void)
10291 {
10292   /* Restore the filename and line number stashed away when we started
10293      this instantiation.  */
10294   input_location = current_tinst_level->locus;
10295   set_refcount_ptr (current_tinst_level, current_tinst_level->next);
10296   --tinst_depth;
10297 }
10298 
10299 /* We're instantiating a deferred template; restore the template
10300    instantiation context in which the instantiation was requested, which
10301    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
10302 
10303 static tree
reopen_tinst_level(struct tinst_level * level)10304 reopen_tinst_level (struct tinst_level *level)
10305 {
10306   struct tinst_level *t;
10307 
10308   tinst_depth = 0;
10309   for (t = level; t; t = t->next)
10310     ++tinst_depth;
10311 
10312   set_refcount_ptr (current_tinst_level, level);
10313   pop_tinst_level ();
10314   if (current_tinst_level)
10315     current_tinst_level->errors = errorcount+sorrycount;
10316   return level->maybe_get_node ();
10317 }
10318 
10319 /* Returns the TINST_LEVEL which gives the original instantiation
10320    context.  */
10321 
10322 struct tinst_level *
outermost_tinst_level(void)10323 outermost_tinst_level (void)
10324 {
10325   struct tinst_level *level = current_tinst_level;
10326   if (level)
10327     while (level->next)
10328       level = level->next;
10329   return level;
10330 }
10331 
10332 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
10333    vector of template arguments, as for tsubst.
10334 
10335    Returns an appropriate tsubst'd friend declaration.  */
10336 
10337 static tree
tsubst_friend_function(tree decl,tree args)10338 tsubst_friend_function (tree decl, tree args)
10339 {
10340   tree new_friend;
10341 
10342   if (TREE_CODE (decl) == FUNCTION_DECL
10343       && DECL_TEMPLATE_INSTANTIATION (decl)
10344       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
10345     /* This was a friend declared with an explicit template
10346        argument list, e.g.:
10347 
10348        friend void f<>(T);
10349 
10350        to indicate that f was a template instantiation, not a new
10351        function declaration.  Now, we have to figure out what
10352        instantiation of what template.  */
10353     {
10354       tree template_id, arglist, fns;
10355       tree new_args;
10356       tree tmpl;
10357       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
10358 
10359       /* Friend functions are looked up in the containing namespace scope.
10360 	 We must enter that scope, to avoid finding member functions of the
10361 	 current class with same name.  */
10362       push_nested_namespace (ns);
10363       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
10364 			 tf_warning_or_error, NULL_TREE,
10365 			 /*integral_constant_expression_p=*/false);
10366       pop_nested_namespace (ns);
10367       arglist = tsubst (DECL_TI_ARGS (decl), args,
10368 			tf_warning_or_error, NULL_TREE);
10369       template_id = lookup_template_function (fns, arglist);
10370 
10371       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
10372       tmpl = determine_specialization (template_id, new_friend,
10373 				       &new_args,
10374 				       /*need_member_template=*/0,
10375 				       TREE_VEC_LENGTH (args),
10376 				       tsk_none);
10377       return instantiate_template (tmpl, new_args, tf_error);
10378     }
10379 
10380   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
10381 
10382   /* The NEW_FRIEND will look like an instantiation, to the
10383      compiler, but is not an instantiation from the point of view of
10384      the language.  For example, we might have had:
10385 
10386      template <class T> struct S {
10387        template <class U> friend void f(T, U);
10388      };
10389 
10390      Then, in S<int>, template <class U> void f(int, U) is not an
10391      instantiation of anything.  */
10392   if (new_friend == error_mark_node)
10393     return error_mark_node;
10394 
10395   DECL_USE_TEMPLATE (new_friend) = 0;
10396   if (TREE_CODE (decl) == TEMPLATE_DECL)
10397     {
10398       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
10399       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
10400 	= DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
10401     }
10402 
10403   /* The mangled name for the NEW_FRIEND is incorrect.  The function
10404      is not a template instantiation and should not be mangled like
10405      one.  Therefore, we forget the mangling here; we'll recompute it
10406      later if we need it.  */
10407   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
10408     {
10409       SET_DECL_RTL (new_friend, NULL);
10410       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
10411     }
10412 
10413   if (DECL_NAMESPACE_SCOPE_P (new_friend))
10414     {
10415       tree old_decl;
10416       tree new_friend_template_info;
10417       tree new_friend_result_template_info;
10418       tree ns;
10419       int  new_friend_is_defn;
10420 
10421       /* We must save some information from NEW_FRIEND before calling
10422 	 duplicate decls since that function will free NEW_FRIEND if
10423 	 possible.  */
10424       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
10425       new_friend_is_defn =
10426 	    (DECL_INITIAL (DECL_TEMPLATE_RESULT
10427 			   (template_for_substitution (new_friend)))
10428 	     != NULL_TREE);
10429       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
10430 	{
10431 	  /* This declaration is a `primary' template.  */
10432 	  DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
10433 
10434 	  new_friend_result_template_info
10435 	    = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
10436 	}
10437       else
10438 	new_friend_result_template_info = NULL_TREE;
10439 
10440       /* Inside pushdecl_namespace_level, we will push into the
10441 	 current namespace. However, the friend function should go
10442 	 into the namespace of the template.  */
10443       ns = decl_namespace_context (new_friend);
10444       push_nested_namespace (ns);
10445       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
10446       pop_nested_namespace (ns);
10447 
10448       if (old_decl == error_mark_node)
10449 	return error_mark_node;
10450 
10451       if (old_decl != new_friend)
10452 	{
10453 	  /* This new friend declaration matched an existing
10454 	     declaration.  For example, given:
10455 
10456 	       template <class T> void f(T);
10457 	       template <class U> class C {
10458 		 template <class T> friend void f(T) {}
10459 	       };
10460 
10461 	     the friend declaration actually provides the definition
10462 	     of `f', once C has been instantiated for some type.  So,
10463 	     old_decl will be the out-of-class template declaration,
10464 	     while new_friend is the in-class definition.
10465 
10466 	     But, if `f' was called before this point, the
10467 	     instantiation of `f' will have DECL_TI_ARGS corresponding
10468 	     to `T' but not to `U', references to which might appear
10469 	     in the definition of `f'.  Previously, the most general
10470 	     template for an instantiation of `f' was the out-of-class
10471 	     version; now it is the in-class version.  Therefore, we
10472 	     run through all specialization of `f', adding to their
10473 	     DECL_TI_ARGS appropriately.  In particular, they need a
10474 	     new set of outer arguments, corresponding to the
10475 	     arguments for this class instantiation.
10476 
10477 	     The same situation can arise with something like this:
10478 
10479 	       friend void f(int);
10480 	       template <class T> class C {
10481 		 friend void f(T) {}
10482 	       };
10483 
10484 	     when `C<int>' is instantiated.  Now, `f(int)' is defined
10485 	     in the class.  */
10486 
10487 	  if (!new_friend_is_defn)
10488 	    /* On the other hand, if the in-class declaration does
10489 	       *not* provide a definition, then we don't want to alter
10490 	       existing definitions.  We can just leave everything
10491 	       alone.  */
10492 	    ;
10493 	  else
10494 	    {
10495 	      tree new_template = TI_TEMPLATE (new_friend_template_info);
10496 	      tree new_args = TI_ARGS (new_friend_template_info);
10497 
10498 	      /* Overwrite whatever template info was there before, if
10499 		 any, with the new template information pertaining to
10500 		 the declaration.  */
10501 	      DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
10502 
10503 	      if (TREE_CODE (old_decl) != TEMPLATE_DECL)
10504 		{
10505 		  /* We should have called reregister_specialization in
10506 		     duplicate_decls.  */
10507 		  gcc_assert (retrieve_specialization (new_template,
10508 						       new_args, 0)
10509 			      == old_decl);
10510 
10511 		  /* Instantiate it if the global has already been used.  */
10512 		  if (DECL_ODR_USED (old_decl))
10513 		    instantiate_decl (old_decl, /*defer_ok=*/true,
10514 				      /*expl_inst_class_mem_p=*/false);
10515 		}
10516 	      else
10517 		{
10518 		  tree t;
10519 
10520 		  /* Indicate that the old function template is a partial
10521 		     instantiation.  */
10522 		  DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
10523 		    = new_friend_result_template_info;
10524 
10525 		  gcc_assert (new_template
10526 			      == most_general_template (new_template));
10527 		  gcc_assert (new_template != old_decl);
10528 
10529 		  /* Reassign any specializations already in the hash table
10530 		     to the new more general template, and add the
10531 		     additional template args.  */
10532 		  for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
10533 		       t != NULL_TREE;
10534 		       t = TREE_CHAIN (t))
10535 		    {
10536 		      tree spec = TREE_VALUE (t);
10537 		      spec_entry elt;
10538 
10539 		      elt.tmpl = old_decl;
10540 		      elt.args = DECL_TI_ARGS (spec);
10541 		      elt.spec = NULL_TREE;
10542 
10543 		      decl_specializations->remove_elt (&elt);
10544 
10545 		      DECL_TI_ARGS (spec)
10546 			= add_outermost_template_args (new_args,
10547 						       DECL_TI_ARGS (spec));
10548 
10549 		      register_specialization
10550 			(spec, new_template, DECL_TI_ARGS (spec), true, 0);
10551 
10552 		    }
10553 		  DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
10554 		}
10555 	    }
10556 
10557 	  /* The information from NEW_FRIEND has been merged into OLD_DECL
10558 	     by duplicate_decls.  */
10559 	  new_friend = old_decl;
10560 	}
10561     }
10562   else
10563     {
10564       tree context = DECL_CONTEXT (new_friend);
10565       bool dependent_p;
10566 
10567       /* In the code
10568 	   template <class T> class C {
10569 	     template <class U> friend void C1<U>::f (); // case 1
10570 	     friend void C2<T>::f ();			 // case 2
10571 	   };
10572 	 we only need to make sure CONTEXT is a complete type for
10573 	 case 2.  To distinguish between the two cases, we note that
10574 	 CONTEXT of case 1 remains dependent type after tsubst while
10575 	 this isn't true for case 2.  */
10576       ++processing_template_decl;
10577       dependent_p = dependent_type_p (context);
10578       --processing_template_decl;
10579 
10580       if (!dependent_p
10581 	  && !complete_type_or_else (context, NULL_TREE))
10582 	return error_mark_node;
10583 
10584       if (COMPLETE_TYPE_P (context))
10585 	{
10586 	  tree fn = new_friend;
10587 	  /* do_friend adds the TEMPLATE_DECL for any member friend
10588 	     template even if it isn't a member template, i.e.
10589 	       template <class T> friend A<T>::f();
10590 	     Look through it in that case.  */
10591 	  if (TREE_CODE (fn) == TEMPLATE_DECL
10592 	      && !PRIMARY_TEMPLATE_P (fn))
10593 	    fn = DECL_TEMPLATE_RESULT (fn);
10594 	  /* Check to see that the declaration is really present, and,
10595 	     possibly obtain an improved declaration.  */
10596 	  fn = check_classfn (context, fn, NULL_TREE);
10597 
10598 	  if (fn)
10599 	    new_friend = fn;
10600 	}
10601     }
10602 
10603   return new_friend;
10604 }
10605 
10606 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
10607    template arguments, as for tsubst.
10608 
10609    Returns an appropriate tsubst'd friend type or error_mark_node on
10610    failure.  */
10611 
10612 static tree
tsubst_friend_class(tree friend_tmpl,tree args)10613 tsubst_friend_class (tree friend_tmpl, tree args)
10614 {
10615   tree tmpl;
10616 
10617   if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
10618     {
10619       tmpl = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
10620       return TREE_TYPE (tmpl);
10621     }
10622 
10623   tree context = CP_DECL_CONTEXT (friend_tmpl);
10624   if (TREE_CODE (context) == NAMESPACE_DECL)
10625     push_nested_namespace (context);
10626   else
10627     {
10628       context = tsubst (context, args, tf_error, NULL_TREE);
10629       push_nested_class (context);
10630     }
10631 
10632   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), /*prefer_type=*/false,
10633 			   /*non_class=*/false, /*block_p=*/false,
10634 			   /*namespaces_only=*/false, LOOKUP_HIDDEN);
10635 
10636   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
10637     {
10638       /* The friend template has already been declared.  Just
10639 	 check to see that the declarations match, and install any new
10640 	 default parameters.  We must tsubst the default parameters,
10641 	 of course.  We only need the innermost template parameters
10642 	 because that is all that redeclare_class_template will look
10643 	 at.  */
10644       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
10645 	  > TMPL_ARGS_DEPTH (args))
10646 	{
10647 	  tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
10648 					      args, tf_warning_or_error);
10649           location_t saved_input_location = input_location;
10650           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
10651           tree cons = get_constraints (tmpl);
10652           redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
10653           input_location = saved_input_location;
10654 	}
10655     }
10656   else
10657     {
10658       /* The friend template has not already been declared.  In this
10659 	 case, the instantiation of the template class will cause the
10660 	 injection of this template into the namespace scope.  */
10661       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
10662 
10663       if (tmpl != error_mark_node)
10664 	{
10665 	  /* The new TMPL is not an instantiation of anything, so we
10666 	     forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE
10667 	     for the new type because that is supposed to be the
10668 	     corresponding template decl, i.e., TMPL.  */
10669 	  DECL_USE_TEMPLATE (tmpl) = 0;
10670 	  DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
10671 	  CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
10672 	  CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
10673 	    = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
10674 
10675 	  /* It is hidden.  */
10676 	  retrofit_lang_decl (DECL_TEMPLATE_RESULT (tmpl));
10677 	  DECL_ANTICIPATED (tmpl)
10678 	    = DECL_ANTICIPATED (DECL_TEMPLATE_RESULT (tmpl)) = true;
10679 
10680 	  /* Inject this template into the enclosing namspace scope.  */
10681 	  tmpl = pushdecl_namespace_level (tmpl, true);
10682 	}
10683     }
10684 
10685   if (TREE_CODE (context) == NAMESPACE_DECL)
10686     pop_nested_namespace (context);
10687   else
10688     pop_nested_class ();
10689 
10690   return TREE_TYPE (tmpl);
10691 }
10692 
10693 /* Returns zero if TYPE cannot be completed later due to circularity.
10694    Otherwise returns one.  */
10695 
10696 static int
can_complete_type_without_circularity(tree type)10697 can_complete_type_without_circularity (tree type)
10698 {
10699   if (type == NULL_TREE || type == error_mark_node)
10700     return 0;
10701   else if (COMPLETE_TYPE_P (type))
10702     return 1;
10703   else if (TREE_CODE (type) == ARRAY_TYPE)
10704     return can_complete_type_without_circularity (TREE_TYPE (type));
10705   else if (CLASS_TYPE_P (type)
10706 	   && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
10707     return 0;
10708   else
10709     return 1;
10710 }
10711 
10712 static tree tsubst_omp_clauses (tree, enum c_omp_region_type, tree,
10713 				tsubst_flags_t, tree);
10714 
10715 /* Instantiate a single dependent attribute T (a TREE_LIST), and return either
10716    T or a new TREE_LIST, possibly a chain in the case of a pack expansion.  */
10717 
10718 static tree
tsubst_attribute(tree t,tree * decl_p,tree args,tsubst_flags_t complain,tree in_decl)10719 tsubst_attribute (tree t, tree *decl_p, tree args,
10720 		  tsubst_flags_t complain, tree in_decl)
10721 {
10722   gcc_assert (ATTR_IS_DEPENDENT (t));
10723 
10724   tree val = TREE_VALUE (t);
10725   if (val == NULL_TREE)
10726     /* Nothing to do.  */;
10727   else if ((flag_openmp || flag_openmp_simd)
10728 	   && is_attribute_p ("omp declare simd",
10729 			      get_attribute_name (t)))
10730     {
10731       tree clauses = TREE_VALUE (val);
10732       clauses = tsubst_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD, args,
10733 				    complain, in_decl);
10734       c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
10735       clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
10736       tree parms = DECL_ARGUMENTS (*decl_p);
10737       clauses
10738 	= c_omp_declare_simd_clauses_to_numbers (parms, clauses);
10739       if (clauses)
10740 	val = build_tree_list (NULL_TREE, clauses);
10741       else
10742 	val = NULL_TREE;
10743     }
10744   /* If the first attribute argument is an identifier, don't
10745      pass it through tsubst.  Attributes like mode, format,
10746      cleanup and several target specific attributes expect it
10747      unmodified.  */
10748   else if (attribute_takes_identifier_p (get_attribute_name (t)))
10749     {
10750       tree chain
10751 	= tsubst_expr (TREE_CHAIN (val), args, complain, in_decl,
10752 		       /*integral_constant_expression_p=*/false);
10753       if (chain != TREE_CHAIN (val))
10754 	val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
10755     }
10756   else if (PACK_EXPANSION_P (val))
10757     {
10758       /* An attribute pack expansion.  */
10759       tree purp = TREE_PURPOSE (t);
10760       tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
10761       if (pack == error_mark_node)
10762 	return error_mark_node;
10763       int len = TREE_VEC_LENGTH (pack);
10764       tree list = NULL_TREE;
10765       tree *q = &list;
10766       for (int i = 0; i < len; ++i)
10767 	{
10768 	  tree elt = TREE_VEC_ELT (pack, i);
10769 	  *q = build_tree_list (purp, elt);
10770 	  q = &TREE_CHAIN (*q);
10771 	}
10772       return list;
10773     }
10774   else
10775     val = tsubst_expr (val, args, complain, in_decl,
10776 		       /*integral_constant_expression_p=*/false);
10777 
10778   if (val != TREE_VALUE (t))
10779     return build_tree_list (TREE_PURPOSE (t), val);
10780   return t;
10781 }
10782 
10783 /* Instantiate any dependent attributes in ATTRIBUTES, returning either it
10784    unchanged or a new TREE_LIST chain.  */
10785 
10786 static tree
tsubst_attributes(tree attributes,tree args,tsubst_flags_t complain,tree in_decl)10787 tsubst_attributes (tree attributes, tree args,
10788 		   tsubst_flags_t complain, tree in_decl)
10789 {
10790   tree last_dep = NULL_TREE;
10791 
10792   for (tree t = attributes; t; t = TREE_CHAIN (t))
10793     if (ATTR_IS_DEPENDENT (t))
10794       {
10795 	last_dep = t;
10796 	attributes = copy_list (attributes);
10797 	break;
10798       }
10799 
10800   if (last_dep)
10801     for (tree *p = &attributes; *p; )
10802       {
10803 	tree t = *p;
10804 	if (ATTR_IS_DEPENDENT (t))
10805 	  {
10806 	    tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
10807 	    if (subst != t)
10808 	      {
10809 		*p = subst;
10810 		while (*p)
10811 		  p = &TREE_CHAIN (*p);
10812 		*p = TREE_CHAIN (t);
10813 		continue;
10814 	      }
10815 	  }
10816 	p = &TREE_CHAIN (*p);
10817       }
10818 
10819   return attributes;
10820 }
10821 
10822 /* Apply any attributes which had to be deferred until instantiation
10823    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
10824    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
10825 
10826 static void
apply_late_template_attributes(tree * decl_p,tree attributes,int attr_flags,tree args,tsubst_flags_t complain,tree in_decl)10827 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
10828 				tree args, tsubst_flags_t complain, tree in_decl)
10829 {
10830   tree last_dep = NULL_TREE;
10831   tree t;
10832   tree *p;
10833 
10834   if (attributes == NULL_TREE)
10835     return;
10836 
10837   if (DECL_P (*decl_p))
10838     {
10839       if (TREE_TYPE (*decl_p) == error_mark_node)
10840 	return;
10841       p = &DECL_ATTRIBUTES (*decl_p);
10842       /* DECL_ATTRIBUTES comes from copy_node in tsubst_decl, and is identical
10843          to our attributes parameter.  */
10844       gcc_assert (*p == attributes);
10845     }
10846   else
10847     {
10848       p = &TYPE_ATTRIBUTES (*decl_p);
10849       /* TYPE_ATTRIBUTES was set up (with abi_tag and may_alias) in
10850 	 lookup_template_class_1, and should be preserved.  */
10851       gcc_assert (*p != attributes);
10852       while (*p)
10853 	p = &TREE_CHAIN (*p);
10854     }
10855 
10856   for (t = attributes; t; t = TREE_CHAIN (t))
10857     if (ATTR_IS_DEPENDENT (t))
10858       {
10859 	last_dep = t;
10860 	attributes = copy_list (attributes);
10861 	break;
10862       }
10863 
10864   *p = attributes;
10865   if (last_dep)
10866     {
10867       tree late_attrs = NULL_TREE;
10868       tree *q = &late_attrs;
10869 
10870       for (; *p; )
10871 	{
10872 	  t = *p;
10873 	  if (ATTR_IS_DEPENDENT (t))
10874 	    {
10875 	      *p = TREE_CHAIN (t);
10876 	      TREE_CHAIN (t) = NULL_TREE;
10877 	      *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
10878 	      while (*q)
10879 		q = &TREE_CHAIN (*q);
10880 	    }
10881 	  else
10882 	    p = &TREE_CHAIN (t);
10883 	}
10884 
10885       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
10886     }
10887 }
10888 
10889 /* Perform (or defer) access check for typedefs that were referenced
10890    from within the template TMPL code.
10891    This is a subroutine of instantiate_decl and instantiate_class_template.
10892    TMPL is the template to consider and TARGS is the list of arguments of
10893    that template.  */
10894 
10895 static void
perform_typedefs_access_check(tree tmpl,tree targs)10896 perform_typedefs_access_check (tree tmpl, tree targs)
10897 {
10898   location_t saved_location;
10899   unsigned i;
10900   qualified_typedef_usage_t *iter;
10901 
10902   if (!tmpl
10903       || (!CLASS_TYPE_P (tmpl)
10904 	  && TREE_CODE (tmpl) != FUNCTION_DECL))
10905     return;
10906 
10907   saved_location = input_location;
10908   FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (tmpl), i, iter)
10909     {
10910       tree type_decl = iter->typedef_decl;
10911       tree type_scope = iter->context;
10912 
10913       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
10914 	continue;
10915 
10916       if (uses_template_parms (type_decl))
10917 	type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
10918       if (uses_template_parms (type_scope))
10919 	type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
10920 
10921       /* Make access check error messages point to the location
10922          of the use of the typedef.  */
10923       input_location = iter->locus;
10924       perform_or_defer_access_check (TYPE_BINFO (type_scope),
10925 				     type_decl, type_decl,
10926 				     tf_warning_or_error);
10927     }
10928     input_location = saved_location;
10929 }
10930 
10931 static tree
instantiate_class_template_1(tree type)10932 instantiate_class_template_1 (tree type)
10933 {
10934   tree templ, args, pattern, t, member;
10935   tree typedecl;
10936   tree pbinfo;
10937   tree base_list;
10938   unsigned int saved_maximum_field_alignment;
10939   tree fn_context;
10940 
10941   if (type == error_mark_node)
10942     return error_mark_node;
10943 
10944   if (COMPLETE_OR_OPEN_TYPE_P (type)
10945       || uses_template_parms (type))
10946     return type;
10947 
10948   /* Figure out which template is being instantiated.  */
10949   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
10950   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
10951 
10952   /* Mark the type as in the process of being defined.  */
10953   TYPE_BEING_DEFINED (type) = 1;
10954 
10955   /* We may be in the middle of deferred access check.  Disable
10956      it now.  */
10957   deferring_access_check_sentinel acs (dk_no_deferred);
10958 
10959   /* Determine what specialization of the original template to
10960      instantiate.  */
10961   t = most_specialized_partial_spec (type, tf_warning_or_error);
10962   if (t == error_mark_node)
10963     return error_mark_node;
10964   else if (t)
10965     {
10966       /* This TYPE is actually an instantiation of a partial
10967 	 specialization.  We replace the innermost set of ARGS with
10968 	 the arguments appropriate for substitution.  For example,
10969 	 given:
10970 
10971 	   template <class T> struct S {};
10972 	   template <class T> struct S<T*> {};
10973 
10974 	 and supposing that we are instantiating S<int*>, ARGS will
10975 	 presently be {int*} -- but we need {int}.  */
10976       pattern = TREE_TYPE (t);
10977       args = TREE_PURPOSE (t);
10978     }
10979   else
10980     {
10981       pattern = TREE_TYPE (templ);
10982       args = CLASSTYPE_TI_ARGS (type);
10983     }
10984 
10985   /* If the template we're instantiating is incomplete, then clearly
10986      there's nothing we can do.  */
10987   if (!COMPLETE_TYPE_P (pattern))
10988     {
10989       /* We can try again later.  */
10990       TYPE_BEING_DEFINED (type) = 0;
10991       return type;
10992     }
10993 
10994   /* If we've recursively instantiated too many templates, stop.  */
10995   if (! push_tinst_level (type))
10996     return type;
10997 
10998   int saved_unevaluated_operand = cp_unevaluated_operand;
10999   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
11000 
11001   fn_context = decl_function_context (TYPE_MAIN_DECL (type));
11002   /* Also avoid push_to_top_level for a lambda in an NSDMI.  */
11003   if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
11004     fn_context = error_mark_node;
11005   if (!fn_context)
11006     push_to_top_level ();
11007   else
11008     {
11009       cp_unevaluated_operand = 0;
11010       c_inhibit_evaluation_warnings = 0;
11011     }
11012   /* Use #pragma pack from the template context.  */
11013   saved_maximum_field_alignment = maximum_field_alignment;
11014   maximum_field_alignment = TYPE_PRECISION (pattern);
11015 
11016   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
11017 
11018   /* Set the input location to the most specialized template definition.
11019      This is needed if tsubsting causes an error.  */
11020   typedecl = TYPE_MAIN_DECL (pattern);
11021   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
11022     DECL_SOURCE_LOCATION (typedecl);
11023 
11024   TYPE_PACKED (type) = TYPE_PACKED (pattern);
11025   SET_TYPE_ALIGN (type, TYPE_ALIGN (pattern));
11026   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
11027   CLASSTYPE_NON_AGGREGATE (type) = CLASSTYPE_NON_AGGREGATE (pattern);
11028   if (ANON_AGGR_TYPE_P (pattern))
11029     SET_ANON_AGGR_TYPE_P (type);
11030   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
11031     {
11032       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
11033       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
11034       /* Adjust visibility for template arguments.  */
11035       determine_visibility (TYPE_MAIN_DECL (type));
11036     }
11037   if (CLASS_TYPE_P (type))
11038     CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
11039 
11040   pbinfo = TYPE_BINFO (pattern);
11041 
11042   /* We should never instantiate a nested class before its enclosing
11043      class; we need to look up the nested class by name before we can
11044      instantiate it, and that lookup should instantiate the enclosing
11045      class.  */
11046   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
11047 	      || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
11048 
11049   base_list = NULL_TREE;
11050   if (BINFO_N_BASE_BINFOS (pbinfo))
11051     {
11052       tree pbase_binfo;
11053       tree pushed_scope;
11054       int i;
11055 
11056       /* We must enter the scope containing the type, as that is where
11057 	 the accessibility of types named in dependent bases are
11058 	 looked up from.  */
11059       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
11060 
11061       /* Substitute into each of the bases to determine the actual
11062 	 basetypes.  */
11063       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
11064 	{
11065 	  tree base;
11066 	  tree access = BINFO_BASE_ACCESS (pbinfo, i);
11067           tree expanded_bases = NULL_TREE;
11068           int idx, len = 1;
11069 
11070           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
11071             {
11072               expanded_bases =
11073 		tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
11074 				       args, tf_error, NULL_TREE);
11075               if (expanded_bases == error_mark_node)
11076                 continue;
11077 
11078               len = TREE_VEC_LENGTH (expanded_bases);
11079             }
11080 
11081           for (idx = 0; idx < len; idx++)
11082             {
11083               if (expanded_bases)
11084                 /* Extract the already-expanded base class.  */
11085                 base = TREE_VEC_ELT (expanded_bases, idx);
11086               else
11087                 /* Substitute to figure out the base class.  */
11088                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
11089                                NULL_TREE);
11090 
11091               if (base == error_mark_node)
11092                 continue;
11093 
11094               base_list = tree_cons (access, base, base_list);
11095               if (BINFO_VIRTUAL_P (pbase_binfo))
11096                 TREE_TYPE (base_list) = integer_type_node;
11097             }
11098 	}
11099 
11100       /* The list is now in reverse order; correct that.  */
11101       base_list = nreverse (base_list);
11102 
11103       if (pushed_scope)
11104 	pop_scope (pushed_scope);
11105     }
11106   /* Now call xref_basetypes to set up all the base-class
11107      information.  */
11108   xref_basetypes (type, base_list);
11109 
11110   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
11111 				  (int) ATTR_FLAG_TYPE_IN_PLACE,
11112 				  args, tf_error, NULL_TREE);
11113   fixup_attribute_variants (type);
11114 
11115   /* Now that our base classes are set up, enter the scope of the
11116      class, so that name lookups into base classes, etc. will work
11117      correctly.  This is precisely analogous to what we do in
11118      begin_class_definition when defining an ordinary non-template
11119      class, except we also need to push the enclosing classes.  */
11120   push_nested_class (type);
11121 
11122   /* Now members are processed in the order of declaration.  */
11123   for (member = CLASSTYPE_DECL_LIST (pattern);
11124        member; member = TREE_CHAIN (member))
11125     {
11126       tree t = TREE_VALUE (member);
11127 
11128       if (TREE_PURPOSE (member))
11129 	{
11130 	  if (TYPE_P (t))
11131 	    {
11132 	      if (LAMBDA_TYPE_P (t))
11133 		/* A closure type for a lambda in an NSDMI or default argument.
11134 		   Ignore it; it will be regenerated when needed.  */
11135 		continue;
11136 
11137 	      /* Build new CLASSTYPE_NESTED_UTDS.  */
11138 
11139 	      tree newtag;
11140 	      bool class_template_p;
11141 
11142 	      class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
11143 				  && TYPE_LANG_SPECIFIC (t)
11144 				  && CLASSTYPE_IS_TEMPLATE (t));
11145 	      /* If the member is a class template, then -- even after
11146 		 substitution -- there may be dependent types in the
11147 		 template argument list for the class.  We increment
11148 		 PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
11149 		 that function will assume that no types are dependent
11150 		 when outside of a template.  */
11151 	      if (class_template_p)
11152 		++processing_template_decl;
11153 	      newtag = tsubst (t, args, tf_error, NULL_TREE);
11154 	      if (class_template_p)
11155 		--processing_template_decl;
11156 	      if (newtag == error_mark_node)
11157 		continue;
11158 
11159 	      if (TREE_CODE (newtag) != ENUMERAL_TYPE)
11160 		{
11161 		  tree name = TYPE_IDENTIFIER (t);
11162 
11163 		  if (class_template_p)
11164 		    /* Unfortunately, lookup_template_class sets
11165 		       CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
11166 		       instantiation (i.e., for the type of a member
11167 		       template class nested within a template class.)
11168 		       This behavior is required for
11169 		       maybe_process_partial_specialization to work
11170 		       correctly, but is not accurate in this case;
11171 		       the TAG is not an instantiation of anything.
11172 		       (The corresponding TEMPLATE_DECL is an
11173 		       instantiation, but the TYPE is not.) */
11174 		    CLASSTYPE_USE_TEMPLATE (newtag) = 0;
11175 
11176 		  /* Now, we call pushtag to put this NEWTAG into the scope of
11177 		     TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
11178 		     pushtag calling push_template_decl.  We don't have to do
11179 		     this for enums because it will already have been done in
11180 		     tsubst_enum.  */
11181 		  if (name)
11182 		    SET_IDENTIFIER_TYPE_VALUE (name, newtag);
11183 		  pushtag (name, newtag, /*tag_scope=*/ts_current);
11184 		}
11185 	    }
11186 	  else if (DECL_DECLARES_FUNCTION_P (t))
11187 	    {
11188 	      tree r;
11189 
11190 	      if (TREE_CODE (t) == TEMPLATE_DECL)
11191 		++processing_template_decl;
11192 	      r = tsubst (t, args, tf_error, NULL_TREE);
11193 	      if (TREE_CODE (t) == TEMPLATE_DECL)
11194 		--processing_template_decl;
11195 	      set_current_access_from_decl (r);
11196 	      finish_member_declaration (r);
11197 	      /* Instantiate members marked with attribute used.  */
11198 	      if (r != error_mark_node && DECL_PRESERVE_P (r))
11199 		mark_used (r);
11200 	      if (TREE_CODE (r) == FUNCTION_DECL
11201 		  && DECL_OMP_DECLARE_REDUCTION_P (r))
11202 		cp_check_omp_declare_reduction (r);
11203 	    }
11204 	  else if ((DECL_CLASS_TEMPLATE_P (t) || DECL_IMPLICIT_TYPEDEF_P (t))
11205 		   && LAMBDA_TYPE_P (TREE_TYPE (t)))
11206 	    /* A closure type for a lambda in an NSDMI or default argument.
11207 	       Ignore it; it will be regenerated when needed.  */;
11208 	  else
11209 	    {
11210 	      /* Build new TYPE_FIELDS.  */
11211               if (TREE_CODE (t) == STATIC_ASSERT)
11212                 {
11213                   tree condition;
11214 
11215 		  ++c_inhibit_evaluation_warnings;
11216 		  condition =
11217 		    tsubst_expr (STATIC_ASSERT_CONDITION (t), args,
11218 				 tf_warning_or_error, NULL_TREE,
11219 				 /*integral_constant_expression_p=*/true);
11220 		  --c_inhibit_evaluation_warnings;
11221 
11222                   finish_static_assert (condition,
11223                                         STATIC_ASSERT_MESSAGE (t),
11224                                         STATIC_ASSERT_SOURCE_LOCATION (t),
11225                                         /*member_p=*/true);
11226                 }
11227 	      else if (TREE_CODE (t) != CONST_DECL)
11228 		{
11229 		  tree r;
11230 		  tree vec = NULL_TREE;
11231 		  int len = 1;
11232 
11233 		  /* The file and line for this declaration, to
11234 		     assist in error message reporting.  Since we
11235 		     called push_tinst_level above, we don't need to
11236 		     restore these.  */
11237 		  input_location = DECL_SOURCE_LOCATION (t);
11238 
11239 		  if (TREE_CODE (t) == TEMPLATE_DECL)
11240 		    ++processing_template_decl;
11241 		  r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
11242 		  if (TREE_CODE (t) == TEMPLATE_DECL)
11243 		    --processing_template_decl;
11244 
11245 		  if (TREE_CODE (r) == TREE_VEC)
11246 		    {
11247 		      /* A capture pack became multiple fields.  */
11248 		      vec = r;
11249 		      len = TREE_VEC_LENGTH (vec);
11250 		    }
11251 
11252 		  for (int i = 0; i < len; ++i)
11253 		    {
11254 		      if (vec)
11255 			r = TREE_VEC_ELT (vec, i);
11256 		      if (VAR_P (r))
11257 			{
11258 			  /* In [temp.inst]:
11259 
11260 			     [t]he initialization (and any associated
11261 			     side-effects) of a static data member does
11262 			     not occur unless the static data member is
11263 			     itself used in a way that requires the
11264 			     definition of the static data member to
11265 			     exist.
11266 
11267 			     Therefore, we do not substitute into the
11268 			     initialized for the static data member here.  */
11269 			  finish_static_data_member_decl
11270 			    (r,
11271 			     /*init=*/NULL_TREE,
11272 			     /*init_const_expr_p=*/false,
11273 			     /*asmspec_tree=*/NULL_TREE,
11274 			     /*flags=*/0);
11275 			  /* Instantiate members marked with attribute used. */
11276 			  if (r != error_mark_node && DECL_PRESERVE_P (r))
11277 			    mark_used (r);
11278 			}
11279 		      else if (TREE_CODE (r) == FIELD_DECL)
11280 			{
11281 			  /* Determine whether R has a valid type and can be
11282 			     completed later.  If R is invalid, then its type
11283 			     is replaced by error_mark_node.  */
11284 			  tree rtype = TREE_TYPE (r);
11285 			  if (can_complete_type_without_circularity (rtype))
11286 			    complete_type (rtype);
11287 
11288 			  if (!complete_or_array_type_p (rtype))
11289 			    {
11290 			      /* If R's type couldn't be completed and
11291 				 it isn't a flexible array member (whose
11292 				 type is incomplete by definition) give
11293 				 an error.  */
11294 			      cxx_incomplete_type_error (r, rtype);
11295 			      TREE_TYPE (r) = error_mark_node;
11296 			    }
11297 			  else if (TREE_CODE (rtype) == ARRAY_TYPE
11298 				   && TYPE_DOMAIN (rtype) == NULL_TREE
11299 				   && (TREE_CODE (type) == UNION_TYPE
11300 				       || TREE_CODE (type) == QUAL_UNION_TYPE))
11301 			    {
11302 			      error ("flexible array member %qD in union", r);
11303 			      TREE_TYPE (r) = error_mark_node;
11304 			    }
11305 			}
11306 
11307 		      /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
11308 			 such a thing will already have been added to the field
11309 			 list by tsubst_enum in finish_member_declaration in the
11310 			 CLASSTYPE_NESTED_UTDS case above.  */
11311 		      if (!(TREE_CODE (r) == TYPE_DECL
11312 			    && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
11313 			    && DECL_ARTIFICIAL (r)))
11314 			{
11315 			  set_current_access_from_decl (r);
11316 			  finish_member_declaration (r);
11317 			}
11318 		    }
11319 		}
11320 	    }
11321 	}
11322       else
11323 	{
11324 	  if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
11325 	      || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11326 	    {
11327 	      /* Build new CLASSTYPE_FRIEND_CLASSES.  */
11328 
11329 	      tree friend_type = t;
11330 	      bool adjust_processing_template_decl = false;
11331 
11332 	      if (TREE_CODE (friend_type) == TEMPLATE_DECL)
11333 		{
11334 		  /* template <class T> friend class C;  */
11335 		  friend_type = tsubst_friend_class (friend_type, args);
11336 		  adjust_processing_template_decl = true;
11337 		}
11338 	      else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
11339 		{
11340 		  /* template <class T> friend class C::D;  */
11341 		  friend_type = tsubst (friend_type, args,
11342 					tf_warning_or_error, NULL_TREE);
11343 		  if (TREE_CODE (friend_type) == TEMPLATE_DECL)
11344 		    friend_type = TREE_TYPE (friend_type);
11345 		  adjust_processing_template_decl = true;
11346 		}
11347 	      else if (TREE_CODE (friend_type) == TYPENAME_TYPE
11348 		       || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
11349 		{
11350 		  /* This could be either
11351 
11352 		       friend class T::C;
11353 
11354 		     when dependent_type_p is false or
11355 
11356 		       template <class U> friend class T::C;
11357 
11358 		     otherwise.  */
11359 		  /* Bump processing_template_decl in case this is something like
11360 		     template <class T> friend struct A<T>::B.  */
11361 		  ++processing_template_decl;
11362 		  friend_type = tsubst (friend_type, args,
11363 					tf_warning_or_error, NULL_TREE);
11364 		  if (dependent_type_p (friend_type))
11365 		    adjust_processing_template_decl = true;
11366 		  --processing_template_decl;
11367 		}
11368 	      else if (TREE_CODE (friend_type) != BOUND_TEMPLATE_TEMPLATE_PARM
11369 		       && !CLASSTYPE_USE_TEMPLATE (friend_type)
11370 		       && TYPE_HIDDEN_P (friend_type))
11371 		{
11372 		  /* friend class C;
11373 
11374 		     where C hasn't been declared yet.  Let's lookup name
11375 		     from namespace scope directly, bypassing any name that
11376 		     come from dependent base class.  */
11377 		  tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
11378 
11379 		  /* The call to xref_tag_from_type does injection for friend
11380 		     classes.  */
11381 		  push_nested_namespace (ns);
11382 		  friend_type =
11383 		    xref_tag_from_type (friend_type, NULL_TREE,
11384 					/*tag_scope=*/ts_current);
11385 		  pop_nested_namespace (ns);
11386 		}
11387 	      else if (uses_template_parms (friend_type))
11388 		/* friend class C<T>;  */
11389 		friend_type = tsubst (friend_type, args,
11390 				      tf_warning_or_error, NULL_TREE);
11391 	      /* Otherwise it's
11392 
11393 		   friend class C;
11394 
11395 		 where C is already declared or
11396 
11397 		   friend class C<int>;
11398 
11399 		 We don't have to do anything in these cases.  */
11400 
11401 	      if (adjust_processing_template_decl)
11402 		/* Trick make_friend_class into realizing that the friend
11403 		   we're adding is a template, not an ordinary class.  It's
11404 		   important that we use make_friend_class since it will
11405 		   perform some error-checking and output cross-reference
11406 		   information.  */
11407 		++processing_template_decl;
11408 
11409 	      if (friend_type != error_mark_node)
11410 		make_friend_class (type, friend_type, /*complain=*/false);
11411 
11412 	      if (adjust_processing_template_decl)
11413 		--processing_template_decl;
11414 	    }
11415 	  else
11416 	    {
11417 	      /* Build new DECL_FRIENDLIST.  */
11418 	      tree r;
11419 
11420 	      /* The file and line for this declaration, to
11421 		 assist in error message reporting.  Since we
11422 		 called push_tinst_level above, we don't need to
11423 		 restore these.  */
11424 	      input_location = DECL_SOURCE_LOCATION (t);
11425 
11426 	      if (TREE_CODE (t) == TEMPLATE_DECL)
11427 		{
11428 		  ++processing_template_decl;
11429 		  push_deferring_access_checks (dk_no_check);
11430 		}
11431 
11432 	      r = tsubst_friend_function (t, args);
11433 	      add_friend (type, r, /*complain=*/false);
11434 	      if (TREE_CODE (t) == TEMPLATE_DECL)
11435 		{
11436 		  pop_deferring_access_checks ();
11437 		  --processing_template_decl;
11438 		}
11439 	    }
11440 	}
11441     }
11442 
11443   if (fn_context)
11444     {
11445       /* Restore these before substituting into the lambda capture
11446 	 initializers.  */
11447       cp_unevaluated_operand = saved_unevaluated_operand;
11448       c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
11449     }
11450 
11451   /* Set the file and line number information to whatever is given for
11452      the class itself.  This puts error messages involving generated
11453      implicit functions at a predictable point, and the same point
11454      that would be used for non-template classes.  */
11455   input_location = DECL_SOURCE_LOCATION (typedecl);
11456 
11457   unreverse_member_declarations (type);
11458   finish_struct_1 (type);
11459   TYPE_BEING_DEFINED (type) = 0;
11460 
11461   /* We don't instantiate default arguments for member functions.  14.7.1:
11462 
11463      The implicit instantiation of a class template specialization causes
11464      the implicit instantiation of the declarations, but not of the
11465      definitions or default arguments, of the class member functions,
11466      member classes, static data members and member templates....  */
11467 
11468   /* Some typedefs referenced from within the template code need to be access
11469      checked at template instantiation time, i.e now. These types were
11470      added to the template at parsing time. Let's get those and perform
11471      the access checks then.  */
11472   perform_typedefs_access_check (pattern, args);
11473   perform_deferred_access_checks (tf_warning_or_error);
11474   pop_nested_class ();
11475   maximum_field_alignment = saved_maximum_field_alignment;
11476   if (!fn_context)
11477     pop_from_top_level ();
11478   pop_tinst_level ();
11479 
11480   /* The vtable for a template class can be emitted in any translation
11481      unit in which the class is instantiated.  When there is no key
11482      method, however, finish_struct_1 will already have added TYPE to
11483      the keyed_classes.  */
11484   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
11485     vec_safe_push (keyed_classes, type);
11486 
11487   return type;
11488 }
11489 
11490 /* Wrapper for instantiate_class_template_1.  */
11491 
11492 tree
instantiate_class_template(tree type)11493 instantiate_class_template (tree type)
11494 {
11495   tree ret;
11496   timevar_push (TV_TEMPLATE_INST);
11497   ret = instantiate_class_template_1 (type);
11498   timevar_pop (TV_TEMPLATE_INST);
11499   return ret;
11500 }
11501 
11502 static tree
tsubst_template_arg(tree t,tree args,tsubst_flags_t complain,tree in_decl)11503 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11504 {
11505   tree r;
11506 
11507   if (!t)
11508     r = t;
11509   else if (TYPE_P (t))
11510     r = tsubst (t, args, complain, in_decl);
11511   else
11512     {
11513       if (!(complain & tf_warning))
11514 	++c_inhibit_evaluation_warnings;
11515       r = tsubst_expr (t, args, complain, in_decl,
11516 		       /*integral_constant_expression_p=*/true);
11517       if (!(complain & tf_warning))
11518 	--c_inhibit_evaluation_warnings;
11519     }
11520   return r;
11521 }
11522 
11523 /* Given a function parameter pack TMPL_PARM and some function parameters
11524    instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
11525    and set *SPEC_P to point at the next point in the list.  */
11526 
11527 tree
extract_fnparm_pack(tree tmpl_parm,tree * spec_p)11528 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
11529 {
11530   /* Collect all of the extra "packed" parameters into an
11531      argument pack.  */
11532   tree parmvec;
11533   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
11534   tree spec_parm = *spec_p;
11535   int i, len;
11536 
11537   for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
11538     if (tmpl_parm
11539 	&& !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
11540       break;
11541 
11542   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
11543   parmvec = make_tree_vec (len);
11544   spec_parm = *spec_p;
11545   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
11546     {
11547       tree elt = spec_parm;
11548       if (DECL_PACK_P (elt))
11549 	elt = make_pack_expansion (elt);
11550       TREE_VEC_ELT (parmvec, i) = elt;
11551     }
11552 
11553   /* Build the argument packs.  */
11554   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
11555   *spec_p = spec_parm;
11556 
11557   return argpack;
11558 }
11559 
11560 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
11561    NONTYPE_ARGUMENT_PACK.  */
11562 
11563 static tree
make_fnparm_pack(tree spec_parm)11564 make_fnparm_pack (tree spec_parm)
11565 {
11566   return extract_fnparm_pack (NULL_TREE, &spec_parm);
11567 }
11568 
11569 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
11570    pack expansion with no extra args, 2 if it has extra args, or 0
11571    if it is not a pack expansion.  */
11572 
11573 static int
argument_pack_element_is_expansion_p(tree arg_pack,int i)11574 argument_pack_element_is_expansion_p (tree arg_pack, int i)
11575 {
11576   tree vec = ARGUMENT_PACK_ARGS (arg_pack);
11577   if (i >= TREE_VEC_LENGTH (vec))
11578     return 0;
11579   tree elt = TREE_VEC_ELT (vec, i);
11580   if (DECL_P (elt))
11581     /* A decl pack is itself an expansion.  */
11582     elt = TREE_TYPE (elt);
11583   if (!PACK_EXPANSION_P (elt))
11584     return 0;
11585   if (PACK_EXPANSION_EXTRA_ARGS (elt))
11586     return 2;
11587   return 1;
11588 }
11589 
11590 
11591 /* Creates and return an ARGUMENT_PACK_SELECT tree node.  */
11592 
11593 static tree
make_argument_pack_select(tree arg_pack,unsigned index)11594 make_argument_pack_select (tree arg_pack, unsigned index)
11595 {
11596   tree aps = make_node (ARGUMENT_PACK_SELECT);
11597 
11598   ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
11599   ARGUMENT_PACK_SELECT_INDEX (aps) = index;
11600 
11601   return aps;
11602 }
11603 
11604 /*  This is a subroutine of tsubst_pack_expansion.
11605 
11606     It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
11607     mechanism to store the (non complete list of) arguments of the
11608     substitution and return a non substituted pack expansion, in order
11609     to wait for when we have enough arguments to really perform the
11610     substitution.  */
11611 
11612 static bool
use_pack_expansion_extra_args_p(tree parm_packs,int arg_pack_len,bool has_empty_arg)11613 use_pack_expansion_extra_args_p (tree parm_packs,
11614 				 int arg_pack_len,
11615 				 bool has_empty_arg)
11616 {
11617   /* If one pack has an expansion and another pack has a normal
11618      argument or if one pack has an empty argument and an another
11619      one hasn't then tsubst_pack_expansion cannot perform the
11620      substitution and need to fall back on the
11621      PACK_EXPANSION_EXTRA mechanism.  */
11622   if (parm_packs == NULL_TREE)
11623     return false;
11624   else if (has_empty_arg)
11625     return true;
11626 
11627   bool has_expansion_arg = false;
11628   for (int i = 0 ; i < arg_pack_len; ++i)
11629     {
11630       bool has_non_expansion_arg = false;
11631       for (tree parm_pack = parm_packs;
11632 	   parm_pack;
11633 	   parm_pack = TREE_CHAIN (parm_pack))
11634 	{
11635 	  tree arg = TREE_VALUE (parm_pack);
11636 
11637 	  int exp = argument_pack_element_is_expansion_p (arg, i);
11638 	  if (exp == 2)
11639 	    /* We can't substitute a pack expansion with extra args into
11640 	       our pattern.  */
11641 	    return true;
11642 	  else if (exp)
11643 	    has_expansion_arg = true;
11644 	  else
11645 	    has_non_expansion_arg = true;
11646 	}
11647 
11648       if (has_expansion_arg && has_non_expansion_arg)
11649 	return true;
11650     }
11651   return false;
11652 }
11653 
11654 /* [temp.variadic]/6 says that:
11655 
11656        The instantiation of a pack expansion [...]
11657        produces a list E1,E2, ..., En, where N is the number of elements
11658        in the pack expansion parameters.
11659 
11660    This subroutine of tsubst_pack_expansion produces one of these Ei.
11661 
11662    PATTERN is the pattern of the pack expansion.  PARM_PACKS is a
11663    TREE_LIST in which each TREE_PURPOSE is a parameter pack of
11664    PATTERN, and each TREE_VALUE is its corresponding argument pack.
11665    INDEX is the index 'i' of the element Ei to produce.  ARGS,
11666    COMPLAIN, and IN_DECL are the same parameters as for the
11667    tsubst_pack_expansion function.
11668 
11669    The function returns the resulting Ei upon successful completion,
11670    or error_mark_node.
11671 
11672    Note that this function possibly modifies the ARGS parameter, so
11673    it's the responsibility of the caller to restore it.  */
11674 
11675 static tree
gen_elem_of_pack_expansion_instantiation(tree pattern,tree parm_packs,unsigned index,tree args,tsubst_flags_t complain,tree in_decl)11676 gen_elem_of_pack_expansion_instantiation (tree pattern,
11677 					  tree parm_packs,
11678 					  unsigned index,
11679 					  tree args /* This parm gets
11680 						       modified.  */,
11681 					  tsubst_flags_t complain,
11682 					  tree in_decl)
11683 {
11684   tree t;
11685   bool ith_elem_is_expansion = false;
11686 
11687   /* For each parameter pack, change the substitution of the parameter
11688      pack to the ith argument in its argument pack, then expand the
11689      pattern.  */
11690   for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
11691     {
11692       tree parm = TREE_PURPOSE (pack);
11693       tree arg_pack = TREE_VALUE (pack);
11694       tree aps;			/* instance of ARGUMENT_PACK_SELECT.  */
11695 
11696       ith_elem_is_expansion |=
11697 	argument_pack_element_is_expansion_p (arg_pack, index);
11698 
11699       /* Select the Ith argument from the pack.  */
11700       if (TREE_CODE (parm) == PARM_DECL
11701 	  || VAR_P (parm)
11702 	  || TREE_CODE (parm) == FIELD_DECL)
11703 	{
11704 	  if (index == 0)
11705 	    {
11706 	      aps = make_argument_pack_select (arg_pack, index);
11707 	      if (!mark_used (parm, complain) && !(complain & tf_error))
11708 		return error_mark_node;
11709 	      register_local_specialization (aps, parm);
11710 	    }
11711 	  else
11712 	    aps = retrieve_local_specialization (parm);
11713 	}
11714       else
11715 	{
11716 	  int idx, level;
11717 	  template_parm_level_and_index (parm, &level, &idx);
11718 
11719 	  if (index == 0)
11720 	    {
11721 	      aps = make_argument_pack_select (arg_pack, index);
11722 	      /* Update the corresponding argument.  */
11723 	      TMPL_ARG (args, level, idx) = aps;
11724 	    }
11725 	  else
11726 	    /* Re-use the ARGUMENT_PACK_SELECT.  */
11727 	    aps = TMPL_ARG (args, level, idx);
11728 	}
11729       ARGUMENT_PACK_SELECT_INDEX (aps) = index;
11730     }
11731 
11732   /* Substitute into the PATTERN with the (possibly altered)
11733      arguments.  */
11734   if (pattern == in_decl)
11735     /* Expanding a fixed parameter pack from
11736        coerce_template_parameter_pack.  */
11737     t = tsubst_decl (pattern, args, complain);
11738   else if (pattern == error_mark_node)
11739     t = error_mark_node;
11740   else if (constraint_p (pattern))
11741     {
11742       if (processing_template_decl)
11743 	t = tsubst_constraint (pattern, args, complain, in_decl);
11744       else
11745 	t = (constraints_satisfied_p (pattern, args)
11746 	     ? boolean_true_node : boolean_false_node);
11747     }
11748   else if (!TYPE_P (pattern))
11749     t = tsubst_expr (pattern, args, complain, in_decl,
11750 		     /*integral_constant_expression_p=*/false);
11751   else
11752     t = tsubst (pattern, args, complain, in_decl);
11753 
11754   /*  If the Ith argument pack element is a pack expansion, then
11755       the Ith element resulting from the substituting is going to
11756       be a pack expansion as well.  */
11757   if (ith_elem_is_expansion)
11758     t = make_pack_expansion (t, complain);
11759 
11760   return t;
11761 }
11762 
11763 /* When the unexpanded parameter pack in a fold expression expands to an empty
11764    sequence, the value of the expression is as follows; the program is
11765    ill-formed if the operator is not listed in this table.
11766 
11767    &&	true
11768    ||	false
11769    ,	void()  */
11770 
11771 tree
expand_empty_fold(tree t,tsubst_flags_t complain)11772 expand_empty_fold (tree t, tsubst_flags_t complain)
11773 {
11774   tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
11775   if (!FOLD_EXPR_MODIFY_P (t))
11776     switch (code)
11777       {
11778       case TRUTH_ANDIF_EXPR:
11779 	return boolean_true_node;
11780       case TRUTH_ORIF_EXPR:
11781 	return boolean_false_node;
11782       case COMPOUND_EXPR:
11783 	return void_node;
11784       default:
11785 	break;
11786       }
11787 
11788   if (complain & tf_error)
11789     error_at (location_of (t),
11790 	      "fold of empty expansion over %O", code);
11791   return error_mark_node;
11792 }
11793 
11794 /* Given a fold-expression T and a current LEFT and RIGHT operand,
11795    form an expression that combines the two terms using the
11796    operator of T. */
11797 
11798 static tree
fold_expression(tree t,tree left,tree right,tsubst_flags_t complain)11799 fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
11800 {
11801   tree op = FOLD_EXPR_OP (t);
11802   tree_code code = (tree_code)TREE_INT_CST_LOW (op);
11803 
11804   // Handle compound assignment operators.
11805   if (FOLD_EXPR_MODIFY_P (t))
11806     return build_x_modify_expr (input_location, left, code, right, complain);
11807 
11808   switch (code)
11809     {
11810     case COMPOUND_EXPR:
11811       return build_x_compound_expr (input_location, left, right, complain);
11812     default:
11813       return build_x_binary_op (input_location, code,
11814                                 left, TREE_CODE (left),
11815                                 right, TREE_CODE (right),
11816                                 /*overload=*/NULL,
11817                                 complain);
11818     }
11819 }
11820 
11821 /* Substitute ARGS into the pack of a fold expression T. */
11822 
11823 static inline tree
tsubst_fold_expr_pack(tree t,tree args,tsubst_flags_t complain,tree in_decl)11824 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11825 {
11826   return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
11827 }
11828 
11829 /* Substitute ARGS into the pack of a fold expression T. */
11830 
11831 static inline tree
tsubst_fold_expr_init(tree t,tree args,tsubst_flags_t complain,tree in_decl)11832 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11833 {
11834   return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl, false);
11835 }
11836 
11837 /* Expand a PACK of arguments into a grouped as left fold.
11838    Given a pack containing elements A0, A1, ..., An and an
11839    operator @, this builds the expression:
11840 
11841       ((A0 @ A1) @ A2) ... @ An
11842 
11843    Note that PACK must not be empty.
11844 
11845    The operator is defined by the original fold expression T. */
11846 
11847 static tree
expand_left_fold(tree t,tree pack,tsubst_flags_t complain)11848 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
11849 {
11850   tree left = TREE_VEC_ELT (pack, 0);
11851   for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
11852     {
11853       tree right = TREE_VEC_ELT (pack, i);
11854       left = fold_expression (t, left, right, complain);
11855     }
11856   return left;
11857 }
11858 
11859 /* Substitute into a unary left fold expression. */
11860 
11861 static tree
tsubst_unary_left_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)11862 tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
11863                         tree in_decl)
11864 {
11865   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11866   if (pack == error_mark_node)
11867     return error_mark_node;
11868   if (PACK_EXPANSION_P (pack))
11869     {
11870       tree r = copy_node (t);
11871       FOLD_EXPR_PACK (r) = pack;
11872       return r;
11873     }
11874   if (TREE_VEC_LENGTH (pack) == 0)
11875     return expand_empty_fold (t, complain);
11876   else
11877     return expand_left_fold (t, pack, complain);
11878 }
11879 
11880 /* Substitute into a binary left fold expression.
11881 
11882    Do ths by building a single (non-empty) vector of argumnts and
11883    building the expression from those elements. */
11884 
11885 static tree
tsubst_binary_left_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)11886 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
11887                          tree in_decl)
11888 {
11889   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11890   if (pack == error_mark_node)
11891     return error_mark_node;
11892   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
11893   if (init == error_mark_node)
11894     return error_mark_node;
11895 
11896   if (PACK_EXPANSION_P (pack))
11897     {
11898       tree r = copy_node (t);
11899       FOLD_EXPR_PACK (r) = pack;
11900       FOLD_EXPR_INIT (r) = init;
11901       return r;
11902     }
11903 
11904   tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
11905   TREE_VEC_ELT (vec, 0) = init;
11906   for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
11907     TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
11908 
11909   return expand_left_fold (t, vec, complain);
11910 }
11911 
11912 /* Expand a PACK of arguments into a grouped as right fold.
11913    Given a pack containing elementns A0, A1, ..., and an
11914    operator @, this builds the expression:
11915 
11916       A0@ ... (An-2 @ (An-1 @ An))
11917 
11918    Note that PACK must not be empty.
11919 
11920    The operator is defined by the original fold expression T. */
11921 
11922 tree
expand_right_fold(tree t,tree pack,tsubst_flags_t complain)11923 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
11924 {
11925   // Build the expression.
11926   int n = TREE_VEC_LENGTH (pack);
11927   tree right = TREE_VEC_ELT (pack, n - 1);
11928   for (--n; n != 0; --n)
11929     {
11930       tree left = TREE_VEC_ELT (pack, n - 1);
11931       right = fold_expression (t, left, right, complain);
11932     }
11933   return right;
11934 }
11935 
11936 /* Substitute into a unary right fold expression. */
11937 
11938 static tree
tsubst_unary_right_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)11939 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
11940                          tree in_decl)
11941 {
11942   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11943   if (pack == error_mark_node)
11944     return error_mark_node;
11945   if (PACK_EXPANSION_P (pack))
11946     {
11947       tree r = copy_node (t);
11948       FOLD_EXPR_PACK (r) = pack;
11949       return r;
11950     }
11951   if (TREE_VEC_LENGTH (pack) == 0)
11952     return expand_empty_fold (t, complain);
11953   else
11954     return expand_right_fold (t, pack, complain);
11955 }
11956 
11957 /* Substitute into a binary right fold expression.
11958 
11959    Do ths by building a single (non-empty) vector of arguments and
11960    building the expression from those elements. */
11961 
11962 static tree
tsubst_binary_right_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)11963 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
11964                          tree in_decl)
11965 {
11966   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11967   if (pack == error_mark_node)
11968     return error_mark_node;
11969   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
11970   if (init == error_mark_node)
11971     return error_mark_node;
11972 
11973   if (PACK_EXPANSION_P (pack))
11974     {
11975       tree r = copy_node (t);
11976       FOLD_EXPR_PACK (r) = pack;
11977       FOLD_EXPR_INIT (r) = init;
11978       return r;
11979     }
11980 
11981   int n = TREE_VEC_LENGTH (pack);
11982   tree vec = make_tree_vec (n + 1);
11983   for (int i = 0; i < n; ++i)
11984     TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
11985   TREE_VEC_ELT (vec, n) = init;
11986 
11987   return expand_right_fold (t, vec, complain);
11988 }
11989 
11990 /* Walk through the pattern of a pack expansion, adding everything in
11991    local_specializations to a list.  */
11992 
11993 struct el_data
11994 {
11995   hash_set<tree> internal;
11996   tree extra;
11997   tsubst_flags_t complain;
11998 
el_datael_data11999   el_data (tsubst_flags_t c)
12000     : extra (NULL_TREE), complain (c) {}
12001 };
12002 static tree
extract_locals_r(tree * tp,int *,void * data_)12003 extract_locals_r (tree *tp, int */*walk_subtrees*/, void *data_)
12004 {
12005   el_data &data = *reinterpret_cast<el_data*>(data_);
12006   tree *extra = &data.extra;
12007   tsubst_flags_t complain = data.complain;
12008 
12009   if (TYPE_P (*tp) && typedef_variant_p (*tp))
12010     /* Remember local typedefs (85214).  */
12011     tp = &TYPE_NAME (*tp);
12012 
12013   if (TREE_CODE (*tp) == DECL_EXPR)
12014     {
12015       tree decl = DECL_EXPR_DECL (*tp);
12016       data.internal.add (decl);
12017       if (VAR_P (decl)
12018 	  && DECL_DECOMPOSITION_P (decl)
12019 	  && TREE_TYPE (decl) != error_mark_node)
12020 	{
12021 	  gcc_assert (DECL_NAME (decl) == NULL_TREE);
12022 	  for (tree decl2 = DECL_CHAIN (decl);
12023 	       decl2
12024 	       && VAR_P (decl2)
12025 	       && DECL_DECOMPOSITION_P (decl2)
12026 	       && DECL_NAME (decl2)
12027 	       && TREE_TYPE (decl2) != error_mark_node;
12028 	       decl2 = DECL_CHAIN (decl2))
12029 	    {
12030 	      gcc_assert (DECL_DECOMP_BASE (decl2) == decl);
12031 	      data.internal.add (decl2);
12032 	    }
12033 	}
12034     }
12035   else if (tree spec = retrieve_local_specialization (*tp))
12036     {
12037       if (data.internal.contains (*tp))
12038 	/* Don't mess with variables declared within the pattern.  */
12039 	return NULL_TREE;
12040       if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
12041 	{
12042 	  /* Maybe pull out the PARM_DECL for a partial instantiation.  */
12043 	  tree args = ARGUMENT_PACK_ARGS (spec);
12044 	  if (TREE_VEC_LENGTH (args) == 1)
12045 	    {
12046 	      tree elt = TREE_VEC_ELT (args, 0);
12047 	      if (PACK_EXPANSION_P (elt))
12048 		elt = PACK_EXPANSION_PATTERN (elt);
12049 	      if (DECL_PACK_P (elt))
12050 		spec = elt;
12051 	    }
12052 	  if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
12053 	    {
12054 	      /* Handle lambda capture here, since we aren't doing any
12055 		 substitution now, and so tsubst_copy won't call
12056 		 process_outer_var_ref.  */
12057 	      tree args = ARGUMENT_PACK_ARGS (spec);
12058 	      int len = TREE_VEC_LENGTH (args);
12059 	      for (int i = 0; i < len; ++i)
12060 		{
12061 		  tree arg = TREE_VEC_ELT (args, i);
12062 		  tree carg = arg;
12063 		  if (outer_automatic_var_p (arg))
12064 		    carg = process_outer_var_ref (arg, complain);
12065 		  if (carg != arg)
12066 		    {
12067 		      /* Make a new NONTYPE_ARGUMENT_PACK of the capture
12068 			 proxies.  */
12069 		      if (i == 0)
12070 			{
12071 			  spec = copy_node (spec);
12072 			  args = copy_node (args);
12073 			  SET_ARGUMENT_PACK_ARGS (spec, args);
12074 			  register_local_specialization (spec, *tp);
12075 			}
12076 		      TREE_VEC_ELT (args, i) = carg;
12077 		    }
12078 		}
12079 	    }
12080 	}
12081       if (outer_automatic_var_p (spec))
12082 	spec = process_outer_var_ref (spec, complain);
12083       *extra = tree_cons (*tp, spec, *extra);
12084     }
12085   return NULL_TREE;
12086 }
12087 static tree
extract_local_specs(tree pattern,tsubst_flags_t complain)12088 extract_local_specs (tree pattern, tsubst_flags_t complain)
12089 {
12090   el_data data (complain);
12091   cp_walk_tree_without_duplicates (&pattern, extract_locals_r, &data);
12092   return data.extra;
12093 }
12094 
12095 /* Extract any uses of local_specializations from PATTERN and add them to ARGS
12096    for use in PACK_EXPANSION_EXTRA_ARGS.  */
12097 
12098 tree
build_extra_args(tree pattern,tree args,tsubst_flags_t complain)12099 build_extra_args (tree pattern, tree args, tsubst_flags_t complain)
12100 {
12101   tree extra = args;
12102   if (local_specializations)
12103     if (tree locals = extract_local_specs (pattern, complain))
12104       extra = tree_cons (NULL_TREE, extra, locals);
12105   return extra;
12106 }
12107 
12108 /* Apply any local specializations from PACK_EXPANSION_EXTRA_ARGS and add the
12109    normal template args to ARGS.  */
12110 
12111 tree
add_extra_args(tree extra,tree args)12112 add_extra_args (tree extra, tree args)
12113 {
12114   if (extra && TREE_CODE (extra) == TREE_LIST)
12115     {
12116       for (tree elt = TREE_CHAIN (extra); elt; elt = TREE_CHAIN (elt))
12117 	{
12118 	  /* The partial instantiation involved local declarations collected in
12119 	     extract_local_specs; map from the general template to our local
12120 	     context.  */
12121 	  tree gen = TREE_PURPOSE (elt);
12122 	  tree inst = TREE_VALUE (elt);
12123 	  if (DECL_P (inst))
12124 	    if (tree local = retrieve_local_specialization (inst))
12125 	      inst = local;
12126 	  /* else inst is already a full instantiation of the pack.  */
12127 	  register_local_specialization (inst, gen);
12128 	}
12129       gcc_assert (!TREE_PURPOSE (extra));
12130       extra = TREE_VALUE (extra);
12131     }
12132   return add_to_template_args (extra, args);
12133 }
12134 
12135 /* Substitute ARGS into T, which is an pack expansion
12136    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
12137    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
12138    (if only a partial substitution could be performed) or
12139    ERROR_MARK_NODE if there was an error.  */
12140 tree
tsubst_pack_expansion(tree t,tree args,tsubst_flags_t complain,tree in_decl)12141 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
12142 		       tree in_decl)
12143 {
12144   tree pattern;
12145   tree pack, packs = NULL_TREE;
12146   bool unsubstituted_packs = false;
12147   bool unsubstituted_fn_pack = false;
12148   int i, len = -1;
12149   tree result;
12150   hash_map<tree, tree> *saved_local_specializations = NULL;
12151   bool need_local_specializations = false;
12152   int levels;
12153 
12154   gcc_assert (PACK_EXPANSION_P (t));
12155   pattern = PACK_EXPANSION_PATTERN (t);
12156 
12157   /* Add in any args remembered from an earlier partial instantiation.  */
12158   args = add_extra_args (PACK_EXPANSION_EXTRA_ARGS (t), args);
12159 
12160   levels = TMPL_ARGS_DEPTH (args);
12161 
12162   /* Determine the argument packs that will instantiate the parameter
12163      packs used in the expansion expression. While we're at it,
12164      compute the number of arguments to be expanded and make sure it
12165      is consistent.  */
12166   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
12167        pack = TREE_CHAIN (pack))
12168     {
12169       tree parm_pack = TREE_VALUE (pack);
12170       tree arg_pack = NULL_TREE;
12171       tree orig_arg = NULL_TREE;
12172       int level = 0;
12173 
12174       if (TREE_CODE (parm_pack) == BASES)
12175 	{
12176 	  gcc_assert (parm_pack == pattern);
12177 	  if (BASES_DIRECT (parm_pack))
12178 	    return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
12179 							args, complain,
12180 							in_decl, false),
12181 					   complain);
12182 	  else
12183 	    return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
12184 						 args, complain, in_decl,
12185 						 false), complain);
12186 	}
12187       else if (builtin_pack_call_p (parm_pack))
12188 	{
12189 	  /* ??? Support use in other patterns.  */
12190 	  gcc_assert (parm_pack == pattern);
12191 	  return expand_builtin_pack_call (parm_pack, args,
12192 					   complain, in_decl);
12193 	}
12194       else if (TREE_CODE (parm_pack) == PARM_DECL)
12195 	{
12196 	  /* We know we have correct local_specializations if this
12197 	     expansion is at function scope, or if we're dealing with a
12198 	     local parameter in a requires expression; for the latter,
12199 	     tsubst_requires_expr set it up appropriately.  */
12200 	  if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
12201 	    arg_pack = retrieve_local_specialization (parm_pack);
12202 	  else
12203 	    /* We can't rely on local_specializations for a parameter
12204 	       name used later in a function declaration (such as in a
12205 	       late-specified return type).  Even if it exists, it might
12206 	       have the wrong value for a recursive call.  */
12207 	    need_local_specializations = true;
12208 
12209 	  if (!arg_pack)
12210 	    {
12211 	      /* This parameter pack was used in an unevaluated context.  Just
12212 		 make a dummy decl, since it's only used for its type.  */
12213 	      ++cp_unevaluated_operand;
12214 	      arg_pack = tsubst_decl (parm_pack, args, complain);
12215 	      --cp_unevaluated_operand;
12216 	      if (arg_pack && DECL_PACK_P (arg_pack))
12217 		/* Partial instantiation of the parm_pack, we can't build
12218 		   up an argument pack yet.  */
12219 		arg_pack = NULL_TREE;
12220 	      else
12221 		arg_pack = make_fnparm_pack (arg_pack);
12222 	    }
12223 	  else if (argument_pack_element_is_expansion_p (arg_pack, 0))
12224 	    /* This argument pack isn't fully instantiated yet.  We set this
12225 	       flag rather than clear arg_pack because we do want to do the
12226 	       optimization below, and we don't want to substitute directly
12227 	       into the pattern (as that would expose a NONTYPE_ARGUMENT_PACK
12228 	       where it isn't expected).  */
12229 	    unsubstituted_fn_pack = true;
12230 	}
12231       else if (is_normal_capture_proxy (parm_pack))
12232 	{
12233 	  arg_pack = retrieve_local_specialization (parm_pack);
12234 	  if (argument_pack_element_is_expansion_p (arg_pack, 0))
12235 	    unsubstituted_fn_pack = true;
12236 	}
12237       else
12238         {
12239 	  int idx;
12240           template_parm_level_and_index (parm_pack, &level, &idx);
12241 
12242           if (level <= levels)
12243             arg_pack = TMPL_ARG (args, level, idx);
12244         }
12245 
12246       orig_arg = arg_pack;
12247       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12248 	arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12249 
12250       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
12251 	/* This can only happen if we forget to expand an argument
12252 	   pack somewhere else. Just return an error, silently.  */
12253 	{
12254 	  result = make_tree_vec (1);
12255 	  TREE_VEC_ELT (result, 0) = error_mark_node;
12256 	  return result;
12257 	}
12258 
12259       if (arg_pack)
12260         {
12261           int my_len =
12262             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
12263 
12264 	  /* Don't bother trying to do a partial substitution with
12265 	     incomplete packs; we'll try again after deduction.  */
12266           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
12267             return t;
12268 
12269           if (len < 0)
12270 	    len = my_len;
12271           else if (len != my_len
12272 		   && !unsubstituted_fn_pack)
12273             {
12274 	      if (!(complain & tf_error))
12275 		/* Fail quietly.  */;
12276               else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
12277                 error ("mismatched argument pack lengths while expanding %qT",
12278                        pattern);
12279               else
12280                 error ("mismatched argument pack lengths while expanding %qE",
12281                        pattern);
12282               return error_mark_node;
12283             }
12284 
12285           /* Keep track of the parameter packs and their corresponding
12286              argument packs.  */
12287           packs = tree_cons (parm_pack, arg_pack, packs);
12288           TREE_TYPE (packs) = orig_arg;
12289         }
12290       else
12291 	{
12292 	  /* We can't substitute for this parameter pack.  We use a flag as
12293 	     well as the missing_level counter because function parameter
12294 	     packs don't have a level.  */
12295 	  gcc_assert (processing_template_decl || is_auto (parm_pack));
12296 	  unsubstituted_packs = true;
12297 	}
12298     }
12299 
12300   /* If the expansion is just T..., return the matching argument pack, unless
12301      we need to call convert_from_reference on all the elements.  This is an
12302      important optimization; see c++/68422.  */
12303   if (!unsubstituted_packs
12304       && TREE_PURPOSE (packs) == pattern)
12305     {
12306       tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
12307 
12308       /* If the argument pack is a single pack expansion, pull it out.  */
12309       if (TREE_VEC_LENGTH (args) == 1
12310 	  && pack_expansion_args_count (args))
12311 	return TREE_VEC_ELT (args, 0);
12312 
12313       /* Types need no adjustment, nor does sizeof..., and if we still have
12314 	 some pack expansion args we won't do anything yet.  */
12315       if (TREE_CODE (t) == TYPE_PACK_EXPANSION
12316 	  || PACK_EXPANSION_SIZEOF_P (t)
12317 	  || pack_expansion_args_count (args))
12318 	return args;
12319       /* Also optimize expression pack expansions if we can tell that the
12320 	 elements won't have reference type.  */
12321       tree type = TREE_TYPE (pattern);
12322       if (type && TREE_CODE (type) != REFERENCE_TYPE
12323 	  && !PACK_EXPANSION_P (type)
12324 	  && !WILDCARD_TYPE_P (type))
12325 	return args;
12326       /* Otherwise use the normal path so we get convert_from_reference.  */
12327     }
12328 
12329   /* We cannot expand this expansion expression, because we don't have
12330      all of the argument packs we need.  */
12331   if (use_pack_expansion_extra_args_p (packs, len, unsubstituted_packs))
12332     {
12333       /* We got some full packs, but we can't substitute them in until we
12334 	 have values for all the packs.  So remember these until then.  */
12335 
12336       t = make_pack_expansion (pattern, complain);
12337       PACK_EXPANSION_EXTRA_ARGS (t)
12338 	= build_extra_args (pattern, args, complain);
12339       return t;
12340     }
12341   else if (unsubstituted_packs)
12342     {
12343       /* There were no real arguments, we're just replacing a parameter
12344 	 pack with another version of itself. Substitute into the
12345 	 pattern and return a PACK_EXPANSION_*. The caller will need to
12346 	 deal with that.  */
12347       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
12348 	t = tsubst_expr (pattern, args, complain, in_decl,
12349 			 /*integral_constant_expression_p=*/false);
12350       else
12351 	t = tsubst (pattern, args, complain, in_decl);
12352       t = make_pack_expansion (t, complain);
12353       return t;
12354     }
12355 
12356   gcc_assert (len >= 0);
12357 
12358   if (need_local_specializations)
12359     {
12360       /* We're in a late-specified return type, so create our own local
12361 	 specializations map; the current map is either NULL or (in the
12362 	 case of recursive unification) might have bindings that we don't
12363 	 want to use or alter.  */
12364       saved_local_specializations = local_specializations;
12365       local_specializations = new hash_map<tree, tree>;
12366     }
12367 
12368   /* For each argument in each argument pack, substitute into the
12369      pattern.  */
12370   result = make_tree_vec (len);
12371   tree elem_args = copy_template_args (args);
12372   for (i = 0; i < len; ++i)
12373     {
12374       t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
12375 						    i,
12376 						    elem_args, complain,
12377 						    in_decl);
12378       TREE_VEC_ELT (result, i) = t;
12379       if (t == error_mark_node)
12380 	{
12381 	  result = error_mark_node;
12382 	  break;
12383 	}
12384     }
12385 
12386   /* Update ARGS to restore the substitution from parameter packs to
12387      their argument packs.  */
12388   for (pack = packs; pack; pack = TREE_CHAIN (pack))
12389     {
12390       tree parm = TREE_PURPOSE (pack);
12391 
12392       if (TREE_CODE (parm) == PARM_DECL
12393 	  || VAR_P (parm)
12394 	  || TREE_CODE (parm) == FIELD_DECL)
12395         register_local_specialization (TREE_TYPE (pack), parm);
12396       else
12397         {
12398           int idx, level;
12399 
12400 	  if (TREE_VALUE (pack) == NULL_TREE)
12401 	    continue;
12402 
12403           template_parm_level_and_index (parm, &level, &idx);
12404 
12405           /* Update the corresponding argument.  */
12406           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
12407             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
12408               TREE_TYPE (pack);
12409           else
12410             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
12411         }
12412     }
12413 
12414   if (need_local_specializations)
12415     {
12416       delete local_specializations;
12417       local_specializations = saved_local_specializations;
12418     }
12419 
12420   /* If the dependent pack arguments were such that we end up with only a
12421      single pack expansion again, there's no need to keep it in a TREE_VEC.  */
12422   if (len == 1 && TREE_CODE (result) == TREE_VEC
12423       && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
12424     return TREE_VEC_ELT (result, 0);
12425 
12426   return result;
12427 }
12428 
12429 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
12430    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
12431    parameter packs; all parms generated from a function parameter pack will
12432    have the same DECL_PARM_INDEX.  */
12433 
12434 tree
get_pattern_parm(tree parm,tree tmpl)12435 get_pattern_parm (tree parm, tree tmpl)
12436 {
12437   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
12438   tree patparm;
12439 
12440   if (DECL_ARTIFICIAL (parm))
12441     {
12442       for (patparm = DECL_ARGUMENTS (pattern);
12443 	   patparm; patparm = DECL_CHAIN (patparm))
12444 	if (DECL_ARTIFICIAL (patparm)
12445 	    && DECL_NAME (parm) == DECL_NAME (patparm))
12446 	  break;
12447     }
12448   else
12449     {
12450       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
12451       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
12452       gcc_assert (DECL_PARM_INDEX (patparm)
12453 		  == DECL_PARM_INDEX (parm));
12454     }
12455 
12456   return patparm;
12457 }
12458 
12459 /* Make an argument pack out of the TREE_VEC VEC.  */
12460 
12461 static tree
make_argument_pack(tree vec)12462 make_argument_pack (tree vec)
12463 {
12464   tree pack;
12465   tree elt = TREE_VEC_ELT (vec, 0);
12466   if (TYPE_P (elt))
12467     pack = cxx_make_type (TYPE_ARGUMENT_PACK);
12468   else
12469     {
12470       pack = make_node (NONTYPE_ARGUMENT_PACK);
12471       TREE_CONSTANT (pack) = 1;
12472     }
12473   SET_ARGUMENT_PACK_ARGS (pack, vec);
12474   return pack;
12475 }
12476 
12477 /* Return an exact copy of template args T that can be modified
12478    independently.  */
12479 
12480 static tree
copy_template_args(tree t)12481 copy_template_args (tree t)
12482 {
12483   if (t == error_mark_node)
12484     return t;
12485 
12486   int len = TREE_VEC_LENGTH (t);
12487   tree new_vec = make_tree_vec (len);
12488 
12489   for (int i = 0; i < len; ++i)
12490     {
12491       tree elt = TREE_VEC_ELT (t, i);
12492       if (elt && TREE_CODE (elt) == TREE_VEC)
12493 	elt = copy_template_args (elt);
12494       TREE_VEC_ELT (new_vec, i) = elt;
12495     }
12496 
12497   NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
12498     = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
12499 
12500   return new_vec;
12501 }
12502 
12503 /* Substitute ARGS into the vector or list of template arguments T.  */
12504 
12505 static tree
tsubst_template_args(tree t,tree args,tsubst_flags_t complain,tree in_decl)12506 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12507 {
12508   tree orig_t = t;
12509   int len, need_new = 0, i, expanded_len_adjust = 0, out;
12510   tree *elts;
12511 
12512   if (t == error_mark_node)
12513     return error_mark_node;
12514 
12515   len = TREE_VEC_LENGTH (t);
12516   elts = XALLOCAVEC (tree, len);
12517 
12518   for (i = 0; i < len; i++)
12519     {
12520       tree orig_arg = TREE_VEC_ELT (t, i);
12521       tree new_arg;
12522 
12523       if (TREE_CODE (orig_arg) == TREE_VEC)
12524 	new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
12525       else if (PACK_EXPANSION_P (orig_arg))
12526         {
12527           /* Substitute into an expansion expression.  */
12528           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
12529 
12530           if (TREE_CODE (new_arg) == TREE_VEC)
12531             /* Add to the expanded length adjustment the number of
12532                expanded arguments. We subtract one from this
12533                measurement, because the argument pack expression
12534                itself is already counted as 1 in
12535                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
12536                the argument pack is empty.  */
12537             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
12538         }
12539       else if (ARGUMENT_PACK_P (orig_arg))
12540         {
12541           /* Substitute into each of the arguments.  */
12542           new_arg = TYPE_P (orig_arg)
12543             ? cxx_make_type (TREE_CODE (orig_arg))
12544             : make_node (TREE_CODE (orig_arg));
12545 
12546 	  tree pack_args = tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
12547 						 args, complain, in_decl);
12548           if (pack_args == error_mark_node)
12549             new_arg = error_mark_node;
12550 	  else
12551 	    SET_ARGUMENT_PACK_ARGS (new_arg, pack_args);
12552 
12553           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK)
12554 	    TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
12555         }
12556       else
12557 	new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
12558 
12559       if (new_arg == error_mark_node)
12560 	return error_mark_node;
12561 
12562       elts[i] = new_arg;
12563       if (new_arg != orig_arg)
12564 	need_new = 1;
12565     }
12566 
12567   if (!need_new)
12568     return t;
12569 
12570   /* Make space for the expanded arguments coming from template
12571      argument packs.  */
12572   t = make_tree_vec (len + expanded_len_adjust);
12573   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
12574      arguments for a member template.
12575      In that case each TREE_VEC in ORIG_T represents a level of template
12576      arguments, and ORIG_T won't carry any non defaulted argument count.
12577      It will rather be the nested TREE_VECs that will carry one.
12578      In other words, ORIG_T carries a non defaulted argument count only
12579      if it doesn't contain any nested TREE_VEC.  */
12580   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
12581     {
12582       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
12583       count += expanded_len_adjust;
12584       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
12585     }
12586   for (i = 0, out = 0; i < len; i++)
12587     {
12588       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
12589            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
12590           && TREE_CODE (elts[i]) == TREE_VEC)
12591         {
12592           int idx;
12593 
12594           /* Now expand the template argument pack "in place".  */
12595           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
12596             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
12597         }
12598       else
12599         {
12600           TREE_VEC_ELT (t, out) = elts[i];
12601           out++;
12602         }
12603     }
12604 
12605   return t;
12606 }
12607 
12608 /* Substitute ARGS into one level PARMS of template parameters.  */
12609 
12610 static tree
tsubst_template_parms_level(tree parms,tree args,tsubst_flags_t complain)12611 tsubst_template_parms_level (tree parms, tree args, tsubst_flags_t complain)
12612 {
12613   if (parms == error_mark_node)
12614     return error_mark_node;
12615 
12616   tree new_vec = make_tree_vec (TREE_VEC_LENGTH (parms));
12617 
12618   for (int i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
12619     {
12620       tree tuple = TREE_VEC_ELT (parms, i);
12621 
12622       if (tuple == error_mark_node)
12623 	continue;
12624 
12625       TREE_VEC_ELT (new_vec, i) =
12626 	tsubst_template_parm (tuple, args, complain);
12627     }
12628 
12629   return new_vec;
12630 }
12631 
12632 /* Return the result of substituting ARGS into the template parameters
12633    given by PARMS.  If there are m levels of ARGS and m + n levels of
12634    PARMS, then the result will contain n levels of PARMS.  For
12635    example, if PARMS is `template <class T> template <class U>
12636    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
12637    result will be `template <int*, double, class V>'.  */
12638 
12639 static tree
tsubst_template_parms(tree parms,tree args,tsubst_flags_t complain)12640 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
12641 {
12642   tree r = NULL_TREE;
12643   tree* new_parms;
12644 
12645   /* When substituting into a template, we must set
12646      PROCESSING_TEMPLATE_DECL as the template parameters may be
12647      dependent if they are based on one-another, and the dependency
12648      predicates are short-circuit outside of templates.  */
12649   ++processing_template_decl;
12650 
12651   for (new_parms = &r;
12652        parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
12653        new_parms = &(TREE_CHAIN (*new_parms)),
12654 	 parms = TREE_CHAIN (parms))
12655     {
12656       tree new_vec = tsubst_template_parms_level (TREE_VALUE (parms),
12657 						  args, complain);
12658       *new_parms =
12659 	tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
12660 			     - TMPL_ARGS_DEPTH (args)),
12661 		   new_vec, NULL_TREE);
12662     }
12663 
12664   --processing_template_decl;
12665 
12666   return r;
12667 }
12668 
12669 /* Return the result of substituting ARGS into one template parameter
12670    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
12671    parameter and which TREE_PURPOSE is the default argument of the
12672    template parameter.  */
12673 
12674 static tree
tsubst_template_parm(tree t,tree args,tsubst_flags_t complain)12675 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
12676 {
12677   tree default_value, parm_decl;
12678 
12679   if (args == NULL_TREE
12680       || t == NULL_TREE
12681       || t == error_mark_node)
12682     return t;
12683 
12684   gcc_assert (TREE_CODE (t) == TREE_LIST);
12685 
12686   default_value = TREE_PURPOSE (t);
12687   parm_decl = TREE_VALUE (t);
12688 
12689   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
12690   if (TREE_CODE (parm_decl) == PARM_DECL
12691       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
12692     parm_decl = error_mark_node;
12693   default_value = tsubst_template_arg (default_value, args,
12694 				       complain, NULL_TREE);
12695 
12696   return build_tree_list (default_value, parm_decl);
12697 }
12698 
12699 /* Substitute the ARGS into the indicated aggregate (or enumeration)
12700    type T.  If T is not an aggregate or enumeration type, it is
12701    handled as if by tsubst.  IN_DECL is as for tsubst.  If
12702    ENTERING_SCOPE is nonzero, T is the context for a template which
12703    we are presently tsubst'ing.  Return the substituted value.  */
12704 
12705 static tree
tsubst_aggr_type(tree t,tree args,tsubst_flags_t complain,tree in_decl,int entering_scope)12706 tsubst_aggr_type (tree t,
12707 		  tree args,
12708 		  tsubst_flags_t complain,
12709 		  tree in_decl,
12710 		  int entering_scope)
12711 {
12712   if (t == NULL_TREE)
12713     return NULL_TREE;
12714 
12715   switch (TREE_CODE (t))
12716     {
12717     case RECORD_TYPE:
12718       if (TYPE_PTRMEMFUNC_P (t))
12719 	return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
12720 
12721       /* Fall through.  */
12722     case ENUMERAL_TYPE:
12723     case UNION_TYPE:
12724       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
12725 	{
12726 	  tree argvec;
12727 	  tree context;
12728 	  tree r;
12729 	  int saved_unevaluated_operand;
12730 	  int saved_inhibit_evaluation_warnings;
12731 
12732 	  /* In "sizeof(X<I>)" we need to evaluate "I".  */
12733 	  saved_unevaluated_operand = cp_unevaluated_operand;
12734 	  cp_unevaluated_operand = 0;
12735 	  saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
12736 	  c_inhibit_evaluation_warnings = 0;
12737 
12738 	  /* First, determine the context for the type we are looking
12739 	     up.  */
12740 	  context = TYPE_CONTEXT (t);
12741 	  if (context && TYPE_P (context))
12742 	    {
12743 	      context = tsubst_aggr_type (context, args, complain,
12744 					  in_decl, /*entering_scope=*/1);
12745 	      /* If context is a nested class inside a class template,
12746 	         it may still need to be instantiated (c++/33959).  */
12747 	      context = complete_type (context);
12748 	    }
12749 
12750 	  /* Then, figure out what arguments are appropriate for the
12751 	     type we are trying to find.  For example, given:
12752 
12753 	       template <class T> struct S;
12754 	       template <class T, class U> void f(T, U) { S<U> su; }
12755 
12756 	     and supposing that we are instantiating f<int, double>,
12757 	     then our ARGS will be {int, double}, but, when looking up
12758 	     S we only want {double}.  */
12759 	  argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
12760 					 complain, in_decl);
12761 	  if (argvec == error_mark_node)
12762 	    r = error_mark_node;
12763 	  else
12764 	    {
12765 	      r = lookup_template_class (t, argvec, in_decl, context,
12766 					 entering_scope, complain);
12767 	      r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
12768 	    }
12769 
12770 	  cp_unevaluated_operand = saved_unevaluated_operand;
12771 	  c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
12772 
12773 	  return r;
12774 	}
12775       else
12776 	/* This is not a template type, so there's nothing to do.  */
12777 	return t;
12778 
12779     default:
12780       return tsubst (t, args, complain, in_decl);
12781     }
12782 }
12783 
12784 static GTY((cache)) tree_cache_map *defarg_inst;
12785 
12786 /* Substitute into the default argument ARG (a default argument for
12787    FN), which has the indicated TYPE.  */
12788 
12789 tree
tsubst_default_argument(tree fn,int parmnum,tree type,tree arg,tsubst_flags_t complain)12790 tsubst_default_argument (tree fn, int parmnum, tree type, tree arg,
12791 			 tsubst_flags_t complain)
12792 {
12793   tree saved_class_ptr = NULL_TREE;
12794   tree saved_class_ref = NULL_TREE;
12795   int errs = errorcount + sorrycount;
12796 
12797   /* This can happen in invalid code.  */
12798   if (TREE_CODE (arg) == DEFAULT_ARG)
12799     return arg;
12800 
12801   tree parm = FUNCTION_FIRST_USER_PARM (fn);
12802   parm = chain_index (parmnum, parm);
12803   tree parmtype = TREE_TYPE (parm);
12804   if (DECL_BY_REFERENCE (parm))
12805     parmtype = TREE_TYPE (parmtype);
12806   if (parmtype == error_mark_node)
12807     return error_mark_node;
12808 
12809   gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, parmtype));
12810 
12811   tree *slot;
12812   if (defarg_inst && (slot = defarg_inst->get (parm)))
12813     return *slot;
12814 
12815   /* This default argument came from a template.  Instantiate the
12816      default argument here, not in tsubst.  In the case of
12817      something like:
12818 
12819        template <class T>
12820        struct S {
12821 	 static T t();
12822 	 void f(T = t());
12823        };
12824 
12825      we must be careful to do name lookup in the scope of S<T>,
12826      rather than in the current class.  */
12827   push_access_scope (fn);
12828   /* The "this" pointer is not valid in a default argument.  */
12829   if (cfun)
12830     {
12831       saved_class_ptr = current_class_ptr;
12832       cp_function_chain->x_current_class_ptr = NULL_TREE;
12833       saved_class_ref = current_class_ref;
12834       cp_function_chain->x_current_class_ref = NULL_TREE;
12835     }
12836 
12837   start_lambda_scope (parm);
12838 
12839   push_deferring_access_checks(dk_no_deferred);
12840   /* The default argument expression may cause implicitly defined
12841      member functions to be synthesized, which will result in garbage
12842      collection.  We must treat this situation as if we were within
12843      the body of function so as to avoid collecting live data on the
12844      stack.  */
12845   ++function_depth;
12846   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
12847 		     complain, NULL_TREE,
12848 		     /*integral_constant_expression_p=*/false);
12849   --function_depth;
12850   pop_deferring_access_checks();
12851 
12852   finish_lambda_scope ();
12853 
12854   /* Restore the "this" pointer.  */
12855   if (cfun)
12856     {
12857       cp_function_chain->x_current_class_ptr = saved_class_ptr;
12858       cp_function_chain->x_current_class_ref = saved_class_ref;
12859     }
12860 
12861   if (errorcount+sorrycount > errs
12862       && (complain & tf_warning_or_error))
12863     inform (input_location,
12864 	    "  when instantiating default argument for call to %qD", fn);
12865 
12866   /* Make sure the default argument is reasonable.  */
12867   arg = check_default_argument (type, arg, complain);
12868 
12869   pop_access_scope (fn);
12870 
12871   if (arg != error_mark_node && !cp_unevaluated_operand)
12872     {
12873       if (!defarg_inst)
12874 	defarg_inst = tree_cache_map::create_ggc (37);
12875       defarg_inst->put (parm, arg);
12876     }
12877 
12878   return arg;
12879 }
12880 
12881 /* Substitute into all the default arguments for FN.  */
12882 
12883 static void
tsubst_default_arguments(tree fn,tsubst_flags_t complain)12884 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
12885 {
12886   tree arg;
12887   tree tmpl_args;
12888 
12889   tmpl_args = DECL_TI_ARGS (fn);
12890 
12891   /* If this function is not yet instantiated, we certainly don't need
12892      its default arguments.  */
12893   if (uses_template_parms (tmpl_args))
12894     return;
12895   /* Don't do this again for clones.  */
12896   if (DECL_CLONED_FUNCTION_P (fn))
12897     return;
12898 
12899   int i = 0;
12900   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
12901        arg;
12902        arg = TREE_CHAIN (arg), ++i)
12903     if (TREE_PURPOSE (arg))
12904       TREE_PURPOSE (arg) = tsubst_default_argument (fn, i,
12905 						    TREE_VALUE (arg),
12906 						    TREE_PURPOSE (arg),
12907 						    complain);
12908 }
12909 
12910 /* Subroutine of tsubst_decl for the case when T is a FUNCTION_DECL.  */
12911 
12912 static tree
tsubst_function_decl(tree t,tree args,tsubst_flags_t complain,tree lambda_fntype)12913 tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
12914 		      tree lambda_fntype)
12915 {
12916   tree gen_tmpl, argvec;
12917   hashval_t hash = 0;
12918   tree in_decl = t;
12919 
12920   /* Nobody should be tsubst'ing into non-template functions.  */
12921   gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
12922 
12923   if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
12924     {
12925       /* If T is not dependent, just return it.  */
12926       if (!uses_template_parms (DECL_TI_ARGS (t)))
12927 	return t;
12928 
12929       /* Calculate the most general template of which R is a
12930 	 specialization.  */
12931       gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
12932 
12933       /* We're substituting a lambda function under tsubst_lambda_expr but not
12934 	 directly from it; find the matching function we're already inside.
12935 	 But don't do this if T is a generic lambda with a single level of
12936 	 template parms, as in that case we're doing a normal instantiation. */
12937       if (LAMBDA_FUNCTION_P (t) && !lambda_fntype
12938 	  && (!generic_lambda_fn_p (t)
12939 	      || TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)) > 1))
12940 	return enclosing_instantiation_of (t);
12941 
12942       /* Calculate the complete set of arguments used to
12943 	 specialize R.  */
12944       argvec = tsubst_template_args (DECL_TI_ARGS
12945 				     (DECL_TEMPLATE_RESULT
12946 				      (DECL_TI_TEMPLATE (t))),
12947 				     args, complain, in_decl);
12948       if (argvec == error_mark_node)
12949 	return error_mark_node;
12950 
12951       /* Check to see if we already have this specialization.  */
12952       if (!lambda_fntype)
12953 	{
12954 	  hash = hash_tmpl_and_args (gen_tmpl, argvec);
12955 	  if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
12956 	    return spec;
12957 	}
12958 
12959       /* We can see more levels of arguments than parameters if
12960 	 there was a specialization of a member template, like
12961 	 this:
12962 
12963 	 template <class T> struct S { template <class U> void f(); }
12964 	 template <> template <class U> void S<int>::f(U);
12965 
12966 	 Here, we'll be substituting into the specialization,
12967 	 because that's where we can find the code we actually
12968 	 want to generate, but we'll have enough arguments for
12969 	 the most general template.
12970 
12971 	 We also deal with the peculiar case:
12972 
12973 	 template <class T> struct S {
12974 	   template <class U> friend void f();
12975 	 };
12976 	 template <class U> void f() {}
12977 	 template S<int>;
12978 	 template void f<double>();
12979 
12980 	 Here, the ARGS for the instantiation of will be {int,
12981 	 double}.  But, we only need as many ARGS as there are
12982 	 levels of template parameters in CODE_PATTERN.  We are
12983 	 careful not to get fooled into reducing the ARGS in
12984 	 situations like:
12985 
12986 	 template <class T> struct S { template <class U> void f(U); }
12987 	 template <class T> template <> void S<T>::f(int) {}
12988 
12989 	 which we can spot because the pattern will be a
12990 	 specialization in this case.  */
12991       int args_depth = TMPL_ARGS_DEPTH (args);
12992       int parms_depth =
12993 	TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
12994 
12995       if (args_depth > parms_depth && !DECL_TEMPLATE_SPECIALIZATION (t))
12996 	args = get_innermost_template_args (args, parms_depth);
12997     }
12998   else
12999     {
13000       /* This special case arises when we have something like this:
13001 
13002 	 template <class T> struct S {
13003 	 friend void f<int>(int, double);
13004 	 };
13005 
13006 	 Here, the DECL_TI_TEMPLATE for the friend declaration
13007 	 will be an IDENTIFIER_NODE.  We are being called from
13008 	 tsubst_friend_function, and we want only to create a
13009 	 new decl (R) with appropriate types so that we can call
13010 	 determine_specialization.  */
13011       gen_tmpl = NULL_TREE;
13012       argvec = NULL_TREE;
13013     }
13014 
13015   tree closure = (lambda_fntype ? TYPE_METHOD_BASETYPE (lambda_fntype)
13016 		  : NULL_TREE);
13017   tree ctx = closure ? closure : DECL_CONTEXT (t);
13018   bool member = ctx && TYPE_P (ctx);
13019 
13020   if (member && !closure)
13021     ctx = tsubst_aggr_type (ctx, args,
13022 			    complain, t, /*entering_scope=*/1);
13023 
13024   tree type = (lambda_fntype ? lambda_fntype
13025 	       : tsubst (TREE_TYPE (t), args,
13026 			 complain | tf_fndecl_type, in_decl));
13027   if (type == error_mark_node)
13028     return error_mark_node;
13029 
13030   /* If we hit excessive deduction depth, the type is bogus even if
13031      it isn't error_mark_node, so don't build a decl.  */
13032   if (excessive_deduction_depth)
13033     return error_mark_node;
13034 
13035   /* We do NOT check for matching decls pushed separately at this
13036      point, as they may not represent instantiations of this
13037      template, and in any case are considered separate under the
13038      discrete model.  */
13039   tree r = copy_decl (t);
13040   DECL_USE_TEMPLATE (r) = 0;
13041   TREE_TYPE (r) = type;
13042   /* Clear out the mangled name and RTL for the instantiation.  */
13043   SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
13044   SET_DECL_RTL (r, NULL);
13045   /* Leave DECL_INITIAL set on deleted instantiations.  */
13046   if (!DECL_DELETED_FN (r))
13047     DECL_INITIAL (r) = NULL_TREE;
13048   DECL_CONTEXT (r) = ctx;
13049 
13050   /* OpenMP UDRs have the only argument a reference to the declared
13051      type.  We want to diagnose if the declared type is a reference,
13052      which is invalid, but as references to references are usually
13053      quietly merged, diagnose it here.  */
13054   if (DECL_OMP_DECLARE_REDUCTION_P (t))
13055     {
13056       tree argtype
13057 	= TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
13058       argtype = tsubst (argtype, args, complain, in_decl);
13059       if (TREE_CODE (argtype) == REFERENCE_TYPE)
13060 	error_at (DECL_SOURCE_LOCATION (t),
13061 		  "reference type %qT in "
13062 		  "%<#pragma omp declare reduction%>", argtype);
13063       if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
13064 	DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
13065 					  argtype);
13066     }
13067 
13068   if (member && DECL_CONV_FN_P (r))
13069     /* Type-conversion operator.  Reconstruct the name, in
13070        case it's the name of one of the template's parameters.  */
13071     DECL_NAME (r) = make_conv_op_name (TREE_TYPE (type));
13072 
13073   tree parms = DECL_ARGUMENTS (t);
13074   if (closure)
13075     parms = DECL_CHAIN (parms);
13076   parms = tsubst (parms, args, complain, t);
13077   for (tree parm = parms; parm; parm = DECL_CHAIN (parm))
13078     DECL_CONTEXT (parm) = r;
13079   if (closure)
13080     {
13081       tree tparm = build_this_parm (r, closure, type_memfn_quals (type));
13082       DECL_CHAIN (tparm) = parms;
13083       parms = tparm;
13084     }
13085   DECL_ARGUMENTS (r) = parms;
13086   DECL_RESULT (r) = NULL_TREE;
13087 
13088   TREE_STATIC (r) = 0;
13089   TREE_PUBLIC (r) = TREE_PUBLIC (t);
13090   DECL_EXTERNAL (r) = 1;
13091   /* If this is an instantiation of a function with internal
13092      linkage, we already know what object file linkage will be
13093      assigned to the instantiation.  */
13094   DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
13095   DECL_DEFER_OUTPUT (r) = 0;
13096   DECL_CHAIN (r) = NULL_TREE;
13097   DECL_PENDING_INLINE_INFO (r) = 0;
13098   DECL_PENDING_INLINE_P (r) = 0;
13099   DECL_SAVED_TREE (r) = NULL_TREE;
13100   DECL_STRUCT_FUNCTION (r) = NULL;
13101   TREE_USED (r) = 0;
13102   /* We'll re-clone as appropriate in instantiate_template.  */
13103   DECL_CLONED_FUNCTION (r) = NULL_TREE;
13104 
13105   /* If we aren't complaining now, return on error before we register
13106      the specialization so that we'll complain eventually.  */
13107   if ((complain & tf_error) == 0
13108       && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
13109       && !grok_op_properties (r, /*complain=*/false))
13110     return error_mark_node;
13111 
13112   /* When instantiating a constrained member, substitute
13113      into the constraints to create a new constraint.  */
13114   if (tree ci = get_constraints (t))
13115     if (member)
13116       {
13117 	ci = tsubst_constraint_info (ci, argvec, complain, NULL_TREE);
13118 	set_constraints (r, ci);
13119       }
13120 
13121   if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
13122     SET_DECL_FRIEND_CONTEXT (r,
13123 			     tsubst (DECL_FRIEND_CONTEXT (t),
13124 				     args, complain, in_decl));
13125 
13126   /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
13127      this in the special friend case mentioned above where
13128      GEN_TMPL is NULL.  */
13129   if (gen_tmpl && !closure)
13130     {
13131       DECL_TEMPLATE_INFO (r)
13132 	= build_template_info (gen_tmpl, argvec);
13133       SET_DECL_IMPLICIT_INSTANTIATION (r);
13134 
13135       tree new_r
13136 	= register_specialization (r, gen_tmpl, argvec, false, hash);
13137       if (new_r != r)
13138 	/* We instantiated this while substituting into
13139 	   the type earlier (template/friend54.C).  */
13140 	return new_r;
13141 
13142       /* We're not supposed to instantiate default arguments
13143 	 until they are called, for a template.  But, for a
13144 	 declaration like:
13145 
13146 	 template <class T> void f ()
13147 	 { extern void g(int i = T()); }
13148 
13149 	 we should do the substitution when the template is
13150 	 instantiated.  We handle the member function case in
13151 	 instantiate_class_template since the default arguments
13152 	 might refer to other members of the class.  */
13153       if (!member
13154 	  && !PRIMARY_TEMPLATE_P (gen_tmpl)
13155 	  && !uses_template_parms (argvec))
13156 	tsubst_default_arguments (r, complain);
13157     }
13158   else
13159     DECL_TEMPLATE_INFO (r) = NULL_TREE;
13160 
13161   /* Copy the list of befriending classes.  */
13162   for (tree *friends = &DECL_BEFRIENDING_CLASSES (r);
13163        *friends;
13164        friends = &TREE_CHAIN (*friends))
13165     {
13166       *friends = copy_node (*friends);
13167       TREE_VALUE (*friends)
13168 	= tsubst (TREE_VALUE (*friends), args, complain, in_decl);
13169     }
13170 
13171   if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
13172     {
13173       maybe_retrofit_in_chrg (r);
13174       if (DECL_CONSTRUCTOR_P (r) && !grok_ctor_properties (ctx, r))
13175 	return error_mark_node;
13176       /* If this is an instantiation of a member template, clone it.
13177 	 If it isn't, that'll be handled by
13178 	 clone_constructors_and_destructors.  */
13179       if (PRIMARY_TEMPLATE_P (gen_tmpl))
13180 	clone_function_decl (r, /*update_methods=*/false);
13181     }
13182   else if ((complain & tf_error) != 0
13183 	   && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
13184 	   && !grok_op_properties (r, /*complain=*/true))
13185     return error_mark_node;
13186 
13187   /* Possibly limit visibility based on template args.  */
13188   DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
13189   if (DECL_VISIBILITY_SPECIFIED (t))
13190     {
13191       DECL_VISIBILITY_SPECIFIED (r) = 0;
13192       DECL_ATTRIBUTES (r)
13193 	= remove_attribute ("visibility", DECL_ATTRIBUTES (r));
13194     }
13195   determine_visibility (r);
13196   if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
13197       && !processing_template_decl)
13198     defaulted_late_check (r);
13199 
13200   apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
13201 				  args, complain, in_decl);
13202   return r;
13203 }
13204 
13205 /* Subroutine of tsubst_decl for the case when T is a TEMPLATE_DECL.  */
13206 
13207 static tree
tsubst_template_decl(tree t,tree args,tsubst_flags_t complain,tree lambda_fntype)13208 tsubst_template_decl (tree t, tree args, tsubst_flags_t complain,
13209 		      tree lambda_fntype)
13210 {
13211   /* We can get here when processing a member function template,
13212      member class template, or template template parameter.  */
13213   tree decl = DECL_TEMPLATE_RESULT (t);
13214   tree in_decl = t;
13215   tree spec;
13216   tree tmpl_args;
13217   tree full_args;
13218   tree r;
13219   hashval_t hash = 0;
13220 
13221   if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
13222     {
13223       /* Template template parameter is treated here.  */
13224       tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13225       if (new_type == error_mark_node)
13226 	r = error_mark_node;
13227       /* If we get a real template back, return it.  This can happen in
13228 	 the context of most_specialized_partial_spec.  */
13229       else if (TREE_CODE (new_type) == TEMPLATE_DECL)
13230 	r = new_type;
13231       else
13232 	/* The new TEMPLATE_DECL was built in
13233 	   reduce_template_parm_level.  */
13234 	r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
13235       return r;
13236     }
13237 
13238   if (!lambda_fntype)
13239     {
13240       /* We might already have an instance of this template.
13241 	 The ARGS are for the surrounding class type, so the
13242 	 full args contain the tsubst'd args for the context,
13243 	 plus the innermost args from the template decl.  */
13244       tmpl_args = DECL_CLASS_TEMPLATE_P (t)
13245 	? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
13246 	: DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
13247       /* Because this is a template, the arguments will still be
13248 	 dependent, even after substitution.  If
13249 	 PROCESSING_TEMPLATE_DECL is not set, the dependency
13250 	 predicates will short-circuit.  */
13251       ++processing_template_decl;
13252       full_args = tsubst_template_args (tmpl_args, args,
13253 					complain, in_decl);
13254       --processing_template_decl;
13255       if (full_args == error_mark_node)
13256 	return error_mark_node;
13257 
13258       /* If this is a default template template argument,
13259 	 tsubst might not have changed anything.  */
13260       if (full_args == tmpl_args)
13261 	return t;
13262 
13263       hash = hash_tmpl_and_args (t, full_args);
13264       spec = retrieve_specialization (t, full_args, hash);
13265       if (spec != NULL_TREE)
13266 	return spec;
13267     }
13268 
13269   /* Make a new template decl.  It will be similar to the
13270      original, but will record the current template arguments.
13271      We also create a new function declaration, which is just
13272      like the old one, but points to this new template, rather
13273      than the old one.  */
13274   r = copy_decl (t);
13275   gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
13276   DECL_CHAIN (r) = NULL_TREE;
13277 
13278   // Build new template info linking to the original template decl.
13279   if (!lambda_fntype)
13280     {
13281       DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
13282       SET_DECL_IMPLICIT_INSTANTIATION (r);
13283     }
13284   else
13285     DECL_TEMPLATE_INFO (r) = NULL_TREE;
13286 
13287   /* The template parameters for this new template are all the
13288      template parameters for the old template, except the
13289      outermost level of parameters.  */
13290   DECL_TEMPLATE_PARMS (r)
13291     = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
13292 			     complain);
13293 
13294   if (TREE_CODE (decl) == TYPE_DECL
13295       && !TYPE_DECL_ALIAS_P (decl))
13296     {
13297       tree new_type;
13298       ++processing_template_decl;
13299       new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13300       --processing_template_decl;
13301       if (new_type == error_mark_node)
13302 	return error_mark_node;
13303 
13304       TREE_TYPE (r) = new_type;
13305       /* For a partial specialization, we need to keep pointing to
13306 	 the primary template.  */
13307       if (!DECL_TEMPLATE_SPECIALIZATION (t))
13308 	CLASSTYPE_TI_TEMPLATE (new_type) = r;
13309       DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
13310       DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
13311       DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
13312     }
13313   else
13314     {
13315       tree new_decl;
13316       ++processing_template_decl;
13317       if (TREE_CODE (decl) == FUNCTION_DECL)
13318 	new_decl = tsubst_function_decl (decl, args, complain, lambda_fntype);
13319       else
13320 	new_decl = tsubst (decl, args, complain, in_decl);
13321       --processing_template_decl;
13322       if (new_decl == error_mark_node)
13323 	return error_mark_node;
13324 
13325       DECL_TEMPLATE_RESULT (r) = new_decl;
13326       TREE_TYPE (r) = TREE_TYPE (new_decl);
13327       DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
13328       if (lambda_fntype)
13329 	{
13330 	  tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (r));
13331 	  DECL_TEMPLATE_INFO (new_decl) = build_template_info (r, args);
13332 	}
13333       else
13334 	{
13335 	  DECL_TI_TEMPLATE (new_decl) = r;
13336 	  DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
13337 	}
13338     }
13339 
13340   DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
13341   DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
13342 
13343   if (PRIMARY_TEMPLATE_P (t))
13344     DECL_PRIMARY_TEMPLATE (r) = r;
13345 
13346   if (TREE_CODE (decl) != TYPE_DECL && !VAR_P (decl)
13347       && !lambda_fntype)
13348     /* Record this non-type partial instantiation.  */
13349     register_specialization (r, t,
13350 			     DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
13351 			     false, hash);
13352 
13353   return r;
13354 }
13355 
13356 /* True if FN is the op() for a lambda in an uninstantiated template.  */
13357 
13358 bool
lambda_fn_in_template_p(tree fn)13359 lambda_fn_in_template_p (tree fn)
13360 {
13361   if (!fn || !LAMBDA_FUNCTION_P (fn))
13362     return false;
13363   tree closure = DECL_CONTEXT (fn);
13364   return CLASSTYPE_TEMPLATE_INFO (closure) != NULL_TREE;
13365 }
13366 
13367 /* We're instantiating a variable from template function TCTX.  Return the
13368    corresponding current enclosing scope.  This gets complicated because lambda
13369    functions in templates are regenerated rather than instantiated, but generic
13370    lambda functions are subsequently instantiated.  */
13371 
13372 static tree
enclosing_instantiation_of(tree otctx)13373 enclosing_instantiation_of (tree otctx)
13374 {
13375   tree tctx = otctx;
13376   tree fn = current_function_decl;
13377   int lambda_count = 0;
13378 
13379   for (; tctx && lambda_fn_in_template_p (tctx);
13380        tctx = decl_function_context (tctx))
13381     ++lambda_count;
13382   for (; fn; fn = decl_function_context (fn))
13383     {
13384       tree ofn = fn;
13385       int flambda_count = 0;
13386       for (; flambda_count < lambda_count && fn && LAMBDA_FUNCTION_P (fn);
13387 	   fn = decl_function_context (fn))
13388 	++flambda_count;
13389       if ((fn && DECL_TEMPLATE_INFO (fn))
13390 	  ? most_general_template (fn) != most_general_template (tctx)
13391 	  : fn != tctx)
13392 	continue;
13393       gcc_assert (DECL_NAME (ofn) == DECL_NAME (otctx)
13394 		  || DECL_CONV_FN_P (ofn));
13395       return ofn;
13396     }
13397   gcc_unreachable ();
13398 }
13399 
13400 /* Substitute the ARGS into the T, which is a _DECL.  Return the
13401    result of the substitution.  Issue error and warning messages under
13402    control of COMPLAIN.  */
13403 
13404 static tree
tsubst_decl(tree t,tree args,tsubst_flags_t complain)13405 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
13406 {
13407 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
13408   location_t saved_loc;
13409   tree r = NULL_TREE;
13410   tree in_decl = t;
13411   hashval_t hash = 0;
13412 
13413   /* Set the filename and linenumber to improve error-reporting.  */
13414   saved_loc = input_location;
13415   input_location = DECL_SOURCE_LOCATION (t);
13416 
13417   switch (TREE_CODE (t))
13418     {
13419     case TEMPLATE_DECL:
13420       r = tsubst_template_decl (t, args, complain, /*lambda*/NULL_TREE);
13421       break;
13422 
13423     case FUNCTION_DECL:
13424       r = tsubst_function_decl (t, args, complain, /*lambda*/NULL_TREE);
13425       break;
13426 
13427     case PARM_DECL:
13428       {
13429 	tree type = NULL_TREE;
13430         int i, len = 1;
13431         tree expanded_types = NULL_TREE;
13432         tree prev_r = NULL_TREE;
13433         tree first_r = NULL_TREE;
13434 
13435         if (DECL_PACK_P (t))
13436           {
13437             /* If there is a local specialization that isn't a
13438                parameter pack, it means that we're doing a "simple"
13439                substitution from inside tsubst_pack_expansion. Just
13440                return the local specialization (which will be a single
13441                parm).  */
13442             tree spec = retrieve_local_specialization (t);
13443             if (spec
13444                 && TREE_CODE (spec) == PARM_DECL
13445                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
13446               RETURN (spec);
13447 
13448             /* Expand the TYPE_PACK_EXPANSION that provides the types for
13449                the parameters in this function parameter pack.  */
13450             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
13451 						    complain, in_decl);
13452             if (TREE_CODE (expanded_types) == TREE_VEC)
13453               {
13454                 len = TREE_VEC_LENGTH (expanded_types);
13455 
13456                 /* Zero-length parameter packs are boring. Just substitute
13457                    into the chain.  */
13458 		if (len == 0 && !cp_unevaluated_operand)
13459                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
13460 				  TREE_CHAIN (t)));
13461               }
13462             else
13463               {
13464                 /* All we did was update the type. Make a note of that.  */
13465                 type = expanded_types;
13466                 expanded_types = NULL_TREE;
13467               }
13468           }
13469 
13470         /* Loop through all of the parameters we'll build. When T is
13471            a function parameter pack, LEN is the number of expanded
13472            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
13473         r = NULL_TREE;
13474         for (i = 0; i < len; ++i)
13475           {
13476             prev_r = r;
13477             r = copy_node (t);
13478             if (DECL_TEMPLATE_PARM_P (t))
13479               SET_DECL_TEMPLATE_PARM_P (r);
13480 
13481             if (expanded_types)
13482               /* We're on the Ith parameter of the function parameter
13483                  pack.  */
13484               {
13485                 /* Get the Ith type.  */
13486                 type = TREE_VEC_ELT (expanded_types, i);
13487 
13488 		/* Rename the parameter to include the index.  */
13489 		DECL_NAME (r)
13490 		  = make_ith_pack_parameter_name (DECL_NAME (r), i);
13491               }
13492             else if (!type)
13493               /* We're dealing with a normal parameter.  */
13494               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13495 
13496             type = type_decays_to (type);
13497             TREE_TYPE (r) = type;
13498             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
13499 
13500             if (DECL_INITIAL (r))
13501               {
13502                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
13503                   DECL_INITIAL (r) = TREE_TYPE (r);
13504                 else
13505                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
13506                                              complain, in_decl);
13507               }
13508 
13509             DECL_CONTEXT (r) = NULL_TREE;
13510 
13511             if (!DECL_TEMPLATE_PARM_P (r))
13512               DECL_ARG_TYPE (r) = type_passed_as (type);
13513 
13514 	    apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
13515 					    args, complain, in_decl);
13516 
13517             /* Keep track of the first new parameter we
13518                generate. That's what will be returned to the
13519                caller.  */
13520             if (!first_r)
13521               first_r = r;
13522 
13523             /* Build a proper chain of parameters when substituting
13524                into a function parameter pack.  */
13525             if (prev_r)
13526               DECL_CHAIN (prev_r) = r;
13527           }
13528 
13529 	/* If cp_unevaluated_operand is set, we're just looking for a
13530 	   single dummy parameter, so don't keep going.  */
13531 	if (DECL_CHAIN (t) && !cp_unevaluated_operand)
13532 	  DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
13533 				   complain, DECL_CHAIN (t));
13534 
13535         /* FIRST_R contains the start of the chain we've built.  */
13536         r = first_r;
13537       }
13538       break;
13539 
13540     case FIELD_DECL:
13541       {
13542 	tree type = NULL_TREE;
13543 	tree vec = NULL_TREE;
13544 	tree expanded_types = NULL_TREE;
13545 	int len = 1;
13546 
13547 	if (PACK_EXPANSION_P (TREE_TYPE (t)))
13548 	  {
13549 	    /* This field is a lambda capture pack.  Return a TREE_VEC of
13550 	       the expanded fields to instantiate_class_template_1.  */
13551             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
13552 						    complain, in_decl);
13553             if (TREE_CODE (expanded_types) == TREE_VEC)
13554               {
13555                 len = TREE_VEC_LENGTH (expanded_types);
13556 		vec = make_tree_vec (len);
13557               }
13558             else
13559               {
13560                 /* All we did was update the type. Make a note of that.  */
13561                 type = expanded_types;
13562                 expanded_types = NULL_TREE;
13563               }
13564 	  }
13565 
13566 	for (int i = 0; i < len; ++i)
13567 	  {
13568 	    r = copy_decl (t);
13569 	    if (expanded_types)
13570 	      {
13571 		type = TREE_VEC_ELT (expanded_types, i);
13572 		DECL_NAME (r)
13573 		  = make_ith_pack_parameter_name (DECL_NAME (r), i);
13574 	      }
13575             else if (!type)
13576               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13577 
13578 	    if (type == error_mark_node)
13579 	      RETURN (error_mark_node);
13580 	    TREE_TYPE (r) = type;
13581 	    cp_apply_type_quals_to_decl (cp_type_quals (type), r);
13582 
13583 	    if (DECL_C_BIT_FIELD (r))
13584 	      /* For bit-fields, DECL_BIT_FIELD_REPRESENTATIVE gives the
13585 		 number of bits.  */
13586 	      DECL_BIT_FIELD_REPRESENTATIVE (r)
13587 		= tsubst_expr (DECL_BIT_FIELD_REPRESENTATIVE (t), args,
13588 			       complain, in_decl,
13589 			       /*integral_constant_expression_p=*/true);
13590 	    if (DECL_INITIAL (t))
13591 	      {
13592 		/* Set up DECL_TEMPLATE_INFO so that we can get at the
13593 		   NSDMI in perform_member_init.  Still set DECL_INITIAL
13594 		   so that we know there is one.  */
13595 		DECL_INITIAL (r) = void_node;
13596 		gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
13597 		retrofit_lang_decl (r);
13598 		DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
13599 	      }
13600 	    /* We don't have to set DECL_CONTEXT here; it is set by
13601 	       finish_member_declaration.  */
13602 	    DECL_CHAIN (r) = NULL_TREE;
13603 
13604 	    apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
13605 					    args, complain, in_decl);
13606 
13607 	    if (vec)
13608 	      TREE_VEC_ELT (vec, i) = r;
13609 	  }
13610 
13611 	if (vec)
13612 	  r = vec;
13613       }
13614       break;
13615 
13616     case USING_DECL:
13617       /* We reach here only for member using decls.  We also need to check
13618 	 uses_template_parms because DECL_DEPENDENT_P is not set for a
13619 	 using-declaration that designates a member of the current
13620 	 instantiation (c++/53549).  */
13621       if (DECL_DEPENDENT_P (t)
13622 	  || uses_template_parms (USING_DECL_SCOPE (t)))
13623 	{
13624 	  tree scope = USING_DECL_SCOPE (t);
13625 	  tree name = tsubst_copy (DECL_NAME (t), args, complain, in_decl);
13626 	  if (PACK_EXPANSION_P (scope))
13627 	    {
13628 	      tree vec = tsubst_pack_expansion (scope, args, complain, in_decl);
13629 	      int len = TREE_VEC_LENGTH (vec);
13630 	      r = make_tree_vec (len);
13631 	      for (int i = 0; i < len; ++i)
13632 		{
13633 		  tree escope = TREE_VEC_ELT (vec, i);
13634 		  tree elt = do_class_using_decl (escope, name);
13635 		  if (!elt)
13636 		    {
13637 		      r = error_mark_node;
13638 		      break;
13639 		    }
13640 		  else
13641 		    {
13642 		      TREE_PROTECTED (elt) = TREE_PROTECTED (t);
13643 		      TREE_PRIVATE (elt) = TREE_PRIVATE (t);
13644 		    }
13645 		  TREE_VEC_ELT (r, i) = elt;
13646 		}
13647 	    }
13648 	  else
13649 	    {
13650 	      tree inst_scope = tsubst_copy (USING_DECL_SCOPE (t), args,
13651 					     complain, in_decl);
13652 	      r = do_class_using_decl (inst_scope, name);
13653 	      if (!r)
13654 		r = error_mark_node;
13655 	      else
13656 		{
13657 		  TREE_PROTECTED (r) = TREE_PROTECTED (t);
13658 		  TREE_PRIVATE (r) = TREE_PRIVATE (t);
13659 		}
13660 	    }
13661 	}
13662       else
13663 	{
13664 	  r = copy_node (t);
13665 	  DECL_CHAIN (r) = NULL_TREE;
13666 	}
13667       break;
13668 
13669     case TYPE_DECL:
13670     case VAR_DECL:
13671       {
13672 	tree argvec = NULL_TREE;
13673 	tree gen_tmpl = NULL_TREE;
13674 	tree spec;
13675 	tree tmpl = NULL_TREE;
13676 	tree ctx;
13677 	tree type = NULL_TREE;
13678 	bool local_p;
13679 
13680 	if (TREE_TYPE (t) == error_mark_node)
13681 	  RETURN (error_mark_node);
13682 
13683 	if (TREE_CODE (t) == TYPE_DECL
13684 	    && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
13685 	  {
13686 	    /* If this is the canonical decl, we don't have to
13687 	       mess with instantiations, and often we can't (for
13688 	       typename, template type parms and such).  Note that
13689 	       TYPE_NAME is not correct for the above test if
13690 	       we've copied the type for a typedef.  */
13691 	    type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13692 	    if (type == error_mark_node)
13693 	      RETURN (error_mark_node);
13694 	    r = TYPE_NAME (type);
13695 	    break;
13696 	  }
13697 
13698 	/* Check to see if we already have the specialization we
13699 	   need.  */
13700 	spec = NULL_TREE;
13701 	if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
13702 	  {
13703 	    /* T is a static data member or namespace-scope entity.
13704 	       We have to substitute into namespace-scope variables
13705 	       (not just variable templates) because of cases like:
13706 
13707 	         template <class T> void f() { extern T t; }
13708 
13709 	       where the entity referenced is not known until
13710 	       instantiation time.  */
13711 	    local_p = false;
13712 	    ctx = DECL_CONTEXT (t);
13713 	    if (DECL_CLASS_SCOPE_P (t))
13714 	      {
13715 		ctx = tsubst_aggr_type (ctx, args,
13716 					complain,
13717 					in_decl, /*entering_scope=*/1);
13718 		/* If CTX is unchanged, then T is in fact the
13719 		   specialization we want.  That situation occurs when
13720 		   referencing a static data member within in its own
13721 		   class.  We can use pointer equality, rather than
13722 		   same_type_p, because DECL_CONTEXT is always
13723 		   canonical...  */
13724 		if (ctx == DECL_CONTEXT (t)
13725 		    /* ... unless T is a member template; in which
13726 		       case our caller can be willing to create a
13727 		       specialization of that template represented
13728 		       by T.  */
13729 		    && !(DECL_TI_TEMPLATE (t)
13730 			 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
13731 		  spec = t;
13732 	      }
13733 
13734 	    if (!spec)
13735 	      {
13736 		tmpl = DECL_TI_TEMPLATE (t);
13737 		gen_tmpl = most_general_template (tmpl);
13738 		argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
13739 		if (argvec != error_mark_node)
13740 		  argvec = (coerce_innermost_template_parms
13741 			    (DECL_TEMPLATE_PARMS (gen_tmpl),
13742 			     argvec, t, complain,
13743 			     /*all*/true, /*defarg*/true));
13744 		if (argvec == error_mark_node)
13745 		  RETURN (error_mark_node);
13746 		hash = hash_tmpl_and_args (gen_tmpl, argvec);
13747 		spec = retrieve_specialization (gen_tmpl, argvec, hash);
13748 	      }
13749 	  }
13750 	else
13751 	  {
13752 	    /* A local variable.  */
13753 	    local_p = true;
13754 	    /* Subsequent calls to pushdecl will fill this in.  */
13755 	    ctx = NULL_TREE;
13756 	    /* Unless this is a reference to a static variable from an
13757 	       enclosing function, in which case we need to fill it in now.  */
13758 	    if (TREE_STATIC (t))
13759 	      {
13760 		tree fn = enclosing_instantiation_of (DECL_CONTEXT (t));
13761 		if (fn != current_function_decl)
13762 		  ctx = fn;
13763 	      }
13764 	    spec = retrieve_local_specialization (t);
13765 	  }
13766 	/* If we already have the specialization we need, there is
13767 	   nothing more to do.  */
13768 	if (spec)
13769 	  {
13770 	    r = spec;
13771 	    break;
13772 	  }
13773 
13774 	/* Create a new node for the specialization we need.  */
13775 	r = copy_decl (t);
13776 	if (type == NULL_TREE)
13777 	  {
13778 	    if (is_typedef_decl (t))
13779 	      type = DECL_ORIGINAL_TYPE (t);
13780 	    else
13781 	      type = TREE_TYPE (t);
13782 	    if (VAR_P (t)
13783 		&& VAR_HAD_UNKNOWN_BOUND (t)
13784 		&& type != error_mark_node)
13785 	      type = strip_array_domain (type);
13786 	    tree sub_args = args;
13787 	    if (tree auto_node = type_uses_auto (type))
13788 	      {
13789 		/* Mask off any template args past the variable's context so we
13790 		   don't replace the auto with an unrelated argument.  */
13791 		int nouter = TEMPLATE_TYPE_LEVEL (auto_node) - 1;
13792 		int extra = TMPL_ARGS_DEPTH (args) - nouter;
13793 		if (extra > 0)
13794 		  /* This should never happen with the new lambda instantiation
13795 		     model, but keep the handling just in case.  */
13796 		  gcc_assert (!CHECKING_P),
13797 		  sub_args = strip_innermost_template_args (args, extra);
13798 	      }
13799 	    type = tsubst (type, sub_args, complain, in_decl);
13800 	  }
13801 	if (VAR_P (r))
13802 	  {
13803 	    /* Even if the original location is out of scope, the
13804 	       newly substituted one is not.  */
13805 	    DECL_DEAD_FOR_LOCAL (r) = 0;
13806 	    DECL_INITIALIZED_P (r) = 0;
13807 	    DECL_TEMPLATE_INSTANTIATED (r) = 0;
13808 	    if (type == error_mark_node)
13809 	      RETURN (error_mark_node);
13810 	    if (TREE_CODE (type) == FUNCTION_TYPE)
13811 	      {
13812 		/* It may seem that this case cannot occur, since:
13813 
13814 		   typedef void f();
13815 		   void g() { f x; }
13816 
13817 		   declares a function, not a variable.  However:
13818 
13819 		   typedef void f();
13820 		   template <typename T> void g() { T t; }
13821 		   template void g<f>();
13822 
13823 		   is an attempt to declare a variable with function
13824 		   type.  */
13825 		error ("variable %qD has function type",
13826 		       /* R is not yet sufficiently initialized, so we
13827 			  just use its name.  */
13828 		       DECL_NAME (r));
13829 		RETURN (error_mark_node);
13830 	      }
13831 	    type = complete_type (type);
13832 	    /* Wait until cp_finish_decl to set this again, to handle
13833 	       circular dependency (template/instantiate6.C). */
13834 	    DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
13835 	    type = check_var_type (DECL_NAME (r), type);
13836 
13837 	    if (DECL_HAS_VALUE_EXPR_P (t))
13838 	      {
13839 		tree ve = DECL_VALUE_EXPR (t);
13840 		/* If the DECL_VALUE_EXPR is converted to the declared type,
13841 		   preserve the identity so that gimplify_type_sizes works.  */
13842 		bool nop = (TREE_CODE (ve) == NOP_EXPR);
13843 		if (nop)
13844 		  ve = TREE_OPERAND (ve, 0);
13845 		ve = tsubst_expr (ve, args, complain, in_decl,
13846 				  /*constant_expression_p=*/false);
13847 		if (REFERENCE_REF_P (ve))
13848 		  {
13849 		    gcc_assert (TREE_CODE (type) == REFERENCE_TYPE);
13850 		    ve = TREE_OPERAND (ve, 0);
13851 		  }
13852 		if (nop)
13853 		  ve = build_nop (type, ve);
13854 		else
13855 		  gcc_checking_assert (TREE_TYPE (ve) == type);
13856 		SET_DECL_VALUE_EXPR (r, ve);
13857 	      }
13858 	    if (CP_DECL_THREAD_LOCAL_P (r)
13859 		&& !processing_template_decl)
13860 	      set_decl_tls_model (r, decl_default_tls_model (r));
13861 	  }
13862 	else if (DECL_SELF_REFERENCE_P (t))
13863 	  SET_DECL_SELF_REFERENCE_P (r);
13864 	TREE_TYPE (r) = type;
13865 	cp_apply_type_quals_to_decl (cp_type_quals (type), r);
13866 	DECL_CONTEXT (r) = ctx;
13867 	/* Clear out the mangled name and RTL for the instantiation.  */
13868 	SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
13869 	if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
13870 	  SET_DECL_RTL (r, NULL);
13871 	/* The initializer must not be expanded until it is required;
13872 	   see [temp.inst].  */
13873 	DECL_INITIAL (r) = NULL_TREE;
13874 	DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
13875 	if (VAR_P (r))
13876 	  {
13877 	    if (DECL_LANG_SPECIFIC (r))
13878 	      SET_DECL_DEPENDENT_INIT_P (r, false);
13879 
13880 	    SET_DECL_MODE (r, VOIDmode);
13881 
13882 	    /* Possibly limit visibility based on template args.  */
13883 	    DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
13884 	    if (DECL_VISIBILITY_SPECIFIED (t))
13885 	      {
13886 		DECL_VISIBILITY_SPECIFIED (r) = 0;
13887 		DECL_ATTRIBUTES (r)
13888 		  = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
13889 	      }
13890 	    determine_visibility (r);
13891 	  }
13892 
13893 	if (!local_p)
13894 	  {
13895 	    /* A static data member declaration is always marked
13896 	       external when it is declared in-class, even if an
13897 	       initializer is present.  We mimic the non-template
13898 	       processing here.  */
13899 	    DECL_EXTERNAL (r) = 1;
13900 	    if (DECL_NAMESPACE_SCOPE_P (t))
13901 	      DECL_NOT_REALLY_EXTERN (r) = 1;
13902 
13903 	    DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
13904 	    SET_DECL_IMPLICIT_INSTANTIATION (r);
13905 	    register_specialization (r, gen_tmpl, argvec, false, hash);
13906 	  }
13907 	else
13908 	  {
13909 	    if (DECL_LANG_SPECIFIC (r))
13910 	      DECL_TEMPLATE_INFO (r) = NULL_TREE;
13911 	    if (!cp_unevaluated_operand)
13912 	      register_local_specialization (r, t);
13913 	  }
13914 
13915 	DECL_CHAIN (r) = NULL_TREE;
13916 
13917 	apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
13918 					/*flags=*/0,
13919 					args, complain, in_decl);
13920 
13921 	/* Preserve a typedef that names a type.  */
13922 	if (is_typedef_decl (r) && type != error_mark_node)
13923 	  {
13924 	    DECL_ORIGINAL_TYPE (r) = NULL_TREE;
13925 	    set_underlying_type (r);
13926 	    if (TYPE_DECL_ALIAS_P (r))
13927 	      /* An alias template specialization can be dependent
13928 		 even if its underlying type is not.  */
13929 	      TYPE_DEPENDENT_P_VALID (TREE_TYPE (r)) = false;
13930 	  }
13931 
13932 	layout_decl (r, 0);
13933       }
13934       break;
13935 
13936     default:
13937       gcc_unreachable ();
13938     }
13939 #undef RETURN
13940 
13941  out:
13942   /* Restore the file and line information.  */
13943   input_location = saved_loc;
13944 
13945   return r;
13946 }
13947 
13948 /* Substitute into the ARG_TYPES of a function type.
13949    If END is a TREE_CHAIN, leave it and any following types
13950    un-substituted.  */
13951 
13952 static tree
tsubst_arg_types(tree arg_types,tree args,tree end,tsubst_flags_t complain,tree in_decl)13953 tsubst_arg_types (tree arg_types,
13954 		  tree args,
13955 		  tree end,
13956 		  tsubst_flags_t complain,
13957 		  tree in_decl)
13958 {
13959   tree remaining_arg_types;
13960   tree type = NULL_TREE;
13961   int i = 1;
13962   tree expanded_args = NULL_TREE;
13963   tree default_arg;
13964 
13965   if (!arg_types || arg_types == void_list_node || arg_types == end)
13966     return arg_types;
13967 
13968   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
13969 					  args, end, complain, in_decl);
13970   if (remaining_arg_types == error_mark_node)
13971     return error_mark_node;
13972 
13973   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
13974     {
13975       /* For a pack expansion, perform substitution on the
13976          entire expression. Later on, we'll handle the arguments
13977          one-by-one.  */
13978       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
13979                                             args, complain, in_decl);
13980 
13981       if (TREE_CODE (expanded_args) == TREE_VEC)
13982         /* So that we'll spin through the parameters, one by one.  */
13983         i = TREE_VEC_LENGTH (expanded_args);
13984       else
13985         {
13986           /* We only partially substituted into the parameter
13987              pack. Our type is TYPE_PACK_EXPANSION.  */
13988           type = expanded_args;
13989           expanded_args = NULL_TREE;
13990         }
13991     }
13992 
13993   while (i > 0) {
13994     --i;
13995 
13996     if (expanded_args)
13997       type = TREE_VEC_ELT (expanded_args, i);
13998     else if (!type)
13999       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
14000 
14001     if (type == error_mark_node)
14002       return error_mark_node;
14003     if (VOID_TYPE_P (type))
14004       {
14005         if (complain & tf_error)
14006           {
14007             error ("invalid parameter type %qT", type);
14008             if (in_decl)
14009               error ("in declaration %q+D", in_decl);
14010           }
14011         return error_mark_node;
14012     }
14013     /* DR 657. */
14014     if (abstract_virtuals_error_sfinae (ACU_PARM, type, complain))
14015       return error_mark_node;
14016 
14017     /* Do array-to-pointer, function-to-pointer conversion, and ignore
14018        top-level qualifiers as required.  */
14019     type = cv_unqualified (type_decays_to (type));
14020 
14021     /* We do not substitute into default arguments here.  The standard
14022        mandates that they be instantiated only when needed, which is
14023        done in build_over_call.  */
14024     default_arg = TREE_PURPOSE (arg_types);
14025 
14026     /* Except that we do substitute default arguments under tsubst_lambda_expr,
14027        since the new op() won't have any associated template arguments for us
14028        to refer to later.  */
14029     if (lambda_fn_in_template_p (in_decl))
14030       default_arg = tsubst_copy_and_build (default_arg, args, complain, in_decl,
14031 					   false/*fn*/, false/*constexpr*/);
14032 
14033     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
14034       {
14035         /* We've instantiated a template before its default arguments
14036            have been parsed.  This can happen for a nested template
14037            class, and is not an error unless we require the default
14038            argument in a call of this function.  */
14039         remaining_arg_types =
14040           tree_cons (default_arg, type, remaining_arg_types);
14041         vec_safe_push (DEFARG_INSTANTIATIONS(default_arg), remaining_arg_types);
14042       }
14043     else
14044       remaining_arg_types =
14045         hash_tree_cons (default_arg, type, remaining_arg_types);
14046   }
14047 
14048   return remaining_arg_types;
14049 }
14050 
14051 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
14052    *not* handle the exception-specification for FNTYPE, because the
14053    initial substitution of explicitly provided template parameters
14054    during argument deduction forbids substitution into the
14055    exception-specification:
14056 
14057      [temp.deduct]
14058 
14059      All references in the function type of the function template to  the
14060      corresponding template parameters are replaced by the specified tem-
14061      plate argument values.  If a substitution in a template parameter or
14062      in  the function type of the function template results in an invalid
14063      type, type deduction fails.  [Note: The equivalent  substitution  in
14064      exception specifications is done only when the function is instanti-
14065      ated, at which point a program is  ill-formed  if  the  substitution
14066      results in an invalid type.]  */
14067 
14068 static tree
tsubst_function_type(tree t,tree args,tsubst_flags_t complain,tree in_decl)14069 tsubst_function_type (tree t,
14070 		      tree args,
14071 		      tsubst_flags_t complain,
14072 		      tree in_decl)
14073 {
14074   tree return_type;
14075   tree arg_types = NULL_TREE;
14076   tree fntype;
14077 
14078   /* The TYPE_CONTEXT is not used for function/method types.  */
14079   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
14080 
14081   /* DR 1227: Mixing immediate and non-immediate contexts in deduction
14082      failure.  */
14083   bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
14084 
14085   if (late_return_type_p)
14086     {
14087       /* Substitute the argument types.  */
14088       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
14089 				    complain, in_decl);
14090       if (arg_types == error_mark_node)
14091 	return error_mark_node;
14092 
14093       tree save_ccp = current_class_ptr;
14094       tree save_ccr = current_class_ref;
14095       tree this_type = (TREE_CODE (t) == METHOD_TYPE
14096 			? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
14097       bool do_inject = this_type && CLASS_TYPE_P (this_type);
14098       if (do_inject)
14099 	{
14100 	  /* DR 1207: 'this' is in scope in the trailing return type.  */
14101 	  inject_this_parameter (this_type, cp_type_quals (this_type));
14102 	}
14103 
14104       /* Substitute the return type.  */
14105       return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14106 
14107       if (do_inject)
14108 	{
14109 	  current_class_ptr = save_ccp;
14110 	  current_class_ref = save_ccr;
14111 	}
14112     }
14113   else
14114     /* Substitute the return type.  */
14115     return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14116 
14117   if (return_type == error_mark_node)
14118     return error_mark_node;
14119   /* DR 486 clarifies that creation of a function type with an
14120      invalid return type is a deduction failure.  */
14121   if (TREE_CODE (return_type) == ARRAY_TYPE
14122       || TREE_CODE (return_type) == FUNCTION_TYPE)
14123     {
14124       if (complain & tf_error)
14125 	{
14126 	  if (TREE_CODE (return_type) == ARRAY_TYPE)
14127 	    error ("function returning an array");
14128 	  else
14129 	    error ("function returning a function");
14130 	}
14131       return error_mark_node;
14132     }
14133   /* And DR 657. */
14134   if (abstract_virtuals_error_sfinae (ACU_RETURN, return_type, complain))
14135     return error_mark_node;
14136 
14137   if (!late_return_type_p)
14138     {
14139       /* Substitute the argument types.  */
14140       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
14141 				    complain, in_decl);
14142       if (arg_types == error_mark_node)
14143 	return error_mark_node;
14144     }
14145 
14146   /* Construct a new type node and return it.  */
14147   if (TREE_CODE (t) == FUNCTION_TYPE)
14148     {
14149       fntype = build_function_type (return_type, arg_types);
14150       fntype = apply_memfn_quals (fntype,
14151 				  type_memfn_quals (t),
14152 				  type_memfn_rqual (t));
14153     }
14154   else
14155     {
14156       tree r = TREE_TYPE (TREE_VALUE (arg_types));
14157       /* Don't pick up extra function qualifiers from the basetype.  */
14158       r = cp_build_qualified_type_real (r, type_memfn_quals (t), complain);
14159       if (! MAYBE_CLASS_TYPE_P (r))
14160 	{
14161 	  /* [temp.deduct]
14162 
14163 	     Type deduction may fail for any of the following
14164 	     reasons:
14165 
14166 	     -- Attempting to create "pointer to member of T" when T
14167 	     is not a class type.  */
14168 	  if (complain & tf_error)
14169 	    error ("creating pointer to member function of non-class type %qT",
14170 		      r);
14171 	  return error_mark_node;
14172 	}
14173 
14174       fntype = build_method_type_directly (r, return_type,
14175 					   TREE_CHAIN (arg_types));
14176       fntype = build_ref_qualified_type (fntype, type_memfn_rqual (t));
14177     }
14178   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
14179 
14180   if (late_return_type_p)
14181     TYPE_HAS_LATE_RETURN_TYPE (fntype) = 1;
14182 
14183   return fntype;
14184 }
14185 
14186 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
14187    ARGS into that specification, and return the substituted
14188    specification.  If there is no specification, return NULL_TREE.  */
14189 
14190 static tree
tsubst_exception_specification(tree fntype,tree args,tsubst_flags_t complain,tree in_decl,bool defer_ok)14191 tsubst_exception_specification (tree fntype,
14192 				tree args,
14193 				tsubst_flags_t complain,
14194 				tree in_decl,
14195 				bool defer_ok)
14196 {
14197   tree specs;
14198   tree new_specs;
14199 
14200   specs = TYPE_RAISES_EXCEPTIONS (fntype);
14201   new_specs = NULL_TREE;
14202   if (specs && TREE_PURPOSE (specs))
14203     {
14204       /* A noexcept-specifier.  */
14205       tree expr = TREE_PURPOSE (specs);
14206       if (TREE_CODE (expr) == INTEGER_CST)
14207 	new_specs = expr;
14208       else if (defer_ok)
14209 	{
14210 	  /* Defer instantiation of noexcept-specifiers to avoid
14211 	     excessive instantiations (c++/49107).  */
14212 	  new_specs = make_node (DEFERRED_NOEXCEPT);
14213 	  if (DEFERRED_NOEXCEPT_SPEC_P (specs))
14214 	    {
14215 	      /* We already partially instantiated this member template,
14216 		 so combine the new args with the old.  */
14217 	      DEFERRED_NOEXCEPT_PATTERN (new_specs)
14218 		= DEFERRED_NOEXCEPT_PATTERN (expr);
14219 	      DEFERRED_NOEXCEPT_ARGS (new_specs)
14220 		= add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
14221 	    }
14222 	  else
14223 	    {
14224 	      DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
14225 	      DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
14226 	    }
14227 	}
14228       else
14229 	new_specs = tsubst_copy_and_build
14230 	  (expr, args, complain, in_decl, /*function_p=*/false,
14231 	   /*integral_constant_expression_p=*/true);
14232       new_specs = build_noexcept_spec (new_specs, complain);
14233     }
14234   else if (specs)
14235     {
14236       if (! TREE_VALUE (specs))
14237 	new_specs = specs;
14238       else
14239 	while (specs)
14240 	  {
14241 	    tree spec;
14242             int i, len = 1;
14243             tree expanded_specs = NULL_TREE;
14244 
14245             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
14246               {
14247                 /* Expand the pack expansion type.  */
14248                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
14249                                                        args, complain,
14250                                                        in_decl);
14251 
14252 		if (expanded_specs == error_mark_node)
14253 		  return error_mark_node;
14254 		else if (TREE_CODE (expanded_specs) == TREE_VEC)
14255 		  len = TREE_VEC_LENGTH (expanded_specs);
14256 		else
14257 		  {
14258 		    /* We're substituting into a member template, so
14259 		       we got a TYPE_PACK_EXPANSION back.  Add that
14260 		       expansion and move on.  */
14261 		    gcc_assert (TREE_CODE (expanded_specs)
14262 				== TYPE_PACK_EXPANSION);
14263 		    new_specs = add_exception_specifier (new_specs,
14264 							 expanded_specs,
14265 							 complain);
14266 		    specs = TREE_CHAIN (specs);
14267 		    continue;
14268 		  }
14269               }
14270 
14271             for (i = 0; i < len; ++i)
14272               {
14273                 if (expanded_specs)
14274                   spec = TREE_VEC_ELT (expanded_specs, i);
14275                 else
14276                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
14277                 if (spec == error_mark_node)
14278                   return spec;
14279                 new_specs = add_exception_specifier (new_specs, spec,
14280                                                      complain);
14281               }
14282 
14283             specs = TREE_CHAIN (specs);
14284 	  }
14285     }
14286   return new_specs;
14287 }
14288 
14289 /* Take the tree structure T and replace template parameters used
14290    therein with the argument vector ARGS.  IN_DECL is an associated
14291    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
14292    Issue error and warning messages under control of COMPLAIN.  Note
14293    that we must be relatively non-tolerant of extensions here, in
14294    order to preserve conformance; if we allow substitutions that
14295    should not be allowed, we may allow argument deductions that should
14296    not succeed, and therefore report ambiguous overload situations
14297    where there are none.  In theory, we could allow the substitution,
14298    but indicate that it should have failed, and allow our caller to
14299    make sure that the right thing happens, but we don't try to do this
14300    yet.
14301 
14302    This function is used for dealing with types, decls and the like;
14303    for expressions, use tsubst_expr or tsubst_copy.  */
14304 
14305 tree
tsubst(tree t,tree args,tsubst_flags_t complain,tree in_decl)14306 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
14307 {
14308   enum tree_code code;
14309   tree type, r = NULL_TREE;
14310 
14311   if (t == NULL_TREE || t == error_mark_node
14312       || t == integer_type_node
14313       || t == void_type_node
14314       || t == char_type_node
14315       || t == unknown_type_node
14316       || TREE_CODE (t) == NAMESPACE_DECL
14317       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
14318     return t;
14319 
14320   if (DECL_P (t))
14321     return tsubst_decl (t, args, complain);
14322 
14323   if (args == NULL_TREE)
14324     return t;
14325 
14326   code = TREE_CODE (t);
14327 
14328   if (code == IDENTIFIER_NODE)
14329     type = IDENTIFIER_TYPE_VALUE (t);
14330   else
14331     type = TREE_TYPE (t);
14332 
14333   gcc_assert (type != unknown_type_node);
14334 
14335   /* Reuse typedefs.  We need to do this to handle dependent attributes,
14336      such as attribute aligned.  */
14337   if (TYPE_P (t)
14338       && typedef_variant_p (t))
14339     {
14340       tree decl = TYPE_NAME (t);
14341 
14342       if (alias_template_specialization_p (t))
14343 	{
14344 	  /* DECL represents an alias template and we want to
14345 	     instantiate it.  */
14346 	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
14347 	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
14348 	  r = instantiate_alias_template (tmpl, gen_args, complain);
14349 	}
14350       else if (DECL_CLASS_SCOPE_P (decl)
14351 	       && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
14352 	       && uses_template_parms (DECL_CONTEXT (decl)))
14353 	{
14354 	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
14355 	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
14356 	  r = retrieve_specialization (tmpl, gen_args, 0);
14357 	}
14358       else if (DECL_FUNCTION_SCOPE_P (decl)
14359 	       && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
14360 	       && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
14361 	r = retrieve_local_specialization (decl);
14362       else
14363 	/* The typedef is from a non-template context.  */
14364 	return t;
14365 
14366       if (r)
14367 	{
14368 	  r = TREE_TYPE (r);
14369 	  r = cp_build_qualified_type_real
14370 	    (r, cp_type_quals (t) | cp_type_quals (r),
14371 	     complain | tf_ignore_bad_quals);
14372 	  return r;
14373 	}
14374       else
14375 	{
14376 	  /* We don't have an instantiation yet, so drop the typedef.  */
14377 	  int quals = cp_type_quals (t);
14378 	  t = DECL_ORIGINAL_TYPE (decl);
14379 	  t = cp_build_qualified_type_real (t, quals,
14380 					    complain | tf_ignore_bad_quals);
14381 	}
14382     }
14383 
14384   bool fndecl_type = (complain & tf_fndecl_type);
14385   complain &= ~tf_fndecl_type;
14386 
14387   if (type
14388       && code != TYPENAME_TYPE
14389       && code != TEMPLATE_TYPE_PARM
14390       && code != TEMPLATE_PARM_INDEX
14391       && code != IDENTIFIER_NODE
14392       && code != FUNCTION_TYPE
14393       && code != METHOD_TYPE)
14394     type = tsubst (type, args, complain, in_decl);
14395   if (type == error_mark_node)
14396     return error_mark_node;
14397 
14398   switch (code)
14399     {
14400     case RECORD_TYPE:
14401     case UNION_TYPE:
14402     case ENUMERAL_TYPE:
14403       return tsubst_aggr_type (t, args, complain, in_decl,
14404 			       /*entering_scope=*/0);
14405 
14406     case ERROR_MARK:
14407     case IDENTIFIER_NODE:
14408     case VOID_TYPE:
14409     case REAL_TYPE:
14410     case COMPLEX_TYPE:
14411     case VECTOR_TYPE:
14412     case BOOLEAN_TYPE:
14413     case NULLPTR_TYPE:
14414     case LANG_TYPE:
14415       return t;
14416 
14417     case INTEGER_TYPE:
14418       if (t == integer_type_node)
14419 	return t;
14420 
14421       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
14422           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
14423         return t;
14424 
14425       {
14426 	tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
14427 
14428 	max = tsubst_expr (omax, args, complain, in_decl,
14429 			   /*integral_constant_expression_p=*/false);
14430 
14431 	/* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
14432 	   needed.  */
14433 	if (TREE_CODE (max) == NOP_EXPR
14434 	    && TREE_SIDE_EFFECTS (omax)
14435 	    && !TREE_TYPE (max))
14436 	  TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
14437 
14438 	/* If we're in a partial instantiation, preserve the magic NOP_EXPR
14439 	   with TREE_SIDE_EFFECTS that indicates this is not an integral
14440 	   constant expression.  */
14441 	if (processing_template_decl
14442 	    && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
14443 	  {
14444 	    gcc_assert (TREE_CODE (max) == NOP_EXPR);
14445 	    TREE_SIDE_EFFECTS (max) = 1;
14446 	  }
14447 
14448 	return compute_array_index_type (NULL_TREE, max, complain);
14449       }
14450 
14451     case TEMPLATE_TYPE_PARM:
14452     case TEMPLATE_TEMPLATE_PARM:
14453     case BOUND_TEMPLATE_TEMPLATE_PARM:
14454     case TEMPLATE_PARM_INDEX:
14455       {
14456 	int idx;
14457 	int level;
14458 	int levels;
14459 	tree arg = NULL_TREE;
14460 
14461 	/* Early in template argument deduction substitution, we don't
14462 	   want to reduce the level of 'auto', or it will be confused
14463 	   with a normal template parm in subsequent deduction.  */
14464 	if (is_auto (t) && (complain & tf_partial))
14465 	  return t;
14466 
14467 	r = NULL_TREE;
14468 
14469 	gcc_assert (TREE_VEC_LENGTH (args) > 0);
14470 	template_parm_level_and_index (t, &level, &idx);
14471 
14472 	levels = TMPL_ARGS_DEPTH (args);
14473 	if (level <= levels
14474 	    && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
14475 	  {
14476 	    arg = TMPL_ARG (args, level, idx);
14477 
14478 	    /* See through ARGUMENT_PACK_SELECT arguments. */
14479 	    if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
14480 	      arg = argument_pack_select_arg (arg);
14481 	  }
14482 
14483 	if (arg == error_mark_node)
14484 	  return error_mark_node;
14485 	else if (arg != NULL_TREE)
14486 	  {
14487 	    if (ARGUMENT_PACK_P (arg))
14488 	      /* If ARG is an argument pack, we don't actually want to
14489 		 perform a substitution here, because substitutions
14490 		 for argument packs are only done
14491 		 element-by-element. We can get to this point when
14492 		 substituting the type of a non-type template
14493 		 parameter pack, when that type actually contains
14494 		 template parameter packs from an outer template, e.g.,
14495 
14496 	         template<typename... Types> struct A {
14497 		   template<Types... Values> struct B { };
14498                  };  */
14499 	      return t;
14500 
14501 	    if (code == TEMPLATE_TYPE_PARM)
14502 	      {
14503 		int quals;
14504 		gcc_assert (TYPE_P (arg));
14505 
14506 		quals = cp_type_quals (arg) | cp_type_quals (t);
14507 
14508 		return cp_build_qualified_type_real
14509 		  (arg, quals, complain | tf_ignore_bad_quals);
14510 	      }
14511 	    else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
14512 	      {
14513 		/* We are processing a type constructed from a
14514 		   template template parameter.  */
14515 		tree argvec = tsubst (TYPE_TI_ARGS (t),
14516 				      args, complain, in_decl);
14517 		if (argvec == error_mark_node)
14518 		  return error_mark_node;
14519 
14520 		gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
14521 			    || TREE_CODE (arg) == TEMPLATE_DECL
14522 			    || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
14523 
14524 		if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
14525 		  /* Consider this code:
14526 
14527 			template <template <class> class Template>
14528 			struct Internal {
14529 			template <class Arg> using Bind = Template<Arg>;
14530 			};
14531 
14532 			template <template <class> class Template, class Arg>
14533 			using Instantiate = Template<Arg>; //#0
14534 
14535 			template <template <class> class Template,
14536                                   class Argument>
14537 			using Bind =
14538 			  Instantiate<Internal<Template>::template Bind,
14539 				      Argument>; //#1
14540 
14541 		     When #1 is parsed, the
14542 		     BOUND_TEMPLATE_TEMPLATE_PARM representing the
14543 		     parameter `Template' in #0 matches the
14544 		     UNBOUND_CLASS_TEMPLATE representing the argument
14545 		     `Internal<Template>::template Bind'; We then want
14546 		     to assemble the type `Bind<Argument>' that can't
14547 		     be fully created right now, because
14548 		     `Internal<Template>' not being complete, the Bind
14549 		     template cannot be looked up in that context.  So
14550 		     we need to "store" `Bind<Argument>' for later
14551 		     when the context of Bind becomes complete.  Let's
14552 		     store that in a TYPENAME_TYPE.  */
14553 		  return make_typename_type (TYPE_CONTEXT (arg),
14554 					     build_nt (TEMPLATE_ID_EXPR,
14555 						       TYPE_IDENTIFIER (arg),
14556 						       argvec),
14557 					     typename_type,
14558 					     complain);
14559 
14560 		/* We can get a TEMPLATE_TEMPLATE_PARM here when we
14561 		   are resolving nested-types in the signature of a
14562 		   member function templates.  Otherwise ARG is a
14563 		   TEMPLATE_DECL and is the real template to be
14564 		   instantiated.  */
14565 		if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
14566 		  arg = TYPE_NAME (arg);
14567 
14568 		r = lookup_template_class (arg,
14569 					   argvec, in_decl,
14570 					   DECL_CONTEXT (arg),
14571 					    /*entering_scope=*/0,
14572 					   complain);
14573 		return cp_build_qualified_type_real
14574 		  (r, cp_type_quals (t) | cp_type_quals (r), complain);
14575 	      }
14576 	    else if (code == TEMPLATE_TEMPLATE_PARM)
14577 	      return arg;
14578 	    else
14579 	      /* TEMPLATE_PARM_INDEX.  */
14580 	      return convert_from_reference (unshare_expr (arg));
14581 	  }
14582 
14583 	if (level == 1)
14584 	  /* This can happen during the attempted tsubst'ing in
14585 	     unify.  This means that we don't yet have any information
14586 	     about the template parameter in question.  */
14587 	  return t;
14588 
14589 	/* If we get here, we must have been looking at a parm for a
14590 	   more deeply nested template.  Make a new version of this
14591 	   template parameter, but with a lower level.  */
14592 	switch (code)
14593 	  {
14594 	  case TEMPLATE_TYPE_PARM:
14595 	  case TEMPLATE_TEMPLATE_PARM:
14596 	  case BOUND_TEMPLATE_TEMPLATE_PARM:
14597 	    if (cp_type_quals (t))
14598 	      {
14599 		r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
14600 		r = cp_build_qualified_type_real
14601 		  (r, cp_type_quals (t),
14602 		   complain | (code == TEMPLATE_TYPE_PARM
14603 			       ? tf_ignore_bad_quals : 0));
14604 	      }
14605 	    else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
14606 		     && PLACEHOLDER_TYPE_CONSTRAINTS (t)
14607 		     && (r = (TEMPLATE_PARM_DESCENDANTS
14608 			      (TEMPLATE_TYPE_PARM_INDEX (t))))
14609 		     && (r = TREE_TYPE (r))
14610 		     && !PLACEHOLDER_TYPE_CONSTRAINTS (r))
14611 	      /* Break infinite recursion when substituting the constraints
14612 		 of a constrained placeholder.  */;
14613 	    else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
14614 		     && !PLACEHOLDER_TYPE_CONSTRAINTS (t)
14615 		     && !CLASS_PLACEHOLDER_TEMPLATE (t)
14616 		     && (arg = TEMPLATE_TYPE_PARM_INDEX (t),
14617 			 r = TEMPLATE_PARM_DESCENDANTS (arg))
14618 		     && (TEMPLATE_PARM_LEVEL (r)
14619 			 == TEMPLATE_PARM_LEVEL (arg) - levels))
14620 		/* Cache the simple case of lowering a type parameter.  */
14621 	      r = TREE_TYPE (r);
14622 	    else
14623 	      {
14624 		r = copy_type (t);
14625 		TEMPLATE_TYPE_PARM_INDEX (r)
14626 		  = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
14627 						r, levels, args, complain);
14628 		TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
14629 		TYPE_MAIN_VARIANT (r) = r;
14630 		TYPE_POINTER_TO (r) = NULL_TREE;
14631 		TYPE_REFERENCE_TO (r) = NULL_TREE;
14632 
14633                 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
14634 		  {
14635 		    /* Propagate constraints on placeholders.  */
14636 		    if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
14637 		      PLACEHOLDER_TYPE_CONSTRAINTS (r)
14638 			= tsubst_constraint (constr, args, complain, in_decl);
14639 		    else if (tree pl = CLASS_PLACEHOLDER_TEMPLATE (t))
14640 		      {
14641 			pl = tsubst_copy (pl, args, complain, in_decl);
14642 			CLASS_PLACEHOLDER_TEMPLATE (r) = pl;
14643 		      }
14644 		  }
14645 
14646 		if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
14647 		  /* We have reduced the level of the template
14648 		     template parameter, but not the levels of its
14649 		     template parameters, so canonical_type_parameter
14650 		     will not be able to find the canonical template
14651 		     template parameter for this level. Thus, we
14652 		     require structural equality checking to compare
14653 		     TEMPLATE_TEMPLATE_PARMs. */
14654 		  SET_TYPE_STRUCTURAL_EQUALITY (r);
14655 		else if (TYPE_STRUCTURAL_EQUALITY_P (t))
14656 		  SET_TYPE_STRUCTURAL_EQUALITY (r);
14657 		else
14658 		  TYPE_CANONICAL (r) = canonical_type_parameter (r);
14659 
14660 		if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
14661 		  {
14662 		    tree tinfo = TYPE_TEMPLATE_INFO (t);
14663 		    /* We might need to substitute into the types of non-type
14664 		       template parameters.  */
14665 		    tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
14666 					complain, in_decl);
14667 		    if (tmpl == error_mark_node)
14668 		      return error_mark_node;
14669 		    tree argvec = tsubst (TI_ARGS (tinfo), args,
14670 					  complain, in_decl);
14671 		    if (argvec == error_mark_node)
14672 		      return error_mark_node;
14673 
14674 		    TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
14675 		      = build_template_info (tmpl, argvec);
14676 		  }
14677 	      }
14678 	    break;
14679 
14680 	  case TEMPLATE_PARM_INDEX:
14681 	    /* OK, now substitute the type of the non-type parameter.  We
14682 	       couldn't do it earlier because it might be an auto parameter,
14683 	       and we wouldn't need to if we had an argument.  */
14684 	    type = tsubst (type, args, complain, in_decl);
14685 	    if (type == error_mark_node)
14686 	      return error_mark_node;
14687 	    r = reduce_template_parm_level (t, type, levels, args, complain);
14688 	    break;
14689 
14690 	  default:
14691 	    gcc_unreachable ();
14692 	  }
14693 
14694 	return r;
14695       }
14696 
14697     case TREE_LIST:
14698       {
14699 	tree purpose, value, chain;
14700 
14701 	if (t == void_list_node)
14702 	  return t;
14703 
14704 	purpose = TREE_PURPOSE (t);
14705 	if (purpose)
14706 	  {
14707 	    purpose = tsubst (purpose, args, complain, in_decl);
14708 	    if (purpose == error_mark_node)
14709 	      return error_mark_node;
14710 	  }
14711 	value = TREE_VALUE (t);
14712 	if (value)
14713 	  {
14714 	    value = tsubst (value, args, complain, in_decl);
14715 	    if (value == error_mark_node)
14716 	      return error_mark_node;
14717 	  }
14718 	chain = TREE_CHAIN (t);
14719 	if (chain && chain != void_type_node)
14720 	  {
14721 	    chain = tsubst (chain, args, complain, in_decl);
14722 	    if (chain == error_mark_node)
14723 	      return error_mark_node;
14724 	  }
14725 	if (purpose == TREE_PURPOSE (t)
14726 	    && value == TREE_VALUE (t)
14727 	    && chain == TREE_CHAIN (t))
14728 	  return t;
14729 	return hash_tree_cons (purpose, value, chain);
14730       }
14731 
14732     case TREE_BINFO:
14733       /* We should never be tsubsting a binfo.  */
14734       gcc_unreachable ();
14735 
14736     case TREE_VEC:
14737       /* A vector of template arguments.  */
14738       gcc_assert (!type);
14739       return tsubst_template_args (t, args, complain, in_decl);
14740 
14741     case POINTER_TYPE:
14742     case REFERENCE_TYPE:
14743       {
14744 	if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
14745 	  return t;
14746 
14747 	/* [temp.deduct]
14748 
14749 	   Type deduction may fail for any of the following
14750 	   reasons:
14751 
14752 	   -- Attempting to create a pointer to reference type.
14753 	   -- Attempting to create a reference to a reference type or
14754 	      a reference to void.
14755 
14756 	  Core issue 106 says that creating a reference to a reference
14757 	  during instantiation is no longer a cause for failure. We
14758 	  only enforce this check in strict C++98 mode.  */
14759 	if ((TREE_CODE (type) == REFERENCE_TYPE
14760 	     && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
14761 	    || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
14762 	  {
14763 	    static location_t last_loc;
14764 
14765 	    /* We keep track of the last time we issued this error
14766 	       message to avoid spewing a ton of messages during a
14767 	       single bad template instantiation.  */
14768 	    if (complain & tf_error
14769 		&& last_loc != input_location)
14770 	      {
14771 		if (VOID_TYPE_P (type))
14772 		  error ("forming reference to void");
14773                else if (code == POINTER_TYPE)
14774                  error ("forming pointer to reference type %qT", type);
14775                else
14776 		  error ("forming reference to reference type %qT", type);
14777 		last_loc = input_location;
14778 	      }
14779 
14780 	    return error_mark_node;
14781 	  }
14782 	else if (TREE_CODE (type) == FUNCTION_TYPE
14783 		 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
14784 		     || type_memfn_rqual (type) != REF_QUAL_NONE))
14785 	  {
14786 	    if (complain & tf_error)
14787 	      {
14788 		if (code == POINTER_TYPE)
14789 		  error ("forming pointer to qualified function type %qT",
14790 			 type);
14791 		else
14792 		  error ("forming reference to qualified function type %qT",
14793 			 type);
14794 	      }
14795 	    return error_mark_node;
14796 	  }
14797 	else if (code == POINTER_TYPE)
14798 	  {
14799 	    r = build_pointer_type (type);
14800 	    if (TREE_CODE (type) == METHOD_TYPE)
14801 	      r = build_ptrmemfunc_type (r);
14802 	  }
14803 	else if (TREE_CODE (type) == REFERENCE_TYPE)
14804 	  /* In C++0x, during template argument substitution, when there is an
14805 	     attempt to create a reference to a reference type, reference
14806 	     collapsing is applied as described in [14.3.1/4 temp.arg.type]:
14807 
14808 	     "If a template-argument for a template-parameter T names a type
14809 	     that is a reference to a type A, an attempt to create the type
14810 	     'lvalue reference to cv T' creates the type 'lvalue reference to
14811 	     A,' while an attempt to create the type type rvalue reference to
14812 	     cv T' creates the type T"
14813 	  */
14814 	  r = cp_build_reference_type
14815 	      (TREE_TYPE (type),
14816 	       TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
14817 	else
14818 	  r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
14819 	r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
14820 
14821 	if (r != error_mark_node)
14822 	  /* Will this ever be needed for TYPE_..._TO values?  */
14823 	  layout_type (r);
14824 
14825 	return r;
14826       }
14827     case OFFSET_TYPE:
14828       {
14829 	r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
14830 	if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
14831 	  {
14832 	    /* [temp.deduct]
14833 
14834 	       Type deduction may fail for any of the following
14835 	       reasons:
14836 
14837 	       -- Attempting to create "pointer to member of T" when T
14838 		  is not a class type.  */
14839 	    if (complain & tf_error)
14840 	      error ("creating pointer to member of non-class type %qT", r);
14841 	    return error_mark_node;
14842 	  }
14843 	if (TREE_CODE (type) == REFERENCE_TYPE)
14844 	  {
14845 	    if (complain & tf_error)
14846 	      error ("creating pointer to member reference type %qT", type);
14847 	    return error_mark_node;
14848 	  }
14849 	if (VOID_TYPE_P (type))
14850 	  {
14851 	    if (complain & tf_error)
14852 	      error ("creating pointer to member of type void");
14853 	    return error_mark_node;
14854 	  }
14855 	gcc_assert (TREE_CODE (type) != METHOD_TYPE);
14856 	if (TREE_CODE (type) == FUNCTION_TYPE)
14857 	  {
14858 	    /* The type of the implicit object parameter gets its
14859 	       cv-qualifiers from the FUNCTION_TYPE. */
14860 	    tree memptr;
14861 	    tree method_type
14862 	      = build_memfn_type (type, r, type_memfn_quals (type),
14863 				  type_memfn_rqual (type));
14864 	    memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
14865 	    return cp_build_qualified_type_real (memptr, cp_type_quals (t),
14866 						 complain);
14867 	  }
14868 	else
14869 	  return cp_build_qualified_type_real (build_ptrmem_type (r, type),
14870 					       cp_type_quals (t),
14871 					       complain);
14872       }
14873     case FUNCTION_TYPE:
14874     case METHOD_TYPE:
14875       {
14876 	tree fntype;
14877 	tree specs;
14878 	fntype = tsubst_function_type (t, args, complain, in_decl);
14879 	if (fntype == error_mark_node)
14880 	  return error_mark_node;
14881 
14882 	/* Substitute the exception specification.  */
14883 	specs = tsubst_exception_specification (t, args, complain, in_decl,
14884 						/*defer_ok*/fndecl_type);
14885 	if (specs == error_mark_node)
14886 	  return error_mark_node;
14887 	if (specs)
14888 	  fntype = build_exception_variant (fntype, specs);
14889 	return fntype;
14890       }
14891     case ARRAY_TYPE:
14892       {
14893 	tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
14894 	if (domain == error_mark_node)
14895 	  return error_mark_node;
14896 
14897 	/* As an optimization, we avoid regenerating the array type if
14898 	   it will obviously be the same as T.  */
14899 	if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
14900 	  return t;
14901 
14902 	/* These checks should match the ones in create_array_type_for_decl.
14903 
14904 	   [temp.deduct]
14905 
14906 	   The deduction may fail for any of the following reasons:
14907 
14908 	   -- Attempting to create an array with an element type that
14909 	      is void, a function type, or a reference type, or [DR337]
14910 	      an abstract class type.  */
14911 	if (VOID_TYPE_P (type)
14912 	    || TREE_CODE (type) == FUNCTION_TYPE
14913 	    || (TREE_CODE (type) == ARRAY_TYPE
14914 		&& TYPE_DOMAIN (type) == NULL_TREE)
14915 	    || TREE_CODE (type) == REFERENCE_TYPE)
14916 	  {
14917 	    if (complain & tf_error)
14918 	      error ("creating array of %qT", type);
14919 	    return error_mark_node;
14920 	  }
14921 
14922 	if (abstract_virtuals_error_sfinae (ACU_ARRAY, type, complain))
14923 	  return error_mark_node;
14924 
14925 	r = build_cplus_array_type (type, domain);
14926 
14927 	if (TYPE_USER_ALIGN (t))
14928 	  {
14929 	    SET_TYPE_ALIGN (r, TYPE_ALIGN (t));
14930 	    TYPE_USER_ALIGN (r) = 1;
14931 	  }
14932 
14933 	return r;
14934       }
14935 
14936     case TYPENAME_TYPE:
14937       {
14938 	tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
14939 				     in_decl, /*entering_scope=*/1);
14940 	if (ctx == error_mark_node)
14941 	  return error_mark_node;
14942 
14943 	tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
14944 			      complain, in_decl);
14945 	if (f == error_mark_node)
14946 	  return error_mark_node;
14947 
14948 	if (!MAYBE_CLASS_TYPE_P (ctx))
14949 	  {
14950 	    if (complain & tf_error)
14951 	      error ("%qT is not a class, struct, or union type", ctx);
14952 	    return error_mark_node;
14953 	  }
14954 	else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
14955 	  {
14956 	    /* Normally, make_typename_type does not require that the CTX
14957 	       have complete type in order to allow things like:
14958 
14959 		 template <class T> struct S { typename S<T>::X Y; };
14960 
14961 	       But, such constructs have already been resolved by this
14962 	       point, so here CTX really should have complete type, unless
14963 	       it's a partial instantiation.  */
14964 	    ctx = complete_type (ctx);
14965 	    if (!COMPLETE_TYPE_P (ctx))
14966 	      {
14967 		if (complain & tf_error)
14968 		  cxx_incomplete_type_error (NULL_TREE, ctx);
14969 		return error_mark_node;
14970 	      }
14971 	  }
14972 
14973 	f = make_typename_type (ctx, f, typename_type,
14974 				complain | tf_keep_type_decl);
14975 	if (f == error_mark_node)
14976 	  return f;
14977 	if (TREE_CODE (f) == TYPE_DECL)
14978 	  {
14979 	    complain |= tf_ignore_bad_quals;
14980 	    f = TREE_TYPE (f);
14981 	  }
14982 
14983 	if (TREE_CODE (f) != TYPENAME_TYPE)
14984 	  {
14985 	    if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
14986 	      {
14987 		if (complain & tf_error)
14988 		  error ("%qT resolves to %qT, which is not an enumeration type",
14989 			 t, f);
14990 		else
14991 		  return error_mark_node;
14992 	      }
14993 	    else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
14994 	      {
14995 		if (complain & tf_error)
14996 		  error ("%qT resolves to %qT, which is is not a class type",
14997 			 t, f);
14998 		else
14999 		  return error_mark_node;
15000 	      }
15001 	  }
15002 
15003 	return cp_build_qualified_type_real
15004 	  (f, cp_type_quals (f) | cp_type_quals (t), complain);
15005       }
15006 
15007     case UNBOUND_CLASS_TEMPLATE:
15008       {
15009 	tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
15010 				     in_decl, /*entering_scope=*/1);
15011 	tree name = TYPE_IDENTIFIER (t);
15012 	tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
15013 
15014 	if (ctx == error_mark_node || name == error_mark_node)
15015 	  return error_mark_node;
15016 
15017 	if (parm_list)
15018 	  parm_list = tsubst_template_parms (parm_list, args, complain);
15019 	return make_unbound_class_template (ctx, name, parm_list, complain);
15020       }
15021 
15022     case TYPEOF_TYPE:
15023       {
15024 	tree type;
15025 
15026 	++cp_unevaluated_operand;
15027 	++c_inhibit_evaluation_warnings;
15028 
15029 	type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
15030 			    complain, in_decl,
15031 			    /*integral_constant_expression_p=*/false);
15032 
15033 	--cp_unevaluated_operand;
15034 	--c_inhibit_evaluation_warnings;
15035 
15036 	type = finish_typeof (type);
15037 	return cp_build_qualified_type_real (type,
15038 					     cp_type_quals (t)
15039 					     | cp_type_quals (type),
15040 					     complain);
15041       }
15042 
15043     case DECLTYPE_TYPE:
15044       {
15045 	tree type;
15046 
15047 	++cp_unevaluated_operand;
15048 	++c_inhibit_evaluation_warnings;
15049 
15050 	type = tsubst_copy_and_build (DECLTYPE_TYPE_EXPR (t), args,
15051 				      complain|tf_decltype, in_decl,
15052 				      /*function_p*/false,
15053 				      /*integral_constant_expression*/false);
15054 
15055 	if (DECLTYPE_FOR_INIT_CAPTURE (t))
15056 	  {
15057 	    if (type == NULL_TREE)
15058 	      {
15059 		if (complain & tf_error)
15060 		  error ("empty initializer in lambda init-capture");
15061 		type = error_mark_node;
15062 	      }
15063 	    else if (TREE_CODE (type) == TREE_LIST)
15064 	      type = build_x_compound_expr_from_list (type, ELK_INIT, complain);
15065 	  }
15066 
15067 	--cp_unevaluated_operand;
15068 	--c_inhibit_evaluation_warnings;
15069 
15070 	if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
15071 	  type = lambda_capture_field_type (type,
15072 					    DECLTYPE_FOR_INIT_CAPTURE (t),
15073 					    DECLTYPE_FOR_REF_CAPTURE (t));
15074 	else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
15075 	  type = lambda_proxy_type (type);
15076 	else
15077 	  {
15078 	    bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
15079 	    if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
15080 		&& EXPR_P (type))
15081 	      /* In a template ~id could be either a complement expression
15082 		 or an unqualified-id naming a destructor; if instantiating
15083 		 it produces an expression, it's not an id-expression or
15084 		 member access.  */
15085 	      id = false;
15086 	    type = finish_decltype_type (type, id, complain);
15087 	  }
15088 	return cp_build_qualified_type_real (type,
15089 					     cp_type_quals (t)
15090 					     | cp_type_quals (type),
15091 					     complain | tf_ignore_bad_quals);
15092       }
15093 
15094     case UNDERLYING_TYPE:
15095       {
15096 	tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
15097 			    complain, in_decl);
15098 	return finish_underlying_type (type);
15099       }
15100 
15101     case TYPE_ARGUMENT_PACK:
15102     case NONTYPE_ARGUMENT_PACK:
15103       {
15104         tree r;
15105 
15106 	if (code == NONTYPE_ARGUMENT_PACK)
15107 	  r = make_node (code);
15108 	else
15109 	  r = cxx_make_type (code);
15110 
15111 	tree pack_args = ARGUMENT_PACK_ARGS (t);
15112 	pack_args = tsubst_template_args (pack_args, args, complain, in_decl);
15113 	SET_ARGUMENT_PACK_ARGS (r, pack_args);
15114 
15115 	return r;
15116       }
15117 
15118     case VOID_CST:
15119     case INTEGER_CST:
15120     case REAL_CST:
15121     case STRING_CST:
15122     case PLUS_EXPR:
15123     case MINUS_EXPR:
15124     case NEGATE_EXPR:
15125     case NOP_EXPR:
15126     case INDIRECT_REF:
15127     case ADDR_EXPR:
15128     case CALL_EXPR:
15129     case ARRAY_REF:
15130     case SCOPE_REF:
15131       /* We should use one of the expression tsubsts for these codes.  */
15132       gcc_unreachable ();
15133 
15134     default:
15135       sorry ("use of %qs in template", get_tree_code_name (code));
15136       return error_mark_node;
15137     }
15138 }
15139 
15140 /* tsubst a BASELINK.  OBJECT_TYPE, if non-NULL, is the type of the
15141    expression on the left-hand side of the "." or "->" operator.  We
15142    only do the lookup if we had a dependent BASELINK.  Otherwise we
15143    adjust it onto the instantiated heirarchy.  */
15144 
15145 static tree
tsubst_baselink(tree baselink,tree object_type,tree args,tsubst_flags_t complain,tree in_decl)15146 tsubst_baselink (tree baselink, tree object_type,
15147 		 tree args, tsubst_flags_t complain, tree in_decl)
15148 {
15149   bool qualified_p = BASELINK_QUALIFIED_P (baselink);
15150   tree qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
15151   qualifying_scope = tsubst (qualifying_scope, args, complain, in_decl);
15152 
15153   tree optype = BASELINK_OPTYPE (baselink);
15154   optype = tsubst (optype, args, complain, in_decl);
15155 
15156   tree template_args = NULL_TREE;
15157   bool template_id_p = false;
15158   tree fns = BASELINK_FUNCTIONS (baselink);
15159   if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
15160     {
15161       template_id_p = true;
15162       template_args = TREE_OPERAND (fns, 1);
15163       fns = TREE_OPERAND (fns, 0);
15164       if (template_args)
15165 	template_args = tsubst_template_args (template_args, args,
15166 					      complain, in_decl);
15167     }
15168 
15169   tree binfo_type = BINFO_TYPE (BASELINK_BINFO (baselink));
15170   binfo_type = tsubst (binfo_type, args, complain, in_decl);
15171   bool dependent_p = binfo_type != BINFO_TYPE (BASELINK_BINFO (baselink));
15172 
15173   if (dependent_p)
15174     {
15175       tree name = OVL_NAME (fns);
15176       if (IDENTIFIER_CONV_OP_P (name))
15177 	name = make_conv_op_name (optype);
15178 
15179       if (name == complete_dtor_identifier)
15180 	/* Treat as-if non-dependent below.  */
15181 	dependent_p = false;
15182 
15183       baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
15184       if (!baselink)
15185 	{
15186 	  if ((complain & tf_error)
15187 	      && constructor_name_p (name, qualifying_scope))
15188 	    error ("cannot call constructor %<%T::%D%> directly",
15189 		   qualifying_scope, name);
15190 	  return error_mark_node;
15191 	}
15192 
15193       if (BASELINK_P (baselink))
15194 	fns = BASELINK_FUNCTIONS (baselink);
15195     }
15196   else
15197     /* We're going to overwrite pieces below, make a duplicate.  */
15198     baselink = copy_node (baselink);
15199 
15200   /* If lookup found a single function, mark it as used at this point.
15201      (If lookup found multiple functions the one selected later by
15202      overload resolution will be marked as used at that point.)  */
15203   if (!template_id_p && !really_overloaded_fn (fns))
15204     {
15205       tree fn = OVL_FIRST (fns);
15206       bool ok = mark_used (fn, complain);
15207       if (!ok && !(complain & tf_error))
15208 	return error_mark_node;
15209       if (ok && BASELINK_P (baselink))
15210 	/* We might have instantiated an auto function.  */
15211 	TREE_TYPE (baselink) = TREE_TYPE (fn);
15212     }
15213 
15214   if (BASELINK_P (baselink))
15215     {
15216       /* Add back the template arguments, if present.  */
15217       if (template_id_p)
15218 	BASELINK_FUNCTIONS (baselink)
15219 	  = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, template_args);
15220 
15221       /* Update the conversion operator type.  */
15222       BASELINK_OPTYPE (baselink) = optype;
15223     }
15224 
15225   if (!object_type)
15226     object_type = current_class_type;
15227 
15228   if (qualified_p || !dependent_p)
15229     {
15230       baselink = adjust_result_of_qualified_name_lookup (baselink,
15231 							 qualifying_scope,
15232 							 object_type);
15233       if (!qualified_p)
15234 	/* We need to call adjust_result_of_qualified_name_lookup in case the
15235 	   destructor names a base class, but we unset BASELINK_QUALIFIED_P
15236 	   so that we still get virtual function binding.  */
15237 	BASELINK_QUALIFIED_P (baselink) = false;
15238     }
15239 
15240   return baselink;
15241 }
15242 
15243 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
15244    true if the qualified-id will be a postfix-expression in-and-of
15245    itself; false if more of the postfix-expression follows the
15246    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
15247    of "&".  */
15248 
15249 static tree
tsubst_qualified_id(tree qualified_id,tree args,tsubst_flags_t complain,tree in_decl,bool done,bool address_p)15250 tsubst_qualified_id (tree qualified_id, tree args,
15251 		     tsubst_flags_t complain, tree in_decl,
15252 		     bool done, bool address_p)
15253 {
15254   tree expr;
15255   tree scope;
15256   tree name;
15257   bool is_template;
15258   tree template_args;
15259   location_t loc = UNKNOWN_LOCATION;
15260 
15261   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
15262 
15263   /* Figure out what name to look up.  */
15264   name = TREE_OPERAND (qualified_id, 1);
15265   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
15266     {
15267       is_template = true;
15268       loc = EXPR_LOCATION (name);
15269       template_args = TREE_OPERAND (name, 1);
15270       if (template_args)
15271 	template_args = tsubst_template_args (template_args, args,
15272 					      complain, in_decl);
15273       if (template_args == error_mark_node)
15274 	return error_mark_node;
15275       name = TREE_OPERAND (name, 0);
15276     }
15277   else
15278     {
15279       is_template = false;
15280       template_args = NULL_TREE;
15281     }
15282 
15283   /* Substitute into the qualifying scope.  When there are no ARGS, we
15284      are just trying to simplify a non-dependent expression.  In that
15285      case the qualifying scope may be dependent, and, in any case,
15286      substituting will not help.  */
15287   scope = TREE_OPERAND (qualified_id, 0);
15288   if (args)
15289     {
15290       scope = tsubst (scope, args, complain, in_decl);
15291       expr = tsubst_copy (name, args, complain, in_decl);
15292     }
15293   else
15294     expr = name;
15295 
15296   if (dependent_scope_p (scope))
15297     {
15298       if (is_template)
15299 	expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr, template_args);
15300       tree r = build_qualified_name (NULL_TREE, scope, expr,
15301 				     QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
15302       REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (qualified_id);
15303       return r;
15304     }
15305 
15306   if (!BASELINK_P (name) && !DECL_P (expr))
15307     {
15308       if (TREE_CODE (expr) == BIT_NOT_EXPR)
15309 	{
15310 	  /* A BIT_NOT_EXPR is used to represent a destructor.  */
15311 	  if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
15312 	    {
15313 	      error ("qualifying type %qT does not match destructor name ~%qT",
15314 		     scope, TREE_OPERAND (expr, 0));
15315 	      expr = error_mark_node;
15316 	    }
15317 	  else
15318 	    expr = lookup_qualified_name (scope, complete_dtor_identifier,
15319 					  /*is_type_p=*/0, false);
15320 	}
15321       else
15322 	expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
15323       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
15324 		     ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
15325 	{
15326 	  if (complain & tf_error)
15327 	    {
15328 	      error ("dependent-name %qE is parsed as a non-type, but "
15329 		     "instantiation yields a type", qualified_id);
15330 	      inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
15331 	    }
15332 	  return error_mark_node;
15333 	}
15334     }
15335 
15336   if (DECL_P (expr))
15337     {
15338       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
15339 					   scope);
15340       /* Remember that there was a reference to this entity.  */
15341       if (!mark_used (expr, complain) && !(complain & tf_error))
15342 	return error_mark_node;
15343     }
15344 
15345   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
15346     {
15347       if (complain & tf_error)
15348 	qualified_name_lookup_error (scope,
15349 				     TREE_OPERAND (qualified_id, 1),
15350 				     expr, input_location);
15351       return error_mark_node;
15352     }
15353 
15354   if (is_template)
15355     {
15356       /* We may be repeating a check already done during parsing, but
15357 	 if it was well-formed and passed then, it will pass again
15358 	 now, and if it didn't, we wouldn't have got here.  The case
15359 	 we want to catch is when we couldn't tell then, and can now,
15360 	 namely when templ prior to substitution was an
15361 	 identifier.  */
15362       if (flag_concepts && check_auto_in_tmpl_args (expr, template_args))
15363 	return error_mark_node;
15364 
15365       if (variable_template_p (expr))
15366 	expr = lookup_and_finish_template_variable (expr, template_args,
15367 						    complain);
15368       else
15369 	expr = lookup_template_function (expr, template_args);
15370     }
15371 
15372   if (expr == error_mark_node && complain & tf_error)
15373     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
15374 				 expr, input_location);
15375   else if (TYPE_P (scope))
15376     {
15377       expr = (adjust_result_of_qualified_name_lookup
15378 	      (expr, scope, current_nonlambda_class_type ()));
15379       expr = (finish_qualified_id_expr
15380 	      (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
15381 	       QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
15382 	       /*template_arg_p=*/false, complain));
15383     }
15384 
15385   /* Expressions do not generally have reference type.  */
15386   if (TREE_CODE (expr) != SCOPE_REF
15387       /* However, if we're about to form a pointer-to-member, we just
15388 	 want the referenced member referenced.  */
15389       && TREE_CODE (expr) != OFFSET_REF)
15390     expr = convert_from_reference (expr);
15391 
15392   if (REF_PARENTHESIZED_P (qualified_id))
15393     expr = force_paren_expr (expr);
15394 
15395   return expr;
15396 }
15397 
15398 /* tsubst the initializer for a VAR_DECL.  INIT is the unsubstituted
15399    initializer, DECL is the substituted VAR_DECL.  Other arguments are as
15400    for tsubst.  */
15401 
15402 static tree
tsubst_init(tree init,tree decl,tree args,tsubst_flags_t complain,tree in_decl)15403 tsubst_init (tree init, tree decl, tree args,
15404 	     tsubst_flags_t complain, tree in_decl)
15405 {
15406   if (!init)
15407     return NULL_TREE;
15408 
15409   init = tsubst_expr (init, args, complain, in_decl, false);
15410 
15411   if (!init && TREE_TYPE (decl) != error_mark_node)
15412     {
15413       /* If we had an initializer but it
15414 	 instantiated to nothing,
15415 	 value-initialize the object.  This will
15416 	 only occur when the initializer was a
15417 	 pack expansion where the parameter packs
15418 	 used in that expansion were of length
15419 	 zero.  */
15420       init = build_value_init (TREE_TYPE (decl),
15421 			       complain);
15422       if (TREE_CODE (init) == AGGR_INIT_EXPR)
15423 	init = get_target_expr_sfinae (init, complain);
15424       if (TREE_CODE (init) == TARGET_EXPR)
15425 	TARGET_EXPR_DIRECT_INIT_P (init) = true;
15426     }
15427 
15428   return init;
15429 }
15430 
15431 /* Like tsubst, but deals with expressions.  This function just replaces
15432    template parms; to finish processing the resultant expression, use
15433    tsubst_copy_and_build or tsubst_expr.  */
15434 
15435 static tree
tsubst_copy(tree t,tree args,tsubst_flags_t complain,tree in_decl)15436 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15437 {
15438   enum tree_code code;
15439   tree r;
15440 
15441   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
15442     return t;
15443 
15444   code = TREE_CODE (t);
15445 
15446   switch (code)
15447     {
15448     case PARM_DECL:
15449       r = retrieve_local_specialization (t);
15450 
15451       if (r == NULL_TREE)
15452 	{
15453 	  /* We get here for a use of 'this' in an NSDMI.  */
15454 	  if (DECL_NAME (t) == this_identifier && current_class_ptr)
15455 	    return current_class_ptr;
15456 
15457 	  /* This can happen for a parameter name used later in a function
15458 	     declaration (such as in a late-specified return type).  Just
15459 	     make a dummy decl, since it's only used for its type.  */
15460 	  gcc_assert (cp_unevaluated_operand != 0);
15461 	  r = tsubst_decl (t, args, complain);
15462 	  /* Give it the template pattern as its context; its true context
15463 	     hasn't been instantiated yet and this is good enough for
15464 	     mangling.  */
15465 	  DECL_CONTEXT (r) = DECL_CONTEXT (t);
15466 	}
15467 
15468       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
15469 	r = argument_pack_select_arg (r);
15470       if (!mark_used (r, complain) && !(complain & tf_error))
15471 	return error_mark_node;
15472       return r;
15473 
15474     case CONST_DECL:
15475       {
15476 	tree enum_type;
15477 	tree v;
15478 
15479 	if (DECL_TEMPLATE_PARM_P (t))
15480 	  return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
15481 	/* There is no need to substitute into namespace-scope
15482 	   enumerators.  */
15483 	if (DECL_NAMESPACE_SCOPE_P (t))
15484 	  return t;
15485 	/* If ARGS is NULL, then T is known to be non-dependent.  */
15486 	if (args == NULL_TREE)
15487 	  return scalar_constant_value (t);
15488 
15489 	/* Unfortunately, we cannot just call lookup_name here.
15490 	   Consider:
15491 
15492 	     template <int I> int f() {
15493 	     enum E { a = I };
15494 	     struct S { void g() { E e = a; } };
15495 	     };
15496 
15497 	   When we instantiate f<7>::S::g(), say, lookup_name is not
15498 	   clever enough to find f<7>::a.  */
15499 	enum_type
15500 	  = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
15501 			      /*entering_scope=*/0);
15502 
15503 	for (v = TYPE_VALUES (enum_type);
15504 	     v != NULL_TREE;
15505 	     v = TREE_CHAIN (v))
15506 	  if (TREE_PURPOSE (v) == DECL_NAME (t))
15507 	    return TREE_VALUE (v);
15508 
15509 	  /* We didn't find the name.  That should never happen; if
15510 	     name-lookup found it during preliminary parsing, we
15511 	     should find it again here during instantiation.  */
15512 	gcc_unreachable ();
15513       }
15514       return t;
15515 
15516     case FIELD_DECL:
15517       if (DECL_CONTEXT (t))
15518 	{
15519 	  tree ctx;
15520 
15521 	  ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
15522 				  /*entering_scope=*/1);
15523 	  if (ctx != DECL_CONTEXT (t))
15524 	    {
15525 	      tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
15526 	      if (!r)
15527 		{
15528 		  if (complain & tf_error)
15529 		    error ("using invalid field %qD", t);
15530 		  return error_mark_node;
15531 		}
15532 	      return r;
15533 	    }
15534 	}
15535 
15536       return t;
15537 
15538     case VAR_DECL:
15539     case FUNCTION_DECL:
15540       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
15541 	r = tsubst (t, args, complain, in_decl);
15542       else if (local_variable_p (t)
15543 	       && uses_template_parms (DECL_CONTEXT (t)))
15544 	{
15545 	  r = retrieve_local_specialization (t);
15546 	  if (r == NULL_TREE)
15547 	    {
15548 	      /* First try name lookup to find the instantiation.  */
15549 	      r = lookup_name (DECL_NAME (t));
15550 	      if (r && !is_capture_proxy (r))
15551 		{
15552 		  /* Make sure that the one we found is the one we want.  */
15553 		  tree ctx = enclosing_instantiation_of (DECL_CONTEXT (t));
15554 		  if (ctx != DECL_CONTEXT (r))
15555 		    r = NULL_TREE;
15556 		}
15557 
15558 	      if (r)
15559 		/* OK */;
15560 	      else
15561 		{
15562 		  /* This can happen for a variable used in a
15563 		     late-specified return type of a local lambda, or for a
15564 		     local static or constant.  Building a new VAR_DECL
15565 		     should be OK in all those cases.  */
15566 		  r = tsubst_decl (t, args, complain);
15567 		  if (local_specializations)
15568 		    /* Avoid infinite recursion (79640).  */
15569 		    register_local_specialization (r, t);
15570 		  if (decl_maybe_constant_var_p (r))
15571 		    {
15572 		      /* We can't call cp_finish_decl, so handle the
15573 			 initializer by hand.  */
15574 		      tree init = tsubst_init (DECL_INITIAL (t), r, args,
15575 					       complain, in_decl);
15576 		      if (!processing_template_decl)
15577 			init = maybe_constant_init (init);
15578 		      if (processing_template_decl
15579 			  ? potential_constant_expression (init)
15580 			  : reduced_constant_expression_p (init))
15581 			DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
15582 			  = TREE_CONSTANT (r) = true;
15583 		      DECL_INITIAL (r) = init;
15584 		      if (tree auto_node = type_uses_auto (TREE_TYPE (r)))
15585 			TREE_TYPE (r)
15586 			  = do_auto_deduction (TREE_TYPE (r), init, auto_node,
15587 					       complain, adc_variable_type);
15588 		    }
15589 		  gcc_assert (cp_unevaluated_operand || TREE_STATIC (r)
15590 			      || decl_constant_var_p (r)
15591 			      || errorcount || sorrycount);
15592 		  if (!processing_template_decl
15593 		      && !TREE_STATIC (r))
15594 		    r = process_outer_var_ref (r, complain);
15595 		}
15596 	      /* Remember this for subsequent uses.  */
15597 	      if (local_specializations)
15598 		register_local_specialization (r, t);
15599 	    }
15600 	  if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
15601 	    r = argument_pack_select_arg (r);
15602 	}
15603       else
15604 	r = t;
15605       if (!mark_used (r, complain))
15606 	return error_mark_node;
15607       return r;
15608 
15609     case NAMESPACE_DECL:
15610       return t;
15611 
15612     case OVERLOAD:
15613       /* An OVERLOAD will always be a non-dependent overload set; an
15614 	 overload set from function scope will just be represented with an
15615 	 IDENTIFIER_NODE, and from class scope with a BASELINK.  */
15616       gcc_assert (!uses_template_parms (t));
15617       /* We must have marked any lookups as persistent.  */
15618       gcc_assert (!OVL_LOOKUP_P (t) || OVL_USED_P (t));
15619       return t;
15620 
15621     case BASELINK:
15622       return tsubst_baselink (t, current_nonlambda_class_type (),
15623 			      args, complain, in_decl);
15624 
15625     case TEMPLATE_DECL:
15626       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
15627 	return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
15628 		       args, complain, in_decl);
15629       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
15630 	return tsubst (t, args, complain, in_decl);
15631       else if (DECL_CLASS_SCOPE_P (t)
15632 	       && uses_template_parms (DECL_CONTEXT (t)))
15633 	{
15634 	  /* Template template argument like the following example need
15635 	     special treatment:
15636 
15637 	       template <template <class> class TT> struct C {};
15638 	       template <class T> struct D {
15639 		 template <class U> struct E {};
15640 		 C<E> c;				// #1
15641 	       };
15642 	       D<int> d;				// #2
15643 
15644 	     We are processing the template argument `E' in #1 for
15645 	     the template instantiation #2.  Originally, `E' is a
15646 	     TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
15647 	     have to substitute this with one having context `D<int>'.  */
15648 
15649 	  tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
15650 	  if (dependent_scope_p (context))
15651 	    {
15652 	      /* When rewriting a constructor into a deduction guide, a
15653 		 non-dependent name can become dependent, so memtmpl<args>
15654 		 becomes context::template memtmpl<args>.  */
15655 	      tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15656 	      return build_qualified_name (type, context, DECL_NAME (t),
15657 					   /*template*/true);
15658 	    }
15659 	  return lookup_field (context, DECL_NAME(t), 0, false);
15660 	}
15661       else
15662 	/* Ordinary template template argument.  */
15663 	return t;
15664 
15665     case NON_LVALUE_EXPR:
15666     case VIEW_CONVERT_EXPR:
15667 	{
15668 	  /* Handle location wrappers by substituting the wrapped node
15669 	     first, *then* reusing the resulting type.  Doing the type
15670 	     first ensures that we handle template parameters and
15671 	     parameter pack expansions.  */
15672 	  gcc_assert (location_wrapper_p (t));
15673 	  tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15674 	  return maybe_wrap_with_location (op0, EXPR_LOCATION (t));
15675 	}
15676 
15677     case CAST_EXPR:
15678     case REINTERPRET_CAST_EXPR:
15679     case CONST_CAST_EXPR:
15680     case STATIC_CAST_EXPR:
15681     case DYNAMIC_CAST_EXPR:
15682     case IMPLICIT_CONV_EXPR:
15683     case CONVERT_EXPR:
15684     case NOP_EXPR:
15685       {
15686 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15687 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15688 	return build1 (code, type, op0);
15689       }
15690 
15691     case SIZEOF_EXPR:
15692       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
15693 	  || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
15694         {
15695           tree expanded, op = TREE_OPERAND (t, 0);
15696 	  int len = 0;
15697 
15698 	  if (SIZEOF_EXPR_TYPE_P (t))
15699 	    op = TREE_TYPE (op);
15700 
15701 	  ++cp_unevaluated_operand;
15702 	  ++c_inhibit_evaluation_warnings;
15703 	  /* We only want to compute the number of arguments.  */
15704 	  if (PACK_EXPANSION_P (op))
15705 	    expanded = tsubst_pack_expansion (op, args, complain, in_decl);
15706 	  else
15707 	    expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
15708 					     args, complain, in_decl);
15709 	  --cp_unevaluated_operand;
15710 	  --c_inhibit_evaluation_warnings;
15711 
15712 	  if (TREE_CODE (expanded) == TREE_VEC)
15713 	    {
15714 	      len = TREE_VEC_LENGTH (expanded);
15715 	      /* Set TREE_USED for the benefit of -Wunused.  */
15716 	      for (int i = 0; i < len; i++)
15717 		if (DECL_P (TREE_VEC_ELT (expanded, i)))
15718 		  TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
15719 	    }
15720 
15721 	  if (expanded == error_mark_node)
15722 	    return error_mark_node;
15723 	  else if (PACK_EXPANSION_P (expanded)
15724 		   || (TREE_CODE (expanded) == TREE_VEC
15725 		       && pack_expansion_args_count (expanded)))
15726 
15727 	    {
15728 	      if (PACK_EXPANSION_P (expanded))
15729 		/* OK.  */;
15730 	      else if (TREE_VEC_LENGTH (expanded) == 1)
15731 		expanded = TREE_VEC_ELT (expanded, 0);
15732 	      else
15733 		expanded = make_argument_pack (expanded);
15734 
15735 	      if (TYPE_P (expanded))
15736 		return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR,
15737 						   false,
15738 						   complain & tf_error);
15739 	      else
15740 		return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
15741                                                    complain & tf_error);
15742 	    }
15743 	  else
15744 	    return build_int_cst (size_type_node, len);
15745         }
15746       if (SIZEOF_EXPR_TYPE_P (t))
15747 	{
15748 	  r = tsubst (TREE_TYPE (TREE_OPERAND (t, 0)),
15749 		      args, complain, in_decl);
15750 	  r = build1 (NOP_EXPR, r, error_mark_node);
15751 	  r = build1 (SIZEOF_EXPR,
15752 		      tsubst (TREE_TYPE (t), args, complain, in_decl), r);
15753 	  SIZEOF_EXPR_TYPE_P (r) = 1;
15754 	  return r;
15755 	}
15756       /* Fall through */
15757 
15758     case INDIRECT_REF:
15759     case NEGATE_EXPR:
15760     case TRUTH_NOT_EXPR:
15761     case BIT_NOT_EXPR:
15762     case ADDR_EXPR:
15763     case UNARY_PLUS_EXPR:      /* Unary + */
15764     case ALIGNOF_EXPR:
15765     case AT_ENCODE_EXPR:
15766     case ARROW_EXPR:
15767     case THROW_EXPR:
15768     case TYPEID_EXPR:
15769     case REALPART_EXPR:
15770     case IMAGPART_EXPR:
15771     case PAREN_EXPR:
15772       {
15773 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15774 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15775 	r = build1 (code, type, op0);
15776 	if (code == ALIGNOF_EXPR)
15777 	  ALIGNOF_EXPR_STD_P (r) = ALIGNOF_EXPR_STD_P (t);
15778 	return r;
15779       }
15780 
15781     case COMPONENT_REF:
15782       {
15783 	tree object;
15784 	tree name;
15785 
15786 	object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15787 	name = TREE_OPERAND (t, 1);
15788 	if (TREE_CODE (name) == BIT_NOT_EXPR)
15789 	  {
15790 	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
15791 				complain, in_decl);
15792 	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
15793 	  }
15794 	else if (TREE_CODE (name) == SCOPE_REF
15795 		 && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
15796 	  {
15797 	    tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
15798 				     complain, in_decl);
15799 	    name = TREE_OPERAND (name, 1);
15800 	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
15801 				complain, in_decl);
15802 	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
15803 	    name = build_qualified_name (/*type=*/NULL_TREE,
15804 					 base, name,
15805 					 /*template_p=*/false);
15806 	  }
15807 	else if (BASELINK_P (name))
15808 	  name = tsubst_baselink (name,
15809 				  non_reference (TREE_TYPE (object)),
15810 				  args, complain,
15811 				  in_decl);
15812 	else
15813 	  name = tsubst_copy (name, args, complain, in_decl);
15814 	return build_nt (COMPONENT_REF, object, name, NULL_TREE);
15815       }
15816 
15817     case PLUS_EXPR:
15818     case MINUS_EXPR:
15819     case MULT_EXPR:
15820     case TRUNC_DIV_EXPR:
15821     case CEIL_DIV_EXPR:
15822     case FLOOR_DIV_EXPR:
15823     case ROUND_DIV_EXPR:
15824     case EXACT_DIV_EXPR:
15825     case BIT_AND_EXPR:
15826     case BIT_IOR_EXPR:
15827     case BIT_XOR_EXPR:
15828     case TRUNC_MOD_EXPR:
15829     case FLOOR_MOD_EXPR:
15830     case TRUTH_ANDIF_EXPR:
15831     case TRUTH_ORIF_EXPR:
15832     case TRUTH_AND_EXPR:
15833     case TRUTH_OR_EXPR:
15834     case RSHIFT_EXPR:
15835     case LSHIFT_EXPR:
15836     case RROTATE_EXPR:
15837     case LROTATE_EXPR:
15838     case EQ_EXPR:
15839     case NE_EXPR:
15840     case MAX_EXPR:
15841     case MIN_EXPR:
15842     case LE_EXPR:
15843     case GE_EXPR:
15844     case LT_EXPR:
15845     case GT_EXPR:
15846     case COMPOUND_EXPR:
15847     case DOTSTAR_EXPR:
15848     case MEMBER_REF:
15849     case PREDECREMENT_EXPR:
15850     case PREINCREMENT_EXPR:
15851     case POSTDECREMENT_EXPR:
15852     case POSTINCREMENT_EXPR:
15853       {
15854 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15855 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15856 	return build_nt (code, op0, op1);
15857       }
15858 
15859     case SCOPE_REF:
15860       {
15861 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15862 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15863 	return build_qualified_name (/*type=*/NULL_TREE, op0, op1,
15864 				     QUALIFIED_NAME_IS_TEMPLATE (t));
15865       }
15866 
15867     case ARRAY_REF:
15868       {
15869 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15870 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15871 	return build_nt (ARRAY_REF, op0, op1, NULL_TREE, NULL_TREE);
15872       }
15873 
15874     case CALL_EXPR:
15875       {
15876 	int n = VL_EXP_OPERAND_LENGTH (t);
15877 	tree result = build_vl_exp (CALL_EXPR, n);
15878 	int i;
15879 	for (i = 0; i < n; i++)
15880 	  TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
15881 					     complain, in_decl);
15882 	return result;
15883       }
15884 
15885     case COND_EXPR:
15886     case MODOP_EXPR:
15887     case PSEUDO_DTOR_EXPR:
15888     case VEC_PERM_EXPR:
15889       {
15890 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15891 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15892 	tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
15893 	r = build_nt (code, op0, op1, op2);
15894 	TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
15895 	return r;
15896       }
15897 
15898     case NEW_EXPR:
15899       {
15900 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15901 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15902 	tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
15903 	r = build_nt (code, op0, op1, op2);
15904 	NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
15905 	return r;
15906       }
15907 
15908     case DELETE_EXPR:
15909       {
15910 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15911 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15912 	r = build_nt (code, op0, op1);
15913 	DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
15914 	DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
15915 	return r;
15916       }
15917 
15918     case TEMPLATE_ID_EXPR:
15919       {
15920 	/* Substituted template arguments */
15921 	tree fn = TREE_OPERAND (t, 0);
15922 	tree targs = TREE_OPERAND (t, 1);
15923 
15924 	fn = tsubst_copy (fn, args, complain, in_decl);
15925 	if (targs)
15926 	  targs = tsubst_template_args (targs, args, complain, in_decl);
15927 
15928 	return lookup_template_function (fn, targs);
15929       }
15930 
15931     case TREE_LIST:
15932       {
15933 	tree purpose, value, chain;
15934 
15935 	if (t == void_list_node)
15936 	  return t;
15937 
15938 	purpose = TREE_PURPOSE (t);
15939 	if (purpose)
15940 	  purpose = tsubst_copy (purpose, args, complain, in_decl);
15941 	value = TREE_VALUE (t);
15942 	if (value)
15943 	  value = tsubst_copy (value, args, complain, in_decl);
15944 	chain = TREE_CHAIN (t);
15945 	if (chain && chain != void_type_node)
15946 	  chain = tsubst_copy (chain, args, complain, in_decl);
15947 	if (purpose == TREE_PURPOSE (t)
15948 	    && value == TREE_VALUE (t)
15949 	    && chain == TREE_CHAIN (t))
15950 	  return t;
15951 	return tree_cons (purpose, value, chain);
15952       }
15953 
15954     case RECORD_TYPE:
15955     case UNION_TYPE:
15956     case ENUMERAL_TYPE:
15957     case INTEGER_TYPE:
15958     case TEMPLATE_TYPE_PARM:
15959     case TEMPLATE_TEMPLATE_PARM:
15960     case BOUND_TEMPLATE_TEMPLATE_PARM:
15961     case TEMPLATE_PARM_INDEX:
15962     case POINTER_TYPE:
15963     case REFERENCE_TYPE:
15964     case OFFSET_TYPE:
15965     case FUNCTION_TYPE:
15966     case METHOD_TYPE:
15967     case ARRAY_TYPE:
15968     case TYPENAME_TYPE:
15969     case UNBOUND_CLASS_TEMPLATE:
15970     case TYPEOF_TYPE:
15971     case DECLTYPE_TYPE:
15972     case TYPE_DECL:
15973       return tsubst (t, args, complain, in_decl);
15974 
15975     case USING_DECL:
15976       t = DECL_NAME (t);
15977       /* Fall through.  */
15978     case IDENTIFIER_NODE:
15979       if (IDENTIFIER_CONV_OP_P (t))
15980 	{
15981 	  tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15982 	  return make_conv_op_name (new_type);
15983 	}
15984       else
15985 	return t;
15986 
15987     case CONSTRUCTOR:
15988       /* This is handled by tsubst_copy_and_build.  */
15989       gcc_unreachable ();
15990 
15991     case VA_ARG_EXPR:
15992       {
15993 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15994 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15995 	return build_x_va_arg (EXPR_LOCATION (t), op0, type);
15996       }
15997 
15998     case CLEANUP_POINT_EXPR:
15999       /* We shouldn't have built any of these during initial template
16000 	 generation.  Instead, they should be built during instantiation
16001 	 in response to the saved STMT_IS_FULL_EXPR_P setting.  */
16002       gcc_unreachable ();
16003 
16004     case OFFSET_REF:
16005       {
16006 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16007 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16008 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16009 	r = build2 (code, type, op0, op1);
16010 	PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
16011 	if (!mark_used (TREE_OPERAND (r, 1), complain)
16012 	    && !(complain & tf_error))
16013 	  return error_mark_node;
16014 	return r;
16015       }
16016 
16017     case EXPR_PACK_EXPANSION:
16018       error ("invalid use of pack expansion expression");
16019       return error_mark_node;
16020 
16021     case NONTYPE_ARGUMENT_PACK:
16022       error ("use %<...%> to expand argument pack");
16023       return error_mark_node;
16024 
16025     case VOID_CST:
16026       gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
16027       return t;
16028 
16029     case INTEGER_CST:
16030     case REAL_CST:
16031     case STRING_CST:
16032     case COMPLEX_CST:
16033       {
16034 	/* Instantiate any typedefs in the type.  */
16035 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16036 	r = fold_convert (type, t);
16037 	gcc_assert (TREE_CODE (r) == code);
16038 	return r;
16039       }
16040 
16041     case PTRMEM_CST:
16042       /* These can sometimes show up in a partial instantiation, but never
16043 	 involve template parms.  */
16044       gcc_assert (!uses_template_parms (t));
16045       return t;
16046 
16047     case UNARY_LEFT_FOLD_EXPR:
16048       return tsubst_unary_left_fold (t, args, complain, in_decl);
16049     case UNARY_RIGHT_FOLD_EXPR:
16050       return tsubst_unary_right_fold (t, args, complain, in_decl);
16051     case BINARY_LEFT_FOLD_EXPR:
16052       return tsubst_binary_left_fold (t, args, complain, in_decl);
16053     case BINARY_RIGHT_FOLD_EXPR:
16054       return tsubst_binary_right_fold (t, args, complain, in_decl);
16055     case PREDICT_EXPR:
16056       return t;
16057 
16058     case DEBUG_BEGIN_STMT:
16059       /* ??? There's no point in copying it for now, but maybe some
16060 	 day it will contain more information, such as a pointer back
16061 	 to the containing function, inlined copy or so.  */
16062       return t;
16063 
16064     default:
16065       /* We shouldn't get here, but keep going if !flag_checking.  */
16066       if (flag_checking)
16067 	gcc_unreachable ();
16068       return t;
16069     }
16070 }
16071 
16072 /* Helper function for tsubst_omp_clauses, used for instantiation of
16073    OMP_CLAUSE_DECL of clauses.  */
16074 
16075 static tree
tsubst_omp_clause_decl(tree decl,tree args,tsubst_flags_t complain,tree in_decl)16076 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
16077 			tree in_decl)
16078 {
16079   if (decl == NULL_TREE)
16080     return NULL_TREE;
16081 
16082   /* Handle an OpenMP array section represented as a TREE_LIST (or
16083      OMP_CLAUSE_DEPEND_KIND).  An OMP_CLAUSE_DEPEND (with a depend
16084      kind of OMP_CLAUSE_DEPEND_SINK) can also be represented as a
16085      TREE_LIST.  We can handle it exactly the same as an array section
16086      (purpose, value, and a chain), even though the nomenclature
16087      (low_bound, length, etc) is different.  */
16088   if (TREE_CODE (decl) == TREE_LIST)
16089     {
16090       tree low_bound
16091 	= tsubst_expr (TREE_PURPOSE (decl), args, complain, in_decl,
16092 		       /*integral_constant_expression_p=*/false);
16093       tree length = tsubst_expr (TREE_VALUE (decl), args, complain, in_decl,
16094 				 /*integral_constant_expression_p=*/false);
16095       tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
16096 					   in_decl);
16097       if (TREE_PURPOSE (decl) == low_bound
16098 	  && TREE_VALUE (decl) == length
16099 	  && TREE_CHAIN (decl) == chain)
16100 	return decl;
16101       tree ret = tree_cons (low_bound, length, chain);
16102       OMP_CLAUSE_DEPEND_SINK_NEGATIVE (ret)
16103 	= OMP_CLAUSE_DEPEND_SINK_NEGATIVE (decl);
16104       return ret;
16105     }
16106   tree ret = tsubst_expr (decl, args, complain, in_decl,
16107 			  /*integral_constant_expression_p=*/false);
16108   /* Undo convert_from_reference tsubst_expr could have called.  */
16109   if (decl
16110       && REFERENCE_REF_P (ret)
16111       && !REFERENCE_REF_P (decl))
16112     ret = TREE_OPERAND (ret, 0);
16113   return ret;
16114 }
16115 
16116 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
16117 
16118 static tree
tsubst_omp_clauses(tree clauses,enum c_omp_region_type ort,tree args,tsubst_flags_t complain,tree in_decl)16119 tsubst_omp_clauses (tree clauses, enum c_omp_region_type ort,
16120 		    tree args, tsubst_flags_t complain, tree in_decl)
16121 {
16122   tree new_clauses = NULL_TREE, nc, oc;
16123   tree linear_no_step = NULL_TREE;
16124 
16125   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
16126     {
16127       nc = copy_node (oc);
16128       OMP_CLAUSE_CHAIN (nc) = new_clauses;
16129       new_clauses = nc;
16130 
16131       switch (OMP_CLAUSE_CODE (nc))
16132 	{
16133 	case OMP_CLAUSE_LASTPRIVATE:
16134 	  if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
16135 	    {
16136 	      OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
16137 	      tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
16138 			   in_decl, /*integral_constant_expression_p=*/false);
16139 	      OMP_CLAUSE_LASTPRIVATE_STMT (nc)
16140 		= pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
16141 	    }
16142 	  /* FALLTHRU */
16143 	case OMP_CLAUSE_PRIVATE:
16144 	case OMP_CLAUSE_SHARED:
16145 	case OMP_CLAUSE_FIRSTPRIVATE:
16146 	case OMP_CLAUSE_COPYIN:
16147 	case OMP_CLAUSE_COPYPRIVATE:
16148 	case OMP_CLAUSE_UNIFORM:
16149 	case OMP_CLAUSE_DEPEND:
16150 	case OMP_CLAUSE_FROM:
16151 	case OMP_CLAUSE_TO:
16152 	case OMP_CLAUSE_MAP:
16153 	case OMP_CLAUSE__CACHE_:
16154 	case OMP_CLAUSE_USE_DEVICE_PTR:
16155 	case OMP_CLAUSE_IS_DEVICE_PTR:
16156 	  OMP_CLAUSE_DECL (nc)
16157 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16158 				      in_decl);
16159 	  break;
16160 	case OMP_CLAUSE_TILE:
16161 	case OMP_CLAUSE_IF:
16162 	case OMP_CLAUSE_NUM_THREADS:
16163 	case OMP_CLAUSE_SCHEDULE:
16164 	case OMP_CLAUSE_COLLAPSE:
16165 	case OMP_CLAUSE_FINAL:
16166 	case OMP_CLAUSE_DEVICE:
16167 	case OMP_CLAUSE_DIST_SCHEDULE:
16168 	case OMP_CLAUSE_NUM_TEAMS:
16169 	case OMP_CLAUSE_THREAD_LIMIT:
16170 	case OMP_CLAUSE_SAFELEN:
16171 	case OMP_CLAUSE_SIMDLEN:
16172 	case OMP_CLAUSE_NUM_TASKS:
16173 	case OMP_CLAUSE_GRAINSIZE:
16174 	case OMP_CLAUSE_PRIORITY:
16175 	case OMP_CLAUSE_ORDERED:
16176 	case OMP_CLAUSE_HINT:
16177 	case OMP_CLAUSE_NUM_GANGS:
16178 	case OMP_CLAUSE_NUM_WORKERS:
16179 	case OMP_CLAUSE_VECTOR_LENGTH:
16180 	case OMP_CLAUSE_WORKER:
16181 	case OMP_CLAUSE_VECTOR:
16182 	case OMP_CLAUSE_ASYNC:
16183 	case OMP_CLAUSE_WAIT:
16184 	  OMP_CLAUSE_OPERAND (nc, 0)
16185 	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain,
16186 			   in_decl, /*integral_constant_expression_p=*/false);
16187 	  break;
16188 	case OMP_CLAUSE_REDUCTION:
16189 	  if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
16190 	    {
16191 	      tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
16192 	      if (TREE_CODE (placeholder) == SCOPE_REF)
16193 		{
16194 		  tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
16195 				       complain, in_decl);
16196 		  OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
16197 		    = build_qualified_name (NULL_TREE, scope,
16198 					    TREE_OPERAND (placeholder, 1),
16199 					    false);
16200 		}
16201 	      else
16202 		gcc_assert (identifier_p (placeholder));
16203 	    }
16204 	  OMP_CLAUSE_DECL (nc)
16205 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16206 				      in_decl);
16207 	  break;
16208 	case OMP_CLAUSE_GANG:
16209 	case OMP_CLAUSE_ALIGNED:
16210 	  OMP_CLAUSE_DECL (nc)
16211 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16212 				      in_decl);
16213 	  OMP_CLAUSE_OPERAND (nc, 1)
16214 	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain,
16215 			   in_decl, /*integral_constant_expression_p=*/false);
16216 	  break;
16217 	case OMP_CLAUSE_LINEAR:
16218 	  OMP_CLAUSE_DECL (nc)
16219 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16220 				      in_decl);
16221 	  if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
16222 	    {
16223 	      gcc_assert (!linear_no_step);
16224 	      linear_no_step = nc;
16225 	    }
16226 	  else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
16227 	    OMP_CLAUSE_LINEAR_STEP (nc)
16228 	      = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
16229 					complain, in_decl);
16230 	  else
16231 	    OMP_CLAUSE_LINEAR_STEP (nc)
16232 	      = tsubst_expr (OMP_CLAUSE_LINEAR_STEP (oc), args, complain,
16233 			     in_decl,
16234 			     /*integral_constant_expression_p=*/false);
16235 	  break;
16236 	case OMP_CLAUSE_NOWAIT:
16237 	case OMP_CLAUSE_DEFAULT:
16238 	case OMP_CLAUSE_UNTIED:
16239 	case OMP_CLAUSE_MERGEABLE:
16240 	case OMP_CLAUSE_INBRANCH:
16241 	case OMP_CLAUSE_NOTINBRANCH:
16242 	case OMP_CLAUSE_PROC_BIND:
16243 	case OMP_CLAUSE_FOR:
16244 	case OMP_CLAUSE_PARALLEL:
16245 	case OMP_CLAUSE_SECTIONS:
16246 	case OMP_CLAUSE_TASKGROUP:
16247 	case OMP_CLAUSE_NOGROUP:
16248 	case OMP_CLAUSE_THREADS:
16249 	case OMP_CLAUSE_SIMD:
16250 	case OMP_CLAUSE_DEFAULTMAP:
16251 	case OMP_CLAUSE_INDEPENDENT:
16252 	case OMP_CLAUSE_AUTO:
16253 	case OMP_CLAUSE_SEQ:
16254 	  break;
16255 	default:
16256 	  gcc_unreachable ();
16257 	}
16258       if ((ort & C_ORT_OMP_DECLARE_SIMD) == C_ORT_OMP)
16259 	switch (OMP_CLAUSE_CODE (nc))
16260 	  {
16261 	  case OMP_CLAUSE_SHARED:
16262 	  case OMP_CLAUSE_PRIVATE:
16263 	  case OMP_CLAUSE_FIRSTPRIVATE:
16264 	  case OMP_CLAUSE_LASTPRIVATE:
16265 	  case OMP_CLAUSE_COPYPRIVATE:
16266 	  case OMP_CLAUSE_LINEAR:
16267 	  case OMP_CLAUSE_REDUCTION:
16268 	  case OMP_CLAUSE_USE_DEVICE_PTR:
16269 	  case OMP_CLAUSE_IS_DEVICE_PTR:
16270 	    /* tsubst_expr on SCOPE_REF results in returning
16271 	       finish_non_static_data_member result.  Undo that here.  */
16272 	    if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
16273 		&& (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
16274 		    == IDENTIFIER_NODE))
16275 	      {
16276 		tree t = OMP_CLAUSE_DECL (nc);
16277 		tree v = t;
16278 		while (v)
16279 		  switch (TREE_CODE (v))
16280 		    {
16281 		    case COMPONENT_REF:
16282 		    case MEM_REF:
16283 		    case INDIRECT_REF:
16284 		    CASE_CONVERT:
16285 		    case POINTER_PLUS_EXPR:
16286 		      v = TREE_OPERAND (v, 0);
16287 		      continue;
16288 		    case PARM_DECL:
16289 		      if (DECL_CONTEXT (v) == current_function_decl
16290 			  && DECL_ARTIFICIAL (v)
16291 			  && DECL_NAME (v) == this_identifier)
16292 			OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
16293 		      /* FALLTHRU */
16294 		    default:
16295 		      v = NULL_TREE;
16296 		      break;
16297 		    }
16298 	      }
16299 	    else if (VAR_P (OMP_CLAUSE_DECL (oc))
16300 		     && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
16301 		     && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
16302 		     && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
16303 		     && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
16304 	      {
16305 		tree decl = OMP_CLAUSE_DECL (nc);
16306 		if (VAR_P (decl))
16307 		  {
16308 		    retrofit_lang_decl (decl);
16309 		    DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
16310 		  }
16311 	      }
16312 	    break;
16313 	  default:
16314 	    break;
16315 	  }
16316     }
16317 
16318   new_clauses = nreverse (new_clauses);
16319   if (ort != C_ORT_OMP_DECLARE_SIMD)
16320     {
16321       new_clauses = finish_omp_clauses (new_clauses, ort);
16322       if (linear_no_step)
16323 	for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
16324 	  if (nc == linear_no_step)
16325 	    {
16326 	      OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
16327 	      break;
16328 	    }
16329     }
16330   return new_clauses;
16331 }
16332 
16333 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
16334 
16335 static tree
tsubst_copy_asm_operands(tree t,tree args,tsubst_flags_t complain,tree in_decl)16336 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
16337 			  tree in_decl)
16338 {
16339 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
16340 
16341   tree purpose, value, chain;
16342 
16343   if (t == NULL)
16344     return t;
16345 
16346   if (TREE_CODE (t) != TREE_LIST)
16347     return tsubst_copy_and_build (t, args, complain, in_decl,
16348 				  /*function_p=*/false,
16349 				  /*integral_constant_expression_p=*/false);
16350 
16351   if (t == void_list_node)
16352     return t;
16353 
16354   purpose = TREE_PURPOSE (t);
16355   if (purpose)
16356     purpose = RECUR (purpose);
16357   value = TREE_VALUE (t);
16358   if (value)
16359     {
16360       if (TREE_CODE (value) != LABEL_DECL)
16361 	value = RECUR (value);
16362       else
16363 	{
16364 	  value = lookup_label (DECL_NAME (value));
16365 	  gcc_assert (TREE_CODE (value) == LABEL_DECL);
16366 	  TREE_USED (value) = 1;
16367 	}
16368     }
16369   chain = TREE_CHAIN (t);
16370   if (chain && chain != void_type_node)
16371     chain = RECUR (chain);
16372   return tree_cons (purpose, value, chain);
16373 #undef RECUR
16374 }
16375 
16376 /* Used to temporarily communicate the list of #pragma omp parallel
16377    clauses to #pragma omp for instantiation if they are combined
16378    together.  */
16379 
16380 static tree *omp_parallel_combined_clauses;
16381 
16382 /* Substitute one OMP_FOR iterator.  */
16383 
16384 static void
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)16385 tsubst_omp_for_iterator (tree t, int i, tree declv, tree orig_declv,
16386 			 tree initv, tree condv, tree incrv, tree *clauses,
16387 			 tree args, tsubst_flags_t complain, tree in_decl,
16388 			 bool integral_constant_expression_p)
16389 {
16390 #define RECUR(NODE)				\
16391   tsubst_expr ((NODE), args, complain, in_decl,	\
16392 	       integral_constant_expression_p)
16393   tree decl, init, cond, incr;
16394 
16395   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
16396   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
16397 
16398   if (orig_declv && OMP_FOR_ORIG_DECLS (t))
16399     {
16400       tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
16401       TREE_VEC_ELT (orig_declv, i) = RECUR (o);
16402     }
16403 
16404   decl = TREE_OPERAND (init, 0);
16405   init = TREE_OPERAND (init, 1);
16406   tree decl_expr = NULL_TREE;
16407   if (init && TREE_CODE (init) == DECL_EXPR)
16408     {
16409       /* We need to jump through some hoops to handle declarations in the
16410 	 init-statement, since we might need to handle auto deduction,
16411 	 but we need to keep control of initialization.  */
16412       decl_expr = init;
16413       init = DECL_INITIAL (DECL_EXPR_DECL (init));
16414       decl = tsubst_decl (decl, args, complain);
16415     }
16416   else
16417     {
16418       if (TREE_CODE (decl) == SCOPE_REF)
16419 	{
16420 	  decl = RECUR (decl);
16421 	  if (TREE_CODE (decl) == COMPONENT_REF)
16422 	    {
16423 	      tree v = decl;
16424 	      while (v)
16425 		switch (TREE_CODE (v))
16426 		  {
16427 		  case COMPONENT_REF:
16428 		  case MEM_REF:
16429 		  case INDIRECT_REF:
16430 		  CASE_CONVERT:
16431 		  case POINTER_PLUS_EXPR:
16432 		    v = TREE_OPERAND (v, 0);
16433 		    continue;
16434 		  case PARM_DECL:
16435 		    if (DECL_CONTEXT (v) == current_function_decl
16436 			&& DECL_ARTIFICIAL (v)
16437 			&& DECL_NAME (v) == this_identifier)
16438 		      {
16439 			decl = TREE_OPERAND (decl, 1);
16440 			decl = omp_privatize_field (decl, false);
16441 		      }
16442 		    /* FALLTHRU */
16443 		  default:
16444 		    v = NULL_TREE;
16445 		    break;
16446 		  }
16447 	    }
16448 	}
16449       else
16450 	decl = RECUR (decl);
16451     }
16452   init = RECUR (init);
16453 
16454   tree auto_node = type_uses_auto (TREE_TYPE (decl));
16455   if (auto_node && init)
16456     TREE_TYPE (decl)
16457       = do_auto_deduction (TREE_TYPE (decl), init, auto_node, complain);
16458 
16459   gcc_assert (!type_dependent_expression_p (decl));
16460 
16461   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
16462     {
16463       if (decl_expr)
16464 	{
16465 	  /* Declare the variable, but don't let that initialize it.  */
16466 	  tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
16467 	  DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
16468 	  RECUR (decl_expr);
16469 	  DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
16470 	}
16471 
16472       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
16473       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
16474       if (TREE_CODE (incr) == MODIFY_EXPR)
16475 	{
16476 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
16477 	  tree rhs = RECUR (TREE_OPERAND (incr, 1));
16478 	  incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
16479 				      NOP_EXPR, rhs, complain);
16480 	}
16481       else
16482 	incr = RECUR (incr);
16483       TREE_VEC_ELT (declv, i) = decl;
16484       TREE_VEC_ELT (initv, i) = init;
16485       TREE_VEC_ELT (condv, i) = cond;
16486       TREE_VEC_ELT (incrv, i) = incr;
16487       return;
16488     }
16489 
16490   if (decl_expr)
16491     {
16492       /* Declare and initialize the variable.  */
16493       RECUR (decl_expr);
16494       init = NULL_TREE;
16495     }
16496   else if (init)
16497     {
16498       tree *pc;
16499       int j;
16500       for (j = (omp_parallel_combined_clauses == NULL ? 1 : 0); j < 2; j++)
16501 	{
16502 	  for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
16503 	    {
16504 	      if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
16505 		  && OMP_CLAUSE_DECL (*pc) == decl)
16506 		break;
16507 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
16508 		       && OMP_CLAUSE_DECL (*pc) == decl)
16509 		{
16510 		  if (j)
16511 		    break;
16512 		  /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES.  */
16513 		  tree c = *pc;
16514 		  *pc = OMP_CLAUSE_CHAIN (c);
16515 		  OMP_CLAUSE_CHAIN (c) = *clauses;
16516 		  *clauses = c;
16517 		}
16518 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
16519 		       && OMP_CLAUSE_DECL (*pc) == decl)
16520 		{
16521 		  error ("iteration variable %qD should not be firstprivate",
16522 			 decl);
16523 		  *pc = OMP_CLAUSE_CHAIN (*pc);
16524 		}
16525 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
16526 		       && OMP_CLAUSE_DECL (*pc) == decl)
16527 		{
16528 		  error ("iteration variable %qD should not be reduction",
16529 			 decl);
16530 		  *pc = OMP_CLAUSE_CHAIN (*pc);
16531 		}
16532 	      else
16533 		pc = &OMP_CLAUSE_CHAIN (*pc);
16534 	    }
16535 	  if (*pc)
16536 	    break;
16537 	}
16538       if (*pc == NULL_TREE)
16539 	{
16540 	  tree c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
16541 	  OMP_CLAUSE_DECL (c) = decl;
16542 	  c = finish_omp_clauses (c, C_ORT_OMP);
16543 	  if (c)
16544 	    {
16545 	      OMP_CLAUSE_CHAIN (c) = *clauses;
16546 	      *clauses = c;
16547 	    }
16548 	}
16549     }
16550   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
16551   if (COMPARISON_CLASS_P (cond))
16552     {
16553       tree op0 = RECUR (TREE_OPERAND (cond, 0));
16554       tree op1 = RECUR (TREE_OPERAND (cond, 1));
16555       cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
16556     }
16557   else
16558     cond = RECUR (cond);
16559   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
16560   switch (TREE_CODE (incr))
16561     {
16562     case PREINCREMENT_EXPR:
16563     case PREDECREMENT_EXPR:
16564     case POSTINCREMENT_EXPR:
16565     case POSTDECREMENT_EXPR:
16566       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
16567 		     RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
16568       break;
16569     case MODIFY_EXPR:
16570       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
16571 	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
16572 	{
16573 	  tree rhs = TREE_OPERAND (incr, 1);
16574 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
16575 	  tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
16576 	  tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
16577 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
16578 			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
16579 				 rhs0, rhs1));
16580 	}
16581       else
16582 	incr = RECUR (incr);
16583       break;
16584     case MODOP_EXPR:
16585       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
16586 	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
16587 	{
16588 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
16589 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
16590 			 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
16591 				 TREE_TYPE (decl), lhs,
16592 				 RECUR (TREE_OPERAND (incr, 2))));
16593 	}
16594       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
16595 	       && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
16596 		   || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
16597 	{
16598 	  tree rhs = TREE_OPERAND (incr, 2);
16599 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
16600 	  tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
16601 	  tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
16602 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
16603 			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
16604 				 rhs0, rhs1));
16605 	}
16606       else
16607 	incr = RECUR (incr);
16608       break;
16609     default:
16610       incr = RECUR (incr);
16611       break;
16612     }
16613 
16614   TREE_VEC_ELT (declv, i) = decl;
16615   TREE_VEC_ELT (initv, i) = init;
16616   TREE_VEC_ELT (condv, i) = cond;
16617   TREE_VEC_ELT (incrv, i) = incr;
16618 #undef RECUR
16619 }
16620 
16621 /* Helper function of tsubst_expr, find OMP_TEAMS inside
16622    of OMP_TARGET's body.  */
16623 
16624 static tree
tsubst_find_omp_teams(tree * tp,int * walk_subtrees,void *)16625 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
16626 {
16627   *walk_subtrees = 0;
16628   switch (TREE_CODE (*tp))
16629     {
16630     case OMP_TEAMS:
16631       return *tp;
16632     case BIND_EXPR:
16633     case STATEMENT_LIST:
16634       *walk_subtrees = 1;
16635       break;
16636     default:
16637       break;
16638     }
16639   return NULL_TREE;
16640 }
16641 
16642 /* Helper function for tsubst_expr.  For decomposition declaration
16643    artificial base DECL, which is tsubsted PATTERN_DECL, tsubst
16644    also the corresponding decls representing the identifiers
16645    of the decomposition declaration.  Return DECL if successful
16646    or error_mark_node otherwise, set *FIRST to the first decl
16647    in the list chained through DECL_CHAIN and *CNT to the number
16648    of such decls.  */
16649 
16650 static tree
tsubst_decomp_names(tree decl,tree pattern_decl,tree args,tsubst_flags_t complain,tree in_decl,tree * first,unsigned int * cnt)16651 tsubst_decomp_names (tree decl, tree pattern_decl, tree args,
16652 		     tsubst_flags_t complain, tree in_decl, tree *first,
16653 		     unsigned int *cnt)
16654 {
16655   tree decl2, decl3, prev = decl;
16656   *cnt = 0;
16657   gcc_assert (DECL_NAME (decl) == NULL_TREE);
16658   for (decl2 = DECL_CHAIN (pattern_decl);
16659        decl2
16660        && VAR_P (decl2)
16661        && DECL_DECOMPOSITION_P (decl2)
16662        && DECL_NAME (decl2);
16663        decl2 = DECL_CHAIN (decl2))
16664     {
16665       if (TREE_TYPE (decl2) == error_mark_node && *cnt == 0)
16666 	{
16667 	  gcc_assert (errorcount);
16668 	  return error_mark_node;
16669 	}
16670       (*cnt)++;
16671       gcc_assert (DECL_DECOMP_BASE (decl2) == pattern_decl);
16672       gcc_assert (DECL_HAS_VALUE_EXPR_P (decl2));
16673       tree v = DECL_VALUE_EXPR (decl2);
16674       DECL_HAS_VALUE_EXPR_P (decl2) = 0;
16675       SET_DECL_VALUE_EXPR (decl2, NULL_TREE);
16676       decl3 = tsubst (decl2, args, complain, in_decl);
16677       SET_DECL_VALUE_EXPR (decl2, v);
16678       DECL_HAS_VALUE_EXPR_P (decl2) = 1;
16679       if (VAR_P (decl3))
16680 	DECL_TEMPLATE_INSTANTIATED (decl3) = 1;
16681       else
16682 	{
16683 	  gcc_assert (errorcount);
16684 	  decl = error_mark_node;
16685 	  continue;
16686 	}
16687       maybe_push_decl (decl3);
16688       if (error_operand_p (decl3))
16689 	decl = error_mark_node;
16690       else if (decl != error_mark_node
16691 	       && DECL_CHAIN (decl3) != prev
16692 	       && decl != prev)
16693 	{
16694 	  gcc_assert (errorcount);
16695 	  decl = error_mark_node;
16696 	}
16697       else
16698 	prev = decl3;
16699     }
16700   *first = prev;
16701   return decl;
16702 }
16703 
16704 /* Like tsubst_copy for expressions, etc. but also does semantic
16705    processing.  */
16706 
16707 tree
tsubst_expr(tree t,tree args,tsubst_flags_t complain,tree in_decl,bool integral_constant_expression_p)16708 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
16709 	     bool integral_constant_expression_p)
16710 {
16711 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
16712 #define RECUR(NODE)				\
16713   tsubst_expr ((NODE), args, complain, in_decl,	\
16714 	       integral_constant_expression_p)
16715 
16716   tree stmt, tmp;
16717   tree r;
16718   location_t loc;
16719 
16720   if (t == NULL_TREE || t == error_mark_node)
16721     return t;
16722 
16723   loc = input_location;
16724   if (EXPR_HAS_LOCATION (t))
16725     input_location = EXPR_LOCATION (t);
16726   if (STATEMENT_CODE_P (TREE_CODE (t)))
16727     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
16728 
16729   switch (TREE_CODE (t))
16730     {
16731     case STATEMENT_LIST:
16732       {
16733 	tree_stmt_iterator i;
16734 	for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
16735 	  RECUR (tsi_stmt (i));
16736 	break;
16737       }
16738 
16739     case CTOR_INITIALIZER:
16740       finish_mem_initializers (tsubst_initializer_list
16741 			       (TREE_OPERAND (t, 0), args));
16742       break;
16743 
16744     case RETURN_EXPR:
16745       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
16746       break;
16747 
16748     case EXPR_STMT:
16749       tmp = RECUR (EXPR_STMT_EXPR (t));
16750       if (EXPR_STMT_STMT_EXPR_RESULT (t))
16751 	finish_stmt_expr_expr (tmp, cur_stmt_expr);
16752       else
16753 	finish_expr_stmt (tmp);
16754       break;
16755 
16756     case USING_STMT:
16757       finish_local_using_directive (USING_STMT_NAMESPACE (t),
16758 				    /*attribs=*/NULL_TREE);
16759       break;
16760 
16761     case DECL_EXPR:
16762       {
16763 	tree decl, pattern_decl;
16764 	tree init;
16765 
16766 	pattern_decl = decl = DECL_EXPR_DECL (t);
16767 	if (TREE_CODE (decl) == LABEL_DECL)
16768 	  finish_label_decl (DECL_NAME (decl));
16769 	else if (TREE_CODE (decl) == USING_DECL)
16770 	  {
16771 	    tree scope = USING_DECL_SCOPE (decl);
16772 	    tree name = DECL_NAME (decl);
16773 
16774 	    scope = tsubst (scope, args, complain, in_decl);
16775 	    decl = lookup_qualified_name (scope, name,
16776 					  /*is_type_p=*/false,
16777 					  /*complain=*/false);
16778 	    if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
16779 	      qualified_name_lookup_error (scope, name, decl, input_location);
16780 	    else
16781 	      finish_local_using_decl (decl, scope, name);
16782 	  }
16783 	else if (is_capture_proxy (decl)
16784 		 && !DECL_TEMPLATE_INSTANTIATION (current_function_decl))
16785 	  {
16786 	    /* We're in tsubst_lambda_expr, we've already inserted a new
16787 	       capture proxy, so look it up and register it.  */
16788 	    tree inst;
16789 	    if (DECL_PACK_P (decl))
16790 	      {
16791 		inst = (retrieve_local_specialization
16792 			(DECL_CAPTURED_VARIABLE (decl)));
16793 		gcc_assert (TREE_CODE (inst) == NONTYPE_ARGUMENT_PACK);
16794 	      }
16795 	    else
16796 	      {
16797 		inst = lookup_name_real (DECL_NAME (decl), 0, 0,
16798 					 /*block_p=*/true, 0, LOOKUP_HIDDEN);
16799 		gcc_assert (inst != decl && is_capture_proxy (inst));
16800 	      }
16801 	    register_local_specialization (inst, decl);
16802 	    break;
16803 	  }
16804 	else if (DECL_IMPLICIT_TYPEDEF_P (decl)
16805 		 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
16806 	  /* Don't copy the old closure; we'll create a new one in
16807 	     tsubst_lambda_expr.  */
16808 	  break;
16809 	else
16810 	  {
16811 	    init = DECL_INITIAL (decl);
16812 	    decl = tsubst (decl, args, complain, in_decl);
16813 	    if (decl != error_mark_node)
16814 	      {
16815 		/* By marking the declaration as instantiated, we avoid
16816 		   trying to instantiate it.  Since instantiate_decl can't
16817 		   handle local variables, and since we've already done
16818 		   all that needs to be done, that's the right thing to
16819 		   do.  */
16820 		if (VAR_P (decl))
16821 		  DECL_TEMPLATE_INSTANTIATED (decl) = 1;
16822 		if (VAR_P (decl) && !DECL_NAME (decl)
16823 		    && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
16824 		  /* Anonymous aggregates are a special case.  */
16825 		  finish_anon_union (decl);
16826 		else if (is_capture_proxy (DECL_EXPR_DECL (t)))
16827 		  {
16828 		    DECL_CONTEXT (decl) = current_function_decl;
16829 		    if (DECL_NAME (decl) == this_identifier)
16830 		      {
16831 			tree lam = DECL_CONTEXT (current_function_decl);
16832 			lam = CLASSTYPE_LAMBDA_EXPR (lam);
16833 			LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
16834 		      }
16835 		    insert_capture_proxy (decl);
16836 		  }
16837 		else if (DECL_IMPLICIT_TYPEDEF_P (t))
16838 		  /* We already did a pushtag.  */;
16839 		else if (TREE_CODE (decl) == FUNCTION_DECL
16840 			 && DECL_OMP_DECLARE_REDUCTION_P (decl)
16841 			 && DECL_FUNCTION_SCOPE_P (pattern_decl))
16842 		  {
16843 		    DECL_CONTEXT (decl) = NULL_TREE;
16844 		    pushdecl (decl);
16845 		    DECL_CONTEXT (decl) = current_function_decl;
16846 		    cp_check_omp_declare_reduction (decl);
16847 		  }
16848 		else
16849 		  {
16850 		    int const_init = false;
16851 		    unsigned int cnt = 0;
16852 		    tree first = NULL_TREE, ndecl = error_mark_node;
16853 		    tree asmspec_tree = NULL_TREE;
16854 		    maybe_push_decl (decl);
16855 
16856 		    if (VAR_P (decl)
16857 			&& DECL_DECOMPOSITION_P (decl)
16858 			&& TREE_TYPE (pattern_decl) != error_mark_node)
16859 		      ndecl = tsubst_decomp_names (decl, pattern_decl, args,
16860 						   complain, in_decl, &first,
16861 						   &cnt);
16862 
16863 		    if (VAR_P (decl)
16864 			&& DECL_PRETTY_FUNCTION_P (decl))
16865 		      {
16866 			/* For __PRETTY_FUNCTION__ we have to adjust the
16867 			   initializer.  */
16868 			const char *const name
16869 			  = cxx_printable_name (current_function_decl, 2);
16870 			init = cp_fname_init (name, &TREE_TYPE (decl));
16871 		      }
16872 		    else
16873 		      init = tsubst_init (init, decl, args, complain, in_decl);
16874 
16875 		    if (VAR_P (decl))
16876 		      const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
16877 				    (pattern_decl));
16878 
16879 		    if (ndecl != error_mark_node)
16880 		      cp_maybe_mangle_decomp (ndecl, first, cnt);
16881 
16882 		    if (VAR_P (decl) && DECL_HARD_REGISTER (pattern_decl))
16883 		      {
16884 			tree id = DECL_ASSEMBLER_NAME (pattern_decl);
16885 			const char *asmspec = IDENTIFIER_POINTER (id);
16886 			gcc_assert (asmspec[0] == '*');
16887 			asmspec_tree
16888 			  = build_string (IDENTIFIER_LENGTH (id) - 1,
16889 					  asmspec + 1);
16890 			TREE_TYPE (asmspec_tree) = char_array_type_node;
16891 		      }
16892 
16893 		    cp_finish_decl (decl, init, const_init, asmspec_tree, 0);
16894 
16895 		    if (ndecl != error_mark_node)
16896 		      cp_finish_decomp (ndecl, first, cnt);
16897 		  }
16898 	      }
16899 	  }
16900 
16901 	break;
16902       }
16903 
16904     case FOR_STMT:
16905       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
16906       RECUR (FOR_INIT_STMT (t));
16907       finish_init_stmt (stmt);
16908       tmp = RECUR (FOR_COND (t));
16909       finish_for_cond (tmp, stmt, false, 0);
16910       tmp = RECUR (FOR_EXPR (t));
16911       finish_for_expr (tmp, stmt);
16912       {
16913 	bool prev = note_iteration_stmt_body_start ();
16914 	RECUR (FOR_BODY (t));
16915 	note_iteration_stmt_body_end (prev);
16916       }
16917       finish_for_stmt (stmt);
16918       break;
16919 
16920     case RANGE_FOR_STMT:
16921       {
16922 	/* Construct another range_for, if this is not a final
16923 	   substitution (for inside inside a generic lambda of a
16924 	   template).  Otherwise convert to a regular for.  */
16925         tree decl, expr;
16926         stmt = (processing_template_decl
16927 		? begin_range_for_stmt (NULL_TREE, NULL_TREE)
16928 		: begin_for_stmt (NULL_TREE, NULL_TREE));
16929         decl = RANGE_FOR_DECL (t);
16930         decl = tsubst (decl, args, complain, in_decl);
16931         maybe_push_decl (decl);
16932         expr = RECUR (RANGE_FOR_EXPR (t));
16933 
16934 	tree decomp_first = NULL_TREE;
16935 	unsigned decomp_cnt = 0;
16936 	if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
16937 	  decl = tsubst_decomp_names (decl, RANGE_FOR_DECL (t), args,
16938 				      complain, in_decl,
16939 				      &decomp_first, &decomp_cnt);
16940 
16941 	if (processing_template_decl)
16942 	  {
16943 	    RANGE_FOR_IVDEP (stmt) = RANGE_FOR_IVDEP (t);
16944 	    RANGE_FOR_UNROLL (stmt) = RANGE_FOR_UNROLL (t);
16945 	    finish_range_for_decl (stmt, decl, expr);
16946 	    if (decomp_first && decl != error_mark_node)
16947 	      cp_finish_decomp (decl, decomp_first, decomp_cnt);
16948 	  }
16949 	else
16950 	  {
16951 	    unsigned short unroll = (RANGE_FOR_UNROLL (t)
16952 				     ? tree_to_uhwi (RANGE_FOR_UNROLL (t)) : 0);
16953 	    stmt = cp_convert_range_for (stmt, decl, expr,
16954 					 decomp_first, decomp_cnt,
16955 					 RANGE_FOR_IVDEP (t), unroll);
16956 	  }
16957 
16958 	bool prev = note_iteration_stmt_body_start ();
16959         RECUR (RANGE_FOR_BODY (t));
16960 	note_iteration_stmt_body_end (prev);
16961         finish_for_stmt (stmt);
16962       }
16963       break;
16964 
16965     case WHILE_STMT:
16966       stmt = begin_while_stmt ();
16967       tmp = RECUR (WHILE_COND (t));
16968       finish_while_stmt_cond (tmp, stmt, false, 0);
16969       {
16970 	bool prev = note_iteration_stmt_body_start ();
16971 	RECUR (WHILE_BODY (t));
16972 	note_iteration_stmt_body_end (prev);
16973       }
16974       finish_while_stmt (stmt);
16975       break;
16976 
16977     case DO_STMT:
16978       stmt = begin_do_stmt ();
16979       {
16980 	bool prev = note_iteration_stmt_body_start ();
16981 	RECUR (DO_BODY (t));
16982 	note_iteration_stmt_body_end (prev);
16983       }
16984       finish_do_body (stmt);
16985       tmp = RECUR (DO_COND (t));
16986       finish_do_stmt (tmp, stmt, false, 0);
16987       break;
16988 
16989     case IF_STMT:
16990       stmt = begin_if_stmt ();
16991       IF_STMT_CONSTEXPR_P (stmt) = IF_STMT_CONSTEXPR_P (t);
16992       if (IF_STMT_CONSTEXPR_P (t))
16993 	args = add_extra_args (IF_STMT_EXTRA_ARGS (t), args);
16994       tmp = RECUR (IF_COND (t));
16995       tmp = finish_if_stmt_cond (tmp, stmt);
16996       if (IF_STMT_CONSTEXPR_P (t)
16997 	  && instantiation_dependent_expression_p (tmp))
16998 	{
16999 	  /* We're partially instantiating a generic lambda, but the condition
17000 	     of the constexpr if is still dependent.  Don't substitute into the
17001 	     branches now, just remember the template arguments.  */
17002 	  do_poplevel (IF_SCOPE (stmt));
17003 	  IF_COND (stmt) = IF_COND (t);
17004 	  THEN_CLAUSE (stmt) = THEN_CLAUSE (t);
17005 	  ELSE_CLAUSE (stmt) = ELSE_CLAUSE (t);
17006 	  IF_STMT_EXTRA_ARGS (stmt) = build_extra_args (t, args, complain);
17007 	  add_stmt (stmt);
17008 	  break;
17009 	}
17010       if (IF_STMT_CONSTEXPR_P (t) && integer_zerop (tmp))
17011 	/* Don't instantiate the THEN_CLAUSE. */;
17012       else
17013 	{
17014 	  bool inhibit = integer_zerop (fold_non_dependent_expr (tmp));
17015 	  if (inhibit)
17016 	    ++c_inhibit_evaluation_warnings;
17017 	  RECUR (THEN_CLAUSE (t));
17018 	  if (inhibit)
17019 	    --c_inhibit_evaluation_warnings;
17020 	}
17021       finish_then_clause (stmt);
17022 
17023       if (IF_STMT_CONSTEXPR_P (t) && integer_nonzerop (tmp))
17024 	/* Don't instantiate the ELSE_CLAUSE. */;
17025       else if (ELSE_CLAUSE (t))
17026 	{
17027 	  bool inhibit = integer_nonzerop (fold_non_dependent_expr (tmp));
17028 	  begin_else_clause (stmt);
17029 	  if (inhibit)
17030 	    ++c_inhibit_evaluation_warnings;
17031 	  RECUR (ELSE_CLAUSE (t));
17032 	  if (inhibit)
17033 	    --c_inhibit_evaluation_warnings;
17034 	  finish_else_clause (stmt);
17035 	}
17036 
17037       finish_if_stmt (stmt);
17038       break;
17039 
17040     case BIND_EXPR:
17041       if (BIND_EXPR_BODY_BLOCK (t))
17042 	stmt = begin_function_body ();
17043       else
17044 	stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
17045 				    ? BCS_TRY_BLOCK : 0);
17046 
17047       RECUR (BIND_EXPR_BODY (t));
17048 
17049       if (BIND_EXPR_BODY_BLOCK (t))
17050 	finish_function_body (stmt);
17051       else
17052 	finish_compound_stmt (stmt);
17053       break;
17054 
17055     case BREAK_STMT:
17056       finish_break_stmt ();
17057       break;
17058 
17059     case CONTINUE_STMT:
17060       finish_continue_stmt ();
17061       break;
17062 
17063     case SWITCH_STMT:
17064       stmt = begin_switch_stmt ();
17065       tmp = RECUR (SWITCH_STMT_COND (t));
17066       finish_switch_cond (tmp, stmt);
17067       RECUR (SWITCH_STMT_BODY (t));
17068       finish_switch_stmt (stmt);
17069       break;
17070 
17071     case CASE_LABEL_EXPR:
17072       {
17073 	tree low = RECUR (CASE_LOW (t));
17074 	tree high = RECUR (CASE_HIGH (t));
17075 	tree l = finish_case_label (EXPR_LOCATION (t), low, high);
17076 	if (l && TREE_CODE (l) == CASE_LABEL_EXPR)
17077 	  FALLTHROUGH_LABEL_P (CASE_LABEL (l))
17078 	    = FALLTHROUGH_LABEL_P (CASE_LABEL (t));
17079       }
17080       break;
17081 
17082     case LABEL_EXPR:
17083       {
17084 	tree decl = LABEL_EXPR_LABEL (t);
17085 	tree label;
17086 
17087 	label = finish_label_stmt (DECL_NAME (decl));
17088 	if (TREE_CODE (label) == LABEL_DECL)
17089 	  FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
17090 	if (DECL_ATTRIBUTES (decl) != NULL_TREE)
17091 	  cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
17092       }
17093       break;
17094 
17095     case GOTO_EXPR:
17096       tmp = GOTO_DESTINATION (t);
17097       if (TREE_CODE (tmp) != LABEL_DECL)
17098 	/* Computed goto's must be tsubst'd into.  On the other hand,
17099 	   non-computed gotos must not be; the identifier in question
17100 	   will have no binding.  */
17101 	tmp = RECUR (tmp);
17102       else
17103 	tmp = DECL_NAME (tmp);
17104       finish_goto_stmt (tmp);
17105       break;
17106 
17107     case ASM_EXPR:
17108       {
17109 	tree string = RECUR (ASM_STRING (t));
17110 	tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
17111 						 complain, in_decl);
17112 	tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
17113 						complain, in_decl);
17114 	tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
17115 	 					  complain, in_decl);
17116 	tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
17117 						complain, in_decl);
17118 	tmp = finish_asm_stmt (ASM_VOLATILE_P (t), string, outputs, inputs,
17119 			       clobbers, labels, ASM_INLINE_P (t));
17120 	tree asm_expr = tmp;
17121 	if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
17122 	  asm_expr = TREE_OPERAND (asm_expr, 0);
17123 	ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
17124       }
17125       break;
17126 
17127     case TRY_BLOCK:
17128       if (CLEANUP_P (t))
17129 	{
17130 	  stmt = begin_try_block ();
17131 	  RECUR (TRY_STMTS (t));
17132 	  finish_cleanup_try_block (stmt);
17133 	  finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
17134 	}
17135       else
17136 	{
17137 	  tree compound_stmt = NULL_TREE;
17138 
17139 	  if (FN_TRY_BLOCK_P (t))
17140 	    stmt = begin_function_try_block (&compound_stmt);
17141 	  else
17142 	    stmt = begin_try_block ();
17143 
17144 	  RECUR (TRY_STMTS (t));
17145 
17146 	  if (FN_TRY_BLOCK_P (t))
17147 	    finish_function_try_block (stmt);
17148 	  else
17149 	    finish_try_block (stmt);
17150 
17151 	  RECUR (TRY_HANDLERS (t));
17152 	  if (FN_TRY_BLOCK_P (t))
17153 	    finish_function_handler_sequence (stmt, compound_stmt);
17154 	  else
17155 	    finish_handler_sequence (stmt);
17156 	}
17157       break;
17158 
17159     case HANDLER:
17160       {
17161 	tree decl = HANDLER_PARMS (t);
17162 
17163 	if (decl)
17164 	  {
17165 	    decl = tsubst (decl, args, complain, in_decl);
17166 	    /* Prevent instantiate_decl from trying to instantiate
17167 	       this variable.  We've already done all that needs to be
17168 	       done.  */
17169 	    if (decl != error_mark_node)
17170 	      DECL_TEMPLATE_INSTANTIATED (decl) = 1;
17171 	  }
17172 	stmt = begin_handler ();
17173 	finish_handler_parms (decl, stmt);
17174 	RECUR (HANDLER_BODY (t));
17175 	finish_handler (stmt);
17176       }
17177       break;
17178 
17179     case TAG_DEFN:
17180       tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
17181       if (CLASS_TYPE_P (tmp))
17182 	{
17183 	  /* Local classes are not independent templates; they are
17184 	     instantiated along with their containing function.  And this
17185 	     way we don't have to deal with pushing out of one local class
17186 	     to instantiate a member of another local class.  */
17187 	  /* Closures are handled by the LAMBDA_EXPR.  */
17188 	  gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
17189 	  complete_type (tmp);
17190 	  for (tree fld = TYPE_FIELDS (tmp); fld; fld = DECL_CHAIN (fld))
17191 	    if ((VAR_P (fld)
17192 		 || (TREE_CODE (fld) == FUNCTION_DECL
17193 		     && !DECL_ARTIFICIAL (fld)))
17194 		&& DECL_TEMPLATE_INSTANTIATION (fld))
17195 	      instantiate_decl (fld, /*defer_ok=*/false,
17196 				/*expl_inst_class=*/false);
17197 	}
17198       break;
17199 
17200     case STATIC_ASSERT:
17201       {
17202 	tree condition;
17203 
17204 	++c_inhibit_evaluation_warnings;
17205         condition =
17206           tsubst_expr (STATIC_ASSERT_CONDITION (t),
17207                        args,
17208                        complain, in_decl,
17209                        /*integral_constant_expression_p=*/true);
17210 	--c_inhibit_evaluation_warnings;
17211 
17212         finish_static_assert (condition,
17213                               STATIC_ASSERT_MESSAGE (t),
17214                               STATIC_ASSERT_SOURCE_LOCATION (t),
17215                               /*member_p=*/false);
17216       }
17217       break;
17218 
17219     case OACC_KERNELS:
17220     case OACC_PARALLEL:
17221       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_ACC, args, complain,
17222 				in_decl);
17223       stmt = begin_omp_parallel ();
17224       RECUR (OMP_BODY (t));
17225       finish_omp_construct (TREE_CODE (t), stmt, tmp);
17226       break;
17227 
17228     case OMP_PARALLEL:
17229       r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
17230       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), C_ORT_OMP, args,
17231 				complain, in_decl);
17232       if (OMP_PARALLEL_COMBINED (t))
17233 	omp_parallel_combined_clauses = &tmp;
17234       stmt = begin_omp_parallel ();
17235       RECUR (OMP_PARALLEL_BODY (t));
17236       gcc_assert (omp_parallel_combined_clauses == NULL);
17237       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
17238 	= OMP_PARALLEL_COMBINED (t);
17239       pop_omp_privatization_clauses (r);
17240       break;
17241 
17242     case OMP_TASK:
17243       r = push_omp_privatization_clauses (false);
17244       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
17245 				complain, in_decl);
17246       stmt = begin_omp_task ();
17247       RECUR (OMP_TASK_BODY (t));
17248       finish_omp_task (tmp, stmt);
17249       pop_omp_privatization_clauses (r);
17250       break;
17251 
17252     case OMP_FOR:
17253     case OMP_SIMD:
17254     case OMP_DISTRIBUTE:
17255     case OMP_TASKLOOP:
17256     case OACC_LOOP:
17257       {
17258 	tree clauses, body, pre_body;
17259 	tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
17260 	tree orig_declv = NULL_TREE;
17261 	tree incrv = NULL_TREE;
17262 	enum c_omp_region_type ort = C_ORT_OMP;
17263 	int i;
17264 
17265 	if (TREE_CODE (t) == OACC_LOOP)
17266 	  ort = C_ORT_ACC;
17267 
17268 	r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
17269 	clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), ort, args, complain,
17270 				      in_decl);
17271 	if (OMP_FOR_INIT (t) != NULL_TREE)
17272 	  {
17273 	    declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17274 	    if (OMP_FOR_ORIG_DECLS (t))
17275 	      orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17276 	    initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17277 	    condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17278 	    incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17279 	  }
17280 
17281 	stmt = begin_omp_structured_block ();
17282 
17283 	pre_body = push_stmt_list ();
17284 	RECUR (OMP_FOR_PRE_BODY (t));
17285 	pre_body = pop_stmt_list (pre_body);
17286 
17287 	if (OMP_FOR_INIT (t) != NULL_TREE)
17288 	  for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
17289 	    tsubst_omp_for_iterator (t, i, declv, orig_declv, initv, condv,
17290 				     incrv, &clauses, args, complain, in_decl,
17291 				     integral_constant_expression_p);
17292 	omp_parallel_combined_clauses = NULL;
17293 
17294 	body = push_stmt_list ();
17295 	RECUR (OMP_FOR_BODY (t));
17296 	body = pop_stmt_list (body);
17297 
17298 	if (OMP_FOR_INIT (t) != NULL_TREE)
17299 	  t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
17300 			      orig_declv, initv, condv, incrv, body, pre_body,
17301 			      NULL, clauses);
17302 	else
17303 	  {
17304 	    t = make_node (TREE_CODE (t));
17305 	    TREE_TYPE (t) = void_type_node;
17306 	    OMP_FOR_BODY (t) = body;
17307 	    OMP_FOR_PRE_BODY (t) = pre_body;
17308 	    OMP_FOR_CLAUSES (t) = clauses;
17309 	    SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
17310 	    add_stmt (t);
17311 	  }
17312 
17313 	add_stmt (finish_omp_structured_block (stmt));
17314 	pop_omp_privatization_clauses (r);
17315       }
17316       break;
17317 
17318     case OMP_SECTIONS:
17319       omp_parallel_combined_clauses = NULL;
17320       /* FALLTHRU */
17321     case OMP_SINGLE:
17322     case OMP_TEAMS:
17323     case OMP_CRITICAL:
17324       r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
17325 					  && OMP_TEAMS_COMBINED (t));
17326       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_OMP, args, complain,
17327 				in_decl);
17328       stmt = push_stmt_list ();
17329       RECUR (OMP_BODY (t));
17330       stmt = pop_stmt_list (stmt);
17331 
17332       t = copy_node (t);
17333       OMP_BODY (t) = stmt;
17334       OMP_CLAUSES (t) = tmp;
17335       add_stmt (t);
17336       pop_omp_privatization_clauses (r);
17337       break;
17338 
17339     case OACC_DATA:
17340     case OMP_TARGET_DATA:
17341     case OMP_TARGET:
17342       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), (TREE_CODE (t) == OACC_DATA)
17343 				? C_ORT_ACC : C_ORT_OMP, args, complain,
17344 				in_decl);
17345       keep_next_level (true);
17346       stmt = begin_omp_structured_block ();
17347 
17348       RECUR (OMP_BODY (t));
17349       stmt = finish_omp_structured_block (stmt);
17350 
17351       t = copy_node (t);
17352       OMP_BODY (t) = stmt;
17353       OMP_CLAUSES (t) = tmp;
17354       if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
17355 	{
17356 	  tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
17357 	  if (teams)
17358 	    {
17359 	      /* For combined target teams, ensure the num_teams and
17360 		 thread_limit clause expressions are evaluated on the host,
17361 		 before entering the target construct.  */
17362 	      tree c;
17363 	      for (c = OMP_TEAMS_CLAUSES (teams);
17364 		   c; c = OMP_CLAUSE_CHAIN (c))
17365 		if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
17366 		     || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
17367 		    && TREE_CODE (OMP_CLAUSE_OPERAND (c, 0)) != INTEGER_CST)
17368 		  {
17369 		    tree expr = OMP_CLAUSE_OPERAND (c, 0);
17370 		    expr = force_target_expr (TREE_TYPE (expr), expr, tf_none);
17371 		    if (expr == error_mark_node)
17372 		      continue;
17373 		    tmp = TARGET_EXPR_SLOT (expr);
17374 		    add_stmt (expr);
17375 		    OMP_CLAUSE_OPERAND (c, 0) = expr;
17376 		    tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
17377 						OMP_CLAUSE_FIRSTPRIVATE);
17378 		    OMP_CLAUSE_DECL (tc) = tmp;
17379 		    OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
17380 		    OMP_TARGET_CLAUSES (t) = tc;
17381 		  }
17382 	    }
17383 	}
17384       add_stmt (t);
17385       break;
17386 
17387     case OACC_DECLARE:
17388       t = copy_node (t);
17389       tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), C_ORT_ACC, args,
17390 				complain, in_decl);
17391       OACC_DECLARE_CLAUSES (t) = tmp;
17392       add_stmt (t);
17393       break;
17394 
17395     case OMP_TARGET_UPDATE:
17396     case OMP_TARGET_ENTER_DATA:
17397     case OMP_TARGET_EXIT_DATA:
17398       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_OMP, args,
17399 				complain, in_decl);
17400       t = copy_node (t);
17401       OMP_STANDALONE_CLAUSES (t) = tmp;
17402       add_stmt (t);
17403       break;
17404 
17405     case OACC_CACHE:
17406     case OACC_ENTER_DATA:
17407     case OACC_EXIT_DATA:
17408     case OACC_UPDATE:
17409       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_ACC, args,
17410 				complain, in_decl);
17411       t = copy_node (t);
17412       OMP_STANDALONE_CLAUSES (t) = tmp;
17413       add_stmt (t);
17414       break;
17415 
17416     case OMP_ORDERED:
17417       tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), C_ORT_OMP, args,
17418 				complain, in_decl);
17419       stmt = push_stmt_list ();
17420       RECUR (OMP_BODY (t));
17421       stmt = pop_stmt_list (stmt);
17422 
17423       t = copy_node (t);
17424       OMP_BODY (t) = stmt;
17425       OMP_ORDERED_CLAUSES (t) = tmp;
17426       add_stmt (t);
17427       break;
17428 
17429     case OMP_SECTION:
17430     case OMP_MASTER:
17431     case OMP_TASKGROUP:
17432       stmt = push_stmt_list ();
17433       RECUR (OMP_BODY (t));
17434       stmt = pop_stmt_list (stmt);
17435 
17436       t = copy_node (t);
17437       OMP_BODY (t) = stmt;
17438       add_stmt (t);
17439       break;
17440 
17441     case OMP_ATOMIC:
17442       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
17443       if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
17444 	{
17445 	  tree op1 = TREE_OPERAND (t, 1);
17446 	  tree rhs1 = NULL_TREE;
17447 	  tree lhs, rhs;
17448 	  if (TREE_CODE (op1) == COMPOUND_EXPR)
17449 	    {
17450 	      rhs1 = RECUR (TREE_OPERAND (op1, 0));
17451 	      op1 = TREE_OPERAND (op1, 1);
17452 	    }
17453 	  lhs = RECUR (TREE_OPERAND (op1, 0));
17454 	  rhs = RECUR (TREE_OPERAND (op1, 1));
17455 	  finish_omp_atomic (OMP_ATOMIC, TREE_CODE (op1), lhs, rhs,
17456 			     NULL_TREE, NULL_TREE, rhs1,
17457 			     OMP_ATOMIC_SEQ_CST (t));
17458 	}
17459       else
17460 	{
17461 	  tree op1 = TREE_OPERAND (t, 1);
17462 	  tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
17463 	  tree rhs1 = NULL_TREE;
17464 	  enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
17465 	  enum tree_code opcode = NOP_EXPR;
17466 	  if (code == OMP_ATOMIC_READ)
17467 	    {
17468 	      v = RECUR (TREE_OPERAND (op1, 0));
17469 	      lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
17470 	    }
17471 	  else if (code == OMP_ATOMIC_CAPTURE_OLD
17472 		   || code == OMP_ATOMIC_CAPTURE_NEW)
17473 	    {
17474 	      tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
17475 	      v = RECUR (TREE_OPERAND (op1, 0));
17476 	      lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
17477 	      if (TREE_CODE (op11) == COMPOUND_EXPR)
17478 		{
17479 		  rhs1 = RECUR (TREE_OPERAND (op11, 0));
17480 		  op11 = TREE_OPERAND (op11, 1);
17481 		}
17482 	      lhs = RECUR (TREE_OPERAND (op11, 0));
17483 	      rhs = RECUR (TREE_OPERAND (op11, 1));
17484 	      opcode = TREE_CODE (op11);
17485 	      if (opcode == MODIFY_EXPR)
17486 		opcode = NOP_EXPR;
17487 	    }
17488 	  else
17489 	    {
17490 	      code = OMP_ATOMIC;
17491 	      lhs = RECUR (TREE_OPERAND (op1, 0));
17492 	      rhs = RECUR (TREE_OPERAND (op1, 1));
17493 	    }
17494 	  finish_omp_atomic (code, opcode, lhs, rhs, v, lhs1, rhs1,
17495 			     OMP_ATOMIC_SEQ_CST (t));
17496 	}
17497       break;
17498 
17499     case TRANSACTION_EXPR:
17500       {
17501 	int flags = 0;
17502 	flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
17503 	flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
17504 
17505         if (TRANSACTION_EXPR_IS_STMT (t))
17506           {
17507 	    tree body = TRANSACTION_EXPR_BODY (t);
17508 	    tree noex = NULL_TREE;
17509 	    if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
17510 	      {
17511 		noex = MUST_NOT_THROW_COND (body);
17512 		if (noex == NULL_TREE)
17513 		  noex = boolean_true_node;
17514 		body = TREE_OPERAND (body, 0);
17515 	      }
17516             stmt = begin_transaction_stmt (input_location, NULL, flags);
17517             RECUR (body);
17518             finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
17519           }
17520         else
17521           {
17522             stmt = build_transaction_expr (EXPR_LOCATION (t),
17523 					   RECUR (TRANSACTION_EXPR_BODY (t)),
17524 					   flags, NULL_TREE);
17525             RETURN (stmt);
17526           }
17527       }
17528       break;
17529 
17530     case MUST_NOT_THROW_EXPR:
17531       {
17532 	tree op0 = RECUR (TREE_OPERAND (t, 0));
17533 	tree cond = RECUR (MUST_NOT_THROW_COND (t));
17534 	RETURN (build_must_not_throw_expr (op0, cond));
17535       }
17536 
17537     case EXPR_PACK_EXPANSION:
17538       error ("invalid use of pack expansion expression");
17539       RETURN (error_mark_node);
17540 
17541     case NONTYPE_ARGUMENT_PACK:
17542       error ("use %<...%> to expand argument pack");
17543       RETURN (error_mark_node);
17544 
17545     case COMPOUND_EXPR:
17546       tmp = RECUR (TREE_OPERAND (t, 0));
17547       if (tmp == NULL_TREE)
17548 	/* If the first operand was a statement, we're done with it.  */
17549 	RETURN (RECUR (TREE_OPERAND (t, 1)));
17550       RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
17551 				    RECUR (TREE_OPERAND (t, 1)),
17552 				    complain));
17553 
17554     case ANNOTATE_EXPR:
17555       tmp = RECUR (TREE_OPERAND (t, 0));
17556       RETURN (build3_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
17557 			  TREE_TYPE (tmp), tmp,
17558 			  RECUR (TREE_OPERAND (t, 1)),
17559 			  RECUR (TREE_OPERAND (t, 2))));
17560 
17561     default:
17562       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
17563 
17564       RETURN (tsubst_copy_and_build (t, args, complain, in_decl,
17565 				    /*function_p=*/false,
17566 				    integral_constant_expression_p));
17567     }
17568 
17569   RETURN (NULL_TREE);
17570  out:
17571   input_location = loc;
17572   return r;
17573 #undef RECUR
17574 #undef RETURN
17575 }
17576 
17577 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
17578    function.  For description of the body see comment above
17579    cp_parser_omp_declare_reduction_exprs.  */
17580 
17581 static void
tsubst_omp_udr(tree t,tree args,tsubst_flags_t complain,tree in_decl)17582 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
17583 {
17584   if (t == NULL_TREE || t == error_mark_node)
17585     return;
17586 
17587   gcc_assert (TREE_CODE (t) == STATEMENT_LIST);
17588 
17589   tree_stmt_iterator tsi;
17590   int i;
17591   tree stmts[7];
17592   memset (stmts, 0, sizeof stmts);
17593   for (i = 0, tsi = tsi_start (t);
17594        i < 7 && !tsi_end_p (tsi);
17595        i++, tsi_next (&tsi))
17596     stmts[i] = tsi_stmt (tsi);
17597   gcc_assert (tsi_end_p (tsi));
17598 
17599   if (i >= 3)
17600     {
17601       gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
17602 		  && TREE_CODE (stmts[1]) == DECL_EXPR);
17603       tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
17604 			     args, complain, in_decl);
17605       tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
17606 			    args, complain, in_decl);
17607       DECL_CONTEXT (omp_out) = current_function_decl;
17608       DECL_CONTEXT (omp_in) = current_function_decl;
17609       keep_next_level (true);
17610       tree block = begin_omp_structured_block ();
17611       tsubst_expr (stmts[2], args, complain, in_decl, false);
17612       block = finish_omp_structured_block (block);
17613       block = maybe_cleanup_point_expr_void (block);
17614       add_decl_expr (omp_out);
17615       if (TREE_NO_WARNING (DECL_EXPR_DECL (stmts[0])))
17616 	TREE_NO_WARNING (omp_out) = 1;
17617       add_decl_expr (omp_in);
17618       finish_expr_stmt (block);
17619     }
17620   if (i >= 6)
17621     {
17622       gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
17623 		  && TREE_CODE (stmts[4]) == DECL_EXPR);
17624       tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
17625 			      args, complain, in_decl);
17626       tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
17627 			      args, complain, in_decl);
17628       DECL_CONTEXT (omp_priv) = current_function_decl;
17629       DECL_CONTEXT (omp_orig) = current_function_decl;
17630       keep_next_level (true);
17631       tree block = begin_omp_structured_block ();
17632       tsubst_expr (stmts[5], args, complain, in_decl, false);
17633       block = finish_omp_structured_block (block);
17634       block = maybe_cleanup_point_expr_void (block);
17635       cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
17636       add_decl_expr (omp_priv);
17637       add_decl_expr (omp_orig);
17638       finish_expr_stmt (block);
17639       if (i == 7)
17640 	add_decl_expr (omp_orig);
17641     }
17642 }
17643 
17644 /* T is a postfix-expression that is not being used in a function
17645    call.  Return the substituted version of T.  */
17646 
17647 static tree
tsubst_non_call_postfix_expression(tree t,tree args,tsubst_flags_t complain,tree in_decl)17648 tsubst_non_call_postfix_expression (tree t, tree args,
17649 				    tsubst_flags_t complain,
17650 				    tree in_decl)
17651 {
17652   if (TREE_CODE (t) == SCOPE_REF)
17653     t = tsubst_qualified_id (t, args, complain, in_decl,
17654 			     /*done=*/false, /*address_p=*/false);
17655   else
17656     t = tsubst_copy_and_build (t, args, complain, in_decl,
17657 			       /*function_p=*/false,
17658 			       /*integral_constant_expression_p=*/false);
17659 
17660   return t;
17661 }
17662 
17663 /* T is a LAMBDA_EXPR.  Generate a new LAMBDA_EXPR for the current
17664    instantiation context.  Instantiating a pack expansion containing a lambda
17665    might result in multiple lambdas all based on the same lambda in the
17666    template.  */
17667 
17668 tree
tsubst_lambda_expr(tree t,tree args,tsubst_flags_t complain,tree in_decl)17669 tsubst_lambda_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
17670 {
17671   tree oldfn = lambda_function (t);
17672   in_decl = oldfn;
17673 
17674   tree r = build_lambda_expr ();
17675 
17676   LAMBDA_EXPR_LOCATION (r)
17677     = LAMBDA_EXPR_LOCATION (t);
17678   LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
17679     = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
17680   LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
17681 
17682   if (LAMBDA_EXPR_EXTRA_SCOPE (t) == NULL_TREE)
17683     /* A lambda in a default argument outside a class gets no
17684        LAMBDA_EXPR_EXTRA_SCOPE, as specified by the ABI.  But
17685        tsubst_default_argument calls start_lambda_scope, so we need to
17686        specifically ignore it here, and use the global scope.  */
17687     record_null_lambda_scope (r);
17688   else
17689     record_lambda_scope (r);
17690 
17691   gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
17692 	      && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
17693 
17694   for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t); cap;
17695        cap = TREE_CHAIN (cap))
17696     {
17697       tree field = TREE_PURPOSE (cap);
17698       if (PACK_EXPANSION_P (field))
17699 	field = PACK_EXPANSION_PATTERN (field);
17700       field = tsubst_decl (field, args, complain);
17701 
17702       if (field == error_mark_node)
17703 	return error_mark_node;
17704 
17705       tree init = TREE_VALUE (cap);
17706       if (PACK_EXPANSION_P (init))
17707 	init = tsubst_pack_expansion (init, args, complain, in_decl);
17708       else
17709 	init = tsubst_copy_and_build (init, args, complain, in_decl,
17710 				      /*fn*/false, /*constexpr*/false);
17711 
17712       if (TREE_CODE (field) == TREE_VEC)
17713 	{
17714 	  int len = TREE_VEC_LENGTH (field);
17715 	  gcc_assert (TREE_CODE (init) == TREE_VEC
17716 		      && TREE_VEC_LENGTH (init) == len);
17717 	  for (int i = 0; i < len; ++i)
17718 	    LAMBDA_EXPR_CAPTURE_LIST (r)
17719 	      = tree_cons (TREE_VEC_ELT (field, i),
17720 			   TREE_VEC_ELT (init, i),
17721 			   LAMBDA_EXPR_CAPTURE_LIST (r));
17722 	}
17723       else
17724 	{
17725 	  LAMBDA_EXPR_CAPTURE_LIST (r)
17726 	    = tree_cons (field, init, LAMBDA_EXPR_CAPTURE_LIST (r));
17727 
17728 	  if (id_equal (DECL_NAME (field), "__this"))
17729 	    LAMBDA_EXPR_THIS_CAPTURE (r) = field;
17730 	}
17731     }
17732 
17733   tree type = begin_lambda_type (r);
17734   if (type == error_mark_node)
17735     return error_mark_node;
17736 
17737   /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
17738   determine_visibility (TYPE_NAME (type));
17739 
17740   register_capture_members (LAMBDA_EXPR_CAPTURE_LIST (r));
17741 
17742   tree oldtmpl = (generic_lambda_fn_p (oldfn)
17743 		  ? DECL_TI_TEMPLATE (oldfn)
17744 		  : NULL_TREE);
17745 
17746   tree fntype = static_fn_type (oldfn);
17747   if (oldtmpl)
17748     ++processing_template_decl;
17749   fntype = tsubst (fntype, args, complain, in_decl);
17750   if (oldtmpl)
17751     --processing_template_decl;
17752 
17753   if (fntype == error_mark_node)
17754     r = error_mark_node;
17755   else
17756     {
17757       /* Fix the type of 'this'.  */
17758       fntype = build_memfn_type (fntype, type,
17759 				 type_memfn_quals (fntype),
17760 				 type_memfn_rqual (fntype));
17761       tree fn, tmpl;
17762       if (oldtmpl)
17763 	{
17764 	  tmpl = tsubst_template_decl (oldtmpl, args, complain, fntype);
17765 	  fn = DECL_TEMPLATE_RESULT (tmpl);
17766 	  finish_member_declaration (tmpl);
17767 	}
17768       else
17769 	{
17770 	  tmpl = NULL_TREE;
17771 	  fn = tsubst_function_decl (oldfn, args, complain, fntype);
17772 	  finish_member_declaration (fn);
17773 	}
17774 
17775       /* Let finish_function set this.  */
17776       DECL_DECLARED_CONSTEXPR_P (fn) = false;
17777 
17778       bool nested = cfun;
17779       if (nested)
17780 	push_function_context ();
17781       else
17782 	/* Still increment function_depth so that we don't GC in the
17783 	   middle of an expression.  */
17784 	++function_depth;
17785 
17786       local_specialization_stack s (lss_copy);
17787 
17788       tree body = start_lambda_function (fn, r);
17789 
17790       register_parameter_specializations (oldfn, fn);
17791 
17792       if (oldtmpl)
17793 	{
17794 	  /* We might not partially instantiate some parts of the function, so
17795 	     copy these flags from the original template.  */
17796 	  language_function *ol = DECL_STRUCT_FUNCTION (oldfn)->language;
17797 	  current_function_returns_value = ol->returns_value;
17798 	  current_function_returns_null = ol->returns_null;
17799 	  current_function_returns_abnormally = ol->returns_abnormally;
17800 	  current_function_infinite_loop = ol->infinite_loop;
17801 	}
17802 
17803       tsubst_expr (DECL_SAVED_TREE (oldfn), args, complain, r,
17804 		   /*constexpr*/false);
17805 
17806       finish_lambda_function (body);
17807 
17808       if (nested)
17809 	pop_function_context ();
17810       else
17811 	--function_depth;
17812 
17813       /* The capture list was built up in reverse order; fix that now.  */
17814       LAMBDA_EXPR_CAPTURE_LIST (r)
17815 	= nreverse (LAMBDA_EXPR_CAPTURE_LIST (r));
17816 
17817       LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
17818 
17819       maybe_add_lambda_conv_op (type);
17820     }
17821 
17822   finish_struct (type, /*attr*/NULL_TREE);
17823 
17824   insert_pending_capture_proxies ();
17825 
17826   return r;
17827 }
17828 
17829 /* Like tsubst but deals with expressions and performs semantic
17830    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
17831 
17832 tree
tsubst_copy_and_build(tree t,tree args,tsubst_flags_t complain,tree in_decl,bool function_p,bool integral_constant_expression_p)17833 tsubst_copy_and_build (tree t,
17834 		       tree args,
17835 		       tsubst_flags_t complain,
17836 		       tree in_decl,
17837 		       bool function_p,
17838 		       bool integral_constant_expression_p)
17839 {
17840 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
17841 #define RECUR(NODE)						\
17842   tsubst_copy_and_build (NODE, args, complain, in_decl, 	\
17843 			 /*function_p=*/false,			\
17844 			 integral_constant_expression_p)
17845 
17846   tree retval, op1;
17847   location_t loc;
17848 
17849   if (t == NULL_TREE || t == error_mark_node)
17850     return t;
17851 
17852   loc = input_location;
17853   if (EXPR_HAS_LOCATION (t))
17854     input_location = EXPR_LOCATION (t);
17855 
17856   /* N3276 decltype magic only applies to calls at the top level or on the
17857      right side of a comma.  */
17858   tsubst_flags_t decltype_flag = (complain & tf_decltype);
17859   complain &= ~tf_decltype;
17860 
17861   switch (TREE_CODE (t))
17862     {
17863     case USING_DECL:
17864       t = DECL_NAME (t);
17865       /* Fall through.  */
17866     case IDENTIFIER_NODE:
17867       {
17868 	tree decl;
17869 	cp_id_kind idk;
17870 	bool non_integral_constant_expression_p;
17871 	const char *error_msg;
17872 
17873 	if (IDENTIFIER_CONV_OP_P (t))
17874 	  {
17875 	    tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17876 	    t = make_conv_op_name (new_type);
17877 	  }
17878 
17879 	/* Look up the name.  */
17880 	decl = lookup_name (t);
17881 
17882 	/* By convention, expressions use ERROR_MARK_NODE to indicate
17883 	   failure, not NULL_TREE.  */
17884 	if (decl == NULL_TREE)
17885 	  decl = error_mark_node;
17886 
17887 	decl = finish_id_expression (t, decl, NULL_TREE,
17888 				     &idk,
17889 				     integral_constant_expression_p,
17890           /*allow_non_integral_constant_expression_p=*/(cxx_dialect >= cxx11),
17891 				     &non_integral_constant_expression_p,
17892 				     /*template_p=*/false,
17893 				     /*done=*/true,
17894 				     /*address_p=*/false,
17895 				     /*template_arg_p=*/false,
17896 				     &error_msg,
17897 				     input_location);
17898 	if (error_msg)
17899 	  error (error_msg);
17900 	if (!function_p && identifier_p (decl))
17901 	  {
17902 	    if (complain & tf_error)
17903 	      unqualified_name_lookup_error (decl);
17904 	    decl = error_mark_node;
17905 	  }
17906 	RETURN (decl);
17907       }
17908 
17909     case TEMPLATE_ID_EXPR:
17910       {
17911 	tree object;
17912 	tree templ = RECUR (TREE_OPERAND (t, 0));
17913 	tree targs = TREE_OPERAND (t, 1);
17914 
17915 	if (targs)
17916 	  targs = tsubst_template_args (targs, args, complain, in_decl);
17917 	if (targs == error_mark_node)
17918 	  RETURN (error_mark_node);
17919 
17920 	if (TREE_CODE (templ) == SCOPE_REF)
17921 	  {
17922 	    tree name = TREE_OPERAND (templ, 1);
17923 	    tree tid = lookup_template_function (name, targs);
17924 	    TREE_OPERAND (templ, 1) = tid;
17925 	    RETURN (templ);
17926 	  }
17927 
17928 	if (variable_template_p (templ))
17929 	  RETURN (lookup_and_finish_template_variable (templ, targs, complain));
17930 
17931 	if (TREE_CODE (templ) == COMPONENT_REF)
17932 	  {
17933 	    object = TREE_OPERAND (templ, 0);
17934 	    templ = TREE_OPERAND (templ, 1);
17935 	  }
17936 	else
17937 	  object = NULL_TREE;
17938 	templ = lookup_template_function (templ, targs);
17939 
17940 	if (object)
17941 	  RETURN (build3 (COMPONENT_REF, TREE_TYPE (templ),
17942 			 object, templ, NULL_TREE));
17943 	else
17944 	  RETURN (baselink_for_fns (templ));
17945       }
17946 
17947     case INDIRECT_REF:
17948       {
17949 	tree r = RECUR (TREE_OPERAND (t, 0));
17950 
17951 	if (REFERENCE_REF_P (t))
17952 	  {
17953 	    /* A type conversion to reference type will be enclosed in
17954 	       such an indirect ref, but the substitution of the cast
17955 	       will have also added such an indirect ref.  */
17956 	    r = convert_from_reference (r);
17957 	  }
17958 	else
17959 	  r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
17960 				    complain|decltype_flag);
17961 
17962 	if (REF_PARENTHESIZED_P (t))
17963 	  r = force_paren_expr (r);
17964 
17965 	RETURN (r);
17966       }
17967 
17968     case NOP_EXPR:
17969       {
17970 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17971 	tree op0 = RECUR (TREE_OPERAND (t, 0));
17972 	RETURN (build_nop (type, op0));
17973       }
17974 
17975     case IMPLICIT_CONV_EXPR:
17976       {
17977 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17978 	tree expr = RECUR (TREE_OPERAND (t, 0));
17979 	if (dependent_type_p (type) || type_dependent_expression_p (expr))
17980 	  {
17981 	    retval = copy_node (t);
17982 	    TREE_TYPE (retval) = type;
17983 	    TREE_OPERAND (retval, 0) = expr;
17984 	    RETURN (retval);
17985 	  }
17986 	if (IMPLICIT_CONV_EXPR_NONTYPE_ARG (t))
17987 	  /* We'll pass this to convert_nontype_argument again, we don't need
17988 	     to actually perform any conversion here.  */
17989 	  RETURN (expr);
17990 	int flags = LOOKUP_IMPLICIT;
17991 	if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
17992 	  flags = LOOKUP_NORMAL;
17993 	RETURN (perform_implicit_conversion_flags (type, expr, complain,
17994 						  flags));
17995       }
17996 
17997     case CONVERT_EXPR:
17998       {
17999 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
18000 	tree op0 = RECUR (TREE_OPERAND (t, 0));
18001 	if (op0 == error_mark_node)
18002 	  RETURN (error_mark_node);
18003 	RETURN (build1 (CONVERT_EXPR, type, op0));
18004       }
18005 
18006     case CAST_EXPR:
18007     case REINTERPRET_CAST_EXPR:
18008     case CONST_CAST_EXPR:
18009     case DYNAMIC_CAST_EXPR:
18010     case STATIC_CAST_EXPR:
18011       {
18012 	tree type;
18013 	tree op, r = NULL_TREE;
18014 
18015 	type = tsubst (TREE_TYPE (t), args, complain, in_decl);
18016 	if (integral_constant_expression_p
18017 	    && !cast_valid_in_integral_constant_expression_p (type))
18018 	  {
18019             if (complain & tf_error)
18020               error ("a cast to a type other than an integral or "
18021                      "enumeration type cannot appear in a constant-expression");
18022 	    RETURN (error_mark_node);
18023 	  }
18024 
18025 	op = RECUR (TREE_OPERAND (t, 0));
18026 
18027 	warning_sentinel s(warn_useless_cast);
18028 	warning_sentinel s2(warn_ignored_qualifiers);
18029 	switch (TREE_CODE (t))
18030 	  {
18031 	  case CAST_EXPR:
18032 	    r = build_functional_cast (type, op, complain);
18033 	    break;
18034 	  case REINTERPRET_CAST_EXPR:
18035 	    r = build_reinterpret_cast (type, op, complain);
18036 	    break;
18037 	  case CONST_CAST_EXPR:
18038 	    r = build_const_cast (type, op, complain);
18039 	    break;
18040 	  case DYNAMIC_CAST_EXPR:
18041 	    r = build_dynamic_cast (type, op, complain);
18042 	    break;
18043 	  case STATIC_CAST_EXPR:
18044 	    r = build_static_cast (type, op, complain);
18045 	    break;
18046 	  default:
18047 	    gcc_unreachable ();
18048 	  }
18049 
18050 	RETURN (r);
18051       }
18052 
18053     case POSTDECREMENT_EXPR:
18054     case POSTINCREMENT_EXPR:
18055       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
18056 						args, complain, in_decl);
18057       RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
18058 				complain|decltype_flag));
18059 
18060     case PREDECREMENT_EXPR:
18061     case PREINCREMENT_EXPR:
18062     case NEGATE_EXPR:
18063     case BIT_NOT_EXPR:
18064     case ABS_EXPR:
18065     case TRUTH_NOT_EXPR:
18066     case UNARY_PLUS_EXPR:  /* Unary + */
18067     case REALPART_EXPR:
18068     case IMAGPART_EXPR:
18069       RETURN (build_x_unary_op (input_location, TREE_CODE (t),
18070 				RECUR (TREE_OPERAND (t, 0)),
18071 				complain|decltype_flag));
18072 
18073     case FIX_TRUNC_EXPR:
18074       gcc_unreachable ();
18075 
18076     case ADDR_EXPR:
18077       op1 = TREE_OPERAND (t, 0);
18078       if (TREE_CODE (op1) == LABEL_DECL)
18079 	RETURN (finish_label_address_expr (DECL_NAME (op1),
18080 					  EXPR_LOCATION (op1)));
18081       if (TREE_CODE (op1) == SCOPE_REF)
18082 	op1 = tsubst_qualified_id (op1, args, complain, in_decl,
18083 				   /*done=*/true, /*address_p=*/true);
18084       else
18085 	op1 = tsubst_non_call_postfix_expression (op1, args, complain,
18086 						  in_decl);
18087       RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
18088 				complain|decltype_flag));
18089 
18090     case PLUS_EXPR:
18091     case MINUS_EXPR:
18092     case MULT_EXPR:
18093     case TRUNC_DIV_EXPR:
18094     case CEIL_DIV_EXPR:
18095     case FLOOR_DIV_EXPR:
18096     case ROUND_DIV_EXPR:
18097     case EXACT_DIV_EXPR:
18098     case BIT_AND_EXPR:
18099     case BIT_IOR_EXPR:
18100     case BIT_XOR_EXPR:
18101     case TRUNC_MOD_EXPR:
18102     case FLOOR_MOD_EXPR:
18103     case TRUTH_ANDIF_EXPR:
18104     case TRUTH_ORIF_EXPR:
18105     case TRUTH_AND_EXPR:
18106     case TRUTH_OR_EXPR:
18107     case RSHIFT_EXPR:
18108     case LSHIFT_EXPR:
18109     case RROTATE_EXPR:
18110     case LROTATE_EXPR:
18111     case EQ_EXPR:
18112     case NE_EXPR:
18113     case MAX_EXPR:
18114     case MIN_EXPR:
18115     case LE_EXPR:
18116     case GE_EXPR:
18117     case LT_EXPR:
18118     case GT_EXPR:
18119     case MEMBER_REF:
18120     case DOTSTAR_EXPR:
18121       {
18122 	warning_sentinel s1(warn_type_limits);
18123 	warning_sentinel s2(warn_div_by_zero);
18124 	warning_sentinel s3(warn_logical_op);
18125 	warning_sentinel s4(warn_tautological_compare);
18126 	tree op0 = RECUR (TREE_OPERAND (t, 0));
18127 	tree op1 = RECUR (TREE_OPERAND (t, 1));
18128 	tree r = build_x_binary_op
18129 	  (input_location, TREE_CODE (t),
18130 	   op0,
18131 	   (TREE_NO_WARNING (TREE_OPERAND (t, 0))
18132 	    ? ERROR_MARK
18133 	    : TREE_CODE (TREE_OPERAND (t, 0))),
18134 	   op1,
18135 	   (TREE_NO_WARNING (TREE_OPERAND (t, 1))
18136 	    ? ERROR_MARK
18137 	    : TREE_CODE (TREE_OPERAND (t, 1))),
18138 	   /*overload=*/NULL,
18139 	   complain|decltype_flag);
18140 	if (EXPR_P (r) && TREE_NO_WARNING (t))
18141 	  TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
18142 
18143 	RETURN (r);
18144       }
18145 
18146     case POINTER_PLUS_EXPR:
18147       {
18148 	tree op0 = RECUR (TREE_OPERAND (t, 0));
18149 	tree op1 = RECUR (TREE_OPERAND (t, 1));
18150 	RETURN (fold_build_pointer_plus (op0, op1));
18151       }
18152 
18153     case SCOPE_REF:
18154       RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
18155 				  /*address_p=*/false));
18156     case ARRAY_REF:
18157       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
18158 						args, complain, in_decl);
18159       RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
18160 				 RECUR (TREE_OPERAND (t, 1)),
18161 				 complain|decltype_flag));
18162 
18163     case SIZEOF_EXPR:
18164       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
18165 	  || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
18166 	RETURN (tsubst_copy (t, args, complain, in_decl));
18167       /* Fall through */
18168 
18169     case ALIGNOF_EXPR:
18170       {
18171 	tree r;
18172 
18173 	op1 = TREE_OPERAND (t, 0);
18174 	if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
18175 	  op1 = TREE_TYPE (op1);
18176 	bool std_alignof = (TREE_CODE (t) == ALIGNOF_EXPR
18177 			    && ALIGNOF_EXPR_STD_P (t));
18178         if (!args)
18179 	  {
18180 	    /* When there are no ARGS, we are trying to evaluate a
18181 	       non-dependent expression from the parser.  Trying to do
18182 	       the substitutions may not work.  */
18183 	    if (!TYPE_P (op1))
18184 	      op1 = TREE_TYPE (op1);
18185 	  }
18186 	else
18187 	  {
18188 	    ++cp_unevaluated_operand;
18189 	    ++c_inhibit_evaluation_warnings;
18190 	    if (TYPE_P (op1))
18191 	      op1 = tsubst (op1, args, complain, in_decl);
18192 	    else
18193 	      op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
18194 					   /*function_p=*/false,
18195 					   /*integral_constant_expression_p=*/
18196 					   false);
18197 	    --cp_unevaluated_operand;
18198 	    --c_inhibit_evaluation_warnings;
18199 	  }
18200         if (TYPE_P (op1))
18201 	  r = cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), std_alignof,
18202 					  complain & tf_error);
18203 	else
18204 	  r = cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t),
18205 					  complain & tf_error);
18206 	if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
18207 	  {
18208 	    if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
18209 	      {
18210 		if (!processing_template_decl && TYPE_P (op1))
18211 		  {
18212 		    r = build_min (SIZEOF_EXPR, size_type_node,
18213 				   build1 (NOP_EXPR, op1, error_mark_node));
18214 		    SIZEOF_EXPR_TYPE_P (r) = 1;
18215 		  }
18216 		else
18217 		  r = build_min (SIZEOF_EXPR, size_type_node, op1);
18218 		TREE_SIDE_EFFECTS (r) = 0;
18219 		TREE_READONLY (r) = 1;
18220 	      }
18221 	    SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
18222 	  }
18223 	RETURN (r);
18224       }
18225 
18226     case AT_ENCODE_EXPR:
18227       {
18228 	op1 = TREE_OPERAND (t, 0);
18229 	++cp_unevaluated_operand;
18230 	++c_inhibit_evaluation_warnings;
18231 	op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
18232 				     /*function_p=*/false,
18233 				     /*integral_constant_expression_p=*/false);
18234 	--cp_unevaluated_operand;
18235 	--c_inhibit_evaluation_warnings;
18236 	RETURN (objc_build_encode_expr (op1));
18237       }
18238 
18239     case NOEXCEPT_EXPR:
18240       op1 = TREE_OPERAND (t, 0);
18241       ++cp_unevaluated_operand;
18242       ++c_inhibit_evaluation_warnings;
18243       ++cp_noexcept_operand;
18244       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
18245 				   /*function_p=*/false,
18246 				   /*integral_constant_expression_p=*/false);
18247       --cp_unevaluated_operand;
18248       --c_inhibit_evaluation_warnings;
18249       --cp_noexcept_operand;
18250       RETURN (finish_noexcept_expr (op1, complain));
18251 
18252     case MODOP_EXPR:
18253       {
18254 	warning_sentinel s(warn_div_by_zero);
18255 	tree lhs = RECUR (TREE_OPERAND (t, 0));
18256 	tree rhs = RECUR (TREE_OPERAND (t, 2));
18257 	tree r = build_x_modify_expr
18258 	  (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
18259 	   complain|decltype_flag);
18260 	/* TREE_NO_WARNING must be set if either the expression was
18261 	   parenthesized or it uses an operator such as >>= rather
18262 	   than plain assignment.  In the former case, it was already
18263 	   set and must be copied.  In the latter case,
18264 	   build_x_modify_expr sets it and it must not be reset
18265 	   here.  */
18266 	if (TREE_NO_WARNING (t))
18267 	  TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
18268 
18269 	RETURN (r);
18270       }
18271 
18272     case ARROW_EXPR:
18273       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
18274 						args, complain, in_decl);
18275       /* Remember that there was a reference to this entity.  */
18276       if (DECL_P (op1)
18277 	  && !mark_used (op1, complain) && !(complain & tf_error))
18278 	RETURN (error_mark_node);
18279       RETURN (build_x_arrow (input_location, op1, complain));
18280 
18281     case NEW_EXPR:
18282       {
18283 	tree placement = RECUR (TREE_OPERAND (t, 0));
18284 	tree init = RECUR (TREE_OPERAND (t, 3));
18285 	vec<tree, va_gc> *placement_vec;
18286 	vec<tree, va_gc> *init_vec;
18287 	tree ret;
18288 
18289 	if (placement == NULL_TREE)
18290 	  placement_vec = NULL;
18291 	else
18292 	  {
18293 	    placement_vec = make_tree_vector ();
18294 	    for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
18295 	      vec_safe_push (placement_vec, TREE_VALUE (placement));
18296 	  }
18297 
18298 	/* If there was an initializer in the original tree, but it
18299 	   instantiated to an empty list, then we should pass a
18300 	   non-NULL empty vector to tell build_new that it was an
18301 	   empty initializer() rather than no initializer.  This can
18302 	   only happen when the initializer is a pack expansion whose
18303 	   parameter packs are of length zero.  */
18304 	if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
18305 	  init_vec = NULL;
18306 	else
18307 	  {
18308 	    init_vec = make_tree_vector ();
18309 	    if (init == void_node)
18310 	      gcc_assert (init_vec != NULL);
18311 	    else
18312 	      {
18313 		for (; init != NULL_TREE; init = TREE_CHAIN (init))
18314 		  vec_safe_push (init_vec, TREE_VALUE (init));
18315 	      }
18316 	  }
18317 
18318 	tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
18319 	tree op2 = RECUR (TREE_OPERAND (t, 2));
18320 	ret = build_new (&placement_vec, op1, op2, &init_vec,
18321 			 NEW_EXPR_USE_GLOBAL (t),
18322 			 complain);
18323 
18324 	if (placement_vec != NULL)
18325 	  release_tree_vector (placement_vec);
18326 	if (init_vec != NULL)
18327 	  release_tree_vector (init_vec);
18328 
18329 	RETURN (ret);
18330       }
18331 
18332     case DELETE_EXPR:
18333       {
18334 	tree op0 = RECUR (TREE_OPERAND (t, 0));
18335 	tree op1 = RECUR (TREE_OPERAND (t, 1));
18336 	RETURN (delete_sanity (op0, op1,
18337 			       DELETE_EXPR_USE_VEC (t),
18338 			       DELETE_EXPR_USE_GLOBAL (t),
18339 			       complain));
18340       }
18341 
18342     case COMPOUND_EXPR:
18343       {
18344 	tree op0 = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
18345 					  complain & ~tf_decltype, in_decl,
18346 					  /*function_p=*/false,
18347 					  integral_constant_expression_p);
18348 	RETURN (build_x_compound_expr (EXPR_LOCATION (t),
18349 				       op0,
18350 				       RECUR (TREE_OPERAND (t, 1)),
18351 				       complain|decltype_flag));
18352       }
18353 
18354     case CALL_EXPR:
18355       {
18356 	tree function;
18357 	vec<tree, va_gc> *call_args;
18358 	unsigned int nargs, i;
18359 	bool qualified_p;
18360 	bool koenig_p;
18361 	tree ret;
18362 
18363 	function = CALL_EXPR_FN (t);
18364 	/* Internal function with no arguments.  */
18365 	if (function == NULL_TREE && call_expr_nargs (t) == 0)
18366 	  RETURN (t);
18367 
18368 	/* When we parsed the expression, we determined whether or
18369 	   not Koenig lookup should be performed.  */
18370 	koenig_p = KOENIG_LOOKUP_P (t);
18371 	if (function == NULL_TREE)
18372 	  {
18373 	    koenig_p = false;
18374 	    qualified_p = false;
18375 	  }
18376 	else if (TREE_CODE (function) == SCOPE_REF)
18377 	  {
18378 	    qualified_p = true;
18379 	    function = tsubst_qualified_id (function, args, complain, in_decl,
18380 					    /*done=*/false,
18381 					    /*address_p=*/false);
18382 	  }
18383 	else if (koenig_p && identifier_p (function))
18384 	  {
18385 	    /* Do nothing; calling tsubst_copy_and_build on an identifier
18386 	       would incorrectly perform unqualified lookup again.
18387 
18388 	       Note that we can also have an IDENTIFIER_NODE if the earlier
18389 	       unqualified lookup found a member function; in that case
18390 	       koenig_p will be false and we do want to do the lookup
18391 	       again to find the instantiated member function.
18392 
18393 	       FIXME but doing that causes c++/15272, so we need to stop
18394 	       using IDENTIFIER_NODE in that situation.  */
18395 	    qualified_p = false;
18396 	  }
18397 	else
18398 	  {
18399 	    if (TREE_CODE (function) == COMPONENT_REF)
18400 	      {
18401 		tree op = TREE_OPERAND (function, 1);
18402 
18403 		qualified_p = (TREE_CODE (op) == SCOPE_REF
18404 			       || (BASELINK_P (op)
18405 				   && BASELINK_QUALIFIED_P (op)));
18406 	      }
18407 	    else
18408 	      qualified_p = false;
18409 
18410 	    if (TREE_CODE (function) == ADDR_EXPR
18411 		&& TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
18412 	      /* Avoid error about taking the address of a constructor.  */
18413 	      function = TREE_OPERAND (function, 0);
18414 
18415 	    function = tsubst_copy_and_build (function, args, complain,
18416 					      in_decl,
18417 					      !qualified_p,
18418 					      integral_constant_expression_p);
18419 
18420 	    if (BASELINK_P (function))
18421 	      qualified_p = true;
18422 	  }
18423 
18424 	nargs = call_expr_nargs (t);
18425 	call_args = make_tree_vector ();
18426 	for (i = 0; i < nargs; ++i)
18427 	  {
18428 	    tree arg = CALL_EXPR_ARG (t, i);
18429 
18430 	    if (!PACK_EXPANSION_P (arg))
18431 	      vec_safe_push (call_args, RECUR (CALL_EXPR_ARG (t, i)));
18432 	    else
18433 	      {
18434 		/* Expand the pack expansion and push each entry onto
18435 		   CALL_ARGS.  */
18436 		arg = tsubst_pack_expansion (arg, args, complain, in_decl);
18437 		if (TREE_CODE (arg) == TREE_VEC)
18438 		  {
18439 		    unsigned int len, j;
18440 
18441 		    len = TREE_VEC_LENGTH (arg);
18442 		    for (j = 0; j < len; ++j)
18443 		      {
18444 			tree value = TREE_VEC_ELT (arg, j);
18445 			if (value != NULL_TREE)
18446 			  value = convert_from_reference (value);
18447 			vec_safe_push (call_args, value);
18448 		      }
18449 		  }
18450 		else
18451 		  {
18452 		    /* A partial substitution.  Add one entry.  */
18453 		    vec_safe_push (call_args, arg);
18454 		  }
18455 	      }
18456 	  }
18457 
18458 	/* We do not perform argument-dependent lookup if normal
18459 	   lookup finds a non-function, in accordance with the
18460 	   expected resolution of DR 218.  */
18461 	if (koenig_p
18462 	    && ((is_overloaded_fn (function)
18463 		 /* If lookup found a member function, the Koenig lookup is
18464 		    not appropriate, even if an unqualified-name was used
18465 		    to denote the function.  */
18466 		 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
18467 		|| identifier_p (function))
18468 	    /* Only do this when substitution turns a dependent call
18469 	       into a non-dependent call.  */
18470 	    && type_dependent_expression_p_push (t)
18471 	    && !any_type_dependent_arguments_p (call_args))
18472 	  function = perform_koenig_lookup (function, call_args, tf_none);
18473 
18474 	if (function != NULL_TREE
18475 	    && identifier_p (function)
18476 	    && !any_type_dependent_arguments_p (call_args))
18477 	  {
18478 	    if (koenig_p && (complain & tf_warning_or_error))
18479 	      {
18480 		/* For backwards compatibility and good diagnostics, try
18481 		   the unqualified lookup again if we aren't in SFINAE
18482 		   context.  */
18483 		tree unq = (tsubst_copy_and_build
18484 			    (function, args, complain, in_decl, true,
18485 			     integral_constant_expression_p));
18486 		if (unq == error_mark_node)
18487 		  {
18488 		    release_tree_vector (call_args);
18489 		    RETURN (error_mark_node);
18490 		  }
18491 
18492 		if (unq != function)
18493 		  {
18494 		    /* In a lambda fn, we have to be careful to not
18495 		       introduce new this captures.  Legacy code can't
18496 		       be using lambdas anyway, so it's ok to be
18497 		       stricter.  */
18498 		    bool in_lambda = (current_class_type
18499 				      && LAMBDA_TYPE_P (current_class_type));
18500 		    char const *const msg
18501 		      = G_("%qD was not declared in this scope, "
18502 			   "and no declarations were found by "
18503 			   "argument-dependent lookup at the point "
18504 			   "of instantiation");
18505 
18506 		    bool diag = true;
18507 		    if (in_lambda)
18508 		      error_at (EXPR_LOC_OR_LOC (t, input_location),
18509 				msg, function);
18510 		    else
18511 		      diag = permerror (EXPR_LOC_OR_LOC (t, input_location),
18512 					msg, function);
18513 		    if (diag)
18514 		      {
18515 			tree fn = unq;
18516 
18517 			if (INDIRECT_REF_P (fn))
18518 			  fn = TREE_OPERAND (fn, 0);
18519 			if (is_overloaded_fn (fn))
18520 			  fn = get_first_fn (fn);
18521 
18522 			if (!DECL_P (fn))
18523 			  /* Can't say anything more.  */;
18524 			else if (DECL_CLASS_SCOPE_P (fn))
18525 			  {
18526 			    location_t loc = EXPR_LOC_OR_LOC (t,
18527 							      input_location);
18528 			    inform (loc,
18529 				    "declarations in dependent base %qT are "
18530 				    "not found by unqualified lookup",
18531 				    DECL_CLASS_CONTEXT (fn));
18532 			    if (current_class_ptr)
18533 			      inform (loc,
18534 				      "use %<this->%D%> instead", function);
18535 			    else
18536 			      inform (loc,
18537 				      "use %<%T::%D%> instead",
18538 				      current_class_name, function);
18539 			  }
18540 			else
18541 			  inform (DECL_SOURCE_LOCATION (fn),
18542 				  "%qD declared here, later in the "
18543 				  "translation unit", fn);
18544 			if (in_lambda)
18545 			  {
18546 			    release_tree_vector (call_args);
18547 			    RETURN (error_mark_node);
18548 			  }
18549 		      }
18550 
18551 		    function = unq;
18552 		  }
18553 	      }
18554 	    if (identifier_p (function))
18555 	      {
18556 		if (complain & tf_error)
18557 		  unqualified_name_lookup_error (function);
18558 		release_tree_vector (call_args);
18559 		RETURN (error_mark_node);
18560 	      }
18561 	  }
18562 
18563 	/* Remember that there was a reference to this entity.  */
18564 	if (function != NULL_TREE
18565 	    && DECL_P (function)
18566 	    && !mark_used (function, complain) && !(complain & tf_error))
18567 	  {
18568 	    release_tree_vector (call_args);
18569 	    RETURN (error_mark_node);
18570 	  }
18571 
18572 	/* Put back tf_decltype for the actual call.  */
18573 	complain |= decltype_flag;
18574 
18575 	if (function == NULL_TREE)
18576 	  switch (CALL_EXPR_IFN (t))
18577 	    {
18578 	    case IFN_LAUNDER:
18579 	      gcc_assert (nargs == 1);
18580 	      if (vec_safe_length (call_args) != 1)
18581 		{
18582 		  error_at (EXPR_LOC_OR_LOC (t, input_location),
18583 			    "wrong number of arguments to "
18584 			    "%<__builtin_launder%>");
18585 		  ret = error_mark_node;
18586 		}
18587 	      else
18588 		ret = finish_builtin_launder (EXPR_LOC_OR_LOC (t,
18589 							       input_location),
18590 					      (*call_args)[0], complain);
18591 	      break;
18592 
18593 	    default:
18594 	      /* Unsupported internal function with arguments.  */
18595 	      gcc_unreachable ();
18596 	    }
18597 	else if (TREE_CODE (function) == OFFSET_REF
18598 		 || TREE_CODE (function) == DOTSTAR_EXPR
18599 		 || TREE_CODE (function) == MEMBER_REF)
18600 	  ret = build_offset_ref_call_from_tree (function, &call_args,
18601 						 complain);
18602 	else if (TREE_CODE (function) == COMPONENT_REF)
18603 	  {
18604 	    tree instance = TREE_OPERAND (function, 0);
18605 	    tree fn = TREE_OPERAND (function, 1);
18606 
18607 	    if (processing_template_decl
18608 		&& (type_dependent_expression_p (instance)
18609 		    || (!BASELINK_P (fn)
18610 			&& TREE_CODE (fn) != FIELD_DECL)
18611 		    || type_dependent_expression_p (fn)
18612 		    || any_type_dependent_arguments_p (call_args)))
18613 	      ret = build_min_nt_call_vec (function, call_args);
18614 	    else if (!BASELINK_P (fn))
18615 	      ret = finish_call_expr (function, &call_args,
18616 				       /*disallow_virtual=*/false,
18617 				       /*koenig_p=*/false,
18618 				       complain);
18619 	    else
18620 	      ret = (build_new_method_call
18621 		      (instance, fn,
18622 		       &call_args, NULL_TREE,
18623 		       qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
18624 		       /*fn_p=*/NULL,
18625 		       complain));
18626 	  }
18627 	else
18628 	  ret = finish_call_expr (function, &call_args,
18629 				  /*disallow_virtual=*/qualified_p,
18630 				  koenig_p,
18631 				  complain);
18632 
18633 	release_tree_vector (call_args);
18634 
18635 	if (ret != error_mark_node)
18636 	  {
18637 	    bool op = CALL_EXPR_OPERATOR_SYNTAX (t);
18638 	    bool ord = CALL_EXPR_ORDERED_ARGS (t);
18639 	    bool rev = CALL_EXPR_REVERSE_ARGS (t);
18640 	    bool thk = CALL_FROM_THUNK_P (t);
18641 	    if (op || ord || rev || thk)
18642 	      {
18643 		function = extract_call_expr (ret);
18644 		CALL_EXPR_OPERATOR_SYNTAX (function) = op;
18645 		CALL_EXPR_ORDERED_ARGS (function) = ord;
18646 		CALL_EXPR_REVERSE_ARGS (function) = rev;
18647 		if (thk)
18648 		  {
18649 		    /* The thunk location is not interesting.  */
18650 		    SET_EXPR_LOCATION (function, UNKNOWN_LOCATION);
18651 		  }
18652 	      }
18653 	  }
18654 
18655 	RETURN (ret);
18656       }
18657 
18658     case COND_EXPR:
18659       {
18660 	tree cond = RECUR (TREE_OPERAND (t, 0));
18661 	cond = mark_rvalue_use (cond);
18662 	tree folded_cond = fold_non_dependent_expr (cond);
18663 	tree exp1, exp2;
18664 
18665 	if (TREE_CODE (folded_cond) == INTEGER_CST)
18666 	  {
18667 	    if (integer_zerop (folded_cond))
18668 	      {
18669 		++c_inhibit_evaluation_warnings;
18670 		exp1 = RECUR (TREE_OPERAND (t, 1));
18671 		--c_inhibit_evaluation_warnings;
18672 		exp2 = RECUR (TREE_OPERAND (t, 2));
18673 	      }
18674 	    else
18675 	      {
18676 		exp1 = RECUR (TREE_OPERAND (t, 1));
18677 		++c_inhibit_evaluation_warnings;
18678 		exp2 = RECUR (TREE_OPERAND (t, 2));
18679 		--c_inhibit_evaluation_warnings;
18680 	      }
18681 	    cond = folded_cond;
18682 	  }
18683 	else
18684 	  {
18685 	    exp1 = RECUR (TREE_OPERAND (t, 1));
18686 	    exp2 = RECUR (TREE_OPERAND (t, 2));
18687 	  }
18688 
18689 	warning_sentinel s(warn_duplicated_branches);
18690 	RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
18691 					 cond, exp1, exp2, complain));
18692       }
18693 
18694     case PSEUDO_DTOR_EXPR:
18695       {
18696 	tree op0 = RECUR (TREE_OPERAND (t, 0));
18697 	tree op1 = RECUR (TREE_OPERAND (t, 1));
18698 	tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
18699 	RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
18700 					       input_location));
18701       }
18702 
18703     case TREE_LIST:
18704       {
18705 	tree purpose, value, chain;
18706 
18707 	if (t == void_list_node)
18708 	  RETURN (t);
18709 
18710         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
18711             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
18712           {
18713             /* We have pack expansions, so expand those and
18714                create a new list out of it.  */
18715             tree purposevec = NULL_TREE;
18716             tree valuevec = NULL_TREE;
18717             tree chain;
18718             int i, len = -1;
18719 
18720             /* Expand the argument expressions.  */
18721             if (TREE_PURPOSE (t))
18722               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
18723                                                  complain, in_decl);
18724             if (TREE_VALUE (t))
18725               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
18726                                                complain, in_decl);
18727 
18728             /* Build the rest of the list.  */
18729             chain = TREE_CHAIN (t);
18730             if (chain && chain != void_type_node)
18731               chain = RECUR (chain);
18732 
18733             /* Determine the number of arguments.  */
18734             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
18735               {
18736                 len = TREE_VEC_LENGTH (purposevec);
18737                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
18738               }
18739             else if (TREE_CODE (valuevec) == TREE_VEC)
18740               len = TREE_VEC_LENGTH (valuevec);
18741             else
18742               {
18743                 /* Since we only performed a partial substitution into
18744                    the argument pack, we only RETURN (a single list
18745                    node.  */
18746                 if (purposevec == TREE_PURPOSE (t)
18747                     && valuevec == TREE_VALUE (t)
18748                     && chain == TREE_CHAIN (t))
18749                   RETURN (t);
18750 
18751                 RETURN (tree_cons (purposevec, valuevec, chain));
18752               }
18753 
18754             /* Convert the argument vectors into a TREE_LIST */
18755             i = len;
18756             while (i > 0)
18757               {
18758                 /* Grab the Ith values.  */
18759                 i--;
18760                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i)
18761 		                     : NULL_TREE;
18762                 value
18763 		  = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i))
18764                              : NULL_TREE;
18765 
18766                 /* Build the list (backwards).  */
18767                 chain = tree_cons (purpose, value, chain);
18768               }
18769 
18770             RETURN (chain);
18771           }
18772 
18773 	purpose = TREE_PURPOSE (t);
18774 	if (purpose)
18775 	  purpose = RECUR (purpose);
18776 	value = TREE_VALUE (t);
18777 	if (value)
18778 	  value = RECUR (value);
18779 	chain = TREE_CHAIN (t);
18780 	if (chain && chain != void_type_node)
18781 	  chain = RECUR (chain);
18782 	if (purpose == TREE_PURPOSE (t)
18783 	    && value == TREE_VALUE (t)
18784 	    && chain == TREE_CHAIN (t))
18785 	  RETURN (t);
18786 	RETURN (tree_cons (purpose, value, chain));
18787       }
18788 
18789     case COMPONENT_REF:
18790       {
18791 	tree object;
18792 	tree object_type;
18793 	tree member;
18794 	tree r;
18795 
18796 	object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
18797 						     args, complain, in_decl);
18798 	/* Remember that there was a reference to this entity.  */
18799 	if (DECL_P (object)
18800 	    && !mark_used (object, complain) && !(complain & tf_error))
18801 	  RETURN (error_mark_node);
18802 	object_type = TREE_TYPE (object);
18803 
18804 	member = TREE_OPERAND (t, 1);
18805 	if (BASELINK_P (member))
18806 	  member = tsubst_baselink (member,
18807 				    non_reference (TREE_TYPE (object)),
18808 				    args, complain, in_decl);
18809 	else
18810 	  member = tsubst_copy (member, args, complain, in_decl);
18811 	if (member == error_mark_node)
18812 	  RETURN (error_mark_node);
18813 
18814 	if (TREE_CODE (member) == FIELD_DECL)
18815 	  {
18816 	    r = finish_non_static_data_member (member, object, NULL_TREE);
18817 	    if (TREE_CODE (r) == COMPONENT_REF)
18818 	      REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
18819 	    RETURN (r);
18820 	  }
18821 	else if (type_dependent_expression_p (object))
18822 	  /* We can't do much here.  */;
18823 	else if (!CLASS_TYPE_P (object_type))
18824 	  {
18825 	    if (scalarish_type_p (object_type))
18826 	      {
18827 		tree s = NULL_TREE;
18828 		tree dtor = member;
18829 
18830 		if (TREE_CODE (dtor) == SCOPE_REF)
18831 		  {
18832 		    s = TREE_OPERAND (dtor, 0);
18833 		    dtor = TREE_OPERAND (dtor, 1);
18834 		  }
18835 		if (TREE_CODE (dtor) == BIT_NOT_EXPR)
18836 		  {
18837 		    dtor = TREE_OPERAND (dtor, 0);
18838 		    if (TYPE_P (dtor))
18839 		      RETURN (finish_pseudo_destructor_expr
18840 			      (object, s, dtor, input_location));
18841 		  }
18842 	      }
18843 	  }
18844 	else if (TREE_CODE (member) == SCOPE_REF
18845 		 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
18846 	  {
18847 	    /* Lookup the template functions now that we know what the
18848 	       scope is.  */
18849 	    tree scope = TREE_OPERAND (member, 0);
18850 	    tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
18851 	    tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
18852 	    member = lookup_qualified_name (scope, tmpl,
18853 					    /*is_type_p=*/false,
18854 					    /*complain=*/false);
18855 	    if (BASELINK_P (member))
18856 	      {
18857 		BASELINK_FUNCTIONS (member)
18858 		  = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
18859 			      args);
18860 		member = (adjust_result_of_qualified_name_lookup
18861 			  (member, BINFO_TYPE (BASELINK_BINFO (member)),
18862 			   object_type));
18863 	      }
18864 	    else
18865 	      {
18866 		qualified_name_lookup_error (scope, tmpl, member,
18867 					     input_location);
18868 		RETURN (error_mark_node);
18869 	      }
18870 	  }
18871 	else if (TREE_CODE (member) == SCOPE_REF
18872 		 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
18873 		 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
18874 	  {
18875 	    if (complain & tf_error)
18876 	      {
18877 		if (TYPE_P (TREE_OPERAND (member, 0)))
18878 		  error ("%qT is not a class or namespace",
18879 			 TREE_OPERAND (member, 0));
18880 		else
18881 		  error ("%qD is not a class or namespace",
18882 			 TREE_OPERAND (member, 0));
18883 	      }
18884 	    RETURN (error_mark_node);
18885 	  }
18886 
18887 	r = finish_class_member_access_expr (object, member,
18888 					     /*template_p=*/false,
18889 					     complain);
18890 	if (TREE_CODE (r) == COMPONENT_REF)
18891 	  REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
18892 	RETURN (r);
18893       }
18894 
18895     case THROW_EXPR:
18896       RETURN (build_throw
18897 	(RECUR (TREE_OPERAND (t, 0))));
18898 
18899     case CONSTRUCTOR:
18900       {
18901 	vec<constructor_elt, va_gc> *n;
18902 	constructor_elt *ce;
18903 	unsigned HOST_WIDE_INT idx;
18904 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
18905 	bool process_index_p;
18906         int newlen;
18907         bool need_copy_p = false;
18908 	tree r;
18909 
18910 	if (type == error_mark_node)
18911 	  RETURN (error_mark_node);
18912 
18913 	/* We do not want to process the index of aggregate
18914 	   initializers as they are identifier nodes which will be
18915 	   looked up by digest_init.  */
18916 	process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
18917 
18918 	if (null_member_pointer_value_p (t))
18919 	  {
18920 	    gcc_assert (same_type_p (type, TREE_TYPE (t)));
18921 	    RETURN (t);
18922 	  }
18923 
18924 	n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
18925         newlen = vec_safe_length (n);
18926 	FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
18927 	  {
18928 	    if (ce->index && process_index_p
18929 		/* An identifier index is looked up in the type
18930 		   being initialized, not the current scope.  */
18931 		&& TREE_CODE (ce->index) != IDENTIFIER_NODE)
18932 	      ce->index = RECUR (ce->index);
18933 
18934             if (PACK_EXPANSION_P (ce->value))
18935               {
18936                 /* Substitute into the pack expansion.  */
18937                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
18938                                                   in_decl);
18939 
18940 		if (ce->value == error_mark_node
18941 		    || PACK_EXPANSION_P (ce->value))
18942 		  ;
18943 		else if (TREE_VEC_LENGTH (ce->value) == 1)
18944                   /* Just move the argument into place.  */
18945                   ce->value = TREE_VEC_ELT (ce->value, 0);
18946                 else
18947                   {
18948                     /* Update the length of the final CONSTRUCTOR
18949                        arguments vector, and note that we will need to
18950                        copy.*/
18951                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
18952                     need_copy_p = true;
18953                   }
18954               }
18955             else
18956               ce->value = RECUR (ce->value);
18957 	  }
18958 
18959         if (need_copy_p)
18960           {
18961             vec<constructor_elt, va_gc> *old_n = n;
18962 
18963             vec_alloc (n, newlen);
18964             FOR_EACH_VEC_ELT (*old_n, idx, ce)
18965               {
18966                 if (TREE_CODE (ce->value) == TREE_VEC)
18967                   {
18968                     int i, len = TREE_VEC_LENGTH (ce->value);
18969                     for (i = 0; i < len; ++i)
18970                       CONSTRUCTOR_APPEND_ELT (n, 0,
18971                                               TREE_VEC_ELT (ce->value, i));
18972                   }
18973                 else
18974                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
18975               }
18976           }
18977 
18978 	r = build_constructor (init_list_type_node, n);
18979 	CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
18980 
18981 	if (TREE_HAS_CONSTRUCTOR (t))
18982 	  {
18983 	    fcl_t cl = fcl_functional;
18984 	    if (CONSTRUCTOR_C99_COMPOUND_LITERAL (t))
18985 	      cl = fcl_c99;
18986 	    RETURN (finish_compound_literal (type, r, complain, cl));
18987 	  }
18988 
18989 	TREE_TYPE (r) = type;
18990 	RETURN (r);
18991       }
18992 
18993     case TYPEID_EXPR:
18994       {
18995 	tree operand_0 = TREE_OPERAND (t, 0);
18996 	if (TYPE_P (operand_0))
18997 	  {
18998 	    operand_0 = tsubst (operand_0, args, complain, in_decl);
18999 	    RETURN (get_typeid (operand_0, complain));
19000 	  }
19001 	else
19002 	  {
19003 	    operand_0 = RECUR (operand_0);
19004 	    RETURN (build_typeid (operand_0, complain));
19005 	  }
19006       }
19007 
19008     case VAR_DECL:
19009       if (!args)
19010 	RETURN (t);
19011       /* Fall through */
19012 
19013     case PARM_DECL:
19014       {
19015 	tree r = tsubst_copy (t, args, complain, in_decl);
19016 	/* ??? We're doing a subset of finish_id_expression here.  */
19017 	if (tree wrap = maybe_get_tls_wrapper_call (r))
19018 	  /* Replace an evaluated use of the thread_local variable with
19019 	     a call to its wrapper.  */
19020 	  r = wrap;
19021 	else if (outer_automatic_var_p (r))
19022 	  r = process_outer_var_ref (r, complain);
19023 
19024 	if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
19025 	  /* If the original type was a reference, we'll be wrapped in
19026 	     the appropriate INDIRECT_REF.  */
19027 	  r = convert_from_reference (r);
19028 	RETURN (r);
19029       }
19030 
19031     case VA_ARG_EXPR:
19032       {
19033 	tree op0 = RECUR (TREE_OPERAND (t, 0));
19034 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19035 	RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
19036       }
19037 
19038     case OFFSETOF_EXPR:
19039       {
19040 	tree object_ptr
19041 	  = tsubst_copy_and_build (TREE_OPERAND (t, 1), args, complain,
19042 				   in_decl, /*function_p=*/false,
19043 				   /*integral_constant_expression_p=*/false);
19044 	RETURN (finish_offsetof (object_ptr,
19045 				 RECUR (TREE_OPERAND (t, 0)),
19046 				 EXPR_LOCATION (t)));
19047       }
19048 
19049     case ADDRESSOF_EXPR:
19050       RETURN (cp_build_addressof (EXPR_LOCATION (t),
19051 				  RECUR (TREE_OPERAND (t, 0)), complain));
19052 
19053     case TRAIT_EXPR:
19054       {
19055 	tree type1 = tsubst (TRAIT_EXPR_TYPE1 (t), args,
19056 			     complain, in_decl);
19057 
19058 	tree type2 = TRAIT_EXPR_TYPE2 (t);
19059 	if (type2 && TREE_CODE (type2) == TREE_LIST)
19060 	  type2 = RECUR (type2);
19061 	else if (type2)
19062 	  type2 = tsubst (type2, args, complain, in_decl);
19063 
19064 	RETURN (finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2));
19065       }
19066 
19067     case STMT_EXPR:
19068       {
19069 	tree old_stmt_expr = cur_stmt_expr;
19070 	tree stmt_expr = begin_stmt_expr ();
19071 
19072 	cur_stmt_expr = stmt_expr;
19073 	tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
19074 		     integral_constant_expression_p);
19075 	stmt_expr = finish_stmt_expr (stmt_expr, false);
19076 	cur_stmt_expr = old_stmt_expr;
19077 
19078 	/* If the resulting list of expression statement is empty,
19079 	   fold it further into void_node.  */
19080 	if (empty_expr_stmt_p (stmt_expr))
19081 	  stmt_expr = void_node;
19082 
19083 	RETURN (stmt_expr);
19084       }
19085 
19086     case LAMBDA_EXPR:
19087       {
19088 	tree r = tsubst_lambda_expr (t, args, complain, in_decl);
19089 
19090 	RETURN (build_lambda_object (r));
19091       }
19092 
19093     case TARGET_EXPR:
19094       /* We can get here for a constant initializer of non-dependent type.
19095          FIXME stop folding in cp_parser_initializer_clause.  */
19096       {
19097 	tree r = get_target_expr_sfinae (RECUR (TARGET_EXPR_INITIAL (t)),
19098 					 complain);
19099 	RETURN (r);
19100       }
19101 
19102     case TRANSACTION_EXPR:
19103       RETURN (tsubst_expr(t, args, complain, in_decl,
19104 	     integral_constant_expression_p));
19105 
19106     case PAREN_EXPR:
19107       RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
19108 
19109     case VEC_PERM_EXPR:
19110       {
19111 	tree op0 = RECUR (TREE_OPERAND (t, 0));
19112 	tree op1 = RECUR (TREE_OPERAND (t, 1));
19113 	tree op2 = RECUR (TREE_OPERAND (t, 2));
19114 	RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
19115 				       complain));
19116       }
19117 
19118     case REQUIRES_EXPR:
19119       RETURN (tsubst_requires_expr (t, args, complain, in_decl));
19120 
19121     case RANGE_EXPR:
19122       /* No need to substitute further, a RANGE_EXPR will always be built
19123 	 with constant operands.  */
19124       RETURN (t);
19125 
19126     case NON_LVALUE_EXPR:
19127     case VIEW_CONVERT_EXPR:
19128       /* We should only see these for location wrapper nodes, or within
19129 	 instantiate_non_dependent_expr (when args is NULL_TREE).  */
19130       gcc_assert (location_wrapper_p (t) || args == NULL_TREE);
19131       if (location_wrapper_p (t))
19132 	RETURN (maybe_wrap_with_location (RECUR (TREE_OPERAND (t, 0)),
19133 					  EXPR_LOCATION (t)));
19134       /* fallthrough.  */
19135 
19136     default:
19137       /* Handle Objective-C++ constructs, if appropriate.  */
19138       {
19139 	tree subst
19140 	  = objcp_tsubst_copy_and_build (t, args, complain,
19141 					 in_decl, /*function_p=*/false);
19142 	if (subst)
19143 	  RETURN (subst);
19144       }
19145       RETURN (tsubst_copy (t, args, complain, in_decl));
19146     }
19147 
19148 #undef RECUR
19149 #undef RETURN
19150  out:
19151   input_location = loc;
19152   return retval;
19153 }
19154 
19155 /* Verify that the instantiated ARGS are valid. For type arguments,
19156    make sure that the type's linkage is ok. For non-type arguments,
19157    make sure they are constants if they are integral or enumerations.
19158    Emit an error under control of COMPLAIN, and return TRUE on error.  */
19159 
19160 static bool
check_instantiated_arg(tree tmpl,tree t,tsubst_flags_t complain)19161 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
19162 {
19163   if (dependent_template_arg_p (t))
19164     return false;
19165   if (ARGUMENT_PACK_P (t))
19166     {
19167       tree vec = ARGUMENT_PACK_ARGS (t);
19168       int len = TREE_VEC_LENGTH (vec);
19169       bool result = false;
19170       int i;
19171 
19172       for (i = 0; i < len; ++i)
19173 	if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
19174 	  result = true;
19175       return result;
19176     }
19177   else if (TYPE_P (t))
19178     {
19179       /* [basic.link]: A name with no linkage (notably, the name
19180 	 of a class or enumeration declared in a local scope)
19181 	 shall not be used to declare an entity with linkage.
19182 	 This implies that names with no linkage cannot be used as
19183 	 template arguments
19184 
19185 	 DR 757 relaxes this restriction for C++0x.  */
19186       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
19187 		 : no_linkage_check (t, /*relaxed_p=*/false));
19188 
19189       if (nt)
19190 	{
19191 	  /* DR 488 makes use of a type with no linkage cause
19192 	     type deduction to fail.  */
19193 	  if (complain & tf_error)
19194 	    {
19195 	      if (TYPE_UNNAMED_P (nt))
19196 		error ("%qT is/uses unnamed type", t);
19197 	      else
19198 		error ("template argument for %qD uses local type %qT",
19199 		       tmpl, t);
19200 	    }
19201 	  return true;
19202 	}
19203       /* In order to avoid all sorts of complications, we do not
19204 	 allow variably-modified types as template arguments.  */
19205       else if (variably_modified_type_p (t, NULL_TREE))
19206 	{
19207 	  if (complain & tf_error)
19208 	    error ("%qT is a variably modified type", t);
19209 	  return true;
19210 	}
19211     }
19212   /* Class template and alias template arguments should be OK.  */
19213   else if (DECL_TYPE_TEMPLATE_P (t))
19214     ;
19215   /* A non-type argument of integral or enumerated type must be a
19216      constant.  */
19217   else if (TREE_TYPE (t)
19218 	   && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
19219 	   && !REFERENCE_REF_P (t)
19220 	   && !TREE_CONSTANT (t))
19221     {
19222       if (complain & tf_error)
19223 	error ("integral expression %qE is not constant", t);
19224       return true;
19225     }
19226   return false;
19227 }
19228 
19229 static bool
check_instantiated_args(tree tmpl,tree args,tsubst_flags_t complain)19230 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
19231 {
19232   int ix, len = DECL_NTPARMS (tmpl);
19233   bool result = false;
19234 
19235   for (ix = 0; ix != len; ix++)
19236     {
19237       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
19238 	result = true;
19239     }
19240   if (result && (complain & tf_error))
19241     error ("  trying to instantiate %qD", tmpl);
19242   return result;
19243 }
19244 
19245 /* We're out of SFINAE context now, so generate diagnostics for the access
19246    errors we saw earlier when instantiating D from TMPL and ARGS.  */
19247 
19248 static void
recheck_decl_substitution(tree d,tree tmpl,tree args)19249 recheck_decl_substitution (tree d, tree tmpl, tree args)
19250 {
19251   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
19252   tree type = TREE_TYPE (pattern);
19253   location_t loc = input_location;
19254 
19255   push_access_scope (d);
19256   push_deferring_access_checks (dk_no_deferred);
19257   input_location = DECL_SOURCE_LOCATION (pattern);
19258   tsubst (type, args, tf_warning_or_error, d);
19259   input_location = loc;
19260   pop_deferring_access_checks ();
19261   pop_access_scope (d);
19262 }
19263 
19264 /* Instantiate the indicated variable, function, or alias template TMPL with
19265    the template arguments in TARG_PTR.  */
19266 
19267 static tree
instantiate_template_1(tree tmpl,tree orig_args,tsubst_flags_t complain)19268 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
19269 {
19270   tree targ_ptr = orig_args;
19271   tree fndecl;
19272   tree gen_tmpl;
19273   tree spec;
19274   bool access_ok = true;
19275 
19276   if (tmpl == error_mark_node)
19277     return error_mark_node;
19278 
19279   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
19280 
19281   /* If this function is a clone, handle it specially.  */
19282   if (DECL_CLONED_FUNCTION_P (tmpl))
19283     {
19284       tree spec;
19285       tree clone;
19286 
19287       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
19288 	 DECL_CLONED_FUNCTION.  */
19289       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
19290 				   targ_ptr, complain);
19291       if (spec == error_mark_node)
19292 	return error_mark_node;
19293 
19294       /* Look for the clone.  */
19295       FOR_EACH_CLONE (clone, spec)
19296 	if (DECL_NAME (clone) == DECL_NAME (tmpl))
19297 	  return clone;
19298       /* We should always have found the clone by now.  */
19299       gcc_unreachable ();
19300       return NULL_TREE;
19301     }
19302 
19303   if (targ_ptr == error_mark_node)
19304     return error_mark_node;
19305 
19306   /* Check to see if we already have this specialization.  */
19307   gen_tmpl = most_general_template (tmpl);
19308   if (TMPL_ARGS_DEPTH (targ_ptr)
19309       < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)))
19310     /* targ_ptr only has the innermost template args, so add the outer ones
19311        from tmpl, which could be either a partial instantiation or gen_tmpl (in
19312        the case of a non-dependent call within a template definition).  */
19313     targ_ptr = (add_outermost_template_args
19314 		(DECL_TI_ARGS (DECL_TEMPLATE_RESULT (tmpl)),
19315 		 targ_ptr));
19316 
19317   /* It would be nice to avoid hashing here and then again in tsubst_decl,
19318      but it doesn't seem to be on the hot path.  */
19319   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
19320 
19321   gcc_assert (tmpl == gen_tmpl
19322 	      || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
19323 		  == spec)
19324 	      || fndecl == NULL_TREE);
19325 
19326   if (spec != NULL_TREE)
19327     {
19328       if (FNDECL_HAS_ACCESS_ERRORS (spec))
19329 	{
19330 	  if (complain & tf_error)
19331 	    recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
19332 	  return error_mark_node;
19333 	}
19334       return spec;
19335     }
19336 
19337   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
19338 			       complain))
19339     return error_mark_node;
19340 
19341   /* We are building a FUNCTION_DECL, during which the access of its
19342      parameters and return types have to be checked.  However this
19343      FUNCTION_DECL which is the desired context for access checking
19344      is not built yet.  We solve this chicken-and-egg problem by
19345      deferring all checks until we have the FUNCTION_DECL.  */
19346   push_deferring_access_checks (dk_deferred);
19347 
19348   /* Instantiation of the function happens in the context of the function
19349      template, not the context of the overload resolution we're doing.  */
19350   push_to_top_level ();
19351   /* If there are dependent arguments, e.g. because we're doing partial
19352      ordering, make sure processing_template_decl stays set.  */
19353   if (uses_template_parms (targ_ptr))
19354     ++processing_template_decl;
19355   if (DECL_CLASS_SCOPE_P (gen_tmpl))
19356     {
19357       tree ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
19358 				   complain, gen_tmpl, true);
19359       push_nested_class (ctx);
19360     }
19361 
19362   tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
19363 
19364   fndecl = NULL_TREE;
19365   if (VAR_P (pattern))
19366     {
19367       /* We need to determine if we're using a partial or explicit
19368 	 specialization now, because the type of the variable could be
19369 	 different.  */
19370       tree tid = lookup_template_variable (gen_tmpl, targ_ptr);
19371       tree elt = most_specialized_partial_spec (tid, complain);
19372       if (elt == error_mark_node)
19373 	pattern = error_mark_node;
19374       else if (elt)
19375 	{
19376 	  tree partial_tmpl = TREE_VALUE (elt);
19377 	  tree partial_args = TREE_PURPOSE (elt);
19378 	  tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
19379 	  fndecl = tsubst (partial_pat, partial_args, complain, gen_tmpl);
19380 	}
19381     }
19382 
19383   /* Substitute template parameters to obtain the specialization.  */
19384   if (fndecl == NULL_TREE)
19385     fndecl = tsubst (pattern, targ_ptr, complain, gen_tmpl);
19386   if (DECL_CLASS_SCOPE_P (gen_tmpl))
19387     pop_nested_class ();
19388   pop_from_top_level ();
19389 
19390   if (fndecl == error_mark_node)
19391     {
19392       pop_deferring_access_checks ();
19393       return error_mark_node;
19394     }
19395 
19396   /* The DECL_TI_TEMPLATE should always be the immediate parent
19397      template, not the most general template.  */
19398   DECL_TI_TEMPLATE (fndecl) = tmpl;
19399   DECL_TI_ARGS (fndecl) = targ_ptr;
19400 
19401   /* Now we know the specialization, compute access previously
19402      deferred.  Do no access control for inheriting constructors,
19403      as we already checked access for the inherited constructor.  */
19404   if (!(flag_new_inheriting_ctors
19405 	&& DECL_INHERITED_CTOR (fndecl)))
19406     {
19407       push_access_scope (fndecl);
19408       if (!perform_deferred_access_checks (complain))
19409 	access_ok = false;
19410       pop_access_scope (fndecl);
19411     }
19412   pop_deferring_access_checks ();
19413 
19414   /* If we've just instantiated the main entry point for a function,
19415      instantiate all the alternate entry points as well.  We do this
19416      by cloning the instantiation of the main entry point, not by
19417      instantiating the template clones.  */
19418   if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
19419     clone_function_decl (fndecl, /*update_methods=*/false);
19420 
19421   if (!access_ok)
19422     {
19423       if (!(complain & tf_error))
19424 	{
19425 	  /* Remember to reinstantiate when we're out of SFINAE so the user
19426 	     can see the errors.  */
19427 	  FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
19428 	}
19429       return error_mark_node;
19430     }
19431   return fndecl;
19432 }
19433 
19434 /* Wrapper for instantiate_template_1.  */
19435 
19436 tree
instantiate_template(tree tmpl,tree orig_args,tsubst_flags_t complain)19437 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
19438 {
19439   tree ret;
19440   timevar_push (TV_TEMPLATE_INST);
19441   ret = instantiate_template_1 (tmpl, orig_args,  complain);
19442   timevar_pop (TV_TEMPLATE_INST);
19443   return ret;
19444 }
19445 
19446 /* Instantiate the alias template TMPL with ARGS.  Also push a template
19447    instantiation level, which instantiate_template doesn't do because
19448    functions and variables have sufficient context established by the
19449    callers.  */
19450 
19451 static tree
instantiate_alias_template(tree tmpl,tree args,tsubst_flags_t complain)19452 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
19453 {
19454   if (tmpl == error_mark_node || args == error_mark_node)
19455     return error_mark_node;
19456   if (!push_tinst_level (tmpl, args))
19457     return error_mark_node;
19458 
19459   args =
19460     coerce_innermost_template_parms (DECL_TEMPLATE_PARMS (tmpl),
19461 				     args, tmpl, complain,
19462 				     /*require_all_args=*/true,
19463 				     /*use_default_args=*/true);
19464 
19465   tree r = instantiate_template (tmpl, args, complain);
19466   pop_tinst_level ();
19467 
19468   return r;
19469 }
19470 
19471 /* PARM is a template parameter pack for FN.  Returns true iff
19472    PARM is used in a deducible way in the argument list of FN.  */
19473 
19474 static bool
pack_deducible_p(tree parm,tree fn)19475 pack_deducible_p (tree parm, tree fn)
19476 {
19477   tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
19478   for (; t; t = TREE_CHAIN (t))
19479     {
19480       tree type = TREE_VALUE (t);
19481       tree packs;
19482       if (!PACK_EXPANSION_P (type))
19483 	continue;
19484       for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
19485 	   packs; packs = TREE_CHAIN (packs))
19486 	if (template_args_equal (TREE_VALUE (packs), parm))
19487 	  {
19488 	    /* The template parameter pack is used in a function parameter
19489 	       pack.  If this is the end of the parameter list, the
19490 	       template parameter pack is deducible.  */
19491 	    if (TREE_CHAIN (t) == void_list_node)
19492 	      return true;
19493 	    else
19494 	      /* Otherwise, not.  Well, it could be deduced from
19495 		 a non-pack parameter, but doing so would end up with
19496 		 a deduction mismatch, so don't bother.  */
19497 	      return false;
19498 	  }
19499     }
19500   /* The template parameter pack isn't used in any function parameter
19501      packs, but it might be used deeper, e.g. tuple<Args...>.  */
19502   return true;
19503 }
19504 
19505 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
19506    NARGS elements of the arguments that are being used when calling
19507    it.  TARGS is a vector into which the deduced template arguments
19508    are placed.
19509 
19510    Returns either a FUNCTION_DECL for the matching specialization of FN or
19511    NULL_TREE if no suitable specialization can be found.  If EXPLAIN_P is
19512    true, diagnostics will be printed to explain why it failed.
19513 
19514    If FN is a conversion operator, or we are trying to produce a specific
19515    specialization, RETURN_TYPE is the return type desired.
19516 
19517    The EXPLICIT_TARGS are explicit template arguments provided via a
19518    template-id.
19519 
19520    The parameter STRICT is one of:
19521 
19522    DEDUCE_CALL:
19523      We are deducing arguments for a function call, as in
19524      [temp.deduct.call].  If RETURN_TYPE is non-null, we are
19525      deducing arguments for a call to the result of a conversion
19526      function template, as in [over.call.object].
19527 
19528    DEDUCE_CONV:
19529      We are deducing arguments for a conversion function, as in
19530      [temp.deduct.conv].
19531 
19532    DEDUCE_EXACT:
19533      We are deducing arguments when doing an explicit instantiation
19534      as in [temp.explicit], when determining an explicit specialization
19535      as in [temp.expl.spec], or when taking the address of a function
19536      template, as in [temp.deduct.funcaddr].  */
19537 
19538 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,bool explain_p,bool decltype_p)19539 fn_type_unification (tree fn,
19540 		     tree explicit_targs,
19541 		     tree targs,
19542 		     const tree *args,
19543 		     unsigned int nargs,
19544 		     tree return_type,
19545 		     unification_kind_t strict,
19546 		     int flags,
19547 		     bool explain_p,
19548 		     bool decltype_p)
19549 {
19550   tree parms;
19551   tree fntype;
19552   tree decl = NULL_TREE;
19553   tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
19554   bool ok;
19555   static int deduction_depth;
19556 
19557   tree orig_fn = fn;
19558   if (flag_new_inheriting_ctors)
19559     fn = strip_inheriting_ctors (fn);
19560 
19561   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
19562   tree r = error_mark_node;
19563 
19564   tree full_targs = targs;
19565   if (TMPL_ARGS_DEPTH (targs)
19566       < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (fn)))
19567     full_targs = (add_outermost_template_args
19568 		  (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (fn)),
19569 		   targs));
19570 
19571   if (decltype_p)
19572     complain |= tf_decltype;
19573 
19574   /* In C++0x, it's possible to have a function template whose type depends
19575      on itself recursively.  This is most obvious with decltype, but can also
19576      occur with enumeration scope (c++/48969).  So we need to catch infinite
19577      recursion and reject the substitution at deduction time; this function
19578      will return error_mark_node for any repeated substitution.
19579 
19580      This also catches excessive recursion such as when f<N> depends on
19581      f<N-1> across all integers, and returns error_mark_node for all the
19582      substitutions back up to the initial one.
19583 
19584      This is, of course, not reentrant.  */
19585   if (excessive_deduction_depth)
19586     return error_mark_node;
19587   ++deduction_depth;
19588 
19589   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
19590 
19591   fntype = TREE_TYPE (fn);
19592   if (explicit_targs)
19593     {
19594       /* [temp.deduct]
19595 
19596 	 The specified template arguments must match the template
19597 	 parameters in kind (i.e., type, nontype, template), and there
19598 	 must not be more arguments than there are parameters;
19599 	 otherwise type deduction fails.
19600 
19601 	 Nontype arguments must match the types of the corresponding
19602 	 nontype template parameters, or must be convertible to the
19603 	 types of the corresponding nontype parameters as specified in
19604 	 _temp.arg.nontype_, otherwise type deduction fails.
19605 
19606 	 All references in the function type of the function template
19607 	 to the corresponding template parameters are replaced by the
19608 	 specified template argument values.  If a substitution in a
19609 	 template parameter or in the function type of the function
19610 	 template results in an invalid type, type deduction fails.  */
19611       int i, len = TREE_VEC_LENGTH (tparms);
19612       location_t loc = input_location;
19613       bool incomplete = false;
19614 
19615       if (explicit_targs == error_mark_node)
19616 	goto fail;
19617 
19618       if (TMPL_ARGS_DEPTH (explicit_targs)
19619 	  < TMPL_ARGS_DEPTH (full_targs))
19620 	explicit_targs = add_outermost_template_args (full_targs,
19621 						      explicit_targs);
19622 
19623       /* Adjust any explicit template arguments before entering the
19624 	 substitution context.  */
19625       explicit_targs
19626 	= (coerce_template_parms (tparms, explicit_targs, NULL_TREE,
19627 				  complain,
19628 				  /*require_all_args=*/false,
19629 				  /*use_default_args=*/false));
19630       if (explicit_targs == error_mark_node)
19631 	goto fail;
19632 
19633       /* Substitute the explicit args into the function type.  This is
19634 	 necessary so that, for instance, explicitly declared function
19635 	 arguments can match null pointed constants.  If we were given
19636 	 an incomplete set of explicit args, we must not do semantic
19637 	 processing during substitution as we could create partial
19638 	 instantiations.  */
19639       for (i = 0; i < len; i++)
19640         {
19641           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
19642           bool parameter_pack = false;
19643 	  tree targ = TREE_VEC_ELT (explicit_targs, i);
19644 
19645           /* Dig out the actual parm.  */
19646           if (TREE_CODE (parm) == TYPE_DECL
19647               || TREE_CODE (parm) == TEMPLATE_DECL)
19648             {
19649               parm = TREE_TYPE (parm);
19650               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
19651             }
19652           else if (TREE_CODE (parm) == PARM_DECL)
19653             {
19654               parm = DECL_INITIAL (parm);
19655               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
19656             }
19657 
19658 	  if (!parameter_pack && targ == NULL_TREE)
19659 	    /* No explicit argument for this template parameter.  */
19660 	    incomplete = true;
19661 
19662           if (parameter_pack && pack_deducible_p (parm, fn))
19663             {
19664               /* Mark the argument pack as "incomplete". We could
19665                  still deduce more arguments during unification.
19666 	         We remove this mark in type_unification_real.  */
19667               if (targ)
19668                 {
19669                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
19670                   ARGUMENT_PACK_EXPLICIT_ARGS (targ)
19671                     = ARGUMENT_PACK_ARGS (targ);
19672                 }
19673 
19674               /* We have some incomplete argument packs.  */
19675               incomplete = true;
19676             }
19677         }
19678 
19679       if (!push_tinst_level (fn, explicit_targs))
19680 	{
19681 	  excessive_deduction_depth = true;
19682 	  goto fail;
19683 	}
19684       processing_template_decl += incomplete;
19685       input_location = DECL_SOURCE_LOCATION (fn);
19686       /* Ignore any access checks; we'll see them again in
19687 	 instantiate_template and they might have the wrong
19688 	 access path at this point.  */
19689       push_deferring_access_checks (dk_deferred);
19690       fntype = tsubst (TREE_TYPE (fn), explicit_targs,
19691 		       complain | tf_partial | tf_fndecl_type, NULL_TREE);
19692       pop_deferring_access_checks ();
19693       input_location = loc;
19694       processing_template_decl -= incomplete;
19695       pop_tinst_level ();
19696 
19697       if (fntype == error_mark_node)
19698 	goto fail;
19699 
19700       /* Place the explicitly specified arguments in TARGS.  */
19701       explicit_targs = INNERMOST_TEMPLATE_ARGS (explicit_targs);
19702       for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
19703 	TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
19704     }
19705 
19706   /* Never do unification on the 'this' parameter.  */
19707   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
19708 
19709   if (return_type && strict == DEDUCE_CALL)
19710     {
19711       /* We're deducing for a call to the result of a template conversion
19712          function.  The parms we really want are in return_type.  */
19713       if (POINTER_TYPE_P (return_type))
19714 	return_type = TREE_TYPE (return_type);
19715       parms = TYPE_ARG_TYPES (return_type);
19716     }
19717   else if (return_type)
19718     {
19719       tree *new_args;
19720 
19721       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
19722       new_args = XALLOCAVEC (tree, nargs + 1);
19723       new_args[0] = return_type;
19724       memcpy (new_args + 1, args, nargs * sizeof (tree));
19725       args = new_args;
19726       ++nargs;
19727     }
19728 
19729   /* We allow incomplete unification without an error message here
19730      because the standard doesn't seem to explicitly prohibit it.  Our
19731      callers must be ready to deal with unification failures in any
19732      event.  */
19733 
19734   /* If we aren't explaining yet, push tinst context so we can see where
19735      any errors (e.g. from class instantiations triggered by instantiation
19736      of default template arguments) come from.  If we are explaining, this
19737      context is redundant.  */
19738   if (!explain_p && !push_tinst_level (fn, targs))
19739     {
19740       excessive_deduction_depth = true;
19741       goto fail;
19742     }
19743 
19744   /* type_unification_real will pass back any access checks from default
19745      template argument substitution.  */
19746   vec<deferred_access_check, va_gc> *checks;
19747   checks = NULL;
19748 
19749   ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
19750 			       full_targs, parms, args, nargs, /*subr=*/0,
19751 			       strict, flags, &checks, explain_p);
19752   if (!explain_p)
19753     pop_tinst_level ();
19754   if (!ok)
19755     goto fail;
19756 
19757   /* Now that we have bindings for all of the template arguments,
19758      ensure that the arguments deduced for the template template
19759      parameters have compatible template parameter lists.  We cannot
19760      check this property before we have deduced all template
19761      arguments, because the template parameter types of a template
19762      template parameter might depend on prior template parameters
19763      deduced after the template template parameter.  The following
19764      ill-formed example illustrates this issue:
19765 
19766        template<typename T, template<T> class C> void f(C<5>, T);
19767 
19768        template<int N> struct X {};
19769 
19770        void g() {
19771          f(X<5>(), 5l); // error: template argument deduction fails
19772        }
19773 
19774      The template parameter list of 'C' depends on the template type
19775      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
19776      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
19777      time that we deduce 'C'.  */
19778   if (!template_template_parm_bindings_ok_p
19779            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
19780     {
19781       unify_inconsistent_template_template_parameters (explain_p);
19782       goto fail;
19783     }
19784 
19785   /* All is well so far.  Now, check:
19786 
19787      [temp.deduct]
19788 
19789      When all template arguments have been deduced, all uses of
19790      template parameters in nondeduced contexts are replaced with
19791      the corresponding deduced argument values.  If the
19792      substitution results in an invalid type, as described above,
19793      type deduction fails.  */
19794   if (!push_tinst_level (fn, targs))
19795     {
19796       excessive_deduction_depth = true;
19797       goto fail;
19798     }
19799 
19800   /* Also collect access checks from the instantiation.  */
19801   reopen_deferring_access_checks (checks);
19802 
19803   decl = instantiate_template (fn, targs, complain);
19804 
19805   checks = get_deferred_access_checks ();
19806   pop_deferring_access_checks ();
19807 
19808   pop_tinst_level ();
19809 
19810   if (decl == error_mark_node)
19811     goto fail;
19812 
19813   /* Now perform any access checks encountered during substitution.  */
19814   push_access_scope (decl);
19815   ok = perform_access_checks (checks, complain);
19816   pop_access_scope (decl);
19817   if (!ok)
19818     goto fail;
19819 
19820   /* If we're looking for an exact match, check that what we got
19821      is indeed an exact match.  It might not be if some template
19822      parameters are used in non-deduced contexts.  But don't check
19823      for an exact match if we have dependent template arguments;
19824      in that case we're doing partial ordering, and we already know
19825      that we have two candidates that will provide the actual type.  */
19826   if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
19827     {
19828       tree substed = TREE_TYPE (decl);
19829       unsigned int i;
19830 
19831       tree sarg
19832 	= skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
19833       if (return_type)
19834 	sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
19835       for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
19836 	if (!same_type_p (args[i], TREE_VALUE (sarg)))
19837 	  {
19838 	    unify_type_mismatch (explain_p, args[i],
19839 				 TREE_VALUE (sarg));
19840 	    goto fail;
19841 	  }
19842     }
19843 
19844   /* After doing deduction with the inherited constructor, actually return an
19845      instantiation of the inheriting constructor.  */
19846   if (orig_fn != fn)
19847     decl = instantiate_template (orig_fn, targs, complain);
19848 
19849   r = decl;
19850 
19851  fail:
19852   --deduction_depth;
19853   if (excessive_deduction_depth)
19854     {
19855       if (deduction_depth == 0)
19856 	/* Reset once we're all the way out.  */
19857 	excessive_deduction_depth = false;
19858     }
19859 
19860   return r;
19861 }
19862 
19863 /* Adjust types before performing type deduction, as described in
19864    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
19865    sections are symmetric.  PARM is the type of a function parameter
19866    or the return type of the conversion function.  ARG is the type of
19867    the argument passed to the call, or the type of the value
19868    initialized with the result of the conversion function.
19869    ARG_EXPR is the original argument expression, which may be null.  */
19870 
19871 static int
maybe_adjust_types_for_deduction(unification_kind_t strict,tree * parm,tree * arg,tree arg_expr)19872 maybe_adjust_types_for_deduction (unification_kind_t strict,
19873 				  tree* parm,
19874 				  tree* arg,
19875 				  tree arg_expr)
19876 {
19877   int result = 0;
19878 
19879   switch (strict)
19880     {
19881     case DEDUCE_CALL:
19882       break;
19883 
19884     case DEDUCE_CONV:
19885       /* Swap PARM and ARG throughout the remainder of this
19886 	 function; the handling is precisely symmetric since PARM
19887 	 will initialize ARG rather than vice versa.  */
19888       std::swap (parm, arg);
19889       break;
19890 
19891     case DEDUCE_EXACT:
19892       /* Core issue #873: Do the DR606 thing (see below) for these cases,
19893 	 too, but here handle it by stripping the reference from PARM
19894 	 rather than by adding it to ARG.  */
19895       if (TREE_CODE (*parm) == REFERENCE_TYPE
19896 	  && TYPE_REF_IS_RVALUE (*parm)
19897 	  && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
19898 	  && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
19899 	  && TREE_CODE (*arg) == REFERENCE_TYPE
19900 	  && !TYPE_REF_IS_RVALUE (*arg))
19901 	*parm = TREE_TYPE (*parm);
19902       /* Nothing else to do in this case.  */
19903       return 0;
19904 
19905     default:
19906       gcc_unreachable ();
19907     }
19908 
19909   if (TREE_CODE (*parm) != REFERENCE_TYPE)
19910     {
19911       /* [temp.deduct.call]
19912 
19913 	 If P is not a reference type:
19914 
19915 	 --If A is an array type, the pointer type produced by the
19916 	 array-to-pointer standard conversion (_conv.array_) is
19917 	 used in place of A for type deduction; otherwise,
19918 
19919 	 --If A is a function type, the pointer type produced by
19920 	 the function-to-pointer standard conversion
19921 	 (_conv.func_) is used in place of A for type deduction;
19922 	 otherwise,
19923 
19924 	 --If A is a cv-qualified type, the top level
19925 	 cv-qualifiers of A's type are ignored for type
19926 	 deduction.  */
19927       if (TREE_CODE (*arg) == ARRAY_TYPE)
19928 	*arg = build_pointer_type (TREE_TYPE (*arg));
19929       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
19930 	*arg = build_pointer_type (*arg);
19931       else
19932 	*arg = TYPE_MAIN_VARIANT (*arg);
19933     }
19934 
19935   /* [14.8.2.1/3 temp.deduct.call], "A forwarding reference is an rvalue
19936      reference to a cv-unqualified template parameter that does not represent a
19937      template parameter of a class template (during class template argument
19938      deduction (13.3.1.8)). If P is a forwarding reference and the argument is
19939      an lvalue, the type "lvalue reference to A" is used in place of A for type
19940      deduction. */
19941   if (TREE_CODE (*parm) == REFERENCE_TYPE
19942       && TYPE_REF_IS_RVALUE (*parm)
19943       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
19944       && !TEMPLATE_TYPE_PARM_FOR_CLASS (TREE_TYPE (*parm))
19945       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
19946       && (arg_expr ? lvalue_p (arg_expr)
19947 	  /* try_one_overload doesn't provide an arg_expr, but
19948 	     functions are always lvalues.  */
19949 	  : TREE_CODE (*arg) == FUNCTION_TYPE))
19950     *arg = build_reference_type (*arg);
19951 
19952   /* [temp.deduct.call]
19953 
19954      If P is a cv-qualified type, the top level cv-qualifiers
19955      of P's type are ignored for type deduction.  If P is a
19956      reference type, the type referred to by P is used for
19957      type deduction.  */
19958   *parm = TYPE_MAIN_VARIANT (*parm);
19959   if (TREE_CODE (*parm) == REFERENCE_TYPE)
19960     {
19961       *parm = TREE_TYPE (*parm);
19962       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
19963     }
19964 
19965   /* DR 322. For conversion deduction, remove a reference type on parm
19966      too (which has been swapped into ARG).  */
19967   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
19968     *arg = TREE_TYPE (*arg);
19969 
19970   return result;
19971 }
19972 
19973 /* Subroutine of unify_one_argument.  PARM is a function parameter of a
19974    template which does contain any deducible template parameters; check if
19975    ARG is a suitable match for it.  STRICT, FLAGS and EXPLAIN_P are as in
19976    unify_one_argument.  */
19977 
19978 static int
check_non_deducible_conversion(tree parm,tree arg,int strict,int flags,bool explain_p)19979 check_non_deducible_conversion (tree parm, tree arg, int strict,
19980 				int flags, bool explain_p)
19981 {
19982   tree type;
19983 
19984   if (!TYPE_P (arg))
19985     type = TREE_TYPE (arg);
19986   else
19987     type = arg;
19988 
19989   if (same_type_p (parm, type))
19990     return unify_success (explain_p);
19991 
19992   if (strict == DEDUCE_CONV)
19993     {
19994       if (can_convert_arg (type, parm, NULL_TREE, flags,
19995 			   explain_p ? tf_warning_or_error : tf_none))
19996 	return unify_success (explain_p);
19997     }
19998   else if (strict != DEDUCE_EXACT)
19999     {
20000       if (can_convert_arg (parm, type,
20001 			   TYPE_P (arg) ? NULL_TREE : arg,
20002 			   flags, explain_p ? tf_warning_or_error : tf_none))
20003 	return unify_success (explain_p);
20004     }
20005 
20006   if (strict == DEDUCE_EXACT)
20007     return unify_type_mismatch (explain_p, parm, arg);
20008   else
20009     return unify_arg_conversion (explain_p, parm, type, arg);
20010 }
20011 
20012 static bool uses_deducible_template_parms (tree type);
20013 
20014 /* Returns true iff the expression EXPR is one from which a template
20015    argument can be deduced.  In other words, if it's an undecorated
20016    use of a template non-type parameter.  */
20017 
20018 static bool
deducible_expression(tree expr)20019 deducible_expression (tree expr)
20020 {
20021   /* Strip implicit conversions.  */
20022   while (CONVERT_EXPR_P (expr))
20023     expr = TREE_OPERAND (expr, 0);
20024   return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
20025 }
20026 
20027 /* Returns true iff the array domain DOMAIN uses a template parameter in a
20028    deducible way; that is, if it has a max value of <PARM> - 1.  */
20029 
20030 static bool
deducible_array_bound(tree domain)20031 deducible_array_bound (tree domain)
20032 {
20033   if (domain == NULL_TREE)
20034     return false;
20035 
20036   tree max = TYPE_MAX_VALUE (domain);
20037   if (TREE_CODE (max) != MINUS_EXPR)
20038     return false;
20039 
20040   return deducible_expression (TREE_OPERAND (max, 0));
20041 }
20042 
20043 /* Returns true iff the template arguments ARGS use a template parameter
20044    in a deducible way.  */
20045 
20046 static bool
deducible_template_args(tree args)20047 deducible_template_args (tree args)
20048 {
20049   for (int i = 0; i < TREE_VEC_LENGTH (args); ++i)
20050     {
20051       bool deducible;
20052       tree elt = TREE_VEC_ELT (args, i);
20053       if (ARGUMENT_PACK_P (elt))
20054 	deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
20055       else
20056 	{
20057 	  if (PACK_EXPANSION_P (elt))
20058 	    elt = PACK_EXPANSION_PATTERN (elt);
20059 	  if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
20060 	    deducible = true;
20061 	  else if (TYPE_P (elt))
20062 	    deducible = uses_deducible_template_parms (elt);
20063 	  else
20064 	    deducible = deducible_expression (elt);
20065 	}
20066       if (deducible)
20067 	return true;
20068     }
20069   return false;
20070 }
20071 
20072 /* Returns true iff TYPE contains any deducible references to template
20073    parameters, as per 14.8.2.5.  */
20074 
20075 static bool
uses_deducible_template_parms(tree type)20076 uses_deducible_template_parms (tree type)
20077 {
20078   if (PACK_EXPANSION_P (type))
20079     type = PACK_EXPANSION_PATTERN (type);
20080 
20081   /* T
20082      cv-list T
20083      TT<T>
20084      TT<i>
20085      TT<> */
20086   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
20087       || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
20088     return true;
20089 
20090   /* T*
20091      T&
20092      T&&  */
20093   if (POINTER_TYPE_P (type))
20094     return uses_deducible_template_parms (TREE_TYPE (type));
20095 
20096   /* T[integer-constant ]
20097      type [i]  */
20098   if (TREE_CODE (type) == ARRAY_TYPE)
20099     return (uses_deducible_template_parms (TREE_TYPE (type))
20100 	    || deducible_array_bound (TYPE_DOMAIN (type)));
20101 
20102   /* T type ::*
20103      type T::*
20104      T T::*
20105      T (type ::*)()
20106      type (T::*)()
20107      type (type ::*)(T)
20108      type (T::*)(T)
20109      T (type ::*)(T)
20110      T (T::*)()
20111      T (T::*)(T) */
20112   if (TYPE_PTRMEM_P (type))
20113     return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
20114 	    || (uses_deducible_template_parms
20115 		(TYPE_PTRMEM_POINTED_TO_TYPE (type))));
20116 
20117   /* template-name <T> (where template-name refers to a class template)
20118      template-name <i> (where template-name refers to a class template) */
20119   if (CLASS_TYPE_P (type)
20120       && CLASSTYPE_TEMPLATE_INFO (type)
20121       && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
20122     return deducible_template_args (INNERMOST_TEMPLATE_ARGS
20123 				    (CLASSTYPE_TI_ARGS (type)));
20124 
20125   /* type (T)
20126      T()
20127      T(T)  */
20128   if (TREE_CODE (type) == FUNCTION_TYPE
20129       || TREE_CODE (type) == METHOD_TYPE)
20130     {
20131       if (uses_deducible_template_parms (TREE_TYPE (type)))
20132 	return true;
20133       tree parm = TYPE_ARG_TYPES (type);
20134       if (TREE_CODE (type) == METHOD_TYPE)
20135 	parm = TREE_CHAIN (parm);
20136       for (; parm; parm = TREE_CHAIN (parm))
20137 	if (uses_deducible_template_parms (TREE_VALUE (parm)))
20138 	  return true;
20139     }
20140 
20141   return false;
20142 }
20143 
20144 /* Subroutine of type_unification_real and unify_pack_expansion to
20145    handle unification of a single P/A pair.  Parameters are as
20146    for those functions.  */
20147 
20148 static int
unify_one_argument(tree tparms,tree targs,tree parm,tree arg,int subr,unification_kind_t strict,bool explain_p)20149 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
20150 		    int subr, unification_kind_t strict,
20151 		    bool explain_p)
20152 {
20153   tree arg_expr = NULL_TREE;
20154   int arg_strict;
20155 
20156   if (arg == error_mark_node || parm == error_mark_node)
20157     return unify_invalid (explain_p);
20158   if (arg == unknown_type_node)
20159     /* We can't deduce anything from this, but we might get all the
20160        template args from other function args.  */
20161     return unify_success (explain_p);
20162 
20163   /* Implicit conversions (Clause 4) will be performed on a function
20164      argument to convert it to the type of the corresponding function
20165      parameter if the parameter type contains no template-parameters that
20166      participate in template argument deduction.  */
20167   if (strict != DEDUCE_EXACT
20168       && TYPE_P (parm) && !uses_deducible_template_parms (parm))
20169     /* For function parameters with no deducible template parameters,
20170        just return.  We'll check non-dependent conversions later.  */
20171     return unify_success (explain_p);
20172 
20173   switch (strict)
20174     {
20175     case DEDUCE_CALL:
20176       arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
20177 		    | UNIFY_ALLOW_MORE_CV_QUAL
20178 		    | UNIFY_ALLOW_DERIVED);
20179       break;
20180 
20181     case DEDUCE_CONV:
20182       arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
20183       break;
20184 
20185     case DEDUCE_EXACT:
20186       arg_strict = UNIFY_ALLOW_NONE;
20187       break;
20188 
20189     default:
20190       gcc_unreachable ();
20191     }
20192 
20193   /* We only do these transformations if this is the top-level
20194      parameter_type_list in a call or declaration matching; in other
20195      situations (nested function declarators, template argument lists) we
20196      won't be comparing a type to an expression, and we don't do any type
20197      adjustments.  */
20198   if (!subr)
20199     {
20200       if (!TYPE_P (arg))
20201 	{
20202 	  gcc_assert (TREE_TYPE (arg) != NULL_TREE);
20203 	  if (type_unknown_p (arg))
20204 	    {
20205 	      /* [temp.deduct.type] A template-argument can be
20206 		 deduced from a pointer to function or pointer
20207 		 to member function argument if the set of
20208 		 overloaded functions does not contain function
20209 		 templates and at most one of a set of
20210 		 overloaded functions provides a unique
20211 		 match.  */
20212 	      resolve_overloaded_unification (tparms, targs, parm,
20213 					      arg, strict,
20214 					      arg_strict, explain_p);
20215 	      /* If a unique match was not found, this is a
20216 	         non-deduced context, so we still succeed. */
20217 	      return unify_success (explain_p);
20218 	    }
20219 
20220 	  arg_expr = arg;
20221 	  arg = unlowered_expr_type (arg);
20222 	  if (arg == error_mark_node)
20223 	    return unify_invalid (explain_p);
20224 	}
20225 
20226       arg_strict |=
20227 	maybe_adjust_types_for_deduction (strict, &parm, &arg, arg_expr);
20228     }
20229   else
20230     if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
20231 	!= (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
20232       return unify_template_argument_mismatch (explain_p, parm, arg);
20233 
20234   /* For deduction from an init-list we need the actual list.  */
20235   if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
20236     arg = arg_expr;
20237   return unify (tparms, targs, parm, arg, arg_strict, explain_p);
20238 }
20239 
20240 /* for_each_template_parm callback that always returns 0.  */
20241 
20242 static int
zero_r(tree,void *)20243 zero_r (tree, void *)
20244 {
20245   return 0;
20246 }
20247 
20248 /* for_each_template_parm any_fn callback to handle deduction of a template
20249    type argument from the type of an array bound.  */
20250 
20251 static int
array_deduction_r(tree t,void * data)20252 array_deduction_r (tree t, void *data)
20253 {
20254   tree_pair_p d = (tree_pair_p)data;
20255   tree &tparms = d->purpose;
20256   tree &targs = d->value;
20257 
20258   if (TREE_CODE (t) == ARRAY_TYPE)
20259     if (tree dom = TYPE_DOMAIN (t))
20260       if (tree max = TYPE_MAX_VALUE (dom))
20261 	{
20262 	  if (TREE_CODE (max) == MINUS_EXPR)
20263 	    max = TREE_OPERAND (max, 0);
20264 	  if (TREE_CODE (max) == TEMPLATE_PARM_INDEX)
20265 	    unify (tparms, targs, TREE_TYPE (max), size_type_node,
20266 		   UNIFY_ALLOW_NONE, /*explain*/false);
20267 	}
20268 
20269   /* Keep walking.  */
20270   return 0;
20271 }
20272 
20273 /* Try to deduce any not-yet-deduced template type arguments from the type of
20274    an array bound.  This is handled separately from unify because 14.8.2.5 says
20275    "The type of a type parameter is only deduced from an array bound if it is
20276    not otherwise deduced."  */
20277 
20278 static void
try_array_deduction(tree tparms,tree targs,tree parm)20279 try_array_deduction (tree tparms, tree targs, tree parm)
20280 {
20281   tree_pair_s data = { tparms, targs };
20282   hash_set<tree> visited;
20283   for_each_template_parm (parm, zero_r, &data, &visited,
20284 			  /*nondeduced*/false, array_deduction_r);
20285 }
20286 
20287 /* Returns how many levels of { } INIT contains.  */
20288 
20289 static int
braced_init_depth(tree init)20290 braced_init_depth (tree init)
20291 {
20292   if (!init || !BRACE_ENCLOSED_INITIALIZER_P (init))
20293     return 0;
20294   unsigned i; tree val;
20295   unsigned max = 0;
20296   FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (init), i, val)
20297     {
20298       unsigned elt_d = braced_init_depth (val);
20299       if (elt_d > max)
20300 	max = elt_d;
20301     }
20302   return max + 1;
20303 }
20304 
20305 /* Most parms like fn_type_unification.
20306 
20307    If SUBR is 1, we're being called recursively (to unify the
20308    arguments of a function or method parameter of a function
20309    template).
20310 
20311    CHECKS is a pointer to a vector of access checks encountered while
20312    substituting default template arguments.  */
20313 
20314 static int
type_unification_real(tree tparms,tree full_targs,tree xparms,const tree * xargs,unsigned int xnargs,int subr,unification_kind_t strict,int flags,vec<deferred_access_check,va_gc> ** checks,bool explain_p)20315 type_unification_real (tree tparms,
20316 		       tree full_targs,
20317 		       tree xparms,
20318 		       const tree *xargs,
20319 		       unsigned int xnargs,
20320 		       int subr,
20321 		       unification_kind_t strict,
20322 		       int flags,
20323 		       vec<deferred_access_check, va_gc> **checks,
20324 		       bool explain_p)
20325 {
20326   tree parm, arg;
20327   int i;
20328   int ntparms = TREE_VEC_LENGTH (tparms);
20329   int saw_undeduced = 0;
20330   tree parms;
20331   const tree *args;
20332   unsigned int nargs;
20333   unsigned int ia;
20334 
20335   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
20336   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
20337   gcc_assert (ntparms > 0);
20338 
20339   tree targs = INNERMOST_TEMPLATE_ARGS (full_targs);
20340 
20341   /* Reset the number of non-defaulted template arguments contained
20342      in TARGS.  */
20343   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
20344 
20345  again:
20346   parms = xparms;
20347   args = xargs;
20348   nargs = xnargs;
20349 
20350   ia = 0;
20351   while (parms && parms != void_list_node
20352 	 && ia < nargs)
20353     {
20354       parm = TREE_VALUE (parms);
20355 
20356       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
20357 	  && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
20358 	/* For a function parameter pack that occurs at the end of the
20359 	   parameter-declaration-list, the type A of each remaining
20360 	   argument of the call is compared with the type P of the
20361 	   declarator-id of the function parameter pack.  */
20362 	break;
20363 
20364       parms = TREE_CHAIN (parms);
20365 
20366       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
20367 	/* For a function parameter pack that does not occur at the
20368 	   end of the parameter-declaration-list, the type of the
20369 	   parameter pack is a non-deduced context.  */
20370 	continue;
20371 
20372       arg = args[ia];
20373       ++ia;
20374 
20375       if (unify_one_argument (tparms, full_targs, parm, arg, subr, strict,
20376 			      explain_p))
20377 	return 1;
20378     }
20379 
20380   if (parms
20381       && parms != void_list_node
20382       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
20383     {
20384       /* Unify the remaining arguments with the pack expansion type.  */
20385       tree argvec;
20386       tree parmvec = make_tree_vec (1);
20387 
20388       /* Allocate a TREE_VEC and copy in all of the arguments */
20389       argvec = make_tree_vec (nargs - ia);
20390       for (i = 0; ia < nargs; ++ia, ++i)
20391 	TREE_VEC_ELT (argvec, i) = args[ia];
20392 
20393       /* Copy the parameter into parmvec.  */
20394       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
20395       if (unify_pack_expansion (tparms, full_targs, parmvec, argvec, strict,
20396                                 /*subr=*/subr, explain_p))
20397         return 1;
20398 
20399       /* Advance to the end of the list of parameters.  */
20400       parms = TREE_CHAIN (parms);
20401     }
20402 
20403   /* Fail if we've reached the end of the parm list, and more args
20404      are present, and the parm list isn't variadic.  */
20405   if (ia < nargs && parms == void_list_node)
20406     return unify_too_many_arguments (explain_p, nargs, ia);
20407   /* Fail if parms are left and they don't have default values and
20408      they aren't all deduced as empty packs (c++/57397).  This is
20409      consistent with sufficient_parms_p.  */
20410   if (parms && parms != void_list_node
20411       && TREE_PURPOSE (parms) == NULL_TREE)
20412     {
20413       unsigned int count = nargs;
20414       tree p = parms;
20415       bool type_pack_p;
20416       do
20417 	{
20418 	  type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
20419 	  if (!type_pack_p)
20420 	    count++;
20421 	  p = TREE_CHAIN (p);
20422 	}
20423       while (p && p != void_list_node);
20424       if (count != nargs)
20425 	return unify_too_few_arguments (explain_p, ia, count,
20426 					type_pack_p);
20427     }
20428 
20429   if (!subr)
20430     {
20431       tsubst_flags_t complain = (explain_p
20432 				 ? tf_warning_or_error
20433 				 : tf_none);
20434       bool tried_array_deduction = (cxx_dialect < cxx17);
20435 
20436       for (i = 0; i < ntparms; i++)
20437 	{
20438 	  tree targ = TREE_VEC_ELT (targs, i);
20439 	  tree tparm = TREE_VEC_ELT (tparms, i);
20440 
20441 	  /* Clear the "incomplete" flags on all argument packs now so that
20442 	     substituting them into later default arguments works.  */
20443 	  if (targ && ARGUMENT_PACK_P (targ))
20444             {
20445               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
20446               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
20447             }
20448 
20449 	  if (targ || tparm == error_mark_node)
20450 	    continue;
20451 	  tparm = TREE_VALUE (tparm);
20452 
20453 	  if (TREE_CODE (tparm) == TYPE_DECL
20454 	      && !tried_array_deduction)
20455 	    {
20456 	      try_array_deduction (tparms, targs, xparms);
20457 	      tried_array_deduction = true;
20458 	      if (TREE_VEC_ELT (targs, i))
20459 		continue;
20460 	    }
20461 
20462 	  /* If this is an undeduced nontype parameter that depends on
20463 	     a type parameter, try another pass; its type may have been
20464 	     deduced from a later argument than the one from which
20465 	     this parameter can be deduced.  */
20466 	  if (TREE_CODE (tparm) == PARM_DECL
20467 	      && uses_template_parms (TREE_TYPE (tparm))
20468 	      && saw_undeduced < 2)
20469 	    {
20470 	      saw_undeduced = 1;
20471 	      continue;
20472 	    }
20473 
20474 	  /* Core issue #226 (C++0x) [temp.deduct]:
20475 
20476 	     If a template argument has not been deduced, its
20477 	     default template argument, if any, is used.
20478 
20479 	     When we are in C++98 mode, TREE_PURPOSE will either
20480 	     be NULL_TREE or ERROR_MARK_NODE, so we do not need
20481 	     to explicitly check cxx_dialect here.  */
20482 	  if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
20483 	    /* OK, there is a default argument.  Wait until after the
20484 	       conversion check to do substitution.  */
20485 	    continue;
20486 
20487 	  /* If the type parameter is a parameter pack, then it will
20488 	     be deduced to an empty parameter pack.  */
20489 	  if (template_parameter_pack_p (tparm))
20490 	    {
20491 	      tree arg;
20492 
20493 	      if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
20494 		{
20495 		  arg = make_node (NONTYPE_ARGUMENT_PACK);
20496 		  TREE_CONSTANT (arg) = 1;
20497 		}
20498 	      else
20499 		arg = cxx_make_type (TYPE_ARGUMENT_PACK);
20500 
20501 	      SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
20502 
20503 	      TREE_VEC_ELT (targs, i) = arg;
20504 	      continue;
20505 	    }
20506 
20507 	  return unify_parameter_deduction_failure (explain_p, tparm);
20508 	}
20509 
20510       /* DR 1391: All parameters have args, now check non-dependent parms for
20511 	 convertibility.  */
20512       if (saw_undeduced < 2)
20513 	for (ia = 0, parms = xparms, args = xargs, nargs = xnargs;
20514 	     parms && parms != void_list_node && ia < nargs; )
20515 	  {
20516 	    parm = TREE_VALUE (parms);
20517 
20518 	    if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
20519 		&& (!TREE_CHAIN (parms)
20520 		    || TREE_CHAIN (parms) == void_list_node))
20521 	      /* For a function parameter pack that occurs at the end of the
20522 		 parameter-declaration-list, the type A of each remaining
20523 		 argument of the call is compared with the type P of the
20524 		 declarator-id of the function parameter pack.  */
20525 	      break;
20526 
20527 	    parms = TREE_CHAIN (parms);
20528 
20529 	    if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
20530 	      /* For a function parameter pack that does not occur at the
20531 		 end of the parameter-declaration-list, the type of the
20532 		 parameter pack is a non-deduced context.  */
20533 	      continue;
20534 
20535 	    arg = args[ia];
20536 	    ++ia;
20537 
20538 	    if (uses_template_parms (parm))
20539 	      continue;
20540 	    /* Workaround for c++/80290: avoid combinatorial explosion on
20541 	       deeply nested braced init-lists.  */
20542 	    if (braced_init_depth (arg) > 2)
20543 	      continue;
20544 	    if (check_non_deducible_conversion (parm, arg, strict, flags,
20545 						explain_p))
20546 	      return 1;
20547 	  }
20548 
20549       /* Now substitute into the default template arguments.  */
20550       for (i = 0; i < ntparms; i++)
20551 	{
20552 	  tree targ = TREE_VEC_ELT (targs, i);
20553 	  tree tparm = TREE_VEC_ELT (tparms, i);
20554 
20555 	  if (targ || tparm == error_mark_node)
20556 	    continue;
20557 	  tree parm = TREE_VALUE (tparm);
20558 	  tree arg = TREE_PURPOSE (tparm);
20559 	  reopen_deferring_access_checks (*checks);
20560 	  location_t save_loc = input_location;
20561 	  if (DECL_P (parm))
20562 	    input_location = DECL_SOURCE_LOCATION (parm);
20563 
20564 	  if (saw_undeduced == 1
20565 	      && TREE_CODE (parm) == PARM_DECL
20566 	      && uses_template_parms (TREE_TYPE (parm)))
20567 	    {
20568 	      /* The type of this non-type parameter depends on undeduced
20569 		 parameters.  Don't try to use its default argument yet,
20570 		 since we might deduce an argument for it on the next pass,
20571 		 but do check whether the arguments we already have cause
20572 		 substitution failure, so that that happens before we try
20573 		 later default arguments (78489).  */
20574 	      ++processing_template_decl;
20575 	      tree type = tsubst (TREE_TYPE (parm), full_targs, complain,
20576 				  NULL_TREE);
20577 	      --processing_template_decl;
20578 	      if (type == error_mark_node)
20579 		arg = error_mark_node;
20580 	      else
20581 		arg = NULL_TREE;
20582 	    }
20583 	  else
20584 	    {
20585 	      /* Even if the call is happening in template context, getting
20586 		 here means it's non-dependent, and a default argument is
20587 		 considered a separate definition under [temp.decls], so we can
20588 		 do this substitution without processing_template_decl.  This
20589 		 is important if the default argument contains something that
20590 		 might be instantiation-dependent like access (87480).  */
20591 	      processing_template_decl_sentinel s;
20592 	      tree substed = NULL_TREE;
20593 	      if (saw_undeduced == 1)
20594 		{
20595 		  /* First instatiate in template context, in case we still
20596 		     depend on undeduced template parameters.  */
20597 		  ++processing_template_decl;
20598 		  substed = tsubst_template_arg (arg, full_targs, complain,
20599 						 NULL_TREE);
20600 		  --processing_template_decl;
20601 		  if (substed != error_mark_node
20602 		      && !uses_template_parms (substed))
20603 		    /* We replaced all the tparms, substitute again out of
20604 		       template context.  */
20605 		    substed = NULL_TREE;
20606 		}
20607 	      if (!substed)
20608 		substed = tsubst_template_arg (arg, full_targs, complain,
20609 					       NULL_TREE);
20610 
20611 	      if (!uses_template_parms (substed))
20612 		arg = convert_template_argument (parm, substed, full_targs,
20613 						 complain, i, NULL_TREE);
20614 	      else if (saw_undeduced == 1)
20615 		arg = NULL_TREE;
20616 	      else
20617 		arg = error_mark_node;
20618 	    }
20619 
20620 	  input_location = save_loc;
20621 	  *checks = get_deferred_access_checks ();
20622 	  pop_deferring_access_checks ();
20623 
20624 	  if (arg == error_mark_node)
20625 	    return 1;
20626 	  else if (arg)
20627 	    {
20628 	      TREE_VEC_ELT (targs, i) = arg;
20629 	      /* The position of the first default template argument,
20630 		 is also the number of non-defaulted arguments in TARGS.
20631 		 Record that.  */
20632 	      if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
20633 		SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
20634 	    }
20635 	}
20636 
20637       if (saw_undeduced++ == 1)
20638 	goto again;
20639     }
20640 
20641   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
20642     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
20643 
20644   return unify_success (explain_p);
20645 }
20646 
20647 /* Subroutine of type_unification_real.  Args are like the variables
20648    at the call site.  ARG is an overloaded function (or template-id);
20649    we try deducing template args from each of the overloads, and if
20650    only one succeeds, we go with that.  Modifies TARGS and returns
20651    true on success.  */
20652 
20653 static bool
resolve_overloaded_unification(tree tparms,tree targs,tree parm,tree arg,unification_kind_t strict,int sub_strict,bool explain_p)20654 resolve_overloaded_unification (tree tparms,
20655 				tree targs,
20656 				tree parm,
20657 				tree arg,
20658 				unification_kind_t strict,
20659 				int sub_strict,
20660 			        bool explain_p)
20661 {
20662   tree tempargs = copy_node (targs);
20663   int good = 0;
20664   tree goodfn = NULL_TREE;
20665   bool addr_p;
20666 
20667   if (TREE_CODE (arg) == ADDR_EXPR)
20668     {
20669       arg = TREE_OPERAND (arg, 0);
20670       addr_p = true;
20671     }
20672   else
20673     addr_p = false;
20674 
20675   if (TREE_CODE (arg) == COMPONENT_REF)
20676     /* Handle `&x' where `x' is some static or non-static member
20677        function name.  */
20678     arg = TREE_OPERAND (arg, 1);
20679 
20680   if (TREE_CODE (arg) == OFFSET_REF)
20681     arg = TREE_OPERAND (arg, 1);
20682 
20683   /* Strip baselink information.  */
20684   if (BASELINK_P (arg))
20685     arg = BASELINK_FUNCTIONS (arg);
20686 
20687   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
20688     {
20689       /* If we got some explicit template args, we need to plug them into
20690 	 the affected templates before we try to unify, in case the
20691 	 explicit args will completely resolve the templates in question.  */
20692 
20693       int ok = 0;
20694       tree expl_subargs = TREE_OPERAND (arg, 1);
20695       arg = TREE_OPERAND (arg, 0);
20696 
20697       for (lkp_iterator iter (arg); iter; ++iter)
20698 	{
20699 	  tree fn = *iter;
20700 	  tree subargs, elem;
20701 
20702 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
20703 	    continue;
20704 
20705 	  subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
20706 					   expl_subargs, NULL_TREE, tf_none,
20707 					   /*require_all_args=*/true,
20708 					   /*use_default_args=*/true);
20709 	  if (subargs != error_mark_node
20710 	      && !any_dependent_template_arguments_p (subargs))
20711 	    {
20712 	      elem = TREE_TYPE (instantiate_template (fn, subargs, tf_none));
20713 	      if (try_one_overload (tparms, targs, tempargs, parm,
20714 				    elem, strict, sub_strict, addr_p, explain_p)
20715 		  && (!goodfn || !same_type_p (goodfn, elem)))
20716 		{
20717 		  goodfn = elem;
20718 		  ++good;
20719 		}
20720 	    }
20721 	  else if (subargs)
20722 	    ++ok;
20723 	}
20724       /* If no templates (or more than one) are fully resolved by the
20725 	 explicit arguments, this template-id is a non-deduced context; it
20726 	 could still be OK if we deduce all template arguments for the
20727 	 enclosing call through other arguments.  */
20728       if (good != 1)
20729 	good = ok;
20730     }
20731   else if (TREE_CODE (arg) != OVERLOAD
20732 	   && TREE_CODE (arg) != FUNCTION_DECL)
20733     /* If ARG is, for example, "(0, &f)" then its type will be unknown
20734        -- but the deduction does not succeed because the expression is
20735        not just the function on its own.  */
20736     return false;
20737   else
20738     for (lkp_iterator iter (arg); iter; ++iter)
20739       {
20740 	tree fn = *iter;
20741 	if (try_one_overload (tparms, targs, tempargs, parm, TREE_TYPE (fn),
20742 			      strict, sub_strict, addr_p, explain_p)
20743 	    && (!goodfn || !decls_match (goodfn, fn)))
20744 	  {
20745 	    goodfn = fn;
20746 	    ++good;
20747 	  }
20748       }
20749 
20750   /* [temp.deduct.type] A template-argument can be deduced from a pointer
20751      to function or pointer to member function argument if the set of
20752      overloaded functions does not contain function templates and at most
20753      one of a set of overloaded functions provides a unique match.
20754 
20755      So if we found multiple possibilities, we return success but don't
20756      deduce anything.  */
20757 
20758   if (good == 1)
20759     {
20760       int i = TREE_VEC_LENGTH (targs);
20761       for (; i--; )
20762 	if (TREE_VEC_ELT (tempargs, i))
20763 	  {
20764 	    tree old = TREE_VEC_ELT (targs, i);
20765 	    tree new_ = TREE_VEC_ELT (tempargs, i);
20766 	    if (new_ && old && ARGUMENT_PACK_P (old)
20767 		&& ARGUMENT_PACK_EXPLICIT_ARGS (old))
20768 	      /* Don't forget explicit template arguments in a pack.  */
20769 	      ARGUMENT_PACK_EXPLICIT_ARGS (new_)
20770 		= ARGUMENT_PACK_EXPLICIT_ARGS (old);
20771 	    TREE_VEC_ELT (targs, i) = new_;
20772 	  }
20773     }
20774   if (good)
20775     return true;
20776 
20777   return false;
20778 }
20779 
20780 /* Core DR 115: In contexts where deduction is done and fails, or in
20781    contexts where deduction is not done, if a template argument list is
20782    specified and it, along with any default template arguments, identifies
20783    a single function template specialization, then the template-id is an
20784    lvalue for the function template specialization.  */
20785 
20786 tree
resolve_nondeduced_context(tree orig_expr,tsubst_flags_t complain)20787 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
20788 {
20789   tree expr, offset, baselink;
20790   bool addr;
20791 
20792   if (!type_unknown_p (orig_expr))
20793     return orig_expr;
20794 
20795   expr = orig_expr;
20796   addr = false;
20797   offset = NULL_TREE;
20798   baselink = NULL_TREE;
20799 
20800   if (TREE_CODE (expr) == ADDR_EXPR)
20801     {
20802       expr = TREE_OPERAND (expr, 0);
20803       addr = true;
20804     }
20805   if (TREE_CODE (expr) == OFFSET_REF)
20806     {
20807       offset = expr;
20808       expr = TREE_OPERAND (expr, 1);
20809     }
20810   if (BASELINK_P (expr))
20811     {
20812       baselink = expr;
20813       expr = BASELINK_FUNCTIONS (expr);
20814     }
20815 
20816   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
20817     {
20818       int good = 0;
20819       tree goodfn = NULL_TREE;
20820 
20821       /* If we got some explicit template args, we need to plug them into
20822 	 the affected templates before we try to unify, in case the
20823 	 explicit args will completely resolve the templates in question.  */
20824 
20825       tree expl_subargs = TREE_OPERAND (expr, 1);
20826       tree arg = TREE_OPERAND (expr, 0);
20827       tree badfn = NULL_TREE;
20828       tree badargs = NULL_TREE;
20829 
20830       for (lkp_iterator iter (arg); iter; ++iter)
20831 	{
20832 	  tree fn = *iter;
20833 	  tree subargs, elem;
20834 
20835 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
20836 	    continue;
20837 
20838 	  subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
20839 					   expl_subargs, NULL_TREE, tf_none,
20840 					   /*require_all_args=*/true,
20841 					   /*use_default_args=*/true);
20842 	  if (subargs != error_mark_node
20843 	      && !any_dependent_template_arguments_p (subargs))
20844 	    {
20845 	      elem = instantiate_template (fn, subargs, tf_none);
20846 	      if (elem == error_mark_node)
20847 		{
20848 		  badfn = fn;
20849 		  badargs = subargs;
20850 		}
20851 	      else if (elem && (!goodfn || !decls_match (goodfn, elem)))
20852 		{
20853 		  goodfn = elem;
20854 		  ++good;
20855 		}
20856 	    }
20857 	}
20858       if (good == 1)
20859 	{
20860 	  mark_used (goodfn);
20861 	  expr = goodfn;
20862 	  if (baselink)
20863 	    expr = build_baselink (BASELINK_BINFO (baselink),
20864 				   BASELINK_ACCESS_BINFO (baselink),
20865 				   expr, BASELINK_OPTYPE (baselink));
20866 	  if (offset)
20867 	    {
20868 	      tree base
20869 		= TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
20870 	      expr = build_offset_ref (base, expr, addr, complain);
20871 	    }
20872 	  if (addr)
20873 	    expr = cp_build_addr_expr (expr, complain);
20874 	  return expr;
20875 	}
20876       else if (good == 0 && badargs && (complain & tf_error))
20877 	/* There were no good options and at least one bad one, so let the
20878 	   user know what the problem is.  */
20879 	instantiate_template (badfn, badargs, complain);
20880     }
20881   return orig_expr;
20882 }
20883 
20884 /* Subroutine of resolve_overloaded_unification; does deduction for a single
20885    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
20886    different overloads deduce different arguments for a given parm.
20887    ADDR_P is true if the expression for which deduction is being
20888    performed was of the form "& fn" rather than simply "fn".
20889 
20890    Returns 1 on success.  */
20891 
20892 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)20893 try_one_overload (tree tparms,
20894 		  tree orig_targs,
20895 		  tree targs,
20896 		  tree parm,
20897 		  tree arg,
20898 		  unification_kind_t strict,
20899 		  int sub_strict,
20900 		  bool addr_p,
20901 		  bool explain_p)
20902 {
20903   int nargs;
20904   tree tempargs;
20905   int i;
20906 
20907   if (arg == error_mark_node)
20908     return 0;
20909 
20910   /* [temp.deduct.type] A template-argument can be deduced from a pointer
20911      to function or pointer to member function argument if the set of
20912      overloaded functions does not contain function templates and at most
20913      one of a set of overloaded functions provides a unique match.
20914 
20915      So if this is a template, just return success.  */
20916 
20917   if (uses_template_parms (arg))
20918     return 1;
20919 
20920   if (TREE_CODE (arg) == METHOD_TYPE)
20921     arg = build_ptrmemfunc_type (build_pointer_type (arg));
20922   else if (addr_p)
20923     arg = build_pointer_type (arg);
20924 
20925   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
20926 
20927   /* We don't copy orig_targs for this because if we have already deduced
20928      some template args from previous args, unify would complain when we
20929      try to deduce a template parameter for the same argument, even though
20930      there isn't really a conflict.  */
20931   nargs = TREE_VEC_LENGTH (targs);
20932   tempargs = make_tree_vec (nargs);
20933 
20934   if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
20935     return 0;
20936 
20937   /* First make sure we didn't deduce anything that conflicts with
20938      explicitly specified args.  */
20939   for (i = nargs; i--; )
20940     {
20941       tree elt = TREE_VEC_ELT (tempargs, i);
20942       tree oldelt = TREE_VEC_ELT (orig_targs, i);
20943 
20944       if (!elt)
20945 	/*NOP*/;
20946       else if (uses_template_parms (elt))
20947 	/* Since we're unifying against ourselves, we will fill in
20948 	   template args used in the function parm list with our own
20949 	   template parms.  Discard them.  */
20950 	TREE_VEC_ELT (tempargs, i) = NULL_TREE;
20951       else if (oldelt && ARGUMENT_PACK_P (oldelt))
20952 	{
20953 	  /* Check that the argument at each index of the deduced argument pack
20954 	     is equivalent to the corresponding explicitly specified argument.
20955 	     We may have deduced more arguments than were explicitly specified,
20956 	     and that's OK.  */
20957 
20958 	  /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
20959 	     that's wrong if we deduce the same argument pack from multiple
20960 	     function arguments: it's only incomplete the first time.  */
20961 
20962 	  tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
20963 	  tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
20964 
20965 	  if (TREE_VEC_LENGTH (deduced_pack)
20966 	      < TREE_VEC_LENGTH (explicit_pack))
20967 	    return 0;
20968 
20969 	  for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
20970 	    if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
20971 				      TREE_VEC_ELT (deduced_pack, j)))
20972 	      return 0;
20973 	}
20974       else if (oldelt && !template_args_equal (oldelt, elt))
20975 	return 0;
20976     }
20977 
20978   for (i = nargs; i--; )
20979     {
20980       tree elt = TREE_VEC_ELT (tempargs, i);
20981 
20982       if (elt)
20983 	TREE_VEC_ELT (targs, i) = elt;
20984     }
20985 
20986   return 1;
20987 }
20988 
20989 /* PARM is a template class (perhaps with unbound template
20990    parameters).  ARG is a fully instantiated type.  If ARG can be
20991    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
20992    TARGS are as for unify.  */
20993 
20994 static tree
try_class_unification(tree tparms,tree targs,tree parm,tree arg,bool explain_p)20995 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
20996 		       bool explain_p)
20997 {
20998   tree copy_of_targs;
20999 
21000   if (!CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
21001     return NULL_TREE;
21002   else if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
21003     /* Matches anything.  */;
21004   else if (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
21005 	   != most_general_template (CLASSTYPE_TI_TEMPLATE (parm)))
21006     return NULL_TREE;
21007 
21008   /* We need to make a new template argument vector for the call to
21009      unify.  If we used TARGS, we'd clutter it up with the result of
21010      the attempted unification, even if this class didn't work out.
21011      We also don't want to commit ourselves to all the unifications
21012      we've already done, since unification is supposed to be done on
21013      an argument-by-argument basis.  In other words, consider the
21014      following pathological case:
21015 
21016        template <int I, int J, int K>
21017        struct S {};
21018 
21019        template <int I, int J>
21020        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
21021 
21022        template <int I, int J, int K>
21023        void f(S<I, J, K>, S<I, I, I>);
21024 
21025        void g() {
21026 	 S<0, 0, 0> s0;
21027 	 S<0, 1, 2> s2;
21028 
21029 	 f(s0, s2);
21030        }
21031 
21032      Now, by the time we consider the unification involving `s2', we
21033      already know that we must have `f<0, 0, 0>'.  But, even though
21034      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
21035      because there are two ways to unify base classes of S<0, 1, 2>
21036      with S<I, I, I>.  If we kept the already deduced knowledge, we
21037      would reject the possibility I=1.  */
21038   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
21039 
21040   if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
21041     {
21042       if (unify_bound_ttp_args (tparms, copy_of_targs, parm, arg, explain_p))
21043 	return NULL_TREE;
21044       return arg;
21045     }
21046 
21047   /* If unification failed, we're done.  */
21048   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
21049 	     CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
21050     return NULL_TREE;
21051 
21052   return arg;
21053 }
21054 
21055 /* Given a template type PARM and a class type ARG, find the unique
21056    base type in ARG that is an instance of PARM.  We do not examine
21057    ARG itself; only its base-classes.  If there is not exactly one
21058    appropriate base class, return NULL_TREE.  PARM may be the type of
21059    a partial specialization, as well as a plain template type.  Used
21060    by unify.  */
21061 
21062 static enum template_base_result
get_template_base(tree tparms,tree targs,tree parm,tree arg,bool explain_p,tree * result)21063 get_template_base (tree tparms, tree targs, tree parm, tree arg,
21064 		   bool explain_p, tree *result)
21065 {
21066   tree rval = NULL_TREE;
21067   tree binfo;
21068 
21069   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
21070 
21071   binfo = TYPE_BINFO (complete_type (arg));
21072   if (!binfo)
21073     {
21074       /* The type could not be completed.  */
21075       *result = NULL_TREE;
21076       return tbr_incomplete_type;
21077     }
21078 
21079   /* Walk in inheritance graph order.  The search order is not
21080      important, and this avoids multiple walks of virtual bases.  */
21081   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
21082     {
21083       tree r = try_class_unification (tparms, targs, parm,
21084 				      BINFO_TYPE (binfo), explain_p);
21085 
21086       if (r)
21087 	{
21088 	  /* If there is more than one satisfactory baseclass, then:
21089 
21090 	       [temp.deduct.call]
21091 
21092 	      If they yield more than one possible deduced A, the type
21093 	      deduction fails.
21094 
21095 	     applies.  */
21096 	  if (rval && !same_type_p (r, rval))
21097 	    {
21098 	      *result = NULL_TREE;
21099 	      return tbr_ambiguous_baseclass;
21100 	    }
21101 
21102 	  rval = r;
21103 	}
21104     }
21105 
21106   *result = rval;
21107   return tbr_success;
21108 }
21109 
21110 /* Returns the level of DECL, which declares a template parameter.  */
21111 
21112 static int
template_decl_level(tree decl)21113 template_decl_level (tree decl)
21114 {
21115   switch (TREE_CODE (decl))
21116     {
21117     case TYPE_DECL:
21118     case TEMPLATE_DECL:
21119       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
21120 
21121     case PARM_DECL:
21122       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
21123 
21124     default:
21125       gcc_unreachable ();
21126     }
21127   return 0;
21128 }
21129 
21130 /* Decide whether ARG can be unified with PARM, considering only the
21131    cv-qualifiers of each type, given STRICT as documented for unify.
21132    Returns nonzero iff the unification is OK on that basis.  */
21133 
21134 static int
check_cv_quals_for_unify(int strict,tree arg,tree parm)21135 check_cv_quals_for_unify (int strict, tree arg, tree parm)
21136 {
21137   int arg_quals = cp_type_quals (arg);
21138   int parm_quals = cp_type_quals (parm);
21139 
21140   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
21141       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
21142     {
21143       /*  Although a CVR qualifier is ignored when being applied to a
21144 	  substituted template parameter ([8.3.2]/1 for example), that
21145 	  does not allow us to unify "const T" with "int&" because both
21146 	  types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
21147 	  It is ok when we're allowing additional CV qualifiers
21148 	  at the outer level [14.8.2.1]/3,1st bullet.  */
21149       if ((TREE_CODE (arg) == REFERENCE_TYPE
21150 	   || TREE_CODE (arg) == FUNCTION_TYPE
21151 	   || TREE_CODE (arg) == METHOD_TYPE)
21152 	  && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
21153 	return 0;
21154 
21155       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
21156 	  && (parm_quals & TYPE_QUAL_RESTRICT))
21157 	return 0;
21158     }
21159 
21160   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
21161       && (arg_quals & parm_quals) != parm_quals)
21162     return 0;
21163 
21164   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
21165       && (parm_quals & arg_quals) != arg_quals)
21166     return 0;
21167 
21168   return 1;
21169 }
21170 
21171 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
21172 void
template_parm_level_and_index(tree parm,int * level,int * index)21173 template_parm_level_and_index (tree parm, int* level, int* index)
21174 {
21175   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
21176       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
21177       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
21178     {
21179       *index = TEMPLATE_TYPE_IDX (parm);
21180       *level = TEMPLATE_TYPE_LEVEL (parm);
21181     }
21182   else
21183     {
21184       *index = TEMPLATE_PARM_IDX (parm);
21185       *level = TEMPLATE_PARM_LEVEL (parm);
21186     }
21187 }
21188 
21189 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)			\
21190   do {									\
21191     if (unify (TP, TA, P, A, S, EP))					\
21192       return 1;								\
21193   } while (0)
21194 
21195 /* Unifies the remaining arguments in PACKED_ARGS with the pack
21196    expansion at the end of PACKED_PARMS. Returns 0 if the type
21197    deduction succeeds, 1 otherwise. STRICT is the same as in
21198    fn_type_unification. CALL_ARGS_P is true iff PACKED_ARGS is actually a
21199    function call argument list. We'll need to adjust the arguments to make them
21200    types. SUBR tells us if this is from a recursive call to
21201    type_unification_real, or for comparing two template argument
21202    lists. */
21203 
21204 static int
unify_pack_expansion(tree tparms,tree targs,tree packed_parms,tree packed_args,unification_kind_t strict,bool subr,bool explain_p)21205 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
21206                       tree packed_args, unification_kind_t strict,
21207                       bool subr, bool explain_p)
21208 {
21209   tree parm
21210     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
21211   tree pattern = PACK_EXPANSION_PATTERN (parm);
21212   tree pack, packs = NULL_TREE;
21213   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
21214 
21215   /* Add in any args remembered from an earlier partial instantiation.  */
21216   targs = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (parm), targs);
21217   int levels = TMPL_ARGS_DEPTH (targs);
21218 
21219   packed_args = expand_template_argument_pack (packed_args);
21220 
21221   int len = TREE_VEC_LENGTH (packed_args);
21222 
21223   /* Determine the parameter packs we will be deducing from the
21224      pattern, and record their current deductions.  */
21225   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
21226        pack; pack = TREE_CHAIN (pack))
21227     {
21228       tree parm_pack = TREE_VALUE (pack);
21229       int idx, level;
21230 
21231       /* Only template parameter packs can be deduced, not e.g. function
21232 	 parameter packs or __bases or __integer_pack.  */
21233       if (!TEMPLATE_PARM_P (parm_pack))
21234 	continue;
21235 
21236       /* Determine the index and level of this parameter pack.  */
21237       template_parm_level_and_index (parm_pack, &level, &idx);
21238       if (level < levels)
21239 	continue;
21240 
21241       /* Keep track of the parameter packs and their corresponding
21242          argument packs.  */
21243       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
21244       TREE_TYPE (packs) = make_tree_vec (len - start);
21245     }
21246 
21247   /* Loop through all of the arguments that have not yet been
21248      unified and unify each with the pattern.  */
21249   for (i = start; i < len; i++)
21250     {
21251       tree parm;
21252       bool any_explicit = false;
21253       tree arg = TREE_VEC_ELT (packed_args, i);
21254 
21255       /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
21256 	 or the element of its argument pack at the current index if
21257 	 this argument was explicitly specified.  */
21258       for (pack = packs; pack; pack = TREE_CHAIN (pack))
21259         {
21260           int idx, level;
21261           tree arg, pargs;
21262           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
21263 
21264           arg = NULL_TREE;
21265           if (TREE_VALUE (pack)
21266               && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
21267               && (i - start < TREE_VEC_LENGTH (pargs)))
21268             {
21269               any_explicit = true;
21270               arg = TREE_VEC_ELT (pargs, i - start);
21271             }
21272           TMPL_ARG (targs, level, idx) = arg;
21273         }
21274 
21275       /* If we had explicit template arguments, substitute them into the
21276 	 pattern before deduction.  */
21277       if (any_explicit)
21278 	{
21279 	  /* Some arguments might still be unspecified or dependent.  */
21280 	  bool dependent;
21281 	  ++processing_template_decl;
21282 	  dependent = any_dependent_template_arguments_p (targs);
21283 	  if (!dependent)
21284 	    --processing_template_decl;
21285 	  parm = tsubst (pattern, targs,
21286 			 explain_p ? tf_warning_or_error : tf_none,
21287 			 NULL_TREE);
21288 	  if (dependent)
21289 	    --processing_template_decl;
21290 	  if (parm == error_mark_node)
21291 	    return 1;
21292 	}
21293       else
21294 	parm = pattern;
21295 
21296       /* Unify the pattern with the current argument.  */
21297       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
21298 			      explain_p))
21299 	return 1;
21300 
21301       /* For each parameter pack, collect the deduced value.  */
21302       for (pack = packs; pack; pack = TREE_CHAIN (pack))
21303         {
21304           int idx, level;
21305           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
21306 
21307           TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
21308             TMPL_ARG (targs, level, idx);
21309         }
21310     }
21311 
21312   /* Verify that the results of unification with the parameter packs
21313      produce results consistent with what we've seen before, and make
21314      the deduced argument packs available.  */
21315   for (pack = packs; pack; pack = TREE_CHAIN (pack))
21316     {
21317       tree old_pack = TREE_VALUE (pack);
21318       tree new_args = TREE_TYPE (pack);
21319       int i, len = TREE_VEC_LENGTH (new_args);
21320       int idx, level;
21321       bool nondeduced_p = false;
21322 
21323       /* By default keep the original deduced argument pack.
21324 	 If necessary, more specific code is going to update the
21325 	 resulting deduced argument later down in this function.  */
21326       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
21327       TMPL_ARG (targs, level, idx) = old_pack;
21328 
21329       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
21330 	 actually deduce anything.  */
21331       for (i = 0; i < len && !nondeduced_p; ++i)
21332 	if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
21333 	  nondeduced_p = true;
21334       if (nondeduced_p)
21335 	continue;
21336 
21337       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
21338         {
21339           /* If we had fewer function args than explicit template args,
21340              just use the explicits.  */
21341           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
21342           int explicit_len = TREE_VEC_LENGTH (explicit_args);
21343           if (len < explicit_len)
21344             new_args = explicit_args;
21345         }
21346 
21347       if (!old_pack)
21348         {
21349           tree result;
21350           /* Build the deduced *_ARGUMENT_PACK.  */
21351           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
21352             {
21353               result = make_node (NONTYPE_ARGUMENT_PACK);
21354               TREE_CONSTANT (result) = 1;
21355             }
21356           else
21357             result = cxx_make_type (TYPE_ARGUMENT_PACK);
21358 
21359           SET_ARGUMENT_PACK_ARGS (result, new_args);
21360 
21361           /* Note the deduced argument packs for this parameter
21362              pack.  */
21363           TMPL_ARG (targs, level, idx) = result;
21364         }
21365       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
21366                && (ARGUMENT_PACK_ARGS (old_pack)
21367                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
21368         {
21369           /* We only had the explicitly-provided arguments before, but
21370              now we have a complete set of arguments.  */
21371           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
21372 
21373           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
21374           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
21375           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
21376         }
21377       else
21378 	{
21379 	  tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
21380 	  tree old_args = ARGUMENT_PACK_ARGS (old_pack);
21381 
21382 	  if (!comp_template_args (old_args, new_args,
21383 				   &bad_old_arg, &bad_new_arg))
21384 	    /* Inconsistent unification of this parameter pack.  */
21385 	    return unify_parameter_pack_inconsistent (explain_p,
21386 						      bad_old_arg,
21387 						      bad_new_arg);
21388 	}
21389     }
21390 
21391   return unify_success (explain_p);
21392 }
21393 
21394 /* Handle unification of the domain of an array.  PARM_DOM and ARG_DOM are
21395    INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs.  The other
21396    parameters and return value are as for unify.  */
21397 
21398 static int
unify_array_domain(tree tparms,tree targs,tree parm_dom,tree arg_dom,bool explain_p)21399 unify_array_domain (tree tparms, tree targs,
21400 		    tree parm_dom, tree arg_dom,
21401 		    bool explain_p)
21402 {
21403   tree parm_max;
21404   tree arg_max;
21405   bool parm_cst;
21406   bool arg_cst;
21407 
21408   /* Our representation of array types uses "N - 1" as the
21409      TYPE_MAX_VALUE for an array with "N" elements, if "N" is
21410      not an integer constant.  We cannot unify arbitrarily
21411      complex expressions, so we eliminate the MINUS_EXPRs
21412      here.  */
21413   parm_max = TYPE_MAX_VALUE (parm_dom);
21414   parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
21415   if (!parm_cst)
21416     {
21417       gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
21418       parm_max = TREE_OPERAND (parm_max, 0);
21419     }
21420   arg_max = TYPE_MAX_VALUE (arg_dom);
21421   arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
21422   if (!arg_cst)
21423     {
21424       /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
21425 	 trying to unify the type of a variable with the type
21426 	 of a template parameter.  For example:
21427 
21428 	   template <unsigned int N>
21429 	   void f (char (&) [N]);
21430 	   int g();
21431 	   void h(int i) {
21432 	     char a[g(i)];
21433 	     f(a);
21434 	   }
21435 
21436 	 Here, the type of the ARG will be "int [g(i)]", and
21437 	 may be a SAVE_EXPR, etc.  */
21438       if (TREE_CODE (arg_max) != MINUS_EXPR)
21439 	return unify_vla_arg (explain_p, arg_dom);
21440       arg_max = TREE_OPERAND (arg_max, 0);
21441     }
21442 
21443   /* If only one of the bounds used a MINUS_EXPR, compensate
21444      by adding one to the other bound.  */
21445   if (parm_cst && !arg_cst)
21446     parm_max = fold_build2_loc (input_location, PLUS_EXPR,
21447 				integer_type_node,
21448 				parm_max,
21449 				integer_one_node);
21450   else if (arg_cst && !parm_cst)
21451     arg_max = fold_build2_loc (input_location, PLUS_EXPR,
21452 			       integer_type_node,
21453 			       arg_max,
21454 			       integer_one_node);
21455 
21456   return unify (tparms, targs, parm_max, arg_max,
21457 		UNIFY_ALLOW_INTEGER, explain_p);
21458 }
21459 
21460 /* Returns whether T, a P or A in unify, is a type, template or expression.  */
21461 
21462 enum pa_kind_t { pa_type, pa_tmpl, pa_expr };
21463 
21464 static pa_kind_t
pa_kind(tree t)21465 pa_kind (tree t)
21466 {
21467   if (PACK_EXPANSION_P (t))
21468     t = PACK_EXPANSION_PATTERN (t);
21469   if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
21470       || TREE_CODE (t) == UNBOUND_CLASS_TEMPLATE
21471       || DECL_TYPE_TEMPLATE_P (t))
21472     return pa_tmpl;
21473   else if (TYPE_P (t))
21474     return pa_type;
21475   else
21476     return pa_expr;
21477 }
21478 
21479 /* Deduce the value of template parameters.  TPARMS is the (innermost)
21480    set of template parameters to a template.  TARGS is the bindings
21481    for those template parameters, as determined thus far; TARGS may
21482    include template arguments for outer levels of template parameters
21483    as well.  PARM is a parameter to a template function, or a
21484    subcomponent of that parameter; ARG is the corresponding argument.
21485    This function attempts to match PARM with ARG in a manner
21486    consistent with the existing assignments in TARGS.  If more values
21487    are deduced, then TARGS is updated.
21488 
21489    Returns 0 if the type deduction succeeds, 1 otherwise.  The
21490    parameter STRICT is a bitwise or of the following flags:
21491 
21492      UNIFY_ALLOW_NONE:
21493        Require an exact match between PARM and ARG.
21494      UNIFY_ALLOW_MORE_CV_QUAL:
21495        Allow the deduced ARG to be more cv-qualified (by qualification
21496        conversion) than ARG.
21497      UNIFY_ALLOW_LESS_CV_QUAL:
21498        Allow the deduced ARG to be less cv-qualified than ARG.
21499      UNIFY_ALLOW_DERIVED:
21500        Allow the deduced ARG to be a template base class of ARG,
21501        or a pointer to a template base class of the type pointed to by
21502        ARG.
21503      UNIFY_ALLOW_INTEGER:
21504        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
21505        case for more information.
21506      UNIFY_ALLOW_OUTER_LEVEL:
21507        This is the outermost level of a deduction. Used to determine validity
21508        of qualification conversions. A valid qualification conversion must
21509        have const qualified pointers leading up to the inner type which
21510        requires additional CV quals, except at the outer level, where const
21511        is not required [conv.qual]. It would be normal to set this flag in
21512        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
21513      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
21514        This is the outermost level of a deduction, and PARM can be more CV
21515        qualified at this point.
21516      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
21517        This is the outermost level of a deduction, and PARM can be less CV
21518        qualified at this point.  */
21519 
21520 static int
unify(tree tparms,tree targs,tree parm,tree arg,int strict,bool explain_p)21521 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
21522        bool explain_p)
21523 {
21524   int idx;
21525   tree targ;
21526   tree tparm;
21527   int strict_in = strict;
21528   tsubst_flags_t complain = (explain_p
21529 			     ? tf_warning_or_error
21530 			     : tf_none);
21531 
21532   /* I don't think this will do the right thing with respect to types.
21533      But the only case I've seen it in so far has been array bounds, where
21534      signedness is the only information lost, and I think that will be
21535      okay.  */
21536   while (CONVERT_EXPR_P (parm))
21537     parm = TREE_OPERAND (parm, 0);
21538 
21539   if (arg == error_mark_node)
21540     return unify_invalid (explain_p);
21541   if (arg == unknown_type_node
21542       || arg == init_list_type_node)
21543     /* We can't deduce anything from this, but we might get all the
21544        template args from other function args.  */
21545     return unify_success (explain_p);
21546 
21547   if (parm == any_targ_node || arg == any_targ_node)
21548     return unify_success (explain_p);
21549 
21550   /* If PARM uses template parameters, then we can't bail out here,
21551      even if ARG == PARM, since we won't record unifications for the
21552      template parameters.  We might need them if we're trying to
21553      figure out which of two things is more specialized.  */
21554   if (arg == parm && !uses_template_parms (parm))
21555     return unify_success (explain_p);
21556 
21557   /* Handle init lists early, so the rest of the function can assume
21558      we're dealing with a type. */
21559   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
21560     {
21561       tree elt, elttype;
21562       unsigned i;
21563       tree orig_parm = parm;
21564 
21565       /* Replace T with std::initializer_list<T> for deduction.  */
21566       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
21567 	  && flag_deduce_init_list)
21568 	parm = listify (parm);
21569 
21570       if (!is_std_init_list (parm)
21571 	  && TREE_CODE (parm) != ARRAY_TYPE)
21572 	/* We can only deduce from an initializer list argument if the
21573 	   parameter is std::initializer_list or an array; otherwise this
21574 	   is a non-deduced context. */
21575 	return unify_success (explain_p);
21576 
21577       if (TREE_CODE (parm) == ARRAY_TYPE)
21578 	elttype = TREE_TYPE (parm);
21579       else
21580 	{
21581 	  elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
21582 	  /* Deduction is defined in terms of a single type, so just punt
21583 	     on the (bizarre) std::initializer_list<T...>.  */
21584 	  if (PACK_EXPANSION_P (elttype))
21585 	    return unify_success (explain_p);
21586 	}
21587 
21588       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
21589 	{
21590 	  int elt_strict = strict;
21591 
21592 	  if (elt == error_mark_node)
21593 	    return unify_invalid (explain_p);
21594 
21595 	  if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
21596 	    {
21597 	      tree type = TREE_TYPE (elt);
21598 	      if (type == error_mark_node)
21599 		return unify_invalid (explain_p);
21600 	      /* It should only be possible to get here for a call.  */
21601 	      gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
21602 	      elt_strict |= maybe_adjust_types_for_deduction
21603 		(DEDUCE_CALL, &elttype, &type, elt);
21604 	      elt = type;
21605 	    }
21606 
21607 	  RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
21608 				   explain_p);
21609 	}
21610 
21611       if (TREE_CODE (parm) == ARRAY_TYPE
21612 	  && deducible_array_bound (TYPE_DOMAIN (parm)))
21613 	{
21614 	  /* Also deduce from the length of the initializer list.  */
21615 	  tree max = size_int (CONSTRUCTOR_NELTS (arg));
21616 	  tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
21617 	  if (idx == error_mark_node)
21618 	    return unify_invalid (explain_p);
21619 	  return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
21620 				     idx, explain_p);
21621 	}
21622 
21623       /* If the std::initializer_list<T> deduction worked, replace the
21624 	 deduced A with std::initializer_list<A>.  */
21625       if (orig_parm != parm)
21626 	{
21627 	  idx = TEMPLATE_TYPE_IDX (orig_parm);
21628 	  targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
21629 	  targ = listify (targ);
21630 	  TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
21631 	}
21632       return unify_success (explain_p);
21633     }
21634 
21635   /* If parm and arg aren't the same kind of thing (template, type, or
21636      expression), fail early.  */
21637   if (pa_kind (parm) != pa_kind (arg))
21638     return unify_invalid (explain_p);
21639 
21640   /* Immediately reject some pairs that won't unify because of
21641      cv-qualification mismatches.  */
21642   if (TREE_CODE (arg) == TREE_CODE (parm)
21643       && TYPE_P (arg)
21644       /* It is the elements of the array which hold the cv quals of an array
21645 	 type, and the elements might be template type parms. We'll check
21646 	 when we recurse.  */
21647       && TREE_CODE (arg) != ARRAY_TYPE
21648       /* We check the cv-qualifiers when unifying with template type
21649 	 parameters below.  We want to allow ARG `const T' to unify with
21650 	 PARM `T' for example, when computing which of two templates
21651 	 is more specialized, for example.  */
21652       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
21653       && !check_cv_quals_for_unify (strict_in, arg, parm))
21654     return unify_cv_qual_mismatch (explain_p, parm, arg);
21655 
21656   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
21657       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
21658     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
21659   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
21660   strict &= ~UNIFY_ALLOW_DERIVED;
21661   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
21662   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
21663 
21664   switch (TREE_CODE (parm))
21665     {
21666     case TYPENAME_TYPE:
21667     case SCOPE_REF:
21668     case UNBOUND_CLASS_TEMPLATE:
21669       /* In a type which contains a nested-name-specifier, template
21670 	 argument values cannot be deduced for template parameters used
21671 	 within the nested-name-specifier.  */
21672       return unify_success (explain_p);
21673 
21674     case TEMPLATE_TYPE_PARM:
21675     case TEMPLATE_TEMPLATE_PARM:
21676     case BOUND_TEMPLATE_TEMPLATE_PARM:
21677       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
21678       if (error_operand_p (tparm))
21679 	return unify_invalid (explain_p);
21680 
21681       if (TEMPLATE_TYPE_LEVEL (parm)
21682 	  != template_decl_level (tparm))
21683 	/* The PARM is not one we're trying to unify.  Just check
21684 	   to see if it matches ARG.  */
21685 	{
21686 	  if (TREE_CODE (arg) == TREE_CODE (parm)
21687 	      && (is_auto (parm) ? is_auto (arg)
21688 		  : same_type_p (parm, arg)))
21689 	    return unify_success (explain_p);
21690 	  else
21691 	    return unify_type_mismatch (explain_p, parm, arg);
21692 	}
21693       idx = TEMPLATE_TYPE_IDX (parm);
21694       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
21695       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
21696       if (error_operand_p (tparm))
21697 	return unify_invalid (explain_p);
21698 
21699       /* Check for mixed types and values.  */
21700       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
21701 	   && TREE_CODE (tparm) != TYPE_DECL)
21702 	  || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
21703 	      && TREE_CODE (tparm) != TEMPLATE_DECL))
21704 	gcc_unreachable ();
21705 
21706       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
21707 	{
21708 	  if ((strict_in & UNIFY_ALLOW_DERIVED)
21709 	      && CLASS_TYPE_P (arg))
21710 	    {
21711 	      /* First try to match ARG directly.  */
21712 	      tree t = try_class_unification (tparms, targs, parm, arg,
21713 					      explain_p);
21714 	      if (!t)
21715 		{
21716 		  /* Otherwise, look for a suitable base of ARG, as below.  */
21717 		  enum template_base_result r;
21718 		  r = get_template_base (tparms, targs, parm, arg,
21719 					 explain_p, &t);
21720 		  if (!t)
21721 		    return unify_no_common_base (explain_p, r, parm, arg);
21722 		  arg = t;
21723 		}
21724 	    }
21725 	  /* ARG must be constructed from a template class or a template
21726 	     template parameter.  */
21727 	  else if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
21728 		   && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
21729 	    return unify_template_deduction_failure (explain_p, parm, arg);
21730 
21731 	  /* Deduce arguments T, i from TT<T> or TT<i>.  */
21732 	  if (unify_bound_ttp_args (tparms, targs, parm, arg, explain_p))
21733 	    return 1;
21734 
21735 	  arg = TYPE_TI_TEMPLATE (arg);
21736 
21737 	  /* Fall through to deduce template name.  */
21738 	}
21739 
21740       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
21741 	  || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
21742 	{
21743 	  /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
21744 
21745 	  /* Simple cases: Value already set, does match or doesn't.  */
21746 	  if (targ != NULL_TREE && template_args_equal (targ, arg))
21747 	    return unify_success (explain_p);
21748 	  else if (targ)
21749 	    return unify_inconsistency (explain_p, parm, targ, arg);
21750 	}
21751       else
21752 	{
21753 	  /* If PARM is `const T' and ARG is only `int', we don't have
21754 	     a match unless we are allowing additional qualification.
21755 	     If ARG is `const int' and PARM is just `T' that's OK;
21756 	     that binds `const int' to `T'.  */
21757 	  if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
21758 					 arg, parm))
21759 	    return unify_cv_qual_mismatch (explain_p, parm, arg);
21760 
21761 	  /* Consider the case where ARG is `const volatile int' and
21762 	     PARM is `const T'.  Then, T should be `volatile int'.  */
21763 	  arg = cp_build_qualified_type_real
21764 	    (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
21765 	  if (arg == error_mark_node)
21766 	    return unify_invalid (explain_p);
21767 
21768 	  /* Simple cases: Value already set, does match or doesn't.  */
21769 	  if (targ != NULL_TREE && same_type_p (targ, arg))
21770 	    return unify_success (explain_p);
21771 	  else if (targ)
21772 	    return unify_inconsistency (explain_p, parm, targ, arg);
21773 
21774 	  /* Make sure that ARG is not a variable-sized array.  (Note
21775 	     that were talking about variable-sized arrays (like
21776 	     `int[n]'), rather than arrays of unknown size (like
21777 	     `int[]').)  We'll get very confused by such a type since
21778 	     the bound of the array is not constant, and therefore
21779 	     not mangleable.  Besides, such types are not allowed in
21780 	     ISO C++, so we can do as we please here.  We do allow
21781 	     them for 'auto' deduction, since that isn't ABI-exposed.  */
21782 	  if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
21783 	    return unify_vla_arg (explain_p, arg);
21784 
21785 	  /* Strip typedefs as in convert_template_argument.  */
21786 	  arg = canonicalize_type_argument (arg, tf_none);
21787 	}
21788 
21789       /* If ARG is a parameter pack or an expansion, we cannot unify
21790 	 against it unless PARM is also a parameter pack.  */
21791       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
21792 	  && !template_parameter_pack_p (parm))
21793 	return unify_parameter_pack_mismatch (explain_p, parm, arg);
21794 
21795       /* If the argument deduction results is a METHOD_TYPE,
21796          then there is a problem.
21797          METHOD_TYPE doesn't map to any real C++ type the result of
21798 	 the deduction can not be of that type.  */
21799       if (TREE_CODE (arg) == METHOD_TYPE)
21800 	return unify_method_type_error (explain_p, arg);
21801 
21802       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
21803       return unify_success (explain_p);
21804 
21805     case TEMPLATE_PARM_INDEX:
21806       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
21807       if (error_operand_p (tparm))
21808 	return unify_invalid (explain_p);
21809 
21810       if (TEMPLATE_PARM_LEVEL (parm)
21811 	  != template_decl_level (tparm))
21812 	{
21813 	  /* The PARM is not one we're trying to unify.  Just check
21814 	     to see if it matches ARG.  */
21815 	  int result = !(TREE_CODE (arg) == TREE_CODE (parm)
21816 			 && cp_tree_equal (parm, arg));
21817 	  if (result)
21818 	    unify_expression_unequal (explain_p, parm, arg);
21819 	  return result;
21820 	}
21821 
21822       idx = TEMPLATE_PARM_IDX (parm);
21823       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
21824 
21825       if (targ)
21826 	{
21827 	  if ((strict & UNIFY_ALLOW_INTEGER)
21828 	      && TREE_TYPE (targ) && TREE_TYPE (arg)
21829 	      && CP_INTEGRAL_TYPE_P (TREE_TYPE (targ)))
21830 	    /* We're deducing from an array bound, the type doesn't matter.  */
21831 	    arg = fold_convert (TREE_TYPE (targ), arg);
21832 	  int x = !cp_tree_equal (targ, arg);
21833 	  if (x)
21834 	    unify_inconsistency (explain_p, parm, targ, arg);
21835 	  return x;
21836 	}
21837 
21838       /* [temp.deduct.type] If, in the declaration of a function template
21839 	 with a non-type template-parameter, the non-type
21840 	 template-parameter is used in an expression in the function
21841 	 parameter-list and, if the corresponding template-argument is
21842 	 deduced, the template-argument type shall match the type of the
21843 	 template-parameter exactly, except that a template-argument
21844 	 deduced from an array bound may be of any integral type.
21845 	 The non-type parameter might use already deduced type parameters.  */
21846       tparm = TREE_TYPE (parm);
21847       if (TEMPLATE_PARM_LEVEL (parm) > TMPL_ARGS_DEPTH (targs))
21848 	/* We don't have enough levels of args to do any substitution.  This
21849 	   can happen in the context of -fnew-ttp-matching.  */;
21850       else
21851 	{
21852 	  ++processing_template_decl;
21853 	  tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
21854 	  --processing_template_decl;
21855 
21856 	  if (tree a = type_uses_auto (tparm))
21857 	    {
21858 	      tparm = do_auto_deduction (tparm, arg, a, complain, adc_unify);
21859 	      if (tparm == error_mark_node)
21860 		return 1;
21861 	    }
21862 	}
21863 
21864       if (!TREE_TYPE (arg))
21865 	/* Template-parameter dependent expression.  Just accept it for now.
21866 	   It will later be processed in convert_template_argument.  */
21867 	;
21868       else if (same_type_p (non_reference (TREE_TYPE (arg)),
21869 			    non_reference (tparm)))
21870 	/* OK */;
21871       else if ((strict & UNIFY_ALLOW_INTEGER)
21872 	       && CP_INTEGRAL_TYPE_P (tparm))
21873 	/* Convert the ARG to the type of PARM; the deduced non-type
21874 	   template argument must exactly match the types of the
21875 	   corresponding parameter.  */
21876 	arg = fold (build_nop (tparm, arg));
21877       else if (uses_template_parms (tparm))
21878 	{
21879 	  /* We haven't deduced the type of this parameter yet.  */
21880 	  if (cxx_dialect >= cxx17
21881 	      /* We deduce from array bounds in try_array_deduction.  */
21882 	      && !(strict & UNIFY_ALLOW_INTEGER))
21883 	    {
21884 	      /* Deduce it from the non-type argument.  */
21885 	      tree atype = TREE_TYPE (arg);
21886 	      RECUR_AND_CHECK_FAILURE (tparms, targs,
21887 				       tparm, atype,
21888 				       UNIFY_ALLOW_NONE, explain_p);
21889 	    }
21890 	  else
21891 	    /* Try again later.  */
21892 	    return unify_success (explain_p);
21893 	}
21894       else
21895 	return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
21896 
21897       /* If ARG is a parameter pack or an expansion, we cannot unify
21898 	 against it unless PARM is also a parameter pack.  */
21899       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
21900 	  && !TEMPLATE_PARM_PARAMETER_PACK (parm))
21901 	return unify_parameter_pack_mismatch (explain_p, parm, arg);
21902 
21903       {
21904 	bool removed_attr = false;
21905 	arg = strip_typedefs_expr (arg, &removed_attr);
21906       }
21907       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
21908       return unify_success (explain_p);
21909 
21910     case PTRMEM_CST:
21911      {
21912 	/* A pointer-to-member constant can be unified only with
21913 	 another constant.  */
21914       if (TREE_CODE (arg) != PTRMEM_CST)
21915 	return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
21916 
21917       /* Just unify the class member. It would be useless (and possibly
21918 	 wrong, depending on the strict flags) to unify also
21919 	 PTRMEM_CST_CLASS, because we want to be sure that both parm and
21920 	 arg refer to the same variable, even if through different
21921 	 classes. For instance:
21922 
21923 	 struct A { int x; };
21924 	 struct B : A { };
21925 
21926 	 Unification of &A::x and &B::x must succeed.  */
21927       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
21928 		    PTRMEM_CST_MEMBER (arg), strict, explain_p);
21929      }
21930 
21931     case POINTER_TYPE:
21932       {
21933 	if (!TYPE_PTR_P (arg))
21934 	  return unify_type_mismatch (explain_p, parm, arg);
21935 
21936 	/* [temp.deduct.call]
21937 
21938 	   A can be another pointer or pointer to member type that can
21939 	   be converted to the deduced A via a qualification
21940 	   conversion (_conv.qual_).
21941 
21942 	   We pass down STRICT here rather than UNIFY_ALLOW_NONE.
21943 	   This will allow for additional cv-qualification of the
21944 	   pointed-to types if appropriate.  */
21945 
21946 	if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
21947 	  /* The derived-to-base conversion only persists through one
21948 	     level of pointers.  */
21949 	  strict |= (strict_in & UNIFY_ALLOW_DERIVED);
21950 
21951 	return unify (tparms, targs, TREE_TYPE (parm),
21952 		      TREE_TYPE (arg), strict, explain_p);
21953       }
21954 
21955     case REFERENCE_TYPE:
21956       if (TREE_CODE (arg) != REFERENCE_TYPE)
21957 	return unify_type_mismatch (explain_p, parm, arg);
21958       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
21959 		    strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
21960 
21961     case ARRAY_TYPE:
21962       if (TREE_CODE (arg) != ARRAY_TYPE)
21963 	return unify_type_mismatch (explain_p, parm, arg);
21964       if ((TYPE_DOMAIN (parm) == NULL_TREE)
21965 	  != (TYPE_DOMAIN (arg) == NULL_TREE))
21966 	return unify_type_mismatch (explain_p, parm, arg);
21967       RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
21968 			       strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
21969       if (TYPE_DOMAIN (parm) != NULL_TREE)
21970 	return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
21971 				   TYPE_DOMAIN (arg), explain_p);
21972       return unify_success (explain_p);
21973 
21974     case REAL_TYPE:
21975     case COMPLEX_TYPE:
21976     case VECTOR_TYPE:
21977     case INTEGER_TYPE:
21978     case BOOLEAN_TYPE:
21979     case ENUMERAL_TYPE:
21980     case VOID_TYPE:
21981     case NULLPTR_TYPE:
21982       if (TREE_CODE (arg) != TREE_CODE (parm))
21983 	return unify_type_mismatch (explain_p, parm, arg);
21984 
21985       /* We have already checked cv-qualification at the top of the
21986 	 function.  */
21987       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
21988 	return unify_type_mismatch (explain_p, parm, arg);
21989 
21990       /* As far as unification is concerned, this wins.	 Later checks
21991 	 will invalidate it if necessary.  */
21992       return unify_success (explain_p);
21993 
21994       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
21995       /* Type INTEGER_CST can come from ordinary constant template args.  */
21996     case INTEGER_CST:
21997       while (CONVERT_EXPR_P (arg))
21998 	arg = TREE_OPERAND (arg, 0);
21999 
22000       if (TREE_CODE (arg) != INTEGER_CST)
22001 	return unify_template_argument_mismatch (explain_p, parm, arg);
22002       return (tree_int_cst_equal (parm, arg)
22003 	      ? unify_success (explain_p)
22004 	      : unify_template_argument_mismatch (explain_p, parm, arg));
22005 
22006     case TREE_VEC:
22007       {
22008 	int i, len, argslen;
22009 	int parm_variadic_p = 0;
22010 
22011 	if (TREE_CODE (arg) != TREE_VEC)
22012 	  return unify_template_argument_mismatch (explain_p, parm, arg);
22013 
22014 	len = TREE_VEC_LENGTH (parm);
22015 	argslen = TREE_VEC_LENGTH (arg);
22016 
22017 	/* Check for pack expansions in the parameters.  */
22018 	for (i = 0; i < len; ++i)
22019 	  {
22020 	    if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
22021 	      {
22022 		if (i == len - 1)
22023 		  /* We can unify against something with a trailing
22024 		     parameter pack.  */
22025 		  parm_variadic_p = 1;
22026 		else
22027 		  /* [temp.deduct.type]/9: If the template argument list of
22028 		     P contains a pack expansion that is not the last
22029 		     template argument, the entire template argument list
22030 		     is a non-deduced context.  */
22031 		  return unify_success (explain_p);
22032 	      }
22033 	  }
22034 
22035         /* If we don't have enough arguments to satisfy the parameters
22036            (not counting the pack expression at the end), or we have
22037            too many arguments for a parameter list that doesn't end in
22038            a pack expression, we can't unify.  */
22039 	if (parm_variadic_p
22040 	    ? argslen < len - parm_variadic_p
22041 	    : argslen != len)
22042 	  return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
22043 
22044 	/* Unify all of the parameters that precede the (optional)
22045 	   pack expression.  */
22046 	for (i = 0; i < len - parm_variadic_p; ++i)
22047 	  {
22048 	    RECUR_AND_CHECK_FAILURE (tparms, targs,
22049 				     TREE_VEC_ELT (parm, i),
22050 				     TREE_VEC_ELT (arg, i),
22051 				     UNIFY_ALLOW_NONE, explain_p);
22052 	  }
22053 	if (parm_variadic_p)
22054 	  return unify_pack_expansion (tparms, targs, parm, arg,
22055 				       DEDUCE_EXACT,
22056 				       /*subr=*/true, explain_p);
22057 	return unify_success (explain_p);
22058       }
22059 
22060     case RECORD_TYPE:
22061     case UNION_TYPE:
22062       if (TREE_CODE (arg) != TREE_CODE (parm))
22063 	return unify_type_mismatch (explain_p, parm, arg);
22064 
22065       if (TYPE_PTRMEMFUNC_P (parm))
22066 	{
22067 	  if (!TYPE_PTRMEMFUNC_P (arg))
22068 	    return unify_type_mismatch (explain_p, parm, arg);
22069 
22070 	  return unify (tparms, targs,
22071 			TYPE_PTRMEMFUNC_FN_TYPE (parm),
22072 			TYPE_PTRMEMFUNC_FN_TYPE (arg),
22073 			strict, explain_p);
22074 	}
22075       else if (TYPE_PTRMEMFUNC_P (arg))
22076 	return unify_type_mismatch (explain_p, parm, arg);
22077 
22078       if (CLASSTYPE_TEMPLATE_INFO (parm))
22079 	{
22080 	  tree t = NULL_TREE;
22081 
22082 	  if (strict_in & UNIFY_ALLOW_DERIVED)
22083 	    {
22084 	      /* First, we try to unify the PARM and ARG directly.  */
22085 	      t = try_class_unification (tparms, targs,
22086 					 parm, arg, explain_p);
22087 
22088 	      if (!t)
22089 		{
22090 		  /* Fallback to the special case allowed in
22091 		     [temp.deduct.call]:
22092 
22093 		       If P is a class, and P has the form
22094 		       template-id, then A can be a derived class of
22095 		       the deduced A.  Likewise, if P is a pointer to
22096 		       a class of the form template-id, A can be a
22097 		       pointer to a derived class pointed to by the
22098 		       deduced A.  */
22099 		  enum template_base_result r;
22100 		  r = get_template_base (tparms, targs, parm, arg,
22101 					 explain_p, &t);
22102 
22103 		  if (!t)
22104 		    {
22105 		      /* Don't give the derived diagnostic if we're
22106 			 already dealing with the same template.  */
22107 		      bool same_template
22108 			= (CLASSTYPE_TEMPLATE_INFO (arg)
22109 			   && (CLASSTYPE_TI_TEMPLATE (parm)
22110 			       == CLASSTYPE_TI_TEMPLATE (arg)));
22111 		      return unify_no_common_base (explain_p && !same_template,
22112 						   r, parm, arg);
22113 		    }
22114 		}
22115 	    }
22116 	  else if (CLASSTYPE_TEMPLATE_INFO (arg)
22117 		   && (CLASSTYPE_TI_TEMPLATE (parm)
22118 		       == CLASSTYPE_TI_TEMPLATE (arg)))
22119 	    /* Perhaps PARM is something like S<U> and ARG is S<int>.
22120 	       Then, we should unify `int' and `U'.  */
22121 	    t = arg;
22122 	  else
22123 	    /* There's no chance of unification succeeding.  */
22124 	    return unify_type_mismatch (explain_p, parm, arg);
22125 
22126 	  return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
22127 			CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
22128 	}
22129       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
22130 	return unify_type_mismatch (explain_p, parm, arg);
22131       return unify_success (explain_p);
22132 
22133     case METHOD_TYPE:
22134     case FUNCTION_TYPE:
22135       {
22136 	unsigned int nargs;
22137 	tree *args;
22138 	tree a;
22139 	unsigned int i;
22140 
22141 	if (TREE_CODE (arg) != TREE_CODE (parm))
22142 	  return unify_type_mismatch (explain_p, parm, arg);
22143 
22144 	/* CV qualifications for methods can never be deduced, they must
22145 	   match exactly.  We need to check them explicitly here,
22146 	   because type_unification_real treats them as any other
22147 	   cv-qualified parameter.  */
22148 	if (TREE_CODE (parm) == METHOD_TYPE
22149 	    && (!check_cv_quals_for_unify
22150 		(UNIFY_ALLOW_NONE,
22151 		 class_of_this_parm (arg),
22152 		 class_of_this_parm (parm))))
22153 	  return unify_cv_qual_mismatch (explain_p, parm, arg);
22154 	if (TREE_CODE (arg) == FUNCTION_TYPE
22155 	    && type_memfn_quals (parm) != type_memfn_quals (arg))
22156 	  return unify_cv_qual_mismatch (explain_p, parm, arg);
22157 	if (type_memfn_rqual (parm) != type_memfn_rqual (arg))
22158 	  return unify_type_mismatch (explain_p, parm, arg);
22159 
22160 	RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
22161 				 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
22162 
22163 	nargs = list_length (TYPE_ARG_TYPES (arg));
22164 	args = XALLOCAVEC (tree, nargs);
22165 	for (a = TYPE_ARG_TYPES (arg), i = 0;
22166 	     a != NULL_TREE && a != void_list_node;
22167 	     a = TREE_CHAIN (a), ++i)
22168 	  args[i] = TREE_VALUE (a);
22169 	nargs = i;
22170 
22171 	if (type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
22172 				   args, nargs, 1, DEDUCE_EXACT,
22173 				   LOOKUP_NORMAL, NULL, explain_p))
22174 	  return 1;
22175 
22176 	if (flag_noexcept_type)
22177 	  {
22178 	    tree pspec = TYPE_RAISES_EXCEPTIONS (parm);
22179 	    tree aspec = canonical_eh_spec (TYPE_RAISES_EXCEPTIONS (arg));
22180 	    if (pspec == NULL_TREE) pspec = noexcept_false_spec;
22181 	    if (aspec == NULL_TREE) aspec = noexcept_false_spec;
22182 	    if (TREE_PURPOSE (pspec) && TREE_PURPOSE (aspec)
22183 		&& uses_template_parms (TREE_PURPOSE (pspec)))
22184 	      RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_PURPOSE (pspec),
22185 				       TREE_PURPOSE (aspec),
22186 				       UNIFY_ALLOW_NONE, explain_p);
22187 	    else if (nothrow_spec_p (pspec) && !nothrow_spec_p (aspec))
22188 	      return unify_type_mismatch (explain_p, parm, arg);
22189 	  }
22190 
22191 	return 0;
22192       }
22193 
22194     case OFFSET_TYPE:
22195       /* Unify a pointer to member with a pointer to member function, which
22196 	 deduces the type of the member as a function type. */
22197       if (TYPE_PTRMEMFUNC_P (arg))
22198 	{
22199 	  /* Check top-level cv qualifiers */
22200 	  if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
22201 	    return unify_cv_qual_mismatch (explain_p, parm, arg);
22202 
22203 	  RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
22204 				   TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
22205 				   UNIFY_ALLOW_NONE, explain_p);
22206 
22207 	  /* Determine the type of the function we are unifying against. */
22208 	  tree fntype = static_fn_type (arg);
22209 
22210 	  return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
22211 	}
22212 
22213       if (TREE_CODE (arg) != OFFSET_TYPE)
22214 	return unify_type_mismatch (explain_p, parm, arg);
22215       RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
22216 			       TYPE_OFFSET_BASETYPE (arg),
22217 			       UNIFY_ALLOW_NONE, explain_p);
22218       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
22219 		    strict, explain_p);
22220 
22221     case CONST_DECL:
22222       if (DECL_TEMPLATE_PARM_P (parm))
22223 	return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
22224       if (arg != scalar_constant_value (parm))
22225 	return unify_template_argument_mismatch (explain_p, parm, arg);
22226       return unify_success (explain_p);
22227 
22228     case FIELD_DECL:
22229     case TEMPLATE_DECL:
22230       /* Matched cases are handled by the ARG == PARM test above.  */
22231       return unify_template_argument_mismatch (explain_p, parm, arg);
22232 
22233     case VAR_DECL:
22234       /* We might get a variable as a non-type template argument in parm if the
22235 	 corresponding parameter is type-dependent.  Make any necessary
22236 	 adjustments based on whether arg is a reference.  */
22237       if (CONSTANT_CLASS_P (arg))
22238 	parm = fold_non_dependent_expr (parm);
22239       else if (REFERENCE_REF_P (arg))
22240 	{
22241 	  tree sub = TREE_OPERAND (arg, 0);
22242 	  STRIP_NOPS (sub);
22243 	  if (TREE_CODE (sub) == ADDR_EXPR)
22244 	    arg = TREE_OPERAND (sub, 0);
22245 	}
22246       /* Now use the normal expression code to check whether they match.  */
22247       goto expr;
22248 
22249     case TYPE_ARGUMENT_PACK:
22250     case NONTYPE_ARGUMENT_PACK:
22251       return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
22252 		    ARGUMENT_PACK_ARGS (arg), strict, explain_p);
22253 
22254     case TYPEOF_TYPE:
22255     case DECLTYPE_TYPE:
22256     case UNDERLYING_TYPE:
22257       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
22258 	 or UNDERLYING_TYPE nodes.  */
22259       return unify_success (explain_p);
22260 
22261     case ERROR_MARK:
22262       /* Unification fails if we hit an error node.  */
22263       return unify_invalid (explain_p);
22264 
22265     case INDIRECT_REF:
22266       if (REFERENCE_REF_P (parm))
22267 	{
22268 	  bool pexp = PACK_EXPANSION_P (arg);
22269 	  if (pexp)
22270 	    arg = PACK_EXPANSION_PATTERN (arg);
22271 	  if (REFERENCE_REF_P (arg))
22272 	    arg = TREE_OPERAND (arg, 0);
22273 	  if (pexp)
22274 	    arg = make_pack_expansion (arg, complain);
22275 	  return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
22276 			strict, explain_p);
22277 	}
22278       /* FALLTHRU */
22279 
22280     default:
22281       /* An unresolved overload is a nondeduced context.  */
22282       if (is_overloaded_fn (parm) || type_unknown_p (parm))
22283 	return unify_success (explain_p);
22284       gcc_assert (EXPR_P (parm) || TREE_CODE (parm) == TRAIT_EXPR);
22285     expr:
22286       /* We must be looking at an expression.  This can happen with
22287 	 something like:
22288 
22289 	   template <int I>
22290 	   void foo(S<I>, S<I + 2>);
22291 
22292 	 This is a "nondeduced context":
22293 
22294 	   [deduct.type]
22295 
22296 	   The nondeduced contexts are:
22297 
22298 	   --A type that is a template-id in which one or more of
22299 	     the template-arguments is an expression that references
22300 	     a template-parameter.
22301 
22302 	 In these cases, we assume deduction succeeded, but don't
22303 	 actually infer any unifications.  */
22304 
22305       if (!uses_template_parms (parm)
22306 	  && !template_args_equal (parm, arg))
22307 	return unify_expression_unequal (explain_p, parm, arg);
22308       else
22309 	return unify_success (explain_p);
22310     }
22311 }
22312 #undef RECUR_AND_CHECK_FAILURE
22313 
22314 /* Note that DECL can be defined in this translation unit, if
22315    required.  */
22316 
22317 static void
mark_definable(tree decl)22318 mark_definable (tree decl)
22319 {
22320   tree clone;
22321   DECL_NOT_REALLY_EXTERN (decl) = 1;
22322   FOR_EACH_CLONE (clone, decl)
22323     DECL_NOT_REALLY_EXTERN (clone) = 1;
22324 }
22325 
22326 /* Called if RESULT is explicitly instantiated, or is a member of an
22327    explicitly instantiated class.  */
22328 
22329 void
mark_decl_instantiated(tree result,int extern_p)22330 mark_decl_instantiated (tree result, int extern_p)
22331 {
22332   SET_DECL_EXPLICIT_INSTANTIATION (result);
22333 
22334   /* If this entity has already been written out, it's too late to
22335      make any modifications.  */
22336   if (TREE_ASM_WRITTEN (result))
22337     return;
22338 
22339   /* For anonymous namespace we don't need to do anything.  */
22340   if (decl_anon_ns_mem_p (result))
22341     {
22342       gcc_assert (!TREE_PUBLIC (result));
22343       return;
22344     }
22345 
22346   if (TREE_CODE (result) != FUNCTION_DECL)
22347     /* The TREE_PUBLIC flag for function declarations will have been
22348        set correctly by tsubst.  */
22349     TREE_PUBLIC (result) = 1;
22350 
22351   /* This might have been set by an earlier implicit instantiation.  */
22352   DECL_COMDAT (result) = 0;
22353 
22354   if (extern_p)
22355     DECL_NOT_REALLY_EXTERN (result) = 0;
22356   else
22357     {
22358       mark_definable (result);
22359       mark_needed (result);
22360       /* Always make artificials weak.  */
22361       if (DECL_ARTIFICIAL (result) && flag_weak)
22362 	comdat_linkage (result);
22363       /* For WIN32 we also want to put explicit instantiations in
22364 	 linkonce sections.  */
22365       else if (TREE_PUBLIC (result))
22366 	maybe_make_one_only (result);
22367     }
22368 
22369   /* If EXTERN_P, then this function will not be emitted -- unless
22370      followed by an explicit instantiation, at which point its linkage
22371      will be adjusted.  If !EXTERN_P, then this function will be
22372      emitted here.  In neither circumstance do we want
22373      import_export_decl to adjust the linkage.  */
22374   DECL_INTERFACE_KNOWN (result) = 1;
22375 }
22376 
22377 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
22378    important template arguments.  If any are missing, we check whether
22379    they're important by using error_mark_node for substituting into any
22380    args that were used for partial ordering (the ones between ARGS and END)
22381    and seeing if it bubbles up.  */
22382 
22383 static bool
check_undeduced_parms(tree targs,tree args,tree end)22384 check_undeduced_parms (tree targs, tree args, tree end)
22385 {
22386   bool found = false;
22387   int i;
22388   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
22389     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
22390       {
22391 	found = true;
22392 	TREE_VEC_ELT (targs, i) = error_mark_node;
22393       }
22394   if (found)
22395     {
22396       tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
22397       if (substed == error_mark_node)
22398 	return true;
22399     }
22400   return false;
22401 }
22402 
22403 /* Given two function templates PAT1 and PAT2, return:
22404 
22405    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
22406    -1 if PAT2 is more specialized than PAT1.
22407    0 if neither is more specialized.
22408 
22409    LEN indicates the number of parameters we should consider
22410    (defaulted parameters should not be considered).
22411 
22412    The 1998 std underspecified function template partial ordering, and
22413    DR214 addresses the issue.  We take pairs of arguments, one from
22414    each of the templates, and deduce them against each other.  One of
22415    the templates will be more specialized if all the *other*
22416    template's arguments deduce against its arguments and at least one
22417    of its arguments *does* *not* deduce against the other template's
22418    corresponding argument.  Deduction is done as for class templates.
22419    The arguments used in deduction have reference and top level cv
22420    qualifiers removed.  Iff both arguments were originally reference
22421    types *and* deduction succeeds in both directions, an lvalue reference
22422    wins against an rvalue reference and otherwise the template
22423    with the more cv-qualified argument wins for that pairing (if
22424    neither is more cv-qualified, they both are equal).  Unlike regular
22425    deduction, after all the arguments have been deduced in this way,
22426    we do *not* verify the deduced template argument values can be
22427    substituted into non-deduced contexts.
22428 
22429    The logic can be a bit confusing here, because we look at deduce1 and
22430    targs1 to see if pat2 is at least as specialized, and vice versa; if we
22431    can find template arguments for pat1 to make arg1 look like arg2, that
22432    means that arg2 is at least as specialized as arg1.  */
22433 
22434 int
more_specialized_fn(tree pat1,tree pat2,int len)22435 more_specialized_fn (tree pat1, tree pat2, int len)
22436 {
22437   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
22438   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
22439   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
22440   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
22441   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
22442   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
22443   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
22444   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
22445   tree origs1, origs2;
22446   bool lose1 = false;
22447   bool lose2 = false;
22448 
22449   /* Remove the this parameter from non-static member functions.  If
22450      one is a non-static member function and the other is not a static
22451      member function, remove the first parameter from that function
22452      also.  This situation occurs for operator functions where we
22453      locate both a member function (with this pointer) and non-member
22454      operator (with explicit first operand).  */
22455   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
22456     {
22457       len--; /* LEN is the number of significant arguments for DECL1 */
22458       args1 = TREE_CHAIN (args1);
22459       if (!DECL_STATIC_FUNCTION_P (decl2))
22460 	args2 = TREE_CHAIN (args2);
22461     }
22462   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
22463     {
22464       args2 = TREE_CHAIN (args2);
22465       if (!DECL_STATIC_FUNCTION_P (decl1))
22466 	{
22467 	  len--;
22468 	  args1 = TREE_CHAIN (args1);
22469 	}
22470     }
22471 
22472   /* If only one is a conversion operator, they are unordered.  */
22473   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
22474     return 0;
22475 
22476   /* Consider the return type for a conversion function */
22477   if (DECL_CONV_FN_P (decl1))
22478     {
22479       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
22480       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
22481       len++;
22482     }
22483 
22484   processing_template_decl++;
22485 
22486   origs1 = args1;
22487   origs2 = args2;
22488 
22489   while (len--
22490 	 /* Stop when an ellipsis is seen.  */
22491 	 && args1 != NULL_TREE && args2 != NULL_TREE)
22492     {
22493       tree arg1 = TREE_VALUE (args1);
22494       tree arg2 = TREE_VALUE (args2);
22495       int deduce1, deduce2;
22496       int quals1 = -1;
22497       int quals2 = -1;
22498       int ref1 = 0;
22499       int ref2 = 0;
22500 
22501       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
22502           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
22503         {
22504           /* When both arguments are pack expansions, we need only
22505              unify the patterns themselves.  */
22506           arg1 = PACK_EXPANSION_PATTERN (arg1);
22507           arg2 = PACK_EXPANSION_PATTERN (arg2);
22508 
22509           /* This is the last comparison we need to do.  */
22510           len = 0;
22511         }
22512 
22513       /* DR 1847: If a particular P contains no template-parameters that
22514 	 participate in template argument deduction, that P is not used to
22515 	 determine the ordering.  */
22516       if (!uses_deducible_template_parms (arg1)
22517 	  && !uses_deducible_template_parms (arg2))
22518 	goto next;
22519 
22520       if (TREE_CODE (arg1) == REFERENCE_TYPE)
22521 	{
22522 	  ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
22523 	  arg1 = TREE_TYPE (arg1);
22524 	  quals1 = cp_type_quals (arg1);
22525 	}
22526 
22527       if (TREE_CODE (arg2) == REFERENCE_TYPE)
22528 	{
22529 	  ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
22530 	  arg2 = TREE_TYPE (arg2);
22531 	  quals2 = cp_type_quals (arg2);
22532 	}
22533 
22534       arg1 = TYPE_MAIN_VARIANT (arg1);
22535       arg2 = TYPE_MAIN_VARIANT (arg2);
22536 
22537       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
22538         {
22539           int i, len2 = remaining_arguments (args2);
22540           tree parmvec = make_tree_vec (1);
22541           tree argvec = make_tree_vec (len2);
22542           tree ta = args2;
22543 
22544           /* Setup the parameter vector, which contains only ARG1.  */
22545           TREE_VEC_ELT (parmvec, 0) = arg1;
22546 
22547           /* Setup the argument vector, which contains the remaining
22548              arguments.  */
22549           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
22550             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
22551 
22552           deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
22553 					   argvec, DEDUCE_EXACT,
22554 					   /*subr=*/true, /*explain_p=*/false)
22555 		     == 0);
22556 
22557           /* We cannot deduce in the other direction, because ARG1 is
22558              a pack expansion but ARG2 is not.  */
22559           deduce2 = 0;
22560         }
22561       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
22562         {
22563           int i, len1 = remaining_arguments (args1);
22564           tree parmvec = make_tree_vec (1);
22565           tree argvec = make_tree_vec (len1);
22566           tree ta = args1;
22567 
22568           /* Setup the parameter vector, which contains only ARG1.  */
22569           TREE_VEC_ELT (parmvec, 0) = arg2;
22570 
22571           /* Setup the argument vector, which contains the remaining
22572              arguments.  */
22573           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
22574             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
22575 
22576           deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
22577 					   argvec, DEDUCE_EXACT,
22578 					   /*subr=*/true, /*explain_p=*/false)
22579 		     == 0);
22580 
22581           /* We cannot deduce in the other direction, because ARG2 is
22582              a pack expansion but ARG1 is not.*/
22583           deduce1 = 0;
22584         }
22585 
22586       else
22587         {
22588           /* The normal case, where neither argument is a pack
22589              expansion.  */
22590           deduce1 = (unify (tparms1, targs1, arg1, arg2,
22591 			    UNIFY_ALLOW_NONE, /*explain_p=*/false)
22592 		     == 0);
22593           deduce2 = (unify (tparms2, targs2, arg2, arg1,
22594 			    UNIFY_ALLOW_NONE, /*explain_p=*/false)
22595 		     == 0);
22596         }
22597 
22598       /* If we couldn't deduce arguments for tparms1 to make arg1 match
22599 	 arg2, then arg2 is not as specialized as arg1.  */
22600       if (!deduce1)
22601 	lose2 = true;
22602       if (!deduce2)
22603 	lose1 = true;
22604 
22605       /* "If, for a given type, deduction succeeds in both directions
22606 	 (i.e., the types are identical after the transformations above)
22607 	 and both P and A were reference types (before being replaced with
22608 	 the type referred to above):
22609 	 - if the type from the argument template was an lvalue reference and
22610 	 the type from the parameter template was not, the argument type is
22611 	 considered to be more specialized than the other; otherwise,
22612 	 - if the type from the argument template is more cv-qualified
22613 	 than the type from the parameter template (as described above),
22614 	 the argument type is considered to be more specialized than the other;
22615 	 otherwise,
22616 	 - neither type is more specialized than the other."  */
22617 
22618       if (deduce1 && deduce2)
22619 	{
22620 	  if (ref1 && ref2 && ref1 != ref2)
22621 	    {
22622 	      if (ref1 > ref2)
22623 		lose1 = true;
22624 	      else
22625 		lose2 = true;
22626 	    }
22627 	  else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
22628 	    {
22629 	      if ((quals1 & quals2) == quals2)
22630 		lose2 = true;
22631 	      if ((quals1 & quals2) == quals1)
22632 		lose1 = true;
22633 	    }
22634 	}
22635 
22636       if (lose1 && lose2)
22637 	/* We've failed to deduce something in either direction.
22638 	   These must be unordered.  */
22639 	break;
22640 
22641     next:
22642 
22643       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
22644           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
22645         /* We have already processed all of the arguments in our
22646            handing of the pack expansion type.  */
22647         len = 0;
22648 
22649       args1 = TREE_CHAIN (args1);
22650       args2 = TREE_CHAIN (args2);
22651     }
22652 
22653   /* "In most cases, all template parameters must have values in order for
22654      deduction to succeed, but for partial ordering purposes a template
22655      parameter may remain without a value provided it is not used in the
22656      types being used for partial ordering."
22657 
22658      Thus, if we are missing any of the targs1 we need to substitute into
22659      origs1, then pat2 is not as specialized as pat1.  This can happen when
22660      there is a nondeduced context.  */
22661   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
22662     lose2 = true;
22663   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
22664     lose1 = true;
22665 
22666   processing_template_decl--;
22667 
22668   /* If both deductions succeed, the partial ordering selects the more
22669      constrained template.  */
22670   if (!lose1 && !lose2)
22671     {
22672       tree c1 = get_constraints (DECL_TEMPLATE_RESULT (pat1));
22673       tree c2 = get_constraints (DECL_TEMPLATE_RESULT (pat2));
22674       lose1 = !subsumes_constraints (c1, c2);
22675       lose2 = !subsumes_constraints (c2, c1);
22676     }
22677 
22678   /* All things being equal, if the next argument is a pack expansion
22679      for one function but not for the other, prefer the
22680      non-variadic function.  FIXME this is bogus; see c++/41958.  */
22681   if (lose1 == lose2
22682       && args1 && TREE_VALUE (args1)
22683       && args2 && TREE_VALUE (args2))
22684     {
22685       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
22686       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
22687     }
22688 
22689   if (lose1 == lose2)
22690     return 0;
22691   else if (!lose1)
22692     return 1;
22693   else
22694     return -1;
22695 }
22696 
22697 /* Determine which of two partial specializations of TMPL is more
22698    specialized.
22699 
22700    PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
22701    to the first partial specialization.  The TREE_PURPOSE is the
22702    innermost set of template parameters for the partial
22703    specialization.  PAT2 is similar, but for the second template.
22704 
22705    Return 1 if the first partial specialization is more specialized;
22706    -1 if the second is more specialized; 0 if neither is more
22707    specialized.
22708 
22709    See [temp.class.order] for information about determining which of
22710    two templates is more specialized.  */
22711 
22712 static int
more_specialized_partial_spec(tree tmpl,tree pat1,tree pat2)22713 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
22714 {
22715   tree targs;
22716   int winner = 0;
22717   bool any_deductions = false;
22718 
22719   tree tmpl1 = TREE_VALUE (pat1);
22720   tree tmpl2 = TREE_VALUE (pat2);
22721   tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
22722   tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
22723 
22724   /* Just like what happens for functions, if we are ordering between
22725      different template specializations, we may encounter dependent
22726      types in the arguments, and we need our dependency check functions
22727      to behave correctly.  */
22728   ++processing_template_decl;
22729   targs = get_partial_spec_bindings (tmpl, tmpl1, specargs2);
22730   if (targs)
22731     {
22732       --winner;
22733       any_deductions = true;
22734     }
22735 
22736   targs = get_partial_spec_bindings (tmpl, tmpl2, specargs1);
22737   if (targs)
22738     {
22739       ++winner;
22740       any_deductions = true;
22741     }
22742   --processing_template_decl;
22743 
22744   /* If both deductions succeed, the partial ordering selects the more
22745      constrained template.  */
22746   if (!winner && any_deductions)
22747     return more_constrained (tmpl1, tmpl2);
22748 
22749   /* In the case of a tie where at least one of the templates
22750      has a parameter pack at the end, the template with the most
22751      non-packed parameters wins.  */
22752   if (winner == 0
22753       && any_deductions
22754       && (template_args_variadic_p (TREE_PURPOSE (pat1))
22755           || template_args_variadic_p (TREE_PURPOSE (pat2))))
22756     {
22757       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
22758       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
22759       int len1 = TREE_VEC_LENGTH (args1);
22760       int len2 = TREE_VEC_LENGTH (args2);
22761 
22762       /* We don't count the pack expansion at the end.  */
22763       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
22764         --len1;
22765       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
22766         --len2;
22767 
22768       if (len1 > len2)
22769         return 1;
22770       else if (len1 < len2)
22771         return -1;
22772     }
22773 
22774   return winner;
22775 }
22776 
22777 /* Return the template arguments that will produce the function signature
22778    DECL from the function template FN, with the explicit template
22779    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
22780    also match.  Return NULL_TREE if no satisfactory arguments could be
22781    found.  */
22782 
22783 static tree
get_bindings(tree fn,tree decl,tree explicit_args,bool check_rettype)22784 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
22785 {
22786   int ntparms = DECL_NTPARMS (fn);
22787   tree targs = make_tree_vec (ntparms);
22788   tree decl_type = TREE_TYPE (decl);
22789   tree decl_arg_types;
22790   tree *args;
22791   unsigned int nargs, ix;
22792   tree arg;
22793 
22794   gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
22795 
22796   /* Never do unification on the 'this' parameter.  */
22797   decl_arg_types = skip_artificial_parms_for (decl,
22798 					      TYPE_ARG_TYPES (decl_type));
22799 
22800   nargs = list_length (decl_arg_types);
22801   args = XALLOCAVEC (tree, nargs);
22802   for (arg = decl_arg_types, ix = 0;
22803        arg != NULL_TREE && arg != void_list_node;
22804        arg = TREE_CHAIN (arg), ++ix)
22805     args[ix] = TREE_VALUE (arg);
22806 
22807   if (fn_type_unification (fn, explicit_args, targs,
22808 			   args, ix,
22809 			   (check_rettype || DECL_CONV_FN_P (fn)
22810 			    ? TREE_TYPE (decl_type) : NULL_TREE),
22811 			   DEDUCE_EXACT, LOOKUP_NORMAL, /*explain_p=*/false,
22812 			   /*decltype*/false)
22813       == error_mark_node)
22814     return NULL_TREE;
22815 
22816   return targs;
22817 }
22818 
22819 /* Return the innermost template arguments that, when applied to a partial
22820    specialization SPEC_TMPL of TMPL, yield the ARGS.
22821 
22822    For example, suppose we have:
22823 
22824      template <class T, class U> struct S {};
22825      template <class T> struct S<T*, int> {};
22826 
22827    Then, suppose we want to get `S<double*, int>'.  SPEC_TMPL will be the
22828    partial specialization and the ARGS will be {double*, int}.  The resulting
22829    vector will be {double}, indicating that `T' is bound to `double'.  */
22830 
22831 static tree
get_partial_spec_bindings(tree tmpl,tree spec_tmpl,tree args)22832 get_partial_spec_bindings (tree tmpl, tree spec_tmpl, tree args)
22833 {
22834   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
22835   tree spec_args
22836     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (spec_tmpl)));
22837   int i, ntparms = TREE_VEC_LENGTH (tparms);
22838   tree deduced_args;
22839   tree innermost_deduced_args;
22840 
22841   innermost_deduced_args = make_tree_vec (ntparms);
22842   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
22843     {
22844       deduced_args = copy_node (args);
22845       SET_TMPL_ARGS_LEVEL (deduced_args,
22846 			   TMPL_ARGS_DEPTH (deduced_args),
22847 			   innermost_deduced_args);
22848     }
22849   else
22850     deduced_args = innermost_deduced_args;
22851 
22852   bool tried_array_deduction = (cxx_dialect < cxx17);
22853  again:
22854   if (unify (tparms, deduced_args,
22855 	     INNERMOST_TEMPLATE_ARGS (spec_args),
22856 	     INNERMOST_TEMPLATE_ARGS (args),
22857 	     UNIFY_ALLOW_NONE, /*explain_p=*/false))
22858     return NULL_TREE;
22859 
22860   for (i =  0; i < ntparms; ++i)
22861     if (! TREE_VEC_ELT (innermost_deduced_args, i))
22862       {
22863 	if (!tried_array_deduction)
22864 	  {
22865 	    try_array_deduction (tparms, innermost_deduced_args,
22866 				 INNERMOST_TEMPLATE_ARGS (spec_args));
22867 	    tried_array_deduction = true;
22868 	    if (TREE_VEC_ELT (innermost_deduced_args, i))
22869 	      goto again;
22870 	  }
22871 	return NULL_TREE;
22872       }
22873 
22874   if (!push_tinst_level (spec_tmpl, deduced_args))
22875     {
22876       excessive_deduction_depth = true;
22877       return NULL_TREE;
22878     }
22879 
22880   /* Verify that nondeduced template arguments agree with the type
22881      obtained from argument deduction.
22882 
22883      For example:
22884 
22885        struct A { typedef int X; };
22886        template <class T, class U> struct C {};
22887        template <class T> struct C<T, typename T::X> {};
22888 
22889      Then with the instantiation `C<A, int>', we can deduce that
22890      `T' is `A' but unify () does not check whether `typename T::X'
22891      is `int'.  */
22892   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
22893 
22894   if (spec_args != error_mark_node)
22895     spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
22896 				       INNERMOST_TEMPLATE_ARGS (spec_args),
22897 				       tmpl, tf_none, false, false);
22898 
22899   pop_tinst_level ();
22900 
22901   if (spec_args == error_mark_node
22902       /* We only need to check the innermost arguments; the other
22903 	 arguments will always agree.  */
22904       || !comp_template_args_porder (INNERMOST_TEMPLATE_ARGS (spec_args),
22905 				     INNERMOST_TEMPLATE_ARGS (args)))
22906     return NULL_TREE;
22907 
22908   /* Now that we have bindings for all of the template arguments,
22909      ensure that the arguments deduced for the template template
22910      parameters have compatible template parameter lists.  See the use
22911      of template_template_parm_bindings_ok_p in fn_type_unification
22912      for more information.  */
22913   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
22914     return NULL_TREE;
22915 
22916   return deduced_args;
22917 }
22918 
22919 // Compare two function templates T1 and T2 by deducing bindings
22920 // from one against the other. If both deductions succeed, compare
22921 // constraints to see which is more constrained.
22922 static int
more_specialized_inst(tree t1,tree t2)22923 more_specialized_inst (tree t1, tree t2)
22924 {
22925   int fate = 0;
22926   int count = 0;
22927 
22928   if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
22929     {
22930       --fate;
22931       ++count;
22932     }
22933 
22934   if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
22935     {
22936       ++fate;
22937       ++count;
22938     }
22939 
22940   // If both deductions succeed, then one may be more constrained.
22941   if (count == 2 && fate == 0)
22942     fate = more_constrained (t1, t2);
22943 
22944   return fate;
22945 }
22946 
22947 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
22948    Return the TREE_LIST node with the most specialized template, if
22949    any.  If there is no most specialized template, the error_mark_node
22950    is returned.
22951 
22952    Note that this function does not look at, or modify, the
22953    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
22954    returned is one of the elements of INSTANTIATIONS, callers may
22955    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
22956    and retrieve it from the value returned.  */
22957 
22958 tree
most_specialized_instantiation(tree templates)22959 most_specialized_instantiation (tree templates)
22960 {
22961   tree fn, champ;
22962 
22963   ++processing_template_decl;
22964 
22965   champ = templates;
22966   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
22967     {
22968       gcc_assert (TREE_VALUE (champ) != TREE_VALUE (fn));
22969       int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
22970       if (fate == -1)
22971 	champ = fn;
22972       else if (!fate)
22973 	{
22974 	  /* Equally specialized, move to next function.  If there
22975 	     is no next function, nothing's most specialized.  */
22976 	  fn = TREE_CHAIN (fn);
22977 	  champ = fn;
22978 	  if (!fn)
22979 	    break;
22980 	}
22981     }
22982 
22983   if (champ)
22984     /* Now verify that champ is better than everything earlier in the
22985        instantiation list.  */
22986     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
22987       if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
22988       {
22989         champ = NULL_TREE;
22990         break;
22991       }
22992     }
22993 
22994   processing_template_decl--;
22995 
22996   if (!champ)
22997     return error_mark_node;
22998 
22999   return champ;
23000 }
23001 
23002 /* If DECL is a specialization of some template, return the most
23003    general such template.  Otherwise, returns NULL_TREE.
23004 
23005    For example, given:
23006 
23007      template <class T> struct S { template <class U> void f(U); };
23008 
23009    if TMPL is `template <class U> void S<int>::f(U)' this will return
23010    the full template.  This function will not trace past partial
23011    specializations, however.  For example, given in addition:
23012 
23013      template <class T> struct S<T*> { template <class U> void f(U); };
23014 
23015    if TMPL is `template <class U> void S<int*>::f(U)' this will return
23016    `template <class T> template <class U> S<T*>::f(U)'.  */
23017 
23018 tree
most_general_template(tree decl)23019 most_general_template (tree decl)
23020 {
23021   if (TREE_CODE (decl) != TEMPLATE_DECL)
23022     {
23023       if (tree tinfo = get_template_info (decl))
23024 	decl = TI_TEMPLATE (tinfo);
23025       /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
23026 	 template friend, or a FIELD_DECL for a capture pack.  */
23027       if (TREE_CODE (decl) != TEMPLATE_DECL)
23028 	return NULL_TREE;
23029     }
23030 
23031   /* Look for more and more general templates.  */
23032   while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
23033     {
23034       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
23035 	 (See cp-tree.h for details.)  */
23036       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
23037 	break;
23038 
23039       if (CLASS_TYPE_P (TREE_TYPE (decl))
23040 	  && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
23041 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
23042 	break;
23043 
23044       /* Stop if we run into an explicitly specialized class template.  */
23045       if (!DECL_NAMESPACE_SCOPE_P (decl)
23046 	  && DECL_CONTEXT (decl)
23047 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
23048 	break;
23049 
23050       decl = DECL_TI_TEMPLATE (decl);
23051     }
23052 
23053   return decl;
23054 }
23055 
23056 /* Return the most specialized of the template partial specializations
23057    which can produce TARGET, a specialization of some class or variable
23058    template.  The value returned is actually a TREE_LIST; the TREE_VALUE is
23059    a TEMPLATE_DECL node corresponding to the partial specialization, while
23060    the TREE_PURPOSE is the set of template arguments that must be
23061    substituted into the template pattern in order to generate TARGET.
23062 
23063    If the choice of partial specialization is ambiguous, a diagnostic
23064    is issued, and the error_mark_node is returned.  If there are no
23065    partial specializations matching TARGET, then NULL_TREE is
23066    returned, indicating that the primary template should be used.  */
23067 
23068 static tree
most_specialized_partial_spec(tree target,tsubst_flags_t complain)23069 most_specialized_partial_spec (tree target, tsubst_flags_t complain)
23070 {
23071   tree list = NULL_TREE;
23072   tree t;
23073   tree champ;
23074   int fate;
23075   bool ambiguous_p;
23076   tree outer_args = NULL_TREE;
23077   tree tmpl, args;
23078 
23079   if (TYPE_P (target))
23080     {
23081       tree tinfo = CLASSTYPE_TEMPLATE_INFO (target);
23082       tmpl = TI_TEMPLATE (tinfo);
23083       args = TI_ARGS (tinfo);
23084     }
23085   else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
23086     {
23087       tmpl = TREE_OPERAND (target, 0);
23088       args = TREE_OPERAND (target, 1);
23089     }
23090   else if (VAR_P (target))
23091     {
23092       tree tinfo = DECL_TEMPLATE_INFO (target);
23093       tmpl = TI_TEMPLATE (tinfo);
23094       args = TI_ARGS (tinfo);
23095     }
23096   else
23097     gcc_unreachable ();
23098 
23099   tree main_tmpl = most_general_template (tmpl);
23100 
23101   /* For determining which partial specialization to use, only the
23102      innermost args are interesting.  */
23103   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
23104     {
23105       outer_args = strip_innermost_template_args (args, 1);
23106       args = INNERMOST_TEMPLATE_ARGS (args);
23107     }
23108 
23109   /* The caller hasn't called push_to_top_level yet, but we need
23110      get_partial_spec_bindings to be done in non-template context so that we'll
23111      fully resolve everything.  */
23112   processing_template_decl_sentinel ptds;
23113 
23114   for (t = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl); t; t = TREE_CHAIN (t))
23115     {
23116       tree spec_args;
23117       tree spec_tmpl = TREE_VALUE (t);
23118 
23119       if (outer_args)
23120 	{
23121 	  /* Substitute in the template args from the enclosing class.  */
23122 	  ++processing_template_decl;
23123 	  spec_tmpl = tsubst (spec_tmpl, outer_args, tf_none, NULL_TREE);
23124 	  --processing_template_decl;
23125 	}
23126 
23127       if (spec_tmpl == error_mark_node)
23128 	return error_mark_node;
23129 
23130       spec_args = get_partial_spec_bindings (tmpl, spec_tmpl, args);
23131       if (spec_args)
23132 	{
23133 	  if (outer_args)
23134 	    spec_args = add_to_template_args (outer_args, spec_args);
23135 
23136           /* Keep the candidate only if the constraints are satisfied,
23137              or if we're not compiling with concepts.  */
23138           if (!flag_concepts
23139               || constraints_satisfied_p (spec_tmpl, spec_args))
23140             {
23141               list = tree_cons (spec_args, TREE_VALUE (t), list);
23142               TREE_TYPE (list) = TREE_TYPE (t);
23143             }
23144 	}
23145     }
23146 
23147   if (! list)
23148     return NULL_TREE;
23149 
23150   ambiguous_p = false;
23151   t = list;
23152   champ = t;
23153   t = TREE_CHAIN (t);
23154   for (; t; t = TREE_CHAIN (t))
23155     {
23156       fate = more_specialized_partial_spec (tmpl, champ, t);
23157       if (fate == 1)
23158 	;
23159       else
23160 	{
23161 	  if (fate == 0)
23162 	    {
23163 	      t = TREE_CHAIN (t);
23164 	      if (! t)
23165 		{
23166 		  ambiguous_p = true;
23167 		  break;
23168 		}
23169 	    }
23170 	  champ = t;
23171 	}
23172     }
23173 
23174   if (!ambiguous_p)
23175     for (t = list; t && t != champ; t = TREE_CHAIN (t))
23176       {
23177 	fate = more_specialized_partial_spec (tmpl, champ, t);
23178 	if (fate != 1)
23179 	  {
23180 	    ambiguous_p = true;
23181 	    break;
23182 	  }
23183       }
23184 
23185   if (ambiguous_p)
23186     {
23187       const char *str;
23188       char *spaces = NULL;
23189       if (!(complain & tf_error))
23190 	return error_mark_node;
23191       if (TYPE_P (target))
23192 	error ("ambiguous template instantiation for %q#T", target);
23193       else
23194 	error ("ambiguous template instantiation for %q#D", target);
23195       str = ngettext ("candidate is:", "candidates are:", list_length (list));
23196       for (t = list; t; t = TREE_CHAIN (t))
23197         {
23198 	  tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
23199           inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
23200 		  "%s %#qS", spaces ? spaces : str, subst);
23201           spaces = spaces ? spaces : get_spaces (str);
23202         }
23203       free (spaces);
23204       return error_mark_node;
23205     }
23206 
23207   return champ;
23208 }
23209 
23210 /* Explicitly instantiate DECL.  */
23211 
23212 void
do_decl_instantiation(tree decl,tree storage)23213 do_decl_instantiation (tree decl, tree storage)
23214 {
23215   tree result = NULL_TREE;
23216   int extern_p = 0;
23217 
23218   if (!decl || decl == error_mark_node)
23219     /* An error occurred, for which grokdeclarator has already issued
23220        an appropriate message.  */
23221     return;
23222   else if (! DECL_LANG_SPECIFIC (decl))
23223     {
23224       error ("explicit instantiation of non-template %q#D", decl);
23225       return;
23226     }
23227 
23228   bool var_templ = (DECL_TEMPLATE_INFO (decl)
23229                     && variable_template_p (DECL_TI_TEMPLATE (decl)));
23230 
23231   if (VAR_P (decl) && !var_templ)
23232     {
23233       /* There is an asymmetry here in the way VAR_DECLs and
23234 	 FUNCTION_DECLs are handled by grokdeclarator.  In the case of
23235 	 the latter, the DECL we get back will be marked as a
23236 	 template instantiation, and the appropriate
23237 	 DECL_TEMPLATE_INFO will be set up.  This does not happen for
23238 	 VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
23239 	 should handle VAR_DECLs as it currently handles
23240 	 FUNCTION_DECLs.  */
23241       if (!DECL_CLASS_SCOPE_P (decl))
23242 	{
23243 	  error ("%qD is not a static data member of a class template", decl);
23244 	  return;
23245 	}
23246       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
23247       if (!result || !VAR_P (result))
23248 	{
23249 	  error ("no matching template for %qD found", decl);
23250 	  return;
23251 	}
23252       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
23253 	{
23254 	  error ("type %qT for explicit instantiation %qD does not match "
23255 		 "declared type %qT", TREE_TYPE (result), decl,
23256 		 TREE_TYPE (decl));
23257 	  return;
23258 	}
23259     }
23260   else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
23261     {
23262       error ("explicit instantiation of %q#D", decl);
23263       return;
23264     }
23265   else
23266     result = decl;
23267 
23268   /* Check for various error cases.  Note that if the explicit
23269      instantiation is valid the RESULT will currently be marked as an
23270      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
23271      until we get here.  */
23272 
23273   if (DECL_TEMPLATE_SPECIALIZATION (result))
23274     {
23275       /* DR 259 [temp.spec].
23276 
23277 	 Both an explicit instantiation and a declaration of an explicit
23278 	 specialization shall not appear in a program unless the explicit
23279 	 instantiation follows a declaration of the explicit specialization.
23280 
23281 	 For a given set of template parameters, if an explicit
23282 	 instantiation of a template appears after a declaration of an
23283 	 explicit specialization for that template, the explicit
23284 	 instantiation has no effect.  */
23285       return;
23286     }
23287   else if (DECL_EXPLICIT_INSTANTIATION (result))
23288     {
23289       /* [temp.spec]
23290 
23291 	 No program shall explicitly instantiate any template more
23292 	 than once.
23293 
23294 	 We check DECL_NOT_REALLY_EXTERN so as not to complain when
23295 	 the first instantiation was `extern' and the second is not,
23296 	 and EXTERN_P for the opposite case.  */
23297       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
23298 	permerror (input_location, "duplicate explicit instantiation of %q#D", result);
23299       /* If an "extern" explicit instantiation follows an ordinary
23300 	 explicit instantiation, the template is instantiated.  */
23301       if (extern_p)
23302 	return;
23303     }
23304   else if (!DECL_IMPLICIT_INSTANTIATION (result))
23305     {
23306       error ("no matching template for %qD found", result);
23307       return;
23308     }
23309   else if (!DECL_TEMPLATE_INFO (result))
23310     {
23311       permerror (input_location, "explicit instantiation of non-template %q#D", result);
23312       return;
23313     }
23314 
23315   if (storage == NULL_TREE)
23316     ;
23317   else if (storage == ridpointers[(int) RID_EXTERN])
23318     {
23319       if (!in_system_header_at (input_location) && (cxx_dialect == cxx98))
23320 	pedwarn (input_location, OPT_Wpedantic,
23321 		 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
23322 		 "instantiations");
23323       extern_p = 1;
23324     }
23325   else
23326     error ("storage class %qD applied to template instantiation", storage);
23327 
23328   check_explicit_instantiation_namespace (result);
23329   mark_decl_instantiated (result, extern_p);
23330   if (! extern_p)
23331     instantiate_decl (result, /*defer_ok=*/true,
23332 		      /*expl_inst_class_mem_p=*/false);
23333 }
23334 
23335 static void
mark_class_instantiated(tree t,int extern_p)23336 mark_class_instantiated (tree t, int extern_p)
23337 {
23338   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
23339   SET_CLASSTYPE_INTERFACE_KNOWN (t);
23340   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
23341   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
23342   if (! extern_p)
23343     {
23344       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
23345       rest_of_type_compilation (t, 1);
23346     }
23347 }
23348 
23349 /* Called from do_type_instantiation through binding_table_foreach to
23350    do recursive instantiation for the type bound in ENTRY.  */
23351 static void
bt_instantiate_type_proc(binding_entry entry,void * data)23352 bt_instantiate_type_proc (binding_entry entry, void *data)
23353 {
23354   tree storage = *(tree *) data;
23355 
23356   if (MAYBE_CLASS_TYPE_P (entry->type)
23357       && CLASSTYPE_TEMPLATE_INFO (entry->type)
23358       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
23359     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
23360 }
23361 
23362 /* Perform an explicit instantiation of template class T.  STORAGE, if
23363    non-null, is the RID for extern, inline or static.  COMPLAIN is
23364    nonzero if this is called from the parser, zero if called recursively,
23365    since the standard is unclear (as detailed below).  */
23366 
23367 void
do_type_instantiation(tree t,tree storage,tsubst_flags_t complain)23368 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
23369 {
23370   int extern_p = 0;
23371   int nomem_p = 0;
23372   int static_p = 0;
23373   int previous_instantiation_extern_p = 0;
23374 
23375   if (TREE_CODE (t) == TYPE_DECL)
23376     t = TREE_TYPE (t);
23377 
23378   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
23379     {
23380       tree tmpl =
23381 	(TYPE_TEMPLATE_INFO (t)) ? TYPE_TI_TEMPLATE (t) : NULL;
23382       if (tmpl)
23383 	error ("explicit instantiation of non-class template %qD", tmpl);
23384       else
23385 	error ("explicit instantiation of non-template type %qT", t);
23386       return;
23387     }
23388 
23389   complete_type (t);
23390 
23391   if (!COMPLETE_TYPE_P (t))
23392     {
23393       if (complain & tf_error)
23394 	error ("explicit instantiation of %q#T before definition of template",
23395 	       t);
23396       return;
23397     }
23398 
23399   if (storage != NULL_TREE)
23400     {
23401       if (!in_system_header_at (input_location))
23402 	{
23403 	  if (storage == ridpointers[(int) RID_EXTERN])
23404 	    {
23405 	      if (cxx_dialect == cxx98)
23406 		pedwarn (input_location, OPT_Wpedantic,
23407 			 "ISO C++ 1998 forbids the use of %<extern%> on "
23408 			 "explicit instantiations");
23409 	    }
23410 	  else
23411 	    pedwarn (input_location, OPT_Wpedantic,
23412 		     "ISO C++ forbids the use of %qE"
23413 		     " on explicit instantiations", storage);
23414 	}
23415 
23416       if (storage == ridpointers[(int) RID_INLINE])
23417 	nomem_p = 1;
23418       else if (storage == ridpointers[(int) RID_EXTERN])
23419 	extern_p = 1;
23420       else if (storage == ridpointers[(int) RID_STATIC])
23421 	static_p = 1;
23422       else
23423 	{
23424 	  error ("storage class %qD applied to template instantiation",
23425 		 storage);
23426 	  extern_p = 0;
23427 	}
23428     }
23429 
23430   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
23431     {
23432       /* DR 259 [temp.spec].
23433 
23434 	 Both an explicit instantiation and a declaration of an explicit
23435 	 specialization shall not appear in a program unless the explicit
23436 	 instantiation follows a declaration of the explicit specialization.
23437 
23438 	 For a given set of template parameters, if an explicit
23439 	 instantiation of a template appears after a declaration of an
23440 	 explicit specialization for that template, the explicit
23441 	 instantiation has no effect.  */
23442       return;
23443     }
23444   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
23445     {
23446       /* [temp.spec]
23447 
23448 	 No program shall explicitly instantiate any template more
23449 	 than once.
23450 
23451 	 If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
23452 	 instantiation was `extern'.  If EXTERN_P then the second is.
23453 	 These cases are OK.  */
23454       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
23455 
23456       if (!previous_instantiation_extern_p && !extern_p
23457 	  && (complain & tf_error))
23458 	permerror (input_location, "duplicate explicit instantiation of %q#T", t);
23459 
23460       /* If we've already instantiated the template, just return now.  */
23461       if (!CLASSTYPE_INTERFACE_ONLY (t))
23462 	return;
23463     }
23464 
23465   check_explicit_instantiation_namespace (TYPE_NAME (t));
23466   mark_class_instantiated (t, extern_p);
23467 
23468   if (nomem_p)
23469     return;
23470 
23471   /* In contrast to implicit instantiation, where only the
23472      declarations, and not the definitions, of members are
23473      instantiated, we have here:
23474 
23475 	 [temp.explicit]
23476 
23477 	 The explicit instantiation of a class template specialization
23478 	 implies the instantiation of all of its members not
23479 	 previously explicitly specialized in the translation unit
23480 	 containing the explicit instantiation.
23481 
23482      Of course, we can't instantiate member template classes, since we
23483      don't have any arguments for them.  Note that the standard is
23484      unclear on whether the instantiation of the members are
23485      *explicit* instantiations or not.  However, the most natural
23486      interpretation is that it should be an explicit
23487      instantiation.  */
23488   for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
23489     if ((VAR_P (fld)
23490 	 || (TREE_CODE (fld) == FUNCTION_DECL
23491 	     && !static_p
23492 	     && user_provided_p (fld)))
23493 	&& DECL_TEMPLATE_INSTANTIATION (fld))
23494       {
23495 	mark_decl_instantiated (fld, extern_p);
23496 	if (! extern_p)
23497 	  instantiate_decl (fld, /*defer_ok=*/true,
23498 			    /*expl_inst_class_mem_p=*/true);
23499       }
23500 
23501   if (CLASSTYPE_NESTED_UTDS (t))
23502     binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
23503 			   bt_instantiate_type_proc, &storage);
23504 }
23505 
23506 /* Given a function DECL, which is a specialization of TMPL, modify
23507    DECL to be a re-instantiation of TMPL with the same template
23508    arguments.  TMPL should be the template into which tsubst'ing
23509    should occur for DECL, not the most general template.
23510 
23511    One reason for doing this is a scenario like this:
23512 
23513      template <class T>
23514      void f(const T&, int i);
23515 
23516      void g() { f(3, 7); }
23517 
23518      template <class T>
23519      void f(const T& t, const int i) { }
23520 
23521    Note that when the template is first instantiated, with
23522    instantiate_template, the resulting DECL will have no name for the
23523    first parameter, and the wrong type for the second.  So, when we go
23524    to instantiate the DECL, we regenerate it.  */
23525 
23526 static void
regenerate_decl_from_template(tree decl,tree tmpl,tree args)23527 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
23528 {
23529   /* The arguments used to instantiate DECL, from the most general
23530      template.  */
23531   tree code_pattern;
23532 
23533   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
23534 
23535   /* Make sure that we can see identifiers, and compute access
23536      correctly.  */
23537   push_access_scope (decl);
23538 
23539   if (TREE_CODE (decl) == FUNCTION_DECL)
23540     {
23541       tree decl_parm;
23542       tree pattern_parm;
23543       tree specs;
23544       int args_depth;
23545       int parms_depth;
23546 
23547       args_depth = TMPL_ARGS_DEPTH (args);
23548       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
23549       if (args_depth > parms_depth)
23550 	args = get_innermost_template_args (args, parms_depth);
23551 
23552       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
23553 					      args, tf_error, NULL_TREE,
23554 					      /*defer_ok*/false);
23555       if (specs && specs != error_mark_node)
23556 	TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
23557 						    specs);
23558 
23559       /* Merge parameter declarations.  */
23560       decl_parm = skip_artificial_parms_for (decl,
23561 					     DECL_ARGUMENTS (decl));
23562       pattern_parm
23563 	= skip_artificial_parms_for (code_pattern,
23564 				     DECL_ARGUMENTS (code_pattern));
23565       while (decl_parm && !DECL_PACK_P (pattern_parm))
23566 	{
23567 	  tree parm_type;
23568 	  tree attributes;
23569 
23570 	  if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
23571 	    DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
23572 	  parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
23573 			      NULL_TREE);
23574 	  parm_type = type_decays_to (parm_type);
23575 	  if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
23576 	    TREE_TYPE (decl_parm) = parm_type;
23577 	  attributes = DECL_ATTRIBUTES (pattern_parm);
23578 	  if (DECL_ATTRIBUTES (decl_parm) != attributes)
23579 	    {
23580 	      DECL_ATTRIBUTES (decl_parm) = attributes;
23581 	      cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
23582 	    }
23583 	  decl_parm = DECL_CHAIN (decl_parm);
23584 	  pattern_parm = DECL_CHAIN (pattern_parm);
23585 	}
23586       /* Merge any parameters that match with the function parameter
23587          pack.  */
23588       if (pattern_parm && DECL_PACK_P (pattern_parm))
23589         {
23590           int i, len;
23591           tree expanded_types;
23592           /* Expand the TYPE_PACK_EXPANSION that provides the types for
23593              the parameters in this function parameter pack.  */
23594           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm),
23595                                                  args, tf_error, NULL_TREE);
23596           len = TREE_VEC_LENGTH (expanded_types);
23597           for (i = 0; i < len; i++)
23598             {
23599               tree parm_type;
23600               tree attributes;
23601 
23602               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
23603                 /* Rename the parameter to include the index.  */
23604                 DECL_NAME (decl_parm) =
23605                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
23606               parm_type = TREE_VEC_ELT (expanded_types, i);
23607               parm_type = type_decays_to (parm_type);
23608               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
23609                 TREE_TYPE (decl_parm) = parm_type;
23610               attributes = DECL_ATTRIBUTES (pattern_parm);
23611               if (DECL_ATTRIBUTES (decl_parm) != attributes)
23612                 {
23613                   DECL_ATTRIBUTES (decl_parm) = attributes;
23614                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
23615                 }
23616               decl_parm = DECL_CHAIN (decl_parm);
23617             }
23618         }
23619       /* Merge additional specifiers from the CODE_PATTERN.  */
23620       if (DECL_DECLARED_INLINE_P (code_pattern)
23621 	  && !DECL_DECLARED_INLINE_P (decl))
23622 	DECL_DECLARED_INLINE_P (decl) = 1;
23623     }
23624   else if (VAR_P (decl))
23625     {
23626       start_lambda_scope (decl);
23627       DECL_INITIAL (decl) =
23628 	tsubst_expr (DECL_INITIAL (code_pattern), args,
23629 		     tf_error, DECL_TI_TEMPLATE (decl),
23630 		     /*integral_constant_expression_p=*/false);
23631       finish_lambda_scope ();
23632       if (VAR_HAD_UNKNOWN_BOUND (decl))
23633 	TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
23634 				   tf_error, DECL_TI_TEMPLATE (decl));
23635     }
23636   else
23637     gcc_unreachable ();
23638 
23639   pop_access_scope (decl);
23640 }
23641 
23642 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
23643    substituted to get DECL.  */
23644 
23645 tree
template_for_substitution(tree decl)23646 template_for_substitution (tree decl)
23647 {
23648   tree tmpl = DECL_TI_TEMPLATE (decl);
23649 
23650   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
23651      for the instantiation.  This is not always the most general
23652      template.  Consider, for example:
23653 
23654 	template <class T>
23655 	struct S { template <class U> void f();
23656 		   template <> void f<int>(); };
23657 
23658      and an instantiation of S<double>::f<int>.  We want TD to be the
23659      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
23660   while (/* An instantiation cannot have a definition, so we need a
23661 	    more general template.  */
23662 	 DECL_TEMPLATE_INSTANTIATION (tmpl)
23663 	   /* We must also deal with friend templates.  Given:
23664 
23665 		template <class T> struct S {
23666 		  template <class U> friend void f() {};
23667 		};
23668 
23669 	      S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
23670 	      so far as the language is concerned, but that's still
23671 	      where we get the pattern for the instantiation from.  On
23672 	      other hand, if the definition comes outside the class, say:
23673 
23674 		template <class T> struct S {
23675 		  template <class U> friend void f();
23676 		};
23677 		template <class U> friend void f() {}
23678 
23679 	      we don't need to look any further.  That's what the check for
23680 	      DECL_INITIAL is for.  */
23681 	  || (TREE_CODE (decl) == FUNCTION_DECL
23682 	      && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
23683 	      && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
23684     {
23685       /* The present template, TD, should not be a definition.  If it
23686 	 were a definition, we should be using it!  Note that we
23687 	 cannot restructure the loop to just keep going until we find
23688 	 a template with a definition, since that might go too far if
23689 	 a specialization was declared, but not defined.  */
23690 
23691       /* Fetch the more general template.  */
23692       tmpl = DECL_TI_TEMPLATE (tmpl);
23693     }
23694 
23695   return tmpl;
23696 }
23697 
23698 /* Returns true if we need to instantiate this template instance even if we
23699    know we aren't going to emit it.  */
23700 
23701 bool
always_instantiate_p(tree decl)23702 always_instantiate_p (tree decl)
23703 {
23704   /* We always instantiate inline functions so that we can inline them.  An
23705      explicit instantiation declaration prohibits implicit instantiation of
23706      non-inline functions.  With high levels of optimization, we would
23707      normally inline non-inline functions -- but we're not allowed to do
23708      that for "extern template" functions.  Therefore, we check
23709      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
23710   return ((TREE_CODE (decl) == FUNCTION_DECL
23711 	   && (DECL_DECLARED_INLINE_P (decl)
23712 	       || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
23713 	  /* And we need to instantiate static data members so that
23714 	     their initializers are available in integral constant
23715 	     expressions.  */
23716 	  || (VAR_P (decl)
23717 	      && decl_maybe_constant_var_p (decl)));
23718 }
23719 
23720 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
23721    instantiate it now, modifying TREE_TYPE (fn).  Returns false on
23722    error, true otherwise.  */
23723 
23724 bool
maybe_instantiate_noexcept(tree fn,tsubst_flags_t complain)23725 maybe_instantiate_noexcept (tree fn, tsubst_flags_t complain)
23726 {
23727   tree fntype, spec, noex, clone;
23728 
23729   /* Don't instantiate a noexcept-specification from template context.  */
23730   if (processing_template_decl
23731       && (!flag_noexcept_type || type_dependent_expression_p (fn)))
23732     return true;
23733 
23734   if (DECL_CLONED_FUNCTION_P (fn))
23735     fn = DECL_CLONED_FUNCTION (fn);
23736   fntype = TREE_TYPE (fn);
23737   spec = TYPE_RAISES_EXCEPTIONS (fntype);
23738 
23739   if (!spec || !TREE_PURPOSE (spec))
23740     return true;
23741 
23742   noex = TREE_PURPOSE (spec);
23743 
23744   if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
23745     {
23746       static hash_set<tree>* fns = new hash_set<tree>;
23747       bool added = false;
23748       if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
23749 	spec = get_defaulted_eh_spec (fn, complain);
23750       else if (!(added = !fns->add (fn)))
23751 	{
23752 	  /* If hash_set::add returns true, the element was already there.  */
23753 	  location_t loc = EXPR_LOC_OR_LOC (DEFERRED_NOEXCEPT_PATTERN (noex),
23754 					    DECL_SOURCE_LOCATION (fn));
23755 	  error_at (loc,
23756 		    "exception specification of %qD depends on itself",
23757 		    fn);
23758 	  spec = noexcept_false_spec;
23759 	}
23760       else if (push_tinst_level (fn))
23761 	{
23762 	  push_access_scope (fn);
23763 	  push_deferring_access_checks (dk_no_deferred);
23764 	  input_location = DECL_SOURCE_LOCATION (fn);
23765 	  noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
23766 					DEFERRED_NOEXCEPT_ARGS (noex),
23767 					tf_warning_or_error, fn,
23768 					/*function_p=*/false,
23769 					/*integral_constant_expression_p=*/true);
23770 	  spec = build_noexcept_spec (noex, tf_warning_or_error);
23771 	  pop_deferring_access_checks ();
23772 	  pop_access_scope (fn);
23773 	  pop_tinst_level ();
23774 	  if (spec == error_mark_node)
23775 	    spec = noexcept_false_spec;
23776 	}
23777       else
23778 	spec = noexcept_false_spec;
23779 
23780       if (added)
23781 	fns->remove (fn);
23782 
23783       if (spec == error_mark_node)
23784 	return false;
23785 
23786       TREE_TYPE (fn) = build_exception_variant (fntype, spec);
23787     }
23788 
23789   FOR_EACH_CLONE (clone, fn)
23790     {
23791       if (TREE_TYPE (clone) == fntype)
23792 	TREE_TYPE (clone) = TREE_TYPE (fn);
23793       else
23794 	TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone), spec);
23795     }
23796 
23797   return true;
23798 }
23799 
23800 /* We're starting to process the function INST, an instantiation of PATTERN;
23801    add their parameters to local_specializations.  */
23802 
23803 static void
register_parameter_specializations(tree pattern,tree inst)23804 register_parameter_specializations (tree pattern, tree inst)
23805 {
23806   tree tmpl_parm = DECL_ARGUMENTS (pattern);
23807   tree spec_parm = DECL_ARGUMENTS (inst);
23808   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (inst))
23809     {
23810       register_local_specialization (spec_parm, tmpl_parm);
23811       spec_parm = skip_artificial_parms_for (inst, spec_parm);
23812       tmpl_parm = skip_artificial_parms_for (pattern, tmpl_parm);
23813     }
23814   for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
23815     {
23816       if (!DECL_PACK_P (tmpl_parm))
23817 	{
23818 	  register_local_specialization (spec_parm, tmpl_parm);
23819 	  spec_parm = DECL_CHAIN (spec_parm);
23820 	}
23821       else
23822 	{
23823 	  /* Register the (value) argument pack as a specialization of
23824 	     TMPL_PARM, then move on.  */
23825 	  tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
23826 	  register_local_specialization (argpack, tmpl_parm);
23827 	}
23828     }
23829   gcc_assert (!spec_parm);
23830 }
23831 
23832 /* Produce the definition of D, a _DECL generated from a template.  If
23833    DEFER_OK is true, then we don't have to actually do the
23834    instantiation now; we just have to do it sometime.  Normally it is
23835    an error if this is an explicit instantiation but D is undefined.
23836    EXPL_INST_CLASS_MEM_P is true iff D is a member of an explicitly
23837    instantiated class template.  */
23838 
23839 tree
instantiate_decl(tree d,bool defer_ok,bool expl_inst_class_mem_p)23840 instantiate_decl (tree d, bool defer_ok, bool expl_inst_class_mem_p)
23841 {
23842   tree tmpl = DECL_TI_TEMPLATE (d);
23843   tree gen_args;
23844   tree args;
23845   tree td;
23846   tree code_pattern;
23847   tree spec;
23848   tree gen_tmpl;
23849   bool pattern_defined;
23850   location_t saved_loc = input_location;
23851   int saved_unevaluated_operand = cp_unevaluated_operand;
23852   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
23853   bool external_p;
23854   bool deleted_p;
23855 
23856   /* This function should only be used to instantiate templates for
23857      functions and static member variables.  */
23858   gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
23859 
23860   /* A concept is never instantiated. */
23861   gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
23862 
23863   /* Variables are never deferred; if instantiation is required, they
23864      are instantiated right away.  That allows for better code in the
23865      case that an expression refers to the value of the variable --
23866      if the variable has a constant value the referring expression can
23867      take advantage of that fact.  */
23868   if (VAR_P (d))
23869     defer_ok = false;
23870 
23871   /* Don't instantiate cloned functions.  Instead, instantiate the
23872      functions they cloned.  */
23873   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
23874     d = DECL_CLONED_FUNCTION (d);
23875 
23876   if (DECL_TEMPLATE_INSTANTIATED (d)
23877       || (TREE_CODE (d) == FUNCTION_DECL
23878 	  && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
23879       || DECL_TEMPLATE_SPECIALIZATION (d))
23880     /* D has already been instantiated or explicitly specialized, so
23881        there's nothing for us to do here.
23882 
23883        It might seem reasonable to check whether or not D is an explicit
23884        instantiation, and, if so, stop here.  But when an explicit
23885        instantiation is deferred until the end of the compilation,
23886        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
23887        the instantiation.  */
23888     return d;
23889 
23890   /* Check to see whether we know that this template will be
23891      instantiated in some other file, as with "extern template"
23892      extension.  */
23893   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
23894 
23895   /* In general, we do not instantiate such templates.  */
23896   if (external_p && !always_instantiate_p (d))
23897     return d;
23898 
23899   gen_tmpl = most_general_template (tmpl);
23900   gen_args = DECL_TI_ARGS (d);
23901 
23902   if (tmpl != gen_tmpl)
23903     /* We should already have the extra args.  */
23904     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
23905 		== TMPL_ARGS_DEPTH (gen_args));
23906   /* And what's in the hash table should match D.  */
23907   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
23908 	      || spec == NULL_TREE);
23909 
23910   /* This needs to happen before any tsubsting.  */
23911   if (! push_tinst_level (d))
23912     return d;
23913 
23914   timevar_push (TV_TEMPLATE_INST);
23915 
23916   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
23917      for the instantiation.  */
23918   td = template_for_substitution (d);
23919   args = gen_args;
23920 
23921   if (VAR_P (d))
23922     {
23923       /* Look up an explicit specialization, if any.  */
23924       tree tid = lookup_template_variable (gen_tmpl, gen_args);
23925       tree elt = most_specialized_partial_spec (tid, tf_warning_or_error);
23926       if (elt && elt != error_mark_node)
23927 	{
23928 	  td = TREE_VALUE (elt);
23929 	  args = TREE_PURPOSE (elt);
23930 	}
23931     }
23932 
23933   code_pattern = DECL_TEMPLATE_RESULT (td);
23934 
23935   /* We should never be trying to instantiate a member of a class
23936      template or partial specialization.  */
23937   gcc_assert (d != code_pattern);
23938 
23939   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
23940       || DECL_TEMPLATE_SPECIALIZATION (td))
23941     /* In the case of a friend template whose definition is provided
23942        outside the class, we may have too many arguments.  Drop the
23943        ones we don't need.  The same is true for specializations.  */
23944     args = get_innermost_template_args
23945       (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
23946 
23947   if (TREE_CODE (d) == FUNCTION_DECL)
23948     {
23949       deleted_p = DECL_DELETED_FN (code_pattern);
23950       pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
23951 			  && DECL_INITIAL (code_pattern) != error_mark_node)
23952 			 || DECL_DEFAULTED_OUTSIDE_CLASS_P (code_pattern)
23953 			 || deleted_p);
23954     }
23955   else
23956     {
23957       deleted_p = false;
23958       if (DECL_CLASS_SCOPE_P (code_pattern))
23959 	pattern_defined = (! DECL_IN_AGGR_P (code_pattern)
23960 			   || DECL_INLINE_VAR_P (code_pattern));
23961       else
23962 	pattern_defined = ! DECL_EXTERNAL (code_pattern);
23963     }
23964 
23965   /* We may be in the middle of deferred access check.  Disable it now.  */
23966   push_deferring_access_checks (dk_no_deferred);
23967 
23968   /* Unless an explicit instantiation directive has already determined
23969      the linkage of D, remember that a definition is available for
23970      this entity.  */
23971   if (pattern_defined
23972       && !DECL_INTERFACE_KNOWN (d)
23973       && !DECL_NOT_REALLY_EXTERN (d))
23974     mark_definable (d);
23975 
23976   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
23977   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
23978   input_location = DECL_SOURCE_LOCATION (d);
23979 
23980   /* If D is a member of an explicitly instantiated class template,
23981      and no definition is available, treat it like an implicit
23982      instantiation.  */
23983   if (!pattern_defined && expl_inst_class_mem_p
23984       && DECL_EXPLICIT_INSTANTIATION (d))
23985     {
23986       /* Leave linkage flags alone on instantiations with anonymous
23987 	 visibility.  */
23988       if (TREE_PUBLIC (d))
23989 	{
23990 	  DECL_NOT_REALLY_EXTERN (d) = 0;
23991 	  DECL_INTERFACE_KNOWN (d) = 0;
23992 	}
23993       SET_DECL_IMPLICIT_INSTANTIATION (d);
23994     }
23995 
23996   /* Defer all other templates, unless we have been explicitly
23997      forbidden from doing so.  */
23998   if (/* If there is no definition, we cannot instantiate the
23999 	 template.  */
24000       ! pattern_defined
24001       /* If it's OK to postpone instantiation, do so.  */
24002       || defer_ok
24003       /* If this is a static data member that will be defined
24004 	 elsewhere, we don't want to instantiate the entire data
24005 	 member, but we do want to instantiate the initializer so that
24006 	 we can substitute that elsewhere.  */
24007       || (external_p && VAR_P (d))
24008       /* Handle here a deleted function too, avoid generating
24009 	 its body (c++/61080).  */
24010       || deleted_p)
24011     {
24012       /* The definition of the static data member is now required so
24013 	 we must substitute the initializer.  */
24014       if (VAR_P (d)
24015 	  && !DECL_INITIAL (d)
24016 	  && DECL_INITIAL (code_pattern))
24017 	{
24018 	  tree ns;
24019 	  tree init;
24020 	  bool const_init = false;
24021 	  bool enter_context = DECL_CLASS_SCOPE_P (d);
24022 
24023 	  ns = decl_namespace_context (d);
24024 	  push_nested_namespace (ns);
24025 	  if (enter_context)
24026 	    push_nested_class (DECL_CONTEXT (d));
24027 	  init = tsubst_expr (DECL_INITIAL (code_pattern),
24028 			      args,
24029 			      tf_warning_or_error, NULL_TREE,
24030 			      /*integral_constant_expression_p=*/false);
24031 	  /* If instantiating the initializer involved instantiating this
24032 	     again, don't call cp_finish_decl twice.  */
24033 	  if (!DECL_INITIAL (d))
24034 	    {
24035 	      /* Make sure the initializer is still constant, in case of
24036 		 circular dependency (template/instantiate6.C). */
24037 	      const_init
24038 		= DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
24039 	      cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
24040 			      /*asmspec_tree=*/NULL_TREE,
24041 			      LOOKUP_ONLYCONVERTING);
24042 	    }
24043 	  if (enter_context)
24044 	    pop_nested_class ();
24045 	  pop_nested_namespace (ns);
24046 	}
24047 
24048       /* We restore the source position here because it's used by
24049 	 add_pending_template.  */
24050       input_location = saved_loc;
24051 
24052       if (at_eof && !pattern_defined
24053 	  && DECL_EXPLICIT_INSTANTIATION (d)
24054 	  && DECL_NOT_REALLY_EXTERN (d))
24055 	/* [temp.explicit]
24056 
24057 	   The definition of a non-exported function template, a
24058 	   non-exported member function template, or a non-exported
24059 	   member function or static data member of a class template
24060 	   shall be present in every translation unit in which it is
24061 	   explicitly instantiated.  */
24062 	permerror (input_location,  "explicit instantiation of %qD "
24063 		   "but no definition available", d);
24064 
24065       /* If we're in unevaluated context, we just wanted to get the
24066 	 constant value; this isn't an odr use, so don't queue
24067 	 a full instantiation.  */
24068       if (cp_unevaluated_operand != 0)
24069 	goto out;
24070       /* ??? Historically, we have instantiated inline functions, even
24071 	 when marked as "extern template".  */
24072       if (!(external_p && VAR_P (d)))
24073 	add_pending_template (d);
24074       goto out;
24075     }
24076   /* Tell the repository that D is available in this translation unit
24077      -- and see if it is supposed to be instantiated here.  */
24078   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
24079     {
24080       /* In a PCH file, despite the fact that the repository hasn't
24081 	 requested instantiation in the PCH it is still possible that
24082 	 an instantiation will be required in a file that includes the
24083 	 PCH.  */
24084       if (pch_file)
24085 	add_pending_template (d);
24086       /* Instantiate inline functions so that the inliner can do its
24087 	 job, even though we'll not be emitting a copy of this
24088 	 function.  */
24089       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
24090 	goto out;
24091     }
24092 
24093   bool push_to_top, nested;
24094   tree fn_context;
24095   fn_context = decl_function_context (d);
24096   if (LAMBDA_FUNCTION_P (d))
24097     /* tsubst_lambda_expr resolved any references to enclosing functions.  */
24098     fn_context = NULL_TREE;
24099   nested = current_function_decl != NULL_TREE;
24100   push_to_top = !(nested && fn_context == current_function_decl);
24101 
24102   vec<tree> omp_privatization_save;
24103   if (nested)
24104     save_omp_privatization_clauses (omp_privatization_save);
24105 
24106   if (push_to_top)
24107     push_to_top_level ();
24108   else
24109     {
24110       push_function_context ();
24111       cp_unevaluated_operand = 0;
24112       c_inhibit_evaluation_warnings = 0;
24113     }
24114 
24115   /* Mark D as instantiated so that recursive calls to
24116      instantiate_decl do not try to instantiate it again.  */
24117   DECL_TEMPLATE_INSTANTIATED (d) = 1;
24118 
24119   /* Regenerate the declaration in case the template has been modified
24120      by a subsequent redeclaration.  */
24121   regenerate_decl_from_template (d, td, args);
24122 
24123   /* We already set the file and line above.  Reset them now in case
24124      they changed as a result of calling regenerate_decl_from_template.  */
24125   input_location = DECL_SOURCE_LOCATION (d);
24126 
24127   if (VAR_P (d))
24128     {
24129       tree init;
24130       bool const_init = false;
24131 
24132       /* Clear out DECL_RTL; whatever was there before may not be right
24133 	 since we've reset the type of the declaration.  */
24134       SET_DECL_RTL (d, NULL);
24135       DECL_IN_AGGR_P (d) = 0;
24136 
24137       /* The initializer is placed in DECL_INITIAL by
24138 	 regenerate_decl_from_template so we don't need to
24139 	 push/pop_access_scope again here.  Pull it out so that
24140 	 cp_finish_decl can process it.  */
24141       init = DECL_INITIAL (d);
24142       DECL_INITIAL (d) = NULL_TREE;
24143       DECL_INITIALIZED_P (d) = 0;
24144 
24145       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
24146 	 initializer.  That function will defer actual emission until
24147 	 we have a chance to determine linkage.  */
24148       DECL_EXTERNAL (d) = 0;
24149 
24150       /* Enter the scope of D so that access-checking works correctly.  */
24151       bool enter_context = DECL_CLASS_SCOPE_P (d);
24152       if (enter_context)
24153         push_nested_class (DECL_CONTEXT (d));
24154 
24155       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
24156       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
24157 
24158       if (enter_context)
24159         pop_nested_class ();
24160 
24161       if (variable_template_p (gen_tmpl))
24162 	note_variable_template_instantiation (d);
24163     }
24164   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
24165     synthesize_method (d);
24166   else if (TREE_CODE (d) == FUNCTION_DECL)
24167     {
24168       /* Set up the list of local specializations.  */
24169       local_specialization_stack lss (push_to_top ? lss_blank : lss_copy);
24170       tree block = NULL_TREE;
24171 
24172       /* Set up context.  */
24173       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
24174 	  && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
24175 	block = push_stmt_list ();
24176       else
24177 	start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
24178 
24179       /* Some typedefs referenced from within the template code need to be
24180 	 access checked at template instantiation time, i.e now. These
24181 	 types were added to the template at parsing time. Let's get those
24182 	 and perform the access checks then.  */
24183       perform_typedefs_access_check (DECL_TEMPLATE_RESULT (td),
24184 				     args);
24185 
24186       /* Create substitution entries for the parameters.  */
24187       register_parameter_specializations (code_pattern, d);
24188 
24189       /* Substitute into the body of the function.  */
24190       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
24191 	tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
24192 			tf_warning_or_error, tmpl);
24193       else
24194 	{
24195 	  tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
24196 		       tf_warning_or_error, tmpl,
24197 		       /*integral_constant_expression_p=*/false);
24198 
24199 	  /* Set the current input_location to the end of the function
24200 	     so that finish_function knows where we are.  */
24201 	  input_location
24202 	    = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
24203 
24204 	  /* Remember if we saw an infinite loop in the template.  */
24205 	  current_function_infinite_loop
24206 	    = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
24207 	}
24208 
24209       /* Finish the function.  */
24210       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
24211 	  && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
24212 	DECL_SAVED_TREE (d) = pop_stmt_list (block);
24213       else
24214 	{
24215 	  d = finish_function (/*inline_p=*/false);
24216 	  expand_or_defer_fn (d);
24217 	}
24218 
24219       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
24220 	cp_check_omp_declare_reduction (d);
24221     }
24222 
24223   /* We're not deferring instantiation any more.  */
24224   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
24225 
24226   if (push_to_top)
24227     pop_from_top_level ();
24228   else
24229     pop_function_context ();
24230 
24231   if (nested)
24232     restore_omp_privatization_clauses (omp_privatization_save);
24233 
24234 out:
24235   pop_deferring_access_checks ();
24236   timevar_pop (TV_TEMPLATE_INST);
24237   pop_tinst_level ();
24238   input_location = saved_loc;
24239   cp_unevaluated_operand = saved_unevaluated_operand;
24240   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
24241 
24242   return d;
24243 }
24244 
24245 /* Run through the list of templates that we wish we could
24246    instantiate, and instantiate any we can.  RETRIES is the
24247    number of times we retry pending template instantiation.  */
24248 
24249 void
instantiate_pending_templates(int retries)24250 instantiate_pending_templates (int retries)
24251 {
24252   int reconsider;
24253   location_t saved_loc = input_location;
24254 
24255   /* Instantiating templates may trigger vtable generation.  This in turn
24256      may require further template instantiations.  We place a limit here
24257      to avoid infinite loop.  */
24258   if (pending_templates && retries >= max_tinst_depth)
24259     {
24260       tree decl = pending_templates->tinst->maybe_get_node ();
24261 
24262       fatal_error (input_location,
24263 		   "template instantiation depth exceeds maximum of %d"
24264                    " instantiating %q+D, possibly from virtual table generation"
24265                    " (use -ftemplate-depth= to increase the maximum)",
24266                    max_tinst_depth, decl);
24267       if (TREE_CODE (decl) == FUNCTION_DECL)
24268 	/* Pretend that we defined it.  */
24269 	DECL_INITIAL (decl) = error_mark_node;
24270       return;
24271     }
24272 
24273   do
24274     {
24275       struct pending_template **t = &pending_templates;
24276       struct pending_template *last = NULL;
24277       reconsider = 0;
24278       while (*t)
24279 	{
24280 	  tree instantiation = reopen_tinst_level ((*t)->tinst);
24281 	  bool complete = false;
24282 
24283 	  if (TYPE_P (instantiation))
24284 	    {
24285 	      if (!COMPLETE_TYPE_P (instantiation))
24286 		{
24287 		  instantiate_class_template (instantiation);
24288 		  if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
24289 		    for (tree fld = TYPE_FIELDS (instantiation);
24290 			 fld; fld = TREE_CHAIN (fld))
24291 		      if ((VAR_P (fld)
24292 			   || (TREE_CODE (fld) == FUNCTION_DECL
24293 			       && !DECL_ARTIFICIAL (fld)))
24294 			  && DECL_TEMPLATE_INSTANTIATION (fld))
24295 			instantiate_decl (fld,
24296 					  /*defer_ok=*/false,
24297 					  /*expl_inst_class_mem_p=*/false);
24298 
24299 		  if (COMPLETE_TYPE_P (instantiation))
24300 		    reconsider = 1;
24301 		}
24302 
24303 	      complete = COMPLETE_TYPE_P (instantiation);
24304 	    }
24305 	  else
24306 	    {
24307 	      if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
24308 		  && !DECL_TEMPLATE_INSTANTIATED (instantiation))
24309 		{
24310 		  instantiation
24311 		    = instantiate_decl (instantiation,
24312 					/*defer_ok=*/false,
24313 					/*expl_inst_class_mem_p=*/false);
24314 		  if (DECL_TEMPLATE_INSTANTIATED (instantiation))
24315 		    reconsider = 1;
24316 		}
24317 
24318 	      complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
24319 			  || DECL_TEMPLATE_INSTANTIATED (instantiation));
24320 	    }
24321 
24322 	  if (complete)
24323 	    {
24324 	      /* If INSTANTIATION has been instantiated, then we don't
24325 		 need to consider it again in the future.  */
24326 	      struct pending_template *drop = *t;
24327 	      *t = (*t)->next;
24328 	      set_refcount_ptr (drop->tinst);
24329 	      pending_template_freelist ().free (drop);
24330 	    }
24331 	  else
24332 	    {
24333 	      last = *t;
24334 	      t = &(*t)->next;
24335 	    }
24336 	  tinst_depth = 0;
24337 	  set_refcount_ptr (current_tinst_level);
24338 	}
24339       last_pending_template = last;
24340     }
24341   while (reconsider);
24342 
24343   input_location = saved_loc;
24344 }
24345 
24346 /* Substitute ARGVEC into T, which is a list of initializers for
24347    either base class or a non-static data member.  The TREE_PURPOSEs
24348    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
24349    instantiate_decl.  */
24350 
24351 static tree
tsubst_initializer_list(tree t,tree argvec)24352 tsubst_initializer_list (tree t, tree argvec)
24353 {
24354   tree inits = NULL_TREE;
24355   tree target_ctor = error_mark_node;
24356 
24357   for (; t; t = TREE_CHAIN (t))
24358     {
24359       tree decl;
24360       tree init;
24361       tree expanded_bases = NULL_TREE;
24362       tree expanded_arguments = NULL_TREE;
24363       int i, len = 1;
24364 
24365       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
24366         {
24367           tree expr;
24368           tree arg;
24369 
24370           /* Expand the base class expansion type into separate base
24371              classes.  */
24372           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
24373                                                  tf_warning_or_error,
24374                                                  NULL_TREE);
24375           if (expanded_bases == error_mark_node)
24376             continue;
24377 
24378           /* We'll be building separate TREE_LISTs of arguments for
24379              each base.  */
24380           len = TREE_VEC_LENGTH (expanded_bases);
24381           expanded_arguments = make_tree_vec (len);
24382           for (i = 0; i < len; i++)
24383             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
24384 
24385           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
24386              expand each argument in the TREE_VALUE of t.  */
24387           expr = make_node (EXPR_PACK_EXPANSION);
24388 	  PACK_EXPANSION_LOCAL_P (expr) = true;
24389           PACK_EXPANSION_PARAMETER_PACKS (expr) =
24390             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
24391 
24392 	  if (TREE_VALUE (t) == void_type_node)
24393 	    /* VOID_TYPE_NODE is used to indicate
24394 	       value-initialization.  */
24395 	    {
24396 	      for (i = 0; i < len; i++)
24397 		TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
24398 	    }
24399 	  else
24400 	    {
24401 	      /* Substitute parameter packs into each argument in the
24402 		 TREE_LIST.  */
24403 	      in_base_initializer = 1;
24404 	      for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
24405 		{
24406 		  tree expanded_exprs;
24407 
24408 		  /* Expand the argument.  */
24409 		  SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
24410 		  expanded_exprs
24411 		    = tsubst_pack_expansion (expr, argvec,
24412 					     tf_warning_or_error,
24413 					     NULL_TREE);
24414 		  if (expanded_exprs == error_mark_node)
24415 		    continue;
24416 
24417 		  /* Prepend each of the expanded expressions to the
24418 		     corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
24419 		  for (i = 0; i < len; i++)
24420 		    {
24421 		      TREE_VEC_ELT (expanded_arguments, i) =
24422 			tree_cons (NULL_TREE,
24423 				   TREE_VEC_ELT (expanded_exprs, i),
24424 				   TREE_VEC_ELT (expanded_arguments, i));
24425 		    }
24426 		}
24427 	      in_base_initializer = 0;
24428 
24429 	      /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
24430 		 since we built them backwards.  */
24431 	      for (i = 0; i < len; i++)
24432 		{
24433 		  TREE_VEC_ELT (expanded_arguments, i) =
24434 		    nreverse (TREE_VEC_ELT (expanded_arguments, i));
24435 		}
24436 	    }
24437         }
24438 
24439       for (i = 0; i < len; ++i)
24440         {
24441           if (expanded_bases)
24442             {
24443               decl = TREE_VEC_ELT (expanded_bases, i);
24444               decl = expand_member_init (decl);
24445               init = TREE_VEC_ELT (expanded_arguments, i);
24446             }
24447           else
24448             {
24449 	      tree tmp;
24450               decl = tsubst_copy (TREE_PURPOSE (t), argvec,
24451                                   tf_warning_or_error, NULL_TREE);
24452 
24453               decl = expand_member_init (decl);
24454               if (decl && !DECL_P (decl))
24455                 in_base_initializer = 1;
24456 
24457 	      init = TREE_VALUE (t);
24458 	      tmp = init;
24459 	      if (init != void_type_node)
24460 		init = tsubst_expr (init, argvec,
24461 				    tf_warning_or_error, NULL_TREE,
24462 				    /*integral_constant_expression_p=*/false);
24463 	      if (init == NULL_TREE && tmp != NULL_TREE)
24464 		/* If we had an initializer but it instantiated to nothing,
24465 		   value-initialize the object.  This will only occur when
24466 		   the initializer was a pack expansion where the parameter
24467 		   packs used in that expansion were of length zero.  */
24468 		init = void_type_node;
24469               in_base_initializer = 0;
24470             }
24471 
24472 	  if (target_ctor != error_mark_node
24473 	      && init != error_mark_node)
24474 	    {
24475 	      error ("mem-initializer for %qD follows constructor delegation",
24476 		     decl);
24477 	      return inits;
24478 	    }
24479 	  /* Look for a target constructor. */
24480 	  if (init != error_mark_node
24481 	      && decl && CLASS_TYPE_P (decl)
24482 	      && same_type_p (decl, current_class_type))
24483 	    {
24484 	      maybe_warn_cpp0x (CPP0X_DELEGATING_CTORS);
24485 	      if (inits)
24486 		{
24487 		  error ("constructor delegation follows mem-initializer for %qD",
24488 			 TREE_PURPOSE (inits));
24489 		  continue;
24490 		}
24491 	      target_ctor = init;
24492 	    }
24493 
24494           if (decl)
24495             {
24496               init = build_tree_list (decl, init);
24497               TREE_CHAIN (init) = inits;
24498               inits = init;
24499             }
24500         }
24501     }
24502   return inits;
24503 }
24504 
24505 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
24506 
24507 static void
set_current_access_from_decl(tree decl)24508 set_current_access_from_decl (tree decl)
24509 {
24510   if (TREE_PRIVATE (decl))
24511     current_access_specifier = access_private_node;
24512   else if (TREE_PROTECTED (decl))
24513     current_access_specifier = access_protected_node;
24514   else
24515     current_access_specifier = access_public_node;
24516 }
24517 
24518 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
24519    is the instantiation (which should have been created with
24520    start_enum) and ARGS are the template arguments to use.  */
24521 
24522 static void
tsubst_enum(tree tag,tree newtag,tree args)24523 tsubst_enum (tree tag, tree newtag, tree args)
24524 {
24525   tree e;
24526 
24527   if (SCOPED_ENUM_P (newtag))
24528     begin_scope (sk_scoped_enum, newtag);
24529 
24530   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
24531     {
24532       tree value;
24533       tree decl;
24534 
24535       decl = TREE_VALUE (e);
24536       /* Note that in a template enum, the TREE_VALUE is the
24537 	 CONST_DECL, not the corresponding INTEGER_CST.  */
24538       value = tsubst_expr (DECL_INITIAL (decl),
24539 			   args, tf_warning_or_error, NULL_TREE,
24540 			   /*integral_constant_expression_p=*/true);
24541 
24542       /* Give this enumeration constant the correct access.  */
24543       set_current_access_from_decl (decl);
24544 
24545       /* Actually build the enumerator itself.  Here we're assuming that
24546 	 enumerators can't have dependent attributes.  */
24547       build_enumerator (DECL_NAME (decl), value, newtag,
24548 			DECL_ATTRIBUTES (decl), DECL_SOURCE_LOCATION (decl));
24549     }
24550 
24551   if (SCOPED_ENUM_P (newtag))
24552     finish_scope ();
24553 
24554   finish_enum_value_list (newtag);
24555   finish_enum (newtag);
24556 
24557   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
24558     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
24559 }
24560 
24561 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
24562    its type -- but without substituting the innermost set of template
24563    arguments.  So, innermost set of template parameters will appear in
24564    the type.  */
24565 
24566 tree
get_mostly_instantiated_function_type(tree decl)24567 get_mostly_instantiated_function_type (tree decl)
24568 {
24569   /* For a function, DECL_TI_TEMPLATE is partially instantiated.  */
24570   return TREE_TYPE (DECL_TI_TEMPLATE (decl));
24571 }
24572 
24573 /* Return truthvalue if we're processing a template different from
24574    the last one involved in diagnostics.  */
24575 bool
problematic_instantiation_changed(void)24576 problematic_instantiation_changed (void)
24577 {
24578   return current_tinst_level != last_error_tinst_level;
24579 }
24580 
24581 /* Remember current template involved in diagnostics.  */
24582 void
record_last_problematic_instantiation(void)24583 record_last_problematic_instantiation (void)
24584 {
24585   set_refcount_ptr (last_error_tinst_level, current_tinst_level);
24586 }
24587 
24588 struct tinst_level *
current_instantiation(void)24589 current_instantiation (void)
24590 {
24591   return current_tinst_level;
24592 }
24593 
24594 /* Return TRUE if current_function_decl is being instantiated, false
24595    otherwise.  */
24596 
24597 bool
instantiating_current_function_p(void)24598 instantiating_current_function_p (void)
24599 {
24600   return (current_instantiation ()
24601 	  && (current_instantiation ()->maybe_get_node ()
24602 	      == current_function_decl));
24603 }
24604 
24605 /* [temp.param] Check that template non-type parm TYPE is of an allowable
24606    type.  Return false for ok, true for disallowed.  Issue error and
24607    inform messages under control of COMPLAIN.  */
24608 
24609 static bool
invalid_nontype_parm_type_p(tree type,tsubst_flags_t complain)24610 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
24611 {
24612   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
24613     return false;
24614   else if (TYPE_PTR_P (type))
24615     return false;
24616   else if (TREE_CODE (type) == REFERENCE_TYPE
24617 	   && !TYPE_REF_IS_RVALUE (type))
24618     return false;
24619   else if (TYPE_PTRMEM_P (type))
24620     return false;
24621   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
24622     return false;
24623   else if (TREE_CODE (type) == TYPENAME_TYPE)
24624     return false;
24625   else if (TREE_CODE (type) == DECLTYPE_TYPE)
24626     return false;
24627   else if (TREE_CODE (type) == NULLPTR_TYPE)
24628     return false;
24629   /* A bound template template parm could later be instantiated to have a valid
24630      nontype parm type via an alias template.  */
24631   else if (cxx_dialect >= cxx11
24632 	   && TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
24633     return false;
24634 
24635   if (complain & tf_error)
24636     {
24637       if (type == error_mark_node)
24638 	inform (input_location, "invalid template non-type parameter");
24639       else
24640 	error ("%q#T is not a valid type for a template non-type parameter",
24641 	       type);
24642     }
24643   return true;
24644 }
24645 
24646 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
24647    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
24648 
24649 static bool
dependent_type_p_r(tree type)24650 dependent_type_p_r (tree type)
24651 {
24652   tree scope;
24653 
24654   /* [temp.dep.type]
24655 
24656      A type is dependent if it is:
24657 
24658      -- a template parameter. Template template parameters are types
24659 	for us (since TYPE_P holds true for them) so we handle
24660 	them here.  */
24661   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
24662       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
24663     return true;
24664   /* -- a qualified-id with a nested-name-specifier which contains a
24665 	class-name that names a dependent type or whose unqualified-id
24666 	names a dependent type.  */
24667   if (TREE_CODE (type) == TYPENAME_TYPE)
24668     return true;
24669 
24670   /* An alias template specialization can be dependent even if the
24671      resulting type is not.  */
24672   if (dependent_alias_template_spec_p (type))
24673     return true;
24674 
24675   /* -- a cv-qualified type where the cv-unqualified type is
24676 	dependent.
24677      No code is necessary for this bullet; the code below handles
24678      cv-qualified types, and we don't want to strip aliases with
24679      TYPE_MAIN_VARIANT because of DR 1558.  */
24680   /* -- a compound type constructed from any dependent type.  */
24681   if (TYPE_PTRMEM_P (type))
24682     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
24683 	    || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
24684 					   (type)));
24685   else if (TYPE_PTR_P (type)
24686 	   || TREE_CODE (type) == REFERENCE_TYPE)
24687     return dependent_type_p (TREE_TYPE (type));
24688   else if (TREE_CODE (type) == FUNCTION_TYPE
24689 	   || TREE_CODE (type) == METHOD_TYPE)
24690     {
24691       tree arg_type;
24692 
24693       if (dependent_type_p (TREE_TYPE (type)))
24694 	return true;
24695       for (arg_type = TYPE_ARG_TYPES (type);
24696 	   arg_type;
24697 	   arg_type = TREE_CHAIN (arg_type))
24698 	if (dependent_type_p (TREE_VALUE (arg_type)))
24699 	  return true;
24700       if (cxx_dialect >= cxx17)
24701 	/* A value-dependent noexcept-specifier makes the type dependent.  */
24702 	if (tree spec = TYPE_RAISES_EXCEPTIONS (type))
24703 	  if (tree noex = TREE_PURPOSE (spec))
24704 	    /* Treat DEFERRED_NOEXCEPT as non-dependent, since it doesn't
24705 	       affect overload resolution and treating it as dependent breaks
24706 	       things.  */
24707 	    if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
24708 		&& value_dependent_expression_p (noex))
24709 	      return true;
24710       return false;
24711     }
24712   /* -- an array type constructed from any dependent type or whose
24713 	size is specified by a constant expression that is
24714 	value-dependent.
24715 
24716         We checked for type- and value-dependence of the bounds in
24717         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
24718   if (TREE_CODE (type) == ARRAY_TYPE)
24719     {
24720       if (TYPE_DOMAIN (type)
24721 	  && dependent_type_p (TYPE_DOMAIN (type)))
24722 	return true;
24723       return dependent_type_p (TREE_TYPE (type));
24724     }
24725 
24726   /* -- a template-id in which either the template name is a template
24727      parameter ...  */
24728   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
24729     return true;
24730   /* ... or any of the template arguments is a dependent type or
24731 	an expression that is type-dependent or value-dependent.  */
24732   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
24733 	   && (any_dependent_template_arguments_p
24734 	       (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
24735     return true;
24736 
24737   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
24738      dependent; if the argument of the `typeof' expression is not
24739      type-dependent, then it should already been have resolved.  */
24740   if (TREE_CODE (type) == TYPEOF_TYPE
24741       || TREE_CODE (type) == DECLTYPE_TYPE
24742       || TREE_CODE (type) == UNDERLYING_TYPE)
24743     return true;
24744 
24745   /* A template argument pack is dependent if any of its packed
24746      arguments are.  */
24747   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
24748     {
24749       tree args = ARGUMENT_PACK_ARGS (type);
24750       int i, len = TREE_VEC_LENGTH (args);
24751       for (i = 0; i < len; ++i)
24752         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
24753           return true;
24754     }
24755 
24756   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
24757      be template parameters.  */
24758   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
24759     return true;
24760 
24761   if (any_dependent_type_attributes_p (TYPE_ATTRIBUTES (type)))
24762     return true;
24763 
24764   /* The standard does not specifically mention types that are local
24765      to template functions or local classes, but they should be
24766      considered dependent too.  For example:
24767 
24768        template <int I> void f() {
24769 	 enum E { a = I };
24770 	 S<sizeof (E)> s;
24771        }
24772 
24773      The size of `E' cannot be known until the value of `I' has been
24774      determined.  Therefore, `E' must be considered dependent.  */
24775   scope = TYPE_CONTEXT (type);
24776   if (scope && TYPE_P (scope))
24777     return dependent_type_p (scope);
24778   /* Don't use type_dependent_expression_p here, as it can lead
24779      to infinite recursion trying to determine whether a lambda
24780      nested in a lambda is dependent (c++/47687).  */
24781   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
24782 	   && DECL_LANG_SPECIFIC (scope)
24783 	   && DECL_TEMPLATE_INFO (scope)
24784 	   && (any_dependent_template_arguments_p
24785 	       (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
24786     return true;
24787 
24788   /* Other types are non-dependent.  */
24789   return false;
24790 }
24791 
24792 /* Returns TRUE if TYPE is dependent, in the sense of
24793    [temp.dep.type].  Note that a NULL type is considered dependent.  */
24794 
24795 bool
dependent_type_p(tree type)24796 dependent_type_p (tree type)
24797 {
24798   /* If there are no template parameters in scope, then there can't be
24799      any dependent types.  */
24800   if (!processing_template_decl)
24801     {
24802       /* If we are not processing a template, then nobody should be
24803 	 providing us with a dependent type.  */
24804       gcc_assert (type);
24805       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
24806       return false;
24807     }
24808 
24809   /* If the type is NULL, we have not computed a type for the entity
24810      in question; in that case, the type is dependent.  */
24811   if (!type)
24812     return true;
24813 
24814   /* Erroneous types can be considered non-dependent.  */
24815   if (type == error_mark_node)
24816     return false;
24817 
24818   /* Getting here with global_type_node means we improperly called this
24819      function on the TREE_TYPE of an IDENTIFIER_NODE.  */
24820   gcc_checking_assert (type != global_type_node);
24821 
24822   /* If we have not already computed the appropriate value for TYPE,
24823      do so now.  */
24824   if (!TYPE_DEPENDENT_P_VALID (type))
24825     {
24826       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
24827       TYPE_DEPENDENT_P_VALID (type) = 1;
24828     }
24829 
24830   return TYPE_DEPENDENT_P (type);
24831 }
24832 
24833 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
24834    lookup.  In other words, a dependent type that is not the current
24835    instantiation.  */
24836 
24837 bool
dependent_scope_p(tree scope)24838 dependent_scope_p (tree scope)
24839 {
24840   return (scope && TYPE_P (scope) && dependent_type_p (scope)
24841 	  && !currently_open_class (scope));
24842 }
24843 
24844 /* T is a SCOPE_REF.  Return whether it represents a non-static member of
24845    an unknown base of 'this' (and is therefore instantiation-dependent).  */
24846 
24847 static bool
unknown_base_ref_p(tree t)24848 unknown_base_ref_p (tree t)
24849 {
24850   if (!current_class_ptr)
24851     return false;
24852 
24853   tree mem = TREE_OPERAND (t, 1);
24854   if (shared_member_p (mem))
24855     return false;
24856 
24857   tree cur = current_nonlambda_class_type ();
24858   if (!any_dependent_bases_p (cur))
24859     return false;
24860 
24861   tree ctx = TREE_OPERAND (t, 0);
24862   if (DERIVED_FROM_P (ctx, cur))
24863     return false;
24864 
24865   return true;
24866 }
24867 
24868 /* T is a SCOPE_REF; return whether we need to consider it
24869     instantiation-dependent so that we can check access at instantiation
24870     time even though we know which member it resolves to.  */
24871 
24872 static bool
instantiation_dependent_scope_ref_p(tree t)24873 instantiation_dependent_scope_ref_p (tree t)
24874 {
24875   if (DECL_P (TREE_OPERAND (t, 1))
24876       && CLASS_TYPE_P (TREE_OPERAND (t, 0))
24877       && !unknown_base_ref_p (t)
24878       && accessible_in_template_p (TREE_OPERAND (t, 0),
24879 				   TREE_OPERAND (t, 1)))
24880     return false;
24881   else
24882     return true;
24883 }
24884 
24885 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
24886    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
24887    expression.  */
24888 
24889 /* Note that this predicate is not appropriate for general expressions;
24890    only constant expressions (that satisfy potential_constant_expression)
24891    can be tested for value dependence.  */
24892 
24893 bool
value_dependent_expression_p(tree expression)24894 value_dependent_expression_p (tree expression)
24895 {
24896   if (!processing_template_decl || expression == NULL_TREE)
24897     return false;
24898 
24899   /* A type-dependent expression is also value-dependent.  */
24900   if (type_dependent_expression_p (expression))
24901     return true;
24902 
24903   switch (TREE_CODE (expression))
24904     {
24905     case BASELINK:
24906       /* A dependent member function of the current instantiation.  */
24907       return dependent_type_p (BINFO_TYPE (BASELINK_BINFO (expression)));
24908 
24909     case FUNCTION_DECL:
24910       /* A dependent member function of the current instantiation.  */
24911       if (DECL_CLASS_SCOPE_P (expression)
24912 	  && dependent_type_p (DECL_CONTEXT (expression)))
24913 	return true;
24914       break;
24915 
24916     case IDENTIFIER_NODE:
24917       /* A name that has not been looked up -- must be dependent.  */
24918       return true;
24919 
24920     case TEMPLATE_PARM_INDEX:
24921       /* A non-type template parm.  */
24922       return true;
24923 
24924     case CONST_DECL:
24925       /* A non-type template parm.  */
24926       if (DECL_TEMPLATE_PARM_P (expression))
24927 	return true;
24928       return value_dependent_expression_p (DECL_INITIAL (expression));
24929 
24930     case VAR_DECL:
24931        /* A constant with literal type and is initialized
24932 	  with an expression that is value-dependent.  */
24933       if (DECL_DEPENDENT_INIT_P (expression)
24934 	  /* FIXME cp_finish_decl doesn't fold reference initializers.  */
24935 	  || TREE_CODE (TREE_TYPE (expression)) == REFERENCE_TYPE)
24936 	return true;
24937       if (DECL_HAS_VALUE_EXPR_P (expression))
24938 	{
24939 	  tree value_expr = DECL_VALUE_EXPR (expression);
24940 	  if (value_dependent_expression_p (value_expr))
24941 	    return true;
24942 	}
24943       return false;
24944 
24945     case DYNAMIC_CAST_EXPR:
24946     case STATIC_CAST_EXPR:
24947     case CONST_CAST_EXPR:
24948     case REINTERPRET_CAST_EXPR:
24949     case CAST_EXPR:
24950     case IMPLICIT_CONV_EXPR:
24951       /* These expressions are value-dependent if the type to which
24952 	 the cast occurs is dependent or the expression being casted
24953 	 is value-dependent.  */
24954       {
24955 	tree type = TREE_TYPE (expression);
24956 
24957 	if (dependent_type_p (type))
24958 	  return true;
24959 
24960 	/* A functional cast has a list of operands.  */
24961 	expression = TREE_OPERAND (expression, 0);
24962 	if (!expression)
24963 	  {
24964 	    /* If there are no operands, it must be an expression such
24965 	       as "int()". This should not happen for aggregate types
24966 	       because it would form non-constant expressions.  */
24967 	    gcc_assert (cxx_dialect >= cxx11
24968 			|| INTEGRAL_OR_ENUMERATION_TYPE_P (type));
24969 
24970 	    return false;
24971 	  }
24972 
24973 	if (TREE_CODE (expression) == TREE_LIST)
24974 	  return any_value_dependent_elements_p (expression);
24975 
24976 	return value_dependent_expression_p (expression);
24977       }
24978 
24979     case SIZEOF_EXPR:
24980       if (SIZEOF_EXPR_TYPE_P (expression))
24981 	return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
24982       /* FALLTHRU */
24983     case ALIGNOF_EXPR:
24984     case TYPEID_EXPR:
24985       /* A `sizeof' expression is value-dependent if the operand is
24986 	 type-dependent or is a pack expansion.  */
24987       expression = TREE_OPERAND (expression, 0);
24988       if (PACK_EXPANSION_P (expression))
24989         return true;
24990       else if (TYPE_P (expression))
24991 	return dependent_type_p (expression);
24992       return instantiation_dependent_uneval_expression_p (expression);
24993 
24994     case AT_ENCODE_EXPR:
24995       /* An 'encode' expression is value-dependent if the operand is
24996 	 type-dependent.  */
24997       expression = TREE_OPERAND (expression, 0);
24998       return dependent_type_p (expression);
24999 
25000     case NOEXCEPT_EXPR:
25001       expression = TREE_OPERAND (expression, 0);
25002       return instantiation_dependent_uneval_expression_p (expression);
25003 
25004     case SCOPE_REF:
25005       /* All instantiation-dependent expressions should also be considered
25006 	 value-dependent.  */
25007       return instantiation_dependent_scope_ref_p (expression);
25008 
25009     case COMPONENT_REF:
25010       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
25011 	      || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
25012 
25013     case NONTYPE_ARGUMENT_PACK:
25014       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
25015          is value-dependent.  */
25016       {
25017         tree values = ARGUMENT_PACK_ARGS (expression);
25018         int i, len = TREE_VEC_LENGTH (values);
25019 
25020         for (i = 0; i < len; ++i)
25021           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
25022             return true;
25023 
25024         return false;
25025       }
25026 
25027     case TRAIT_EXPR:
25028       {
25029 	tree type2 = TRAIT_EXPR_TYPE2 (expression);
25030 
25031 	if (dependent_type_p (TRAIT_EXPR_TYPE1 (expression)))
25032 	  return true;
25033 
25034 	if (!type2)
25035 	  return false;
25036 
25037 	if (TREE_CODE (type2) != TREE_LIST)
25038 	  return dependent_type_p (type2);
25039 
25040 	for (; type2; type2 = TREE_CHAIN (type2))
25041 	  if (dependent_type_p (TREE_VALUE (type2)))
25042 	    return true;
25043 
25044 	return false;
25045       }
25046 
25047     case MODOP_EXPR:
25048       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
25049 	      || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
25050 
25051     case ARRAY_REF:
25052       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
25053 	      || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
25054 
25055     case ADDR_EXPR:
25056       {
25057 	tree op = TREE_OPERAND (expression, 0);
25058 	return (value_dependent_expression_p (op)
25059 		|| has_value_dependent_address (op));
25060       }
25061 
25062     case REQUIRES_EXPR:
25063       /* Treat all requires-expressions as value-dependent so
25064          we don't try to fold them.  */
25065       return true;
25066 
25067     case TYPE_REQ:
25068       return dependent_type_p (TREE_OPERAND (expression, 0));
25069 
25070     case CALL_EXPR:
25071       {
25072 	if (value_dependent_expression_p (CALL_EXPR_FN (expression)))
25073 	  return true;
25074 	tree fn = get_callee_fndecl (expression);
25075 	int i, nargs;
25076 	nargs = call_expr_nargs (expression);
25077 	for (i = 0; i < nargs; ++i)
25078 	  {
25079 	    tree op = CALL_EXPR_ARG (expression, i);
25080 	    /* In a call to a constexpr member function, look through the
25081 	       implicit ADDR_EXPR on the object argument so that it doesn't
25082 	       cause the call to be considered value-dependent.  We also
25083 	       look through it in potential_constant_expression.  */
25084 	    if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
25085 		&& DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
25086 		&& TREE_CODE (op) == ADDR_EXPR)
25087 	      op = TREE_OPERAND (op, 0);
25088 	    if (value_dependent_expression_p (op))
25089 	      return true;
25090 	  }
25091 	return false;
25092       }
25093 
25094     case TEMPLATE_ID_EXPR:
25095       return variable_concept_p (TREE_OPERAND (expression, 0));
25096 
25097     case CONSTRUCTOR:
25098       {
25099 	unsigned ix;
25100 	tree val;
25101 	if (dependent_type_p (TREE_TYPE (expression)))
25102 	  return true;
25103 	FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
25104 	  if (value_dependent_expression_p (val))
25105 	    return true;
25106 	return false;
25107       }
25108 
25109     case STMT_EXPR:
25110       /* Treat a GNU statement expression as dependent to avoid crashing
25111 	 under instantiate_non_dependent_expr; it can't be constant.  */
25112       return true;
25113 
25114     default:
25115       /* A constant expression is value-dependent if any subexpression is
25116 	 value-dependent.  */
25117       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
25118 	{
25119 	case tcc_reference:
25120 	case tcc_unary:
25121 	case tcc_comparison:
25122 	case tcc_binary:
25123 	case tcc_expression:
25124 	case tcc_vl_exp:
25125 	  {
25126 	    int i, len = cp_tree_operand_length (expression);
25127 
25128 	    for (i = 0; i < len; i++)
25129 	      {
25130 		tree t = TREE_OPERAND (expression, i);
25131 
25132 		/* In some cases, some of the operands may be missing.
25133 		   (For example, in the case of PREDECREMENT_EXPR, the
25134 		   amount to increment by may be missing.)  That doesn't
25135 		   make the expression dependent.  */
25136 		if (t && value_dependent_expression_p (t))
25137 		  return true;
25138 	      }
25139 	  }
25140 	  break;
25141 	default:
25142 	  break;
25143 	}
25144       break;
25145     }
25146 
25147   /* The expression is not value-dependent.  */
25148   return false;
25149 }
25150 
25151 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
25152    [temp.dep.expr].  Note that an expression with no type is
25153    considered dependent.  Other parts of the compiler arrange for an
25154    expression with type-dependent subexpressions to have no type, so
25155    this function doesn't have to be fully recursive.  */
25156 
25157 bool
type_dependent_expression_p(tree expression)25158 type_dependent_expression_p (tree expression)
25159 {
25160   if (!processing_template_decl)
25161     return false;
25162 
25163   if (expression == NULL_TREE || expression == error_mark_node)
25164     return false;
25165 
25166   STRIP_ANY_LOCATION_WRAPPER (expression);
25167 
25168   /* An unresolved name is always dependent.  */
25169   if (identifier_p (expression)
25170       || TREE_CODE (expression) == USING_DECL
25171       || TREE_CODE (expression) == WILDCARD_DECL)
25172     return true;
25173 
25174   /* A fold expression is type-dependent. */
25175   if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
25176       || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
25177       || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
25178       || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
25179     return true;
25180 
25181   /* Some expression forms are never type-dependent.  */
25182   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
25183       || TREE_CODE (expression) == SIZEOF_EXPR
25184       || TREE_CODE (expression) == ALIGNOF_EXPR
25185       || TREE_CODE (expression) == AT_ENCODE_EXPR
25186       || TREE_CODE (expression) == NOEXCEPT_EXPR
25187       || TREE_CODE (expression) == TRAIT_EXPR
25188       || TREE_CODE (expression) == TYPEID_EXPR
25189       || TREE_CODE (expression) == DELETE_EXPR
25190       || TREE_CODE (expression) == VEC_DELETE_EXPR
25191       || TREE_CODE (expression) == THROW_EXPR
25192       || TREE_CODE (expression) == REQUIRES_EXPR)
25193     return false;
25194 
25195   /* The types of these expressions depends only on the type to which
25196      the cast occurs.  */
25197   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
25198       || TREE_CODE (expression) == STATIC_CAST_EXPR
25199       || TREE_CODE (expression) == CONST_CAST_EXPR
25200       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
25201       || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
25202       || TREE_CODE (expression) == CAST_EXPR)
25203     return dependent_type_p (TREE_TYPE (expression));
25204 
25205   /* The types of these expressions depends only on the type created
25206      by the expression.  */
25207   if (TREE_CODE (expression) == NEW_EXPR
25208       || TREE_CODE (expression) == VEC_NEW_EXPR)
25209     {
25210       /* For NEW_EXPR tree nodes created inside a template, either
25211 	 the object type itself or a TREE_LIST may appear as the
25212 	 operand 1.  */
25213       tree type = TREE_OPERAND (expression, 1);
25214       if (TREE_CODE (type) == TREE_LIST)
25215 	/* This is an array type.  We need to check array dimensions
25216 	   as well.  */
25217 	return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
25218 	       || value_dependent_expression_p
25219 		    (TREE_OPERAND (TREE_VALUE (type), 1));
25220       else
25221 	return dependent_type_p (type);
25222     }
25223 
25224   if (TREE_CODE (expression) == SCOPE_REF)
25225     {
25226       tree scope = TREE_OPERAND (expression, 0);
25227       tree name = TREE_OPERAND (expression, 1);
25228 
25229       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
25230 	 contains an identifier associated by name lookup with one or more
25231 	 declarations declared with a dependent type, or...a
25232 	 nested-name-specifier or qualified-id that names a member of an
25233 	 unknown specialization.  */
25234       return (type_dependent_expression_p (name)
25235 	      || dependent_scope_p (scope));
25236     }
25237 
25238   if (TREE_CODE (expression) == TEMPLATE_DECL
25239       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
25240     return uses_outer_template_parms (expression);
25241 
25242   if (TREE_CODE (expression) == STMT_EXPR)
25243     expression = stmt_expr_value_expr (expression);
25244 
25245   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
25246     {
25247       tree elt;
25248       unsigned i;
25249 
25250       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
25251 	{
25252 	  if (type_dependent_expression_p (elt))
25253 	    return true;
25254 	}
25255       return false;
25256     }
25257 
25258   /* A static data member of the current instantiation with incomplete
25259      array type is type-dependent, as the definition and specializations
25260      can have different bounds.  */
25261   if (VAR_P (expression)
25262       && DECL_CLASS_SCOPE_P (expression)
25263       && dependent_type_p (DECL_CONTEXT (expression))
25264       && VAR_HAD_UNKNOWN_BOUND (expression))
25265     return true;
25266 
25267   /* An array of unknown bound depending on a variadic parameter, eg:
25268 
25269      template<typename... Args>
25270        void foo (Args... args)
25271        {
25272          int arr[] = { args... };
25273        }
25274 
25275      template<int... vals>
25276        void bar ()
25277        {
25278          int arr[] = { vals... };
25279        }
25280 
25281      If the array has no length and has an initializer, it must be that
25282      we couldn't determine its length in cp_complete_array_type because
25283      it is dependent.  */
25284   if (VAR_P (expression)
25285       && TREE_TYPE (expression) != NULL_TREE
25286       && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
25287       && !TYPE_DOMAIN (TREE_TYPE (expression))
25288       && DECL_INITIAL (expression))
25289    return true;
25290 
25291   /* A function or variable template-id is type-dependent if it has any
25292      dependent template arguments.  */
25293   if (VAR_OR_FUNCTION_DECL_P (expression)
25294       && DECL_LANG_SPECIFIC (expression)
25295       && DECL_TEMPLATE_INFO (expression))
25296     {
25297       /* Consider the innermost template arguments, since those are the ones
25298 	 that come from the template-id; the template arguments for the
25299 	 enclosing class do not make it type-dependent unless they are used in
25300 	 the type of the decl.  */
25301       if (instantiates_primary_template_p (expression)
25302 	  && (any_dependent_template_arguments_p
25303 	      (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
25304 	return true;
25305     }
25306 
25307   /* Otherwise, if the function decl isn't from a dependent scope, it can't be
25308      type-dependent.  Checking this is important for functions with auto return
25309      type, which looks like a dependent type.  */
25310   if (TREE_CODE (expression) == FUNCTION_DECL
25311       && !(DECL_CLASS_SCOPE_P (expression)
25312 	   && dependent_type_p (DECL_CONTEXT (expression)))
25313       && !(DECL_LANG_SPECIFIC (expression)
25314 	   && DECL_FRIEND_P (expression)
25315 	   && (!DECL_FRIEND_CONTEXT (expression)
25316 	       || dependent_type_p (DECL_FRIEND_CONTEXT (expression))))
25317       && !DECL_LOCAL_FUNCTION_P (expression))
25318     {
25319       gcc_assert (!dependent_type_p (TREE_TYPE (expression))
25320 		  || undeduced_auto_decl (expression));
25321       return false;
25322     }
25323 
25324   /* Always dependent, on the number of arguments if nothing else.  */
25325   if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
25326     return true;
25327 
25328   if (TREE_TYPE (expression) == unknown_type_node)
25329     {
25330       if (TREE_CODE (expression) == ADDR_EXPR)
25331 	return type_dependent_expression_p (TREE_OPERAND (expression, 0));
25332       if (TREE_CODE (expression) == COMPONENT_REF
25333 	  || TREE_CODE (expression) == OFFSET_REF)
25334 	{
25335 	  if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
25336 	    return true;
25337 	  expression = TREE_OPERAND (expression, 1);
25338 	  if (identifier_p (expression))
25339 	    return false;
25340 	}
25341       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
25342       if (TREE_CODE (expression) == SCOPE_REF)
25343 	return false;
25344 
25345       if (BASELINK_P (expression))
25346 	{
25347 	  if (BASELINK_OPTYPE (expression)
25348 	      && dependent_type_p (BASELINK_OPTYPE (expression)))
25349 	    return true;
25350 	  expression = BASELINK_FUNCTIONS (expression);
25351 	}
25352 
25353       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
25354 	{
25355 	  if (any_dependent_template_arguments_p
25356 	      (TREE_OPERAND (expression, 1)))
25357 	    return true;
25358 	  expression = TREE_OPERAND (expression, 0);
25359 	  if (identifier_p (expression))
25360 	    return true;
25361 	}
25362 
25363       gcc_assert (TREE_CODE (expression) == OVERLOAD
25364 		  || TREE_CODE (expression) == FUNCTION_DECL);
25365 
25366       for (lkp_iterator iter (expression); iter; ++iter)
25367 	if (type_dependent_expression_p (*iter))
25368 	  return true;
25369 
25370       return false;
25371     }
25372 
25373   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
25374 
25375   /* Dependent type attributes might not have made it from the decl to
25376      the type yet.  */
25377   if (DECL_P (expression)
25378       && any_dependent_type_attributes_p (DECL_ATTRIBUTES (expression)))
25379     return true;
25380 
25381   return (dependent_type_p (TREE_TYPE (expression)));
25382 }
25383 
25384 /* [temp.dep.expr]/5: A class member access expression (5.2.5) is
25385    type-dependent if the expression refers to a member of the current
25386    instantiation and the type of the referenced member is dependent, or the
25387    class member access expression refers to a member of an unknown
25388    specialization.
25389 
25390    This function returns true if the OBJECT in such a class member access
25391    expression is of an unknown specialization.  */
25392 
25393 bool
type_dependent_object_expression_p(tree object)25394 type_dependent_object_expression_p (tree object)
25395 {
25396   /* An IDENTIFIER_NODE can sometimes have a TREE_TYPE, but it's still
25397      dependent.  */
25398   if (TREE_CODE (object) == IDENTIFIER_NODE)
25399     return true;
25400   tree scope = TREE_TYPE (object);
25401   return (!scope || dependent_scope_p (scope));
25402 }
25403 
25404 /* walk_tree callback function for instantiation_dependent_expression_p,
25405    below.  Returns non-zero if a dependent subexpression is found.  */
25406 
25407 static tree
instantiation_dependent_r(tree * tp,int * walk_subtrees,void *)25408 instantiation_dependent_r (tree *tp, int *walk_subtrees,
25409 			   void * /*data*/)
25410 {
25411   if (TYPE_P (*tp))
25412     {
25413       /* We don't have to worry about decltype currently because decltype
25414 	 of an instantiation-dependent expr is a dependent type.  This
25415 	 might change depending on the resolution of DR 1172.  */
25416       *walk_subtrees = false;
25417       return NULL_TREE;
25418     }
25419   enum tree_code code = TREE_CODE (*tp);
25420   switch (code)
25421     {
25422       /* Don't treat an argument list as dependent just because it has no
25423 	 TREE_TYPE.  */
25424     case TREE_LIST:
25425     case TREE_VEC:
25426     case NONTYPE_ARGUMENT_PACK:
25427       return NULL_TREE;
25428 
25429     case TEMPLATE_PARM_INDEX:
25430       return *tp;
25431 
25432       /* Handle expressions with type operands.  */
25433     case SIZEOF_EXPR:
25434     case ALIGNOF_EXPR:
25435     case TYPEID_EXPR:
25436     case AT_ENCODE_EXPR:
25437       {
25438 	tree op = TREE_OPERAND (*tp, 0);
25439 	if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
25440 	  op = TREE_TYPE (op);
25441 	if (TYPE_P (op))
25442 	  {
25443 	    if (dependent_type_p (op))
25444 	      return *tp;
25445 	    else
25446 	      {
25447 		*walk_subtrees = false;
25448 		return NULL_TREE;
25449 	      }
25450 	  }
25451 	break;
25452       }
25453 
25454     case COMPONENT_REF:
25455       if (identifier_p (TREE_OPERAND (*tp, 1)))
25456 	/* In a template, finish_class_member_access_expr creates a
25457 	   COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
25458 	   type-dependent, so that we can check access control at
25459 	   instantiation time (PR 42277).  See also Core issue 1273.  */
25460 	return *tp;
25461       break;
25462 
25463     case SCOPE_REF:
25464       if (instantiation_dependent_scope_ref_p (*tp))
25465 	return *tp;
25466       else
25467 	break;
25468 
25469       /* Treat statement-expressions as dependent.  */
25470     case BIND_EXPR:
25471       return *tp;
25472 
25473       /* Treat requires-expressions as dependent. */
25474     case REQUIRES_EXPR:
25475       return *tp;
25476 
25477     case CALL_EXPR:
25478       /* Treat calls to function concepts as dependent. */
25479       if (function_concept_check_p (*tp))
25480         return *tp;
25481       break;
25482 
25483     case TEMPLATE_ID_EXPR:
25484       /* And variable concepts.  */
25485       if (variable_concept_p (TREE_OPERAND (*tp, 0)))
25486 	return *tp;
25487       break;
25488 
25489     default:
25490       break;
25491     }
25492 
25493   if (type_dependent_expression_p (*tp))
25494     return *tp;
25495   else
25496     return NULL_TREE;
25497 }
25498 
25499 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
25500    sense defined by the ABI:
25501 
25502    "An expression is instantiation-dependent if it is type-dependent
25503    or value-dependent, or it has a subexpression that is type-dependent
25504    or value-dependent."
25505 
25506    Except don't actually check value-dependence for unevaluated expressions,
25507    because in sizeof(i) we don't care about the value of i.  Checking
25508    type-dependence will in turn check value-dependence of array bounds/template
25509    arguments as needed.  */
25510 
25511 bool
instantiation_dependent_uneval_expression_p(tree expression)25512 instantiation_dependent_uneval_expression_p (tree expression)
25513 {
25514   tree result;
25515 
25516   if (!processing_template_decl)
25517     return false;
25518 
25519   if (expression == error_mark_node)
25520     return false;
25521 
25522   result = cp_walk_tree_without_duplicates (&expression,
25523 					    instantiation_dependent_r, NULL);
25524   return result != NULL_TREE;
25525 }
25526 
25527 /* As above, but also check value-dependence of the expression as a whole.  */
25528 
25529 bool
instantiation_dependent_expression_p(tree expression)25530 instantiation_dependent_expression_p (tree expression)
25531 {
25532   return (instantiation_dependent_uneval_expression_p (expression)
25533 	  || value_dependent_expression_p (expression));
25534 }
25535 
25536 /* Like type_dependent_expression_p, but it also works while not processing
25537    a template definition, i.e. during substitution or mangling.  */
25538 
25539 bool
type_dependent_expression_p_push(tree expr)25540 type_dependent_expression_p_push (tree expr)
25541 {
25542   bool b;
25543   ++processing_template_decl;
25544   b = type_dependent_expression_p (expr);
25545   --processing_template_decl;
25546   return b;
25547 }
25548 
25549 /* Returns TRUE if ARGS contains a type-dependent expression.  */
25550 
25551 bool
any_type_dependent_arguments_p(const vec<tree,va_gc> * args)25552 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
25553 {
25554   unsigned int i;
25555   tree arg;
25556 
25557   FOR_EACH_VEC_SAFE_ELT (args, i, arg)
25558     {
25559       if (type_dependent_expression_p (arg))
25560 	return true;
25561     }
25562   return false;
25563 }
25564 
25565 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
25566    expressions) contains any type-dependent expressions.  */
25567 
25568 bool
any_type_dependent_elements_p(const_tree list)25569 any_type_dependent_elements_p (const_tree list)
25570 {
25571   for (; list; list = TREE_CHAIN (list))
25572     if (type_dependent_expression_p (TREE_VALUE (list)))
25573       return true;
25574 
25575   return false;
25576 }
25577 
25578 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
25579    expressions) contains any value-dependent expressions.  */
25580 
25581 bool
any_value_dependent_elements_p(const_tree list)25582 any_value_dependent_elements_p (const_tree list)
25583 {
25584   for (; list; list = TREE_CHAIN (list))
25585     if (value_dependent_expression_p (TREE_VALUE (list)))
25586       return true;
25587 
25588   return false;
25589 }
25590 
25591 /* Returns TRUE if the ARG (a template argument) is dependent.  */
25592 
25593 bool
dependent_template_arg_p(tree arg)25594 dependent_template_arg_p (tree arg)
25595 {
25596   if (!processing_template_decl)
25597     return false;
25598 
25599   /* Assume a template argument that was wrongly written by the user
25600      is dependent. This is consistent with what
25601      any_dependent_template_arguments_p [that calls this function]
25602      does.  */
25603   if (!arg || arg == error_mark_node)
25604     return true;
25605 
25606   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
25607     arg = argument_pack_select_arg (arg);
25608 
25609   if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
25610     return true;
25611   if (TREE_CODE (arg) == TEMPLATE_DECL)
25612     {
25613       if (DECL_TEMPLATE_PARM_P (arg))
25614 	return true;
25615       /* A member template of a dependent class is not necessarily
25616 	 type-dependent, but it is a dependent template argument because it
25617 	 will be a member of an unknown specialization to that template.  */
25618       tree scope = CP_DECL_CONTEXT (arg);
25619       return TYPE_P (scope) && dependent_type_p (scope);
25620     }
25621   else if (ARGUMENT_PACK_P (arg))
25622     {
25623       tree args = ARGUMENT_PACK_ARGS (arg);
25624       int i, len = TREE_VEC_LENGTH (args);
25625       for (i = 0; i < len; ++i)
25626         {
25627           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
25628             return true;
25629         }
25630 
25631       return false;
25632     }
25633   else if (TYPE_P (arg))
25634     return dependent_type_p (arg);
25635   else
25636     return (type_dependent_expression_p (arg)
25637 	    || value_dependent_expression_p (arg));
25638 }
25639 
25640 /* Returns true if ARGS (a collection of template arguments) contains
25641    any types that require structural equality testing.  */
25642 
25643 bool
any_template_arguments_need_structural_equality_p(tree args)25644 any_template_arguments_need_structural_equality_p (tree args)
25645 {
25646   int i;
25647   int j;
25648 
25649   if (!args)
25650     return false;
25651   if (args == error_mark_node)
25652     return true;
25653 
25654   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
25655     {
25656       tree level = TMPL_ARGS_LEVEL (args, i + 1);
25657       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
25658 	{
25659 	  tree arg = TREE_VEC_ELT (level, j);
25660 	  tree packed_args = NULL_TREE;
25661 	  int k, len = 1;
25662 
25663 	  if (ARGUMENT_PACK_P (arg))
25664 	    {
25665 	      /* Look inside the argument pack.  */
25666 	      packed_args = ARGUMENT_PACK_ARGS (arg);
25667 	      len = TREE_VEC_LENGTH (packed_args);
25668 	    }
25669 
25670 	  for (k = 0; k < len; ++k)
25671 	    {
25672 	      if (packed_args)
25673 		arg = TREE_VEC_ELT (packed_args, k);
25674 
25675 	      if (error_operand_p (arg))
25676 		return true;
25677 	      else if (TREE_CODE (arg) == TEMPLATE_DECL)
25678 		continue;
25679 	      else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
25680 		return true;
25681 	      else if (!TYPE_P (arg) && TREE_TYPE (arg)
25682 		       && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
25683 		return true;
25684 	    }
25685 	}
25686     }
25687 
25688   return false;
25689 }
25690 
25691 /* Returns true if ARGS (a collection of template arguments) contains
25692    any dependent arguments.  */
25693 
25694 bool
any_dependent_template_arguments_p(const_tree args)25695 any_dependent_template_arguments_p (const_tree args)
25696 {
25697   int i;
25698   int j;
25699 
25700   if (!args)
25701     return false;
25702   if (args == error_mark_node)
25703     return true;
25704 
25705   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
25706     {
25707       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
25708       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
25709 	if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
25710 	  return true;
25711     }
25712 
25713   return false;
25714 }
25715 
25716 /* Returns true if ARGS contains any errors.  */
25717 
25718 bool
any_erroneous_template_args_p(const_tree args)25719 any_erroneous_template_args_p (const_tree args)
25720 {
25721   int i;
25722   int j;
25723 
25724   if (args == error_mark_node)
25725     return true;
25726 
25727   if (args && TREE_CODE (args) != TREE_VEC)
25728     {
25729       if (tree ti = get_template_info (args))
25730 	args = TI_ARGS (ti);
25731       else
25732 	args = NULL_TREE;
25733     }
25734 
25735   if (!args)
25736     return false;
25737 
25738   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
25739     {
25740       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
25741       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
25742 	if (error_operand_p (TREE_VEC_ELT (level, j)))
25743 	  return true;
25744     }
25745 
25746   return false;
25747 }
25748 
25749 /* Returns TRUE if the template TMPL is type-dependent.  */
25750 
25751 bool
dependent_template_p(tree tmpl)25752 dependent_template_p (tree tmpl)
25753 {
25754   if (TREE_CODE (tmpl) == OVERLOAD)
25755     {
25756       for (lkp_iterator iter (tmpl); iter; ++iter)
25757 	if (dependent_template_p (*iter))
25758 	  return true;
25759       return false;
25760     }
25761 
25762   /* Template template parameters are dependent.  */
25763   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
25764       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
25765     return true;
25766   /* So are names that have not been looked up.  */
25767   if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
25768     return true;
25769   return false;
25770 }
25771 
25772 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
25773 
25774 bool
dependent_template_id_p(tree tmpl,tree args)25775 dependent_template_id_p (tree tmpl, tree args)
25776 {
25777   return (dependent_template_p (tmpl)
25778 	  || any_dependent_template_arguments_p (args));
25779 }
25780 
25781 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
25782    are dependent.  */
25783 
25784 bool
dependent_omp_for_p(tree declv,tree initv,tree condv,tree incrv)25785 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
25786 {
25787   int i;
25788 
25789   if (!processing_template_decl)
25790     return false;
25791 
25792   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
25793     {
25794       tree decl = TREE_VEC_ELT (declv, i);
25795       tree init = TREE_VEC_ELT (initv, i);
25796       tree cond = TREE_VEC_ELT (condv, i);
25797       tree incr = TREE_VEC_ELT (incrv, i);
25798 
25799       if (type_dependent_expression_p (decl)
25800 	  || TREE_CODE (decl) == SCOPE_REF)
25801 	return true;
25802 
25803       if (init && type_dependent_expression_p (init))
25804 	return true;
25805 
25806       if (type_dependent_expression_p (cond))
25807 	return true;
25808 
25809       if (COMPARISON_CLASS_P (cond)
25810 	  && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
25811 	      || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
25812 	return true;
25813 
25814       if (TREE_CODE (incr) == MODOP_EXPR)
25815 	{
25816 	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
25817 	      || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
25818 	    return true;
25819 	}
25820       else if (type_dependent_expression_p (incr))
25821 	return true;
25822       else if (TREE_CODE (incr) == MODIFY_EXPR)
25823 	{
25824 	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
25825 	    return true;
25826 	  else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
25827 	    {
25828 	      tree t = TREE_OPERAND (incr, 1);
25829 	      if (type_dependent_expression_p (TREE_OPERAND (t, 0))
25830 		  || type_dependent_expression_p (TREE_OPERAND (t, 1)))
25831 		return true;
25832 	    }
25833 	}
25834     }
25835 
25836   return false;
25837 }
25838 
25839 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
25840    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
25841    no such TYPE can be found.  Note that this function peers inside
25842    uninstantiated templates and therefore should be used only in
25843    extremely limited situations.  ONLY_CURRENT_P restricts this
25844    peering to the currently open classes hierarchy (which is required
25845    when comparing types).  */
25846 
25847 tree
resolve_typename_type(tree type,bool only_current_p)25848 resolve_typename_type (tree type, bool only_current_p)
25849 {
25850   tree scope;
25851   tree name;
25852   tree decl;
25853   int quals;
25854   tree pushed_scope;
25855   tree result;
25856 
25857   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
25858 
25859   scope = TYPE_CONTEXT (type);
25860   /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope.  */
25861   gcc_checking_assert (uses_template_parms (scope));
25862 
25863   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
25864      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
25865      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
25866      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
25867      identifier  of the TYPENAME_TYPE anymore.
25868      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
25869      TYPENAME_TYPE instead, we avoid messing up with a possible
25870      typedef variant case.  */
25871   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
25872 
25873   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
25874      it first before we can figure out what NAME refers to.  */
25875   if (TREE_CODE (scope) == TYPENAME_TYPE)
25876     {
25877       if (TYPENAME_IS_RESOLVING_P (scope))
25878 	/* Given a class template A with a dependent base with nested type C,
25879 	   typedef typename A::C::C C will land us here, as trying to resolve
25880 	   the initial A::C leads to the local C typedef, which leads back to
25881 	   A::C::C.  So we break the recursion now.  */
25882 	return type;
25883       else
25884 	scope = resolve_typename_type (scope, only_current_p);
25885     }
25886   /* If we don't know what SCOPE refers to, then we cannot resolve the
25887      TYPENAME_TYPE.  */
25888   if (!CLASS_TYPE_P (scope))
25889     return type;
25890   /* If this is a typedef, we don't want to look inside (c++/11987).  */
25891   if (typedef_variant_p (type))
25892     return type;
25893   /* If SCOPE isn't the template itself, it will not have a valid
25894      TYPE_FIELDS list.  */
25895   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
25896     /* scope is either the template itself or a compatible instantiation
25897        like X<T>, so look up the name in the original template.  */
25898     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
25899   /* If scope has no fields, it can't be a current instantiation.  Check this
25900      before currently_open_class to avoid infinite recursion (71515).  */
25901   if (!TYPE_FIELDS (scope))
25902     return type;
25903   /* If the SCOPE is not the current instantiation, there's no reason
25904      to look inside it.  */
25905   if (only_current_p && !currently_open_class (scope))
25906     return type;
25907   /* Enter the SCOPE so that name lookup will be resolved as if we
25908      were in the class definition.  In particular, SCOPE will no
25909      longer be considered a dependent type.  */
25910   pushed_scope = push_scope (scope);
25911   /* Look up the declaration.  */
25912   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
25913 			tf_warning_or_error);
25914 
25915   result = NULL_TREE;
25916 
25917   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
25918      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
25919   tree fullname = TYPENAME_TYPE_FULLNAME (type);
25920   if (!decl)
25921     /*nop*/;
25922   else if (identifier_p (fullname)
25923 	   && TREE_CODE (decl) == TYPE_DECL)
25924     {
25925       result = TREE_TYPE (decl);
25926       if (result == error_mark_node)
25927 	result = NULL_TREE;
25928     }
25929   else if (TREE_CODE (fullname) == TEMPLATE_ID_EXPR
25930 	   && DECL_CLASS_TEMPLATE_P (decl))
25931     {
25932       /* Obtain the template and the arguments.  */
25933       tree tmpl = TREE_OPERAND (fullname, 0);
25934       if (TREE_CODE (tmpl) == IDENTIFIER_NODE)
25935 	{
25936 	  /* We get here with a plain identifier because a previous tentative
25937 	     parse of the nested-name-specifier as part of a ptr-operator saw
25938 	     ::template X<A>.  The use of ::template is necessary in a
25939 	     ptr-operator, but wrong in a declarator-id.
25940 
25941 	     [temp.names]: In a qualified-id of a declarator-id, the keyword
25942 	     template shall not appear at the top level.  */
25943 	  pedwarn (EXPR_LOC_OR_LOC (fullname, input_location), OPT_Wpedantic,
25944 		   "keyword %<template%> not allowed in declarator-id");
25945 	  tmpl = decl;
25946 	}
25947       tree args = TREE_OPERAND (fullname, 1);
25948       /* Instantiate the template.  */
25949       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
25950 				      /*entering_scope=*/true,
25951 				      tf_error | tf_user);
25952       if (result == error_mark_node)
25953 	result = NULL_TREE;
25954     }
25955 
25956   /* Leave the SCOPE.  */
25957   if (pushed_scope)
25958     pop_scope (pushed_scope);
25959 
25960   /* If we failed to resolve it, return the original typename.  */
25961   if (!result)
25962     return type;
25963 
25964   /* If lookup found a typename type, resolve that too.  */
25965   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
25966     {
25967       /* Ill-formed programs can cause infinite recursion here, so we
25968 	 must catch that.  */
25969       TYPENAME_IS_RESOLVING_P (result) = 1;
25970       result = resolve_typename_type (result, only_current_p);
25971       TYPENAME_IS_RESOLVING_P (result) = 0;
25972     }
25973 
25974   /* Qualify the resulting type.  */
25975   quals = cp_type_quals (type);
25976   if (quals)
25977     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
25978 
25979   return result;
25980 }
25981 
25982 /* EXPR is an expression which is not type-dependent.  Return a proxy
25983    for EXPR that can be used to compute the types of larger
25984    expressions containing EXPR.  */
25985 
25986 tree
build_non_dependent_expr(tree expr)25987 build_non_dependent_expr (tree expr)
25988 {
25989   tree orig_expr = expr;
25990   tree inner_expr;
25991 
25992   /* When checking, try to get a constant value for all non-dependent
25993      expressions in order to expose bugs in *_dependent_expression_p
25994      and constexpr.  This can affect code generation, see PR70704, so
25995      only do this for -fchecking=2.  */
25996   if (flag_checking > 1
25997       && cxx_dialect >= cxx11
25998       /* Don't do this during nsdmi parsing as it can lead to
25999 	 unexpected recursive instantiations.  */
26000       && !parsing_nsdmi ()
26001       /* Don't do this during concept expansion either and for
26002          the same reason.  */
26003       && !expanding_concept ())
26004     fold_non_dependent_expr (expr);
26005 
26006   STRIP_ANY_LOCATION_WRAPPER (expr);
26007 
26008   /* Preserve OVERLOADs; the functions must be available to resolve
26009      types.  */
26010   inner_expr = expr;
26011   if (TREE_CODE (inner_expr) == STMT_EXPR)
26012     inner_expr = stmt_expr_value_expr (inner_expr);
26013   if (TREE_CODE (inner_expr) == ADDR_EXPR)
26014     inner_expr = TREE_OPERAND (inner_expr, 0);
26015   if (TREE_CODE (inner_expr) == COMPONENT_REF)
26016     inner_expr = TREE_OPERAND (inner_expr, 1);
26017   if (is_overloaded_fn (inner_expr)
26018       || TREE_CODE (inner_expr) == OFFSET_REF)
26019     return orig_expr;
26020   /* There is no need to return a proxy for a variable.  */
26021   if (VAR_P (expr))
26022     return orig_expr;
26023   /* Preserve string constants; conversions from string constants to
26024      "char *" are allowed, even though normally a "const char *"
26025      cannot be used to initialize a "char *".  */
26026   if (TREE_CODE (expr) == STRING_CST)
26027     return orig_expr;
26028   /* Preserve void and arithmetic constants, as an optimization -- there is no
26029      reason to create a new node.  */
26030   if (TREE_CODE (expr) == VOID_CST
26031       || TREE_CODE (expr) == INTEGER_CST
26032       || TREE_CODE (expr) == REAL_CST)
26033     return orig_expr;
26034   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
26035      There is at least one place where we want to know that a
26036      particular expression is a throw-expression: when checking a ?:
26037      expression, there are special rules if the second or third
26038      argument is a throw-expression.  */
26039   if (TREE_CODE (expr) == THROW_EXPR)
26040     return orig_expr;
26041 
26042   /* Don't wrap an initializer list, we need to be able to look inside.  */
26043   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
26044     return orig_expr;
26045 
26046   /* Don't wrap a dummy object, we need to be able to test for it.  */
26047   if (is_dummy_object (expr))
26048     return orig_expr;
26049 
26050   if (TREE_CODE (expr) == COND_EXPR)
26051     return build3 (COND_EXPR,
26052 		   TREE_TYPE (expr),
26053 		   TREE_OPERAND (expr, 0),
26054 		   (TREE_OPERAND (expr, 1)
26055 		    ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
26056 		    : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
26057 		   build_non_dependent_expr (TREE_OPERAND (expr, 2)));
26058   if (TREE_CODE (expr) == COMPOUND_EXPR
26059       && !COMPOUND_EXPR_OVERLOADED (expr))
26060     return build2 (COMPOUND_EXPR,
26061 		   TREE_TYPE (expr),
26062 		   TREE_OPERAND (expr, 0),
26063 		   build_non_dependent_expr (TREE_OPERAND (expr, 1)));
26064 
26065   /* If the type is unknown, it can't really be non-dependent */
26066   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
26067 
26068   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
26069   return build1_loc (EXPR_LOCATION (orig_expr), NON_DEPENDENT_EXPR,
26070 		     TREE_TYPE (expr), expr);
26071 }
26072 
26073 /* ARGS is a vector of expressions as arguments to a function call.
26074    Replace the arguments with equivalent non-dependent expressions.
26075    This modifies ARGS in place.  */
26076 
26077 void
make_args_non_dependent(vec<tree,va_gc> * args)26078 make_args_non_dependent (vec<tree, va_gc> *args)
26079 {
26080   unsigned int ix;
26081   tree arg;
26082 
26083   FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
26084     {
26085       tree newarg = build_non_dependent_expr (arg);
26086       if (newarg != arg)
26087 	(*args)[ix] = newarg;
26088     }
26089 }
26090 
26091 /* Returns a type which represents 'auto' or 'decltype(auto)'.  We use a
26092    TEMPLATE_TYPE_PARM with a level one deeper than the actual template
26093    parms.  If set_canonical is true, we set TYPE_CANONICAL on it.  */
26094 
26095 static tree
make_auto_1(tree name,bool set_canonical)26096 make_auto_1 (tree name, bool set_canonical)
26097 {
26098   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
26099   TYPE_NAME (au) = build_decl (input_location,
26100 			       TYPE_DECL, name, au);
26101   TYPE_STUB_DECL (au) = TYPE_NAME (au);
26102   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
26103     (0, processing_template_decl + 1, processing_template_decl + 1,
26104      TYPE_NAME (au), NULL_TREE);
26105   if (set_canonical)
26106     TYPE_CANONICAL (au) = canonical_type_parameter (au);
26107   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
26108   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
26109 
26110   return au;
26111 }
26112 
26113 tree
make_decltype_auto(void)26114 make_decltype_auto (void)
26115 {
26116   return make_auto_1 (decltype_auto_identifier, true);
26117 }
26118 
26119 tree
make_auto(void)26120 make_auto (void)
26121 {
26122   return make_auto_1 (auto_identifier, true);
26123 }
26124 
26125 /* Return a C++17 deduction placeholder for class template TMPL.  */
26126 
26127 tree
make_template_placeholder(tree tmpl)26128 make_template_placeholder (tree tmpl)
26129 {
26130   tree t = make_auto_1 (DECL_NAME (tmpl), false);
26131   CLASS_PLACEHOLDER_TEMPLATE (t) = tmpl;
26132   /* Our canonical type depends on the placeholder.  */
26133   TYPE_CANONICAL (t) = canonical_type_parameter (t);
26134   return t;
26135 }
26136 
26137 /* True iff T is a C++17 class template deduction placeholder.  */
26138 
26139 bool
template_placeholder_p(tree t)26140 template_placeholder_p (tree t)
26141 {
26142   return is_auto (t) && CLASS_PLACEHOLDER_TEMPLATE (t);
26143 }
26144 
26145 /* Make a "constrained auto" type-specifier. This is an
26146    auto type with constraints that must be associated after
26147    deduction.  The constraint is formed from the given
26148    CONC and its optional sequence of arguments, which are
26149    non-null if written as partial-concept-id.  */
26150 
26151 tree
make_constrained_auto(tree con,tree args)26152 make_constrained_auto (tree con, tree args)
26153 {
26154   tree type = make_auto_1 (auto_identifier, false);
26155 
26156   /* Build the constraint. */
26157   tree tmpl = DECL_TI_TEMPLATE (con);
26158   tree expr = VAR_P (con) ? tmpl : ovl_make (tmpl);
26159   expr = build_concept_check (expr, type, args);
26160 
26161   tree constr = normalize_expression (expr);
26162   PLACEHOLDER_TYPE_CONSTRAINTS (type) = constr;
26163 
26164   /* Our canonical type depends on the constraint.  */
26165   TYPE_CANONICAL (type) = canonical_type_parameter (type);
26166 
26167   /* Attach the constraint to the type declaration. */
26168   tree decl = TYPE_NAME (type);
26169   return decl;
26170 }
26171 
26172 /* Given type ARG, return std::initializer_list<ARG>.  */
26173 
26174 static tree
listify(tree arg)26175 listify (tree arg)
26176 {
26177   tree std_init_list = get_namespace_binding (std_node, init_list_identifier);
26178 
26179   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
26180     {
26181       gcc_rich_location richloc (input_location);
26182       maybe_add_include_fixit (&richloc, "<initializer_list>");
26183       error_at (&richloc,
26184 		"deducing from brace-enclosed initializer list"
26185 		" requires %<#include <initializer_list>%>");
26186 
26187       return error_mark_node;
26188     }
26189   tree argvec = make_tree_vec (1);
26190   TREE_VEC_ELT (argvec, 0) = arg;
26191 
26192   return lookup_template_class (std_init_list, argvec, NULL_TREE,
26193 				NULL_TREE, 0, tf_warning_or_error);
26194 }
26195 
26196 /* Replace auto in TYPE with std::initializer_list<auto>.  */
26197 
26198 static tree
listify_autos(tree type,tree auto_node)26199 listify_autos (tree type, tree auto_node)
26200 {
26201   tree init_auto = listify (auto_node);
26202   tree argvec = make_tree_vec (1);
26203   TREE_VEC_ELT (argvec, 0) = init_auto;
26204   if (processing_template_decl)
26205     argvec = add_to_template_args (current_template_args (), argvec);
26206   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
26207 }
26208 
26209 /* Hash traits for hashing possibly constrained 'auto'
26210    TEMPLATE_TYPE_PARMs for use by do_auto_deduction.  */
26211 
26212 struct auto_hash : default_hash_traits<tree>
26213 {
26214   static inline hashval_t hash (tree);
26215   static inline bool equal (tree, tree);
26216 };
26217 
26218 /* Hash the 'auto' T.  */
26219 
26220 inline hashval_t
hash(tree t)26221 auto_hash::hash (tree t)
26222 {
26223   if (tree c = PLACEHOLDER_TYPE_CONSTRAINTS (t))
26224     /* Matching constrained-type-specifiers denote the same template
26225        parameter, so hash the constraint.  */
26226     return hash_placeholder_constraint (c);
26227   else
26228     /* But unconstrained autos are all separate, so just hash the pointer.  */
26229     return iterative_hash_object (t, 0);
26230 }
26231 
26232 /* Compare two 'auto's.  */
26233 
26234 inline bool
equal(tree t1,tree t2)26235 auto_hash::equal (tree t1, tree t2)
26236 {
26237   if (t1 == t2)
26238     return true;
26239 
26240   tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
26241   tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
26242 
26243   /* Two unconstrained autos are distinct.  */
26244   if (!c1 || !c2)
26245     return false;
26246 
26247   return equivalent_placeholder_constraints (c1, c2);
26248 }
26249 
26250 /* for_each_template_parm callback for extract_autos: if t is a (possibly
26251    constrained) auto, add it to the vector.  */
26252 
26253 static int
extract_autos_r(tree t,void * data)26254 extract_autos_r (tree t, void *data)
26255 {
26256   hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
26257   if (is_auto (t))
26258     {
26259       /* All the autos were built with index 0; fix that up now.  */
26260       tree *p = hash.find_slot (t, INSERT);
26261       unsigned idx;
26262       if (*p)
26263 	/* If this is a repeated constrained-type-specifier, use the index we
26264 	   chose before.  */
26265 	idx = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (*p));
26266       else
26267 	{
26268 	  /* Otherwise this is new, so use the current count.  */
26269 	  *p = t;
26270 	  idx = hash.elements () - 1;
26271 	}
26272       TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (t)) = idx;
26273     }
26274 
26275   /* Always keep walking.  */
26276   return 0;
26277 }
26278 
26279 /* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
26280    says they can appear anywhere in the type.  */
26281 
26282 static tree
extract_autos(tree type)26283 extract_autos (tree type)
26284 {
26285   hash_set<tree> visited;
26286   hash_table<auto_hash> hash (2);
26287 
26288   for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
26289 
26290   tree tree_vec = make_tree_vec (hash.elements());
26291   for (hash_table<auto_hash>::iterator iter = hash.begin();
26292        iter != hash.end(); ++iter)
26293     {
26294       tree elt = *iter;
26295       unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
26296       TREE_VEC_ELT (tree_vec, i)
26297 	= build_tree_list (NULL_TREE, TYPE_NAME (elt));
26298     }
26299 
26300   return tree_vec;
26301 }
26302 
26303 /* The stem for deduction guide names.  */
26304 const char *const dguide_base = "__dguide_";
26305 
26306 /* Return the name for a deduction guide for class template TMPL.  */
26307 
26308 tree
dguide_name(tree tmpl)26309 dguide_name (tree tmpl)
26310 {
26311   tree type = (TYPE_P (tmpl) ? tmpl : TREE_TYPE (tmpl));
26312   tree tname = TYPE_IDENTIFIER (type);
26313   char *buf = (char *) alloca (1 + strlen (dguide_base)
26314 			       + IDENTIFIER_LENGTH (tname));
26315   memcpy (buf, dguide_base, strlen (dguide_base));
26316   memcpy (buf + strlen (dguide_base), IDENTIFIER_POINTER (tname),
26317 	  IDENTIFIER_LENGTH (tname) + 1);
26318   tree dname = get_identifier (buf);
26319   TREE_TYPE (dname) = type;
26320   return dname;
26321 }
26322 
26323 /* True if NAME is the name of a deduction guide.  */
26324 
26325 bool
dguide_name_p(tree name)26326 dguide_name_p (tree name)
26327 {
26328   return (TREE_CODE (name) == IDENTIFIER_NODE
26329 	  && TREE_TYPE (name)
26330 	  && !strncmp (IDENTIFIER_POINTER (name), dguide_base,
26331 		       strlen (dguide_base)));
26332 }
26333 
26334 /* True if FN is a deduction guide.  */
26335 
26336 bool
deduction_guide_p(const_tree fn)26337 deduction_guide_p (const_tree fn)
26338 {
26339   if (DECL_P (fn))
26340     if (tree name = DECL_NAME (fn))
26341       return dguide_name_p (name);
26342   return false;
26343 }
26344 
26345 /* True if FN is the copy deduction guide, i.e. A(A)->A.  */
26346 
26347 bool
copy_guide_p(const_tree fn)26348 copy_guide_p (const_tree fn)
26349 {
26350   gcc_assert (deduction_guide_p (fn));
26351   if (!DECL_ARTIFICIAL (fn))
26352     return false;
26353   tree parms = FUNCTION_FIRST_USER_PARMTYPE (DECL_TI_TEMPLATE (fn));
26354   return (TREE_CHAIN (parms) == void_list_node
26355 	  && same_type_p (TREE_VALUE (parms), TREE_TYPE (DECL_NAME (fn))));
26356 }
26357 
26358 /* True if FN is a guide generated from a constructor template.  */
26359 
26360 bool
template_guide_p(const_tree fn)26361 template_guide_p (const_tree fn)
26362 {
26363   gcc_assert (deduction_guide_p (fn));
26364   if (!DECL_ARTIFICIAL (fn))
26365     return false;
26366   tree tmpl = DECL_TI_TEMPLATE (fn);
26367   if (tree org = DECL_ABSTRACT_ORIGIN (tmpl))
26368     return PRIMARY_TEMPLATE_P (org);
26369   return false;
26370 }
26371 
26372 /* OLDDECL is a _DECL for a template parameter.  Return a similar parameter at
26373    LEVEL:INDEX, using tsubst_args and complain for substitution into non-type
26374    template parameter types.  Note that the handling of template template
26375    parameters relies on current_template_parms being set appropriately for the
26376    new template.  */
26377 
26378 static tree
rewrite_template_parm(tree olddecl,unsigned index,unsigned level,tree tsubst_args,tsubst_flags_t complain)26379 rewrite_template_parm (tree olddecl, unsigned index, unsigned level,
26380 		       tree tsubst_args, tsubst_flags_t complain)
26381 {
26382   if (olddecl == error_mark_node)
26383     return error_mark_node;
26384 
26385   tree oldidx = get_template_parm_index (olddecl);
26386 
26387   tree newtype;
26388   if (TREE_CODE (olddecl) == TYPE_DECL
26389       || TREE_CODE (olddecl) == TEMPLATE_DECL)
26390     {
26391       tree oldtype = TREE_TYPE (olddecl);
26392       newtype = cxx_make_type (TREE_CODE (oldtype));
26393       TYPE_MAIN_VARIANT (newtype) = newtype;
26394       if (TREE_CODE (oldtype) == TEMPLATE_TYPE_PARM)
26395 	TEMPLATE_TYPE_PARM_FOR_CLASS (newtype)
26396 	  = TEMPLATE_TYPE_PARM_FOR_CLASS (oldtype);
26397     }
26398   else
26399     {
26400       newtype = TREE_TYPE (olddecl);
26401       if (type_uses_auto (newtype))
26402 	{
26403 	  // Substitute once to fix references to other template parameters.
26404 	  newtype = tsubst (newtype, tsubst_args,
26405 			    complain|tf_partial, NULL_TREE);
26406 	  // Now substitute again to reduce the level of the auto.
26407 	  newtype = tsubst (newtype, current_template_args (),
26408 			    complain, NULL_TREE);
26409 	}
26410       else
26411 	newtype = tsubst (newtype, tsubst_args,
26412 			  complain, NULL_TREE);
26413     }
26414 
26415   tree newdecl
26416     = build_decl (DECL_SOURCE_LOCATION (olddecl), TREE_CODE (olddecl),
26417 		  DECL_NAME (olddecl), newtype);
26418   SET_DECL_TEMPLATE_PARM_P (newdecl);
26419 
26420   tree newidx;
26421   if (TREE_CODE (olddecl) == TYPE_DECL
26422       || TREE_CODE (olddecl) == TEMPLATE_DECL)
26423     {
26424       newidx = TEMPLATE_TYPE_PARM_INDEX (newtype)
26425 	= build_template_parm_index (index, level, level,
26426 				     newdecl, newtype);
26427       TEMPLATE_PARM_PARAMETER_PACK (newidx)
26428 	= TEMPLATE_PARM_PARAMETER_PACK (oldidx);
26429       TYPE_STUB_DECL (newtype) = TYPE_NAME (newtype) = newdecl;
26430       TYPE_CANONICAL (newtype) = canonical_type_parameter (newtype);
26431 
26432       if (TREE_CODE (olddecl) == TEMPLATE_DECL)
26433 	{
26434 	  DECL_TEMPLATE_RESULT (newdecl)
26435 	    = build_decl (DECL_SOURCE_LOCATION (olddecl), TYPE_DECL,
26436 			  DECL_NAME (olddecl), newtype);
26437 	  DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (newdecl)) = true;
26438 	  // First create a copy (ttargs) of tsubst_args with an
26439 	  // additional level for the template template parameter's own
26440 	  // template parameters (ttparms).
26441 	  tree ttparms = (INNERMOST_TEMPLATE_PARMS
26442 			  (DECL_TEMPLATE_PARMS (olddecl)));
26443 	  const int depth = TMPL_ARGS_DEPTH (tsubst_args);
26444 	  tree ttargs = make_tree_vec (depth + 1);
26445 	  for (int i = 0; i < depth; ++i)
26446 	    TREE_VEC_ELT (ttargs, i) = TREE_VEC_ELT (tsubst_args, i);
26447 	  TREE_VEC_ELT (ttargs, depth)
26448 	    = template_parms_level_to_args (ttparms);
26449 	  // Substitute ttargs into ttparms to fix references to
26450 	  // other template parameters.
26451 	  ttparms = tsubst_template_parms_level (ttparms, ttargs,
26452 						 complain|tf_partial);
26453 	  // Now substitute again with args based on tparms, to reduce
26454 	  // the level of the ttparms.
26455 	  ttargs = current_template_args ();
26456 	  ttparms = tsubst_template_parms_level (ttparms, ttargs,
26457 						 complain);
26458 	  // Finally, tack the adjusted parms onto tparms.
26459 	  ttparms = tree_cons (size_int (depth), ttparms,
26460 			       current_template_parms);
26461 	  DECL_TEMPLATE_PARMS (newdecl) = ttparms;
26462 	}
26463     }
26464   else
26465     {
26466       tree oldconst = TEMPLATE_PARM_DECL (oldidx);
26467       tree newconst
26468 	= build_decl (DECL_SOURCE_LOCATION (oldconst),
26469 		      TREE_CODE (oldconst),
26470 		      DECL_NAME (oldconst), newtype);
26471       TREE_CONSTANT (newconst) = TREE_CONSTANT (newdecl)
26472 	= TREE_READONLY (newconst) = TREE_READONLY (newdecl) = true;
26473       SET_DECL_TEMPLATE_PARM_P (newconst);
26474       newidx = build_template_parm_index (index, level, level,
26475 					  newconst, newtype);
26476       TEMPLATE_PARM_PARAMETER_PACK (newidx)
26477 	= TEMPLATE_PARM_PARAMETER_PACK (oldidx);
26478       DECL_INITIAL (newdecl) = DECL_INITIAL (newconst) = newidx;
26479     }
26480 
26481   return newdecl;
26482 }
26483 
26484 /* Returns a C++17 class deduction guide template based on the constructor
26485    CTOR.  As a special case, CTOR can be a RECORD_TYPE for an implicit default
26486    guide, or REFERENCE_TYPE for an implicit copy/move guide.  */
26487 
26488 static tree
build_deduction_guide(tree ctor,tree outer_args,tsubst_flags_t complain)26489 build_deduction_guide (tree ctor, tree outer_args, tsubst_flags_t complain)
26490 {
26491   tree type, tparms, targs, fparms, fargs, ci;
26492   bool memtmpl = false;
26493   bool explicit_p;
26494   location_t loc;
26495   tree fn_tmpl = NULL_TREE;
26496 
26497   if (TYPE_P (ctor))
26498     {
26499       type = ctor;
26500       bool copy_p = TREE_CODE (type) == REFERENCE_TYPE;
26501       if (copy_p)
26502 	{
26503 	  type = TREE_TYPE (type);
26504 	  fparms = tree_cons (NULL_TREE, type, void_list_node);
26505 	}
26506       else
26507 	fparms = void_list_node;
26508 
26509       tree ctmpl = CLASSTYPE_TI_TEMPLATE (type);
26510       tparms = DECL_TEMPLATE_PARMS (ctmpl);
26511       targs = CLASSTYPE_TI_ARGS (type);
26512       ci = NULL_TREE;
26513       fargs = NULL_TREE;
26514       loc = DECL_SOURCE_LOCATION (ctmpl);
26515       explicit_p = false;
26516     }
26517   else
26518     {
26519       ++processing_template_decl;
26520       bool ok = true;
26521 
26522       fn_tmpl
26523 	= (TREE_CODE (ctor) == TEMPLATE_DECL ? ctor
26524 	   : DECL_TI_TEMPLATE (ctor));
26525       if (outer_args)
26526 	fn_tmpl = tsubst (fn_tmpl, outer_args, complain, ctor);
26527       ctor = DECL_TEMPLATE_RESULT (fn_tmpl);
26528 
26529       type = DECL_CONTEXT (ctor);
26530 
26531       tparms = DECL_TEMPLATE_PARMS (fn_tmpl);
26532       /* If type is a member class template, DECL_TI_ARGS (ctor) will have
26533 	 fully specialized args for the enclosing class.  Strip those off, as
26534 	 the deduction guide won't have those template parameters.  */
26535       targs = get_innermost_template_args (DECL_TI_ARGS (ctor),
26536 						TMPL_PARMS_DEPTH (tparms));
26537       /* Discard the 'this' parameter.  */
26538       fparms = FUNCTION_ARG_CHAIN (ctor);
26539       fargs = TREE_CHAIN (DECL_ARGUMENTS (ctor));
26540       ci = get_constraints (ctor);
26541       loc = DECL_SOURCE_LOCATION (ctor);
26542       explicit_p = DECL_NONCONVERTING_P (ctor);
26543 
26544       if (PRIMARY_TEMPLATE_P (fn_tmpl))
26545 	{
26546 	  memtmpl = true;
26547 
26548 	  /* For a member template constructor, we need to flatten the two
26549 	     template parameter lists into one, and then adjust the function
26550 	     signature accordingly.  This gets...complicated.  */
26551 	  tree save_parms = current_template_parms;
26552 
26553 	  /* For a member template we should have two levels of parms/args, one
26554 	     for the class and one for the constructor.  We stripped
26555 	     specialized args for further enclosing classes above.  */
26556 	  const int depth = 2;
26557 	  gcc_assert (TMPL_ARGS_DEPTH (targs) == depth);
26558 
26559 	  /* Template args for translating references to the two-level template
26560 	     parameters into references to the one-level template parameters we
26561 	     are creating.  */
26562 	  tree tsubst_args = copy_node (targs);
26563 	  TMPL_ARGS_LEVEL (tsubst_args, depth)
26564 	    = copy_node (TMPL_ARGS_LEVEL (tsubst_args, depth));
26565 
26566 	  /* Template parms for the constructor template.  */
26567 	  tree ftparms = TREE_VALUE (tparms);
26568 	  unsigned flen = TREE_VEC_LENGTH (ftparms);
26569 	  /* Template parms for the class template.  */
26570 	  tparms = TREE_CHAIN (tparms);
26571 	  tree ctparms = TREE_VALUE (tparms);
26572 	  unsigned clen = TREE_VEC_LENGTH (ctparms);
26573 	  /* Template parms for the deduction guide start as a copy of the
26574 	     template parms for the class.  We set current_template_parms for
26575 	     lookup_template_class_1.  */
26576 	  current_template_parms = tparms = copy_node (tparms);
26577 	  tree new_vec = TREE_VALUE (tparms) = make_tree_vec (flen + clen);
26578 	  for (unsigned i = 0; i < clen; ++i)
26579 	    TREE_VEC_ELT (new_vec, i) = TREE_VEC_ELT (ctparms, i);
26580 
26581 	  /* Now we need to rewrite the constructor parms to append them to the
26582 	     class parms.  */
26583 	  for (unsigned i = 0; i < flen; ++i)
26584 	    {
26585 	      unsigned index = i + clen;
26586 	      unsigned level = 1;
26587 	      tree oldelt = TREE_VEC_ELT (ftparms, i);
26588 	      tree olddecl = TREE_VALUE (oldelt);
26589 	      tree newdecl = rewrite_template_parm (olddecl, index, level,
26590 						    tsubst_args, complain);
26591 	      if (newdecl == error_mark_node)
26592 		ok = false;
26593 	      tree newdef = tsubst_template_arg (TREE_PURPOSE (oldelt),
26594 						 tsubst_args, complain, ctor);
26595 	      tree list = build_tree_list (newdef, newdecl);
26596 	      TEMPLATE_PARM_CONSTRAINTS (list)
26597 		= tsubst_constraint_info (TEMPLATE_PARM_CONSTRAINTS (oldelt),
26598 					  tsubst_args, complain, ctor);
26599 	      TREE_VEC_ELT (new_vec, index) = list;
26600 	      TMPL_ARG (tsubst_args, depth, i) = template_parm_to_arg (list);
26601 	    }
26602 
26603 	  /* Now we have a final set of template parms to substitute into the
26604 	     function signature.  */
26605 	  targs = template_parms_to_args (tparms);
26606 	  fparms = tsubst_arg_types (fparms, tsubst_args, NULL_TREE,
26607 				     complain, ctor);
26608 	  if (fparms == error_mark_node)
26609 	    ok = false;
26610 	  if (ci)
26611 	    ci = tsubst_constraint_info (ci, tsubst_args, complain, ctor);
26612 
26613 	  /* Parms are to have DECL_CHAIN tsubsted, which would be skipped if
26614 	     cp_unevaluated_operand.  */
26615 	  temp_override<int> ev (cp_unevaluated_operand, 0);
26616 	  fargs = tsubst (fargs, tsubst_args, complain, ctor);
26617 	  current_template_parms = save_parms;
26618 	}
26619 
26620       --processing_template_decl;
26621       if (!ok)
26622 	return error_mark_node;
26623     }
26624 
26625   if (!memtmpl)
26626     {
26627       /* Copy the parms so we can set DECL_PRIMARY_TEMPLATE.  */
26628       tparms = copy_node (tparms);
26629       INNERMOST_TEMPLATE_PARMS (tparms)
26630 	= copy_node (INNERMOST_TEMPLATE_PARMS (tparms));
26631     }
26632 
26633   tree fntype = build_function_type (type, fparms);
26634   tree ded_fn = build_lang_decl_loc (loc,
26635 				     FUNCTION_DECL,
26636 				     dguide_name (type), fntype);
26637   DECL_ARGUMENTS (ded_fn) = fargs;
26638   DECL_ARTIFICIAL (ded_fn) = true;
26639   DECL_NONCONVERTING_P (ded_fn) = explicit_p;
26640   tree ded_tmpl = build_template_decl (ded_fn, tparms, /*member*/false);
26641   DECL_ARTIFICIAL (ded_tmpl) = true;
26642   DECL_TEMPLATE_RESULT (ded_tmpl) = ded_fn;
26643   TREE_TYPE (ded_tmpl) = TREE_TYPE (ded_fn);
26644   DECL_TEMPLATE_INFO (ded_fn) = build_template_info (ded_tmpl, targs);
26645   DECL_PRIMARY_TEMPLATE (ded_tmpl) = ded_tmpl;
26646   if (DECL_P (ctor))
26647     DECL_ABSTRACT_ORIGIN (ded_tmpl) = fn_tmpl;
26648   if (ci)
26649     set_constraints (ded_tmpl, ci);
26650 
26651   return ded_tmpl;
26652 }
26653 
26654 /* Deduce template arguments for the class template placeholder PTYPE for
26655    template TMPL based on the initializer INIT, and return the resulting
26656    type.  */
26657 
26658 static tree
do_class_deduction(tree ptype,tree tmpl,tree init,int flags,tsubst_flags_t complain)26659 do_class_deduction (tree ptype, tree tmpl, tree init, int flags,
26660 		    tsubst_flags_t complain)
26661 {
26662   if (!DECL_CLASS_TEMPLATE_P (tmpl))
26663     {
26664       /* We should have handled this in the caller.  */
26665       if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
26666 	return ptype;
26667       if (complain & tf_error)
26668 	error ("non-class template %qT used without template arguments", tmpl);
26669       return error_mark_node;
26670     }
26671   if (init && TREE_TYPE (init) == ptype)
26672     /* Using the template parm as its own argument.  */
26673     return ptype;
26674 
26675   tree type = TREE_TYPE (tmpl);
26676 
26677   bool try_list_ctor = false;
26678 
26679   vec<tree,va_gc> *args;
26680   if (init == NULL_TREE
26681       || TREE_CODE (init) == TREE_LIST)
26682     args = make_tree_vector_from_list (init);
26683   else if (BRACE_ENCLOSED_INITIALIZER_P (init))
26684     {
26685       try_list_ctor = TYPE_HAS_LIST_CTOR (type);
26686       if (try_list_ctor && CONSTRUCTOR_NELTS (init) == 1)
26687 	{
26688 	  /* As an exception, the first phase in 16.3.1.7 (considering the
26689 	     initializer list as a single argument) is omitted if the
26690 	     initializer list consists of a single expression of type cv U,
26691 	     where U is a specialization of C or a class derived from a
26692 	     specialization of C.  */
26693 	  tree elt = CONSTRUCTOR_ELT (init, 0)->value;
26694 	  tree etype = TREE_TYPE (elt);
26695 
26696 	  tree tparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
26697 	  tree targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
26698 	  int err = unify (tparms, targs, type, etype,
26699 			   UNIFY_ALLOW_DERIVED, /*explain*/false);
26700 	  if (err == 0)
26701 	    try_list_ctor = false;
26702 	  ggc_free (targs);
26703 	}
26704       if (try_list_ctor || is_std_init_list (type))
26705 	args = make_tree_vector_single (init);
26706       else
26707 	args = make_tree_vector_from_ctor (init);
26708     }
26709   else
26710     args = make_tree_vector_single (init);
26711 
26712   tree dname = dguide_name (tmpl);
26713   tree cands = lookup_qualified_name (CP_DECL_CONTEXT (tmpl), dname,
26714 				      /*type*/false, /*complain*/false,
26715 				      /*hidden*/false);
26716   bool elided = false;
26717   if (cands == error_mark_node)
26718     cands = NULL_TREE;
26719 
26720   /* Prune explicit deduction guides in copy-initialization context.  */
26721   if (flags & LOOKUP_ONLYCONVERTING)
26722     {
26723       for (lkp_iterator iter (cands); !elided && iter; ++iter)
26724 	if (DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
26725 	  elided = true;
26726 
26727       if (elided)
26728 	{
26729 	  /* Found a nonconverting guide, prune the candidates.  */
26730 	  tree pruned = NULL_TREE;
26731 	  for (lkp_iterator iter (cands); iter; ++iter)
26732 	    if (!DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
26733 	      pruned = lookup_add (*iter, pruned);
26734 
26735 	  cands = pruned;
26736 	}
26737     }
26738 
26739   tree outer_args = NULL_TREE;
26740   if (DECL_CLASS_SCOPE_P (tmpl)
26741       && CLASSTYPE_TEMPLATE_INSTANTIATION (DECL_CONTEXT (tmpl)))
26742     {
26743       outer_args = CLASSTYPE_TI_ARGS (DECL_CONTEXT (tmpl));
26744       type = TREE_TYPE (most_general_template (tmpl));
26745     }
26746 
26747   bool saw_ctor = false;
26748   // FIXME cache artificial deduction guides
26749   for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (type)); iter; ++iter)
26750     {
26751       /* Skip inherited constructors.  */
26752       if (iter.using_p ())
26753 	continue;
26754 
26755       tree guide = build_deduction_guide (*iter, outer_args, complain);
26756       if (guide == error_mark_node)
26757 	return error_mark_node;
26758       if ((flags & LOOKUP_ONLYCONVERTING)
26759 	  && DECL_NONCONVERTING_P (STRIP_TEMPLATE (guide)))
26760 	elided = true;
26761       else
26762 	cands = lookup_add (guide, cands);
26763 
26764       saw_ctor = true;
26765     }
26766 
26767   tree call = error_mark_node;
26768 
26769   /* If this is list-initialization and the class has a list constructor, first
26770      try deducing from the list as a single argument, as [over.match.list].  */
26771   tree list_cands = NULL_TREE;
26772   if (try_list_ctor && cands)
26773     for (lkp_iterator iter (cands); iter; ++iter)
26774       {
26775 	tree dg = *iter;
26776 	if (is_list_ctor (dg))
26777 	  list_cands = lookup_add (dg, list_cands);
26778       }
26779   if (list_cands)
26780     {
26781       ++cp_unevaluated_operand;
26782       call = build_new_function_call (list_cands, &args, tf_decltype);
26783       --cp_unevaluated_operand;
26784 
26785       if (call == error_mark_node)
26786 	{
26787 	  /* That didn't work, now try treating the list as a sequence of
26788 	     arguments.  */
26789 	  release_tree_vector (args);
26790 	  args = make_tree_vector_from_ctor (init);
26791 	}
26792     }
26793 
26794   /* Maybe generate an implicit deduction guide.  */
26795   if (call == error_mark_node && args->length () < 2)
26796     {
26797       tree gtype = NULL_TREE;
26798 
26799       if (args->length () == 1)
26800 	/* Generate a copy guide.  */
26801 	gtype = build_reference_type (type);
26802       else if (!saw_ctor)
26803 	/* Generate a default guide.  */
26804 	gtype = type;
26805 
26806       if (gtype)
26807 	{
26808 	  tree guide = build_deduction_guide (gtype, outer_args, complain);
26809 	  if (guide == error_mark_node)
26810 	    return error_mark_node;
26811 	  cands = lookup_add (guide, cands);
26812 	}
26813     }
26814 
26815   if (elided && !cands)
26816     {
26817       error ("cannot deduce template arguments for copy-initialization"
26818 	     " of %qT, as it has no non-explicit deduction guides or "
26819 	     "user-declared constructors", type);
26820       return error_mark_node;
26821     }
26822   else if (!cands && call == error_mark_node)
26823     {
26824       error ("cannot deduce template arguments of %qT, as it has no viable "
26825 	     "deduction guides", type);
26826       return error_mark_node;
26827     }
26828 
26829   if (call == error_mark_node)
26830     {
26831       ++cp_unevaluated_operand;
26832       call = build_new_function_call (cands, &args, tf_decltype);
26833       --cp_unevaluated_operand;
26834     }
26835 
26836   if (call == error_mark_node && (complain & tf_warning_or_error))
26837     {
26838       error ("class template argument deduction failed:");
26839 
26840       ++cp_unevaluated_operand;
26841       call = build_new_function_call (cands, &args, complain | tf_decltype);
26842       --cp_unevaluated_operand;
26843 
26844       if (elided)
26845 	inform (input_location, "explicit deduction guides not considered "
26846 		"for copy-initialization");
26847     }
26848 
26849   release_tree_vector (args);
26850 
26851   return cp_build_qualified_type (TREE_TYPE (call), cp_type_quals (ptype));
26852 }
26853 
26854 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
26855    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
26856    The CONTEXT determines the context in which auto deduction is performed
26857    and is used to control error diagnostics.  FLAGS are the LOOKUP_* flags.
26858    OUTER_TARGS are used during template argument deduction
26859    (context == adc_unify) to properly substitute the result, and is ignored
26860    in other contexts.
26861 
26862    For partial-concept-ids, extra args may be appended to the list of deduced
26863    template arguments prior to determining constraint satisfaction.  */
26864 
26865 tree
do_auto_deduction(tree type,tree init,tree auto_node,tsubst_flags_t complain,auto_deduction_context context,tree outer_targs,int flags)26866 do_auto_deduction (tree type, tree init, tree auto_node,
26867                    tsubst_flags_t complain, auto_deduction_context context,
26868 		   tree outer_targs, int flags)
26869 {
26870   tree targs;
26871 
26872   if (init == error_mark_node)
26873     return error_mark_node;
26874 
26875   if (init && type_dependent_expression_p (init)
26876       && context != adc_unify)
26877     /* Defining a subset of type-dependent expressions that we can deduce
26878        from ahead of time isn't worth the trouble.  */
26879     return type;
26880 
26881   /* Similarly, we can't deduce from another undeduced decl.  */
26882   if (init && undeduced_auto_decl (init))
26883     return type;
26884 
26885   if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
26886     /* C++17 class template argument deduction.  */
26887     return do_class_deduction (type, tmpl, init, flags, complain);
26888 
26889   if (init == NULL_TREE || TREE_TYPE (init) == NULL_TREE)
26890     /* Nothing we can do with this, even in deduction context.  */
26891     return type;
26892 
26893   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
26894      with either a new invented type template parameter U or, if the
26895      initializer is a braced-init-list (8.5.4), with
26896      std::initializer_list<U>.  */
26897   if (BRACE_ENCLOSED_INITIALIZER_P (init))
26898     {
26899       if (!DIRECT_LIST_INIT_P (init))
26900 	type = listify_autos (type, auto_node);
26901       else if (CONSTRUCTOR_NELTS (init) == 1)
26902 	init = CONSTRUCTOR_ELT (init, 0)->value;
26903       else
26904 	{
26905           if (complain & tf_warning_or_error)
26906             {
26907 	      if (permerror (input_location, "direct-list-initialization of "
26908 			     "%<auto%> requires exactly one element"))
26909 	        inform (input_location,
26910 		        "for deduction to %<std::initializer_list%>, use copy-"
26911 		        "list-initialization (i.e. add %<=%> before the %<{%>)");
26912             }
26913 	  type = listify_autos (type, auto_node);
26914 	}
26915     }
26916 
26917   if (type == error_mark_node)
26918     return error_mark_node;
26919 
26920   init = resolve_nondeduced_context (init, complain);
26921 
26922   if (context == adc_decomp_type
26923       && auto_node == type
26924       && init != error_mark_node
26925       && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
26926     /* [dcl.decomp]/1 - if decomposition declaration has no ref-qualifiers
26927        and initializer has array type, deduce cv-qualified array type.  */
26928     return cp_build_qualified_type_real (TREE_TYPE (init), TYPE_QUALS (type),
26929 					 complain);
26930   else if (AUTO_IS_DECLTYPE (auto_node))
26931     {
26932       bool id = (DECL_P (init)
26933 		 || ((TREE_CODE (init) == COMPONENT_REF
26934 		      || TREE_CODE (init) == SCOPE_REF)
26935 		     && !REF_PARENTHESIZED_P (init)));
26936       targs = make_tree_vec (1);
26937       TREE_VEC_ELT (targs, 0)
26938 	= finish_decltype_type (init, id, tf_warning_or_error);
26939       if (type != auto_node)
26940 	{
26941           if (complain & tf_error)
26942 	    error ("%qT as type rather than plain %<decltype(auto)%>", type);
26943 	  return error_mark_node;
26944 	}
26945     }
26946   else
26947     {
26948       tree parms = build_tree_list (NULL_TREE, type);
26949       tree tparms;
26950 
26951       if (flag_concepts)
26952 	tparms = extract_autos (type);
26953       else
26954 	{
26955 	  tparms = make_tree_vec (1);
26956 	  TREE_VEC_ELT (tparms, 0)
26957 	    = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
26958 	}
26959 
26960       targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
26961       int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
26962 				       DEDUCE_CALL, LOOKUP_NORMAL,
26963 				       NULL, /*explain_p=*/false);
26964       if (val > 0)
26965 	{
26966 	  if (processing_template_decl)
26967 	    /* Try again at instantiation time.  */
26968 	    return type;
26969 	  if (type && type != error_mark_node
26970 	      && (complain & tf_error))
26971 	    /* If type is error_mark_node a diagnostic must have been
26972 	       emitted by now.  Also, having a mention to '<type error>'
26973 	       in the diagnostic is not really useful to the user.  */
26974 	    {
26975 	      if (cfun && auto_node == current_function_auto_return_pattern
26976 		  && LAMBDA_FUNCTION_P (current_function_decl))
26977 		error ("unable to deduce lambda return type from %qE", init);
26978 	      else
26979 		error ("unable to deduce %qT from %qE", type, init);
26980 	      type_unification_real (tparms, targs, parms, &init, 1, 0,
26981 				     DEDUCE_CALL, LOOKUP_NORMAL,
26982 				     NULL, /*explain_p=*/true);
26983 	    }
26984 	  return error_mark_node;
26985 	}
26986     }
26987 
26988   /* Check any placeholder constraints against the deduced type. */
26989   if (flag_concepts && !processing_template_decl)
26990     if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (auto_node))
26991       {
26992         /* Use the deduced type to check the associated constraints. If we
26993            have a partial-concept-id, rebuild the argument list so that
26994            we check using the extra arguments. */
26995         gcc_assert (TREE_CODE (constr) == CHECK_CONSTR);
26996         tree cargs = CHECK_CONSTR_ARGS (constr);
26997         if (TREE_VEC_LENGTH (cargs) > 1)
26998           {
26999             cargs = copy_node (cargs);
27000             TREE_VEC_ELT (cargs, 0) = TREE_VEC_ELT (targs, 0);
27001           }
27002         else
27003           cargs = targs;
27004         if (!constraints_satisfied_p (constr, cargs))
27005           {
27006             if (complain & tf_warning_or_error)
27007               {
27008                 switch (context)
27009                   {
27010                   case adc_unspecified:
27011 		  case adc_unify:
27012                     error("placeholder constraints not satisfied");
27013                     break;
27014                   case adc_variable_type:
27015 		  case adc_decomp_type:
27016                     error ("deduced initializer does not satisfy "
27017                            "placeholder constraints");
27018                     break;
27019                   case adc_return_type:
27020                     error ("deduced return type does not satisfy "
27021                            "placeholder constraints");
27022                     break;
27023                   case adc_requirement:
27024 		    error ("deduced expression type does not satisfy "
27025                            "placeholder constraints");
27026                     break;
27027                   }
27028                 diagnose_constraints (input_location, constr, targs);
27029               }
27030             return error_mark_node;
27031           }
27032       }
27033 
27034   if (processing_template_decl && context != adc_unify)
27035     outer_targs = current_template_args ();
27036   targs = add_to_template_args (outer_targs, targs);
27037   return tsubst (type, targs, complain, NULL_TREE);
27038 }
27039 
27040 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
27041    result.  */
27042 
27043 tree
splice_late_return_type(tree type,tree late_return_type)27044 splice_late_return_type (tree type, tree late_return_type)
27045 {
27046   if (is_auto (type))
27047     {
27048       if (late_return_type)
27049 	return late_return_type;
27050 
27051       tree idx = get_template_parm_index (type);
27052       if (TEMPLATE_PARM_LEVEL (idx) <= processing_template_decl)
27053 	/* In an abbreviated function template we didn't know we were dealing
27054 	   with a function template when we saw the auto return type, so update
27055 	   it to have the correct level.  */
27056 	return make_auto_1 (TYPE_IDENTIFIER (type), true);
27057     }
27058   return type;
27059 }
27060 
27061 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
27062    'decltype(auto)' or a deduced class template.  */
27063 
27064 bool
is_auto(const_tree type)27065 is_auto (const_tree type)
27066 {
27067   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
27068       && (TYPE_IDENTIFIER (type) == auto_identifier
27069 	  || TYPE_IDENTIFIER (type) == decltype_auto_identifier
27070 	  || CLASS_PLACEHOLDER_TEMPLATE (type)))
27071     return true;
27072   else
27073     return false;
27074 }
27075 
27076 /* for_each_template_parm callback for type_uses_auto.  */
27077 
27078 int
is_auto_r(tree tp,void *)27079 is_auto_r (tree tp, void */*data*/)
27080 {
27081   return is_auto (tp);
27082 }
27083 
27084 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
27085    a use of `auto'.  Returns NULL_TREE otherwise.  */
27086 
27087 tree
type_uses_auto(tree type)27088 type_uses_auto (tree type)
27089 {
27090   if (type == NULL_TREE)
27091     return NULL_TREE;
27092   else if (flag_concepts)
27093     {
27094       /* The Concepts TS allows multiple autos in one type-specifier; just
27095 	 return the first one we find, do_auto_deduction will collect all of
27096 	 them.  */
27097       if (uses_template_parms (type))
27098 	return for_each_template_parm (type, is_auto_r, /*data*/NULL,
27099 				       /*visited*/NULL, /*nondeduced*/false);
27100       else
27101 	return NULL_TREE;
27102     }
27103   else
27104     return find_type_usage (type, is_auto);
27105 }
27106 
27107 /* Report ill-formed occurrences of auto types in ARGUMENTS.  If
27108    concepts are enabled, auto is acceptable in template arguments, but
27109    only when TEMPL identifies a template class.  Return TRUE if any
27110    such errors were reported.  */
27111 
27112 bool
check_auto_in_tmpl_args(tree tmpl,tree args)27113 check_auto_in_tmpl_args (tree tmpl, tree args)
27114 {
27115   /* If there were previous errors, nevermind.  */
27116   if (!args || TREE_CODE (args) != TREE_VEC)
27117     return false;
27118 
27119   /* If TMPL is an identifier, we're parsing and we can't tell yet
27120      whether TMPL is supposed to be a type, a function or a variable.
27121      We'll only be able to tell during template substitution, so we
27122      expect to be called again then.  If concepts are enabled and we
27123      know we have a type, we're ok.  */
27124   if (flag_concepts
27125       && (identifier_p (tmpl)
27126 	  || (DECL_P (tmpl)
27127 	      &&  (DECL_TYPE_TEMPLATE_P (tmpl)
27128 		   || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)))))
27129     return false;
27130 
27131   /* Quickly search for any occurrences of auto; usually there won't
27132      be any, and then we'll avoid allocating the vector.  */
27133   if (!type_uses_auto (args))
27134     return false;
27135 
27136   bool errors = false;
27137 
27138   tree vec = extract_autos (args);
27139   for (int i = 0; i < TREE_VEC_LENGTH (vec); i++)
27140     {
27141       tree xauto = TREE_VALUE (TREE_VEC_ELT (vec, i));
27142       error_at (DECL_SOURCE_LOCATION (xauto),
27143 		"invalid use of %qT in template argument", xauto);
27144       errors = true;
27145     }
27146 
27147   return errors;
27148 }
27149 
27150 /* For a given template T, return the vector of typedefs referenced
27151    in T for which access check is needed at T instantiation time.
27152    T is either  a FUNCTION_DECL or a RECORD_TYPE.
27153    Those typedefs were added to T by the function
27154    append_type_to_template_for_access_check.  */
27155 
27156 vec<qualified_typedef_usage_t, va_gc> *
get_types_needing_access_check(tree t)27157 get_types_needing_access_check (tree t)
27158 {
27159   tree ti;
27160   vec<qualified_typedef_usage_t, va_gc> *result = NULL;
27161 
27162   if (!t || t == error_mark_node)
27163     return NULL;
27164 
27165   if (!(ti = get_template_info (t)))
27166     return NULL;
27167 
27168   if (CLASS_TYPE_P (t)
27169       || TREE_CODE (t) == FUNCTION_DECL)
27170     {
27171       if (!TI_TEMPLATE (ti))
27172 	return NULL;
27173 
27174       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
27175     }
27176 
27177   return result;
27178 }
27179 
27180 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
27181    tied to T. That list of typedefs will be access checked at
27182    T instantiation time.
27183    T is either a FUNCTION_DECL or a RECORD_TYPE.
27184    TYPE_DECL is a TYPE_DECL node representing a typedef.
27185    SCOPE is the scope through which TYPE_DECL is accessed.
27186    LOCATION is the location of the usage point of TYPE_DECL.
27187 
27188    This function is a subroutine of
27189    append_type_to_template_for_access_check.  */
27190 
27191 static void
append_type_to_template_for_access_check_1(tree t,tree type_decl,tree scope,location_t location)27192 append_type_to_template_for_access_check_1 (tree t,
27193 					    tree type_decl,
27194 					    tree scope,
27195 					    location_t location)
27196 {
27197   qualified_typedef_usage_t typedef_usage;
27198   tree ti;
27199 
27200   if (!t || t == error_mark_node)
27201     return;
27202 
27203   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
27204 	       || CLASS_TYPE_P (t))
27205 	      && type_decl
27206 	      && TREE_CODE (type_decl) == TYPE_DECL
27207 	      && scope);
27208 
27209   if (!(ti = get_template_info (t)))
27210     return;
27211 
27212   gcc_assert (TI_TEMPLATE (ti));
27213 
27214   typedef_usage.typedef_decl = type_decl;
27215   typedef_usage.context = scope;
27216   typedef_usage.locus = location;
27217 
27218   vec_safe_push (TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti), typedef_usage);
27219 }
27220 
27221 /* Append TYPE_DECL to the template TEMPL.
27222    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
27223    At TEMPL instanciation time, TYPE_DECL will be checked to see
27224    if it can be accessed through SCOPE.
27225    LOCATION is the location of the usage point of TYPE_DECL.
27226 
27227    e.g. consider the following code snippet:
27228 
27229      class C
27230      {
27231        typedef int myint;
27232      };
27233 
27234      template<class U> struct S
27235      {
27236        C::myint mi; // <-- usage point of the typedef C::myint
27237      };
27238 
27239      S<char> s;
27240 
27241    At S<char> instantiation time, we need to check the access of C::myint
27242    In other words, we need to check the access of the myint typedef through
27243    the C scope. For that purpose, this function will add the myint typedef
27244    and the scope C through which its being accessed to a list of typedefs
27245    tied to the template S. That list will be walked at template instantiation
27246    time and access check performed on each typedefs it contains.
27247    Note that this particular code snippet should yield an error because
27248    myint is private to C.  */
27249 
27250 void
append_type_to_template_for_access_check(tree templ,tree type_decl,tree scope,location_t location)27251 append_type_to_template_for_access_check (tree templ,
27252                                           tree type_decl,
27253 					  tree scope,
27254 					  location_t location)
27255 {
27256   qualified_typedef_usage_t *iter;
27257   unsigned i;
27258 
27259   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
27260 
27261   /* Make sure we don't append the type to the template twice.  */
27262   FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (templ), i, iter)
27263     if (iter->typedef_decl == type_decl && scope == iter->context)
27264       return;
27265 
27266   append_type_to_template_for_access_check_1 (templ, type_decl,
27267 					      scope, location);
27268 }
27269 
27270 /* Convert the generic type parameters in PARM that match the types given in the
27271    range [START_IDX, END_IDX) from the current_template_parms into generic type
27272    packs.  */
27273 
27274 tree
convert_generic_types_to_packs(tree parm,int start_idx,int end_idx)27275 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
27276 {
27277   tree current = current_template_parms;
27278   int depth = TMPL_PARMS_DEPTH (current);
27279   current = INNERMOST_TEMPLATE_PARMS (current);
27280   tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
27281 
27282   for (int i = 0; i < start_idx; ++i)
27283     TREE_VEC_ELT (replacement, i)
27284       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
27285 
27286   for (int i = start_idx; i < end_idx; ++i)
27287     {
27288       /* Create a distinct parameter pack type from the current parm and add it
27289 	 to the replacement args to tsubst below into the generic function
27290 	 parameter.  */
27291 
27292       tree o = TREE_TYPE (TREE_VALUE
27293 			  (TREE_VEC_ELT (current, i)));
27294       tree t = copy_type (o);
27295       TEMPLATE_TYPE_PARM_INDEX (t)
27296 	= reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
27297 				      o, 0, 0, tf_none);
27298       TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
27299       TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
27300       TYPE_MAIN_VARIANT (t) = t;
27301       TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
27302       TYPE_CANONICAL (t) = canonical_type_parameter (t);
27303       TREE_VEC_ELT (replacement, i) = t;
27304       TREE_VALUE (TREE_VEC_ELT (current, i)) = TREE_CHAIN (t);
27305     }
27306 
27307   for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
27308     TREE_VEC_ELT (replacement, i)
27309       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
27310 
27311   /* If there are more levels then build up the replacement with the outer
27312      template parms.  */
27313   if (depth > 1)
27314     replacement = add_to_template_args (template_parms_to_args
27315 					(TREE_CHAIN (current_template_parms)),
27316 					replacement);
27317 
27318   return tsubst (parm, replacement, tf_none, NULL_TREE);
27319 }
27320 
27321 /* Entries in the decl_constraint hash table. */
27322 struct GTY((for_user)) constr_entry
27323 {
27324   tree decl;
27325   tree ci;
27326 };
27327 
27328 /* Hashing function and equality for constraint entries. */
27329 struct constr_hasher : ggc_ptr_hash<constr_entry>
27330 {
hashconstr_hasher27331   static hashval_t hash (constr_entry *e)
27332   {
27333     return (hashval_t)DECL_UID (e->decl);
27334   }
27335 
equalconstr_hasher27336   static bool equal (constr_entry *e1, constr_entry *e2)
27337   {
27338     return e1->decl == e2->decl;
27339   }
27340 };
27341 
27342 /* A mapping from declarations to constraint information. Note that
27343    both templates and their underlying declarations are mapped to the
27344    same constraint information.
27345 
27346    FIXME: This is defined in pt.c because garbage collection
27347    code is not being generated for constraint.cc. */
27348 
27349 static GTY (()) hash_table<constr_hasher> *decl_constraints;
27350 
27351 /* Returns the template constraints of declaration T. If T is not
27352    constrained, return NULL_TREE. Note that T must be non-null. */
27353 
27354 tree
get_constraints(tree t)27355 get_constraints (tree t)
27356 {
27357   if (!flag_concepts)
27358     return NULL_TREE;
27359 
27360   gcc_assert (DECL_P (t));
27361   if (TREE_CODE (t) == TEMPLATE_DECL)
27362     t = DECL_TEMPLATE_RESULT (t);
27363   constr_entry elt = { t, NULL_TREE };
27364   constr_entry* found = decl_constraints->find (&elt);
27365   if (found)
27366     return found->ci;
27367   else
27368     return NULL_TREE;
27369 }
27370 
27371 /* Associate the given constraint information CI with the declaration
27372    T. If T is a template, then the constraints are associated with
27373    its underlying declaration. Don't build associations if CI is
27374    NULL_TREE.  */
27375 
27376 void
set_constraints(tree t,tree ci)27377 set_constraints (tree t, tree ci)
27378 {
27379   if (!ci)
27380     return;
27381   gcc_assert (t && flag_concepts);
27382   if (TREE_CODE (t) == TEMPLATE_DECL)
27383     t = DECL_TEMPLATE_RESULT (t);
27384   gcc_assert (!get_constraints (t));
27385   constr_entry elt = {t, ci};
27386   constr_entry** slot = decl_constraints->find_slot (&elt, INSERT);
27387   constr_entry* entry = ggc_alloc<constr_entry> ();
27388   *entry = elt;
27389   *slot = entry;
27390 }
27391 
27392 /* Remove the associated constraints of the declaration T.  */
27393 
27394 void
remove_constraints(tree t)27395 remove_constraints (tree t)
27396 {
27397   gcc_assert (DECL_P (t));
27398   if (TREE_CODE (t) == TEMPLATE_DECL)
27399     t = DECL_TEMPLATE_RESULT (t);
27400 
27401   constr_entry elt = {t, NULL_TREE};
27402   constr_entry** slot = decl_constraints->find_slot (&elt, NO_INSERT);
27403   if (slot)
27404     decl_constraints->clear_slot (slot);
27405 }
27406 
27407 /* Memoized satisfaction results for declarations. This
27408    maps the pair (constraint_info, arguments) to the result computed
27409    by constraints_satisfied_p.  */
27410 
27411 struct GTY((for_user)) constraint_sat_entry
27412 {
27413   tree ci;
27414   tree args;
27415   tree result;
27416 };
27417 
27418 /* Hashing function and equality for constraint entries. */
27419 
27420 struct constraint_sat_hasher : ggc_ptr_hash<constraint_sat_entry>
27421 {
hashconstraint_sat_hasher27422   static hashval_t hash (constraint_sat_entry *e)
27423   {
27424     hashval_t val = iterative_hash_object(e->ci, 0);
27425     return iterative_hash_template_arg (e->args, val);
27426   }
27427 
equalconstraint_sat_hasher27428   static bool equal (constraint_sat_entry *e1, constraint_sat_entry *e2)
27429   {
27430     return e1->ci == e2->ci && comp_template_args (e1->args, e2->args);
27431   }
27432 };
27433 
27434 /* Memoized satisfaction results for concept checks. */
27435 
27436 struct GTY((for_user)) concept_spec_entry
27437 {
27438   tree tmpl;
27439   tree args;
27440   tree result;
27441 };
27442 
27443 /* Hashing function and equality for constraint entries.  */
27444 
27445 struct concept_spec_hasher : ggc_ptr_hash<concept_spec_entry>
27446 {
hashconcept_spec_hasher27447   static hashval_t hash (concept_spec_entry *e)
27448   {
27449     return hash_tmpl_and_args (e->tmpl, e->args);
27450   }
27451 
equalconcept_spec_hasher27452   static bool equal (concept_spec_entry *e1, concept_spec_entry *e2)
27453   {
27454     ++comparing_specializations;
27455     bool eq = e1->tmpl == e2->tmpl && comp_template_args (e1->args, e2->args);
27456     --comparing_specializations;
27457     return eq;
27458   }
27459 };
27460 
27461 static GTY (()) hash_table<constraint_sat_hasher> *constraint_memos;
27462 static GTY (()) hash_table<concept_spec_hasher> *concept_memos;
27463 
27464 /* Search for a memoized satisfaction result. Returns one of the
27465    truth value nodes if previously memoized, or NULL_TREE otherwise.   */
27466 
27467 tree
lookup_constraint_satisfaction(tree ci,tree args)27468 lookup_constraint_satisfaction (tree ci, tree args)
27469 {
27470   constraint_sat_entry elt = { ci, args, NULL_TREE };
27471   constraint_sat_entry* found = constraint_memos->find (&elt);
27472   if (found)
27473     return found->result;
27474   else
27475     return NULL_TREE;
27476 }
27477 
27478 /* Memoize the result of a satisfication test. Returns the saved result.  */
27479 
27480 tree
memoize_constraint_satisfaction(tree ci,tree args,tree result)27481 memoize_constraint_satisfaction (tree ci, tree args, tree result)
27482 {
27483   constraint_sat_entry elt = {ci, args, result};
27484   constraint_sat_entry** slot = constraint_memos->find_slot (&elt, INSERT);
27485   constraint_sat_entry* entry = ggc_alloc<constraint_sat_entry> ();
27486   *entry = elt;
27487   *slot = entry;
27488   return result;
27489 }
27490 
27491 /* Search for a memoized satisfaction result for a concept. */
27492 
27493 tree
lookup_concept_satisfaction(tree tmpl,tree args)27494 lookup_concept_satisfaction (tree tmpl, tree args)
27495 {
27496   concept_spec_entry elt = { tmpl, args, NULL_TREE };
27497   concept_spec_entry* found = concept_memos->find (&elt);
27498   if (found)
27499     return found->result;
27500   else
27501     return NULL_TREE;
27502 }
27503 
27504 /* Memoize the result of a concept check. Returns the saved result.  */
27505 
27506 tree
memoize_concept_satisfaction(tree tmpl,tree args,tree result)27507 memoize_concept_satisfaction (tree tmpl, tree args, tree result)
27508 {
27509   concept_spec_entry elt = {tmpl, args, result};
27510   concept_spec_entry** slot = concept_memos->find_slot (&elt, INSERT);
27511   concept_spec_entry* entry = ggc_alloc<concept_spec_entry> ();
27512   *entry = elt;
27513   *slot = entry;
27514   return result;
27515 }
27516 
27517 static GTY (()) hash_table<concept_spec_hasher> *concept_expansions;
27518 
27519 /* Returns a prior concept specialization. This returns the substituted
27520    and normalized constraints defined by the concept.  */
27521 
27522 tree
get_concept_expansion(tree tmpl,tree args)27523 get_concept_expansion (tree tmpl, tree args)
27524 {
27525   concept_spec_entry elt = { tmpl, args, NULL_TREE };
27526   concept_spec_entry* found = concept_expansions->find (&elt);
27527   if (found)
27528     return found->result;
27529   else
27530     return NULL_TREE;
27531 }
27532 
27533 /* Save a concept expansion for later.  */
27534 
27535 tree
save_concept_expansion(tree tmpl,tree args,tree def)27536 save_concept_expansion (tree tmpl, tree args, tree def)
27537 {
27538   concept_spec_entry elt = {tmpl, args, def};
27539   concept_spec_entry** slot = concept_expansions->find_slot (&elt, INSERT);
27540   concept_spec_entry* entry = ggc_alloc<concept_spec_entry> ();
27541   *entry = elt;
27542   *slot = entry;
27543   return def;
27544 }
27545 
27546 static hashval_t
hash_subsumption_args(tree t1,tree t2)27547 hash_subsumption_args (tree t1, tree t2)
27548 {
27549   gcc_assert (TREE_CODE (t1) == CHECK_CONSTR);
27550   gcc_assert (TREE_CODE (t2) == CHECK_CONSTR);
27551   int val = 0;
27552   val = iterative_hash_object (CHECK_CONSTR_CONCEPT (t1), val);
27553   val = iterative_hash_template_arg (CHECK_CONSTR_ARGS (t1), val);
27554   val = iterative_hash_object (CHECK_CONSTR_CONCEPT (t2), val);
27555   val = iterative_hash_template_arg (CHECK_CONSTR_ARGS (t2), val);
27556   return val;
27557 }
27558 
27559 /* Compare the constraints of two subsumption entries.  The LEFT1 and
27560    LEFT2 arguments comprise the first subsumption pair and the RIGHT1
27561    and RIGHT2 arguments comprise the second. These are all CHECK_CONSTRs. */
27562 
27563 static bool
comp_subsumption_args(tree left1,tree left2,tree right1,tree right2)27564 comp_subsumption_args (tree left1, tree left2, tree right1, tree right2)
27565 {
27566   if (CHECK_CONSTR_CONCEPT (left1) == CHECK_CONSTR_CONCEPT (right1))
27567     if (CHECK_CONSTR_CONCEPT (left2) == CHECK_CONSTR_CONCEPT (right2))
27568       if (comp_template_args (CHECK_CONSTR_ARGS (left1),
27569                              CHECK_CONSTR_ARGS (right1)))
27570         return comp_template_args (CHECK_CONSTR_ARGS (left2),
27571                                   CHECK_CONSTR_ARGS (right2));
27572   return false;
27573 }
27574 
27575 /* Key/value pair for learning and memoizing subsumption results. This
27576    associates a pair of check constraints (including arguments) with
27577    a boolean value indicating the result.  */
27578 
27579 struct GTY((for_user)) subsumption_entry
27580 {
27581   tree t1;
27582   tree t2;
27583   bool result;
27584 };
27585 
27586 /* Hashing function and equality for constraint entries.  */
27587 
27588 struct subsumption_hasher : ggc_ptr_hash<subsumption_entry>
27589 {
hashsubsumption_hasher27590   static hashval_t hash (subsumption_entry *e)
27591   {
27592     return hash_subsumption_args (e->t1, e->t2);
27593   }
27594 
equalsubsumption_hasher27595   static bool equal (subsumption_entry *e1, subsumption_entry *e2)
27596   {
27597     ++comparing_specializations;
27598     bool eq = comp_subsumption_args(e1->t1, e1->t2, e2->t1, e2->t2);
27599     --comparing_specializations;
27600     return eq;
27601   }
27602 };
27603 
27604 static GTY (()) hash_table<subsumption_hasher> *subsumption_table;
27605 
27606 /* Search for a previously cached subsumption result. */
27607 
27608 bool*
lookup_subsumption_result(tree t1,tree t2)27609 lookup_subsumption_result (tree t1, tree t2)
27610 {
27611   subsumption_entry elt = { t1, t2, false };
27612   subsumption_entry* found = subsumption_table->find (&elt);
27613   if (found)
27614     return &found->result;
27615   else
27616     return 0;
27617 }
27618 
27619 /* Save a subsumption result. */
27620 
27621 bool
save_subsumption_result(tree t1,tree t2,bool result)27622 save_subsumption_result (tree t1, tree t2, bool result)
27623 {
27624   subsumption_entry elt = {t1, t2, result};
27625   subsumption_entry** slot = subsumption_table->find_slot (&elt, INSERT);
27626   subsumption_entry* entry = ggc_alloc<subsumption_entry> ();
27627   *entry = elt;
27628   *slot = entry;
27629   return result;
27630 }
27631 
27632 /* Set up the hash table for constraint association. */
27633 
27634 void
init_constraint_processing(void)27635 init_constraint_processing (void)
27636 {
27637   if (!flag_concepts)
27638     return;
27639 
27640   decl_constraints = hash_table<constr_hasher>::create_ggc(37);
27641   constraint_memos = hash_table<constraint_sat_hasher>::create_ggc(37);
27642   concept_memos = hash_table<concept_spec_hasher>::create_ggc(37);
27643   concept_expansions = hash_table<concept_spec_hasher>::create_ggc(37);
27644   subsumption_table = hash_table<subsumption_hasher>::create_ggc(37);
27645 }
27646 
27647 /* __integer_pack(N) in a pack expansion expands to a sequence of numbers from
27648    0..N-1.  */
27649 
27650 void
declare_integer_pack(void)27651 declare_integer_pack (void)
27652 {
27653   tree ipfn = push_library_fn (get_identifier ("__integer_pack"),
27654 			       build_function_type_list (integer_type_node,
27655 							 integer_type_node,
27656 							 NULL_TREE),
27657 			       NULL_TREE, ECF_CONST);
27658   DECL_DECLARED_CONSTEXPR_P (ipfn) = true;
27659   DECL_BUILT_IN_CLASS (ipfn) = BUILT_IN_FRONTEND;
27660 }
27661 
27662 /* Set up the hash tables for template instantiations.  */
27663 
27664 void
init_template_processing(void)27665 init_template_processing (void)
27666 {
27667   decl_specializations = hash_table<spec_hasher>::create_ggc (37);
27668   type_specializations = hash_table<spec_hasher>::create_ggc (37);
27669 
27670   if (cxx_dialect >= cxx11)
27671     declare_integer_pack ();
27672 }
27673 
27674 /* Print stats about the template hash tables for -fstats.  */
27675 
27676 void
print_template_statistics(void)27677 print_template_statistics (void)
27678 {
27679   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
27680 	   "%f collisions\n", (long) decl_specializations->size (),
27681 	   (long) decl_specializations->elements (),
27682 	   decl_specializations->collisions ());
27683   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
27684 	   "%f collisions\n", (long) type_specializations->size (),
27685 	   (long) type_specializations->elements (),
27686 	   type_specializations->collisions ());
27687 }
27688 
27689 #if CHECKING_P
27690 
27691 namespace selftest {
27692 
27693 /* Verify that build_non_dependent_expr () works, for various expressions,
27694    and that location wrappers don't affect the results.  */
27695 
27696 static void
test_build_non_dependent_expr()27697 test_build_non_dependent_expr ()
27698 {
27699   location_t loc = BUILTINS_LOCATION;
27700 
27701   /* Verify constants, without and with location wrappers.  */
27702   tree int_cst = build_int_cst (integer_type_node, 42);
27703   ASSERT_EQ (int_cst, build_non_dependent_expr (int_cst));
27704 
27705   tree wrapped_int_cst = maybe_wrap_with_location (int_cst, loc);
27706   ASSERT_TRUE (location_wrapper_p (wrapped_int_cst));
27707   ASSERT_EQ (wrapped_int_cst, build_non_dependent_expr (wrapped_int_cst));
27708 
27709   tree string_lit = build_string (4, "foo");
27710   TREE_TYPE (string_lit) = char_array_type_node;
27711   string_lit = fix_string_type (string_lit);
27712   ASSERT_EQ (string_lit, build_non_dependent_expr (string_lit));
27713 
27714   tree wrapped_string_lit = maybe_wrap_with_location (string_lit, loc);
27715   ASSERT_TRUE (location_wrapper_p (wrapped_string_lit));
27716   ASSERT_EQ (wrapped_string_lit,
27717 	     build_non_dependent_expr (wrapped_string_lit));
27718 }
27719 
27720 /* Verify that type_dependent_expression_p () works correctly, even
27721    in the presence of location wrapper nodes.  */
27722 
27723 static void
test_type_dependent_expression_p()27724 test_type_dependent_expression_p ()
27725 {
27726   location_t loc = BUILTINS_LOCATION;
27727 
27728   tree name = get_identifier ("foo");
27729 
27730   /* If no templates are involved, nothing is type-dependent.  */
27731   gcc_assert (!processing_template_decl);
27732   ASSERT_FALSE (type_dependent_expression_p (name));
27733 
27734   ++processing_template_decl;
27735 
27736   /* Within a template, an unresolved name is always type-dependent.  */
27737   ASSERT_TRUE (type_dependent_expression_p (name));
27738 
27739   /* Ensure it copes with NULL_TREE and errors.  */
27740   ASSERT_FALSE (type_dependent_expression_p (NULL_TREE));
27741   ASSERT_FALSE (type_dependent_expression_p (error_mark_node));
27742 
27743   /* A USING_DECL in a template should be type-dependent, even if wrapped
27744      with a location wrapper (PR c++/83799).  */
27745   tree using_decl = build_lang_decl (USING_DECL, name, NULL_TREE);
27746   TREE_TYPE (using_decl) = integer_type_node;
27747   ASSERT_TRUE (type_dependent_expression_p (using_decl));
27748   tree wrapped_using_decl = maybe_wrap_with_location (using_decl, loc);
27749   ASSERT_TRUE (location_wrapper_p (wrapped_using_decl));
27750   ASSERT_TRUE (type_dependent_expression_p (wrapped_using_decl));
27751 
27752   --processing_template_decl;
27753 }
27754 
27755 /* Run all of the selftests within this file.  */
27756 
27757 void
cp_pt_c_tests()27758 cp_pt_c_tests ()
27759 {
27760   test_build_non_dependent_expr ();
27761   test_type_dependent_expression_p ();
27762 }
27763 
27764 } // namespace selftest
27765 
27766 #endif /* #if CHECKING_P */
27767 
27768 #include "gt-cp-pt.h"
27769