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       /* Ignore the declaration of a capture proxy for a parameter pack.  */
3818       if (is_capture_proxy (DECL_EXPR_DECL (t)))
3819 	*walk_subtrees = 0;
3820       return NULL_TREE;
3821 
3822     case RECORD_TYPE:
3823       if (TYPE_PTRMEMFUNC_P (t))
3824 	return NULL_TREE;
3825       /* Fall through.  */
3826 
3827     case UNION_TYPE:
3828     case ENUMERAL_TYPE:
3829       if (TYPE_TEMPLATE_INFO (t))
3830 	cp_walk_tree (&TYPE_TI_ARGS (t),
3831 		      &find_parameter_packs_r, ppd, ppd->visited);
3832 
3833       *walk_subtrees = 0;
3834       return NULL_TREE;
3835 
3836     case TEMPLATE_DECL:
3837       if (!DECL_TEMPLATE_TEMPLATE_PARM_P (t))
3838 	return NULL_TREE;
3839       gcc_fallthrough();
3840 
3841     case CONSTRUCTOR:
3842       cp_walk_tree (&TREE_TYPE (t),
3843 		    &find_parameter_packs_r, ppd, ppd->visited);
3844       return NULL_TREE;
3845 
3846     case TYPENAME_TYPE:
3847       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3848                    ppd, ppd->visited);
3849       *walk_subtrees = 0;
3850       return NULL_TREE;
3851 
3852     case TYPE_PACK_EXPANSION:
3853     case EXPR_PACK_EXPANSION:
3854       *walk_subtrees = 0;
3855       return NULL_TREE;
3856 
3857     case INTEGER_TYPE:
3858       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r,
3859 		    ppd, ppd->visited);
3860       *walk_subtrees = 0;
3861       return NULL_TREE;
3862 
3863     case IDENTIFIER_NODE:
3864       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd,
3865 		    ppd->visited);
3866       *walk_subtrees = 0;
3867       return NULL_TREE;
3868 
3869     case LAMBDA_EXPR:
3870       {
3871 	/* Look at explicit captures.  */
3872 	for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t);
3873 	     cap; cap = TREE_CHAIN (cap))
3874 	  cp_walk_tree (&TREE_VALUE (cap), &find_parameter_packs_r, ppd,
3875 			ppd->visited);
3876 	/* Since we defer implicit capture, look in the parms and body.  */
3877 	tree fn = lambda_function (t);
3878 	cp_walk_tree (&TREE_TYPE (fn), &find_parameter_packs_r, ppd,
3879 		      ppd->visited);
3880 	cp_walk_tree (&DECL_SAVED_TREE (fn), &find_parameter_packs_r, ppd,
3881 		      ppd->visited);
3882 	*walk_subtrees = 0;
3883 	return NULL_TREE;
3884       }
3885 
3886     case DECLTYPE_TYPE:
3887       {
3888 	/* When traversing a DECLTYPE_TYPE_EXPR, we need to set
3889 	   type_pack_expansion_p to false so that any placeholders
3890 	   within the expression don't get marked as parameter packs.  */
3891 	bool type_pack_expansion_p = ppd->type_pack_expansion_p;
3892 	ppd->type_pack_expansion_p = false;
3893 	cp_walk_tree (&DECLTYPE_TYPE_EXPR (t), &find_parameter_packs_r,
3894 		      ppd, ppd->visited);
3895 	ppd->type_pack_expansion_p = type_pack_expansion_p;
3896 	*walk_subtrees = 0;
3897 	return NULL_TREE;
3898       }
3899 
3900     case IF_STMT:
3901       cp_walk_tree (&IF_COND (t), &find_parameter_packs_r,
3902 		    ppd, ppd->visited);
3903       cp_walk_tree (&THEN_CLAUSE (t), &find_parameter_packs_r,
3904 		    ppd, ppd->visited);
3905       cp_walk_tree (&ELSE_CLAUSE (t), &find_parameter_packs_r,
3906 		    ppd, ppd->visited);
3907       /* Don't walk into IF_STMT_EXTRA_ARGS.  */
3908       *walk_subtrees = 0;
3909       return NULL_TREE;
3910 
3911     default:
3912       return NULL_TREE;
3913     }
3914 
3915   return NULL_TREE;
3916 }
3917 
3918 /* Determines if the expression or type T uses any parameter packs.  */
3919 bool
uses_parameter_packs(tree t)3920 uses_parameter_packs (tree t)
3921 {
3922   tree parameter_packs = NULL_TREE;
3923   struct find_parameter_pack_data ppd;
3924   ppd.parameter_packs = &parameter_packs;
3925   ppd.visited = new hash_set<tree>;
3926   ppd.type_pack_expansion_p = false;
3927   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3928   delete ppd.visited;
3929   return parameter_packs != NULL_TREE;
3930 }
3931 
3932 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3933    representation a base-class initializer into a parameter pack
3934    expansion. If all goes well, the resulting node will be an
3935    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3936    respectively.  */
3937 tree
make_pack_expansion(tree arg,tsubst_flags_t complain)3938 make_pack_expansion (tree arg, tsubst_flags_t complain)
3939 {
3940   tree result;
3941   tree parameter_packs = NULL_TREE;
3942   bool for_types = false;
3943   struct find_parameter_pack_data ppd;
3944 
3945   if (!arg || arg == error_mark_node)
3946     return arg;
3947 
3948   if (TREE_CODE (arg) == TREE_LIST && TREE_PURPOSE (arg))
3949     {
3950       /* A TREE_LIST with a non-null TREE_PURPOSE is for a base
3951          class initializer.  In this case, the TREE_PURPOSE will be a
3952          _TYPE node (representing the base class expansion we're
3953          initializing) and the TREE_VALUE will be a TREE_LIST
3954          containing the initialization arguments.
3955 
3956          The resulting expansion looks somewhat different from most
3957          expansions. Rather than returning just one _EXPANSION, we
3958          return a TREE_LIST whose TREE_PURPOSE is a
3959          TYPE_PACK_EXPANSION containing the bases that will be
3960          initialized.  The TREE_VALUE will be identical to the
3961          original TREE_VALUE, which is a list of arguments that will
3962          be passed to each base.  We do not introduce any new pack
3963          expansion nodes into the TREE_VALUE (although it is possible
3964          that some already exist), because the TREE_PURPOSE and
3965          TREE_VALUE all need to be expanded together with the same
3966          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3967          resulting TREE_PURPOSE will mention the parameter packs in
3968          both the bases and the arguments to the bases.  */
3969       tree purpose;
3970       tree value;
3971       tree parameter_packs = NULL_TREE;
3972 
3973       /* Determine which parameter packs will be used by the base
3974          class expansion.  */
3975       ppd.visited = new hash_set<tree>;
3976       ppd.parameter_packs = &parameter_packs;
3977       ppd.type_pack_expansion_p = false;
3978       gcc_assert (TYPE_P (TREE_PURPOSE (arg)));
3979       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r,
3980                     &ppd, ppd.visited);
3981 
3982       if (parameter_packs == NULL_TREE)
3983         {
3984 	  if (complain & tf_error)
3985 	    error ("base initializer expansion %qT contains no parameter packs",
3986 		   arg);
3987           delete ppd.visited;
3988           return error_mark_node;
3989         }
3990 
3991       if (TREE_VALUE (arg) != void_type_node)
3992         {
3993           /* Collect the sets of parameter packs used in each of the
3994              initialization arguments.  */
3995           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3996             {
3997               /* Determine which parameter packs will be expanded in this
3998                  argument.  */
3999               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r,
4000                             &ppd, ppd.visited);
4001             }
4002         }
4003 
4004       delete ppd.visited;
4005 
4006       /* Create the pack expansion type for the base type.  */
4007       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
4008       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
4009       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
4010       PACK_EXPANSION_LOCAL_P (purpose) = at_function_scope_p ();
4011 
4012       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4013 	 they will rarely be compared to anything.  */
4014       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
4015 
4016       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
4017     }
4018 
4019   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
4020     for_types = true;
4021 
4022   /* Build the PACK_EXPANSION_* node.  */
4023   result = for_types
4024      ? cxx_make_type (TYPE_PACK_EXPANSION)
4025      : make_node (EXPR_PACK_EXPANSION);
4026   SET_PACK_EXPANSION_PATTERN (result, arg);
4027   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
4028     {
4029       /* Propagate type and const-expression information.  */
4030       TREE_TYPE (result) = TREE_TYPE (arg);
4031       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
4032       /* Mark this read now, since the expansion might be length 0.  */
4033       mark_exp_read (arg);
4034     }
4035   else
4036     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4037        they will rarely be compared to anything.  */
4038     SET_TYPE_STRUCTURAL_EQUALITY (result);
4039 
4040   /* Determine which parameter packs will be expanded.  */
4041   ppd.parameter_packs = &parameter_packs;
4042   ppd.visited = new hash_set<tree>;
4043   ppd.type_pack_expansion_p = TYPE_P (arg);
4044   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
4045   delete ppd.visited;
4046 
4047   /* Make sure we found some parameter packs.  */
4048   if (parameter_packs == NULL_TREE)
4049     {
4050       if (complain & tf_error)
4051 	{
4052 	  if (TYPE_P (arg))
4053 	    error ("expansion pattern %qT contains no argument packs", arg);
4054 	  else
4055 	    error ("expansion pattern %qE contains no argument packs", arg);
4056 	}
4057       return error_mark_node;
4058     }
4059   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
4060 
4061   PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
4062 
4063   return result;
4064 }
4065 
4066 /* Checks T for any "bare" parameter packs, which have not yet been
4067    expanded, and issues an error if any are found. This operation can
4068    only be done on full expressions or types (e.g., an expression
4069    statement, "if" condition, etc.), because we could have expressions like:
4070 
4071      foo(f(g(h(args)))...)
4072 
4073    where "args" is a parameter pack. check_for_bare_parameter_packs
4074    should not be called for the subexpressions args, h(args),
4075    g(h(args)), or f(g(h(args))), because we would produce erroneous
4076    error messages.
4077 
4078    Returns TRUE and emits an error if there were bare parameter packs,
4079    returns FALSE otherwise.  */
4080 bool
check_for_bare_parameter_packs(tree t,location_t loc)4081 check_for_bare_parameter_packs (tree t, location_t loc /* = UNKNOWN_LOCATION */)
4082 {
4083   tree parameter_packs = NULL_TREE;
4084   struct find_parameter_pack_data ppd;
4085 
4086   if (!processing_template_decl || !t || t == error_mark_node)
4087     return false;
4088 
4089   /* A lambda might use a parameter pack from the containing context.  */
4090   if (current_class_type && LAMBDA_TYPE_P (current_class_type)
4091       && CLASSTYPE_TEMPLATE_INFO (current_class_type))
4092     return false;
4093 
4094   if (TREE_CODE (t) == TYPE_DECL)
4095     t = TREE_TYPE (t);
4096 
4097   ppd.parameter_packs = &parameter_packs;
4098   ppd.visited = new hash_set<tree>;
4099   ppd.type_pack_expansion_p = false;
4100   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4101   delete ppd.visited;
4102 
4103   if (parameter_packs)
4104     {
4105       if (loc == UNKNOWN_LOCATION)
4106 	loc = EXPR_LOC_OR_LOC (t, input_location);
4107       error_at (loc, "parameter packs not expanded with %<...%>:");
4108       while (parameter_packs)
4109         {
4110           tree pack = TREE_VALUE (parameter_packs);
4111           tree name = NULL_TREE;
4112 
4113           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
4114               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
4115             name = TYPE_NAME (pack);
4116           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
4117             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
4118 	  else if (TREE_CODE (pack) == CALL_EXPR)
4119 	    name = DECL_NAME (CALL_EXPR_FN (pack));
4120           else
4121             name = DECL_NAME (pack);
4122 
4123 	  if (name)
4124 	    inform (loc, "        %qD", name);
4125 	  else
4126 	    inform (loc, "        <anonymous>");
4127 
4128           parameter_packs = TREE_CHAIN (parameter_packs);
4129         }
4130 
4131       return true;
4132     }
4133 
4134   return false;
4135 }
4136 
4137 /* Expand any parameter packs that occur in the template arguments in
4138    ARGS.  */
4139 tree
expand_template_argument_pack(tree args)4140 expand_template_argument_pack (tree args)
4141 {
4142   if (args == error_mark_node)
4143     return error_mark_node;
4144 
4145   tree result_args = NULL_TREE;
4146   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
4147   int num_result_args = -1;
4148   int non_default_args_count = -1;
4149 
4150   /* First, determine if we need to expand anything, and the number of
4151      slots we'll need.  */
4152   for (in_arg = 0; in_arg < nargs; ++in_arg)
4153     {
4154       tree arg = TREE_VEC_ELT (args, in_arg);
4155       if (arg == NULL_TREE)
4156 	return args;
4157       if (ARGUMENT_PACK_P (arg))
4158         {
4159           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
4160           if (num_result_args < 0)
4161             num_result_args = in_arg + num_packed;
4162           else
4163             num_result_args += num_packed;
4164         }
4165       else
4166         {
4167           if (num_result_args >= 0)
4168             num_result_args++;
4169         }
4170     }
4171 
4172   /* If no expansion is necessary, we're done.  */
4173   if (num_result_args < 0)
4174     return args;
4175 
4176   /* Expand arguments.  */
4177   result_args = make_tree_vec (num_result_args);
4178   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
4179     non_default_args_count =
4180       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
4181   for (in_arg = 0; in_arg < nargs; ++in_arg)
4182     {
4183       tree arg = TREE_VEC_ELT (args, in_arg);
4184       if (ARGUMENT_PACK_P (arg))
4185         {
4186           tree packed = ARGUMENT_PACK_ARGS (arg);
4187           int i, num_packed = TREE_VEC_LENGTH (packed);
4188           for (i = 0; i < num_packed; ++i, ++out_arg)
4189             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
4190 	  if (non_default_args_count > 0)
4191 	    non_default_args_count += num_packed - 1;
4192         }
4193       else
4194         {
4195           TREE_VEC_ELT (result_args, out_arg) = arg;
4196           ++out_arg;
4197         }
4198     }
4199   if (non_default_args_count >= 0)
4200     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
4201   return result_args;
4202 }
4203 
4204 /* Checks if DECL shadows a template parameter.
4205 
4206    [temp.local]: A template-parameter shall not be redeclared within its
4207    scope (including nested scopes).
4208 
4209    Emits an error and returns TRUE if the DECL shadows a parameter,
4210    returns FALSE otherwise.  */
4211 
4212 bool
check_template_shadow(tree decl)4213 check_template_shadow (tree decl)
4214 {
4215   tree olddecl;
4216 
4217   /* If we're not in a template, we can't possibly shadow a template
4218      parameter.  */
4219   if (!current_template_parms)
4220     return true;
4221 
4222   /* Figure out what we're shadowing.  */
4223   decl = OVL_FIRST (decl);
4224   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
4225 
4226   /* If there's no previous binding for this name, we're not shadowing
4227      anything, let alone a template parameter.  */
4228   if (!olddecl)
4229     return true;
4230 
4231   /* If we're not shadowing a template parameter, we're done.  Note
4232      that OLDDECL might be an OVERLOAD (or perhaps even an
4233      ERROR_MARK), so we can't just blithely assume it to be a _DECL
4234      node.  */
4235   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
4236     return true;
4237 
4238   /* We check for decl != olddecl to avoid bogus errors for using a
4239      name inside a class.  We check TPFI to avoid duplicate errors for
4240      inline member templates.  */
4241   if (decl == olddecl
4242       || (DECL_TEMPLATE_PARM_P (decl)
4243 	  && TEMPLATE_PARMS_FOR_INLINE (current_template_parms)))
4244     return true;
4245 
4246   /* Don't complain about the injected class name, as we've already
4247      complained about the class itself.  */
4248   if (DECL_SELF_REFERENCE_P (decl))
4249     return false;
4250 
4251   if (DECL_TEMPLATE_PARM_P (decl))
4252     error ("declaration of template parameter %q+D shadows "
4253 	   "template parameter", decl);
4254   else
4255     error ("declaration of %q+#D shadows template parameter", decl);
4256   inform (DECL_SOURCE_LOCATION (olddecl),
4257 	  "template parameter %qD declared here", olddecl);
4258   return false;
4259 }
4260 
4261 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
4262    ORIG_LEVEL, DECL, and TYPE.  */
4263 
4264 static tree
build_template_parm_index(int index,int level,int orig_level,tree decl,tree type)4265 build_template_parm_index (int index,
4266 			   int level,
4267 			   int orig_level,
4268 			   tree decl,
4269 			   tree type)
4270 {
4271   tree t = make_node (TEMPLATE_PARM_INDEX);
4272   TEMPLATE_PARM_IDX (t) = index;
4273   TEMPLATE_PARM_LEVEL (t) = level;
4274   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
4275   TEMPLATE_PARM_DECL (t) = decl;
4276   TREE_TYPE (t) = type;
4277   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
4278   TREE_READONLY (t) = TREE_READONLY (decl);
4279 
4280   return t;
4281 }
4282 
4283 /* Find the canonical type parameter for the given template type
4284    parameter.  Returns the canonical type parameter, which may be TYPE
4285    if no such parameter existed.  */
4286 
4287 static tree
canonical_type_parameter(tree type)4288 canonical_type_parameter (tree type)
4289 {
4290   tree list;
4291   int idx = TEMPLATE_TYPE_IDX (type);
4292   if (!canonical_template_parms)
4293     vec_alloc (canonical_template_parms, idx + 1);
4294 
4295   if (canonical_template_parms->length () <= (unsigned) idx)
4296     vec_safe_grow_cleared (canonical_template_parms, idx + 1);
4297 
4298   list = (*canonical_template_parms)[idx];
4299   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
4300     list = TREE_CHAIN (list);
4301 
4302   if (list)
4303     return TREE_VALUE (list);
4304   else
4305     {
4306       (*canonical_template_parms)[idx]
4307 	= tree_cons (NULL_TREE, type, (*canonical_template_parms)[idx]);
4308       return type;
4309     }
4310 }
4311 
4312 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
4313    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
4314    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
4315    new one is created.  */
4316 
4317 static tree
reduce_template_parm_level(tree index,tree type,int levels,tree args,tsubst_flags_t complain)4318 reduce_template_parm_level (tree index, tree type, int levels, tree args,
4319 			    tsubst_flags_t complain)
4320 {
4321   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
4322       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
4323 	  != TEMPLATE_PARM_LEVEL (index) - levels)
4324       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
4325     {
4326       tree orig_decl = TEMPLATE_PARM_DECL (index);
4327       tree decl, t;
4328 
4329       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
4330 			 TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
4331       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
4332       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
4333       DECL_ARTIFICIAL (decl) = 1;
4334       SET_DECL_TEMPLATE_PARM_P (decl);
4335 
4336       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
4337 				     TEMPLATE_PARM_LEVEL (index) - levels,
4338 				     TEMPLATE_PARM_ORIG_LEVEL (index),
4339 				     decl, type);
4340       TEMPLATE_PARM_DESCENDANTS (index) = t;
4341       TEMPLATE_PARM_PARAMETER_PACK (t)
4342 	= TEMPLATE_PARM_PARAMETER_PACK (index);
4343 
4344 	/* Template template parameters need this.  */
4345       if (TREE_CODE (decl) == TEMPLATE_DECL)
4346 	{
4347 	  DECL_TEMPLATE_RESULT (decl)
4348 	    = build_decl (DECL_SOURCE_LOCATION (decl),
4349 			  TYPE_DECL, DECL_NAME (decl), type);
4350 	  DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (decl)) = true;
4351 	  DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
4352 	    (DECL_TEMPLATE_PARMS (orig_decl), args, complain);
4353 	}
4354     }
4355 
4356   return TEMPLATE_PARM_DESCENDANTS (index);
4357 }
4358 
4359 /* Process information from new template parameter PARM and append it
4360    to the LIST being built.  This new parameter is a non-type
4361    parameter iff IS_NON_TYPE is true. This new parameter is a
4362    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
4363    is in PARM_LOC.  */
4364 
4365 tree
process_template_parm(tree list,location_t parm_loc,tree parm,bool is_non_type,bool is_parameter_pack)4366 process_template_parm (tree list, location_t parm_loc, tree parm,
4367 		       bool is_non_type, bool is_parameter_pack)
4368 {
4369   tree decl = 0;
4370   int idx = 0;
4371 
4372   gcc_assert (TREE_CODE (parm) == TREE_LIST);
4373   tree defval = TREE_PURPOSE (parm);
4374   tree constr = TREE_TYPE (parm);
4375 
4376   if (list)
4377     {
4378       tree p = tree_last (list);
4379 
4380       if (p && TREE_VALUE (p) != error_mark_node)
4381         {
4382           p = TREE_VALUE (p);
4383           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
4384             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
4385           else
4386             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
4387         }
4388 
4389       ++idx;
4390     }
4391 
4392   if (is_non_type)
4393     {
4394       parm = TREE_VALUE (parm);
4395 
4396       SET_DECL_TEMPLATE_PARM_P (parm);
4397 
4398       if (TREE_TYPE (parm) != error_mark_node)
4399 	{
4400 	  /* [temp.param]
4401 
4402 	     The top-level cv-qualifiers on the template-parameter are
4403 	     ignored when determining its type.  */
4404 	  TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
4405 	  if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
4406 	    TREE_TYPE (parm) = error_mark_node;
4407 	  else if (uses_parameter_packs (TREE_TYPE (parm))
4408 		   && !is_parameter_pack
4409 		   /* If we're in a nested template parameter list, the template
4410 		      template parameter could be a parameter pack.  */
4411 		   && processing_template_parmlist == 1)
4412 	    {
4413 	      /* This template parameter is not a parameter pack, but it
4414 		 should be. Complain about "bare" parameter packs.  */
4415 	      check_for_bare_parameter_packs (TREE_TYPE (parm));
4416 
4417 	      /* Recover by calling this a parameter pack.  */
4418 	      is_parameter_pack = true;
4419 	    }
4420 	}
4421 
4422       /* A template parameter is not modifiable.  */
4423       TREE_CONSTANT (parm) = 1;
4424       TREE_READONLY (parm) = 1;
4425       decl = build_decl (parm_loc,
4426 			 CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
4427       TREE_CONSTANT (decl) = 1;
4428       TREE_READONLY (decl) = 1;
4429       DECL_INITIAL (parm) = DECL_INITIAL (decl)
4430 	= build_template_parm_index (idx, processing_template_decl,
4431 				     processing_template_decl,
4432 				     decl, TREE_TYPE (parm));
4433 
4434       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4435 	= is_parameter_pack;
4436     }
4437   else
4438     {
4439       tree t;
4440       parm = TREE_VALUE (TREE_VALUE (parm));
4441 
4442       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
4443 	{
4444 	  t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
4445 	  /* This is for distinguishing between real templates and template
4446 	     template parameters */
4447 	  TREE_TYPE (parm) = t;
4448 	  TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
4449 	  decl = parm;
4450 	}
4451       else
4452 	{
4453 	  t = cxx_make_type (TEMPLATE_TYPE_PARM);
4454 	  /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
4455 	  decl = build_decl (parm_loc,
4456 			     TYPE_DECL, parm, t);
4457 	}
4458 
4459       TYPE_NAME (t) = decl;
4460       TYPE_STUB_DECL (t) = decl;
4461       parm = decl;
4462       TEMPLATE_TYPE_PARM_INDEX (t)
4463 	= build_template_parm_index (idx, processing_template_decl,
4464 				     processing_template_decl,
4465 				     decl, TREE_TYPE (parm));
4466       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
4467       TYPE_CANONICAL (t) = canonical_type_parameter (t);
4468     }
4469   DECL_ARTIFICIAL (decl) = 1;
4470   SET_DECL_TEMPLATE_PARM_P (decl);
4471 
4472   /* Build requirements for the type/template parameter.
4473      This must be done after SET_DECL_TEMPLATE_PARM_P or
4474      process_template_parm could fail. */
4475   tree reqs = finish_shorthand_constraint (parm, constr);
4476 
4477   pushdecl (decl);
4478 
4479   if (defval && TREE_CODE (defval) == OVERLOAD)
4480     lookup_keep (defval, true);
4481 
4482   /* Build the parameter node linking the parameter declaration,
4483      its default argument (if any), and its constraints (if any). */
4484   parm = build_tree_list (defval, parm);
4485   TEMPLATE_PARM_CONSTRAINTS (parm) = reqs;
4486 
4487   return chainon (list, parm);
4488 }
4489 
4490 /* The end of a template parameter list has been reached.  Process the
4491    tree list into a parameter vector, converting each parameter into a more
4492    useful form.	 Type parameters are saved as IDENTIFIER_NODEs, and others
4493    as PARM_DECLs.  */
4494 
4495 tree
end_template_parm_list(tree parms)4496 end_template_parm_list (tree parms)
4497 {
4498   int nparms;
4499   tree parm, next;
4500   tree saved_parmlist = make_tree_vec (list_length (parms));
4501 
4502   /* Pop the dummy parameter level and add the real one.  */
4503   current_template_parms = TREE_CHAIN (current_template_parms);
4504 
4505   current_template_parms
4506     = tree_cons (size_int (processing_template_decl),
4507 		 saved_parmlist, current_template_parms);
4508 
4509   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
4510     {
4511       next = TREE_CHAIN (parm);
4512       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
4513       TREE_CHAIN (parm) = NULL_TREE;
4514     }
4515 
4516   --processing_template_parmlist;
4517 
4518   return saved_parmlist;
4519 }
4520 
4521 // Explicitly indicate the end of the template parameter list. We assume
4522 // that the current template parameters have been constructed and/or
4523 // managed explicitly, as when creating new template template parameters
4524 // from a shorthand constraint.
4525 void
end_template_parm_list()4526 end_template_parm_list ()
4527 {
4528   --processing_template_parmlist;
4529 }
4530 
4531 /* end_template_decl is called after a template declaration is seen.  */
4532 
4533 void
end_template_decl(void)4534 end_template_decl (void)
4535 {
4536   reset_specialization ();
4537 
4538   if (! processing_template_decl)
4539     return;
4540 
4541   /* This matches the pushlevel in begin_template_parm_list.  */
4542   finish_scope ();
4543 
4544   --processing_template_decl;
4545   current_template_parms = TREE_CHAIN (current_template_parms);
4546 }
4547 
4548 /* Takes a TREE_LIST representing a template parameter and convert it
4549    into an argument suitable to be passed to the type substitution
4550    functions.  Note that If the TREE_LIST contains an error_mark
4551    node, the returned argument is error_mark_node.  */
4552 
4553 tree
template_parm_to_arg(tree t)4554 template_parm_to_arg (tree t)
4555 {
4556 
4557   if (t == NULL_TREE
4558       || TREE_CODE (t) != TREE_LIST)
4559     return t;
4560 
4561   if (error_operand_p (TREE_VALUE (t)))
4562     return error_mark_node;
4563 
4564   t = TREE_VALUE (t);
4565 
4566   if (TREE_CODE (t) == TYPE_DECL
4567       || TREE_CODE (t) == TEMPLATE_DECL)
4568     {
4569       t = TREE_TYPE (t);
4570 
4571       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
4572 	{
4573 	  /* Turn this argument into a TYPE_ARGUMENT_PACK
4574 	     with a single element, which expands T.  */
4575 	  tree vec = make_tree_vec (1);
4576 	  if (CHECKING_P)
4577 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4578 
4579 	  TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4580 
4581 	  t = cxx_make_type (TYPE_ARGUMENT_PACK);
4582 	  SET_ARGUMENT_PACK_ARGS (t, vec);
4583 	}
4584     }
4585   else
4586     {
4587       t = DECL_INITIAL (t);
4588 
4589       if (TEMPLATE_PARM_PARAMETER_PACK (t))
4590 	{
4591 	  /* Turn this argument into a NONTYPE_ARGUMENT_PACK
4592 	     with a single element, which expands T.  */
4593 	  tree vec = make_tree_vec (1);
4594 	  if (CHECKING_P)
4595 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4596 
4597 	  t = convert_from_reference (t);
4598 	  TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4599 
4600 	  t  = make_node (NONTYPE_ARGUMENT_PACK);
4601 	  SET_ARGUMENT_PACK_ARGS (t, vec);
4602 	}
4603       else
4604 	t = convert_from_reference (t);
4605     }
4606   return t;
4607 }
4608 
4609 /* Given a single level of template parameters (a TREE_VEC), return it
4610    as a set of template arguments.  */
4611 
4612 static tree
template_parms_level_to_args(tree parms)4613 template_parms_level_to_args (tree parms)
4614 {
4615   tree a = copy_node (parms);
4616   TREE_TYPE (a) = NULL_TREE;
4617   for (int i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4618     TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4619 
4620   if (CHECKING_P)
4621     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4622 
4623   return a;
4624 }
4625 
4626 /* Given a set of template parameters, return them as a set of template
4627    arguments.  The template parameters are represented as a TREE_VEC, in
4628    the form documented in cp-tree.h for template arguments.  */
4629 
4630 static tree
template_parms_to_args(tree parms)4631 template_parms_to_args (tree parms)
4632 {
4633   tree header;
4634   tree args = NULL_TREE;
4635   int length = TMPL_PARMS_DEPTH (parms);
4636   int l = length;
4637 
4638   /* If there is only one level of template parameters, we do not
4639      create a TREE_VEC of TREE_VECs.  Instead, we return a single
4640      TREE_VEC containing the arguments.  */
4641   if (length > 1)
4642     args = make_tree_vec (length);
4643 
4644   for (header = parms; header; header = TREE_CHAIN (header))
4645     {
4646       tree a = template_parms_level_to_args (TREE_VALUE (header));
4647 
4648       if (length > 1)
4649 	TREE_VEC_ELT (args, --l) = a;
4650       else
4651 	args = a;
4652     }
4653 
4654   return args;
4655 }
4656 
4657 /* Within the declaration of a template, return the currently active
4658    template parameters as an argument TREE_VEC.  */
4659 
4660 static tree
current_template_args(void)4661 current_template_args (void)
4662 {
4663   return template_parms_to_args (current_template_parms);
4664 }
4665 
4666 /* Update the declared TYPE by doing any lookups which were thought to be
4667    dependent, but are not now that we know the SCOPE of the declarator.  */
4668 
4669 tree
maybe_update_decl_type(tree orig_type,tree scope)4670 maybe_update_decl_type (tree orig_type, tree scope)
4671 {
4672   tree type = orig_type;
4673 
4674   if (type == NULL_TREE)
4675     return type;
4676 
4677   if (TREE_CODE (orig_type) == TYPE_DECL)
4678     type = TREE_TYPE (type);
4679 
4680   if (scope && TYPE_P (scope) && dependent_type_p (scope)
4681       && dependent_type_p (type)
4682       /* Don't bother building up the args in this case.  */
4683       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4684     {
4685       /* tsubst in the args corresponding to the template parameters,
4686 	 including auto if present.  Most things will be unchanged, but
4687 	 make_typename_type and tsubst_qualified_id will resolve
4688 	 TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
4689       tree args = current_template_args ();
4690       tree auto_node = type_uses_auto (type);
4691       tree pushed;
4692       if (auto_node)
4693 	{
4694 	  tree auto_vec = make_tree_vec (1);
4695 	  TREE_VEC_ELT (auto_vec, 0) = auto_node;
4696 	  args = add_to_template_args (args, auto_vec);
4697 	}
4698       pushed = push_scope (scope);
4699       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4700       if (pushed)
4701 	pop_scope (scope);
4702     }
4703 
4704   if (type == error_mark_node)
4705     return orig_type;
4706 
4707   if (TREE_CODE (orig_type) == TYPE_DECL)
4708     {
4709       if (same_type_p (type, TREE_TYPE (orig_type)))
4710 	type = orig_type;
4711       else
4712 	type = TYPE_NAME (type);
4713     }
4714   return type;
4715 }
4716 
4717 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4718    template PARMS and constraints, CONSTR.  If MEMBER_TEMPLATE_P is true,
4719    the new  template is a member template. */
4720 
4721 tree
build_template_decl(tree decl,tree parms,bool member_template_p)4722 build_template_decl (tree decl, tree parms, bool member_template_p)
4723 {
4724   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4725   SET_DECL_LANGUAGE (tmpl, DECL_LANGUAGE (decl));
4726   DECL_TEMPLATE_PARMS (tmpl) = parms;
4727   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4728   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
4729   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4730 
4731   return tmpl;
4732 }
4733 
4734 struct template_parm_data
4735 {
4736   /* The level of the template parameters we are currently
4737      processing.  */
4738   int level;
4739 
4740   /* The index of the specialization argument we are currently
4741      processing.  */
4742   int current_arg;
4743 
4744   /* An array whose size is the number of template parameters.  The
4745      elements are nonzero if the parameter has been used in any one
4746      of the arguments processed so far.  */
4747   int* parms;
4748 
4749   /* An array whose size is the number of template arguments.  The
4750      elements are nonzero if the argument makes use of template
4751      parameters of this level.  */
4752   int* arg_uses_template_parms;
4753 };
4754 
4755 /* Subroutine of push_template_decl used to see if each template
4756    parameter in a partial specialization is used in the explicit
4757    argument list.  If T is of the LEVEL given in DATA (which is
4758    treated as a template_parm_data*), then DATA->PARMS is marked
4759    appropriately.  */
4760 
4761 static int
mark_template_parm(tree t,void * data)4762 mark_template_parm (tree t, void* data)
4763 {
4764   int level;
4765   int idx;
4766   struct template_parm_data* tpd = (struct template_parm_data*) data;
4767 
4768   template_parm_level_and_index (t, &level, &idx);
4769 
4770   if (level == tpd->level)
4771     {
4772       tpd->parms[idx] = 1;
4773       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
4774     }
4775 
4776   /* In C++17 the type of a non-type argument is a deduced context.  */
4777   if (cxx_dialect >= cxx17
4778       && TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4779     for_each_template_parm (TREE_TYPE (t),
4780 			    &mark_template_parm,
4781 			    data,
4782 			    NULL,
4783 			    /*include_nondeduced_p=*/false);
4784 
4785   /* Return zero so that for_each_template_parm will continue the
4786      traversal of the tree; we want to mark *every* template parm.  */
4787   return 0;
4788 }
4789 
4790 /* Process the partial specialization DECL.  */
4791 
4792 static tree
process_partial_specialization(tree decl)4793 process_partial_specialization (tree decl)
4794 {
4795   tree type = TREE_TYPE (decl);
4796   tree tinfo = get_template_info (decl);
4797   tree maintmpl = TI_TEMPLATE (tinfo);
4798   tree specargs = TI_ARGS (tinfo);
4799   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
4800   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
4801   tree inner_parms;
4802   tree inst;
4803   int nargs = TREE_VEC_LENGTH (inner_args);
4804   int ntparms;
4805   int  i;
4806   bool did_error_intro = false;
4807   struct template_parm_data tpd;
4808   struct template_parm_data tpd2;
4809 
4810   gcc_assert (current_template_parms);
4811 
4812   /* A concept cannot be specialized.  */
4813   if (flag_concepts && variable_concept_p (maintmpl))
4814     {
4815       error ("specialization of variable concept %q#D", maintmpl);
4816       return error_mark_node;
4817     }
4818 
4819   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4820   ntparms = TREE_VEC_LENGTH (inner_parms);
4821 
4822   /* We check that each of the template parameters given in the
4823      partial specialization is used in the argument list to the
4824      specialization.  For example:
4825 
4826        template <class T> struct S;
4827        template <class T> struct S<T*>;
4828 
4829      The second declaration is OK because `T*' uses the template
4830      parameter T, whereas
4831 
4832        template <class T> struct S<int>;
4833 
4834      is no good.  Even trickier is:
4835 
4836        template <class T>
4837        struct S1
4838        {
4839 	  template <class U>
4840 	  struct S2;
4841 	  template <class U>
4842 	  struct S2<T>;
4843        };
4844 
4845      The S2<T> declaration is actually invalid; it is a
4846      full-specialization.  Of course,
4847 
4848 	  template <class U>
4849 	  struct S2<T (*)(U)>;
4850 
4851      or some such would have been OK.  */
4852   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
4853   tpd.parms = XALLOCAVEC (int, ntparms);
4854   memset (tpd.parms, 0, sizeof (int) * ntparms);
4855 
4856   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4857   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
4858   for (i = 0; i < nargs; ++i)
4859     {
4860       tpd.current_arg = i;
4861       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
4862 			      &mark_template_parm,
4863 			      &tpd,
4864 			      NULL,
4865 			      /*include_nondeduced_p=*/false);
4866     }
4867   for (i = 0; i < ntparms; ++i)
4868     if (tpd.parms[i] == 0)
4869       {
4870 	/* One of the template parms was not used in a deduced context in the
4871 	   specialization.  */
4872 	if (!did_error_intro)
4873 	  {
4874 	    error ("template parameters not deducible in "
4875 		   "partial specialization:");
4876 	    did_error_intro = true;
4877 	  }
4878 
4879 	inform (input_location, "        %qD",
4880 		TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
4881       }
4882 
4883   if (did_error_intro)
4884     return error_mark_node;
4885 
4886   /* [temp.class.spec]
4887 
4888      The argument list of the specialization shall not be identical to
4889      the implicit argument list of the primary template.  */
4890   tree main_args
4891     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
4892   if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args))
4893       && (!flag_concepts
4894 	  || !strictly_subsumes (current_template_constraints (),
4895 				 get_constraints (maintmpl))))
4896     {
4897       if (!flag_concepts)
4898         error ("partial specialization %q+D does not specialize "
4899 	       "any template arguments; to define the primary template, "
4900 	       "remove the template argument list", decl);
4901       else
4902         error ("partial specialization %q+D does not specialize any "
4903 	       "template arguments and is not more constrained than "
4904 	       "the primary template; to define the primary template, "
4905 	       "remove the template argument list", decl);
4906       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
4907     }
4908 
4909   /* A partial specialization that replaces multiple parameters of the
4910      primary template with a pack expansion is less specialized for those
4911      parameters.  */
4912   if (nargs < DECL_NTPARMS (maintmpl))
4913     {
4914       error ("partial specialization is not more specialized than the "
4915 	     "primary template because it replaces multiple parameters "
4916 	     "with a pack expansion");
4917       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
4918       /* Avoid crash in process_partial_specialization.  */
4919       return decl;
4920     }
4921 
4922   /* If we aren't in a dependent class, we can actually try deduction.  */
4923   else if (tpd.level == 1
4924 	   /* FIXME we should be able to handle a partial specialization of a
4925 	      partial instantiation, but currently we can't (c++/41727).  */
4926 	   && TMPL_ARGS_DEPTH (specargs) == 1
4927 	   && !get_partial_spec_bindings (maintmpl, maintmpl, specargs))
4928     {
4929       if (permerror (input_location, "partial specialization %qD is not "
4930 		     "more specialized than", decl))
4931 	inform (DECL_SOURCE_LOCATION (maintmpl), "primary template %qD",
4932 		maintmpl);
4933     }
4934 
4935   /* [temp.class.spec]
4936 
4937      A partially specialized non-type argument expression shall not
4938      involve template parameters of the partial specialization except
4939      when the argument expression is a simple identifier.
4940 
4941      The type of a template parameter corresponding to a specialized
4942      non-type argument shall not be dependent on a parameter of the
4943      specialization.
4944 
4945      Also, we verify that pack expansions only occur at the
4946      end of the argument list.  */
4947   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
4948   tpd2.parms = 0;
4949   for (i = 0; i < nargs; ++i)
4950     {
4951       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
4952       tree arg = TREE_VEC_ELT (inner_args, i);
4953       tree packed_args = NULL_TREE;
4954       int j, len = 1;
4955 
4956       if (ARGUMENT_PACK_P (arg))
4957         {
4958           /* Extract the arguments from the argument pack. We'll be
4959              iterating over these in the following loop.  */
4960           packed_args = ARGUMENT_PACK_ARGS (arg);
4961           len = TREE_VEC_LENGTH (packed_args);
4962         }
4963 
4964       for (j = 0; j < len; j++)
4965         {
4966           if (packed_args)
4967             /* Get the Jth argument in the parameter pack.  */
4968             arg = TREE_VEC_ELT (packed_args, j);
4969 
4970           if (PACK_EXPANSION_P (arg))
4971             {
4972               /* Pack expansions must come at the end of the
4973                  argument list.  */
4974               if ((packed_args && j < len - 1)
4975                   || (!packed_args && i < nargs - 1))
4976                 {
4977                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4978                     error ("parameter pack argument %qE must be at the "
4979 			   "end of the template argument list", arg);
4980                   else
4981                     error ("parameter pack argument %qT must be at the "
4982 			   "end of the template argument list", arg);
4983                 }
4984             }
4985 
4986           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4987             /* We only care about the pattern.  */
4988             arg = PACK_EXPANSION_PATTERN (arg);
4989 
4990           if (/* These first two lines are the `non-type' bit.  */
4991               !TYPE_P (arg)
4992               && TREE_CODE (arg) != TEMPLATE_DECL
4993               /* This next two lines are the `argument expression is not just a
4994                  simple identifier' condition and also the `specialized
4995                  non-type argument' bit.  */
4996               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
4997 	      && !(REFERENCE_REF_P (arg)
4998 		   && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
4999             {
5000               if ((!packed_args && tpd.arg_uses_template_parms[i])
5001                   || (packed_args && uses_template_parms (arg)))
5002                 error ("template argument %qE involves template parameter(s)",
5003                        arg);
5004               else
5005                 {
5006                   /* Look at the corresponding template parameter,
5007                      marking which template parameters its type depends
5008                      upon.  */
5009                   tree type = TREE_TYPE (parm);
5010 
5011                   if (!tpd2.parms)
5012                     {
5013                       /* We haven't yet initialized TPD2.  Do so now.  */
5014                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5015                       /* The number of parameters here is the number in the
5016                          main template, which, as checked in the assertion
5017                          above, is NARGS.  */
5018                       tpd2.parms = XALLOCAVEC (int, nargs);
5019                       tpd2.level =
5020                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
5021                     }
5022 
5023                   /* Mark the template parameters.  But this time, we're
5024                      looking for the template parameters of the main
5025                      template, not in the specialization.  */
5026                   tpd2.current_arg = i;
5027                   tpd2.arg_uses_template_parms[i] = 0;
5028                   memset (tpd2.parms, 0, sizeof (int) * nargs);
5029                   for_each_template_parm (type,
5030                                           &mark_template_parm,
5031                                           &tpd2,
5032                                           NULL,
5033 					  /*include_nondeduced_p=*/false);
5034 
5035                   if (tpd2.arg_uses_template_parms [i])
5036                     {
5037                       /* The type depended on some template parameters.
5038                          If they are fully specialized in the
5039                          specialization, that's OK.  */
5040                       int j;
5041                       int count = 0;
5042                       for (j = 0; j < nargs; ++j)
5043                         if (tpd2.parms[j] != 0
5044                             && tpd.arg_uses_template_parms [j])
5045                           ++count;
5046                       if (count != 0)
5047                         error_n (input_location, count,
5048                                  "type %qT of template argument %qE depends "
5049                                  "on a template parameter",
5050                                  "type %qT of template argument %qE depends "
5051                                  "on template parameters",
5052                                  type,
5053                                  arg);
5054                     }
5055                 }
5056             }
5057         }
5058     }
5059 
5060   /* We should only get here once.  */
5061   if (TREE_CODE (decl) == TYPE_DECL)
5062     gcc_assert (!COMPLETE_TYPE_P (type));
5063 
5064   // Build the template decl.
5065   tree tmpl = build_template_decl (decl, current_template_parms,
5066 				   DECL_MEMBER_TEMPLATE_P (maintmpl));
5067   TREE_TYPE (tmpl) = type;
5068   DECL_TEMPLATE_RESULT (tmpl) = decl;
5069   SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5070   DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
5071   DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
5072 
5073   /* Give template template parms a DECL_CONTEXT of the template
5074      for which they are a parameter.  */
5075   for (i = 0; i < ntparms; ++i)
5076     {
5077       tree parm = TREE_VALUE (TREE_VEC_ELT (inner_parms, i));
5078       if (TREE_CODE (parm) == TEMPLATE_DECL)
5079 	DECL_CONTEXT (parm) = tmpl;
5080     }
5081 
5082   if (VAR_P (decl))
5083     /* We didn't register this in check_explicit_specialization so we could
5084        wait until the constraints were set.  */
5085     decl = register_specialization (decl, maintmpl, specargs, false, 0);
5086   else
5087     associate_classtype_constraints (type);
5088 
5089   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
5090     = tree_cons (specargs, tmpl,
5091                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
5092   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
5093 
5094   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
5095        inst = TREE_CHAIN (inst))
5096     {
5097       tree instance = TREE_VALUE (inst);
5098       if (TYPE_P (instance)
5099 	  ? (COMPLETE_TYPE_P (instance)
5100 	     && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
5101 	  : DECL_TEMPLATE_INSTANTIATION (instance))
5102 	{
5103 	  tree spec = most_specialized_partial_spec (instance, tf_none);
5104 	  tree inst_decl = (DECL_P (instance)
5105 			    ? instance : TYPE_NAME (instance));
5106 	  if (!spec)
5107 	    /* OK */;
5108 	  else if (spec == error_mark_node)
5109 	    permerror (input_location,
5110 		       "declaration of %qD ambiguates earlier template "
5111 		       "instantiation for %qD", decl, inst_decl);
5112 	  else if (TREE_VALUE (spec) == tmpl)
5113 	    permerror (input_location,
5114 		       "partial specialization of %qD after instantiation "
5115 		       "of %qD", decl, inst_decl);
5116 	}
5117     }
5118 
5119   return decl;
5120 }
5121 
5122 /* PARM is a template parameter of some form; return the corresponding
5123    TEMPLATE_PARM_INDEX.  */
5124 
5125 static tree
get_template_parm_index(tree parm)5126 get_template_parm_index (tree parm)
5127 {
5128   if (TREE_CODE (parm) == PARM_DECL
5129       || TREE_CODE (parm) == CONST_DECL)
5130     parm = DECL_INITIAL (parm);
5131   else if (TREE_CODE (parm) == TYPE_DECL
5132 	   || TREE_CODE (parm) == TEMPLATE_DECL)
5133     parm = TREE_TYPE (parm);
5134   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
5135       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM
5136       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
5137     parm = TEMPLATE_TYPE_PARM_INDEX (parm);
5138   gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
5139   return parm;
5140 }
5141 
5142 /* Subroutine of fixed_parameter_pack_p below.  Look for any template
5143    parameter packs used by the template parameter PARM.  */
5144 
5145 static void
fixed_parameter_pack_p_1(tree parm,struct find_parameter_pack_data * ppd)5146 fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
5147 {
5148   /* A type parm can't refer to another parm.  */
5149   if (TREE_CODE (parm) == TYPE_DECL || parm == error_mark_node)
5150     return;
5151   else if (TREE_CODE (parm) == PARM_DECL)
5152     {
5153       cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
5154 		    ppd, ppd->visited);
5155       return;
5156     }
5157 
5158   gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
5159 
5160   tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
5161   for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
5162     fixed_parameter_pack_p_1 (TREE_VALUE (TREE_VEC_ELT (vec, i)), ppd);
5163 }
5164 
5165 /* PARM is a template parameter pack.  Return any parameter packs used in
5166    its type or the type of any of its template parameters.  If there are
5167    any such packs, it will be instantiated into a fixed template parameter
5168    list by partial instantiation rather than be fully deduced.  */
5169 
5170 tree
fixed_parameter_pack_p(tree parm)5171 fixed_parameter_pack_p (tree parm)
5172 {
5173   /* This can only be true in a member template.  */
5174   if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
5175     return NULL_TREE;
5176   /* This can only be true for a parameter pack.  */
5177   if (!template_parameter_pack_p (parm))
5178     return NULL_TREE;
5179   /* A type parm can't refer to another parm.  */
5180   if (TREE_CODE (parm) == TYPE_DECL)
5181     return NULL_TREE;
5182 
5183   tree parameter_packs = NULL_TREE;
5184   struct find_parameter_pack_data ppd;
5185   ppd.parameter_packs = &parameter_packs;
5186   ppd.visited = new hash_set<tree>;
5187   ppd.type_pack_expansion_p = false;
5188 
5189   fixed_parameter_pack_p_1 (parm, &ppd);
5190 
5191   delete ppd.visited;
5192   return parameter_packs;
5193 }
5194 
5195 /* Check that a template declaration's use of default arguments and
5196    parameter packs is not invalid.  Here, PARMS are the template
5197    parameters.  IS_PRIMARY is true if DECL is the thing declared by
5198    a primary template.  IS_PARTIAL is true if DECL is a partial
5199    specialization.
5200 
5201    IS_FRIEND_DECL is nonzero if DECL is either a non-defining friend
5202    function template declaration or a friend class template
5203    declaration.  In the function case, 1 indicates a declaration, 2
5204    indicates a redeclaration.  When IS_FRIEND_DECL=2, no errors are
5205    emitted for extraneous default arguments.
5206 
5207    Returns TRUE if there were no errors found, FALSE otherwise. */
5208 
5209 bool
check_default_tmpl_args(tree decl,tree parms,bool is_primary,bool is_partial,int is_friend_decl)5210 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
5211                          bool is_partial, int is_friend_decl)
5212 {
5213   const char *msg;
5214   int last_level_to_check;
5215   tree parm_level;
5216   bool no_errors = true;
5217 
5218   /* [temp.param]
5219 
5220      A default template-argument shall not be specified in a
5221      function template declaration or a function template definition, nor
5222      in the template-parameter-list of the definition of a member of a
5223      class template.  */
5224 
5225   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
5226       || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_FUNCTION_P (decl)))
5227     /* You can't have a function template declaration in a local
5228        scope, nor you can you define a member of a class template in a
5229        local scope.  */
5230     return true;
5231 
5232   if ((TREE_CODE (decl) == TYPE_DECL
5233        && TREE_TYPE (decl)
5234        && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5235       || (TREE_CODE (decl) == FUNCTION_DECL
5236 	  && LAMBDA_FUNCTION_P (decl)))
5237     /* A lambda doesn't have an explicit declaration; don't complain
5238        about the parms of the enclosing class.  */
5239     return true;
5240 
5241   if (current_class_type
5242       && !TYPE_BEING_DEFINED (current_class_type)
5243       && DECL_LANG_SPECIFIC (decl)
5244       && DECL_DECLARES_FUNCTION_P (decl)
5245       /* If this is either a friend defined in the scope of the class
5246 	 or a member function.  */
5247       && (DECL_FUNCTION_MEMBER_P (decl)
5248 	  ? same_type_p (DECL_CONTEXT (decl), current_class_type)
5249 	  : DECL_FRIEND_CONTEXT (decl)
5250 	  ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
5251 	  : false)
5252       /* And, if it was a member function, it really was defined in
5253 	 the scope of the class.  */
5254       && (!DECL_FUNCTION_MEMBER_P (decl)
5255 	  || DECL_INITIALIZED_IN_CLASS_P (decl)))
5256     /* We already checked these parameters when the template was
5257        declared, so there's no need to do it again now.  This function
5258        was defined in class scope, but we're processing its body now
5259        that the class is complete.  */
5260     return true;
5261 
5262   /* Core issue 226 (C++0x only): the following only applies to class
5263      templates.  */
5264   if (is_primary
5265       && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
5266     {
5267       /* [temp.param]
5268 
5269          If a template-parameter has a default template-argument, all
5270          subsequent template-parameters shall have a default
5271          template-argument supplied.  */
5272       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
5273         {
5274           tree inner_parms = TREE_VALUE (parm_level);
5275           int ntparms = TREE_VEC_LENGTH (inner_parms);
5276           int seen_def_arg_p = 0;
5277           int i;
5278 
5279           for (i = 0; i < ntparms; ++i)
5280             {
5281               tree parm = TREE_VEC_ELT (inner_parms, i);
5282 
5283               if (parm == error_mark_node)
5284                 continue;
5285 
5286               if (TREE_PURPOSE (parm))
5287                 seen_def_arg_p = 1;
5288               else if (seen_def_arg_p
5289 		       && !template_parameter_pack_p (TREE_VALUE (parm)))
5290                 {
5291                   error ("no default argument for %qD", TREE_VALUE (parm));
5292                   /* For better subsequent error-recovery, we indicate that
5293                      there should have been a default argument.  */
5294                   TREE_PURPOSE (parm) = error_mark_node;
5295                   no_errors = false;
5296                 }
5297 	      else if (!is_partial
5298 		       && !is_friend_decl
5299 		       /* Don't complain about an enclosing partial
5300 			  specialization.  */
5301 		       && parm_level == parms
5302 		       && TREE_CODE (decl) == TYPE_DECL
5303 		       && i < ntparms - 1
5304 		       && template_parameter_pack_p (TREE_VALUE (parm))
5305 		       /* A fixed parameter pack will be partially
5306 			  instantiated into a fixed length list.  */
5307 		       && !fixed_parameter_pack_p (TREE_VALUE (parm)))
5308 		{
5309 		  /* A primary class template can only have one
5310 		     parameter pack, at the end of the template
5311 		     parameter list.  */
5312 
5313 		  error ("parameter pack %q+D must be at the end of the"
5314 			 " template parameter list", TREE_VALUE (parm));
5315 
5316 		  TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
5317 		    = error_mark_node;
5318 		  no_errors = false;
5319 		}
5320             }
5321         }
5322     }
5323 
5324   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
5325       || is_partial
5326       || !is_primary
5327       || is_friend_decl)
5328     /* For an ordinary class template, default template arguments are
5329        allowed at the innermost level, e.g.:
5330 	 template <class T = int>
5331 	 struct S {};
5332        but, in a partial specialization, they're not allowed even
5333        there, as we have in [temp.class.spec]:
5334 
5335 	 The template parameter list of a specialization shall not
5336 	 contain default template argument values.
5337 
5338        So, for a partial specialization, or for a function template
5339        (in C++98/C++03), we look at all of them.  */
5340     ;
5341   else
5342     /* But, for a primary class template that is not a partial
5343        specialization we look at all template parameters except the
5344        innermost ones.  */
5345     parms = TREE_CHAIN (parms);
5346 
5347   /* Figure out what error message to issue.  */
5348   if (is_friend_decl == 2)
5349     msg = G_("default template arguments may not be used in function template "
5350 	     "friend re-declaration");
5351   else if (is_friend_decl)
5352     msg = G_("default template arguments may not be used in template "
5353 	     "friend declarations");
5354   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
5355     msg = G_("default template arguments may not be used in function templates "
5356 	     "without -std=c++11 or -std=gnu++11");
5357   else if (is_partial)
5358     msg = G_("default template arguments may not be used in "
5359 	     "partial specializations");
5360   else if (current_class_type && CLASSTYPE_IS_TEMPLATE (current_class_type))
5361     msg = G_("default argument for template parameter for class enclosing %qD");
5362   else
5363     /* Per [temp.param]/9, "A default template-argument shall not be
5364        specified in the template-parameter-lists of the definition of
5365        a member of a class template that appears outside of the member's
5366        class.", thus if we aren't handling a member of a class template
5367        there is no need to examine the parameters.  */
5368     return true;
5369 
5370   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
5371     /* If we're inside a class definition, there's no need to
5372        examine the parameters to the class itself.  On the one
5373        hand, they will be checked when the class is defined, and,
5374        on the other, default arguments are valid in things like:
5375 	 template <class T = double>
5376 	 struct S { template <class U> void f(U); };
5377        Here the default argument for `S' has no bearing on the
5378        declaration of `f'.  */
5379     last_level_to_check = template_class_depth (current_class_type) + 1;
5380   else
5381     /* Check everything.  */
5382     last_level_to_check = 0;
5383 
5384   for (parm_level = parms;
5385        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
5386        parm_level = TREE_CHAIN (parm_level))
5387     {
5388       tree inner_parms = TREE_VALUE (parm_level);
5389       int i;
5390       int ntparms;
5391 
5392       ntparms = TREE_VEC_LENGTH (inner_parms);
5393       for (i = 0; i < ntparms; ++i)
5394         {
5395           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
5396             continue;
5397 
5398 	  if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
5399 	    {
5400 	      if (msg)
5401 	        {
5402                   no_errors = false;
5403                   if (is_friend_decl == 2)
5404                     return no_errors;
5405 
5406 		  error (msg, decl);
5407 		  msg = 0;
5408 	        }
5409 
5410 	      /* Clear out the default argument so that we are not
5411 	         confused later.  */
5412 	      TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
5413 	    }
5414         }
5415 
5416       /* At this point, if we're still interested in issuing messages,
5417 	 they must apply to classes surrounding the object declared.  */
5418       if (msg)
5419 	msg = G_("default argument for template parameter for class "
5420 		 "enclosing %qD");
5421     }
5422 
5423   return no_errors;
5424 }
5425 
5426 /* Worker for push_template_decl_real, called via
5427    for_each_template_parm.  DATA is really an int, indicating the
5428    level of the parameters we are interested in.  If T is a template
5429    parameter of that level, return nonzero.  */
5430 
5431 static int
template_parm_this_level_p(tree t,void * data)5432 template_parm_this_level_p (tree t, void* data)
5433 {
5434   int this_level = *(int *)data;
5435   int level;
5436 
5437   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5438     level = TEMPLATE_PARM_LEVEL (t);
5439   else
5440     level = TEMPLATE_TYPE_LEVEL (t);
5441   return level == this_level;
5442 }
5443 
5444 /* Worker for uses_outer_template_parms, called via for_each_template_parm.
5445    DATA is really an int, indicating the innermost outer level of parameters.
5446    If T is a template parameter of that level or further out, return
5447    nonzero.  */
5448 
5449 static int
template_parm_outer_level(tree t,void * data)5450 template_parm_outer_level (tree t, void *data)
5451 {
5452   int this_level = *(int *)data;
5453   int level;
5454 
5455   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5456     level = TEMPLATE_PARM_LEVEL (t);
5457   else
5458     level = TEMPLATE_TYPE_LEVEL (t);
5459   return level <= this_level;
5460 }
5461 
5462 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
5463    parameters given by current_template_args, or reuses a
5464    previously existing one, if appropriate.  Returns the DECL, or an
5465    equivalent one, if it is replaced via a call to duplicate_decls.
5466 
5467    If IS_FRIEND is true, DECL is a friend declaration.  */
5468 
5469 tree
push_template_decl_real(tree decl,bool is_friend)5470 push_template_decl_real (tree decl, bool is_friend)
5471 {
5472   tree tmpl;
5473   tree args;
5474   tree info;
5475   tree ctx;
5476   bool is_primary;
5477   bool is_partial;
5478   int new_template_p = 0;
5479   /* True if the template is a member template, in the sense of
5480      [temp.mem].  */
5481   bool member_template_p = false;
5482 
5483   if (decl == error_mark_node || !current_template_parms)
5484     return error_mark_node;
5485 
5486   /* See if this is a partial specialization.  */
5487   is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
5488 		 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
5489 		 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
5490 		|| (VAR_P (decl)
5491 		    && DECL_LANG_SPECIFIC (decl)
5492 		    && DECL_TEMPLATE_SPECIALIZATION (decl)
5493 		    && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
5494 
5495   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
5496     is_friend = true;
5497 
5498   if (is_friend)
5499     /* For a friend, we want the context of the friend, not
5500        the type of which it is a friend.  */
5501     ctx = CP_DECL_CONTEXT (decl);
5502   else if (CP_DECL_CONTEXT (decl)
5503 	   && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
5504     /* In the case of a virtual function, we want the class in which
5505        it is defined.  */
5506     ctx = CP_DECL_CONTEXT (decl);
5507   else
5508     /* Otherwise, if we're currently defining some class, the DECL
5509        is assumed to be a member of the class.  */
5510     ctx = current_scope ();
5511 
5512   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
5513     ctx = NULL_TREE;
5514 
5515   if (!DECL_CONTEXT (decl))
5516     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5517 
5518   /* See if this is a primary template.  */
5519   if (is_friend && ctx
5520       && uses_template_parms_level (ctx, processing_template_decl))
5521     /* A friend template that specifies a class context, i.e.
5522          template <typename T> friend void A<T>::f();
5523        is not primary.  */
5524     is_primary = false;
5525   else if (TREE_CODE (decl) == TYPE_DECL
5526 	   && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5527     is_primary = false;
5528   else
5529     is_primary = template_parm_scope_p ();
5530 
5531   if (is_primary)
5532     {
5533       warning (OPT_Wtemplates, "template %qD declared", decl);
5534 
5535       if (DECL_CLASS_SCOPE_P (decl))
5536 	member_template_p = true;
5537       if (TREE_CODE (decl) == TYPE_DECL
5538 	  && anon_aggrname_p (DECL_NAME (decl)))
5539 	{
5540 	  error ("template class without a name");
5541 	  return error_mark_node;
5542 	}
5543       else if (TREE_CODE (decl) == FUNCTION_DECL)
5544 	{
5545 	  if (member_template_p)
5546 	    {
5547 	      if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
5548 		error ("member template %qD may not have virt-specifiers", decl);
5549 	    }
5550 	  if (DECL_DESTRUCTOR_P (decl))
5551 	    {
5552 	      /* [temp.mem]
5553 
5554 		 A destructor shall not be a member template.  */
5555 	      error ("destructor %qD declared as member template", decl);
5556 	      return error_mark_node;
5557 	    }
5558 	  if (IDENTIFIER_NEWDEL_OP_P (DECL_NAME (decl))
5559 	      && (!prototype_p (TREE_TYPE (decl))
5560 		  || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
5561 		  || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5562 		  || (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5563 		      == void_list_node)))
5564 	    {
5565 	      /* [basic.stc.dynamic.allocation]
5566 
5567 		 An allocation function can be a function
5568 		 template. ... Template allocation functions shall
5569 		 have two or more parameters.  */
5570 	      error ("invalid template declaration of %qD", decl);
5571 	      return error_mark_node;
5572 	    }
5573 	}
5574       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5575 	       && CLASS_TYPE_P (TREE_TYPE (decl)))
5576 	{
5577 	  /* Class template, set TEMPLATE_TYPE_PARM_FOR_CLASS.  */
5578 	  tree parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
5579 	  for (int i = 0; i < TREE_VEC_LENGTH (parms); ++i)
5580 	    {
5581 	      tree t = TREE_VALUE (TREE_VEC_ELT (parms, i));
5582 	      if (TREE_CODE (t) == TYPE_DECL)
5583 		t = TREE_TYPE (t);
5584 	      if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
5585 		TEMPLATE_TYPE_PARM_FOR_CLASS (t) = true;
5586 	    }
5587 	}
5588       else if (TREE_CODE (decl) == TYPE_DECL
5589 	       && TYPE_DECL_ALIAS_P (decl))
5590 	/* alias-declaration */
5591 	gcc_assert (!DECL_ARTIFICIAL (decl));
5592       else if (VAR_P (decl))
5593 	/* C++14 variable template. */;
5594       else
5595 	{
5596 	  error ("template declaration of %q#D", decl);
5597 	  return error_mark_node;
5598 	}
5599     }
5600 
5601   /* Check to see that the rules regarding the use of default
5602      arguments are not being violated.  We check args for a friend
5603      functions when we know whether it's a definition, introducing
5604      declaration or re-declaration.  */
5605   if (!is_friend || TREE_CODE (decl) != FUNCTION_DECL)
5606     check_default_tmpl_args (decl, current_template_parms,
5607 			     is_primary, is_partial, is_friend);
5608 
5609   /* Ensure that there are no parameter packs in the type of this
5610      declaration that have not been expanded.  */
5611   if (TREE_CODE (decl) == FUNCTION_DECL)
5612     {
5613       /* Check each of the arguments individually to see if there are
5614          any bare parameter packs.  */
5615       tree type = TREE_TYPE (decl);
5616       tree arg = DECL_ARGUMENTS (decl);
5617       tree argtype = TYPE_ARG_TYPES (type);
5618 
5619       while (arg && argtype)
5620         {
5621           if (!DECL_PACK_P (arg)
5622               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
5623             {
5624             /* This is a PARM_DECL that contains unexpanded parameter
5625                packs. We have already complained about this in the
5626                check_for_bare_parameter_packs call, so just replace
5627                these types with ERROR_MARK_NODE.  */
5628               TREE_TYPE (arg) = error_mark_node;
5629               TREE_VALUE (argtype) = error_mark_node;
5630             }
5631 
5632           arg = DECL_CHAIN (arg);
5633           argtype = TREE_CHAIN (argtype);
5634         }
5635 
5636       /* Check for bare parameter packs in the return type and the
5637          exception specifiers.  */
5638       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
5639 	/* Errors were already issued, set return type to int
5640 	   as the frontend doesn't expect error_mark_node as
5641 	   the return type.  */
5642 	TREE_TYPE (type) = integer_type_node;
5643       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
5644 	TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
5645     }
5646   else if (check_for_bare_parameter_packs ((TREE_CODE (decl) == TYPE_DECL
5647 					    && TYPE_DECL_ALIAS_P (decl))
5648 					   ? DECL_ORIGINAL_TYPE (decl)
5649 					   : TREE_TYPE (decl)))
5650     {
5651       TREE_TYPE (decl) = error_mark_node;
5652       return error_mark_node;
5653     }
5654 
5655   if (is_partial)
5656     return process_partial_specialization (decl);
5657 
5658   args = current_template_args ();
5659 
5660   if (!ctx
5661       || TREE_CODE (ctx) == FUNCTION_DECL
5662       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
5663       || (TREE_CODE (decl) == TYPE_DECL
5664 	  && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5665       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
5666     {
5667       if (DECL_LANG_SPECIFIC (decl)
5668 	  && DECL_TEMPLATE_INFO (decl)
5669 	  && DECL_TI_TEMPLATE (decl))
5670 	tmpl = DECL_TI_TEMPLATE (decl);
5671       /* If DECL is a TYPE_DECL for a class-template, then there won't
5672 	 be DECL_LANG_SPECIFIC.  The information equivalent to
5673 	 DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
5674       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5675 	       && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
5676 	       && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
5677 	{
5678 	  /* Since a template declaration already existed for this
5679 	     class-type, we must be redeclaring it here.  Make sure
5680 	     that the redeclaration is valid.  */
5681 	  redeclare_class_template (TREE_TYPE (decl),
5682 				    current_template_parms,
5683 				    current_template_constraints ());
5684 	  /* We don't need to create a new TEMPLATE_DECL; just use the
5685 	     one we already had.  */
5686 	  tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
5687 	}
5688       else
5689 	{
5690 	  tmpl = build_template_decl (decl, current_template_parms,
5691 				      member_template_p);
5692 	  new_template_p = 1;
5693 
5694 	  if (DECL_LANG_SPECIFIC (decl)
5695 	      && DECL_TEMPLATE_SPECIALIZATION (decl))
5696 	    {
5697 	      /* A specialization of a member template of a template
5698 		 class.  */
5699 	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5700 	      DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
5701 	      DECL_TEMPLATE_INFO (decl) = NULL_TREE;
5702 	    }
5703 	}
5704     }
5705   else
5706     {
5707       tree a, t, current, parms;
5708       int i;
5709       tree tinfo = get_template_info (decl);
5710 
5711       if (!tinfo)
5712 	{
5713 	  error ("template definition of non-template %q#D", decl);
5714 	  return error_mark_node;
5715 	}
5716 
5717       tmpl = TI_TEMPLATE (tinfo);
5718 
5719       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
5720 	  && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
5721 	  && DECL_TEMPLATE_SPECIALIZATION (decl)
5722 	  && DECL_MEMBER_TEMPLATE_P (tmpl))
5723 	{
5724 	  tree new_tmpl;
5725 
5726 	  /* The declaration is a specialization of a member
5727 	     template, declared outside the class.  Therefore, the
5728 	     innermost template arguments will be NULL, so we
5729 	     replace them with the arguments determined by the
5730 	     earlier call to check_explicit_specialization.  */
5731 	  args = DECL_TI_ARGS (decl);
5732 
5733 	  new_tmpl
5734 	    = build_template_decl (decl, current_template_parms,
5735 				   member_template_p);
5736 	  DECL_TEMPLATE_RESULT (new_tmpl) = decl;
5737 	  TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
5738 	  DECL_TI_TEMPLATE (decl) = new_tmpl;
5739 	  SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
5740 	  DECL_TEMPLATE_INFO (new_tmpl)
5741 	    = build_template_info (tmpl, args);
5742 
5743 	  register_specialization (new_tmpl,
5744 				   most_general_template (tmpl),
5745 				   args,
5746 				   is_friend, 0);
5747 	  return decl;
5748 	}
5749 
5750       /* Make sure the template headers we got make sense.  */
5751 
5752       parms = DECL_TEMPLATE_PARMS (tmpl);
5753       i = TMPL_PARMS_DEPTH (parms);
5754       if (TMPL_ARGS_DEPTH (args) != i)
5755 	{
5756 	  error ("expected %d levels of template parms for %q#D, got %d",
5757 		 i, decl, TMPL_ARGS_DEPTH (args));
5758 	  DECL_INTERFACE_KNOWN (decl) = 1;
5759 	  return error_mark_node;
5760 	}
5761       else
5762 	for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
5763 	  {
5764 	    a = TMPL_ARGS_LEVEL (args, i);
5765 	    t = INNERMOST_TEMPLATE_PARMS (parms);
5766 
5767 	    if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
5768 	      {
5769 		if (current == decl)
5770 		  error ("got %d template parameters for %q#D",
5771 			 TREE_VEC_LENGTH (a), decl);
5772 		else
5773 		  error ("got %d template parameters for %q#T",
5774 			 TREE_VEC_LENGTH (a), current);
5775 		error ("  but %d required", TREE_VEC_LENGTH (t));
5776 		/* Avoid crash in import_export_decl.  */
5777 		DECL_INTERFACE_KNOWN (decl) = 1;
5778 		return error_mark_node;
5779 	      }
5780 
5781 	    if (current == decl)
5782 	      current = ctx;
5783 	    else if (current == NULL_TREE)
5784 	      /* Can happen in erroneous input.  */
5785 	      break;
5786 	    else
5787 	      current = get_containing_scope (current);
5788 	  }
5789 
5790       /* Check that the parms are used in the appropriate qualifying scopes
5791 	 in the declarator.  */
5792       if (!comp_template_args
5793 	  (TI_ARGS (tinfo),
5794 	   TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
5795 	{
5796 	  error ("template arguments to %qD do not match original "
5797 		 "template %qD", decl, DECL_TEMPLATE_RESULT (tmpl));
5798 	  if (!uses_template_parms (TI_ARGS (tinfo)))
5799 	    inform (input_location, "use %<template<>%> for"
5800 		    " an explicit specialization");
5801 	  /* Avoid crash in import_export_decl.  */
5802 	  DECL_INTERFACE_KNOWN (decl) = 1;
5803 	  return error_mark_node;
5804 	}
5805     }
5806 
5807   DECL_TEMPLATE_RESULT (tmpl) = decl;
5808   TREE_TYPE (tmpl) = TREE_TYPE (decl);
5809 
5810   /* Push template declarations for global functions and types.  Note
5811      that we do not try to push a global template friend declared in a
5812      template class; such a thing may well depend on the template
5813      parameters of the class.  */
5814   if (new_template_p && !ctx
5815       && !(is_friend && template_class_depth (current_class_type) > 0))
5816     {
5817       tmpl = pushdecl_namespace_level (tmpl, is_friend);
5818       if (tmpl == error_mark_node)
5819 	return error_mark_node;
5820 
5821       /* Hide template friend classes that haven't been declared yet.  */
5822       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
5823 	{
5824 	  DECL_ANTICIPATED (tmpl) = 1;
5825 	  DECL_FRIEND_P (tmpl) = 1;
5826 	}
5827     }
5828 
5829   if (is_primary)
5830     {
5831       tree parms = DECL_TEMPLATE_PARMS (tmpl);
5832 
5833       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
5834 
5835       /* Give template template parms a DECL_CONTEXT of the template
5836 	 for which they are a parameter.  */
5837       parms = INNERMOST_TEMPLATE_PARMS (parms);
5838       for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
5839 	{
5840 	  tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5841 	  if (TREE_CODE (parm) == TEMPLATE_DECL)
5842 	    DECL_CONTEXT (parm) = tmpl;
5843 	}
5844 
5845       if (TREE_CODE (decl) == TYPE_DECL
5846 	  && TYPE_DECL_ALIAS_P (decl)
5847 	  && complex_alias_template_p (tmpl))
5848 	TEMPLATE_DECL_COMPLEX_ALIAS_P (tmpl) = true;
5849     }
5850 
5851   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
5852      back to its most general template.  If TMPL is a specialization,
5853      ARGS may only have the innermost set of arguments.  Add the missing
5854      argument levels if necessary.  */
5855   if (DECL_TEMPLATE_INFO (tmpl))
5856     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
5857 
5858   info = build_template_info (tmpl, args);
5859 
5860   if (DECL_IMPLICIT_TYPEDEF_P (decl))
5861     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
5862   else
5863     {
5864       if (is_primary)
5865 	retrofit_lang_decl (decl);
5866       if (DECL_LANG_SPECIFIC (decl))
5867 	DECL_TEMPLATE_INFO (decl) = info;
5868     }
5869 
5870   if (flag_implicit_templates
5871       && !is_friend
5872       && TREE_PUBLIC (decl)
5873       && VAR_OR_FUNCTION_DECL_P (decl))
5874     /* Set DECL_COMDAT on template instantiations; if we force
5875        them to be emitted by explicit instantiation or -frepo,
5876        mark_needed will tell cgraph to do the right thing.  */
5877     DECL_COMDAT (decl) = true;
5878 
5879   return DECL_TEMPLATE_RESULT (tmpl);
5880 }
5881 
5882 tree
push_template_decl(tree decl)5883 push_template_decl (tree decl)
5884 {
5885   return push_template_decl_real (decl, false);
5886 }
5887 
5888 /* FN is an inheriting constructor that inherits from the constructor
5889    template INHERITED; turn FN into a constructor template with a matching
5890    template header.  */
5891 
5892 tree
add_inherited_template_parms(tree fn,tree inherited)5893 add_inherited_template_parms (tree fn, tree inherited)
5894 {
5895   tree inner_parms
5896     = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
5897   inner_parms = copy_node (inner_parms);
5898   tree parms
5899     = tree_cons (size_int (processing_template_decl + 1),
5900 		 inner_parms, current_template_parms);
5901   tree tmpl = build_template_decl (fn, parms, /*member*/true);
5902   tree args = template_parms_to_args (parms);
5903   DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
5904   TREE_TYPE (tmpl) = TREE_TYPE (fn);
5905   DECL_TEMPLATE_RESULT (tmpl) = fn;
5906   DECL_ARTIFICIAL (tmpl) = true;
5907   DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
5908   return tmpl;
5909 }
5910 
5911 /* Called when a class template TYPE is redeclared with the indicated
5912    template PARMS, e.g.:
5913 
5914      template <class T> struct S;
5915      template <class T> struct S {};  */
5916 
5917 bool
redeclare_class_template(tree type,tree parms,tree cons)5918 redeclare_class_template (tree type, tree parms, tree cons)
5919 {
5920   tree tmpl;
5921   tree tmpl_parms;
5922   int i;
5923 
5924   if (!TYPE_TEMPLATE_INFO (type))
5925     {
5926       error ("%qT is not a template type", type);
5927       return false;
5928     }
5929 
5930   tmpl = TYPE_TI_TEMPLATE (type);
5931   if (!PRIMARY_TEMPLATE_P (tmpl))
5932     /* The type is nested in some template class.  Nothing to worry
5933        about here; there are no new template parameters for the nested
5934        type.  */
5935     return true;
5936 
5937   if (!parms)
5938     {
5939       error ("template specifiers not specified in declaration of %qD",
5940 	     tmpl);
5941       return false;
5942     }
5943 
5944   parms = INNERMOST_TEMPLATE_PARMS (parms);
5945   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
5946 
5947   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
5948     {
5949       error_n (input_location, TREE_VEC_LENGTH (parms),
5950                "redeclared with %d template parameter",
5951                "redeclared with %d template parameters",
5952                TREE_VEC_LENGTH (parms));
5953       inform_n (DECL_SOURCE_LOCATION (tmpl), TREE_VEC_LENGTH (tmpl_parms),
5954                 "previous declaration %qD used %d template parameter",
5955                 "previous declaration %qD used %d template parameters",
5956                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
5957       return false;
5958     }
5959 
5960   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
5961     {
5962       tree tmpl_parm;
5963       tree parm;
5964       tree tmpl_default;
5965       tree parm_default;
5966 
5967       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
5968           || TREE_VEC_ELT (parms, i) == error_mark_node)
5969         continue;
5970 
5971       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
5972       if (error_operand_p (tmpl_parm))
5973 	return false;
5974 
5975       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5976       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
5977       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
5978 
5979       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
5980 	 TEMPLATE_DECL.  */
5981       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
5982 	  || (TREE_CODE (tmpl_parm) != TYPE_DECL
5983 	      && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
5984 	  || (TREE_CODE (tmpl_parm) != PARM_DECL
5985 	      && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
5986 		  != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
5987 	  || (TREE_CODE (tmpl_parm) == PARM_DECL
5988 	      && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
5989 		  != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
5990 	{
5991 	  error ("template parameter %q+#D", tmpl_parm);
5992 	  error ("redeclared here as %q#D", parm);
5993 	  return false;
5994 	}
5995 
5996       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
5997 	{
5998 	  /* We have in [temp.param]:
5999 
6000 	     A template-parameter may not be given default arguments
6001 	     by two different declarations in the same scope.  */
6002 	  error_at (input_location, "redefinition of default argument for %q#D", parm);
6003 	  inform (DECL_SOURCE_LOCATION (tmpl_parm),
6004 		  "original definition appeared here");
6005 	  return false;
6006 	}
6007 
6008       if (parm_default != NULL_TREE)
6009 	/* Update the previous template parameters (which are the ones
6010 	   that will really count) with the new default value.  */
6011 	TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
6012       else if (tmpl_default != NULL_TREE)
6013 	/* Update the new parameters, too; they'll be used as the
6014 	   parameters for any members.  */
6015 	TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
6016 
6017       /* Give each template template parm in this redeclaration a
6018 	 DECL_CONTEXT of the template for which they are a parameter.  */
6019       if (TREE_CODE (parm) == TEMPLATE_DECL)
6020 	{
6021 	  gcc_assert (DECL_CONTEXT (parm) == NULL_TREE);
6022 	  DECL_CONTEXT (parm) = tmpl;
6023 	}
6024 
6025       if (TREE_CODE (parm) == TYPE_DECL)
6026 	TEMPLATE_TYPE_PARM_FOR_CLASS (TREE_TYPE (parm)) = true;
6027     }
6028 
6029   // Cannot redeclare a class template with a different set of constraints.
6030   if (!equivalent_constraints (get_constraints (tmpl), cons))
6031     {
6032       error_at (input_location, "redeclaration %q#D with different "
6033                                 "constraints", tmpl);
6034       inform (DECL_SOURCE_LOCATION (tmpl),
6035               "original declaration appeared here");
6036     }
6037 
6038     return true;
6039 }
6040 
6041 /* The actual substitution part of instantiate_non_dependent_expr_sfinae,
6042    to be used when the caller has already checked
6043    (processing_template_decl
6044     && !instantiation_dependent_expression_p (expr)
6045     && potential_constant_expression (expr))
6046    and cleared processing_template_decl.  */
6047 
6048 tree
instantiate_non_dependent_expr_internal(tree expr,tsubst_flags_t complain)6049 instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
6050 {
6051   return tsubst_copy_and_build (expr,
6052 				/*args=*/NULL_TREE,
6053 				complain,
6054 				/*in_decl=*/NULL_TREE,
6055 				/*function_p=*/false,
6056 				/*integral_constant_expression_p=*/true);
6057 }
6058 
6059 /* Simplify EXPR if it is a non-dependent expression.  Returns the
6060    (possibly simplified) expression.  */
6061 
6062 tree
instantiate_non_dependent_expr_sfinae(tree expr,tsubst_flags_t complain)6063 instantiate_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
6064 {
6065   if (expr == NULL_TREE)
6066     return NULL_TREE;
6067 
6068   /* If we're in a template, but EXPR isn't value dependent, simplify
6069      it.  We're supposed to treat:
6070 
6071        template <typename T> void f(T[1 + 1]);
6072        template <typename T> void f(T[2]);
6073 
6074      as two declarations of the same function, for example.  */
6075   if (processing_template_decl
6076       && is_nondependent_constant_expression (expr))
6077     {
6078       processing_template_decl_sentinel s;
6079       expr = instantiate_non_dependent_expr_internal (expr, complain);
6080     }
6081   return expr;
6082 }
6083 
6084 tree
instantiate_non_dependent_expr(tree expr)6085 instantiate_non_dependent_expr (tree expr)
6086 {
6087   return instantiate_non_dependent_expr_sfinae (expr, tf_error);
6088 }
6089 
6090 /* Like instantiate_non_dependent_expr, but return NULL_TREE rather than
6091    an uninstantiated expression.  */
6092 
6093 tree
instantiate_non_dependent_or_null(tree expr)6094 instantiate_non_dependent_or_null (tree expr)
6095 {
6096   if (expr == NULL_TREE)
6097     return NULL_TREE;
6098   if (processing_template_decl)
6099     {
6100       if (!is_nondependent_constant_expression (expr))
6101 	expr = NULL_TREE;
6102       else
6103 	{
6104 	  processing_template_decl_sentinel s;
6105 	  expr = instantiate_non_dependent_expr_internal (expr, tf_error);
6106 	}
6107     }
6108   return expr;
6109 }
6110 
6111 /* True iff T is a specialization of a variable template.  */
6112 
6113 bool
variable_template_specialization_p(tree t)6114 variable_template_specialization_p (tree t)
6115 {
6116   if (!VAR_P (t) || !DECL_LANG_SPECIFIC (t) || !DECL_TEMPLATE_INFO (t))
6117     return false;
6118   tree tmpl = DECL_TI_TEMPLATE (t);
6119   return variable_template_p (tmpl);
6120 }
6121 
6122 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
6123    template declaration, or a TYPE_DECL for an alias declaration.  */
6124 
6125 bool
alias_type_or_template_p(tree t)6126 alias_type_or_template_p (tree t)
6127 {
6128   if (t == NULL_TREE)
6129     return false;
6130   return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
6131 	  || (TYPE_P (t)
6132 	      && TYPE_NAME (t)
6133 	      && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
6134 	  || DECL_ALIAS_TEMPLATE_P (t));
6135 }
6136 
6137 /* Return TRUE iff T is a specialization of an alias template.  */
6138 
6139 bool
alias_template_specialization_p(const_tree t)6140 alias_template_specialization_p (const_tree t)
6141 {
6142   /* It's an alias template specialization if it's an alias and its
6143      TYPE_NAME is a specialization of a primary template.  */
6144   if (TYPE_ALIAS_P (t))
6145     if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
6146       return PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo));
6147 
6148   return false;
6149 }
6150 
6151 /* An alias template is complex from a SFINAE perspective if a template-id
6152    using that alias can be ill-formed when the expansion is not, as with
6153    the void_t template.  We determine this by checking whether the
6154    expansion for the alias template uses all its template parameters.  */
6155 
6156 struct uses_all_template_parms_data
6157 {
6158   int level;
6159   bool *seen;
6160 };
6161 
6162 static int
uses_all_template_parms_r(tree t,void * data_)6163 uses_all_template_parms_r (tree t, void *data_)
6164 {
6165   struct uses_all_template_parms_data &data
6166     = *(struct uses_all_template_parms_data*)data_;
6167   tree idx = get_template_parm_index (t);
6168 
6169   if (TEMPLATE_PARM_LEVEL (idx) == data.level)
6170     data.seen[TEMPLATE_PARM_IDX (idx)] = true;
6171   return 0;
6172 }
6173 
6174 static bool
complex_alias_template_p(const_tree tmpl)6175 complex_alias_template_p (const_tree tmpl)
6176 {
6177   struct uses_all_template_parms_data data;
6178   tree pat = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6179   tree parms = DECL_TEMPLATE_PARMS (tmpl);
6180   data.level = TMPL_PARMS_DEPTH (parms);
6181   int len = TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS (parms));
6182   data.seen = XALLOCAVEC (bool, len);
6183   for (int i = 0; i < len; ++i)
6184     data.seen[i] = false;
6185 
6186   for_each_template_parm (pat, uses_all_template_parms_r, &data, NULL, true);
6187   for (int i = 0; i < len; ++i)
6188     if (!data.seen[i])
6189       return true;
6190   return false;
6191 }
6192 
6193 /* Return TRUE iff T is a specialization of a complex alias template with
6194    dependent template-arguments.  */
6195 
6196 bool
dependent_alias_template_spec_p(const_tree t)6197 dependent_alias_template_spec_p (const_tree t)
6198 {
6199   if (!alias_template_specialization_p (t))
6200     return false;
6201 
6202   tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t);
6203   if (!TEMPLATE_DECL_COMPLEX_ALIAS_P (TI_TEMPLATE (tinfo)))
6204     return false;
6205 
6206   tree args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo));
6207   if (!any_dependent_template_arguments_p (args))
6208     return false;
6209 
6210   return true;
6211 }
6212 
6213 /* Return the number of innermost template parameters in TMPL.  */
6214 
6215 static int
num_innermost_template_parms(tree tmpl)6216 num_innermost_template_parms (tree tmpl)
6217 {
6218   tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6219   return TREE_VEC_LENGTH (parms);
6220 }
6221 
6222 /* Return either TMPL or another template that it is equivalent to under DR
6223    1286: An alias that just changes the name of a template is equivalent to
6224    the other template.  */
6225 
6226 static tree
get_underlying_template(tree tmpl)6227 get_underlying_template (tree tmpl)
6228 {
6229   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
6230   while (DECL_ALIAS_TEMPLATE_P (tmpl))
6231     {
6232       /* Determine if the alias is equivalent to an underlying template.  */
6233       tree orig_type = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6234       tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (orig_type);
6235       if (!tinfo)
6236 	break;
6237 
6238       tree underlying = TI_TEMPLATE (tinfo);
6239       if (!PRIMARY_TEMPLATE_P (underlying)
6240 	  || (num_innermost_template_parms (tmpl)
6241 	      != num_innermost_template_parms (underlying)))
6242 	break;
6243 
6244       tree alias_args = INNERMOST_TEMPLATE_ARGS
6245 	(template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl)));
6246       if (!comp_template_args (TI_ARGS (tinfo), alias_args))
6247 	break;
6248 
6249       /* Alias is equivalent.  Strip it and repeat.  */
6250       tmpl = underlying;
6251     }
6252 
6253   return tmpl;
6254 }
6255 
6256 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
6257    must be a reference-to-function or a pointer-to-function type, as specified
6258    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
6259    and check that the resulting function has external linkage.  */
6260 
6261 static tree
convert_nontype_argument_function(tree type,tree expr,tsubst_flags_t complain)6262 convert_nontype_argument_function (tree type, tree expr,
6263 				   tsubst_flags_t complain)
6264 {
6265   tree fns = expr;
6266   tree fn, fn_no_ptr;
6267   linkage_kind linkage;
6268 
6269   fn = instantiate_type (type, fns, tf_none);
6270   if (fn == error_mark_node)
6271     return error_mark_node;
6272 
6273   if (value_dependent_expression_p (fn))
6274     goto accept;
6275 
6276   fn_no_ptr = strip_fnptr_conv (fn);
6277   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
6278     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6279   if (BASELINK_P (fn_no_ptr))
6280     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
6281 
6282   /* [temp.arg.nontype]/1
6283 
6284      A template-argument for a non-type, non-template template-parameter
6285      shall be one of:
6286      [...]
6287      -- the address of an object or function with external [C++11: or
6288         internal] linkage.  */
6289 
6290   if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
6291     {
6292       if (complain & tf_error)
6293 	{
6294 	  error ("%qE is not a valid template argument for type %qT",
6295 		 expr, type);
6296 	  if (TYPE_PTR_P (type))
6297 	    inform (input_location, "it must be the address of a function "
6298 		    "with external linkage");
6299 	  else
6300 	    inform (input_location, "it must be the name of a function with "
6301 		    "external linkage");
6302 	}
6303       return NULL_TREE;
6304     }
6305 
6306   linkage = decl_linkage (fn_no_ptr);
6307   if (cxx_dialect >= cxx11 ? linkage == lk_none : linkage != lk_external)
6308     {
6309       if (complain & tf_error)
6310 	{
6311 	  if (cxx_dialect >= cxx11)
6312 	    error ("%qE is not a valid template argument for type %qT "
6313 		   "because %qD has no linkage",
6314 		   expr, type, fn_no_ptr);
6315 	  else
6316 	    error ("%qE is not a valid template argument for type %qT "
6317 		   "because %qD does not have external linkage",
6318 		   expr, type, fn_no_ptr);
6319 	}
6320       return NULL_TREE;
6321     }
6322 
6323  accept:
6324   if (TREE_CODE (type) == REFERENCE_TYPE)
6325     {
6326       if (REFERENCE_REF_P (fn))
6327 	fn = TREE_OPERAND (fn, 0);
6328       else
6329 	fn = build_address (fn);
6330     }
6331   if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (fn)))
6332     fn = build_nop (type, fn);
6333 
6334   return fn;
6335 }
6336 
6337 /* Subroutine of convert_nontype_argument.
6338    Check if EXPR of type TYPE is a valid pointer-to-member constant.
6339    Emit an error otherwise.  */
6340 
6341 static bool
check_valid_ptrmem_cst_expr(tree type,tree expr,tsubst_flags_t complain)6342 check_valid_ptrmem_cst_expr (tree type, tree expr,
6343 			     tsubst_flags_t complain)
6344 {
6345   location_t loc = EXPR_LOC_OR_LOC (expr, input_location);
6346   tree orig_expr = expr;
6347   STRIP_NOPS (expr);
6348   if (null_ptr_cst_p (expr))
6349     return true;
6350   if (TREE_CODE (expr) == PTRMEM_CST
6351       && same_type_p (TYPE_PTRMEM_CLASS_TYPE (type),
6352 		      PTRMEM_CST_CLASS (expr)))
6353     return true;
6354   if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
6355     return true;
6356   if (processing_template_decl
6357       && TREE_CODE (expr) == ADDR_EXPR
6358       && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
6359     return true;
6360   if (complain & tf_error)
6361     {
6362       error_at (loc, "%qE is not a valid template argument for type %qT",
6363 		orig_expr, type);
6364       if (TREE_CODE (expr) != PTRMEM_CST)
6365 	inform (loc, "it must be a pointer-to-member of the form %<&X::Y%>");
6366       else
6367 	inform (loc, "because it is a member of %qT", PTRMEM_CST_CLASS (expr));
6368     }
6369   return false;
6370 }
6371 
6372 /* Returns TRUE iff the address of OP is value-dependent.
6373 
6374    14.6.2.4 [temp.dep.temp]:
6375    A non-integral non-type template-argument is dependent if its type is
6376    dependent or it has either of the following forms
6377      qualified-id
6378      & qualified-id
6379    and contains a nested-name-specifier which specifies a class-name that
6380    names a dependent type.
6381 
6382    We generalize this to just say that the address of a member of a
6383    dependent class is value-dependent; the above doesn't cover the
6384    address of a static data member named with an unqualified-id.  */
6385 
6386 static bool
has_value_dependent_address(tree op)6387 has_value_dependent_address (tree op)
6388 {
6389   /* We could use get_inner_reference here, but there's no need;
6390      this is only relevant for template non-type arguments, which
6391      can only be expressed as &id-expression.  */
6392   if (DECL_P (op))
6393     {
6394       tree ctx = CP_DECL_CONTEXT (op);
6395       if (TYPE_P (ctx) && dependent_type_p (ctx))
6396 	return true;
6397     }
6398 
6399   return false;
6400 }
6401 
6402 /* The next set of functions are used for providing helpful explanatory
6403    diagnostics for failed overload resolution.  Their messages should be
6404    indented by two spaces for consistency with the messages in
6405    call.c  */
6406 
6407 static int
unify_success(bool)6408 unify_success (bool /*explain_p*/)
6409 {
6410   return 0;
6411 }
6412 
6413 /* Other failure functions should call this one, to provide a single function
6414    for setting a breakpoint on.  */
6415 
6416 static int
unify_invalid(bool)6417 unify_invalid (bool /*explain_p*/)
6418 {
6419   return 1;
6420 }
6421 
6422 static int
unify_parameter_deduction_failure(bool explain_p,tree parm)6423 unify_parameter_deduction_failure (bool explain_p, tree parm)
6424 {
6425   if (explain_p)
6426     inform (input_location,
6427 	    "  couldn't deduce template parameter %qD", parm);
6428   return unify_invalid (explain_p);
6429 }
6430 
6431 static int
unify_cv_qual_mismatch(bool explain_p,tree parm,tree arg)6432 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
6433 {
6434   if (explain_p)
6435     inform (input_location,
6436 	    "  types %qT and %qT have incompatible cv-qualifiers",
6437 	    parm, arg);
6438   return unify_invalid (explain_p);
6439 }
6440 
6441 static int
unify_type_mismatch(bool explain_p,tree parm,tree arg)6442 unify_type_mismatch (bool explain_p, tree parm, tree arg)
6443 {
6444   if (explain_p)
6445     inform (input_location, "  mismatched types %qT and %qT", parm, arg);
6446   return unify_invalid (explain_p);
6447 }
6448 
6449 static int
unify_parameter_pack_mismatch(bool explain_p,tree parm,tree arg)6450 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
6451 {
6452   if (explain_p)
6453     inform (input_location,
6454 	    "  template parameter %qD is not a parameter pack, but "
6455 	    "argument %qD is",
6456 	    parm, arg);
6457   return unify_invalid (explain_p);
6458 }
6459 
6460 static int
unify_ptrmem_cst_mismatch(bool explain_p,tree parm,tree arg)6461 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
6462 {
6463   if (explain_p)
6464     inform (input_location,
6465 	    "  template argument %qE does not match "
6466 	    "pointer-to-member constant %qE",
6467 	    arg, parm);
6468   return unify_invalid (explain_p);
6469 }
6470 
6471 static int
unify_expression_unequal(bool explain_p,tree parm,tree arg)6472 unify_expression_unequal (bool explain_p, tree parm, tree arg)
6473 {
6474   if (explain_p)
6475     inform (input_location, "  %qE is not equivalent to %qE", parm, arg);
6476   return unify_invalid (explain_p);
6477 }
6478 
6479 static int
unify_parameter_pack_inconsistent(bool explain_p,tree old_arg,tree new_arg)6480 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
6481 {
6482   if (explain_p)
6483     inform (input_location,
6484 	    "  inconsistent parameter pack deduction with %qT and %qT",
6485 	    old_arg, new_arg);
6486   return unify_invalid (explain_p);
6487 }
6488 
6489 static int
unify_inconsistency(bool explain_p,tree parm,tree first,tree second)6490 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
6491 {
6492   if (explain_p)
6493     {
6494       if (TYPE_P (parm))
6495 	inform (input_location,
6496 		"  deduced conflicting types for parameter %qT (%qT and %qT)",
6497 		parm, first, second);
6498       else
6499 	inform (input_location,
6500 		"  deduced conflicting values for non-type parameter "
6501 		"%qE (%qE and %qE)", parm, first, second);
6502     }
6503   return unify_invalid (explain_p);
6504 }
6505 
6506 static int
unify_vla_arg(bool explain_p,tree arg)6507 unify_vla_arg (bool explain_p, tree arg)
6508 {
6509   if (explain_p)
6510     inform (input_location,
6511 	    "  variable-sized array type %qT is not "
6512 	    "a valid template argument",
6513 	    arg);
6514   return unify_invalid (explain_p);
6515 }
6516 
6517 static int
unify_method_type_error(bool explain_p,tree arg)6518 unify_method_type_error (bool explain_p, tree arg)
6519 {
6520   if (explain_p)
6521     inform (input_location,
6522 	    "  member function type %qT is not a valid template argument",
6523 	    arg);
6524   return unify_invalid (explain_p);
6525 }
6526 
6527 static int
6528 unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
6529 {
6530   if (explain_p)
6531     {
6532       if (least_p)
6533 	inform_n (input_location, wanted,
6534 		  "  candidate expects at least %d argument, %d provided",
6535 		  "  candidate expects at least %d arguments, %d provided",
6536 		  wanted, have);
6537       else
6538 	inform_n (input_location, wanted,
6539 		  "  candidate expects %d argument, %d provided",
6540 		  "  candidate expects %d arguments, %d provided",
6541 		  wanted, have);
6542     }
6543   return unify_invalid (explain_p);
6544 }
6545 
6546 static int
unify_too_many_arguments(bool explain_p,int have,int wanted)6547 unify_too_many_arguments (bool explain_p, int have, int wanted)
6548 {
6549   return unify_arity (explain_p, have, wanted);
6550 }
6551 
6552 static int
6553 unify_too_few_arguments (bool explain_p, int have, int wanted,
6554 			 bool least_p = false)
6555 {
6556   return unify_arity (explain_p, have, wanted, least_p);
6557 }
6558 
6559 static int
unify_arg_conversion(bool explain_p,tree to_type,tree from_type,tree arg)6560 unify_arg_conversion (bool explain_p, tree to_type,
6561 		      tree from_type, tree arg)
6562 {
6563   if (explain_p)
6564     inform (EXPR_LOC_OR_LOC (arg, input_location),
6565 	    "  cannot convert %qE (type %qT) to type %qT",
6566 	    arg, from_type, to_type);
6567   return unify_invalid (explain_p);
6568 }
6569 
6570 static int
unify_no_common_base(bool explain_p,enum template_base_result r,tree parm,tree arg)6571 unify_no_common_base (bool explain_p, enum template_base_result r,
6572 		      tree parm, tree arg)
6573 {
6574   if (explain_p)
6575     switch (r)
6576       {
6577       case tbr_ambiguous_baseclass:
6578 	inform (input_location, "  %qT is an ambiguous base class of %qT",
6579 		parm, arg);
6580 	break;
6581       default:
6582 	inform (input_location, "  %qT is not derived from %qT", arg, parm);
6583 	break;
6584       }
6585   return unify_invalid (explain_p);
6586 }
6587 
6588 static int
unify_inconsistent_template_template_parameters(bool explain_p)6589 unify_inconsistent_template_template_parameters (bool explain_p)
6590 {
6591   if (explain_p)
6592     inform (input_location,
6593 	    "  template parameters of a template template argument are "
6594 	    "inconsistent with other deduced template arguments");
6595   return unify_invalid (explain_p);
6596 }
6597 
6598 static int
unify_template_deduction_failure(bool explain_p,tree parm,tree arg)6599 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
6600 {
6601   if (explain_p)
6602     inform (input_location,
6603 	    "  can't deduce a template for %qT from non-template type %qT",
6604 	    parm, arg);
6605   return unify_invalid (explain_p);
6606 }
6607 
6608 static int
unify_template_argument_mismatch(bool explain_p,tree parm,tree arg)6609 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
6610 {
6611   if (explain_p)
6612     inform (input_location,
6613 	    "  template argument %qE does not match %qE", arg, parm);
6614   return unify_invalid (explain_p);
6615 }
6616 
6617 /* Attempt to convert the non-type template parameter EXPR to the
6618    indicated TYPE.  If the conversion is successful, return the
6619    converted value.  If the conversion is unsuccessful, return
6620    NULL_TREE if we issued an error message, or error_mark_node if we
6621    did not.  We issue error messages for out-and-out bad template
6622    parameters, but not simply because the conversion failed, since we
6623    might be just trying to do argument deduction.  Both TYPE and EXPR
6624    must be non-dependent.
6625 
6626    The conversion follows the special rules described in
6627    [temp.arg.nontype], and it is much more strict than an implicit
6628    conversion.
6629 
6630    This function is called twice for each template argument (see
6631    lookup_template_class for a more accurate description of this
6632    problem). This means that we need to handle expressions which
6633    are not valid in a C++ source, but can be created from the
6634    first call (for instance, casts to perform conversions). These
6635    hacks can go away after we fix the double coercion problem.  */
6636 
6637 static tree
convert_nontype_argument(tree type,tree expr,tsubst_flags_t complain)6638 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
6639 {
6640   tree expr_type;
6641   location_t loc = EXPR_LOC_OR_LOC (expr, input_location);
6642   tree orig_expr = expr;
6643 
6644   /* Detect immediately string literals as invalid non-type argument.
6645      This special-case is not needed for correctness (we would easily
6646      catch this later), but only to provide better diagnostic for this
6647      common user mistake. As suggested by DR 100, we do not mention
6648      linkage issues in the diagnostic as this is not the point.  */
6649   /* FIXME we're making this OK.  */
6650   if (TREE_CODE (expr) == STRING_CST)
6651     {
6652       if (complain & tf_error)
6653 	error ("%qE is not a valid template argument for type %qT "
6654 	       "because string literals can never be used in this context",
6655 	       expr, type);
6656       return NULL_TREE;
6657     }
6658 
6659   /* Add the ADDR_EXPR now for the benefit of
6660      value_dependent_expression_p.  */
6661   if (TYPE_PTROBV_P (type)
6662       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
6663     {
6664       expr = decay_conversion (expr, complain);
6665       if (expr == error_mark_node)
6666 	return error_mark_node;
6667     }
6668 
6669   /* If we are in a template, EXPR may be non-dependent, but still
6670      have a syntactic, rather than semantic, form.  For example, EXPR
6671      might be a SCOPE_REF, rather than the VAR_DECL to which the
6672      SCOPE_REF refers.  Preserving the qualifying scope is necessary
6673      so that access checking can be performed when the template is
6674      instantiated -- but here we need the resolved form so that we can
6675      convert the argument.  */
6676   bool non_dep = false;
6677   if (TYPE_REF_OBJ_P (type)
6678       && has_value_dependent_address (expr))
6679     /* If we want the address and it's value-dependent, don't fold.  */;
6680   else if (processing_template_decl
6681 	   && is_nondependent_constant_expression (expr))
6682     non_dep = true;
6683   if (error_operand_p (expr))
6684     return error_mark_node;
6685   expr_type = TREE_TYPE (expr);
6686 
6687   /* If the argument is non-dependent, perform any conversions in
6688      non-dependent context as well.  */
6689   processing_template_decl_sentinel s (non_dep);
6690   if (non_dep)
6691     expr = instantiate_non_dependent_expr_internal (expr, complain);
6692 
6693   if (value_dependent_expression_p (expr))
6694     expr = canonicalize_expr_argument (expr, complain);
6695 
6696   /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
6697      to a non-type argument of "nullptr".  */
6698   if (NULLPTR_TYPE_P (expr_type) && TYPE_PTR_OR_PTRMEM_P (type))
6699     expr = fold_simple (convert (type, expr));
6700 
6701   /* In C++11, integral or enumeration non-type template arguments can be
6702      arbitrary constant expressions.  Pointer and pointer to
6703      member arguments can be general constant expressions that evaluate
6704      to a null value, but otherwise still need to be of a specific form.  */
6705   if (cxx_dialect >= cxx11)
6706     {
6707       if (TREE_CODE (expr) == PTRMEM_CST)
6708 	/* A PTRMEM_CST is already constant, and a valid template
6709 	   argument for a parameter of pointer to member type, we just want
6710 	   to leave it in that form rather than lower it to a
6711 	   CONSTRUCTOR.  */;
6712       else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
6713 	       || cxx_dialect >= cxx17)
6714 	{
6715 	  /* C++17: A template-argument for a non-type template-parameter shall
6716 	     be a converted constant expression (8.20) of the type of the
6717 	     template-parameter.  */
6718 	  expr = build_converted_constant_expr (type, expr, complain);
6719 	  if (expr == error_mark_node)
6720 	    return error_mark_node;
6721 	  expr = maybe_constant_value (expr);
6722 	  expr = convert_from_reference (expr);
6723 	}
6724       else if (TYPE_PTR_OR_PTRMEM_P (type))
6725 	{
6726 	  tree folded = maybe_constant_value (expr);
6727 	  if (TYPE_PTR_P (type) ? integer_zerop (folded)
6728 	      : null_member_pointer_value_p (folded))
6729 	    expr = folded;
6730 	}
6731     }
6732 
6733   if (TREE_CODE (type) == REFERENCE_TYPE)
6734     expr = mark_lvalue_use (expr);
6735   else
6736     expr = mark_rvalue_use (expr);
6737 
6738   /* HACK: Due to double coercion, we can get a
6739      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
6740      which is the tree that we built on the first call (see
6741      below when coercing to reference to object or to reference to
6742      function). We just strip everything and get to the arg.
6743      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
6744      for examples.  */
6745   if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
6746     {
6747       tree probe_type, probe = expr;
6748       if (REFERENCE_REF_P (probe))
6749 	probe = TREE_OPERAND (probe, 0);
6750       probe_type = TREE_TYPE (probe);
6751       if (TREE_CODE (probe) == NOP_EXPR)
6752 	{
6753 	  /* ??? Maybe we could use convert_from_reference here, but we
6754 	     would need to relax its constraints because the NOP_EXPR
6755 	     could actually change the type to something more cv-qualified,
6756 	     and this is not folded by convert_from_reference.  */
6757 	  tree addr = TREE_OPERAND (probe, 0);
6758 	  if (TREE_CODE (probe_type) == REFERENCE_TYPE
6759 	      && TREE_CODE (addr) == ADDR_EXPR
6760 	      && TYPE_PTR_P (TREE_TYPE (addr))
6761 	      && (same_type_ignoring_top_level_qualifiers_p
6762 		  (TREE_TYPE (probe_type),
6763 		   TREE_TYPE (TREE_TYPE (addr)))))
6764 	    {
6765 	      expr = TREE_OPERAND (addr, 0);
6766 	      expr_type = TREE_TYPE (probe_type);
6767 	    }
6768 	}
6769     }
6770 
6771   /* [temp.arg.nontype]/5, bullet 1
6772 
6773      For a non-type template-parameter of integral or enumeration type,
6774      integral promotions (_conv.prom_) and integral conversions
6775      (_conv.integral_) are applied.  */
6776   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
6777     {
6778       if (cxx_dialect < cxx11)
6779 	{
6780 	  tree t = build_converted_constant_expr (type, expr, complain);
6781 	  t = maybe_constant_value (t);
6782 	  if (t != error_mark_node)
6783 	    expr = t;
6784 	}
6785 
6786       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
6787 	return error_mark_node;
6788 
6789       /* Notice that there are constant expressions like '4 % 0' which
6790 	 do not fold into integer constants.  */
6791       if (TREE_CODE (expr) != INTEGER_CST
6792 	  && !value_dependent_expression_p (expr))
6793 	{
6794 	  if (complain & tf_error)
6795 	    {
6796 	      int errs = errorcount, warns = warningcount + werrorcount;
6797 	      if (!require_potential_constant_expression (expr))
6798 		expr = error_mark_node;
6799 	      else
6800 		expr = cxx_constant_value (expr);
6801 	      if (errorcount > errs || warningcount + werrorcount > warns)
6802 		inform (loc, "in template argument for type %qT", type);
6803 	      if (expr == error_mark_node)
6804 		return NULL_TREE;
6805 	      /* else cxx_constant_value complained but gave us
6806 		 a real constant, so go ahead.  */
6807 	      if (TREE_CODE (expr) != INTEGER_CST)
6808 		{
6809 		  /* Some assemble time constant expressions like
6810 		     (intptr_t)&&lab1 - (intptr_t)&&lab2 or
6811 		     4 + (intptr_t)&&var satisfy reduced_constant_expression_p
6812 		     as we can emit them into .rodata initializers of
6813 		     variables, yet they can't fold into an INTEGER_CST at
6814 		     compile time.  Refuse them here.  */
6815 		  gcc_checking_assert (reduced_constant_expression_p (expr));
6816 		  error_at (loc, "template argument %qE for type %qT not "
6817 				 "a constant integer", expr, type);
6818 		  return NULL_TREE;
6819 		}
6820 	    }
6821 	  else
6822 	    return NULL_TREE;
6823 	}
6824 
6825       /* Avoid typedef problems.  */
6826       if (TREE_TYPE (expr) != type)
6827 	expr = fold_convert (type, expr);
6828     }
6829   /* [temp.arg.nontype]/5, bullet 2
6830 
6831      For a non-type template-parameter of type pointer to object,
6832      qualification conversions (_conv.qual_) and the array-to-pointer
6833      conversion (_conv.array_) are applied.  */
6834   else if (TYPE_PTROBV_P (type))
6835     {
6836       tree decayed = expr;
6837 
6838       /* Look through any NOP_EXPRs around an ADDR_EXPR, whether they come from
6839 	 decay_conversion or an explicit cast.  If it's a problematic cast,
6840 	 we'll complain about it below.  */
6841       if (TREE_CODE (expr) == NOP_EXPR)
6842 	{
6843 	  tree probe = expr;
6844 	  STRIP_NOPS (probe);
6845 	  if (TREE_CODE (probe) == ADDR_EXPR
6846 	      && TYPE_PTR_P (TREE_TYPE (probe)))
6847 	    {
6848 	      expr = probe;
6849 	      expr_type = TREE_TYPE (expr);
6850 	    }
6851 	}
6852 
6853       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
6854 
6855 	 A template-argument for a non-type, non-template template-parameter
6856 	 shall be one of: [...]
6857 
6858 	 -- the name of a non-type template-parameter;
6859 	 -- the address of an object or function with external linkage, [...]
6860 	    expressed as "& id-expression" where the & is optional if the name
6861 	    refers to a function or array, or if the corresponding
6862 	    template-parameter is a reference.
6863 
6864 	Here, we do not care about functions, as they are invalid anyway
6865 	for a parameter of type pointer-to-object.  */
6866 
6867       if (value_dependent_expression_p (expr))
6868 	/* Non-type template parameters are OK.  */
6869 	;
6870       else if (cxx_dialect >= cxx11 && integer_zerop (expr))
6871 	/* Null pointer values are OK in C++11.  */;
6872       else if (TREE_CODE (expr) != ADDR_EXPR)
6873 	{
6874 	  if (VAR_P (expr))
6875 	    {
6876 	      if (complain & tf_error)
6877 		error ("%qD is not a valid template argument "
6878 		       "because %qD is a variable, not the address of "
6879 		       "a variable", orig_expr, expr);
6880 	      return NULL_TREE;
6881 	    }
6882 	  if (POINTER_TYPE_P (expr_type))
6883 	    {
6884 	      if (complain & tf_error)
6885 		error ("%qE is not a valid template argument for %qT "
6886 		       "because it is not the address of a variable",
6887 		       orig_expr, type);
6888 	      return NULL_TREE;
6889 	    }
6890 	  /* Other values, like integer constants, might be valid
6891 	     non-type arguments of some other type.  */
6892 	  return error_mark_node;
6893 	}
6894       else
6895 	{
6896 	  tree decl = TREE_OPERAND (expr, 0);
6897 
6898 	  if (!VAR_P (decl))
6899 	    {
6900 	      if (complain & tf_error)
6901 		error ("%qE is not a valid template argument of type %qT "
6902 		       "because %qE is not a variable", orig_expr, type, decl);
6903 	      return NULL_TREE;
6904 	    }
6905 	  else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
6906 	    {
6907 	      if (complain & tf_error)
6908 		error ("%qE is not a valid template argument of type %qT "
6909 		       "because %qD does not have external linkage",
6910 		       orig_expr, type, decl);
6911 	      return NULL_TREE;
6912 	    }
6913 	  else if ((cxx_dialect >= cxx11 && cxx_dialect < cxx17)
6914 		   && decl_linkage (decl) == lk_none)
6915 	    {
6916 	      if (complain & tf_error)
6917 		error ("%qE is not a valid template argument of type %qT "
6918 		       "because %qD has no linkage", orig_expr, type, decl);
6919 	      return NULL_TREE;
6920 	    }
6921 	  /* C++17: For a non-type template-parameter of reference or pointer
6922 	     type, the value of the constant expression shall not refer to (or
6923 	     for a pointer type, shall not be the address of):
6924 	       * a subobject (4.5),
6925 	       * a temporary object (15.2),
6926 	       * a string literal (5.13.5),
6927 	       * the result of a typeid expression (8.2.8), or
6928 	       * a predefined __func__ variable (11.4.1).  */
6929 	  else if (DECL_ARTIFICIAL (decl))
6930 	    {
6931 	      if (complain & tf_error)
6932 		error ("the address of %qD is not a valid template argument",
6933 		       decl);
6934 	      return NULL_TREE;
6935 	    }
6936 	  else if (!same_type_ignoring_top_level_qualifiers_p
6937 		   (strip_array_types (TREE_TYPE (type)),
6938 		    strip_array_types (TREE_TYPE (decl))))
6939 	    {
6940 	      if (complain & tf_error)
6941 		error ("the address of the %qT subobject of %qD is not a "
6942 		       "valid template argument", TREE_TYPE (type), decl);
6943 	      return NULL_TREE;
6944 	    }
6945 	  else if (!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
6946 	    {
6947 	      if (complain & tf_error)
6948 		error ("the address of %qD is not a valid template argument "
6949 		       "because it does not have static storage duration",
6950 		       decl);
6951 	      return NULL_TREE;
6952 	    }
6953 	}
6954 
6955       expr = decayed;
6956 
6957       expr = perform_qualification_conversions (type, expr);
6958       if (expr == error_mark_node)
6959 	return error_mark_node;
6960     }
6961   /* [temp.arg.nontype]/5, bullet 3
6962 
6963      For a non-type template-parameter of type reference to object, no
6964      conversions apply. The type referred to by the reference may be more
6965      cv-qualified than the (otherwise identical) type of the
6966      template-argument. The template-parameter is bound directly to the
6967      template-argument, which must be an lvalue.  */
6968   else if (TYPE_REF_OBJ_P (type))
6969     {
6970       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
6971 						      expr_type))
6972 	return error_mark_node;
6973 
6974       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
6975 	{
6976 	  if (complain & tf_error)
6977 	    error ("%qE is not a valid template argument for type %qT "
6978 		   "because of conflicts in cv-qualification", expr, type);
6979 	  return NULL_TREE;
6980 	}
6981 
6982       if (!lvalue_p (expr))
6983 	{
6984 	  if (complain & tf_error)
6985 	    error ("%qE is not a valid template argument for type %qT "
6986 		   "because it is not an lvalue", expr, type);
6987 	  return NULL_TREE;
6988 	}
6989 
6990       /* [temp.arg.nontype]/1
6991 
6992 	 A template-argument for a non-type, non-template template-parameter
6993 	 shall be one of: [...]
6994 
6995 	 -- the address of an object or function with external linkage.  */
6996       if (INDIRECT_REF_P (expr)
6997 	  && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
6998 	{
6999 	  expr = TREE_OPERAND (expr, 0);
7000 	  if (DECL_P (expr))
7001 	    {
7002 	      if (complain & tf_error)
7003 		error ("%q#D is not a valid template argument for type %qT "
7004 		       "because a reference variable does not have a constant "
7005 		       "address", expr, type);
7006 	      return NULL_TREE;
7007 	    }
7008 	}
7009 
7010       if (TYPE_REF_OBJ_P (TREE_TYPE (expr))
7011 	  && value_dependent_expression_p (expr))
7012 	/* OK, dependent reference.  We don't want to ask whether a DECL is
7013 	   itself value-dependent, since what we want here is its address.  */;
7014       else
7015 	{
7016 	  if (!DECL_P (expr))
7017 	    {
7018 	      if (complain & tf_error)
7019 		error ("%qE is not a valid template argument for type %qT "
7020 		       "because it is not an object with linkage",
7021 		       expr, type);
7022 	      return NULL_TREE;
7023 	    }
7024 
7025 	  /* DR 1155 allows internal linkage in C++11 and up.  */
7026 	  linkage_kind linkage = decl_linkage (expr);
7027 	  if (linkage < (cxx_dialect >= cxx11 ? lk_internal : lk_external))
7028 	    {
7029 	      if (complain & tf_error)
7030 		error ("%qE is not a valid template argument for type %qT "
7031 		       "because object %qD does not have linkage",
7032 		       expr, type, expr);
7033 	      return NULL_TREE;
7034 	    }
7035 
7036 	  expr = build_address (expr);
7037 	}
7038 
7039       if (!same_type_p (type, TREE_TYPE (expr)))
7040 	expr = build_nop (type, expr);
7041     }
7042   /* [temp.arg.nontype]/5, bullet 4
7043 
7044      For a non-type template-parameter of type pointer to function, only
7045      the function-to-pointer conversion (_conv.func_) is applied. If the
7046      template-argument represents a set of overloaded functions (or a
7047      pointer to such), the matching function is selected from the set
7048      (_over.over_).  */
7049   else if (TYPE_PTRFN_P (type))
7050     {
7051       /* If the argument is a template-id, we might not have enough
7052 	 context information to decay the pointer.  */
7053       if (!type_unknown_p (expr_type))
7054 	{
7055 	  expr = decay_conversion (expr, complain);
7056 	  if (expr == error_mark_node)
7057 	    return error_mark_node;
7058 	}
7059 
7060       if (cxx_dialect >= cxx11 && integer_zerop (expr))
7061 	/* Null pointer values are OK in C++11.  */
7062 	return perform_qualification_conversions (type, expr);
7063 
7064       expr = convert_nontype_argument_function (type, expr, complain);
7065       if (!expr || expr == error_mark_node)
7066 	return expr;
7067     }
7068   /* [temp.arg.nontype]/5, bullet 5
7069 
7070      For a non-type template-parameter of type reference to function, no
7071      conversions apply. If the template-argument represents a set of
7072      overloaded functions, the matching function is selected from the set
7073      (_over.over_).  */
7074   else if (TYPE_REFFN_P (type))
7075     {
7076       if (TREE_CODE (expr) == ADDR_EXPR)
7077 	{
7078 	  if (complain & tf_error)
7079 	    {
7080 	      error ("%qE is not a valid template argument for type %qT "
7081 		     "because it is a pointer", expr, type);
7082 	      inform (input_location, "try using %qE instead",
7083 		      TREE_OPERAND (expr, 0));
7084 	    }
7085 	  return NULL_TREE;
7086 	}
7087 
7088       expr = convert_nontype_argument_function (type, expr, complain);
7089       if (!expr || expr == error_mark_node)
7090 	return expr;
7091     }
7092   /* [temp.arg.nontype]/5, bullet 6
7093 
7094      For a non-type template-parameter of type pointer to member function,
7095      no conversions apply. If the template-argument represents a set of
7096      overloaded member functions, the matching member function is selected
7097      from the set (_over.over_).  */
7098   else if (TYPE_PTRMEMFUNC_P (type))
7099     {
7100       expr = instantiate_type (type, expr, tf_none);
7101       if (expr == error_mark_node)
7102 	return error_mark_node;
7103 
7104       /* [temp.arg.nontype] bullet 1 says the pointer to member
7105          expression must be a pointer-to-member constant.  */
7106       if (!value_dependent_expression_p (expr)
7107 	  && !check_valid_ptrmem_cst_expr (type, expr, complain))
7108 	return NULL_TREE;
7109 
7110       /* Repeated conversion can't deal with a conversion that turns PTRMEM_CST
7111 	 into a CONSTRUCTOR, so build up a new PTRMEM_CST instead.  */
7112       if (fnptr_conv_p (type, TREE_TYPE (expr)))
7113 	expr = make_ptrmem_cst (type, PTRMEM_CST_MEMBER (expr));
7114     }
7115   /* [temp.arg.nontype]/5, bullet 7
7116 
7117      For a non-type template-parameter of type pointer to data member,
7118      qualification conversions (_conv.qual_) are applied.  */
7119   else if (TYPE_PTRDATAMEM_P (type))
7120     {
7121       /* [temp.arg.nontype] bullet 1 says the pointer to member
7122          expression must be a pointer-to-member constant.  */
7123       if (!value_dependent_expression_p (expr)
7124 	  && !check_valid_ptrmem_cst_expr (type, expr, complain))
7125 	return NULL_TREE;
7126 
7127       expr = perform_qualification_conversions (type, expr);
7128       if (expr == error_mark_node)
7129 	return expr;
7130     }
7131   else if (NULLPTR_TYPE_P (type))
7132     {
7133       if (!NULLPTR_TYPE_P (TREE_TYPE (expr)))
7134 	{
7135 	  if (complain & tf_error)
7136 	    error ("%qE is not a valid template argument for type %qT "
7137 		   "because it is of type %qT", expr, type, TREE_TYPE (expr));
7138 	  return NULL_TREE;
7139 	}
7140       return expr;
7141     }
7142   /* A template non-type parameter must be one of the above.  */
7143   else
7144     gcc_unreachable ();
7145 
7146   /* Sanity check: did we actually convert the argument to the
7147      right type?  */
7148   gcc_assert (same_type_ignoring_top_level_qualifiers_p
7149 	      (type, TREE_TYPE (expr)));
7150   return convert_from_reference (expr);
7151 }
7152 
7153 /* Subroutine of coerce_template_template_parms, which returns 1 if
7154    PARM_PARM and ARG_PARM match using the rule for the template
7155    parameters of template template parameters. Both PARM and ARG are
7156    template parameters; the rest of the arguments are the same as for
7157    coerce_template_template_parms.
7158  */
7159 static int
coerce_template_template_parm(tree parm,tree arg,tsubst_flags_t complain,tree in_decl,tree outer_args)7160 coerce_template_template_parm (tree parm,
7161                               tree arg,
7162                               tsubst_flags_t complain,
7163                               tree in_decl,
7164                               tree outer_args)
7165 {
7166   if (arg == NULL_TREE || error_operand_p (arg)
7167       || parm == NULL_TREE || error_operand_p (parm))
7168     return 0;
7169 
7170   if (TREE_CODE (arg) != TREE_CODE (parm))
7171     return 0;
7172 
7173   switch (TREE_CODE (parm))
7174     {
7175     case TEMPLATE_DECL:
7176       /* We encounter instantiations of templates like
7177 	 template <template <template <class> class> class TT>
7178 	 class C;  */
7179       {
7180 	tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
7181 	tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
7182 
7183 	if (!coerce_template_template_parms
7184 	    (parmparm, argparm, complain, in_decl, outer_args))
7185 	  return 0;
7186       }
7187       /* Fall through.  */
7188 
7189     case TYPE_DECL:
7190       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
7191 	  && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7192 	/* Argument is a parameter pack but parameter is not.  */
7193 	return 0;
7194       break;
7195 
7196     case PARM_DECL:
7197       /* The tsubst call is used to handle cases such as
7198 
7199            template <int> class C {};
7200 	   template <class T, template <T> class TT> class D {};
7201 	   D<int, C> d;
7202 
7203 	 i.e. the parameter list of TT depends on earlier parameters.  */
7204       if (!uses_template_parms (TREE_TYPE (arg)))
7205 	{
7206 	  tree t = tsubst (TREE_TYPE (parm), outer_args, complain, in_decl);
7207 	  if (!uses_template_parms (t)
7208 	      && !same_type_p (t, TREE_TYPE (arg)))
7209 	    return 0;
7210 	}
7211 
7212       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
7213 	  && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7214 	/* Argument is a parameter pack but parameter is not.  */
7215 	return 0;
7216 
7217       break;
7218 
7219     default:
7220       gcc_unreachable ();
7221     }
7222 
7223   return 1;
7224 }
7225 
7226 /* Coerce template argument list ARGLIST for use with template
7227    template-parameter TEMPL.  */
7228 
7229 static tree
coerce_template_args_for_ttp(tree templ,tree arglist,tsubst_flags_t complain)7230 coerce_template_args_for_ttp (tree templ, tree arglist,
7231 			      tsubst_flags_t complain)
7232 {
7233   /* Consider an example where a template template parameter declared as
7234 
7235      template <class T, class U = std::allocator<T> > class TT
7236 
7237      The template parameter level of T and U are one level larger than
7238      of TT.  To proper process the default argument of U, say when an
7239      instantiation `TT<int>' is seen, we need to build the full
7240      arguments containing {int} as the innermost level.  Outer levels,
7241      available when not appearing as default template argument, can be
7242      obtained from the arguments of the enclosing template.
7243 
7244      Suppose that TT is later substituted with std::vector.  The above
7245      instantiation is `TT<int, std::allocator<T> >' with TT at
7246      level 1, and T at level 2, while the template arguments at level 1
7247      becomes {std::vector} and the inner level 2 is {int}.  */
7248 
7249   tree outer = DECL_CONTEXT (templ);
7250   if (outer)
7251     {
7252       if (DECL_TEMPLATE_SPECIALIZATION (outer))
7253 	/* We want arguments for the partial specialization, not arguments for
7254 	   the primary template.  */
7255 	outer = template_parms_to_args (DECL_TEMPLATE_PARMS (outer));
7256       else
7257 	outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
7258     }
7259   else if (current_template_parms)
7260     {
7261       /* This is an argument of the current template, so we haven't set
7262 	 DECL_CONTEXT yet.  */
7263       tree relevant_template_parms;
7264 
7265       /* Parameter levels that are greater than the level of the given
7266 	 template template parm are irrelevant.  */
7267       relevant_template_parms = current_template_parms;
7268       while (TMPL_PARMS_DEPTH (relevant_template_parms)
7269 	     != TEMPLATE_TYPE_LEVEL (TREE_TYPE (templ)))
7270 	relevant_template_parms = TREE_CHAIN (relevant_template_parms);
7271 
7272       outer = template_parms_to_args (relevant_template_parms);
7273     }
7274 
7275   if (outer)
7276     arglist = add_to_template_args (outer, arglist);
7277 
7278   tree parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7279   return coerce_template_parms (parmlist, arglist, templ,
7280 				complain,
7281 				/*require_all_args=*/true,
7282 				/*use_default_args=*/true);
7283 }
7284 
7285 /* A cache of template template parameters with match-all default
7286    arguments.  */
7287 static GTY((deletable)) hash_map<tree,tree> *defaulted_ttp_cache;
7288 static void
store_defaulted_ttp(tree v,tree t)7289 store_defaulted_ttp (tree v, tree t)
7290 {
7291   if (!defaulted_ttp_cache)
7292     defaulted_ttp_cache = hash_map<tree,tree>::create_ggc (13);
7293   defaulted_ttp_cache->put (v, t);
7294 }
7295 static tree
lookup_defaulted_ttp(tree v)7296 lookup_defaulted_ttp (tree v)
7297 {
7298   if (defaulted_ttp_cache)
7299     if (tree *p = defaulted_ttp_cache->get (v))
7300       return *p;
7301   return NULL_TREE;
7302 }
7303 
7304 /* T is a bound template template-parameter.  Copy its arguments into default
7305    arguments of the template template-parameter's template parameters.  */
7306 
7307 static tree
add_defaults_to_ttp(tree otmpl)7308 add_defaults_to_ttp (tree otmpl)
7309 {
7310   if (tree c = lookup_defaulted_ttp (otmpl))
7311     return c;
7312 
7313   tree ntmpl = copy_node (otmpl);
7314 
7315   tree ntype = copy_node (TREE_TYPE (otmpl));
7316   TYPE_STUB_DECL (ntype) = TYPE_NAME (ntype) = ntmpl;
7317   TYPE_MAIN_VARIANT (ntype) = ntype;
7318   TYPE_POINTER_TO (ntype) = TYPE_REFERENCE_TO (ntype) = NULL_TREE;
7319   TYPE_NAME (ntype) = ntmpl;
7320   SET_TYPE_STRUCTURAL_EQUALITY (ntype);
7321 
7322   tree idx = TEMPLATE_TYPE_PARM_INDEX (ntype)
7323     = copy_node (TEMPLATE_TYPE_PARM_INDEX (ntype));
7324   TEMPLATE_PARM_DECL (idx) = ntmpl;
7325   TREE_TYPE (ntmpl) = TREE_TYPE (idx) = ntype;
7326 
7327   tree oparms = DECL_TEMPLATE_PARMS (otmpl);
7328   tree parms = DECL_TEMPLATE_PARMS (ntmpl) = copy_node (oparms);
7329   TREE_CHAIN (parms) = TREE_CHAIN (oparms);
7330   tree vec = TREE_VALUE (parms) = copy_node (TREE_VALUE (parms));
7331   for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
7332     {
7333       tree o = TREE_VEC_ELT (vec, i);
7334       if (!template_parameter_pack_p (TREE_VALUE (o)))
7335 	{
7336 	  tree n = TREE_VEC_ELT (vec, i) = copy_node (o);
7337 	  TREE_PURPOSE (n) = any_targ_node;
7338 	}
7339     }
7340 
7341   store_defaulted_ttp (otmpl, ntmpl);
7342   return ntmpl;
7343 }
7344 
7345 /* ARG is a bound potential template template-argument, and PARGS is a list
7346    of arguments for the corresponding template template-parameter.  Adjust
7347    PARGS as appropriate for application to ARG's template, and if ARG is a
7348    BOUND_TEMPLATE_TEMPLATE_PARM, possibly adjust it to add default template
7349    arguments to the template template parameter.  */
7350 
7351 static tree
coerce_ttp_args_for_tta(tree & arg,tree pargs,tsubst_flags_t complain)7352 coerce_ttp_args_for_tta (tree& arg, tree pargs, tsubst_flags_t complain)
7353 {
7354   ++processing_template_decl;
7355   tree arg_tmpl = TYPE_TI_TEMPLATE (arg);
7356   if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
7357     {
7358       /* When comparing two template template-parameters in partial ordering,
7359 	 rewrite the one currently being used as an argument to have default
7360 	 arguments for all parameters.  */
7361       arg_tmpl = add_defaults_to_ttp (arg_tmpl);
7362       pargs = coerce_template_args_for_ttp (arg_tmpl, pargs, complain);
7363       if (pargs != error_mark_node)
7364 	arg = bind_template_template_parm (TREE_TYPE (arg_tmpl),
7365 					   TYPE_TI_ARGS (arg));
7366     }
7367   else
7368     {
7369       tree aparms
7370 	= INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (arg_tmpl));
7371       pargs = coerce_template_parms (aparms, pargs, arg_tmpl, complain,
7372 				       /*require_all*/true,
7373 				       /*use_default*/true);
7374     }
7375   --processing_template_decl;
7376   return pargs;
7377 }
7378 
7379 /* Subroutine of unify for the case when PARM is a
7380    BOUND_TEMPLATE_TEMPLATE_PARM.  */
7381 
7382 static int
unify_bound_ttp_args(tree tparms,tree targs,tree parm,tree & arg,bool explain_p)7383 unify_bound_ttp_args (tree tparms, tree targs, tree parm, tree& arg,
7384 		      bool explain_p)
7385 {
7386   tree parmvec = TYPE_TI_ARGS (parm);
7387   tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
7388 
7389   /* The template template parm might be variadic and the argument
7390      not, so flatten both argument lists.  */
7391   parmvec = expand_template_argument_pack (parmvec);
7392   argvec = expand_template_argument_pack (argvec);
7393 
7394   if (flag_new_ttp)
7395     {
7396       /* In keeping with P0522R0, adjust P's template arguments
7397 	 to apply to A's template; then flatten it again.  */
7398       tree nparmvec = parmvec;
7399       nparmvec = coerce_ttp_args_for_tta (arg, parmvec, tf_none);
7400       nparmvec = expand_template_argument_pack (nparmvec);
7401 
7402       if (unify (tparms, targs, nparmvec, argvec,
7403 		 UNIFY_ALLOW_NONE, explain_p))
7404 	return 1;
7405 
7406       /* If the P0522 adjustment eliminated a pack expansion, deduce
7407 	 empty packs.  */
7408       if (flag_new_ttp
7409 	  && TREE_VEC_LENGTH (nparmvec) < TREE_VEC_LENGTH (parmvec)
7410 	  && unify_pack_expansion (tparms, targs, parmvec, argvec,
7411 				   DEDUCE_EXACT, /*sub*/true, explain_p))
7412 	return 1;
7413     }
7414   else
7415     {
7416       /* Deduce arguments T, i from TT<T> or TT<i>.
7417 	 We check each element of PARMVEC and ARGVEC individually
7418 	 rather than the whole TREE_VEC since they can have
7419 	 different number of elements, which is allowed under N2555.  */
7420 
7421       int len = TREE_VEC_LENGTH (parmvec);
7422 
7423       /* Check if the parameters end in a pack, making them
7424 	 variadic.  */
7425       int parm_variadic_p = 0;
7426       if (len > 0
7427 	  && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
7428 	parm_variadic_p = 1;
7429 
7430       for (int i = 0; i < len - parm_variadic_p; ++i)
7431 	/* If the template argument list of P contains a pack
7432 	   expansion that is not the last template argument, the
7433 	   entire template argument list is a non-deduced
7434 	   context.  */
7435 	if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
7436 	  return unify_success (explain_p);
7437 
7438       if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
7439 	return unify_too_few_arguments (explain_p,
7440 					TREE_VEC_LENGTH (argvec), len);
7441 
7442       for (int i = 0; i < len - parm_variadic_p; ++i)
7443 	if (unify (tparms, targs,
7444 		   TREE_VEC_ELT (parmvec, i),
7445 		   TREE_VEC_ELT (argvec, i),
7446 		   UNIFY_ALLOW_NONE, explain_p))
7447 	  return 1;
7448 
7449       if (parm_variadic_p
7450 	  && unify_pack_expansion (tparms, targs,
7451 				   parmvec, argvec,
7452 				   DEDUCE_EXACT,
7453 				   /*subr=*/true, explain_p))
7454 	return 1;
7455     }
7456 
7457   return 0;
7458 }
7459 
7460 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
7461    template template parameters.  Both PARM_PARMS and ARG_PARMS are
7462    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
7463    or PARM_DECL.
7464 
7465    Consider the example:
7466      template <class T> class A;
7467      template<template <class U> class TT> class B;
7468 
7469    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
7470    the parameters to A, and OUTER_ARGS contains A.  */
7471 
7472 static int
coerce_template_template_parms(tree parm_parms,tree arg_parms,tsubst_flags_t complain,tree in_decl,tree outer_args)7473 coerce_template_template_parms (tree parm_parms,
7474 				tree arg_parms,
7475 				tsubst_flags_t complain,
7476 				tree in_decl,
7477 				tree outer_args)
7478 {
7479   int nparms, nargs, i;
7480   tree parm, arg;
7481   int variadic_p = 0;
7482 
7483   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
7484   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
7485 
7486   nparms = TREE_VEC_LENGTH (parm_parms);
7487   nargs = TREE_VEC_LENGTH (arg_parms);
7488 
7489   if (flag_new_ttp)
7490     {
7491       /* P0522R0: A template template-parameter P is at least as specialized as
7492 	 a template template-argument A if, given the following rewrite to two
7493 	 function templates, the function template corresponding to P is at
7494 	 least as specialized as the function template corresponding to A
7495 	 according to the partial ordering rules for function templates
7496 	 ([temp.func.order]). Given an invented class template X with the
7497 	 template parameter list of A (including default arguments):
7498 
7499 	 * Each of the two function templates has the same template parameters,
7500 	 respectively, as P or A.
7501 
7502 	 * Each function template has a single function parameter whose type is
7503 	 a specialization of X with template arguments corresponding to the
7504 	 template parameters from the respective function template where, for
7505 	 each template parameter PP in the template parameter list of the
7506 	 function template, a corresponding template argument AA is formed. If
7507 	 PP declares a parameter pack, then AA is the pack expansion
7508 	 PP... ([temp.variadic]); otherwise, AA is the id-expression PP.
7509 
7510 	 If the rewrite produces an invalid type, then P is not at least as
7511 	 specialized as A.  */
7512 
7513       /* So coerce P's args to apply to A's parms, and then deduce between A's
7514 	 args and the converted args.  If that succeeds, A is at least as
7515 	 specialized as P, so they match.*/
7516       tree pargs = template_parms_level_to_args (parm_parms);
7517       ++processing_template_decl;
7518       pargs = coerce_template_parms (arg_parms, pargs, NULL_TREE, tf_none,
7519 				     /*require_all*/true, /*use_default*/true);
7520       --processing_template_decl;
7521       if (pargs != error_mark_node)
7522 	{
7523 	  tree targs = make_tree_vec (nargs);
7524 	  tree aargs = template_parms_level_to_args (arg_parms);
7525 	  if (!unify (arg_parms, targs, aargs, pargs, UNIFY_ALLOW_NONE,
7526 		      /*explain*/false))
7527 	    return 1;
7528 	}
7529     }
7530 
7531   /* Determine whether we have a parameter pack at the end of the
7532      template template parameter's template parameter list.  */
7533   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
7534     {
7535       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
7536 
7537       if (error_operand_p (parm))
7538 	return 0;
7539 
7540       switch (TREE_CODE (parm))
7541         {
7542         case TEMPLATE_DECL:
7543         case TYPE_DECL:
7544           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7545             variadic_p = 1;
7546           break;
7547 
7548         case PARM_DECL:
7549           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7550             variadic_p = 1;
7551           break;
7552 
7553         default:
7554           gcc_unreachable ();
7555         }
7556     }
7557 
7558   if (nargs != nparms
7559       && !(variadic_p && nargs >= nparms - 1))
7560     return 0;
7561 
7562   /* Check all of the template parameters except the parameter pack at
7563      the end (if any).  */
7564   for (i = 0; i < nparms - variadic_p; ++i)
7565     {
7566       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
7567           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
7568         continue;
7569 
7570       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
7571       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
7572 
7573       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
7574                                           outer_args))
7575 	return 0;
7576 
7577     }
7578 
7579   if (variadic_p)
7580     {
7581       /* Check each of the template parameters in the template
7582 	 argument against the template parameter pack at the end of
7583 	 the template template parameter.  */
7584       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
7585 	return 0;
7586 
7587       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
7588 
7589       for (; i < nargs; ++i)
7590         {
7591           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
7592             continue;
7593 
7594           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
7595 
7596           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
7597                                               outer_args))
7598             return 0;
7599         }
7600     }
7601 
7602   return 1;
7603 }
7604 
7605 /* Verifies that the deduced template arguments (in TARGS) for the
7606    template template parameters (in TPARMS) represent valid bindings,
7607    by comparing the template parameter list of each template argument
7608    to the template parameter list of its corresponding template
7609    template parameter, in accordance with DR150. This
7610    routine can only be called after all template arguments have been
7611    deduced. It will return TRUE if all of the template template
7612    parameter bindings are okay, FALSE otherwise.  */
7613 bool
template_template_parm_bindings_ok_p(tree tparms,tree targs)7614 template_template_parm_bindings_ok_p (tree tparms, tree targs)
7615 {
7616   int i, ntparms = TREE_VEC_LENGTH (tparms);
7617   bool ret = true;
7618 
7619   /* We're dealing with template parms in this process.  */
7620   ++processing_template_decl;
7621 
7622   targs = INNERMOST_TEMPLATE_ARGS (targs);
7623 
7624   for (i = 0; i < ntparms; ++i)
7625     {
7626       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
7627       tree targ = TREE_VEC_ELT (targs, i);
7628 
7629       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
7630 	{
7631 	  tree packed_args = NULL_TREE;
7632 	  int idx, len = 1;
7633 
7634 	  if (ARGUMENT_PACK_P (targ))
7635 	    {
7636 	      /* Look inside the argument pack.  */
7637 	      packed_args = ARGUMENT_PACK_ARGS (targ);
7638 	      len = TREE_VEC_LENGTH (packed_args);
7639 	    }
7640 
7641 	  for (idx = 0; idx < len; ++idx)
7642 	    {
7643 	      tree targ_parms = NULL_TREE;
7644 
7645 	      if (packed_args)
7646 		/* Extract the next argument from the argument
7647 		   pack.  */
7648 		targ = TREE_VEC_ELT (packed_args, idx);
7649 
7650 	      if (PACK_EXPANSION_P (targ))
7651 		/* Look at the pattern of the pack expansion.  */
7652 		targ = PACK_EXPANSION_PATTERN (targ);
7653 
7654 	      /* Extract the template parameters from the template
7655 		 argument.  */
7656 	      if (TREE_CODE (targ) == TEMPLATE_DECL)
7657 		targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
7658 	      else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
7659 		targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
7660 
7661 	      /* Verify that we can coerce the template template
7662 		 parameters from the template argument to the template
7663 		 parameter.  This requires an exact match.  */
7664 	      if (targ_parms
7665 		  && !coerce_template_template_parms
7666 		       (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
7667 			targ_parms,
7668 			tf_none,
7669 			tparm,
7670 			targs))
7671 		{
7672 		  ret = false;
7673 		  goto out;
7674 		}
7675 	    }
7676 	}
7677     }
7678 
7679  out:
7680 
7681   --processing_template_decl;
7682   return ret;
7683 }
7684 
7685 /* Since type attributes aren't mangled, we need to strip them from
7686    template type arguments.  */
7687 
7688 static tree
canonicalize_type_argument(tree arg,tsubst_flags_t complain)7689 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
7690 {
7691   if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
7692     return arg;
7693   bool removed_attributes = false;
7694   tree canon = strip_typedefs (arg, &removed_attributes);
7695   if (removed_attributes
7696       && (complain & tf_warning))
7697     warning (OPT_Wignored_attributes,
7698 	     "ignoring attributes on template argument %qT", arg);
7699   return canon;
7700 }
7701 
7702 /* And from inside dependent non-type arguments like sizeof(Type).  */
7703 
7704 static tree
canonicalize_expr_argument(tree arg,tsubst_flags_t complain)7705 canonicalize_expr_argument (tree arg, tsubst_flags_t complain)
7706 {
7707   if (!arg || arg == error_mark_node)
7708     return arg;
7709   bool removed_attributes = false;
7710   tree canon = strip_typedefs_expr (arg, &removed_attributes);
7711   if (removed_attributes
7712       && (complain & tf_warning))
7713     warning (OPT_Wignored_attributes,
7714 	     "ignoring attributes in template argument %qE", arg);
7715   return canon;
7716 }
7717 
7718 // A template declaration can be substituted for a constrained
7719 // template template parameter only when the argument is more
7720 // constrained than the parameter.
7721 static bool
is_compatible_template_arg(tree parm,tree arg)7722 is_compatible_template_arg (tree parm, tree arg)
7723 {
7724   tree parm_cons = get_constraints (parm);
7725 
7726   /* For now, allow constrained template template arguments
7727      and unconstrained template template parameters.  */
7728   if (parm_cons == NULL_TREE)
7729     return true;
7730 
7731   tree arg_cons = get_constraints (arg);
7732 
7733   // If the template parameter is constrained, we need to rewrite its
7734   // constraints in terms of the ARG's template parameters. This ensures
7735   // that all of the template parameter types will have the same depth.
7736   //
7737   // Note that this is only valid when coerce_template_template_parm is
7738   // true for the innermost template parameters of PARM and ARG. In other
7739   // words, because coercion is successful, this conversion will be valid.
7740   if (parm_cons)
7741     {
7742       tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (arg));
7743       parm_cons = tsubst_constraint_info (parm_cons,
7744 					  INNERMOST_TEMPLATE_ARGS (args),
7745 					  tf_none, NULL_TREE);
7746       if (parm_cons == error_mark_node)
7747         return false;
7748     }
7749 
7750   return subsumes (parm_cons, arg_cons);
7751 }
7752 
7753 // Convert a placeholder argument into a binding to the original
7754 // parameter. The original parameter is saved as the TREE_TYPE of
7755 // ARG.
7756 static inline tree
convert_wildcard_argument(tree parm,tree arg)7757 convert_wildcard_argument (tree parm, tree arg)
7758 {
7759   TREE_TYPE (arg) = parm;
7760   return arg;
7761 }
7762 
7763 /* We can't fully resolve ARG given as a non-type template argument to TYPE,
7764    because one of them is dependent.  But we need to represent the
7765    conversion for the benefit of cp_tree_equal.  */
7766 
7767 static tree
maybe_convert_nontype_argument(tree type,tree arg)7768 maybe_convert_nontype_argument (tree type, tree arg)
7769 {
7770   /* Auto parms get no conversion.  */
7771   if (type_uses_auto (type))
7772     return arg;
7773   /* We don't need or want to add this conversion now if we're going to use the
7774      argument for deduction.  */
7775   if (value_dependent_expression_p (arg))
7776     return arg;
7777 
7778   type = cv_unqualified (type);
7779   tree argtype = TREE_TYPE (arg);
7780   if (same_type_p (type, argtype))
7781     return arg;
7782 
7783   arg = build1 (IMPLICIT_CONV_EXPR, type, arg);
7784   IMPLICIT_CONV_EXPR_NONTYPE_ARG (arg) = true;
7785   return arg;
7786 }
7787 
7788 /* Convert the indicated template ARG as necessary to match the
7789    indicated template PARM.  Returns the converted ARG, or
7790    error_mark_node if the conversion was unsuccessful.  Error and
7791    warning messages are issued under control of COMPLAIN.  This
7792    conversion is for the Ith parameter in the parameter list.  ARGS is
7793    the full set of template arguments deduced so far.  */
7794 
7795 static tree
convert_template_argument(tree parm,tree arg,tree args,tsubst_flags_t complain,int i,tree in_decl)7796 convert_template_argument (tree parm,
7797 			   tree arg,
7798 			   tree args,
7799 			   tsubst_flags_t complain,
7800 			   int i,
7801 			   tree in_decl)
7802 {
7803   tree orig_arg;
7804   tree val;
7805   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
7806 
7807   if (parm == error_mark_node)
7808     return error_mark_node;
7809 
7810   /* Trivially convert placeholders. */
7811   if (TREE_CODE (arg) == WILDCARD_DECL)
7812     return convert_wildcard_argument (parm, arg);
7813 
7814   if (arg == any_targ_node)
7815     return arg;
7816 
7817   if (TREE_CODE (arg) == TREE_LIST
7818       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
7819     {
7820       /* The template argument was the name of some
7821 	 member function.  That's usually
7822 	 invalid, but static members are OK.  In any
7823 	 case, grab the underlying fields/functions
7824 	 and issue an error later if required.  */
7825       orig_arg = TREE_VALUE (arg);
7826       TREE_TYPE (arg) = unknown_type_node;
7827     }
7828 
7829   orig_arg = arg;
7830 
7831   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
7832   requires_type = (TREE_CODE (parm) == TYPE_DECL
7833 		   || requires_tmpl_type);
7834 
7835   /* When determining whether an argument pack expansion is a template,
7836      look at the pattern.  */
7837   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
7838     arg = PACK_EXPANSION_PATTERN (arg);
7839 
7840   /* Deal with an injected-class-name used as a template template arg.  */
7841   if (requires_tmpl_type && CLASS_TYPE_P (arg))
7842     {
7843       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
7844       if (TREE_CODE (t) == TEMPLATE_DECL)
7845 	{
7846 	  if (cxx_dialect >= cxx11)
7847 	    /* OK under DR 1004.  */;
7848 	  else if (complain & tf_warning_or_error)
7849 	    pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
7850 		     " used as template template argument", TYPE_NAME (arg));
7851 	  else if (flag_pedantic_errors)
7852 	    t = arg;
7853 
7854 	  arg = t;
7855 	}
7856     }
7857 
7858   is_tmpl_type =
7859     ((TREE_CODE (arg) == TEMPLATE_DECL
7860       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
7861      || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
7862      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
7863      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
7864 
7865   if (is_tmpl_type
7866       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
7867 	  || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
7868     arg = TYPE_STUB_DECL (arg);
7869 
7870   is_type = TYPE_P (arg) || is_tmpl_type;
7871 
7872   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
7873       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
7874     {
7875       if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
7876 	{
7877 	  if (complain & tf_error)
7878 	    error ("invalid use of destructor %qE as a type", orig_arg);
7879 	  return error_mark_node;
7880 	}
7881 
7882       permerror (input_location,
7883 		 "to refer to a type member of a template parameter, "
7884 		 "use %<typename %E%>", orig_arg);
7885 
7886       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
7887 				     TREE_OPERAND (arg, 1),
7888 				     typename_type,
7889 				     complain);
7890       arg = orig_arg;
7891       is_type = 1;
7892     }
7893   if (is_type != requires_type)
7894     {
7895       if (in_decl)
7896 	{
7897 	  if (complain & tf_error)
7898 	    {
7899 	      error ("type/value mismatch at argument %d in template "
7900 		     "parameter list for %qD",
7901 		     i + 1, in_decl);
7902 	      if (is_type)
7903 		inform (input_location,
7904 			"  expected a constant of type %qT, got %qT",
7905 			TREE_TYPE (parm),
7906 			(DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
7907 	      else if (requires_tmpl_type)
7908 		inform (input_location,
7909 			"  expected a class template, got %qE", orig_arg);
7910 	      else
7911 		inform (input_location,
7912 			"  expected a type, got %qE", orig_arg);
7913 	    }
7914 	}
7915       return error_mark_node;
7916     }
7917   if (is_tmpl_type ^ requires_tmpl_type)
7918     {
7919       if (in_decl && (complain & tf_error))
7920 	{
7921 	  error ("type/value mismatch at argument %d in template "
7922 		 "parameter list for %qD",
7923 		 i + 1, in_decl);
7924 	  if (is_tmpl_type)
7925 	    inform (input_location,
7926 		    "  expected a type, got %qT", DECL_NAME (arg));
7927 	  else
7928 	    inform (input_location,
7929 		    "  expected a class template, got %qT", orig_arg);
7930 	}
7931       return error_mark_node;
7932     }
7933 
7934   if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
7935     /* We already did the appropriate conversion when packing args.  */
7936     val = orig_arg;
7937   else if (is_type)
7938     {
7939       if (requires_tmpl_type)
7940 	{
7941 	  if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
7942 	    /* The number of argument required is not known yet.
7943 	       Just accept it for now.  */
7944 	    val = orig_arg;
7945 	  else
7946 	    {
7947 	      tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
7948 	      tree argparm;
7949 
7950 	      /* Strip alias templates that are equivalent to another
7951 		 template.  */
7952 	      arg = get_underlying_template (arg);
7953               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
7954 
7955 	      if (coerce_template_template_parms (parmparm, argparm,
7956 						  complain, in_decl,
7957 						  args))
7958 		{
7959 		  val = arg;
7960 
7961 		  /* TEMPLATE_TEMPLATE_PARM node is preferred over
7962 		     TEMPLATE_DECL.  */
7963 		  if (val != error_mark_node)
7964                     {
7965                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
7966                         val = TREE_TYPE (val);
7967 		      if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
7968 			val = make_pack_expansion (val, complain);
7969                     }
7970 		}
7971 	      else
7972 		{
7973 		  if (in_decl && (complain & tf_error))
7974 		    {
7975 		      error ("type/value mismatch at argument %d in "
7976 			     "template parameter list for %qD",
7977 			     i + 1, in_decl);
7978 		      inform (input_location,
7979 			      "  expected a template of type %qD, got %qT",
7980 			      parm, orig_arg);
7981 		    }
7982 
7983 		  val = error_mark_node;
7984 		}
7985 
7986               // Check that the constraints are compatible before allowing the
7987               // substitution.
7988               if (val != error_mark_node)
7989                 if (!is_compatible_template_arg (parm, arg))
7990                   {
7991 		    if (in_decl && (complain & tf_error))
7992                       {
7993                         error ("constraint mismatch at argument %d in "
7994                                "template parameter list for %qD",
7995                                i + 1, in_decl);
7996                         inform (input_location, "  expected %qD but got %qD",
7997                                 parm, arg);
7998                       }
7999 		    val = error_mark_node;
8000                   }
8001 	    }
8002 	}
8003       else
8004 	val = orig_arg;
8005       /* We only form one instance of each template specialization.
8006 	 Therefore, if we use a non-canonical variant (i.e., a
8007 	 typedef), any future messages referring to the type will use
8008 	 the typedef, which is confusing if those future uses do not
8009 	 themselves also use the typedef.  */
8010       if (TYPE_P (val))
8011 	val = canonicalize_type_argument (val, complain);
8012     }
8013   else
8014     {
8015       tree t = TREE_TYPE (parm);
8016 
8017       if (TEMPLATE_PARM_LEVEL (get_template_parm_index (parm))
8018 	  > TMPL_ARGS_DEPTH (args))
8019 	/* We don't have enough levels of args to do any substitution.  This
8020 	   can happen in the context of -fnew-ttp-matching.  */;
8021       else if (tree a = type_uses_auto (t))
8022 	{
8023 	  t = do_auto_deduction (t, arg, a, complain, adc_unify, args);
8024 	  if (t == error_mark_node)
8025 	    return error_mark_node;
8026 	}
8027       else
8028 	t = tsubst (t, args, complain, in_decl);
8029 
8030       if (invalid_nontype_parm_type_p (t, complain))
8031 	return error_mark_node;
8032 
8033       if (!type_dependent_expression_p (orig_arg)
8034 	  && !uses_template_parms (t))
8035 	/* We used to call digest_init here.  However, digest_init
8036 	   will report errors, which we don't want when complain
8037 	   is zero.  More importantly, digest_init will try too
8038 	   hard to convert things: for example, `0' should not be
8039 	   converted to pointer type at this point according to
8040 	   the standard.  Accepting this is not merely an
8041 	   extension, since deciding whether or not these
8042 	   conversions can occur is part of determining which
8043 	   function template to call, or whether a given explicit
8044 	   argument specification is valid.  */
8045 	val = convert_nontype_argument (t, orig_arg, complain);
8046       else
8047 	{
8048 	  val = canonicalize_expr_argument (orig_arg, complain);
8049 	  val = maybe_convert_nontype_argument (t, val);
8050 	}
8051 
8052 
8053       if (val == NULL_TREE)
8054 	val = error_mark_node;
8055       else if (val == error_mark_node && (complain & tf_error))
8056 	error ("could not convert template argument %qE from %qT to %qT",
8057 	       orig_arg, TREE_TYPE (orig_arg), t);
8058 
8059       if (INDIRECT_REF_P (val))
8060         {
8061           /* Reject template arguments that are references to built-in
8062              functions with no library fallbacks.  */
8063           const_tree inner = TREE_OPERAND (val, 0);
8064 	  const_tree innertype = TREE_TYPE (inner);
8065 	  if (innertype
8066 	      && TREE_CODE (innertype) == REFERENCE_TYPE
8067 	      && TREE_CODE (TREE_TYPE (innertype)) == FUNCTION_TYPE
8068 	      && TREE_OPERAND_LENGTH (inner) > 0
8069               && reject_gcc_builtin (TREE_OPERAND (inner, 0)))
8070               return error_mark_node;
8071         }
8072 
8073       if (TREE_CODE (val) == SCOPE_REF)
8074 	{
8075 	  /* Strip typedefs from the SCOPE_REF.  */
8076 	  tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
8077 	  tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
8078 						   complain);
8079 	  val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
8080 				      QUALIFIED_NAME_IS_TEMPLATE (val));
8081 	}
8082     }
8083 
8084   return val;
8085 }
8086 
8087 /* Coerces the remaining template arguments in INNER_ARGS (from
8088    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
8089    Returns the coerced argument pack. PARM_IDX is the position of this
8090    parameter in the template parameter list. ARGS is the original
8091    template argument list.  */
8092 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)8093 coerce_template_parameter_pack (tree parms,
8094                                 int parm_idx,
8095                                 tree args,
8096                                 tree inner_args,
8097                                 int arg_idx,
8098                                 tree new_args,
8099                                 int* lost,
8100                                 tree in_decl,
8101                                 tsubst_flags_t complain)
8102 {
8103   tree parm = TREE_VEC_ELT (parms, parm_idx);
8104   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8105   tree packed_args;
8106   tree argument_pack;
8107   tree packed_parms = NULL_TREE;
8108 
8109   if (arg_idx > nargs)
8110     arg_idx = nargs;
8111 
8112   if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
8113     {
8114       /* When the template parameter is a non-type template parameter pack
8115          or template template parameter pack whose type or template
8116          parameters use parameter packs, we know exactly how many arguments
8117          we are looking for.  Build a vector of the instantiated decls for
8118          these template parameters in PACKED_PARMS.  */
8119       /* We can't use make_pack_expansion here because it would interpret a
8120 	 _DECL as a use rather than a declaration.  */
8121       tree decl = TREE_VALUE (parm);
8122       tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
8123       SET_PACK_EXPANSION_PATTERN (exp, decl);
8124       PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
8125       SET_TYPE_STRUCTURAL_EQUALITY (exp);
8126 
8127       TREE_VEC_LENGTH (args)--;
8128       packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
8129       TREE_VEC_LENGTH (args)++;
8130 
8131       if (packed_parms == error_mark_node)
8132         return error_mark_node;
8133 
8134       /* If we're doing a partial instantiation of a member template,
8135          verify that all of the types used for the non-type
8136          template parameter pack are, in fact, valid for non-type
8137          template parameters.  */
8138       if (arg_idx < nargs
8139           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
8140         {
8141           int j, len = TREE_VEC_LENGTH (packed_parms);
8142           for (j = 0; j < len; ++j)
8143             {
8144               tree t = TREE_TYPE (TREE_VEC_ELT (packed_parms, j));
8145               if (invalid_nontype_parm_type_p (t, complain))
8146                 return error_mark_node;
8147             }
8148 	  /* We don't know how many args we have yet, just
8149 	     use the unconverted ones for now.  */
8150 	  return NULL_TREE;
8151         }
8152 
8153       packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
8154     }
8155   /* Check if we have a placeholder pack, which indicates we're
8156      in the context of a introduction list.  In that case we want
8157      to match this pack to the single placeholder.  */
8158   else if (arg_idx < nargs
8159            && TREE_CODE (TREE_VEC_ELT (inner_args, arg_idx)) == WILDCARD_DECL
8160            && WILDCARD_PACK_P (TREE_VEC_ELT (inner_args, arg_idx)))
8161     {
8162       nargs = arg_idx + 1;
8163       packed_args = make_tree_vec (1);
8164     }
8165   else
8166     packed_args = make_tree_vec (nargs - arg_idx);
8167 
8168   /* Convert the remaining arguments, which will be a part of the
8169      parameter pack "parm".  */
8170   int first_pack_arg = arg_idx;
8171   for (; arg_idx < nargs; ++arg_idx)
8172     {
8173       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
8174       tree actual_parm = TREE_VALUE (parm);
8175       int pack_idx = arg_idx - first_pack_arg;
8176 
8177       if (packed_parms)
8178         {
8179 	  /* Once we've packed as many args as we have types, stop.  */
8180 	  if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
8181 	    break;
8182 	  else if (PACK_EXPANSION_P (arg))
8183 	    /* We don't know how many args we have yet, just
8184 	       use the unconverted ones for now.  */
8185 	    return NULL_TREE;
8186 	  else
8187 	    actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
8188         }
8189 
8190       if (arg == error_mark_node)
8191 	{
8192 	  if (complain & tf_error)
8193 	    error ("template argument %d is invalid", arg_idx + 1);
8194 	}
8195       else
8196 	arg = convert_template_argument (actual_parm,
8197 					 arg, new_args, complain, parm_idx,
8198 					 in_decl);
8199       if (arg == error_mark_node)
8200         (*lost)++;
8201       TREE_VEC_ELT (packed_args, pack_idx) = arg;
8202     }
8203 
8204   if (arg_idx - first_pack_arg < TREE_VEC_LENGTH (packed_args)
8205       && TREE_VEC_LENGTH (packed_args) > 0)
8206     {
8207       if (complain & tf_error)
8208 	error ("wrong number of template arguments (%d, should be %d)",
8209 	       arg_idx - first_pack_arg, TREE_VEC_LENGTH (packed_args));
8210       return error_mark_node;
8211     }
8212 
8213   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
8214       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
8215     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
8216   else
8217     {
8218       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
8219       TREE_CONSTANT (argument_pack) = 1;
8220     }
8221 
8222   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
8223   if (CHECKING_P)
8224     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
8225 					 TREE_VEC_LENGTH (packed_args));
8226   return argument_pack;
8227 }
8228 
8229 /* Returns the number of pack expansions in the template argument vector
8230    ARGS.  */
8231 
8232 static int
pack_expansion_args_count(tree args)8233 pack_expansion_args_count (tree args)
8234 {
8235   int i;
8236   int count = 0;
8237   if (args)
8238     for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
8239       {
8240 	tree elt = TREE_VEC_ELT (args, i);
8241 	if (elt && PACK_EXPANSION_P (elt))
8242 	  ++count;
8243       }
8244   return count;
8245 }
8246 
8247 /* Convert all template arguments to their appropriate types, and
8248    return a vector containing the innermost resulting template
8249    arguments.  If any error occurs, return error_mark_node. Error and
8250    warning messages are issued under control of COMPLAIN.
8251 
8252    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
8253    for arguments not specified in ARGS.  Otherwise, if
8254    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
8255    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
8256    USE_DEFAULT_ARGS is false, then all arguments must be specified in
8257    ARGS.  */
8258 
8259 static tree
coerce_template_parms(tree parms,tree args,tree in_decl,tsubst_flags_t complain,bool require_all_args,bool use_default_args)8260 coerce_template_parms (tree parms,
8261 		       tree args,
8262 		       tree in_decl,
8263 		       tsubst_flags_t complain,
8264 		       bool require_all_args,
8265 		       bool use_default_args)
8266 {
8267   int nparms, nargs, parm_idx, arg_idx, lost = 0;
8268   tree orig_inner_args;
8269   tree inner_args;
8270   tree new_args;
8271   tree new_inner_args;
8272   int saved_unevaluated_operand;
8273   int saved_inhibit_evaluation_warnings;
8274 
8275   /* When used as a boolean value, indicates whether this is a
8276      variadic template parameter list. Since it's an int, we can also
8277      subtract it from nparms to get the number of non-variadic
8278      parameters.  */
8279   int variadic_p = 0;
8280   int variadic_args_p = 0;
8281   int post_variadic_parms = 0;
8282 
8283   /* Adjustment to nparms for fixed parameter packs.  */
8284   int fixed_pack_adjust = 0;
8285   int fixed_packs = 0;
8286   int missing = 0;
8287 
8288   /* Likewise for parameters with default arguments.  */
8289   int default_p = 0;
8290 
8291   if (args == error_mark_node)
8292     return error_mark_node;
8293 
8294   nparms = TREE_VEC_LENGTH (parms);
8295 
8296   /* Determine if there are any parameter packs or default arguments.  */
8297   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
8298     {
8299       tree parm = TREE_VEC_ELT (parms, parm_idx);
8300       if (variadic_p)
8301 	++post_variadic_parms;
8302       if (template_parameter_pack_p (TREE_VALUE (parm)))
8303 	++variadic_p;
8304       if (TREE_PURPOSE (parm))
8305 	++default_p;
8306     }
8307 
8308   inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
8309   /* If there are no parameters that follow a parameter pack, we need to
8310      expand any argument packs so that we can deduce a parameter pack from
8311      some non-packed args followed by an argument pack, as in variadic85.C.
8312      If there are such parameters, we need to leave argument packs intact
8313      so the arguments are assigned properly.  This can happen when dealing
8314      with a nested class inside a partial specialization of a class
8315      template, as in variadic92.C, or when deducing a template parameter pack
8316      from a sub-declarator, as in variadic114.C.  */
8317   if (!post_variadic_parms)
8318     inner_args = expand_template_argument_pack (inner_args);
8319 
8320   /* Count any pack expansion args.  */
8321   variadic_args_p = pack_expansion_args_count (inner_args);
8322 
8323   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8324   if ((nargs - variadic_args_p > nparms && !variadic_p)
8325       || (nargs < nparms - variadic_p
8326 	  && require_all_args
8327 	  && !variadic_args_p
8328 	  && (!use_default_args
8329 	      || (TREE_VEC_ELT (parms, nargs) != error_mark_node
8330                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
8331     {
8332     bad_nargs:
8333       if (complain & tf_error)
8334 	{
8335           if (variadic_p || default_p)
8336             {
8337               nparms -= variadic_p + default_p;
8338 	      error ("wrong number of template arguments "
8339 		     "(%d, should be at least %d)", nargs, nparms);
8340             }
8341 	  else
8342 	     error ("wrong number of template arguments "
8343 		    "(%d, should be %d)", nargs, nparms);
8344 
8345 	  if (in_decl)
8346 	    inform (DECL_SOURCE_LOCATION (in_decl),
8347 		    "provided for %qD", in_decl);
8348 	}
8349 
8350       return error_mark_node;
8351     }
8352   /* We can't pass a pack expansion to a non-pack parameter of an alias
8353      template (DR 1430).  */
8354   else if (in_decl
8355 	   && (DECL_ALIAS_TEMPLATE_P (in_decl)
8356 	       || concept_template_p (in_decl))
8357 	   && variadic_args_p
8358 	   && nargs - variadic_args_p < nparms - variadic_p)
8359     {
8360       if (complain & tf_error)
8361 	{
8362 	  for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
8363 	    {
8364 	      tree arg = TREE_VEC_ELT (inner_args, i);
8365 	      tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
8366 
8367 	      if (PACK_EXPANSION_P (arg)
8368 		  && !template_parameter_pack_p (parm))
8369 		{
8370 		  if (DECL_ALIAS_TEMPLATE_P (in_decl))
8371 		    error_at (location_of (arg),
8372 			      "pack expansion argument for non-pack parameter "
8373 			      "%qD of alias template %qD", parm, in_decl);
8374 		  else
8375 		    error_at (location_of (arg),
8376 			      "pack expansion argument for non-pack parameter "
8377 			      "%qD of concept %qD", parm, in_decl);
8378 		  inform (DECL_SOURCE_LOCATION (parm), "declared here");
8379 		  goto found;
8380 		}
8381 	    }
8382 	  gcc_unreachable ();
8383 	found:;
8384 	}
8385       return error_mark_node;
8386     }
8387 
8388   /* We need to evaluate the template arguments, even though this
8389      template-id may be nested within a "sizeof".  */
8390   saved_unevaluated_operand = cp_unevaluated_operand;
8391   cp_unevaluated_operand = 0;
8392   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
8393   c_inhibit_evaluation_warnings = 0;
8394   new_inner_args = make_tree_vec (nparms);
8395   new_args = add_outermost_template_args (args, new_inner_args);
8396   int pack_adjust = 0;
8397   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
8398     {
8399       tree arg;
8400       tree parm;
8401 
8402       /* Get the Ith template parameter.  */
8403       parm = TREE_VEC_ELT (parms, parm_idx);
8404 
8405       if (parm == error_mark_node)
8406 	{
8407 	  TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
8408 	  continue;
8409 	}
8410 
8411       /* Calculate the next argument.  */
8412       if (arg_idx < nargs)
8413 	arg = TREE_VEC_ELT (inner_args, arg_idx);
8414       else
8415 	arg = NULL_TREE;
8416 
8417       if (template_parameter_pack_p (TREE_VALUE (parm))
8418 	  && !(arg && ARGUMENT_PACK_P (arg)))
8419         {
8420 	  /* Some arguments will be placed in the
8421 	     template parameter pack PARM.  */
8422 	  arg = coerce_template_parameter_pack (parms, parm_idx, args,
8423 						inner_args, arg_idx,
8424 						new_args, &lost,
8425 						in_decl, complain);
8426 
8427 	  if (arg == NULL_TREE)
8428 	    {
8429 	      /* We don't know how many args we have yet, just use the
8430 		 unconverted (and still packed) ones for now.  */
8431 	      new_inner_args = orig_inner_args;
8432 	      arg_idx = nargs;
8433 	      break;
8434 	    }
8435 
8436           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
8437 
8438           /* Store this argument.  */
8439           if (arg == error_mark_node)
8440 	    {
8441 	      lost++;
8442 	      /* We are done with all of the arguments.  */
8443 	      arg_idx = nargs;
8444 	      break;
8445 	    }
8446 	  else
8447 	    {
8448 	      pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
8449 	      arg_idx += pack_adjust;
8450 	      if (fixed_parameter_pack_p (TREE_VALUE (parm)))
8451 		{
8452 		  ++fixed_packs;
8453 		  fixed_pack_adjust += pack_adjust;
8454 		}
8455 	    }
8456 
8457           continue;
8458         }
8459       else if (arg)
8460 	{
8461           if (PACK_EXPANSION_P (arg))
8462             {
8463 	      /* "If every valid specialization of a variadic template
8464 		 requires an empty template parameter pack, the template is
8465 		 ill-formed, no diagnostic required."  So check that the
8466 		 pattern works with this parameter.  */
8467 	      tree pattern = PACK_EXPANSION_PATTERN (arg);
8468 	      tree conv = convert_template_argument (TREE_VALUE (parm),
8469 						     pattern, new_args,
8470 						     complain, parm_idx,
8471 						     in_decl);
8472 	      if (conv == error_mark_node)
8473 		{
8474 		  if (complain & tf_error)
8475 		    inform (input_location, "so any instantiation with a "
8476 			    "non-empty parameter pack would be ill-formed");
8477 		  ++lost;
8478 		}
8479 	      else if (TYPE_P (conv) && !TYPE_P (pattern))
8480 		/* Recover from missing typename.  */
8481 		TREE_VEC_ELT (inner_args, arg_idx)
8482 		  = make_pack_expansion (conv, complain);
8483 
8484               /* We don't know how many args we have yet, just
8485                  use the unconverted ones for now.  */
8486               new_inner_args = inner_args;
8487 	      arg_idx = nargs;
8488               break;
8489             }
8490         }
8491       else if (require_all_args)
8492 	{
8493 	  /* There must be a default arg in this case.  */
8494 	  arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
8495 				     complain, in_decl);
8496 	  /* The position of the first default template argument,
8497 	     is also the number of non-defaulted arguments in NEW_INNER_ARGS.
8498 	     Record that.  */
8499 	  if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
8500 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
8501 						 arg_idx - pack_adjust);
8502 	}
8503       else
8504 	break;
8505 
8506       if (arg == error_mark_node)
8507 	{
8508 	  if (complain & tf_error)
8509 	    error ("template argument %d is invalid", arg_idx + 1);
8510 	}
8511       else if (!arg)
8512 	{
8513 	  /* This can occur if there was an error in the template
8514 	     parameter list itself (which we would already have
8515 	     reported) that we are trying to recover from, e.g., a class
8516 	     template with a parameter list such as
8517 	     template<typename..., typename> (cpp0x/variadic150.C).  */
8518 	  ++lost;
8519 
8520 	  /* This can also happen with a fixed parameter pack (71834).  */
8521 	  if (arg_idx >= nargs)
8522 	    ++missing;
8523 	}
8524       else
8525 	arg = convert_template_argument (TREE_VALUE (parm),
8526 					 arg, new_args, complain,
8527                                          parm_idx, in_decl);
8528 
8529       if (arg == error_mark_node)
8530 	lost++;
8531       TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
8532     }
8533   cp_unevaluated_operand = saved_unevaluated_operand;
8534   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
8535 
8536   if (missing || arg_idx < nargs - variadic_args_p)
8537     {
8538       /* If we had fixed parameter packs, we didn't know how many arguments we
8539 	 actually needed earlier; now we do.  */
8540       nparms += fixed_pack_adjust;
8541       variadic_p -= fixed_packs;
8542       goto bad_nargs;
8543     }
8544 
8545   if (arg_idx < nargs)
8546     {
8547       /* We had some pack expansion arguments that will only work if the packs
8548 	 are empty, but wait until instantiation time to complain.
8549 	 See variadic-ttp3.C.  */
8550       int len = nparms + (nargs - arg_idx);
8551       tree args = make_tree_vec (len);
8552       int i = 0;
8553       for (; i < nparms; ++i)
8554 	TREE_VEC_ELT (args, i) = TREE_VEC_ELT (new_inner_args, i);
8555       for (; i < len; ++i, ++arg_idx)
8556 	TREE_VEC_ELT (args, i) = TREE_VEC_ELT (inner_args,
8557 					       arg_idx - pack_adjust);
8558       new_inner_args = args;
8559     }
8560 
8561   if (lost)
8562     {
8563       gcc_assert (!(complain & tf_error) || seen_error ());
8564       return error_mark_node;
8565     }
8566 
8567   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
8568     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
8569 					 TREE_VEC_LENGTH (new_inner_args));
8570 
8571   return new_inner_args;
8572 }
8573 
8574 /* Convert all template arguments to their appropriate types, and
8575    return a vector containing the innermost resulting template
8576    arguments.  If any error occurs, return error_mark_node. Error and
8577    warning messages are not issued.
8578 
8579    Note that no function argument deduction is performed, and default
8580    arguments are used to fill in unspecified arguments. */
8581 tree
coerce_template_parms(tree parms,tree args,tree in_decl)8582 coerce_template_parms (tree parms, tree args, tree in_decl)
8583 {
8584   return coerce_template_parms (parms, args, in_decl, tf_none, true, true);
8585 }
8586 
8587 /* Convert all template arguments to their appropriate type, and
8588    instantiate default arguments as needed. This returns a vector
8589    containing the innermost resulting template arguments, or
8590    error_mark_node if unsuccessful.  */
8591 tree
coerce_template_parms(tree parms,tree args,tree in_decl,tsubst_flags_t complain)8592 coerce_template_parms (tree parms, tree args, tree in_decl,
8593                        tsubst_flags_t complain)
8594 {
8595   return coerce_template_parms (parms, args, in_decl, complain, true, true);
8596 }
8597 
8598 /* Like coerce_template_parms.  If PARMS represents all template
8599    parameters levels, this function returns a vector of vectors
8600    representing all the resulting argument levels.  Note that in this
8601    case, only the innermost arguments are coerced because the
8602    outermost ones are supposed to have been coerced already.
8603 
8604    Otherwise, if PARMS represents only (the innermost) vector of
8605    parameters, this function returns a vector containing just the
8606    innermost resulting arguments.  */
8607 
8608 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)8609 coerce_innermost_template_parms (tree parms,
8610 				  tree args,
8611 				  tree in_decl,
8612 				  tsubst_flags_t complain,
8613 				  bool require_all_args,
8614 				  bool use_default_args)
8615 {
8616   int parms_depth = TMPL_PARMS_DEPTH (parms);
8617   int args_depth = TMPL_ARGS_DEPTH (args);
8618   tree coerced_args;
8619 
8620   if (parms_depth > 1)
8621     {
8622       coerced_args = make_tree_vec (parms_depth);
8623       tree level;
8624       int cur_depth;
8625 
8626       for (level = parms, cur_depth = parms_depth;
8627 	   parms_depth > 0 && level != NULL_TREE;
8628 	   level = TREE_CHAIN (level), --cur_depth)
8629 	{
8630 	  tree l;
8631 	  if (cur_depth == args_depth)
8632 	    l = coerce_template_parms (TREE_VALUE (level),
8633 				       args, in_decl, complain,
8634 				       require_all_args,
8635 				       use_default_args);
8636 	  else
8637 	    l = TMPL_ARGS_LEVEL (args, cur_depth);
8638 
8639 	  if (l == error_mark_node)
8640 	    return error_mark_node;
8641 
8642 	  SET_TMPL_ARGS_LEVEL (coerced_args, cur_depth, l);
8643 	}
8644     }
8645   else
8646     coerced_args = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parms),
8647 					  args, in_decl, complain,
8648 					  require_all_args,
8649 					  use_default_args);
8650   return coerced_args;
8651 }
8652 
8653 /* Returns 1 if template args OT and NT are equivalent.  */
8654 
8655 int
template_args_equal(tree ot,tree nt,bool partial_order)8656 template_args_equal (tree ot, tree nt, bool partial_order /* = false */)
8657 {
8658   if (nt == ot)
8659     return 1;
8660   if (nt == NULL_TREE || ot == NULL_TREE)
8661     return false;
8662   if (nt == any_targ_node || ot == any_targ_node)
8663     return true;
8664 
8665   if (TREE_CODE (nt) == TREE_VEC)
8666     /* For member templates */
8667     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
8668   else if (PACK_EXPANSION_P (ot))
8669     return (PACK_EXPANSION_P (nt)
8670 	    && template_args_equal (PACK_EXPANSION_PATTERN (ot),
8671 				    PACK_EXPANSION_PATTERN (nt))
8672 	    && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
8673 				    PACK_EXPANSION_EXTRA_ARGS (nt)));
8674   else if (ARGUMENT_PACK_P (ot))
8675     {
8676       int i, len;
8677       tree opack, npack;
8678 
8679       if (!ARGUMENT_PACK_P (nt))
8680 	return 0;
8681 
8682       opack = ARGUMENT_PACK_ARGS (ot);
8683       npack = ARGUMENT_PACK_ARGS (nt);
8684       len = TREE_VEC_LENGTH (opack);
8685       if (TREE_VEC_LENGTH (npack) != len)
8686 	return 0;
8687       for (i = 0; i < len; ++i)
8688 	if (!template_args_equal (TREE_VEC_ELT (opack, i),
8689 				  TREE_VEC_ELT (npack, i)))
8690 	  return 0;
8691       return 1;
8692     }
8693   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
8694     gcc_unreachable ();
8695   else if (TYPE_P (nt))
8696     {
8697       if (!TYPE_P (ot))
8698 	return false;
8699       /* Don't treat an alias template specialization with dependent
8700 	 arguments as equivalent to its underlying type when used as a
8701 	 template argument; we need them to be distinct so that we
8702 	 substitute into the specialization arguments at instantiation
8703 	 time.  And aliases can't be equivalent without being ==, so
8704 	 we don't need to look any deeper.
8705 
8706          During partial ordering, however, we need to treat them normally so
8707          that we can order uses of the same alias with different
8708          cv-qualification (79960).  */
8709       if (!partial_order
8710 	  && (TYPE_ALIAS_P (nt) || TYPE_ALIAS_P (ot)))
8711 	return false;
8712       else
8713 	return same_type_p (ot, nt);
8714     }
8715   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
8716     return 0;
8717   else
8718     {
8719       /* Try to treat a template non-type argument that has been converted
8720 	 to the parameter type as equivalent to one that hasn't yet.  */
8721       for (enum tree_code code1 = TREE_CODE (ot);
8722 	   CONVERT_EXPR_CODE_P (code1)
8723 	     || code1 == NON_LVALUE_EXPR;
8724 	   code1 = TREE_CODE (ot))
8725 	ot = TREE_OPERAND (ot, 0);
8726       for (enum tree_code code2 = TREE_CODE (nt);
8727 	   CONVERT_EXPR_CODE_P (code2)
8728 	     || code2 == NON_LVALUE_EXPR;
8729 	   code2 = TREE_CODE (nt))
8730 	nt = TREE_OPERAND (nt, 0);
8731 
8732       return cp_tree_equal (ot, nt);
8733     }
8734 }
8735 
8736 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
8737    template arguments.  Returns 0 otherwise, and updates OLDARG_PTR and
8738    NEWARG_PTR with the offending arguments if they are non-NULL.  */
8739 
8740 int
comp_template_args(tree oldargs,tree newargs,tree * oldarg_ptr,tree * newarg_ptr,bool partial_order)8741 comp_template_args (tree oldargs, tree newargs,
8742 		    tree *oldarg_ptr, tree *newarg_ptr,
8743 		    bool partial_order)
8744 {
8745   int i;
8746 
8747   if (oldargs == newargs)
8748     return 1;
8749 
8750   if (!oldargs || !newargs)
8751     return 0;
8752 
8753   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
8754     return 0;
8755 
8756   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
8757     {
8758       tree nt = TREE_VEC_ELT (newargs, i);
8759       tree ot = TREE_VEC_ELT (oldargs, i);
8760 
8761       if (! template_args_equal (ot, nt, partial_order))
8762 	{
8763 	  if (oldarg_ptr != NULL)
8764 	    *oldarg_ptr = ot;
8765 	  if (newarg_ptr != NULL)
8766 	    *newarg_ptr = nt;
8767 	  return 0;
8768 	}
8769     }
8770   return 1;
8771 }
8772 
8773 inline bool
comp_template_args_porder(tree oargs,tree nargs)8774 comp_template_args_porder (tree oargs, tree nargs)
8775 {
8776   return comp_template_args (oargs, nargs, NULL, NULL, true);
8777 }
8778 
8779 /* Implement a freelist interface for objects of type T.
8780 
8781    Head is a separate object, rather than a regular member, so that we
8782    can define it as a GTY deletable pointer, which is highly
8783    desirable.  A data member could be declared that way, but then the
8784    containing object would implicitly get GTY((user)), which would
8785    prevent us from instantiating freelists as global objects.
8786    Although this way we can create freelist global objects, they're
8787    such thin wrappers that instantiating temporaries at every use
8788    loses nothing and saves permanent storage for the freelist object.
8789 
8790    Member functions next, anew, poison and reinit have default
8791    implementations that work for most of the types we're interested
8792    in, but if they don't work for some type, they should be explicitly
8793    specialized.  See the comments before them for requirements, and
8794    the example specializations for the tree_list_freelist.  */
8795 template <typename T>
8796 class freelist
8797 {
8798   /* Return the next object in a chain.  We could just do type
8799      punning, but if we access the object with its underlying type, we
8800      avoid strict-aliasing trouble.  This needs only work between
8801      poison and reinit.  */
next(T * obj)8802   static T *&next (T *obj) { return obj->next; }
8803 
8804   /* Return a newly allocated, uninitialized or minimally-initialized
8805      object of type T.  Any initialization performed by anew should
8806      either remain across the life of the object and the execution of
8807      poison, or be redone by reinit.  */
anew()8808   static T *anew () { return ggc_alloc<T> (); }
8809 
8810   /* Optionally scribble all over the bits holding the object, so that
8811      they become (mostly?) uninitialized memory.  This is called while
8812      preparing to make the object part of the free list.  */
poison(T * obj)8813   static void poison (T *obj) {
8814     T *p ATTRIBUTE_UNUSED = obj;
8815     T **q ATTRIBUTE_UNUSED = &next (obj);
8816 
8817 #ifdef ENABLE_GC_CHECKING
8818     /* Poison the data, to indicate the data is garbage.  */
8819     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, sizeof (*p)));
8820     memset (p, 0xa5, sizeof (*p));
8821 #endif
8822     /* Let valgrind know the object is free.  */
8823     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, sizeof (*p)));
8824 
8825     /* Let valgrind know the next portion of the object is available,
8826        but uninitialized.  */
8827     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
8828   }
8829 
8830   /* Bring an object that underwent at least one lifecycle after anew
8831      and before the most recent free and poison, back to a usable
8832      state, reinitializing whatever is needed for it to be
8833      functionally equivalent to an object just allocated and returned
8834      by anew.  This may poison or clear the next field, used by
8835      freelist housekeeping after poison was called.  */
reinit(T * obj)8836   static void reinit (T *obj) {
8837     T **q ATTRIBUTE_UNUSED = &next (obj);
8838 
8839 #ifdef ENABLE_GC_CHECKING
8840     memset (q, 0xa5, sizeof (*q));
8841 #endif
8842     /* Let valgrind know the entire object is available, but
8843        uninitialized.  */
8844     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (*obj)));
8845   }
8846 
8847   /* Reference a GTY-deletable pointer that points to the first object
8848      in the free list proper.  */
8849   T *&head;
8850 public:
8851   /* Construct a freelist object chaining objects off of HEAD.  */
freelist(T * & head)8852   freelist (T *&head) : head(head) {}
8853 
8854   /* Add OBJ to the free object list.  The former head becomes OBJ's
8855      successor.  */
free(T * obj)8856   void free (T *obj)
8857   {
8858     poison (obj);
8859     next (obj) = head;
8860     head = obj;
8861   }
8862 
8863   /* Take an object from the free list, if one is available, or
8864      allocate a new one.  Objects taken from the free list should be
8865      regarded as filled with garbage, except for bits that are
8866      configured to be preserved across free and alloc.  */
alloc()8867   T *alloc ()
8868   {
8869     if (head)
8870       {
8871 	T *obj = head;
8872 	head = next (head);
8873 	reinit (obj);
8874 	return obj;
8875       }
8876     else
8877       return anew ();
8878   }
8879 };
8880 
8881 /* Explicitly specialize the interfaces for freelist<tree_node>: we
8882    want to allocate a TREE_LIST using the usual interface, and ensure
8883    TREE_CHAIN remains functional.  Alas, we have to duplicate a bit of
8884    build_tree_list logic in reinit, so this could go out of sync.  */
8885 template <>
8886 inline tree &
next(tree obj)8887 freelist<tree_node>::next (tree obj)
8888 {
8889   return TREE_CHAIN (obj);
8890 }
8891 template <>
8892 inline tree
anew()8893 freelist<tree_node>::anew ()
8894 {
8895   return build_tree_list (NULL, NULL);
8896 }
8897 template <>
8898 inline void
poison(tree obj ATTRIBUTE_UNUSED)8899 freelist<tree_node>::poison (tree obj ATTRIBUTE_UNUSED)
8900 {
8901   int size ATTRIBUTE_UNUSED = sizeof (tree_list);
8902   tree p ATTRIBUTE_UNUSED = obj;
8903   tree_base *b ATTRIBUTE_UNUSED = &obj->base;
8904   tree *q ATTRIBUTE_UNUSED = &next (obj);
8905 
8906 #ifdef ENABLE_GC_CHECKING
8907   gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
8908 
8909   /* Poison the data, to indicate the data is garbage.  */
8910   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, size));
8911   memset (p, 0xa5, size);
8912 #endif
8913   /* Let valgrind know the object is free.  */
8914   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, size));
8915   /* But we still want to use the TREE_CODE and TREE_CHAIN parts.  */
8916   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
8917   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
8918 
8919 #ifdef ENABLE_GC_CHECKING
8920   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (b, sizeof (*b)));
8921   /* Keep TREE_CHAIN functional.  */
8922   TREE_SET_CODE (obj, TREE_LIST);
8923 #else
8924   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
8925 #endif
8926 }
8927 template <>
8928 inline void
reinit(tree obj ATTRIBUTE_UNUSED)8929 freelist<tree_node>::reinit (tree obj ATTRIBUTE_UNUSED)
8930 {
8931   tree_base *b ATTRIBUTE_UNUSED = &obj->base;
8932 
8933 #ifdef ENABLE_GC_CHECKING
8934   gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
8935   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
8936   memset (obj, 0, sizeof (tree_list));
8937 #endif
8938 
8939   /* Let valgrind know the entire object is available, but
8940      uninitialized.  */
8941   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
8942 
8943 #ifdef ENABLE_GC_CHECKING
8944   TREE_SET_CODE (obj, TREE_LIST);
8945 #else
8946   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
8947 #endif
8948 }
8949 
8950 /* Point to the first object in the TREE_LIST freelist.  */
8951 static GTY((deletable)) tree tree_list_freelist_head;
8952 /* Return the/an actual TREE_LIST freelist.  */
8953 static inline freelist<tree_node>
tree_list_freelist()8954 tree_list_freelist ()
8955 {
8956   return tree_list_freelist_head;
8957 }
8958 
8959 /* Point to the first object in the tinst_level freelist.  */
8960 static GTY((deletable)) tinst_level *tinst_level_freelist_head;
8961 /* Return the/an actual tinst_level freelist.  */
8962 static inline freelist<tinst_level>
tinst_level_freelist()8963 tinst_level_freelist ()
8964 {
8965   return tinst_level_freelist_head;
8966 }
8967 
8968 /* Point to the first object in the pending_template freelist.  */
8969 static GTY((deletable)) pending_template *pending_template_freelist_head;
8970 /* Return the/an actual pending_template freelist.  */
8971 static inline freelist<pending_template>
pending_template_freelist()8972 pending_template_freelist ()
8973 {
8974   return pending_template_freelist_head;
8975 }
8976 
8977 /* Build the TREE_LIST object out of a split list, store it
8978    permanently, and return it.  */
8979 tree
to_list()8980 tinst_level::to_list ()
8981 {
8982   gcc_assert (split_list_p ());
8983   tree ret = tree_list_freelist ().alloc ();
8984   TREE_PURPOSE (ret) = tldcl;
8985   TREE_VALUE (ret) = targs;
8986   tldcl = ret;
8987   targs = NULL;
8988   gcc_assert (tree_list_p ());
8989   return ret;
8990 }
8991 
8992 const unsigned short tinst_level::refcount_infinity;
8993 
8994 /* Increment OBJ's refcount unless it is already infinite.  */
8995 static tinst_level *
inc_refcount_use(tinst_level * obj)8996 inc_refcount_use (tinst_level *obj)
8997 {
8998   if (obj && obj->refcount != tinst_level::refcount_infinity)
8999     ++obj->refcount;
9000   return obj;
9001 }
9002 
9003 /* Release storage for OBJ and node, if it's a TREE_LIST.  */
9004 void
free(tinst_level * obj)9005 tinst_level::free (tinst_level *obj)
9006 {
9007   if (obj->tree_list_p ())
9008     tree_list_freelist ().free (obj->get_node ());
9009   tinst_level_freelist ().free (obj);
9010 }
9011 
9012 /* Decrement OBJ's refcount if not infinite.  If it reaches zero, release
9013    OBJ's DECL and OBJ, and start over with the tinst_level object that
9014    used to be referenced by OBJ's NEXT.  */
9015 static void
dec_refcount_use(tinst_level * obj)9016 dec_refcount_use (tinst_level *obj)
9017 {
9018   while (obj
9019 	 && obj->refcount != tinst_level::refcount_infinity
9020 	 && !--obj->refcount)
9021     {
9022       tinst_level *next = obj->next;
9023       tinst_level::free (obj);
9024       obj = next;
9025     }
9026 }
9027 
9028 /* Modify PTR so that it points to OBJ, adjusting the refcounts of OBJ
9029    and of the former PTR.  Omitting the second argument is equivalent
9030    to passing (T*)NULL; this is allowed because passing the
9031    zero-valued integral constant NULL confuses type deduction and/or
9032    overload resolution.  */
9033 template <typename T>
9034 static void
9035 set_refcount_ptr (T *& ptr, T *obj = NULL)
9036 {
9037   T *save = ptr;
9038   ptr = inc_refcount_use (obj);
9039   dec_refcount_use (save);
9040 }
9041 
9042 static void
add_pending_template(tree d)9043 add_pending_template (tree d)
9044 {
9045   tree ti = (TYPE_P (d)
9046 	     ? CLASSTYPE_TEMPLATE_INFO (d)
9047 	     : DECL_TEMPLATE_INFO (d));
9048   struct pending_template *pt;
9049   int level;
9050 
9051   if (TI_PENDING_TEMPLATE_FLAG (ti))
9052     return;
9053 
9054   /* We are called both from instantiate_decl, where we've already had a
9055      tinst_level pushed, and instantiate_template, where we haven't.
9056      Compensate.  */
9057   gcc_assert (TREE_CODE (d) != TREE_LIST);
9058   level = !current_tinst_level
9059     || current_tinst_level->maybe_get_node () != d;
9060 
9061   if (level)
9062     push_tinst_level (d);
9063 
9064   pt = pending_template_freelist ().alloc ();
9065   pt->next = NULL;
9066   pt->tinst = NULL;
9067   set_refcount_ptr (pt->tinst, current_tinst_level);
9068   if (last_pending_template)
9069     last_pending_template->next = pt;
9070   else
9071     pending_templates = pt;
9072 
9073   last_pending_template = pt;
9074 
9075   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
9076 
9077   if (level)
9078     pop_tinst_level ();
9079 }
9080 
9081 
9082 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
9083    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
9084    documentation for TEMPLATE_ID_EXPR.  */
9085 
9086 tree
lookup_template_function(tree fns,tree arglist)9087 lookup_template_function (tree fns, tree arglist)
9088 {
9089   tree type;
9090 
9091   if (fns == error_mark_node || arglist == error_mark_node)
9092     return error_mark_node;
9093 
9094   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
9095 
9096   if (!is_overloaded_fn (fns) && !identifier_p (fns))
9097     {
9098       error ("%q#D is not a function template", fns);
9099       return error_mark_node;
9100     }
9101 
9102   if (BASELINK_P (fns))
9103     {
9104       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
9105 					 unknown_type_node,
9106 					 BASELINK_FUNCTIONS (fns),
9107 					 arglist);
9108       return fns;
9109     }
9110 
9111   type = TREE_TYPE (fns);
9112   if (TREE_CODE (fns) == OVERLOAD || !type)
9113     type = unknown_type_node;
9114 
9115   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
9116 }
9117 
9118 /* Within the scope of a template class S<T>, the name S gets bound
9119    (in build_self_reference) to a TYPE_DECL for the class, not a
9120    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
9121    or one of its enclosing classes, and that type is a template,
9122    return the associated TEMPLATE_DECL.  Otherwise, the original
9123    DECL is returned.
9124 
9125    Also handle the case when DECL is a TREE_LIST of ambiguous
9126    injected-class-names from different bases.  */
9127 
9128 tree
maybe_get_template_decl_from_type_decl(tree decl)9129 maybe_get_template_decl_from_type_decl (tree decl)
9130 {
9131   if (decl == NULL_TREE)
9132     return decl;
9133 
9134   /* DR 176: A lookup that finds an injected-class-name (10.2
9135      [class.member.lookup]) can result in an ambiguity in certain cases
9136      (for example, if it is found in more than one base class). If all of
9137      the injected-class-names that are found refer to specializations of
9138      the same class template, and if the name is followed by a
9139      template-argument-list, the reference refers to the class template
9140      itself and not a specialization thereof, and is not ambiguous.  */
9141   if (TREE_CODE (decl) == TREE_LIST)
9142     {
9143       tree t, tmpl = NULL_TREE;
9144       for (t = decl; t; t = TREE_CHAIN (t))
9145 	{
9146 	  tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
9147 	  if (!tmpl)
9148 	    tmpl = elt;
9149 	  else if (tmpl != elt)
9150 	    break;
9151 	}
9152       if (tmpl && t == NULL_TREE)
9153 	return tmpl;
9154       else
9155 	return decl;
9156     }
9157 
9158   return (decl != NULL_TREE
9159 	  && DECL_SELF_REFERENCE_P (decl)
9160 	  && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
9161     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
9162 }
9163 
9164 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
9165    parameters, find the desired type.
9166 
9167    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
9168 
9169    IN_DECL, if non-NULL, is the template declaration we are trying to
9170    instantiate.
9171 
9172    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
9173    the class we are looking up.
9174 
9175    Issue error and warning messages under control of COMPLAIN.
9176 
9177    If the template class is really a local class in a template
9178    function, then the FUNCTION_CONTEXT is the function in which it is
9179    being instantiated.
9180 
9181    ??? Note that this function is currently called *twice* for each
9182    template-id: the first time from the parser, while creating the
9183    incomplete type (finish_template_type), and the second type during the
9184    real instantiation (instantiate_template_class). This is surely something
9185    that we want to avoid. It also causes some problems with argument
9186    coercion (see convert_nontype_argument for more information on this).  */
9187 
9188 static tree
lookup_template_class_1(tree d1,tree arglist,tree in_decl,tree context,int entering_scope,tsubst_flags_t complain)9189 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
9190 			 int entering_scope, tsubst_flags_t complain)
9191 {
9192   tree templ = NULL_TREE, parmlist;
9193   tree t;
9194   spec_entry **slot;
9195   spec_entry *entry;
9196   spec_entry elt;
9197   hashval_t hash;
9198 
9199   if (identifier_p (d1))
9200     {
9201       tree value = innermost_non_namespace_value (d1);
9202       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
9203 	templ = value;
9204       else
9205 	{
9206 	  if (context)
9207 	    push_decl_namespace (context);
9208 	  templ = lookup_name (d1);
9209 	  templ = maybe_get_template_decl_from_type_decl (templ);
9210 	  if (context)
9211 	    pop_decl_namespace ();
9212 	}
9213       if (templ)
9214 	context = DECL_CONTEXT (templ);
9215     }
9216   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
9217     {
9218       tree type = TREE_TYPE (d1);
9219 
9220       /* If we are declaring a constructor, say A<T>::A<T>, we will get
9221 	 an implicit typename for the second A.  Deal with it.  */
9222       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
9223 	type = TREE_TYPE (type);
9224 
9225       if (CLASSTYPE_TEMPLATE_INFO (type))
9226 	{
9227 	  templ = CLASSTYPE_TI_TEMPLATE (type);
9228 	  d1 = DECL_NAME (templ);
9229 	}
9230     }
9231   else if (TREE_CODE (d1) == ENUMERAL_TYPE
9232 	   || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
9233     {
9234       templ = TYPE_TI_TEMPLATE (d1);
9235       d1 = DECL_NAME (templ);
9236     }
9237   else if (DECL_TYPE_TEMPLATE_P (d1))
9238     {
9239       templ = d1;
9240       d1 = DECL_NAME (templ);
9241       context = DECL_CONTEXT (templ);
9242     }
9243   else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
9244     {
9245       templ = d1;
9246       d1 = DECL_NAME (templ);
9247     }
9248 
9249   /* Issue an error message if we didn't find a template.  */
9250   if (! templ)
9251     {
9252       if (complain & tf_error)
9253 	error ("%qT is not a template", d1);
9254       return error_mark_node;
9255     }
9256 
9257   if (TREE_CODE (templ) != TEMPLATE_DECL
9258 	 /* Make sure it's a user visible template, if it was named by
9259 	    the user.  */
9260       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
9261 	  && !PRIMARY_TEMPLATE_P (templ)))
9262     {
9263       if (complain & tf_error)
9264 	{
9265 	  error ("non-template type %qT used as a template", d1);
9266 	  if (in_decl)
9267 	    error ("for template declaration %q+D", in_decl);
9268 	}
9269       return error_mark_node;
9270     }
9271 
9272   complain &= ~tf_user;
9273 
9274   /* An alias that just changes the name of a template is equivalent to the
9275      other template, so if any of the arguments are pack expansions, strip
9276      the alias to avoid problems with a pack expansion passed to a non-pack
9277      alias template parameter (DR 1430).  */
9278   if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
9279     templ = get_underlying_template (templ);
9280 
9281   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
9282     {
9283       tree parm;
9284       tree arglist2 = coerce_template_args_for_ttp (templ, arglist, complain);
9285       if (arglist2 == error_mark_node
9286 	  || (!uses_template_parms (arglist2)
9287 	      && check_instantiated_args (templ, arglist2, complain)))
9288 	return error_mark_node;
9289 
9290       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
9291       return parm;
9292     }
9293   else
9294     {
9295       tree template_type = TREE_TYPE (templ);
9296       tree gen_tmpl;
9297       tree type_decl;
9298       tree found = NULL_TREE;
9299       int arg_depth;
9300       int parm_depth;
9301       int is_dependent_type;
9302       int use_partial_inst_tmpl = false;
9303 
9304       if (template_type == error_mark_node)
9305 	/* An error occurred while building the template TEMPL, and a
9306 	   diagnostic has most certainly been emitted for that
9307 	   already.  Let's propagate that error.  */
9308 	return error_mark_node;
9309 
9310       gen_tmpl = most_general_template (templ);
9311       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
9312       parm_depth = TMPL_PARMS_DEPTH (parmlist);
9313       arg_depth = TMPL_ARGS_DEPTH (arglist);
9314 
9315       if (arg_depth == 1 && parm_depth > 1)
9316 	{
9317 	  /* We've been given an incomplete set of template arguments.
9318 	     For example, given:
9319 
9320 	       template <class T> struct S1 {
9321 		 template <class U> struct S2 {};
9322 		 template <class U> struct S2<U*> {};
9323 		};
9324 
9325 	     we will be called with an ARGLIST of `U*', but the
9326 	     TEMPLATE will be `template <class T> template
9327 	     <class U> struct S1<T>::S2'.  We must fill in the missing
9328 	     arguments.  */
9329 	  tree ti = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (templ));
9330 	  arglist = add_outermost_template_args (TI_ARGS (ti), arglist);
9331 	  arg_depth = TMPL_ARGS_DEPTH (arglist);
9332 	}
9333 
9334       /* Now we should have enough arguments.  */
9335       gcc_assert (parm_depth == arg_depth);
9336 
9337       /* From here on, we're only interested in the most general
9338 	 template.  */
9339 
9340       /* Calculate the BOUND_ARGS.  These will be the args that are
9341 	 actually tsubst'd into the definition to create the
9342 	 instantiation.  */
9343       arglist = coerce_innermost_template_parms (parmlist, arglist, gen_tmpl,
9344 						 complain,
9345 						 /*require_all_args=*/true,
9346 						 /*use_default_args=*/true);
9347 
9348       if (arglist == error_mark_node)
9349 	/* We were unable to bind the arguments.  */
9350 	return error_mark_node;
9351 
9352       /* In the scope of a template class, explicit references to the
9353 	 template class refer to the type of the template, not any
9354 	 instantiation of it.  For example, in:
9355 
9356 	   template <class T> class C { void f(C<T>); }
9357 
9358 	 the `C<T>' is just the same as `C'.  Outside of the
9359 	 class, however, such a reference is an instantiation.  */
9360       if (entering_scope
9361 	  || !PRIMARY_TEMPLATE_P (gen_tmpl)
9362 	  || currently_open_class (template_type))
9363 	{
9364 	  tree tinfo = TYPE_TEMPLATE_INFO (template_type);
9365 
9366 	  if (tinfo && comp_template_args (TI_ARGS (tinfo), arglist))
9367 	    return template_type;
9368 	}
9369 
9370       /* If we already have this specialization, return it.  */
9371       elt.tmpl = gen_tmpl;
9372       elt.args = arglist;
9373       elt.spec = NULL_TREE;
9374       hash = spec_hasher::hash (&elt);
9375       entry = type_specializations->find_with_hash (&elt, hash);
9376 
9377       if (entry)
9378 	return entry->spec;
9379 
9380       /* If the the template's constraints are not satisfied,
9381          then we cannot form a valid type.
9382 
9383          Note that the check is deferred until after the hash
9384          lookup. This prevents redundant checks on previously
9385          instantiated specializations. */
9386       if (flag_concepts && !constraints_satisfied_p (gen_tmpl, arglist))
9387         {
9388           if (complain & tf_error)
9389             {
9390               error ("template constraint failure");
9391               diagnose_constraints (input_location, gen_tmpl, arglist);
9392             }
9393           return error_mark_node;
9394         }
9395 
9396       is_dependent_type = uses_template_parms (arglist);
9397 
9398       /* If the deduced arguments are invalid, then the binding
9399 	 failed.  */
9400       if (!is_dependent_type
9401 	  && check_instantiated_args (gen_tmpl,
9402 				      INNERMOST_TEMPLATE_ARGS (arglist),
9403 				      complain))
9404 	return error_mark_node;
9405 
9406       if (!is_dependent_type
9407 	  && !PRIMARY_TEMPLATE_P (gen_tmpl)
9408 	  && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
9409 	  && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
9410 	{
9411 	  found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
9412 				      DECL_NAME (gen_tmpl),
9413 				      /*tag_scope=*/ts_global);
9414 	  return found;
9415 	}
9416 
9417       context = DECL_CONTEXT (gen_tmpl);
9418       if (context && TYPE_P (context))
9419 	{
9420 	  context = tsubst_aggr_type (context, arglist, complain, in_decl, true);
9421 	  context = complete_type (context);
9422 	}
9423       else
9424 	context = tsubst (context, arglist, complain, in_decl);
9425 
9426       if (context == error_mark_node)
9427 	return error_mark_node;
9428 
9429       if (!context)
9430 	context = global_namespace;
9431 
9432       /* Create the type.  */
9433       if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9434 	{
9435 	  /* The user referred to a specialization of an alias
9436 	    template represented by GEN_TMPL.
9437 
9438 	    [temp.alias]/2 says:
9439 
9440 	        When a template-id refers to the specialization of an
9441 		alias template, it is equivalent to the associated
9442 		type obtained by substitution of its
9443 		template-arguments for the template-parameters in the
9444 		type-id of the alias template.  */
9445 
9446 	  t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
9447 	  /* Note that the call above (by indirectly calling
9448 	     register_specialization in tsubst_decl) registers the
9449 	     TYPE_DECL representing the specialization of the alias
9450 	     template.  So next time someone substitutes ARGLIST for
9451 	     the template parms into the alias template (GEN_TMPL),
9452 	     she'll get that TYPE_DECL back.  */
9453 
9454 	  if (t == error_mark_node)
9455 	    return t;
9456 	}
9457       else if (TREE_CODE (template_type) == ENUMERAL_TYPE)
9458 	{
9459 	  if (!is_dependent_type)
9460 	    {
9461 	      set_current_access_from_decl (TYPE_NAME (template_type));
9462 	      t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
9463 			      tsubst (ENUM_UNDERLYING_TYPE (template_type),
9464 				      arglist, complain, in_decl),
9465 			      tsubst_attributes (TYPE_ATTRIBUTES (template_type),
9466 						 arglist, complain, in_decl),
9467 			      SCOPED_ENUM_P (template_type), NULL);
9468 
9469 	      if (t == error_mark_node)
9470 		return t;
9471 	    }
9472 	  else
9473             {
9474               /* We don't want to call start_enum for this type, since
9475                  the values for the enumeration constants may involve
9476                  template parameters.  And, no one should be interested
9477                  in the enumeration constants for such a type.  */
9478               t = cxx_make_type (ENUMERAL_TYPE);
9479               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
9480             }
9481           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
9482 	  ENUM_FIXED_UNDERLYING_TYPE_P (t)
9483 	    = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
9484 	}
9485       else if (CLASS_TYPE_P (template_type))
9486 	{
9487 	  /* Lambda closures are regenerated in tsubst_lambda_expr, not
9488 	     instantiated here.  */
9489 	  gcc_assert (!LAMBDA_TYPE_P (template_type));
9490 
9491 	  t = make_class_type (TREE_CODE (template_type));
9492 	  CLASSTYPE_DECLARED_CLASS (t)
9493 	    = CLASSTYPE_DECLARED_CLASS (template_type);
9494 	  SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
9495 
9496 	  /* A local class.  Make sure the decl gets registered properly.  */
9497 	  if (context == current_function_decl)
9498 	    if (pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current)
9499 		== error_mark_node)
9500 	      return error_mark_node;
9501 
9502 	  if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
9503 	    /* This instantiation is another name for the primary
9504 	       template type. Set the TYPE_CANONICAL field
9505 	       appropriately. */
9506 	    TYPE_CANONICAL (t) = template_type;
9507 	  else if (any_template_arguments_need_structural_equality_p (arglist))
9508 	    /* Some of the template arguments require structural
9509 	       equality testing, so this template class requires
9510 	       structural equality testing. */
9511 	    SET_TYPE_STRUCTURAL_EQUALITY (t);
9512 	}
9513       else
9514 	gcc_unreachable ();
9515 
9516       /* If we called start_enum or pushtag above, this information
9517 	 will already be set up.  */
9518       if (!TYPE_NAME (t))
9519 	{
9520 	  TYPE_CONTEXT (t) = FROB_CONTEXT (context);
9521 
9522 	  type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
9523 	  DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
9524 	  DECL_SOURCE_LOCATION (type_decl)
9525 	    = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
9526 	}
9527       else
9528 	type_decl = TYPE_NAME (t);
9529 
9530       if (CLASS_TYPE_P (template_type))
9531 	{
9532 	  TREE_PRIVATE (type_decl)
9533 	    = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
9534 	  TREE_PROTECTED (type_decl)
9535 	    = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
9536 	  if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
9537 	    {
9538 	      DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
9539 	      DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
9540 	    }
9541 	}
9542 
9543       if (OVERLOAD_TYPE_P (t)
9544 	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9545 	{
9546 	  static const char *tags[] = {"abi_tag", "may_alias"};
9547 
9548 	  for (unsigned ix = 0; ix != 2; ix++)
9549 	    {
9550 	      tree attributes
9551 		= lookup_attribute (tags[ix], TYPE_ATTRIBUTES (template_type));
9552 
9553 	      if (attributes)
9554 		TYPE_ATTRIBUTES (t)
9555 		  = tree_cons (TREE_PURPOSE (attributes),
9556 			       TREE_VALUE (attributes),
9557 			       TYPE_ATTRIBUTES (t));
9558 	    }
9559 	}
9560 
9561       /* Let's consider the explicit specialization of a member
9562          of a class template specialization that is implicitly instantiated,
9563 	 e.g.:
9564 	     template<class T>
9565 	     struct S
9566 	     {
9567 	       template<class U> struct M {}; //#0
9568 	     };
9569 
9570 	     template<>
9571 	     template<>
9572 	     struct S<int>::M<char> //#1
9573 	     {
9574 	       int i;
9575 	     };
9576 	[temp.expl.spec]/4 says this is valid.
9577 
9578 	In this case, when we write:
9579 	S<int>::M<char> m;
9580 
9581 	M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
9582 	the one of #0.
9583 
9584 	When we encounter #1, we want to store the partial instantiation
9585 	of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
9586 
9587 	For all cases other than this "explicit specialization of member of a
9588 	class template", we just want to store the most general template into
9589 	the CLASSTYPE_TI_TEMPLATE of M.
9590 
9591 	This case of "explicit specialization of member of a class template"
9592 	only happens when:
9593 	1/ the enclosing class is an instantiation of, and therefore not
9594 	the same as, the context of the most general template, and
9595 	2/ we aren't looking at the partial instantiation itself, i.e.
9596 	the innermost arguments are not the same as the innermost parms of
9597 	the most general template.
9598 
9599 	So it's only when 1/ and 2/ happens that we want to use the partial
9600 	instantiation of the member template in lieu of its most general
9601 	template.  */
9602 
9603       if (PRIMARY_TEMPLATE_P (gen_tmpl)
9604 	  && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
9605 	  /* the enclosing class must be an instantiation...  */
9606 	  && CLASS_TYPE_P (context)
9607 	  && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
9608 	{
9609 	  TREE_VEC_LENGTH (arglist)--;
9610 	  ++processing_template_decl;
9611 	  tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (gen_tmpl));
9612 	  tree partial_inst_args =
9613 	    tsubst (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)),
9614 		    arglist, complain, NULL_TREE);
9615 	  --processing_template_decl;
9616 	  TREE_VEC_LENGTH (arglist)++;
9617 	  if (partial_inst_args == error_mark_node)
9618 	    return error_mark_node;
9619 	  use_partial_inst_tmpl =
9620 	    /*...and we must not be looking at the partial instantiation
9621 	     itself. */
9622 	    !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
9623 				 partial_inst_args);
9624 	}
9625 
9626       if (!use_partial_inst_tmpl)
9627 	/* This case is easy; there are no member templates involved.  */
9628 	found = gen_tmpl;
9629       else
9630 	{
9631 	  /* This is a full instantiation of a member template.  Find
9632 	     the partial instantiation of which this is an instance.  */
9633 
9634 	  /* Temporarily reduce by one the number of levels in the ARGLIST
9635 	     so as to avoid comparing the last set of arguments.  */
9636 	  TREE_VEC_LENGTH (arglist)--;
9637 	  found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
9638 	  TREE_VEC_LENGTH (arglist)++;
9639 	  /* FOUND is either a proper class type, or an alias
9640 	     template specialization.  In the later case, it's a
9641 	     TYPE_DECL, resulting from the substituting of arguments
9642 	     for parameters in the TYPE_DECL of the alias template
9643 	     done earlier.  So be careful while getting the template
9644 	     of FOUND.  */
9645 	  found = (TREE_CODE (found) == TEMPLATE_DECL
9646 		   ? found
9647 		   : (TREE_CODE (found) == TYPE_DECL
9648 		      ? DECL_TI_TEMPLATE (found)
9649 		      : CLASSTYPE_TI_TEMPLATE (found)));
9650 	}
9651 
9652       // Build template info for the new specialization.
9653       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
9654 
9655       elt.spec = t;
9656       slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
9657       entry = ggc_alloc<spec_entry> ();
9658       *entry = elt;
9659       *slot = entry;
9660 
9661       /* Note this use of the partial instantiation so we can check it
9662 	 later in maybe_process_partial_specialization.  */
9663       DECL_TEMPLATE_INSTANTIATIONS (found)
9664 	= tree_cons (arglist, t,
9665 		     DECL_TEMPLATE_INSTANTIATIONS (found));
9666 
9667       if (TREE_CODE (template_type) == ENUMERAL_TYPE && !is_dependent_type
9668 	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9669 	/* Now that the type has been registered on the instantiations
9670 	   list, we set up the enumerators.  Because the enumeration
9671 	   constants may involve the enumeration type itself, we make
9672 	   sure to register the type first, and then create the
9673 	   constants.  That way, doing tsubst_expr for the enumeration
9674 	   constants won't result in recursive calls here; we'll find
9675 	   the instantiation and exit above.  */
9676 	tsubst_enum (template_type, t, arglist);
9677 
9678       if (CLASS_TYPE_P (template_type) && is_dependent_type)
9679 	/* If the type makes use of template parameters, the
9680 	   code that generates debugging information will crash.  */
9681 	DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
9682 
9683       /* Possibly limit visibility based on template args.  */
9684       TREE_PUBLIC (type_decl) = 1;
9685       determine_visibility (type_decl);
9686 
9687       inherit_targ_abi_tags (t);
9688 
9689       return t;
9690     }
9691 }
9692 
9693 /* Wrapper for lookup_template_class_1.  */
9694 
9695 tree
lookup_template_class(tree d1,tree arglist,tree in_decl,tree context,int entering_scope,tsubst_flags_t complain)9696 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
9697                        int entering_scope, tsubst_flags_t complain)
9698 {
9699   tree ret;
9700   timevar_push (TV_TEMPLATE_INST);
9701   ret = lookup_template_class_1 (d1, arglist, in_decl, context,
9702                                  entering_scope, complain);
9703   timevar_pop (TV_TEMPLATE_INST);
9704   return ret;
9705 }
9706 
9707 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST.  */
9708 
9709 tree
lookup_template_variable(tree templ,tree arglist)9710 lookup_template_variable (tree templ, tree arglist)
9711 {
9712   /* The type of the expression is NULL_TREE since the template-id could refer
9713      to an explicit or partial specialization. */
9714   tree type = NULL_TREE;
9715   if (flag_concepts && variable_concept_p (templ))
9716     /* Except that concepts are always bool.  */
9717     type = boolean_type_node;
9718   return build2 (TEMPLATE_ID_EXPR, type, templ, arglist);
9719 }
9720 
9721 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR for use. */
9722 
9723 tree
finish_template_variable(tree var,tsubst_flags_t complain)9724 finish_template_variable (tree var, tsubst_flags_t complain)
9725 {
9726   tree templ = TREE_OPERAND (var, 0);
9727   tree arglist = TREE_OPERAND (var, 1);
9728 
9729   /* We never want to return a VAR_DECL for a variable concept, since they
9730      aren't instantiated.  In a template, leave the TEMPLATE_ID_EXPR alone.  */
9731   bool concept_p = flag_concepts && variable_concept_p (templ);
9732   if (concept_p && processing_template_decl)
9733     return var;
9734 
9735   tree tmpl_args = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (templ));
9736   arglist = add_outermost_template_args (tmpl_args, arglist);
9737 
9738   templ = most_general_template (templ);
9739   tree parms = DECL_TEMPLATE_PARMS (templ);
9740   arglist = coerce_innermost_template_parms (parms, arglist, templ, complain,
9741 					     /*req_all*/true,
9742 					     /*use_default*/true);
9743 
9744   if (flag_concepts && !constraints_satisfied_p (templ, arglist))
9745     {
9746       if (complain & tf_error)
9747 	{
9748 	  error ("use of invalid variable template %qE", var);
9749 	  diagnose_constraints (location_of (var), templ, arglist);
9750 	}
9751       return error_mark_node;
9752     }
9753 
9754   /* If a template-id refers to a specialization of a variable
9755      concept, then the expression is true if and only if the
9756      concept's constraints are satisfied by the given template
9757      arguments.
9758 
9759      NOTE: This is an extension of Concepts Lite TS that
9760      allows constraints to be used in expressions. */
9761   if (concept_p)
9762     {
9763       tree decl = DECL_TEMPLATE_RESULT (templ);
9764       return evaluate_variable_concept (decl, arglist);
9765     }
9766 
9767   return instantiate_template (templ, arglist, complain);
9768 }
9769 
9770 /* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
9771    TARGS template args, and instantiate it if it's not dependent.  */
9772 
9773 tree
lookup_and_finish_template_variable(tree templ,tree targs,tsubst_flags_t complain)9774 lookup_and_finish_template_variable (tree templ, tree targs,
9775 				     tsubst_flags_t complain)
9776 {
9777   templ = lookup_template_variable (templ, targs);
9778   if (!any_dependent_template_arguments_p (targs))
9779     {
9780       templ = finish_template_variable (templ, complain);
9781       mark_used (templ);
9782     }
9783 
9784   return convert_from_reference (templ);
9785 }
9786 
9787 
9788 struct pair_fn_data
9789 {
9790   tree_fn_t fn;
9791   tree_fn_t any_fn;
9792   void *data;
9793   /* True when we should also visit template parameters that occur in
9794      non-deduced contexts.  */
9795   bool include_nondeduced_p;
9796   hash_set<tree> *visited;
9797 };
9798 
9799 /* Called from for_each_template_parm via walk_tree.  */
9800 
9801 static tree
for_each_template_parm_r(tree * tp,int * walk_subtrees,void * d)9802 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
9803 {
9804   tree t = *tp;
9805   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
9806   tree_fn_t fn = pfd->fn;
9807   void *data = pfd->data;
9808   tree result = NULL_TREE;
9809 
9810 #define WALK_SUBTREE(NODE)						\
9811   do									\
9812     {									\
9813       result = for_each_template_parm (NODE, fn, data, pfd->visited,	\
9814 				       pfd->include_nondeduced_p,	\
9815 				       pfd->any_fn);			\
9816       if (result) goto out;						\
9817     }									\
9818   while (0)
9819 
9820   if (pfd->any_fn && (*pfd->any_fn)(t, data))
9821     return t;
9822 
9823   if (TYPE_P (t)
9824       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
9825     WALK_SUBTREE (TYPE_CONTEXT (t));
9826 
9827   switch (TREE_CODE (t))
9828     {
9829     case RECORD_TYPE:
9830       if (TYPE_PTRMEMFUNC_P (t))
9831 	break;
9832       /* Fall through.  */
9833 
9834     case UNION_TYPE:
9835     case ENUMERAL_TYPE:
9836       if (!TYPE_TEMPLATE_INFO (t))
9837 	*walk_subtrees = 0;
9838       else
9839 	WALK_SUBTREE (TYPE_TI_ARGS (t));
9840       break;
9841 
9842     case INTEGER_TYPE:
9843       WALK_SUBTREE (TYPE_MIN_VALUE (t));
9844       WALK_SUBTREE (TYPE_MAX_VALUE (t));
9845       break;
9846 
9847     case METHOD_TYPE:
9848       /* Since we're not going to walk subtrees, we have to do this
9849 	 explicitly here.  */
9850       WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
9851       /* Fall through.  */
9852 
9853     case FUNCTION_TYPE:
9854       /* Check the return type.  */
9855       WALK_SUBTREE (TREE_TYPE (t));
9856 
9857       /* Check the parameter types.  Since default arguments are not
9858 	 instantiated until they are needed, the TYPE_ARG_TYPES may
9859 	 contain expressions that involve template parameters.  But,
9860 	 no-one should be looking at them yet.  And, once they're
9861 	 instantiated, they don't contain template parameters, so
9862 	 there's no point in looking at them then, either.  */
9863       {
9864 	tree parm;
9865 
9866 	for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
9867 	  WALK_SUBTREE (TREE_VALUE (parm));
9868 
9869 	/* Since we've already handled the TYPE_ARG_TYPES, we don't
9870 	   want walk_tree walking into them itself.  */
9871 	*walk_subtrees = 0;
9872       }
9873 
9874       if (flag_noexcept_type)
9875 	{
9876 	  tree spec = TYPE_RAISES_EXCEPTIONS (t);
9877 	  if (spec)
9878 	    WALK_SUBTREE (TREE_PURPOSE (spec));
9879 	}
9880       break;
9881 
9882     case TYPEOF_TYPE:
9883     case DECLTYPE_TYPE:
9884     case UNDERLYING_TYPE:
9885       if (pfd->include_nondeduced_p
9886 	  && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
9887 				     pfd->visited,
9888 				     pfd->include_nondeduced_p,
9889 				     pfd->any_fn))
9890 	return error_mark_node;
9891       *walk_subtrees = false;
9892       break;
9893 
9894     case FUNCTION_DECL:
9895     case VAR_DECL:
9896       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
9897 	WALK_SUBTREE (DECL_TI_ARGS (t));
9898       /* Fall through.  */
9899 
9900     case PARM_DECL:
9901     case CONST_DECL:
9902       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t))
9903 	WALK_SUBTREE (DECL_INITIAL (t));
9904       if (DECL_CONTEXT (t)
9905 	  && pfd->include_nondeduced_p)
9906 	WALK_SUBTREE (DECL_CONTEXT (t));
9907       break;
9908 
9909     case BOUND_TEMPLATE_TEMPLATE_PARM:
9910       /* Record template parameters such as `T' inside `TT<T>'.  */
9911       WALK_SUBTREE (TYPE_TI_ARGS (t));
9912       /* Fall through.  */
9913 
9914     case TEMPLATE_TEMPLATE_PARM:
9915     case TEMPLATE_TYPE_PARM:
9916     case TEMPLATE_PARM_INDEX:
9917       if (fn && (*fn)(t, data))
9918 	return t;
9919       else if (!fn)
9920 	return t;
9921       break;
9922 
9923     case TEMPLATE_DECL:
9924       /* A template template parameter is encountered.  */
9925       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9926 	WALK_SUBTREE (TREE_TYPE (t));
9927 
9928       /* Already substituted template template parameter */
9929       *walk_subtrees = 0;
9930       break;
9931 
9932     case TYPENAME_TYPE:
9933       /* A template-id in a TYPENAME_TYPE might be a deduced context after
9934 	 partial instantiation.  */
9935       WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
9936       break;
9937 
9938     case CONSTRUCTOR:
9939       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
9940 	  && pfd->include_nondeduced_p)
9941 	WALK_SUBTREE (TYPE_PTRMEMFUNC_FN_TYPE (TREE_TYPE (t)));
9942       break;
9943 
9944     case INDIRECT_REF:
9945     case COMPONENT_REF:
9946       /* If there's no type, then this thing must be some expression
9947 	 involving template parameters.  */
9948       if (!fn && !TREE_TYPE (t))
9949 	return error_mark_node;
9950       break;
9951 
9952     case MODOP_EXPR:
9953     case CAST_EXPR:
9954     case IMPLICIT_CONV_EXPR:
9955     case REINTERPRET_CAST_EXPR:
9956     case CONST_CAST_EXPR:
9957     case STATIC_CAST_EXPR:
9958     case DYNAMIC_CAST_EXPR:
9959     case ARROW_EXPR:
9960     case DOTSTAR_EXPR:
9961     case TYPEID_EXPR:
9962     case PSEUDO_DTOR_EXPR:
9963       if (!fn)
9964 	return error_mark_node;
9965       break;
9966 
9967     default:
9968       break;
9969     }
9970 
9971   #undef WALK_SUBTREE
9972 
9973   /* We didn't find any template parameters we liked.  */
9974  out:
9975   return result;
9976 }
9977 
9978 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
9979    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
9980    call FN with the parameter and the DATA.
9981    If FN returns nonzero, the iteration is terminated, and
9982    for_each_template_parm returns 1.  Otherwise, the iteration
9983    continues.  If FN never returns a nonzero value, the value
9984    returned by for_each_template_parm is 0.  If FN is NULL, it is
9985    considered to be the function which always returns 1.
9986 
9987    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
9988    parameters that occur in non-deduced contexts.  When false, only
9989    visits those template parameters that can be deduced.  */
9990 
9991 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)9992 for_each_template_parm (tree t, tree_fn_t fn, void* data,
9993 			hash_set<tree> *visited,
9994 			bool include_nondeduced_p,
9995 			tree_fn_t any_fn)
9996 {
9997   struct pair_fn_data pfd;
9998   tree result;
9999 
10000   /* Set up.  */
10001   pfd.fn = fn;
10002   pfd.any_fn = any_fn;
10003   pfd.data = data;
10004   pfd.include_nondeduced_p = include_nondeduced_p;
10005 
10006   /* Walk the tree.  (Conceptually, we would like to walk without
10007      duplicates, but for_each_template_parm_r recursively calls
10008      for_each_template_parm, so we would need to reorganize a fair
10009      bit to use walk_tree_without_duplicates, so we keep our own
10010      visited list.)  */
10011   if (visited)
10012     pfd.visited = visited;
10013   else
10014     pfd.visited = new hash_set<tree>;
10015   result = cp_walk_tree (&t,
10016 		         for_each_template_parm_r,
10017 		         &pfd,
10018 		         pfd.visited);
10019 
10020   /* Clean up.  */
10021   if (!visited)
10022     {
10023       delete pfd.visited;
10024       pfd.visited = 0;
10025     }
10026 
10027   return result;
10028 }
10029 
10030 /* Returns true if T depends on any template parameter.  */
10031 
10032 int
uses_template_parms(tree t)10033 uses_template_parms (tree t)
10034 {
10035   if (t == NULL_TREE)
10036     return false;
10037 
10038   bool dependent_p;
10039   int saved_processing_template_decl;
10040 
10041   saved_processing_template_decl = processing_template_decl;
10042   if (!saved_processing_template_decl)
10043     processing_template_decl = 1;
10044   if (TYPE_P (t))
10045     dependent_p = dependent_type_p (t);
10046   else if (TREE_CODE (t) == TREE_VEC)
10047     dependent_p = any_dependent_template_arguments_p (t);
10048   else if (TREE_CODE (t) == TREE_LIST)
10049     dependent_p = (uses_template_parms (TREE_VALUE (t))
10050 		   || uses_template_parms (TREE_CHAIN (t)));
10051   else if (TREE_CODE (t) == TYPE_DECL)
10052     dependent_p = dependent_type_p (TREE_TYPE (t));
10053   else if (DECL_P (t)
10054 	   || EXPR_P (t)
10055 	   || TREE_CODE (t) == TEMPLATE_PARM_INDEX
10056 	   || TREE_CODE (t) == OVERLOAD
10057 	   || BASELINK_P (t)
10058 	   || identifier_p (t)
10059 	   || TREE_CODE (t) == TRAIT_EXPR
10060 	   || TREE_CODE (t) == CONSTRUCTOR
10061 	   || CONSTANT_CLASS_P (t))
10062     dependent_p = (type_dependent_expression_p (t)
10063 		   || value_dependent_expression_p (t));
10064   else
10065     {
10066       gcc_assert (t == error_mark_node);
10067       dependent_p = false;
10068     }
10069 
10070   processing_template_decl = saved_processing_template_decl;
10071 
10072   return dependent_p;
10073 }
10074 
10075 /* Returns true iff current_function_decl is an incompletely instantiated
10076    template.  Useful instead of processing_template_decl because the latter
10077    is set to 0 during instantiate_non_dependent_expr.  */
10078 
10079 bool
in_template_function(void)10080 in_template_function (void)
10081 {
10082   tree fn = current_function_decl;
10083   bool ret;
10084   ++processing_template_decl;
10085   ret = (fn && DECL_LANG_SPECIFIC (fn)
10086 	 && DECL_TEMPLATE_INFO (fn)
10087 	 && any_dependent_template_arguments_p (DECL_TI_ARGS (fn)));
10088   --processing_template_decl;
10089   return ret;
10090 }
10091 
10092 /* Returns true if T depends on any template parameter with level LEVEL.  */
10093 
10094 bool
uses_template_parms_level(tree t,int level)10095 uses_template_parms_level (tree t, int level)
10096 {
10097   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
10098 				 /*include_nondeduced_p=*/true);
10099 }
10100 
10101 /* Returns true if the signature of DECL depends on any template parameter from
10102    its enclosing class.  */
10103 
10104 bool
uses_outer_template_parms(tree decl)10105 uses_outer_template_parms (tree decl)
10106 {
10107   int depth = template_class_depth (CP_DECL_CONTEXT (decl));
10108   if (depth == 0)
10109     return false;
10110   if (for_each_template_parm (TREE_TYPE (decl), template_parm_outer_level,
10111 			      &depth, NULL, /*include_nondeduced_p=*/true))
10112     return true;
10113   if (PRIMARY_TEMPLATE_P (decl)
10114       && for_each_template_parm (INNERMOST_TEMPLATE_PARMS
10115 				 (DECL_TEMPLATE_PARMS (decl)),
10116 				 template_parm_outer_level,
10117 				 &depth, NULL, /*include_nondeduced_p=*/true))
10118     return true;
10119   tree ci = get_constraints (decl);
10120   if (ci)
10121     ci = CI_ASSOCIATED_CONSTRAINTS (ci);
10122   if (ci && for_each_template_parm (ci, template_parm_outer_level,
10123 				    &depth, NULL, /*nondeduced*/true))
10124     return true;
10125   return false;
10126 }
10127 
10128 /* Returns TRUE iff INST is an instantiation we don't need to do in an
10129    ill-formed translation unit, i.e. a variable or function that isn't
10130    usable in a constant expression.  */
10131 
10132 static inline bool
neglectable_inst_p(tree d)10133 neglectable_inst_p (tree d)
10134 {
10135   return (d && DECL_P (d)
10136 	  && !undeduced_auto_decl (d)
10137 	  && !(TREE_CODE (d) == FUNCTION_DECL ? DECL_DECLARED_CONSTEXPR_P (d)
10138 	       : decl_maybe_constant_var_p (d)));
10139 }
10140 
10141 /* Returns TRUE iff we should refuse to instantiate DECL because it's
10142    neglectable and instantiated from within an erroneous instantiation.  */
10143 
10144 static bool
limit_bad_template_recursion(tree decl)10145 limit_bad_template_recursion (tree decl)
10146 {
10147   struct tinst_level *lev = current_tinst_level;
10148   int errs = errorcount + sorrycount;
10149   if (lev == NULL || errs == 0 || !neglectable_inst_p (decl))
10150     return false;
10151 
10152   for (; lev; lev = lev->next)
10153     if (neglectable_inst_p (lev->maybe_get_node ()))
10154       break;
10155 
10156   return (lev && errs > lev->errors);
10157 }
10158 
10159 static int tinst_depth;
10160 extern int max_tinst_depth;
10161 int depth_reached;
10162 
10163 static GTY(()) struct tinst_level *last_error_tinst_level;
10164 
10165 /* We're starting to instantiate D; record the template instantiation context
10166    at LOC for diagnostics and to restore it later.  */
10167 
10168 static bool
push_tinst_level_loc(tree tldcl,tree targs,location_t loc)10169 push_tinst_level_loc (tree tldcl, tree targs, location_t loc)
10170 {
10171   struct tinst_level *new_level;
10172 
10173   if (tinst_depth >= max_tinst_depth)
10174     {
10175       /* Tell error.c not to try to instantiate any templates.  */
10176       at_eof = 2;
10177       fatal_error (input_location,
10178 		   "template instantiation depth exceeds maximum of %d"
10179                    " (use -ftemplate-depth= to increase the maximum)",
10180                    max_tinst_depth);
10181       return false;
10182     }
10183 
10184   /* If the current instantiation caused problems, don't let it instantiate
10185      anything else.  Do allow deduction substitution and decls usable in
10186      constant expressions.  */
10187   if (!targs && limit_bad_template_recursion (tldcl))
10188     return false;
10189 
10190   /* When not -quiet, dump template instantiations other than functions, since
10191      announce_function will take care of those.  */
10192   if (!quiet_flag && !targs
10193       && TREE_CODE (tldcl) != TREE_LIST
10194       && TREE_CODE (tldcl) != FUNCTION_DECL)
10195     fprintf (stderr, " %s", decl_as_string (tldcl, TFF_DECL_SPECIFIERS));
10196 
10197   new_level = tinst_level_freelist ().alloc ();
10198   new_level->tldcl = tldcl;
10199   new_level->targs = targs;
10200   new_level->locus = loc;
10201   new_level->errors = errorcount + sorrycount;
10202   new_level->next = NULL;
10203   new_level->refcount = 0;
10204   set_refcount_ptr (new_level->next, current_tinst_level);
10205   set_refcount_ptr (current_tinst_level, new_level);
10206 
10207   ++tinst_depth;
10208   if (GATHER_STATISTICS && (tinst_depth > depth_reached))
10209     depth_reached = tinst_depth;
10210 
10211   return true;
10212 }
10213 
10214 /* We're starting substitution of TMPL<ARGS>; record the template
10215    substitution context for diagnostics and to restore it later.  */
10216 
10217 static bool
push_tinst_level(tree tmpl,tree args)10218 push_tinst_level (tree tmpl, tree args)
10219 {
10220   return push_tinst_level_loc (tmpl, args, input_location);
10221 }
10222 
10223 /* We're starting to instantiate D; record INPUT_LOCATION and the
10224    template instantiation context for diagnostics and to restore it
10225    later.  */
10226 
10227 bool
push_tinst_level(tree d)10228 push_tinst_level (tree d)
10229 {
10230   return push_tinst_level_loc (d, input_location);
10231 }
10232 
10233 /* Likewise, but record LOC as the program location.  */
10234 
10235 bool
push_tinst_level_loc(tree d,location_t loc)10236 push_tinst_level_loc (tree d, location_t loc)
10237 {
10238   gcc_assert (TREE_CODE (d) != TREE_LIST);
10239   return push_tinst_level_loc (d, NULL, loc);
10240 }
10241 
10242 /* We're done instantiating this template; return to the instantiation
10243    context.  */
10244 
10245 void
pop_tinst_level(void)10246 pop_tinst_level (void)
10247 {
10248   /* Restore the filename and line number stashed away when we started
10249      this instantiation.  */
10250   input_location = current_tinst_level->locus;
10251   set_refcount_ptr (current_tinst_level, current_tinst_level->next);
10252   --tinst_depth;
10253 }
10254 
10255 /* We're instantiating a deferred template; restore the template
10256    instantiation context in which the instantiation was requested, which
10257    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
10258 
10259 static tree
reopen_tinst_level(struct tinst_level * level)10260 reopen_tinst_level (struct tinst_level *level)
10261 {
10262   struct tinst_level *t;
10263 
10264   tinst_depth = 0;
10265   for (t = level; t; t = t->next)
10266     ++tinst_depth;
10267 
10268   set_refcount_ptr (current_tinst_level, level);
10269   pop_tinst_level ();
10270   if (current_tinst_level)
10271     current_tinst_level->errors = errorcount+sorrycount;
10272   return level->maybe_get_node ();
10273 }
10274 
10275 /* Returns the TINST_LEVEL which gives the original instantiation
10276    context.  */
10277 
10278 struct tinst_level *
outermost_tinst_level(void)10279 outermost_tinst_level (void)
10280 {
10281   struct tinst_level *level = current_tinst_level;
10282   if (level)
10283     while (level->next)
10284       level = level->next;
10285   return level;
10286 }
10287 
10288 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
10289    vector of template arguments, as for tsubst.
10290 
10291    Returns an appropriate tsubst'd friend declaration.  */
10292 
10293 static tree
tsubst_friend_function(tree decl,tree args)10294 tsubst_friend_function (tree decl, tree args)
10295 {
10296   tree new_friend;
10297 
10298   if (TREE_CODE (decl) == FUNCTION_DECL
10299       && DECL_TEMPLATE_INSTANTIATION (decl)
10300       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
10301     /* This was a friend declared with an explicit template
10302        argument list, e.g.:
10303 
10304        friend void f<>(T);
10305 
10306        to indicate that f was a template instantiation, not a new
10307        function declaration.  Now, we have to figure out what
10308        instantiation of what template.  */
10309     {
10310       tree template_id, arglist, fns;
10311       tree new_args;
10312       tree tmpl;
10313       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
10314 
10315       /* Friend functions are looked up in the containing namespace scope.
10316 	 We must enter that scope, to avoid finding member functions of the
10317 	 current class with same name.  */
10318       push_nested_namespace (ns);
10319       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
10320 			 tf_warning_or_error, NULL_TREE,
10321 			 /*integral_constant_expression_p=*/false);
10322       pop_nested_namespace (ns);
10323       arglist = tsubst (DECL_TI_ARGS (decl), args,
10324 			tf_warning_or_error, NULL_TREE);
10325       template_id = lookup_template_function (fns, arglist);
10326 
10327       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
10328       tmpl = determine_specialization (template_id, new_friend,
10329 				       &new_args,
10330 				       /*need_member_template=*/0,
10331 				       TREE_VEC_LENGTH (args),
10332 				       tsk_none);
10333       return instantiate_template (tmpl, new_args, tf_error);
10334     }
10335 
10336   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
10337 
10338   /* The NEW_FRIEND will look like an instantiation, to the
10339      compiler, but is not an instantiation from the point of view of
10340      the language.  For example, we might have had:
10341 
10342      template <class T> struct S {
10343        template <class U> friend void f(T, U);
10344      };
10345 
10346      Then, in S<int>, template <class U> void f(int, U) is not an
10347      instantiation of anything.  */
10348   if (new_friend == error_mark_node)
10349     return error_mark_node;
10350 
10351   DECL_USE_TEMPLATE (new_friend) = 0;
10352   if (TREE_CODE (decl) == TEMPLATE_DECL)
10353     {
10354       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
10355       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
10356 	= DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
10357     }
10358 
10359   /* The mangled name for the NEW_FRIEND is incorrect.  The function
10360      is not a template instantiation and should not be mangled like
10361      one.  Therefore, we forget the mangling here; we'll recompute it
10362      later if we need it.  */
10363   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
10364     {
10365       SET_DECL_RTL (new_friend, NULL);
10366       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
10367     }
10368 
10369   if (DECL_NAMESPACE_SCOPE_P (new_friend))
10370     {
10371       tree old_decl;
10372       tree new_friend_template_info;
10373       tree new_friend_result_template_info;
10374       tree ns;
10375       int  new_friend_is_defn;
10376 
10377       /* We must save some information from NEW_FRIEND before calling
10378 	 duplicate decls since that function will free NEW_FRIEND if
10379 	 possible.  */
10380       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
10381       new_friend_is_defn =
10382 	    (DECL_INITIAL (DECL_TEMPLATE_RESULT
10383 			   (template_for_substitution (new_friend)))
10384 	     != NULL_TREE);
10385       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
10386 	{
10387 	  /* This declaration is a `primary' template.  */
10388 	  DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
10389 
10390 	  new_friend_result_template_info
10391 	    = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
10392 	}
10393       else
10394 	new_friend_result_template_info = NULL_TREE;
10395 
10396       /* Inside pushdecl_namespace_level, we will push into the
10397 	 current namespace. However, the friend function should go
10398 	 into the namespace of the template.  */
10399       ns = decl_namespace_context (new_friend);
10400       push_nested_namespace (ns);
10401       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
10402       pop_nested_namespace (ns);
10403 
10404       if (old_decl == error_mark_node)
10405 	return error_mark_node;
10406 
10407       if (old_decl != new_friend)
10408 	{
10409 	  /* This new friend declaration matched an existing
10410 	     declaration.  For example, given:
10411 
10412 	       template <class T> void f(T);
10413 	       template <class U> class C {
10414 		 template <class T> friend void f(T) {}
10415 	       };
10416 
10417 	     the friend declaration actually provides the definition
10418 	     of `f', once C has been instantiated for some type.  So,
10419 	     old_decl will be the out-of-class template declaration,
10420 	     while new_friend is the in-class definition.
10421 
10422 	     But, if `f' was called before this point, the
10423 	     instantiation of `f' will have DECL_TI_ARGS corresponding
10424 	     to `T' but not to `U', references to which might appear
10425 	     in the definition of `f'.  Previously, the most general
10426 	     template for an instantiation of `f' was the out-of-class
10427 	     version; now it is the in-class version.  Therefore, we
10428 	     run through all specialization of `f', adding to their
10429 	     DECL_TI_ARGS appropriately.  In particular, they need a
10430 	     new set of outer arguments, corresponding to the
10431 	     arguments for this class instantiation.
10432 
10433 	     The same situation can arise with something like this:
10434 
10435 	       friend void f(int);
10436 	       template <class T> class C {
10437 		 friend void f(T) {}
10438 	       };
10439 
10440 	     when `C<int>' is instantiated.  Now, `f(int)' is defined
10441 	     in the class.  */
10442 
10443 	  if (!new_friend_is_defn)
10444 	    /* On the other hand, if the in-class declaration does
10445 	       *not* provide a definition, then we don't want to alter
10446 	       existing definitions.  We can just leave everything
10447 	       alone.  */
10448 	    ;
10449 	  else
10450 	    {
10451 	      tree new_template = TI_TEMPLATE (new_friend_template_info);
10452 	      tree new_args = TI_ARGS (new_friend_template_info);
10453 
10454 	      /* Overwrite whatever template info was there before, if
10455 		 any, with the new template information pertaining to
10456 		 the declaration.  */
10457 	      DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
10458 
10459 	      if (TREE_CODE (old_decl) != TEMPLATE_DECL)
10460 		{
10461 		  /* We should have called reregister_specialization in
10462 		     duplicate_decls.  */
10463 		  gcc_assert (retrieve_specialization (new_template,
10464 						       new_args, 0)
10465 			      == old_decl);
10466 
10467 		  /* Instantiate it if the global has already been used.  */
10468 		  if (DECL_ODR_USED (old_decl))
10469 		    instantiate_decl (old_decl, /*defer_ok=*/true,
10470 				      /*expl_inst_class_mem_p=*/false);
10471 		}
10472 	      else
10473 		{
10474 		  tree t;
10475 
10476 		  /* Indicate that the old function template is a partial
10477 		     instantiation.  */
10478 		  DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
10479 		    = new_friend_result_template_info;
10480 
10481 		  gcc_assert (new_template
10482 			      == most_general_template (new_template));
10483 		  gcc_assert (new_template != old_decl);
10484 
10485 		  /* Reassign any specializations already in the hash table
10486 		     to the new more general template, and add the
10487 		     additional template args.  */
10488 		  for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
10489 		       t != NULL_TREE;
10490 		       t = TREE_CHAIN (t))
10491 		    {
10492 		      tree spec = TREE_VALUE (t);
10493 		      spec_entry elt;
10494 
10495 		      elt.tmpl = old_decl;
10496 		      elt.args = DECL_TI_ARGS (spec);
10497 		      elt.spec = NULL_TREE;
10498 
10499 		      decl_specializations->remove_elt (&elt);
10500 
10501 		      DECL_TI_ARGS (spec)
10502 			= add_outermost_template_args (new_args,
10503 						       DECL_TI_ARGS (spec));
10504 
10505 		      register_specialization
10506 			(spec, new_template, DECL_TI_ARGS (spec), true, 0);
10507 
10508 		    }
10509 		  DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
10510 		}
10511 	    }
10512 
10513 	  /* The information from NEW_FRIEND has been merged into OLD_DECL
10514 	     by duplicate_decls.  */
10515 	  new_friend = old_decl;
10516 	}
10517     }
10518   else
10519     {
10520       tree context = DECL_CONTEXT (new_friend);
10521       bool dependent_p;
10522 
10523       /* In the code
10524 	   template <class T> class C {
10525 	     template <class U> friend void C1<U>::f (); // case 1
10526 	     friend void C2<T>::f ();			 // case 2
10527 	   };
10528 	 we only need to make sure CONTEXT is a complete type for
10529 	 case 2.  To distinguish between the two cases, we note that
10530 	 CONTEXT of case 1 remains dependent type after tsubst while
10531 	 this isn't true for case 2.  */
10532       ++processing_template_decl;
10533       dependent_p = dependent_type_p (context);
10534       --processing_template_decl;
10535 
10536       if (!dependent_p
10537 	  && !complete_type_or_else (context, NULL_TREE))
10538 	return error_mark_node;
10539 
10540       if (COMPLETE_TYPE_P (context))
10541 	{
10542 	  tree fn = new_friend;
10543 	  /* do_friend adds the TEMPLATE_DECL for any member friend
10544 	     template even if it isn't a member template, i.e.
10545 	       template <class T> friend A<T>::f();
10546 	     Look through it in that case.  */
10547 	  if (TREE_CODE (fn) == TEMPLATE_DECL
10548 	      && !PRIMARY_TEMPLATE_P (fn))
10549 	    fn = DECL_TEMPLATE_RESULT (fn);
10550 	  /* Check to see that the declaration is really present, and,
10551 	     possibly obtain an improved declaration.  */
10552 	  fn = check_classfn (context, fn, NULL_TREE);
10553 
10554 	  if (fn)
10555 	    new_friend = fn;
10556 	}
10557     }
10558 
10559   return new_friend;
10560 }
10561 
10562 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
10563    template arguments, as for tsubst.
10564 
10565    Returns an appropriate tsubst'd friend type or error_mark_node on
10566    failure.  */
10567 
10568 static tree
tsubst_friend_class(tree friend_tmpl,tree args)10569 tsubst_friend_class (tree friend_tmpl, tree args)
10570 {
10571   tree tmpl;
10572 
10573   if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
10574     {
10575       tmpl = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
10576       return TREE_TYPE (tmpl);
10577     }
10578 
10579   tree context = CP_DECL_CONTEXT (friend_tmpl);
10580   if (TREE_CODE (context) == NAMESPACE_DECL)
10581     push_nested_namespace (context);
10582   else
10583     {
10584       context = tsubst (context, args, tf_error, NULL_TREE);
10585       push_nested_class (context);
10586     }
10587 
10588   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), /*prefer_type=*/false,
10589 			   /*non_class=*/false, /*block_p=*/false,
10590 			   /*namespaces_only=*/false, LOOKUP_HIDDEN);
10591 
10592   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
10593     {
10594       /* The friend template has already been declared.  Just
10595 	 check to see that the declarations match, and install any new
10596 	 default parameters.  We must tsubst the default parameters,
10597 	 of course.  We only need the innermost template parameters
10598 	 because that is all that redeclare_class_template will look
10599 	 at.  */
10600       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
10601 	  > TMPL_ARGS_DEPTH (args))
10602 	{
10603 	  tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
10604 					      args, tf_warning_or_error);
10605           location_t saved_input_location = input_location;
10606           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
10607           tree cons = get_constraints (tmpl);
10608           redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
10609           input_location = saved_input_location;
10610 	}
10611     }
10612   else
10613     {
10614       /* The friend template has not already been declared.  In this
10615 	 case, the instantiation of the template class will cause the
10616 	 injection of this template into the namespace scope.  */
10617       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
10618 
10619       if (tmpl != error_mark_node)
10620 	{
10621 	  /* The new TMPL is not an instantiation of anything, so we
10622 	     forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE
10623 	     for the new type because that is supposed to be the
10624 	     corresponding template decl, i.e., TMPL.  */
10625 	  DECL_USE_TEMPLATE (tmpl) = 0;
10626 	  DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
10627 	  CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
10628 	  CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
10629 	    = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
10630 
10631 	  /* It is hidden.  */
10632 	  retrofit_lang_decl (DECL_TEMPLATE_RESULT (tmpl));
10633 	  DECL_ANTICIPATED (tmpl)
10634 	    = DECL_ANTICIPATED (DECL_TEMPLATE_RESULT (tmpl)) = true;
10635 
10636 	  /* Inject this template into the enclosing namspace scope.  */
10637 	  tmpl = pushdecl_namespace_level (tmpl, true);
10638 	}
10639     }
10640 
10641   if (TREE_CODE (context) == NAMESPACE_DECL)
10642     pop_nested_namespace (context);
10643   else
10644     pop_nested_class ();
10645 
10646   return TREE_TYPE (tmpl);
10647 }
10648 
10649 /* Returns zero if TYPE cannot be completed later due to circularity.
10650    Otherwise returns one.  */
10651 
10652 static int
can_complete_type_without_circularity(tree type)10653 can_complete_type_without_circularity (tree type)
10654 {
10655   if (type == NULL_TREE || type == error_mark_node)
10656     return 0;
10657   else if (COMPLETE_TYPE_P (type))
10658     return 1;
10659   else if (TREE_CODE (type) == ARRAY_TYPE)
10660     return can_complete_type_without_circularity (TREE_TYPE (type));
10661   else if (CLASS_TYPE_P (type)
10662 	   && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
10663     return 0;
10664   else
10665     return 1;
10666 }
10667 
10668 static tree tsubst_omp_clauses (tree, enum c_omp_region_type, tree,
10669 				tsubst_flags_t, tree);
10670 
10671 /* Instantiate a single dependent attribute T (a TREE_LIST), and return either
10672    T or a new TREE_LIST, possibly a chain in the case of a pack expansion.  */
10673 
10674 static tree
tsubst_attribute(tree t,tree * decl_p,tree args,tsubst_flags_t complain,tree in_decl)10675 tsubst_attribute (tree t, tree *decl_p, tree args,
10676 		  tsubst_flags_t complain, tree in_decl)
10677 {
10678   gcc_assert (ATTR_IS_DEPENDENT (t));
10679 
10680   tree val = TREE_VALUE (t);
10681   if (val == NULL_TREE)
10682     /* Nothing to do.  */;
10683   else if ((flag_openmp || flag_openmp_simd)
10684 	   && is_attribute_p ("omp declare simd",
10685 			      get_attribute_name (t)))
10686     {
10687       tree clauses = TREE_VALUE (val);
10688       clauses = tsubst_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD, args,
10689 				    complain, in_decl);
10690       c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
10691       clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
10692       tree parms = DECL_ARGUMENTS (*decl_p);
10693       clauses
10694 	= c_omp_declare_simd_clauses_to_numbers (parms, clauses);
10695       if (clauses)
10696 	val = build_tree_list (NULL_TREE, clauses);
10697       else
10698 	val = NULL_TREE;
10699     }
10700   /* If the first attribute argument is an identifier, don't
10701      pass it through tsubst.  Attributes like mode, format,
10702      cleanup and several target specific attributes expect it
10703      unmodified.  */
10704   else if (attribute_takes_identifier_p (get_attribute_name (t)))
10705     {
10706       tree chain
10707 	= tsubst_expr (TREE_CHAIN (val), args, complain, in_decl,
10708 		       /*integral_constant_expression_p=*/false);
10709       if (chain != TREE_CHAIN (val))
10710 	val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
10711     }
10712   else if (PACK_EXPANSION_P (val))
10713     {
10714       /* An attribute pack expansion.  */
10715       tree purp = TREE_PURPOSE (t);
10716       tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
10717       if (pack == error_mark_node)
10718 	return error_mark_node;
10719       int len = TREE_VEC_LENGTH (pack);
10720       tree list = NULL_TREE;
10721       tree *q = &list;
10722       for (int i = 0; i < len; ++i)
10723 	{
10724 	  tree elt = TREE_VEC_ELT (pack, i);
10725 	  *q = build_tree_list (purp, elt);
10726 	  q = &TREE_CHAIN (*q);
10727 	}
10728       return list;
10729     }
10730   else
10731     val = tsubst_expr (val, args, complain, in_decl,
10732 		       /*integral_constant_expression_p=*/false);
10733 
10734   if (val != TREE_VALUE (t))
10735     return build_tree_list (TREE_PURPOSE (t), val);
10736   return t;
10737 }
10738 
10739 /* Instantiate any dependent attributes in ATTRIBUTES, returning either it
10740    unchanged or a new TREE_LIST chain.  */
10741 
10742 static tree
tsubst_attributes(tree attributes,tree args,tsubst_flags_t complain,tree in_decl)10743 tsubst_attributes (tree attributes, tree args,
10744 		   tsubst_flags_t complain, tree in_decl)
10745 {
10746   tree last_dep = NULL_TREE;
10747 
10748   for (tree t = attributes; t; t = TREE_CHAIN (t))
10749     if (ATTR_IS_DEPENDENT (t))
10750       {
10751 	last_dep = t;
10752 	attributes = copy_list (attributes);
10753 	break;
10754       }
10755 
10756   if (last_dep)
10757     for (tree *p = &attributes; *p; )
10758       {
10759 	tree t = *p;
10760 	if (ATTR_IS_DEPENDENT (t))
10761 	  {
10762 	    tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
10763 	    if (subst != t)
10764 	      {
10765 		*p = subst;
10766 		while (*p)
10767 		  p = &TREE_CHAIN (*p);
10768 		*p = TREE_CHAIN (t);
10769 		continue;
10770 	      }
10771 	  }
10772 	p = &TREE_CHAIN (*p);
10773       }
10774 
10775   return attributes;
10776 }
10777 
10778 /* Apply any attributes which had to be deferred until instantiation
10779    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
10780    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
10781 
10782 static void
apply_late_template_attributes(tree * decl_p,tree attributes,int attr_flags,tree args,tsubst_flags_t complain,tree in_decl)10783 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
10784 				tree args, tsubst_flags_t complain, tree in_decl)
10785 {
10786   tree last_dep = NULL_TREE;
10787   tree t;
10788   tree *p;
10789 
10790   if (attributes == NULL_TREE)
10791     return;
10792 
10793   if (DECL_P (*decl_p))
10794     {
10795       if (TREE_TYPE (*decl_p) == error_mark_node)
10796 	return;
10797       p = &DECL_ATTRIBUTES (*decl_p);
10798       /* DECL_ATTRIBUTES comes from copy_node in tsubst_decl, and is identical
10799          to our attributes parameter.  */
10800       gcc_assert (*p == attributes);
10801     }
10802   else
10803     {
10804       p = &TYPE_ATTRIBUTES (*decl_p);
10805       /* TYPE_ATTRIBUTES was set up (with abi_tag and may_alias) in
10806 	 lookup_template_class_1, and should be preserved.  */
10807       gcc_assert (*p != attributes);
10808       while (*p)
10809 	p = &TREE_CHAIN (*p);
10810     }
10811 
10812   for (t = attributes; t; t = TREE_CHAIN (t))
10813     if (ATTR_IS_DEPENDENT (t))
10814       {
10815 	last_dep = t;
10816 	attributes = copy_list (attributes);
10817 	break;
10818       }
10819 
10820   *p = attributes;
10821   if (last_dep)
10822     {
10823       tree late_attrs = NULL_TREE;
10824       tree *q = &late_attrs;
10825 
10826       for (; *p; )
10827 	{
10828 	  t = *p;
10829 	  if (ATTR_IS_DEPENDENT (t))
10830 	    {
10831 	      *p = TREE_CHAIN (t);
10832 	      TREE_CHAIN (t) = NULL_TREE;
10833 	      *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
10834 	      while (*q)
10835 		q = &TREE_CHAIN (*q);
10836 	    }
10837 	  else
10838 	    p = &TREE_CHAIN (t);
10839 	}
10840 
10841       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
10842     }
10843 }
10844 
10845 /* Perform (or defer) access check for typedefs that were referenced
10846    from within the template TMPL code.
10847    This is a subroutine of instantiate_decl and instantiate_class_template.
10848    TMPL is the template to consider and TARGS is the list of arguments of
10849    that template.  */
10850 
10851 static void
perform_typedefs_access_check(tree tmpl,tree targs)10852 perform_typedefs_access_check (tree tmpl, tree targs)
10853 {
10854   location_t saved_location;
10855   unsigned i;
10856   qualified_typedef_usage_t *iter;
10857 
10858   if (!tmpl
10859       || (!CLASS_TYPE_P (tmpl)
10860 	  && TREE_CODE (tmpl) != FUNCTION_DECL))
10861     return;
10862 
10863   saved_location = input_location;
10864   FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (tmpl), i, iter)
10865     {
10866       tree type_decl = iter->typedef_decl;
10867       tree type_scope = iter->context;
10868 
10869       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
10870 	continue;
10871 
10872       if (uses_template_parms (type_decl))
10873 	type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
10874       if (uses_template_parms (type_scope))
10875 	type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
10876 
10877       /* Make access check error messages point to the location
10878          of the use of the typedef.  */
10879       input_location = iter->locus;
10880       perform_or_defer_access_check (TYPE_BINFO (type_scope),
10881 				     type_decl, type_decl,
10882 				     tf_warning_or_error);
10883     }
10884     input_location = saved_location;
10885 }
10886 
10887 static tree
instantiate_class_template_1(tree type)10888 instantiate_class_template_1 (tree type)
10889 {
10890   tree templ, args, pattern, t, member;
10891   tree typedecl;
10892   tree pbinfo;
10893   tree base_list;
10894   unsigned int saved_maximum_field_alignment;
10895   tree fn_context;
10896 
10897   if (type == error_mark_node)
10898     return error_mark_node;
10899 
10900   if (COMPLETE_OR_OPEN_TYPE_P (type)
10901       || uses_template_parms (type))
10902     return type;
10903 
10904   /* Figure out which template is being instantiated.  */
10905   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
10906   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
10907 
10908   /* Mark the type as in the process of being defined.  */
10909   TYPE_BEING_DEFINED (type) = 1;
10910 
10911   /* We may be in the middle of deferred access check.  Disable
10912      it now.  */
10913   deferring_access_check_sentinel acs (dk_no_deferred);
10914 
10915   /* Determine what specialization of the original template to
10916      instantiate.  */
10917   t = most_specialized_partial_spec (type, tf_warning_or_error);
10918   if (t == error_mark_node)
10919     return error_mark_node;
10920   else if (t)
10921     {
10922       /* This TYPE is actually an instantiation of a partial
10923 	 specialization.  We replace the innermost set of ARGS with
10924 	 the arguments appropriate for substitution.  For example,
10925 	 given:
10926 
10927 	   template <class T> struct S {};
10928 	   template <class T> struct S<T*> {};
10929 
10930 	 and supposing that we are instantiating S<int*>, ARGS will
10931 	 presently be {int*} -- but we need {int}.  */
10932       pattern = TREE_TYPE (t);
10933       args = TREE_PURPOSE (t);
10934     }
10935   else
10936     {
10937       pattern = TREE_TYPE (templ);
10938       args = CLASSTYPE_TI_ARGS (type);
10939     }
10940 
10941   /* If the template we're instantiating is incomplete, then clearly
10942      there's nothing we can do.  */
10943   if (!COMPLETE_TYPE_P (pattern))
10944     {
10945       /* We can try again later.  */
10946       TYPE_BEING_DEFINED (type) = 0;
10947       return type;
10948     }
10949 
10950   /* If we've recursively instantiated too many templates, stop.  */
10951   if (! push_tinst_level (type))
10952     return type;
10953 
10954   int saved_unevaluated_operand = cp_unevaluated_operand;
10955   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
10956 
10957   fn_context = decl_function_context (TYPE_MAIN_DECL (type));
10958   /* Also avoid push_to_top_level for a lambda in an NSDMI.  */
10959   if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
10960     fn_context = error_mark_node;
10961   if (!fn_context)
10962     push_to_top_level ();
10963   else
10964     {
10965       cp_unevaluated_operand = 0;
10966       c_inhibit_evaluation_warnings = 0;
10967     }
10968   /* Use #pragma pack from the template context.  */
10969   saved_maximum_field_alignment = maximum_field_alignment;
10970   maximum_field_alignment = TYPE_PRECISION (pattern);
10971 
10972   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
10973 
10974   /* Set the input location to the most specialized template definition.
10975      This is needed if tsubsting causes an error.  */
10976   typedecl = TYPE_MAIN_DECL (pattern);
10977   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
10978     DECL_SOURCE_LOCATION (typedecl);
10979 
10980   TYPE_PACKED (type) = TYPE_PACKED (pattern);
10981   SET_TYPE_ALIGN (type, TYPE_ALIGN (pattern));
10982   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
10983   CLASSTYPE_NON_AGGREGATE (type) = CLASSTYPE_NON_AGGREGATE (pattern);
10984   if (ANON_AGGR_TYPE_P (pattern))
10985     SET_ANON_AGGR_TYPE_P (type);
10986   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
10987     {
10988       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
10989       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
10990       /* Adjust visibility for template arguments.  */
10991       determine_visibility (TYPE_MAIN_DECL (type));
10992     }
10993   if (CLASS_TYPE_P (type))
10994     CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
10995 
10996   pbinfo = TYPE_BINFO (pattern);
10997 
10998   /* We should never instantiate a nested class before its enclosing
10999      class; we need to look up the nested class by name before we can
11000      instantiate it, and that lookup should instantiate the enclosing
11001      class.  */
11002   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
11003 	      || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
11004 
11005   base_list = NULL_TREE;
11006   if (BINFO_N_BASE_BINFOS (pbinfo))
11007     {
11008       tree pbase_binfo;
11009       tree pushed_scope;
11010       int i;
11011 
11012       /* We must enter the scope containing the type, as that is where
11013 	 the accessibility of types named in dependent bases are
11014 	 looked up from.  */
11015       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
11016 
11017       /* Substitute into each of the bases to determine the actual
11018 	 basetypes.  */
11019       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
11020 	{
11021 	  tree base;
11022 	  tree access = BINFO_BASE_ACCESS (pbinfo, i);
11023           tree expanded_bases = NULL_TREE;
11024           int idx, len = 1;
11025 
11026           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
11027             {
11028               expanded_bases =
11029 		tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
11030 				       args, tf_error, NULL_TREE);
11031               if (expanded_bases == error_mark_node)
11032                 continue;
11033 
11034               len = TREE_VEC_LENGTH (expanded_bases);
11035             }
11036 
11037           for (idx = 0; idx < len; idx++)
11038             {
11039               if (expanded_bases)
11040                 /* Extract the already-expanded base class.  */
11041                 base = TREE_VEC_ELT (expanded_bases, idx);
11042               else
11043                 /* Substitute to figure out the base class.  */
11044                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
11045                                NULL_TREE);
11046 
11047               if (base == error_mark_node)
11048                 continue;
11049 
11050               base_list = tree_cons (access, base, base_list);
11051               if (BINFO_VIRTUAL_P (pbase_binfo))
11052                 TREE_TYPE (base_list) = integer_type_node;
11053             }
11054 	}
11055 
11056       /* The list is now in reverse order; correct that.  */
11057       base_list = nreverse (base_list);
11058 
11059       if (pushed_scope)
11060 	pop_scope (pushed_scope);
11061     }
11062   /* Now call xref_basetypes to set up all the base-class
11063      information.  */
11064   xref_basetypes (type, base_list);
11065 
11066   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
11067 				  (int) ATTR_FLAG_TYPE_IN_PLACE,
11068 				  args, tf_error, NULL_TREE);
11069   fixup_attribute_variants (type);
11070 
11071   /* Now that our base classes are set up, enter the scope of the
11072      class, so that name lookups into base classes, etc. will work
11073      correctly.  This is precisely analogous to what we do in
11074      begin_class_definition when defining an ordinary non-template
11075      class, except we also need to push the enclosing classes.  */
11076   push_nested_class (type);
11077 
11078   /* Now members are processed in the order of declaration.  */
11079   for (member = CLASSTYPE_DECL_LIST (pattern);
11080        member; member = TREE_CHAIN (member))
11081     {
11082       tree t = TREE_VALUE (member);
11083 
11084       if (TREE_PURPOSE (member))
11085 	{
11086 	  if (TYPE_P (t))
11087 	    {
11088 	      if (LAMBDA_TYPE_P (t))
11089 		/* A closure type for a lambda in an NSDMI or default argument.
11090 		   Ignore it; it will be regenerated when needed.  */
11091 		continue;
11092 
11093 	      /* Build new CLASSTYPE_NESTED_UTDS.  */
11094 
11095 	      tree newtag;
11096 	      bool class_template_p;
11097 
11098 	      class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
11099 				  && TYPE_LANG_SPECIFIC (t)
11100 				  && CLASSTYPE_IS_TEMPLATE (t));
11101 	      /* If the member is a class template, then -- even after
11102 		 substitution -- there may be dependent types in the
11103 		 template argument list for the class.  We increment
11104 		 PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
11105 		 that function will assume that no types are dependent
11106 		 when outside of a template.  */
11107 	      if (class_template_p)
11108 		++processing_template_decl;
11109 	      newtag = tsubst (t, args, tf_error, NULL_TREE);
11110 	      if (class_template_p)
11111 		--processing_template_decl;
11112 	      if (newtag == error_mark_node)
11113 		continue;
11114 
11115 	      if (TREE_CODE (newtag) != ENUMERAL_TYPE)
11116 		{
11117 		  tree name = TYPE_IDENTIFIER (t);
11118 
11119 		  if (class_template_p)
11120 		    /* Unfortunately, lookup_template_class sets
11121 		       CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
11122 		       instantiation (i.e., for the type of a member
11123 		       template class nested within a template class.)
11124 		       This behavior is required for
11125 		       maybe_process_partial_specialization to work
11126 		       correctly, but is not accurate in this case;
11127 		       the TAG is not an instantiation of anything.
11128 		       (The corresponding TEMPLATE_DECL is an
11129 		       instantiation, but the TYPE is not.) */
11130 		    CLASSTYPE_USE_TEMPLATE (newtag) = 0;
11131 
11132 		  /* Now, we call pushtag to put this NEWTAG into the scope of
11133 		     TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
11134 		     pushtag calling push_template_decl.  We don't have to do
11135 		     this for enums because it will already have been done in
11136 		     tsubst_enum.  */
11137 		  if (name)
11138 		    SET_IDENTIFIER_TYPE_VALUE (name, newtag);
11139 		  pushtag (name, newtag, /*tag_scope=*/ts_current);
11140 		}
11141 	    }
11142 	  else if (DECL_DECLARES_FUNCTION_P (t))
11143 	    {
11144 	      tree r;
11145 
11146 	      if (TREE_CODE (t) == TEMPLATE_DECL)
11147 		++processing_template_decl;
11148 	      r = tsubst (t, args, tf_error, NULL_TREE);
11149 	      if (TREE_CODE (t) == TEMPLATE_DECL)
11150 		--processing_template_decl;
11151 	      set_current_access_from_decl (r);
11152 	      finish_member_declaration (r);
11153 	      /* Instantiate members marked with attribute used.  */
11154 	      if (r != error_mark_node && DECL_PRESERVE_P (r))
11155 		mark_used (r);
11156 	      if (TREE_CODE (r) == FUNCTION_DECL
11157 		  && DECL_OMP_DECLARE_REDUCTION_P (r))
11158 		cp_check_omp_declare_reduction (r);
11159 	    }
11160 	  else if ((DECL_CLASS_TEMPLATE_P (t) || DECL_IMPLICIT_TYPEDEF_P (t))
11161 		   && LAMBDA_TYPE_P (TREE_TYPE (t)))
11162 	    /* A closure type for a lambda in an NSDMI or default argument.
11163 	       Ignore it; it will be regenerated when needed.  */;
11164 	  else
11165 	    {
11166 	      /* Build new TYPE_FIELDS.  */
11167               if (TREE_CODE (t) == STATIC_ASSERT)
11168                 {
11169                   tree condition;
11170 
11171 		  ++c_inhibit_evaluation_warnings;
11172 		  condition =
11173 		    tsubst_expr (STATIC_ASSERT_CONDITION (t), args,
11174 				 tf_warning_or_error, NULL_TREE,
11175 				 /*integral_constant_expression_p=*/true);
11176 		  --c_inhibit_evaluation_warnings;
11177 
11178                   finish_static_assert (condition,
11179                                         STATIC_ASSERT_MESSAGE (t),
11180                                         STATIC_ASSERT_SOURCE_LOCATION (t),
11181                                         /*member_p=*/true);
11182                 }
11183 	      else if (TREE_CODE (t) != CONST_DECL)
11184 		{
11185 		  tree r;
11186 		  tree vec = NULL_TREE;
11187 		  int len = 1;
11188 
11189 		  /* The file and line for this declaration, to
11190 		     assist in error message reporting.  Since we
11191 		     called push_tinst_level above, we don't need to
11192 		     restore these.  */
11193 		  input_location = DECL_SOURCE_LOCATION (t);
11194 
11195 		  if (TREE_CODE (t) == TEMPLATE_DECL)
11196 		    ++processing_template_decl;
11197 		  r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
11198 		  if (TREE_CODE (t) == TEMPLATE_DECL)
11199 		    --processing_template_decl;
11200 
11201 		  if (TREE_CODE (r) == TREE_VEC)
11202 		    {
11203 		      /* A capture pack became multiple fields.  */
11204 		      vec = r;
11205 		      len = TREE_VEC_LENGTH (vec);
11206 		    }
11207 
11208 		  for (int i = 0; i < len; ++i)
11209 		    {
11210 		      if (vec)
11211 			r = TREE_VEC_ELT (vec, i);
11212 		      if (VAR_P (r))
11213 			{
11214 			  /* In [temp.inst]:
11215 
11216 			     [t]he initialization (and any associated
11217 			     side-effects) of a static data member does
11218 			     not occur unless the static data member is
11219 			     itself used in a way that requires the
11220 			     definition of the static data member to
11221 			     exist.
11222 
11223 			     Therefore, we do not substitute into the
11224 			     initialized for the static data member here.  */
11225 			  finish_static_data_member_decl
11226 			    (r,
11227 			     /*init=*/NULL_TREE,
11228 			     /*init_const_expr_p=*/false,
11229 			     /*asmspec_tree=*/NULL_TREE,
11230 			     /*flags=*/0);
11231 			  /* Instantiate members marked with attribute used. */
11232 			  if (r != error_mark_node && DECL_PRESERVE_P (r))
11233 			    mark_used (r);
11234 			}
11235 		      else if (TREE_CODE (r) == FIELD_DECL)
11236 			{
11237 			  /* Determine whether R has a valid type and can be
11238 			     completed later.  If R is invalid, then its type
11239 			     is replaced by error_mark_node.  */
11240 			  tree rtype = TREE_TYPE (r);
11241 			  if (can_complete_type_without_circularity (rtype))
11242 			    complete_type (rtype);
11243 
11244 			  if (!complete_or_array_type_p (rtype))
11245 			    {
11246 			      /* If R's type couldn't be completed and
11247 				 it isn't a flexible array member (whose
11248 				 type is incomplete by definition) give
11249 				 an error.  */
11250 			      cxx_incomplete_type_error (r, rtype);
11251 			      TREE_TYPE (r) = error_mark_node;
11252 			    }
11253 			  else if (TREE_CODE (rtype) == ARRAY_TYPE
11254 				   && TYPE_DOMAIN (rtype) == NULL_TREE
11255 				   && (TREE_CODE (type) == UNION_TYPE
11256 				       || TREE_CODE (type) == QUAL_UNION_TYPE))
11257 			    {
11258 			      error ("flexible array member %qD in union", r);
11259 			      TREE_TYPE (r) = error_mark_node;
11260 			    }
11261 			}
11262 
11263 		      /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
11264 			 such a thing will already have been added to the field
11265 			 list by tsubst_enum in finish_member_declaration in the
11266 			 CLASSTYPE_NESTED_UTDS case above.  */
11267 		      if (!(TREE_CODE (r) == TYPE_DECL
11268 			    && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
11269 			    && DECL_ARTIFICIAL (r)))
11270 			{
11271 			  set_current_access_from_decl (r);
11272 			  finish_member_declaration (r);
11273 			}
11274 		    }
11275 		}
11276 	    }
11277 	}
11278       else
11279 	{
11280 	  if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
11281 	      || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11282 	    {
11283 	      /* Build new CLASSTYPE_FRIEND_CLASSES.  */
11284 
11285 	      tree friend_type = t;
11286 	      bool adjust_processing_template_decl = false;
11287 
11288 	      if (TREE_CODE (friend_type) == TEMPLATE_DECL)
11289 		{
11290 		  /* template <class T> friend class C;  */
11291 		  friend_type = tsubst_friend_class (friend_type, args);
11292 		  adjust_processing_template_decl = true;
11293 		}
11294 	      else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
11295 		{
11296 		  /* template <class T> friend class C::D;  */
11297 		  friend_type = tsubst (friend_type, args,
11298 					tf_warning_or_error, NULL_TREE);
11299 		  if (TREE_CODE (friend_type) == TEMPLATE_DECL)
11300 		    friend_type = TREE_TYPE (friend_type);
11301 		  adjust_processing_template_decl = true;
11302 		}
11303 	      else if (TREE_CODE (friend_type) == TYPENAME_TYPE
11304 		       || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
11305 		{
11306 		  /* This could be either
11307 
11308 		       friend class T::C;
11309 
11310 		     when dependent_type_p is false or
11311 
11312 		       template <class U> friend class T::C;
11313 
11314 		     otherwise.  */
11315 		  /* Bump processing_template_decl in case this is something like
11316 		     template <class T> friend struct A<T>::B.  */
11317 		  ++processing_template_decl;
11318 		  friend_type = tsubst (friend_type, args,
11319 					tf_warning_or_error, NULL_TREE);
11320 		  if (dependent_type_p (friend_type))
11321 		    adjust_processing_template_decl = true;
11322 		  --processing_template_decl;
11323 		}
11324 	      else if (TREE_CODE (friend_type) != BOUND_TEMPLATE_TEMPLATE_PARM
11325 		       && !CLASSTYPE_USE_TEMPLATE (friend_type)
11326 		       && TYPE_HIDDEN_P (friend_type))
11327 		{
11328 		  /* friend class C;
11329 
11330 		     where C hasn't been declared yet.  Let's lookup name
11331 		     from namespace scope directly, bypassing any name that
11332 		     come from dependent base class.  */
11333 		  tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
11334 
11335 		  /* The call to xref_tag_from_type does injection for friend
11336 		     classes.  */
11337 		  push_nested_namespace (ns);
11338 		  friend_type =
11339 		    xref_tag_from_type (friend_type, NULL_TREE,
11340 					/*tag_scope=*/ts_current);
11341 		  pop_nested_namespace (ns);
11342 		}
11343 	      else if (uses_template_parms (friend_type))
11344 		/* friend class C<T>;  */
11345 		friend_type = tsubst (friend_type, args,
11346 				      tf_warning_or_error, NULL_TREE);
11347 	      /* Otherwise it's
11348 
11349 		   friend class C;
11350 
11351 		 where C is already declared or
11352 
11353 		   friend class C<int>;
11354 
11355 		 We don't have to do anything in these cases.  */
11356 
11357 	      if (adjust_processing_template_decl)
11358 		/* Trick make_friend_class into realizing that the friend
11359 		   we're adding is a template, not an ordinary class.  It's
11360 		   important that we use make_friend_class since it will
11361 		   perform some error-checking and output cross-reference
11362 		   information.  */
11363 		++processing_template_decl;
11364 
11365 	      if (friend_type != error_mark_node)
11366 		make_friend_class (type, friend_type, /*complain=*/false);
11367 
11368 	      if (adjust_processing_template_decl)
11369 		--processing_template_decl;
11370 	    }
11371 	  else
11372 	    {
11373 	      /* Build new DECL_FRIENDLIST.  */
11374 	      tree r;
11375 
11376 	      /* The file and line for this declaration, to
11377 		 assist in error message reporting.  Since we
11378 		 called push_tinst_level above, we don't need to
11379 		 restore these.  */
11380 	      input_location = DECL_SOURCE_LOCATION (t);
11381 
11382 	      if (TREE_CODE (t) == TEMPLATE_DECL)
11383 		{
11384 		  ++processing_template_decl;
11385 		  push_deferring_access_checks (dk_no_check);
11386 		}
11387 
11388 	      r = tsubst_friend_function (t, args);
11389 	      add_friend (type, r, /*complain=*/false);
11390 	      if (TREE_CODE (t) == TEMPLATE_DECL)
11391 		{
11392 		  pop_deferring_access_checks ();
11393 		  --processing_template_decl;
11394 		}
11395 	    }
11396 	}
11397     }
11398 
11399   if (fn_context)
11400     {
11401       /* Restore these before substituting into the lambda capture
11402 	 initializers.  */
11403       cp_unevaluated_operand = saved_unevaluated_operand;
11404       c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
11405     }
11406 
11407   /* Set the file and line number information to whatever is given for
11408      the class itself.  This puts error messages involving generated
11409      implicit functions at a predictable point, and the same point
11410      that would be used for non-template classes.  */
11411   input_location = DECL_SOURCE_LOCATION (typedecl);
11412 
11413   unreverse_member_declarations (type);
11414   finish_struct_1 (type);
11415   TYPE_BEING_DEFINED (type) = 0;
11416 
11417   /* We don't instantiate default arguments for member functions.  14.7.1:
11418 
11419      The implicit instantiation of a class template specialization causes
11420      the implicit instantiation of the declarations, but not of the
11421      definitions or default arguments, of the class member functions,
11422      member classes, static data members and member templates....  */
11423 
11424   /* Some typedefs referenced from within the template code need to be access
11425      checked at template instantiation time, i.e now. These types were
11426      added to the template at parsing time. Let's get those and perform
11427      the access checks then.  */
11428   perform_typedefs_access_check (pattern, args);
11429   perform_deferred_access_checks (tf_warning_or_error);
11430   pop_nested_class ();
11431   maximum_field_alignment = saved_maximum_field_alignment;
11432   if (!fn_context)
11433     pop_from_top_level ();
11434   pop_tinst_level ();
11435 
11436   /* The vtable for a template class can be emitted in any translation
11437      unit in which the class is instantiated.  When there is no key
11438      method, however, finish_struct_1 will already have added TYPE to
11439      the keyed_classes.  */
11440   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
11441     vec_safe_push (keyed_classes, type);
11442 
11443   return type;
11444 }
11445 
11446 /* Wrapper for instantiate_class_template_1.  */
11447 
11448 tree
instantiate_class_template(tree type)11449 instantiate_class_template (tree type)
11450 {
11451   tree ret;
11452   timevar_push (TV_TEMPLATE_INST);
11453   ret = instantiate_class_template_1 (type);
11454   timevar_pop (TV_TEMPLATE_INST);
11455   return ret;
11456 }
11457 
11458 static tree
tsubst_template_arg(tree t,tree args,tsubst_flags_t complain,tree in_decl)11459 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11460 {
11461   tree r;
11462 
11463   if (!t)
11464     r = t;
11465   else if (TYPE_P (t))
11466     r = tsubst (t, args, complain, in_decl);
11467   else
11468     {
11469       if (!(complain & tf_warning))
11470 	++c_inhibit_evaluation_warnings;
11471       r = tsubst_expr (t, args, complain, in_decl,
11472 		       /*integral_constant_expression_p=*/true);
11473       if (!(complain & tf_warning))
11474 	--c_inhibit_evaluation_warnings;
11475     }
11476   return r;
11477 }
11478 
11479 /* Given a function parameter pack TMPL_PARM and some function parameters
11480    instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
11481    and set *SPEC_P to point at the next point in the list.  */
11482 
11483 tree
extract_fnparm_pack(tree tmpl_parm,tree * spec_p)11484 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
11485 {
11486   /* Collect all of the extra "packed" parameters into an
11487      argument pack.  */
11488   tree parmvec;
11489   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
11490   tree spec_parm = *spec_p;
11491   int i, len;
11492 
11493   for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
11494     if (tmpl_parm
11495 	&& !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
11496       break;
11497 
11498   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
11499   parmvec = make_tree_vec (len);
11500   spec_parm = *spec_p;
11501   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
11502     {
11503       tree elt = spec_parm;
11504       if (DECL_PACK_P (elt))
11505 	elt = make_pack_expansion (elt);
11506       TREE_VEC_ELT (parmvec, i) = elt;
11507     }
11508 
11509   /* Build the argument packs.  */
11510   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
11511   *spec_p = spec_parm;
11512 
11513   return argpack;
11514 }
11515 
11516 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
11517    NONTYPE_ARGUMENT_PACK.  */
11518 
11519 static tree
make_fnparm_pack(tree spec_parm)11520 make_fnparm_pack (tree spec_parm)
11521 {
11522   return extract_fnparm_pack (NULL_TREE, &spec_parm);
11523 }
11524 
11525 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
11526    pack expansion with no extra args, 2 if it has extra args, or 0
11527    if it is not a pack expansion.  */
11528 
11529 static int
argument_pack_element_is_expansion_p(tree arg_pack,int i)11530 argument_pack_element_is_expansion_p (tree arg_pack, int i)
11531 {
11532   tree vec = ARGUMENT_PACK_ARGS (arg_pack);
11533   if (i >= TREE_VEC_LENGTH (vec))
11534     return 0;
11535   tree elt = TREE_VEC_ELT (vec, i);
11536   if (DECL_P (elt))
11537     /* A decl pack is itself an expansion.  */
11538     elt = TREE_TYPE (elt);
11539   if (!PACK_EXPANSION_P (elt))
11540     return 0;
11541   if (PACK_EXPANSION_EXTRA_ARGS (elt))
11542     return 2;
11543   return 1;
11544 }
11545 
11546 
11547 /* Creates and return an ARGUMENT_PACK_SELECT tree node.  */
11548 
11549 static tree
make_argument_pack_select(tree arg_pack,unsigned index)11550 make_argument_pack_select (tree arg_pack, unsigned index)
11551 {
11552   tree aps = make_node (ARGUMENT_PACK_SELECT);
11553 
11554   ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
11555   ARGUMENT_PACK_SELECT_INDEX (aps) = index;
11556 
11557   return aps;
11558 }
11559 
11560 /*  This is a subroutine of tsubst_pack_expansion.
11561 
11562     It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
11563     mechanism to store the (non complete list of) arguments of the
11564     substitution and return a non substituted pack expansion, in order
11565     to wait for when we have enough arguments to really perform the
11566     substitution.  */
11567 
11568 static bool
use_pack_expansion_extra_args_p(tree parm_packs,int arg_pack_len,bool has_empty_arg)11569 use_pack_expansion_extra_args_p (tree parm_packs,
11570 				 int arg_pack_len,
11571 				 bool has_empty_arg)
11572 {
11573   /* If one pack has an expansion and another pack has a normal
11574      argument or if one pack has an empty argument and an another
11575      one hasn't then tsubst_pack_expansion cannot perform the
11576      substitution and need to fall back on the
11577      PACK_EXPANSION_EXTRA mechanism.  */
11578   if (parm_packs == NULL_TREE)
11579     return false;
11580   else if (has_empty_arg)
11581     return true;
11582 
11583   bool has_expansion_arg = false;
11584   for (int i = 0 ; i < arg_pack_len; ++i)
11585     {
11586       bool has_non_expansion_arg = false;
11587       for (tree parm_pack = parm_packs;
11588 	   parm_pack;
11589 	   parm_pack = TREE_CHAIN (parm_pack))
11590 	{
11591 	  tree arg = TREE_VALUE (parm_pack);
11592 
11593 	  int exp = argument_pack_element_is_expansion_p (arg, i);
11594 	  if (exp == 2)
11595 	    /* We can't substitute a pack expansion with extra args into
11596 	       our pattern.  */
11597 	    return true;
11598 	  else if (exp)
11599 	    has_expansion_arg = true;
11600 	  else
11601 	    has_non_expansion_arg = true;
11602 	}
11603 
11604       if (has_expansion_arg && has_non_expansion_arg)
11605 	return true;
11606     }
11607   return false;
11608 }
11609 
11610 /* [temp.variadic]/6 says that:
11611 
11612        The instantiation of a pack expansion [...]
11613        produces a list E1,E2, ..., En, where N is the number of elements
11614        in the pack expansion parameters.
11615 
11616    This subroutine of tsubst_pack_expansion produces one of these Ei.
11617 
11618    PATTERN is the pattern of the pack expansion.  PARM_PACKS is a
11619    TREE_LIST in which each TREE_PURPOSE is a parameter pack of
11620    PATTERN, and each TREE_VALUE is its corresponding argument pack.
11621    INDEX is the index 'i' of the element Ei to produce.  ARGS,
11622    COMPLAIN, and IN_DECL are the same parameters as for the
11623    tsubst_pack_expansion function.
11624 
11625    The function returns the resulting Ei upon successful completion,
11626    or error_mark_node.
11627 
11628    Note that this function possibly modifies the ARGS parameter, so
11629    it's the responsibility of the caller to restore it.  */
11630 
11631 static tree
gen_elem_of_pack_expansion_instantiation(tree pattern,tree parm_packs,unsigned index,tree args,tsubst_flags_t complain,tree in_decl)11632 gen_elem_of_pack_expansion_instantiation (tree pattern,
11633 					  tree parm_packs,
11634 					  unsigned index,
11635 					  tree args /* This parm gets
11636 						       modified.  */,
11637 					  tsubst_flags_t complain,
11638 					  tree in_decl)
11639 {
11640   tree t;
11641   bool ith_elem_is_expansion = false;
11642 
11643   /* For each parameter pack, change the substitution of the parameter
11644      pack to the ith argument in its argument pack, then expand the
11645      pattern.  */
11646   for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
11647     {
11648       tree parm = TREE_PURPOSE (pack);
11649       tree arg_pack = TREE_VALUE (pack);
11650       tree aps;			/* instance of ARGUMENT_PACK_SELECT.  */
11651 
11652       ith_elem_is_expansion |=
11653 	argument_pack_element_is_expansion_p (arg_pack, index);
11654 
11655       /* Select the Ith argument from the pack.  */
11656       if (TREE_CODE (parm) == PARM_DECL
11657 	  || VAR_P (parm)
11658 	  || TREE_CODE (parm) == FIELD_DECL)
11659 	{
11660 	  if (index == 0)
11661 	    {
11662 	      aps = make_argument_pack_select (arg_pack, index);
11663 	      if (!mark_used (parm, complain) && !(complain & tf_error))
11664 		return error_mark_node;
11665 	      register_local_specialization (aps, parm);
11666 	    }
11667 	  else
11668 	    aps = retrieve_local_specialization (parm);
11669 	}
11670       else
11671 	{
11672 	  int idx, level;
11673 	  template_parm_level_and_index (parm, &level, &idx);
11674 
11675 	  if (index == 0)
11676 	    {
11677 	      aps = make_argument_pack_select (arg_pack, index);
11678 	      /* Update the corresponding argument.  */
11679 	      TMPL_ARG (args, level, idx) = aps;
11680 	    }
11681 	  else
11682 	    /* Re-use the ARGUMENT_PACK_SELECT.  */
11683 	    aps = TMPL_ARG (args, level, idx);
11684 	}
11685       ARGUMENT_PACK_SELECT_INDEX (aps) = index;
11686     }
11687 
11688   /* Substitute into the PATTERN with the (possibly altered)
11689      arguments.  */
11690   if (pattern == in_decl)
11691     /* Expanding a fixed parameter pack from
11692        coerce_template_parameter_pack.  */
11693     t = tsubst_decl (pattern, args, complain);
11694   else if (pattern == error_mark_node)
11695     t = error_mark_node;
11696   else if (constraint_p (pattern))
11697     {
11698       if (processing_template_decl)
11699 	t = tsubst_constraint (pattern, args, complain, in_decl);
11700       else
11701 	t = (constraints_satisfied_p (pattern, args)
11702 	     ? boolean_true_node : boolean_false_node);
11703     }
11704   else if (!TYPE_P (pattern))
11705     t = tsubst_expr (pattern, args, complain, in_decl,
11706 		     /*integral_constant_expression_p=*/false);
11707   else
11708     t = tsubst (pattern, args, complain, in_decl);
11709 
11710   /*  If the Ith argument pack element is a pack expansion, then
11711       the Ith element resulting from the substituting is going to
11712       be a pack expansion as well.  */
11713   if (ith_elem_is_expansion)
11714     t = make_pack_expansion (t, complain);
11715 
11716   return t;
11717 }
11718 
11719 /* When the unexpanded parameter pack in a fold expression expands to an empty
11720    sequence, the value of the expression is as follows; the program is
11721    ill-formed if the operator is not listed in this table.
11722 
11723    &&	true
11724    ||	false
11725    ,	void()  */
11726 
11727 tree
expand_empty_fold(tree t,tsubst_flags_t complain)11728 expand_empty_fold (tree t, tsubst_flags_t complain)
11729 {
11730   tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
11731   if (!FOLD_EXPR_MODIFY_P (t))
11732     switch (code)
11733       {
11734       case TRUTH_ANDIF_EXPR:
11735 	return boolean_true_node;
11736       case TRUTH_ORIF_EXPR:
11737 	return boolean_false_node;
11738       case COMPOUND_EXPR:
11739 	return void_node;
11740       default:
11741 	break;
11742       }
11743 
11744   if (complain & tf_error)
11745     error_at (location_of (t),
11746 	      "fold of empty expansion over %O", code);
11747   return error_mark_node;
11748 }
11749 
11750 /* Given a fold-expression T and a current LEFT and RIGHT operand,
11751    form an expression that combines the two terms using the
11752    operator of T. */
11753 
11754 static tree
fold_expression(tree t,tree left,tree right,tsubst_flags_t complain)11755 fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
11756 {
11757   tree op = FOLD_EXPR_OP (t);
11758   tree_code code = (tree_code)TREE_INT_CST_LOW (op);
11759 
11760   // Handle compound assignment operators.
11761   if (FOLD_EXPR_MODIFY_P (t))
11762     return build_x_modify_expr (input_location, left, code, right, complain);
11763 
11764   switch (code)
11765     {
11766     case COMPOUND_EXPR:
11767       return build_x_compound_expr (input_location, left, right, complain);
11768     default:
11769       return build_x_binary_op (input_location, code,
11770                                 left, TREE_CODE (left),
11771                                 right, TREE_CODE (right),
11772                                 /*overload=*/NULL,
11773                                 complain);
11774     }
11775 }
11776 
11777 /* Substitute ARGS into the pack of a fold expression T. */
11778 
11779 static inline tree
tsubst_fold_expr_pack(tree t,tree args,tsubst_flags_t complain,tree in_decl)11780 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11781 {
11782   return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
11783 }
11784 
11785 /* Substitute ARGS into the pack of a fold expression T. */
11786 
11787 static inline tree
tsubst_fold_expr_init(tree t,tree args,tsubst_flags_t complain,tree in_decl)11788 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11789 {
11790   return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl, false);
11791 }
11792 
11793 /* Expand a PACK of arguments into a grouped as left fold.
11794    Given a pack containing elements A0, A1, ..., An and an
11795    operator @, this builds the expression:
11796 
11797       ((A0 @ A1) @ A2) ... @ An
11798 
11799    Note that PACK must not be empty.
11800 
11801    The operator is defined by the original fold expression T. */
11802 
11803 static tree
expand_left_fold(tree t,tree pack,tsubst_flags_t complain)11804 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
11805 {
11806   tree left = TREE_VEC_ELT (pack, 0);
11807   for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
11808     {
11809       tree right = TREE_VEC_ELT (pack, i);
11810       left = fold_expression (t, left, right, complain);
11811     }
11812   return left;
11813 }
11814 
11815 /* Substitute into a unary left fold expression. */
11816 
11817 static tree
tsubst_unary_left_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)11818 tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
11819                         tree in_decl)
11820 {
11821   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11822   if (pack == error_mark_node)
11823     return error_mark_node;
11824   if (PACK_EXPANSION_P (pack))
11825     {
11826       tree r = copy_node (t);
11827       FOLD_EXPR_PACK (r) = pack;
11828       return r;
11829     }
11830   if (TREE_VEC_LENGTH (pack) == 0)
11831     return expand_empty_fold (t, complain);
11832   else
11833     return expand_left_fold (t, pack, complain);
11834 }
11835 
11836 /* Substitute into a binary left fold expression.
11837 
11838    Do ths by building a single (non-empty) vector of argumnts and
11839    building the expression from those elements. */
11840 
11841 static tree
tsubst_binary_left_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)11842 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
11843                          tree in_decl)
11844 {
11845   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11846   if (pack == error_mark_node)
11847     return error_mark_node;
11848   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
11849   if (init == error_mark_node)
11850     return error_mark_node;
11851 
11852   if (PACK_EXPANSION_P (pack))
11853     {
11854       tree r = copy_node (t);
11855       FOLD_EXPR_PACK (r) = pack;
11856       FOLD_EXPR_INIT (r) = init;
11857       return r;
11858     }
11859 
11860   tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
11861   TREE_VEC_ELT (vec, 0) = init;
11862   for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
11863     TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
11864 
11865   return expand_left_fold (t, vec, complain);
11866 }
11867 
11868 /* Expand a PACK of arguments into a grouped as right fold.
11869    Given a pack containing elementns A0, A1, ..., and an
11870    operator @, this builds the expression:
11871 
11872       A0@ ... (An-2 @ (An-1 @ An))
11873 
11874    Note that PACK must not be empty.
11875 
11876    The operator is defined by the original fold expression T. */
11877 
11878 tree
expand_right_fold(tree t,tree pack,tsubst_flags_t complain)11879 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
11880 {
11881   // Build the expression.
11882   int n = TREE_VEC_LENGTH (pack);
11883   tree right = TREE_VEC_ELT (pack, n - 1);
11884   for (--n; n != 0; --n)
11885     {
11886       tree left = TREE_VEC_ELT (pack, n - 1);
11887       right = fold_expression (t, left, right, complain);
11888     }
11889   return right;
11890 }
11891 
11892 /* Substitute into a unary right fold expression. */
11893 
11894 static tree
tsubst_unary_right_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)11895 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
11896                          tree in_decl)
11897 {
11898   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11899   if (pack == error_mark_node)
11900     return error_mark_node;
11901   if (PACK_EXPANSION_P (pack))
11902     {
11903       tree r = copy_node (t);
11904       FOLD_EXPR_PACK (r) = pack;
11905       return r;
11906     }
11907   if (TREE_VEC_LENGTH (pack) == 0)
11908     return expand_empty_fold (t, complain);
11909   else
11910     return expand_right_fold (t, pack, complain);
11911 }
11912 
11913 /* Substitute into a binary right fold expression.
11914 
11915    Do ths by building a single (non-empty) vector of arguments and
11916    building the expression from those elements. */
11917 
11918 static tree
tsubst_binary_right_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)11919 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
11920                          tree in_decl)
11921 {
11922   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11923   if (pack == error_mark_node)
11924     return error_mark_node;
11925   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
11926   if (init == error_mark_node)
11927     return error_mark_node;
11928 
11929   if (PACK_EXPANSION_P (pack))
11930     {
11931       tree r = copy_node (t);
11932       FOLD_EXPR_PACK (r) = pack;
11933       FOLD_EXPR_INIT (r) = init;
11934       return r;
11935     }
11936 
11937   int n = TREE_VEC_LENGTH (pack);
11938   tree vec = make_tree_vec (n + 1);
11939   for (int i = 0; i < n; ++i)
11940     TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
11941   TREE_VEC_ELT (vec, n) = init;
11942 
11943   return expand_right_fold (t, vec, complain);
11944 }
11945 
11946 /* Walk through the pattern of a pack expansion, adding everything in
11947    local_specializations to a list.  */
11948 
11949 struct el_data
11950 {
11951   hash_set<tree> internal;
11952   tree extra;
11953   tsubst_flags_t complain;
11954 
el_datael_data11955   el_data (tsubst_flags_t c)
11956     : extra (NULL_TREE), complain (c) {}
11957 };
11958 static tree
extract_locals_r(tree * tp,int *,void * data_)11959 extract_locals_r (tree *tp, int */*walk_subtrees*/, void *data_)
11960 {
11961   el_data &data = *reinterpret_cast<el_data*>(data_);
11962   tree *extra = &data.extra;
11963   tsubst_flags_t complain = data.complain;
11964 
11965   if (TYPE_P (*tp) && typedef_variant_p (*tp))
11966     /* Remember local typedefs (85214).  */
11967     tp = &TYPE_NAME (*tp);
11968 
11969   if (TREE_CODE (*tp) == DECL_EXPR)
11970     data.internal.add (DECL_EXPR_DECL (*tp));
11971   else if (tree spec = retrieve_local_specialization (*tp))
11972     {
11973       if (data.internal.contains (*tp))
11974 	/* Don't mess with variables declared within the pattern.  */
11975 	return NULL_TREE;
11976       if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
11977 	{
11978 	  /* Maybe pull out the PARM_DECL for a partial instantiation.  */
11979 	  tree args = ARGUMENT_PACK_ARGS (spec);
11980 	  if (TREE_VEC_LENGTH (args) == 1)
11981 	    {
11982 	      tree elt = TREE_VEC_ELT (args, 0);
11983 	      if (PACK_EXPANSION_P (elt))
11984 		elt = PACK_EXPANSION_PATTERN (elt);
11985 	      if (DECL_PACK_P (elt))
11986 		spec = elt;
11987 	    }
11988 	  if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
11989 	    {
11990 	      /* Handle lambda capture here, since we aren't doing any
11991 		 substitution now, and so tsubst_copy won't call
11992 		 process_outer_var_ref.  */
11993 	      tree args = ARGUMENT_PACK_ARGS (spec);
11994 	      int len = TREE_VEC_LENGTH (args);
11995 	      for (int i = 0; i < len; ++i)
11996 		{
11997 		  tree arg = TREE_VEC_ELT (args, i);
11998 		  tree carg = arg;
11999 		  if (outer_automatic_var_p (arg))
12000 		    carg = process_outer_var_ref (arg, complain);
12001 		  if (carg != arg)
12002 		    {
12003 		      /* Make a new NONTYPE_ARGUMENT_PACK of the capture
12004 			 proxies.  */
12005 		      if (i == 0)
12006 			{
12007 			  spec = copy_node (spec);
12008 			  args = copy_node (args);
12009 			  SET_ARGUMENT_PACK_ARGS (spec, args);
12010 			  register_local_specialization (spec, *tp);
12011 			}
12012 		      TREE_VEC_ELT (args, i) = carg;
12013 		    }
12014 		}
12015 	    }
12016 	}
12017       if (outer_automatic_var_p (spec))
12018 	spec = process_outer_var_ref (spec, complain);
12019       *extra = tree_cons (*tp, spec, *extra);
12020     }
12021   return NULL_TREE;
12022 }
12023 static tree
extract_local_specs(tree pattern,tsubst_flags_t complain)12024 extract_local_specs (tree pattern, tsubst_flags_t complain)
12025 {
12026   el_data data (complain);
12027   cp_walk_tree_without_duplicates (&pattern, extract_locals_r, &data);
12028   return data.extra;
12029 }
12030 
12031 /* Extract any uses of local_specializations from PATTERN and add them to ARGS
12032    for use in PACK_EXPANSION_EXTRA_ARGS.  */
12033 
12034 tree
build_extra_args(tree pattern,tree args,tsubst_flags_t complain)12035 build_extra_args (tree pattern, tree args, tsubst_flags_t complain)
12036 {
12037   tree extra = args;
12038   if (local_specializations)
12039     if (tree locals = extract_local_specs (pattern, complain))
12040       extra = tree_cons (NULL_TREE, extra, locals);
12041   return extra;
12042 }
12043 
12044 /* Apply any local specializations from PACK_EXPANSION_EXTRA_ARGS and add the
12045    normal template args to ARGS.  */
12046 
12047 tree
add_extra_args(tree extra,tree args)12048 add_extra_args (tree extra, tree args)
12049 {
12050   if (extra && TREE_CODE (extra) == TREE_LIST)
12051     {
12052       for (tree elt = TREE_CHAIN (extra); elt; elt = TREE_CHAIN (elt))
12053 	{
12054 	  /* The partial instantiation involved local declarations collected in
12055 	     extract_local_specs; map from the general template to our local
12056 	     context.  */
12057 	  tree gen = TREE_PURPOSE (elt);
12058 	  tree inst = TREE_VALUE (elt);
12059 	  if (DECL_P (inst))
12060 	    if (tree local = retrieve_local_specialization (inst))
12061 	      inst = local;
12062 	  /* else inst is already a full instantiation of the pack.  */
12063 	  register_local_specialization (inst, gen);
12064 	}
12065       gcc_assert (!TREE_PURPOSE (extra));
12066       extra = TREE_VALUE (extra);
12067     }
12068   return add_to_template_args (extra, args);
12069 }
12070 
12071 /* Substitute ARGS into T, which is an pack expansion
12072    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
12073    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
12074    (if only a partial substitution could be performed) or
12075    ERROR_MARK_NODE if there was an error.  */
12076 tree
tsubst_pack_expansion(tree t,tree args,tsubst_flags_t complain,tree in_decl)12077 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
12078 		       tree in_decl)
12079 {
12080   tree pattern;
12081   tree pack, packs = NULL_TREE;
12082   bool unsubstituted_packs = false;
12083   bool unsubstituted_fn_pack = false;
12084   int i, len = -1;
12085   tree result;
12086   hash_map<tree, tree> *saved_local_specializations = NULL;
12087   bool need_local_specializations = false;
12088   int levels;
12089 
12090   gcc_assert (PACK_EXPANSION_P (t));
12091   pattern = PACK_EXPANSION_PATTERN (t);
12092 
12093   /* Add in any args remembered from an earlier partial instantiation.  */
12094   args = add_extra_args (PACK_EXPANSION_EXTRA_ARGS (t), args);
12095 
12096   levels = TMPL_ARGS_DEPTH (args);
12097 
12098   /* Determine the argument packs that will instantiate the parameter
12099      packs used in the expansion expression. While we're at it,
12100      compute the number of arguments to be expanded and make sure it
12101      is consistent.  */
12102   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
12103        pack = TREE_CHAIN (pack))
12104     {
12105       tree parm_pack = TREE_VALUE (pack);
12106       tree arg_pack = NULL_TREE;
12107       tree orig_arg = NULL_TREE;
12108       int level = 0;
12109 
12110       if (TREE_CODE (parm_pack) == BASES)
12111 	{
12112 	  gcc_assert (parm_pack == pattern);
12113 	  if (BASES_DIRECT (parm_pack))
12114 	    return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
12115 							args, complain,
12116 							in_decl, false),
12117 					   complain);
12118 	  else
12119 	    return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
12120 						 args, complain, in_decl,
12121 						 false), complain);
12122 	}
12123       else if (builtin_pack_call_p (parm_pack))
12124 	{
12125 	  /* ??? Support use in other patterns.  */
12126 	  gcc_assert (parm_pack == pattern);
12127 	  return expand_builtin_pack_call (parm_pack, args,
12128 					   complain, in_decl);
12129 	}
12130       else if (TREE_CODE (parm_pack) == PARM_DECL)
12131 	{
12132 	  /* We know we have correct local_specializations if this
12133 	     expansion is at function scope, or if we're dealing with a
12134 	     local parameter in a requires expression; for the latter,
12135 	     tsubst_requires_expr set it up appropriately.  */
12136 	  if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
12137 	    arg_pack = retrieve_local_specialization (parm_pack);
12138 	  else
12139 	    /* We can't rely on local_specializations for a parameter
12140 	       name used later in a function declaration (such as in a
12141 	       late-specified return type).  Even if it exists, it might
12142 	       have the wrong value for a recursive call.  */
12143 	    need_local_specializations = true;
12144 
12145 	  if (!arg_pack)
12146 	    {
12147 	      /* This parameter pack was used in an unevaluated context.  Just
12148 		 make a dummy decl, since it's only used for its type.  */
12149 	      ++cp_unevaluated_operand;
12150 	      arg_pack = tsubst_decl (parm_pack, args, complain);
12151 	      --cp_unevaluated_operand;
12152 	      if (arg_pack && DECL_PACK_P (arg_pack))
12153 		/* Partial instantiation of the parm_pack, we can't build
12154 		   up an argument pack yet.  */
12155 		arg_pack = NULL_TREE;
12156 	      else
12157 		arg_pack = make_fnparm_pack (arg_pack);
12158 	    }
12159 	  else if (argument_pack_element_is_expansion_p (arg_pack, 0))
12160 	    /* This argument pack isn't fully instantiated yet.  We set this
12161 	       flag rather than clear arg_pack because we do want to do the
12162 	       optimization below, and we don't want to substitute directly
12163 	       into the pattern (as that would expose a NONTYPE_ARGUMENT_PACK
12164 	       where it isn't expected).  */
12165 	    unsubstituted_fn_pack = true;
12166 	}
12167       else if (is_normal_capture_proxy (parm_pack))
12168 	{
12169 	  arg_pack = retrieve_local_specialization (parm_pack);
12170 	  if (argument_pack_element_is_expansion_p (arg_pack, 0))
12171 	    unsubstituted_fn_pack = true;
12172 	}
12173       else
12174         {
12175 	  int idx;
12176           template_parm_level_and_index (parm_pack, &level, &idx);
12177 
12178           if (level <= levels)
12179             arg_pack = TMPL_ARG (args, level, idx);
12180         }
12181 
12182       orig_arg = arg_pack;
12183       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12184 	arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12185 
12186       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
12187 	/* This can only happen if we forget to expand an argument
12188 	   pack somewhere else. Just return an error, silently.  */
12189 	{
12190 	  result = make_tree_vec (1);
12191 	  TREE_VEC_ELT (result, 0) = error_mark_node;
12192 	  return result;
12193 	}
12194 
12195       if (arg_pack)
12196         {
12197           int my_len =
12198             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
12199 
12200 	  /* Don't bother trying to do a partial substitution with
12201 	     incomplete packs; we'll try again after deduction.  */
12202           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
12203             return t;
12204 
12205           if (len < 0)
12206 	    len = my_len;
12207           else if (len != my_len
12208 		   && !unsubstituted_fn_pack)
12209             {
12210 	      if (!(complain & tf_error))
12211 		/* Fail quietly.  */;
12212               else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
12213                 error ("mismatched argument pack lengths while expanding %qT",
12214                        pattern);
12215               else
12216                 error ("mismatched argument pack lengths while expanding %qE",
12217                        pattern);
12218               return error_mark_node;
12219             }
12220 
12221           /* Keep track of the parameter packs and their corresponding
12222              argument packs.  */
12223           packs = tree_cons (parm_pack, arg_pack, packs);
12224           TREE_TYPE (packs) = orig_arg;
12225         }
12226       else
12227 	{
12228 	  /* We can't substitute for this parameter pack.  We use a flag as
12229 	     well as the missing_level counter because function parameter
12230 	     packs don't have a level.  */
12231 	  gcc_assert (processing_template_decl || is_auto (parm_pack));
12232 	  unsubstituted_packs = true;
12233 	}
12234     }
12235 
12236   /* If the expansion is just T..., return the matching argument pack, unless
12237      we need to call convert_from_reference on all the elements.  This is an
12238      important optimization; see c++/68422.  */
12239   if (!unsubstituted_packs
12240       && TREE_PURPOSE (packs) == pattern)
12241     {
12242       tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
12243 
12244       /* If the argument pack is a single pack expansion, pull it out.  */
12245       if (TREE_VEC_LENGTH (args) == 1
12246 	  && pack_expansion_args_count (args))
12247 	return TREE_VEC_ELT (args, 0);
12248 
12249       /* Types need no adjustment, nor does sizeof..., and if we still have
12250 	 some pack expansion args we won't do anything yet.  */
12251       if (TREE_CODE (t) == TYPE_PACK_EXPANSION
12252 	  || PACK_EXPANSION_SIZEOF_P (t)
12253 	  || pack_expansion_args_count (args))
12254 	return args;
12255       /* Also optimize expression pack expansions if we can tell that the
12256 	 elements won't have reference type.  */
12257       tree type = TREE_TYPE (pattern);
12258       if (type && TREE_CODE (type) != REFERENCE_TYPE
12259 	  && !PACK_EXPANSION_P (type)
12260 	  && !WILDCARD_TYPE_P (type))
12261 	return args;
12262       /* Otherwise use the normal path so we get convert_from_reference.  */
12263     }
12264 
12265   /* We cannot expand this expansion expression, because we don't have
12266      all of the argument packs we need.  */
12267   if (use_pack_expansion_extra_args_p (packs, len, unsubstituted_packs))
12268     {
12269       /* We got some full packs, but we can't substitute them in until we
12270 	 have values for all the packs.  So remember these until then.  */
12271 
12272       t = make_pack_expansion (pattern, complain);
12273       PACK_EXPANSION_EXTRA_ARGS (t)
12274 	= build_extra_args (pattern, args, complain);
12275       return t;
12276     }
12277   else if (unsubstituted_packs)
12278     {
12279       /* There were no real arguments, we're just replacing a parameter
12280 	 pack with another version of itself. Substitute into the
12281 	 pattern and return a PACK_EXPANSION_*. The caller will need to
12282 	 deal with that.  */
12283       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
12284 	t = tsubst_expr (pattern, args, complain, in_decl,
12285 			 /*integral_constant_expression_p=*/false);
12286       else
12287 	t = tsubst (pattern, args, complain, in_decl);
12288       t = make_pack_expansion (t, complain);
12289       return t;
12290     }
12291 
12292   gcc_assert (len >= 0);
12293 
12294   if (need_local_specializations)
12295     {
12296       /* We're in a late-specified return type, so create our own local
12297 	 specializations map; the current map is either NULL or (in the
12298 	 case of recursive unification) might have bindings that we don't
12299 	 want to use or alter.  */
12300       saved_local_specializations = local_specializations;
12301       local_specializations = new hash_map<tree, tree>;
12302     }
12303 
12304   /* For each argument in each argument pack, substitute into the
12305      pattern.  */
12306   result = make_tree_vec (len);
12307   tree elem_args = copy_template_args (args);
12308   for (i = 0; i < len; ++i)
12309     {
12310       t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
12311 						    i,
12312 						    elem_args, complain,
12313 						    in_decl);
12314       TREE_VEC_ELT (result, i) = t;
12315       if (t == error_mark_node)
12316 	{
12317 	  result = error_mark_node;
12318 	  break;
12319 	}
12320     }
12321 
12322   /* Update ARGS to restore the substitution from parameter packs to
12323      their argument packs.  */
12324   for (pack = packs; pack; pack = TREE_CHAIN (pack))
12325     {
12326       tree parm = TREE_PURPOSE (pack);
12327 
12328       if (TREE_CODE (parm) == PARM_DECL
12329 	  || VAR_P (parm)
12330 	  || TREE_CODE (parm) == FIELD_DECL)
12331         register_local_specialization (TREE_TYPE (pack), parm);
12332       else
12333         {
12334           int idx, level;
12335 
12336 	  if (TREE_VALUE (pack) == NULL_TREE)
12337 	    continue;
12338 
12339           template_parm_level_and_index (parm, &level, &idx);
12340 
12341           /* Update the corresponding argument.  */
12342           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
12343             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
12344               TREE_TYPE (pack);
12345           else
12346             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
12347         }
12348     }
12349 
12350   if (need_local_specializations)
12351     {
12352       delete local_specializations;
12353       local_specializations = saved_local_specializations;
12354     }
12355 
12356   /* If the dependent pack arguments were such that we end up with only a
12357      single pack expansion again, there's no need to keep it in a TREE_VEC.  */
12358   if (len == 1 && TREE_CODE (result) == TREE_VEC
12359       && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
12360     return TREE_VEC_ELT (result, 0);
12361 
12362   return result;
12363 }
12364 
12365 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
12366    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
12367    parameter packs; all parms generated from a function parameter pack will
12368    have the same DECL_PARM_INDEX.  */
12369 
12370 tree
get_pattern_parm(tree parm,tree tmpl)12371 get_pattern_parm (tree parm, tree tmpl)
12372 {
12373   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
12374   tree patparm;
12375 
12376   if (DECL_ARTIFICIAL (parm))
12377     {
12378       for (patparm = DECL_ARGUMENTS (pattern);
12379 	   patparm; patparm = DECL_CHAIN (patparm))
12380 	if (DECL_ARTIFICIAL (patparm)
12381 	    && DECL_NAME (parm) == DECL_NAME (patparm))
12382 	  break;
12383     }
12384   else
12385     {
12386       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
12387       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
12388       gcc_assert (DECL_PARM_INDEX (patparm)
12389 		  == DECL_PARM_INDEX (parm));
12390     }
12391 
12392   return patparm;
12393 }
12394 
12395 /* Make an argument pack out of the TREE_VEC VEC.  */
12396 
12397 static tree
make_argument_pack(tree vec)12398 make_argument_pack (tree vec)
12399 {
12400   tree pack;
12401   tree elt = TREE_VEC_ELT (vec, 0);
12402   if (TYPE_P (elt))
12403     pack = cxx_make_type (TYPE_ARGUMENT_PACK);
12404   else
12405     {
12406       pack = make_node (NONTYPE_ARGUMENT_PACK);
12407       TREE_CONSTANT (pack) = 1;
12408     }
12409   SET_ARGUMENT_PACK_ARGS (pack, vec);
12410   return pack;
12411 }
12412 
12413 /* Return an exact copy of template args T that can be modified
12414    independently.  */
12415 
12416 static tree
copy_template_args(tree t)12417 copy_template_args (tree t)
12418 {
12419   if (t == error_mark_node)
12420     return t;
12421 
12422   int len = TREE_VEC_LENGTH (t);
12423   tree new_vec = make_tree_vec (len);
12424 
12425   for (int i = 0; i < len; ++i)
12426     {
12427       tree elt = TREE_VEC_ELT (t, i);
12428       if (elt && TREE_CODE (elt) == TREE_VEC)
12429 	elt = copy_template_args (elt);
12430       TREE_VEC_ELT (new_vec, i) = elt;
12431     }
12432 
12433   NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
12434     = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
12435 
12436   return new_vec;
12437 }
12438 
12439 /* Substitute ARGS into the vector or list of template arguments T.  */
12440 
12441 static tree
tsubst_template_args(tree t,tree args,tsubst_flags_t complain,tree in_decl)12442 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12443 {
12444   tree orig_t = t;
12445   int len, need_new = 0, i, expanded_len_adjust = 0, out;
12446   tree *elts;
12447 
12448   if (t == error_mark_node)
12449     return error_mark_node;
12450 
12451   len = TREE_VEC_LENGTH (t);
12452   elts = XALLOCAVEC (tree, len);
12453 
12454   for (i = 0; i < len; i++)
12455     {
12456       tree orig_arg = TREE_VEC_ELT (t, i);
12457       tree new_arg;
12458 
12459       if (TREE_CODE (orig_arg) == TREE_VEC)
12460 	new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
12461       else if (PACK_EXPANSION_P (orig_arg))
12462         {
12463           /* Substitute into an expansion expression.  */
12464           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
12465 
12466           if (TREE_CODE (new_arg) == TREE_VEC)
12467             /* Add to the expanded length adjustment the number of
12468                expanded arguments. We subtract one from this
12469                measurement, because the argument pack expression
12470                itself is already counted as 1 in
12471                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
12472                the argument pack is empty.  */
12473             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
12474         }
12475       else if (ARGUMENT_PACK_P (orig_arg))
12476         {
12477           /* Substitute into each of the arguments.  */
12478           new_arg = TYPE_P (orig_arg)
12479             ? cxx_make_type (TREE_CODE (orig_arg))
12480             : make_node (TREE_CODE (orig_arg));
12481 
12482 	  tree pack_args = tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
12483 						 args, complain, in_decl);
12484           if (pack_args == error_mark_node)
12485             new_arg = error_mark_node;
12486 	  else
12487 	    SET_ARGUMENT_PACK_ARGS (new_arg, pack_args);
12488 
12489           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK)
12490 	    TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
12491         }
12492       else
12493 	new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
12494 
12495       if (new_arg == error_mark_node)
12496 	return error_mark_node;
12497 
12498       elts[i] = new_arg;
12499       if (new_arg != orig_arg)
12500 	need_new = 1;
12501     }
12502 
12503   if (!need_new)
12504     return t;
12505 
12506   /* Make space for the expanded arguments coming from template
12507      argument packs.  */
12508   t = make_tree_vec (len + expanded_len_adjust);
12509   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
12510      arguments for a member template.
12511      In that case each TREE_VEC in ORIG_T represents a level of template
12512      arguments, and ORIG_T won't carry any non defaulted argument count.
12513      It will rather be the nested TREE_VECs that will carry one.
12514      In other words, ORIG_T carries a non defaulted argument count only
12515      if it doesn't contain any nested TREE_VEC.  */
12516   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
12517     {
12518       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
12519       count += expanded_len_adjust;
12520       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
12521     }
12522   for (i = 0, out = 0; i < len; i++)
12523     {
12524       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
12525            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
12526           && TREE_CODE (elts[i]) == TREE_VEC)
12527         {
12528           int idx;
12529 
12530           /* Now expand the template argument pack "in place".  */
12531           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
12532             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
12533         }
12534       else
12535         {
12536           TREE_VEC_ELT (t, out) = elts[i];
12537           out++;
12538         }
12539     }
12540 
12541   return t;
12542 }
12543 
12544 /* Substitute ARGS into one level PARMS of template parameters.  */
12545 
12546 static tree
tsubst_template_parms_level(tree parms,tree args,tsubst_flags_t complain)12547 tsubst_template_parms_level (tree parms, tree args, tsubst_flags_t complain)
12548 {
12549   if (parms == error_mark_node)
12550     return error_mark_node;
12551 
12552   tree new_vec = make_tree_vec (TREE_VEC_LENGTH (parms));
12553 
12554   for (int i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
12555     {
12556       tree tuple = TREE_VEC_ELT (parms, i);
12557 
12558       if (tuple == error_mark_node)
12559 	continue;
12560 
12561       TREE_VEC_ELT (new_vec, i) =
12562 	tsubst_template_parm (tuple, args, complain);
12563     }
12564 
12565   return new_vec;
12566 }
12567 
12568 /* Return the result of substituting ARGS into the template parameters
12569    given by PARMS.  If there are m levels of ARGS and m + n levels of
12570    PARMS, then the result will contain n levels of PARMS.  For
12571    example, if PARMS is `template <class T> template <class U>
12572    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
12573    result will be `template <int*, double, class V>'.  */
12574 
12575 static tree
tsubst_template_parms(tree parms,tree args,tsubst_flags_t complain)12576 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
12577 {
12578   tree r = NULL_TREE;
12579   tree* new_parms;
12580 
12581   /* When substituting into a template, we must set
12582      PROCESSING_TEMPLATE_DECL as the template parameters may be
12583      dependent if they are based on one-another, and the dependency
12584      predicates are short-circuit outside of templates.  */
12585   ++processing_template_decl;
12586 
12587   for (new_parms = &r;
12588        parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
12589        new_parms = &(TREE_CHAIN (*new_parms)),
12590 	 parms = TREE_CHAIN (parms))
12591     {
12592       tree new_vec = tsubst_template_parms_level (TREE_VALUE (parms),
12593 						  args, complain);
12594       *new_parms =
12595 	tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
12596 			     - TMPL_ARGS_DEPTH (args)),
12597 		   new_vec, NULL_TREE);
12598     }
12599 
12600   --processing_template_decl;
12601 
12602   return r;
12603 }
12604 
12605 /* Return the result of substituting ARGS into one template parameter
12606    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
12607    parameter and which TREE_PURPOSE is the default argument of the
12608    template parameter.  */
12609 
12610 static tree
tsubst_template_parm(tree t,tree args,tsubst_flags_t complain)12611 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
12612 {
12613   tree default_value, parm_decl;
12614 
12615   if (args == NULL_TREE
12616       || t == NULL_TREE
12617       || t == error_mark_node)
12618     return t;
12619 
12620   gcc_assert (TREE_CODE (t) == TREE_LIST);
12621 
12622   default_value = TREE_PURPOSE (t);
12623   parm_decl = TREE_VALUE (t);
12624 
12625   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
12626   if (TREE_CODE (parm_decl) == PARM_DECL
12627       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
12628     parm_decl = error_mark_node;
12629   default_value = tsubst_template_arg (default_value, args,
12630 				       complain, NULL_TREE);
12631 
12632   return build_tree_list (default_value, parm_decl);
12633 }
12634 
12635 /* Substitute the ARGS into the indicated aggregate (or enumeration)
12636    type T.  If T is not an aggregate or enumeration type, it is
12637    handled as if by tsubst.  IN_DECL is as for tsubst.  If
12638    ENTERING_SCOPE is nonzero, T is the context for a template which
12639    we are presently tsubst'ing.  Return the substituted value.  */
12640 
12641 static tree
tsubst_aggr_type(tree t,tree args,tsubst_flags_t complain,tree in_decl,int entering_scope)12642 tsubst_aggr_type (tree t,
12643 		  tree args,
12644 		  tsubst_flags_t complain,
12645 		  tree in_decl,
12646 		  int entering_scope)
12647 {
12648   if (t == NULL_TREE)
12649     return NULL_TREE;
12650 
12651   switch (TREE_CODE (t))
12652     {
12653     case RECORD_TYPE:
12654       if (TYPE_PTRMEMFUNC_P (t))
12655 	return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
12656 
12657       /* Fall through.  */
12658     case ENUMERAL_TYPE:
12659     case UNION_TYPE:
12660       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
12661 	{
12662 	  tree argvec;
12663 	  tree context;
12664 	  tree r;
12665 	  int saved_unevaluated_operand;
12666 	  int saved_inhibit_evaluation_warnings;
12667 
12668 	  /* In "sizeof(X<I>)" we need to evaluate "I".  */
12669 	  saved_unevaluated_operand = cp_unevaluated_operand;
12670 	  cp_unevaluated_operand = 0;
12671 	  saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
12672 	  c_inhibit_evaluation_warnings = 0;
12673 
12674 	  /* First, determine the context for the type we are looking
12675 	     up.  */
12676 	  context = TYPE_CONTEXT (t);
12677 	  if (context && TYPE_P (context))
12678 	    {
12679 	      context = tsubst_aggr_type (context, args, complain,
12680 					  in_decl, /*entering_scope=*/1);
12681 	      /* If context is a nested class inside a class template,
12682 	         it may still need to be instantiated (c++/33959).  */
12683 	      context = complete_type (context);
12684 	    }
12685 
12686 	  /* Then, figure out what arguments are appropriate for the
12687 	     type we are trying to find.  For example, given:
12688 
12689 	       template <class T> struct S;
12690 	       template <class T, class U> void f(T, U) { S<U> su; }
12691 
12692 	     and supposing that we are instantiating f<int, double>,
12693 	     then our ARGS will be {int, double}, but, when looking up
12694 	     S we only want {double}.  */
12695 	  argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
12696 					 complain, in_decl);
12697 	  if (argvec == error_mark_node)
12698 	    r = error_mark_node;
12699 	  else
12700 	    {
12701 	      r = lookup_template_class (t, argvec, in_decl, context,
12702 					 entering_scope, complain);
12703 	      r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
12704 	    }
12705 
12706 	  cp_unevaluated_operand = saved_unevaluated_operand;
12707 	  c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
12708 
12709 	  return r;
12710 	}
12711       else
12712 	/* This is not a template type, so there's nothing to do.  */
12713 	return t;
12714 
12715     default:
12716       return tsubst (t, args, complain, in_decl);
12717     }
12718 }
12719 
12720 static GTY((cache)) tree_cache_map *defarg_inst;
12721 
12722 /* Substitute into the default argument ARG (a default argument for
12723    FN), which has the indicated TYPE.  */
12724 
12725 tree
tsubst_default_argument(tree fn,int parmnum,tree type,tree arg,tsubst_flags_t complain)12726 tsubst_default_argument (tree fn, int parmnum, tree type, tree arg,
12727 			 tsubst_flags_t complain)
12728 {
12729   tree saved_class_ptr = NULL_TREE;
12730   tree saved_class_ref = NULL_TREE;
12731   int errs = errorcount + sorrycount;
12732 
12733   /* This can happen in invalid code.  */
12734   if (TREE_CODE (arg) == DEFAULT_ARG)
12735     return arg;
12736 
12737   tree parm = FUNCTION_FIRST_USER_PARM (fn);
12738   parm = chain_index (parmnum, parm);
12739   tree parmtype = TREE_TYPE (parm);
12740   if (DECL_BY_REFERENCE (parm))
12741     parmtype = TREE_TYPE (parmtype);
12742   if (parmtype == error_mark_node)
12743     return error_mark_node;
12744 
12745   gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, parmtype));
12746 
12747   tree *slot;
12748   if (defarg_inst && (slot = defarg_inst->get (parm)))
12749     return *slot;
12750 
12751   /* This default argument came from a template.  Instantiate the
12752      default argument here, not in tsubst.  In the case of
12753      something like:
12754 
12755        template <class T>
12756        struct S {
12757 	 static T t();
12758 	 void f(T = t());
12759        };
12760 
12761      we must be careful to do name lookup in the scope of S<T>,
12762      rather than in the current class.  */
12763   push_access_scope (fn);
12764   /* The "this" pointer is not valid in a default argument.  */
12765   if (cfun)
12766     {
12767       saved_class_ptr = current_class_ptr;
12768       cp_function_chain->x_current_class_ptr = NULL_TREE;
12769       saved_class_ref = current_class_ref;
12770       cp_function_chain->x_current_class_ref = NULL_TREE;
12771     }
12772 
12773   start_lambda_scope (parm);
12774 
12775   push_deferring_access_checks(dk_no_deferred);
12776   /* The default argument expression may cause implicitly defined
12777      member functions to be synthesized, which will result in garbage
12778      collection.  We must treat this situation as if we were within
12779      the body of function so as to avoid collecting live data on the
12780      stack.  */
12781   ++function_depth;
12782   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
12783 		     complain, NULL_TREE,
12784 		     /*integral_constant_expression_p=*/false);
12785   --function_depth;
12786   pop_deferring_access_checks();
12787 
12788   finish_lambda_scope ();
12789 
12790   /* Restore the "this" pointer.  */
12791   if (cfun)
12792     {
12793       cp_function_chain->x_current_class_ptr = saved_class_ptr;
12794       cp_function_chain->x_current_class_ref = saved_class_ref;
12795     }
12796 
12797   if (errorcount+sorrycount > errs
12798       && (complain & tf_warning_or_error))
12799     inform (input_location,
12800 	    "  when instantiating default argument for call to %qD", fn);
12801 
12802   /* Make sure the default argument is reasonable.  */
12803   arg = check_default_argument (type, arg, complain);
12804 
12805   pop_access_scope (fn);
12806 
12807   if (arg != error_mark_node && !cp_unevaluated_operand)
12808     {
12809       if (!defarg_inst)
12810 	defarg_inst = tree_cache_map::create_ggc (37);
12811       defarg_inst->put (parm, arg);
12812     }
12813 
12814   return arg;
12815 }
12816 
12817 /* Substitute into all the default arguments for FN.  */
12818 
12819 static void
tsubst_default_arguments(tree fn,tsubst_flags_t complain)12820 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
12821 {
12822   tree arg;
12823   tree tmpl_args;
12824 
12825   tmpl_args = DECL_TI_ARGS (fn);
12826 
12827   /* If this function is not yet instantiated, we certainly don't need
12828      its default arguments.  */
12829   if (uses_template_parms (tmpl_args))
12830     return;
12831   /* Don't do this again for clones.  */
12832   if (DECL_CLONED_FUNCTION_P (fn))
12833     return;
12834 
12835   int i = 0;
12836   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
12837        arg;
12838        arg = TREE_CHAIN (arg), ++i)
12839     if (TREE_PURPOSE (arg))
12840       TREE_PURPOSE (arg) = tsubst_default_argument (fn, i,
12841 						    TREE_VALUE (arg),
12842 						    TREE_PURPOSE (arg),
12843 						    complain);
12844 }
12845 
12846 /* Subroutine of tsubst_decl for the case when T is a FUNCTION_DECL.  */
12847 
12848 static tree
tsubst_function_decl(tree t,tree args,tsubst_flags_t complain,tree lambda_fntype)12849 tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
12850 		      tree lambda_fntype)
12851 {
12852   tree gen_tmpl, argvec;
12853   hashval_t hash = 0;
12854   tree in_decl = t;
12855 
12856   /* Nobody should be tsubst'ing into non-template functions.  */
12857   gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
12858 
12859   if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
12860     {
12861       /* If T is not dependent, just return it.  */
12862       if (!uses_template_parms (DECL_TI_ARGS (t)))
12863 	return t;
12864 
12865       /* Calculate the most general template of which R is a
12866 	 specialization.  */
12867       gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
12868 
12869       /* We're substituting a lambda function under tsubst_lambda_expr but not
12870 	 directly from it; find the matching function we're already inside.
12871 	 But don't do this if T is a generic lambda with a single level of
12872 	 template parms, as in that case we're doing a normal instantiation. */
12873       if (LAMBDA_FUNCTION_P (t) && !lambda_fntype
12874 	  && (!generic_lambda_fn_p (t)
12875 	      || TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)) > 1))
12876 	return enclosing_instantiation_of (t);
12877 
12878       /* Calculate the complete set of arguments used to
12879 	 specialize R.  */
12880       argvec = tsubst_template_args (DECL_TI_ARGS
12881 				     (DECL_TEMPLATE_RESULT
12882 				      (DECL_TI_TEMPLATE (t))),
12883 				     args, complain, in_decl);
12884       if (argvec == error_mark_node)
12885 	return error_mark_node;
12886 
12887       /* Check to see if we already have this specialization.  */
12888       if (!lambda_fntype)
12889 	{
12890 	  hash = hash_tmpl_and_args (gen_tmpl, argvec);
12891 	  if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
12892 	    return spec;
12893 	}
12894 
12895       /* We can see more levels of arguments than parameters if
12896 	 there was a specialization of a member template, like
12897 	 this:
12898 
12899 	 template <class T> struct S { template <class U> void f(); }
12900 	 template <> template <class U> void S<int>::f(U);
12901 
12902 	 Here, we'll be substituting into the specialization,
12903 	 because that's where we can find the code we actually
12904 	 want to generate, but we'll have enough arguments for
12905 	 the most general template.
12906 
12907 	 We also deal with the peculiar case:
12908 
12909 	 template <class T> struct S {
12910 	   template <class U> friend void f();
12911 	 };
12912 	 template <class U> void f() {}
12913 	 template S<int>;
12914 	 template void f<double>();
12915 
12916 	 Here, the ARGS for the instantiation of will be {int,
12917 	 double}.  But, we only need as many ARGS as there are
12918 	 levels of template parameters in CODE_PATTERN.  We are
12919 	 careful not to get fooled into reducing the ARGS in
12920 	 situations like:
12921 
12922 	 template <class T> struct S { template <class U> void f(U); }
12923 	 template <class T> template <> void S<T>::f(int) {}
12924 
12925 	 which we can spot because the pattern will be a
12926 	 specialization in this case.  */
12927       int args_depth = TMPL_ARGS_DEPTH (args);
12928       int parms_depth =
12929 	TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
12930 
12931       if (args_depth > parms_depth && !DECL_TEMPLATE_SPECIALIZATION (t))
12932 	args = get_innermost_template_args (args, parms_depth);
12933     }
12934   else
12935     {
12936       /* This special case arises when we have something like this:
12937 
12938 	 template <class T> struct S {
12939 	 friend void f<int>(int, double);
12940 	 };
12941 
12942 	 Here, the DECL_TI_TEMPLATE for the friend declaration
12943 	 will be an IDENTIFIER_NODE.  We are being called from
12944 	 tsubst_friend_function, and we want only to create a
12945 	 new decl (R) with appropriate types so that we can call
12946 	 determine_specialization.  */
12947       gen_tmpl = NULL_TREE;
12948       argvec = NULL_TREE;
12949     }
12950 
12951   tree closure = (lambda_fntype ? TYPE_METHOD_BASETYPE (lambda_fntype)
12952 		  : NULL_TREE);
12953   tree ctx = closure ? closure : DECL_CONTEXT (t);
12954   bool member = ctx && TYPE_P (ctx);
12955 
12956   if (member && !closure)
12957     ctx = tsubst_aggr_type (ctx, args,
12958 			    complain, t, /*entering_scope=*/1);
12959 
12960   tree type = (lambda_fntype ? lambda_fntype
12961 	       : tsubst (TREE_TYPE (t), args,
12962 			 complain | tf_fndecl_type, in_decl));
12963   if (type == error_mark_node)
12964     return error_mark_node;
12965 
12966   /* If we hit excessive deduction depth, the type is bogus even if
12967      it isn't error_mark_node, so don't build a decl.  */
12968   if (excessive_deduction_depth)
12969     return error_mark_node;
12970 
12971   /* We do NOT check for matching decls pushed separately at this
12972      point, as they may not represent instantiations of this
12973      template, and in any case are considered separate under the
12974      discrete model.  */
12975   tree r = copy_decl (t);
12976   DECL_USE_TEMPLATE (r) = 0;
12977   TREE_TYPE (r) = type;
12978   /* Clear out the mangled name and RTL for the instantiation.  */
12979   SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
12980   SET_DECL_RTL (r, NULL);
12981   /* Leave DECL_INITIAL set on deleted instantiations.  */
12982   if (!DECL_DELETED_FN (r))
12983     DECL_INITIAL (r) = NULL_TREE;
12984   DECL_CONTEXT (r) = ctx;
12985 
12986   /* OpenMP UDRs have the only argument a reference to the declared
12987      type.  We want to diagnose if the declared type is a reference,
12988      which is invalid, but as references to references are usually
12989      quietly merged, diagnose it here.  */
12990   if (DECL_OMP_DECLARE_REDUCTION_P (t))
12991     {
12992       tree argtype
12993 	= TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
12994       argtype = tsubst (argtype, args, complain, in_decl);
12995       if (TREE_CODE (argtype) == REFERENCE_TYPE)
12996 	error_at (DECL_SOURCE_LOCATION (t),
12997 		  "reference type %qT in "
12998 		  "%<#pragma omp declare reduction%>", argtype);
12999       if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
13000 	DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
13001 					  argtype);
13002     }
13003 
13004   if (member && DECL_CONV_FN_P (r))
13005     /* Type-conversion operator.  Reconstruct the name, in
13006        case it's the name of one of the template's parameters.  */
13007     DECL_NAME (r) = make_conv_op_name (TREE_TYPE (type));
13008 
13009   tree parms = DECL_ARGUMENTS (t);
13010   if (closure)
13011     parms = DECL_CHAIN (parms);
13012   parms = tsubst (parms, args, complain, t);
13013   for (tree parm = parms; parm; parm = DECL_CHAIN (parm))
13014     DECL_CONTEXT (parm) = r;
13015   if (closure)
13016     {
13017       tree tparm = build_this_parm (r, closure, type_memfn_quals (type));
13018       DECL_CHAIN (tparm) = parms;
13019       parms = tparm;
13020     }
13021   DECL_ARGUMENTS (r) = parms;
13022   DECL_RESULT (r) = NULL_TREE;
13023 
13024   TREE_STATIC (r) = 0;
13025   TREE_PUBLIC (r) = TREE_PUBLIC (t);
13026   DECL_EXTERNAL (r) = 1;
13027   /* If this is an instantiation of a function with internal
13028      linkage, we already know what object file linkage will be
13029      assigned to the instantiation.  */
13030   DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
13031   DECL_DEFER_OUTPUT (r) = 0;
13032   DECL_CHAIN (r) = NULL_TREE;
13033   DECL_PENDING_INLINE_INFO (r) = 0;
13034   DECL_PENDING_INLINE_P (r) = 0;
13035   DECL_SAVED_TREE (r) = NULL_TREE;
13036   DECL_STRUCT_FUNCTION (r) = NULL;
13037   TREE_USED (r) = 0;
13038   /* We'll re-clone as appropriate in instantiate_template.  */
13039   DECL_CLONED_FUNCTION (r) = NULL_TREE;
13040 
13041   /* If we aren't complaining now, return on error before we register
13042      the specialization so that we'll complain eventually.  */
13043   if ((complain & tf_error) == 0
13044       && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
13045       && !grok_op_properties (r, /*complain=*/false))
13046     return error_mark_node;
13047 
13048   /* When instantiating a constrained member, substitute
13049      into the constraints to create a new constraint.  */
13050   if (tree ci = get_constraints (t))
13051     if (member)
13052       {
13053 	ci = tsubst_constraint_info (ci, argvec, complain, NULL_TREE);
13054 	set_constraints (r, ci);
13055       }
13056 
13057   if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
13058     SET_DECL_FRIEND_CONTEXT (r,
13059 			     tsubst (DECL_FRIEND_CONTEXT (t),
13060 				     args, complain, in_decl));
13061 
13062   /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
13063      this in the special friend case mentioned above where
13064      GEN_TMPL is NULL.  */
13065   if (gen_tmpl && !closure)
13066     {
13067       DECL_TEMPLATE_INFO (r)
13068 	= build_template_info (gen_tmpl, argvec);
13069       SET_DECL_IMPLICIT_INSTANTIATION (r);
13070 
13071       tree new_r
13072 	= register_specialization (r, gen_tmpl, argvec, false, hash);
13073       if (new_r != r)
13074 	/* We instantiated this while substituting into
13075 	   the type earlier (template/friend54.C).  */
13076 	return new_r;
13077 
13078       /* We're not supposed to instantiate default arguments
13079 	 until they are called, for a template.  But, for a
13080 	 declaration like:
13081 
13082 	 template <class T> void f ()
13083 	 { extern void g(int i = T()); }
13084 
13085 	 we should do the substitution when the template is
13086 	 instantiated.  We handle the member function case in
13087 	 instantiate_class_template since the default arguments
13088 	 might refer to other members of the class.  */
13089       if (!member
13090 	  && !PRIMARY_TEMPLATE_P (gen_tmpl)
13091 	  && !uses_template_parms (argvec))
13092 	tsubst_default_arguments (r, complain);
13093     }
13094   else
13095     DECL_TEMPLATE_INFO (r) = NULL_TREE;
13096 
13097   /* Copy the list of befriending classes.  */
13098   for (tree *friends = &DECL_BEFRIENDING_CLASSES (r);
13099        *friends;
13100        friends = &TREE_CHAIN (*friends))
13101     {
13102       *friends = copy_node (*friends);
13103       TREE_VALUE (*friends)
13104 	= tsubst (TREE_VALUE (*friends), args, complain, in_decl);
13105     }
13106 
13107   if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
13108     {
13109       maybe_retrofit_in_chrg (r);
13110       if (DECL_CONSTRUCTOR_P (r) && !grok_ctor_properties (ctx, r))
13111 	return error_mark_node;
13112       /* If this is an instantiation of a member template, clone it.
13113 	 If it isn't, that'll be handled by
13114 	 clone_constructors_and_destructors.  */
13115       if (PRIMARY_TEMPLATE_P (gen_tmpl))
13116 	clone_function_decl (r, /*update_methods=*/false);
13117     }
13118   else if ((complain & tf_error) != 0
13119 	   && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
13120 	   && !grok_op_properties (r, /*complain=*/true))
13121     return error_mark_node;
13122 
13123   /* Possibly limit visibility based on template args.  */
13124   DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
13125   if (DECL_VISIBILITY_SPECIFIED (t))
13126     {
13127       DECL_VISIBILITY_SPECIFIED (r) = 0;
13128       DECL_ATTRIBUTES (r)
13129 	= remove_attribute ("visibility", DECL_ATTRIBUTES (r));
13130     }
13131   determine_visibility (r);
13132   if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
13133       && !processing_template_decl)
13134     defaulted_late_check (r);
13135 
13136   apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
13137 				  args, complain, in_decl);
13138   return r;
13139 }
13140 
13141 /* Subroutine of tsubst_decl for the case when T is a TEMPLATE_DECL.  */
13142 
13143 static tree
tsubst_template_decl(tree t,tree args,tsubst_flags_t complain,tree lambda_fntype)13144 tsubst_template_decl (tree t, tree args, tsubst_flags_t complain,
13145 		      tree lambda_fntype)
13146 {
13147   /* We can get here when processing a member function template,
13148      member class template, or template template parameter.  */
13149   tree decl = DECL_TEMPLATE_RESULT (t);
13150   tree in_decl = t;
13151   tree spec;
13152   tree tmpl_args;
13153   tree full_args;
13154   tree r;
13155   hashval_t hash = 0;
13156 
13157   if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
13158     {
13159       /* Template template parameter is treated here.  */
13160       tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13161       if (new_type == error_mark_node)
13162 	r = error_mark_node;
13163       /* If we get a real template back, return it.  This can happen in
13164 	 the context of most_specialized_partial_spec.  */
13165       else if (TREE_CODE (new_type) == TEMPLATE_DECL)
13166 	r = new_type;
13167       else
13168 	/* The new TEMPLATE_DECL was built in
13169 	   reduce_template_parm_level.  */
13170 	r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
13171       return r;
13172     }
13173 
13174   if (!lambda_fntype)
13175     {
13176       /* We might already have an instance of this template.
13177 	 The ARGS are for the surrounding class type, so the
13178 	 full args contain the tsubst'd args for the context,
13179 	 plus the innermost args from the template decl.  */
13180       tmpl_args = DECL_CLASS_TEMPLATE_P (t)
13181 	? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
13182 	: DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
13183       /* Because this is a template, the arguments will still be
13184 	 dependent, even after substitution.  If
13185 	 PROCESSING_TEMPLATE_DECL is not set, the dependency
13186 	 predicates will short-circuit.  */
13187       ++processing_template_decl;
13188       full_args = tsubst_template_args (tmpl_args, args,
13189 					complain, in_decl);
13190       --processing_template_decl;
13191       if (full_args == error_mark_node)
13192 	return error_mark_node;
13193 
13194       /* If this is a default template template argument,
13195 	 tsubst might not have changed anything.  */
13196       if (full_args == tmpl_args)
13197 	return t;
13198 
13199       hash = hash_tmpl_and_args (t, full_args);
13200       spec = retrieve_specialization (t, full_args, hash);
13201       if (spec != NULL_TREE)
13202 	return spec;
13203     }
13204 
13205   /* Make a new template decl.  It will be similar to the
13206      original, but will record the current template arguments.
13207      We also create a new function declaration, which is just
13208      like the old one, but points to this new template, rather
13209      than the old one.  */
13210   r = copy_decl (t);
13211   gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
13212   DECL_CHAIN (r) = NULL_TREE;
13213 
13214   // Build new template info linking to the original template decl.
13215   if (!lambda_fntype)
13216     {
13217       DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
13218       SET_DECL_IMPLICIT_INSTANTIATION (r);
13219     }
13220   else
13221     DECL_TEMPLATE_INFO (r) = NULL_TREE;
13222 
13223   /* The template parameters for this new template are all the
13224      template parameters for the old template, except the
13225      outermost level of parameters.  */
13226   DECL_TEMPLATE_PARMS (r)
13227     = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
13228 			     complain);
13229 
13230   if (TREE_CODE (decl) == TYPE_DECL
13231       && !TYPE_DECL_ALIAS_P (decl))
13232     {
13233       tree new_type;
13234       ++processing_template_decl;
13235       new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13236       --processing_template_decl;
13237       if (new_type == error_mark_node)
13238 	return error_mark_node;
13239 
13240       TREE_TYPE (r) = new_type;
13241       /* For a partial specialization, we need to keep pointing to
13242 	 the primary template.  */
13243       if (!DECL_TEMPLATE_SPECIALIZATION (t))
13244 	CLASSTYPE_TI_TEMPLATE (new_type) = r;
13245       DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
13246       DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
13247       DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
13248     }
13249   else
13250     {
13251       tree new_decl;
13252       ++processing_template_decl;
13253       if (TREE_CODE (decl) == FUNCTION_DECL)
13254 	new_decl = tsubst_function_decl (decl, args, complain, lambda_fntype);
13255       else
13256 	new_decl = tsubst (decl, args, complain, in_decl);
13257       --processing_template_decl;
13258       if (new_decl == error_mark_node)
13259 	return error_mark_node;
13260 
13261       DECL_TEMPLATE_RESULT (r) = new_decl;
13262       TREE_TYPE (r) = TREE_TYPE (new_decl);
13263       DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
13264       if (lambda_fntype)
13265 	{
13266 	  tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (r));
13267 	  DECL_TEMPLATE_INFO (new_decl) = build_template_info (r, args);
13268 	}
13269       else
13270 	{
13271 	  DECL_TI_TEMPLATE (new_decl) = r;
13272 	  DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
13273 	}
13274     }
13275 
13276   DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
13277   DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
13278 
13279   if (PRIMARY_TEMPLATE_P (t))
13280     DECL_PRIMARY_TEMPLATE (r) = r;
13281 
13282   if (TREE_CODE (decl) != TYPE_DECL && !VAR_P (decl)
13283       && !lambda_fntype)
13284     /* Record this non-type partial instantiation.  */
13285     register_specialization (r, t,
13286 			     DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
13287 			     false, hash);
13288 
13289   return r;
13290 }
13291 
13292 /* True if FN is the op() for a lambda in an uninstantiated template.  */
13293 
13294 bool
lambda_fn_in_template_p(tree fn)13295 lambda_fn_in_template_p (tree fn)
13296 {
13297   if (!fn || !LAMBDA_FUNCTION_P (fn))
13298     return false;
13299   tree closure = DECL_CONTEXT (fn);
13300   return CLASSTYPE_TEMPLATE_INFO (closure) != NULL_TREE;
13301 }
13302 
13303 /* We're instantiating a variable from template function TCTX.  Return the
13304    corresponding current enclosing scope.  This gets complicated because lambda
13305    functions in templates are regenerated rather than instantiated, but generic
13306    lambda functions are subsequently instantiated.  */
13307 
13308 static tree
enclosing_instantiation_of(tree otctx)13309 enclosing_instantiation_of (tree otctx)
13310 {
13311   tree tctx = otctx;
13312   tree fn = current_function_decl;
13313   int lambda_count = 0;
13314 
13315   for (; tctx && lambda_fn_in_template_p (tctx);
13316        tctx = decl_function_context (tctx))
13317     ++lambda_count;
13318   for (; fn; fn = decl_function_context (fn))
13319     {
13320       tree ofn = fn;
13321       int flambda_count = 0;
13322       for (; flambda_count < lambda_count && fn && LAMBDA_FUNCTION_P (fn);
13323 	   fn = decl_function_context (fn))
13324 	++flambda_count;
13325       if ((fn && DECL_TEMPLATE_INFO (fn))
13326 	  ? most_general_template (fn) != most_general_template (tctx)
13327 	  : fn != tctx)
13328 	continue;
13329       gcc_assert (DECL_NAME (ofn) == DECL_NAME (otctx)
13330 		  || DECL_CONV_FN_P (ofn));
13331       return ofn;
13332     }
13333   gcc_unreachable ();
13334 }
13335 
13336 /* Substitute the ARGS into the T, which is a _DECL.  Return the
13337    result of the substitution.  Issue error and warning messages under
13338    control of COMPLAIN.  */
13339 
13340 static tree
tsubst_decl(tree t,tree args,tsubst_flags_t complain)13341 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
13342 {
13343 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
13344   location_t saved_loc;
13345   tree r = NULL_TREE;
13346   tree in_decl = t;
13347   hashval_t hash = 0;
13348 
13349   /* Set the filename and linenumber to improve error-reporting.  */
13350   saved_loc = input_location;
13351   input_location = DECL_SOURCE_LOCATION (t);
13352 
13353   switch (TREE_CODE (t))
13354     {
13355     case TEMPLATE_DECL:
13356       r = tsubst_template_decl (t, args, complain, /*lambda*/NULL_TREE);
13357       break;
13358 
13359     case FUNCTION_DECL:
13360       r = tsubst_function_decl (t, args, complain, /*lambda*/NULL_TREE);
13361       break;
13362 
13363     case PARM_DECL:
13364       {
13365 	tree type = NULL_TREE;
13366         int i, len = 1;
13367         tree expanded_types = NULL_TREE;
13368         tree prev_r = NULL_TREE;
13369         tree first_r = NULL_TREE;
13370 
13371         if (DECL_PACK_P (t))
13372           {
13373             /* If there is a local specialization that isn't a
13374                parameter pack, it means that we're doing a "simple"
13375                substitution from inside tsubst_pack_expansion. Just
13376                return the local specialization (which will be a single
13377                parm).  */
13378             tree spec = retrieve_local_specialization (t);
13379             if (spec
13380                 && TREE_CODE (spec) == PARM_DECL
13381                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
13382               RETURN (spec);
13383 
13384             /* Expand the TYPE_PACK_EXPANSION that provides the types for
13385                the parameters in this function parameter pack.  */
13386             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
13387 						    complain, in_decl);
13388             if (TREE_CODE (expanded_types) == TREE_VEC)
13389               {
13390                 len = TREE_VEC_LENGTH (expanded_types);
13391 
13392                 /* Zero-length parameter packs are boring. Just substitute
13393                    into the chain.  */
13394 		if (len == 0 && !cp_unevaluated_operand)
13395                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
13396 				  TREE_CHAIN (t)));
13397               }
13398             else
13399               {
13400                 /* All we did was update the type. Make a note of that.  */
13401                 type = expanded_types;
13402                 expanded_types = NULL_TREE;
13403               }
13404           }
13405 
13406         /* Loop through all of the parameters we'll build. When T is
13407            a function parameter pack, LEN is the number of expanded
13408            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
13409         r = NULL_TREE;
13410         for (i = 0; i < len; ++i)
13411           {
13412             prev_r = r;
13413             r = copy_node (t);
13414             if (DECL_TEMPLATE_PARM_P (t))
13415               SET_DECL_TEMPLATE_PARM_P (r);
13416 
13417             if (expanded_types)
13418               /* We're on the Ith parameter of the function parameter
13419                  pack.  */
13420               {
13421                 /* Get the Ith type.  */
13422                 type = TREE_VEC_ELT (expanded_types, i);
13423 
13424 		/* Rename the parameter to include the index.  */
13425 		DECL_NAME (r)
13426 		  = make_ith_pack_parameter_name (DECL_NAME (r), i);
13427               }
13428             else if (!type)
13429               /* We're dealing with a normal parameter.  */
13430               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13431 
13432             type = type_decays_to (type);
13433             TREE_TYPE (r) = type;
13434             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
13435 
13436             if (DECL_INITIAL (r))
13437               {
13438                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
13439                   DECL_INITIAL (r) = TREE_TYPE (r);
13440                 else
13441                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
13442                                              complain, in_decl);
13443               }
13444 
13445             DECL_CONTEXT (r) = NULL_TREE;
13446 
13447             if (!DECL_TEMPLATE_PARM_P (r))
13448               DECL_ARG_TYPE (r) = type_passed_as (type);
13449 
13450 	    apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
13451 					    args, complain, in_decl);
13452 
13453             /* Keep track of the first new parameter we
13454                generate. That's what will be returned to the
13455                caller.  */
13456             if (!first_r)
13457               first_r = r;
13458 
13459             /* Build a proper chain of parameters when substituting
13460                into a function parameter pack.  */
13461             if (prev_r)
13462               DECL_CHAIN (prev_r) = r;
13463           }
13464 
13465 	/* If cp_unevaluated_operand is set, we're just looking for a
13466 	   single dummy parameter, so don't keep going.  */
13467 	if (DECL_CHAIN (t) && !cp_unevaluated_operand)
13468 	  DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
13469 				   complain, DECL_CHAIN (t));
13470 
13471         /* FIRST_R contains the start of the chain we've built.  */
13472         r = first_r;
13473       }
13474       break;
13475 
13476     case FIELD_DECL:
13477       {
13478 	tree type = NULL_TREE;
13479 	tree vec = NULL_TREE;
13480 	tree expanded_types = NULL_TREE;
13481 	int len = 1;
13482 
13483 	if (PACK_EXPANSION_P (TREE_TYPE (t)))
13484 	  {
13485 	    /* This field is a lambda capture pack.  Return a TREE_VEC of
13486 	       the expanded fields to instantiate_class_template_1.  */
13487             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
13488 						    complain, in_decl);
13489             if (TREE_CODE (expanded_types) == TREE_VEC)
13490               {
13491                 len = TREE_VEC_LENGTH (expanded_types);
13492 		vec = make_tree_vec (len);
13493               }
13494             else
13495               {
13496                 /* All we did was update the type. Make a note of that.  */
13497                 type = expanded_types;
13498                 expanded_types = NULL_TREE;
13499               }
13500 	  }
13501 
13502 	for (int i = 0; i < len; ++i)
13503 	  {
13504 	    r = copy_decl (t);
13505 	    if (expanded_types)
13506 	      {
13507 		type = TREE_VEC_ELT (expanded_types, i);
13508 		DECL_NAME (r)
13509 		  = make_ith_pack_parameter_name (DECL_NAME (r), i);
13510 	      }
13511             else if (!type)
13512               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13513 
13514 	    if (type == error_mark_node)
13515 	      RETURN (error_mark_node);
13516 	    TREE_TYPE (r) = type;
13517 	    cp_apply_type_quals_to_decl (cp_type_quals (type), r);
13518 
13519 	    if (DECL_C_BIT_FIELD (r))
13520 	      /* For bit-fields, DECL_BIT_FIELD_REPRESENTATIVE gives the
13521 		 number of bits.  */
13522 	      DECL_BIT_FIELD_REPRESENTATIVE (r)
13523 		= tsubst_expr (DECL_BIT_FIELD_REPRESENTATIVE (t), args,
13524 			       complain, in_decl,
13525 			       /*integral_constant_expression_p=*/true);
13526 	    if (DECL_INITIAL (t))
13527 	      {
13528 		/* Set up DECL_TEMPLATE_INFO so that we can get at the
13529 		   NSDMI in perform_member_init.  Still set DECL_INITIAL
13530 		   so that we know there is one.  */
13531 		DECL_INITIAL (r) = void_node;
13532 		gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
13533 		retrofit_lang_decl (r);
13534 		DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
13535 	      }
13536 	    /* We don't have to set DECL_CONTEXT here; it is set by
13537 	       finish_member_declaration.  */
13538 	    DECL_CHAIN (r) = NULL_TREE;
13539 
13540 	    apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
13541 					    args, complain, in_decl);
13542 
13543 	    if (vec)
13544 	      TREE_VEC_ELT (vec, i) = r;
13545 	  }
13546 
13547 	if (vec)
13548 	  r = vec;
13549       }
13550       break;
13551 
13552     case USING_DECL:
13553       /* We reach here only for member using decls.  We also need to check
13554 	 uses_template_parms because DECL_DEPENDENT_P is not set for a
13555 	 using-declaration that designates a member of the current
13556 	 instantiation (c++/53549).  */
13557       if (DECL_DEPENDENT_P (t)
13558 	  || uses_template_parms (USING_DECL_SCOPE (t)))
13559 	{
13560 	  tree scope = USING_DECL_SCOPE (t);
13561 	  tree name = tsubst_copy (DECL_NAME (t), args, complain, in_decl);
13562 	  if (PACK_EXPANSION_P (scope))
13563 	    {
13564 	      tree vec = tsubst_pack_expansion (scope, args, complain, in_decl);
13565 	      int len = TREE_VEC_LENGTH (vec);
13566 	      r = make_tree_vec (len);
13567 	      for (int i = 0; i < len; ++i)
13568 		{
13569 		  tree escope = TREE_VEC_ELT (vec, i);
13570 		  tree elt = do_class_using_decl (escope, name);
13571 		  if (!elt)
13572 		    {
13573 		      r = error_mark_node;
13574 		      break;
13575 		    }
13576 		  else
13577 		    {
13578 		      TREE_PROTECTED (elt) = TREE_PROTECTED (t);
13579 		      TREE_PRIVATE (elt) = TREE_PRIVATE (t);
13580 		    }
13581 		  TREE_VEC_ELT (r, i) = elt;
13582 		}
13583 	    }
13584 	  else
13585 	    {
13586 	      tree inst_scope = tsubst_copy (USING_DECL_SCOPE (t), args,
13587 					     complain, in_decl);
13588 	      r = do_class_using_decl (inst_scope, name);
13589 	      if (!r)
13590 		r = error_mark_node;
13591 	      else
13592 		{
13593 		  TREE_PROTECTED (r) = TREE_PROTECTED (t);
13594 		  TREE_PRIVATE (r) = TREE_PRIVATE (t);
13595 		}
13596 	    }
13597 	}
13598       else
13599 	{
13600 	  r = copy_node (t);
13601 	  DECL_CHAIN (r) = NULL_TREE;
13602 	}
13603       break;
13604 
13605     case TYPE_DECL:
13606     case VAR_DECL:
13607       {
13608 	tree argvec = NULL_TREE;
13609 	tree gen_tmpl = NULL_TREE;
13610 	tree spec;
13611 	tree tmpl = NULL_TREE;
13612 	tree ctx;
13613 	tree type = NULL_TREE;
13614 	bool local_p;
13615 
13616 	if (TREE_TYPE (t) == error_mark_node)
13617 	  RETURN (error_mark_node);
13618 
13619 	if (TREE_CODE (t) == TYPE_DECL
13620 	    && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
13621 	  {
13622 	    /* If this is the canonical decl, we don't have to
13623 	       mess with instantiations, and often we can't (for
13624 	       typename, template type parms and such).  Note that
13625 	       TYPE_NAME is not correct for the above test if
13626 	       we've copied the type for a typedef.  */
13627 	    type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13628 	    if (type == error_mark_node)
13629 	      RETURN (error_mark_node);
13630 	    r = TYPE_NAME (type);
13631 	    break;
13632 	  }
13633 
13634 	/* Check to see if we already have the specialization we
13635 	   need.  */
13636 	spec = NULL_TREE;
13637 	if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
13638 	  {
13639 	    /* T is a static data member or namespace-scope entity.
13640 	       We have to substitute into namespace-scope variables
13641 	       (not just variable templates) because of cases like:
13642 
13643 	         template <class T> void f() { extern T t; }
13644 
13645 	       where the entity referenced is not known until
13646 	       instantiation time.  */
13647 	    local_p = false;
13648 	    ctx = DECL_CONTEXT (t);
13649 	    if (DECL_CLASS_SCOPE_P (t))
13650 	      {
13651 		ctx = tsubst_aggr_type (ctx, args,
13652 					complain,
13653 					in_decl, /*entering_scope=*/1);
13654 		/* If CTX is unchanged, then T is in fact the
13655 		   specialization we want.  That situation occurs when
13656 		   referencing a static data member within in its own
13657 		   class.  We can use pointer equality, rather than
13658 		   same_type_p, because DECL_CONTEXT is always
13659 		   canonical...  */
13660 		if (ctx == DECL_CONTEXT (t)
13661 		    /* ... unless T is a member template; in which
13662 		       case our caller can be willing to create a
13663 		       specialization of that template represented
13664 		       by T.  */
13665 		    && !(DECL_TI_TEMPLATE (t)
13666 			 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
13667 		  spec = t;
13668 	      }
13669 
13670 	    if (!spec)
13671 	      {
13672 		tmpl = DECL_TI_TEMPLATE (t);
13673 		gen_tmpl = most_general_template (tmpl);
13674 		argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
13675 		if (argvec != error_mark_node)
13676 		  argvec = (coerce_innermost_template_parms
13677 			    (DECL_TEMPLATE_PARMS (gen_tmpl),
13678 			     argvec, t, complain,
13679 			     /*all*/true, /*defarg*/true));
13680 		if (argvec == error_mark_node)
13681 		  RETURN (error_mark_node);
13682 		hash = hash_tmpl_and_args (gen_tmpl, argvec);
13683 		spec = retrieve_specialization (gen_tmpl, argvec, hash);
13684 	      }
13685 	  }
13686 	else
13687 	  {
13688 	    /* A local variable.  */
13689 	    local_p = true;
13690 	    /* Subsequent calls to pushdecl will fill this in.  */
13691 	    ctx = NULL_TREE;
13692 	    /* Unless this is a reference to a static variable from an
13693 	       enclosing function, in which case we need to fill it in now.  */
13694 	    if (TREE_STATIC (t))
13695 	      {
13696 		tree fn = enclosing_instantiation_of (DECL_CONTEXT (t));
13697 		if (fn != current_function_decl)
13698 		  ctx = fn;
13699 	      }
13700 	    spec = retrieve_local_specialization (t);
13701 	  }
13702 	/* If we already have the specialization we need, there is
13703 	   nothing more to do.  */
13704 	if (spec)
13705 	  {
13706 	    r = spec;
13707 	    break;
13708 	  }
13709 
13710 	/* Create a new node for the specialization we need.  */
13711 	r = copy_decl (t);
13712 	if (type == NULL_TREE)
13713 	  {
13714 	    if (is_typedef_decl (t))
13715 	      type = DECL_ORIGINAL_TYPE (t);
13716 	    else
13717 	      type = TREE_TYPE (t);
13718 	    if (VAR_P (t)
13719 		&& VAR_HAD_UNKNOWN_BOUND (t)
13720 		&& type != error_mark_node)
13721 	      type = strip_array_domain (type);
13722 	    tree sub_args = args;
13723 	    if (tree auto_node = type_uses_auto (type))
13724 	      {
13725 		/* Mask off any template args past the variable's context so we
13726 		   don't replace the auto with an unrelated argument.  */
13727 		int nouter = TEMPLATE_TYPE_LEVEL (auto_node) - 1;
13728 		int extra = TMPL_ARGS_DEPTH (args) - nouter;
13729 		if (extra > 0)
13730 		  /* This should never happen with the new lambda instantiation
13731 		     model, but keep the handling just in case.  */
13732 		  gcc_assert (!CHECKING_P),
13733 		  sub_args = strip_innermost_template_args (args, extra);
13734 	      }
13735 	    type = tsubst (type, sub_args, complain, in_decl);
13736 	  }
13737 	if (VAR_P (r))
13738 	  {
13739 	    /* Even if the original location is out of scope, the
13740 	       newly substituted one is not.  */
13741 	    DECL_DEAD_FOR_LOCAL (r) = 0;
13742 	    DECL_INITIALIZED_P (r) = 0;
13743 	    DECL_TEMPLATE_INSTANTIATED (r) = 0;
13744 	    if (type == error_mark_node)
13745 	      RETURN (error_mark_node);
13746 	    if (TREE_CODE (type) == FUNCTION_TYPE)
13747 	      {
13748 		/* It may seem that this case cannot occur, since:
13749 
13750 		   typedef void f();
13751 		   void g() { f x; }
13752 
13753 		   declares a function, not a variable.  However:
13754 
13755 		   typedef void f();
13756 		   template <typename T> void g() { T t; }
13757 		   template void g<f>();
13758 
13759 		   is an attempt to declare a variable with function
13760 		   type.  */
13761 		error ("variable %qD has function type",
13762 		       /* R is not yet sufficiently initialized, so we
13763 			  just use its name.  */
13764 		       DECL_NAME (r));
13765 		RETURN (error_mark_node);
13766 	      }
13767 	    type = complete_type (type);
13768 	    /* Wait until cp_finish_decl to set this again, to handle
13769 	       circular dependency (template/instantiate6.C). */
13770 	    DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
13771 	    type = check_var_type (DECL_NAME (r), type);
13772 
13773 	    if (DECL_HAS_VALUE_EXPR_P (t))
13774 	      {
13775 		tree ve = DECL_VALUE_EXPR (t);
13776 		ve = tsubst_expr (ve, args, complain, in_decl,
13777 				  /*constant_expression_p=*/false);
13778 		if (REFERENCE_REF_P (ve))
13779 		  {
13780 		    gcc_assert (TREE_CODE (type) == REFERENCE_TYPE);
13781 		    ve = TREE_OPERAND (ve, 0);
13782 		  }
13783 		SET_DECL_VALUE_EXPR (r, ve);
13784 	      }
13785 	    if (CP_DECL_THREAD_LOCAL_P (r)
13786 		&& !processing_template_decl)
13787 	      set_decl_tls_model (r, decl_default_tls_model (r));
13788 	  }
13789 	else if (DECL_SELF_REFERENCE_P (t))
13790 	  SET_DECL_SELF_REFERENCE_P (r);
13791 	TREE_TYPE (r) = type;
13792 	cp_apply_type_quals_to_decl (cp_type_quals (type), r);
13793 	DECL_CONTEXT (r) = ctx;
13794 	/* Clear out the mangled name and RTL for the instantiation.  */
13795 	SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
13796 	if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
13797 	  SET_DECL_RTL (r, NULL);
13798 	/* The initializer must not be expanded until it is required;
13799 	   see [temp.inst].  */
13800 	DECL_INITIAL (r) = NULL_TREE;
13801 	DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
13802 	if (VAR_P (r))
13803 	  {
13804 	    if (DECL_LANG_SPECIFIC (r))
13805 	      SET_DECL_DEPENDENT_INIT_P (r, false);
13806 
13807 	    SET_DECL_MODE (r, VOIDmode);
13808 
13809 	    /* Possibly limit visibility based on template args.  */
13810 	    DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
13811 	    if (DECL_VISIBILITY_SPECIFIED (t))
13812 	      {
13813 		DECL_VISIBILITY_SPECIFIED (r) = 0;
13814 		DECL_ATTRIBUTES (r)
13815 		  = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
13816 	      }
13817 	    determine_visibility (r);
13818 	  }
13819 
13820 	if (!local_p)
13821 	  {
13822 	    /* A static data member declaration is always marked
13823 	       external when it is declared in-class, even if an
13824 	       initializer is present.  We mimic the non-template
13825 	       processing here.  */
13826 	    DECL_EXTERNAL (r) = 1;
13827 	    if (DECL_NAMESPACE_SCOPE_P (t))
13828 	      DECL_NOT_REALLY_EXTERN (r) = 1;
13829 
13830 	    DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
13831 	    SET_DECL_IMPLICIT_INSTANTIATION (r);
13832 	    register_specialization (r, gen_tmpl, argvec, false, hash);
13833 	  }
13834 	else
13835 	  {
13836 	    if (DECL_LANG_SPECIFIC (r))
13837 	      DECL_TEMPLATE_INFO (r) = NULL_TREE;
13838 	    if (!cp_unevaluated_operand)
13839 	      register_local_specialization (r, t);
13840 	  }
13841 
13842 	DECL_CHAIN (r) = NULL_TREE;
13843 
13844 	apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
13845 					/*flags=*/0,
13846 					args, complain, in_decl);
13847 
13848 	/* Preserve a typedef that names a type.  */
13849 	if (is_typedef_decl (r) && type != error_mark_node)
13850 	  {
13851 	    DECL_ORIGINAL_TYPE (r) = NULL_TREE;
13852 	    set_underlying_type (r);
13853 	    if (TYPE_DECL_ALIAS_P (r))
13854 	      /* An alias template specialization can be dependent
13855 		 even if its underlying type is not.  */
13856 	      TYPE_DEPENDENT_P_VALID (TREE_TYPE (r)) = false;
13857 	  }
13858 
13859 	layout_decl (r, 0);
13860       }
13861       break;
13862 
13863     default:
13864       gcc_unreachable ();
13865     }
13866 #undef RETURN
13867 
13868  out:
13869   /* Restore the file and line information.  */
13870   input_location = saved_loc;
13871 
13872   return r;
13873 }
13874 
13875 /* Substitute into the ARG_TYPES of a function type.
13876    If END is a TREE_CHAIN, leave it and any following types
13877    un-substituted.  */
13878 
13879 static tree
tsubst_arg_types(tree arg_types,tree args,tree end,tsubst_flags_t complain,tree in_decl)13880 tsubst_arg_types (tree arg_types,
13881 		  tree args,
13882 		  tree end,
13883 		  tsubst_flags_t complain,
13884 		  tree in_decl)
13885 {
13886   tree remaining_arg_types;
13887   tree type = NULL_TREE;
13888   int i = 1;
13889   tree expanded_args = NULL_TREE;
13890   tree default_arg;
13891 
13892   if (!arg_types || arg_types == void_list_node || arg_types == end)
13893     return arg_types;
13894 
13895   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
13896 					  args, end, complain, in_decl);
13897   if (remaining_arg_types == error_mark_node)
13898     return error_mark_node;
13899 
13900   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
13901     {
13902       /* For a pack expansion, perform substitution on the
13903          entire expression. Later on, we'll handle the arguments
13904          one-by-one.  */
13905       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
13906                                             args, complain, in_decl);
13907 
13908       if (TREE_CODE (expanded_args) == TREE_VEC)
13909         /* So that we'll spin through the parameters, one by one.  */
13910         i = TREE_VEC_LENGTH (expanded_args);
13911       else
13912         {
13913           /* We only partially substituted into the parameter
13914              pack. Our type is TYPE_PACK_EXPANSION.  */
13915           type = expanded_args;
13916           expanded_args = NULL_TREE;
13917         }
13918     }
13919 
13920   while (i > 0) {
13921     --i;
13922 
13923     if (expanded_args)
13924       type = TREE_VEC_ELT (expanded_args, i);
13925     else if (!type)
13926       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
13927 
13928     if (type == error_mark_node)
13929       return error_mark_node;
13930     if (VOID_TYPE_P (type))
13931       {
13932         if (complain & tf_error)
13933           {
13934             error ("invalid parameter type %qT", type);
13935             if (in_decl)
13936               error ("in declaration %q+D", in_decl);
13937           }
13938         return error_mark_node;
13939     }
13940     /* DR 657. */
13941     if (abstract_virtuals_error_sfinae (ACU_PARM, type, complain))
13942       return error_mark_node;
13943 
13944     /* Do array-to-pointer, function-to-pointer conversion, and ignore
13945        top-level qualifiers as required.  */
13946     type = cv_unqualified (type_decays_to (type));
13947 
13948     /* We do not substitute into default arguments here.  The standard
13949        mandates that they be instantiated only when needed, which is
13950        done in build_over_call.  */
13951     default_arg = TREE_PURPOSE (arg_types);
13952 
13953     /* Except that we do substitute default arguments under tsubst_lambda_expr,
13954        since the new op() won't have any associated template arguments for us
13955        to refer to later.  */
13956     if (lambda_fn_in_template_p (in_decl))
13957       default_arg = tsubst_copy_and_build (default_arg, args, complain, in_decl,
13958 					   false/*fn*/, false/*constexpr*/);
13959 
13960     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
13961       {
13962         /* We've instantiated a template before its default arguments
13963            have been parsed.  This can happen for a nested template
13964            class, and is not an error unless we require the default
13965            argument in a call of this function.  */
13966         remaining_arg_types =
13967           tree_cons (default_arg, type, remaining_arg_types);
13968         vec_safe_push (DEFARG_INSTANTIATIONS(default_arg), remaining_arg_types);
13969       }
13970     else
13971       remaining_arg_types =
13972         hash_tree_cons (default_arg, type, remaining_arg_types);
13973   }
13974 
13975   return remaining_arg_types;
13976 }
13977 
13978 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
13979    *not* handle the exception-specification for FNTYPE, because the
13980    initial substitution of explicitly provided template parameters
13981    during argument deduction forbids substitution into the
13982    exception-specification:
13983 
13984      [temp.deduct]
13985 
13986      All references in the function type of the function template to  the
13987      corresponding template parameters are replaced by the specified tem-
13988      plate argument values.  If a substitution in a template parameter or
13989      in  the function type of the function template results in an invalid
13990      type, type deduction fails.  [Note: The equivalent  substitution  in
13991      exception specifications is done only when the function is instanti-
13992      ated, at which point a program is  ill-formed  if  the  substitution
13993      results in an invalid type.]  */
13994 
13995 static tree
tsubst_function_type(tree t,tree args,tsubst_flags_t complain,tree in_decl)13996 tsubst_function_type (tree t,
13997 		      tree args,
13998 		      tsubst_flags_t complain,
13999 		      tree in_decl)
14000 {
14001   tree return_type;
14002   tree arg_types = NULL_TREE;
14003   tree fntype;
14004 
14005   /* The TYPE_CONTEXT is not used for function/method types.  */
14006   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
14007 
14008   /* DR 1227: Mixing immediate and non-immediate contexts in deduction
14009      failure.  */
14010   bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
14011 
14012   if (late_return_type_p)
14013     {
14014       /* Substitute the argument types.  */
14015       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
14016 				    complain, in_decl);
14017       if (arg_types == error_mark_node)
14018 	return error_mark_node;
14019 
14020       tree save_ccp = current_class_ptr;
14021       tree save_ccr = current_class_ref;
14022       tree this_type = (TREE_CODE (t) == METHOD_TYPE
14023 			? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
14024       bool do_inject = this_type && CLASS_TYPE_P (this_type);
14025       if (do_inject)
14026 	{
14027 	  /* DR 1207: 'this' is in scope in the trailing return type.  */
14028 	  inject_this_parameter (this_type, cp_type_quals (this_type));
14029 	}
14030 
14031       /* Substitute the return type.  */
14032       return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14033 
14034       if (do_inject)
14035 	{
14036 	  current_class_ptr = save_ccp;
14037 	  current_class_ref = save_ccr;
14038 	}
14039     }
14040   else
14041     /* Substitute the return type.  */
14042     return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14043 
14044   if (return_type == error_mark_node)
14045     return error_mark_node;
14046   /* DR 486 clarifies that creation of a function type with an
14047      invalid return type is a deduction failure.  */
14048   if (TREE_CODE (return_type) == ARRAY_TYPE
14049       || TREE_CODE (return_type) == FUNCTION_TYPE)
14050     {
14051       if (complain & tf_error)
14052 	{
14053 	  if (TREE_CODE (return_type) == ARRAY_TYPE)
14054 	    error ("function returning an array");
14055 	  else
14056 	    error ("function returning a function");
14057 	}
14058       return error_mark_node;
14059     }
14060   /* And DR 657. */
14061   if (abstract_virtuals_error_sfinae (ACU_RETURN, return_type, complain))
14062     return error_mark_node;
14063 
14064   if (!late_return_type_p)
14065     {
14066       /* Substitute the argument types.  */
14067       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
14068 				    complain, in_decl);
14069       if (arg_types == error_mark_node)
14070 	return error_mark_node;
14071     }
14072 
14073   /* Construct a new type node and return it.  */
14074   if (TREE_CODE (t) == FUNCTION_TYPE)
14075     {
14076       fntype = build_function_type (return_type, arg_types);
14077       fntype = apply_memfn_quals (fntype,
14078 				  type_memfn_quals (t),
14079 				  type_memfn_rqual (t));
14080     }
14081   else
14082     {
14083       tree r = TREE_TYPE (TREE_VALUE (arg_types));
14084       /* Don't pick up extra function qualifiers from the basetype.  */
14085       r = cp_build_qualified_type_real (r, type_memfn_quals (t), complain);
14086       if (! MAYBE_CLASS_TYPE_P (r))
14087 	{
14088 	  /* [temp.deduct]
14089 
14090 	     Type deduction may fail for any of the following
14091 	     reasons:
14092 
14093 	     -- Attempting to create "pointer to member of T" when T
14094 	     is not a class type.  */
14095 	  if (complain & tf_error)
14096 	    error ("creating pointer to member function of non-class type %qT",
14097 		      r);
14098 	  return error_mark_node;
14099 	}
14100 
14101       fntype = build_method_type_directly (r, return_type,
14102 					   TREE_CHAIN (arg_types));
14103       fntype = build_ref_qualified_type (fntype, type_memfn_rqual (t));
14104     }
14105   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
14106 
14107   if (late_return_type_p)
14108     TYPE_HAS_LATE_RETURN_TYPE (fntype) = 1;
14109 
14110   return fntype;
14111 }
14112 
14113 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
14114    ARGS into that specification, and return the substituted
14115    specification.  If there is no specification, return NULL_TREE.  */
14116 
14117 static tree
tsubst_exception_specification(tree fntype,tree args,tsubst_flags_t complain,tree in_decl,bool defer_ok)14118 tsubst_exception_specification (tree fntype,
14119 				tree args,
14120 				tsubst_flags_t complain,
14121 				tree in_decl,
14122 				bool defer_ok)
14123 {
14124   tree specs;
14125   tree new_specs;
14126 
14127   specs = TYPE_RAISES_EXCEPTIONS (fntype);
14128   new_specs = NULL_TREE;
14129   if (specs && TREE_PURPOSE (specs))
14130     {
14131       /* A noexcept-specifier.  */
14132       tree expr = TREE_PURPOSE (specs);
14133       if (TREE_CODE (expr) == INTEGER_CST)
14134 	new_specs = expr;
14135       else if (defer_ok)
14136 	{
14137 	  /* Defer instantiation of noexcept-specifiers to avoid
14138 	     excessive instantiations (c++/49107).  */
14139 	  new_specs = make_node (DEFERRED_NOEXCEPT);
14140 	  if (DEFERRED_NOEXCEPT_SPEC_P (specs))
14141 	    {
14142 	      /* We already partially instantiated this member template,
14143 		 so combine the new args with the old.  */
14144 	      DEFERRED_NOEXCEPT_PATTERN (new_specs)
14145 		= DEFERRED_NOEXCEPT_PATTERN (expr);
14146 	      DEFERRED_NOEXCEPT_ARGS (new_specs)
14147 		= add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
14148 	    }
14149 	  else
14150 	    {
14151 	      DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
14152 	      DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
14153 	    }
14154 	}
14155       else
14156 	new_specs = tsubst_copy_and_build
14157 	  (expr, args, complain, in_decl, /*function_p=*/false,
14158 	   /*integral_constant_expression_p=*/true);
14159       new_specs = build_noexcept_spec (new_specs, complain);
14160     }
14161   else if (specs)
14162     {
14163       if (! TREE_VALUE (specs))
14164 	new_specs = specs;
14165       else
14166 	while (specs)
14167 	  {
14168 	    tree spec;
14169             int i, len = 1;
14170             tree expanded_specs = NULL_TREE;
14171 
14172             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
14173               {
14174                 /* Expand the pack expansion type.  */
14175                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
14176                                                        args, complain,
14177                                                        in_decl);
14178 
14179 		if (expanded_specs == error_mark_node)
14180 		  return error_mark_node;
14181 		else if (TREE_CODE (expanded_specs) == TREE_VEC)
14182 		  len = TREE_VEC_LENGTH (expanded_specs);
14183 		else
14184 		  {
14185 		    /* We're substituting into a member template, so
14186 		       we got a TYPE_PACK_EXPANSION back.  Add that
14187 		       expansion and move on.  */
14188 		    gcc_assert (TREE_CODE (expanded_specs)
14189 				== TYPE_PACK_EXPANSION);
14190 		    new_specs = add_exception_specifier (new_specs,
14191 							 expanded_specs,
14192 							 complain);
14193 		    specs = TREE_CHAIN (specs);
14194 		    continue;
14195 		  }
14196               }
14197 
14198             for (i = 0; i < len; ++i)
14199               {
14200                 if (expanded_specs)
14201                   spec = TREE_VEC_ELT (expanded_specs, i);
14202                 else
14203                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
14204                 if (spec == error_mark_node)
14205                   return spec;
14206                 new_specs = add_exception_specifier (new_specs, spec,
14207                                                      complain);
14208               }
14209 
14210             specs = TREE_CHAIN (specs);
14211 	  }
14212     }
14213   return new_specs;
14214 }
14215 
14216 /* Take the tree structure T and replace template parameters used
14217    therein with the argument vector ARGS.  IN_DECL is an associated
14218    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
14219    Issue error and warning messages under control of COMPLAIN.  Note
14220    that we must be relatively non-tolerant of extensions here, in
14221    order to preserve conformance; if we allow substitutions that
14222    should not be allowed, we may allow argument deductions that should
14223    not succeed, and therefore report ambiguous overload situations
14224    where there are none.  In theory, we could allow the substitution,
14225    but indicate that it should have failed, and allow our caller to
14226    make sure that the right thing happens, but we don't try to do this
14227    yet.
14228 
14229    This function is used for dealing with types, decls and the like;
14230    for expressions, use tsubst_expr or tsubst_copy.  */
14231 
14232 tree
tsubst(tree t,tree args,tsubst_flags_t complain,tree in_decl)14233 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
14234 {
14235   enum tree_code code;
14236   tree type, r = NULL_TREE;
14237 
14238   if (t == NULL_TREE || t == error_mark_node
14239       || t == integer_type_node
14240       || t == void_type_node
14241       || t == char_type_node
14242       || t == unknown_type_node
14243       || TREE_CODE (t) == NAMESPACE_DECL
14244       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
14245     return t;
14246 
14247   if (DECL_P (t))
14248     return tsubst_decl (t, args, complain);
14249 
14250   if (args == NULL_TREE)
14251     return t;
14252 
14253   code = TREE_CODE (t);
14254 
14255   if (code == IDENTIFIER_NODE)
14256     type = IDENTIFIER_TYPE_VALUE (t);
14257   else
14258     type = TREE_TYPE (t);
14259 
14260   gcc_assert (type != unknown_type_node);
14261 
14262   /* Reuse typedefs.  We need to do this to handle dependent attributes,
14263      such as attribute aligned.  */
14264   if (TYPE_P (t)
14265       && typedef_variant_p (t))
14266     {
14267       tree decl = TYPE_NAME (t);
14268 
14269       if (alias_template_specialization_p (t))
14270 	{
14271 	  /* DECL represents an alias template and we want to
14272 	     instantiate it.  */
14273 	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
14274 	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
14275 	  r = instantiate_alias_template (tmpl, gen_args, complain);
14276 	}
14277       else if (DECL_CLASS_SCOPE_P (decl)
14278 	       && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
14279 	       && uses_template_parms (DECL_CONTEXT (decl)))
14280 	{
14281 	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
14282 	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
14283 	  r = retrieve_specialization (tmpl, gen_args, 0);
14284 	}
14285       else if (DECL_FUNCTION_SCOPE_P (decl)
14286 	       && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
14287 	       && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
14288 	r = retrieve_local_specialization (decl);
14289       else
14290 	/* The typedef is from a non-template context.  */
14291 	return t;
14292 
14293       if (r)
14294 	{
14295 	  r = TREE_TYPE (r);
14296 	  r = cp_build_qualified_type_real
14297 	    (r, cp_type_quals (t) | cp_type_quals (r),
14298 	     complain | tf_ignore_bad_quals);
14299 	  return r;
14300 	}
14301       else
14302 	{
14303 	  /* We don't have an instantiation yet, so drop the typedef.  */
14304 	  int quals = cp_type_quals (t);
14305 	  t = DECL_ORIGINAL_TYPE (decl);
14306 	  t = cp_build_qualified_type_real (t, quals,
14307 					    complain | tf_ignore_bad_quals);
14308 	}
14309     }
14310 
14311   bool fndecl_type = (complain & tf_fndecl_type);
14312   complain &= ~tf_fndecl_type;
14313 
14314   if (type
14315       && code != TYPENAME_TYPE
14316       && code != TEMPLATE_TYPE_PARM
14317       && code != TEMPLATE_PARM_INDEX
14318       && code != IDENTIFIER_NODE
14319       && code != FUNCTION_TYPE
14320       && code != METHOD_TYPE)
14321     type = tsubst (type, args, complain, in_decl);
14322   if (type == error_mark_node)
14323     return error_mark_node;
14324 
14325   switch (code)
14326     {
14327     case RECORD_TYPE:
14328     case UNION_TYPE:
14329     case ENUMERAL_TYPE:
14330       return tsubst_aggr_type (t, args, complain, in_decl,
14331 			       /*entering_scope=*/0);
14332 
14333     case ERROR_MARK:
14334     case IDENTIFIER_NODE:
14335     case VOID_TYPE:
14336     case REAL_TYPE:
14337     case COMPLEX_TYPE:
14338     case VECTOR_TYPE:
14339     case BOOLEAN_TYPE:
14340     case NULLPTR_TYPE:
14341     case LANG_TYPE:
14342       return t;
14343 
14344     case INTEGER_TYPE:
14345       if (t == integer_type_node)
14346 	return t;
14347 
14348       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
14349           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
14350         return t;
14351 
14352       {
14353 	tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
14354 
14355 	max = tsubst_expr (omax, args, complain, in_decl,
14356 			   /*integral_constant_expression_p=*/false);
14357 
14358 	/* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
14359 	   needed.  */
14360 	if (TREE_CODE (max) == NOP_EXPR
14361 	    && TREE_SIDE_EFFECTS (omax)
14362 	    && !TREE_TYPE (max))
14363 	  TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
14364 
14365 	/* If we're in a partial instantiation, preserve the magic NOP_EXPR
14366 	   with TREE_SIDE_EFFECTS that indicates this is not an integral
14367 	   constant expression.  */
14368 	if (processing_template_decl
14369 	    && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
14370 	  {
14371 	    gcc_assert (TREE_CODE (max) == NOP_EXPR);
14372 	    TREE_SIDE_EFFECTS (max) = 1;
14373 	  }
14374 
14375 	return compute_array_index_type (NULL_TREE, max, complain);
14376       }
14377 
14378     case TEMPLATE_TYPE_PARM:
14379     case TEMPLATE_TEMPLATE_PARM:
14380     case BOUND_TEMPLATE_TEMPLATE_PARM:
14381     case TEMPLATE_PARM_INDEX:
14382       {
14383 	int idx;
14384 	int level;
14385 	int levels;
14386 	tree arg = NULL_TREE;
14387 
14388 	/* Early in template argument deduction substitution, we don't
14389 	   want to reduce the level of 'auto', or it will be confused
14390 	   with a normal template parm in subsequent deduction.  */
14391 	if (is_auto (t) && (complain & tf_partial))
14392 	  return t;
14393 
14394 	r = NULL_TREE;
14395 
14396 	gcc_assert (TREE_VEC_LENGTH (args) > 0);
14397 	template_parm_level_and_index (t, &level, &idx);
14398 
14399 	levels = TMPL_ARGS_DEPTH (args);
14400 	if (level <= levels
14401 	    && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
14402 	  {
14403 	    arg = TMPL_ARG (args, level, idx);
14404 
14405 	    /* See through ARGUMENT_PACK_SELECT arguments. */
14406 	    if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
14407 	      arg = argument_pack_select_arg (arg);
14408 	  }
14409 
14410 	if (arg == error_mark_node)
14411 	  return error_mark_node;
14412 	else if (arg != NULL_TREE)
14413 	  {
14414 	    if (ARGUMENT_PACK_P (arg))
14415 	      /* If ARG is an argument pack, we don't actually want to
14416 		 perform a substitution here, because substitutions
14417 		 for argument packs are only done
14418 		 element-by-element. We can get to this point when
14419 		 substituting the type of a non-type template
14420 		 parameter pack, when that type actually contains
14421 		 template parameter packs from an outer template, e.g.,
14422 
14423 	         template<typename... Types> struct A {
14424 		   template<Types... Values> struct B { };
14425                  };  */
14426 	      return t;
14427 
14428 	    if (code == TEMPLATE_TYPE_PARM)
14429 	      {
14430 		int quals;
14431 		gcc_assert (TYPE_P (arg));
14432 
14433 		quals = cp_type_quals (arg) | cp_type_quals (t);
14434 
14435 		return cp_build_qualified_type_real
14436 		  (arg, quals, complain | tf_ignore_bad_quals);
14437 	      }
14438 	    else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
14439 	      {
14440 		/* We are processing a type constructed from a
14441 		   template template parameter.  */
14442 		tree argvec = tsubst (TYPE_TI_ARGS (t),
14443 				      args, complain, in_decl);
14444 		if (argvec == error_mark_node)
14445 		  return error_mark_node;
14446 
14447 		gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
14448 			    || TREE_CODE (arg) == TEMPLATE_DECL
14449 			    || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
14450 
14451 		if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
14452 		  /* Consider this code:
14453 
14454 			template <template <class> class Template>
14455 			struct Internal {
14456 			template <class Arg> using Bind = Template<Arg>;
14457 			};
14458 
14459 			template <template <class> class Template, class Arg>
14460 			using Instantiate = Template<Arg>; //#0
14461 
14462 			template <template <class> class Template,
14463                                   class Argument>
14464 			using Bind =
14465 			  Instantiate<Internal<Template>::template Bind,
14466 				      Argument>; //#1
14467 
14468 		     When #1 is parsed, the
14469 		     BOUND_TEMPLATE_TEMPLATE_PARM representing the
14470 		     parameter `Template' in #0 matches the
14471 		     UNBOUND_CLASS_TEMPLATE representing the argument
14472 		     `Internal<Template>::template Bind'; We then want
14473 		     to assemble the type `Bind<Argument>' that can't
14474 		     be fully created right now, because
14475 		     `Internal<Template>' not being complete, the Bind
14476 		     template cannot be looked up in that context.  So
14477 		     we need to "store" `Bind<Argument>' for later
14478 		     when the context of Bind becomes complete.  Let's
14479 		     store that in a TYPENAME_TYPE.  */
14480 		  return make_typename_type (TYPE_CONTEXT (arg),
14481 					     build_nt (TEMPLATE_ID_EXPR,
14482 						       TYPE_IDENTIFIER (arg),
14483 						       argvec),
14484 					     typename_type,
14485 					     complain);
14486 
14487 		/* We can get a TEMPLATE_TEMPLATE_PARM here when we
14488 		   are resolving nested-types in the signature of a
14489 		   member function templates.  Otherwise ARG is a
14490 		   TEMPLATE_DECL and is the real template to be
14491 		   instantiated.  */
14492 		if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
14493 		  arg = TYPE_NAME (arg);
14494 
14495 		r = lookup_template_class (arg,
14496 					   argvec, in_decl,
14497 					   DECL_CONTEXT (arg),
14498 					    /*entering_scope=*/0,
14499 					   complain);
14500 		return cp_build_qualified_type_real
14501 		  (r, cp_type_quals (t) | cp_type_quals (r), complain);
14502 	      }
14503 	    else if (code == TEMPLATE_TEMPLATE_PARM)
14504 	      return arg;
14505 	    else
14506 	      /* TEMPLATE_PARM_INDEX.  */
14507 	      return convert_from_reference (unshare_expr (arg));
14508 	  }
14509 
14510 	if (level == 1)
14511 	  /* This can happen during the attempted tsubst'ing in
14512 	     unify.  This means that we don't yet have any information
14513 	     about the template parameter in question.  */
14514 	  return t;
14515 
14516 	/* If we get here, we must have been looking at a parm for a
14517 	   more deeply nested template.  Make a new version of this
14518 	   template parameter, but with a lower level.  */
14519 	switch (code)
14520 	  {
14521 	  case TEMPLATE_TYPE_PARM:
14522 	  case TEMPLATE_TEMPLATE_PARM:
14523 	  case BOUND_TEMPLATE_TEMPLATE_PARM:
14524 	    if (cp_type_quals (t))
14525 	      {
14526 		r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
14527 		r = cp_build_qualified_type_real
14528 		  (r, cp_type_quals (t),
14529 		   complain | (code == TEMPLATE_TYPE_PARM
14530 			       ? tf_ignore_bad_quals : 0));
14531 	      }
14532 	    else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
14533 		     && PLACEHOLDER_TYPE_CONSTRAINTS (t)
14534 		     && (r = (TEMPLATE_PARM_DESCENDANTS
14535 			      (TEMPLATE_TYPE_PARM_INDEX (t))))
14536 		     && (r = TREE_TYPE (r))
14537 		     && !PLACEHOLDER_TYPE_CONSTRAINTS (r))
14538 	      /* Break infinite recursion when substituting the constraints
14539 		 of a constrained placeholder.  */;
14540 	    else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
14541 		     && !PLACEHOLDER_TYPE_CONSTRAINTS (t)
14542 		     && !CLASS_PLACEHOLDER_TEMPLATE (t)
14543 		     && (arg = TEMPLATE_TYPE_PARM_INDEX (t),
14544 			 r = TEMPLATE_PARM_DESCENDANTS (arg))
14545 		     && (TEMPLATE_PARM_LEVEL (r)
14546 			 == TEMPLATE_PARM_LEVEL (arg) - levels))
14547 		/* Cache the simple case of lowering a type parameter.  */
14548 	      r = TREE_TYPE (r);
14549 	    else
14550 	      {
14551 		r = copy_type (t);
14552 		TEMPLATE_TYPE_PARM_INDEX (r)
14553 		  = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
14554 						r, levels, args, complain);
14555 		TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
14556 		TYPE_MAIN_VARIANT (r) = r;
14557 		TYPE_POINTER_TO (r) = NULL_TREE;
14558 		TYPE_REFERENCE_TO (r) = NULL_TREE;
14559 
14560                 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
14561 		  {
14562 		    /* Propagate constraints on placeholders.  */
14563 		    if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
14564 		      PLACEHOLDER_TYPE_CONSTRAINTS (r)
14565 			= tsubst_constraint (constr, args, complain, in_decl);
14566 		    else if (tree pl = CLASS_PLACEHOLDER_TEMPLATE (t))
14567 		      {
14568 			pl = tsubst_copy (pl, args, complain, in_decl);
14569 			CLASS_PLACEHOLDER_TEMPLATE (r) = pl;
14570 		      }
14571 		  }
14572 
14573 		if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
14574 		  /* We have reduced the level of the template
14575 		     template parameter, but not the levels of its
14576 		     template parameters, so canonical_type_parameter
14577 		     will not be able to find the canonical template
14578 		     template parameter for this level. Thus, we
14579 		     require structural equality checking to compare
14580 		     TEMPLATE_TEMPLATE_PARMs. */
14581 		  SET_TYPE_STRUCTURAL_EQUALITY (r);
14582 		else if (TYPE_STRUCTURAL_EQUALITY_P (t))
14583 		  SET_TYPE_STRUCTURAL_EQUALITY (r);
14584 		else
14585 		  TYPE_CANONICAL (r) = canonical_type_parameter (r);
14586 
14587 		if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
14588 		  {
14589 		    tree tinfo = TYPE_TEMPLATE_INFO (t);
14590 		    /* We might need to substitute into the types of non-type
14591 		       template parameters.  */
14592 		    tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
14593 					complain, in_decl);
14594 		    if (tmpl == error_mark_node)
14595 		      return error_mark_node;
14596 		    tree argvec = tsubst (TI_ARGS (tinfo), args,
14597 					  complain, in_decl);
14598 		    if (argvec == error_mark_node)
14599 		      return error_mark_node;
14600 
14601 		    TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
14602 		      = build_template_info (tmpl, argvec);
14603 		  }
14604 	      }
14605 	    break;
14606 
14607 	  case TEMPLATE_PARM_INDEX:
14608 	    /* OK, now substitute the type of the non-type parameter.  We
14609 	       couldn't do it earlier because it might be an auto parameter,
14610 	       and we wouldn't need to if we had an argument.  */
14611 	    type = tsubst (type, args, complain, in_decl);
14612 	    if (type == error_mark_node)
14613 	      return error_mark_node;
14614 	    r = reduce_template_parm_level (t, type, levels, args, complain);
14615 	    break;
14616 
14617 	  default:
14618 	    gcc_unreachable ();
14619 	  }
14620 
14621 	return r;
14622       }
14623 
14624     case TREE_LIST:
14625       {
14626 	tree purpose, value, chain;
14627 
14628 	if (t == void_list_node)
14629 	  return t;
14630 
14631 	purpose = TREE_PURPOSE (t);
14632 	if (purpose)
14633 	  {
14634 	    purpose = tsubst (purpose, args, complain, in_decl);
14635 	    if (purpose == error_mark_node)
14636 	      return error_mark_node;
14637 	  }
14638 	value = TREE_VALUE (t);
14639 	if (value)
14640 	  {
14641 	    value = tsubst (value, args, complain, in_decl);
14642 	    if (value == error_mark_node)
14643 	      return error_mark_node;
14644 	  }
14645 	chain = TREE_CHAIN (t);
14646 	if (chain && chain != void_type_node)
14647 	  {
14648 	    chain = tsubst (chain, args, complain, in_decl);
14649 	    if (chain == error_mark_node)
14650 	      return error_mark_node;
14651 	  }
14652 	if (purpose == TREE_PURPOSE (t)
14653 	    && value == TREE_VALUE (t)
14654 	    && chain == TREE_CHAIN (t))
14655 	  return t;
14656 	return hash_tree_cons (purpose, value, chain);
14657       }
14658 
14659     case TREE_BINFO:
14660       /* We should never be tsubsting a binfo.  */
14661       gcc_unreachable ();
14662 
14663     case TREE_VEC:
14664       /* A vector of template arguments.  */
14665       gcc_assert (!type);
14666       return tsubst_template_args (t, args, complain, in_decl);
14667 
14668     case POINTER_TYPE:
14669     case REFERENCE_TYPE:
14670       {
14671 	if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
14672 	  return t;
14673 
14674 	/* [temp.deduct]
14675 
14676 	   Type deduction may fail for any of the following
14677 	   reasons:
14678 
14679 	   -- Attempting to create a pointer to reference type.
14680 	   -- Attempting to create a reference to a reference type or
14681 	      a reference to void.
14682 
14683 	  Core issue 106 says that creating a reference to a reference
14684 	  during instantiation is no longer a cause for failure. We
14685 	  only enforce this check in strict C++98 mode.  */
14686 	if ((TREE_CODE (type) == REFERENCE_TYPE
14687 	     && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
14688 	    || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
14689 	  {
14690 	    static location_t last_loc;
14691 
14692 	    /* We keep track of the last time we issued this error
14693 	       message to avoid spewing a ton of messages during a
14694 	       single bad template instantiation.  */
14695 	    if (complain & tf_error
14696 		&& last_loc != input_location)
14697 	      {
14698 		if (VOID_TYPE_P (type))
14699 		  error ("forming reference to void");
14700                else if (code == POINTER_TYPE)
14701                  error ("forming pointer to reference type %qT", type);
14702                else
14703 		  error ("forming reference to reference type %qT", type);
14704 		last_loc = input_location;
14705 	      }
14706 
14707 	    return error_mark_node;
14708 	  }
14709 	else if (TREE_CODE (type) == FUNCTION_TYPE
14710 		 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
14711 		     || type_memfn_rqual (type) != REF_QUAL_NONE))
14712 	  {
14713 	    if (complain & tf_error)
14714 	      {
14715 		if (code == POINTER_TYPE)
14716 		  error ("forming pointer to qualified function type %qT",
14717 			 type);
14718 		else
14719 		  error ("forming reference to qualified function type %qT",
14720 			 type);
14721 	      }
14722 	    return error_mark_node;
14723 	  }
14724 	else if (code == POINTER_TYPE)
14725 	  {
14726 	    r = build_pointer_type (type);
14727 	    if (TREE_CODE (type) == METHOD_TYPE)
14728 	      r = build_ptrmemfunc_type (r);
14729 	  }
14730 	else if (TREE_CODE (type) == REFERENCE_TYPE)
14731 	  /* In C++0x, during template argument substitution, when there is an
14732 	     attempt to create a reference to a reference type, reference
14733 	     collapsing is applied as described in [14.3.1/4 temp.arg.type]:
14734 
14735 	     "If a template-argument for a template-parameter T names a type
14736 	     that is a reference to a type A, an attempt to create the type
14737 	     'lvalue reference to cv T' creates the type 'lvalue reference to
14738 	     A,' while an attempt to create the type type rvalue reference to
14739 	     cv T' creates the type T"
14740 	  */
14741 	  r = cp_build_reference_type
14742 	      (TREE_TYPE (type),
14743 	       TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
14744 	else
14745 	  r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
14746 	r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
14747 
14748 	if (r != error_mark_node)
14749 	  /* Will this ever be needed for TYPE_..._TO values?  */
14750 	  layout_type (r);
14751 
14752 	return r;
14753       }
14754     case OFFSET_TYPE:
14755       {
14756 	r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
14757 	if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
14758 	  {
14759 	    /* [temp.deduct]
14760 
14761 	       Type deduction may fail for any of the following
14762 	       reasons:
14763 
14764 	       -- Attempting to create "pointer to member of T" when T
14765 		  is not a class type.  */
14766 	    if (complain & tf_error)
14767 	      error ("creating pointer to member of non-class type %qT", r);
14768 	    return error_mark_node;
14769 	  }
14770 	if (TREE_CODE (type) == REFERENCE_TYPE)
14771 	  {
14772 	    if (complain & tf_error)
14773 	      error ("creating pointer to member reference type %qT", type);
14774 	    return error_mark_node;
14775 	  }
14776 	if (VOID_TYPE_P (type))
14777 	  {
14778 	    if (complain & tf_error)
14779 	      error ("creating pointer to member of type void");
14780 	    return error_mark_node;
14781 	  }
14782 	gcc_assert (TREE_CODE (type) != METHOD_TYPE);
14783 	if (TREE_CODE (type) == FUNCTION_TYPE)
14784 	  {
14785 	    /* The type of the implicit object parameter gets its
14786 	       cv-qualifiers from the FUNCTION_TYPE. */
14787 	    tree memptr;
14788 	    tree method_type
14789 	      = build_memfn_type (type, r, type_memfn_quals (type),
14790 				  type_memfn_rqual (type));
14791 	    memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
14792 	    return cp_build_qualified_type_real (memptr, cp_type_quals (t),
14793 						 complain);
14794 	  }
14795 	else
14796 	  return cp_build_qualified_type_real (build_ptrmem_type (r, type),
14797 					       cp_type_quals (t),
14798 					       complain);
14799       }
14800     case FUNCTION_TYPE:
14801     case METHOD_TYPE:
14802       {
14803 	tree fntype;
14804 	tree specs;
14805 	fntype = tsubst_function_type (t, args, complain, in_decl);
14806 	if (fntype == error_mark_node)
14807 	  return error_mark_node;
14808 
14809 	/* Substitute the exception specification.  */
14810 	specs = tsubst_exception_specification (t, args, complain, in_decl,
14811 						/*defer_ok*/fndecl_type);
14812 	if (specs == error_mark_node)
14813 	  return error_mark_node;
14814 	if (specs)
14815 	  fntype = build_exception_variant (fntype, specs);
14816 	return fntype;
14817       }
14818     case ARRAY_TYPE:
14819       {
14820 	tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
14821 	if (domain == error_mark_node)
14822 	  return error_mark_node;
14823 
14824 	/* As an optimization, we avoid regenerating the array type if
14825 	   it will obviously be the same as T.  */
14826 	if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
14827 	  return t;
14828 
14829 	/* These checks should match the ones in create_array_type_for_decl.
14830 
14831 	   [temp.deduct]
14832 
14833 	   The deduction may fail for any of the following reasons:
14834 
14835 	   -- Attempting to create an array with an element type that
14836 	      is void, a function type, or a reference type, or [DR337]
14837 	      an abstract class type.  */
14838 	if (VOID_TYPE_P (type)
14839 	    || TREE_CODE (type) == FUNCTION_TYPE
14840 	    || (TREE_CODE (type) == ARRAY_TYPE
14841 		&& TYPE_DOMAIN (type) == NULL_TREE)
14842 	    || TREE_CODE (type) == REFERENCE_TYPE)
14843 	  {
14844 	    if (complain & tf_error)
14845 	      error ("creating array of %qT", type);
14846 	    return error_mark_node;
14847 	  }
14848 
14849 	if (abstract_virtuals_error_sfinae (ACU_ARRAY, type, complain))
14850 	  return error_mark_node;
14851 
14852 	r = build_cplus_array_type (type, domain);
14853 
14854 	if (TYPE_USER_ALIGN (t))
14855 	  {
14856 	    SET_TYPE_ALIGN (r, TYPE_ALIGN (t));
14857 	    TYPE_USER_ALIGN (r) = 1;
14858 	  }
14859 
14860 	return r;
14861       }
14862 
14863     case TYPENAME_TYPE:
14864       {
14865 	tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
14866 				     in_decl, /*entering_scope=*/1);
14867 	if (ctx == error_mark_node)
14868 	  return error_mark_node;
14869 
14870 	tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
14871 			      complain, in_decl);
14872 	if (f == error_mark_node)
14873 	  return error_mark_node;
14874 
14875 	if (!MAYBE_CLASS_TYPE_P (ctx))
14876 	  {
14877 	    if (complain & tf_error)
14878 	      error ("%qT is not a class, struct, or union type", ctx);
14879 	    return error_mark_node;
14880 	  }
14881 	else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
14882 	  {
14883 	    /* Normally, make_typename_type does not require that the CTX
14884 	       have complete type in order to allow things like:
14885 
14886 		 template <class T> struct S { typename S<T>::X Y; };
14887 
14888 	       But, such constructs have already been resolved by this
14889 	       point, so here CTX really should have complete type, unless
14890 	       it's a partial instantiation.  */
14891 	    ctx = complete_type (ctx);
14892 	    if (!COMPLETE_TYPE_P (ctx))
14893 	      {
14894 		if (complain & tf_error)
14895 		  cxx_incomplete_type_error (NULL_TREE, ctx);
14896 		return error_mark_node;
14897 	      }
14898 	  }
14899 
14900 	f = make_typename_type (ctx, f, typename_type,
14901 				complain | tf_keep_type_decl);
14902 	if (f == error_mark_node)
14903 	  return f;
14904 	if (TREE_CODE (f) == TYPE_DECL)
14905 	  {
14906 	    complain |= tf_ignore_bad_quals;
14907 	    f = TREE_TYPE (f);
14908 	  }
14909 
14910 	if (TREE_CODE (f) != TYPENAME_TYPE)
14911 	  {
14912 	    if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
14913 	      {
14914 		if (complain & tf_error)
14915 		  error ("%qT resolves to %qT, which is not an enumeration type",
14916 			 t, f);
14917 		else
14918 		  return error_mark_node;
14919 	      }
14920 	    else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
14921 	      {
14922 		if (complain & tf_error)
14923 		  error ("%qT resolves to %qT, which is is not a class type",
14924 			 t, f);
14925 		else
14926 		  return error_mark_node;
14927 	      }
14928 	  }
14929 
14930 	return cp_build_qualified_type_real
14931 	  (f, cp_type_quals (f) | cp_type_quals (t), complain);
14932       }
14933 
14934     case UNBOUND_CLASS_TEMPLATE:
14935       {
14936 	tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
14937 				     in_decl, /*entering_scope=*/1);
14938 	tree name = TYPE_IDENTIFIER (t);
14939 	tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
14940 
14941 	if (ctx == error_mark_node || name == error_mark_node)
14942 	  return error_mark_node;
14943 
14944 	if (parm_list)
14945 	  parm_list = tsubst_template_parms (parm_list, args, complain);
14946 	return make_unbound_class_template (ctx, name, parm_list, complain);
14947       }
14948 
14949     case TYPEOF_TYPE:
14950       {
14951 	tree type;
14952 
14953 	++cp_unevaluated_operand;
14954 	++c_inhibit_evaluation_warnings;
14955 
14956 	type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
14957 			    complain, in_decl,
14958 			    /*integral_constant_expression_p=*/false);
14959 
14960 	--cp_unevaluated_operand;
14961 	--c_inhibit_evaluation_warnings;
14962 
14963 	type = finish_typeof (type);
14964 	return cp_build_qualified_type_real (type,
14965 					     cp_type_quals (t)
14966 					     | cp_type_quals (type),
14967 					     complain);
14968       }
14969 
14970     case DECLTYPE_TYPE:
14971       {
14972 	tree type;
14973 
14974 	++cp_unevaluated_operand;
14975 	++c_inhibit_evaluation_warnings;
14976 
14977 	type = tsubst_copy_and_build (DECLTYPE_TYPE_EXPR (t), args,
14978 				      complain|tf_decltype, in_decl,
14979 				      /*function_p*/false,
14980 				      /*integral_constant_expression*/false);
14981 
14982 	if (DECLTYPE_FOR_INIT_CAPTURE (t))
14983 	  {
14984 	    if (type == NULL_TREE)
14985 	      {
14986 		if (complain & tf_error)
14987 		  error ("empty initializer in lambda init-capture");
14988 		type = error_mark_node;
14989 	      }
14990 	    else if (TREE_CODE (type) == TREE_LIST)
14991 	      type = build_x_compound_expr_from_list (type, ELK_INIT, complain);
14992 	  }
14993 
14994 	--cp_unevaluated_operand;
14995 	--c_inhibit_evaluation_warnings;
14996 
14997 	if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
14998 	  type = lambda_capture_field_type (type,
14999 					    DECLTYPE_FOR_INIT_CAPTURE (t),
15000 					    DECLTYPE_FOR_REF_CAPTURE (t));
15001 	else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
15002 	  type = lambda_proxy_type (type);
15003 	else
15004 	  {
15005 	    bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
15006 	    if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
15007 		&& EXPR_P (type))
15008 	      /* In a template ~id could be either a complement expression
15009 		 or an unqualified-id naming a destructor; if instantiating
15010 		 it produces an expression, it's not an id-expression or
15011 		 member access.  */
15012 	      id = false;
15013 	    type = finish_decltype_type (type, id, complain);
15014 	  }
15015 	return cp_build_qualified_type_real (type,
15016 					     cp_type_quals (t)
15017 					     | cp_type_quals (type),
15018 					     complain | tf_ignore_bad_quals);
15019       }
15020 
15021     case UNDERLYING_TYPE:
15022       {
15023 	tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
15024 			    complain, in_decl);
15025 	return finish_underlying_type (type);
15026       }
15027 
15028     case TYPE_ARGUMENT_PACK:
15029     case NONTYPE_ARGUMENT_PACK:
15030       {
15031         tree r;
15032 
15033 	if (code == NONTYPE_ARGUMENT_PACK)
15034 	  r = make_node (code);
15035 	else
15036 	  r = cxx_make_type (code);
15037 
15038 	tree pack_args = ARGUMENT_PACK_ARGS (t);
15039 	pack_args = tsubst_template_args (pack_args, args, complain, in_decl);
15040 	SET_ARGUMENT_PACK_ARGS (r, pack_args);
15041 
15042 	return r;
15043       }
15044 
15045     case VOID_CST:
15046     case INTEGER_CST:
15047     case REAL_CST:
15048     case STRING_CST:
15049     case PLUS_EXPR:
15050     case MINUS_EXPR:
15051     case NEGATE_EXPR:
15052     case NOP_EXPR:
15053     case INDIRECT_REF:
15054     case ADDR_EXPR:
15055     case CALL_EXPR:
15056     case ARRAY_REF:
15057     case SCOPE_REF:
15058       /* We should use one of the expression tsubsts for these codes.  */
15059       gcc_unreachable ();
15060 
15061     default:
15062       sorry ("use of %qs in template", get_tree_code_name (code));
15063       return error_mark_node;
15064     }
15065 }
15066 
15067 /* tsubst a BASELINK.  OBJECT_TYPE, if non-NULL, is the type of the
15068    expression on the left-hand side of the "." or "->" operator.  We
15069    only do the lookup if we had a dependent BASELINK.  Otherwise we
15070    adjust it onto the instantiated heirarchy.  */
15071 
15072 static tree
tsubst_baselink(tree baselink,tree object_type,tree args,tsubst_flags_t complain,tree in_decl)15073 tsubst_baselink (tree baselink, tree object_type,
15074 		 tree args, tsubst_flags_t complain, tree in_decl)
15075 {
15076   bool qualified_p = BASELINK_QUALIFIED_P (baselink);
15077   tree qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
15078   qualifying_scope = tsubst (qualifying_scope, args, complain, in_decl);
15079 
15080   tree optype = BASELINK_OPTYPE (baselink);
15081   optype = tsubst (optype, args, complain, in_decl);
15082 
15083   tree template_args = NULL_TREE;
15084   bool template_id_p = false;
15085   tree fns = BASELINK_FUNCTIONS (baselink);
15086   if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
15087     {
15088       template_id_p = true;
15089       template_args = TREE_OPERAND (fns, 1);
15090       fns = TREE_OPERAND (fns, 0);
15091       if (template_args)
15092 	template_args = tsubst_template_args (template_args, args,
15093 					      complain, in_decl);
15094     }
15095 
15096   tree binfo_type = BINFO_TYPE (BASELINK_BINFO (baselink));
15097   binfo_type = tsubst (binfo_type, args, complain, in_decl);
15098   bool dependent_p = binfo_type != BINFO_TYPE (BASELINK_BINFO (baselink));
15099 
15100   if (dependent_p)
15101     {
15102       tree name = OVL_NAME (fns);
15103       if (IDENTIFIER_CONV_OP_P (name))
15104 	name = make_conv_op_name (optype);
15105 
15106       if (name == complete_dtor_identifier)
15107 	/* Treat as-if non-dependent below.  */
15108 	dependent_p = false;
15109 
15110       baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
15111       if (!baselink)
15112 	{
15113 	  if ((complain & tf_error)
15114 	      && constructor_name_p (name, qualifying_scope))
15115 	    error ("cannot call constructor %<%T::%D%> directly",
15116 		   qualifying_scope, name);
15117 	  return error_mark_node;
15118 	}
15119 
15120       if (BASELINK_P (baselink))
15121 	fns = BASELINK_FUNCTIONS (baselink);
15122     }
15123   else
15124     /* We're going to overwrite pieces below, make a duplicate.  */
15125     baselink = copy_node (baselink);
15126 
15127   /* If lookup found a single function, mark it as used at this point.
15128      (If lookup found multiple functions the one selected later by
15129      overload resolution will be marked as used at that point.)  */
15130   if (!template_id_p && !really_overloaded_fn (fns))
15131     {
15132       tree fn = OVL_FIRST (fns);
15133       bool ok = mark_used (fn, complain);
15134       if (!ok && !(complain & tf_error))
15135 	return error_mark_node;
15136       if (ok && BASELINK_P (baselink))
15137 	/* We might have instantiated an auto function.  */
15138 	TREE_TYPE (baselink) = TREE_TYPE (fn);
15139     }
15140 
15141   if (BASELINK_P (baselink))
15142     {
15143       /* Add back the template arguments, if present.  */
15144       if (template_id_p)
15145 	BASELINK_FUNCTIONS (baselink)
15146 	  = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, template_args);
15147 
15148       /* Update the conversion operator type.  */
15149       BASELINK_OPTYPE (baselink) = optype;
15150     }
15151 
15152   if (!object_type)
15153     object_type = current_class_type;
15154 
15155   if (qualified_p || !dependent_p)
15156     {
15157       baselink = adjust_result_of_qualified_name_lookup (baselink,
15158 							 qualifying_scope,
15159 							 object_type);
15160       if (!qualified_p)
15161 	/* We need to call adjust_result_of_qualified_name_lookup in case the
15162 	   destructor names a base class, but we unset BASELINK_QUALIFIED_P
15163 	   so that we still get virtual function binding.  */
15164 	BASELINK_QUALIFIED_P (baselink) = false;
15165     }
15166 
15167   return baselink;
15168 }
15169 
15170 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
15171    true if the qualified-id will be a postfix-expression in-and-of
15172    itself; false if more of the postfix-expression follows the
15173    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
15174    of "&".  */
15175 
15176 static tree
tsubst_qualified_id(tree qualified_id,tree args,tsubst_flags_t complain,tree in_decl,bool done,bool address_p)15177 tsubst_qualified_id (tree qualified_id, tree args,
15178 		     tsubst_flags_t complain, tree in_decl,
15179 		     bool done, bool address_p)
15180 {
15181   tree expr;
15182   tree scope;
15183   tree name;
15184   bool is_template;
15185   tree template_args;
15186   location_t loc = UNKNOWN_LOCATION;
15187 
15188   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
15189 
15190   /* Figure out what name to look up.  */
15191   name = TREE_OPERAND (qualified_id, 1);
15192   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
15193     {
15194       is_template = true;
15195       loc = EXPR_LOCATION (name);
15196       template_args = TREE_OPERAND (name, 1);
15197       if (template_args)
15198 	template_args = tsubst_template_args (template_args, args,
15199 					      complain, in_decl);
15200       if (template_args == error_mark_node)
15201 	return error_mark_node;
15202       name = TREE_OPERAND (name, 0);
15203     }
15204   else
15205     {
15206       is_template = false;
15207       template_args = NULL_TREE;
15208     }
15209 
15210   /* Substitute into the qualifying scope.  When there are no ARGS, we
15211      are just trying to simplify a non-dependent expression.  In that
15212      case the qualifying scope may be dependent, and, in any case,
15213      substituting will not help.  */
15214   scope = TREE_OPERAND (qualified_id, 0);
15215   if (args)
15216     {
15217       scope = tsubst (scope, args, complain, in_decl);
15218       expr = tsubst_copy (name, args, complain, in_decl);
15219     }
15220   else
15221     expr = name;
15222 
15223   if (dependent_scope_p (scope))
15224     {
15225       if (is_template)
15226 	expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr, template_args);
15227       tree r = build_qualified_name (NULL_TREE, scope, expr,
15228 				     QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
15229       REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (qualified_id);
15230       return r;
15231     }
15232 
15233   if (!BASELINK_P (name) && !DECL_P (expr))
15234     {
15235       if (TREE_CODE (expr) == BIT_NOT_EXPR)
15236 	{
15237 	  /* A BIT_NOT_EXPR is used to represent a destructor.  */
15238 	  if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
15239 	    {
15240 	      error ("qualifying type %qT does not match destructor name ~%qT",
15241 		     scope, TREE_OPERAND (expr, 0));
15242 	      expr = error_mark_node;
15243 	    }
15244 	  else
15245 	    expr = lookup_qualified_name (scope, complete_dtor_identifier,
15246 					  /*is_type_p=*/0, false);
15247 	}
15248       else
15249 	expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
15250       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
15251 		     ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
15252 	{
15253 	  if (complain & tf_error)
15254 	    {
15255 	      error ("dependent-name %qE is parsed as a non-type, but "
15256 		     "instantiation yields a type", qualified_id);
15257 	      inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
15258 	    }
15259 	  return error_mark_node;
15260 	}
15261     }
15262 
15263   if (DECL_P (expr))
15264     {
15265       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
15266 					   scope);
15267       /* Remember that there was a reference to this entity.  */
15268       if (!mark_used (expr, complain) && !(complain & tf_error))
15269 	return error_mark_node;
15270     }
15271 
15272   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
15273     {
15274       if (complain & tf_error)
15275 	qualified_name_lookup_error (scope,
15276 				     TREE_OPERAND (qualified_id, 1),
15277 				     expr, input_location);
15278       return error_mark_node;
15279     }
15280 
15281   if (is_template)
15282     {
15283       /* We may be repeating a check already done during parsing, but
15284 	 if it was well-formed and passed then, it will pass again
15285 	 now, and if it didn't, we wouldn't have got here.  The case
15286 	 we want to catch is when we couldn't tell then, and can now,
15287 	 namely when templ prior to substitution was an
15288 	 identifier.  */
15289       if (flag_concepts && check_auto_in_tmpl_args (expr, template_args))
15290 	return error_mark_node;
15291 
15292       if (variable_template_p (expr))
15293 	expr = lookup_and_finish_template_variable (expr, template_args,
15294 						    complain);
15295       else
15296 	expr = lookup_template_function (expr, template_args);
15297     }
15298 
15299   if (expr == error_mark_node && complain & tf_error)
15300     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
15301 				 expr, input_location);
15302   else if (TYPE_P (scope))
15303     {
15304       expr = (adjust_result_of_qualified_name_lookup
15305 	      (expr, scope, current_nonlambda_class_type ()));
15306       expr = (finish_qualified_id_expr
15307 	      (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
15308 	       QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
15309 	       /*template_arg_p=*/false, complain));
15310     }
15311 
15312   /* Expressions do not generally have reference type.  */
15313   if (TREE_CODE (expr) != SCOPE_REF
15314       /* However, if we're about to form a pointer-to-member, we just
15315 	 want the referenced member referenced.  */
15316       && TREE_CODE (expr) != OFFSET_REF)
15317     expr = convert_from_reference (expr);
15318 
15319   if (REF_PARENTHESIZED_P (qualified_id))
15320     expr = force_paren_expr (expr);
15321 
15322   return expr;
15323 }
15324 
15325 /* tsubst the initializer for a VAR_DECL.  INIT is the unsubstituted
15326    initializer, DECL is the substituted VAR_DECL.  Other arguments are as
15327    for tsubst.  */
15328 
15329 static tree
tsubst_init(tree init,tree decl,tree args,tsubst_flags_t complain,tree in_decl)15330 tsubst_init (tree init, tree decl, tree args,
15331 	     tsubst_flags_t complain, tree in_decl)
15332 {
15333   if (!init)
15334     return NULL_TREE;
15335 
15336   init = tsubst_expr (init, args, complain, in_decl, false);
15337 
15338   if (!init && TREE_TYPE (decl) != error_mark_node)
15339     {
15340       /* If we had an initializer but it
15341 	 instantiated to nothing,
15342 	 value-initialize the object.  This will
15343 	 only occur when the initializer was a
15344 	 pack expansion where the parameter packs
15345 	 used in that expansion were of length
15346 	 zero.  */
15347       init = build_value_init (TREE_TYPE (decl),
15348 			       complain);
15349       if (TREE_CODE (init) == AGGR_INIT_EXPR)
15350 	init = get_target_expr_sfinae (init, complain);
15351       if (TREE_CODE (init) == TARGET_EXPR)
15352 	TARGET_EXPR_DIRECT_INIT_P (init) = true;
15353     }
15354 
15355   return init;
15356 }
15357 
15358 /* Like tsubst, but deals with expressions.  This function just replaces
15359    template parms; to finish processing the resultant expression, use
15360    tsubst_copy_and_build or tsubst_expr.  */
15361 
15362 static tree
tsubst_copy(tree t,tree args,tsubst_flags_t complain,tree in_decl)15363 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15364 {
15365   enum tree_code code;
15366   tree r;
15367 
15368   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
15369     return t;
15370 
15371   code = TREE_CODE (t);
15372 
15373   switch (code)
15374     {
15375     case PARM_DECL:
15376       r = retrieve_local_specialization (t);
15377 
15378       if (r == NULL_TREE)
15379 	{
15380 	  /* We get here for a use of 'this' in an NSDMI.  */
15381 	  if (DECL_NAME (t) == this_identifier && current_class_ptr)
15382 	    return current_class_ptr;
15383 
15384 	  /* This can happen for a parameter name used later in a function
15385 	     declaration (such as in a late-specified return type).  Just
15386 	     make a dummy decl, since it's only used for its type.  */
15387 	  gcc_assert (cp_unevaluated_operand != 0);
15388 	  r = tsubst_decl (t, args, complain);
15389 	  /* Give it the template pattern as its context; its true context
15390 	     hasn't been instantiated yet and this is good enough for
15391 	     mangling.  */
15392 	  DECL_CONTEXT (r) = DECL_CONTEXT (t);
15393 	}
15394 
15395       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
15396 	r = argument_pack_select_arg (r);
15397       if (!mark_used (r, complain) && !(complain & tf_error))
15398 	return error_mark_node;
15399       return r;
15400 
15401     case CONST_DECL:
15402       {
15403 	tree enum_type;
15404 	tree v;
15405 
15406 	if (DECL_TEMPLATE_PARM_P (t))
15407 	  return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
15408 	/* There is no need to substitute into namespace-scope
15409 	   enumerators.  */
15410 	if (DECL_NAMESPACE_SCOPE_P (t))
15411 	  return t;
15412 	/* If ARGS is NULL, then T is known to be non-dependent.  */
15413 	if (args == NULL_TREE)
15414 	  return scalar_constant_value (t);
15415 
15416 	/* Unfortunately, we cannot just call lookup_name here.
15417 	   Consider:
15418 
15419 	     template <int I> int f() {
15420 	     enum E { a = I };
15421 	     struct S { void g() { E e = a; } };
15422 	     };
15423 
15424 	   When we instantiate f<7>::S::g(), say, lookup_name is not
15425 	   clever enough to find f<7>::a.  */
15426 	enum_type
15427 	  = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
15428 			      /*entering_scope=*/0);
15429 
15430 	for (v = TYPE_VALUES (enum_type);
15431 	     v != NULL_TREE;
15432 	     v = TREE_CHAIN (v))
15433 	  if (TREE_PURPOSE (v) == DECL_NAME (t))
15434 	    return TREE_VALUE (v);
15435 
15436 	  /* We didn't find the name.  That should never happen; if
15437 	     name-lookup found it during preliminary parsing, we
15438 	     should find it again here during instantiation.  */
15439 	gcc_unreachable ();
15440       }
15441       return t;
15442 
15443     case FIELD_DECL:
15444       if (DECL_CONTEXT (t))
15445 	{
15446 	  tree ctx;
15447 
15448 	  ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
15449 				  /*entering_scope=*/1);
15450 	  if (ctx != DECL_CONTEXT (t))
15451 	    {
15452 	      tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
15453 	      if (!r)
15454 		{
15455 		  if (complain & tf_error)
15456 		    error ("using invalid field %qD", t);
15457 		  return error_mark_node;
15458 		}
15459 	      return r;
15460 	    }
15461 	}
15462 
15463       return t;
15464 
15465     case VAR_DECL:
15466     case FUNCTION_DECL:
15467       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
15468 	r = tsubst (t, args, complain, in_decl);
15469       else if (local_variable_p (t)
15470 	       && uses_template_parms (DECL_CONTEXT (t)))
15471 	{
15472 	  r = retrieve_local_specialization (t);
15473 	  if (r == NULL_TREE)
15474 	    {
15475 	      /* First try name lookup to find the instantiation.  */
15476 	      r = lookup_name (DECL_NAME (t));
15477 	      if (r && !is_capture_proxy (r))
15478 		{
15479 		  /* Make sure that the one we found is the one we want.  */
15480 		  tree ctx = enclosing_instantiation_of (DECL_CONTEXT (t));
15481 		  if (ctx != DECL_CONTEXT (r))
15482 		    r = NULL_TREE;
15483 		}
15484 
15485 	      if (r)
15486 		/* OK */;
15487 	      else
15488 		{
15489 		  /* This can happen for a variable used in a
15490 		     late-specified return type of a local lambda, or for a
15491 		     local static or constant.  Building a new VAR_DECL
15492 		     should be OK in all those cases.  */
15493 		  r = tsubst_decl (t, args, complain);
15494 		  if (local_specializations)
15495 		    /* Avoid infinite recursion (79640).  */
15496 		    register_local_specialization (r, t);
15497 		  if (decl_maybe_constant_var_p (r))
15498 		    {
15499 		      /* We can't call cp_finish_decl, so handle the
15500 			 initializer by hand.  */
15501 		      tree init = tsubst_init (DECL_INITIAL (t), r, args,
15502 					       complain, in_decl);
15503 		      if (!processing_template_decl)
15504 			init = maybe_constant_init (init);
15505 		      if (processing_template_decl
15506 			  ? potential_constant_expression (init)
15507 			  : reduced_constant_expression_p (init))
15508 			DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
15509 			  = TREE_CONSTANT (r) = true;
15510 		      DECL_INITIAL (r) = init;
15511 		      if (tree auto_node = type_uses_auto (TREE_TYPE (r)))
15512 			TREE_TYPE (r)
15513 			  = do_auto_deduction (TREE_TYPE (r), init, auto_node,
15514 					       complain, adc_variable_type);
15515 		    }
15516 		  gcc_assert (cp_unevaluated_operand || TREE_STATIC (r)
15517 			      || decl_constant_var_p (r)
15518 			      || errorcount || sorrycount);
15519 		  if (!processing_template_decl
15520 		      && !TREE_STATIC (r))
15521 		    r = process_outer_var_ref (r, complain);
15522 		}
15523 	      /* Remember this for subsequent uses.  */
15524 	      if (local_specializations)
15525 		register_local_specialization (r, t);
15526 	    }
15527 	  if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
15528 	    r = argument_pack_select_arg (r);
15529 	}
15530       else
15531 	r = t;
15532       if (!mark_used (r, complain))
15533 	return error_mark_node;
15534       return r;
15535 
15536     case NAMESPACE_DECL:
15537       return t;
15538 
15539     case OVERLOAD:
15540       /* An OVERLOAD will always be a non-dependent overload set; an
15541 	 overload set from function scope will just be represented with an
15542 	 IDENTIFIER_NODE, and from class scope with a BASELINK.  */
15543       gcc_assert (!uses_template_parms (t));
15544       /* We must have marked any lookups as persistent.  */
15545       gcc_assert (!OVL_LOOKUP_P (t) || OVL_USED_P (t));
15546       return t;
15547 
15548     case BASELINK:
15549       return tsubst_baselink (t, current_nonlambda_class_type (),
15550 			      args, complain, in_decl);
15551 
15552     case TEMPLATE_DECL:
15553       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
15554 	return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
15555 		       args, complain, in_decl);
15556       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
15557 	return tsubst (t, args, complain, in_decl);
15558       else if (DECL_CLASS_SCOPE_P (t)
15559 	       && uses_template_parms (DECL_CONTEXT (t)))
15560 	{
15561 	  /* Template template argument like the following example need
15562 	     special treatment:
15563 
15564 	       template <template <class> class TT> struct C {};
15565 	       template <class T> struct D {
15566 		 template <class U> struct E {};
15567 		 C<E> c;				// #1
15568 	       };
15569 	       D<int> d;				// #2
15570 
15571 	     We are processing the template argument `E' in #1 for
15572 	     the template instantiation #2.  Originally, `E' is a
15573 	     TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
15574 	     have to substitute this with one having context `D<int>'.  */
15575 
15576 	  tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
15577 	  if (dependent_scope_p (context))
15578 	    {
15579 	      /* When rewriting a constructor into a deduction guide, a
15580 		 non-dependent name can become dependent, so memtmpl<args>
15581 		 becomes context::template memtmpl<args>.  */
15582 	      tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15583 	      return build_qualified_name (type, context, DECL_NAME (t),
15584 					   /*template*/true);
15585 	    }
15586 	  return lookup_field (context, DECL_NAME(t), 0, false);
15587 	}
15588       else
15589 	/* Ordinary template template argument.  */
15590 	return t;
15591 
15592     case NON_LVALUE_EXPR:
15593     case VIEW_CONVERT_EXPR:
15594 	{
15595 	  /* Handle location wrappers by substituting the wrapped node
15596 	     first, *then* reusing the resulting type.  Doing the type
15597 	     first ensures that we handle template parameters and
15598 	     parameter pack expansions.  */
15599 	  gcc_assert (location_wrapper_p (t));
15600 	  tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15601 	  return maybe_wrap_with_location (op0, EXPR_LOCATION (t));
15602 	}
15603 
15604     case CAST_EXPR:
15605     case REINTERPRET_CAST_EXPR:
15606     case CONST_CAST_EXPR:
15607     case STATIC_CAST_EXPR:
15608     case DYNAMIC_CAST_EXPR:
15609     case IMPLICIT_CONV_EXPR:
15610     case CONVERT_EXPR:
15611     case NOP_EXPR:
15612       {
15613 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15614 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15615 	return build1 (code, type, op0);
15616       }
15617 
15618     case SIZEOF_EXPR:
15619       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
15620 	  || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
15621         {
15622           tree expanded, op = TREE_OPERAND (t, 0);
15623 	  int len = 0;
15624 
15625 	  if (SIZEOF_EXPR_TYPE_P (t))
15626 	    op = TREE_TYPE (op);
15627 
15628 	  ++cp_unevaluated_operand;
15629 	  ++c_inhibit_evaluation_warnings;
15630 	  /* We only want to compute the number of arguments.  */
15631 	  if (PACK_EXPANSION_P (op))
15632 	    expanded = tsubst_pack_expansion (op, args, complain, in_decl);
15633 	  else
15634 	    expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
15635 					     args, complain, in_decl);
15636 	  --cp_unevaluated_operand;
15637 	  --c_inhibit_evaluation_warnings;
15638 
15639 	  if (TREE_CODE (expanded) == TREE_VEC)
15640 	    {
15641 	      len = TREE_VEC_LENGTH (expanded);
15642 	      /* Set TREE_USED for the benefit of -Wunused.  */
15643 	      for (int i = 0; i < len; i++)
15644 		if (DECL_P (TREE_VEC_ELT (expanded, i)))
15645 		  TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
15646 	    }
15647 
15648 	  if (expanded == error_mark_node)
15649 	    return error_mark_node;
15650 	  else if (PACK_EXPANSION_P (expanded)
15651 		   || (TREE_CODE (expanded) == TREE_VEC
15652 		       && pack_expansion_args_count (expanded)))
15653 
15654 	    {
15655 	      if (PACK_EXPANSION_P (expanded))
15656 		/* OK.  */;
15657 	      else if (TREE_VEC_LENGTH (expanded) == 1)
15658 		expanded = TREE_VEC_ELT (expanded, 0);
15659 	      else
15660 		expanded = make_argument_pack (expanded);
15661 
15662 	      if (TYPE_P (expanded))
15663 		return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR,
15664 						   false,
15665 						   complain & tf_error);
15666 	      else
15667 		return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
15668                                                    complain & tf_error);
15669 	    }
15670 	  else
15671 	    return build_int_cst (size_type_node, len);
15672         }
15673       if (SIZEOF_EXPR_TYPE_P (t))
15674 	{
15675 	  r = tsubst (TREE_TYPE (TREE_OPERAND (t, 0)),
15676 		      args, complain, in_decl);
15677 	  r = build1 (NOP_EXPR, r, error_mark_node);
15678 	  r = build1 (SIZEOF_EXPR,
15679 		      tsubst (TREE_TYPE (t), args, complain, in_decl), r);
15680 	  SIZEOF_EXPR_TYPE_P (r) = 1;
15681 	  return r;
15682 	}
15683       /* Fall through */
15684 
15685     case INDIRECT_REF:
15686     case NEGATE_EXPR:
15687     case TRUTH_NOT_EXPR:
15688     case BIT_NOT_EXPR:
15689     case ADDR_EXPR:
15690     case UNARY_PLUS_EXPR:      /* Unary + */
15691     case ALIGNOF_EXPR:
15692     case AT_ENCODE_EXPR:
15693     case ARROW_EXPR:
15694     case THROW_EXPR:
15695     case TYPEID_EXPR:
15696     case REALPART_EXPR:
15697     case IMAGPART_EXPR:
15698     case PAREN_EXPR:
15699       {
15700 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15701 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15702 	r = build1 (code, type, op0);
15703 	if (code == ALIGNOF_EXPR)
15704 	  ALIGNOF_EXPR_STD_P (r) = ALIGNOF_EXPR_STD_P (t);
15705 	return r;
15706       }
15707 
15708     case COMPONENT_REF:
15709       {
15710 	tree object;
15711 	tree name;
15712 
15713 	object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15714 	name = TREE_OPERAND (t, 1);
15715 	if (TREE_CODE (name) == BIT_NOT_EXPR)
15716 	  {
15717 	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
15718 				complain, in_decl);
15719 	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
15720 	  }
15721 	else if (TREE_CODE (name) == SCOPE_REF
15722 		 && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
15723 	  {
15724 	    tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
15725 				     complain, in_decl);
15726 	    name = TREE_OPERAND (name, 1);
15727 	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
15728 				complain, in_decl);
15729 	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
15730 	    name = build_qualified_name (/*type=*/NULL_TREE,
15731 					 base, name,
15732 					 /*template_p=*/false);
15733 	  }
15734 	else if (BASELINK_P (name))
15735 	  name = tsubst_baselink (name,
15736 				  non_reference (TREE_TYPE (object)),
15737 				  args, complain,
15738 				  in_decl);
15739 	else
15740 	  name = tsubst_copy (name, args, complain, in_decl);
15741 	return build_nt (COMPONENT_REF, object, name, NULL_TREE);
15742       }
15743 
15744     case PLUS_EXPR:
15745     case MINUS_EXPR:
15746     case MULT_EXPR:
15747     case TRUNC_DIV_EXPR:
15748     case CEIL_DIV_EXPR:
15749     case FLOOR_DIV_EXPR:
15750     case ROUND_DIV_EXPR:
15751     case EXACT_DIV_EXPR:
15752     case BIT_AND_EXPR:
15753     case BIT_IOR_EXPR:
15754     case BIT_XOR_EXPR:
15755     case TRUNC_MOD_EXPR:
15756     case FLOOR_MOD_EXPR:
15757     case TRUTH_ANDIF_EXPR:
15758     case TRUTH_ORIF_EXPR:
15759     case TRUTH_AND_EXPR:
15760     case TRUTH_OR_EXPR:
15761     case RSHIFT_EXPR:
15762     case LSHIFT_EXPR:
15763     case RROTATE_EXPR:
15764     case LROTATE_EXPR:
15765     case EQ_EXPR:
15766     case NE_EXPR:
15767     case MAX_EXPR:
15768     case MIN_EXPR:
15769     case LE_EXPR:
15770     case GE_EXPR:
15771     case LT_EXPR:
15772     case GT_EXPR:
15773     case COMPOUND_EXPR:
15774     case DOTSTAR_EXPR:
15775     case MEMBER_REF:
15776     case PREDECREMENT_EXPR:
15777     case PREINCREMENT_EXPR:
15778     case POSTDECREMENT_EXPR:
15779     case POSTINCREMENT_EXPR:
15780       {
15781 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15782 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15783 	return build_nt (code, op0, op1);
15784       }
15785 
15786     case SCOPE_REF:
15787       {
15788 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15789 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15790 	return build_qualified_name (/*type=*/NULL_TREE, op0, op1,
15791 				     QUALIFIED_NAME_IS_TEMPLATE (t));
15792       }
15793 
15794     case ARRAY_REF:
15795       {
15796 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15797 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15798 	return build_nt (ARRAY_REF, op0, op1, NULL_TREE, NULL_TREE);
15799       }
15800 
15801     case CALL_EXPR:
15802       {
15803 	int n = VL_EXP_OPERAND_LENGTH (t);
15804 	tree result = build_vl_exp (CALL_EXPR, n);
15805 	int i;
15806 	for (i = 0; i < n; i++)
15807 	  TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
15808 					     complain, in_decl);
15809 	return result;
15810       }
15811 
15812     case COND_EXPR:
15813     case MODOP_EXPR:
15814     case PSEUDO_DTOR_EXPR:
15815     case VEC_PERM_EXPR:
15816       {
15817 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15818 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15819 	tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
15820 	r = build_nt (code, op0, op1, op2);
15821 	TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
15822 	return r;
15823       }
15824 
15825     case NEW_EXPR:
15826       {
15827 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15828 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15829 	tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
15830 	r = build_nt (code, op0, op1, op2);
15831 	NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
15832 	return r;
15833       }
15834 
15835     case DELETE_EXPR:
15836       {
15837 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15838 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15839 	r = build_nt (code, op0, op1);
15840 	DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
15841 	DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
15842 	return r;
15843       }
15844 
15845     case TEMPLATE_ID_EXPR:
15846       {
15847 	/* Substituted template arguments */
15848 	tree fn = TREE_OPERAND (t, 0);
15849 	tree targs = TREE_OPERAND (t, 1);
15850 
15851 	fn = tsubst_copy (fn, args, complain, in_decl);
15852 	if (targs)
15853 	  targs = tsubst_template_args (targs, args, complain, in_decl);
15854 
15855 	return lookup_template_function (fn, targs);
15856       }
15857 
15858     case TREE_LIST:
15859       {
15860 	tree purpose, value, chain;
15861 
15862 	if (t == void_list_node)
15863 	  return t;
15864 
15865 	purpose = TREE_PURPOSE (t);
15866 	if (purpose)
15867 	  purpose = tsubst_copy (purpose, args, complain, in_decl);
15868 	value = TREE_VALUE (t);
15869 	if (value)
15870 	  value = tsubst_copy (value, args, complain, in_decl);
15871 	chain = TREE_CHAIN (t);
15872 	if (chain && chain != void_type_node)
15873 	  chain = tsubst_copy (chain, args, complain, in_decl);
15874 	if (purpose == TREE_PURPOSE (t)
15875 	    && value == TREE_VALUE (t)
15876 	    && chain == TREE_CHAIN (t))
15877 	  return t;
15878 	return tree_cons (purpose, value, chain);
15879       }
15880 
15881     case RECORD_TYPE:
15882     case UNION_TYPE:
15883     case ENUMERAL_TYPE:
15884     case INTEGER_TYPE:
15885     case TEMPLATE_TYPE_PARM:
15886     case TEMPLATE_TEMPLATE_PARM:
15887     case BOUND_TEMPLATE_TEMPLATE_PARM:
15888     case TEMPLATE_PARM_INDEX:
15889     case POINTER_TYPE:
15890     case REFERENCE_TYPE:
15891     case OFFSET_TYPE:
15892     case FUNCTION_TYPE:
15893     case METHOD_TYPE:
15894     case ARRAY_TYPE:
15895     case TYPENAME_TYPE:
15896     case UNBOUND_CLASS_TEMPLATE:
15897     case TYPEOF_TYPE:
15898     case DECLTYPE_TYPE:
15899     case TYPE_DECL:
15900       return tsubst (t, args, complain, in_decl);
15901 
15902     case USING_DECL:
15903       t = DECL_NAME (t);
15904       /* Fall through.  */
15905     case IDENTIFIER_NODE:
15906       if (IDENTIFIER_CONV_OP_P (t))
15907 	{
15908 	  tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15909 	  return make_conv_op_name (new_type);
15910 	}
15911       else
15912 	return t;
15913 
15914     case CONSTRUCTOR:
15915       /* This is handled by tsubst_copy_and_build.  */
15916       gcc_unreachable ();
15917 
15918     case VA_ARG_EXPR:
15919       {
15920 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15921 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15922 	return build_x_va_arg (EXPR_LOCATION (t), op0, type);
15923       }
15924 
15925     case CLEANUP_POINT_EXPR:
15926       /* We shouldn't have built any of these during initial template
15927 	 generation.  Instead, they should be built during instantiation
15928 	 in response to the saved STMT_IS_FULL_EXPR_P setting.  */
15929       gcc_unreachable ();
15930 
15931     case OFFSET_REF:
15932       {
15933 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15934 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15935 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15936 	r = build2 (code, type, op0, op1);
15937 	PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
15938 	if (!mark_used (TREE_OPERAND (r, 1), complain)
15939 	    && !(complain & tf_error))
15940 	  return error_mark_node;
15941 	return r;
15942       }
15943 
15944     case EXPR_PACK_EXPANSION:
15945       error ("invalid use of pack expansion expression");
15946       return error_mark_node;
15947 
15948     case NONTYPE_ARGUMENT_PACK:
15949       error ("use %<...%> to expand argument pack");
15950       return error_mark_node;
15951 
15952     case VOID_CST:
15953       gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
15954       return t;
15955 
15956     case INTEGER_CST:
15957     case REAL_CST:
15958     case STRING_CST:
15959     case COMPLEX_CST:
15960       {
15961 	/* Instantiate any typedefs in the type.  */
15962 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15963 	r = fold_convert (type, t);
15964 	gcc_assert (TREE_CODE (r) == code);
15965 	return r;
15966       }
15967 
15968     case PTRMEM_CST:
15969       /* These can sometimes show up in a partial instantiation, but never
15970 	 involve template parms.  */
15971       gcc_assert (!uses_template_parms (t));
15972       return t;
15973 
15974     case UNARY_LEFT_FOLD_EXPR:
15975       return tsubst_unary_left_fold (t, args, complain, in_decl);
15976     case UNARY_RIGHT_FOLD_EXPR:
15977       return tsubst_unary_right_fold (t, args, complain, in_decl);
15978     case BINARY_LEFT_FOLD_EXPR:
15979       return tsubst_binary_left_fold (t, args, complain, in_decl);
15980     case BINARY_RIGHT_FOLD_EXPR:
15981       return tsubst_binary_right_fold (t, args, complain, in_decl);
15982     case PREDICT_EXPR:
15983       return t;
15984 
15985     case DEBUG_BEGIN_STMT:
15986       /* ??? There's no point in copying it for now, but maybe some
15987 	 day it will contain more information, such as a pointer back
15988 	 to the containing function, inlined copy or so.  */
15989       return t;
15990 
15991     default:
15992       /* We shouldn't get here, but keep going if !flag_checking.  */
15993       if (flag_checking)
15994 	gcc_unreachable ();
15995       return t;
15996     }
15997 }
15998 
15999 /* Helper function for tsubst_omp_clauses, used for instantiation of
16000    OMP_CLAUSE_DECL of clauses.  */
16001 
16002 static tree
tsubst_omp_clause_decl(tree decl,tree args,tsubst_flags_t complain,tree in_decl)16003 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
16004 			tree in_decl)
16005 {
16006   if (decl == NULL_TREE)
16007     return NULL_TREE;
16008 
16009   /* Handle an OpenMP array section represented as a TREE_LIST (or
16010      OMP_CLAUSE_DEPEND_KIND).  An OMP_CLAUSE_DEPEND (with a depend
16011      kind of OMP_CLAUSE_DEPEND_SINK) can also be represented as a
16012      TREE_LIST.  We can handle it exactly the same as an array section
16013      (purpose, value, and a chain), even though the nomenclature
16014      (low_bound, length, etc) is different.  */
16015   if (TREE_CODE (decl) == TREE_LIST)
16016     {
16017       tree low_bound
16018 	= tsubst_expr (TREE_PURPOSE (decl), args, complain, in_decl,
16019 		       /*integral_constant_expression_p=*/false);
16020       tree length = tsubst_expr (TREE_VALUE (decl), args, complain, in_decl,
16021 				 /*integral_constant_expression_p=*/false);
16022       tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
16023 					   in_decl);
16024       if (TREE_PURPOSE (decl) == low_bound
16025 	  && TREE_VALUE (decl) == length
16026 	  && TREE_CHAIN (decl) == chain)
16027 	return decl;
16028       tree ret = tree_cons (low_bound, length, chain);
16029       OMP_CLAUSE_DEPEND_SINK_NEGATIVE (ret)
16030 	= OMP_CLAUSE_DEPEND_SINK_NEGATIVE (decl);
16031       return ret;
16032     }
16033   tree ret = tsubst_expr (decl, args, complain, in_decl,
16034 			  /*integral_constant_expression_p=*/false);
16035   /* Undo convert_from_reference tsubst_expr could have called.  */
16036   if (decl
16037       && REFERENCE_REF_P (ret)
16038       && !REFERENCE_REF_P (decl))
16039     ret = TREE_OPERAND (ret, 0);
16040   return ret;
16041 }
16042 
16043 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
16044 
16045 static tree
tsubst_omp_clauses(tree clauses,enum c_omp_region_type ort,tree args,tsubst_flags_t complain,tree in_decl)16046 tsubst_omp_clauses (tree clauses, enum c_omp_region_type ort,
16047 		    tree args, tsubst_flags_t complain, tree in_decl)
16048 {
16049   tree new_clauses = NULL_TREE, nc, oc;
16050   tree linear_no_step = NULL_TREE;
16051 
16052   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
16053     {
16054       nc = copy_node (oc);
16055       OMP_CLAUSE_CHAIN (nc) = new_clauses;
16056       new_clauses = nc;
16057 
16058       switch (OMP_CLAUSE_CODE (nc))
16059 	{
16060 	case OMP_CLAUSE_LASTPRIVATE:
16061 	  if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
16062 	    {
16063 	      OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
16064 	      tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
16065 			   in_decl, /*integral_constant_expression_p=*/false);
16066 	      OMP_CLAUSE_LASTPRIVATE_STMT (nc)
16067 		= pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
16068 	    }
16069 	  /* FALLTHRU */
16070 	case OMP_CLAUSE_PRIVATE:
16071 	case OMP_CLAUSE_SHARED:
16072 	case OMP_CLAUSE_FIRSTPRIVATE:
16073 	case OMP_CLAUSE_COPYIN:
16074 	case OMP_CLAUSE_COPYPRIVATE:
16075 	case OMP_CLAUSE_UNIFORM:
16076 	case OMP_CLAUSE_DEPEND:
16077 	case OMP_CLAUSE_FROM:
16078 	case OMP_CLAUSE_TO:
16079 	case OMP_CLAUSE_MAP:
16080 	case OMP_CLAUSE_USE_DEVICE_PTR:
16081 	case OMP_CLAUSE_IS_DEVICE_PTR:
16082 	  OMP_CLAUSE_DECL (nc)
16083 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16084 				      in_decl);
16085 	  break;
16086 	case OMP_CLAUSE_TILE:
16087 	case OMP_CLAUSE_IF:
16088 	case OMP_CLAUSE_NUM_THREADS:
16089 	case OMP_CLAUSE_SCHEDULE:
16090 	case OMP_CLAUSE_COLLAPSE:
16091 	case OMP_CLAUSE_FINAL:
16092 	case OMP_CLAUSE_DEVICE:
16093 	case OMP_CLAUSE_DIST_SCHEDULE:
16094 	case OMP_CLAUSE_NUM_TEAMS:
16095 	case OMP_CLAUSE_THREAD_LIMIT:
16096 	case OMP_CLAUSE_SAFELEN:
16097 	case OMP_CLAUSE_SIMDLEN:
16098 	case OMP_CLAUSE_NUM_TASKS:
16099 	case OMP_CLAUSE_GRAINSIZE:
16100 	case OMP_CLAUSE_PRIORITY:
16101 	case OMP_CLAUSE_ORDERED:
16102 	case OMP_CLAUSE_HINT:
16103 	case OMP_CLAUSE_NUM_GANGS:
16104 	case OMP_CLAUSE_NUM_WORKERS:
16105 	case OMP_CLAUSE_VECTOR_LENGTH:
16106 	case OMP_CLAUSE_WORKER:
16107 	case OMP_CLAUSE_VECTOR:
16108 	case OMP_CLAUSE_ASYNC:
16109 	case OMP_CLAUSE_WAIT:
16110 	  OMP_CLAUSE_OPERAND (nc, 0)
16111 	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain,
16112 			   in_decl, /*integral_constant_expression_p=*/false);
16113 	  break;
16114 	case OMP_CLAUSE_REDUCTION:
16115 	  if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
16116 	    {
16117 	      tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
16118 	      if (TREE_CODE (placeholder) == SCOPE_REF)
16119 		{
16120 		  tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
16121 				       complain, in_decl);
16122 		  OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
16123 		    = build_qualified_name (NULL_TREE, scope,
16124 					    TREE_OPERAND (placeholder, 1),
16125 					    false);
16126 		}
16127 	      else
16128 		gcc_assert (identifier_p (placeholder));
16129 	    }
16130 	  OMP_CLAUSE_DECL (nc)
16131 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16132 				      in_decl);
16133 	  break;
16134 	case OMP_CLAUSE_GANG:
16135 	case OMP_CLAUSE_ALIGNED:
16136 	  OMP_CLAUSE_DECL (nc)
16137 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16138 				      in_decl);
16139 	  OMP_CLAUSE_OPERAND (nc, 1)
16140 	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain,
16141 			   in_decl, /*integral_constant_expression_p=*/false);
16142 	  break;
16143 	case OMP_CLAUSE_LINEAR:
16144 	  OMP_CLAUSE_DECL (nc)
16145 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16146 				      in_decl);
16147 	  if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
16148 	    {
16149 	      gcc_assert (!linear_no_step);
16150 	      linear_no_step = nc;
16151 	    }
16152 	  else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
16153 	    OMP_CLAUSE_LINEAR_STEP (nc)
16154 	      = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
16155 					complain, in_decl);
16156 	  else
16157 	    OMP_CLAUSE_LINEAR_STEP (nc)
16158 	      = tsubst_expr (OMP_CLAUSE_LINEAR_STEP (oc), args, complain,
16159 			     in_decl,
16160 			     /*integral_constant_expression_p=*/false);
16161 	  break;
16162 	case OMP_CLAUSE_NOWAIT:
16163 	case OMP_CLAUSE_DEFAULT:
16164 	case OMP_CLAUSE_UNTIED:
16165 	case OMP_CLAUSE_MERGEABLE:
16166 	case OMP_CLAUSE_INBRANCH:
16167 	case OMP_CLAUSE_NOTINBRANCH:
16168 	case OMP_CLAUSE_PROC_BIND:
16169 	case OMP_CLAUSE_FOR:
16170 	case OMP_CLAUSE_PARALLEL:
16171 	case OMP_CLAUSE_SECTIONS:
16172 	case OMP_CLAUSE_TASKGROUP:
16173 	case OMP_CLAUSE_NOGROUP:
16174 	case OMP_CLAUSE_THREADS:
16175 	case OMP_CLAUSE_SIMD:
16176 	case OMP_CLAUSE_DEFAULTMAP:
16177 	case OMP_CLAUSE_INDEPENDENT:
16178 	case OMP_CLAUSE_AUTO:
16179 	case OMP_CLAUSE_SEQ:
16180 	  break;
16181 	default:
16182 	  gcc_unreachable ();
16183 	}
16184       if ((ort & C_ORT_OMP_DECLARE_SIMD) == C_ORT_OMP)
16185 	switch (OMP_CLAUSE_CODE (nc))
16186 	  {
16187 	  case OMP_CLAUSE_SHARED:
16188 	  case OMP_CLAUSE_PRIVATE:
16189 	  case OMP_CLAUSE_FIRSTPRIVATE:
16190 	  case OMP_CLAUSE_LASTPRIVATE:
16191 	  case OMP_CLAUSE_COPYPRIVATE:
16192 	  case OMP_CLAUSE_LINEAR:
16193 	  case OMP_CLAUSE_REDUCTION:
16194 	  case OMP_CLAUSE_USE_DEVICE_PTR:
16195 	  case OMP_CLAUSE_IS_DEVICE_PTR:
16196 	    /* tsubst_expr on SCOPE_REF results in returning
16197 	       finish_non_static_data_member result.  Undo that here.  */
16198 	    if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
16199 		&& (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
16200 		    == IDENTIFIER_NODE))
16201 	      {
16202 		tree t = OMP_CLAUSE_DECL (nc);
16203 		tree v = t;
16204 		while (v)
16205 		  switch (TREE_CODE (v))
16206 		    {
16207 		    case COMPONENT_REF:
16208 		    case MEM_REF:
16209 		    case INDIRECT_REF:
16210 		    CASE_CONVERT:
16211 		    case POINTER_PLUS_EXPR:
16212 		      v = TREE_OPERAND (v, 0);
16213 		      continue;
16214 		    case PARM_DECL:
16215 		      if (DECL_CONTEXT (v) == current_function_decl
16216 			  && DECL_ARTIFICIAL (v)
16217 			  && DECL_NAME (v) == this_identifier)
16218 			OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
16219 		      /* FALLTHRU */
16220 		    default:
16221 		      v = NULL_TREE;
16222 		      break;
16223 		    }
16224 	      }
16225 	    else if (VAR_P (OMP_CLAUSE_DECL (oc))
16226 		     && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
16227 		     && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
16228 		     && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
16229 		     && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
16230 	      {
16231 		tree decl = OMP_CLAUSE_DECL (nc);
16232 		if (VAR_P (decl))
16233 		  {
16234 		    retrofit_lang_decl (decl);
16235 		    DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
16236 		  }
16237 	      }
16238 	    break;
16239 	  default:
16240 	    break;
16241 	  }
16242     }
16243 
16244   new_clauses = nreverse (new_clauses);
16245   if (ort != C_ORT_OMP_DECLARE_SIMD)
16246     {
16247       new_clauses = finish_omp_clauses (new_clauses, ort);
16248       if (linear_no_step)
16249 	for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
16250 	  if (nc == linear_no_step)
16251 	    {
16252 	      OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
16253 	      break;
16254 	    }
16255     }
16256   return new_clauses;
16257 }
16258 
16259 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
16260 
16261 static tree
tsubst_copy_asm_operands(tree t,tree args,tsubst_flags_t complain,tree in_decl)16262 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
16263 			  tree in_decl)
16264 {
16265 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
16266 
16267   tree purpose, value, chain;
16268 
16269   if (t == NULL)
16270     return t;
16271 
16272   if (TREE_CODE (t) != TREE_LIST)
16273     return tsubst_copy_and_build (t, args, complain, in_decl,
16274 				  /*function_p=*/false,
16275 				  /*integral_constant_expression_p=*/false);
16276 
16277   if (t == void_list_node)
16278     return t;
16279 
16280   purpose = TREE_PURPOSE (t);
16281   if (purpose)
16282     purpose = RECUR (purpose);
16283   value = TREE_VALUE (t);
16284   if (value)
16285     {
16286       if (TREE_CODE (value) != LABEL_DECL)
16287 	value = RECUR (value);
16288       else
16289 	{
16290 	  value = lookup_label (DECL_NAME (value));
16291 	  gcc_assert (TREE_CODE (value) == LABEL_DECL);
16292 	  TREE_USED (value) = 1;
16293 	}
16294     }
16295   chain = TREE_CHAIN (t);
16296   if (chain && chain != void_type_node)
16297     chain = RECUR (chain);
16298   return tree_cons (purpose, value, chain);
16299 #undef RECUR
16300 }
16301 
16302 /* Used to temporarily communicate the list of #pragma omp parallel
16303    clauses to #pragma omp for instantiation if they are combined
16304    together.  */
16305 
16306 static tree *omp_parallel_combined_clauses;
16307 
16308 /* Substitute one OMP_FOR iterator.  */
16309 
16310 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)16311 tsubst_omp_for_iterator (tree t, int i, tree declv, tree orig_declv,
16312 			 tree initv, tree condv, tree incrv, tree *clauses,
16313 			 tree args, tsubst_flags_t complain, tree in_decl,
16314 			 bool integral_constant_expression_p)
16315 {
16316 #define RECUR(NODE)				\
16317   tsubst_expr ((NODE), args, complain, in_decl,	\
16318 	       integral_constant_expression_p)
16319   tree decl, init, cond, incr;
16320 
16321   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
16322   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
16323 
16324   if (orig_declv && OMP_FOR_ORIG_DECLS (t))
16325     {
16326       tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
16327       TREE_VEC_ELT (orig_declv, i) = RECUR (o);
16328     }
16329 
16330   decl = TREE_OPERAND (init, 0);
16331   init = TREE_OPERAND (init, 1);
16332   tree decl_expr = NULL_TREE;
16333   if (init && TREE_CODE (init) == DECL_EXPR)
16334     {
16335       /* We need to jump through some hoops to handle declarations in the
16336 	 init-statement, since we might need to handle auto deduction,
16337 	 but we need to keep control of initialization.  */
16338       decl_expr = init;
16339       init = DECL_INITIAL (DECL_EXPR_DECL (init));
16340       decl = tsubst_decl (decl, args, complain);
16341     }
16342   else
16343     {
16344       if (TREE_CODE (decl) == SCOPE_REF)
16345 	{
16346 	  decl = RECUR (decl);
16347 	  if (TREE_CODE (decl) == COMPONENT_REF)
16348 	    {
16349 	      tree v = decl;
16350 	      while (v)
16351 		switch (TREE_CODE (v))
16352 		  {
16353 		  case COMPONENT_REF:
16354 		  case MEM_REF:
16355 		  case INDIRECT_REF:
16356 		  CASE_CONVERT:
16357 		  case POINTER_PLUS_EXPR:
16358 		    v = TREE_OPERAND (v, 0);
16359 		    continue;
16360 		  case PARM_DECL:
16361 		    if (DECL_CONTEXT (v) == current_function_decl
16362 			&& DECL_ARTIFICIAL (v)
16363 			&& DECL_NAME (v) == this_identifier)
16364 		      {
16365 			decl = TREE_OPERAND (decl, 1);
16366 			decl = omp_privatize_field (decl, false);
16367 		      }
16368 		    /* FALLTHRU */
16369 		  default:
16370 		    v = NULL_TREE;
16371 		    break;
16372 		  }
16373 	    }
16374 	}
16375       else
16376 	decl = RECUR (decl);
16377     }
16378   init = RECUR (init);
16379 
16380   tree auto_node = type_uses_auto (TREE_TYPE (decl));
16381   if (auto_node && init)
16382     TREE_TYPE (decl)
16383       = do_auto_deduction (TREE_TYPE (decl), init, auto_node, complain);
16384 
16385   gcc_assert (!type_dependent_expression_p (decl));
16386 
16387   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
16388     {
16389       if (decl_expr)
16390 	{
16391 	  /* Declare the variable, but don't let that initialize it.  */
16392 	  tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
16393 	  DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
16394 	  RECUR (decl_expr);
16395 	  DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
16396 	}
16397 
16398       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
16399       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
16400       if (TREE_CODE (incr) == MODIFY_EXPR)
16401 	{
16402 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
16403 	  tree rhs = RECUR (TREE_OPERAND (incr, 1));
16404 	  incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
16405 				      NOP_EXPR, rhs, complain);
16406 	}
16407       else
16408 	incr = RECUR (incr);
16409       TREE_VEC_ELT (declv, i) = decl;
16410       TREE_VEC_ELT (initv, i) = init;
16411       TREE_VEC_ELT (condv, i) = cond;
16412       TREE_VEC_ELT (incrv, i) = incr;
16413       return;
16414     }
16415 
16416   if (decl_expr)
16417     {
16418       /* Declare and initialize the variable.  */
16419       RECUR (decl_expr);
16420       init = NULL_TREE;
16421     }
16422   else if (init)
16423     {
16424       tree *pc;
16425       int j;
16426       for (j = (omp_parallel_combined_clauses == NULL ? 1 : 0); j < 2; j++)
16427 	{
16428 	  for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
16429 	    {
16430 	      if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
16431 		  && OMP_CLAUSE_DECL (*pc) == decl)
16432 		break;
16433 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
16434 		       && OMP_CLAUSE_DECL (*pc) == decl)
16435 		{
16436 		  if (j)
16437 		    break;
16438 		  /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES.  */
16439 		  tree c = *pc;
16440 		  *pc = OMP_CLAUSE_CHAIN (c);
16441 		  OMP_CLAUSE_CHAIN (c) = *clauses;
16442 		  *clauses = c;
16443 		}
16444 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
16445 		       && OMP_CLAUSE_DECL (*pc) == decl)
16446 		{
16447 		  error ("iteration variable %qD should not be firstprivate",
16448 			 decl);
16449 		  *pc = OMP_CLAUSE_CHAIN (*pc);
16450 		}
16451 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
16452 		       && OMP_CLAUSE_DECL (*pc) == decl)
16453 		{
16454 		  error ("iteration variable %qD should not be reduction",
16455 			 decl);
16456 		  *pc = OMP_CLAUSE_CHAIN (*pc);
16457 		}
16458 	      else
16459 		pc = &OMP_CLAUSE_CHAIN (*pc);
16460 	    }
16461 	  if (*pc)
16462 	    break;
16463 	}
16464       if (*pc == NULL_TREE)
16465 	{
16466 	  tree c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
16467 	  OMP_CLAUSE_DECL (c) = decl;
16468 	  c = finish_omp_clauses (c, C_ORT_OMP);
16469 	  if (c)
16470 	    {
16471 	      OMP_CLAUSE_CHAIN (c) = *clauses;
16472 	      *clauses = c;
16473 	    }
16474 	}
16475     }
16476   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
16477   if (COMPARISON_CLASS_P (cond))
16478     {
16479       tree op0 = RECUR (TREE_OPERAND (cond, 0));
16480       tree op1 = RECUR (TREE_OPERAND (cond, 1));
16481       cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
16482     }
16483   else
16484     cond = RECUR (cond);
16485   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
16486   switch (TREE_CODE (incr))
16487     {
16488     case PREINCREMENT_EXPR:
16489     case PREDECREMENT_EXPR:
16490     case POSTINCREMENT_EXPR:
16491     case POSTDECREMENT_EXPR:
16492       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
16493 		     RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
16494       break;
16495     case MODIFY_EXPR:
16496       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
16497 	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
16498 	{
16499 	  tree rhs = TREE_OPERAND (incr, 1);
16500 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
16501 	  tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
16502 	  tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
16503 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
16504 			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
16505 				 rhs0, rhs1));
16506 	}
16507       else
16508 	incr = RECUR (incr);
16509       break;
16510     case MODOP_EXPR:
16511       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
16512 	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
16513 	{
16514 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
16515 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
16516 			 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
16517 				 TREE_TYPE (decl), lhs,
16518 				 RECUR (TREE_OPERAND (incr, 2))));
16519 	}
16520       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
16521 	       && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
16522 		   || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
16523 	{
16524 	  tree rhs = TREE_OPERAND (incr, 2);
16525 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
16526 	  tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
16527 	  tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
16528 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
16529 			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
16530 				 rhs0, rhs1));
16531 	}
16532       else
16533 	incr = RECUR (incr);
16534       break;
16535     default:
16536       incr = RECUR (incr);
16537       break;
16538     }
16539 
16540   TREE_VEC_ELT (declv, i) = decl;
16541   TREE_VEC_ELT (initv, i) = init;
16542   TREE_VEC_ELT (condv, i) = cond;
16543   TREE_VEC_ELT (incrv, i) = incr;
16544 #undef RECUR
16545 }
16546 
16547 /* Helper function of tsubst_expr, find OMP_TEAMS inside
16548    of OMP_TARGET's body.  */
16549 
16550 static tree
tsubst_find_omp_teams(tree * tp,int * walk_subtrees,void *)16551 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
16552 {
16553   *walk_subtrees = 0;
16554   switch (TREE_CODE (*tp))
16555     {
16556     case OMP_TEAMS:
16557       return *tp;
16558     case BIND_EXPR:
16559     case STATEMENT_LIST:
16560       *walk_subtrees = 1;
16561       break;
16562     default:
16563       break;
16564     }
16565   return NULL_TREE;
16566 }
16567 
16568 /* Helper function for tsubst_expr.  For decomposition declaration
16569    artificial base DECL, which is tsubsted PATTERN_DECL, tsubst
16570    also the corresponding decls representing the identifiers
16571    of the decomposition declaration.  Return DECL if successful
16572    or error_mark_node otherwise, set *FIRST to the first decl
16573    in the list chained through DECL_CHAIN and *CNT to the number
16574    of such decls.  */
16575 
16576 static tree
tsubst_decomp_names(tree decl,tree pattern_decl,tree args,tsubst_flags_t complain,tree in_decl,tree * first,unsigned int * cnt)16577 tsubst_decomp_names (tree decl, tree pattern_decl, tree args,
16578 		     tsubst_flags_t complain, tree in_decl, tree *first,
16579 		     unsigned int *cnt)
16580 {
16581   tree decl2, decl3, prev = decl;
16582   *cnt = 0;
16583   gcc_assert (DECL_NAME (decl) == NULL_TREE);
16584   for (decl2 = DECL_CHAIN (pattern_decl);
16585        decl2
16586        && VAR_P (decl2)
16587        && DECL_DECOMPOSITION_P (decl2)
16588        && DECL_NAME (decl2);
16589        decl2 = DECL_CHAIN (decl2))
16590     {
16591       if (TREE_TYPE (decl2) == error_mark_node && *cnt == 0)
16592 	{
16593 	  gcc_assert (errorcount);
16594 	  return error_mark_node;
16595 	}
16596       (*cnt)++;
16597       gcc_assert (DECL_DECOMP_BASE (decl2) == pattern_decl);
16598       gcc_assert (DECL_HAS_VALUE_EXPR_P (decl2));
16599       tree v = DECL_VALUE_EXPR (decl2);
16600       DECL_HAS_VALUE_EXPR_P (decl2) = 0;
16601       SET_DECL_VALUE_EXPR (decl2, NULL_TREE);
16602       decl3 = tsubst (decl2, args, complain, in_decl);
16603       SET_DECL_VALUE_EXPR (decl2, v);
16604       DECL_HAS_VALUE_EXPR_P (decl2) = 1;
16605       if (VAR_P (decl3))
16606 	DECL_TEMPLATE_INSTANTIATED (decl3) = 1;
16607       else
16608 	{
16609 	  gcc_assert (errorcount);
16610 	  decl = error_mark_node;
16611 	  continue;
16612 	}
16613       maybe_push_decl (decl3);
16614       if (error_operand_p (decl3))
16615 	decl = error_mark_node;
16616       else if (decl != error_mark_node
16617 	       && DECL_CHAIN (decl3) != prev
16618 	       && decl != prev)
16619 	{
16620 	  gcc_assert (errorcount);
16621 	  decl = error_mark_node;
16622 	}
16623       else
16624 	prev = decl3;
16625     }
16626   *first = prev;
16627   return decl;
16628 }
16629 
16630 /* Like tsubst_copy for expressions, etc. but also does semantic
16631    processing.  */
16632 
16633 tree
tsubst_expr(tree t,tree args,tsubst_flags_t complain,tree in_decl,bool integral_constant_expression_p)16634 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
16635 	     bool integral_constant_expression_p)
16636 {
16637 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
16638 #define RECUR(NODE)				\
16639   tsubst_expr ((NODE), args, complain, in_decl,	\
16640 	       integral_constant_expression_p)
16641 
16642   tree stmt, tmp;
16643   tree r;
16644   location_t loc;
16645 
16646   if (t == NULL_TREE || t == error_mark_node)
16647     return t;
16648 
16649   loc = input_location;
16650   if (EXPR_HAS_LOCATION (t))
16651     input_location = EXPR_LOCATION (t);
16652   if (STATEMENT_CODE_P (TREE_CODE (t)))
16653     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
16654 
16655   switch (TREE_CODE (t))
16656     {
16657     case STATEMENT_LIST:
16658       {
16659 	tree_stmt_iterator i;
16660 	for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
16661 	  RECUR (tsi_stmt (i));
16662 	break;
16663       }
16664 
16665     case CTOR_INITIALIZER:
16666       finish_mem_initializers (tsubst_initializer_list
16667 			       (TREE_OPERAND (t, 0), args));
16668       break;
16669 
16670     case RETURN_EXPR:
16671       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
16672       break;
16673 
16674     case EXPR_STMT:
16675       tmp = RECUR (EXPR_STMT_EXPR (t));
16676       if (EXPR_STMT_STMT_EXPR_RESULT (t))
16677 	finish_stmt_expr_expr (tmp, cur_stmt_expr);
16678       else
16679 	finish_expr_stmt (tmp);
16680       break;
16681 
16682     case USING_STMT:
16683       finish_local_using_directive (USING_STMT_NAMESPACE (t),
16684 				    /*attribs=*/NULL_TREE);
16685       break;
16686 
16687     case DECL_EXPR:
16688       {
16689 	tree decl, pattern_decl;
16690 	tree init;
16691 
16692 	pattern_decl = decl = DECL_EXPR_DECL (t);
16693 	if (TREE_CODE (decl) == LABEL_DECL)
16694 	  finish_label_decl (DECL_NAME (decl));
16695 	else if (TREE_CODE (decl) == USING_DECL)
16696 	  {
16697 	    tree scope = USING_DECL_SCOPE (decl);
16698 	    tree name = DECL_NAME (decl);
16699 
16700 	    scope = tsubst (scope, args, complain, in_decl);
16701 	    decl = lookup_qualified_name (scope, name,
16702 					  /*is_type_p=*/false,
16703 					  /*complain=*/false);
16704 	    if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
16705 	      qualified_name_lookup_error (scope, name, decl, input_location);
16706 	    else
16707 	      finish_local_using_decl (decl, scope, name);
16708 	  }
16709 	else if (is_capture_proxy (decl)
16710 		 && !DECL_TEMPLATE_INSTANTIATION (current_function_decl))
16711 	  {
16712 	    /* We're in tsubst_lambda_expr, we've already inserted a new
16713 	       capture proxy, so look it up and register it.  */
16714 	    tree inst;
16715 	    if (DECL_PACK_P (decl))
16716 	      {
16717 		inst = (retrieve_local_specialization
16718 			(DECL_CAPTURED_VARIABLE (decl)));
16719 		gcc_assert (TREE_CODE (inst) == NONTYPE_ARGUMENT_PACK);
16720 	      }
16721 	    else
16722 	      {
16723 		inst = lookup_name_real (DECL_NAME (decl), 0, 0,
16724 					 /*block_p=*/true, 0, LOOKUP_HIDDEN);
16725 		gcc_assert (inst != decl && is_capture_proxy (inst));
16726 	      }
16727 	    register_local_specialization (inst, decl);
16728 	    break;
16729 	  }
16730 	else if (DECL_IMPLICIT_TYPEDEF_P (decl)
16731 		 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
16732 	  /* Don't copy the old closure; we'll create a new one in
16733 	     tsubst_lambda_expr.  */
16734 	  break;
16735 	else
16736 	  {
16737 	    init = DECL_INITIAL (decl);
16738 	    decl = tsubst (decl, args, complain, in_decl);
16739 	    if (decl != error_mark_node)
16740 	      {
16741 		/* By marking the declaration as instantiated, we avoid
16742 		   trying to instantiate it.  Since instantiate_decl can't
16743 		   handle local variables, and since we've already done
16744 		   all that needs to be done, that's the right thing to
16745 		   do.  */
16746 		if (VAR_P (decl))
16747 		  DECL_TEMPLATE_INSTANTIATED (decl) = 1;
16748 		if (VAR_P (decl) && !DECL_NAME (decl)
16749 		    && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
16750 		  /* Anonymous aggregates are a special case.  */
16751 		  finish_anon_union (decl);
16752 		else if (is_capture_proxy (DECL_EXPR_DECL (t)))
16753 		  {
16754 		    DECL_CONTEXT (decl) = current_function_decl;
16755 		    if (DECL_NAME (decl) == this_identifier)
16756 		      {
16757 			tree lam = DECL_CONTEXT (current_function_decl);
16758 			lam = CLASSTYPE_LAMBDA_EXPR (lam);
16759 			LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
16760 		      }
16761 		    insert_capture_proxy (decl);
16762 		  }
16763 		else if (DECL_IMPLICIT_TYPEDEF_P (t))
16764 		  /* We already did a pushtag.  */;
16765 		else if (TREE_CODE (decl) == FUNCTION_DECL
16766 			 && DECL_OMP_DECLARE_REDUCTION_P (decl)
16767 			 && DECL_FUNCTION_SCOPE_P (pattern_decl))
16768 		  {
16769 		    DECL_CONTEXT (decl) = NULL_TREE;
16770 		    pushdecl (decl);
16771 		    DECL_CONTEXT (decl) = current_function_decl;
16772 		    cp_check_omp_declare_reduction (decl);
16773 		  }
16774 		else
16775 		  {
16776 		    int const_init = false;
16777 		    unsigned int cnt = 0;
16778 		    tree first = NULL_TREE, ndecl = error_mark_node;
16779 		    maybe_push_decl (decl);
16780 
16781 		    if (VAR_P (decl)
16782 			&& DECL_DECOMPOSITION_P (decl)
16783 			&& TREE_TYPE (pattern_decl) != error_mark_node)
16784 		      ndecl = tsubst_decomp_names (decl, pattern_decl, args,
16785 						   complain, in_decl, &first,
16786 						   &cnt);
16787 
16788 		    if (VAR_P (decl)
16789 			&& DECL_PRETTY_FUNCTION_P (decl))
16790 		      {
16791 			/* For __PRETTY_FUNCTION__ we have to adjust the
16792 			   initializer.  */
16793 			const char *const name
16794 			  = cxx_printable_name (current_function_decl, 2);
16795 			init = cp_fname_init (name, &TREE_TYPE (decl));
16796 		      }
16797 		    else
16798 		      init = tsubst_init (init, decl, args, complain, in_decl);
16799 
16800 		    if (VAR_P (decl))
16801 		      const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
16802 				    (pattern_decl));
16803 
16804 		    if (ndecl != error_mark_node)
16805 		      cp_maybe_mangle_decomp (ndecl, first, cnt);
16806 
16807 		    cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
16808 
16809 		    if (ndecl != error_mark_node)
16810 		      cp_finish_decomp (ndecl, first, cnt);
16811 		  }
16812 	      }
16813 	  }
16814 
16815 	break;
16816       }
16817 
16818     case FOR_STMT:
16819       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
16820       RECUR (FOR_INIT_STMT (t));
16821       finish_init_stmt (stmt);
16822       tmp = RECUR (FOR_COND (t));
16823       finish_for_cond (tmp, stmt, false, 0);
16824       tmp = RECUR (FOR_EXPR (t));
16825       finish_for_expr (tmp, stmt);
16826       {
16827 	bool prev = note_iteration_stmt_body_start ();
16828 	RECUR (FOR_BODY (t));
16829 	note_iteration_stmt_body_end (prev);
16830       }
16831       finish_for_stmt (stmt);
16832       break;
16833 
16834     case RANGE_FOR_STMT:
16835       {
16836 	/* Construct another range_for, if this is not a final
16837 	   substitution (for inside inside a generic lambda of a
16838 	   template).  Otherwise convert to a regular for.  */
16839         tree decl, expr;
16840         stmt = (processing_template_decl
16841 		? begin_range_for_stmt (NULL_TREE, NULL_TREE)
16842 		: begin_for_stmt (NULL_TREE, NULL_TREE));
16843         decl = RANGE_FOR_DECL (t);
16844         decl = tsubst (decl, args, complain, in_decl);
16845         maybe_push_decl (decl);
16846         expr = RECUR (RANGE_FOR_EXPR (t));
16847 
16848 	tree decomp_first = NULL_TREE;
16849 	unsigned decomp_cnt = 0;
16850 	if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
16851 	  decl = tsubst_decomp_names (decl, RANGE_FOR_DECL (t), args,
16852 				      complain, in_decl,
16853 				      &decomp_first, &decomp_cnt);
16854 
16855 	if (processing_template_decl)
16856 	  {
16857 	    RANGE_FOR_IVDEP (stmt) = RANGE_FOR_IVDEP (t);
16858 	    RANGE_FOR_UNROLL (stmt) = RANGE_FOR_UNROLL (t);
16859 	    finish_range_for_decl (stmt, decl, expr);
16860 	    if (decomp_first && decl != error_mark_node)
16861 	      cp_finish_decomp (decl, decomp_first, decomp_cnt);
16862 	  }
16863 	else
16864 	  {
16865 	    unsigned short unroll = (RANGE_FOR_UNROLL (t)
16866 				     ? tree_to_uhwi (RANGE_FOR_UNROLL (t)) : 0);
16867 	    stmt = cp_convert_range_for (stmt, decl, expr,
16868 					 decomp_first, decomp_cnt,
16869 					 RANGE_FOR_IVDEP (t), unroll);
16870 	  }
16871 
16872 	bool prev = note_iteration_stmt_body_start ();
16873         RECUR (RANGE_FOR_BODY (t));
16874 	note_iteration_stmt_body_end (prev);
16875         finish_for_stmt (stmt);
16876       }
16877       break;
16878 
16879     case WHILE_STMT:
16880       stmt = begin_while_stmt ();
16881       tmp = RECUR (WHILE_COND (t));
16882       finish_while_stmt_cond (tmp, stmt, false, 0);
16883       {
16884 	bool prev = note_iteration_stmt_body_start ();
16885 	RECUR (WHILE_BODY (t));
16886 	note_iteration_stmt_body_end (prev);
16887       }
16888       finish_while_stmt (stmt);
16889       break;
16890 
16891     case DO_STMT:
16892       stmt = begin_do_stmt ();
16893       {
16894 	bool prev = note_iteration_stmt_body_start ();
16895 	RECUR (DO_BODY (t));
16896 	note_iteration_stmt_body_end (prev);
16897       }
16898       finish_do_body (stmt);
16899       tmp = RECUR (DO_COND (t));
16900       finish_do_stmt (tmp, stmt, false, 0);
16901       break;
16902 
16903     case IF_STMT:
16904       stmt = begin_if_stmt ();
16905       IF_STMT_CONSTEXPR_P (stmt) = IF_STMT_CONSTEXPR_P (t);
16906       if (IF_STMT_CONSTEXPR_P (t))
16907 	args = add_extra_args (IF_STMT_EXTRA_ARGS (t), args);
16908       tmp = RECUR (IF_COND (t));
16909       tmp = finish_if_stmt_cond (tmp, stmt);
16910       if (IF_STMT_CONSTEXPR_P (t)
16911 	  && instantiation_dependent_expression_p (tmp))
16912 	{
16913 	  /* We're partially instantiating a generic lambda, but the condition
16914 	     of the constexpr if is still dependent.  Don't substitute into the
16915 	     branches now, just remember the template arguments.  */
16916 	  do_poplevel (IF_SCOPE (stmt));
16917 	  IF_COND (stmt) = IF_COND (t);
16918 	  THEN_CLAUSE (stmt) = THEN_CLAUSE (t);
16919 	  ELSE_CLAUSE (stmt) = ELSE_CLAUSE (t);
16920 	  IF_STMT_EXTRA_ARGS (stmt) = build_extra_args (t, args, complain);
16921 	  add_stmt (stmt);
16922 	  break;
16923 	}
16924       if (IF_STMT_CONSTEXPR_P (t) && integer_zerop (tmp))
16925 	/* Don't instantiate the THEN_CLAUSE. */;
16926       else
16927 	{
16928 	  bool inhibit = integer_zerop (fold_non_dependent_expr (tmp));
16929 	  if (inhibit)
16930 	    ++c_inhibit_evaluation_warnings;
16931 	  RECUR (THEN_CLAUSE (t));
16932 	  if (inhibit)
16933 	    --c_inhibit_evaluation_warnings;
16934 	}
16935       finish_then_clause (stmt);
16936 
16937       if (IF_STMT_CONSTEXPR_P (t) && integer_nonzerop (tmp))
16938 	/* Don't instantiate the ELSE_CLAUSE. */;
16939       else if (ELSE_CLAUSE (t))
16940 	{
16941 	  bool inhibit = integer_nonzerop (fold_non_dependent_expr (tmp));
16942 	  begin_else_clause (stmt);
16943 	  if (inhibit)
16944 	    ++c_inhibit_evaluation_warnings;
16945 	  RECUR (ELSE_CLAUSE (t));
16946 	  if (inhibit)
16947 	    --c_inhibit_evaluation_warnings;
16948 	  finish_else_clause (stmt);
16949 	}
16950 
16951       finish_if_stmt (stmt);
16952       break;
16953 
16954     case BIND_EXPR:
16955       if (BIND_EXPR_BODY_BLOCK (t))
16956 	stmt = begin_function_body ();
16957       else
16958 	stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
16959 				    ? BCS_TRY_BLOCK : 0);
16960 
16961       RECUR (BIND_EXPR_BODY (t));
16962 
16963       if (BIND_EXPR_BODY_BLOCK (t))
16964 	finish_function_body (stmt);
16965       else
16966 	finish_compound_stmt (stmt);
16967       break;
16968 
16969     case BREAK_STMT:
16970       finish_break_stmt ();
16971       break;
16972 
16973     case CONTINUE_STMT:
16974       finish_continue_stmt ();
16975       break;
16976 
16977     case SWITCH_STMT:
16978       stmt = begin_switch_stmt ();
16979       tmp = RECUR (SWITCH_STMT_COND (t));
16980       finish_switch_cond (tmp, stmt);
16981       RECUR (SWITCH_STMT_BODY (t));
16982       finish_switch_stmt (stmt);
16983       break;
16984 
16985     case CASE_LABEL_EXPR:
16986       {
16987 	tree low = RECUR (CASE_LOW (t));
16988 	tree high = RECUR (CASE_HIGH (t));
16989 	tree l = finish_case_label (EXPR_LOCATION (t), low, high);
16990 	if (l && TREE_CODE (l) == CASE_LABEL_EXPR)
16991 	  FALLTHROUGH_LABEL_P (CASE_LABEL (l))
16992 	    = FALLTHROUGH_LABEL_P (CASE_LABEL (t));
16993       }
16994       break;
16995 
16996     case LABEL_EXPR:
16997       {
16998 	tree decl = LABEL_EXPR_LABEL (t);
16999 	tree label;
17000 
17001 	label = finish_label_stmt (DECL_NAME (decl));
17002 	if (TREE_CODE (label) == LABEL_DECL)
17003 	  FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
17004 	if (DECL_ATTRIBUTES (decl) != NULL_TREE)
17005 	  cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
17006       }
17007       break;
17008 
17009     case GOTO_EXPR:
17010       tmp = GOTO_DESTINATION (t);
17011       if (TREE_CODE (tmp) != LABEL_DECL)
17012 	/* Computed goto's must be tsubst'd into.  On the other hand,
17013 	   non-computed gotos must not be; the identifier in question
17014 	   will have no binding.  */
17015 	tmp = RECUR (tmp);
17016       else
17017 	tmp = DECL_NAME (tmp);
17018       finish_goto_stmt (tmp);
17019       break;
17020 
17021     case ASM_EXPR:
17022       {
17023 	tree string = RECUR (ASM_STRING (t));
17024 	tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
17025 						 complain, in_decl);
17026 	tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
17027 						complain, in_decl);
17028 	tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
17029 	 					  complain, in_decl);
17030 	tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
17031 						complain, in_decl);
17032 	tmp = finish_asm_stmt (ASM_VOLATILE_P (t), string, outputs, inputs,
17033 			       clobbers, labels, ASM_INLINE_P (t));
17034 	tree asm_expr = tmp;
17035 	if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
17036 	  asm_expr = TREE_OPERAND (asm_expr, 0);
17037 	ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
17038       }
17039       break;
17040 
17041     case TRY_BLOCK:
17042       if (CLEANUP_P (t))
17043 	{
17044 	  stmt = begin_try_block ();
17045 	  RECUR (TRY_STMTS (t));
17046 	  finish_cleanup_try_block (stmt);
17047 	  finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
17048 	}
17049       else
17050 	{
17051 	  tree compound_stmt = NULL_TREE;
17052 
17053 	  if (FN_TRY_BLOCK_P (t))
17054 	    stmt = begin_function_try_block (&compound_stmt);
17055 	  else
17056 	    stmt = begin_try_block ();
17057 
17058 	  RECUR (TRY_STMTS (t));
17059 
17060 	  if (FN_TRY_BLOCK_P (t))
17061 	    finish_function_try_block (stmt);
17062 	  else
17063 	    finish_try_block (stmt);
17064 
17065 	  RECUR (TRY_HANDLERS (t));
17066 	  if (FN_TRY_BLOCK_P (t))
17067 	    finish_function_handler_sequence (stmt, compound_stmt);
17068 	  else
17069 	    finish_handler_sequence (stmt);
17070 	}
17071       break;
17072 
17073     case HANDLER:
17074       {
17075 	tree decl = HANDLER_PARMS (t);
17076 
17077 	if (decl)
17078 	  {
17079 	    decl = tsubst (decl, args, complain, in_decl);
17080 	    /* Prevent instantiate_decl from trying to instantiate
17081 	       this variable.  We've already done all that needs to be
17082 	       done.  */
17083 	    if (decl != error_mark_node)
17084 	      DECL_TEMPLATE_INSTANTIATED (decl) = 1;
17085 	  }
17086 	stmt = begin_handler ();
17087 	finish_handler_parms (decl, stmt);
17088 	RECUR (HANDLER_BODY (t));
17089 	finish_handler (stmt);
17090       }
17091       break;
17092 
17093     case TAG_DEFN:
17094       tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
17095       if (CLASS_TYPE_P (tmp))
17096 	{
17097 	  /* Local classes are not independent templates; they are
17098 	     instantiated along with their containing function.  And this
17099 	     way we don't have to deal with pushing out of one local class
17100 	     to instantiate a member of another local class.  */
17101 	  /* Closures are handled by the LAMBDA_EXPR.  */
17102 	  gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
17103 	  complete_type (tmp);
17104 	  for (tree fld = TYPE_FIELDS (tmp); fld; fld = DECL_CHAIN (fld))
17105 	    if ((VAR_P (fld)
17106 		 || (TREE_CODE (fld) == FUNCTION_DECL
17107 		     && !DECL_ARTIFICIAL (fld)))
17108 		&& DECL_TEMPLATE_INSTANTIATION (fld))
17109 	      instantiate_decl (fld, /*defer_ok=*/false,
17110 				/*expl_inst_class=*/false);
17111 	}
17112       break;
17113 
17114     case STATIC_ASSERT:
17115       {
17116 	tree condition;
17117 
17118 	++c_inhibit_evaluation_warnings;
17119         condition =
17120           tsubst_expr (STATIC_ASSERT_CONDITION (t),
17121                        args,
17122                        complain, in_decl,
17123                        /*integral_constant_expression_p=*/true);
17124 	--c_inhibit_evaluation_warnings;
17125 
17126         finish_static_assert (condition,
17127                               STATIC_ASSERT_MESSAGE (t),
17128                               STATIC_ASSERT_SOURCE_LOCATION (t),
17129                               /*member_p=*/false);
17130       }
17131       break;
17132 
17133     case OACC_KERNELS:
17134     case OACC_PARALLEL:
17135       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_ACC, args, complain,
17136 				in_decl);
17137       stmt = begin_omp_parallel ();
17138       RECUR (OMP_BODY (t));
17139       finish_omp_construct (TREE_CODE (t), stmt, tmp);
17140       break;
17141 
17142     case OMP_PARALLEL:
17143       r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
17144       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), C_ORT_OMP, args,
17145 				complain, in_decl);
17146       if (OMP_PARALLEL_COMBINED (t))
17147 	omp_parallel_combined_clauses = &tmp;
17148       stmt = begin_omp_parallel ();
17149       RECUR (OMP_PARALLEL_BODY (t));
17150       gcc_assert (omp_parallel_combined_clauses == NULL);
17151       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
17152 	= OMP_PARALLEL_COMBINED (t);
17153       pop_omp_privatization_clauses (r);
17154       break;
17155 
17156     case OMP_TASK:
17157       r = push_omp_privatization_clauses (false);
17158       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
17159 				complain, in_decl);
17160       stmt = begin_omp_task ();
17161       RECUR (OMP_TASK_BODY (t));
17162       finish_omp_task (tmp, stmt);
17163       pop_omp_privatization_clauses (r);
17164       break;
17165 
17166     case OMP_FOR:
17167     case OMP_SIMD:
17168     case OMP_DISTRIBUTE:
17169     case OMP_TASKLOOP:
17170     case OACC_LOOP:
17171       {
17172 	tree clauses, body, pre_body;
17173 	tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
17174 	tree orig_declv = NULL_TREE;
17175 	tree incrv = NULL_TREE;
17176 	enum c_omp_region_type ort = C_ORT_OMP;
17177 	int i;
17178 
17179 	if (TREE_CODE (t) == OACC_LOOP)
17180 	  ort = C_ORT_ACC;
17181 
17182 	r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
17183 	clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), ort, args, complain,
17184 				      in_decl);
17185 	if (OMP_FOR_INIT (t) != NULL_TREE)
17186 	  {
17187 	    declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17188 	    if (OMP_FOR_ORIG_DECLS (t))
17189 	      orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17190 	    initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17191 	    condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17192 	    incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17193 	  }
17194 
17195 	stmt = begin_omp_structured_block ();
17196 
17197 	pre_body = push_stmt_list ();
17198 	RECUR (OMP_FOR_PRE_BODY (t));
17199 	pre_body = pop_stmt_list (pre_body);
17200 
17201 	if (OMP_FOR_INIT (t) != NULL_TREE)
17202 	  for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
17203 	    tsubst_omp_for_iterator (t, i, declv, orig_declv, initv, condv,
17204 				     incrv, &clauses, args, complain, in_decl,
17205 				     integral_constant_expression_p);
17206 	omp_parallel_combined_clauses = NULL;
17207 
17208 	body = push_stmt_list ();
17209 	RECUR (OMP_FOR_BODY (t));
17210 	body = pop_stmt_list (body);
17211 
17212 	if (OMP_FOR_INIT (t) != NULL_TREE)
17213 	  t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
17214 			      orig_declv, initv, condv, incrv, body, pre_body,
17215 			      NULL, clauses);
17216 	else
17217 	  {
17218 	    t = make_node (TREE_CODE (t));
17219 	    TREE_TYPE (t) = void_type_node;
17220 	    OMP_FOR_BODY (t) = body;
17221 	    OMP_FOR_PRE_BODY (t) = pre_body;
17222 	    OMP_FOR_CLAUSES (t) = clauses;
17223 	    SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
17224 	    add_stmt (t);
17225 	  }
17226 
17227 	add_stmt (finish_omp_structured_block (stmt));
17228 	pop_omp_privatization_clauses (r);
17229       }
17230       break;
17231 
17232     case OMP_SECTIONS:
17233       omp_parallel_combined_clauses = NULL;
17234       /* FALLTHRU */
17235     case OMP_SINGLE:
17236     case OMP_TEAMS:
17237     case OMP_CRITICAL:
17238       r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
17239 					  && OMP_TEAMS_COMBINED (t));
17240       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_OMP, args, complain,
17241 				in_decl);
17242       stmt = push_stmt_list ();
17243       RECUR (OMP_BODY (t));
17244       stmt = pop_stmt_list (stmt);
17245 
17246       t = copy_node (t);
17247       OMP_BODY (t) = stmt;
17248       OMP_CLAUSES (t) = tmp;
17249       add_stmt (t);
17250       pop_omp_privatization_clauses (r);
17251       break;
17252 
17253     case OACC_DATA:
17254     case OMP_TARGET_DATA:
17255     case OMP_TARGET:
17256       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), (TREE_CODE (t) == OACC_DATA)
17257 				? C_ORT_ACC : C_ORT_OMP, args, complain,
17258 				in_decl);
17259       keep_next_level (true);
17260       stmt = begin_omp_structured_block ();
17261 
17262       RECUR (OMP_BODY (t));
17263       stmt = finish_omp_structured_block (stmt);
17264 
17265       t = copy_node (t);
17266       OMP_BODY (t) = stmt;
17267       OMP_CLAUSES (t) = tmp;
17268       if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
17269 	{
17270 	  tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
17271 	  if (teams)
17272 	    {
17273 	      /* For combined target teams, ensure the num_teams and
17274 		 thread_limit clause expressions are evaluated on the host,
17275 		 before entering the target construct.  */
17276 	      tree c;
17277 	      for (c = OMP_TEAMS_CLAUSES (teams);
17278 		   c; c = OMP_CLAUSE_CHAIN (c))
17279 		if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
17280 		     || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
17281 		    && TREE_CODE (OMP_CLAUSE_OPERAND (c, 0)) != INTEGER_CST)
17282 		  {
17283 		    tree expr = OMP_CLAUSE_OPERAND (c, 0);
17284 		    expr = force_target_expr (TREE_TYPE (expr), expr, tf_none);
17285 		    if (expr == error_mark_node)
17286 		      continue;
17287 		    tmp = TARGET_EXPR_SLOT (expr);
17288 		    add_stmt (expr);
17289 		    OMP_CLAUSE_OPERAND (c, 0) = expr;
17290 		    tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
17291 						OMP_CLAUSE_FIRSTPRIVATE);
17292 		    OMP_CLAUSE_DECL (tc) = tmp;
17293 		    OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
17294 		    OMP_TARGET_CLAUSES (t) = tc;
17295 		  }
17296 	    }
17297 	}
17298       add_stmt (t);
17299       break;
17300 
17301     case OACC_DECLARE:
17302       t = copy_node (t);
17303       tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), C_ORT_ACC, args,
17304 				complain, in_decl);
17305       OACC_DECLARE_CLAUSES (t) = tmp;
17306       add_stmt (t);
17307       break;
17308 
17309     case OMP_TARGET_UPDATE:
17310     case OMP_TARGET_ENTER_DATA:
17311     case OMP_TARGET_EXIT_DATA:
17312       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_OMP, args,
17313 				complain, in_decl);
17314       t = copy_node (t);
17315       OMP_STANDALONE_CLAUSES (t) = tmp;
17316       add_stmt (t);
17317       break;
17318 
17319     case OACC_ENTER_DATA:
17320     case OACC_EXIT_DATA:
17321     case OACC_UPDATE:
17322       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_ACC, args,
17323 				complain, in_decl);
17324       t = copy_node (t);
17325       OMP_STANDALONE_CLAUSES (t) = tmp;
17326       add_stmt (t);
17327       break;
17328 
17329     case OMP_ORDERED:
17330       tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), C_ORT_OMP, args,
17331 				complain, in_decl);
17332       stmt = push_stmt_list ();
17333       RECUR (OMP_BODY (t));
17334       stmt = pop_stmt_list (stmt);
17335 
17336       t = copy_node (t);
17337       OMP_BODY (t) = stmt;
17338       OMP_ORDERED_CLAUSES (t) = tmp;
17339       add_stmt (t);
17340       break;
17341 
17342     case OMP_SECTION:
17343     case OMP_MASTER:
17344     case OMP_TASKGROUP:
17345       stmt = push_stmt_list ();
17346       RECUR (OMP_BODY (t));
17347       stmt = pop_stmt_list (stmt);
17348 
17349       t = copy_node (t);
17350       OMP_BODY (t) = stmt;
17351       add_stmt (t);
17352       break;
17353 
17354     case OMP_ATOMIC:
17355       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
17356       if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
17357 	{
17358 	  tree op1 = TREE_OPERAND (t, 1);
17359 	  tree rhs1 = NULL_TREE;
17360 	  tree lhs, rhs;
17361 	  if (TREE_CODE (op1) == COMPOUND_EXPR)
17362 	    {
17363 	      rhs1 = RECUR (TREE_OPERAND (op1, 0));
17364 	      op1 = TREE_OPERAND (op1, 1);
17365 	    }
17366 	  lhs = RECUR (TREE_OPERAND (op1, 0));
17367 	  rhs = RECUR (TREE_OPERAND (op1, 1));
17368 	  finish_omp_atomic (OMP_ATOMIC, TREE_CODE (op1), lhs, rhs,
17369 			     NULL_TREE, NULL_TREE, rhs1,
17370 			     OMP_ATOMIC_SEQ_CST (t));
17371 	}
17372       else
17373 	{
17374 	  tree op1 = TREE_OPERAND (t, 1);
17375 	  tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
17376 	  tree rhs1 = NULL_TREE;
17377 	  enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
17378 	  enum tree_code opcode = NOP_EXPR;
17379 	  if (code == OMP_ATOMIC_READ)
17380 	    {
17381 	      v = RECUR (TREE_OPERAND (op1, 0));
17382 	      lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
17383 	    }
17384 	  else if (code == OMP_ATOMIC_CAPTURE_OLD
17385 		   || code == OMP_ATOMIC_CAPTURE_NEW)
17386 	    {
17387 	      tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
17388 	      v = RECUR (TREE_OPERAND (op1, 0));
17389 	      lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
17390 	      if (TREE_CODE (op11) == COMPOUND_EXPR)
17391 		{
17392 		  rhs1 = RECUR (TREE_OPERAND (op11, 0));
17393 		  op11 = TREE_OPERAND (op11, 1);
17394 		}
17395 	      lhs = RECUR (TREE_OPERAND (op11, 0));
17396 	      rhs = RECUR (TREE_OPERAND (op11, 1));
17397 	      opcode = TREE_CODE (op11);
17398 	      if (opcode == MODIFY_EXPR)
17399 		opcode = NOP_EXPR;
17400 	    }
17401 	  else
17402 	    {
17403 	      code = OMP_ATOMIC;
17404 	      lhs = RECUR (TREE_OPERAND (op1, 0));
17405 	      rhs = RECUR (TREE_OPERAND (op1, 1));
17406 	    }
17407 	  finish_omp_atomic (code, opcode, lhs, rhs, v, lhs1, rhs1,
17408 			     OMP_ATOMIC_SEQ_CST (t));
17409 	}
17410       break;
17411 
17412     case TRANSACTION_EXPR:
17413       {
17414 	int flags = 0;
17415 	flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
17416 	flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
17417 
17418         if (TRANSACTION_EXPR_IS_STMT (t))
17419           {
17420 	    tree body = TRANSACTION_EXPR_BODY (t);
17421 	    tree noex = NULL_TREE;
17422 	    if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
17423 	      {
17424 		noex = MUST_NOT_THROW_COND (body);
17425 		if (noex == NULL_TREE)
17426 		  noex = boolean_true_node;
17427 		body = TREE_OPERAND (body, 0);
17428 	      }
17429             stmt = begin_transaction_stmt (input_location, NULL, flags);
17430             RECUR (body);
17431             finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
17432           }
17433         else
17434           {
17435             stmt = build_transaction_expr (EXPR_LOCATION (t),
17436 					   RECUR (TRANSACTION_EXPR_BODY (t)),
17437 					   flags, NULL_TREE);
17438             RETURN (stmt);
17439           }
17440       }
17441       break;
17442 
17443     case MUST_NOT_THROW_EXPR:
17444       {
17445 	tree op0 = RECUR (TREE_OPERAND (t, 0));
17446 	tree cond = RECUR (MUST_NOT_THROW_COND (t));
17447 	RETURN (build_must_not_throw_expr (op0, cond));
17448       }
17449 
17450     case EXPR_PACK_EXPANSION:
17451       error ("invalid use of pack expansion expression");
17452       RETURN (error_mark_node);
17453 
17454     case NONTYPE_ARGUMENT_PACK:
17455       error ("use %<...%> to expand argument pack");
17456       RETURN (error_mark_node);
17457 
17458     case COMPOUND_EXPR:
17459       tmp = RECUR (TREE_OPERAND (t, 0));
17460       if (tmp == NULL_TREE)
17461 	/* If the first operand was a statement, we're done with it.  */
17462 	RETURN (RECUR (TREE_OPERAND (t, 1)));
17463       RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
17464 				    RECUR (TREE_OPERAND (t, 1)),
17465 				    complain));
17466 
17467     case ANNOTATE_EXPR:
17468       tmp = RECUR (TREE_OPERAND (t, 0));
17469       RETURN (build3_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
17470 			  TREE_TYPE (tmp), tmp,
17471 			  RECUR (TREE_OPERAND (t, 1)),
17472 			  RECUR (TREE_OPERAND (t, 2))));
17473 
17474     default:
17475       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
17476 
17477       RETURN (tsubst_copy_and_build (t, args, complain, in_decl,
17478 				    /*function_p=*/false,
17479 				    integral_constant_expression_p));
17480     }
17481 
17482   RETURN (NULL_TREE);
17483  out:
17484   input_location = loc;
17485   return r;
17486 #undef RECUR
17487 #undef RETURN
17488 }
17489 
17490 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
17491    function.  For description of the body see comment above
17492    cp_parser_omp_declare_reduction_exprs.  */
17493 
17494 static void
tsubst_omp_udr(tree t,tree args,tsubst_flags_t complain,tree in_decl)17495 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
17496 {
17497   if (t == NULL_TREE || t == error_mark_node)
17498     return;
17499 
17500   gcc_assert (TREE_CODE (t) == STATEMENT_LIST);
17501 
17502   tree_stmt_iterator tsi;
17503   int i;
17504   tree stmts[7];
17505   memset (stmts, 0, sizeof stmts);
17506   for (i = 0, tsi = tsi_start (t);
17507        i < 7 && !tsi_end_p (tsi);
17508        i++, tsi_next (&tsi))
17509     stmts[i] = tsi_stmt (tsi);
17510   gcc_assert (tsi_end_p (tsi));
17511 
17512   if (i >= 3)
17513     {
17514       gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
17515 		  && TREE_CODE (stmts[1]) == DECL_EXPR);
17516       tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
17517 			     args, complain, in_decl);
17518       tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
17519 			    args, complain, in_decl);
17520       DECL_CONTEXT (omp_out) = current_function_decl;
17521       DECL_CONTEXT (omp_in) = current_function_decl;
17522       keep_next_level (true);
17523       tree block = begin_omp_structured_block ();
17524       tsubst_expr (stmts[2], args, complain, in_decl, false);
17525       block = finish_omp_structured_block (block);
17526       block = maybe_cleanup_point_expr_void (block);
17527       add_decl_expr (omp_out);
17528       if (TREE_NO_WARNING (DECL_EXPR_DECL (stmts[0])))
17529 	TREE_NO_WARNING (omp_out) = 1;
17530       add_decl_expr (omp_in);
17531       finish_expr_stmt (block);
17532     }
17533   if (i >= 6)
17534     {
17535       gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
17536 		  && TREE_CODE (stmts[4]) == DECL_EXPR);
17537       tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
17538 			      args, complain, in_decl);
17539       tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
17540 			      args, complain, in_decl);
17541       DECL_CONTEXT (omp_priv) = current_function_decl;
17542       DECL_CONTEXT (omp_orig) = current_function_decl;
17543       keep_next_level (true);
17544       tree block = begin_omp_structured_block ();
17545       tsubst_expr (stmts[5], args, complain, in_decl, false);
17546       block = finish_omp_structured_block (block);
17547       block = maybe_cleanup_point_expr_void (block);
17548       cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
17549       add_decl_expr (omp_priv);
17550       add_decl_expr (omp_orig);
17551       finish_expr_stmt (block);
17552       if (i == 7)
17553 	add_decl_expr (omp_orig);
17554     }
17555 }
17556 
17557 /* T is a postfix-expression that is not being used in a function
17558    call.  Return the substituted version of T.  */
17559 
17560 static tree
tsubst_non_call_postfix_expression(tree t,tree args,tsubst_flags_t complain,tree in_decl)17561 tsubst_non_call_postfix_expression (tree t, tree args,
17562 				    tsubst_flags_t complain,
17563 				    tree in_decl)
17564 {
17565   if (TREE_CODE (t) == SCOPE_REF)
17566     t = tsubst_qualified_id (t, args, complain, in_decl,
17567 			     /*done=*/false, /*address_p=*/false);
17568   else
17569     t = tsubst_copy_and_build (t, args, complain, in_decl,
17570 			       /*function_p=*/false,
17571 			       /*integral_constant_expression_p=*/false);
17572 
17573   return t;
17574 }
17575 
17576 /* T is a LAMBDA_EXPR.  Generate a new LAMBDA_EXPR for the current
17577    instantiation context.  Instantiating a pack expansion containing a lambda
17578    might result in multiple lambdas all based on the same lambda in the
17579    template.  */
17580 
17581 tree
tsubst_lambda_expr(tree t,tree args,tsubst_flags_t complain,tree in_decl)17582 tsubst_lambda_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
17583 {
17584   tree oldfn = lambda_function (t);
17585   in_decl = oldfn;
17586 
17587   tree r = build_lambda_expr ();
17588 
17589   LAMBDA_EXPR_LOCATION (r)
17590     = LAMBDA_EXPR_LOCATION (t);
17591   LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
17592     = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
17593   LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
17594 
17595   if (LAMBDA_EXPR_EXTRA_SCOPE (t) == NULL_TREE)
17596     /* A lambda in a default argument outside a class gets no
17597        LAMBDA_EXPR_EXTRA_SCOPE, as specified by the ABI.  But
17598        tsubst_default_argument calls start_lambda_scope, so we need to
17599        specifically ignore it here, and use the global scope.  */
17600     record_null_lambda_scope (r);
17601   else
17602     record_lambda_scope (r);
17603 
17604   gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
17605 	      && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
17606 
17607   for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t); cap;
17608        cap = TREE_CHAIN (cap))
17609     {
17610       tree field = TREE_PURPOSE (cap);
17611       if (PACK_EXPANSION_P (field))
17612 	field = PACK_EXPANSION_PATTERN (field);
17613       field = tsubst_decl (field, args, complain);
17614 
17615       if (field == error_mark_node)
17616 	return error_mark_node;
17617 
17618       tree init = TREE_VALUE (cap);
17619       if (PACK_EXPANSION_P (init))
17620 	init = tsubst_pack_expansion (init, args, complain, in_decl);
17621       else
17622 	init = tsubst_copy_and_build (init, args, complain, in_decl,
17623 				      /*fn*/false, /*constexpr*/false);
17624 
17625       if (TREE_CODE (field) == TREE_VEC)
17626 	{
17627 	  int len = TREE_VEC_LENGTH (field);
17628 	  gcc_assert (TREE_CODE (init) == TREE_VEC
17629 		      && TREE_VEC_LENGTH (init) == len);
17630 	  for (int i = 0; i < len; ++i)
17631 	    LAMBDA_EXPR_CAPTURE_LIST (r)
17632 	      = tree_cons (TREE_VEC_ELT (field, i),
17633 			   TREE_VEC_ELT (init, i),
17634 			   LAMBDA_EXPR_CAPTURE_LIST (r));
17635 	}
17636       else
17637 	{
17638 	  LAMBDA_EXPR_CAPTURE_LIST (r)
17639 	    = tree_cons (field, init, LAMBDA_EXPR_CAPTURE_LIST (r));
17640 
17641 	  if (id_equal (DECL_NAME (field), "__this"))
17642 	    LAMBDA_EXPR_THIS_CAPTURE (r) = field;
17643 	}
17644     }
17645 
17646   tree type = begin_lambda_type (r);
17647   if (type == error_mark_node)
17648     return error_mark_node;
17649 
17650   /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
17651   determine_visibility (TYPE_NAME (type));
17652 
17653   register_capture_members (LAMBDA_EXPR_CAPTURE_LIST (r));
17654 
17655   tree oldtmpl = (generic_lambda_fn_p (oldfn)
17656 		  ? DECL_TI_TEMPLATE (oldfn)
17657 		  : NULL_TREE);
17658 
17659   tree fntype = static_fn_type (oldfn);
17660   if (oldtmpl)
17661     ++processing_template_decl;
17662   fntype = tsubst (fntype, args, complain, in_decl);
17663   if (oldtmpl)
17664     --processing_template_decl;
17665 
17666   if (fntype == error_mark_node)
17667     r = error_mark_node;
17668   else
17669     {
17670       /* Fix the type of 'this'.  */
17671       fntype = build_memfn_type (fntype, type,
17672 				 type_memfn_quals (fntype),
17673 				 type_memfn_rqual (fntype));
17674       tree fn, tmpl;
17675       if (oldtmpl)
17676 	{
17677 	  tmpl = tsubst_template_decl (oldtmpl, args, complain, fntype);
17678 	  fn = DECL_TEMPLATE_RESULT (tmpl);
17679 	  finish_member_declaration (tmpl);
17680 	}
17681       else
17682 	{
17683 	  tmpl = NULL_TREE;
17684 	  fn = tsubst_function_decl (oldfn, args, complain, fntype);
17685 	  finish_member_declaration (fn);
17686 	}
17687 
17688       /* Let finish_function set this.  */
17689       DECL_DECLARED_CONSTEXPR_P (fn) = false;
17690 
17691       bool nested = cfun;
17692       if (nested)
17693 	push_function_context ();
17694       else
17695 	/* Still increment function_depth so that we don't GC in the
17696 	   middle of an expression.  */
17697 	++function_depth;
17698 
17699       local_specialization_stack s (lss_copy);
17700 
17701       tree body = start_lambda_function (fn, r);
17702 
17703       register_parameter_specializations (oldfn, fn);
17704 
17705       if (oldtmpl)
17706 	{
17707 	  /* We might not partially instantiate some parts of the function, so
17708 	     copy these flags from the original template.  */
17709 	  language_function *ol = DECL_STRUCT_FUNCTION (oldfn)->language;
17710 	  current_function_returns_value = ol->returns_value;
17711 	  current_function_returns_null = ol->returns_null;
17712 	  current_function_returns_abnormally = ol->returns_abnormally;
17713 	  current_function_infinite_loop = ol->infinite_loop;
17714 	}
17715 
17716       tsubst_expr (DECL_SAVED_TREE (oldfn), args, complain, r,
17717 		   /*constexpr*/false);
17718 
17719       finish_lambda_function (body);
17720 
17721       if (nested)
17722 	pop_function_context ();
17723       else
17724 	--function_depth;
17725 
17726       /* The capture list was built up in reverse order; fix that now.  */
17727       LAMBDA_EXPR_CAPTURE_LIST (r)
17728 	= nreverse (LAMBDA_EXPR_CAPTURE_LIST (r));
17729 
17730       LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
17731 
17732       maybe_add_lambda_conv_op (type);
17733     }
17734 
17735   finish_struct (type, /*attr*/NULL_TREE);
17736 
17737   insert_pending_capture_proxies ();
17738 
17739   return r;
17740 }
17741 
17742 /* Like tsubst but deals with expressions and performs semantic
17743    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
17744 
17745 tree
tsubst_copy_and_build(tree t,tree args,tsubst_flags_t complain,tree in_decl,bool function_p,bool integral_constant_expression_p)17746 tsubst_copy_and_build (tree t,
17747 		       tree args,
17748 		       tsubst_flags_t complain,
17749 		       tree in_decl,
17750 		       bool function_p,
17751 		       bool integral_constant_expression_p)
17752 {
17753 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
17754 #define RECUR(NODE)						\
17755   tsubst_copy_and_build (NODE, args, complain, in_decl, 	\
17756 			 /*function_p=*/false,			\
17757 			 integral_constant_expression_p)
17758 
17759   tree retval, op1;
17760   location_t loc;
17761 
17762   if (t == NULL_TREE || t == error_mark_node)
17763     return t;
17764 
17765   loc = input_location;
17766   if (EXPR_HAS_LOCATION (t))
17767     input_location = EXPR_LOCATION (t);
17768 
17769   /* N3276 decltype magic only applies to calls at the top level or on the
17770      right side of a comma.  */
17771   tsubst_flags_t decltype_flag = (complain & tf_decltype);
17772   complain &= ~tf_decltype;
17773 
17774   switch (TREE_CODE (t))
17775     {
17776     case USING_DECL:
17777       t = DECL_NAME (t);
17778       /* Fall through.  */
17779     case IDENTIFIER_NODE:
17780       {
17781 	tree decl;
17782 	cp_id_kind idk;
17783 	bool non_integral_constant_expression_p;
17784 	const char *error_msg;
17785 
17786 	if (IDENTIFIER_CONV_OP_P (t))
17787 	  {
17788 	    tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17789 	    t = make_conv_op_name (new_type);
17790 	  }
17791 
17792 	/* Look up the name.  */
17793 	decl = lookup_name (t);
17794 
17795 	/* By convention, expressions use ERROR_MARK_NODE to indicate
17796 	   failure, not NULL_TREE.  */
17797 	if (decl == NULL_TREE)
17798 	  decl = error_mark_node;
17799 
17800 	decl = finish_id_expression (t, decl, NULL_TREE,
17801 				     &idk,
17802 				     integral_constant_expression_p,
17803           /*allow_non_integral_constant_expression_p=*/(cxx_dialect >= cxx11),
17804 				     &non_integral_constant_expression_p,
17805 				     /*template_p=*/false,
17806 				     /*done=*/true,
17807 				     /*address_p=*/false,
17808 				     /*template_arg_p=*/false,
17809 				     &error_msg,
17810 				     input_location);
17811 	if (error_msg)
17812 	  error (error_msg);
17813 	if (!function_p && identifier_p (decl))
17814 	  {
17815 	    if (complain & tf_error)
17816 	      unqualified_name_lookup_error (decl);
17817 	    decl = error_mark_node;
17818 	  }
17819 	RETURN (decl);
17820       }
17821 
17822     case TEMPLATE_ID_EXPR:
17823       {
17824 	tree object;
17825 	tree templ = RECUR (TREE_OPERAND (t, 0));
17826 	tree targs = TREE_OPERAND (t, 1);
17827 
17828 	if (targs)
17829 	  targs = tsubst_template_args (targs, args, complain, in_decl);
17830 	if (targs == error_mark_node)
17831 	  RETURN (error_mark_node);
17832 
17833 	if (TREE_CODE (templ) == SCOPE_REF)
17834 	  {
17835 	    tree name = TREE_OPERAND (templ, 1);
17836 	    tree tid = lookup_template_function (name, targs);
17837 	    TREE_OPERAND (templ, 1) = tid;
17838 	    RETURN (templ);
17839 	  }
17840 
17841 	if (variable_template_p (templ))
17842 	  RETURN (lookup_and_finish_template_variable (templ, targs, complain));
17843 
17844 	if (TREE_CODE (templ) == COMPONENT_REF)
17845 	  {
17846 	    object = TREE_OPERAND (templ, 0);
17847 	    templ = TREE_OPERAND (templ, 1);
17848 	  }
17849 	else
17850 	  object = NULL_TREE;
17851 	templ = lookup_template_function (templ, targs);
17852 
17853 	if (object)
17854 	  RETURN (build3 (COMPONENT_REF, TREE_TYPE (templ),
17855 			 object, templ, NULL_TREE));
17856 	else
17857 	  RETURN (baselink_for_fns (templ));
17858       }
17859 
17860     case INDIRECT_REF:
17861       {
17862 	tree r = RECUR (TREE_OPERAND (t, 0));
17863 
17864 	if (REFERENCE_REF_P (t))
17865 	  {
17866 	    /* A type conversion to reference type will be enclosed in
17867 	       such an indirect ref, but the substitution of the cast
17868 	       will have also added such an indirect ref.  */
17869 	    r = convert_from_reference (r);
17870 	  }
17871 	else
17872 	  r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
17873 				    complain|decltype_flag);
17874 
17875 	if (REF_PARENTHESIZED_P (t))
17876 	  r = force_paren_expr (r);
17877 
17878 	RETURN (r);
17879       }
17880 
17881     case NOP_EXPR:
17882       {
17883 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17884 	tree op0 = RECUR (TREE_OPERAND (t, 0));
17885 	RETURN (build_nop (type, op0));
17886       }
17887 
17888     case IMPLICIT_CONV_EXPR:
17889       {
17890 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17891 	tree expr = RECUR (TREE_OPERAND (t, 0));
17892 	if (dependent_type_p (type) || type_dependent_expression_p (expr))
17893 	  {
17894 	    retval = copy_node (t);
17895 	    TREE_TYPE (retval) = type;
17896 	    TREE_OPERAND (retval, 0) = expr;
17897 	    RETURN (retval);
17898 	  }
17899 	if (IMPLICIT_CONV_EXPR_NONTYPE_ARG (t))
17900 	  /* We'll pass this to convert_nontype_argument again, we don't need
17901 	     to actually perform any conversion here.  */
17902 	  RETURN (expr);
17903 	int flags = LOOKUP_IMPLICIT;
17904 	if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
17905 	  flags = LOOKUP_NORMAL;
17906 	RETURN (perform_implicit_conversion_flags (type, expr, complain,
17907 						  flags));
17908       }
17909 
17910     case CONVERT_EXPR:
17911       {
17912 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17913 	tree op0 = RECUR (TREE_OPERAND (t, 0));
17914 	if (op0 == error_mark_node)
17915 	  RETURN (error_mark_node);
17916 	RETURN (build1 (CONVERT_EXPR, type, op0));
17917       }
17918 
17919     case CAST_EXPR:
17920     case REINTERPRET_CAST_EXPR:
17921     case CONST_CAST_EXPR:
17922     case DYNAMIC_CAST_EXPR:
17923     case STATIC_CAST_EXPR:
17924       {
17925 	tree type;
17926 	tree op, r = NULL_TREE;
17927 
17928 	type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17929 	if (integral_constant_expression_p
17930 	    && !cast_valid_in_integral_constant_expression_p (type))
17931 	  {
17932             if (complain & tf_error)
17933               error ("a cast to a type other than an integral or "
17934                      "enumeration type cannot appear in a constant-expression");
17935 	    RETURN (error_mark_node);
17936 	  }
17937 
17938 	op = RECUR (TREE_OPERAND (t, 0));
17939 
17940 	warning_sentinel s(warn_useless_cast);
17941 	warning_sentinel s2(warn_ignored_qualifiers);
17942 	switch (TREE_CODE (t))
17943 	  {
17944 	  case CAST_EXPR:
17945 	    r = build_functional_cast (type, op, complain);
17946 	    break;
17947 	  case REINTERPRET_CAST_EXPR:
17948 	    r = build_reinterpret_cast (type, op, complain);
17949 	    break;
17950 	  case CONST_CAST_EXPR:
17951 	    r = build_const_cast (type, op, complain);
17952 	    break;
17953 	  case DYNAMIC_CAST_EXPR:
17954 	    r = build_dynamic_cast (type, op, complain);
17955 	    break;
17956 	  case STATIC_CAST_EXPR:
17957 	    r = build_static_cast (type, op, complain);
17958 	    break;
17959 	  default:
17960 	    gcc_unreachable ();
17961 	  }
17962 
17963 	RETURN (r);
17964       }
17965 
17966     case POSTDECREMENT_EXPR:
17967     case POSTINCREMENT_EXPR:
17968       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
17969 						args, complain, in_decl);
17970       RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
17971 				complain|decltype_flag));
17972 
17973     case PREDECREMENT_EXPR:
17974     case PREINCREMENT_EXPR:
17975     case NEGATE_EXPR:
17976     case BIT_NOT_EXPR:
17977     case ABS_EXPR:
17978     case TRUTH_NOT_EXPR:
17979     case UNARY_PLUS_EXPR:  /* Unary + */
17980     case REALPART_EXPR:
17981     case IMAGPART_EXPR:
17982       RETURN (build_x_unary_op (input_location, TREE_CODE (t),
17983 				RECUR (TREE_OPERAND (t, 0)),
17984 				complain|decltype_flag));
17985 
17986     case FIX_TRUNC_EXPR:
17987       gcc_unreachable ();
17988 
17989     case ADDR_EXPR:
17990       op1 = TREE_OPERAND (t, 0);
17991       if (TREE_CODE (op1) == LABEL_DECL)
17992 	RETURN (finish_label_address_expr (DECL_NAME (op1),
17993 					  EXPR_LOCATION (op1)));
17994       if (TREE_CODE (op1) == SCOPE_REF)
17995 	op1 = tsubst_qualified_id (op1, args, complain, in_decl,
17996 				   /*done=*/true, /*address_p=*/true);
17997       else
17998 	op1 = tsubst_non_call_postfix_expression (op1, args, complain,
17999 						  in_decl);
18000       RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
18001 				complain|decltype_flag));
18002 
18003     case PLUS_EXPR:
18004     case MINUS_EXPR:
18005     case MULT_EXPR:
18006     case TRUNC_DIV_EXPR:
18007     case CEIL_DIV_EXPR:
18008     case FLOOR_DIV_EXPR:
18009     case ROUND_DIV_EXPR:
18010     case EXACT_DIV_EXPR:
18011     case BIT_AND_EXPR:
18012     case BIT_IOR_EXPR:
18013     case BIT_XOR_EXPR:
18014     case TRUNC_MOD_EXPR:
18015     case FLOOR_MOD_EXPR:
18016     case TRUTH_ANDIF_EXPR:
18017     case TRUTH_ORIF_EXPR:
18018     case TRUTH_AND_EXPR:
18019     case TRUTH_OR_EXPR:
18020     case RSHIFT_EXPR:
18021     case LSHIFT_EXPR:
18022     case RROTATE_EXPR:
18023     case LROTATE_EXPR:
18024     case EQ_EXPR:
18025     case NE_EXPR:
18026     case MAX_EXPR:
18027     case MIN_EXPR:
18028     case LE_EXPR:
18029     case GE_EXPR:
18030     case LT_EXPR:
18031     case GT_EXPR:
18032     case MEMBER_REF:
18033     case DOTSTAR_EXPR:
18034       {
18035 	warning_sentinel s1(warn_type_limits);
18036 	warning_sentinel s2(warn_div_by_zero);
18037 	warning_sentinel s3(warn_logical_op);
18038 	warning_sentinel s4(warn_tautological_compare);
18039 	tree op0 = RECUR (TREE_OPERAND (t, 0));
18040 	tree op1 = RECUR (TREE_OPERAND (t, 1));
18041 	tree r = build_x_binary_op
18042 	  (input_location, TREE_CODE (t),
18043 	   op0,
18044 	   (TREE_NO_WARNING (TREE_OPERAND (t, 0))
18045 	    ? ERROR_MARK
18046 	    : TREE_CODE (TREE_OPERAND (t, 0))),
18047 	   op1,
18048 	   (TREE_NO_WARNING (TREE_OPERAND (t, 1))
18049 	    ? ERROR_MARK
18050 	    : TREE_CODE (TREE_OPERAND (t, 1))),
18051 	   /*overload=*/NULL,
18052 	   complain|decltype_flag);
18053 	if (EXPR_P (r) && TREE_NO_WARNING (t))
18054 	  TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
18055 
18056 	RETURN (r);
18057       }
18058 
18059     case POINTER_PLUS_EXPR:
18060       {
18061 	tree op0 = RECUR (TREE_OPERAND (t, 0));
18062 	tree op1 = RECUR (TREE_OPERAND (t, 1));
18063 	RETURN (fold_build_pointer_plus (op0, op1));
18064       }
18065 
18066     case SCOPE_REF:
18067       RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
18068 				  /*address_p=*/false));
18069     case ARRAY_REF:
18070       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
18071 						args, complain, in_decl);
18072       RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
18073 				 RECUR (TREE_OPERAND (t, 1)),
18074 				 complain|decltype_flag));
18075 
18076     case SIZEOF_EXPR:
18077       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
18078 	  || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
18079 	RETURN (tsubst_copy (t, args, complain, in_decl));
18080       /* Fall through */
18081 
18082     case ALIGNOF_EXPR:
18083       {
18084 	tree r;
18085 
18086 	op1 = TREE_OPERAND (t, 0);
18087 	if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
18088 	  op1 = TREE_TYPE (op1);
18089 	bool std_alignof = (TREE_CODE (t) == ALIGNOF_EXPR
18090 			    && ALIGNOF_EXPR_STD_P (t));
18091         if (!args)
18092 	  {
18093 	    /* When there are no ARGS, we are trying to evaluate a
18094 	       non-dependent expression from the parser.  Trying to do
18095 	       the substitutions may not work.  */
18096 	    if (!TYPE_P (op1))
18097 	      op1 = TREE_TYPE (op1);
18098 	  }
18099 	else
18100 	  {
18101 	    ++cp_unevaluated_operand;
18102 	    ++c_inhibit_evaluation_warnings;
18103 	    if (TYPE_P (op1))
18104 	      op1 = tsubst (op1, args, complain, in_decl);
18105 	    else
18106 	      op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
18107 					   /*function_p=*/false,
18108 					   /*integral_constant_expression_p=*/
18109 					   false);
18110 	    --cp_unevaluated_operand;
18111 	    --c_inhibit_evaluation_warnings;
18112 	  }
18113         if (TYPE_P (op1))
18114 	  r = cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), std_alignof,
18115 					  complain & tf_error);
18116 	else
18117 	  r = cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t),
18118 					  complain & tf_error);
18119 	if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
18120 	  {
18121 	    if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
18122 	      {
18123 		if (!processing_template_decl && TYPE_P (op1))
18124 		  {
18125 		    r = build_min (SIZEOF_EXPR, size_type_node,
18126 				   build1 (NOP_EXPR, op1, error_mark_node));
18127 		    SIZEOF_EXPR_TYPE_P (r) = 1;
18128 		  }
18129 		else
18130 		  r = build_min (SIZEOF_EXPR, size_type_node, op1);
18131 		TREE_SIDE_EFFECTS (r) = 0;
18132 		TREE_READONLY (r) = 1;
18133 	      }
18134 	    SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
18135 	  }
18136 	RETURN (r);
18137       }
18138 
18139     case AT_ENCODE_EXPR:
18140       {
18141 	op1 = TREE_OPERAND (t, 0);
18142 	++cp_unevaluated_operand;
18143 	++c_inhibit_evaluation_warnings;
18144 	op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
18145 				     /*function_p=*/false,
18146 				     /*integral_constant_expression_p=*/false);
18147 	--cp_unevaluated_operand;
18148 	--c_inhibit_evaluation_warnings;
18149 	RETURN (objc_build_encode_expr (op1));
18150       }
18151 
18152     case NOEXCEPT_EXPR:
18153       op1 = TREE_OPERAND (t, 0);
18154       ++cp_unevaluated_operand;
18155       ++c_inhibit_evaluation_warnings;
18156       ++cp_noexcept_operand;
18157       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
18158 				   /*function_p=*/false,
18159 				   /*integral_constant_expression_p=*/false);
18160       --cp_unevaluated_operand;
18161       --c_inhibit_evaluation_warnings;
18162       --cp_noexcept_operand;
18163       RETURN (finish_noexcept_expr (op1, complain));
18164 
18165     case MODOP_EXPR:
18166       {
18167 	warning_sentinel s(warn_div_by_zero);
18168 	tree lhs = RECUR (TREE_OPERAND (t, 0));
18169 	tree rhs = RECUR (TREE_OPERAND (t, 2));
18170 	tree r = build_x_modify_expr
18171 	  (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
18172 	   complain|decltype_flag);
18173 	/* TREE_NO_WARNING must be set if either the expression was
18174 	   parenthesized or it uses an operator such as >>= rather
18175 	   than plain assignment.  In the former case, it was already
18176 	   set and must be copied.  In the latter case,
18177 	   build_x_modify_expr sets it and it must not be reset
18178 	   here.  */
18179 	if (TREE_NO_WARNING (t))
18180 	  TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
18181 
18182 	RETURN (r);
18183       }
18184 
18185     case ARROW_EXPR:
18186       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
18187 						args, complain, in_decl);
18188       /* Remember that there was a reference to this entity.  */
18189       if (DECL_P (op1)
18190 	  && !mark_used (op1, complain) && !(complain & tf_error))
18191 	RETURN (error_mark_node);
18192       RETURN (build_x_arrow (input_location, op1, complain));
18193 
18194     case NEW_EXPR:
18195       {
18196 	tree placement = RECUR (TREE_OPERAND (t, 0));
18197 	tree init = RECUR (TREE_OPERAND (t, 3));
18198 	vec<tree, va_gc> *placement_vec;
18199 	vec<tree, va_gc> *init_vec;
18200 	tree ret;
18201 
18202 	if (placement == NULL_TREE)
18203 	  placement_vec = NULL;
18204 	else
18205 	  {
18206 	    placement_vec = make_tree_vector ();
18207 	    for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
18208 	      vec_safe_push (placement_vec, TREE_VALUE (placement));
18209 	  }
18210 
18211 	/* If there was an initializer in the original tree, but it
18212 	   instantiated to an empty list, then we should pass a
18213 	   non-NULL empty vector to tell build_new that it was an
18214 	   empty initializer() rather than no initializer.  This can
18215 	   only happen when the initializer is a pack expansion whose
18216 	   parameter packs are of length zero.  */
18217 	if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
18218 	  init_vec = NULL;
18219 	else
18220 	  {
18221 	    init_vec = make_tree_vector ();
18222 	    if (init == void_node)
18223 	      gcc_assert (init_vec != NULL);
18224 	    else
18225 	      {
18226 		for (; init != NULL_TREE; init = TREE_CHAIN (init))
18227 		  vec_safe_push (init_vec, TREE_VALUE (init));
18228 	      }
18229 	  }
18230 
18231 	tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
18232 	tree op2 = RECUR (TREE_OPERAND (t, 2));
18233 	ret = build_new (&placement_vec, op1, op2, &init_vec,
18234 			 NEW_EXPR_USE_GLOBAL (t),
18235 			 complain);
18236 
18237 	if (placement_vec != NULL)
18238 	  release_tree_vector (placement_vec);
18239 	if (init_vec != NULL)
18240 	  release_tree_vector (init_vec);
18241 
18242 	RETURN (ret);
18243       }
18244 
18245     case DELETE_EXPR:
18246       {
18247 	tree op0 = RECUR (TREE_OPERAND (t, 0));
18248 	tree op1 = RECUR (TREE_OPERAND (t, 1));
18249 	RETURN (delete_sanity (op0, op1,
18250 			       DELETE_EXPR_USE_VEC (t),
18251 			       DELETE_EXPR_USE_GLOBAL (t),
18252 			       complain));
18253       }
18254 
18255     case COMPOUND_EXPR:
18256       {
18257 	tree op0 = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
18258 					  complain & ~tf_decltype, in_decl,
18259 					  /*function_p=*/false,
18260 					  integral_constant_expression_p);
18261 	RETURN (build_x_compound_expr (EXPR_LOCATION (t),
18262 				       op0,
18263 				       RECUR (TREE_OPERAND (t, 1)),
18264 				       complain|decltype_flag));
18265       }
18266 
18267     case CALL_EXPR:
18268       {
18269 	tree function;
18270 	vec<tree, va_gc> *call_args;
18271 	unsigned int nargs, i;
18272 	bool qualified_p;
18273 	bool koenig_p;
18274 	tree ret;
18275 
18276 	function = CALL_EXPR_FN (t);
18277 	/* Internal function with no arguments.  */
18278 	if (function == NULL_TREE && call_expr_nargs (t) == 0)
18279 	  RETURN (t);
18280 
18281 	/* When we parsed the expression, we determined whether or
18282 	   not Koenig lookup should be performed.  */
18283 	koenig_p = KOENIG_LOOKUP_P (t);
18284 	if (function == NULL_TREE)
18285 	  {
18286 	    koenig_p = false;
18287 	    qualified_p = false;
18288 	  }
18289 	else if (TREE_CODE (function) == SCOPE_REF)
18290 	  {
18291 	    qualified_p = true;
18292 	    function = tsubst_qualified_id (function, args, complain, in_decl,
18293 					    /*done=*/false,
18294 					    /*address_p=*/false);
18295 	  }
18296 	else if (koenig_p && identifier_p (function))
18297 	  {
18298 	    /* Do nothing; calling tsubst_copy_and_build on an identifier
18299 	       would incorrectly perform unqualified lookup again.
18300 
18301 	       Note that we can also have an IDENTIFIER_NODE if the earlier
18302 	       unqualified lookup found a member function; in that case
18303 	       koenig_p will be false and we do want to do the lookup
18304 	       again to find the instantiated member function.
18305 
18306 	       FIXME but doing that causes c++/15272, so we need to stop
18307 	       using IDENTIFIER_NODE in that situation.  */
18308 	    qualified_p = false;
18309 	  }
18310 	else
18311 	  {
18312 	    if (TREE_CODE (function) == COMPONENT_REF)
18313 	      {
18314 		tree op = TREE_OPERAND (function, 1);
18315 
18316 		qualified_p = (TREE_CODE (op) == SCOPE_REF
18317 			       || (BASELINK_P (op)
18318 				   && BASELINK_QUALIFIED_P (op)));
18319 	      }
18320 	    else
18321 	      qualified_p = false;
18322 
18323 	    if (TREE_CODE (function) == ADDR_EXPR
18324 		&& TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
18325 	      /* Avoid error about taking the address of a constructor.  */
18326 	      function = TREE_OPERAND (function, 0);
18327 
18328 	    function = tsubst_copy_and_build (function, args, complain,
18329 					      in_decl,
18330 					      !qualified_p,
18331 					      integral_constant_expression_p);
18332 
18333 	    if (BASELINK_P (function))
18334 	      qualified_p = true;
18335 	  }
18336 
18337 	nargs = call_expr_nargs (t);
18338 	call_args = make_tree_vector ();
18339 	for (i = 0; i < nargs; ++i)
18340 	  {
18341 	    tree arg = CALL_EXPR_ARG (t, i);
18342 
18343 	    if (!PACK_EXPANSION_P (arg))
18344 	      vec_safe_push (call_args, RECUR (CALL_EXPR_ARG (t, i)));
18345 	    else
18346 	      {
18347 		/* Expand the pack expansion and push each entry onto
18348 		   CALL_ARGS.  */
18349 		arg = tsubst_pack_expansion (arg, args, complain, in_decl);
18350 		if (TREE_CODE (arg) == TREE_VEC)
18351 		  {
18352 		    unsigned int len, j;
18353 
18354 		    len = TREE_VEC_LENGTH (arg);
18355 		    for (j = 0; j < len; ++j)
18356 		      {
18357 			tree value = TREE_VEC_ELT (arg, j);
18358 			if (value != NULL_TREE)
18359 			  value = convert_from_reference (value);
18360 			vec_safe_push (call_args, value);
18361 		      }
18362 		  }
18363 		else
18364 		  {
18365 		    /* A partial substitution.  Add one entry.  */
18366 		    vec_safe_push (call_args, arg);
18367 		  }
18368 	      }
18369 	  }
18370 
18371 	/* We do not perform argument-dependent lookup if normal
18372 	   lookup finds a non-function, in accordance with the
18373 	   expected resolution of DR 218.  */
18374 	if (koenig_p
18375 	    && ((is_overloaded_fn (function)
18376 		 /* If lookup found a member function, the Koenig lookup is
18377 		    not appropriate, even if an unqualified-name was used
18378 		    to denote the function.  */
18379 		 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
18380 		|| identifier_p (function))
18381 	    /* Only do this when substitution turns a dependent call
18382 	       into a non-dependent call.  */
18383 	    && type_dependent_expression_p_push (t)
18384 	    && !any_type_dependent_arguments_p (call_args))
18385 	  function = perform_koenig_lookup (function, call_args, tf_none);
18386 
18387 	if (function != NULL_TREE
18388 	    && identifier_p (function)
18389 	    && !any_type_dependent_arguments_p (call_args))
18390 	  {
18391 	    if (koenig_p && (complain & tf_warning_or_error))
18392 	      {
18393 		/* For backwards compatibility and good diagnostics, try
18394 		   the unqualified lookup again if we aren't in SFINAE
18395 		   context.  */
18396 		tree unq = (tsubst_copy_and_build
18397 			    (function, args, complain, in_decl, true,
18398 			     integral_constant_expression_p));
18399 		if (unq == error_mark_node)
18400 		  {
18401 		    release_tree_vector (call_args);
18402 		    RETURN (error_mark_node);
18403 		  }
18404 
18405 		if (unq != function)
18406 		  {
18407 		    /* In a lambda fn, we have to be careful to not
18408 		       introduce new this captures.  Legacy code can't
18409 		       be using lambdas anyway, so it's ok to be
18410 		       stricter.  */
18411 		    bool in_lambda = (current_class_type
18412 				      && LAMBDA_TYPE_P (current_class_type));
18413 		    char const *const msg
18414 		      = G_("%qD was not declared in this scope, "
18415 			   "and no declarations were found by "
18416 			   "argument-dependent lookup at the point "
18417 			   "of instantiation");
18418 
18419 		    bool diag = true;
18420 		    if (in_lambda)
18421 		      error_at (EXPR_LOC_OR_LOC (t, input_location),
18422 				msg, function);
18423 		    else
18424 		      diag = permerror (EXPR_LOC_OR_LOC (t, input_location),
18425 					msg, function);
18426 		    if (diag)
18427 		      {
18428 			tree fn = unq;
18429 
18430 			if (INDIRECT_REF_P (fn))
18431 			  fn = TREE_OPERAND (fn, 0);
18432 			if (is_overloaded_fn (fn))
18433 			  fn = get_first_fn (fn);
18434 
18435 			if (!DECL_P (fn))
18436 			  /* Can't say anything more.  */;
18437 			else if (DECL_CLASS_SCOPE_P (fn))
18438 			  {
18439 			    location_t loc = EXPR_LOC_OR_LOC (t,
18440 							      input_location);
18441 			    inform (loc,
18442 				    "declarations in dependent base %qT are "
18443 				    "not found by unqualified lookup",
18444 				    DECL_CLASS_CONTEXT (fn));
18445 			    if (current_class_ptr)
18446 			      inform (loc,
18447 				      "use %<this->%D%> instead", function);
18448 			    else
18449 			      inform (loc,
18450 				      "use %<%T::%D%> instead",
18451 				      current_class_name, function);
18452 			  }
18453 			else
18454 			  inform (DECL_SOURCE_LOCATION (fn),
18455 				  "%qD declared here, later in the "
18456 				  "translation unit", fn);
18457 			if (in_lambda)
18458 			  {
18459 			    release_tree_vector (call_args);
18460 			    RETURN (error_mark_node);
18461 			  }
18462 		      }
18463 
18464 		    function = unq;
18465 		  }
18466 	      }
18467 	    if (identifier_p (function))
18468 	      {
18469 		if (complain & tf_error)
18470 		  unqualified_name_lookup_error (function);
18471 		release_tree_vector (call_args);
18472 		RETURN (error_mark_node);
18473 	      }
18474 	  }
18475 
18476 	/* Remember that there was a reference to this entity.  */
18477 	if (function != NULL_TREE
18478 	    && DECL_P (function)
18479 	    && !mark_used (function, complain) && !(complain & tf_error))
18480 	  {
18481 	    release_tree_vector (call_args);
18482 	    RETURN (error_mark_node);
18483 	  }
18484 
18485 	/* Put back tf_decltype for the actual call.  */
18486 	complain |= decltype_flag;
18487 
18488 	if (function == NULL_TREE)
18489 	  switch (CALL_EXPR_IFN (t))
18490 	    {
18491 	    case IFN_LAUNDER:
18492 	      gcc_assert (nargs == 1);
18493 	      if (vec_safe_length (call_args) != 1)
18494 		{
18495 		  error_at (EXPR_LOC_OR_LOC (t, input_location),
18496 			    "wrong number of arguments to "
18497 			    "%<__builtin_launder%>");
18498 		  ret = error_mark_node;
18499 		}
18500 	      else
18501 		ret = finish_builtin_launder (EXPR_LOC_OR_LOC (t,
18502 							       input_location),
18503 					      (*call_args)[0], complain);
18504 	      break;
18505 
18506 	    default:
18507 	      /* Unsupported internal function with arguments.  */
18508 	      gcc_unreachable ();
18509 	    }
18510 	else if (TREE_CODE (function) == OFFSET_REF
18511 		 || TREE_CODE (function) == DOTSTAR_EXPR
18512 		 || TREE_CODE (function) == MEMBER_REF)
18513 	  ret = build_offset_ref_call_from_tree (function, &call_args,
18514 						 complain);
18515 	else if (TREE_CODE (function) == COMPONENT_REF)
18516 	  {
18517 	    tree instance = TREE_OPERAND (function, 0);
18518 	    tree fn = TREE_OPERAND (function, 1);
18519 
18520 	    if (processing_template_decl
18521 		&& (type_dependent_expression_p (instance)
18522 		    || (!BASELINK_P (fn)
18523 			&& TREE_CODE (fn) != FIELD_DECL)
18524 		    || type_dependent_expression_p (fn)
18525 		    || any_type_dependent_arguments_p (call_args)))
18526 	      ret = build_min_nt_call_vec (function, call_args);
18527 	    else if (!BASELINK_P (fn))
18528 	      ret = finish_call_expr (function, &call_args,
18529 				       /*disallow_virtual=*/false,
18530 				       /*koenig_p=*/false,
18531 				       complain);
18532 	    else
18533 	      ret = (build_new_method_call
18534 		      (instance, fn,
18535 		       &call_args, NULL_TREE,
18536 		       qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
18537 		       /*fn_p=*/NULL,
18538 		       complain));
18539 	  }
18540 	else
18541 	  ret = finish_call_expr (function, &call_args,
18542 				  /*disallow_virtual=*/qualified_p,
18543 				  koenig_p,
18544 				  complain);
18545 
18546 	release_tree_vector (call_args);
18547 
18548 	if (ret != error_mark_node)
18549 	  {
18550 	    bool op = CALL_EXPR_OPERATOR_SYNTAX (t);
18551 	    bool ord = CALL_EXPR_ORDERED_ARGS (t);
18552 	    bool rev = CALL_EXPR_REVERSE_ARGS (t);
18553 	    bool thk = CALL_FROM_THUNK_P (t);
18554 	    if (op || ord || rev || thk)
18555 	      {
18556 		function = extract_call_expr (ret);
18557 		CALL_EXPR_OPERATOR_SYNTAX (function) = op;
18558 		CALL_EXPR_ORDERED_ARGS (function) = ord;
18559 		CALL_EXPR_REVERSE_ARGS (function) = rev;
18560 		if (thk)
18561 		  {
18562 		    /* The thunk location is not interesting.  */
18563 		    SET_EXPR_LOCATION (function, UNKNOWN_LOCATION);
18564 		  }
18565 	      }
18566 	  }
18567 
18568 	RETURN (ret);
18569       }
18570 
18571     case COND_EXPR:
18572       {
18573 	tree cond = RECUR (TREE_OPERAND (t, 0));
18574 	cond = mark_rvalue_use (cond);
18575 	tree folded_cond = fold_non_dependent_expr (cond);
18576 	tree exp1, exp2;
18577 
18578 	if (TREE_CODE (folded_cond) == INTEGER_CST)
18579 	  {
18580 	    if (integer_zerop (folded_cond))
18581 	      {
18582 		++c_inhibit_evaluation_warnings;
18583 		exp1 = RECUR (TREE_OPERAND (t, 1));
18584 		--c_inhibit_evaluation_warnings;
18585 		exp2 = RECUR (TREE_OPERAND (t, 2));
18586 	      }
18587 	    else
18588 	      {
18589 		exp1 = RECUR (TREE_OPERAND (t, 1));
18590 		++c_inhibit_evaluation_warnings;
18591 		exp2 = RECUR (TREE_OPERAND (t, 2));
18592 		--c_inhibit_evaluation_warnings;
18593 	      }
18594 	    cond = folded_cond;
18595 	  }
18596 	else
18597 	  {
18598 	    exp1 = RECUR (TREE_OPERAND (t, 1));
18599 	    exp2 = RECUR (TREE_OPERAND (t, 2));
18600 	  }
18601 
18602 	warning_sentinel s(warn_duplicated_branches);
18603 	RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
18604 					 cond, exp1, exp2, complain));
18605       }
18606 
18607     case PSEUDO_DTOR_EXPR:
18608       {
18609 	tree op0 = RECUR (TREE_OPERAND (t, 0));
18610 	tree op1 = RECUR (TREE_OPERAND (t, 1));
18611 	tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
18612 	RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
18613 					       input_location));
18614       }
18615 
18616     case TREE_LIST:
18617       {
18618 	tree purpose, value, chain;
18619 
18620 	if (t == void_list_node)
18621 	  RETURN (t);
18622 
18623         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
18624             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
18625           {
18626             /* We have pack expansions, so expand those and
18627                create a new list out of it.  */
18628             tree purposevec = NULL_TREE;
18629             tree valuevec = NULL_TREE;
18630             tree chain;
18631             int i, len = -1;
18632 
18633             /* Expand the argument expressions.  */
18634             if (TREE_PURPOSE (t))
18635               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
18636                                                  complain, in_decl);
18637             if (TREE_VALUE (t))
18638               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
18639                                                complain, in_decl);
18640 
18641             /* Build the rest of the list.  */
18642             chain = TREE_CHAIN (t);
18643             if (chain && chain != void_type_node)
18644               chain = RECUR (chain);
18645 
18646             /* Determine the number of arguments.  */
18647             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
18648               {
18649                 len = TREE_VEC_LENGTH (purposevec);
18650                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
18651               }
18652             else if (TREE_CODE (valuevec) == TREE_VEC)
18653               len = TREE_VEC_LENGTH (valuevec);
18654             else
18655               {
18656                 /* Since we only performed a partial substitution into
18657                    the argument pack, we only RETURN (a single list
18658                    node.  */
18659                 if (purposevec == TREE_PURPOSE (t)
18660                     && valuevec == TREE_VALUE (t)
18661                     && chain == TREE_CHAIN (t))
18662                   RETURN (t);
18663 
18664                 RETURN (tree_cons (purposevec, valuevec, chain));
18665               }
18666 
18667             /* Convert the argument vectors into a TREE_LIST */
18668             i = len;
18669             while (i > 0)
18670               {
18671                 /* Grab the Ith values.  */
18672                 i--;
18673                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i)
18674 		                     : NULL_TREE;
18675                 value
18676 		  = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i))
18677                              : NULL_TREE;
18678 
18679                 /* Build the list (backwards).  */
18680                 chain = tree_cons (purpose, value, chain);
18681               }
18682 
18683             RETURN (chain);
18684           }
18685 
18686 	purpose = TREE_PURPOSE (t);
18687 	if (purpose)
18688 	  purpose = RECUR (purpose);
18689 	value = TREE_VALUE (t);
18690 	if (value)
18691 	  value = RECUR (value);
18692 	chain = TREE_CHAIN (t);
18693 	if (chain && chain != void_type_node)
18694 	  chain = RECUR (chain);
18695 	if (purpose == TREE_PURPOSE (t)
18696 	    && value == TREE_VALUE (t)
18697 	    && chain == TREE_CHAIN (t))
18698 	  RETURN (t);
18699 	RETURN (tree_cons (purpose, value, chain));
18700       }
18701 
18702     case COMPONENT_REF:
18703       {
18704 	tree object;
18705 	tree object_type;
18706 	tree member;
18707 	tree r;
18708 
18709 	object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
18710 						     args, complain, in_decl);
18711 	/* Remember that there was a reference to this entity.  */
18712 	if (DECL_P (object)
18713 	    && !mark_used (object, complain) && !(complain & tf_error))
18714 	  RETURN (error_mark_node);
18715 	object_type = TREE_TYPE (object);
18716 
18717 	member = TREE_OPERAND (t, 1);
18718 	if (BASELINK_P (member))
18719 	  member = tsubst_baselink (member,
18720 				    non_reference (TREE_TYPE (object)),
18721 				    args, complain, in_decl);
18722 	else
18723 	  member = tsubst_copy (member, args, complain, in_decl);
18724 	if (member == error_mark_node)
18725 	  RETURN (error_mark_node);
18726 
18727 	if (TREE_CODE (member) == FIELD_DECL)
18728 	  {
18729 	    r = finish_non_static_data_member (member, object, NULL_TREE);
18730 	    if (TREE_CODE (r) == COMPONENT_REF)
18731 	      REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
18732 	    RETURN (r);
18733 	  }
18734 	else if (type_dependent_expression_p (object))
18735 	  /* We can't do much here.  */;
18736 	else if (!CLASS_TYPE_P (object_type))
18737 	  {
18738 	    if (scalarish_type_p (object_type))
18739 	      {
18740 		tree s = NULL_TREE;
18741 		tree dtor = member;
18742 
18743 		if (TREE_CODE (dtor) == SCOPE_REF)
18744 		  {
18745 		    s = TREE_OPERAND (dtor, 0);
18746 		    dtor = TREE_OPERAND (dtor, 1);
18747 		  }
18748 		if (TREE_CODE (dtor) == BIT_NOT_EXPR)
18749 		  {
18750 		    dtor = TREE_OPERAND (dtor, 0);
18751 		    if (TYPE_P (dtor))
18752 		      RETURN (finish_pseudo_destructor_expr
18753 			      (object, s, dtor, input_location));
18754 		  }
18755 	      }
18756 	  }
18757 	else if (TREE_CODE (member) == SCOPE_REF
18758 		 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
18759 	  {
18760 	    /* Lookup the template functions now that we know what the
18761 	       scope is.  */
18762 	    tree scope = TREE_OPERAND (member, 0);
18763 	    tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
18764 	    tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
18765 	    member = lookup_qualified_name (scope, tmpl,
18766 					    /*is_type_p=*/false,
18767 					    /*complain=*/false);
18768 	    if (BASELINK_P (member))
18769 	      {
18770 		BASELINK_FUNCTIONS (member)
18771 		  = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
18772 			      args);
18773 		member = (adjust_result_of_qualified_name_lookup
18774 			  (member, BINFO_TYPE (BASELINK_BINFO (member)),
18775 			   object_type));
18776 	      }
18777 	    else
18778 	      {
18779 		qualified_name_lookup_error (scope, tmpl, member,
18780 					     input_location);
18781 		RETURN (error_mark_node);
18782 	      }
18783 	  }
18784 	else if (TREE_CODE (member) == SCOPE_REF
18785 		 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
18786 		 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
18787 	  {
18788 	    if (complain & tf_error)
18789 	      {
18790 		if (TYPE_P (TREE_OPERAND (member, 0)))
18791 		  error ("%qT is not a class or namespace",
18792 			 TREE_OPERAND (member, 0));
18793 		else
18794 		  error ("%qD is not a class or namespace",
18795 			 TREE_OPERAND (member, 0));
18796 	      }
18797 	    RETURN (error_mark_node);
18798 	  }
18799 
18800 	r = finish_class_member_access_expr (object, member,
18801 					     /*template_p=*/false,
18802 					     complain);
18803 	if (TREE_CODE (r) == COMPONENT_REF)
18804 	  REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
18805 	RETURN (r);
18806       }
18807 
18808     case THROW_EXPR:
18809       RETURN (build_throw
18810 	(RECUR (TREE_OPERAND (t, 0))));
18811 
18812     case CONSTRUCTOR:
18813       {
18814 	vec<constructor_elt, va_gc> *n;
18815 	constructor_elt *ce;
18816 	unsigned HOST_WIDE_INT idx;
18817 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
18818 	bool process_index_p;
18819         int newlen;
18820         bool need_copy_p = false;
18821 	tree r;
18822 
18823 	if (type == error_mark_node)
18824 	  RETURN (error_mark_node);
18825 
18826 	/* We do not want to process the index of aggregate
18827 	   initializers as they are identifier nodes which will be
18828 	   looked up by digest_init.  */
18829 	process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
18830 
18831 	if (null_member_pointer_value_p (t))
18832 	  {
18833 	    gcc_assert (same_type_p (type, TREE_TYPE (t)));
18834 	    RETURN (t);
18835 	  }
18836 
18837 	n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
18838         newlen = vec_safe_length (n);
18839 	FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
18840 	  {
18841 	    if (ce->index && process_index_p
18842 		/* An identifier index is looked up in the type
18843 		   being initialized, not the current scope.  */
18844 		&& TREE_CODE (ce->index) != IDENTIFIER_NODE)
18845 	      ce->index = RECUR (ce->index);
18846 
18847             if (PACK_EXPANSION_P (ce->value))
18848               {
18849                 /* Substitute into the pack expansion.  */
18850                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
18851                                                   in_decl);
18852 
18853 		if (ce->value == error_mark_node
18854 		    || PACK_EXPANSION_P (ce->value))
18855 		  ;
18856 		else if (TREE_VEC_LENGTH (ce->value) == 1)
18857                   /* Just move the argument into place.  */
18858                   ce->value = TREE_VEC_ELT (ce->value, 0);
18859                 else
18860                   {
18861                     /* Update the length of the final CONSTRUCTOR
18862                        arguments vector, and note that we will need to
18863                        copy.*/
18864                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
18865                     need_copy_p = true;
18866                   }
18867               }
18868             else
18869               ce->value = RECUR (ce->value);
18870 	  }
18871 
18872         if (need_copy_p)
18873           {
18874             vec<constructor_elt, va_gc> *old_n = n;
18875 
18876             vec_alloc (n, newlen);
18877             FOR_EACH_VEC_ELT (*old_n, idx, ce)
18878               {
18879                 if (TREE_CODE (ce->value) == TREE_VEC)
18880                   {
18881                     int i, len = TREE_VEC_LENGTH (ce->value);
18882                     for (i = 0; i < len; ++i)
18883                       CONSTRUCTOR_APPEND_ELT (n, 0,
18884                                               TREE_VEC_ELT (ce->value, i));
18885                   }
18886                 else
18887                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
18888               }
18889           }
18890 
18891 	r = build_constructor (init_list_type_node, n);
18892 	CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
18893 
18894 	if (TREE_HAS_CONSTRUCTOR (t))
18895 	  {
18896 	    fcl_t cl = fcl_functional;
18897 	    if (CONSTRUCTOR_C99_COMPOUND_LITERAL (t))
18898 	      cl = fcl_c99;
18899 	    RETURN (finish_compound_literal (type, r, complain, cl));
18900 	  }
18901 
18902 	TREE_TYPE (r) = type;
18903 	RETURN (r);
18904       }
18905 
18906     case TYPEID_EXPR:
18907       {
18908 	tree operand_0 = TREE_OPERAND (t, 0);
18909 	if (TYPE_P (operand_0))
18910 	  {
18911 	    operand_0 = tsubst (operand_0, args, complain, in_decl);
18912 	    RETURN (get_typeid (operand_0, complain));
18913 	  }
18914 	else
18915 	  {
18916 	    operand_0 = RECUR (operand_0);
18917 	    RETURN (build_typeid (operand_0, complain));
18918 	  }
18919       }
18920 
18921     case VAR_DECL:
18922       if (!args)
18923 	RETURN (t);
18924       /* Fall through */
18925 
18926     case PARM_DECL:
18927       {
18928 	tree r = tsubst_copy (t, args, complain, in_decl);
18929 	/* ??? We're doing a subset of finish_id_expression here.  */
18930 	if (tree wrap = maybe_get_tls_wrapper_call (r))
18931 	  /* Replace an evaluated use of the thread_local variable with
18932 	     a call to its wrapper.  */
18933 	  r = wrap;
18934 	else if (outer_automatic_var_p (r))
18935 	  r = process_outer_var_ref (r, complain);
18936 
18937 	if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
18938 	  /* If the original type was a reference, we'll be wrapped in
18939 	     the appropriate INDIRECT_REF.  */
18940 	  r = convert_from_reference (r);
18941 	RETURN (r);
18942       }
18943 
18944     case VA_ARG_EXPR:
18945       {
18946 	tree op0 = RECUR (TREE_OPERAND (t, 0));
18947 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
18948 	RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
18949       }
18950 
18951     case OFFSETOF_EXPR:
18952       {
18953 	tree object_ptr
18954 	  = tsubst_copy_and_build (TREE_OPERAND (t, 1), args, complain,
18955 				   in_decl, /*function_p=*/false,
18956 				   /*integral_constant_expression_p=*/false);
18957 	RETURN (finish_offsetof (object_ptr,
18958 				 RECUR (TREE_OPERAND (t, 0)),
18959 				 EXPR_LOCATION (t)));
18960       }
18961 
18962     case ADDRESSOF_EXPR:
18963       RETURN (cp_build_addressof (EXPR_LOCATION (t),
18964 				  RECUR (TREE_OPERAND (t, 0)), complain));
18965 
18966     case TRAIT_EXPR:
18967       {
18968 	tree type1 = tsubst (TRAIT_EXPR_TYPE1 (t), args,
18969 			     complain, in_decl);
18970 
18971 	tree type2 = TRAIT_EXPR_TYPE2 (t);
18972 	if (type2 && TREE_CODE (type2) == TREE_LIST)
18973 	  type2 = RECUR (type2);
18974 	else if (type2)
18975 	  type2 = tsubst (type2, args, complain, in_decl);
18976 
18977 	RETURN (finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2));
18978       }
18979 
18980     case STMT_EXPR:
18981       {
18982 	tree old_stmt_expr = cur_stmt_expr;
18983 	tree stmt_expr = begin_stmt_expr ();
18984 
18985 	cur_stmt_expr = stmt_expr;
18986 	tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
18987 		     integral_constant_expression_p);
18988 	stmt_expr = finish_stmt_expr (stmt_expr, false);
18989 	cur_stmt_expr = old_stmt_expr;
18990 
18991 	/* If the resulting list of expression statement is empty,
18992 	   fold it further into void_node.  */
18993 	if (empty_expr_stmt_p (stmt_expr))
18994 	  stmt_expr = void_node;
18995 
18996 	RETURN (stmt_expr);
18997       }
18998 
18999     case LAMBDA_EXPR:
19000       {
19001 	tree r = tsubst_lambda_expr (t, args, complain, in_decl);
19002 
19003 	RETURN (build_lambda_object (r));
19004       }
19005 
19006     case TARGET_EXPR:
19007       /* We can get here for a constant initializer of non-dependent type.
19008          FIXME stop folding in cp_parser_initializer_clause.  */
19009       {
19010 	tree r = get_target_expr_sfinae (RECUR (TARGET_EXPR_INITIAL (t)),
19011 					 complain);
19012 	RETURN (r);
19013       }
19014 
19015     case TRANSACTION_EXPR:
19016       RETURN (tsubst_expr(t, args, complain, in_decl,
19017 	     integral_constant_expression_p));
19018 
19019     case PAREN_EXPR:
19020       RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
19021 
19022     case VEC_PERM_EXPR:
19023       {
19024 	tree op0 = RECUR (TREE_OPERAND (t, 0));
19025 	tree op1 = RECUR (TREE_OPERAND (t, 1));
19026 	tree op2 = RECUR (TREE_OPERAND (t, 2));
19027 	RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
19028 				       complain));
19029       }
19030 
19031     case REQUIRES_EXPR:
19032       RETURN (tsubst_requires_expr (t, args, complain, in_decl));
19033 
19034     case RANGE_EXPR:
19035       /* No need to substitute further, a RANGE_EXPR will always be built
19036 	 with constant operands.  */
19037       RETURN (t);
19038 
19039     case NON_LVALUE_EXPR:
19040     case VIEW_CONVERT_EXPR:
19041       /* We should only see these for location wrapper nodes, or within
19042 	 instantiate_non_dependent_expr (when args is NULL_TREE).  */
19043       gcc_assert (location_wrapper_p (t) || args == NULL_TREE);
19044       if (location_wrapper_p (t))
19045 	RETURN (maybe_wrap_with_location (RECUR (TREE_OPERAND (t, 0)),
19046 					  EXPR_LOCATION (t)));
19047       /* fallthrough.  */
19048 
19049     default:
19050       /* Handle Objective-C++ constructs, if appropriate.  */
19051       {
19052 	tree subst
19053 	  = objcp_tsubst_copy_and_build (t, args, complain,
19054 					 in_decl, /*function_p=*/false);
19055 	if (subst)
19056 	  RETURN (subst);
19057       }
19058       RETURN (tsubst_copy (t, args, complain, in_decl));
19059     }
19060 
19061 #undef RECUR
19062 #undef RETURN
19063  out:
19064   input_location = loc;
19065   return retval;
19066 }
19067 
19068 /* Verify that the instantiated ARGS are valid. For type arguments,
19069    make sure that the type's linkage is ok. For non-type arguments,
19070    make sure they are constants if they are integral or enumerations.
19071    Emit an error under control of COMPLAIN, and return TRUE on error.  */
19072 
19073 static bool
check_instantiated_arg(tree tmpl,tree t,tsubst_flags_t complain)19074 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
19075 {
19076   if (dependent_template_arg_p (t))
19077     return false;
19078   if (ARGUMENT_PACK_P (t))
19079     {
19080       tree vec = ARGUMENT_PACK_ARGS (t);
19081       int len = TREE_VEC_LENGTH (vec);
19082       bool result = false;
19083       int i;
19084 
19085       for (i = 0; i < len; ++i)
19086 	if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
19087 	  result = true;
19088       return result;
19089     }
19090   else if (TYPE_P (t))
19091     {
19092       /* [basic.link]: A name with no linkage (notably, the name
19093 	 of a class or enumeration declared in a local scope)
19094 	 shall not be used to declare an entity with linkage.
19095 	 This implies that names with no linkage cannot be used as
19096 	 template arguments
19097 
19098 	 DR 757 relaxes this restriction for C++0x.  */
19099       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
19100 		 : no_linkage_check (t, /*relaxed_p=*/false));
19101 
19102       if (nt)
19103 	{
19104 	  /* DR 488 makes use of a type with no linkage cause
19105 	     type deduction to fail.  */
19106 	  if (complain & tf_error)
19107 	    {
19108 	      if (TYPE_UNNAMED_P (nt))
19109 		error ("%qT is/uses unnamed type", t);
19110 	      else
19111 		error ("template argument for %qD uses local type %qT",
19112 		       tmpl, t);
19113 	    }
19114 	  return true;
19115 	}
19116       /* In order to avoid all sorts of complications, we do not
19117 	 allow variably-modified types as template arguments.  */
19118       else if (variably_modified_type_p (t, NULL_TREE))
19119 	{
19120 	  if (complain & tf_error)
19121 	    error ("%qT is a variably modified type", t);
19122 	  return true;
19123 	}
19124     }
19125   /* Class template and alias template arguments should be OK.  */
19126   else if (DECL_TYPE_TEMPLATE_P (t))
19127     ;
19128   /* A non-type argument of integral or enumerated type must be a
19129      constant.  */
19130   else if (TREE_TYPE (t)
19131 	   && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
19132 	   && !REFERENCE_REF_P (t)
19133 	   && !TREE_CONSTANT (t))
19134     {
19135       if (complain & tf_error)
19136 	error ("integral expression %qE is not constant", t);
19137       return true;
19138     }
19139   return false;
19140 }
19141 
19142 static bool
check_instantiated_args(tree tmpl,tree args,tsubst_flags_t complain)19143 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
19144 {
19145   int ix, len = DECL_NTPARMS (tmpl);
19146   bool result = false;
19147 
19148   for (ix = 0; ix != len; ix++)
19149     {
19150       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
19151 	result = true;
19152     }
19153   if (result && (complain & tf_error))
19154     error ("  trying to instantiate %qD", tmpl);
19155   return result;
19156 }
19157 
19158 /* We're out of SFINAE context now, so generate diagnostics for the access
19159    errors we saw earlier when instantiating D from TMPL and ARGS.  */
19160 
19161 static void
recheck_decl_substitution(tree d,tree tmpl,tree args)19162 recheck_decl_substitution (tree d, tree tmpl, tree args)
19163 {
19164   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
19165   tree type = TREE_TYPE (pattern);
19166   location_t loc = input_location;
19167 
19168   push_access_scope (d);
19169   push_deferring_access_checks (dk_no_deferred);
19170   input_location = DECL_SOURCE_LOCATION (pattern);
19171   tsubst (type, args, tf_warning_or_error, d);
19172   input_location = loc;
19173   pop_deferring_access_checks ();
19174   pop_access_scope (d);
19175 }
19176 
19177 /* Instantiate the indicated variable, function, or alias template TMPL with
19178    the template arguments in TARG_PTR.  */
19179 
19180 static tree
instantiate_template_1(tree tmpl,tree orig_args,tsubst_flags_t complain)19181 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
19182 {
19183   tree targ_ptr = orig_args;
19184   tree fndecl;
19185   tree gen_tmpl;
19186   tree spec;
19187   bool access_ok = true;
19188 
19189   if (tmpl == error_mark_node)
19190     return error_mark_node;
19191 
19192   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
19193 
19194   /* If this function is a clone, handle it specially.  */
19195   if (DECL_CLONED_FUNCTION_P (tmpl))
19196     {
19197       tree spec;
19198       tree clone;
19199 
19200       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
19201 	 DECL_CLONED_FUNCTION.  */
19202       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
19203 				   targ_ptr, complain);
19204       if (spec == error_mark_node)
19205 	return error_mark_node;
19206 
19207       /* Look for the clone.  */
19208       FOR_EACH_CLONE (clone, spec)
19209 	if (DECL_NAME (clone) == DECL_NAME (tmpl))
19210 	  return clone;
19211       /* We should always have found the clone by now.  */
19212       gcc_unreachable ();
19213       return NULL_TREE;
19214     }
19215 
19216   if (targ_ptr == error_mark_node)
19217     return error_mark_node;
19218 
19219   /* Check to see if we already have this specialization.  */
19220   gen_tmpl = most_general_template (tmpl);
19221   if (TMPL_ARGS_DEPTH (targ_ptr)
19222       < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)))
19223     /* targ_ptr only has the innermost template args, so add the outer ones
19224        from tmpl, which could be either a partial instantiation or gen_tmpl (in
19225        the case of a non-dependent call within a template definition).  */
19226     targ_ptr = (add_outermost_template_args
19227 		(DECL_TI_ARGS (DECL_TEMPLATE_RESULT (tmpl)),
19228 		 targ_ptr));
19229 
19230   /* It would be nice to avoid hashing here and then again in tsubst_decl,
19231      but it doesn't seem to be on the hot path.  */
19232   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
19233 
19234   gcc_assert (tmpl == gen_tmpl
19235 	      || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
19236 		  == spec)
19237 	      || fndecl == NULL_TREE);
19238 
19239   if (spec != NULL_TREE)
19240     {
19241       if (FNDECL_HAS_ACCESS_ERRORS (spec))
19242 	{
19243 	  if (complain & tf_error)
19244 	    recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
19245 	  return error_mark_node;
19246 	}
19247       return spec;
19248     }
19249 
19250   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
19251 			       complain))
19252     return error_mark_node;
19253 
19254   /* We are building a FUNCTION_DECL, during which the access of its
19255      parameters and return types have to be checked.  However this
19256      FUNCTION_DECL which is the desired context for access checking
19257      is not built yet.  We solve this chicken-and-egg problem by
19258      deferring all checks until we have the FUNCTION_DECL.  */
19259   push_deferring_access_checks (dk_deferred);
19260 
19261   /* Instantiation of the function happens in the context of the function
19262      template, not the context of the overload resolution we're doing.  */
19263   push_to_top_level ();
19264   /* If there are dependent arguments, e.g. because we're doing partial
19265      ordering, make sure processing_template_decl stays set.  */
19266   if (uses_template_parms (targ_ptr))
19267     ++processing_template_decl;
19268   if (DECL_CLASS_SCOPE_P (gen_tmpl))
19269     {
19270       tree ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
19271 				   complain, gen_tmpl, true);
19272       push_nested_class (ctx);
19273     }
19274 
19275   tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
19276 
19277   fndecl = NULL_TREE;
19278   if (VAR_P (pattern))
19279     {
19280       /* We need to determine if we're using a partial or explicit
19281 	 specialization now, because the type of the variable could be
19282 	 different.  */
19283       tree tid = lookup_template_variable (gen_tmpl, targ_ptr);
19284       tree elt = most_specialized_partial_spec (tid, complain);
19285       if (elt == error_mark_node)
19286 	pattern = error_mark_node;
19287       else if (elt)
19288 	{
19289 	  tree partial_tmpl = TREE_VALUE (elt);
19290 	  tree partial_args = TREE_PURPOSE (elt);
19291 	  tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
19292 	  fndecl = tsubst (partial_pat, partial_args, complain, gen_tmpl);
19293 	}
19294     }
19295 
19296   /* Substitute template parameters to obtain the specialization.  */
19297   if (fndecl == NULL_TREE)
19298     fndecl = tsubst (pattern, targ_ptr, complain, gen_tmpl);
19299   if (DECL_CLASS_SCOPE_P (gen_tmpl))
19300     pop_nested_class ();
19301   pop_from_top_level ();
19302 
19303   if (fndecl == error_mark_node)
19304     {
19305       pop_deferring_access_checks ();
19306       return error_mark_node;
19307     }
19308 
19309   /* The DECL_TI_TEMPLATE should always be the immediate parent
19310      template, not the most general template.  */
19311   DECL_TI_TEMPLATE (fndecl) = tmpl;
19312   DECL_TI_ARGS (fndecl) = targ_ptr;
19313 
19314   /* Now we know the specialization, compute access previously
19315      deferred.  Do no access control for inheriting constructors,
19316      as we already checked access for the inherited constructor.  */
19317   if (!(flag_new_inheriting_ctors
19318 	&& DECL_INHERITED_CTOR (fndecl)))
19319     {
19320       push_access_scope (fndecl);
19321       if (!perform_deferred_access_checks (complain))
19322 	access_ok = false;
19323       pop_access_scope (fndecl);
19324     }
19325   pop_deferring_access_checks ();
19326 
19327   /* If we've just instantiated the main entry point for a function,
19328      instantiate all the alternate entry points as well.  We do this
19329      by cloning the instantiation of the main entry point, not by
19330      instantiating the template clones.  */
19331   if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
19332     clone_function_decl (fndecl, /*update_methods=*/false);
19333 
19334   if (!access_ok)
19335     {
19336       if (!(complain & tf_error))
19337 	{
19338 	  /* Remember to reinstantiate when we're out of SFINAE so the user
19339 	     can see the errors.  */
19340 	  FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
19341 	}
19342       return error_mark_node;
19343     }
19344   return fndecl;
19345 }
19346 
19347 /* Wrapper for instantiate_template_1.  */
19348 
19349 tree
instantiate_template(tree tmpl,tree orig_args,tsubst_flags_t complain)19350 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
19351 {
19352   tree ret;
19353   timevar_push (TV_TEMPLATE_INST);
19354   ret = instantiate_template_1 (tmpl, orig_args,  complain);
19355   timevar_pop (TV_TEMPLATE_INST);
19356   return ret;
19357 }
19358 
19359 /* Instantiate the alias template TMPL with ARGS.  Also push a template
19360    instantiation level, which instantiate_template doesn't do because
19361    functions and variables have sufficient context established by the
19362    callers.  */
19363 
19364 static tree
instantiate_alias_template(tree tmpl,tree args,tsubst_flags_t complain)19365 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
19366 {
19367   if (tmpl == error_mark_node || args == error_mark_node)
19368     return error_mark_node;
19369   if (!push_tinst_level (tmpl, args))
19370     return error_mark_node;
19371 
19372   args =
19373     coerce_innermost_template_parms (DECL_TEMPLATE_PARMS (tmpl),
19374 				     args, tmpl, complain,
19375 				     /*require_all_args=*/true,
19376 				     /*use_default_args=*/true);
19377 
19378   tree r = instantiate_template (tmpl, args, complain);
19379   pop_tinst_level ();
19380 
19381   return r;
19382 }
19383 
19384 /* PARM is a template parameter pack for FN.  Returns true iff
19385    PARM is used in a deducible way in the argument list of FN.  */
19386 
19387 static bool
pack_deducible_p(tree parm,tree fn)19388 pack_deducible_p (tree parm, tree fn)
19389 {
19390   tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
19391   for (; t; t = TREE_CHAIN (t))
19392     {
19393       tree type = TREE_VALUE (t);
19394       tree packs;
19395       if (!PACK_EXPANSION_P (type))
19396 	continue;
19397       for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
19398 	   packs; packs = TREE_CHAIN (packs))
19399 	if (template_args_equal (TREE_VALUE (packs), parm))
19400 	  {
19401 	    /* The template parameter pack is used in a function parameter
19402 	       pack.  If this is the end of the parameter list, the
19403 	       template parameter pack is deducible.  */
19404 	    if (TREE_CHAIN (t) == void_list_node)
19405 	      return true;
19406 	    else
19407 	      /* Otherwise, not.  Well, it could be deduced from
19408 		 a non-pack parameter, but doing so would end up with
19409 		 a deduction mismatch, so don't bother.  */
19410 	      return false;
19411 	  }
19412     }
19413   /* The template parameter pack isn't used in any function parameter
19414      packs, but it might be used deeper, e.g. tuple<Args...>.  */
19415   return true;
19416 }
19417 
19418 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
19419    NARGS elements of the arguments that are being used when calling
19420    it.  TARGS is a vector into which the deduced template arguments
19421    are placed.
19422 
19423    Returns either a FUNCTION_DECL for the matching specialization of FN or
19424    NULL_TREE if no suitable specialization can be found.  If EXPLAIN_P is
19425    true, diagnostics will be printed to explain why it failed.
19426 
19427    If FN is a conversion operator, or we are trying to produce a specific
19428    specialization, RETURN_TYPE is the return type desired.
19429 
19430    The EXPLICIT_TARGS are explicit template arguments provided via a
19431    template-id.
19432 
19433    The parameter STRICT is one of:
19434 
19435    DEDUCE_CALL:
19436      We are deducing arguments for a function call, as in
19437      [temp.deduct.call].  If RETURN_TYPE is non-null, we are
19438      deducing arguments for a call to the result of a conversion
19439      function template, as in [over.call.object].
19440 
19441    DEDUCE_CONV:
19442      We are deducing arguments for a conversion function, as in
19443      [temp.deduct.conv].
19444 
19445    DEDUCE_EXACT:
19446      We are deducing arguments when doing an explicit instantiation
19447      as in [temp.explicit], when determining an explicit specialization
19448      as in [temp.expl.spec], or when taking the address of a function
19449      template, as in [temp.deduct.funcaddr].  */
19450 
19451 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)19452 fn_type_unification (tree fn,
19453 		     tree explicit_targs,
19454 		     tree targs,
19455 		     const tree *args,
19456 		     unsigned int nargs,
19457 		     tree return_type,
19458 		     unification_kind_t strict,
19459 		     int flags,
19460 		     bool explain_p,
19461 		     bool decltype_p)
19462 {
19463   tree parms;
19464   tree fntype;
19465   tree decl = NULL_TREE;
19466   tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
19467   bool ok;
19468   static int deduction_depth;
19469 
19470   tree orig_fn = fn;
19471   if (flag_new_inheriting_ctors)
19472     fn = strip_inheriting_ctors (fn);
19473 
19474   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
19475   tree r = error_mark_node;
19476 
19477   tree full_targs = targs;
19478   if (TMPL_ARGS_DEPTH (targs)
19479       < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (fn)))
19480     full_targs = (add_outermost_template_args
19481 		  (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (fn)),
19482 		   targs));
19483 
19484   if (decltype_p)
19485     complain |= tf_decltype;
19486 
19487   /* In C++0x, it's possible to have a function template whose type depends
19488      on itself recursively.  This is most obvious with decltype, but can also
19489      occur with enumeration scope (c++/48969).  So we need to catch infinite
19490      recursion and reject the substitution at deduction time; this function
19491      will return error_mark_node for any repeated substitution.
19492 
19493      This also catches excessive recursion such as when f<N> depends on
19494      f<N-1> across all integers, and returns error_mark_node for all the
19495      substitutions back up to the initial one.
19496 
19497      This is, of course, not reentrant.  */
19498   if (excessive_deduction_depth)
19499     return error_mark_node;
19500   ++deduction_depth;
19501 
19502   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
19503 
19504   fntype = TREE_TYPE (fn);
19505   if (explicit_targs)
19506     {
19507       /* [temp.deduct]
19508 
19509 	 The specified template arguments must match the template
19510 	 parameters in kind (i.e., type, nontype, template), and there
19511 	 must not be more arguments than there are parameters;
19512 	 otherwise type deduction fails.
19513 
19514 	 Nontype arguments must match the types of the corresponding
19515 	 nontype template parameters, or must be convertible to the
19516 	 types of the corresponding nontype parameters as specified in
19517 	 _temp.arg.nontype_, otherwise type deduction fails.
19518 
19519 	 All references in the function type of the function template
19520 	 to the corresponding template parameters are replaced by the
19521 	 specified template argument values.  If a substitution in a
19522 	 template parameter or in the function type of the function
19523 	 template results in an invalid type, type deduction fails.  */
19524       int i, len = TREE_VEC_LENGTH (tparms);
19525       location_t loc = input_location;
19526       bool incomplete = false;
19527 
19528       if (explicit_targs == error_mark_node)
19529 	goto fail;
19530 
19531       if (TMPL_ARGS_DEPTH (explicit_targs)
19532 	  < TMPL_ARGS_DEPTH (full_targs))
19533 	explicit_targs = add_outermost_template_args (full_targs,
19534 						      explicit_targs);
19535 
19536       /* Adjust any explicit template arguments before entering the
19537 	 substitution context.  */
19538       explicit_targs
19539 	= (coerce_template_parms (tparms, explicit_targs, NULL_TREE,
19540 				  complain,
19541 				  /*require_all_args=*/false,
19542 				  /*use_default_args=*/false));
19543       if (explicit_targs == error_mark_node)
19544 	goto fail;
19545 
19546       /* Substitute the explicit args into the function type.  This is
19547 	 necessary so that, for instance, explicitly declared function
19548 	 arguments can match null pointed constants.  If we were given
19549 	 an incomplete set of explicit args, we must not do semantic
19550 	 processing during substitution as we could create partial
19551 	 instantiations.  */
19552       for (i = 0; i < len; i++)
19553         {
19554           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
19555           bool parameter_pack = false;
19556 	  tree targ = TREE_VEC_ELT (explicit_targs, i);
19557 
19558           /* Dig out the actual parm.  */
19559           if (TREE_CODE (parm) == TYPE_DECL
19560               || TREE_CODE (parm) == TEMPLATE_DECL)
19561             {
19562               parm = TREE_TYPE (parm);
19563               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
19564             }
19565           else if (TREE_CODE (parm) == PARM_DECL)
19566             {
19567               parm = DECL_INITIAL (parm);
19568               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
19569             }
19570 
19571 	  if (!parameter_pack && targ == NULL_TREE)
19572 	    /* No explicit argument for this template parameter.  */
19573 	    incomplete = true;
19574 
19575           if (parameter_pack && pack_deducible_p (parm, fn))
19576             {
19577               /* Mark the argument pack as "incomplete". We could
19578                  still deduce more arguments during unification.
19579 	         We remove this mark in type_unification_real.  */
19580               if (targ)
19581                 {
19582                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
19583                   ARGUMENT_PACK_EXPLICIT_ARGS (targ)
19584                     = ARGUMENT_PACK_ARGS (targ);
19585                 }
19586 
19587               /* We have some incomplete argument packs.  */
19588               incomplete = true;
19589             }
19590         }
19591 
19592       if (!push_tinst_level (fn, explicit_targs))
19593 	{
19594 	  excessive_deduction_depth = true;
19595 	  goto fail;
19596 	}
19597       processing_template_decl += incomplete;
19598       input_location = DECL_SOURCE_LOCATION (fn);
19599       /* Ignore any access checks; we'll see them again in
19600 	 instantiate_template and they might have the wrong
19601 	 access path at this point.  */
19602       push_deferring_access_checks (dk_deferred);
19603       fntype = tsubst (TREE_TYPE (fn), explicit_targs,
19604 		       complain | tf_partial | tf_fndecl_type, NULL_TREE);
19605       pop_deferring_access_checks ();
19606       input_location = loc;
19607       processing_template_decl -= incomplete;
19608       pop_tinst_level ();
19609 
19610       if (fntype == error_mark_node)
19611 	goto fail;
19612 
19613       /* Place the explicitly specified arguments in TARGS.  */
19614       explicit_targs = INNERMOST_TEMPLATE_ARGS (explicit_targs);
19615       for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
19616 	TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
19617     }
19618 
19619   /* Never do unification on the 'this' parameter.  */
19620   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
19621 
19622   if (return_type && strict == DEDUCE_CALL)
19623     {
19624       /* We're deducing for a call to the result of a template conversion
19625          function.  The parms we really want are in return_type.  */
19626       if (POINTER_TYPE_P (return_type))
19627 	return_type = TREE_TYPE (return_type);
19628       parms = TYPE_ARG_TYPES (return_type);
19629     }
19630   else if (return_type)
19631     {
19632       tree *new_args;
19633 
19634       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
19635       new_args = XALLOCAVEC (tree, nargs + 1);
19636       new_args[0] = return_type;
19637       memcpy (new_args + 1, args, nargs * sizeof (tree));
19638       args = new_args;
19639       ++nargs;
19640     }
19641 
19642   /* We allow incomplete unification without an error message here
19643      because the standard doesn't seem to explicitly prohibit it.  Our
19644      callers must be ready to deal with unification failures in any
19645      event.  */
19646 
19647   /* If we aren't explaining yet, push tinst context so we can see where
19648      any errors (e.g. from class instantiations triggered by instantiation
19649      of default template arguments) come from.  If we are explaining, this
19650      context is redundant.  */
19651   if (!explain_p && !push_tinst_level (fn, targs))
19652     {
19653       excessive_deduction_depth = true;
19654       goto fail;
19655     }
19656 
19657   /* type_unification_real will pass back any access checks from default
19658      template argument substitution.  */
19659   vec<deferred_access_check, va_gc> *checks;
19660   checks = NULL;
19661 
19662   ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
19663 			       full_targs, parms, args, nargs, /*subr=*/0,
19664 			       strict, flags, &checks, explain_p);
19665   if (!explain_p)
19666     pop_tinst_level ();
19667   if (!ok)
19668     goto fail;
19669 
19670   /* Now that we have bindings for all of the template arguments,
19671      ensure that the arguments deduced for the template template
19672      parameters have compatible template parameter lists.  We cannot
19673      check this property before we have deduced all template
19674      arguments, because the template parameter types of a template
19675      template parameter might depend on prior template parameters
19676      deduced after the template template parameter.  The following
19677      ill-formed example illustrates this issue:
19678 
19679        template<typename T, template<T> class C> void f(C<5>, T);
19680 
19681        template<int N> struct X {};
19682 
19683        void g() {
19684          f(X<5>(), 5l); // error: template argument deduction fails
19685        }
19686 
19687      The template parameter list of 'C' depends on the template type
19688      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
19689      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
19690      time that we deduce 'C'.  */
19691   if (!template_template_parm_bindings_ok_p
19692            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
19693     {
19694       unify_inconsistent_template_template_parameters (explain_p);
19695       goto fail;
19696     }
19697 
19698   /* All is well so far.  Now, check:
19699 
19700      [temp.deduct]
19701 
19702      When all template arguments have been deduced, all uses of
19703      template parameters in nondeduced contexts are replaced with
19704      the corresponding deduced argument values.  If the
19705      substitution results in an invalid type, as described above,
19706      type deduction fails.  */
19707   if (!push_tinst_level (fn, targs))
19708     {
19709       excessive_deduction_depth = true;
19710       goto fail;
19711     }
19712 
19713   /* Also collect access checks from the instantiation.  */
19714   reopen_deferring_access_checks (checks);
19715 
19716   decl = instantiate_template (fn, targs, complain);
19717 
19718   checks = get_deferred_access_checks ();
19719   pop_deferring_access_checks ();
19720 
19721   pop_tinst_level ();
19722 
19723   if (decl == error_mark_node)
19724     goto fail;
19725 
19726   /* Now perform any access checks encountered during substitution.  */
19727   push_access_scope (decl);
19728   ok = perform_access_checks (checks, complain);
19729   pop_access_scope (decl);
19730   if (!ok)
19731     goto fail;
19732 
19733   /* If we're looking for an exact match, check that what we got
19734      is indeed an exact match.  It might not be if some template
19735      parameters are used in non-deduced contexts.  But don't check
19736      for an exact match if we have dependent template arguments;
19737      in that case we're doing partial ordering, and we already know
19738      that we have two candidates that will provide the actual type.  */
19739   if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
19740     {
19741       tree substed = TREE_TYPE (decl);
19742       unsigned int i;
19743 
19744       tree sarg
19745 	= skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
19746       if (return_type)
19747 	sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
19748       for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
19749 	if (!same_type_p (args[i], TREE_VALUE (sarg)))
19750 	  {
19751 	    unify_type_mismatch (explain_p, args[i],
19752 				 TREE_VALUE (sarg));
19753 	    goto fail;
19754 	  }
19755     }
19756 
19757   /* After doing deduction with the inherited constructor, actually return an
19758      instantiation of the inheriting constructor.  */
19759   if (orig_fn != fn)
19760     decl = instantiate_template (orig_fn, targs, complain);
19761 
19762   r = decl;
19763 
19764  fail:
19765   --deduction_depth;
19766   if (excessive_deduction_depth)
19767     {
19768       if (deduction_depth == 0)
19769 	/* Reset once we're all the way out.  */
19770 	excessive_deduction_depth = false;
19771     }
19772 
19773   return r;
19774 }
19775 
19776 /* Adjust types before performing type deduction, as described in
19777    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
19778    sections are symmetric.  PARM is the type of a function parameter
19779    or the return type of the conversion function.  ARG is the type of
19780    the argument passed to the call, or the type of the value
19781    initialized with the result of the conversion function.
19782    ARG_EXPR is the original argument expression, which may be null.  */
19783 
19784 static int
maybe_adjust_types_for_deduction(unification_kind_t strict,tree * parm,tree * arg,tree arg_expr)19785 maybe_adjust_types_for_deduction (unification_kind_t strict,
19786 				  tree* parm,
19787 				  tree* arg,
19788 				  tree arg_expr)
19789 {
19790   int result = 0;
19791 
19792   switch (strict)
19793     {
19794     case DEDUCE_CALL:
19795       break;
19796 
19797     case DEDUCE_CONV:
19798       /* Swap PARM and ARG throughout the remainder of this
19799 	 function; the handling is precisely symmetric since PARM
19800 	 will initialize ARG rather than vice versa.  */
19801       std::swap (parm, arg);
19802       break;
19803 
19804     case DEDUCE_EXACT:
19805       /* Core issue #873: Do the DR606 thing (see below) for these cases,
19806 	 too, but here handle it by stripping the reference from PARM
19807 	 rather than by adding it to ARG.  */
19808       if (TREE_CODE (*parm) == REFERENCE_TYPE
19809 	  && TYPE_REF_IS_RVALUE (*parm)
19810 	  && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
19811 	  && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
19812 	  && TREE_CODE (*arg) == REFERENCE_TYPE
19813 	  && !TYPE_REF_IS_RVALUE (*arg))
19814 	*parm = TREE_TYPE (*parm);
19815       /* Nothing else to do in this case.  */
19816       return 0;
19817 
19818     default:
19819       gcc_unreachable ();
19820     }
19821 
19822   if (TREE_CODE (*parm) != REFERENCE_TYPE)
19823     {
19824       /* [temp.deduct.call]
19825 
19826 	 If P is not a reference type:
19827 
19828 	 --If A is an array type, the pointer type produced by the
19829 	 array-to-pointer standard conversion (_conv.array_) is
19830 	 used in place of A for type deduction; otherwise,
19831 
19832 	 --If A is a function type, the pointer type produced by
19833 	 the function-to-pointer standard conversion
19834 	 (_conv.func_) is used in place of A for type deduction;
19835 	 otherwise,
19836 
19837 	 --If A is a cv-qualified type, the top level
19838 	 cv-qualifiers of A's type are ignored for type
19839 	 deduction.  */
19840       if (TREE_CODE (*arg) == ARRAY_TYPE)
19841 	*arg = build_pointer_type (TREE_TYPE (*arg));
19842       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
19843 	*arg = build_pointer_type (*arg);
19844       else
19845 	*arg = TYPE_MAIN_VARIANT (*arg);
19846     }
19847 
19848   /* [14.8.2.1/3 temp.deduct.call], "A forwarding reference is an rvalue
19849      reference to a cv-unqualified template parameter that does not represent a
19850      template parameter of a class template (during class template argument
19851      deduction (13.3.1.8)). If P is a forwarding reference and the argument is
19852      an lvalue, the type "lvalue reference to A" is used in place of A for type
19853      deduction. */
19854   if (TREE_CODE (*parm) == REFERENCE_TYPE
19855       && TYPE_REF_IS_RVALUE (*parm)
19856       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
19857       && !TEMPLATE_TYPE_PARM_FOR_CLASS (TREE_TYPE (*parm))
19858       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
19859       && (arg_expr ? lvalue_p (arg_expr)
19860 	  /* try_one_overload doesn't provide an arg_expr, but
19861 	     functions are always lvalues.  */
19862 	  : TREE_CODE (*arg) == FUNCTION_TYPE))
19863     *arg = build_reference_type (*arg);
19864 
19865   /* [temp.deduct.call]
19866 
19867      If P is a cv-qualified type, the top level cv-qualifiers
19868      of P's type are ignored for type deduction.  If P is a
19869      reference type, the type referred to by P is used for
19870      type deduction.  */
19871   *parm = TYPE_MAIN_VARIANT (*parm);
19872   if (TREE_CODE (*parm) == REFERENCE_TYPE)
19873     {
19874       *parm = TREE_TYPE (*parm);
19875       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
19876     }
19877 
19878   /* DR 322. For conversion deduction, remove a reference type on parm
19879      too (which has been swapped into ARG).  */
19880   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
19881     *arg = TREE_TYPE (*arg);
19882 
19883   return result;
19884 }
19885 
19886 /* Subroutine of unify_one_argument.  PARM is a function parameter of a
19887    template which does contain any deducible template parameters; check if
19888    ARG is a suitable match for it.  STRICT, FLAGS and EXPLAIN_P are as in
19889    unify_one_argument.  */
19890 
19891 static int
check_non_deducible_conversion(tree parm,tree arg,int strict,int flags,bool explain_p)19892 check_non_deducible_conversion (tree parm, tree arg, int strict,
19893 				int flags, bool explain_p)
19894 {
19895   tree type;
19896 
19897   if (!TYPE_P (arg))
19898     type = TREE_TYPE (arg);
19899   else
19900     type = arg;
19901 
19902   if (same_type_p (parm, type))
19903     return unify_success (explain_p);
19904 
19905   if (strict == DEDUCE_CONV)
19906     {
19907       if (can_convert_arg (type, parm, NULL_TREE, flags,
19908 			   explain_p ? tf_warning_or_error : tf_none))
19909 	return unify_success (explain_p);
19910     }
19911   else if (strict != DEDUCE_EXACT)
19912     {
19913       if (can_convert_arg (parm, type,
19914 			   TYPE_P (arg) ? NULL_TREE : arg,
19915 			   flags, explain_p ? tf_warning_or_error : tf_none))
19916 	return unify_success (explain_p);
19917     }
19918 
19919   if (strict == DEDUCE_EXACT)
19920     return unify_type_mismatch (explain_p, parm, arg);
19921   else
19922     return unify_arg_conversion (explain_p, parm, type, arg);
19923 }
19924 
19925 static bool uses_deducible_template_parms (tree type);
19926 
19927 /* Returns true iff the expression EXPR is one from which a template
19928    argument can be deduced.  In other words, if it's an undecorated
19929    use of a template non-type parameter.  */
19930 
19931 static bool
deducible_expression(tree expr)19932 deducible_expression (tree expr)
19933 {
19934   /* Strip implicit conversions.  */
19935   while (CONVERT_EXPR_P (expr))
19936     expr = TREE_OPERAND (expr, 0);
19937   return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
19938 }
19939 
19940 /* Returns true iff the array domain DOMAIN uses a template parameter in a
19941    deducible way; that is, if it has a max value of <PARM> - 1.  */
19942 
19943 static bool
deducible_array_bound(tree domain)19944 deducible_array_bound (tree domain)
19945 {
19946   if (domain == NULL_TREE)
19947     return false;
19948 
19949   tree max = TYPE_MAX_VALUE (domain);
19950   if (TREE_CODE (max) != MINUS_EXPR)
19951     return false;
19952 
19953   return deducible_expression (TREE_OPERAND (max, 0));
19954 }
19955 
19956 /* Returns true iff the template arguments ARGS use a template parameter
19957    in a deducible way.  */
19958 
19959 static bool
deducible_template_args(tree args)19960 deducible_template_args (tree args)
19961 {
19962   for (int i = 0; i < TREE_VEC_LENGTH (args); ++i)
19963     {
19964       bool deducible;
19965       tree elt = TREE_VEC_ELT (args, i);
19966       if (ARGUMENT_PACK_P (elt))
19967 	deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
19968       else
19969 	{
19970 	  if (PACK_EXPANSION_P (elt))
19971 	    elt = PACK_EXPANSION_PATTERN (elt);
19972 	  if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
19973 	    deducible = true;
19974 	  else if (TYPE_P (elt))
19975 	    deducible = uses_deducible_template_parms (elt);
19976 	  else
19977 	    deducible = deducible_expression (elt);
19978 	}
19979       if (deducible)
19980 	return true;
19981     }
19982   return false;
19983 }
19984 
19985 /* Returns true iff TYPE contains any deducible references to template
19986    parameters, as per 14.8.2.5.  */
19987 
19988 static bool
uses_deducible_template_parms(tree type)19989 uses_deducible_template_parms (tree type)
19990 {
19991   if (PACK_EXPANSION_P (type))
19992     type = PACK_EXPANSION_PATTERN (type);
19993 
19994   /* T
19995      cv-list T
19996      TT<T>
19997      TT<i>
19998      TT<> */
19999   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
20000       || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
20001     return true;
20002 
20003   /* T*
20004      T&
20005      T&&  */
20006   if (POINTER_TYPE_P (type))
20007     return uses_deducible_template_parms (TREE_TYPE (type));
20008 
20009   /* T[integer-constant ]
20010      type [i]  */
20011   if (TREE_CODE (type) == ARRAY_TYPE)
20012     return (uses_deducible_template_parms (TREE_TYPE (type))
20013 	    || deducible_array_bound (TYPE_DOMAIN (type)));
20014 
20015   /* T type ::*
20016      type T::*
20017      T T::*
20018      T (type ::*)()
20019      type (T::*)()
20020      type (type ::*)(T)
20021      type (T::*)(T)
20022      T (type ::*)(T)
20023      T (T::*)()
20024      T (T::*)(T) */
20025   if (TYPE_PTRMEM_P (type))
20026     return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
20027 	    || (uses_deducible_template_parms
20028 		(TYPE_PTRMEM_POINTED_TO_TYPE (type))));
20029 
20030   /* template-name <T> (where template-name refers to a class template)
20031      template-name <i> (where template-name refers to a class template) */
20032   if (CLASS_TYPE_P (type)
20033       && CLASSTYPE_TEMPLATE_INFO (type)
20034       && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
20035     return deducible_template_args (INNERMOST_TEMPLATE_ARGS
20036 				    (CLASSTYPE_TI_ARGS (type)));
20037 
20038   /* type (T)
20039      T()
20040      T(T)  */
20041   if (TREE_CODE (type) == FUNCTION_TYPE
20042       || TREE_CODE (type) == METHOD_TYPE)
20043     {
20044       if (uses_deducible_template_parms (TREE_TYPE (type)))
20045 	return true;
20046       tree parm = TYPE_ARG_TYPES (type);
20047       if (TREE_CODE (type) == METHOD_TYPE)
20048 	parm = TREE_CHAIN (parm);
20049       for (; parm; parm = TREE_CHAIN (parm))
20050 	if (uses_deducible_template_parms (TREE_VALUE (parm)))
20051 	  return true;
20052     }
20053 
20054   return false;
20055 }
20056 
20057 /* Subroutine of type_unification_real and unify_pack_expansion to
20058    handle unification of a single P/A pair.  Parameters are as
20059    for those functions.  */
20060 
20061 static int
unify_one_argument(tree tparms,tree targs,tree parm,tree arg,int subr,unification_kind_t strict,bool explain_p)20062 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
20063 		    int subr, unification_kind_t strict,
20064 		    bool explain_p)
20065 {
20066   tree arg_expr = NULL_TREE;
20067   int arg_strict;
20068 
20069   if (arg == error_mark_node || parm == error_mark_node)
20070     return unify_invalid (explain_p);
20071   if (arg == unknown_type_node)
20072     /* We can't deduce anything from this, but we might get all the
20073        template args from other function args.  */
20074     return unify_success (explain_p);
20075 
20076   /* Implicit conversions (Clause 4) will be performed on a function
20077      argument to convert it to the type of the corresponding function
20078      parameter if the parameter type contains no template-parameters that
20079      participate in template argument deduction.  */
20080   if (strict != DEDUCE_EXACT
20081       && TYPE_P (parm) && !uses_deducible_template_parms (parm))
20082     /* For function parameters with no deducible template parameters,
20083        just return.  We'll check non-dependent conversions later.  */
20084     return unify_success (explain_p);
20085 
20086   switch (strict)
20087     {
20088     case DEDUCE_CALL:
20089       arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
20090 		    | UNIFY_ALLOW_MORE_CV_QUAL
20091 		    | UNIFY_ALLOW_DERIVED);
20092       break;
20093 
20094     case DEDUCE_CONV:
20095       arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
20096       break;
20097 
20098     case DEDUCE_EXACT:
20099       arg_strict = UNIFY_ALLOW_NONE;
20100       break;
20101 
20102     default:
20103       gcc_unreachable ();
20104     }
20105 
20106   /* We only do these transformations if this is the top-level
20107      parameter_type_list in a call or declaration matching; in other
20108      situations (nested function declarators, template argument lists) we
20109      won't be comparing a type to an expression, and we don't do any type
20110      adjustments.  */
20111   if (!subr)
20112     {
20113       if (!TYPE_P (arg))
20114 	{
20115 	  gcc_assert (TREE_TYPE (arg) != NULL_TREE);
20116 	  if (type_unknown_p (arg))
20117 	    {
20118 	      /* [temp.deduct.type] A template-argument can be
20119 		 deduced from a pointer to function or pointer
20120 		 to member function argument if the set of
20121 		 overloaded functions does not contain function
20122 		 templates and at most one of a set of
20123 		 overloaded functions provides a unique
20124 		 match.  */
20125 	      resolve_overloaded_unification (tparms, targs, parm,
20126 					      arg, strict,
20127 					      arg_strict, explain_p);
20128 	      /* If a unique match was not found, this is a
20129 	         non-deduced context, so we still succeed. */
20130 	      return unify_success (explain_p);
20131 	    }
20132 
20133 	  arg_expr = arg;
20134 	  arg = unlowered_expr_type (arg);
20135 	  if (arg == error_mark_node)
20136 	    return unify_invalid (explain_p);
20137 	}
20138 
20139       arg_strict |=
20140 	maybe_adjust_types_for_deduction (strict, &parm, &arg, arg_expr);
20141     }
20142   else
20143     if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
20144 	!= (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
20145       return unify_template_argument_mismatch (explain_p, parm, arg);
20146 
20147   /* For deduction from an init-list we need the actual list.  */
20148   if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
20149     arg = arg_expr;
20150   return unify (tparms, targs, parm, arg, arg_strict, explain_p);
20151 }
20152 
20153 /* for_each_template_parm callback that always returns 0.  */
20154 
20155 static int
zero_r(tree,void *)20156 zero_r (tree, void *)
20157 {
20158   return 0;
20159 }
20160 
20161 /* for_each_template_parm any_fn callback to handle deduction of a template
20162    type argument from the type of an array bound.  */
20163 
20164 static int
array_deduction_r(tree t,void * data)20165 array_deduction_r (tree t, void *data)
20166 {
20167   tree_pair_p d = (tree_pair_p)data;
20168   tree &tparms = d->purpose;
20169   tree &targs = d->value;
20170 
20171   if (TREE_CODE (t) == ARRAY_TYPE)
20172     if (tree dom = TYPE_DOMAIN (t))
20173       if (tree max = TYPE_MAX_VALUE (dom))
20174 	{
20175 	  if (TREE_CODE (max) == MINUS_EXPR)
20176 	    max = TREE_OPERAND (max, 0);
20177 	  if (TREE_CODE (max) == TEMPLATE_PARM_INDEX)
20178 	    unify (tparms, targs, TREE_TYPE (max), size_type_node,
20179 		   UNIFY_ALLOW_NONE, /*explain*/false);
20180 	}
20181 
20182   /* Keep walking.  */
20183   return 0;
20184 }
20185 
20186 /* Try to deduce any not-yet-deduced template type arguments from the type of
20187    an array bound.  This is handled separately from unify because 14.8.2.5 says
20188    "The type of a type parameter is only deduced from an array bound if it is
20189    not otherwise deduced."  */
20190 
20191 static void
try_array_deduction(tree tparms,tree targs,tree parm)20192 try_array_deduction (tree tparms, tree targs, tree parm)
20193 {
20194   tree_pair_s data = { tparms, targs };
20195   hash_set<tree> visited;
20196   for_each_template_parm (parm, zero_r, &data, &visited,
20197 			  /*nondeduced*/false, array_deduction_r);
20198 }
20199 
20200 /* Returns how many levels of { } INIT contains.  */
20201 
20202 static int
braced_init_depth(tree init)20203 braced_init_depth (tree init)
20204 {
20205   if (!init || !BRACE_ENCLOSED_INITIALIZER_P (init))
20206     return 0;
20207   unsigned i; tree val;
20208   unsigned max = 0;
20209   FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (init), i, val)
20210     {
20211       unsigned elt_d = braced_init_depth (val);
20212       if (elt_d > max)
20213 	max = elt_d;
20214     }
20215   return max + 1;
20216 }
20217 
20218 /* Most parms like fn_type_unification.
20219 
20220    If SUBR is 1, we're being called recursively (to unify the
20221    arguments of a function or method parameter of a function
20222    template).
20223 
20224    CHECKS is a pointer to a vector of access checks encountered while
20225    substituting default template arguments.  */
20226 
20227 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)20228 type_unification_real (tree tparms,
20229 		       tree full_targs,
20230 		       tree xparms,
20231 		       const tree *xargs,
20232 		       unsigned int xnargs,
20233 		       int subr,
20234 		       unification_kind_t strict,
20235 		       int flags,
20236 		       vec<deferred_access_check, va_gc> **checks,
20237 		       bool explain_p)
20238 {
20239   tree parm, arg;
20240   int i;
20241   int ntparms = TREE_VEC_LENGTH (tparms);
20242   int saw_undeduced = 0;
20243   tree parms;
20244   const tree *args;
20245   unsigned int nargs;
20246   unsigned int ia;
20247 
20248   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
20249   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
20250   gcc_assert (ntparms > 0);
20251 
20252   tree targs = INNERMOST_TEMPLATE_ARGS (full_targs);
20253 
20254   /* Reset the number of non-defaulted template arguments contained
20255      in TARGS.  */
20256   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
20257 
20258  again:
20259   parms = xparms;
20260   args = xargs;
20261   nargs = xnargs;
20262 
20263   ia = 0;
20264   while (parms && parms != void_list_node
20265 	 && ia < nargs)
20266     {
20267       parm = TREE_VALUE (parms);
20268 
20269       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
20270 	  && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
20271 	/* For a function parameter pack that occurs at the end of the
20272 	   parameter-declaration-list, the type A of each remaining
20273 	   argument of the call is compared with the type P of the
20274 	   declarator-id of the function parameter pack.  */
20275 	break;
20276 
20277       parms = TREE_CHAIN (parms);
20278 
20279       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
20280 	/* For a function parameter pack that does not occur at the
20281 	   end of the parameter-declaration-list, the type of the
20282 	   parameter pack is a non-deduced context.  */
20283 	continue;
20284 
20285       arg = args[ia];
20286       ++ia;
20287 
20288       if (unify_one_argument (tparms, full_targs, parm, arg, subr, strict,
20289 			      explain_p))
20290 	return 1;
20291     }
20292 
20293   if (parms
20294       && parms != void_list_node
20295       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
20296     {
20297       /* Unify the remaining arguments with the pack expansion type.  */
20298       tree argvec;
20299       tree parmvec = make_tree_vec (1);
20300 
20301       /* Allocate a TREE_VEC and copy in all of the arguments */
20302       argvec = make_tree_vec (nargs - ia);
20303       for (i = 0; ia < nargs; ++ia, ++i)
20304 	TREE_VEC_ELT (argvec, i) = args[ia];
20305 
20306       /* Copy the parameter into parmvec.  */
20307       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
20308       if (unify_pack_expansion (tparms, full_targs, parmvec, argvec, strict,
20309                                 /*subr=*/subr, explain_p))
20310         return 1;
20311 
20312       /* Advance to the end of the list of parameters.  */
20313       parms = TREE_CHAIN (parms);
20314     }
20315 
20316   /* Fail if we've reached the end of the parm list, and more args
20317      are present, and the parm list isn't variadic.  */
20318   if (ia < nargs && parms == void_list_node)
20319     return unify_too_many_arguments (explain_p, nargs, ia);
20320   /* Fail if parms are left and they don't have default values and
20321      they aren't all deduced as empty packs (c++/57397).  This is
20322      consistent with sufficient_parms_p.  */
20323   if (parms && parms != void_list_node
20324       && TREE_PURPOSE (parms) == NULL_TREE)
20325     {
20326       unsigned int count = nargs;
20327       tree p = parms;
20328       bool type_pack_p;
20329       do
20330 	{
20331 	  type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
20332 	  if (!type_pack_p)
20333 	    count++;
20334 	  p = TREE_CHAIN (p);
20335 	}
20336       while (p && p != void_list_node);
20337       if (count != nargs)
20338 	return unify_too_few_arguments (explain_p, ia, count,
20339 					type_pack_p);
20340     }
20341 
20342   if (!subr)
20343     {
20344       tsubst_flags_t complain = (explain_p
20345 				 ? tf_warning_or_error
20346 				 : tf_none);
20347       bool tried_array_deduction = (cxx_dialect < cxx17);
20348 
20349       for (i = 0; i < ntparms; i++)
20350 	{
20351 	  tree targ = TREE_VEC_ELT (targs, i);
20352 	  tree tparm = TREE_VEC_ELT (tparms, i);
20353 
20354 	  /* Clear the "incomplete" flags on all argument packs now so that
20355 	     substituting them into later default arguments works.  */
20356 	  if (targ && ARGUMENT_PACK_P (targ))
20357             {
20358               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
20359               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
20360             }
20361 
20362 	  if (targ || tparm == error_mark_node)
20363 	    continue;
20364 	  tparm = TREE_VALUE (tparm);
20365 
20366 	  if (TREE_CODE (tparm) == TYPE_DECL
20367 	      && !tried_array_deduction)
20368 	    {
20369 	      try_array_deduction (tparms, targs, xparms);
20370 	      tried_array_deduction = true;
20371 	      if (TREE_VEC_ELT (targs, i))
20372 		continue;
20373 	    }
20374 
20375 	  /* If this is an undeduced nontype parameter that depends on
20376 	     a type parameter, try another pass; its type may have been
20377 	     deduced from a later argument than the one from which
20378 	     this parameter can be deduced.  */
20379 	  if (TREE_CODE (tparm) == PARM_DECL
20380 	      && uses_template_parms (TREE_TYPE (tparm))
20381 	      && saw_undeduced < 2)
20382 	    {
20383 	      saw_undeduced = 1;
20384 	      continue;
20385 	    }
20386 
20387 	  /* Core issue #226 (C++0x) [temp.deduct]:
20388 
20389 	     If a template argument has not been deduced, its
20390 	     default template argument, if any, is used.
20391 
20392 	     When we are in C++98 mode, TREE_PURPOSE will either
20393 	     be NULL_TREE or ERROR_MARK_NODE, so we do not need
20394 	     to explicitly check cxx_dialect here.  */
20395 	  if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
20396 	    /* OK, there is a default argument.  Wait until after the
20397 	       conversion check to do substitution.  */
20398 	    continue;
20399 
20400 	  /* If the type parameter is a parameter pack, then it will
20401 	     be deduced to an empty parameter pack.  */
20402 	  if (template_parameter_pack_p (tparm))
20403 	    {
20404 	      tree arg;
20405 
20406 	      if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
20407 		{
20408 		  arg = make_node (NONTYPE_ARGUMENT_PACK);
20409 		  TREE_CONSTANT (arg) = 1;
20410 		}
20411 	      else
20412 		arg = cxx_make_type (TYPE_ARGUMENT_PACK);
20413 
20414 	      SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
20415 
20416 	      TREE_VEC_ELT (targs, i) = arg;
20417 	      continue;
20418 	    }
20419 
20420 	  return unify_parameter_deduction_failure (explain_p, tparm);
20421 	}
20422 
20423       /* DR 1391: All parameters have args, now check non-dependent parms for
20424 	 convertibility.  */
20425       if (saw_undeduced < 2)
20426 	for (ia = 0, parms = xparms, args = xargs, nargs = xnargs;
20427 	     parms && parms != void_list_node && ia < nargs; )
20428 	  {
20429 	    parm = TREE_VALUE (parms);
20430 
20431 	    if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
20432 		&& (!TREE_CHAIN (parms)
20433 		    || TREE_CHAIN (parms) == void_list_node))
20434 	      /* For a function parameter pack that occurs at the end of the
20435 		 parameter-declaration-list, the type A of each remaining
20436 		 argument of the call is compared with the type P of the
20437 		 declarator-id of the function parameter pack.  */
20438 	      break;
20439 
20440 	    parms = TREE_CHAIN (parms);
20441 
20442 	    if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
20443 	      /* For a function parameter pack that does not occur at the
20444 		 end of the parameter-declaration-list, the type of the
20445 		 parameter pack is a non-deduced context.  */
20446 	      continue;
20447 
20448 	    arg = args[ia];
20449 	    ++ia;
20450 
20451 	    if (uses_template_parms (parm))
20452 	      continue;
20453 	    /* Workaround for c++/80290: avoid combinatorial explosion on
20454 	       deeply nested braced init-lists.  */
20455 	    if (braced_init_depth (arg) > 2)
20456 	      continue;
20457 	    if (check_non_deducible_conversion (parm, arg, strict, flags,
20458 						explain_p))
20459 	      return 1;
20460 	  }
20461 
20462       /* Now substitute into the default template arguments.  */
20463       for (i = 0; i < ntparms; i++)
20464 	{
20465 	  tree targ = TREE_VEC_ELT (targs, i);
20466 	  tree tparm = TREE_VEC_ELT (tparms, i);
20467 
20468 	  if (targ || tparm == error_mark_node)
20469 	    continue;
20470 	  tree parm = TREE_VALUE (tparm);
20471 	  tree arg = TREE_PURPOSE (tparm);
20472 	  reopen_deferring_access_checks (*checks);
20473 	  location_t save_loc = input_location;
20474 	  if (DECL_P (parm))
20475 	    input_location = DECL_SOURCE_LOCATION (parm);
20476 
20477 	  if (saw_undeduced == 1
20478 	      && TREE_CODE (parm) == PARM_DECL
20479 	      && uses_template_parms (TREE_TYPE (parm)))
20480 	    {
20481 	      /* The type of this non-type parameter depends on undeduced
20482 		 parameters.  Don't try to use its default argument yet,
20483 		 since we might deduce an argument for it on the next pass,
20484 		 but do check whether the arguments we already have cause
20485 		 substitution failure, so that that happens before we try
20486 		 later default arguments (78489).  */
20487 	      ++processing_template_decl;
20488 	      tree type = tsubst (TREE_TYPE (parm), full_targs, complain,
20489 				  NULL_TREE);
20490 	      --processing_template_decl;
20491 	      if (type == error_mark_node)
20492 		arg = error_mark_node;
20493 	      else
20494 		arg = NULL_TREE;
20495 	    }
20496 	  else
20497 	    {
20498 	      /* Even if the call is happening in template context, getting
20499 		 here means it's non-dependent, and a default argument is
20500 		 considered a separate definition under [temp.decls], so we can
20501 		 do this substitution without processing_template_decl.  This
20502 		 is important if the default argument contains something that
20503 		 might be instantiation-dependent like access (87480).  */
20504 	      processing_template_decl_sentinel s;
20505 	      tree substed = NULL_TREE;
20506 	      if (saw_undeduced == 1)
20507 		{
20508 		  /* First instatiate in template context, in case we still
20509 		     depend on undeduced template parameters.  */
20510 		  ++processing_template_decl;
20511 		  substed = tsubst_template_arg (arg, full_targs, complain,
20512 						 NULL_TREE);
20513 		  --processing_template_decl;
20514 		  if (substed != error_mark_node
20515 		      && !uses_template_parms (substed))
20516 		    /* We replaced all the tparms, substitute again out of
20517 		       template context.  */
20518 		    substed = NULL_TREE;
20519 		}
20520 	      if (!substed)
20521 		substed = tsubst_template_arg (arg, full_targs, complain,
20522 					       NULL_TREE);
20523 
20524 	      if (!uses_template_parms (substed))
20525 		arg = convert_template_argument (parm, substed, full_targs,
20526 						 complain, i, NULL_TREE);
20527 	      else if (saw_undeduced == 1)
20528 		arg = NULL_TREE;
20529 	      else
20530 		arg = error_mark_node;
20531 	    }
20532 
20533 	  input_location = save_loc;
20534 	  *checks = get_deferred_access_checks ();
20535 	  pop_deferring_access_checks ();
20536 
20537 	  if (arg == error_mark_node)
20538 	    return 1;
20539 	  else if (arg)
20540 	    {
20541 	      TREE_VEC_ELT (targs, i) = arg;
20542 	      /* The position of the first default template argument,
20543 		 is also the number of non-defaulted arguments in TARGS.
20544 		 Record that.  */
20545 	      if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
20546 		SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
20547 	    }
20548 	}
20549 
20550       if (saw_undeduced++ == 1)
20551 	goto again;
20552     }
20553 
20554   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
20555     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
20556 
20557   return unify_success (explain_p);
20558 }
20559 
20560 /* Subroutine of type_unification_real.  Args are like the variables
20561    at the call site.  ARG is an overloaded function (or template-id);
20562    we try deducing template args from each of the overloads, and if
20563    only one succeeds, we go with that.  Modifies TARGS and returns
20564    true on success.  */
20565 
20566 static bool
resolve_overloaded_unification(tree tparms,tree targs,tree parm,tree arg,unification_kind_t strict,int sub_strict,bool explain_p)20567 resolve_overloaded_unification (tree tparms,
20568 				tree targs,
20569 				tree parm,
20570 				tree arg,
20571 				unification_kind_t strict,
20572 				int sub_strict,
20573 			        bool explain_p)
20574 {
20575   tree tempargs = copy_node (targs);
20576   int good = 0;
20577   tree goodfn = NULL_TREE;
20578   bool addr_p;
20579 
20580   if (TREE_CODE (arg) == ADDR_EXPR)
20581     {
20582       arg = TREE_OPERAND (arg, 0);
20583       addr_p = true;
20584     }
20585   else
20586     addr_p = false;
20587 
20588   if (TREE_CODE (arg) == COMPONENT_REF)
20589     /* Handle `&x' where `x' is some static or non-static member
20590        function name.  */
20591     arg = TREE_OPERAND (arg, 1);
20592 
20593   if (TREE_CODE (arg) == OFFSET_REF)
20594     arg = TREE_OPERAND (arg, 1);
20595 
20596   /* Strip baselink information.  */
20597   if (BASELINK_P (arg))
20598     arg = BASELINK_FUNCTIONS (arg);
20599 
20600   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
20601     {
20602       /* If we got some explicit template args, we need to plug them into
20603 	 the affected templates before we try to unify, in case the
20604 	 explicit args will completely resolve the templates in question.  */
20605 
20606       int ok = 0;
20607       tree expl_subargs = TREE_OPERAND (arg, 1);
20608       arg = TREE_OPERAND (arg, 0);
20609 
20610       for (lkp_iterator iter (arg); iter; ++iter)
20611 	{
20612 	  tree fn = *iter;
20613 	  tree subargs, elem;
20614 
20615 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
20616 	    continue;
20617 
20618 	  subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
20619 					   expl_subargs, NULL_TREE, tf_none,
20620 					   /*require_all_args=*/true,
20621 					   /*use_default_args=*/true);
20622 	  if (subargs != error_mark_node
20623 	      && !any_dependent_template_arguments_p (subargs))
20624 	    {
20625 	      elem = TREE_TYPE (instantiate_template (fn, subargs, tf_none));
20626 	      if (try_one_overload (tparms, targs, tempargs, parm,
20627 				    elem, strict, sub_strict, addr_p, explain_p)
20628 		  && (!goodfn || !same_type_p (goodfn, elem)))
20629 		{
20630 		  goodfn = elem;
20631 		  ++good;
20632 		}
20633 	    }
20634 	  else if (subargs)
20635 	    ++ok;
20636 	}
20637       /* If no templates (or more than one) are fully resolved by the
20638 	 explicit arguments, this template-id is a non-deduced context; it
20639 	 could still be OK if we deduce all template arguments for the
20640 	 enclosing call through other arguments.  */
20641       if (good != 1)
20642 	good = ok;
20643     }
20644   else if (TREE_CODE (arg) != OVERLOAD
20645 	   && TREE_CODE (arg) != FUNCTION_DECL)
20646     /* If ARG is, for example, "(0, &f)" then its type will be unknown
20647        -- but the deduction does not succeed because the expression is
20648        not just the function on its own.  */
20649     return false;
20650   else
20651     for (lkp_iterator iter (arg); iter; ++iter)
20652       {
20653 	tree fn = *iter;
20654 	if (try_one_overload (tparms, targs, tempargs, parm, TREE_TYPE (fn),
20655 			      strict, sub_strict, addr_p, explain_p)
20656 	    && (!goodfn || !decls_match (goodfn, fn)))
20657 	  {
20658 	    goodfn = fn;
20659 	    ++good;
20660 	  }
20661       }
20662 
20663   /* [temp.deduct.type] A template-argument can be deduced from a pointer
20664      to function or pointer to member function argument if the set of
20665      overloaded functions does not contain function templates and at most
20666      one of a set of overloaded functions provides a unique match.
20667 
20668      So if we found multiple possibilities, we return success but don't
20669      deduce anything.  */
20670 
20671   if (good == 1)
20672     {
20673       int i = TREE_VEC_LENGTH (targs);
20674       for (; i--; )
20675 	if (TREE_VEC_ELT (tempargs, i))
20676 	  {
20677 	    tree old = TREE_VEC_ELT (targs, i);
20678 	    tree new_ = TREE_VEC_ELT (tempargs, i);
20679 	    if (new_ && old && ARGUMENT_PACK_P (old)
20680 		&& ARGUMENT_PACK_EXPLICIT_ARGS (old))
20681 	      /* Don't forget explicit template arguments in a pack.  */
20682 	      ARGUMENT_PACK_EXPLICIT_ARGS (new_)
20683 		= ARGUMENT_PACK_EXPLICIT_ARGS (old);
20684 	    TREE_VEC_ELT (targs, i) = new_;
20685 	  }
20686     }
20687   if (good)
20688     return true;
20689 
20690   return false;
20691 }
20692 
20693 /* Core DR 115: In contexts where deduction is done and fails, or in
20694    contexts where deduction is not done, if a template argument list is
20695    specified and it, along with any default template arguments, identifies
20696    a single function template specialization, then the template-id is an
20697    lvalue for the function template specialization.  */
20698 
20699 tree
resolve_nondeduced_context(tree orig_expr,tsubst_flags_t complain)20700 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
20701 {
20702   tree expr, offset, baselink;
20703   bool addr;
20704 
20705   if (!type_unknown_p (orig_expr))
20706     return orig_expr;
20707 
20708   expr = orig_expr;
20709   addr = false;
20710   offset = NULL_TREE;
20711   baselink = NULL_TREE;
20712 
20713   if (TREE_CODE (expr) == ADDR_EXPR)
20714     {
20715       expr = TREE_OPERAND (expr, 0);
20716       addr = true;
20717     }
20718   if (TREE_CODE (expr) == OFFSET_REF)
20719     {
20720       offset = expr;
20721       expr = TREE_OPERAND (expr, 1);
20722     }
20723   if (BASELINK_P (expr))
20724     {
20725       baselink = expr;
20726       expr = BASELINK_FUNCTIONS (expr);
20727     }
20728 
20729   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
20730     {
20731       int good = 0;
20732       tree goodfn = NULL_TREE;
20733 
20734       /* If we got some explicit template args, we need to plug them into
20735 	 the affected templates before we try to unify, in case the
20736 	 explicit args will completely resolve the templates in question.  */
20737 
20738       tree expl_subargs = TREE_OPERAND (expr, 1);
20739       tree arg = TREE_OPERAND (expr, 0);
20740       tree badfn = NULL_TREE;
20741       tree badargs = NULL_TREE;
20742 
20743       for (lkp_iterator iter (arg); iter; ++iter)
20744 	{
20745 	  tree fn = *iter;
20746 	  tree subargs, elem;
20747 
20748 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
20749 	    continue;
20750 
20751 	  subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
20752 					   expl_subargs, NULL_TREE, tf_none,
20753 					   /*require_all_args=*/true,
20754 					   /*use_default_args=*/true);
20755 	  if (subargs != error_mark_node
20756 	      && !any_dependent_template_arguments_p (subargs))
20757 	    {
20758 	      elem = instantiate_template (fn, subargs, tf_none);
20759 	      if (elem == error_mark_node)
20760 		{
20761 		  badfn = fn;
20762 		  badargs = subargs;
20763 		}
20764 	      else if (elem && (!goodfn || !decls_match (goodfn, elem)))
20765 		{
20766 		  goodfn = elem;
20767 		  ++good;
20768 		}
20769 	    }
20770 	}
20771       if (good == 1)
20772 	{
20773 	  mark_used (goodfn);
20774 	  expr = goodfn;
20775 	  if (baselink)
20776 	    expr = build_baselink (BASELINK_BINFO (baselink),
20777 				   BASELINK_ACCESS_BINFO (baselink),
20778 				   expr, BASELINK_OPTYPE (baselink));
20779 	  if (offset)
20780 	    {
20781 	      tree base
20782 		= TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
20783 	      expr = build_offset_ref (base, expr, addr, complain);
20784 	    }
20785 	  if (addr)
20786 	    expr = cp_build_addr_expr (expr, complain);
20787 	  return expr;
20788 	}
20789       else if (good == 0 && badargs && (complain & tf_error))
20790 	/* There were no good options and at least one bad one, so let the
20791 	   user know what the problem is.  */
20792 	instantiate_template (badfn, badargs, complain);
20793     }
20794   return orig_expr;
20795 }
20796 
20797 /* Subroutine of resolve_overloaded_unification; does deduction for a single
20798    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
20799    different overloads deduce different arguments for a given parm.
20800    ADDR_P is true if the expression for which deduction is being
20801    performed was of the form "& fn" rather than simply "fn".
20802 
20803    Returns 1 on success.  */
20804 
20805 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)20806 try_one_overload (tree tparms,
20807 		  tree orig_targs,
20808 		  tree targs,
20809 		  tree parm,
20810 		  tree arg,
20811 		  unification_kind_t strict,
20812 		  int sub_strict,
20813 		  bool addr_p,
20814 		  bool explain_p)
20815 {
20816   int nargs;
20817   tree tempargs;
20818   int i;
20819 
20820   if (arg == error_mark_node)
20821     return 0;
20822 
20823   /* [temp.deduct.type] A template-argument can be deduced from a pointer
20824      to function or pointer to member function argument if the set of
20825      overloaded functions does not contain function templates and at most
20826      one of a set of overloaded functions provides a unique match.
20827 
20828      So if this is a template, just return success.  */
20829 
20830   if (uses_template_parms (arg))
20831     return 1;
20832 
20833   if (TREE_CODE (arg) == METHOD_TYPE)
20834     arg = build_ptrmemfunc_type (build_pointer_type (arg));
20835   else if (addr_p)
20836     arg = build_pointer_type (arg);
20837 
20838   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
20839 
20840   /* We don't copy orig_targs for this because if we have already deduced
20841      some template args from previous args, unify would complain when we
20842      try to deduce a template parameter for the same argument, even though
20843      there isn't really a conflict.  */
20844   nargs = TREE_VEC_LENGTH (targs);
20845   tempargs = make_tree_vec (nargs);
20846 
20847   if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
20848     return 0;
20849 
20850   /* First make sure we didn't deduce anything that conflicts with
20851      explicitly specified args.  */
20852   for (i = nargs; i--; )
20853     {
20854       tree elt = TREE_VEC_ELT (tempargs, i);
20855       tree oldelt = TREE_VEC_ELT (orig_targs, i);
20856 
20857       if (!elt)
20858 	/*NOP*/;
20859       else if (uses_template_parms (elt))
20860 	/* Since we're unifying against ourselves, we will fill in
20861 	   template args used in the function parm list with our own
20862 	   template parms.  Discard them.  */
20863 	TREE_VEC_ELT (tempargs, i) = NULL_TREE;
20864       else if (oldelt && ARGUMENT_PACK_P (oldelt))
20865 	{
20866 	  /* Check that the argument at each index of the deduced argument pack
20867 	     is equivalent to the corresponding explicitly specified argument.
20868 	     We may have deduced more arguments than were explicitly specified,
20869 	     and that's OK.  */
20870 
20871 	  /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
20872 	     that's wrong if we deduce the same argument pack from multiple
20873 	     function arguments: it's only incomplete the first time.  */
20874 
20875 	  tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
20876 	  tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
20877 
20878 	  if (TREE_VEC_LENGTH (deduced_pack)
20879 	      < TREE_VEC_LENGTH (explicit_pack))
20880 	    return 0;
20881 
20882 	  for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
20883 	    if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
20884 				      TREE_VEC_ELT (deduced_pack, j)))
20885 	      return 0;
20886 	}
20887       else if (oldelt && !template_args_equal (oldelt, elt))
20888 	return 0;
20889     }
20890 
20891   for (i = nargs; i--; )
20892     {
20893       tree elt = TREE_VEC_ELT (tempargs, i);
20894 
20895       if (elt)
20896 	TREE_VEC_ELT (targs, i) = elt;
20897     }
20898 
20899   return 1;
20900 }
20901 
20902 /* PARM is a template class (perhaps with unbound template
20903    parameters).  ARG is a fully instantiated type.  If ARG can be
20904    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
20905    TARGS are as for unify.  */
20906 
20907 static tree
try_class_unification(tree tparms,tree targs,tree parm,tree arg,bool explain_p)20908 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
20909 		       bool explain_p)
20910 {
20911   tree copy_of_targs;
20912 
20913   if (!CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
20914     return NULL_TREE;
20915   else if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
20916     /* Matches anything.  */;
20917   else if (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
20918 	   != most_general_template (CLASSTYPE_TI_TEMPLATE (parm)))
20919     return NULL_TREE;
20920 
20921   /* We need to make a new template argument vector for the call to
20922      unify.  If we used TARGS, we'd clutter it up with the result of
20923      the attempted unification, even if this class didn't work out.
20924      We also don't want to commit ourselves to all the unifications
20925      we've already done, since unification is supposed to be done on
20926      an argument-by-argument basis.  In other words, consider the
20927      following pathological case:
20928 
20929        template <int I, int J, int K>
20930        struct S {};
20931 
20932        template <int I, int J>
20933        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
20934 
20935        template <int I, int J, int K>
20936        void f(S<I, J, K>, S<I, I, I>);
20937 
20938        void g() {
20939 	 S<0, 0, 0> s0;
20940 	 S<0, 1, 2> s2;
20941 
20942 	 f(s0, s2);
20943        }
20944 
20945      Now, by the time we consider the unification involving `s2', we
20946      already know that we must have `f<0, 0, 0>'.  But, even though
20947      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
20948      because there are two ways to unify base classes of S<0, 1, 2>
20949      with S<I, I, I>.  If we kept the already deduced knowledge, we
20950      would reject the possibility I=1.  */
20951   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
20952 
20953   if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
20954     {
20955       if (unify_bound_ttp_args (tparms, copy_of_targs, parm, arg, explain_p))
20956 	return NULL_TREE;
20957       return arg;
20958     }
20959 
20960   /* If unification failed, we're done.  */
20961   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
20962 	     CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
20963     return NULL_TREE;
20964 
20965   return arg;
20966 }
20967 
20968 /* Given a template type PARM and a class type ARG, find the unique
20969    base type in ARG that is an instance of PARM.  We do not examine
20970    ARG itself; only its base-classes.  If there is not exactly one
20971    appropriate base class, return NULL_TREE.  PARM may be the type of
20972    a partial specialization, as well as a plain template type.  Used
20973    by unify.  */
20974 
20975 static enum template_base_result
get_template_base(tree tparms,tree targs,tree parm,tree arg,bool explain_p,tree * result)20976 get_template_base (tree tparms, tree targs, tree parm, tree arg,
20977 		   bool explain_p, tree *result)
20978 {
20979   tree rval = NULL_TREE;
20980   tree binfo;
20981 
20982   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
20983 
20984   binfo = TYPE_BINFO (complete_type (arg));
20985   if (!binfo)
20986     {
20987       /* The type could not be completed.  */
20988       *result = NULL_TREE;
20989       return tbr_incomplete_type;
20990     }
20991 
20992   /* Walk in inheritance graph order.  The search order is not
20993      important, and this avoids multiple walks of virtual bases.  */
20994   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
20995     {
20996       tree r = try_class_unification (tparms, targs, parm,
20997 				      BINFO_TYPE (binfo), explain_p);
20998 
20999       if (r)
21000 	{
21001 	  /* If there is more than one satisfactory baseclass, then:
21002 
21003 	       [temp.deduct.call]
21004 
21005 	      If they yield more than one possible deduced A, the type
21006 	      deduction fails.
21007 
21008 	     applies.  */
21009 	  if (rval && !same_type_p (r, rval))
21010 	    {
21011 	      *result = NULL_TREE;
21012 	      return tbr_ambiguous_baseclass;
21013 	    }
21014 
21015 	  rval = r;
21016 	}
21017     }
21018 
21019   *result = rval;
21020   return tbr_success;
21021 }
21022 
21023 /* Returns the level of DECL, which declares a template parameter.  */
21024 
21025 static int
template_decl_level(tree decl)21026 template_decl_level (tree decl)
21027 {
21028   switch (TREE_CODE (decl))
21029     {
21030     case TYPE_DECL:
21031     case TEMPLATE_DECL:
21032       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
21033 
21034     case PARM_DECL:
21035       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
21036 
21037     default:
21038       gcc_unreachable ();
21039     }
21040   return 0;
21041 }
21042 
21043 /* Decide whether ARG can be unified with PARM, considering only the
21044    cv-qualifiers of each type, given STRICT as documented for unify.
21045    Returns nonzero iff the unification is OK on that basis.  */
21046 
21047 static int
check_cv_quals_for_unify(int strict,tree arg,tree parm)21048 check_cv_quals_for_unify (int strict, tree arg, tree parm)
21049 {
21050   int arg_quals = cp_type_quals (arg);
21051   int parm_quals = cp_type_quals (parm);
21052 
21053   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
21054       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
21055     {
21056       /*  Although a CVR qualifier is ignored when being applied to a
21057 	  substituted template parameter ([8.3.2]/1 for example), that
21058 	  does not allow us to unify "const T" with "int&" because both
21059 	  types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
21060 	  It is ok when we're allowing additional CV qualifiers
21061 	  at the outer level [14.8.2.1]/3,1st bullet.  */
21062       if ((TREE_CODE (arg) == REFERENCE_TYPE
21063 	   || TREE_CODE (arg) == FUNCTION_TYPE
21064 	   || TREE_CODE (arg) == METHOD_TYPE)
21065 	  && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
21066 	return 0;
21067 
21068       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
21069 	  && (parm_quals & TYPE_QUAL_RESTRICT))
21070 	return 0;
21071     }
21072 
21073   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
21074       && (arg_quals & parm_quals) != parm_quals)
21075     return 0;
21076 
21077   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
21078       && (parm_quals & arg_quals) != arg_quals)
21079     return 0;
21080 
21081   return 1;
21082 }
21083 
21084 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
21085 void
template_parm_level_and_index(tree parm,int * level,int * index)21086 template_parm_level_and_index (tree parm, int* level, int* index)
21087 {
21088   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
21089       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
21090       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
21091     {
21092       *index = TEMPLATE_TYPE_IDX (parm);
21093       *level = TEMPLATE_TYPE_LEVEL (parm);
21094     }
21095   else
21096     {
21097       *index = TEMPLATE_PARM_IDX (parm);
21098       *level = TEMPLATE_PARM_LEVEL (parm);
21099     }
21100 }
21101 
21102 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)			\
21103   do {									\
21104     if (unify (TP, TA, P, A, S, EP))					\
21105       return 1;								\
21106   } while (0)
21107 
21108 /* Unifies the remaining arguments in PACKED_ARGS with the pack
21109    expansion at the end of PACKED_PARMS. Returns 0 if the type
21110    deduction succeeds, 1 otherwise. STRICT is the same as in
21111    fn_type_unification. CALL_ARGS_P is true iff PACKED_ARGS is actually a
21112    function call argument list. We'll need to adjust the arguments to make them
21113    types. SUBR tells us if this is from a recursive call to
21114    type_unification_real, or for comparing two template argument
21115    lists. */
21116 
21117 static int
unify_pack_expansion(tree tparms,tree targs,tree packed_parms,tree packed_args,unification_kind_t strict,bool subr,bool explain_p)21118 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
21119                       tree packed_args, unification_kind_t strict,
21120                       bool subr, bool explain_p)
21121 {
21122   tree parm
21123     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
21124   tree pattern = PACK_EXPANSION_PATTERN (parm);
21125   tree pack, packs = NULL_TREE;
21126   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
21127 
21128   /* Add in any args remembered from an earlier partial instantiation.  */
21129   targs = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (parm), targs);
21130   int levels = TMPL_ARGS_DEPTH (targs);
21131 
21132   packed_args = expand_template_argument_pack (packed_args);
21133 
21134   int len = TREE_VEC_LENGTH (packed_args);
21135 
21136   /* Determine the parameter packs we will be deducing from the
21137      pattern, and record their current deductions.  */
21138   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
21139        pack; pack = TREE_CHAIN (pack))
21140     {
21141       tree parm_pack = TREE_VALUE (pack);
21142       int idx, level;
21143 
21144       /* Only template parameter packs can be deduced, not e.g. function
21145 	 parameter packs or __bases or __integer_pack.  */
21146       if (!TEMPLATE_PARM_P (parm_pack))
21147 	continue;
21148 
21149       /* Determine the index and level of this parameter pack.  */
21150       template_parm_level_and_index (parm_pack, &level, &idx);
21151       if (level < levels)
21152 	continue;
21153 
21154       /* Keep track of the parameter packs and their corresponding
21155          argument packs.  */
21156       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
21157       TREE_TYPE (packs) = make_tree_vec (len - start);
21158     }
21159 
21160   /* Loop through all of the arguments that have not yet been
21161      unified and unify each with the pattern.  */
21162   for (i = start; i < len; i++)
21163     {
21164       tree parm;
21165       bool any_explicit = false;
21166       tree arg = TREE_VEC_ELT (packed_args, i);
21167 
21168       /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
21169 	 or the element of its argument pack at the current index if
21170 	 this argument was explicitly specified.  */
21171       for (pack = packs; pack; pack = TREE_CHAIN (pack))
21172         {
21173           int idx, level;
21174           tree arg, pargs;
21175           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
21176 
21177           arg = NULL_TREE;
21178           if (TREE_VALUE (pack)
21179               && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
21180               && (i - start < TREE_VEC_LENGTH (pargs)))
21181             {
21182               any_explicit = true;
21183               arg = TREE_VEC_ELT (pargs, i - start);
21184             }
21185           TMPL_ARG (targs, level, idx) = arg;
21186         }
21187 
21188       /* If we had explicit template arguments, substitute them into the
21189 	 pattern before deduction.  */
21190       if (any_explicit)
21191 	{
21192 	  /* Some arguments might still be unspecified or dependent.  */
21193 	  bool dependent;
21194 	  ++processing_template_decl;
21195 	  dependent = any_dependent_template_arguments_p (targs);
21196 	  if (!dependent)
21197 	    --processing_template_decl;
21198 	  parm = tsubst (pattern, targs,
21199 			 explain_p ? tf_warning_or_error : tf_none,
21200 			 NULL_TREE);
21201 	  if (dependent)
21202 	    --processing_template_decl;
21203 	  if (parm == error_mark_node)
21204 	    return 1;
21205 	}
21206       else
21207 	parm = pattern;
21208 
21209       /* Unify the pattern with the current argument.  */
21210       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
21211 			      explain_p))
21212 	return 1;
21213 
21214       /* For each parameter pack, collect the deduced value.  */
21215       for (pack = packs; pack; pack = TREE_CHAIN (pack))
21216         {
21217           int idx, level;
21218           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
21219 
21220           TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
21221             TMPL_ARG (targs, level, idx);
21222         }
21223     }
21224 
21225   /* Verify that the results of unification with the parameter packs
21226      produce results consistent with what we've seen before, and make
21227      the deduced argument packs available.  */
21228   for (pack = packs; pack; pack = TREE_CHAIN (pack))
21229     {
21230       tree old_pack = TREE_VALUE (pack);
21231       tree new_args = TREE_TYPE (pack);
21232       int i, len = TREE_VEC_LENGTH (new_args);
21233       int idx, level;
21234       bool nondeduced_p = false;
21235 
21236       /* By default keep the original deduced argument pack.
21237 	 If necessary, more specific code is going to update the
21238 	 resulting deduced argument later down in this function.  */
21239       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
21240       TMPL_ARG (targs, level, idx) = old_pack;
21241 
21242       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
21243 	 actually deduce anything.  */
21244       for (i = 0; i < len && !nondeduced_p; ++i)
21245 	if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
21246 	  nondeduced_p = true;
21247       if (nondeduced_p)
21248 	continue;
21249 
21250       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
21251         {
21252           /* If we had fewer function args than explicit template args,
21253              just use the explicits.  */
21254           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
21255           int explicit_len = TREE_VEC_LENGTH (explicit_args);
21256           if (len < explicit_len)
21257             new_args = explicit_args;
21258         }
21259 
21260       if (!old_pack)
21261         {
21262           tree result;
21263           /* Build the deduced *_ARGUMENT_PACK.  */
21264           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
21265             {
21266               result = make_node (NONTYPE_ARGUMENT_PACK);
21267               TREE_CONSTANT (result) = 1;
21268             }
21269           else
21270             result = cxx_make_type (TYPE_ARGUMENT_PACK);
21271 
21272           SET_ARGUMENT_PACK_ARGS (result, new_args);
21273 
21274           /* Note the deduced argument packs for this parameter
21275              pack.  */
21276           TMPL_ARG (targs, level, idx) = result;
21277         }
21278       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
21279                && (ARGUMENT_PACK_ARGS (old_pack)
21280                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
21281         {
21282           /* We only had the explicitly-provided arguments before, but
21283              now we have a complete set of arguments.  */
21284           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
21285 
21286           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
21287           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
21288           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
21289         }
21290       else
21291 	{
21292 	  tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
21293 	  tree old_args = ARGUMENT_PACK_ARGS (old_pack);
21294 
21295 	  if (!comp_template_args (old_args, new_args,
21296 				   &bad_old_arg, &bad_new_arg))
21297 	    /* Inconsistent unification of this parameter pack.  */
21298 	    return unify_parameter_pack_inconsistent (explain_p,
21299 						      bad_old_arg,
21300 						      bad_new_arg);
21301 	}
21302     }
21303 
21304   return unify_success (explain_p);
21305 }
21306 
21307 /* Handle unification of the domain of an array.  PARM_DOM and ARG_DOM are
21308    INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs.  The other
21309    parameters and return value are as for unify.  */
21310 
21311 static int
unify_array_domain(tree tparms,tree targs,tree parm_dom,tree arg_dom,bool explain_p)21312 unify_array_domain (tree tparms, tree targs,
21313 		    tree parm_dom, tree arg_dom,
21314 		    bool explain_p)
21315 {
21316   tree parm_max;
21317   tree arg_max;
21318   bool parm_cst;
21319   bool arg_cst;
21320 
21321   /* Our representation of array types uses "N - 1" as the
21322      TYPE_MAX_VALUE for an array with "N" elements, if "N" is
21323      not an integer constant.  We cannot unify arbitrarily
21324      complex expressions, so we eliminate the MINUS_EXPRs
21325      here.  */
21326   parm_max = TYPE_MAX_VALUE (parm_dom);
21327   parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
21328   if (!parm_cst)
21329     {
21330       gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
21331       parm_max = TREE_OPERAND (parm_max, 0);
21332     }
21333   arg_max = TYPE_MAX_VALUE (arg_dom);
21334   arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
21335   if (!arg_cst)
21336     {
21337       /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
21338 	 trying to unify the type of a variable with the type
21339 	 of a template parameter.  For example:
21340 
21341 	   template <unsigned int N>
21342 	   void f (char (&) [N]);
21343 	   int g();
21344 	   void h(int i) {
21345 	     char a[g(i)];
21346 	     f(a);
21347 	   }
21348 
21349 	 Here, the type of the ARG will be "int [g(i)]", and
21350 	 may be a SAVE_EXPR, etc.  */
21351       if (TREE_CODE (arg_max) != MINUS_EXPR)
21352 	return unify_vla_arg (explain_p, arg_dom);
21353       arg_max = TREE_OPERAND (arg_max, 0);
21354     }
21355 
21356   /* If only one of the bounds used a MINUS_EXPR, compensate
21357      by adding one to the other bound.  */
21358   if (parm_cst && !arg_cst)
21359     parm_max = fold_build2_loc (input_location, PLUS_EXPR,
21360 				integer_type_node,
21361 				parm_max,
21362 				integer_one_node);
21363   else if (arg_cst && !parm_cst)
21364     arg_max = fold_build2_loc (input_location, PLUS_EXPR,
21365 			       integer_type_node,
21366 			       arg_max,
21367 			       integer_one_node);
21368 
21369   return unify (tparms, targs, parm_max, arg_max,
21370 		UNIFY_ALLOW_INTEGER, explain_p);
21371 }
21372 
21373 /* Returns whether T, a P or A in unify, is a type, template or expression.  */
21374 
21375 enum pa_kind_t { pa_type, pa_tmpl, pa_expr };
21376 
21377 static pa_kind_t
pa_kind(tree t)21378 pa_kind (tree t)
21379 {
21380   if (PACK_EXPANSION_P (t))
21381     t = PACK_EXPANSION_PATTERN (t);
21382   if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
21383       || TREE_CODE (t) == UNBOUND_CLASS_TEMPLATE
21384       || DECL_TYPE_TEMPLATE_P (t))
21385     return pa_tmpl;
21386   else if (TYPE_P (t))
21387     return pa_type;
21388   else
21389     return pa_expr;
21390 }
21391 
21392 /* Deduce the value of template parameters.  TPARMS is the (innermost)
21393    set of template parameters to a template.  TARGS is the bindings
21394    for those template parameters, as determined thus far; TARGS may
21395    include template arguments for outer levels of template parameters
21396    as well.  PARM is a parameter to a template function, or a
21397    subcomponent of that parameter; ARG is the corresponding argument.
21398    This function attempts to match PARM with ARG in a manner
21399    consistent with the existing assignments in TARGS.  If more values
21400    are deduced, then TARGS is updated.
21401 
21402    Returns 0 if the type deduction succeeds, 1 otherwise.  The
21403    parameter STRICT is a bitwise or of the following flags:
21404 
21405      UNIFY_ALLOW_NONE:
21406        Require an exact match between PARM and ARG.
21407      UNIFY_ALLOW_MORE_CV_QUAL:
21408        Allow the deduced ARG to be more cv-qualified (by qualification
21409        conversion) than ARG.
21410      UNIFY_ALLOW_LESS_CV_QUAL:
21411        Allow the deduced ARG to be less cv-qualified than ARG.
21412      UNIFY_ALLOW_DERIVED:
21413        Allow the deduced ARG to be a template base class of ARG,
21414        or a pointer to a template base class of the type pointed to by
21415        ARG.
21416      UNIFY_ALLOW_INTEGER:
21417        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
21418        case for more information.
21419      UNIFY_ALLOW_OUTER_LEVEL:
21420        This is the outermost level of a deduction. Used to determine validity
21421        of qualification conversions. A valid qualification conversion must
21422        have const qualified pointers leading up to the inner type which
21423        requires additional CV quals, except at the outer level, where const
21424        is not required [conv.qual]. It would be normal to set this flag in
21425        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
21426      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
21427        This is the outermost level of a deduction, and PARM can be more CV
21428        qualified at this point.
21429      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
21430        This is the outermost level of a deduction, and PARM can be less CV
21431        qualified at this point.  */
21432 
21433 static int
unify(tree tparms,tree targs,tree parm,tree arg,int strict,bool explain_p)21434 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
21435        bool explain_p)
21436 {
21437   int idx;
21438   tree targ;
21439   tree tparm;
21440   int strict_in = strict;
21441   tsubst_flags_t complain = (explain_p
21442 			     ? tf_warning_or_error
21443 			     : tf_none);
21444 
21445   /* I don't think this will do the right thing with respect to types.
21446      But the only case I've seen it in so far has been array bounds, where
21447      signedness is the only information lost, and I think that will be
21448      okay.  */
21449   while (CONVERT_EXPR_P (parm))
21450     parm = TREE_OPERAND (parm, 0);
21451 
21452   if (arg == error_mark_node)
21453     return unify_invalid (explain_p);
21454   if (arg == unknown_type_node
21455       || arg == init_list_type_node)
21456     /* We can't deduce anything from this, but we might get all the
21457        template args from other function args.  */
21458     return unify_success (explain_p);
21459 
21460   if (parm == any_targ_node || arg == any_targ_node)
21461     return unify_success (explain_p);
21462 
21463   /* If PARM uses template parameters, then we can't bail out here,
21464      even if ARG == PARM, since we won't record unifications for the
21465      template parameters.  We might need them if we're trying to
21466      figure out which of two things is more specialized.  */
21467   if (arg == parm && !uses_template_parms (parm))
21468     return unify_success (explain_p);
21469 
21470   /* Handle init lists early, so the rest of the function can assume
21471      we're dealing with a type. */
21472   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
21473     {
21474       tree elt, elttype;
21475       unsigned i;
21476       tree orig_parm = parm;
21477 
21478       /* Replace T with std::initializer_list<T> for deduction.  */
21479       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
21480 	  && flag_deduce_init_list)
21481 	parm = listify (parm);
21482 
21483       if (!is_std_init_list (parm)
21484 	  && TREE_CODE (parm) != ARRAY_TYPE)
21485 	/* We can only deduce from an initializer list argument if the
21486 	   parameter is std::initializer_list or an array; otherwise this
21487 	   is a non-deduced context. */
21488 	return unify_success (explain_p);
21489 
21490       if (TREE_CODE (parm) == ARRAY_TYPE)
21491 	elttype = TREE_TYPE (parm);
21492       else
21493 	{
21494 	  elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
21495 	  /* Deduction is defined in terms of a single type, so just punt
21496 	     on the (bizarre) std::initializer_list<T...>.  */
21497 	  if (PACK_EXPANSION_P (elttype))
21498 	    return unify_success (explain_p);
21499 	}
21500 
21501       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
21502 	{
21503 	  int elt_strict = strict;
21504 
21505 	  if (elt == error_mark_node)
21506 	    return unify_invalid (explain_p);
21507 
21508 	  if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
21509 	    {
21510 	      tree type = TREE_TYPE (elt);
21511 	      if (type == error_mark_node)
21512 		return unify_invalid (explain_p);
21513 	      /* It should only be possible to get here for a call.  */
21514 	      gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
21515 	      elt_strict |= maybe_adjust_types_for_deduction
21516 		(DEDUCE_CALL, &elttype, &type, elt);
21517 	      elt = type;
21518 	    }
21519 
21520 	  RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
21521 				   explain_p);
21522 	}
21523 
21524       if (TREE_CODE (parm) == ARRAY_TYPE
21525 	  && deducible_array_bound (TYPE_DOMAIN (parm)))
21526 	{
21527 	  /* Also deduce from the length of the initializer list.  */
21528 	  tree max = size_int (CONSTRUCTOR_NELTS (arg));
21529 	  tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
21530 	  if (idx == error_mark_node)
21531 	    return unify_invalid (explain_p);
21532 	  return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
21533 				     idx, explain_p);
21534 	}
21535 
21536       /* If the std::initializer_list<T> deduction worked, replace the
21537 	 deduced A with std::initializer_list<A>.  */
21538       if (orig_parm != parm)
21539 	{
21540 	  idx = TEMPLATE_TYPE_IDX (orig_parm);
21541 	  targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
21542 	  targ = listify (targ);
21543 	  TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
21544 	}
21545       return unify_success (explain_p);
21546     }
21547 
21548   /* If parm and arg aren't the same kind of thing (template, type, or
21549      expression), fail early.  */
21550   if (pa_kind (parm) != pa_kind (arg))
21551     return unify_invalid (explain_p);
21552 
21553   /* Immediately reject some pairs that won't unify because of
21554      cv-qualification mismatches.  */
21555   if (TREE_CODE (arg) == TREE_CODE (parm)
21556       && TYPE_P (arg)
21557       /* It is the elements of the array which hold the cv quals of an array
21558 	 type, and the elements might be template type parms. We'll check
21559 	 when we recurse.  */
21560       && TREE_CODE (arg) != ARRAY_TYPE
21561       /* We check the cv-qualifiers when unifying with template type
21562 	 parameters below.  We want to allow ARG `const T' to unify with
21563 	 PARM `T' for example, when computing which of two templates
21564 	 is more specialized, for example.  */
21565       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
21566       && !check_cv_quals_for_unify (strict_in, arg, parm))
21567     return unify_cv_qual_mismatch (explain_p, parm, arg);
21568 
21569   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
21570       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
21571     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
21572   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
21573   strict &= ~UNIFY_ALLOW_DERIVED;
21574   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
21575   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
21576 
21577   switch (TREE_CODE (parm))
21578     {
21579     case TYPENAME_TYPE:
21580     case SCOPE_REF:
21581     case UNBOUND_CLASS_TEMPLATE:
21582       /* In a type which contains a nested-name-specifier, template
21583 	 argument values cannot be deduced for template parameters used
21584 	 within the nested-name-specifier.  */
21585       return unify_success (explain_p);
21586 
21587     case TEMPLATE_TYPE_PARM:
21588     case TEMPLATE_TEMPLATE_PARM:
21589     case BOUND_TEMPLATE_TEMPLATE_PARM:
21590       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
21591       if (error_operand_p (tparm))
21592 	return unify_invalid (explain_p);
21593 
21594       if (TEMPLATE_TYPE_LEVEL (parm)
21595 	  != template_decl_level (tparm))
21596 	/* The PARM is not one we're trying to unify.  Just check
21597 	   to see if it matches ARG.  */
21598 	{
21599 	  if (TREE_CODE (arg) == TREE_CODE (parm)
21600 	      && (is_auto (parm) ? is_auto (arg)
21601 		  : same_type_p (parm, arg)))
21602 	    return unify_success (explain_p);
21603 	  else
21604 	    return unify_type_mismatch (explain_p, parm, arg);
21605 	}
21606       idx = TEMPLATE_TYPE_IDX (parm);
21607       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
21608       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
21609       if (error_operand_p (tparm))
21610 	return unify_invalid (explain_p);
21611 
21612       /* Check for mixed types and values.  */
21613       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
21614 	   && TREE_CODE (tparm) != TYPE_DECL)
21615 	  || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
21616 	      && TREE_CODE (tparm) != TEMPLATE_DECL))
21617 	gcc_unreachable ();
21618 
21619       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
21620 	{
21621 	  if ((strict_in & UNIFY_ALLOW_DERIVED)
21622 	      && CLASS_TYPE_P (arg))
21623 	    {
21624 	      /* First try to match ARG directly.  */
21625 	      tree t = try_class_unification (tparms, targs, parm, arg,
21626 					      explain_p);
21627 	      if (!t)
21628 		{
21629 		  /* Otherwise, look for a suitable base of ARG, as below.  */
21630 		  enum template_base_result r;
21631 		  r = get_template_base (tparms, targs, parm, arg,
21632 					 explain_p, &t);
21633 		  if (!t)
21634 		    return unify_no_common_base (explain_p, r, parm, arg);
21635 		  arg = t;
21636 		}
21637 	    }
21638 	  /* ARG must be constructed from a template class or a template
21639 	     template parameter.  */
21640 	  else if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
21641 		   && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
21642 	    return unify_template_deduction_failure (explain_p, parm, arg);
21643 
21644 	  /* Deduce arguments T, i from TT<T> or TT<i>.  */
21645 	  if (unify_bound_ttp_args (tparms, targs, parm, arg, explain_p))
21646 	    return 1;
21647 
21648 	  arg = TYPE_TI_TEMPLATE (arg);
21649 
21650 	  /* Fall through to deduce template name.  */
21651 	}
21652 
21653       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
21654 	  || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
21655 	{
21656 	  /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
21657 
21658 	  /* Simple cases: Value already set, does match or doesn't.  */
21659 	  if (targ != NULL_TREE && template_args_equal (targ, arg))
21660 	    return unify_success (explain_p);
21661 	  else if (targ)
21662 	    return unify_inconsistency (explain_p, parm, targ, arg);
21663 	}
21664       else
21665 	{
21666 	  /* If PARM is `const T' and ARG is only `int', we don't have
21667 	     a match unless we are allowing additional qualification.
21668 	     If ARG is `const int' and PARM is just `T' that's OK;
21669 	     that binds `const int' to `T'.  */
21670 	  if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
21671 					 arg, parm))
21672 	    return unify_cv_qual_mismatch (explain_p, parm, arg);
21673 
21674 	  /* Consider the case where ARG is `const volatile int' and
21675 	     PARM is `const T'.  Then, T should be `volatile int'.  */
21676 	  arg = cp_build_qualified_type_real
21677 	    (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
21678 	  if (arg == error_mark_node)
21679 	    return unify_invalid (explain_p);
21680 
21681 	  /* Simple cases: Value already set, does match or doesn't.  */
21682 	  if (targ != NULL_TREE && same_type_p (targ, arg))
21683 	    return unify_success (explain_p);
21684 	  else if (targ)
21685 	    return unify_inconsistency (explain_p, parm, targ, arg);
21686 
21687 	  /* Make sure that ARG is not a variable-sized array.  (Note
21688 	     that were talking about variable-sized arrays (like
21689 	     `int[n]'), rather than arrays of unknown size (like
21690 	     `int[]').)  We'll get very confused by such a type since
21691 	     the bound of the array is not constant, and therefore
21692 	     not mangleable.  Besides, such types are not allowed in
21693 	     ISO C++, so we can do as we please here.  We do allow
21694 	     them for 'auto' deduction, since that isn't ABI-exposed.  */
21695 	  if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
21696 	    return unify_vla_arg (explain_p, arg);
21697 
21698 	  /* Strip typedefs as in convert_template_argument.  */
21699 	  arg = canonicalize_type_argument (arg, tf_none);
21700 	}
21701 
21702       /* If ARG is a parameter pack or an expansion, we cannot unify
21703 	 against it unless PARM is also a parameter pack.  */
21704       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
21705 	  && !template_parameter_pack_p (parm))
21706 	return unify_parameter_pack_mismatch (explain_p, parm, arg);
21707 
21708       /* If the argument deduction results is a METHOD_TYPE,
21709          then there is a problem.
21710          METHOD_TYPE doesn't map to any real C++ type the result of
21711 	 the deduction can not be of that type.  */
21712       if (TREE_CODE (arg) == METHOD_TYPE)
21713 	return unify_method_type_error (explain_p, arg);
21714 
21715       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
21716       return unify_success (explain_p);
21717 
21718     case TEMPLATE_PARM_INDEX:
21719       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
21720       if (error_operand_p (tparm))
21721 	return unify_invalid (explain_p);
21722 
21723       if (TEMPLATE_PARM_LEVEL (parm)
21724 	  != template_decl_level (tparm))
21725 	{
21726 	  /* The PARM is not one we're trying to unify.  Just check
21727 	     to see if it matches ARG.  */
21728 	  int result = !(TREE_CODE (arg) == TREE_CODE (parm)
21729 			 && cp_tree_equal (parm, arg));
21730 	  if (result)
21731 	    unify_expression_unequal (explain_p, parm, arg);
21732 	  return result;
21733 	}
21734 
21735       idx = TEMPLATE_PARM_IDX (parm);
21736       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
21737 
21738       if (targ)
21739 	{
21740 	  if ((strict & UNIFY_ALLOW_INTEGER)
21741 	      && TREE_TYPE (targ) && TREE_TYPE (arg)
21742 	      && CP_INTEGRAL_TYPE_P (TREE_TYPE (targ)))
21743 	    /* We're deducing from an array bound, the type doesn't matter.  */
21744 	    arg = fold_convert (TREE_TYPE (targ), arg);
21745 	  int x = !cp_tree_equal (targ, arg);
21746 	  if (x)
21747 	    unify_inconsistency (explain_p, parm, targ, arg);
21748 	  return x;
21749 	}
21750 
21751       /* [temp.deduct.type] If, in the declaration of a function template
21752 	 with a non-type template-parameter, the non-type
21753 	 template-parameter is used in an expression in the function
21754 	 parameter-list and, if the corresponding template-argument is
21755 	 deduced, the template-argument type shall match the type of the
21756 	 template-parameter exactly, except that a template-argument
21757 	 deduced from an array bound may be of any integral type.
21758 	 The non-type parameter might use already deduced type parameters.  */
21759       tparm = TREE_TYPE (parm);
21760       if (TEMPLATE_PARM_LEVEL (parm) > TMPL_ARGS_DEPTH (targs))
21761 	/* We don't have enough levels of args to do any substitution.  This
21762 	   can happen in the context of -fnew-ttp-matching.  */;
21763       else
21764 	{
21765 	  ++processing_template_decl;
21766 	  tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
21767 	  --processing_template_decl;
21768 
21769 	  if (tree a = type_uses_auto (tparm))
21770 	    {
21771 	      tparm = do_auto_deduction (tparm, arg, a, complain, adc_unify);
21772 	      if (tparm == error_mark_node)
21773 		return 1;
21774 	    }
21775 	}
21776 
21777       if (!TREE_TYPE (arg))
21778 	/* Template-parameter dependent expression.  Just accept it for now.
21779 	   It will later be processed in convert_template_argument.  */
21780 	;
21781       else if (same_type_p (non_reference (TREE_TYPE (arg)),
21782 			    non_reference (tparm)))
21783 	/* OK */;
21784       else if ((strict & UNIFY_ALLOW_INTEGER)
21785 	       && CP_INTEGRAL_TYPE_P (tparm))
21786 	/* Convert the ARG to the type of PARM; the deduced non-type
21787 	   template argument must exactly match the types of the
21788 	   corresponding parameter.  */
21789 	arg = fold (build_nop (tparm, arg));
21790       else if (uses_template_parms (tparm))
21791 	{
21792 	  /* We haven't deduced the type of this parameter yet.  */
21793 	  if (cxx_dialect >= cxx17
21794 	      /* We deduce from array bounds in try_array_deduction.  */
21795 	      && !(strict & UNIFY_ALLOW_INTEGER))
21796 	    {
21797 	      /* Deduce it from the non-type argument.  */
21798 	      tree atype = TREE_TYPE (arg);
21799 	      RECUR_AND_CHECK_FAILURE (tparms, targs,
21800 				       tparm, atype,
21801 				       UNIFY_ALLOW_NONE, explain_p);
21802 	    }
21803 	  else
21804 	    /* Try again later.  */
21805 	    return unify_success (explain_p);
21806 	}
21807       else
21808 	return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
21809 
21810       /* If ARG is a parameter pack or an expansion, we cannot unify
21811 	 against it unless PARM is also a parameter pack.  */
21812       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
21813 	  && !TEMPLATE_PARM_PARAMETER_PACK (parm))
21814 	return unify_parameter_pack_mismatch (explain_p, parm, arg);
21815 
21816       {
21817 	bool removed_attr = false;
21818 	arg = strip_typedefs_expr (arg, &removed_attr);
21819       }
21820       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
21821       return unify_success (explain_p);
21822 
21823     case PTRMEM_CST:
21824      {
21825 	/* A pointer-to-member constant can be unified only with
21826 	 another constant.  */
21827       if (TREE_CODE (arg) != PTRMEM_CST)
21828 	return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
21829 
21830       /* Just unify the class member. It would be useless (and possibly
21831 	 wrong, depending on the strict flags) to unify also
21832 	 PTRMEM_CST_CLASS, because we want to be sure that both parm and
21833 	 arg refer to the same variable, even if through different
21834 	 classes. For instance:
21835 
21836 	 struct A { int x; };
21837 	 struct B : A { };
21838 
21839 	 Unification of &A::x and &B::x must succeed.  */
21840       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
21841 		    PTRMEM_CST_MEMBER (arg), strict, explain_p);
21842      }
21843 
21844     case POINTER_TYPE:
21845       {
21846 	if (!TYPE_PTR_P (arg))
21847 	  return unify_type_mismatch (explain_p, parm, arg);
21848 
21849 	/* [temp.deduct.call]
21850 
21851 	   A can be another pointer or pointer to member type that can
21852 	   be converted to the deduced A via a qualification
21853 	   conversion (_conv.qual_).
21854 
21855 	   We pass down STRICT here rather than UNIFY_ALLOW_NONE.
21856 	   This will allow for additional cv-qualification of the
21857 	   pointed-to types if appropriate.  */
21858 
21859 	if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
21860 	  /* The derived-to-base conversion only persists through one
21861 	     level of pointers.  */
21862 	  strict |= (strict_in & UNIFY_ALLOW_DERIVED);
21863 
21864 	return unify (tparms, targs, TREE_TYPE (parm),
21865 		      TREE_TYPE (arg), strict, explain_p);
21866       }
21867 
21868     case REFERENCE_TYPE:
21869       if (TREE_CODE (arg) != REFERENCE_TYPE)
21870 	return unify_type_mismatch (explain_p, parm, arg);
21871       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
21872 		    strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
21873 
21874     case ARRAY_TYPE:
21875       if (TREE_CODE (arg) != ARRAY_TYPE)
21876 	return unify_type_mismatch (explain_p, parm, arg);
21877       if ((TYPE_DOMAIN (parm) == NULL_TREE)
21878 	  != (TYPE_DOMAIN (arg) == NULL_TREE))
21879 	return unify_type_mismatch (explain_p, parm, arg);
21880       RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
21881 			       strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
21882       if (TYPE_DOMAIN (parm) != NULL_TREE)
21883 	return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
21884 				   TYPE_DOMAIN (arg), explain_p);
21885       return unify_success (explain_p);
21886 
21887     case REAL_TYPE:
21888     case COMPLEX_TYPE:
21889     case VECTOR_TYPE:
21890     case INTEGER_TYPE:
21891     case BOOLEAN_TYPE:
21892     case ENUMERAL_TYPE:
21893     case VOID_TYPE:
21894     case NULLPTR_TYPE:
21895       if (TREE_CODE (arg) != TREE_CODE (parm))
21896 	return unify_type_mismatch (explain_p, parm, arg);
21897 
21898       /* We have already checked cv-qualification at the top of the
21899 	 function.  */
21900       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
21901 	return unify_type_mismatch (explain_p, parm, arg);
21902 
21903       /* As far as unification is concerned, this wins.	 Later checks
21904 	 will invalidate it if necessary.  */
21905       return unify_success (explain_p);
21906 
21907       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
21908       /* Type INTEGER_CST can come from ordinary constant template args.  */
21909     case INTEGER_CST:
21910       while (CONVERT_EXPR_P (arg))
21911 	arg = TREE_OPERAND (arg, 0);
21912 
21913       if (TREE_CODE (arg) != INTEGER_CST)
21914 	return unify_template_argument_mismatch (explain_p, parm, arg);
21915       return (tree_int_cst_equal (parm, arg)
21916 	      ? unify_success (explain_p)
21917 	      : unify_template_argument_mismatch (explain_p, parm, arg));
21918 
21919     case TREE_VEC:
21920       {
21921 	int i, len, argslen;
21922 	int parm_variadic_p = 0;
21923 
21924 	if (TREE_CODE (arg) != TREE_VEC)
21925 	  return unify_template_argument_mismatch (explain_p, parm, arg);
21926 
21927 	len = TREE_VEC_LENGTH (parm);
21928 	argslen = TREE_VEC_LENGTH (arg);
21929 
21930 	/* Check for pack expansions in the parameters.  */
21931 	for (i = 0; i < len; ++i)
21932 	  {
21933 	    if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
21934 	      {
21935 		if (i == len - 1)
21936 		  /* We can unify against something with a trailing
21937 		     parameter pack.  */
21938 		  parm_variadic_p = 1;
21939 		else
21940 		  /* [temp.deduct.type]/9: If the template argument list of
21941 		     P contains a pack expansion that is not the last
21942 		     template argument, the entire template argument list
21943 		     is a non-deduced context.  */
21944 		  return unify_success (explain_p);
21945 	      }
21946 	  }
21947 
21948         /* If we don't have enough arguments to satisfy the parameters
21949            (not counting the pack expression at the end), or we have
21950            too many arguments for a parameter list that doesn't end in
21951            a pack expression, we can't unify.  */
21952 	if (parm_variadic_p
21953 	    ? argslen < len - parm_variadic_p
21954 	    : argslen != len)
21955 	  return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
21956 
21957 	/* Unify all of the parameters that precede the (optional)
21958 	   pack expression.  */
21959 	for (i = 0; i < len - parm_variadic_p; ++i)
21960 	  {
21961 	    RECUR_AND_CHECK_FAILURE (tparms, targs,
21962 				     TREE_VEC_ELT (parm, i),
21963 				     TREE_VEC_ELT (arg, i),
21964 				     UNIFY_ALLOW_NONE, explain_p);
21965 	  }
21966 	if (parm_variadic_p)
21967 	  return unify_pack_expansion (tparms, targs, parm, arg,
21968 				       DEDUCE_EXACT,
21969 				       /*subr=*/true, explain_p);
21970 	return unify_success (explain_p);
21971       }
21972 
21973     case RECORD_TYPE:
21974     case UNION_TYPE:
21975       if (TREE_CODE (arg) != TREE_CODE (parm))
21976 	return unify_type_mismatch (explain_p, parm, arg);
21977 
21978       if (TYPE_PTRMEMFUNC_P (parm))
21979 	{
21980 	  if (!TYPE_PTRMEMFUNC_P (arg))
21981 	    return unify_type_mismatch (explain_p, parm, arg);
21982 
21983 	  return unify (tparms, targs,
21984 			TYPE_PTRMEMFUNC_FN_TYPE (parm),
21985 			TYPE_PTRMEMFUNC_FN_TYPE (arg),
21986 			strict, explain_p);
21987 	}
21988       else if (TYPE_PTRMEMFUNC_P (arg))
21989 	return unify_type_mismatch (explain_p, parm, arg);
21990 
21991       if (CLASSTYPE_TEMPLATE_INFO (parm))
21992 	{
21993 	  tree t = NULL_TREE;
21994 
21995 	  if (strict_in & UNIFY_ALLOW_DERIVED)
21996 	    {
21997 	      /* First, we try to unify the PARM and ARG directly.  */
21998 	      t = try_class_unification (tparms, targs,
21999 					 parm, arg, explain_p);
22000 
22001 	      if (!t)
22002 		{
22003 		  /* Fallback to the special case allowed in
22004 		     [temp.deduct.call]:
22005 
22006 		       If P is a class, and P has the form
22007 		       template-id, then A can be a derived class of
22008 		       the deduced A.  Likewise, if P is a pointer to
22009 		       a class of the form template-id, A can be a
22010 		       pointer to a derived class pointed to by the
22011 		       deduced A.  */
22012 		  enum template_base_result r;
22013 		  r = get_template_base (tparms, targs, parm, arg,
22014 					 explain_p, &t);
22015 
22016 		  if (!t)
22017 		    {
22018 		      /* Don't give the derived diagnostic if we're
22019 			 already dealing with the same template.  */
22020 		      bool same_template
22021 			= (CLASSTYPE_TEMPLATE_INFO (arg)
22022 			   && (CLASSTYPE_TI_TEMPLATE (parm)
22023 			       == CLASSTYPE_TI_TEMPLATE (arg)));
22024 		      return unify_no_common_base (explain_p && !same_template,
22025 						   r, parm, arg);
22026 		    }
22027 		}
22028 	    }
22029 	  else if (CLASSTYPE_TEMPLATE_INFO (arg)
22030 		   && (CLASSTYPE_TI_TEMPLATE (parm)
22031 		       == CLASSTYPE_TI_TEMPLATE (arg)))
22032 	    /* Perhaps PARM is something like S<U> and ARG is S<int>.
22033 	       Then, we should unify `int' and `U'.  */
22034 	    t = arg;
22035 	  else
22036 	    /* There's no chance of unification succeeding.  */
22037 	    return unify_type_mismatch (explain_p, parm, arg);
22038 
22039 	  return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
22040 			CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
22041 	}
22042       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
22043 	return unify_type_mismatch (explain_p, parm, arg);
22044       return unify_success (explain_p);
22045 
22046     case METHOD_TYPE:
22047     case FUNCTION_TYPE:
22048       {
22049 	unsigned int nargs;
22050 	tree *args;
22051 	tree a;
22052 	unsigned int i;
22053 
22054 	if (TREE_CODE (arg) != TREE_CODE (parm))
22055 	  return unify_type_mismatch (explain_p, parm, arg);
22056 
22057 	/* CV qualifications for methods can never be deduced, they must
22058 	   match exactly.  We need to check them explicitly here,
22059 	   because type_unification_real treats them as any other
22060 	   cv-qualified parameter.  */
22061 	if (TREE_CODE (parm) == METHOD_TYPE
22062 	    && (!check_cv_quals_for_unify
22063 		(UNIFY_ALLOW_NONE,
22064 		 class_of_this_parm (arg),
22065 		 class_of_this_parm (parm))))
22066 	  return unify_cv_qual_mismatch (explain_p, parm, arg);
22067 	if (TREE_CODE (arg) == FUNCTION_TYPE
22068 	    && type_memfn_quals (parm) != type_memfn_quals (arg))
22069 	  return unify_cv_qual_mismatch (explain_p, parm, arg);
22070 	if (type_memfn_rqual (parm) != type_memfn_rqual (arg))
22071 	  return unify_type_mismatch (explain_p, parm, arg);
22072 
22073 	RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
22074 				 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
22075 
22076 	nargs = list_length (TYPE_ARG_TYPES (arg));
22077 	args = XALLOCAVEC (tree, nargs);
22078 	for (a = TYPE_ARG_TYPES (arg), i = 0;
22079 	     a != NULL_TREE && a != void_list_node;
22080 	     a = TREE_CHAIN (a), ++i)
22081 	  args[i] = TREE_VALUE (a);
22082 	nargs = i;
22083 
22084 	if (type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
22085 				   args, nargs, 1, DEDUCE_EXACT,
22086 				   LOOKUP_NORMAL, NULL, explain_p))
22087 	  return 1;
22088 
22089 	if (flag_noexcept_type)
22090 	  {
22091 	    tree pspec = TYPE_RAISES_EXCEPTIONS (parm);
22092 	    tree aspec = canonical_eh_spec (TYPE_RAISES_EXCEPTIONS (arg));
22093 	    if (pspec == NULL_TREE) pspec = noexcept_false_spec;
22094 	    if (aspec == NULL_TREE) aspec = noexcept_false_spec;
22095 	    if (TREE_PURPOSE (pspec) && TREE_PURPOSE (aspec)
22096 		&& uses_template_parms (TREE_PURPOSE (pspec)))
22097 	      RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_PURPOSE (pspec),
22098 				       TREE_PURPOSE (aspec),
22099 				       UNIFY_ALLOW_NONE, explain_p);
22100 	    else if (nothrow_spec_p (pspec) && !nothrow_spec_p (aspec))
22101 	      return unify_type_mismatch (explain_p, parm, arg);
22102 	  }
22103 
22104 	return 0;
22105       }
22106 
22107     case OFFSET_TYPE:
22108       /* Unify a pointer to member with a pointer to member function, which
22109 	 deduces the type of the member as a function type. */
22110       if (TYPE_PTRMEMFUNC_P (arg))
22111 	{
22112 	  /* Check top-level cv qualifiers */
22113 	  if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
22114 	    return unify_cv_qual_mismatch (explain_p, parm, arg);
22115 
22116 	  RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
22117 				   TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
22118 				   UNIFY_ALLOW_NONE, explain_p);
22119 
22120 	  /* Determine the type of the function we are unifying against. */
22121 	  tree fntype = static_fn_type (arg);
22122 
22123 	  return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
22124 	}
22125 
22126       if (TREE_CODE (arg) != OFFSET_TYPE)
22127 	return unify_type_mismatch (explain_p, parm, arg);
22128       RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
22129 			       TYPE_OFFSET_BASETYPE (arg),
22130 			       UNIFY_ALLOW_NONE, explain_p);
22131       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
22132 		    strict, explain_p);
22133 
22134     case CONST_DECL:
22135       if (DECL_TEMPLATE_PARM_P (parm))
22136 	return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
22137       if (arg != scalar_constant_value (parm))
22138 	return unify_template_argument_mismatch (explain_p, parm, arg);
22139       return unify_success (explain_p);
22140 
22141     case FIELD_DECL:
22142     case TEMPLATE_DECL:
22143       /* Matched cases are handled by the ARG == PARM test above.  */
22144       return unify_template_argument_mismatch (explain_p, parm, arg);
22145 
22146     case VAR_DECL:
22147       /* We might get a variable as a non-type template argument in parm if the
22148 	 corresponding parameter is type-dependent.  Make any necessary
22149 	 adjustments based on whether arg is a reference.  */
22150       if (CONSTANT_CLASS_P (arg))
22151 	parm = fold_non_dependent_expr (parm);
22152       else if (REFERENCE_REF_P (arg))
22153 	{
22154 	  tree sub = TREE_OPERAND (arg, 0);
22155 	  STRIP_NOPS (sub);
22156 	  if (TREE_CODE (sub) == ADDR_EXPR)
22157 	    arg = TREE_OPERAND (sub, 0);
22158 	}
22159       /* Now use the normal expression code to check whether they match.  */
22160       goto expr;
22161 
22162     case TYPE_ARGUMENT_PACK:
22163     case NONTYPE_ARGUMENT_PACK:
22164       return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
22165 		    ARGUMENT_PACK_ARGS (arg), strict, explain_p);
22166 
22167     case TYPEOF_TYPE:
22168     case DECLTYPE_TYPE:
22169     case UNDERLYING_TYPE:
22170       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
22171 	 or UNDERLYING_TYPE nodes.  */
22172       return unify_success (explain_p);
22173 
22174     case ERROR_MARK:
22175       /* Unification fails if we hit an error node.  */
22176       return unify_invalid (explain_p);
22177 
22178     case INDIRECT_REF:
22179       if (REFERENCE_REF_P (parm))
22180 	{
22181 	  bool pexp = PACK_EXPANSION_P (arg);
22182 	  if (pexp)
22183 	    arg = PACK_EXPANSION_PATTERN (arg);
22184 	  if (REFERENCE_REF_P (arg))
22185 	    arg = TREE_OPERAND (arg, 0);
22186 	  if (pexp)
22187 	    arg = make_pack_expansion (arg, complain);
22188 	  return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
22189 			strict, explain_p);
22190 	}
22191       /* FALLTHRU */
22192 
22193     default:
22194       /* An unresolved overload is a nondeduced context.  */
22195       if (is_overloaded_fn (parm) || type_unknown_p (parm))
22196 	return unify_success (explain_p);
22197       gcc_assert (EXPR_P (parm) || TREE_CODE (parm) == TRAIT_EXPR);
22198     expr:
22199       /* We must be looking at an expression.  This can happen with
22200 	 something like:
22201 
22202 	   template <int I>
22203 	   void foo(S<I>, S<I + 2>);
22204 
22205 	 This is a "nondeduced context":
22206 
22207 	   [deduct.type]
22208 
22209 	   The nondeduced contexts are:
22210 
22211 	   --A type that is a template-id in which one or more of
22212 	     the template-arguments is an expression that references
22213 	     a template-parameter.
22214 
22215 	 In these cases, we assume deduction succeeded, but don't
22216 	 actually infer any unifications.  */
22217 
22218       if (!uses_template_parms (parm)
22219 	  && !template_args_equal (parm, arg))
22220 	return unify_expression_unequal (explain_p, parm, arg);
22221       else
22222 	return unify_success (explain_p);
22223     }
22224 }
22225 #undef RECUR_AND_CHECK_FAILURE
22226 
22227 /* Note that DECL can be defined in this translation unit, if
22228    required.  */
22229 
22230 static void
mark_definable(tree decl)22231 mark_definable (tree decl)
22232 {
22233   tree clone;
22234   DECL_NOT_REALLY_EXTERN (decl) = 1;
22235   FOR_EACH_CLONE (clone, decl)
22236     DECL_NOT_REALLY_EXTERN (clone) = 1;
22237 }
22238 
22239 /* Called if RESULT is explicitly instantiated, or is a member of an
22240    explicitly instantiated class.  */
22241 
22242 void
mark_decl_instantiated(tree result,int extern_p)22243 mark_decl_instantiated (tree result, int extern_p)
22244 {
22245   SET_DECL_EXPLICIT_INSTANTIATION (result);
22246 
22247   /* If this entity has already been written out, it's too late to
22248      make any modifications.  */
22249   if (TREE_ASM_WRITTEN (result))
22250     return;
22251 
22252   /* For anonymous namespace we don't need to do anything.  */
22253   if (decl_anon_ns_mem_p (result))
22254     {
22255       gcc_assert (!TREE_PUBLIC (result));
22256       return;
22257     }
22258 
22259   if (TREE_CODE (result) != FUNCTION_DECL)
22260     /* The TREE_PUBLIC flag for function declarations will have been
22261        set correctly by tsubst.  */
22262     TREE_PUBLIC (result) = 1;
22263 
22264   /* This might have been set by an earlier implicit instantiation.  */
22265   DECL_COMDAT (result) = 0;
22266 
22267   if (extern_p)
22268     DECL_NOT_REALLY_EXTERN (result) = 0;
22269   else
22270     {
22271       mark_definable (result);
22272       mark_needed (result);
22273       /* Always make artificials weak.  */
22274       if (DECL_ARTIFICIAL (result) && flag_weak)
22275 	comdat_linkage (result);
22276       /* For WIN32 we also want to put explicit instantiations in
22277 	 linkonce sections.  */
22278       else if (TREE_PUBLIC (result))
22279 	maybe_make_one_only (result);
22280     }
22281 
22282   /* If EXTERN_P, then this function will not be emitted -- unless
22283      followed by an explicit instantiation, at which point its linkage
22284      will be adjusted.  If !EXTERN_P, then this function will be
22285      emitted here.  In neither circumstance do we want
22286      import_export_decl to adjust the linkage.  */
22287   DECL_INTERFACE_KNOWN (result) = 1;
22288 }
22289 
22290 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
22291    important template arguments.  If any are missing, we check whether
22292    they're important by using error_mark_node for substituting into any
22293    args that were used for partial ordering (the ones between ARGS and END)
22294    and seeing if it bubbles up.  */
22295 
22296 static bool
check_undeduced_parms(tree targs,tree args,tree end)22297 check_undeduced_parms (tree targs, tree args, tree end)
22298 {
22299   bool found = false;
22300   int i;
22301   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
22302     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
22303       {
22304 	found = true;
22305 	TREE_VEC_ELT (targs, i) = error_mark_node;
22306       }
22307   if (found)
22308     {
22309       tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
22310       if (substed == error_mark_node)
22311 	return true;
22312     }
22313   return false;
22314 }
22315 
22316 /* Given two function templates PAT1 and PAT2, return:
22317 
22318    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
22319    -1 if PAT2 is more specialized than PAT1.
22320    0 if neither is more specialized.
22321 
22322    LEN indicates the number of parameters we should consider
22323    (defaulted parameters should not be considered).
22324 
22325    The 1998 std underspecified function template partial ordering, and
22326    DR214 addresses the issue.  We take pairs of arguments, one from
22327    each of the templates, and deduce them against each other.  One of
22328    the templates will be more specialized if all the *other*
22329    template's arguments deduce against its arguments and at least one
22330    of its arguments *does* *not* deduce against the other template's
22331    corresponding argument.  Deduction is done as for class templates.
22332    The arguments used in deduction have reference and top level cv
22333    qualifiers removed.  Iff both arguments were originally reference
22334    types *and* deduction succeeds in both directions, an lvalue reference
22335    wins against an rvalue reference and otherwise the template
22336    with the more cv-qualified argument wins for that pairing (if
22337    neither is more cv-qualified, they both are equal).  Unlike regular
22338    deduction, after all the arguments have been deduced in this way,
22339    we do *not* verify the deduced template argument values can be
22340    substituted into non-deduced contexts.
22341 
22342    The logic can be a bit confusing here, because we look at deduce1 and
22343    targs1 to see if pat2 is at least as specialized, and vice versa; if we
22344    can find template arguments for pat1 to make arg1 look like arg2, that
22345    means that arg2 is at least as specialized as arg1.  */
22346 
22347 int
more_specialized_fn(tree pat1,tree pat2,int len)22348 more_specialized_fn (tree pat1, tree pat2, int len)
22349 {
22350   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
22351   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
22352   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
22353   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
22354   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
22355   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
22356   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
22357   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
22358   tree origs1, origs2;
22359   bool lose1 = false;
22360   bool lose2 = false;
22361 
22362   /* Remove the this parameter from non-static member functions.  If
22363      one is a non-static member function and the other is not a static
22364      member function, remove the first parameter from that function
22365      also.  This situation occurs for operator functions where we
22366      locate both a member function (with this pointer) and non-member
22367      operator (with explicit first operand).  */
22368   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
22369     {
22370       len--; /* LEN is the number of significant arguments for DECL1 */
22371       args1 = TREE_CHAIN (args1);
22372       if (!DECL_STATIC_FUNCTION_P (decl2))
22373 	args2 = TREE_CHAIN (args2);
22374     }
22375   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
22376     {
22377       args2 = TREE_CHAIN (args2);
22378       if (!DECL_STATIC_FUNCTION_P (decl1))
22379 	{
22380 	  len--;
22381 	  args1 = TREE_CHAIN (args1);
22382 	}
22383     }
22384 
22385   /* If only one is a conversion operator, they are unordered.  */
22386   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
22387     return 0;
22388 
22389   /* Consider the return type for a conversion function */
22390   if (DECL_CONV_FN_P (decl1))
22391     {
22392       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
22393       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
22394       len++;
22395     }
22396 
22397   processing_template_decl++;
22398 
22399   origs1 = args1;
22400   origs2 = args2;
22401 
22402   while (len--
22403 	 /* Stop when an ellipsis is seen.  */
22404 	 && args1 != NULL_TREE && args2 != NULL_TREE)
22405     {
22406       tree arg1 = TREE_VALUE (args1);
22407       tree arg2 = TREE_VALUE (args2);
22408       int deduce1, deduce2;
22409       int quals1 = -1;
22410       int quals2 = -1;
22411       int ref1 = 0;
22412       int ref2 = 0;
22413 
22414       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
22415           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
22416         {
22417           /* When both arguments are pack expansions, we need only
22418              unify the patterns themselves.  */
22419           arg1 = PACK_EXPANSION_PATTERN (arg1);
22420           arg2 = PACK_EXPANSION_PATTERN (arg2);
22421 
22422           /* This is the last comparison we need to do.  */
22423           len = 0;
22424         }
22425 
22426       /* DR 1847: If a particular P contains no template-parameters that
22427 	 participate in template argument deduction, that P is not used to
22428 	 determine the ordering.  */
22429       if (!uses_deducible_template_parms (arg1)
22430 	  && !uses_deducible_template_parms (arg2))
22431 	goto next;
22432 
22433       if (TREE_CODE (arg1) == REFERENCE_TYPE)
22434 	{
22435 	  ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
22436 	  arg1 = TREE_TYPE (arg1);
22437 	  quals1 = cp_type_quals (arg1);
22438 	}
22439 
22440       if (TREE_CODE (arg2) == REFERENCE_TYPE)
22441 	{
22442 	  ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
22443 	  arg2 = TREE_TYPE (arg2);
22444 	  quals2 = cp_type_quals (arg2);
22445 	}
22446 
22447       arg1 = TYPE_MAIN_VARIANT (arg1);
22448       arg2 = TYPE_MAIN_VARIANT (arg2);
22449 
22450       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
22451         {
22452           int i, len2 = remaining_arguments (args2);
22453           tree parmvec = make_tree_vec (1);
22454           tree argvec = make_tree_vec (len2);
22455           tree ta = args2;
22456 
22457           /* Setup the parameter vector, which contains only ARG1.  */
22458           TREE_VEC_ELT (parmvec, 0) = arg1;
22459 
22460           /* Setup the argument vector, which contains the remaining
22461              arguments.  */
22462           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
22463             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
22464 
22465           deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
22466 					   argvec, DEDUCE_EXACT,
22467 					   /*subr=*/true, /*explain_p=*/false)
22468 		     == 0);
22469 
22470           /* We cannot deduce in the other direction, because ARG1 is
22471              a pack expansion but ARG2 is not.  */
22472           deduce2 = 0;
22473         }
22474       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
22475         {
22476           int i, len1 = remaining_arguments (args1);
22477           tree parmvec = make_tree_vec (1);
22478           tree argvec = make_tree_vec (len1);
22479           tree ta = args1;
22480 
22481           /* Setup the parameter vector, which contains only ARG1.  */
22482           TREE_VEC_ELT (parmvec, 0) = arg2;
22483 
22484           /* Setup the argument vector, which contains the remaining
22485              arguments.  */
22486           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
22487             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
22488 
22489           deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
22490 					   argvec, DEDUCE_EXACT,
22491 					   /*subr=*/true, /*explain_p=*/false)
22492 		     == 0);
22493 
22494           /* We cannot deduce in the other direction, because ARG2 is
22495              a pack expansion but ARG1 is not.*/
22496           deduce1 = 0;
22497         }
22498 
22499       else
22500         {
22501           /* The normal case, where neither argument is a pack
22502              expansion.  */
22503           deduce1 = (unify (tparms1, targs1, arg1, arg2,
22504 			    UNIFY_ALLOW_NONE, /*explain_p=*/false)
22505 		     == 0);
22506           deduce2 = (unify (tparms2, targs2, arg2, arg1,
22507 			    UNIFY_ALLOW_NONE, /*explain_p=*/false)
22508 		     == 0);
22509         }
22510 
22511       /* If we couldn't deduce arguments for tparms1 to make arg1 match
22512 	 arg2, then arg2 is not as specialized as arg1.  */
22513       if (!deduce1)
22514 	lose2 = true;
22515       if (!deduce2)
22516 	lose1 = true;
22517 
22518       /* "If, for a given type, deduction succeeds in both directions
22519 	 (i.e., the types are identical after the transformations above)
22520 	 and both P and A were reference types (before being replaced with
22521 	 the type referred to above):
22522 	 - if the type from the argument template was an lvalue reference and
22523 	 the type from the parameter template was not, the argument type is
22524 	 considered to be more specialized than the other; otherwise,
22525 	 - if the type from the argument template is more cv-qualified
22526 	 than the type from the parameter template (as described above),
22527 	 the argument type is considered to be more specialized than the other;
22528 	 otherwise,
22529 	 - neither type is more specialized than the other."  */
22530 
22531       if (deduce1 && deduce2)
22532 	{
22533 	  if (ref1 && ref2 && ref1 != ref2)
22534 	    {
22535 	      if (ref1 > ref2)
22536 		lose1 = true;
22537 	      else
22538 		lose2 = true;
22539 	    }
22540 	  else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
22541 	    {
22542 	      if ((quals1 & quals2) == quals2)
22543 		lose2 = true;
22544 	      if ((quals1 & quals2) == quals1)
22545 		lose1 = true;
22546 	    }
22547 	}
22548 
22549       if (lose1 && lose2)
22550 	/* We've failed to deduce something in either direction.
22551 	   These must be unordered.  */
22552 	break;
22553 
22554     next:
22555 
22556       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
22557           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
22558         /* We have already processed all of the arguments in our
22559            handing of the pack expansion type.  */
22560         len = 0;
22561 
22562       args1 = TREE_CHAIN (args1);
22563       args2 = TREE_CHAIN (args2);
22564     }
22565 
22566   /* "In most cases, all template parameters must have values in order for
22567      deduction to succeed, but for partial ordering purposes a template
22568      parameter may remain without a value provided it is not used in the
22569      types being used for partial ordering."
22570 
22571      Thus, if we are missing any of the targs1 we need to substitute into
22572      origs1, then pat2 is not as specialized as pat1.  This can happen when
22573      there is a nondeduced context.  */
22574   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
22575     lose2 = true;
22576   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
22577     lose1 = true;
22578 
22579   processing_template_decl--;
22580 
22581   /* If both deductions succeed, the partial ordering selects the more
22582      constrained template.  */
22583   if (!lose1 && !lose2)
22584     {
22585       tree c1 = get_constraints (DECL_TEMPLATE_RESULT (pat1));
22586       tree c2 = get_constraints (DECL_TEMPLATE_RESULT (pat2));
22587       lose1 = !subsumes_constraints (c1, c2);
22588       lose2 = !subsumes_constraints (c2, c1);
22589     }
22590 
22591   /* All things being equal, if the next argument is a pack expansion
22592      for one function but not for the other, prefer the
22593      non-variadic function.  FIXME this is bogus; see c++/41958.  */
22594   if (lose1 == lose2
22595       && args1 && TREE_VALUE (args1)
22596       && args2 && TREE_VALUE (args2))
22597     {
22598       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
22599       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
22600     }
22601 
22602   if (lose1 == lose2)
22603     return 0;
22604   else if (!lose1)
22605     return 1;
22606   else
22607     return -1;
22608 }
22609 
22610 /* Determine which of two partial specializations of TMPL is more
22611    specialized.
22612 
22613    PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
22614    to the first partial specialization.  The TREE_PURPOSE is the
22615    innermost set of template parameters for the partial
22616    specialization.  PAT2 is similar, but for the second template.
22617 
22618    Return 1 if the first partial specialization is more specialized;
22619    -1 if the second is more specialized; 0 if neither is more
22620    specialized.
22621 
22622    See [temp.class.order] for information about determining which of
22623    two templates is more specialized.  */
22624 
22625 static int
more_specialized_partial_spec(tree tmpl,tree pat1,tree pat2)22626 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
22627 {
22628   tree targs;
22629   int winner = 0;
22630   bool any_deductions = false;
22631 
22632   tree tmpl1 = TREE_VALUE (pat1);
22633   tree tmpl2 = TREE_VALUE (pat2);
22634   tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
22635   tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
22636 
22637   /* Just like what happens for functions, if we are ordering between
22638      different template specializations, we may encounter dependent
22639      types in the arguments, and we need our dependency check functions
22640      to behave correctly.  */
22641   ++processing_template_decl;
22642   targs = get_partial_spec_bindings (tmpl, tmpl1, specargs2);
22643   if (targs)
22644     {
22645       --winner;
22646       any_deductions = true;
22647     }
22648 
22649   targs = get_partial_spec_bindings (tmpl, tmpl2, specargs1);
22650   if (targs)
22651     {
22652       ++winner;
22653       any_deductions = true;
22654     }
22655   --processing_template_decl;
22656 
22657   /* If both deductions succeed, the partial ordering selects the more
22658      constrained template.  */
22659   if (!winner && any_deductions)
22660     return more_constrained (tmpl1, tmpl2);
22661 
22662   /* In the case of a tie where at least one of the templates
22663      has a parameter pack at the end, the template with the most
22664      non-packed parameters wins.  */
22665   if (winner == 0
22666       && any_deductions
22667       && (template_args_variadic_p (TREE_PURPOSE (pat1))
22668           || template_args_variadic_p (TREE_PURPOSE (pat2))))
22669     {
22670       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
22671       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
22672       int len1 = TREE_VEC_LENGTH (args1);
22673       int len2 = TREE_VEC_LENGTH (args2);
22674 
22675       /* We don't count the pack expansion at the end.  */
22676       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
22677         --len1;
22678       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
22679         --len2;
22680 
22681       if (len1 > len2)
22682         return 1;
22683       else if (len1 < len2)
22684         return -1;
22685     }
22686 
22687   return winner;
22688 }
22689 
22690 /* Return the template arguments that will produce the function signature
22691    DECL from the function template FN, with the explicit template
22692    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
22693    also match.  Return NULL_TREE if no satisfactory arguments could be
22694    found.  */
22695 
22696 static tree
get_bindings(tree fn,tree decl,tree explicit_args,bool check_rettype)22697 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
22698 {
22699   int ntparms = DECL_NTPARMS (fn);
22700   tree targs = make_tree_vec (ntparms);
22701   tree decl_type = TREE_TYPE (decl);
22702   tree decl_arg_types;
22703   tree *args;
22704   unsigned int nargs, ix;
22705   tree arg;
22706 
22707   gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
22708 
22709   /* Never do unification on the 'this' parameter.  */
22710   decl_arg_types = skip_artificial_parms_for (decl,
22711 					      TYPE_ARG_TYPES (decl_type));
22712 
22713   nargs = list_length (decl_arg_types);
22714   args = XALLOCAVEC (tree, nargs);
22715   for (arg = decl_arg_types, ix = 0;
22716        arg != NULL_TREE && arg != void_list_node;
22717        arg = TREE_CHAIN (arg), ++ix)
22718     args[ix] = TREE_VALUE (arg);
22719 
22720   if (fn_type_unification (fn, explicit_args, targs,
22721 			   args, ix,
22722 			   (check_rettype || DECL_CONV_FN_P (fn)
22723 			    ? TREE_TYPE (decl_type) : NULL_TREE),
22724 			   DEDUCE_EXACT, LOOKUP_NORMAL, /*explain_p=*/false,
22725 			   /*decltype*/false)
22726       == error_mark_node)
22727     return NULL_TREE;
22728 
22729   return targs;
22730 }
22731 
22732 /* Return the innermost template arguments that, when applied to a partial
22733    specialization SPEC_TMPL of TMPL, yield the ARGS.
22734 
22735    For example, suppose we have:
22736 
22737      template <class T, class U> struct S {};
22738      template <class T> struct S<T*, int> {};
22739 
22740    Then, suppose we want to get `S<double*, int>'.  SPEC_TMPL will be the
22741    partial specialization and the ARGS will be {double*, int}.  The resulting
22742    vector will be {double}, indicating that `T' is bound to `double'.  */
22743 
22744 static tree
get_partial_spec_bindings(tree tmpl,tree spec_tmpl,tree args)22745 get_partial_spec_bindings (tree tmpl, tree spec_tmpl, tree args)
22746 {
22747   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
22748   tree spec_args
22749     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (spec_tmpl)));
22750   int i, ntparms = TREE_VEC_LENGTH (tparms);
22751   tree deduced_args;
22752   tree innermost_deduced_args;
22753 
22754   innermost_deduced_args = make_tree_vec (ntparms);
22755   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
22756     {
22757       deduced_args = copy_node (args);
22758       SET_TMPL_ARGS_LEVEL (deduced_args,
22759 			   TMPL_ARGS_DEPTH (deduced_args),
22760 			   innermost_deduced_args);
22761     }
22762   else
22763     deduced_args = innermost_deduced_args;
22764 
22765   bool tried_array_deduction = (cxx_dialect < cxx17);
22766  again:
22767   if (unify (tparms, deduced_args,
22768 	     INNERMOST_TEMPLATE_ARGS (spec_args),
22769 	     INNERMOST_TEMPLATE_ARGS (args),
22770 	     UNIFY_ALLOW_NONE, /*explain_p=*/false))
22771     return NULL_TREE;
22772 
22773   for (i =  0; i < ntparms; ++i)
22774     if (! TREE_VEC_ELT (innermost_deduced_args, i))
22775       {
22776 	if (!tried_array_deduction)
22777 	  {
22778 	    try_array_deduction (tparms, innermost_deduced_args,
22779 				 INNERMOST_TEMPLATE_ARGS (spec_args));
22780 	    tried_array_deduction = true;
22781 	    if (TREE_VEC_ELT (innermost_deduced_args, i))
22782 	      goto again;
22783 	  }
22784 	return NULL_TREE;
22785       }
22786 
22787   if (!push_tinst_level (spec_tmpl, deduced_args))
22788     {
22789       excessive_deduction_depth = true;
22790       return NULL_TREE;
22791     }
22792 
22793   /* Verify that nondeduced template arguments agree with the type
22794      obtained from argument deduction.
22795 
22796      For example:
22797 
22798        struct A { typedef int X; };
22799        template <class T, class U> struct C {};
22800        template <class T> struct C<T, typename T::X> {};
22801 
22802      Then with the instantiation `C<A, int>', we can deduce that
22803      `T' is `A' but unify () does not check whether `typename T::X'
22804      is `int'.  */
22805   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
22806 
22807   if (spec_args != error_mark_node)
22808     spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
22809 				       INNERMOST_TEMPLATE_ARGS (spec_args),
22810 				       tmpl, tf_none, false, false);
22811 
22812   pop_tinst_level ();
22813 
22814   if (spec_args == error_mark_node
22815       /* We only need to check the innermost arguments; the other
22816 	 arguments will always agree.  */
22817       || !comp_template_args_porder (INNERMOST_TEMPLATE_ARGS (spec_args),
22818 				     INNERMOST_TEMPLATE_ARGS (args)))
22819     return NULL_TREE;
22820 
22821   /* Now that we have bindings for all of the template arguments,
22822      ensure that the arguments deduced for the template template
22823      parameters have compatible template parameter lists.  See the use
22824      of template_template_parm_bindings_ok_p in fn_type_unification
22825      for more information.  */
22826   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
22827     return NULL_TREE;
22828 
22829   return deduced_args;
22830 }
22831 
22832 // Compare two function templates T1 and T2 by deducing bindings
22833 // from one against the other. If both deductions succeed, compare
22834 // constraints to see which is more constrained.
22835 static int
more_specialized_inst(tree t1,tree t2)22836 more_specialized_inst (tree t1, tree t2)
22837 {
22838   int fate = 0;
22839   int count = 0;
22840 
22841   if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
22842     {
22843       --fate;
22844       ++count;
22845     }
22846 
22847   if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
22848     {
22849       ++fate;
22850       ++count;
22851     }
22852 
22853   // If both deductions succeed, then one may be more constrained.
22854   if (count == 2 && fate == 0)
22855     fate = more_constrained (t1, t2);
22856 
22857   return fate;
22858 }
22859 
22860 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
22861    Return the TREE_LIST node with the most specialized template, if
22862    any.  If there is no most specialized template, the error_mark_node
22863    is returned.
22864 
22865    Note that this function does not look at, or modify, the
22866    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
22867    returned is one of the elements of INSTANTIATIONS, callers may
22868    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
22869    and retrieve it from the value returned.  */
22870 
22871 tree
most_specialized_instantiation(tree templates)22872 most_specialized_instantiation (tree templates)
22873 {
22874   tree fn, champ;
22875 
22876   ++processing_template_decl;
22877 
22878   champ = templates;
22879   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
22880     {
22881       gcc_assert (TREE_VALUE (champ) != TREE_VALUE (fn));
22882       int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
22883       if (fate == -1)
22884 	champ = fn;
22885       else if (!fate)
22886 	{
22887 	  /* Equally specialized, move to next function.  If there
22888 	     is no next function, nothing's most specialized.  */
22889 	  fn = TREE_CHAIN (fn);
22890 	  champ = fn;
22891 	  if (!fn)
22892 	    break;
22893 	}
22894     }
22895 
22896   if (champ)
22897     /* Now verify that champ is better than everything earlier in the
22898        instantiation list.  */
22899     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
22900       if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
22901       {
22902         champ = NULL_TREE;
22903         break;
22904       }
22905     }
22906 
22907   processing_template_decl--;
22908 
22909   if (!champ)
22910     return error_mark_node;
22911 
22912   return champ;
22913 }
22914 
22915 /* If DECL is a specialization of some template, return the most
22916    general such template.  Otherwise, returns NULL_TREE.
22917 
22918    For example, given:
22919 
22920      template <class T> struct S { template <class U> void f(U); };
22921 
22922    if TMPL is `template <class U> void S<int>::f(U)' this will return
22923    the full template.  This function will not trace past partial
22924    specializations, however.  For example, given in addition:
22925 
22926      template <class T> struct S<T*> { template <class U> void f(U); };
22927 
22928    if TMPL is `template <class U> void S<int*>::f(U)' this will return
22929    `template <class T> template <class U> S<T*>::f(U)'.  */
22930 
22931 tree
most_general_template(tree decl)22932 most_general_template (tree decl)
22933 {
22934   if (TREE_CODE (decl) != TEMPLATE_DECL)
22935     {
22936       if (tree tinfo = get_template_info (decl))
22937 	decl = TI_TEMPLATE (tinfo);
22938       /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
22939 	 template friend, or a FIELD_DECL for a capture pack.  */
22940       if (TREE_CODE (decl) != TEMPLATE_DECL)
22941 	return NULL_TREE;
22942     }
22943 
22944   /* Look for more and more general templates.  */
22945   while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
22946     {
22947       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
22948 	 (See cp-tree.h for details.)  */
22949       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
22950 	break;
22951 
22952       if (CLASS_TYPE_P (TREE_TYPE (decl))
22953 	  && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
22954 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
22955 	break;
22956 
22957       /* Stop if we run into an explicitly specialized class template.  */
22958       if (!DECL_NAMESPACE_SCOPE_P (decl)
22959 	  && DECL_CONTEXT (decl)
22960 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
22961 	break;
22962 
22963       decl = DECL_TI_TEMPLATE (decl);
22964     }
22965 
22966   return decl;
22967 }
22968 
22969 /* Return the most specialized of the template partial specializations
22970    which can produce TARGET, a specialization of some class or variable
22971    template.  The value returned is actually a TREE_LIST; the TREE_VALUE is
22972    a TEMPLATE_DECL node corresponding to the partial specialization, while
22973    the TREE_PURPOSE is the set of template arguments that must be
22974    substituted into the template pattern in order to generate TARGET.
22975 
22976    If the choice of partial specialization is ambiguous, a diagnostic
22977    is issued, and the error_mark_node is returned.  If there are no
22978    partial specializations matching TARGET, then NULL_TREE is
22979    returned, indicating that the primary template should be used.  */
22980 
22981 static tree
most_specialized_partial_spec(tree target,tsubst_flags_t complain)22982 most_specialized_partial_spec (tree target, tsubst_flags_t complain)
22983 {
22984   tree list = NULL_TREE;
22985   tree t;
22986   tree champ;
22987   int fate;
22988   bool ambiguous_p;
22989   tree outer_args = NULL_TREE;
22990   tree tmpl, args;
22991 
22992   if (TYPE_P (target))
22993     {
22994       tree tinfo = CLASSTYPE_TEMPLATE_INFO (target);
22995       tmpl = TI_TEMPLATE (tinfo);
22996       args = TI_ARGS (tinfo);
22997     }
22998   else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
22999     {
23000       tmpl = TREE_OPERAND (target, 0);
23001       args = TREE_OPERAND (target, 1);
23002     }
23003   else if (VAR_P (target))
23004     {
23005       tree tinfo = DECL_TEMPLATE_INFO (target);
23006       tmpl = TI_TEMPLATE (tinfo);
23007       args = TI_ARGS (tinfo);
23008     }
23009   else
23010     gcc_unreachable ();
23011 
23012   tree main_tmpl = most_general_template (tmpl);
23013 
23014   /* For determining which partial specialization to use, only the
23015      innermost args are interesting.  */
23016   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
23017     {
23018       outer_args = strip_innermost_template_args (args, 1);
23019       args = INNERMOST_TEMPLATE_ARGS (args);
23020     }
23021 
23022   /* The caller hasn't called push_to_top_level yet, but we need
23023      get_partial_spec_bindings to be done in non-template context so that we'll
23024      fully resolve everything.  */
23025   processing_template_decl_sentinel ptds;
23026 
23027   for (t = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl); t; t = TREE_CHAIN (t))
23028     {
23029       tree spec_args;
23030       tree spec_tmpl = TREE_VALUE (t);
23031 
23032       if (outer_args)
23033 	{
23034 	  /* Substitute in the template args from the enclosing class.  */
23035 	  ++processing_template_decl;
23036 	  spec_tmpl = tsubst (spec_tmpl, outer_args, tf_none, NULL_TREE);
23037 	  --processing_template_decl;
23038 	}
23039 
23040       if (spec_tmpl == error_mark_node)
23041 	return error_mark_node;
23042 
23043       spec_args = get_partial_spec_bindings (tmpl, spec_tmpl, args);
23044       if (spec_args)
23045 	{
23046 	  if (outer_args)
23047 	    spec_args = add_to_template_args (outer_args, spec_args);
23048 
23049           /* Keep the candidate only if the constraints are satisfied,
23050              or if we're not compiling with concepts.  */
23051           if (!flag_concepts
23052               || constraints_satisfied_p (spec_tmpl, spec_args))
23053             {
23054               list = tree_cons (spec_args, TREE_VALUE (t), list);
23055               TREE_TYPE (list) = TREE_TYPE (t);
23056             }
23057 	}
23058     }
23059 
23060   if (! list)
23061     return NULL_TREE;
23062 
23063   ambiguous_p = false;
23064   t = list;
23065   champ = t;
23066   t = TREE_CHAIN (t);
23067   for (; t; t = TREE_CHAIN (t))
23068     {
23069       fate = more_specialized_partial_spec (tmpl, champ, t);
23070       if (fate == 1)
23071 	;
23072       else
23073 	{
23074 	  if (fate == 0)
23075 	    {
23076 	      t = TREE_CHAIN (t);
23077 	      if (! t)
23078 		{
23079 		  ambiguous_p = true;
23080 		  break;
23081 		}
23082 	    }
23083 	  champ = t;
23084 	}
23085     }
23086 
23087   if (!ambiguous_p)
23088     for (t = list; t && t != champ; t = TREE_CHAIN (t))
23089       {
23090 	fate = more_specialized_partial_spec (tmpl, champ, t);
23091 	if (fate != 1)
23092 	  {
23093 	    ambiguous_p = true;
23094 	    break;
23095 	  }
23096       }
23097 
23098   if (ambiguous_p)
23099     {
23100       const char *str;
23101       char *spaces = NULL;
23102       if (!(complain & tf_error))
23103 	return error_mark_node;
23104       if (TYPE_P (target))
23105 	error ("ambiguous template instantiation for %q#T", target);
23106       else
23107 	error ("ambiguous template instantiation for %q#D", target);
23108       str = ngettext ("candidate is:", "candidates are:", list_length (list));
23109       for (t = list; t; t = TREE_CHAIN (t))
23110         {
23111 	  tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
23112           inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
23113 		  "%s %#qS", spaces ? spaces : str, subst);
23114           spaces = spaces ? spaces : get_spaces (str);
23115         }
23116       free (spaces);
23117       return error_mark_node;
23118     }
23119 
23120   return champ;
23121 }
23122 
23123 /* Explicitly instantiate DECL.  */
23124 
23125 void
do_decl_instantiation(tree decl,tree storage)23126 do_decl_instantiation (tree decl, tree storage)
23127 {
23128   tree result = NULL_TREE;
23129   int extern_p = 0;
23130 
23131   if (!decl || decl == error_mark_node)
23132     /* An error occurred, for which grokdeclarator has already issued
23133        an appropriate message.  */
23134     return;
23135   else if (! DECL_LANG_SPECIFIC (decl))
23136     {
23137       error ("explicit instantiation of non-template %q#D", decl);
23138       return;
23139     }
23140 
23141   bool var_templ = (DECL_TEMPLATE_INFO (decl)
23142                     && variable_template_p (DECL_TI_TEMPLATE (decl)));
23143 
23144   if (VAR_P (decl) && !var_templ)
23145     {
23146       /* There is an asymmetry here in the way VAR_DECLs and
23147 	 FUNCTION_DECLs are handled by grokdeclarator.  In the case of
23148 	 the latter, the DECL we get back will be marked as a
23149 	 template instantiation, and the appropriate
23150 	 DECL_TEMPLATE_INFO will be set up.  This does not happen for
23151 	 VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
23152 	 should handle VAR_DECLs as it currently handles
23153 	 FUNCTION_DECLs.  */
23154       if (!DECL_CLASS_SCOPE_P (decl))
23155 	{
23156 	  error ("%qD is not a static data member of a class template", decl);
23157 	  return;
23158 	}
23159       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
23160       if (!result || !VAR_P (result))
23161 	{
23162 	  error ("no matching template for %qD found", decl);
23163 	  return;
23164 	}
23165       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
23166 	{
23167 	  error ("type %qT for explicit instantiation %qD does not match "
23168 		 "declared type %qT", TREE_TYPE (result), decl,
23169 		 TREE_TYPE (decl));
23170 	  return;
23171 	}
23172     }
23173   else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
23174     {
23175       error ("explicit instantiation of %q#D", decl);
23176       return;
23177     }
23178   else
23179     result = decl;
23180 
23181   /* Check for various error cases.  Note that if the explicit
23182      instantiation is valid the RESULT will currently be marked as an
23183      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
23184      until we get here.  */
23185 
23186   if (DECL_TEMPLATE_SPECIALIZATION (result))
23187     {
23188       /* DR 259 [temp.spec].
23189 
23190 	 Both an explicit instantiation and a declaration of an explicit
23191 	 specialization shall not appear in a program unless the explicit
23192 	 instantiation follows a declaration of the explicit specialization.
23193 
23194 	 For a given set of template parameters, if an explicit
23195 	 instantiation of a template appears after a declaration of an
23196 	 explicit specialization for that template, the explicit
23197 	 instantiation has no effect.  */
23198       return;
23199     }
23200   else if (DECL_EXPLICIT_INSTANTIATION (result))
23201     {
23202       /* [temp.spec]
23203 
23204 	 No program shall explicitly instantiate any template more
23205 	 than once.
23206 
23207 	 We check DECL_NOT_REALLY_EXTERN so as not to complain when
23208 	 the first instantiation was `extern' and the second is not,
23209 	 and EXTERN_P for the opposite case.  */
23210       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
23211 	permerror (input_location, "duplicate explicit instantiation of %q#D", result);
23212       /* If an "extern" explicit instantiation follows an ordinary
23213 	 explicit instantiation, the template is instantiated.  */
23214       if (extern_p)
23215 	return;
23216     }
23217   else if (!DECL_IMPLICIT_INSTANTIATION (result))
23218     {
23219       error ("no matching template for %qD found", result);
23220       return;
23221     }
23222   else if (!DECL_TEMPLATE_INFO (result))
23223     {
23224       permerror (input_location, "explicit instantiation of non-template %q#D", result);
23225       return;
23226     }
23227 
23228   if (storage == NULL_TREE)
23229     ;
23230   else if (storage == ridpointers[(int) RID_EXTERN])
23231     {
23232       if (!in_system_header_at (input_location) && (cxx_dialect == cxx98))
23233 	pedwarn (input_location, OPT_Wpedantic,
23234 		 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
23235 		 "instantiations");
23236       extern_p = 1;
23237     }
23238   else
23239     error ("storage class %qD applied to template instantiation", storage);
23240 
23241   check_explicit_instantiation_namespace (result);
23242   mark_decl_instantiated (result, extern_p);
23243   if (! extern_p)
23244     instantiate_decl (result, /*defer_ok=*/true,
23245 		      /*expl_inst_class_mem_p=*/false);
23246 }
23247 
23248 static void
mark_class_instantiated(tree t,int extern_p)23249 mark_class_instantiated (tree t, int extern_p)
23250 {
23251   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
23252   SET_CLASSTYPE_INTERFACE_KNOWN (t);
23253   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
23254   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
23255   if (! extern_p)
23256     {
23257       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
23258       rest_of_type_compilation (t, 1);
23259     }
23260 }
23261 
23262 /* Called from do_type_instantiation through binding_table_foreach to
23263    do recursive instantiation for the type bound in ENTRY.  */
23264 static void
bt_instantiate_type_proc(binding_entry entry,void * data)23265 bt_instantiate_type_proc (binding_entry entry, void *data)
23266 {
23267   tree storage = *(tree *) data;
23268 
23269   if (MAYBE_CLASS_TYPE_P (entry->type)
23270       && CLASSTYPE_TEMPLATE_INFO (entry->type)
23271       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
23272     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
23273 }
23274 
23275 /* Perform an explicit instantiation of template class T.  STORAGE, if
23276    non-null, is the RID for extern, inline or static.  COMPLAIN is
23277    nonzero if this is called from the parser, zero if called recursively,
23278    since the standard is unclear (as detailed below).  */
23279 
23280 void
do_type_instantiation(tree t,tree storage,tsubst_flags_t complain)23281 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
23282 {
23283   int extern_p = 0;
23284   int nomem_p = 0;
23285   int static_p = 0;
23286   int previous_instantiation_extern_p = 0;
23287 
23288   if (TREE_CODE (t) == TYPE_DECL)
23289     t = TREE_TYPE (t);
23290 
23291   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
23292     {
23293       tree tmpl =
23294 	(TYPE_TEMPLATE_INFO (t)) ? TYPE_TI_TEMPLATE (t) : NULL;
23295       if (tmpl)
23296 	error ("explicit instantiation of non-class template %qD", tmpl);
23297       else
23298 	error ("explicit instantiation of non-template type %qT", t);
23299       return;
23300     }
23301 
23302   complete_type (t);
23303 
23304   if (!COMPLETE_TYPE_P (t))
23305     {
23306       if (complain & tf_error)
23307 	error ("explicit instantiation of %q#T before definition of template",
23308 	       t);
23309       return;
23310     }
23311 
23312   if (storage != NULL_TREE)
23313     {
23314       if (!in_system_header_at (input_location))
23315 	{
23316 	  if (storage == ridpointers[(int) RID_EXTERN])
23317 	    {
23318 	      if (cxx_dialect == cxx98)
23319 		pedwarn (input_location, OPT_Wpedantic,
23320 			 "ISO C++ 1998 forbids the use of %<extern%> on "
23321 			 "explicit instantiations");
23322 	    }
23323 	  else
23324 	    pedwarn (input_location, OPT_Wpedantic,
23325 		     "ISO C++ forbids the use of %qE"
23326 		     " on explicit instantiations", storage);
23327 	}
23328 
23329       if (storage == ridpointers[(int) RID_INLINE])
23330 	nomem_p = 1;
23331       else if (storage == ridpointers[(int) RID_EXTERN])
23332 	extern_p = 1;
23333       else if (storage == ridpointers[(int) RID_STATIC])
23334 	static_p = 1;
23335       else
23336 	{
23337 	  error ("storage class %qD applied to template instantiation",
23338 		 storage);
23339 	  extern_p = 0;
23340 	}
23341     }
23342 
23343   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
23344     {
23345       /* DR 259 [temp.spec].
23346 
23347 	 Both an explicit instantiation and a declaration of an explicit
23348 	 specialization shall not appear in a program unless the explicit
23349 	 instantiation follows a declaration of the explicit specialization.
23350 
23351 	 For a given set of template parameters, if an explicit
23352 	 instantiation of a template appears after a declaration of an
23353 	 explicit specialization for that template, the explicit
23354 	 instantiation has no effect.  */
23355       return;
23356     }
23357   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
23358     {
23359       /* [temp.spec]
23360 
23361 	 No program shall explicitly instantiate any template more
23362 	 than once.
23363 
23364 	 If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
23365 	 instantiation was `extern'.  If EXTERN_P then the second is.
23366 	 These cases are OK.  */
23367       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
23368 
23369       if (!previous_instantiation_extern_p && !extern_p
23370 	  && (complain & tf_error))
23371 	permerror (input_location, "duplicate explicit instantiation of %q#T", t);
23372 
23373       /* If we've already instantiated the template, just return now.  */
23374       if (!CLASSTYPE_INTERFACE_ONLY (t))
23375 	return;
23376     }
23377 
23378   check_explicit_instantiation_namespace (TYPE_NAME (t));
23379   mark_class_instantiated (t, extern_p);
23380 
23381   if (nomem_p)
23382     return;
23383 
23384   /* In contrast to implicit instantiation, where only the
23385      declarations, and not the definitions, of members are
23386      instantiated, we have here:
23387 
23388 	 [temp.explicit]
23389 
23390 	 The explicit instantiation of a class template specialization
23391 	 implies the instantiation of all of its members not
23392 	 previously explicitly specialized in the translation unit
23393 	 containing the explicit instantiation.
23394 
23395      Of course, we can't instantiate member template classes, since we
23396      don't have any arguments for them.  Note that the standard is
23397      unclear on whether the instantiation of the members are
23398      *explicit* instantiations or not.  However, the most natural
23399      interpretation is that it should be an explicit
23400      instantiation.  */
23401   for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
23402     if ((VAR_P (fld)
23403 	 || (TREE_CODE (fld) == FUNCTION_DECL
23404 	     && !static_p
23405 	     && user_provided_p (fld)))
23406 	&& DECL_TEMPLATE_INSTANTIATION (fld))
23407       {
23408 	mark_decl_instantiated (fld, extern_p);
23409 	if (! extern_p)
23410 	  instantiate_decl (fld, /*defer_ok=*/true,
23411 			    /*expl_inst_class_mem_p=*/true);
23412       }
23413 
23414   if (CLASSTYPE_NESTED_UTDS (t))
23415     binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
23416 			   bt_instantiate_type_proc, &storage);
23417 }
23418 
23419 /* Given a function DECL, which is a specialization of TMPL, modify
23420    DECL to be a re-instantiation of TMPL with the same template
23421    arguments.  TMPL should be the template into which tsubst'ing
23422    should occur for DECL, not the most general template.
23423 
23424    One reason for doing this is a scenario like this:
23425 
23426      template <class T>
23427      void f(const T&, int i);
23428 
23429      void g() { f(3, 7); }
23430 
23431      template <class T>
23432      void f(const T& t, const int i) { }
23433 
23434    Note that when the template is first instantiated, with
23435    instantiate_template, the resulting DECL will have no name for the
23436    first parameter, and the wrong type for the second.  So, when we go
23437    to instantiate the DECL, we regenerate it.  */
23438 
23439 static void
regenerate_decl_from_template(tree decl,tree tmpl,tree args)23440 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
23441 {
23442   /* The arguments used to instantiate DECL, from the most general
23443      template.  */
23444   tree code_pattern;
23445 
23446   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
23447 
23448   /* Make sure that we can see identifiers, and compute access
23449      correctly.  */
23450   push_access_scope (decl);
23451 
23452   if (TREE_CODE (decl) == FUNCTION_DECL)
23453     {
23454       tree decl_parm;
23455       tree pattern_parm;
23456       tree specs;
23457       int args_depth;
23458       int parms_depth;
23459 
23460       args_depth = TMPL_ARGS_DEPTH (args);
23461       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
23462       if (args_depth > parms_depth)
23463 	args = get_innermost_template_args (args, parms_depth);
23464 
23465       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
23466 					      args, tf_error, NULL_TREE,
23467 					      /*defer_ok*/false);
23468       if (specs && specs != error_mark_node)
23469 	TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
23470 						    specs);
23471 
23472       /* Merge parameter declarations.  */
23473       decl_parm = skip_artificial_parms_for (decl,
23474 					     DECL_ARGUMENTS (decl));
23475       pattern_parm
23476 	= skip_artificial_parms_for (code_pattern,
23477 				     DECL_ARGUMENTS (code_pattern));
23478       while (decl_parm && !DECL_PACK_P (pattern_parm))
23479 	{
23480 	  tree parm_type;
23481 	  tree attributes;
23482 
23483 	  if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
23484 	    DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
23485 	  parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
23486 			      NULL_TREE);
23487 	  parm_type = type_decays_to (parm_type);
23488 	  if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
23489 	    TREE_TYPE (decl_parm) = parm_type;
23490 	  attributes = DECL_ATTRIBUTES (pattern_parm);
23491 	  if (DECL_ATTRIBUTES (decl_parm) != attributes)
23492 	    {
23493 	      DECL_ATTRIBUTES (decl_parm) = attributes;
23494 	      cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
23495 	    }
23496 	  decl_parm = DECL_CHAIN (decl_parm);
23497 	  pattern_parm = DECL_CHAIN (pattern_parm);
23498 	}
23499       /* Merge any parameters that match with the function parameter
23500          pack.  */
23501       if (pattern_parm && DECL_PACK_P (pattern_parm))
23502         {
23503           int i, len;
23504           tree expanded_types;
23505           /* Expand the TYPE_PACK_EXPANSION that provides the types for
23506              the parameters in this function parameter pack.  */
23507           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm),
23508                                                  args, tf_error, NULL_TREE);
23509           len = TREE_VEC_LENGTH (expanded_types);
23510           for (i = 0; i < len; i++)
23511             {
23512               tree parm_type;
23513               tree attributes;
23514 
23515               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
23516                 /* Rename the parameter to include the index.  */
23517                 DECL_NAME (decl_parm) =
23518                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
23519               parm_type = TREE_VEC_ELT (expanded_types, i);
23520               parm_type = type_decays_to (parm_type);
23521               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
23522                 TREE_TYPE (decl_parm) = parm_type;
23523               attributes = DECL_ATTRIBUTES (pattern_parm);
23524               if (DECL_ATTRIBUTES (decl_parm) != attributes)
23525                 {
23526                   DECL_ATTRIBUTES (decl_parm) = attributes;
23527                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
23528                 }
23529               decl_parm = DECL_CHAIN (decl_parm);
23530             }
23531         }
23532       /* Merge additional specifiers from the CODE_PATTERN.  */
23533       if (DECL_DECLARED_INLINE_P (code_pattern)
23534 	  && !DECL_DECLARED_INLINE_P (decl))
23535 	DECL_DECLARED_INLINE_P (decl) = 1;
23536     }
23537   else if (VAR_P (decl))
23538     {
23539       start_lambda_scope (decl);
23540       DECL_INITIAL (decl) =
23541 	tsubst_expr (DECL_INITIAL (code_pattern), args,
23542 		     tf_error, DECL_TI_TEMPLATE (decl),
23543 		     /*integral_constant_expression_p=*/false);
23544       finish_lambda_scope ();
23545       if (VAR_HAD_UNKNOWN_BOUND (decl))
23546 	TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
23547 				   tf_error, DECL_TI_TEMPLATE (decl));
23548     }
23549   else
23550     gcc_unreachable ();
23551 
23552   pop_access_scope (decl);
23553 }
23554 
23555 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
23556    substituted to get DECL.  */
23557 
23558 tree
template_for_substitution(tree decl)23559 template_for_substitution (tree decl)
23560 {
23561   tree tmpl = DECL_TI_TEMPLATE (decl);
23562 
23563   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
23564      for the instantiation.  This is not always the most general
23565      template.  Consider, for example:
23566 
23567 	template <class T>
23568 	struct S { template <class U> void f();
23569 		   template <> void f<int>(); };
23570 
23571      and an instantiation of S<double>::f<int>.  We want TD to be the
23572      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
23573   while (/* An instantiation cannot have a definition, so we need a
23574 	    more general template.  */
23575 	 DECL_TEMPLATE_INSTANTIATION (tmpl)
23576 	   /* We must also deal with friend templates.  Given:
23577 
23578 		template <class T> struct S {
23579 		  template <class U> friend void f() {};
23580 		};
23581 
23582 	      S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
23583 	      so far as the language is concerned, but that's still
23584 	      where we get the pattern for the instantiation from.  On
23585 	      other hand, if the definition comes outside the class, say:
23586 
23587 		template <class T> struct S {
23588 		  template <class U> friend void f();
23589 		};
23590 		template <class U> friend void f() {}
23591 
23592 	      we don't need to look any further.  That's what the check for
23593 	      DECL_INITIAL is for.  */
23594 	  || (TREE_CODE (decl) == FUNCTION_DECL
23595 	      && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
23596 	      && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
23597     {
23598       /* The present template, TD, should not be a definition.  If it
23599 	 were a definition, we should be using it!  Note that we
23600 	 cannot restructure the loop to just keep going until we find
23601 	 a template with a definition, since that might go too far if
23602 	 a specialization was declared, but not defined.  */
23603 
23604       /* Fetch the more general template.  */
23605       tmpl = DECL_TI_TEMPLATE (tmpl);
23606     }
23607 
23608   return tmpl;
23609 }
23610 
23611 /* Returns true if we need to instantiate this template instance even if we
23612    know we aren't going to emit it.  */
23613 
23614 bool
always_instantiate_p(tree decl)23615 always_instantiate_p (tree decl)
23616 {
23617   /* We always instantiate inline functions so that we can inline them.  An
23618      explicit instantiation declaration prohibits implicit instantiation of
23619      non-inline functions.  With high levels of optimization, we would
23620      normally inline non-inline functions -- but we're not allowed to do
23621      that for "extern template" functions.  Therefore, we check
23622      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
23623   return ((TREE_CODE (decl) == FUNCTION_DECL
23624 	   && (DECL_DECLARED_INLINE_P (decl)
23625 	       || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
23626 	  /* And we need to instantiate static data members so that
23627 	     their initializers are available in integral constant
23628 	     expressions.  */
23629 	  || (VAR_P (decl)
23630 	      && decl_maybe_constant_var_p (decl)));
23631 }
23632 
23633 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
23634    instantiate it now, modifying TREE_TYPE (fn).  Returns false on
23635    error, true otherwise.  */
23636 
23637 bool
maybe_instantiate_noexcept(tree fn,tsubst_flags_t complain)23638 maybe_instantiate_noexcept (tree fn, tsubst_flags_t complain)
23639 {
23640   tree fntype, spec, noex, clone;
23641 
23642   /* Don't instantiate a noexcept-specification from template context.  */
23643   if (processing_template_decl
23644       && (!flag_noexcept_type || type_dependent_expression_p (fn)))
23645     return true;
23646 
23647   if (DECL_CLONED_FUNCTION_P (fn))
23648     fn = DECL_CLONED_FUNCTION (fn);
23649   fntype = TREE_TYPE (fn);
23650   spec = TYPE_RAISES_EXCEPTIONS (fntype);
23651 
23652   if (!spec || !TREE_PURPOSE (spec))
23653     return true;
23654 
23655   noex = TREE_PURPOSE (spec);
23656 
23657   if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
23658     {
23659       static hash_set<tree>* fns = new hash_set<tree>;
23660       bool added = false;
23661       if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
23662 	spec = get_defaulted_eh_spec (fn, complain);
23663       else if (!(added = !fns->add (fn)))
23664 	{
23665 	  /* If hash_set::add returns true, the element was already there.  */
23666 	  location_t loc = EXPR_LOC_OR_LOC (DEFERRED_NOEXCEPT_PATTERN (noex),
23667 					    DECL_SOURCE_LOCATION (fn));
23668 	  error_at (loc,
23669 		    "exception specification of %qD depends on itself",
23670 		    fn);
23671 	  spec = noexcept_false_spec;
23672 	}
23673       else if (push_tinst_level (fn))
23674 	{
23675 	  push_access_scope (fn);
23676 	  push_deferring_access_checks (dk_no_deferred);
23677 	  input_location = DECL_SOURCE_LOCATION (fn);
23678 	  noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
23679 					DEFERRED_NOEXCEPT_ARGS (noex),
23680 					tf_warning_or_error, fn,
23681 					/*function_p=*/false,
23682 					/*integral_constant_expression_p=*/true);
23683 	  spec = build_noexcept_spec (noex, tf_warning_or_error);
23684 	  pop_deferring_access_checks ();
23685 	  pop_access_scope (fn);
23686 	  pop_tinst_level ();
23687 	  if (spec == error_mark_node)
23688 	    spec = noexcept_false_spec;
23689 	}
23690       else
23691 	spec = noexcept_false_spec;
23692 
23693       if (added)
23694 	fns->remove (fn);
23695 
23696       if (spec == error_mark_node)
23697 	return false;
23698 
23699       TREE_TYPE (fn) = build_exception_variant (fntype, spec);
23700     }
23701 
23702   FOR_EACH_CLONE (clone, fn)
23703     {
23704       if (TREE_TYPE (clone) == fntype)
23705 	TREE_TYPE (clone) = TREE_TYPE (fn);
23706       else
23707 	TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone), spec);
23708     }
23709 
23710   return true;
23711 }
23712 
23713 /* We're starting to process the function INST, an instantiation of PATTERN;
23714    add their parameters to local_specializations.  */
23715 
23716 static void
register_parameter_specializations(tree pattern,tree inst)23717 register_parameter_specializations (tree pattern, tree inst)
23718 {
23719   tree tmpl_parm = DECL_ARGUMENTS (pattern);
23720   tree spec_parm = DECL_ARGUMENTS (inst);
23721   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (inst))
23722     {
23723       register_local_specialization (spec_parm, tmpl_parm);
23724       spec_parm = skip_artificial_parms_for (inst, spec_parm);
23725       tmpl_parm = skip_artificial_parms_for (pattern, tmpl_parm);
23726     }
23727   for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
23728     {
23729       if (!DECL_PACK_P (tmpl_parm))
23730 	{
23731 	  register_local_specialization (spec_parm, tmpl_parm);
23732 	  spec_parm = DECL_CHAIN (spec_parm);
23733 	}
23734       else
23735 	{
23736 	  /* Register the (value) argument pack as a specialization of
23737 	     TMPL_PARM, then move on.  */
23738 	  tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
23739 	  register_local_specialization (argpack, tmpl_parm);
23740 	}
23741     }
23742   gcc_assert (!spec_parm);
23743 }
23744 
23745 /* Produce the definition of D, a _DECL generated from a template.  If
23746    DEFER_OK is true, then we don't have to actually do the
23747    instantiation now; we just have to do it sometime.  Normally it is
23748    an error if this is an explicit instantiation but D is undefined.
23749    EXPL_INST_CLASS_MEM_P is true iff D is a member of an explicitly
23750    instantiated class template.  */
23751 
23752 tree
instantiate_decl(tree d,bool defer_ok,bool expl_inst_class_mem_p)23753 instantiate_decl (tree d, bool defer_ok, bool expl_inst_class_mem_p)
23754 {
23755   tree tmpl = DECL_TI_TEMPLATE (d);
23756   tree gen_args;
23757   tree args;
23758   tree td;
23759   tree code_pattern;
23760   tree spec;
23761   tree gen_tmpl;
23762   bool pattern_defined;
23763   location_t saved_loc = input_location;
23764   int saved_unevaluated_operand = cp_unevaluated_operand;
23765   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
23766   bool external_p;
23767   bool deleted_p;
23768 
23769   /* This function should only be used to instantiate templates for
23770      functions and static member variables.  */
23771   gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
23772 
23773   /* A concept is never instantiated. */
23774   gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
23775 
23776   /* Variables are never deferred; if instantiation is required, they
23777      are instantiated right away.  That allows for better code in the
23778      case that an expression refers to the value of the variable --
23779      if the variable has a constant value the referring expression can
23780      take advantage of that fact.  */
23781   if (VAR_P (d))
23782     defer_ok = false;
23783 
23784   /* Don't instantiate cloned functions.  Instead, instantiate the
23785      functions they cloned.  */
23786   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
23787     d = DECL_CLONED_FUNCTION (d);
23788 
23789   if (DECL_TEMPLATE_INSTANTIATED (d)
23790       || (TREE_CODE (d) == FUNCTION_DECL
23791 	  && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
23792       || DECL_TEMPLATE_SPECIALIZATION (d))
23793     /* D has already been instantiated or explicitly specialized, so
23794        there's nothing for us to do here.
23795 
23796        It might seem reasonable to check whether or not D is an explicit
23797        instantiation, and, if so, stop here.  But when an explicit
23798        instantiation is deferred until the end of the compilation,
23799        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
23800        the instantiation.  */
23801     return d;
23802 
23803   /* Check to see whether we know that this template will be
23804      instantiated in some other file, as with "extern template"
23805      extension.  */
23806   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
23807 
23808   /* In general, we do not instantiate such templates.  */
23809   if (external_p && !always_instantiate_p (d))
23810     return d;
23811 
23812   gen_tmpl = most_general_template (tmpl);
23813   gen_args = DECL_TI_ARGS (d);
23814 
23815   if (tmpl != gen_tmpl)
23816     /* We should already have the extra args.  */
23817     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
23818 		== TMPL_ARGS_DEPTH (gen_args));
23819   /* And what's in the hash table should match D.  */
23820   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
23821 	      || spec == NULL_TREE);
23822 
23823   /* This needs to happen before any tsubsting.  */
23824   if (! push_tinst_level (d))
23825     return d;
23826 
23827   timevar_push (TV_TEMPLATE_INST);
23828 
23829   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
23830      for the instantiation.  */
23831   td = template_for_substitution (d);
23832   args = gen_args;
23833 
23834   if (VAR_P (d))
23835     {
23836       /* Look up an explicit specialization, if any.  */
23837       tree tid = lookup_template_variable (gen_tmpl, gen_args);
23838       tree elt = most_specialized_partial_spec (tid, tf_warning_or_error);
23839       if (elt && elt != error_mark_node)
23840 	{
23841 	  td = TREE_VALUE (elt);
23842 	  args = TREE_PURPOSE (elt);
23843 	}
23844     }
23845 
23846   code_pattern = DECL_TEMPLATE_RESULT (td);
23847 
23848   /* We should never be trying to instantiate a member of a class
23849      template or partial specialization.  */
23850   gcc_assert (d != code_pattern);
23851 
23852   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
23853       || DECL_TEMPLATE_SPECIALIZATION (td))
23854     /* In the case of a friend template whose definition is provided
23855        outside the class, we may have too many arguments.  Drop the
23856        ones we don't need.  The same is true for specializations.  */
23857     args = get_innermost_template_args
23858       (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
23859 
23860   if (TREE_CODE (d) == FUNCTION_DECL)
23861     {
23862       deleted_p = DECL_DELETED_FN (code_pattern);
23863       pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
23864 			  && DECL_INITIAL (code_pattern) != error_mark_node)
23865 			 || DECL_DEFAULTED_OUTSIDE_CLASS_P (code_pattern)
23866 			 || deleted_p);
23867     }
23868   else
23869     {
23870       deleted_p = false;
23871       if (DECL_CLASS_SCOPE_P (code_pattern))
23872 	pattern_defined = (! DECL_IN_AGGR_P (code_pattern)
23873 			   || DECL_INLINE_VAR_P (code_pattern));
23874       else
23875 	pattern_defined = ! DECL_EXTERNAL (code_pattern);
23876     }
23877 
23878   /* We may be in the middle of deferred access check.  Disable it now.  */
23879   push_deferring_access_checks (dk_no_deferred);
23880 
23881   /* Unless an explicit instantiation directive has already determined
23882      the linkage of D, remember that a definition is available for
23883      this entity.  */
23884   if (pattern_defined
23885       && !DECL_INTERFACE_KNOWN (d)
23886       && !DECL_NOT_REALLY_EXTERN (d))
23887     mark_definable (d);
23888 
23889   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
23890   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
23891   input_location = DECL_SOURCE_LOCATION (d);
23892 
23893   /* If D is a member of an explicitly instantiated class template,
23894      and no definition is available, treat it like an implicit
23895      instantiation.  */
23896   if (!pattern_defined && expl_inst_class_mem_p
23897       && DECL_EXPLICIT_INSTANTIATION (d))
23898     {
23899       /* Leave linkage flags alone on instantiations with anonymous
23900 	 visibility.  */
23901       if (TREE_PUBLIC (d))
23902 	{
23903 	  DECL_NOT_REALLY_EXTERN (d) = 0;
23904 	  DECL_INTERFACE_KNOWN (d) = 0;
23905 	}
23906       SET_DECL_IMPLICIT_INSTANTIATION (d);
23907     }
23908 
23909   /* Defer all other templates, unless we have been explicitly
23910      forbidden from doing so.  */
23911   if (/* If there is no definition, we cannot instantiate the
23912 	 template.  */
23913       ! pattern_defined
23914       /* If it's OK to postpone instantiation, do so.  */
23915       || defer_ok
23916       /* If this is a static data member that will be defined
23917 	 elsewhere, we don't want to instantiate the entire data
23918 	 member, but we do want to instantiate the initializer so that
23919 	 we can substitute that elsewhere.  */
23920       || (external_p && VAR_P (d))
23921       /* Handle here a deleted function too, avoid generating
23922 	 its body (c++/61080).  */
23923       || deleted_p)
23924     {
23925       /* The definition of the static data member is now required so
23926 	 we must substitute the initializer.  */
23927       if (VAR_P (d)
23928 	  && !DECL_INITIAL (d)
23929 	  && DECL_INITIAL (code_pattern))
23930 	{
23931 	  tree ns;
23932 	  tree init;
23933 	  bool const_init = false;
23934 	  bool enter_context = DECL_CLASS_SCOPE_P (d);
23935 
23936 	  ns = decl_namespace_context (d);
23937 	  push_nested_namespace (ns);
23938 	  if (enter_context)
23939 	    push_nested_class (DECL_CONTEXT (d));
23940 	  init = tsubst_expr (DECL_INITIAL (code_pattern),
23941 			      args,
23942 			      tf_warning_or_error, NULL_TREE,
23943 			      /*integral_constant_expression_p=*/false);
23944 	  /* If instantiating the initializer involved instantiating this
23945 	     again, don't call cp_finish_decl twice.  */
23946 	  if (!DECL_INITIAL (d))
23947 	    {
23948 	      /* Make sure the initializer is still constant, in case of
23949 		 circular dependency (template/instantiate6.C). */
23950 	      const_init
23951 		= DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
23952 	      cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
23953 			      /*asmspec_tree=*/NULL_TREE,
23954 			      LOOKUP_ONLYCONVERTING);
23955 	    }
23956 	  if (enter_context)
23957 	    pop_nested_class ();
23958 	  pop_nested_namespace (ns);
23959 	}
23960 
23961       /* We restore the source position here because it's used by
23962 	 add_pending_template.  */
23963       input_location = saved_loc;
23964 
23965       if (at_eof && !pattern_defined
23966 	  && DECL_EXPLICIT_INSTANTIATION (d)
23967 	  && DECL_NOT_REALLY_EXTERN (d))
23968 	/* [temp.explicit]
23969 
23970 	   The definition of a non-exported function template, a
23971 	   non-exported member function template, or a non-exported
23972 	   member function or static data member of a class template
23973 	   shall be present in every translation unit in which it is
23974 	   explicitly instantiated.  */
23975 	permerror (input_location,  "explicit instantiation of %qD "
23976 		   "but no definition available", d);
23977 
23978       /* If we're in unevaluated context, we just wanted to get the
23979 	 constant value; this isn't an odr use, so don't queue
23980 	 a full instantiation.  */
23981       if (cp_unevaluated_operand != 0)
23982 	goto out;
23983       /* ??? Historically, we have instantiated inline functions, even
23984 	 when marked as "extern template".  */
23985       if (!(external_p && VAR_P (d)))
23986 	add_pending_template (d);
23987       goto out;
23988     }
23989   /* Tell the repository that D is available in this translation unit
23990      -- and see if it is supposed to be instantiated here.  */
23991   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
23992     {
23993       /* In a PCH file, despite the fact that the repository hasn't
23994 	 requested instantiation in the PCH it is still possible that
23995 	 an instantiation will be required in a file that includes the
23996 	 PCH.  */
23997       if (pch_file)
23998 	add_pending_template (d);
23999       /* Instantiate inline functions so that the inliner can do its
24000 	 job, even though we'll not be emitting a copy of this
24001 	 function.  */
24002       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
24003 	goto out;
24004     }
24005 
24006   bool push_to_top, nested;
24007   tree fn_context;
24008   fn_context = decl_function_context (d);
24009   if (LAMBDA_FUNCTION_P (d))
24010     /* tsubst_lambda_expr resolved any references to enclosing functions.  */
24011     fn_context = NULL_TREE;
24012   nested = current_function_decl != NULL_TREE;
24013   push_to_top = !(nested && fn_context == current_function_decl);
24014 
24015   vec<tree> omp_privatization_save;
24016   if (nested)
24017     save_omp_privatization_clauses (omp_privatization_save);
24018 
24019   if (push_to_top)
24020     push_to_top_level ();
24021   else
24022     {
24023       push_function_context ();
24024       cp_unevaluated_operand = 0;
24025       c_inhibit_evaluation_warnings = 0;
24026     }
24027 
24028   /* Mark D as instantiated so that recursive calls to
24029      instantiate_decl do not try to instantiate it again.  */
24030   DECL_TEMPLATE_INSTANTIATED (d) = 1;
24031 
24032   /* Regenerate the declaration in case the template has been modified
24033      by a subsequent redeclaration.  */
24034   regenerate_decl_from_template (d, td, args);
24035 
24036   /* We already set the file and line above.  Reset them now in case
24037      they changed as a result of calling regenerate_decl_from_template.  */
24038   input_location = DECL_SOURCE_LOCATION (d);
24039 
24040   if (VAR_P (d))
24041     {
24042       tree init;
24043       bool const_init = false;
24044 
24045       /* Clear out DECL_RTL; whatever was there before may not be right
24046 	 since we've reset the type of the declaration.  */
24047       SET_DECL_RTL (d, NULL);
24048       DECL_IN_AGGR_P (d) = 0;
24049 
24050       /* The initializer is placed in DECL_INITIAL by
24051 	 regenerate_decl_from_template so we don't need to
24052 	 push/pop_access_scope again here.  Pull it out so that
24053 	 cp_finish_decl can process it.  */
24054       init = DECL_INITIAL (d);
24055       DECL_INITIAL (d) = NULL_TREE;
24056       DECL_INITIALIZED_P (d) = 0;
24057 
24058       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
24059 	 initializer.  That function will defer actual emission until
24060 	 we have a chance to determine linkage.  */
24061       DECL_EXTERNAL (d) = 0;
24062 
24063       /* Enter the scope of D so that access-checking works correctly.  */
24064       bool enter_context = DECL_CLASS_SCOPE_P (d);
24065       if (enter_context)
24066         push_nested_class (DECL_CONTEXT (d));
24067 
24068       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
24069       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
24070 
24071       if (enter_context)
24072         pop_nested_class ();
24073 
24074       if (variable_template_p (gen_tmpl))
24075 	note_variable_template_instantiation (d);
24076     }
24077   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
24078     synthesize_method (d);
24079   else if (TREE_CODE (d) == FUNCTION_DECL)
24080     {
24081       /* Set up the list of local specializations.  */
24082       local_specialization_stack lss (push_to_top ? lss_blank : lss_copy);
24083       tree block = NULL_TREE;
24084 
24085       /* Set up context.  */
24086       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
24087 	  && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
24088 	block = push_stmt_list ();
24089       else
24090 	start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
24091 
24092       /* Some typedefs referenced from within the template code need to be
24093 	 access checked at template instantiation time, i.e now. These
24094 	 types were added to the template at parsing time. Let's get those
24095 	 and perform the access checks then.  */
24096       perform_typedefs_access_check (DECL_TEMPLATE_RESULT (td),
24097 				     args);
24098 
24099       /* Create substitution entries for the parameters.  */
24100       register_parameter_specializations (code_pattern, d);
24101 
24102       /* Substitute into the body of the function.  */
24103       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
24104 	tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
24105 			tf_warning_or_error, tmpl);
24106       else
24107 	{
24108 	  tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
24109 		       tf_warning_or_error, tmpl,
24110 		       /*integral_constant_expression_p=*/false);
24111 
24112 	  /* Set the current input_location to the end of the function
24113 	     so that finish_function knows where we are.  */
24114 	  input_location
24115 	    = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
24116 
24117 	  /* Remember if we saw an infinite loop in the template.  */
24118 	  current_function_infinite_loop
24119 	    = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
24120 	}
24121 
24122       /* Finish the function.  */
24123       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
24124 	  && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
24125 	DECL_SAVED_TREE (d) = pop_stmt_list (block);
24126       else
24127 	{
24128 	  d = finish_function (/*inline_p=*/false);
24129 	  expand_or_defer_fn (d);
24130 	}
24131 
24132       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
24133 	cp_check_omp_declare_reduction (d);
24134     }
24135 
24136   /* We're not deferring instantiation any more.  */
24137   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
24138 
24139   if (push_to_top)
24140     pop_from_top_level ();
24141   else
24142     pop_function_context ();
24143 
24144   if (nested)
24145     restore_omp_privatization_clauses (omp_privatization_save);
24146 
24147 out:
24148   pop_deferring_access_checks ();
24149   timevar_pop (TV_TEMPLATE_INST);
24150   pop_tinst_level ();
24151   input_location = saved_loc;
24152   cp_unevaluated_operand = saved_unevaluated_operand;
24153   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
24154 
24155   return d;
24156 }
24157 
24158 /* Run through the list of templates that we wish we could
24159    instantiate, and instantiate any we can.  RETRIES is the
24160    number of times we retry pending template instantiation.  */
24161 
24162 void
instantiate_pending_templates(int retries)24163 instantiate_pending_templates (int retries)
24164 {
24165   int reconsider;
24166   location_t saved_loc = input_location;
24167 
24168   /* Instantiating templates may trigger vtable generation.  This in turn
24169      may require further template instantiations.  We place a limit here
24170      to avoid infinite loop.  */
24171   if (pending_templates && retries >= max_tinst_depth)
24172     {
24173       tree decl = pending_templates->tinst->maybe_get_node ();
24174 
24175       fatal_error (input_location,
24176 		   "template instantiation depth exceeds maximum of %d"
24177                    " instantiating %q+D, possibly from virtual table generation"
24178                    " (use -ftemplate-depth= to increase the maximum)",
24179                    max_tinst_depth, decl);
24180       if (TREE_CODE (decl) == FUNCTION_DECL)
24181 	/* Pretend that we defined it.  */
24182 	DECL_INITIAL (decl) = error_mark_node;
24183       return;
24184     }
24185 
24186   do
24187     {
24188       struct pending_template **t = &pending_templates;
24189       struct pending_template *last = NULL;
24190       reconsider = 0;
24191       while (*t)
24192 	{
24193 	  tree instantiation = reopen_tinst_level ((*t)->tinst);
24194 	  bool complete = false;
24195 
24196 	  if (TYPE_P (instantiation))
24197 	    {
24198 	      if (!COMPLETE_TYPE_P (instantiation))
24199 		{
24200 		  instantiate_class_template (instantiation);
24201 		  if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
24202 		    for (tree fld = TYPE_FIELDS (instantiation);
24203 			 fld; fld = TREE_CHAIN (fld))
24204 		      if ((VAR_P (fld)
24205 			   || (TREE_CODE (fld) == FUNCTION_DECL
24206 			       && !DECL_ARTIFICIAL (fld)))
24207 			  && DECL_TEMPLATE_INSTANTIATION (fld))
24208 			instantiate_decl (fld,
24209 					  /*defer_ok=*/false,
24210 					  /*expl_inst_class_mem_p=*/false);
24211 
24212 		  if (COMPLETE_TYPE_P (instantiation))
24213 		    reconsider = 1;
24214 		}
24215 
24216 	      complete = COMPLETE_TYPE_P (instantiation);
24217 	    }
24218 	  else
24219 	    {
24220 	      if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
24221 		  && !DECL_TEMPLATE_INSTANTIATED (instantiation))
24222 		{
24223 		  instantiation
24224 		    = instantiate_decl (instantiation,
24225 					/*defer_ok=*/false,
24226 					/*expl_inst_class_mem_p=*/false);
24227 		  if (DECL_TEMPLATE_INSTANTIATED (instantiation))
24228 		    reconsider = 1;
24229 		}
24230 
24231 	      complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
24232 			  || DECL_TEMPLATE_INSTANTIATED (instantiation));
24233 	    }
24234 
24235 	  if (complete)
24236 	    {
24237 	      /* If INSTANTIATION has been instantiated, then we don't
24238 		 need to consider it again in the future.  */
24239 	      struct pending_template *drop = *t;
24240 	      *t = (*t)->next;
24241 	      set_refcount_ptr (drop->tinst);
24242 	      pending_template_freelist ().free (drop);
24243 	    }
24244 	  else
24245 	    {
24246 	      last = *t;
24247 	      t = &(*t)->next;
24248 	    }
24249 	  tinst_depth = 0;
24250 	  set_refcount_ptr (current_tinst_level);
24251 	}
24252       last_pending_template = last;
24253     }
24254   while (reconsider);
24255 
24256   input_location = saved_loc;
24257 }
24258 
24259 /* Substitute ARGVEC into T, which is a list of initializers for
24260    either base class or a non-static data member.  The TREE_PURPOSEs
24261    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
24262    instantiate_decl.  */
24263 
24264 static tree
tsubst_initializer_list(tree t,tree argvec)24265 tsubst_initializer_list (tree t, tree argvec)
24266 {
24267   tree inits = NULL_TREE;
24268   tree target_ctor = error_mark_node;
24269 
24270   for (; t; t = TREE_CHAIN (t))
24271     {
24272       tree decl;
24273       tree init;
24274       tree expanded_bases = NULL_TREE;
24275       tree expanded_arguments = NULL_TREE;
24276       int i, len = 1;
24277 
24278       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
24279         {
24280           tree expr;
24281           tree arg;
24282 
24283           /* Expand the base class expansion type into separate base
24284              classes.  */
24285           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
24286                                                  tf_warning_or_error,
24287                                                  NULL_TREE);
24288           if (expanded_bases == error_mark_node)
24289             continue;
24290 
24291           /* We'll be building separate TREE_LISTs of arguments for
24292              each base.  */
24293           len = TREE_VEC_LENGTH (expanded_bases);
24294           expanded_arguments = make_tree_vec (len);
24295           for (i = 0; i < len; i++)
24296             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
24297 
24298           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
24299              expand each argument in the TREE_VALUE of t.  */
24300           expr = make_node (EXPR_PACK_EXPANSION);
24301 	  PACK_EXPANSION_LOCAL_P (expr) = true;
24302           PACK_EXPANSION_PARAMETER_PACKS (expr) =
24303             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
24304 
24305 	  if (TREE_VALUE (t) == void_type_node)
24306 	    /* VOID_TYPE_NODE is used to indicate
24307 	       value-initialization.  */
24308 	    {
24309 	      for (i = 0; i < len; i++)
24310 		TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
24311 	    }
24312 	  else
24313 	    {
24314 	      /* Substitute parameter packs into each argument in the
24315 		 TREE_LIST.  */
24316 	      in_base_initializer = 1;
24317 	      for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
24318 		{
24319 		  tree expanded_exprs;
24320 
24321 		  /* Expand the argument.  */
24322 		  SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
24323 		  expanded_exprs
24324 		    = tsubst_pack_expansion (expr, argvec,
24325 					     tf_warning_or_error,
24326 					     NULL_TREE);
24327 		  if (expanded_exprs == error_mark_node)
24328 		    continue;
24329 
24330 		  /* Prepend each of the expanded expressions to the
24331 		     corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
24332 		  for (i = 0; i < len; i++)
24333 		    {
24334 		      TREE_VEC_ELT (expanded_arguments, i) =
24335 			tree_cons (NULL_TREE,
24336 				   TREE_VEC_ELT (expanded_exprs, i),
24337 				   TREE_VEC_ELT (expanded_arguments, i));
24338 		    }
24339 		}
24340 	      in_base_initializer = 0;
24341 
24342 	      /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
24343 		 since we built them backwards.  */
24344 	      for (i = 0; i < len; i++)
24345 		{
24346 		  TREE_VEC_ELT (expanded_arguments, i) =
24347 		    nreverse (TREE_VEC_ELT (expanded_arguments, i));
24348 		}
24349 	    }
24350         }
24351 
24352       for (i = 0; i < len; ++i)
24353         {
24354           if (expanded_bases)
24355             {
24356               decl = TREE_VEC_ELT (expanded_bases, i);
24357               decl = expand_member_init (decl);
24358               init = TREE_VEC_ELT (expanded_arguments, i);
24359             }
24360           else
24361             {
24362 	      tree tmp;
24363               decl = tsubst_copy (TREE_PURPOSE (t), argvec,
24364                                   tf_warning_or_error, NULL_TREE);
24365 
24366               decl = expand_member_init (decl);
24367               if (decl && !DECL_P (decl))
24368                 in_base_initializer = 1;
24369 
24370 	      init = TREE_VALUE (t);
24371 	      tmp = init;
24372 	      if (init != void_type_node)
24373 		init = tsubst_expr (init, argvec,
24374 				    tf_warning_or_error, NULL_TREE,
24375 				    /*integral_constant_expression_p=*/false);
24376 	      if (init == NULL_TREE && tmp != NULL_TREE)
24377 		/* If we had an initializer but it instantiated to nothing,
24378 		   value-initialize the object.  This will only occur when
24379 		   the initializer was a pack expansion where the parameter
24380 		   packs used in that expansion were of length zero.  */
24381 		init = void_type_node;
24382               in_base_initializer = 0;
24383             }
24384 
24385 	  if (target_ctor != error_mark_node
24386 	      && init != error_mark_node)
24387 	    {
24388 	      error ("mem-initializer for %qD follows constructor delegation",
24389 		     decl);
24390 	      return inits;
24391 	    }
24392 	  /* Look for a target constructor. */
24393 	  if (init != error_mark_node
24394 	      && decl && CLASS_TYPE_P (decl)
24395 	      && same_type_p (decl, current_class_type))
24396 	    {
24397 	      maybe_warn_cpp0x (CPP0X_DELEGATING_CTORS);
24398 	      if (inits)
24399 		{
24400 		  error ("constructor delegation follows mem-initializer for %qD",
24401 			 TREE_PURPOSE (inits));
24402 		  continue;
24403 		}
24404 	      target_ctor = init;
24405 	    }
24406 
24407           if (decl)
24408             {
24409               init = build_tree_list (decl, init);
24410               TREE_CHAIN (init) = inits;
24411               inits = init;
24412             }
24413         }
24414     }
24415   return inits;
24416 }
24417 
24418 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
24419 
24420 static void
set_current_access_from_decl(tree decl)24421 set_current_access_from_decl (tree decl)
24422 {
24423   if (TREE_PRIVATE (decl))
24424     current_access_specifier = access_private_node;
24425   else if (TREE_PROTECTED (decl))
24426     current_access_specifier = access_protected_node;
24427   else
24428     current_access_specifier = access_public_node;
24429 }
24430 
24431 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
24432    is the instantiation (which should have been created with
24433    start_enum) and ARGS are the template arguments to use.  */
24434 
24435 static void
tsubst_enum(tree tag,tree newtag,tree args)24436 tsubst_enum (tree tag, tree newtag, tree args)
24437 {
24438   tree e;
24439 
24440   if (SCOPED_ENUM_P (newtag))
24441     begin_scope (sk_scoped_enum, newtag);
24442 
24443   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
24444     {
24445       tree value;
24446       tree decl;
24447 
24448       decl = TREE_VALUE (e);
24449       /* Note that in a template enum, the TREE_VALUE is the
24450 	 CONST_DECL, not the corresponding INTEGER_CST.  */
24451       value = tsubst_expr (DECL_INITIAL (decl),
24452 			   args, tf_warning_or_error, NULL_TREE,
24453 			   /*integral_constant_expression_p=*/true);
24454 
24455       /* Give this enumeration constant the correct access.  */
24456       set_current_access_from_decl (decl);
24457 
24458       /* Actually build the enumerator itself.  Here we're assuming that
24459 	 enumerators can't have dependent attributes.  */
24460       build_enumerator (DECL_NAME (decl), value, newtag,
24461 			DECL_ATTRIBUTES (decl), DECL_SOURCE_LOCATION (decl));
24462     }
24463 
24464   if (SCOPED_ENUM_P (newtag))
24465     finish_scope ();
24466 
24467   finish_enum_value_list (newtag);
24468   finish_enum (newtag);
24469 
24470   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
24471     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
24472 }
24473 
24474 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
24475    its type -- but without substituting the innermost set of template
24476    arguments.  So, innermost set of template parameters will appear in
24477    the type.  */
24478 
24479 tree
get_mostly_instantiated_function_type(tree decl)24480 get_mostly_instantiated_function_type (tree decl)
24481 {
24482   /* For a function, DECL_TI_TEMPLATE is partially instantiated.  */
24483   return TREE_TYPE (DECL_TI_TEMPLATE (decl));
24484 }
24485 
24486 /* Return truthvalue if we're processing a template different from
24487    the last one involved in diagnostics.  */
24488 bool
problematic_instantiation_changed(void)24489 problematic_instantiation_changed (void)
24490 {
24491   return current_tinst_level != last_error_tinst_level;
24492 }
24493 
24494 /* Remember current template involved in diagnostics.  */
24495 void
record_last_problematic_instantiation(void)24496 record_last_problematic_instantiation (void)
24497 {
24498   set_refcount_ptr (last_error_tinst_level, current_tinst_level);
24499 }
24500 
24501 struct tinst_level *
current_instantiation(void)24502 current_instantiation (void)
24503 {
24504   return current_tinst_level;
24505 }
24506 
24507 /* Return TRUE if current_function_decl is being instantiated, false
24508    otherwise.  */
24509 
24510 bool
instantiating_current_function_p(void)24511 instantiating_current_function_p (void)
24512 {
24513   return (current_instantiation ()
24514 	  && (current_instantiation ()->maybe_get_node ()
24515 	      == current_function_decl));
24516 }
24517 
24518 /* [temp.param] Check that template non-type parm TYPE is of an allowable
24519    type.  Return false for ok, true for disallowed.  Issue error and
24520    inform messages under control of COMPLAIN.  */
24521 
24522 static bool
invalid_nontype_parm_type_p(tree type,tsubst_flags_t complain)24523 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
24524 {
24525   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
24526     return false;
24527   else if (TYPE_PTR_P (type))
24528     return false;
24529   else if (TREE_CODE (type) == REFERENCE_TYPE
24530 	   && !TYPE_REF_IS_RVALUE (type))
24531     return false;
24532   else if (TYPE_PTRMEM_P (type))
24533     return false;
24534   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
24535     return false;
24536   else if (TREE_CODE (type) == TYPENAME_TYPE)
24537     return false;
24538   else if (TREE_CODE (type) == DECLTYPE_TYPE)
24539     return false;
24540   else if (TREE_CODE (type) == NULLPTR_TYPE)
24541     return false;
24542   /* A bound template template parm could later be instantiated to have a valid
24543      nontype parm type via an alias template.  */
24544   else if (cxx_dialect >= cxx11
24545 	   && TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
24546     return false;
24547 
24548   if (complain & tf_error)
24549     {
24550       if (type == error_mark_node)
24551 	inform (input_location, "invalid template non-type parameter");
24552       else
24553 	error ("%q#T is not a valid type for a template non-type parameter",
24554 	       type);
24555     }
24556   return true;
24557 }
24558 
24559 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
24560    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
24561 
24562 static bool
dependent_type_p_r(tree type)24563 dependent_type_p_r (tree type)
24564 {
24565   tree scope;
24566 
24567   /* [temp.dep.type]
24568 
24569      A type is dependent if it is:
24570 
24571      -- a template parameter. Template template parameters are types
24572 	for us (since TYPE_P holds true for them) so we handle
24573 	them here.  */
24574   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
24575       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
24576     return true;
24577   /* -- a qualified-id with a nested-name-specifier which contains a
24578 	class-name that names a dependent type or whose unqualified-id
24579 	names a dependent type.  */
24580   if (TREE_CODE (type) == TYPENAME_TYPE)
24581     return true;
24582 
24583   /* An alias template specialization can be dependent even if the
24584      resulting type is not.  */
24585   if (dependent_alias_template_spec_p (type))
24586     return true;
24587 
24588   /* -- a cv-qualified type where the cv-unqualified type is
24589 	dependent.
24590      No code is necessary for this bullet; the code below handles
24591      cv-qualified types, and we don't want to strip aliases with
24592      TYPE_MAIN_VARIANT because of DR 1558.  */
24593   /* -- a compound type constructed from any dependent type.  */
24594   if (TYPE_PTRMEM_P (type))
24595     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
24596 	    || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
24597 					   (type)));
24598   else if (TYPE_PTR_P (type)
24599 	   || TREE_CODE (type) == REFERENCE_TYPE)
24600     return dependent_type_p (TREE_TYPE (type));
24601   else if (TREE_CODE (type) == FUNCTION_TYPE
24602 	   || TREE_CODE (type) == METHOD_TYPE)
24603     {
24604       tree arg_type;
24605 
24606       if (dependent_type_p (TREE_TYPE (type)))
24607 	return true;
24608       for (arg_type = TYPE_ARG_TYPES (type);
24609 	   arg_type;
24610 	   arg_type = TREE_CHAIN (arg_type))
24611 	if (dependent_type_p (TREE_VALUE (arg_type)))
24612 	  return true;
24613       if (cxx_dialect >= cxx17)
24614 	/* A value-dependent noexcept-specifier makes the type dependent.  */
24615 	if (tree spec = TYPE_RAISES_EXCEPTIONS (type))
24616 	  if (tree noex = TREE_PURPOSE (spec))
24617 	    /* Treat DEFERRED_NOEXCEPT as non-dependent, since it doesn't
24618 	       affect overload resolution and treating it as dependent breaks
24619 	       things.  */
24620 	    if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
24621 		&& value_dependent_expression_p (noex))
24622 	      return true;
24623       return false;
24624     }
24625   /* -- an array type constructed from any dependent type or whose
24626 	size is specified by a constant expression that is
24627 	value-dependent.
24628 
24629         We checked for type- and value-dependence of the bounds in
24630         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
24631   if (TREE_CODE (type) == ARRAY_TYPE)
24632     {
24633       if (TYPE_DOMAIN (type)
24634 	  && dependent_type_p (TYPE_DOMAIN (type)))
24635 	return true;
24636       return dependent_type_p (TREE_TYPE (type));
24637     }
24638 
24639   /* -- a template-id in which either the template name is a template
24640      parameter ...  */
24641   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
24642     return true;
24643   /* ... or any of the template arguments is a dependent type or
24644 	an expression that is type-dependent or value-dependent.  */
24645   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
24646 	   && (any_dependent_template_arguments_p
24647 	       (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
24648     return true;
24649 
24650   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
24651      dependent; if the argument of the `typeof' expression is not
24652      type-dependent, then it should already been have resolved.  */
24653   if (TREE_CODE (type) == TYPEOF_TYPE
24654       || TREE_CODE (type) == DECLTYPE_TYPE
24655       || TREE_CODE (type) == UNDERLYING_TYPE)
24656     return true;
24657 
24658   /* A template argument pack is dependent if any of its packed
24659      arguments are.  */
24660   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
24661     {
24662       tree args = ARGUMENT_PACK_ARGS (type);
24663       int i, len = TREE_VEC_LENGTH (args);
24664       for (i = 0; i < len; ++i)
24665         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
24666           return true;
24667     }
24668 
24669   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
24670      be template parameters.  */
24671   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
24672     return true;
24673 
24674   if (any_dependent_type_attributes_p (TYPE_ATTRIBUTES (type)))
24675     return true;
24676 
24677   /* The standard does not specifically mention types that are local
24678      to template functions or local classes, but they should be
24679      considered dependent too.  For example:
24680 
24681        template <int I> void f() {
24682 	 enum E { a = I };
24683 	 S<sizeof (E)> s;
24684        }
24685 
24686      The size of `E' cannot be known until the value of `I' has been
24687      determined.  Therefore, `E' must be considered dependent.  */
24688   scope = TYPE_CONTEXT (type);
24689   if (scope && TYPE_P (scope))
24690     return dependent_type_p (scope);
24691   /* Don't use type_dependent_expression_p here, as it can lead
24692      to infinite recursion trying to determine whether a lambda
24693      nested in a lambda is dependent (c++/47687).  */
24694   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
24695 	   && DECL_LANG_SPECIFIC (scope)
24696 	   && DECL_TEMPLATE_INFO (scope)
24697 	   && (any_dependent_template_arguments_p
24698 	       (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
24699     return true;
24700 
24701   /* Other types are non-dependent.  */
24702   return false;
24703 }
24704 
24705 /* Returns TRUE if TYPE is dependent, in the sense of
24706    [temp.dep.type].  Note that a NULL type is considered dependent.  */
24707 
24708 bool
dependent_type_p(tree type)24709 dependent_type_p (tree type)
24710 {
24711   /* If there are no template parameters in scope, then there can't be
24712      any dependent types.  */
24713   if (!processing_template_decl)
24714     {
24715       /* If we are not processing a template, then nobody should be
24716 	 providing us with a dependent type.  */
24717       gcc_assert (type);
24718       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
24719       return false;
24720     }
24721 
24722   /* If the type is NULL, we have not computed a type for the entity
24723      in question; in that case, the type is dependent.  */
24724   if (!type)
24725     return true;
24726 
24727   /* Erroneous types can be considered non-dependent.  */
24728   if (type == error_mark_node)
24729     return false;
24730 
24731   /* Getting here with global_type_node means we improperly called this
24732      function on the TREE_TYPE of an IDENTIFIER_NODE.  */
24733   gcc_checking_assert (type != global_type_node);
24734 
24735   /* If we have not already computed the appropriate value for TYPE,
24736      do so now.  */
24737   if (!TYPE_DEPENDENT_P_VALID (type))
24738     {
24739       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
24740       TYPE_DEPENDENT_P_VALID (type) = 1;
24741     }
24742 
24743   return TYPE_DEPENDENT_P (type);
24744 }
24745 
24746 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
24747    lookup.  In other words, a dependent type that is not the current
24748    instantiation.  */
24749 
24750 bool
dependent_scope_p(tree scope)24751 dependent_scope_p (tree scope)
24752 {
24753   return (scope && TYPE_P (scope) && dependent_type_p (scope)
24754 	  && !currently_open_class (scope));
24755 }
24756 
24757 /* T is a SCOPE_REF.  Return whether it represents a non-static member of
24758    an unknown base of 'this' (and is therefore instantiation-dependent).  */
24759 
24760 static bool
unknown_base_ref_p(tree t)24761 unknown_base_ref_p (tree t)
24762 {
24763   if (!current_class_ptr)
24764     return false;
24765 
24766   tree mem = TREE_OPERAND (t, 1);
24767   if (shared_member_p (mem))
24768     return false;
24769 
24770   tree cur = current_nonlambda_class_type ();
24771   if (!any_dependent_bases_p (cur))
24772     return false;
24773 
24774   tree ctx = TREE_OPERAND (t, 0);
24775   if (DERIVED_FROM_P (ctx, cur))
24776     return false;
24777 
24778   return true;
24779 }
24780 
24781 /* T is a SCOPE_REF; return whether we need to consider it
24782     instantiation-dependent so that we can check access at instantiation
24783     time even though we know which member it resolves to.  */
24784 
24785 static bool
instantiation_dependent_scope_ref_p(tree t)24786 instantiation_dependent_scope_ref_p (tree t)
24787 {
24788   if (DECL_P (TREE_OPERAND (t, 1))
24789       && CLASS_TYPE_P (TREE_OPERAND (t, 0))
24790       && !unknown_base_ref_p (t)
24791       && accessible_in_template_p (TREE_OPERAND (t, 0),
24792 				   TREE_OPERAND (t, 1)))
24793     return false;
24794   else
24795     return true;
24796 }
24797 
24798 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
24799    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
24800    expression.  */
24801 
24802 /* Note that this predicate is not appropriate for general expressions;
24803    only constant expressions (that satisfy potential_constant_expression)
24804    can be tested for value dependence.  */
24805 
24806 bool
value_dependent_expression_p(tree expression)24807 value_dependent_expression_p (tree expression)
24808 {
24809   if (!processing_template_decl || expression == NULL_TREE)
24810     return false;
24811 
24812   /* A type-dependent expression is also value-dependent.  */
24813   if (type_dependent_expression_p (expression))
24814     return true;
24815 
24816   switch (TREE_CODE (expression))
24817     {
24818     case BASELINK:
24819       /* A dependent member function of the current instantiation.  */
24820       return dependent_type_p (BINFO_TYPE (BASELINK_BINFO (expression)));
24821 
24822     case FUNCTION_DECL:
24823       /* A dependent member function of the current instantiation.  */
24824       if (DECL_CLASS_SCOPE_P (expression)
24825 	  && dependent_type_p (DECL_CONTEXT (expression)))
24826 	return true;
24827       break;
24828 
24829     case IDENTIFIER_NODE:
24830       /* A name that has not been looked up -- must be dependent.  */
24831       return true;
24832 
24833     case TEMPLATE_PARM_INDEX:
24834       /* A non-type template parm.  */
24835       return true;
24836 
24837     case CONST_DECL:
24838       /* A non-type template parm.  */
24839       if (DECL_TEMPLATE_PARM_P (expression))
24840 	return true;
24841       return value_dependent_expression_p (DECL_INITIAL (expression));
24842 
24843     case VAR_DECL:
24844        /* A constant with literal type and is initialized
24845 	  with an expression that is value-dependent.  */
24846       if (DECL_DEPENDENT_INIT_P (expression)
24847 	  /* FIXME cp_finish_decl doesn't fold reference initializers.  */
24848 	  || TREE_CODE (TREE_TYPE (expression)) == REFERENCE_TYPE)
24849 	return true;
24850       if (DECL_HAS_VALUE_EXPR_P (expression))
24851 	{
24852 	  tree value_expr = DECL_VALUE_EXPR (expression);
24853 	  if (value_dependent_expression_p (value_expr))
24854 	    return true;
24855 	}
24856       return false;
24857 
24858     case DYNAMIC_CAST_EXPR:
24859     case STATIC_CAST_EXPR:
24860     case CONST_CAST_EXPR:
24861     case REINTERPRET_CAST_EXPR:
24862     case CAST_EXPR:
24863     case IMPLICIT_CONV_EXPR:
24864       /* These expressions are value-dependent if the type to which
24865 	 the cast occurs is dependent or the expression being casted
24866 	 is value-dependent.  */
24867       {
24868 	tree type = TREE_TYPE (expression);
24869 
24870 	if (dependent_type_p (type))
24871 	  return true;
24872 
24873 	/* A functional cast has a list of operands.  */
24874 	expression = TREE_OPERAND (expression, 0);
24875 	if (!expression)
24876 	  {
24877 	    /* If there are no operands, it must be an expression such
24878 	       as "int()". This should not happen for aggregate types
24879 	       because it would form non-constant expressions.  */
24880 	    gcc_assert (cxx_dialect >= cxx11
24881 			|| INTEGRAL_OR_ENUMERATION_TYPE_P (type));
24882 
24883 	    return false;
24884 	  }
24885 
24886 	if (TREE_CODE (expression) == TREE_LIST)
24887 	  return any_value_dependent_elements_p (expression);
24888 
24889 	return value_dependent_expression_p (expression);
24890       }
24891 
24892     case SIZEOF_EXPR:
24893       if (SIZEOF_EXPR_TYPE_P (expression))
24894 	return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
24895       /* FALLTHRU */
24896     case ALIGNOF_EXPR:
24897     case TYPEID_EXPR:
24898       /* A `sizeof' expression is value-dependent if the operand is
24899 	 type-dependent or is a pack expansion.  */
24900       expression = TREE_OPERAND (expression, 0);
24901       if (PACK_EXPANSION_P (expression))
24902         return true;
24903       else if (TYPE_P (expression))
24904 	return dependent_type_p (expression);
24905       return instantiation_dependent_uneval_expression_p (expression);
24906 
24907     case AT_ENCODE_EXPR:
24908       /* An 'encode' expression is value-dependent if the operand is
24909 	 type-dependent.  */
24910       expression = TREE_OPERAND (expression, 0);
24911       return dependent_type_p (expression);
24912 
24913     case NOEXCEPT_EXPR:
24914       expression = TREE_OPERAND (expression, 0);
24915       return instantiation_dependent_uneval_expression_p (expression);
24916 
24917     case SCOPE_REF:
24918       /* All instantiation-dependent expressions should also be considered
24919 	 value-dependent.  */
24920       return instantiation_dependent_scope_ref_p (expression);
24921 
24922     case COMPONENT_REF:
24923       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
24924 	      || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
24925 
24926     case NONTYPE_ARGUMENT_PACK:
24927       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
24928          is value-dependent.  */
24929       {
24930         tree values = ARGUMENT_PACK_ARGS (expression);
24931         int i, len = TREE_VEC_LENGTH (values);
24932 
24933         for (i = 0; i < len; ++i)
24934           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
24935             return true;
24936 
24937         return false;
24938       }
24939 
24940     case TRAIT_EXPR:
24941       {
24942 	tree type2 = TRAIT_EXPR_TYPE2 (expression);
24943 
24944 	if (dependent_type_p (TRAIT_EXPR_TYPE1 (expression)))
24945 	  return true;
24946 
24947 	if (!type2)
24948 	  return false;
24949 
24950 	if (TREE_CODE (type2) != TREE_LIST)
24951 	  return dependent_type_p (type2);
24952 
24953 	for (; type2; type2 = TREE_CHAIN (type2))
24954 	  if (dependent_type_p (TREE_VALUE (type2)))
24955 	    return true;
24956 
24957 	return false;
24958       }
24959 
24960     case MODOP_EXPR:
24961       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
24962 	      || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
24963 
24964     case ARRAY_REF:
24965       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
24966 	      || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
24967 
24968     case ADDR_EXPR:
24969       {
24970 	tree op = TREE_OPERAND (expression, 0);
24971 	return (value_dependent_expression_p (op)
24972 		|| has_value_dependent_address (op));
24973       }
24974 
24975     case REQUIRES_EXPR:
24976       /* Treat all requires-expressions as value-dependent so
24977          we don't try to fold them.  */
24978       return true;
24979 
24980     case TYPE_REQ:
24981       return dependent_type_p (TREE_OPERAND (expression, 0));
24982 
24983     case CALL_EXPR:
24984       {
24985 	if (value_dependent_expression_p (CALL_EXPR_FN (expression)))
24986 	  return true;
24987 	tree fn = get_callee_fndecl (expression);
24988 	int i, nargs;
24989 	nargs = call_expr_nargs (expression);
24990 	for (i = 0; i < nargs; ++i)
24991 	  {
24992 	    tree op = CALL_EXPR_ARG (expression, i);
24993 	    /* In a call to a constexpr member function, look through the
24994 	       implicit ADDR_EXPR on the object argument so that it doesn't
24995 	       cause the call to be considered value-dependent.  We also
24996 	       look through it in potential_constant_expression.  */
24997 	    if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
24998 		&& DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
24999 		&& TREE_CODE (op) == ADDR_EXPR)
25000 	      op = TREE_OPERAND (op, 0);
25001 	    if (value_dependent_expression_p (op))
25002 	      return true;
25003 	  }
25004 	return false;
25005       }
25006 
25007     case TEMPLATE_ID_EXPR:
25008       return variable_concept_p (TREE_OPERAND (expression, 0));
25009 
25010     case CONSTRUCTOR:
25011       {
25012 	unsigned ix;
25013 	tree val;
25014 	if (dependent_type_p (TREE_TYPE (expression)))
25015 	  return true;
25016 	FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
25017 	  if (value_dependent_expression_p (val))
25018 	    return true;
25019 	return false;
25020       }
25021 
25022     case STMT_EXPR:
25023       /* Treat a GNU statement expression as dependent to avoid crashing
25024 	 under instantiate_non_dependent_expr; it can't be constant.  */
25025       return true;
25026 
25027     default:
25028       /* A constant expression is value-dependent if any subexpression is
25029 	 value-dependent.  */
25030       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
25031 	{
25032 	case tcc_reference:
25033 	case tcc_unary:
25034 	case tcc_comparison:
25035 	case tcc_binary:
25036 	case tcc_expression:
25037 	case tcc_vl_exp:
25038 	  {
25039 	    int i, len = cp_tree_operand_length (expression);
25040 
25041 	    for (i = 0; i < len; i++)
25042 	      {
25043 		tree t = TREE_OPERAND (expression, i);
25044 
25045 		/* In some cases, some of the operands may be missing.
25046 		   (For example, in the case of PREDECREMENT_EXPR, the
25047 		   amount to increment by may be missing.)  That doesn't
25048 		   make the expression dependent.  */
25049 		if (t && value_dependent_expression_p (t))
25050 		  return true;
25051 	      }
25052 	  }
25053 	  break;
25054 	default:
25055 	  break;
25056 	}
25057       break;
25058     }
25059 
25060   /* The expression is not value-dependent.  */
25061   return false;
25062 }
25063 
25064 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
25065    [temp.dep.expr].  Note that an expression with no type is
25066    considered dependent.  Other parts of the compiler arrange for an
25067    expression with type-dependent subexpressions to have no type, so
25068    this function doesn't have to be fully recursive.  */
25069 
25070 bool
type_dependent_expression_p(tree expression)25071 type_dependent_expression_p (tree expression)
25072 {
25073   if (!processing_template_decl)
25074     return false;
25075 
25076   if (expression == NULL_TREE || expression == error_mark_node)
25077     return false;
25078 
25079   STRIP_ANY_LOCATION_WRAPPER (expression);
25080 
25081   /* An unresolved name is always dependent.  */
25082   if (identifier_p (expression)
25083       || TREE_CODE (expression) == USING_DECL
25084       || TREE_CODE (expression) == WILDCARD_DECL)
25085     return true;
25086 
25087   /* A fold expression is type-dependent. */
25088   if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
25089       || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
25090       || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
25091       || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
25092     return true;
25093 
25094   /* Some expression forms are never type-dependent.  */
25095   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
25096       || TREE_CODE (expression) == SIZEOF_EXPR
25097       || TREE_CODE (expression) == ALIGNOF_EXPR
25098       || TREE_CODE (expression) == AT_ENCODE_EXPR
25099       || TREE_CODE (expression) == NOEXCEPT_EXPR
25100       || TREE_CODE (expression) == TRAIT_EXPR
25101       || TREE_CODE (expression) == TYPEID_EXPR
25102       || TREE_CODE (expression) == DELETE_EXPR
25103       || TREE_CODE (expression) == VEC_DELETE_EXPR
25104       || TREE_CODE (expression) == THROW_EXPR
25105       || TREE_CODE (expression) == REQUIRES_EXPR)
25106     return false;
25107 
25108   /* The types of these expressions depends only on the type to which
25109      the cast occurs.  */
25110   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
25111       || TREE_CODE (expression) == STATIC_CAST_EXPR
25112       || TREE_CODE (expression) == CONST_CAST_EXPR
25113       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
25114       || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
25115       || TREE_CODE (expression) == CAST_EXPR)
25116     return dependent_type_p (TREE_TYPE (expression));
25117 
25118   /* The types of these expressions depends only on the type created
25119      by the expression.  */
25120   if (TREE_CODE (expression) == NEW_EXPR
25121       || TREE_CODE (expression) == VEC_NEW_EXPR)
25122     {
25123       /* For NEW_EXPR tree nodes created inside a template, either
25124 	 the object type itself or a TREE_LIST may appear as the
25125 	 operand 1.  */
25126       tree type = TREE_OPERAND (expression, 1);
25127       if (TREE_CODE (type) == TREE_LIST)
25128 	/* This is an array type.  We need to check array dimensions
25129 	   as well.  */
25130 	return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
25131 	       || value_dependent_expression_p
25132 		    (TREE_OPERAND (TREE_VALUE (type), 1));
25133       else
25134 	return dependent_type_p (type);
25135     }
25136 
25137   if (TREE_CODE (expression) == SCOPE_REF)
25138     {
25139       tree scope = TREE_OPERAND (expression, 0);
25140       tree name = TREE_OPERAND (expression, 1);
25141 
25142       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
25143 	 contains an identifier associated by name lookup with one or more
25144 	 declarations declared with a dependent type, or...a
25145 	 nested-name-specifier or qualified-id that names a member of an
25146 	 unknown specialization.  */
25147       return (type_dependent_expression_p (name)
25148 	      || dependent_scope_p (scope));
25149     }
25150 
25151   if (TREE_CODE (expression) == TEMPLATE_DECL
25152       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
25153     return uses_outer_template_parms (expression);
25154 
25155   if (TREE_CODE (expression) == STMT_EXPR)
25156     expression = stmt_expr_value_expr (expression);
25157 
25158   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
25159     {
25160       tree elt;
25161       unsigned i;
25162 
25163       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
25164 	{
25165 	  if (type_dependent_expression_p (elt))
25166 	    return true;
25167 	}
25168       return false;
25169     }
25170 
25171   /* A static data member of the current instantiation with incomplete
25172      array type is type-dependent, as the definition and specializations
25173      can have different bounds.  */
25174   if (VAR_P (expression)
25175       && DECL_CLASS_SCOPE_P (expression)
25176       && dependent_type_p (DECL_CONTEXT (expression))
25177       && VAR_HAD_UNKNOWN_BOUND (expression))
25178     return true;
25179 
25180   /* An array of unknown bound depending on a variadic parameter, eg:
25181 
25182      template<typename... Args>
25183        void foo (Args... args)
25184        {
25185          int arr[] = { args... };
25186        }
25187 
25188      template<int... vals>
25189        void bar ()
25190        {
25191          int arr[] = { vals... };
25192        }
25193 
25194      If the array has no length and has an initializer, it must be that
25195      we couldn't determine its length in cp_complete_array_type because
25196      it is dependent.  */
25197   if (VAR_P (expression)
25198       && TREE_TYPE (expression) != NULL_TREE
25199       && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
25200       && !TYPE_DOMAIN (TREE_TYPE (expression))
25201       && DECL_INITIAL (expression))
25202    return true;
25203 
25204   /* A function or variable template-id is type-dependent if it has any
25205      dependent template arguments.  */
25206   if (VAR_OR_FUNCTION_DECL_P (expression)
25207       && DECL_LANG_SPECIFIC (expression)
25208       && DECL_TEMPLATE_INFO (expression))
25209     {
25210       /* Consider the innermost template arguments, since those are the ones
25211 	 that come from the template-id; the template arguments for the
25212 	 enclosing class do not make it type-dependent unless they are used in
25213 	 the type of the decl.  */
25214       if (instantiates_primary_template_p (expression)
25215 	  && (any_dependent_template_arguments_p
25216 	      (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
25217 	return true;
25218     }
25219 
25220   /* Otherwise, if the function decl isn't from a dependent scope, it can't be
25221      type-dependent.  Checking this is important for functions with auto return
25222      type, which looks like a dependent type.  */
25223   if (TREE_CODE (expression) == FUNCTION_DECL
25224       && !(DECL_CLASS_SCOPE_P (expression)
25225 	   && dependent_type_p (DECL_CONTEXT (expression)))
25226       && !(DECL_LANG_SPECIFIC (expression)
25227 	   && DECL_FRIEND_P (expression)
25228 	   && (!DECL_FRIEND_CONTEXT (expression)
25229 	       || dependent_type_p (DECL_FRIEND_CONTEXT (expression))))
25230       && !DECL_LOCAL_FUNCTION_P (expression))
25231     {
25232       gcc_assert (!dependent_type_p (TREE_TYPE (expression))
25233 		  || undeduced_auto_decl (expression));
25234       return false;
25235     }
25236 
25237   /* Always dependent, on the number of arguments if nothing else.  */
25238   if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
25239     return true;
25240 
25241   if (TREE_TYPE (expression) == unknown_type_node)
25242     {
25243       if (TREE_CODE (expression) == ADDR_EXPR)
25244 	return type_dependent_expression_p (TREE_OPERAND (expression, 0));
25245       if (TREE_CODE (expression) == COMPONENT_REF
25246 	  || TREE_CODE (expression) == OFFSET_REF)
25247 	{
25248 	  if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
25249 	    return true;
25250 	  expression = TREE_OPERAND (expression, 1);
25251 	  if (identifier_p (expression))
25252 	    return false;
25253 	}
25254       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
25255       if (TREE_CODE (expression) == SCOPE_REF)
25256 	return false;
25257 
25258       if (BASELINK_P (expression))
25259 	{
25260 	  if (BASELINK_OPTYPE (expression)
25261 	      && dependent_type_p (BASELINK_OPTYPE (expression)))
25262 	    return true;
25263 	  expression = BASELINK_FUNCTIONS (expression);
25264 	}
25265 
25266       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
25267 	{
25268 	  if (any_dependent_template_arguments_p
25269 	      (TREE_OPERAND (expression, 1)))
25270 	    return true;
25271 	  expression = TREE_OPERAND (expression, 0);
25272 	  if (identifier_p (expression))
25273 	    return true;
25274 	}
25275 
25276       gcc_assert (TREE_CODE (expression) == OVERLOAD
25277 		  || TREE_CODE (expression) == FUNCTION_DECL);
25278 
25279       for (lkp_iterator iter (expression); iter; ++iter)
25280 	if (type_dependent_expression_p (*iter))
25281 	  return true;
25282 
25283       return false;
25284     }
25285 
25286   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
25287 
25288   /* Dependent type attributes might not have made it from the decl to
25289      the type yet.  */
25290   if (DECL_P (expression)
25291       && any_dependent_type_attributes_p (DECL_ATTRIBUTES (expression)))
25292     return true;
25293 
25294   return (dependent_type_p (TREE_TYPE (expression)));
25295 }
25296 
25297 /* [temp.dep.expr]/5: A class member access expression (5.2.5) is
25298    type-dependent if the expression refers to a member of the current
25299    instantiation and the type of the referenced member is dependent, or the
25300    class member access expression refers to a member of an unknown
25301    specialization.
25302 
25303    This function returns true if the OBJECT in such a class member access
25304    expression is of an unknown specialization.  */
25305 
25306 bool
type_dependent_object_expression_p(tree object)25307 type_dependent_object_expression_p (tree object)
25308 {
25309   /* An IDENTIFIER_NODE can sometimes have a TREE_TYPE, but it's still
25310      dependent.  */
25311   if (TREE_CODE (object) == IDENTIFIER_NODE)
25312     return true;
25313   tree scope = TREE_TYPE (object);
25314   return (!scope || dependent_scope_p (scope));
25315 }
25316 
25317 /* walk_tree callback function for instantiation_dependent_expression_p,
25318    below.  Returns non-zero if a dependent subexpression is found.  */
25319 
25320 static tree
instantiation_dependent_r(tree * tp,int * walk_subtrees,void *)25321 instantiation_dependent_r (tree *tp, int *walk_subtrees,
25322 			   void * /*data*/)
25323 {
25324   if (TYPE_P (*tp))
25325     {
25326       /* We don't have to worry about decltype currently because decltype
25327 	 of an instantiation-dependent expr is a dependent type.  This
25328 	 might change depending on the resolution of DR 1172.  */
25329       *walk_subtrees = false;
25330       return NULL_TREE;
25331     }
25332   enum tree_code code = TREE_CODE (*tp);
25333   switch (code)
25334     {
25335       /* Don't treat an argument list as dependent just because it has no
25336 	 TREE_TYPE.  */
25337     case TREE_LIST:
25338     case TREE_VEC:
25339     case NONTYPE_ARGUMENT_PACK:
25340       return NULL_TREE;
25341 
25342     case TEMPLATE_PARM_INDEX:
25343       return *tp;
25344 
25345       /* Handle expressions with type operands.  */
25346     case SIZEOF_EXPR:
25347     case ALIGNOF_EXPR:
25348     case TYPEID_EXPR:
25349     case AT_ENCODE_EXPR:
25350       {
25351 	tree op = TREE_OPERAND (*tp, 0);
25352 	if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
25353 	  op = TREE_TYPE (op);
25354 	if (TYPE_P (op))
25355 	  {
25356 	    if (dependent_type_p (op))
25357 	      return *tp;
25358 	    else
25359 	      {
25360 		*walk_subtrees = false;
25361 		return NULL_TREE;
25362 	      }
25363 	  }
25364 	break;
25365       }
25366 
25367     case COMPONENT_REF:
25368       if (identifier_p (TREE_OPERAND (*tp, 1)))
25369 	/* In a template, finish_class_member_access_expr creates a
25370 	   COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
25371 	   type-dependent, so that we can check access control at
25372 	   instantiation time (PR 42277).  See also Core issue 1273.  */
25373 	return *tp;
25374       break;
25375 
25376     case SCOPE_REF:
25377       if (instantiation_dependent_scope_ref_p (*tp))
25378 	return *tp;
25379       else
25380 	break;
25381 
25382       /* Treat statement-expressions as dependent.  */
25383     case BIND_EXPR:
25384       return *tp;
25385 
25386       /* Treat requires-expressions as dependent. */
25387     case REQUIRES_EXPR:
25388       return *tp;
25389 
25390     case CALL_EXPR:
25391       /* Treat calls to function concepts as dependent. */
25392       if (function_concept_check_p (*tp))
25393         return *tp;
25394       break;
25395 
25396     case TEMPLATE_ID_EXPR:
25397       /* And variable concepts.  */
25398       if (variable_concept_p (TREE_OPERAND (*tp, 0)))
25399 	return *tp;
25400       break;
25401 
25402     default:
25403       break;
25404     }
25405 
25406   if (type_dependent_expression_p (*tp))
25407     return *tp;
25408   else
25409     return NULL_TREE;
25410 }
25411 
25412 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
25413    sense defined by the ABI:
25414 
25415    "An expression is instantiation-dependent if it is type-dependent
25416    or value-dependent, or it has a subexpression that is type-dependent
25417    or value-dependent."
25418 
25419    Except don't actually check value-dependence for unevaluated expressions,
25420    because in sizeof(i) we don't care about the value of i.  Checking
25421    type-dependence will in turn check value-dependence of array bounds/template
25422    arguments as needed.  */
25423 
25424 bool
instantiation_dependent_uneval_expression_p(tree expression)25425 instantiation_dependent_uneval_expression_p (tree expression)
25426 {
25427   tree result;
25428 
25429   if (!processing_template_decl)
25430     return false;
25431 
25432   if (expression == error_mark_node)
25433     return false;
25434 
25435   result = cp_walk_tree_without_duplicates (&expression,
25436 					    instantiation_dependent_r, NULL);
25437   return result != NULL_TREE;
25438 }
25439 
25440 /* As above, but also check value-dependence of the expression as a whole.  */
25441 
25442 bool
instantiation_dependent_expression_p(tree expression)25443 instantiation_dependent_expression_p (tree expression)
25444 {
25445   return (instantiation_dependent_uneval_expression_p (expression)
25446 	  || value_dependent_expression_p (expression));
25447 }
25448 
25449 /* Like type_dependent_expression_p, but it also works while not processing
25450    a template definition, i.e. during substitution or mangling.  */
25451 
25452 bool
type_dependent_expression_p_push(tree expr)25453 type_dependent_expression_p_push (tree expr)
25454 {
25455   bool b;
25456   ++processing_template_decl;
25457   b = type_dependent_expression_p (expr);
25458   --processing_template_decl;
25459   return b;
25460 }
25461 
25462 /* Returns TRUE if ARGS contains a type-dependent expression.  */
25463 
25464 bool
any_type_dependent_arguments_p(const vec<tree,va_gc> * args)25465 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
25466 {
25467   unsigned int i;
25468   tree arg;
25469 
25470   FOR_EACH_VEC_SAFE_ELT (args, i, arg)
25471     {
25472       if (type_dependent_expression_p (arg))
25473 	return true;
25474     }
25475   return false;
25476 }
25477 
25478 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
25479    expressions) contains any type-dependent expressions.  */
25480 
25481 bool
any_type_dependent_elements_p(const_tree list)25482 any_type_dependent_elements_p (const_tree list)
25483 {
25484   for (; list; list = TREE_CHAIN (list))
25485     if (type_dependent_expression_p (TREE_VALUE (list)))
25486       return true;
25487 
25488   return false;
25489 }
25490 
25491 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
25492    expressions) contains any value-dependent expressions.  */
25493 
25494 bool
any_value_dependent_elements_p(const_tree list)25495 any_value_dependent_elements_p (const_tree list)
25496 {
25497   for (; list; list = TREE_CHAIN (list))
25498     if (value_dependent_expression_p (TREE_VALUE (list)))
25499       return true;
25500 
25501   return false;
25502 }
25503 
25504 /* Returns TRUE if the ARG (a template argument) is dependent.  */
25505 
25506 bool
dependent_template_arg_p(tree arg)25507 dependent_template_arg_p (tree arg)
25508 {
25509   if (!processing_template_decl)
25510     return false;
25511 
25512   /* Assume a template argument that was wrongly written by the user
25513      is dependent. This is consistent with what
25514      any_dependent_template_arguments_p [that calls this function]
25515      does.  */
25516   if (!arg || arg == error_mark_node)
25517     return true;
25518 
25519   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
25520     arg = argument_pack_select_arg (arg);
25521 
25522   if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
25523     return true;
25524   if (TREE_CODE (arg) == TEMPLATE_DECL)
25525     {
25526       if (DECL_TEMPLATE_PARM_P (arg))
25527 	return true;
25528       /* A member template of a dependent class is not necessarily
25529 	 type-dependent, but it is a dependent template argument because it
25530 	 will be a member of an unknown specialization to that template.  */
25531       tree scope = CP_DECL_CONTEXT (arg);
25532       return TYPE_P (scope) && dependent_type_p (scope);
25533     }
25534   else if (ARGUMENT_PACK_P (arg))
25535     {
25536       tree args = ARGUMENT_PACK_ARGS (arg);
25537       int i, len = TREE_VEC_LENGTH (args);
25538       for (i = 0; i < len; ++i)
25539         {
25540           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
25541             return true;
25542         }
25543 
25544       return false;
25545     }
25546   else if (TYPE_P (arg))
25547     return dependent_type_p (arg);
25548   else
25549     return (type_dependent_expression_p (arg)
25550 	    || value_dependent_expression_p (arg));
25551 }
25552 
25553 /* Returns true if ARGS (a collection of template arguments) contains
25554    any types that require structural equality testing.  */
25555 
25556 bool
any_template_arguments_need_structural_equality_p(tree args)25557 any_template_arguments_need_structural_equality_p (tree args)
25558 {
25559   int i;
25560   int j;
25561 
25562   if (!args)
25563     return false;
25564   if (args == error_mark_node)
25565     return true;
25566 
25567   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
25568     {
25569       tree level = TMPL_ARGS_LEVEL (args, i + 1);
25570       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
25571 	{
25572 	  tree arg = TREE_VEC_ELT (level, j);
25573 	  tree packed_args = NULL_TREE;
25574 	  int k, len = 1;
25575 
25576 	  if (ARGUMENT_PACK_P (arg))
25577 	    {
25578 	      /* Look inside the argument pack.  */
25579 	      packed_args = ARGUMENT_PACK_ARGS (arg);
25580 	      len = TREE_VEC_LENGTH (packed_args);
25581 	    }
25582 
25583 	  for (k = 0; k < len; ++k)
25584 	    {
25585 	      if (packed_args)
25586 		arg = TREE_VEC_ELT (packed_args, k);
25587 
25588 	      if (error_operand_p (arg))
25589 		return true;
25590 	      else if (TREE_CODE (arg) == TEMPLATE_DECL)
25591 		continue;
25592 	      else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
25593 		return true;
25594 	      else if (!TYPE_P (arg) && TREE_TYPE (arg)
25595 		       && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
25596 		return true;
25597 	    }
25598 	}
25599     }
25600 
25601   return false;
25602 }
25603 
25604 /* Returns true if ARGS (a collection of template arguments) contains
25605    any dependent arguments.  */
25606 
25607 bool
any_dependent_template_arguments_p(const_tree args)25608 any_dependent_template_arguments_p (const_tree args)
25609 {
25610   int i;
25611   int j;
25612 
25613   if (!args)
25614     return false;
25615   if (args == error_mark_node)
25616     return true;
25617 
25618   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
25619     {
25620       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
25621       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
25622 	if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
25623 	  return true;
25624     }
25625 
25626   return false;
25627 }
25628 
25629 /* Returns true if ARGS contains any errors.  */
25630 
25631 bool
any_erroneous_template_args_p(const_tree args)25632 any_erroneous_template_args_p (const_tree args)
25633 {
25634   int i;
25635   int j;
25636 
25637   if (args == error_mark_node)
25638     return true;
25639 
25640   if (args && TREE_CODE (args) != TREE_VEC)
25641     {
25642       if (tree ti = get_template_info (args))
25643 	args = TI_ARGS (ti);
25644       else
25645 	args = NULL_TREE;
25646     }
25647 
25648   if (!args)
25649     return false;
25650 
25651   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
25652     {
25653       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
25654       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
25655 	if (error_operand_p (TREE_VEC_ELT (level, j)))
25656 	  return true;
25657     }
25658 
25659   return false;
25660 }
25661 
25662 /* Returns TRUE if the template TMPL is type-dependent.  */
25663 
25664 bool
dependent_template_p(tree tmpl)25665 dependent_template_p (tree tmpl)
25666 {
25667   if (TREE_CODE (tmpl) == OVERLOAD)
25668     {
25669       for (lkp_iterator iter (tmpl); iter; ++iter)
25670 	if (dependent_template_p (*iter))
25671 	  return true;
25672       return false;
25673     }
25674 
25675   /* Template template parameters are dependent.  */
25676   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
25677       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
25678     return true;
25679   /* So are names that have not been looked up.  */
25680   if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
25681     return true;
25682   return false;
25683 }
25684 
25685 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
25686 
25687 bool
dependent_template_id_p(tree tmpl,tree args)25688 dependent_template_id_p (tree tmpl, tree args)
25689 {
25690   return (dependent_template_p (tmpl)
25691 	  || any_dependent_template_arguments_p (args));
25692 }
25693 
25694 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
25695    are dependent.  */
25696 
25697 bool
dependent_omp_for_p(tree declv,tree initv,tree condv,tree incrv)25698 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
25699 {
25700   int i;
25701 
25702   if (!processing_template_decl)
25703     return false;
25704 
25705   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
25706     {
25707       tree decl = TREE_VEC_ELT (declv, i);
25708       tree init = TREE_VEC_ELT (initv, i);
25709       tree cond = TREE_VEC_ELT (condv, i);
25710       tree incr = TREE_VEC_ELT (incrv, i);
25711 
25712       if (type_dependent_expression_p (decl)
25713 	  || TREE_CODE (decl) == SCOPE_REF)
25714 	return true;
25715 
25716       if (init && type_dependent_expression_p (init))
25717 	return true;
25718 
25719       if (type_dependent_expression_p (cond))
25720 	return true;
25721 
25722       if (COMPARISON_CLASS_P (cond)
25723 	  && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
25724 	      || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
25725 	return true;
25726 
25727       if (TREE_CODE (incr) == MODOP_EXPR)
25728 	{
25729 	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
25730 	      || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
25731 	    return true;
25732 	}
25733       else if (type_dependent_expression_p (incr))
25734 	return true;
25735       else if (TREE_CODE (incr) == MODIFY_EXPR)
25736 	{
25737 	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
25738 	    return true;
25739 	  else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
25740 	    {
25741 	      tree t = TREE_OPERAND (incr, 1);
25742 	      if (type_dependent_expression_p (TREE_OPERAND (t, 0))
25743 		  || type_dependent_expression_p (TREE_OPERAND (t, 1)))
25744 		return true;
25745 	    }
25746 	}
25747     }
25748 
25749   return false;
25750 }
25751 
25752 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
25753    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
25754    no such TYPE can be found.  Note that this function peers inside
25755    uninstantiated templates and therefore should be used only in
25756    extremely limited situations.  ONLY_CURRENT_P restricts this
25757    peering to the currently open classes hierarchy (which is required
25758    when comparing types).  */
25759 
25760 tree
resolve_typename_type(tree type,bool only_current_p)25761 resolve_typename_type (tree type, bool only_current_p)
25762 {
25763   tree scope;
25764   tree name;
25765   tree decl;
25766   int quals;
25767   tree pushed_scope;
25768   tree result;
25769 
25770   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
25771 
25772   scope = TYPE_CONTEXT (type);
25773   /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope.  */
25774   gcc_checking_assert (uses_template_parms (scope));
25775 
25776   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
25777      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
25778      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
25779      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
25780      identifier  of the TYPENAME_TYPE anymore.
25781      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
25782      TYPENAME_TYPE instead, we avoid messing up with a possible
25783      typedef variant case.  */
25784   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
25785 
25786   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
25787      it first before we can figure out what NAME refers to.  */
25788   if (TREE_CODE (scope) == TYPENAME_TYPE)
25789     {
25790       if (TYPENAME_IS_RESOLVING_P (scope))
25791 	/* Given a class template A with a dependent base with nested type C,
25792 	   typedef typename A::C::C C will land us here, as trying to resolve
25793 	   the initial A::C leads to the local C typedef, which leads back to
25794 	   A::C::C.  So we break the recursion now.  */
25795 	return type;
25796       else
25797 	scope = resolve_typename_type (scope, only_current_p);
25798     }
25799   /* If we don't know what SCOPE refers to, then we cannot resolve the
25800      TYPENAME_TYPE.  */
25801   if (!CLASS_TYPE_P (scope))
25802     return type;
25803   /* If this is a typedef, we don't want to look inside (c++/11987).  */
25804   if (typedef_variant_p (type))
25805     return type;
25806   /* If SCOPE isn't the template itself, it will not have a valid
25807      TYPE_FIELDS list.  */
25808   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
25809     /* scope is either the template itself or a compatible instantiation
25810        like X<T>, so look up the name in the original template.  */
25811     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
25812   /* If scope has no fields, it can't be a current instantiation.  Check this
25813      before currently_open_class to avoid infinite recursion (71515).  */
25814   if (!TYPE_FIELDS (scope))
25815     return type;
25816   /* If the SCOPE is not the current instantiation, there's no reason
25817      to look inside it.  */
25818   if (only_current_p && !currently_open_class (scope))
25819     return type;
25820   /* Enter the SCOPE so that name lookup will be resolved as if we
25821      were in the class definition.  In particular, SCOPE will no
25822      longer be considered a dependent type.  */
25823   pushed_scope = push_scope (scope);
25824   /* Look up the declaration.  */
25825   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
25826 			tf_warning_or_error);
25827 
25828   result = NULL_TREE;
25829 
25830   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
25831      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
25832   tree fullname = TYPENAME_TYPE_FULLNAME (type);
25833   if (!decl)
25834     /*nop*/;
25835   else if (identifier_p (fullname)
25836 	   && TREE_CODE (decl) == TYPE_DECL)
25837     {
25838       result = TREE_TYPE (decl);
25839       if (result == error_mark_node)
25840 	result = NULL_TREE;
25841     }
25842   else if (TREE_CODE (fullname) == TEMPLATE_ID_EXPR
25843 	   && DECL_CLASS_TEMPLATE_P (decl))
25844     {
25845       /* Obtain the template and the arguments.  */
25846       tree tmpl = TREE_OPERAND (fullname, 0);
25847       if (TREE_CODE (tmpl) == IDENTIFIER_NODE)
25848 	{
25849 	  /* We get here with a plain identifier because a previous tentative
25850 	     parse of the nested-name-specifier as part of a ptr-operator saw
25851 	     ::template X<A>.  The use of ::template is necessary in a
25852 	     ptr-operator, but wrong in a declarator-id.
25853 
25854 	     [temp.names]: In a qualified-id of a declarator-id, the keyword
25855 	     template shall not appear at the top level.  */
25856 	  pedwarn (EXPR_LOC_OR_LOC (fullname, input_location), OPT_Wpedantic,
25857 		   "keyword %<template%> not allowed in declarator-id");
25858 	  tmpl = decl;
25859 	}
25860       tree args = TREE_OPERAND (fullname, 1);
25861       /* Instantiate the template.  */
25862       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
25863 				      /*entering_scope=*/true,
25864 				      tf_error | tf_user);
25865       if (result == error_mark_node)
25866 	result = NULL_TREE;
25867     }
25868 
25869   /* Leave the SCOPE.  */
25870   if (pushed_scope)
25871     pop_scope (pushed_scope);
25872 
25873   /* If we failed to resolve it, return the original typename.  */
25874   if (!result)
25875     return type;
25876 
25877   /* If lookup found a typename type, resolve that too.  */
25878   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
25879     {
25880       /* Ill-formed programs can cause infinite recursion here, so we
25881 	 must catch that.  */
25882       TYPENAME_IS_RESOLVING_P (result) = 1;
25883       result = resolve_typename_type (result, only_current_p);
25884       TYPENAME_IS_RESOLVING_P (result) = 0;
25885     }
25886 
25887   /* Qualify the resulting type.  */
25888   quals = cp_type_quals (type);
25889   if (quals)
25890     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
25891 
25892   return result;
25893 }
25894 
25895 /* EXPR is an expression which is not type-dependent.  Return a proxy
25896    for EXPR that can be used to compute the types of larger
25897    expressions containing EXPR.  */
25898 
25899 tree
build_non_dependent_expr(tree expr)25900 build_non_dependent_expr (tree expr)
25901 {
25902   tree orig_expr = expr;
25903   tree inner_expr;
25904 
25905   /* When checking, try to get a constant value for all non-dependent
25906      expressions in order to expose bugs in *_dependent_expression_p
25907      and constexpr.  This can affect code generation, see PR70704, so
25908      only do this for -fchecking=2.  */
25909   if (flag_checking > 1
25910       && cxx_dialect >= cxx11
25911       /* Don't do this during nsdmi parsing as it can lead to
25912 	 unexpected recursive instantiations.  */
25913       && !parsing_nsdmi ()
25914       /* Don't do this during concept expansion either and for
25915          the same reason.  */
25916       && !expanding_concept ())
25917     fold_non_dependent_expr (expr);
25918 
25919   STRIP_ANY_LOCATION_WRAPPER (expr);
25920 
25921   /* Preserve OVERLOADs; the functions must be available to resolve
25922      types.  */
25923   inner_expr = expr;
25924   if (TREE_CODE (inner_expr) == STMT_EXPR)
25925     inner_expr = stmt_expr_value_expr (inner_expr);
25926   if (TREE_CODE (inner_expr) == ADDR_EXPR)
25927     inner_expr = TREE_OPERAND (inner_expr, 0);
25928   if (TREE_CODE (inner_expr) == COMPONENT_REF)
25929     inner_expr = TREE_OPERAND (inner_expr, 1);
25930   if (is_overloaded_fn (inner_expr)
25931       || TREE_CODE (inner_expr) == OFFSET_REF)
25932     return orig_expr;
25933   /* There is no need to return a proxy for a variable.  */
25934   if (VAR_P (expr))
25935     return orig_expr;
25936   /* Preserve string constants; conversions from string constants to
25937      "char *" are allowed, even though normally a "const char *"
25938      cannot be used to initialize a "char *".  */
25939   if (TREE_CODE (expr) == STRING_CST)
25940     return orig_expr;
25941   /* Preserve void and arithmetic constants, as an optimization -- there is no
25942      reason to create a new node.  */
25943   if (TREE_CODE (expr) == VOID_CST
25944       || TREE_CODE (expr) == INTEGER_CST
25945       || TREE_CODE (expr) == REAL_CST)
25946     return orig_expr;
25947   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
25948      There is at least one place where we want to know that a
25949      particular expression is a throw-expression: when checking a ?:
25950      expression, there are special rules if the second or third
25951      argument is a throw-expression.  */
25952   if (TREE_CODE (expr) == THROW_EXPR)
25953     return orig_expr;
25954 
25955   /* Don't wrap an initializer list, we need to be able to look inside.  */
25956   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
25957     return orig_expr;
25958 
25959   /* Don't wrap a dummy object, we need to be able to test for it.  */
25960   if (is_dummy_object (expr))
25961     return orig_expr;
25962 
25963   if (TREE_CODE (expr) == COND_EXPR)
25964     return build3 (COND_EXPR,
25965 		   TREE_TYPE (expr),
25966 		   TREE_OPERAND (expr, 0),
25967 		   (TREE_OPERAND (expr, 1)
25968 		    ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
25969 		    : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
25970 		   build_non_dependent_expr (TREE_OPERAND (expr, 2)));
25971   if (TREE_CODE (expr) == COMPOUND_EXPR
25972       && !COMPOUND_EXPR_OVERLOADED (expr))
25973     return build2 (COMPOUND_EXPR,
25974 		   TREE_TYPE (expr),
25975 		   TREE_OPERAND (expr, 0),
25976 		   build_non_dependent_expr (TREE_OPERAND (expr, 1)));
25977 
25978   /* If the type is unknown, it can't really be non-dependent */
25979   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
25980 
25981   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
25982   return build1_loc (EXPR_LOCATION (orig_expr), NON_DEPENDENT_EXPR,
25983 		     TREE_TYPE (expr), expr);
25984 }
25985 
25986 /* ARGS is a vector of expressions as arguments to a function call.
25987    Replace the arguments with equivalent non-dependent expressions.
25988    This modifies ARGS in place.  */
25989 
25990 void
make_args_non_dependent(vec<tree,va_gc> * args)25991 make_args_non_dependent (vec<tree, va_gc> *args)
25992 {
25993   unsigned int ix;
25994   tree arg;
25995 
25996   FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
25997     {
25998       tree newarg = build_non_dependent_expr (arg);
25999       if (newarg != arg)
26000 	(*args)[ix] = newarg;
26001     }
26002 }
26003 
26004 /* Returns a type which represents 'auto' or 'decltype(auto)'.  We use a
26005    TEMPLATE_TYPE_PARM with a level one deeper than the actual template
26006    parms.  If set_canonical is true, we set TYPE_CANONICAL on it.  */
26007 
26008 static tree
make_auto_1(tree name,bool set_canonical)26009 make_auto_1 (tree name, bool set_canonical)
26010 {
26011   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
26012   TYPE_NAME (au) = build_decl (input_location,
26013 			       TYPE_DECL, name, au);
26014   TYPE_STUB_DECL (au) = TYPE_NAME (au);
26015   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
26016     (0, processing_template_decl + 1, processing_template_decl + 1,
26017      TYPE_NAME (au), NULL_TREE);
26018   if (set_canonical)
26019     TYPE_CANONICAL (au) = canonical_type_parameter (au);
26020   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
26021   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
26022 
26023   return au;
26024 }
26025 
26026 tree
make_decltype_auto(void)26027 make_decltype_auto (void)
26028 {
26029   return make_auto_1 (decltype_auto_identifier, true);
26030 }
26031 
26032 tree
make_auto(void)26033 make_auto (void)
26034 {
26035   return make_auto_1 (auto_identifier, true);
26036 }
26037 
26038 /* Return a C++17 deduction placeholder for class template TMPL.  */
26039 
26040 tree
make_template_placeholder(tree tmpl)26041 make_template_placeholder (tree tmpl)
26042 {
26043   tree t = make_auto_1 (DECL_NAME (tmpl), false);
26044   CLASS_PLACEHOLDER_TEMPLATE (t) = tmpl;
26045   /* Our canonical type depends on the placeholder.  */
26046   TYPE_CANONICAL (t) = canonical_type_parameter (t);
26047   return t;
26048 }
26049 
26050 /* True iff T is a C++17 class template deduction placeholder.  */
26051 
26052 bool
template_placeholder_p(tree t)26053 template_placeholder_p (tree t)
26054 {
26055   return is_auto (t) && CLASS_PLACEHOLDER_TEMPLATE (t);
26056 }
26057 
26058 /* Make a "constrained auto" type-specifier. This is an
26059    auto type with constraints that must be associated after
26060    deduction.  The constraint is formed from the given
26061    CONC and its optional sequence of arguments, which are
26062    non-null if written as partial-concept-id.  */
26063 
26064 tree
make_constrained_auto(tree con,tree args)26065 make_constrained_auto (tree con, tree args)
26066 {
26067   tree type = make_auto_1 (auto_identifier, false);
26068 
26069   /* Build the constraint. */
26070   tree tmpl = DECL_TI_TEMPLATE (con);
26071   tree expr = VAR_P (con) ? tmpl : ovl_make (tmpl);
26072   expr = build_concept_check (expr, type, args);
26073 
26074   tree constr = normalize_expression (expr);
26075   PLACEHOLDER_TYPE_CONSTRAINTS (type) = constr;
26076 
26077   /* Our canonical type depends on the constraint.  */
26078   TYPE_CANONICAL (type) = canonical_type_parameter (type);
26079 
26080   /* Attach the constraint to the type declaration. */
26081   tree decl = TYPE_NAME (type);
26082   return decl;
26083 }
26084 
26085 /* Given type ARG, return std::initializer_list<ARG>.  */
26086 
26087 static tree
listify(tree arg)26088 listify (tree arg)
26089 {
26090   tree std_init_list = get_namespace_binding (std_node, init_list_identifier);
26091 
26092   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
26093     {
26094       gcc_rich_location richloc (input_location);
26095       maybe_add_include_fixit (&richloc, "<initializer_list>");
26096       error_at (&richloc,
26097 		"deducing from brace-enclosed initializer list"
26098 		" requires %<#include <initializer_list>%>");
26099 
26100       return error_mark_node;
26101     }
26102   tree argvec = make_tree_vec (1);
26103   TREE_VEC_ELT (argvec, 0) = arg;
26104 
26105   return lookup_template_class (std_init_list, argvec, NULL_TREE,
26106 				NULL_TREE, 0, tf_warning_or_error);
26107 }
26108 
26109 /* Replace auto in TYPE with std::initializer_list<auto>.  */
26110 
26111 static tree
listify_autos(tree type,tree auto_node)26112 listify_autos (tree type, tree auto_node)
26113 {
26114   tree init_auto = listify (auto_node);
26115   tree argvec = make_tree_vec (1);
26116   TREE_VEC_ELT (argvec, 0) = init_auto;
26117   if (processing_template_decl)
26118     argvec = add_to_template_args (current_template_args (), argvec);
26119   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
26120 }
26121 
26122 /* Hash traits for hashing possibly constrained 'auto'
26123    TEMPLATE_TYPE_PARMs for use by do_auto_deduction.  */
26124 
26125 struct auto_hash : default_hash_traits<tree>
26126 {
26127   static inline hashval_t hash (tree);
26128   static inline bool equal (tree, tree);
26129 };
26130 
26131 /* Hash the 'auto' T.  */
26132 
26133 inline hashval_t
hash(tree t)26134 auto_hash::hash (tree t)
26135 {
26136   if (tree c = PLACEHOLDER_TYPE_CONSTRAINTS (t))
26137     /* Matching constrained-type-specifiers denote the same template
26138        parameter, so hash the constraint.  */
26139     return hash_placeholder_constraint (c);
26140   else
26141     /* But unconstrained autos are all separate, so just hash the pointer.  */
26142     return iterative_hash_object (t, 0);
26143 }
26144 
26145 /* Compare two 'auto's.  */
26146 
26147 inline bool
equal(tree t1,tree t2)26148 auto_hash::equal (tree t1, tree t2)
26149 {
26150   if (t1 == t2)
26151     return true;
26152 
26153   tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
26154   tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
26155 
26156   /* Two unconstrained autos are distinct.  */
26157   if (!c1 || !c2)
26158     return false;
26159 
26160   return equivalent_placeholder_constraints (c1, c2);
26161 }
26162 
26163 /* for_each_template_parm callback for extract_autos: if t is a (possibly
26164    constrained) auto, add it to the vector.  */
26165 
26166 static int
extract_autos_r(tree t,void * data)26167 extract_autos_r (tree t, void *data)
26168 {
26169   hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
26170   if (is_auto (t))
26171     {
26172       /* All the autos were built with index 0; fix that up now.  */
26173       tree *p = hash.find_slot (t, INSERT);
26174       unsigned idx;
26175       if (*p)
26176 	/* If this is a repeated constrained-type-specifier, use the index we
26177 	   chose before.  */
26178 	idx = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (*p));
26179       else
26180 	{
26181 	  /* Otherwise this is new, so use the current count.  */
26182 	  *p = t;
26183 	  idx = hash.elements () - 1;
26184 	}
26185       TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (t)) = idx;
26186     }
26187 
26188   /* Always keep walking.  */
26189   return 0;
26190 }
26191 
26192 /* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
26193    says they can appear anywhere in the type.  */
26194 
26195 static tree
extract_autos(tree type)26196 extract_autos (tree type)
26197 {
26198   hash_set<tree> visited;
26199   hash_table<auto_hash> hash (2);
26200 
26201   for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
26202 
26203   tree tree_vec = make_tree_vec (hash.elements());
26204   for (hash_table<auto_hash>::iterator iter = hash.begin();
26205        iter != hash.end(); ++iter)
26206     {
26207       tree elt = *iter;
26208       unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
26209       TREE_VEC_ELT (tree_vec, i)
26210 	= build_tree_list (NULL_TREE, TYPE_NAME (elt));
26211     }
26212 
26213   return tree_vec;
26214 }
26215 
26216 /* The stem for deduction guide names.  */
26217 const char *const dguide_base = "__dguide_";
26218 
26219 /* Return the name for a deduction guide for class template TMPL.  */
26220 
26221 tree
dguide_name(tree tmpl)26222 dguide_name (tree tmpl)
26223 {
26224   tree type = (TYPE_P (tmpl) ? tmpl : TREE_TYPE (tmpl));
26225   tree tname = TYPE_IDENTIFIER (type);
26226   char *buf = (char *) alloca (1 + strlen (dguide_base)
26227 			       + IDENTIFIER_LENGTH (tname));
26228   memcpy (buf, dguide_base, strlen (dguide_base));
26229   memcpy (buf + strlen (dguide_base), IDENTIFIER_POINTER (tname),
26230 	  IDENTIFIER_LENGTH (tname) + 1);
26231   tree dname = get_identifier (buf);
26232   TREE_TYPE (dname) = type;
26233   return dname;
26234 }
26235 
26236 /* True if NAME is the name of a deduction guide.  */
26237 
26238 bool
dguide_name_p(tree name)26239 dguide_name_p (tree name)
26240 {
26241   return (TREE_CODE (name) == IDENTIFIER_NODE
26242 	  && TREE_TYPE (name)
26243 	  && !strncmp (IDENTIFIER_POINTER (name), dguide_base,
26244 		       strlen (dguide_base)));
26245 }
26246 
26247 /* True if FN is a deduction guide.  */
26248 
26249 bool
deduction_guide_p(const_tree fn)26250 deduction_guide_p (const_tree fn)
26251 {
26252   if (DECL_P (fn))
26253     if (tree name = DECL_NAME (fn))
26254       return dguide_name_p (name);
26255   return false;
26256 }
26257 
26258 /* True if FN is the copy deduction guide, i.e. A(A)->A.  */
26259 
26260 bool
copy_guide_p(const_tree fn)26261 copy_guide_p (const_tree fn)
26262 {
26263   gcc_assert (deduction_guide_p (fn));
26264   if (!DECL_ARTIFICIAL (fn))
26265     return false;
26266   tree parms = FUNCTION_FIRST_USER_PARMTYPE (DECL_TI_TEMPLATE (fn));
26267   return (TREE_CHAIN (parms) == void_list_node
26268 	  && same_type_p (TREE_VALUE (parms), TREE_TYPE (DECL_NAME (fn))));
26269 }
26270 
26271 /* True if FN is a guide generated from a constructor template.  */
26272 
26273 bool
template_guide_p(const_tree fn)26274 template_guide_p (const_tree fn)
26275 {
26276   gcc_assert (deduction_guide_p (fn));
26277   if (!DECL_ARTIFICIAL (fn))
26278     return false;
26279   tree tmpl = DECL_TI_TEMPLATE (fn);
26280   if (tree org = DECL_ABSTRACT_ORIGIN (tmpl))
26281     return PRIMARY_TEMPLATE_P (org);
26282   return false;
26283 }
26284 
26285 /* OLDDECL is a _DECL for a template parameter.  Return a similar parameter at
26286    LEVEL:INDEX, using tsubst_args and complain for substitution into non-type
26287    template parameter types.  Note that the handling of template template
26288    parameters relies on current_template_parms being set appropriately for the
26289    new template.  */
26290 
26291 static tree
rewrite_template_parm(tree olddecl,unsigned index,unsigned level,tree tsubst_args,tsubst_flags_t complain)26292 rewrite_template_parm (tree olddecl, unsigned index, unsigned level,
26293 		       tree tsubst_args, tsubst_flags_t complain)
26294 {
26295   if (olddecl == error_mark_node)
26296     return error_mark_node;
26297 
26298   tree oldidx = get_template_parm_index (olddecl);
26299 
26300   tree newtype;
26301   if (TREE_CODE (olddecl) == TYPE_DECL
26302       || TREE_CODE (olddecl) == TEMPLATE_DECL)
26303     {
26304       tree oldtype = TREE_TYPE (olddecl);
26305       newtype = cxx_make_type (TREE_CODE (oldtype));
26306       TYPE_MAIN_VARIANT (newtype) = newtype;
26307       if (TREE_CODE (oldtype) == TEMPLATE_TYPE_PARM)
26308 	TEMPLATE_TYPE_PARM_FOR_CLASS (newtype)
26309 	  = TEMPLATE_TYPE_PARM_FOR_CLASS (oldtype);
26310     }
26311   else
26312     {
26313       newtype = TREE_TYPE (olddecl);
26314       if (type_uses_auto (newtype))
26315 	{
26316 	  // Substitute once to fix references to other template parameters.
26317 	  newtype = tsubst (newtype, tsubst_args,
26318 			    complain|tf_partial, NULL_TREE);
26319 	  // Now substitute again to reduce the level of the auto.
26320 	  newtype = tsubst (newtype, current_template_args (),
26321 			    complain, NULL_TREE);
26322 	}
26323       else
26324 	newtype = tsubst (newtype, tsubst_args,
26325 			  complain, NULL_TREE);
26326     }
26327 
26328   tree newdecl
26329     = build_decl (DECL_SOURCE_LOCATION (olddecl), TREE_CODE (olddecl),
26330 		  DECL_NAME (olddecl), newtype);
26331   SET_DECL_TEMPLATE_PARM_P (newdecl);
26332 
26333   tree newidx;
26334   if (TREE_CODE (olddecl) == TYPE_DECL
26335       || TREE_CODE (olddecl) == TEMPLATE_DECL)
26336     {
26337       newidx = TEMPLATE_TYPE_PARM_INDEX (newtype)
26338 	= build_template_parm_index (index, level, level,
26339 				     newdecl, newtype);
26340       TEMPLATE_PARM_PARAMETER_PACK (newidx)
26341 	= TEMPLATE_PARM_PARAMETER_PACK (oldidx);
26342       TYPE_STUB_DECL (newtype) = TYPE_NAME (newtype) = newdecl;
26343       TYPE_CANONICAL (newtype) = canonical_type_parameter (newtype);
26344 
26345       if (TREE_CODE (olddecl) == TEMPLATE_DECL)
26346 	{
26347 	  DECL_TEMPLATE_RESULT (newdecl)
26348 	    = build_decl (DECL_SOURCE_LOCATION (olddecl), TYPE_DECL,
26349 			  DECL_NAME (olddecl), newtype);
26350 	  DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (newdecl)) = true;
26351 	  // First create a copy (ttargs) of tsubst_args with an
26352 	  // additional level for the template template parameter's own
26353 	  // template parameters (ttparms).
26354 	  tree ttparms = (INNERMOST_TEMPLATE_PARMS
26355 			  (DECL_TEMPLATE_PARMS (olddecl)));
26356 	  const int depth = TMPL_ARGS_DEPTH (tsubst_args);
26357 	  tree ttargs = make_tree_vec (depth + 1);
26358 	  for (int i = 0; i < depth; ++i)
26359 	    TREE_VEC_ELT (ttargs, i) = TREE_VEC_ELT (tsubst_args, i);
26360 	  TREE_VEC_ELT (ttargs, depth)
26361 	    = template_parms_level_to_args (ttparms);
26362 	  // Substitute ttargs into ttparms to fix references to
26363 	  // other template parameters.
26364 	  ttparms = tsubst_template_parms_level (ttparms, ttargs,
26365 						 complain|tf_partial);
26366 	  // Now substitute again with args based on tparms, to reduce
26367 	  // the level of the ttparms.
26368 	  ttargs = current_template_args ();
26369 	  ttparms = tsubst_template_parms_level (ttparms, ttargs,
26370 						 complain);
26371 	  // Finally, tack the adjusted parms onto tparms.
26372 	  ttparms = tree_cons (size_int (depth), ttparms,
26373 			       current_template_parms);
26374 	  DECL_TEMPLATE_PARMS (newdecl) = ttparms;
26375 	}
26376     }
26377   else
26378     {
26379       tree oldconst = TEMPLATE_PARM_DECL (oldidx);
26380       tree newconst
26381 	= build_decl (DECL_SOURCE_LOCATION (oldconst),
26382 		      TREE_CODE (oldconst),
26383 		      DECL_NAME (oldconst), newtype);
26384       TREE_CONSTANT (newconst) = TREE_CONSTANT (newdecl)
26385 	= TREE_READONLY (newconst) = TREE_READONLY (newdecl) = true;
26386       SET_DECL_TEMPLATE_PARM_P (newconst);
26387       newidx = build_template_parm_index (index, level, level,
26388 					  newconst, newtype);
26389       TEMPLATE_PARM_PARAMETER_PACK (newidx)
26390 	= TEMPLATE_PARM_PARAMETER_PACK (oldidx);
26391       DECL_INITIAL (newdecl) = DECL_INITIAL (newconst) = newidx;
26392     }
26393 
26394   return newdecl;
26395 }
26396 
26397 /* Returns a C++17 class deduction guide template based on the constructor
26398    CTOR.  As a special case, CTOR can be a RECORD_TYPE for an implicit default
26399    guide, or REFERENCE_TYPE for an implicit copy/move guide.  */
26400 
26401 static tree
build_deduction_guide(tree ctor,tree outer_args,tsubst_flags_t complain)26402 build_deduction_guide (tree ctor, tree outer_args, tsubst_flags_t complain)
26403 {
26404   tree type, tparms, targs, fparms, fargs, ci;
26405   bool memtmpl = false;
26406   bool explicit_p;
26407   location_t loc;
26408   tree fn_tmpl = NULL_TREE;
26409 
26410   if (TYPE_P (ctor))
26411     {
26412       type = ctor;
26413       bool copy_p = TREE_CODE (type) == REFERENCE_TYPE;
26414       if (copy_p)
26415 	{
26416 	  type = TREE_TYPE (type);
26417 	  fparms = tree_cons (NULL_TREE, type, void_list_node);
26418 	}
26419       else
26420 	fparms = void_list_node;
26421 
26422       tree ctmpl = CLASSTYPE_TI_TEMPLATE (type);
26423       tparms = DECL_TEMPLATE_PARMS (ctmpl);
26424       targs = CLASSTYPE_TI_ARGS (type);
26425       ci = NULL_TREE;
26426       fargs = NULL_TREE;
26427       loc = DECL_SOURCE_LOCATION (ctmpl);
26428       explicit_p = false;
26429     }
26430   else
26431     {
26432       ++processing_template_decl;
26433       bool ok = true;
26434 
26435       fn_tmpl
26436 	= (TREE_CODE (ctor) == TEMPLATE_DECL ? ctor
26437 	   : DECL_TI_TEMPLATE (ctor));
26438       if (outer_args)
26439 	fn_tmpl = tsubst (fn_tmpl, outer_args, complain, ctor);
26440       ctor = DECL_TEMPLATE_RESULT (fn_tmpl);
26441 
26442       type = DECL_CONTEXT (ctor);
26443 
26444       tparms = DECL_TEMPLATE_PARMS (fn_tmpl);
26445       /* If type is a member class template, DECL_TI_ARGS (ctor) will have
26446 	 fully specialized args for the enclosing class.  Strip those off, as
26447 	 the deduction guide won't have those template parameters.  */
26448       targs = get_innermost_template_args (DECL_TI_ARGS (ctor),
26449 						TMPL_PARMS_DEPTH (tparms));
26450       /* Discard the 'this' parameter.  */
26451       fparms = FUNCTION_ARG_CHAIN (ctor);
26452       fargs = TREE_CHAIN (DECL_ARGUMENTS (ctor));
26453       ci = get_constraints (ctor);
26454       loc = DECL_SOURCE_LOCATION (ctor);
26455       explicit_p = DECL_NONCONVERTING_P (ctor);
26456 
26457       if (PRIMARY_TEMPLATE_P (fn_tmpl))
26458 	{
26459 	  memtmpl = true;
26460 
26461 	  /* For a member template constructor, we need to flatten the two
26462 	     template parameter lists into one, and then adjust the function
26463 	     signature accordingly.  This gets...complicated.  */
26464 	  tree save_parms = current_template_parms;
26465 
26466 	  /* For a member template we should have two levels of parms/args, one
26467 	     for the class and one for the constructor.  We stripped
26468 	     specialized args for further enclosing classes above.  */
26469 	  const int depth = 2;
26470 	  gcc_assert (TMPL_ARGS_DEPTH (targs) == depth);
26471 
26472 	  /* Template args for translating references to the two-level template
26473 	     parameters into references to the one-level template parameters we
26474 	     are creating.  */
26475 	  tree tsubst_args = copy_node (targs);
26476 	  TMPL_ARGS_LEVEL (tsubst_args, depth)
26477 	    = copy_node (TMPL_ARGS_LEVEL (tsubst_args, depth));
26478 
26479 	  /* Template parms for the constructor template.  */
26480 	  tree ftparms = TREE_VALUE (tparms);
26481 	  unsigned flen = TREE_VEC_LENGTH (ftparms);
26482 	  /* Template parms for the class template.  */
26483 	  tparms = TREE_CHAIN (tparms);
26484 	  tree ctparms = TREE_VALUE (tparms);
26485 	  unsigned clen = TREE_VEC_LENGTH (ctparms);
26486 	  /* Template parms for the deduction guide start as a copy of the
26487 	     template parms for the class.  We set current_template_parms for
26488 	     lookup_template_class_1.  */
26489 	  current_template_parms = tparms = copy_node (tparms);
26490 	  tree new_vec = TREE_VALUE (tparms) = make_tree_vec (flen + clen);
26491 	  for (unsigned i = 0; i < clen; ++i)
26492 	    TREE_VEC_ELT (new_vec, i) = TREE_VEC_ELT (ctparms, i);
26493 
26494 	  /* Now we need to rewrite the constructor parms to append them to the
26495 	     class parms.  */
26496 	  for (unsigned i = 0; i < flen; ++i)
26497 	    {
26498 	      unsigned index = i + clen;
26499 	      unsigned level = 1;
26500 	      tree oldelt = TREE_VEC_ELT (ftparms, i);
26501 	      tree olddecl = TREE_VALUE (oldelt);
26502 	      tree newdecl = rewrite_template_parm (olddecl, index, level,
26503 						    tsubst_args, complain);
26504 	      if (newdecl == error_mark_node)
26505 		ok = false;
26506 	      tree newdef = tsubst_template_arg (TREE_PURPOSE (oldelt),
26507 						 tsubst_args, complain, ctor);
26508 	      tree list = build_tree_list (newdef, newdecl);
26509 	      TEMPLATE_PARM_CONSTRAINTS (list)
26510 		= tsubst_constraint_info (TEMPLATE_PARM_CONSTRAINTS (oldelt),
26511 					  tsubst_args, complain, ctor);
26512 	      TREE_VEC_ELT (new_vec, index) = list;
26513 	      TMPL_ARG (tsubst_args, depth, i) = template_parm_to_arg (list);
26514 	    }
26515 
26516 	  /* Now we have a final set of template parms to substitute into the
26517 	     function signature.  */
26518 	  targs = template_parms_to_args (tparms);
26519 	  fparms = tsubst_arg_types (fparms, tsubst_args, NULL_TREE,
26520 				     complain, ctor);
26521 	  if (fparms == error_mark_node)
26522 	    ok = false;
26523 	  fargs = tsubst (fargs, tsubst_args, complain, ctor);
26524 	  if (ci)
26525 	    ci = tsubst_constraint_info (ci, tsubst_args, complain, ctor);
26526 
26527 	  current_template_parms = save_parms;
26528 	}
26529 
26530       --processing_template_decl;
26531       if (!ok)
26532 	return error_mark_node;
26533     }
26534 
26535   if (!memtmpl)
26536     {
26537       /* Copy the parms so we can set DECL_PRIMARY_TEMPLATE.  */
26538       tparms = copy_node (tparms);
26539       INNERMOST_TEMPLATE_PARMS (tparms)
26540 	= copy_node (INNERMOST_TEMPLATE_PARMS (tparms));
26541     }
26542 
26543   tree fntype = build_function_type (type, fparms);
26544   tree ded_fn = build_lang_decl_loc (loc,
26545 				     FUNCTION_DECL,
26546 				     dguide_name (type), fntype);
26547   DECL_ARGUMENTS (ded_fn) = fargs;
26548   DECL_ARTIFICIAL (ded_fn) = true;
26549   DECL_NONCONVERTING_P (ded_fn) = explicit_p;
26550   tree ded_tmpl = build_template_decl (ded_fn, tparms, /*member*/false);
26551   DECL_ARTIFICIAL (ded_tmpl) = true;
26552   DECL_TEMPLATE_RESULT (ded_tmpl) = ded_fn;
26553   TREE_TYPE (ded_tmpl) = TREE_TYPE (ded_fn);
26554   DECL_TEMPLATE_INFO (ded_fn) = build_template_info (ded_tmpl, targs);
26555   DECL_PRIMARY_TEMPLATE (ded_tmpl) = ded_tmpl;
26556   if (DECL_P (ctor))
26557     DECL_ABSTRACT_ORIGIN (ded_tmpl) = fn_tmpl;
26558   if (ci)
26559     set_constraints (ded_tmpl, ci);
26560 
26561   return ded_tmpl;
26562 }
26563 
26564 /* Deduce template arguments for the class template placeholder PTYPE for
26565    template TMPL based on the initializer INIT, and return the resulting
26566    type.  */
26567 
26568 static tree
do_class_deduction(tree ptype,tree tmpl,tree init,int flags,tsubst_flags_t complain)26569 do_class_deduction (tree ptype, tree tmpl, tree init, int flags,
26570 		    tsubst_flags_t complain)
26571 {
26572   if (!DECL_CLASS_TEMPLATE_P (tmpl))
26573     {
26574       /* We should have handled this in the caller.  */
26575       if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
26576 	return ptype;
26577       if (complain & tf_error)
26578 	error ("non-class template %qT used without template arguments", tmpl);
26579       return error_mark_node;
26580     }
26581   if (init && TREE_TYPE (init) == ptype)
26582     /* Using the template parm as its own argument.  */
26583     return ptype;
26584 
26585   tree type = TREE_TYPE (tmpl);
26586 
26587   bool try_list_ctor = false;
26588 
26589   vec<tree,va_gc> *args;
26590   if (init == NULL_TREE
26591       || TREE_CODE (init) == TREE_LIST)
26592     args = make_tree_vector_from_list (init);
26593   else if (BRACE_ENCLOSED_INITIALIZER_P (init))
26594     {
26595       try_list_ctor = TYPE_HAS_LIST_CTOR (type);
26596       if (try_list_ctor && CONSTRUCTOR_NELTS (init) == 1)
26597 	{
26598 	  /* As an exception, the first phase in 16.3.1.7 (considering the
26599 	     initializer list as a single argument) is omitted if the
26600 	     initializer list consists of a single expression of type cv U,
26601 	     where U is a specialization of C or a class derived from a
26602 	     specialization of C.  */
26603 	  tree elt = CONSTRUCTOR_ELT (init, 0)->value;
26604 	  tree etype = TREE_TYPE (elt);
26605 
26606 	  tree tparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
26607 	  tree targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
26608 	  int err = unify (tparms, targs, type, etype,
26609 			   UNIFY_ALLOW_DERIVED, /*explain*/false);
26610 	  if (err == 0)
26611 	    try_list_ctor = false;
26612 	  ggc_free (targs);
26613 	}
26614       if (try_list_ctor || is_std_init_list (type))
26615 	args = make_tree_vector_single (init);
26616       else
26617 	args = make_tree_vector_from_ctor (init);
26618     }
26619   else
26620     args = make_tree_vector_single (init);
26621 
26622   tree dname = dguide_name (tmpl);
26623   tree cands = lookup_qualified_name (CP_DECL_CONTEXT (tmpl), dname,
26624 				      /*type*/false, /*complain*/false,
26625 				      /*hidden*/false);
26626   bool elided = false;
26627   if (cands == error_mark_node)
26628     cands = NULL_TREE;
26629 
26630   /* Prune explicit deduction guides in copy-initialization context.  */
26631   if (flags & LOOKUP_ONLYCONVERTING)
26632     {
26633       for (lkp_iterator iter (cands); !elided && iter; ++iter)
26634 	if (DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
26635 	  elided = true;
26636 
26637       if (elided)
26638 	{
26639 	  /* Found a nonconverting guide, prune the candidates.  */
26640 	  tree pruned = NULL_TREE;
26641 	  for (lkp_iterator iter (cands); iter; ++iter)
26642 	    if (!DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
26643 	      pruned = lookup_add (*iter, pruned);
26644 
26645 	  cands = pruned;
26646 	}
26647     }
26648 
26649   tree outer_args = NULL_TREE;
26650   if (DECL_CLASS_SCOPE_P (tmpl)
26651       && CLASSTYPE_TEMPLATE_INSTANTIATION (DECL_CONTEXT (tmpl)))
26652     {
26653       outer_args = CLASSTYPE_TI_ARGS (DECL_CONTEXT (tmpl));
26654       type = TREE_TYPE (most_general_template (tmpl));
26655     }
26656 
26657   bool saw_ctor = false;
26658   // FIXME cache artificial deduction guides
26659   for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (type)); iter; ++iter)
26660     {
26661       /* Skip inherited constructors.  */
26662       if (iter.using_p ())
26663 	continue;
26664 
26665       tree guide = build_deduction_guide (*iter, outer_args, complain);
26666       if (guide == error_mark_node)
26667 	return error_mark_node;
26668       if ((flags & LOOKUP_ONLYCONVERTING)
26669 	  && DECL_NONCONVERTING_P (STRIP_TEMPLATE (guide)))
26670 	elided = true;
26671       else
26672 	cands = lookup_add (guide, cands);
26673 
26674       saw_ctor = true;
26675     }
26676 
26677   tree call = error_mark_node;
26678 
26679   /* If this is list-initialization and the class has a list constructor, first
26680      try deducing from the list as a single argument, as [over.match.list].  */
26681   tree list_cands = NULL_TREE;
26682   if (try_list_ctor && cands)
26683     for (lkp_iterator iter (cands); iter; ++iter)
26684       {
26685 	tree dg = *iter;
26686 	if (is_list_ctor (dg))
26687 	  list_cands = lookup_add (dg, list_cands);
26688       }
26689   if (list_cands)
26690     {
26691       ++cp_unevaluated_operand;
26692       call = build_new_function_call (list_cands, &args, tf_decltype);
26693       --cp_unevaluated_operand;
26694 
26695       if (call == error_mark_node)
26696 	{
26697 	  /* That didn't work, now try treating the list as a sequence of
26698 	     arguments.  */
26699 	  release_tree_vector (args);
26700 	  args = make_tree_vector_from_ctor (init);
26701 	}
26702     }
26703 
26704   /* Maybe generate an implicit deduction guide.  */
26705   if (call == error_mark_node && args->length () < 2)
26706     {
26707       tree gtype = NULL_TREE;
26708 
26709       if (args->length () == 1)
26710 	/* Generate a copy guide.  */
26711 	gtype = build_reference_type (type);
26712       else if (!saw_ctor)
26713 	/* Generate a default guide.  */
26714 	gtype = type;
26715 
26716       if (gtype)
26717 	{
26718 	  tree guide = build_deduction_guide (gtype, outer_args, complain);
26719 	  if (guide == error_mark_node)
26720 	    return error_mark_node;
26721 	  cands = lookup_add (guide, cands);
26722 	}
26723     }
26724 
26725   if (elided && !cands)
26726     {
26727       error ("cannot deduce template arguments for copy-initialization"
26728 	     " of %qT, as it has no non-explicit deduction guides or "
26729 	     "user-declared constructors", type);
26730       return error_mark_node;
26731     }
26732   else if (!cands && call == error_mark_node)
26733     {
26734       error ("cannot deduce template arguments of %qT, as it has no viable "
26735 	     "deduction guides", type);
26736       return error_mark_node;
26737     }
26738 
26739   if (call == error_mark_node)
26740     {
26741       ++cp_unevaluated_operand;
26742       call = build_new_function_call (cands, &args, tf_decltype);
26743       --cp_unevaluated_operand;
26744     }
26745 
26746   if (call == error_mark_node && (complain & tf_warning_or_error))
26747     {
26748       error ("class template argument deduction failed:");
26749 
26750       ++cp_unevaluated_operand;
26751       call = build_new_function_call (cands, &args, complain | tf_decltype);
26752       --cp_unevaluated_operand;
26753 
26754       if (elided)
26755 	inform (input_location, "explicit deduction guides not considered "
26756 		"for copy-initialization");
26757     }
26758 
26759   release_tree_vector (args);
26760 
26761   return cp_build_qualified_type (TREE_TYPE (call), cp_type_quals (ptype));
26762 }
26763 
26764 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
26765    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
26766    The CONTEXT determines the context in which auto deduction is performed
26767    and is used to control error diagnostics.  FLAGS are the LOOKUP_* flags.
26768    OUTER_TARGS are used during template argument deduction
26769    (context == adc_unify) to properly substitute the result, and is ignored
26770    in other contexts.
26771 
26772    For partial-concept-ids, extra args may be appended to the list of deduced
26773    template arguments prior to determining constraint satisfaction.  */
26774 
26775 tree
do_auto_deduction(tree type,tree init,tree auto_node,tsubst_flags_t complain,auto_deduction_context context,tree outer_targs,int flags)26776 do_auto_deduction (tree type, tree init, tree auto_node,
26777                    tsubst_flags_t complain, auto_deduction_context context,
26778 		   tree outer_targs, int flags)
26779 {
26780   tree targs;
26781 
26782   if (init == error_mark_node)
26783     return error_mark_node;
26784 
26785   if (init && type_dependent_expression_p (init)
26786       && context != adc_unify)
26787     /* Defining a subset of type-dependent expressions that we can deduce
26788        from ahead of time isn't worth the trouble.  */
26789     return type;
26790 
26791   /* Similarly, we can't deduce from another undeduced decl.  */
26792   if (init && undeduced_auto_decl (init))
26793     return type;
26794 
26795   if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
26796     /* C++17 class template argument deduction.  */
26797     return do_class_deduction (type, tmpl, init, flags, complain);
26798 
26799   if (init == NULL_TREE || TREE_TYPE (init) == NULL_TREE)
26800     /* Nothing we can do with this, even in deduction context.  */
26801     return type;
26802 
26803   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
26804      with either a new invented type template parameter U or, if the
26805      initializer is a braced-init-list (8.5.4), with
26806      std::initializer_list<U>.  */
26807   if (BRACE_ENCLOSED_INITIALIZER_P (init))
26808     {
26809       if (!DIRECT_LIST_INIT_P (init))
26810 	type = listify_autos (type, auto_node);
26811       else if (CONSTRUCTOR_NELTS (init) == 1)
26812 	init = CONSTRUCTOR_ELT (init, 0)->value;
26813       else
26814 	{
26815           if (complain & tf_warning_or_error)
26816             {
26817 	      if (permerror (input_location, "direct-list-initialization of "
26818 			     "%<auto%> requires exactly one element"))
26819 	        inform (input_location,
26820 		        "for deduction to %<std::initializer_list%>, use copy-"
26821 		        "list-initialization (i.e. add %<=%> before the %<{%>)");
26822             }
26823 	  type = listify_autos (type, auto_node);
26824 	}
26825     }
26826 
26827   if (type == error_mark_node)
26828     return error_mark_node;
26829 
26830   init = resolve_nondeduced_context (init, complain);
26831 
26832   if (context == adc_decomp_type
26833       && auto_node == type
26834       && init != error_mark_node
26835       && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
26836     /* [dcl.decomp]/1 - if decomposition declaration has no ref-qualifiers
26837        and initializer has array type, deduce cv-qualified array type.  */
26838     return cp_build_qualified_type_real (TREE_TYPE (init), TYPE_QUALS (type),
26839 					 complain);
26840   else if (AUTO_IS_DECLTYPE (auto_node))
26841     {
26842       bool id = (DECL_P (init)
26843 		 || ((TREE_CODE (init) == COMPONENT_REF
26844 		      || TREE_CODE (init) == SCOPE_REF)
26845 		     && !REF_PARENTHESIZED_P (init)));
26846       targs = make_tree_vec (1);
26847       TREE_VEC_ELT (targs, 0)
26848 	= finish_decltype_type (init, id, tf_warning_or_error);
26849       if (type != auto_node)
26850 	{
26851           if (complain & tf_error)
26852 	    error ("%qT as type rather than plain %<decltype(auto)%>", type);
26853 	  return error_mark_node;
26854 	}
26855     }
26856   else
26857     {
26858       tree parms = build_tree_list (NULL_TREE, type);
26859       tree tparms;
26860 
26861       if (flag_concepts)
26862 	tparms = extract_autos (type);
26863       else
26864 	{
26865 	  tparms = make_tree_vec (1);
26866 	  TREE_VEC_ELT (tparms, 0)
26867 	    = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
26868 	}
26869 
26870       targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
26871       int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
26872 				       DEDUCE_CALL, LOOKUP_NORMAL,
26873 				       NULL, /*explain_p=*/false);
26874       if (val > 0)
26875 	{
26876 	  if (processing_template_decl)
26877 	    /* Try again at instantiation time.  */
26878 	    return type;
26879 	  if (type && type != error_mark_node
26880 	      && (complain & tf_error))
26881 	    /* If type is error_mark_node a diagnostic must have been
26882 	       emitted by now.  Also, having a mention to '<type error>'
26883 	       in the diagnostic is not really useful to the user.  */
26884 	    {
26885 	      if (cfun && auto_node == current_function_auto_return_pattern
26886 		  && LAMBDA_FUNCTION_P (current_function_decl))
26887 		error ("unable to deduce lambda return type from %qE", init);
26888 	      else
26889 		error ("unable to deduce %qT from %qE", type, init);
26890 	      type_unification_real (tparms, targs, parms, &init, 1, 0,
26891 				     DEDUCE_CALL, LOOKUP_NORMAL,
26892 				     NULL, /*explain_p=*/true);
26893 	    }
26894 	  return error_mark_node;
26895 	}
26896     }
26897 
26898   /* Check any placeholder constraints against the deduced type. */
26899   if (flag_concepts && !processing_template_decl)
26900     if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (auto_node))
26901       {
26902         /* Use the deduced type to check the associated constraints. If we
26903            have a partial-concept-id, rebuild the argument list so that
26904            we check using the extra arguments. */
26905         gcc_assert (TREE_CODE (constr) == CHECK_CONSTR);
26906         tree cargs = CHECK_CONSTR_ARGS (constr);
26907         if (TREE_VEC_LENGTH (cargs) > 1)
26908           {
26909             cargs = copy_node (cargs);
26910             TREE_VEC_ELT (cargs, 0) = TREE_VEC_ELT (targs, 0);
26911           }
26912         else
26913           cargs = targs;
26914         if (!constraints_satisfied_p (constr, cargs))
26915           {
26916             if (complain & tf_warning_or_error)
26917               {
26918                 switch (context)
26919                   {
26920                   case adc_unspecified:
26921 		  case adc_unify:
26922                     error("placeholder constraints not satisfied");
26923                     break;
26924                   case adc_variable_type:
26925 		  case adc_decomp_type:
26926                     error ("deduced initializer does not satisfy "
26927                            "placeholder constraints");
26928                     break;
26929                   case adc_return_type:
26930                     error ("deduced return type does not satisfy "
26931                            "placeholder constraints");
26932                     break;
26933                   case adc_requirement:
26934 		    error ("deduced expression type does not satisfy "
26935                            "placeholder constraints");
26936                     break;
26937                   }
26938                 diagnose_constraints (input_location, constr, targs);
26939               }
26940             return error_mark_node;
26941           }
26942       }
26943 
26944   if (processing_template_decl && context != adc_unify)
26945     outer_targs = current_template_args ();
26946   targs = add_to_template_args (outer_targs, targs);
26947   return tsubst (type, targs, complain, NULL_TREE);
26948 }
26949 
26950 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
26951    result.  */
26952 
26953 tree
splice_late_return_type(tree type,tree late_return_type)26954 splice_late_return_type (tree type, tree late_return_type)
26955 {
26956   if (is_auto (type))
26957     {
26958       if (late_return_type)
26959 	return late_return_type;
26960 
26961       tree idx = get_template_parm_index (type);
26962       if (TEMPLATE_PARM_LEVEL (idx) <= processing_template_decl)
26963 	/* In an abbreviated function template we didn't know we were dealing
26964 	   with a function template when we saw the auto return type, so update
26965 	   it to have the correct level.  */
26966 	return make_auto_1 (TYPE_IDENTIFIER (type), true);
26967     }
26968   return type;
26969 }
26970 
26971 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
26972    'decltype(auto)' or a deduced class template.  */
26973 
26974 bool
is_auto(const_tree type)26975 is_auto (const_tree type)
26976 {
26977   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
26978       && (TYPE_IDENTIFIER (type) == auto_identifier
26979 	  || TYPE_IDENTIFIER (type) == decltype_auto_identifier
26980 	  || CLASS_PLACEHOLDER_TEMPLATE (type)))
26981     return true;
26982   else
26983     return false;
26984 }
26985 
26986 /* for_each_template_parm callback for type_uses_auto.  */
26987 
26988 int
is_auto_r(tree tp,void *)26989 is_auto_r (tree tp, void */*data*/)
26990 {
26991   return is_auto (tp);
26992 }
26993 
26994 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
26995    a use of `auto'.  Returns NULL_TREE otherwise.  */
26996 
26997 tree
type_uses_auto(tree type)26998 type_uses_auto (tree type)
26999 {
27000   if (type == NULL_TREE)
27001     return NULL_TREE;
27002   else if (flag_concepts)
27003     {
27004       /* The Concepts TS allows multiple autos in one type-specifier; just
27005 	 return the first one we find, do_auto_deduction will collect all of
27006 	 them.  */
27007       if (uses_template_parms (type))
27008 	return for_each_template_parm (type, is_auto_r, /*data*/NULL,
27009 				       /*visited*/NULL, /*nondeduced*/false);
27010       else
27011 	return NULL_TREE;
27012     }
27013   else
27014     return find_type_usage (type, is_auto);
27015 }
27016 
27017 /* Report ill-formed occurrences of auto types in ARGUMENTS.  If
27018    concepts are enabled, auto is acceptable in template arguments, but
27019    only when TEMPL identifies a template class.  Return TRUE if any
27020    such errors were reported.  */
27021 
27022 bool
check_auto_in_tmpl_args(tree tmpl,tree args)27023 check_auto_in_tmpl_args (tree tmpl, tree args)
27024 {
27025   /* If there were previous errors, nevermind.  */
27026   if (!args || TREE_CODE (args) != TREE_VEC)
27027     return false;
27028 
27029   /* If TMPL is an identifier, we're parsing and we can't tell yet
27030      whether TMPL is supposed to be a type, a function or a variable.
27031      We'll only be able to tell during template substitution, so we
27032      expect to be called again then.  If concepts are enabled and we
27033      know we have a type, we're ok.  */
27034   if (flag_concepts
27035       && (identifier_p (tmpl)
27036 	  || (DECL_P (tmpl)
27037 	      &&  (DECL_TYPE_TEMPLATE_P (tmpl)
27038 		   || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)))))
27039     return false;
27040 
27041   /* Quickly search for any occurrences of auto; usually there won't
27042      be any, and then we'll avoid allocating the vector.  */
27043   if (!type_uses_auto (args))
27044     return false;
27045 
27046   bool errors = false;
27047 
27048   tree vec = extract_autos (args);
27049   for (int i = 0; i < TREE_VEC_LENGTH (vec); i++)
27050     {
27051       tree xauto = TREE_VALUE (TREE_VEC_ELT (vec, i));
27052       error_at (DECL_SOURCE_LOCATION (xauto),
27053 		"invalid use of %qT in template argument", xauto);
27054       errors = true;
27055     }
27056 
27057   return errors;
27058 }
27059 
27060 /* For a given template T, return the vector of typedefs referenced
27061    in T for which access check is needed at T instantiation time.
27062    T is either  a FUNCTION_DECL or a RECORD_TYPE.
27063    Those typedefs were added to T by the function
27064    append_type_to_template_for_access_check.  */
27065 
27066 vec<qualified_typedef_usage_t, va_gc> *
get_types_needing_access_check(tree t)27067 get_types_needing_access_check (tree t)
27068 {
27069   tree ti;
27070   vec<qualified_typedef_usage_t, va_gc> *result = NULL;
27071 
27072   if (!t || t == error_mark_node)
27073     return NULL;
27074 
27075   if (!(ti = get_template_info (t)))
27076     return NULL;
27077 
27078   if (CLASS_TYPE_P (t)
27079       || TREE_CODE (t) == FUNCTION_DECL)
27080     {
27081       if (!TI_TEMPLATE (ti))
27082 	return NULL;
27083 
27084       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
27085     }
27086 
27087   return result;
27088 }
27089 
27090 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
27091    tied to T. That list of typedefs will be access checked at
27092    T instantiation time.
27093    T is either a FUNCTION_DECL or a RECORD_TYPE.
27094    TYPE_DECL is a TYPE_DECL node representing a typedef.
27095    SCOPE is the scope through which TYPE_DECL is accessed.
27096    LOCATION is the location of the usage point of TYPE_DECL.
27097 
27098    This function is a subroutine of
27099    append_type_to_template_for_access_check.  */
27100 
27101 static void
append_type_to_template_for_access_check_1(tree t,tree type_decl,tree scope,location_t location)27102 append_type_to_template_for_access_check_1 (tree t,
27103 					    tree type_decl,
27104 					    tree scope,
27105 					    location_t location)
27106 {
27107   qualified_typedef_usage_t typedef_usage;
27108   tree ti;
27109 
27110   if (!t || t == error_mark_node)
27111     return;
27112 
27113   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
27114 	       || CLASS_TYPE_P (t))
27115 	      && type_decl
27116 	      && TREE_CODE (type_decl) == TYPE_DECL
27117 	      && scope);
27118 
27119   if (!(ti = get_template_info (t)))
27120     return;
27121 
27122   gcc_assert (TI_TEMPLATE (ti));
27123 
27124   typedef_usage.typedef_decl = type_decl;
27125   typedef_usage.context = scope;
27126   typedef_usage.locus = location;
27127 
27128   vec_safe_push (TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti), typedef_usage);
27129 }
27130 
27131 /* Append TYPE_DECL to the template TEMPL.
27132    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
27133    At TEMPL instanciation time, TYPE_DECL will be checked to see
27134    if it can be accessed through SCOPE.
27135    LOCATION is the location of the usage point of TYPE_DECL.
27136 
27137    e.g. consider the following code snippet:
27138 
27139      class C
27140      {
27141        typedef int myint;
27142      };
27143 
27144      template<class U> struct S
27145      {
27146        C::myint mi; // <-- usage point of the typedef C::myint
27147      };
27148 
27149      S<char> s;
27150 
27151    At S<char> instantiation time, we need to check the access of C::myint
27152    In other words, we need to check the access of the myint typedef through
27153    the C scope. For that purpose, this function will add the myint typedef
27154    and the scope C through which its being accessed to a list of typedefs
27155    tied to the template S. That list will be walked at template instantiation
27156    time and access check performed on each typedefs it contains.
27157    Note that this particular code snippet should yield an error because
27158    myint is private to C.  */
27159 
27160 void
append_type_to_template_for_access_check(tree templ,tree type_decl,tree scope,location_t location)27161 append_type_to_template_for_access_check (tree templ,
27162                                           tree type_decl,
27163 					  tree scope,
27164 					  location_t location)
27165 {
27166   qualified_typedef_usage_t *iter;
27167   unsigned i;
27168 
27169   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
27170 
27171   /* Make sure we don't append the type to the template twice.  */
27172   FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (templ), i, iter)
27173     if (iter->typedef_decl == type_decl && scope == iter->context)
27174       return;
27175 
27176   append_type_to_template_for_access_check_1 (templ, type_decl,
27177 					      scope, location);
27178 }
27179 
27180 /* Convert the generic type parameters in PARM that match the types given in the
27181    range [START_IDX, END_IDX) from the current_template_parms into generic type
27182    packs.  */
27183 
27184 tree
convert_generic_types_to_packs(tree parm,int start_idx,int end_idx)27185 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
27186 {
27187   tree current = current_template_parms;
27188   int depth = TMPL_PARMS_DEPTH (current);
27189   current = INNERMOST_TEMPLATE_PARMS (current);
27190   tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
27191 
27192   for (int i = 0; i < start_idx; ++i)
27193     TREE_VEC_ELT (replacement, i)
27194       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
27195 
27196   for (int i = start_idx; i < end_idx; ++i)
27197     {
27198       /* Create a distinct parameter pack type from the current parm and add it
27199 	 to the replacement args to tsubst below into the generic function
27200 	 parameter.  */
27201 
27202       tree o = TREE_TYPE (TREE_VALUE
27203 			  (TREE_VEC_ELT (current, i)));
27204       tree t = copy_type (o);
27205       TEMPLATE_TYPE_PARM_INDEX (t)
27206 	= reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
27207 				      o, 0, 0, tf_none);
27208       TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
27209       TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
27210       TYPE_MAIN_VARIANT (t) = t;
27211       TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
27212       TYPE_CANONICAL (t) = canonical_type_parameter (t);
27213       TREE_VEC_ELT (replacement, i) = t;
27214       TREE_VALUE (TREE_VEC_ELT (current, i)) = TREE_CHAIN (t);
27215     }
27216 
27217   for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
27218     TREE_VEC_ELT (replacement, i)
27219       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
27220 
27221   /* If there are more levels then build up the replacement with the outer
27222      template parms.  */
27223   if (depth > 1)
27224     replacement = add_to_template_args (template_parms_to_args
27225 					(TREE_CHAIN (current_template_parms)),
27226 					replacement);
27227 
27228   return tsubst (parm, replacement, tf_none, NULL_TREE);
27229 }
27230 
27231 /* Entries in the decl_constraint hash table. */
27232 struct GTY((for_user)) constr_entry
27233 {
27234   tree decl;
27235   tree ci;
27236 };
27237 
27238 /* Hashing function and equality for constraint entries. */
27239 struct constr_hasher : ggc_ptr_hash<constr_entry>
27240 {
hashconstr_hasher27241   static hashval_t hash (constr_entry *e)
27242   {
27243     return (hashval_t)DECL_UID (e->decl);
27244   }
27245 
equalconstr_hasher27246   static bool equal (constr_entry *e1, constr_entry *e2)
27247   {
27248     return e1->decl == e2->decl;
27249   }
27250 };
27251 
27252 /* A mapping from declarations to constraint information. Note that
27253    both templates and their underlying declarations are mapped to the
27254    same constraint information.
27255 
27256    FIXME: This is defined in pt.c because garbage collection
27257    code is not being generated for constraint.cc. */
27258 
27259 static GTY (()) hash_table<constr_hasher> *decl_constraints;
27260 
27261 /* Returns the template constraints of declaration T. If T is not
27262    constrained, return NULL_TREE. Note that T must be non-null. */
27263 
27264 tree
get_constraints(tree t)27265 get_constraints (tree t)
27266 {
27267   if (!flag_concepts)
27268     return NULL_TREE;
27269 
27270   gcc_assert (DECL_P (t));
27271   if (TREE_CODE (t) == TEMPLATE_DECL)
27272     t = DECL_TEMPLATE_RESULT (t);
27273   constr_entry elt = { t, NULL_TREE };
27274   constr_entry* found = decl_constraints->find (&elt);
27275   if (found)
27276     return found->ci;
27277   else
27278     return NULL_TREE;
27279 }
27280 
27281 /* Associate the given constraint information CI with the declaration
27282    T. If T is a template, then the constraints are associated with
27283    its underlying declaration. Don't build associations if CI is
27284    NULL_TREE.  */
27285 
27286 void
set_constraints(tree t,tree ci)27287 set_constraints (tree t, tree ci)
27288 {
27289   if (!ci)
27290     return;
27291   gcc_assert (t && flag_concepts);
27292   if (TREE_CODE (t) == TEMPLATE_DECL)
27293     t = DECL_TEMPLATE_RESULT (t);
27294   gcc_assert (!get_constraints (t));
27295   constr_entry elt = {t, ci};
27296   constr_entry** slot = decl_constraints->find_slot (&elt, INSERT);
27297   constr_entry* entry = ggc_alloc<constr_entry> ();
27298   *entry = elt;
27299   *slot = entry;
27300 }
27301 
27302 /* Remove the associated constraints of the declaration T.  */
27303 
27304 void
remove_constraints(tree t)27305 remove_constraints (tree t)
27306 {
27307   gcc_assert (DECL_P (t));
27308   if (TREE_CODE (t) == TEMPLATE_DECL)
27309     t = DECL_TEMPLATE_RESULT (t);
27310 
27311   constr_entry elt = {t, NULL_TREE};
27312   constr_entry** slot = decl_constraints->find_slot (&elt, NO_INSERT);
27313   if (slot)
27314     decl_constraints->clear_slot (slot);
27315 }
27316 
27317 /* Memoized satisfaction results for declarations. This
27318    maps the pair (constraint_info, arguments) to the result computed
27319    by constraints_satisfied_p.  */
27320 
27321 struct GTY((for_user)) constraint_sat_entry
27322 {
27323   tree ci;
27324   tree args;
27325   tree result;
27326 };
27327 
27328 /* Hashing function and equality for constraint entries. */
27329 
27330 struct constraint_sat_hasher : ggc_ptr_hash<constraint_sat_entry>
27331 {
hashconstraint_sat_hasher27332   static hashval_t hash (constraint_sat_entry *e)
27333   {
27334     hashval_t val = iterative_hash_object(e->ci, 0);
27335     return iterative_hash_template_arg (e->args, val);
27336   }
27337 
equalconstraint_sat_hasher27338   static bool equal (constraint_sat_entry *e1, constraint_sat_entry *e2)
27339   {
27340     return e1->ci == e2->ci && comp_template_args (e1->args, e2->args);
27341   }
27342 };
27343 
27344 /* Memoized satisfaction results for concept checks. */
27345 
27346 struct GTY((for_user)) concept_spec_entry
27347 {
27348   tree tmpl;
27349   tree args;
27350   tree result;
27351 };
27352 
27353 /* Hashing function and equality for constraint entries.  */
27354 
27355 struct concept_spec_hasher : ggc_ptr_hash<concept_spec_entry>
27356 {
hashconcept_spec_hasher27357   static hashval_t hash (concept_spec_entry *e)
27358   {
27359     return hash_tmpl_and_args (e->tmpl, e->args);
27360   }
27361 
equalconcept_spec_hasher27362   static bool equal (concept_spec_entry *e1, concept_spec_entry *e2)
27363   {
27364     ++comparing_specializations;
27365     bool eq = e1->tmpl == e2->tmpl && comp_template_args (e1->args, e2->args);
27366     --comparing_specializations;
27367     return eq;
27368   }
27369 };
27370 
27371 static GTY (()) hash_table<constraint_sat_hasher> *constraint_memos;
27372 static GTY (()) hash_table<concept_spec_hasher> *concept_memos;
27373 
27374 /* Search for a memoized satisfaction result. Returns one of the
27375    truth value nodes if previously memoized, or NULL_TREE otherwise.   */
27376 
27377 tree
lookup_constraint_satisfaction(tree ci,tree args)27378 lookup_constraint_satisfaction (tree ci, tree args)
27379 {
27380   constraint_sat_entry elt = { ci, args, NULL_TREE };
27381   constraint_sat_entry* found = constraint_memos->find (&elt);
27382   if (found)
27383     return found->result;
27384   else
27385     return NULL_TREE;
27386 }
27387 
27388 /* Memoize the result of a satisfication test. Returns the saved result.  */
27389 
27390 tree
memoize_constraint_satisfaction(tree ci,tree args,tree result)27391 memoize_constraint_satisfaction (tree ci, tree args, tree result)
27392 {
27393   constraint_sat_entry elt = {ci, args, result};
27394   constraint_sat_entry** slot = constraint_memos->find_slot (&elt, INSERT);
27395   constraint_sat_entry* entry = ggc_alloc<constraint_sat_entry> ();
27396   *entry = elt;
27397   *slot = entry;
27398   return result;
27399 }
27400 
27401 /* Search for a memoized satisfaction result for a concept. */
27402 
27403 tree
lookup_concept_satisfaction(tree tmpl,tree args)27404 lookup_concept_satisfaction (tree tmpl, tree args)
27405 {
27406   concept_spec_entry elt = { tmpl, args, NULL_TREE };
27407   concept_spec_entry* found = concept_memos->find (&elt);
27408   if (found)
27409     return found->result;
27410   else
27411     return NULL_TREE;
27412 }
27413 
27414 /* Memoize the result of a concept check. Returns the saved result.  */
27415 
27416 tree
memoize_concept_satisfaction(tree tmpl,tree args,tree result)27417 memoize_concept_satisfaction (tree tmpl, tree args, tree result)
27418 {
27419   concept_spec_entry elt = {tmpl, args, result};
27420   concept_spec_entry** slot = concept_memos->find_slot (&elt, INSERT);
27421   concept_spec_entry* entry = ggc_alloc<concept_spec_entry> ();
27422   *entry = elt;
27423   *slot = entry;
27424   return result;
27425 }
27426 
27427 static GTY (()) hash_table<concept_spec_hasher> *concept_expansions;
27428 
27429 /* Returns a prior concept specialization. This returns the substituted
27430    and normalized constraints defined by the concept.  */
27431 
27432 tree
get_concept_expansion(tree tmpl,tree args)27433 get_concept_expansion (tree tmpl, tree args)
27434 {
27435   concept_spec_entry elt = { tmpl, args, NULL_TREE };
27436   concept_spec_entry* found = concept_expansions->find (&elt);
27437   if (found)
27438     return found->result;
27439   else
27440     return NULL_TREE;
27441 }
27442 
27443 /* Save a concept expansion for later.  */
27444 
27445 tree
save_concept_expansion(tree tmpl,tree args,tree def)27446 save_concept_expansion (tree tmpl, tree args, tree def)
27447 {
27448   concept_spec_entry elt = {tmpl, args, def};
27449   concept_spec_entry** slot = concept_expansions->find_slot (&elt, INSERT);
27450   concept_spec_entry* entry = ggc_alloc<concept_spec_entry> ();
27451   *entry = elt;
27452   *slot = entry;
27453   return def;
27454 }
27455 
27456 static hashval_t
hash_subsumption_args(tree t1,tree t2)27457 hash_subsumption_args (tree t1, tree t2)
27458 {
27459   gcc_assert (TREE_CODE (t1) == CHECK_CONSTR);
27460   gcc_assert (TREE_CODE (t2) == CHECK_CONSTR);
27461   int val = 0;
27462   val = iterative_hash_object (CHECK_CONSTR_CONCEPT (t1), val);
27463   val = iterative_hash_template_arg (CHECK_CONSTR_ARGS (t1), val);
27464   val = iterative_hash_object (CHECK_CONSTR_CONCEPT (t2), val);
27465   val = iterative_hash_template_arg (CHECK_CONSTR_ARGS (t2), val);
27466   return val;
27467 }
27468 
27469 /* Compare the constraints of two subsumption entries.  The LEFT1 and
27470    LEFT2 arguments comprise the first subsumption pair and the RIGHT1
27471    and RIGHT2 arguments comprise the second. These are all CHECK_CONSTRs. */
27472 
27473 static bool
comp_subsumption_args(tree left1,tree left2,tree right1,tree right2)27474 comp_subsumption_args (tree left1, tree left2, tree right1, tree right2)
27475 {
27476   if (CHECK_CONSTR_CONCEPT (left1) == CHECK_CONSTR_CONCEPT (right1))
27477     if (CHECK_CONSTR_CONCEPT (left2) == CHECK_CONSTR_CONCEPT (right2))
27478       if (comp_template_args (CHECK_CONSTR_ARGS (left1),
27479                              CHECK_CONSTR_ARGS (right1)))
27480         return comp_template_args (CHECK_CONSTR_ARGS (left2),
27481                                   CHECK_CONSTR_ARGS (right2));
27482   return false;
27483 }
27484 
27485 /* Key/value pair for learning and memoizing subsumption results. This
27486    associates a pair of check constraints (including arguments) with
27487    a boolean value indicating the result.  */
27488 
27489 struct GTY((for_user)) subsumption_entry
27490 {
27491   tree t1;
27492   tree t2;
27493   bool result;
27494 };
27495 
27496 /* Hashing function and equality for constraint entries.  */
27497 
27498 struct subsumption_hasher : ggc_ptr_hash<subsumption_entry>
27499 {
hashsubsumption_hasher27500   static hashval_t hash (subsumption_entry *e)
27501   {
27502     return hash_subsumption_args (e->t1, e->t2);
27503   }
27504 
equalsubsumption_hasher27505   static bool equal (subsumption_entry *e1, subsumption_entry *e2)
27506   {
27507     ++comparing_specializations;
27508     bool eq = comp_subsumption_args(e1->t1, e1->t2, e2->t1, e2->t2);
27509     --comparing_specializations;
27510     return eq;
27511   }
27512 };
27513 
27514 static GTY (()) hash_table<subsumption_hasher> *subsumption_table;
27515 
27516 /* Search for a previously cached subsumption result. */
27517 
27518 bool*
lookup_subsumption_result(tree t1,tree t2)27519 lookup_subsumption_result (tree t1, tree t2)
27520 {
27521   subsumption_entry elt = { t1, t2, false };
27522   subsumption_entry* found = subsumption_table->find (&elt);
27523   if (found)
27524     return &found->result;
27525   else
27526     return 0;
27527 }
27528 
27529 /* Save a subsumption result. */
27530 
27531 bool
save_subsumption_result(tree t1,tree t2,bool result)27532 save_subsumption_result (tree t1, tree t2, bool result)
27533 {
27534   subsumption_entry elt = {t1, t2, result};
27535   subsumption_entry** slot = subsumption_table->find_slot (&elt, INSERT);
27536   subsumption_entry* entry = ggc_alloc<subsumption_entry> ();
27537   *entry = elt;
27538   *slot = entry;
27539   return result;
27540 }
27541 
27542 /* Set up the hash table for constraint association. */
27543 
27544 void
init_constraint_processing(void)27545 init_constraint_processing (void)
27546 {
27547   if (!flag_concepts)
27548     return;
27549 
27550   decl_constraints = hash_table<constr_hasher>::create_ggc(37);
27551   constraint_memos = hash_table<constraint_sat_hasher>::create_ggc(37);
27552   concept_memos = hash_table<concept_spec_hasher>::create_ggc(37);
27553   concept_expansions = hash_table<concept_spec_hasher>::create_ggc(37);
27554   subsumption_table = hash_table<subsumption_hasher>::create_ggc(37);
27555 }
27556 
27557 /* __integer_pack(N) in a pack expansion expands to a sequence of numbers from
27558    0..N-1.  */
27559 
27560 void
declare_integer_pack(void)27561 declare_integer_pack (void)
27562 {
27563   tree ipfn = push_library_fn (get_identifier ("__integer_pack"),
27564 			       build_function_type_list (integer_type_node,
27565 							 integer_type_node,
27566 							 NULL_TREE),
27567 			       NULL_TREE, ECF_CONST);
27568   DECL_DECLARED_CONSTEXPR_P (ipfn) = true;
27569   DECL_BUILT_IN_CLASS (ipfn) = BUILT_IN_FRONTEND;
27570 }
27571 
27572 /* Set up the hash tables for template instantiations.  */
27573 
27574 void
init_template_processing(void)27575 init_template_processing (void)
27576 {
27577   decl_specializations = hash_table<spec_hasher>::create_ggc (37);
27578   type_specializations = hash_table<spec_hasher>::create_ggc (37);
27579 
27580   if (cxx_dialect >= cxx11)
27581     declare_integer_pack ();
27582 }
27583 
27584 /* Print stats about the template hash tables for -fstats.  */
27585 
27586 void
print_template_statistics(void)27587 print_template_statistics (void)
27588 {
27589   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
27590 	   "%f collisions\n", (long) decl_specializations->size (),
27591 	   (long) decl_specializations->elements (),
27592 	   decl_specializations->collisions ());
27593   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
27594 	   "%f collisions\n", (long) type_specializations->size (),
27595 	   (long) type_specializations->elements (),
27596 	   type_specializations->collisions ());
27597 }
27598 
27599 #if CHECKING_P
27600 
27601 namespace selftest {
27602 
27603 /* Verify that build_non_dependent_expr () works, for various expressions,
27604    and that location wrappers don't affect the results.  */
27605 
27606 static void
test_build_non_dependent_expr()27607 test_build_non_dependent_expr ()
27608 {
27609   location_t loc = BUILTINS_LOCATION;
27610 
27611   /* Verify constants, without and with location wrappers.  */
27612   tree int_cst = build_int_cst (integer_type_node, 42);
27613   ASSERT_EQ (int_cst, build_non_dependent_expr (int_cst));
27614 
27615   tree wrapped_int_cst = maybe_wrap_with_location (int_cst, loc);
27616   ASSERT_TRUE (location_wrapper_p (wrapped_int_cst));
27617   ASSERT_EQ (wrapped_int_cst, build_non_dependent_expr (wrapped_int_cst));
27618 
27619   tree string_lit = build_string (4, "foo");
27620   TREE_TYPE (string_lit) = char_array_type_node;
27621   string_lit = fix_string_type (string_lit);
27622   ASSERT_EQ (string_lit, build_non_dependent_expr (string_lit));
27623 
27624   tree wrapped_string_lit = maybe_wrap_with_location (string_lit, loc);
27625   ASSERT_TRUE (location_wrapper_p (wrapped_string_lit));
27626   ASSERT_EQ (wrapped_string_lit,
27627 	     build_non_dependent_expr (wrapped_string_lit));
27628 }
27629 
27630 /* Verify that type_dependent_expression_p () works correctly, even
27631    in the presence of location wrapper nodes.  */
27632 
27633 static void
test_type_dependent_expression_p()27634 test_type_dependent_expression_p ()
27635 {
27636   location_t loc = BUILTINS_LOCATION;
27637 
27638   tree name = get_identifier ("foo");
27639 
27640   /* If no templates are involved, nothing is type-dependent.  */
27641   gcc_assert (!processing_template_decl);
27642   ASSERT_FALSE (type_dependent_expression_p (name));
27643 
27644   ++processing_template_decl;
27645 
27646   /* Within a template, an unresolved name is always type-dependent.  */
27647   ASSERT_TRUE (type_dependent_expression_p (name));
27648 
27649   /* Ensure it copes with NULL_TREE and errors.  */
27650   ASSERT_FALSE (type_dependent_expression_p (NULL_TREE));
27651   ASSERT_FALSE (type_dependent_expression_p (error_mark_node));
27652 
27653   /* A USING_DECL in a template should be type-dependent, even if wrapped
27654      with a location wrapper (PR c++/83799).  */
27655   tree using_decl = build_lang_decl (USING_DECL, name, NULL_TREE);
27656   TREE_TYPE (using_decl) = integer_type_node;
27657   ASSERT_TRUE (type_dependent_expression_p (using_decl));
27658   tree wrapped_using_decl = maybe_wrap_with_location (using_decl, loc);
27659   ASSERT_TRUE (location_wrapper_p (wrapped_using_decl));
27660   ASSERT_TRUE (type_dependent_expression_p (wrapped_using_decl));
27661 
27662   --processing_template_decl;
27663 }
27664 
27665 /* Run all of the selftests within this file.  */
27666 
27667 void
cp_pt_c_tests()27668 cp_pt_c_tests ()
27669 {
27670   test_build_non_dependent_expr ();
27671   test_type_dependent_expression_p ();
27672 }
27673 
27674 } // namespace selftest
27675 
27676 #endif /* #if CHECKING_P */
27677 
27678 #include "gt-cp-pt.h"
27679