c++: fix throwing cleanup with label
[official-gcc.git] / gcc / cp / pt.cc
blob6b20c58ce6664c219166093b4a814a18cecfe75f
1 /* Handle parameterized types (templates) for GNU -*- C++ -*-.
2 Copyright (C) 1992-2023 Free Software Foundation, Inc.
3 Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
4 Rewritten by Jason Merrill (jason@cygnus.com).
6 This file is part of GCC.
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.
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.
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/>. */
22 /* Known bugs or deficiencies include:
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".
27 Fixed by: C++20 modules. */
29 #include "config.h"
30 #define INCLUDE_ALGORITHM // for std::equal
31 #include "system.h"
32 #include "coretypes.h"
33 #include "cp-tree.h"
34 #include "timevar.h"
35 #include "stringpool.h"
36 #include "varasm.h"
37 #include "attribs.h"
38 #include "stor-layout.h"
39 #include "intl.h"
40 #include "c-family/c-objc.h"
41 #include "cp-objcp-common.h"
42 #include "toplev.h"
43 #include "tree-iterator.h"
44 #include "type-utils.h"
45 #include "gimplify.h"
46 #include "gcc-rich-location.h"
47 #include "selftest.h"
48 #include "target.h"
50 /* The type of functions taking a tree, and some additional data, and
51 returning an int. */
52 typedef int (*tree_fn_t) (tree, void*);
54 /* The PENDING_TEMPLATES is a list of templates whose instantiations
55 have been deferred, either because their definitions were not yet
56 available, or because we were putting off doing the work. */
57 struct GTY ((chain_next ("%h.next"))) pending_template
59 struct pending_template *next;
60 struct tinst_level *tinst;
63 static GTY(()) struct pending_template *pending_templates;
64 static GTY(()) struct pending_template *last_pending_template;
66 int processing_template_parmlist;
67 static int template_header_count;
69 static vec<int> inline_parm_levels;
71 static GTY(()) struct tinst_level *current_tinst_level;
73 static GTY(()) vec<tree, va_gc> *saved_access_scope;
75 /* Live only within one (recursive) call to tsubst_expr. We use
76 this to pass the statement expression node from the STMT_EXPR
77 to the EXPR_STMT that is its result. */
78 static tree cur_stmt_expr;
80 // -------------------------------------------------------------------------- //
81 // Local Specialization Stack
83 // Implementation of the RAII helper for creating new local
84 // specializations.
85 local_specialization_stack::local_specialization_stack (lss_policy policy)
86 : saved (local_specializations)
88 if (policy == lss_nop)
90 else if (policy == lss_blank || !saved)
91 local_specializations = new hash_map<tree, tree>;
92 else
93 local_specializations = new hash_map<tree, tree>(*saved);
96 local_specialization_stack::~local_specialization_stack ()
98 if (local_specializations != saved)
100 delete local_specializations;
101 local_specializations = saved;
105 /* True if we've recursed into fn_type_unification too many times. */
106 static bool excessive_deduction_depth;
108 struct spec_hasher : ggc_ptr_hash<spec_entry>
110 static hashval_t hash (tree, tree);
111 static hashval_t hash (spec_entry *);
112 static bool equal (spec_entry *, spec_entry *);
115 /* The general template is not in these tables. */
116 typedef hash_table<spec_hasher> spec_hash_table;
117 static GTY (()) spec_hash_table *decl_specializations;
118 static GTY (()) spec_hash_table *type_specializations;
120 /* Contains canonical template parameter types. The vector is indexed by
121 the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
122 TREE_LIST, whose TREE_VALUEs contain the canonical template
123 parameters of various types and levels. */
124 static GTY(()) vec<tree, va_gc> *canonical_template_parms;
126 #define UNIFY_ALLOW_NONE 0
127 #define UNIFY_ALLOW_MORE_CV_QUAL 1
128 #define UNIFY_ALLOW_LESS_CV_QUAL 2
129 #define UNIFY_ALLOW_DERIVED 4
130 #define UNIFY_ALLOW_INTEGER 8
131 #define UNIFY_ALLOW_OUTER_LEVEL 16
132 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
133 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
135 enum template_base_result {
136 tbr_incomplete_type,
137 tbr_ambiguous_baseclass,
138 tbr_success
141 static bool resolve_overloaded_unification (tree, tree, tree, tree,
142 unification_kind_t, int,
143 bool);
144 static int try_one_overload (tree, tree, tree, tree, tree,
145 unification_kind_t, int, bool, bool);
146 static int unify (tree, tree, tree, tree, int, bool);
147 static void add_pending_template (tree);
148 static tree reopen_tinst_level (struct tinst_level *);
149 static tree tsubst_initializer_list (tree, tree);
150 static tree get_partial_spec_bindings (tree, tree, tree);
151 static void tsubst_enum (tree, tree, tree);
152 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
153 static int check_non_deducible_conversion (tree, tree, unification_kind_t, int,
154 struct conversion **, bool);
155 static int maybe_adjust_types_for_deduction (tree, unification_kind_t,
156 tree*, tree*, tree);
157 static int type_unification_real (tree, tree, tree, const tree *,
158 unsigned int, int, unification_kind_t,
159 vec<deferred_access_check, va_gc> **,
160 bool);
161 static void note_template_header (int);
162 static tree convert_nontype_argument_function (tree, tree, tsubst_flags_t);
163 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
164 static tree convert_template_argument (tree, tree, tree,
165 tsubst_flags_t, int, tree);
166 static tree for_each_template_parm (tree, tree_fn_t, void*,
167 hash_set<tree> *, bool, tree_fn_t = NULL);
168 static tree expand_template_argument_pack (tree);
169 static tree build_template_parm_index (int, int, int, tree, tree);
170 static bool inline_needs_template_parms (tree, bool);
171 static void push_inline_template_parms_recursive (tree, int);
172 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
173 static int mark_template_parm (tree, void *);
174 static int template_parm_this_level_p (tree, void *);
175 static tree tsubst_friend_function (tree, tree);
176 static tree tsubst_friend_class (tree, tree);
177 static int can_complete_type_without_circularity (tree);
178 static tree get_bindings (tree, tree, tree, bool);
179 static int template_decl_level (tree);
180 static int check_cv_quals_for_unify (int, tree, tree);
181 static int unify_pack_expansion (tree, tree, tree,
182 tree, unification_kind_t, bool, bool);
183 static tree copy_template_args (tree);
184 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
185 static void tsubst_each_template_parm_constraints (tree, tree, tsubst_flags_t);
186 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
187 static tree tsubst_aggr_type_1 (tree, tree, tsubst_flags_t, tree, int);
188 static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
189 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
190 static bool check_specialization_scope (void);
191 static tree process_partial_specialization (tree);
192 static enum template_base_result get_template_base (tree, tree, tree, tree,
193 bool , tree *);
194 static tree try_class_unification (tree, tree, tree, tree, bool);
195 static bool class_nttp_const_wrapper_p (tree t);
196 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
197 tree, tree);
198 static bool template_template_parm_bindings_ok_p (tree, tree);
199 static void tsubst_default_arguments (tree, tsubst_flags_t);
200 static tree for_each_template_parm_r (tree *, int *, void *);
201 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
202 static void copy_default_args_to_explicit_spec (tree);
203 static bool invalid_nontype_parm_type_p (tree, tsubst_flags_t);
204 static bool dependent_template_arg_p (tree);
205 static bool dependent_type_p_r (tree);
206 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
207 static tree tsubst_decl (tree, tree, tsubst_flags_t);
208 static tree tsubst_scope (tree, tree, tsubst_flags_t, tree);
209 static void perform_instantiation_time_access_checks (tree, tree);
210 static tree listify (tree);
211 static tree listify_autos (tree, tree);
212 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
213 static tree instantiate_alias_template (tree, tree, tsubst_flags_t);
214 static bool complex_alias_template_p (const_tree tmpl);
215 static tree get_underlying_template (tree);
216 static tree tsubst_attributes (tree, tree, tsubst_flags_t, tree);
217 static tree canonicalize_expr_argument (tree, tsubst_flags_t);
218 static tree make_argument_pack (tree);
219 static tree enclosing_instantiation_of (tree tctx);
220 static void instantiate_body (tree pattern, tree args, tree d, bool nested);
221 static tree maybe_dependent_member_ref (tree, tree, tsubst_flags_t, tree);
222 static void mark_template_arguments_used (tree, tree);
224 /* Make the current scope suitable for access checking when we are
225 processing T. T can be FUNCTION_DECL for instantiated function
226 template, VAR_DECL for static member variable, or TYPE_DECL for
227 for a class or alias template (needed by instantiate_decl). */
229 void
230 push_access_scope (tree t)
232 gcc_assert (VAR_OR_FUNCTION_DECL_P (t)
233 || TREE_CODE (t) == TYPE_DECL);
235 if (DECL_FRIEND_CONTEXT (t))
236 push_nested_class (DECL_FRIEND_CONTEXT (t));
237 else if (DECL_IMPLICIT_TYPEDEF_P (t)
238 && CLASS_TYPE_P (TREE_TYPE (t)))
239 push_nested_class (TREE_TYPE (t));
240 else if (DECL_CLASS_SCOPE_P (t))
241 push_nested_class (DECL_CONTEXT (t));
242 else if (deduction_guide_p (t) && DECL_ARTIFICIAL (t))
243 /* An artificial deduction guide should have the same access as
244 the constructor. */
245 push_nested_class (TREE_TYPE (TREE_TYPE (t)));
246 else
247 push_to_top_level ();
249 if (TREE_CODE (t) == FUNCTION_DECL)
251 vec_safe_push (saved_access_scope, current_function_decl);
252 current_function_decl = t;
256 /* Restore the scope set up by push_access_scope. T is the node we
257 are processing. */
259 void
260 pop_access_scope (tree t)
262 if (TREE_CODE (t) == FUNCTION_DECL)
263 current_function_decl = saved_access_scope->pop();
265 if (DECL_FRIEND_CONTEXT (t)
266 || (DECL_IMPLICIT_TYPEDEF_P (t)
267 && CLASS_TYPE_P (TREE_TYPE (t)))
268 || DECL_CLASS_SCOPE_P (t)
269 || (deduction_guide_p (t) && DECL_ARTIFICIAL (t)))
270 pop_nested_class ();
271 else
272 pop_from_top_level ();
275 /* Do any processing required when DECL (a member template
276 declaration) is finished. Returns the TEMPLATE_DECL corresponding
277 to DECL, unless it is a specialization, in which case the DECL
278 itself is returned. */
280 tree
281 finish_member_template_decl (tree decl)
283 if (decl == error_mark_node)
284 return error_mark_node;
286 gcc_assert (DECL_P (decl));
288 if (TREE_CODE (decl) == TYPE_DECL)
290 tree type;
292 type = TREE_TYPE (decl);
293 if (type == error_mark_node)
294 return error_mark_node;
295 if (MAYBE_CLASS_TYPE_P (type)
296 && CLASSTYPE_TEMPLATE_INFO (type)
297 && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
299 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
300 check_member_template (tmpl);
301 return tmpl;
303 return NULL_TREE;
305 else if (TREE_CODE (decl) == FIELD_DECL)
306 error_at (DECL_SOURCE_LOCATION (decl),
307 "data member %qD cannot be a member template", decl);
308 else if (DECL_TEMPLATE_INFO (decl))
310 if (!DECL_TEMPLATE_SPECIALIZATION (decl))
312 check_member_template (DECL_TI_TEMPLATE (decl));
313 return DECL_TI_TEMPLATE (decl);
315 else
316 return decl;
318 else
319 error_at (DECL_SOURCE_LOCATION (decl),
320 "invalid member template declaration %qD", decl);
322 return error_mark_node;
325 /* Create a template info node. */
327 tree
328 build_template_info (tree template_decl, tree template_args)
330 tree result = make_node (TEMPLATE_INFO);
331 TI_TEMPLATE (result) = template_decl;
332 TI_ARGS (result) = template_args;
333 return result;
336 /* Return the template info node corresponding to T, whatever T is. */
338 tree
339 get_template_info (const_tree t)
341 tree tinfo = NULL_TREE;
343 if (!t || t == error_mark_node)
344 return NULL;
346 if (TREE_CODE (t) == NAMESPACE_DECL
347 || TREE_CODE (t) == PARM_DECL)
348 return NULL;
350 if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
351 tinfo = DECL_TEMPLATE_INFO (t);
353 if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
354 t = TREE_TYPE (t);
356 if (OVERLOAD_TYPE_P (t))
357 tinfo = TYPE_TEMPLATE_INFO (t);
358 else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
359 tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
361 return tinfo;
364 /* Returns the template nesting level of the indicated class TYPE.
366 For example, in:
367 template <class T>
368 struct A
370 template <class U>
371 struct B {};
374 A<T>::B<U> has depth two, while A<T> has depth one.
375 Both A<T>::B<int> and A<int>::B<U> have depth one, if
376 they are instantiations, not specializations.
378 This function is guaranteed to return 0 if passed NULL_TREE so
379 that, for example, `template_class_depth (current_class_type)' is
380 always safe. */
383 template_class_depth (tree type)
385 int depth;
387 for (depth = 0; type && TREE_CODE (type) != NAMESPACE_DECL; )
389 tree tinfo = get_template_info (type);
391 if (tinfo
392 && TREE_CODE (TI_TEMPLATE (tinfo)) == TEMPLATE_DECL
393 && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
394 && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
395 ++depth;
397 if (DECL_P (type))
399 if (tree fctx = DECL_FRIEND_CONTEXT (type))
400 type = fctx;
401 else
402 type = CP_DECL_CONTEXT (type);
404 else if (LAMBDA_TYPE_P (type) && LAMBDA_TYPE_EXTRA_SCOPE (type))
405 type = LAMBDA_TYPE_EXTRA_SCOPE (type);
406 else
407 type = CP_TYPE_CONTEXT (type);
410 return depth;
413 /* Return TRUE if NODE instantiates a template that has arguments of
414 its own, be it directly a primary template or indirectly through a
415 partial specializations. */
416 static bool
417 instantiates_primary_template_p (tree node)
419 tree tinfo = get_template_info (node);
420 if (!tinfo)
421 return false;
423 tree tmpl = TI_TEMPLATE (tinfo);
424 if (PRIMARY_TEMPLATE_P (tmpl))
425 return true;
427 if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
428 return false;
430 /* So now we know we have a specialization, but it could be a full
431 or a partial specialization. To tell which, compare the depth of
432 its template arguments with those of its context. */
434 tree ctxt = DECL_CONTEXT (tmpl);
435 tree ctinfo = get_template_info (ctxt);
436 if (!ctinfo)
437 return true;
439 return (TMPL_ARGS_DEPTH (TI_ARGS (tinfo))
440 > TMPL_ARGS_DEPTH (TI_ARGS (ctinfo)));
443 /* Subroutine of maybe_begin_member_template_processing.
444 Returns true if processing DECL needs us to push template parms. */
446 static bool
447 inline_needs_template_parms (tree decl, bool nsdmi)
449 if (!decl || (!nsdmi && ! DECL_TEMPLATE_INFO (decl)))
450 return false;
452 return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
453 > (current_template_depth + DECL_TEMPLATE_SPECIALIZATION (decl)));
456 /* Subroutine of maybe_begin_member_template_processing.
457 Push the template parms in PARMS, starting from LEVELS steps into the
458 chain, and ending at the beginning, since template parms are listed
459 innermost first. */
461 static void
462 push_inline_template_parms_recursive (tree parmlist, int levels)
464 tree parms = TREE_VALUE (parmlist);
465 int i;
467 if (levels > 1)
468 push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
470 ++processing_template_decl;
471 current_template_parms
472 = tree_cons (size_int (current_template_depth + 1),
473 parms, current_template_parms);
474 TEMPLATE_PARMS_CONSTRAINTS (current_template_parms)
475 = TEMPLATE_PARMS_CONSTRAINTS (parmlist);
476 TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
478 begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
479 NULL);
480 for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
482 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
484 if (error_operand_p (parm))
485 continue;
487 gcc_assert (DECL_P (parm));
489 switch (TREE_CODE (parm))
491 case TYPE_DECL:
492 case TEMPLATE_DECL:
493 pushdecl (parm);
494 break;
496 case PARM_DECL:
497 /* Push the CONST_DECL. */
498 pushdecl (TEMPLATE_PARM_DECL (DECL_INITIAL (parm)));
499 break;
501 default:
502 gcc_unreachable ();
507 /* Restore the template parameter context for a member template, a
508 friend template defined in a class definition, or a non-template
509 member of template class. */
511 void
512 maybe_begin_member_template_processing (tree decl)
514 tree parms;
515 int levels = 0;
516 bool nsdmi = TREE_CODE (decl) == FIELD_DECL;
518 if (nsdmi)
520 tree ctx = DECL_CONTEXT (decl);
521 decl = (CLASSTYPE_TEMPLATE_INFO (ctx)
522 /* Disregard full specializations (c++/60999). */
523 && uses_template_parms (ctx)
524 ? CLASSTYPE_TI_TEMPLATE (ctx) : NULL_TREE);
527 if (inline_needs_template_parms (decl, nsdmi))
529 parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
530 levels = TMPL_PARMS_DEPTH (parms) - current_template_depth;
532 if (DECL_TEMPLATE_SPECIALIZATION (decl))
534 --levels;
535 parms = TREE_CHAIN (parms);
538 push_inline_template_parms_recursive (parms, levels);
541 /* Remember how many levels of template parameters we pushed so that
542 we can pop them later. */
543 inline_parm_levels.safe_push (levels);
546 /* Undo the effects of maybe_begin_member_template_processing. */
548 void
549 maybe_end_member_template_processing (void)
551 int i;
552 int last;
554 if (inline_parm_levels.length () == 0)
555 return;
557 last = inline_parm_levels.pop ();
558 for (i = 0; i < last; ++i)
560 --processing_template_decl;
561 current_template_parms = TREE_CHAIN (current_template_parms);
562 poplevel (0, 0, 0);
566 /* Return a new template argument vector which contains all of ARGS,
567 but has as its innermost set of arguments the EXTRA_ARGS. */
569 tree
570 add_to_template_args (tree args, tree extra_args)
572 tree new_args;
573 int extra_depth;
574 int i;
575 int j;
577 if (args == NULL_TREE || extra_args == error_mark_node)
578 return extra_args;
580 extra_depth = TMPL_ARGS_DEPTH (extra_args);
581 new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
583 for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
584 SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
586 for (j = 1; j <= extra_depth; ++j, ++i)
587 SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
589 return new_args;
592 /* Like add_to_template_args, but only the outermost ARGS are added to
593 the EXTRA_ARGS. In particular, all but TMPL_ARGS_DEPTH
594 (EXTRA_ARGS) levels are added. This function is used to combine
595 the template arguments from a partial instantiation with the
596 template arguments used to attain the full instantiation from the
597 partial instantiation.
599 If ARGS is a TEMPLATE_DECL, use its parameters as args. */
601 tree
602 add_outermost_template_args (tree args, tree extra_args)
604 tree new_args;
606 if (!args)
607 return extra_args;
608 if (TREE_CODE (args) == TEMPLATE_DECL)
610 tree ti = get_template_info (DECL_TEMPLATE_RESULT (args));
611 args = TI_ARGS (ti);
614 /* If there are more levels of EXTRA_ARGS than there are ARGS,
615 something very fishy is going on. */
616 gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
618 /* If *all* the new arguments will be the EXTRA_ARGS, just return
619 them. */
620 if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
621 return extra_args;
623 /* For the moment, we make ARGS look like it contains fewer levels. */
624 TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
626 new_args = add_to_template_args (args, extra_args);
628 /* Now, we restore ARGS to its full dimensions. */
629 TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
631 return new_args;
634 /* Return the N levels of innermost template arguments from the ARGS. */
636 tree
637 get_innermost_template_args (tree args, int n)
639 tree new_args;
640 int extra_levels;
641 int i;
643 gcc_assert (n >= 0);
645 /* If N is 1, just return the innermost set of template arguments. */
646 if (n == 1)
647 return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
649 /* If we're not removing anything, just return the arguments we were
650 given. */
651 extra_levels = TMPL_ARGS_DEPTH (args) - n;
652 gcc_assert (extra_levels >= 0);
653 if (extra_levels == 0)
654 return args;
656 /* Make a new set of arguments, not containing the outer arguments. */
657 new_args = make_tree_vec (n);
658 for (i = 1; i <= n; ++i)
659 SET_TMPL_ARGS_LEVEL (new_args, i,
660 TMPL_ARGS_LEVEL (args, i + extra_levels));
662 return new_args;
665 /* The inverse of get_innermost_template_args: Return all but the innermost
666 EXTRA_LEVELS levels of template arguments from the ARGS. */
668 static tree
669 strip_innermost_template_args (tree args, int extra_levels)
671 tree new_args;
672 int n = TMPL_ARGS_DEPTH (args) - extra_levels;
673 int i;
675 gcc_assert (n >= 0);
677 /* If N is 1, just return the outermost set of template arguments. */
678 if (n == 1)
679 return TMPL_ARGS_LEVEL (args, 1);
681 /* If we're not removing anything, just return the arguments we were
682 given. */
683 gcc_assert (extra_levels >= 0);
684 if (extra_levels == 0)
685 return args;
687 /* Make a new set of arguments, not containing the inner arguments. */
688 new_args = make_tree_vec (n);
689 for (i = 1; i <= n; ++i)
690 SET_TMPL_ARGS_LEVEL (new_args, i,
691 TMPL_ARGS_LEVEL (args, i));
693 return new_args;
696 /* We've got a template header coming up; push to a new level for storing
697 the parms. */
699 void
700 begin_template_parm_list (void)
702 /* We use a non-tag-transparent scope here, which causes pushtag to
703 put tags in this scope, rather than in the enclosing class or
704 namespace scope. This is the right thing, since we want
705 TEMPLATE_DECLS, and not TYPE_DECLS for template classes. For a
706 global template class, push_template_decl handles putting the
707 TEMPLATE_DECL into top-level scope. For a nested template class,
708 e.g.:
710 template <class T> struct S1 {
711 template <class T> struct S2 {};
714 pushtag contains special code to insert the TEMPLATE_DECL for S2
715 at the right scope. */
716 begin_scope (sk_template_parms, NULL);
717 ++processing_template_decl;
718 ++processing_template_parmlist;
719 note_template_header (0);
721 /* Add a dummy parameter level while we process the parameter list. */
722 current_template_parms
723 = tree_cons (size_int (current_template_depth + 1),
724 make_tree_vec (0),
725 current_template_parms);
728 /* This routine is called when a specialization is declared. If it is
729 invalid to declare a specialization here, an error is reported and
730 false is returned, otherwise this routine will return true. */
732 static bool
733 check_specialization_scope (void)
735 tree scope = current_scope ();
737 /* [temp.expl.spec]
739 An explicit specialization shall be declared in the namespace of
740 which the template is a member, or, for member templates, in the
741 namespace of which the enclosing class or enclosing class
742 template is a member. An explicit specialization of a member
743 function, member class or static data member of a class template
744 shall be declared in the namespace of which the class template
745 is a member. */
746 if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
748 error ("explicit specialization in non-namespace scope %qD", scope);
749 return false;
752 /* [temp.expl.spec]
754 In an explicit specialization declaration for a member of a class
755 template or a member template that appears in namespace scope,
756 the member template and some of its enclosing class templates may
757 remain unspecialized, except that the declaration shall not
758 explicitly specialize a class member template if its enclosing
759 class templates are not explicitly specialized as well. */
760 if (current_template_parms)
762 error ("enclosing class templates are not explicitly specialized");
763 return false;
766 return true;
769 /* We've just seen template <>. */
771 bool
772 begin_specialization (void)
774 begin_scope (sk_template_spec, NULL);
775 note_template_header (1);
776 return check_specialization_scope ();
779 /* Called at then end of processing a declaration preceded by
780 template<>. */
782 void
783 end_specialization (void)
785 finish_scope ();
786 reset_specialization ();
789 /* Any template <>'s that we have seen thus far are not referring to a
790 function specialization. */
792 void
793 reset_specialization (void)
795 processing_specialization = 0;
796 template_header_count = 0;
799 /* We've just seen a template header. If SPECIALIZATION is nonzero,
800 it was of the form template <>. */
802 static void
803 note_template_header (int specialization)
805 processing_specialization = specialization;
806 template_header_count++;
809 /* We're beginning an explicit instantiation. */
811 void
812 begin_explicit_instantiation (void)
814 gcc_assert (!processing_explicit_instantiation);
815 processing_explicit_instantiation = true;
819 void
820 end_explicit_instantiation (void)
822 gcc_assert (processing_explicit_instantiation);
823 processing_explicit_instantiation = false;
826 /* An explicit specialization or partial specialization of TMPL is being
827 declared. Check that the namespace in which the specialization is
828 occurring is permissible. Returns false iff it is invalid to
829 specialize TMPL in the current namespace. */
831 static bool
832 check_specialization_namespace (tree tmpl)
834 tree tpl_ns = decl_namespace_context (tmpl);
836 /* [tmpl.expl.spec]
838 An explicit specialization shall be declared in a namespace enclosing the
839 specialized template. An explicit specialization whose declarator-id is
840 not qualified shall be declared in the nearest enclosing namespace of the
841 template, or, if the namespace is inline (7.3.1), any namespace from its
842 enclosing namespace set. */
843 if (current_scope() != DECL_CONTEXT (tmpl)
844 && !at_namespace_scope_p ())
846 error ("specialization of %qD must appear at namespace scope", tmpl);
847 return false;
850 if (is_nested_namespace (current_namespace, tpl_ns, cxx_dialect < cxx11))
851 /* Same or enclosing namespace. */
852 return true;
853 else
855 auto_diagnostic_group d;
856 if (permerror (input_location,
857 "specialization of %qD in different namespace", tmpl))
858 inform (DECL_SOURCE_LOCATION (tmpl),
859 " from definition of %q#D", tmpl);
860 return false;
864 /* SPEC is an explicit instantiation. Check that it is valid to
865 perform this explicit instantiation in the current namespace. */
867 static void
868 check_explicit_instantiation_namespace (tree spec)
870 tree ns;
872 /* DR 275: An explicit instantiation shall appear in an enclosing
873 namespace of its template. */
874 ns = decl_namespace_context (spec);
875 if (!is_nested_namespace (current_namespace, ns))
876 permerror (input_location, "explicit instantiation of %qD in namespace %qD "
877 "(which does not enclose namespace %qD)",
878 spec, current_namespace, ns);
881 /* Returns true if TYPE is a new partial specialization that needs to be
882 set up. This may also modify TYPE to point to the correct (new or
883 existing) constrained partial specialization. */
885 static bool
886 maybe_new_partial_specialization (tree& type)
888 /* An implicit instantiation of an incomplete type implies
889 the definition of a new class template.
891 template<typename T>
892 struct S;
894 template<typename T>
895 struct S<T*>;
897 Here, S<T*> is an implicit instantiation of S whose type
898 is incomplete. */
899 if (CLASSTYPE_IMPLICIT_INSTANTIATION (type) && !COMPLETE_TYPE_P (type))
900 return true;
902 /* It can also be the case that TYPE is a completed specialization.
903 Continuing the previous example, suppose we also declare:
905 template<typename T>
906 requires Integral<T>
907 struct S<T*>;
909 Here, S<T*> refers to the specialization S<T*> defined
910 above. However, we need to differentiate definitions because
911 we intend to define a new partial specialization. In this case,
912 we rely on the fact that the constraints are different for
913 this declaration than that above.
915 Note that we also get here for injected class names and
916 late-parsed template definitions. We must ensure that we
917 do not create new type declarations for those cases. */
918 if (flag_concepts && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
920 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
921 tree args = CLASSTYPE_TI_ARGS (type);
923 /* If there are no template parameters, this cannot be a new
924 partial template specialization? */
925 if (!current_template_parms)
926 return false;
928 /* The injected-class-name is not a new partial specialization. */
929 if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
930 return false;
932 /* If the constraints are not the same as those of the primary
933 then, we can probably create a new specialization. */
934 tree type_constr = current_template_constraints ();
936 if (type == TREE_TYPE (tmpl))
938 tree main_constr = get_constraints (tmpl);
939 if (equivalent_constraints (type_constr, main_constr))
940 return false;
943 /* Also, if there's a pre-existing specialization with matching
944 constraints, then this also isn't new. */
945 tree specs = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
946 while (specs)
948 tree spec_tmpl = TREE_VALUE (specs);
949 tree spec_args = TREE_PURPOSE (specs);
950 tree spec_constr = get_constraints (spec_tmpl);
951 if (comp_template_args (args, spec_args)
952 && equivalent_constraints (type_constr, spec_constr))
954 type = TREE_TYPE (spec_tmpl);
955 return false;
957 specs = TREE_CHAIN (specs);
960 /* Create a new type node (and corresponding type decl)
961 for the newly declared specialization. */
962 tree t = make_class_type (TREE_CODE (type));
963 CLASSTYPE_DECLARED_CLASS (t) = CLASSTYPE_DECLARED_CLASS (type);
964 SET_TYPE_TEMPLATE_INFO (t, build_template_info (tmpl, args));
966 /* We only need a separate type node for storing the definition of this
967 partial specialization; uses of S<T*> are unconstrained, so all are
968 equivalent. So keep TYPE_CANONICAL the same. */
969 TYPE_CANONICAL (t) = TYPE_CANONICAL (type);
971 /* Build the corresponding type decl. */
972 tree d = create_implicit_typedef (DECL_NAME (tmpl), t);
973 DECL_CONTEXT (d) = TYPE_CONTEXT (t);
974 DECL_SOURCE_LOCATION (d) = input_location;
975 TREE_PRIVATE (d) = (current_access_specifier == access_private_node);
976 TREE_PROTECTED (d) = (current_access_specifier == access_protected_node);
978 set_instantiating_module (d);
979 DECL_MODULE_EXPORT_P (d) = DECL_MODULE_EXPORT_P (tmpl);
981 type = t;
982 return true;
985 return false;
988 /* The TYPE is being declared. If it is a template type, that means it
989 is a partial specialization. Do appropriate error-checking. */
991 tree
992 maybe_process_partial_specialization (tree type)
994 tree context;
996 if (type == error_mark_node)
997 return error_mark_node;
999 /* A lambda that appears in specialization context is not itself a
1000 specialization. */
1001 if (CLASS_TYPE_P (type) && CLASSTYPE_LAMBDA_EXPR (type))
1002 return type;
1004 /* An injected-class-name is not a specialization. */
1005 if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
1006 return type;
1008 if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
1010 error ("name of class shadows template template parameter %qD",
1011 TYPE_NAME (type));
1012 return error_mark_node;
1015 context = TYPE_CONTEXT (type);
1017 if (TYPE_ALIAS_P (type))
1019 tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (type);
1021 if (tinfo && DECL_ALIAS_TEMPLATE_P (TI_TEMPLATE (tinfo)))
1022 error ("specialization of alias template %qD",
1023 TI_TEMPLATE (tinfo));
1024 else
1025 error ("explicit specialization of non-template %qT", type);
1026 return error_mark_node;
1028 else if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
1030 /* This is for ordinary explicit specialization and partial
1031 specialization of a template class such as:
1033 template <> class C<int>;
1037 template <class T> class C<T*>;
1039 Make sure that `C<int>' and `C<T*>' are implicit instantiations. */
1041 if (maybe_new_partial_specialization (type))
1043 if (!check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type))
1044 && !at_namespace_scope_p ())
1045 return error_mark_node;
1046 SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1047 DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1048 if (processing_template_decl)
1050 tree decl = push_template_decl (TYPE_MAIN_DECL (type));
1051 if (decl == error_mark_node)
1052 return error_mark_node;
1053 return TREE_TYPE (decl);
1056 else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
1057 error ("specialization of %qT after instantiation", type);
1058 else if (errorcount && !processing_specialization
1059 && CLASSTYPE_TEMPLATE_SPECIALIZATION (type)
1060 && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
1061 /* Trying to define a specialization either without a template<> header
1062 or in an inappropriate place. We've already given an error, so just
1063 bail now so we don't actually define the specialization. */
1064 return error_mark_node;
1066 else if (CLASS_TYPE_P (type)
1067 && !CLASSTYPE_USE_TEMPLATE (type)
1068 && CLASSTYPE_TEMPLATE_INFO (type)
1069 && context && CLASS_TYPE_P (context)
1070 && CLASSTYPE_TEMPLATE_INFO (context))
1072 /* This is for an explicit specialization of member class
1073 template according to [temp.expl.spec/18]:
1075 template <> template <class U> class C<int>::D;
1077 The context `C<int>' must be an implicit instantiation.
1078 Otherwise this is just a member class template declared
1079 earlier like:
1081 template <> class C<int> { template <class U> class D; };
1082 template <> template <class U> class C<int>::D;
1084 In the first case, `C<int>::D' is a specialization of `C<T>::D'
1085 while in the second case, `C<int>::D' is a primary template
1086 and `C<T>::D' may not exist. */
1088 if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
1089 && !COMPLETE_TYPE_P (type))
1091 tree t;
1092 tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
1094 if (current_namespace
1095 != decl_namespace_context (tmpl))
1097 if (permerror (input_location,
1098 "specialization of %qD in different namespace",
1099 type))
1100 inform (DECL_SOURCE_LOCATION (tmpl),
1101 "from definition of %q#D", tmpl);
1104 /* Check for invalid specialization after instantiation:
1106 template <> template <> class C<int>::D<int>;
1107 template <> template <class U> class C<int>::D; */
1109 for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
1110 t; t = TREE_CHAIN (t))
1112 tree inst = TREE_VALUE (t);
1113 if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst)
1114 || !COMPLETE_OR_OPEN_TYPE_P (inst))
1116 /* We already have a full specialization of this partial
1117 instantiation, or a full specialization has been
1118 looked up but not instantiated. Reassign it to the
1119 new member specialization template. */
1120 spec_entry elt;
1121 spec_entry *entry;
1123 elt.tmpl = most_general_template (tmpl);
1124 elt.args = CLASSTYPE_TI_ARGS (inst);
1125 elt.spec = inst;
1127 type_specializations->remove_elt (&elt);
1129 elt.tmpl = tmpl;
1130 CLASSTYPE_TI_ARGS (inst)
1131 = elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
1133 spec_entry **slot
1134 = type_specializations->find_slot (&elt, INSERT);
1135 entry = ggc_alloc<spec_entry> ();
1136 *entry = elt;
1137 *slot = entry;
1139 else
1140 /* But if we've had an implicit instantiation, that's a
1141 problem ([temp.expl.spec]/6). */
1142 error ("specialization %qT after instantiation %qT",
1143 type, inst);
1146 /* Mark TYPE as a specialization. And as a result, we only
1147 have one level of template argument for the innermost
1148 class template. */
1149 SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1150 DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1151 CLASSTYPE_TI_ARGS (type)
1152 = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
1155 else if (processing_specialization)
1157 /* Someday C++0x may allow for enum template specialization. */
1158 if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
1159 && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
1160 pedwarn (input_location, OPT_Wpedantic, "template specialization "
1161 "of %qD not allowed by ISO C++", type);
1162 else
1164 error ("explicit specialization of non-template %qT", type);
1165 return error_mark_node;
1169 return type;
1172 /* Make sure ARGS doesn't use any inappropriate typedefs; we should have
1173 gone through coerce_template_parms by now. */
1175 static void
1176 verify_unstripped_args_1 (tree inner)
1178 for (int i = 0; i < TREE_VEC_LENGTH (inner); ++i)
1180 tree arg = TREE_VEC_ELT (inner, i);
1181 if (TREE_CODE (arg) == TEMPLATE_DECL)
1182 /* OK */;
1183 else if (TYPE_P (arg))
1184 gcc_assert (strip_typedefs (arg, NULL) == arg);
1185 else if (ARGUMENT_PACK_P (arg))
1186 verify_unstripped_args_1 (ARGUMENT_PACK_ARGS (arg));
1187 else if (strip_typedefs (TREE_TYPE (arg), NULL) != TREE_TYPE (arg))
1188 /* Allow typedefs on the type of a non-type argument, since a
1189 parameter can have them. */;
1190 else
1191 gcc_assert (strip_typedefs_expr (arg, NULL) == arg);
1195 static void
1196 verify_unstripped_args (tree args)
1198 ++processing_template_decl;
1199 if (!any_dependent_template_arguments_p (args))
1200 verify_unstripped_args_1 (INNERMOST_TEMPLATE_ARGS (args));
1201 --processing_template_decl;
1204 /* Retrieve the specialization (in the sense of [temp.spec] - a
1205 specialization is either an instantiation or an explicit
1206 specialization) of TMPL for the given template ARGS. If there is
1207 no such specialization, return NULL_TREE. The ARGS are a vector of
1208 arguments, or a vector of vectors of arguments, in the case of
1209 templates with more than one level of parameters.
1211 If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
1212 then we search for a partial specialization matching ARGS. This
1213 parameter is ignored if TMPL is not a class template.
1215 We can also look up a FIELD_DECL, if it is a lambda capture pack; the
1216 result is a NONTYPE_ARGUMENT_PACK. */
1218 static tree
1219 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1221 if (tmpl == NULL_TREE)
1222 return NULL_TREE;
1224 if (args == error_mark_node)
1225 return NULL_TREE;
1227 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL
1228 || TREE_CODE (tmpl) == FIELD_DECL);
1230 /* There should be as many levels of arguments as there are
1231 levels of parameters. */
1232 gcc_assert (TMPL_ARGS_DEPTH (args)
1233 == (TREE_CODE (tmpl) == TEMPLATE_DECL
1234 ? TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl))
1235 : template_class_depth (DECL_CONTEXT (tmpl))));
1237 if (flag_checking)
1238 verify_unstripped_args (args);
1240 /* Lambda functions in templates aren't instantiated normally, but through
1241 tsubst_lambda_expr. */
1242 if (lambda_fn_in_template_p (tmpl))
1243 return NULL_TREE;
1245 spec_entry elt;
1246 elt.tmpl = tmpl;
1247 elt.args = args;
1248 elt.spec = NULL_TREE;
1250 spec_hash_table *specializations;
1251 if (DECL_CLASS_TEMPLATE_P (tmpl))
1252 specializations = type_specializations;
1253 else
1254 specializations = decl_specializations;
1256 if (hash == 0)
1257 hash = spec_hasher::hash (&elt);
1258 if (spec_entry *found = specializations->find_with_hash (&elt, hash))
1259 return found->spec;
1261 return NULL_TREE;
1264 /* Like retrieve_specialization, but for local declarations. */
1266 tree
1267 retrieve_local_specialization (tree tmpl)
1269 if (local_specializations == NULL)
1270 return NULL_TREE;
1272 tree *slot = local_specializations->get (tmpl);
1273 return slot ? *slot : NULL_TREE;
1276 /* Returns nonzero iff DECL is a specialization of TMPL. */
1279 is_specialization_of (tree decl, tree tmpl)
1281 tree t;
1283 if (TREE_CODE (decl) == FUNCTION_DECL)
1285 for (t = decl;
1286 t != NULL_TREE;
1287 t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1288 if (t == tmpl)
1289 return 1;
1291 else
1293 gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1295 for (t = TREE_TYPE (decl);
1296 t != NULL_TREE;
1297 t = CLASSTYPE_USE_TEMPLATE (t)
1298 ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1299 if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1300 return 1;
1303 return 0;
1306 /* Returns nonzero iff DECL is a specialization of friend declaration
1307 FRIEND_DECL according to [temp.friend]. */
1309 bool
1310 is_specialization_of_friend (tree decl, tree friend_decl)
1312 bool need_template = true;
1313 int template_depth;
1315 gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1316 || TREE_CODE (decl) == TYPE_DECL);
1318 /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1319 of a template class, we want to check if DECL is a specialization
1320 if this. */
1321 if (TREE_CODE (friend_decl) == FUNCTION_DECL
1322 && DECL_CLASS_SCOPE_P (friend_decl)
1323 && DECL_TEMPLATE_INFO (friend_decl)
1324 && !DECL_USE_TEMPLATE (friend_decl))
1326 /* We want a TEMPLATE_DECL for `is_specialization_of'. */
1327 friend_decl = DECL_TI_TEMPLATE (friend_decl);
1328 need_template = false;
1330 else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1331 && !PRIMARY_TEMPLATE_P (friend_decl))
1332 need_template = false;
1334 /* There is nothing to do if this is not a template friend. */
1335 if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1336 return false;
1338 if (is_specialization_of (decl, friend_decl))
1339 return true;
1341 /* [temp.friend/6]
1342 A member of a class template may be declared to be a friend of a
1343 non-template class. In this case, the corresponding member of
1344 every specialization of the class template is a friend of the
1345 class granting friendship.
1347 For example, given a template friend declaration
1349 template <class T> friend void A<T>::f();
1351 the member function below is considered a friend
1353 template <> struct A<int> {
1354 void f();
1357 For this type of template friend, TEMPLATE_DEPTH below will be
1358 nonzero. To determine if DECL is a friend of FRIEND, we first
1359 check if the enclosing class is a specialization of another. */
1361 template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1362 if (template_depth
1363 && DECL_CLASS_SCOPE_P (decl)
1364 && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1365 CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1367 /* Next, we check the members themselves. In order to handle
1368 a few tricky cases, such as when FRIEND_DECL's are
1370 template <class T> friend void A<T>::g(T t);
1371 template <class T> template <T t> friend void A<T>::h();
1373 and DECL's are
1375 void A<int>::g(int);
1376 template <int> void A<int>::h();
1378 we need to figure out ARGS, the template arguments from
1379 the context of DECL. This is required for template substitution
1380 of `T' in the function parameter of `g' and template parameter
1381 of `h' in the above examples. Here ARGS corresponds to `int'. */
1383 tree context = DECL_CONTEXT (decl);
1384 tree args = NULL_TREE;
1385 int current_depth = 0;
1387 while (current_depth < template_depth)
1389 if (CLASSTYPE_TEMPLATE_INFO (context))
1391 if (current_depth == 0)
1392 args = TYPE_TI_ARGS (context);
1393 else
1394 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1395 current_depth++;
1397 context = TYPE_CONTEXT (context);
1400 if (TREE_CODE (decl) == FUNCTION_DECL)
1402 bool is_template;
1403 tree friend_type;
1404 tree decl_type;
1405 tree friend_args_type;
1406 tree decl_args_type;
1408 /* Make sure that both DECL and FRIEND_DECL are templates or
1409 non-templates. */
1410 is_template = DECL_TEMPLATE_INFO (decl)
1411 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1412 if (need_template ^ is_template)
1413 return false;
1414 else if (is_template)
1416 /* If both are templates, check template parameter list. */
1417 tree friend_parms
1418 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1419 args, tf_none);
1420 if (!comp_template_parms
1421 (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1422 friend_parms))
1423 return false;
1425 decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1427 else
1428 decl_type = TREE_TYPE (decl);
1430 friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1431 tf_none, NULL_TREE);
1432 if (friend_type == error_mark_node)
1433 return false;
1435 /* Check if return types match. */
1436 if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1437 return false;
1439 /* Check if function parameter types match, ignoring the
1440 `this' parameter. */
1441 friend_args_type = TYPE_ARG_TYPES (friend_type);
1442 decl_args_type = TYPE_ARG_TYPES (decl_type);
1443 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1444 friend_args_type = TREE_CHAIN (friend_args_type);
1445 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1446 decl_args_type = TREE_CHAIN (decl_args_type);
1448 return compparms (decl_args_type, friend_args_type);
1450 else
1452 /* DECL is a TYPE_DECL */
1453 bool is_template;
1454 tree decl_type = TREE_TYPE (decl);
1456 /* Make sure that both DECL and FRIEND_DECL are templates or
1457 non-templates. */
1458 is_template
1459 = CLASSTYPE_TEMPLATE_INFO (decl_type)
1460 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1462 if (need_template ^ is_template)
1463 return false;
1464 else if (is_template)
1466 tree friend_parms;
1467 /* If both are templates, check the name of the two
1468 TEMPLATE_DECL's first because is_friend didn't. */
1469 if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1470 != DECL_NAME (friend_decl))
1471 return false;
1473 /* Now check template parameter list. */
1474 friend_parms
1475 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1476 args, tf_none);
1477 return comp_template_parms
1478 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1479 friend_parms);
1481 else
1482 return (DECL_NAME (decl)
1483 == DECL_NAME (friend_decl));
1486 return false;
1489 /* Register the specialization SPEC as a specialization of TMPL with
1490 the indicated ARGS. IS_FRIEND indicates whether the specialization
1491 is actually just a friend declaration. ATTRLIST is the list of
1492 attributes that the specialization is declared with or NULL when
1493 it isn't. Returns SPEC, or an equivalent prior declaration, if
1494 available.
1496 We also store instantiations of field packs in the hash table, even
1497 though they are not themselves templates, to make lookup easier. */
1499 static tree
1500 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1501 hashval_t hash)
1503 tree fn;
1505 gcc_assert ((TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec))
1506 || (TREE_CODE (tmpl) == FIELD_DECL
1507 && TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK));
1509 if (TREE_CODE (spec) == FUNCTION_DECL
1510 && uses_template_parms (DECL_TI_ARGS (spec)))
1511 /* This is the FUNCTION_DECL for a partial instantiation. Don't
1512 register it; we want the corresponding TEMPLATE_DECL instead.
1513 We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1514 the more obvious `uses_template_parms (spec)' to avoid problems
1515 with default function arguments. In particular, given
1516 something like this:
1518 template <class T> void f(T t1, T t = T())
1520 the default argument expression is not substituted for in an
1521 instantiation unless and until it is actually needed. */
1522 return spec;
1524 spec_entry elt;
1525 elt.tmpl = tmpl;
1526 elt.args = args;
1527 elt.spec = spec;
1529 if (hash == 0)
1530 hash = spec_hasher::hash (&elt);
1532 spec_entry **slot = decl_specializations->find_slot_with_hash (&elt, hash, INSERT);
1533 if (*slot)
1534 fn = (*slot)->spec;
1535 else
1536 fn = NULL_TREE;
1538 /* We can sometimes try to re-register a specialization that we've
1539 already got. In particular, regenerate_decl_from_template calls
1540 duplicate_decls which will update the specialization list. But,
1541 we'll still get called again here anyhow. It's more convenient
1542 to simply allow this than to try to prevent it. */
1543 if (fn == spec)
1544 return spec;
1545 else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1547 if (DECL_TEMPLATE_INSTANTIATION (fn))
1549 if (DECL_ODR_USED (fn)
1550 || DECL_EXPLICIT_INSTANTIATION (fn))
1552 error ("specialization of %qD after instantiation",
1553 fn);
1554 return error_mark_node;
1556 else
1558 tree clone;
1559 /* This situation should occur only if the first
1560 specialization is an implicit instantiation, the
1561 second is an explicit specialization, and the
1562 implicit instantiation has not yet been used. That
1563 situation can occur if we have implicitly
1564 instantiated a member function and then specialized
1565 it later.
1567 We can also wind up here if a friend declaration that
1568 looked like an instantiation turns out to be a
1569 specialization:
1571 template <class T> void foo(T);
1572 class S { friend void foo<>(int) };
1573 template <> void foo(int);
1575 We transform the existing DECL in place so that any
1576 pointers to it become pointers to the updated
1577 declaration.
1579 If there was a definition for the template, but not
1580 for the specialization, we want this to look as if
1581 there were no definition, and vice versa. */
1582 DECL_INITIAL (fn) = NULL_TREE;
1583 duplicate_decls (spec, fn, /*hiding=*/is_friend);
1585 /* The call to duplicate_decls will have applied
1586 [temp.expl.spec]:
1588 An explicit specialization of a function template
1589 is inline only if it is explicitly declared to be,
1590 and independently of whether its function template
1593 to the primary function; now copy the inline bits to
1594 the various clones. */
1595 FOR_EACH_CLONE (clone, fn)
1597 DECL_DECLARED_INLINE_P (clone)
1598 = DECL_DECLARED_INLINE_P (fn);
1599 DECL_SOURCE_LOCATION (clone)
1600 = DECL_SOURCE_LOCATION (fn);
1601 DECL_DELETED_FN (clone)
1602 = DECL_DELETED_FN (fn);
1604 check_specialization_namespace (tmpl);
1606 return fn;
1609 else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1611 tree dd = duplicate_decls (spec, fn, /*hiding=*/is_friend);
1612 if (dd == error_mark_node)
1613 /* We've already complained in duplicate_decls. */
1614 return error_mark_node;
1616 if (dd == NULL_TREE && DECL_INITIAL (spec))
1617 /* Dup decl failed, but this is a new definition. Set the
1618 line number so any errors match this new
1619 definition. */
1620 DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1622 return fn;
1625 else if (fn)
1626 return duplicate_decls (spec, fn, /*hiding=*/is_friend);
1628 /* A specialization must be declared in the same namespace as the
1629 template it is specializing. */
1630 if (DECL_P (spec) && DECL_TEMPLATE_SPECIALIZATION (spec)
1631 && !check_specialization_namespace (tmpl))
1632 DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1634 spec_entry *entry = ggc_alloc<spec_entry> ();
1635 gcc_assert (tmpl && args && spec);
1636 *entry = elt;
1637 *slot = entry;
1638 if ((TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1639 && PRIMARY_TEMPLATE_P (tmpl)
1640 && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1641 || variable_template_p (tmpl))
1642 /* If TMPL is a forward declaration of a template function, keep a list
1643 of all specializations in case we need to reassign them to a friend
1644 template later in tsubst_friend_function.
1646 Also keep a list of all variable template instantiations so that
1647 process_partial_specialization can check whether a later partial
1648 specialization would have used it. */
1649 DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1650 = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1652 return spec;
1655 /* Restricts tree and type comparisons. */
1656 int comparing_specializations;
1657 int comparing_dependent_aliases;
1659 /* Returns true iff two spec_entry nodes are equivalent. */
1661 bool
1662 spec_hasher::equal (spec_entry *e1, spec_entry *e2)
1664 int equal;
1666 ++comparing_specializations;
1667 ++comparing_dependent_aliases;
1668 ++processing_template_decl;
1669 equal = (e1->tmpl == e2->tmpl
1670 && comp_template_args (e1->args, e2->args));
1671 if (equal && flag_concepts
1672 /* tmpl could be a FIELD_DECL for a capture pack. */
1673 && TREE_CODE (e1->tmpl) == TEMPLATE_DECL
1674 && VAR_P (DECL_TEMPLATE_RESULT (e1->tmpl))
1675 && uses_template_parms (e1->args))
1677 /* Partial specializations of a variable template can be distinguished by
1678 constraints. */
1679 tree c1 = e1->spec ? get_constraints (e1->spec) : NULL_TREE;
1680 tree c2 = e2->spec ? get_constraints (e2->spec) : NULL_TREE;
1681 equal = equivalent_constraints (c1, c2);
1683 --processing_template_decl;
1684 --comparing_dependent_aliases;
1685 --comparing_specializations;
1687 return equal;
1690 /* Returns a hash for a template TMPL and template arguments ARGS. */
1692 static hashval_t
1693 hash_tmpl_and_args (tree tmpl, tree args)
1695 hashval_t val = iterative_hash_object (DECL_UID (tmpl), 0);
1696 return iterative_hash_template_arg (args, val);
1699 hashval_t
1700 spec_hasher::hash (tree tmpl, tree args)
1702 ++comparing_specializations;
1703 hashval_t val = hash_tmpl_and_args (tmpl, args);
1704 --comparing_specializations;
1705 return val;
1708 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1709 ignoring SPEC. */
1711 hashval_t
1712 spec_hasher::hash (spec_entry *e)
1714 return spec_hasher::hash (e->tmpl, e->args);
1717 /* Recursively calculate a hash value for a template argument ARG, for use
1718 in the hash tables of template specializations. We must be
1719 careful to (at least) skip the same entities template_args_equal
1720 does. */
1722 hashval_t
1723 iterative_hash_template_arg (tree arg, hashval_t val)
1725 if (arg == NULL_TREE)
1726 return iterative_hash_object (arg, val);
1728 if (!TYPE_P (arg))
1729 /* Strip nop-like things, but not the same as STRIP_NOPS. */
1730 while (CONVERT_EXPR_P (arg)
1731 || TREE_CODE (arg) == NON_LVALUE_EXPR
1732 || class_nttp_const_wrapper_p (arg))
1733 arg = TREE_OPERAND (arg, 0);
1735 enum tree_code code = TREE_CODE (arg);
1737 val = iterative_hash_object (code, val);
1739 switch (code)
1741 case ARGUMENT_PACK_SELECT:
1742 /* Getting here with an ARGUMENT_PACK_SELECT means we're probably
1743 preserving it in a hash table, which is bad because it will change
1744 meaning when gen_elem_of_pack_expansion_instantiation changes the
1745 ARGUMENT_PACK_SELECT_INDEX. */
1746 gcc_unreachable ();
1748 case ERROR_MARK:
1749 return val;
1751 case IDENTIFIER_NODE:
1752 return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1754 case TREE_VEC:
1755 for (tree elt : tree_vec_range (arg))
1756 val = iterative_hash_template_arg (elt, val);
1757 return val;
1759 case TYPE_PACK_EXPANSION:
1760 case EXPR_PACK_EXPANSION:
1761 val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1762 return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1764 case TYPE_ARGUMENT_PACK:
1765 case NONTYPE_ARGUMENT_PACK:
1766 return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1768 case TREE_LIST:
1769 for (; arg; arg = TREE_CHAIN (arg))
1770 val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1771 return val;
1773 case OVERLOAD:
1774 for (lkp_iterator iter (arg); iter; ++iter)
1775 val = iterative_hash_template_arg (*iter, val);
1776 return val;
1778 case CONSTRUCTOR:
1780 iterative_hash_template_arg (TREE_TYPE (arg), val);
1781 for (auto &e: CONSTRUCTOR_ELTS (arg))
1783 val = iterative_hash_template_arg (e.index, val);
1784 val = iterative_hash_template_arg (e.value, val);
1786 return val;
1789 case PARM_DECL:
1790 if (!DECL_ARTIFICIAL (arg))
1792 val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1793 val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1795 return iterative_hash_template_arg (TREE_TYPE (arg), val);
1797 case TARGET_EXPR:
1798 return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1800 case PTRMEM_CST:
1801 val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1802 return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1804 case TEMPLATE_PARM_INDEX:
1805 val = iterative_hash_template_arg
1806 (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1807 val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1808 return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1810 case TRAIT_EXPR:
1811 val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1812 val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1813 return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1815 case BASELINK:
1816 val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1817 val);
1818 return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1819 val);
1821 case MODOP_EXPR:
1822 val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1823 code = TREE_CODE (TREE_OPERAND (arg, 1));
1824 val = iterative_hash_object (code, val);
1825 return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1827 case LAMBDA_EXPR:
1828 /* [temp.over.link] Two lambda-expressions are never considered
1829 equivalent.
1831 So just hash the closure type. */
1832 return iterative_hash_template_arg (TREE_TYPE (arg), val);
1834 case CAST_EXPR:
1835 case IMPLICIT_CONV_EXPR:
1836 case STATIC_CAST_EXPR:
1837 case REINTERPRET_CAST_EXPR:
1838 case CONST_CAST_EXPR:
1839 case DYNAMIC_CAST_EXPR:
1840 case NEW_EXPR:
1841 val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1842 /* Now hash operands as usual. */
1843 break;
1845 case CALL_EXPR:
1847 tree fn = CALL_EXPR_FN (arg);
1848 if (tree name = call_expr_dependent_name (arg))
1850 if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
1851 val = iterative_hash_template_arg (TREE_OPERAND (fn, 1), val);
1852 fn = name;
1854 val = iterative_hash_template_arg (fn, val);
1855 call_expr_arg_iterator ai;
1856 for (tree x = first_call_expr_arg (arg, &ai); x;
1857 x = next_call_expr_arg (&ai))
1858 val = iterative_hash_template_arg (x, val);
1859 return val;
1862 default:
1863 break;
1866 char tclass = TREE_CODE_CLASS (code);
1867 switch (tclass)
1869 case tcc_type:
1870 if (tree ats = alias_template_specialization_p (arg, nt_transparent))
1872 // We want an alias specialization that survived strip_typedefs
1873 // to hash differently from its TYPE_CANONICAL, to avoid hash
1874 // collisions that compare as different in template_args_equal.
1875 // These could be dependent specializations that strip_typedefs
1876 // left alone, or untouched specializations because
1877 // coerce_template_parms returns the unconverted template
1878 // arguments if it sees incomplete argument packs.
1879 tree ti = TYPE_ALIAS_TEMPLATE_INFO (ats);
1880 return hash_tmpl_and_args (TI_TEMPLATE (ti), TI_ARGS (ti));
1883 switch (code)
1885 case DECLTYPE_TYPE:
1886 val = iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1887 break;
1889 case TYPENAME_TYPE:
1890 if (comparing_specializations)
1892 /* Hash the components that are relevant to TYPENAME_TYPE
1893 equivalence as determined by structural_comptypes. We
1894 can only coherently do this when comparing_specializations
1895 is set, because otherwise structural_comptypes tries
1896 resolving TYPENAME_TYPE via the current instantiation. */
1897 tree context = TYPE_MAIN_VARIANT (TYPE_CONTEXT (arg));
1898 tree fullname = TYPENAME_TYPE_FULLNAME (arg);
1899 val = iterative_hash_template_arg (context, val);
1900 val = iterative_hash_template_arg (fullname, val);
1902 break;
1904 default:
1905 if (tree canonical = TYPE_CANONICAL (arg))
1906 val = iterative_hash_object (TYPE_HASH (canonical), val);
1907 break;
1910 return val;
1912 case tcc_declaration:
1913 case tcc_constant:
1914 return iterative_hash_expr (arg, val);
1916 default:
1917 gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1918 for (int i = 0, n = cp_tree_operand_length (arg); i < n; ++i)
1919 val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1920 return val;
1924 /* Unregister the specialization SPEC as a specialization of TMPL.
1925 Replace it with NEW_SPEC, if NEW_SPEC is non-NULL. Returns true
1926 if the SPEC was listed as a specialization of TMPL.
1928 Note that SPEC has been ggc_freed, so we can't look inside it. */
1930 bool
1931 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1933 spec_entry *entry;
1934 spec_entry elt;
1936 elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1937 elt.args = TI_ARGS (tinfo);
1938 elt.spec = NULL_TREE;
1940 entry = decl_specializations->find (&elt);
1941 if (entry != NULL)
1943 gcc_assert (entry->spec == spec || entry->spec == new_spec);
1944 gcc_assert (new_spec != NULL_TREE);
1945 entry->spec = new_spec;
1946 return 1;
1949 return 0;
1952 /* Like register_specialization, but for local declarations. We are
1953 registering SPEC, an instantiation of TMPL. */
1955 void
1956 register_local_specialization (tree spec, tree tmpl)
1958 gcc_assert (tmpl != spec);
1959 local_specializations->put (tmpl, spec);
1962 /* Registers T as a specialization of itself. This is used to preserve
1963 the references to already-parsed parameters when instantiating
1964 postconditions. */
1966 void
1967 register_local_identity (tree t)
1969 local_specializations->put (t, t);
1972 /* TYPE is a class type. Returns true if TYPE is an explicitly
1973 specialized class. */
1975 bool
1976 explicit_class_specialization_p (tree type)
1978 if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1979 return false;
1980 return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1983 /* Print the list of functions at FNS, going through all the overloads
1984 for each element of the list. Alternatively, FNS cannot be a
1985 TREE_LIST, in which case it will be printed together with all the
1986 overloads.
1988 MORE and *STR should respectively be FALSE and NULL when the function
1989 is called from the outside. They are used internally on recursive
1990 calls. print_candidates manages the two parameters and leaves NULL
1991 in *STR when it ends. */
1993 static void
1994 print_candidates_1 (tree fns, char **str, bool more = false)
1996 if (TREE_CODE (fns) == TREE_LIST)
1997 for (; fns; fns = TREE_CHAIN (fns))
1998 print_candidates_1 (TREE_VALUE (fns), str, more || TREE_CHAIN (fns));
1999 else
2000 for (lkp_iterator iter (fns); iter;)
2002 tree cand = *iter;
2003 ++iter;
2005 const char *pfx = *str;
2006 if (!pfx)
2008 if (more || iter)
2009 pfx = _("candidates are:");
2010 else
2011 pfx = _("candidate is:");
2012 *str = get_spaces (pfx);
2014 inform (DECL_SOURCE_LOCATION (cand), "%s %#qD", pfx, cand);
2018 /* Print the list of candidate FNS in an error message. FNS can also
2019 be a TREE_LIST of non-functions in the case of an ambiguous lookup. */
2021 void
2022 print_candidates (tree fns)
2024 char *str = NULL;
2025 print_candidates_1 (fns, &str);
2026 free (str);
2029 /* Get a (possibly) constrained template declaration for the
2030 purpose of ordering candidates. */
2031 static tree
2032 get_template_for_ordering (tree list)
2034 gcc_assert (TREE_CODE (list) == TREE_LIST);
2035 tree f = TREE_VALUE (list);
2036 if (tree ti = DECL_TEMPLATE_INFO (f))
2037 return TI_TEMPLATE (ti);
2038 return f;
2041 /* Among candidates having the same signature, return the
2042 most constrained or NULL_TREE if there is no best candidate.
2043 If the signatures of candidates vary (e.g., template
2044 specialization vs. member function), then there can be no
2045 most constrained.
2047 Note that we don't compare constraints on the functions
2048 themselves, but rather those of their templates. */
2049 static tree
2050 most_constrained_function (tree candidates)
2052 // Try to find the best candidate in a first pass.
2053 tree champ = candidates;
2054 for (tree c = TREE_CHAIN (champ); c; c = TREE_CHAIN (c))
2056 int winner = more_constrained (get_template_for_ordering (champ),
2057 get_template_for_ordering (c));
2058 if (winner == -1)
2059 champ = c; // The candidate is more constrained
2060 else if (winner == 0)
2061 return NULL_TREE; // Neither is more constrained
2064 // Verify that the champ is better than previous candidates.
2065 for (tree c = candidates; c != champ; c = TREE_CHAIN (c)) {
2066 if (!more_constrained (get_template_for_ordering (champ),
2067 get_template_for_ordering (c)))
2068 return NULL_TREE;
2071 return champ;
2075 /* Returns the template (one of the functions given by TEMPLATE_ID)
2076 which can be specialized to match the indicated DECL with the
2077 explicit template args given in TEMPLATE_ID. The DECL may be
2078 NULL_TREE if none is available. In that case, the functions in
2079 TEMPLATE_ID are non-members.
2081 If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
2082 specialization of a member template.
2084 The TEMPLATE_COUNT is the number of references to qualifying
2085 template classes that appeared in the name of the function. See
2086 check_explicit_specialization for a more accurate description.
2088 TSK indicates what kind of template declaration (if any) is being
2089 declared. TSK_TEMPLATE indicates that the declaration given by
2090 DECL, though a FUNCTION_DECL, has template parameters, and is
2091 therefore a template function.
2093 The template args (those explicitly specified and those deduced)
2094 are output in a newly created vector *TARGS_OUT.
2096 If it is impossible to determine the result, an error message is
2097 issued. The error_mark_node is returned to indicate failure. */
2099 static tree
2100 determine_specialization (tree template_id,
2101 tree decl,
2102 tree* targs_out,
2103 int need_member_template,
2104 int template_count,
2105 tmpl_spec_kind tsk)
2107 tree fns;
2108 tree targs;
2109 tree explicit_targs;
2110 tree candidates = NULL_TREE;
2112 /* A TREE_LIST of templates of which DECL may be a specialization.
2113 The TREE_VALUE of each node is a TEMPLATE_DECL. The
2114 corresponding TREE_PURPOSE is the set of template arguments that,
2115 when used to instantiate the template, would produce a function
2116 with the signature of DECL. */
2117 tree templates = NULL_TREE;
2118 int header_count;
2119 cp_binding_level *b;
2121 *targs_out = NULL_TREE;
2123 if (template_id == error_mark_node || decl == error_mark_node)
2124 return error_mark_node;
2126 /* We shouldn't be specializing a member template of an
2127 unspecialized class template; we already gave an error in
2128 check_specialization_scope, now avoid crashing. */
2129 if (!VAR_P (decl)
2130 && template_count && DECL_CLASS_SCOPE_P (decl)
2131 && template_class_depth (DECL_CONTEXT (decl)) > 0)
2133 gcc_assert (errorcount);
2134 return error_mark_node;
2137 fns = TREE_OPERAND (template_id, 0);
2138 explicit_targs = TREE_OPERAND (template_id, 1);
2140 if (fns == error_mark_node)
2141 return error_mark_node;
2143 /* Check for baselinks. */
2144 if (BASELINK_P (fns))
2145 fns = BASELINK_FUNCTIONS (fns);
2147 if (TREE_CODE (decl) == FUNCTION_DECL && !is_overloaded_fn (fns))
2149 error_at (DECL_SOURCE_LOCATION (decl),
2150 "%qD is not a function template", fns);
2151 return error_mark_node;
2153 else if (VAR_P (decl) && !variable_template_p (fns))
2155 error ("%qD is not a variable template", fns);
2156 return error_mark_node;
2159 /* Count the number of template headers specified for this
2160 specialization. */
2161 header_count = 0;
2162 for (b = current_binding_level;
2163 b->kind == sk_template_parms;
2164 b = b->level_chain)
2165 ++header_count;
2167 tree orig_fns = fns;
2168 bool header_mismatch = false;
2170 if (variable_template_p (fns))
2172 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (fns));
2173 targs = coerce_template_parms (parms, explicit_targs, fns,
2174 tf_warning_or_error);
2175 if (targs != error_mark_node
2176 && constraints_satisfied_p (fns, targs))
2177 templates = tree_cons (targs, fns, templates);
2179 else for (lkp_iterator iter (fns); iter; ++iter)
2181 tree fn = *iter;
2183 if (TREE_CODE (fn) == TEMPLATE_DECL)
2185 tree decl_arg_types;
2186 tree fn_arg_types;
2188 /* In case of explicit specialization, we need to check if
2189 the number of template headers appearing in the specialization
2190 is correct. This is usually done in check_explicit_specialization,
2191 but the check done there cannot be exhaustive when specializing
2192 member functions. Consider the following code:
2194 template <> void A<int>::f(int);
2195 template <> template <> void A<int>::f(int);
2197 Assuming that A<int> is not itself an explicit specialization
2198 already, the first line specializes "f" which is a non-template
2199 member function, whilst the second line specializes "f" which
2200 is a template member function. So both lines are syntactically
2201 correct, and check_explicit_specialization does not reject
2202 them.
2204 Here, we can do better, as we are matching the specialization
2205 against the declarations. We count the number of template
2206 headers, and we check if they match TEMPLATE_COUNT + 1
2207 (TEMPLATE_COUNT is the number of qualifying template classes,
2208 plus there must be another header for the member template
2209 itself).
2211 Notice that if header_count is zero, this is not a
2212 specialization but rather a template instantiation, so there
2213 is no check we can perform here. */
2214 if (header_count && header_count != template_count + 1)
2216 header_mismatch = true;
2217 continue;
2220 /* Check that the number of template arguments at the
2221 innermost level for DECL is the same as for FN. */
2222 if (current_binding_level->kind == sk_template_parms
2223 && !current_binding_level->explicit_spec_p
2224 && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
2225 != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
2226 (current_template_parms))))
2227 continue;
2229 /* DECL might be a specialization of FN. */
2230 decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2231 fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
2233 /* For a non-static member function, we need to make sure
2234 that the const qualification is the same. Since
2235 get_bindings does not try to merge the "this" parameter,
2236 we must do the comparison explicitly. */
2237 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
2239 if (!same_type_p (TREE_VALUE (fn_arg_types),
2240 TREE_VALUE (decl_arg_types)))
2241 continue;
2243 /* And the ref-qualification. */
2244 if (type_memfn_rqual (TREE_TYPE (decl))
2245 != type_memfn_rqual (TREE_TYPE (fn)))
2246 continue;
2249 /* Skip the "this" parameter and, for constructors of
2250 classes with virtual bases, the VTT parameter. A
2251 full specialization of a constructor will have a VTT
2252 parameter, but a template never will. */
2253 decl_arg_types
2254 = skip_artificial_parms_for (decl, decl_arg_types);
2255 fn_arg_types
2256 = skip_artificial_parms_for (fn, fn_arg_types);
2258 /* Function templates cannot be specializations; there are
2259 no partial specializations of functions. Therefore, if
2260 the type of DECL does not match FN, there is no
2261 match.
2263 Note that it should never be the case that we have both
2264 candidates added here, and for regular member functions
2265 below. */
2266 if (tsk == tsk_template)
2268 if (!comp_template_parms (DECL_TEMPLATE_PARMS (fn),
2269 current_template_parms))
2270 continue;
2271 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2272 TREE_TYPE (TREE_TYPE (fn))))
2273 continue;
2274 if (!compparms (fn_arg_types, decl_arg_types))
2275 continue;
2277 tree freq = get_constraints (fn);
2278 tree dreq = get_constraints (decl);
2279 if (!freq != !dreq)
2280 continue;
2281 if (freq)
2283 /* C++20 CA104: Substitute directly into the
2284 constraint-expression. */
2285 tree fargs = DECL_TI_ARGS (fn);
2286 tsubst_flags_t complain = tf_none;
2287 freq = tsubst_constraint_info (freq, fargs, complain, fn);
2288 if (!cp_tree_equal (freq, dreq))
2289 continue;
2292 candidates = tree_cons (NULL_TREE, fn, candidates);
2293 continue;
2296 /* See whether this function might be a specialization of this
2297 template. Suppress access control because we might be trying
2298 to make this specialization a friend, and we have already done
2299 access control for the declaration of the specialization. */
2300 push_deferring_access_checks (dk_no_check);
2301 targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
2302 pop_deferring_access_checks ();
2304 if (!targs)
2305 /* We cannot deduce template arguments that when used to
2306 specialize TMPL will produce DECL. */
2307 continue;
2309 if (uses_template_parms (targs))
2310 /* We deduced something involving 'auto', which isn't a valid
2311 template argument. */
2312 continue;
2314 /* Save this template, and the arguments deduced. */
2315 templates = tree_cons (targs, fn, templates);
2317 else if (need_member_template)
2318 /* FN is an ordinary member function, and we need a
2319 specialization of a member template. */
2321 else if (TREE_CODE (fn) != FUNCTION_DECL)
2322 /* We can get IDENTIFIER_NODEs here in certain erroneous
2323 cases. */
2325 else if (!DECL_FUNCTION_MEMBER_P (fn))
2326 /* This is just an ordinary non-member function. Nothing can
2327 be a specialization of that. */
2329 else if (DECL_ARTIFICIAL (fn))
2330 /* Cannot specialize functions that are created implicitly. */
2332 else
2334 tree decl_arg_types;
2336 /* This is an ordinary member function. However, since
2337 we're here, we can assume its enclosing class is a
2338 template class. For example,
2340 template <typename T> struct S { void f(); };
2341 template <> void S<int>::f() {}
2343 Here, S<int>::f is a non-template, but S<int> is a
2344 template class. If FN has the same type as DECL, we
2345 might be in business. */
2347 if (!DECL_TEMPLATE_INFO (fn))
2348 /* Its enclosing class is an explicit specialization
2349 of a template class. This is not a candidate. */
2350 continue;
2352 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2353 TREE_TYPE (TREE_TYPE (fn))))
2354 /* The return types differ. */
2355 continue;
2357 /* Adjust the type of DECL in case FN is a static member. */
2358 decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2359 if (DECL_STATIC_FUNCTION_P (fn)
2360 && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2361 decl_arg_types = TREE_CHAIN (decl_arg_types);
2363 if (!compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2364 decl_arg_types))
2365 continue;
2367 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2368 && (type_memfn_rqual (TREE_TYPE (decl))
2369 != type_memfn_rqual (TREE_TYPE (fn))))
2370 continue;
2372 // If the deduced arguments do not satisfy the constraints,
2373 // this is not a candidate.
2374 if (flag_concepts && !constraints_satisfied_p (fn))
2375 continue;
2377 // Add the candidate.
2378 candidates = tree_cons (NULL_TREE, fn, candidates);
2382 if (templates && TREE_CHAIN (templates))
2384 /* We have:
2386 [temp.expl.spec]
2388 It is possible for a specialization with a given function
2389 signature to be instantiated from more than one function
2390 template. In such cases, explicit specification of the
2391 template arguments must be used to uniquely identify the
2392 function template specialization being specialized.
2394 Note that here, there's no suggestion that we're supposed to
2395 determine which of the candidate templates is most
2396 specialized. However, we, also have:
2398 [temp.func.order]
2400 Partial ordering of overloaded function template
2401 declarations is used in the following contexts to select
2402 the function template to which a function template
2403 specialization refers:
2405 -- when an explicit specialization refers to a function
2406 template.
2408 So, we do use the partial ordering rules, at least for now.
2409 This extension can only serve to make invalid programs valid,
2410 so it's safe. And, there is strong anecdotal evidence that
2411 the committee intended the partial ordering rules to apply;
2412 the EDG front end has that behavior, and John Spicer claims
2413 that the committee simply forgot to delete the wording in
2414 [temp.expl.spec]. */
2415 tree tmpl = most_specialized_instantiation (templates);
2416 if (tmpl != error_mark_node)
2418 templates = tmpl;
2419 TREE_CHAIN (templates) = NULL_TREE;
2423 // Concepts allows multiple declarations of member functions
2424 // with the same signature. Like above, we need to rely on
2425 // on the partial ordering of those candidates to determine which
2426 // is the best.
2427 if (flag_concepts && candidates && TREE_CHAIN (candidates))
2429 if (tree cand = most_constrained_function (candidates))
2431 candidates = cand;
2432 TREE_CHAIN (cand) = NULL_TREE;
2436 if (templates == NULL_TREE && candidates == NULL_TREE)
2438 error ("template-id %qD for %q+D does not match any template "
2439 "declaration", template_id, decl);
2440 if (header_mismatch)
2441 inform (DECL_SOURCE_LOCATION (decl),
2442 "saw %d %<template<>%>, need %d for "
2443 "specializing a member function template",
2444 header_count, template_count + 1);
2445 print_candidates (orig_fns);
2446 return error_mark_node;
2448 else if ((templates && TREE_CHAIN (templates))
2449 || (candidates && TREE_CHAIN (candidates))
2450 || (templates && candidates))
2452 error ("ambiguous template specialization %qD for %q+D",
2453 template_id, decl);
2454 candidates = chainon (candidates, templates);
2455 print_candidates (candidates);
2456 return error_mark_node;
2459 /* We have one, and exactly one, match. */
2460 if (candidates)
2462 tree fn = TREE_VALUE (candidates);
2463 *targs_out = copy_node (DECL_TI_ARGS (fn));
2465 /* Propagate the candidate's constraints to the declaration. */
2466 if (tsk != tsk_template)
2467 set_constraints (decl, get_constraints (fn));
2469 /* DECL is a re-declaration or partial instantiation of a template
2470 function. */
2471 if (TREE_CODE (fn) == TEMPLATE_DECL)
2472 return fn;
2473 /* It was a specialization of an ordinary member function in a
2474 template class. */
2475 return DECL_TI_TEMPLATE (fn);
2478 /* It was a specialization of a template. */
2479 tree tmpl = TREE_VALUE (templates);
2480 *targs_out = add_outermost_template_args (tmpl, TREE_PURPOSE (templates));
2482 /* Propagate the template's constraints to the declaration. */
2483 if (tsk != tsk_template)
2484 set_constraints (decl, get_constraints (tmpl));
2486 return tmpl;
2489 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2490 but with the default argument values filled in from those in the
2491 TMPL_TYPES. */
2493 static tree
2494 copy_default_args_to_explicit_spec_1 (tree spec_types,
2495 tree tmpl_types)
2497 tree new_spec_types;
2499 if (!spec_types)
2500 return NULL_TREE;
2502 if (spec_types == void_list_node)
2503 return void_list_node;
2505 /* Substitute into the rest of the list. */
2506 new_spec_types =
2507 copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2508 TREE_CHAIN (tmpl_types));
2510 /* Add the default argument for this parameter. */
2511 return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2512 TREE_VALUE (spec_types),
2513 new_spec_types);
2516 /* DECL is an explicit specialization. Replicate default arguments
2517 from the template it specializes. (That way, code like:
2519 template <class T> void f(T = 3);
2520 template <> void f(double);
2521 void g () { f (); }
2523 works, as required.) An alternative approach would be to look up
2524 the correct default arguments at the call-site, but this approach
2525 is consistent with how implicit instantiations are handled. */
2527 static void
2528 copy_default_args_to_explicit_spec (tree decl)
2530 tree tmpl;
2531 tree spec_types;
2532 tree tmpl_types;
2533 tree new_spec_types;
2534 tree old_type;
2535 tree new_type;
2536 tree t;
2537 tree object_type = NULL_TREE;
2538 tree in_charge = NULL_TREE;
2539 tree vtt = NULL_TREE;
2541 /* See if there's anything we need to do. */
2542 tmpl = DECL_TI_TEMPLATE (decl);
2543 tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2544 for (t = tmpl_types; t; t = TREE_CHAIN (t))
2545 if (TREE_PURPOSE (t))
2546 break;
2547 if (!t)
2548 return;
2550 old_type = TREE_TYPE (decl);
2551 spec_types = TYPE_ARG_TYPES (old_type);
2553 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2555 /* Remove the this pointer, but remember the object's type for
2556 CV quals. */
2557 object_type = TREE_TYPE (TREE_VALUE (spec_types));
2558 spec_types = TREE_CHAIN (spec_types);
2559 tmpl_types = TREE_CHAIN (tmpl_types);
2561 if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2563 /* DECL may contain more parameters than TMPL due to the extra
2564 in-charge parameter in constructors and destructors. */
2565 in_charge = spec_types;
2566 spec_types = TREE_CHAIN (spec_types);
2568 if (DECL_HAS_VTT_PARM_P (decl))
2570 vtt = spec_types;
2571 spec_types = TREE_CHAIN (spec_types);
2575 /* Compute the merged default arguments. */
2576 new_spec_types =
2577 copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2579 /* Compute the new FUNCTION_TYPE. */
2580 if (object_type)
2582 if (vtt)
2583 new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2584 TREE_VALUE (vtt),
2585 new_spec_types);
2587 if (in_charge)
2588 /* Put the in-charge parameter back. */
2589 new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2590 TREE_VALUE (in_charge),
2591 new_spec_types);
2593 new_type = build_method_type_directly (object_type,
2594 TREE_TYPE (old_type),
2595 new_spec_types);
2597 else
2598 new_type = build_function_type (TREE_TYPE (old_type),
2599 new_spec_types);
2600 new_type = cp_build_type_attribute_variant (new_type,
2601 TYPE_ATTRIBUTES (old_type));
2602 new_type = cxx_copy_lang_qualifiers (new_type, old_type);
2604 TREE_TYPE (decl) = new_type;
2607 /* Return the number of template headers we expect to see for a definition
2608 or specialization of CTYPE or one of its non-template members. */
2611 num_template_headers_for_class (tree ctype)
2613 int num_templates = 0;
2615 while (ctype && CLASS_TYPE_P (ctype))
2617 /* You're supposed to have one `template <...>' for every
2618 template class, but you don't need one for a full
2619 specialization. For example:
2621 template <class T> struct S{};
2622 template <> struct S<int> { void f(); };
2623 void S<int>::f () {}
2625 is correct; there shouldn't be a `template <>' for the
2626 definition of `S<int>::f'. */
2627 if (!CLASSTYPE_TEMPLATE_INFO (ctype))
2628 /* If CTYPE does not have template information of any
2629 kind, then it is not a template, nor is it nested
2630 within a template. */
2631 break;
2632 if (explicit_class_specialization_p (ctype))
2633 break;
2634 if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (ctype)))
2635 ++num_templates;
2637 ctype = TYPE_CONTEXT (ctype);
2640 return num_templates;
2643 /* Do a simple sanity check on the template headers that precede the
2644 variable declaration DECL. */
2646 void
2647 check_template_variable (tree decl)
2649 tree ctx = CP_DECL_CONTEXT (decl);
2650 int wanted = num_template_headers_for_class (ctx);
2651 if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
2652 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
2654 if (cxx_dialect < cxx14)
2655 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wc__14_extensions,
2656 "variable templates only available with "
2657 "%<-std=c++14%> or %<-std=gnu++14%>");
2659 // Namespace-scope variable templates should have a template header.
2660 ++wanted;
2662 if (template_header_count > wanted)
2664 auto_diagnostic_group d;
2665 bool warned = pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2666 "too many template headers for %qD "
2667 "(should be %d)",
2668 decl, wanted);
2669 if (warned && CLASS_TYPE_P (ctx)
2670 && CLASSTYPE_TEMPLATE_SPECIALIZATION (ctx))
2671 inform (DECL_SOURCE_LOCATION (decl),
2672 "members of an explicitly specialized class are defined "
2673 "without a template header");
2677 /* An explicit specialization whose declarator-id or class-head-name is not
2678 qualified shall be declared in the nearest enclosing namespace of the
2679 template, or, if the namespace is inline (7.3.1), any namespace from its
2680 enclosing namespace set.
2682 If the name declared in the explicit instantiation is an unqualified name,
2683 the explicit instantiation shall appear in the namespace where its template
2684 is declared or, if that namespace is inline (7.3.1), any namespace from its
2685 enclosing namespace set. */
2687 void
2688 check_unqualified_spec_or_inst (tree t, location_t loc)
2690 tree tmpl = most_general_template (t);
2691 if (DECL_NAMESPACE_SCOPE_P (tmpl)
2692 && !is_nested_namespace (current_namespace,
2693 CP_DECL_CONTEXT (tmpl), true))
2695 if (processing_specialization)
2696 permerror (loc, "explicit specialization of %qD outside its "
2697 "namespace must use a nested-name-specifier", tmpl);
2698 else if (processing_explicit_instantiation
2699 && cxx_dialect >= cxx11)
2700 /* This was allowed in C++98, so only pedwarn. */
2701 pedwarn (loc, OPT_Wpedantic, "explicit instantiation of %qD "
2702 "outside its namespace must use a nested-name-"
2703 "specifier", tmpl);
2707 /* Warn for a template specialization SPEC that is missing some of a set
2708 of function or type attributes that the template TEMPL is declared with.
2709 ATTRLIST is a list of additional attributes that SPEC should be taken
2710 to ultimately be declared with. */
2712 static void
2713 warn_spec_missing_attributes (tree tmpl, tree spec, tree attrlist)
2715 if (DECL_FUNCTION_TEMPLATE_P (tmpl))
2716 tmpl = DECL_TEMPLATE_RESULT (tmpl);
2718 /* Avoid warning if the difference between the primary and
2719 the specialization is not in one of the attributes below. */
2720 const char* const blacklist[] = {
2721 "alloc_align", "alloc_size", "assume_aligned", "format",
2722 "format_arg", "malloc", "nonnull", NULL
2725 /* Put together a list of the black listed attributes that the primary
2726 template is declared with that the specialization is not, in case
2727 it's not apparent from the most recent declaration of the primary. */
2728 pretty_printer str;
2729 unsigned nattrs = decls_mismatched_attributes (tmpl, spec, attrlist,
2730 blacklist, &str);
2732 if (!nattrs)
2733 return;
2735 auto_diagnostic_group d;
2736 if (warning_at (DECL_SOURCE_LOCATION (spec), OPT_Wmissing_attributes,
2737 "explicit specialization %q#D may be missing attributes",
2738 spec))
2739 inform (DECL_SOURCE_LOCATION (tmpl),
2740 nattrs > 1
2741 ? G_("missing primary template attributes %s")
2742 : G_("missing primary template attribute %s"),
2743 pp_formatted_text (&str));
2746 /* Check to see if the function just declared, as indicated in
2747 DECLARATOR, and in DECL, is a specialization of a function
2748 template. We may also discover that the declaration is an explicit
2749 instantiation at this point.
2751 Returns DECL, or an equivalent declaration that should be used
2752 instead if all goes well. Issues an error message if something is
2753 amiss. Returns error_mark_node if the error is not easily
2754 recoverable.
2756 FLAGS is a bitmask consisting of the following flags:
2758 2: The function has a definition.
2759 4: The function is a friend.
2761 The TEMPLATE_COUNT is the number of references to qualifying
2762 template classes that appeared in the name of the function. For
2763 example, in
2765 template <class T> struct S { void f(); };
2766 void S<int>::f();
2768 the TEMPLATE_COUNT would be 1. However, explicitly specialized
2769 classes are not counted in the TEMPLATE_COUNT, so that in
2771 template <class T> struct S {};
2772 template <> struct S<int> { void f(); }
2773 template <> void S<int>::f();
2775 the TEMPLATE_COUNT would be 0. (Note that this declaration is
2776 invalid; there should be no template <>.)
2778 If the function is a specialization, it is marked as such via
2779 DECL_TEMPLATE_SPECIALIZATION. Furthermore, its DECL_TEMPLATE_INFO
2780 is set up correctly, and it is added to the list of specializations
2781 for that template. */
2783 tree
2784 check_explicit_specialization (tree declarator,
2785 tree decl,
2786 int template_count,
2787 int flags,
2788 tree attrlist)
2790 int have_def = flags & 2;
2791 int is_friend = flags & 4;
2792 bool is_concept = flags & 8;
2793 int specialization = 0;
2794 int explicit_instantiation = 0;
2795 int member_specialization = 0;
2796 tree ctype = DECL_CLASS_CONTEXT (decl);
2797 tree dname = DECL_NAME (decl);
2798 tmpl_spec_kind tsk;
2800 if (is_friend)
2802 if (!processing_specialization)
2803 tsk = tsk_none;
2804 else
2805 tsk = tsk_excessive_parms;
2807 else
2808 tsk = current_tmpl_spec_kind (template_count);
2810 switch (tsk)
2812 case tsk_none:
2813 if (processing_specialization && !VAR_P (decl))
2815 specialization = 1;
2816 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2818 else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR
2819 || (DECL_LANG_SPECIFIC (decl)
2820 && DECL_IMPLICIT_INSTANTIATION (decl)))
2822 if (is_friend)
2823 /* This could be something like:
2825 template <class T> void f(T);
2826 class S { friend void f<>(int); } */
2827 specialization = 1;
2828 else
2830 /* This case handles bogus declarations like template <>
2831 template <class T> void f<int>(); */
2833 error_at (cp_expr_loc_or_input_loc (declarator),
2834 "template-id %qE in declaration of primary template",
2835 declarator);
2836 return decl;
2839 break;
2841 case tsk_invalid_member_spec:
2842 /* The error has already been reported in
2843 check_specialization_scope. */
2844 return error_mark_node;
2846 case tsk_invalid_expl_inst:
2847 error ("template parameter list used in explicit instantiation");
2849 /* Fall through. */
2851 case tsk_expl_inst:
2852 if (have_def)
2853 error ("definition provided for explicit instantiation");
2855 explicit_instantiation = 1;
2856 break;
2858 case tsk_excessive_parms:
2859 case tsk_insufficient_parms:
2860 if (tsk == tsk_excessive_parms)
2861 error ("too many template parameter lists in declaration of %qD",
2862 decl);
2863 else if (template_header_count)
2864 error("too few template parameter lists in declaration of %qD", decl);
2865 else
2866 error("explicit specialization of %qD must be introduced by "
2867 "%<template <>%>", decl);
2869 /* Fall through. */
2870 case tsk_expl_spec:
2871 if (is_concept)
2872 error ("explicit specialization declared %<concept%>");
2874 if (VAR_P (decl) && TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2875 /* In cases like template<> constexpr bool v = true;
2876 We'll give an error in check_template_variable. */
2877 break;
2879 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2880 if (ctype)
2881 member_specialization = 1;
2882 else
2883 specialization = 1;
2884 break;
2886 case tsk_template:
2887 if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2889 /* This case handles bogus declarations like template <>
2890 template <class T> void f<int>(); */
2892 if (!uses_template_parms (TREE_OPERAND (declarator, 1)))
2893 error_at (cp_expr_loc_or_input_loc (declarator),
2894 "template-id %qE in declaration of primary template",
2895 declarator);
2896 else if (variable_template_p (TREE_OPERAND (declarator, 0)))
2898 /* Partial specialization of variable template. */
2899 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2900 specialization = 1;
2901 goto ok;
2903 else if (cxx_dialect < cxx14)
2904 error_at (cp_expr_loc_or_input_loc (declarator),
2905 "non-type partial specialization %qE "
2906 "is not allowed", declarator);
2907 else
2908 error_at (cp_expr_loc_or_input_loc (declarator),
2909 "non-class, non-variable partial specialization %qE "
2910 "is not allowed", declarator);
2911 return decl;
2912 ok:;
2915 if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2916 /* This is a specialization of a member template, without
2917 specialization the containing class. Something like:
2919 template <class T> struct S {
2920 template <class U> void f (U);
2922 template <> template <class U> void S<int>::f(U) {}
2924 That's a specialization -- but of the entire template. */
2925 specialization = 1;
2926 break;
2928 default:
2929 gcc_unreachable ();
2932 if ((specialization || member_specialization)
2933 /* This doesn't apply to variable templates. */
2934 && FUNC_OR_METHOD_TYPE_P (TREE_TYPE (decl)))
2936 tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2937 for (; t; t = TREE_CHAIN (t))
2938 if (TREE_PURPOSE (t))
2940 permerror (input_location,
2941 "default argument specified in explicit specialization");
2942 break;
2946 if (specialization || member_specialization || explicit_instantiation)
2948 tree tmpl = NULL_TREE;
2949 tree targs = NULL_TREE;
2950 bool was_template_id = (TREE_CODE (declarator) == TEMPLATE_ID_EXPR);
2951 bool found_hidden = false;
2953 /* Make sure that the declarator is a TEMPLATE_ID_EXPR. */
2954 if (!was_template_id)
2956 tree fns;
2958 gcc_assert (identifier_p (declarator));
2959 if (ctype)
2960 fns = dname;
2961 else
2963 /* If there is no class context, the explicit instantiation
2964 must be at namespace scope. */
2965 gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2967 /* Find the namespace binding, using the declaration
2968 context. */
2969 fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2970 LOOK_want::NORMAL, true);
2971 if (fns == error_mark_node)
2973 /* If lookup fails, look for a friend declaration so we can
2974 give a better diagnostic. */
2975 fns = (lookup_qualified_name
2976 (CP_DECL_CONTEXT (decl), dname,
2977 LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND,
2978 /*complain*/true));
2979 found_hidden = true;
2982 if (fns == error_mark_node || !is_overloaded_fn (fns))
2984 error ("%qD is not a template function", dname);
2985 fns = error_mark_node;
2989 declarator = lookup_template_function (fns, NULL_TREE);
2992 if (declarator == error_mark_node)
2993 return error_mark_node;
2995 if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2997 if (!explicit_instantiation)
2998 /* A specialization in class scope. This is invalid,
2999 but the error will already have been flagged by
3000 check_specialization_scope. */
3001 return error_mark_node;
3002 else
3004 /* It's not valid to write an explicit instantiation in
3005 class scope, e.g.:
3007 class C { template void f(); }
3009 This case is caught by the parser. However, on
3010 something like:
3012 template class C { void f(); };
3014 (which is invalid) we can get here. The error will be
3015 issued later. */
3019 return decl;
3021 else if (ctype != NULL_TREE
3022 && (identifier_p (TREE_OPERAND (declarator, 0))))
3024 // We'll match variable templates in start_decl.
3025 if (VAR_P (decl))
3026 return decl;
3028 /* Find the list of functions in ctype that have the same
3029 name as the declared function. */
3030 tree name = TREE_OPERAND (declarator, 0);
3032 if (constructor_name_p (name, ctype))
3034 if (DECL_CONSTRUCTOR_P (decl)
3035 ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
3036 : !CLASSTYPE_DESTRUCTOR (ctype))
3038 /* From [temp.expl.spec]:
3040 If such an explicit specialization for the member
3041 of a class template names an implicitly-declared
3042 special member function (clause _special_), the
3043 program is ill-formed.
3045 Similar language is found in [temp.explicit]. */
3046 error ("specialization of implicitly-declared special member function");
3047 return error_mark_node;
3050 name = DECL_NAME (decl);
3053 /* For a type-conversion operator, We might be looking for
3054 `operator int' which will be a specialization of
3055 `operator T'. Grab all the conversion operators, and
3056 then select from them. */
3057 tree fns = get_class_binding (ctype, IDENTIFIER_CONV_OP_P (name)
3058 ? conv_op_identifier : name);
3060 if (fns == NULL_TREE)
3062 error ("no member function %qD declared in %qT", name, ctype);
3063 return error_mark_node;
3065 else
3066 TREE_OPERAND (declarator, 0) = fns;
3069 /* Figure out what exactly is being specialized at this point.
3070 Note that for an explicit instantiation, even one for a
3071 member function, we cannot tell a priori whether the
3072 instantiation is for a member template, or just a member
3073 function of a template class. Even if a member template is
3074 being instantiated, the member template arguments may be
3075 elided if they can be deduced from the rest of the
3076 declaration. */
3077 tmpl = determine_specialization (declarator, decl,
3078 &targs,
3079 member_specialization,
3080 template_count,
3081 tsk);
3083 if (!tmpl || tmpl == error_mark_node)
3084 /* We couldn't figure out what this declaration was
3085 specializing. */
3086 return error_mark_node;
3087 else
3089 if (found_hidden && TREE_CODE (decl) == FUNCTION_DECL)
3091 auto_diagnostic_group d;
3092 if (pedwarn (DECL_SOURCE_LOCATION (decl), 0,
3093 "friend declaration %qD is not visible to "
3094 "explicit specialization", tmpl))
3095 inform (DECL_SOURCE_LOCATION (tmpl),
3096 "friend declaration here");
3099 if (!ctype && !is_friend
3100 && CP_DECL_CONTEXT (decl) == current_namespace)
3101 check_unqualified_spec_or_inst (tmpl, DECL_SOURCE_LOCATION (decl));
3103 tree gen_tmpl = most_general_template (tmpl);
3105 if (explicit_instantiation)
3107 /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
3108 is done by do_decl_instantiation later. */
3110 int arg_depth = TMPL_ARGS_DEPTH (targs);
3111 int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
3113 if (arg_depth > parm_depth)
3115 /* If TMPL is not the most general template (for
3116 example, if TMPL is a friend template that is
3117 injected into namespace scope), then there will
3118 be too many levels of TARGS. Remove some of them
3119 here. */
3120 int i;
3121 tree new_targs;
3123 new_targs = make_tree_vec (parm_depth);
3124 for (i = arg_depth - parm_depth; i < arg_depth; ++i)
3125 TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
3126 = TREE_VEC_ELT (targs, i);
3127 targs = new_targs;
3130 return instantiate_template (tmpl, targs, tf_error);
3133 /* If we thought that the DECL was a member function, but it
3134 turns out to be specializing a static member function,
3135 make DECL a static member function as well. */
3136 if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3137 && DECL_STATIC_FUNCTION_P (tmpl)
3138 && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
3139 revert_static_member_fn (decl);
3141 /* If this is a specialization of a member template of a
3142 template class, we want to return the TEMPLATE_DECL, not
3143 the specialization of it. */
3144 if (tsk == tsk_template && !was_template_id)
3146 tree result = DECL_TEMPLATE_RESULT (tmpl);
3147 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3148 DECL_INITIAL (result) = NULL_TREE;
3149 if (have_def)
3151 tree parm;
3152 DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
3153 DECL_SOURCE_LOCATION (result)
3154 = DECL_SOURCE_LOCATION (decl);
3155 /* We want to use the argument list specified in the
3156 definition, not in the original declaration. */
3157 DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
3158 for (parm = DECL_ARGUMENTS (result); parm;
3159 parm = DECL_CHAIN (parm))
3160 DECL_CONTEXT (parm) = result;
3162 decl = register_specialization (tmpl, gen_tmpl, targs,
3163 is_friend, 0);
3164 remove_contract_attributes (result);
3165 return decl;
3168 /* Set up the DECL_TEMPLATE_INFO for DECL. */
3169 DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
3171 if (was_template_id)
3172 TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl)) = true;
3174 /* Inherit default function arguments from the template
3175 DECL is specializing. */
3176 if (DECL_FUNCTION_TEMPLATE_P (tmpl))
3177 copy_default_args_to_explicit_spec (decl);
3179 /* This specialization has the same protection as the
3180 template it specializes. */
3181 TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
3182 TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
3184 /* 7.1.1-1 [dcl.stc]
3186 A storage-class-specifier shall not be specified in an
3187 explicit specialization...
3189 The parser rejects these, so unless action is taken here,
3190 explicit function specializations will always appear with
3191 global linkage.
3193 The action recommended by the C++ CWG in response to C++
3194 defect report 605 is to make the storage class and linkage
3195 of the explicit specialization match the templated function:
3197 http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
3199 if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
3201 tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
3202 gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
3204 /* A concept cannot be specialized. */
3205 if (DECL_DECLARED_CONCEPT_P (tmpl_func))
3207 error ("explicit specialization of function concept %qD",
3208 gen_tmpl);
3209 return error_mark_node;
3212 /* This specialization has the same linkage and visibility as
3213 the function template it specializes. */
3214 TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
3215 if (! TREE_PUBLIC (decl))
3217 DECL_INTERFACE_KNOWN (decl) = 1;
3218 DECL_NOT_REALLY_EXTERN (decl) = 1;
3220 DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
3221 if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
3223 DECL_VISIBILITY_SPECIFIED (decl) = 1;
3224 DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
3228 /* If DECL is a friend declaration, declared using an
3229 unqualified name, the namespace associated with DECL may
3230 have been set incorrectly. For example, in:
3232 template <typename T> void f(T);
3233 namespace N {
3234 struct S { friend void f<int>(int); }
3237 we will have set the DECL_CONTEXT for the friend
3238 declaration to N, rather than to the global namespace. */
3239 if (DECL_NAMESPACE_SCOPE_P (decl))
3240 DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
3242 if (is_friend && !have_def)
3243 /* This is not really a declaration of a specialization.
3244 It's just the name of an instantiation. But, it's not
3245 a request for an instantiation, either. */
3246 SET_DECL_IMPLICIT_INSTANTIATION (decl);
3247 else if (TREE_CODE (decl) == FUNCTION_DECL)
3248 /* A specialization is not necessarily COMDAT. */
3249 DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
3250 && DECL_DECLARED_INLINE_P (decl));
3251 else if (VAR_P (decl))
3252 DECL_COMDAT (decl) = false;
3254 /* If this is a full specialization, register it so that we can find
3255 it again. Partial specializations will be registered in
3256 process_partial_specialization. */
3257 if (!processing_template_decl)
3259 warn_spec_missing_attributes (gen_tmpl, decl, attrlist);
3261 decl = register_specialization (decl, gen_tmpl, targs,
3262 is_friend, 0);
3265 /* If this is a specialization, splice any contracts that may have
3266 been inherited from the template, removing them. */
3267 if (decl != error_mark_node && DECL_TEMPLATE_SPECIALIZATION (decl))
3268 remove_contract_attributes (decl);
3270 /* A 'structor should already have clones. */
3271 gcc_assert (decl == error_mark_node
3272 || variable_template_p (tmpl)
3273 || !(DECL_CONSTRUCTOR_P (decl)
3274 || DECL_DESTRUCTOR_P (decl))
3275 || DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
3279 return decl;
3282 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
3283 parameters. These are represented in the same format used for
3284 DECL_TEMPLATE_PARMS. */
3287 comp_template_parms (const_tree parms1, const_tree parms2)
3289 const_tree p1;
3290 const_tree p2;
3292 if (parms1 == parms2)
3293 return 1;
3295 for (p1 = parms1, p2 = parms2;
3296 p1 != NULL_TREE && p2 != NULL_TREE;
3297 p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
3299 tree t1 = TREE_VALUE (p1);
3300 tree t2 = TREE_VALUE (p2);
3301 int i;
3303 gcc_assert (TREE_CODE (t1) == TREE_VEC);
3304 gcc_assert (TREE_CODE (t2) == TREE_VEC);
3306 if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
3307 return 0;
3309 for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
3311 tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
3312 tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
3314 /* If either of the template parameters are invalid, assume
3315 they match for the sake of error recovery. */
3316 if (error_operand_p (parm1) || error_operand_p (parm2))
3317 return 1;
3319 if (TREE_CODE (parm1) != TREE_CODE (parm2))
3320 return 0;
3322 if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
3323 && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
3324 == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
3325 continue;
3326 else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
3327 return 0;
3331 if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3332 /* One set of parameters has more parameters lists than the
3333 other. */
3334 return 0;
3336 return 1;
3339 /* Returns true if two template parameters are declared with
3340 equivalent constraints. */
3342 static bool
3343 template_parameter_constraints_equivalent_p (const_tree parm1, const_tree parm2)
3345 tree req1 = TREE_TYPE (parm1);
3346 tree req2 = TREE_TYPE (parm2);
3347 if (!req1 != !req2)
3348 return false;
3349 if (req1)
3350 return cp_tree_equal (req1, req2);
3351 return true;
3354 /* Returns true when two template parameters are equivalent. */
3356 static bool
3357 template_parameters_equivalent_p (const_tree parm1, const_tree parm2)
3359 tree decl1 = TREE_VALUE (parm1);
3360 tree decl2 = TREE_VALUE (parm2);
3362 /* If either of the template parameters are invalid, assume
3363 they match for the sake of error recovery. */
3364 if (error_operand_p (decl1) || error_operand_p (decl2))
3365 return true;
3367 /* ... they declare parameters of the same kind. */
3368 if (TREE_CODE (decl1) != TREE_CODE (decl2))
3369 return false;
3371 /* ... one parameter was introduced by a parameter declaration, then
3372 both are. This case arises as a result of eagerly rewriting declarations
3373 during parsing. */
3374 if (DECL_VIRTUAL_P (decl1) != DECL_VIRTUAL_P (decl2))
3375 return false;
3377 /* ... if either declares a pack, they both do. */
3378 if (template_parameter_pack_p (decl1) != template_parameter_pack_p (decl2))
3379 return false;
3381 if (TREE_CODE (decl1) == PARM_DECL)
3383 /* ... if they declare non-type parameters, the types are equivalent. */
3384 if (!same_type_p (TREE_TYPE (decl1), TREE_TYPE (decl2)))
3385 return false;
3387 else if (TREE_CODE (decl2) == TEMPLATE_DECL)
3389 /* ... if they declare template template parameters, their template
3390 parameter lists are equivalent. */
3391 if (!template_heads_equivalent_p (decl1, decl2))
3392 return false;
3395 /* ... if they are declared with a qualified-concept name, they both
3396 are, and those names are equivalent. */
3397 return template_parameter_constraints_equivalent_p (parm1, parm2);
3400 /* Returns true if two template parameters lists are equivalent.
3401 Two template parameter lists are equivalent if they have the
3402 same length and their corresponding parameters are equivalent.
3404 PARMS1 and PARMS2 are TREE_LISTs containing TREE_VECs: the
3405 data structure returned by DECL_TEMPLATE_PARMS.
3407 This is generally the same implementation as comp_template_parms
3408 except that it also the concept names and arguments used to
3409 introduce parameters. */
3411 static bool
3412 template_parameter_lists_equivalent_p (const_tree parms1, const_tree parms2)
3414 if (parms1 == parms2)
3415 return true;
3417 const_tree p1 = parms1;
3418 const_tree p2 = parms2;
3419 while (p1 != NULL_TREE && p2 != NULL_TREE)
3421 tree list1 = TREE_VALUE (p1);
3422 tree list2 = TREE_VALUE (p2);
3424 if (TREE_VEC_LENGTH (list1) != TREE_VEC_LENGTH (list2))
3425 return 0;
3427 for (int i = 0; i < TREE_VEC_LENGTH (list2); ++i)
3429 tree parm1 = TREE_VEC_ELT (list1, i);
3430 tree parm2 = TREE_VEC_ELT (list2, i);
3431 if (!template_parameters_equivalent_p (parm1, parm2))
3432 return false;
3435 p1 = TREE_CHAIN (p1);
3436 p2 = TREE_CHAIN (p2);
3439 if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3440 return false;
3442 return true;
3445 /* Return true if the requires-clause of the template parameter lists are
3446 equivalent and false otherwise. */
3447 static bool
3448 template_requirements_equivalent_p (const_tree parms1, const_tree parms2)
3450 tree req1 = TEMPLATE_PARMS_CONSTRAINTS (parms1);
3451 tree req2 = TEMPLATE_PARMS_CONSTRAINTS (parms2);
3452 if ((req1 != NULL_TREE) != (req2 != NULL_TREE))
3453 return false;
3454 if (!cp_tree_equal (req1, req2))
3455 return false;
3456 return true;
3459 /* Returns true if two template heads are equivalent. 17.6.6.1p6:
3460 Two template heads are equivalent if their template parameter
3461 lists are equivalent and their requires clauses are equivalent.
3463 In pre-C++20, this is equivalent to calling comp_template_parms
3464 for the template parameters of TMPL1 and TMPL2. */
3466 bool
3467 template_heads_equivalent_p (const_tree tmpl1, const_tree tmpl2)
3469 tree parms1 = DECL_TEMPLATE_PARMS (tmpl1);
3470 tree parms2 = DECL_TEMPLATE_PARMS (tmpl2);
3472 /* Don't change the matching rules for pre-C++20. */
3473 if (cxx_dialect < cxx20)
3474 return comp_template_parms (parms1, parms2);
3476 /* ... have the same number of template parameters, and their
3477 corresponding parameters are equivalent. */
3478 if (!template_parameter_lists_equivalent_p (parms1, parms2))
3479 return false;
3481 /* ... if either has a requires-clause, they both do and their
3482 corresponding constraint-expressions are equivalent. */
3483 return template_requirements_equivalent_p (parms1, parms2);
3486 /* Determine whether PARM is a parameter pack. */
3488 bool
3489 template_parameter_pack_p (const_tree parm)
3491 /* Determine if we have a non-type template parameter pack. */
3492 if (TREE_CODE (parm) == PARM_DECL)
3493 return (DECL_TEMPLATE_PARM_P (parm)
3494 && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
3495 if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
3496 return TEMPLATE_PARM_PARAMETER_PACK (parm);
3498 /* If this is a list of template parameters, we could get a
3499 TYPE_DECL or a TEMPLATE_DECL. */
3500 if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
3501 parm = TREE_TYPE (parm);
3503 /* Otherwise it must be a type template parameter. */
3504 return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
3505 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
3506 && TEMPLATE_TYPE_PARAMETER_PACK (parm));
3509 /* Determine if T is a function parameter pack. */
3511 bool
3512 function_parameter_pack_p (const_tree t)
3514 if (t && TREE_CODE (t) == PARM_DECL)
3515 return DECL_PACK_P (t);
3516 return false;
3519 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
3520 PRIMARY_FUNC_TMPL_INST is a primary function template instantiation. */
3522 tree
3523 get_function_template_decl (const_tree primary_func_tmpl_inst)
3525 if (! primary_func_tmpl_inst
3526 || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
3527 || ! primary_template_specialization_p (primary_func_tmpl_inst))
3528 return NULL;
3530 return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
3533 /* Return true iff the function parameter PARAM_DECL was expanded
3534 from the function parameter pack PACK. */
3536 bool
3537 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
3539 if (DECL_ARTIFICIAL (param_decl)
3540 || !function_parameter_pack_p (pack))
3541 return false;
3543 /* The parameter pack and its pack arguments have the same
3544 DECL_PARM_INDEX. */
3545 return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
3548 /* Determine whether ARGS describes a variadic template args list,
3549 i.e., one that is terminated by a template argument pack. */
3551 static bool
3552 template_args_variadic_p (tree args)
3554 int nargs;
3555 tree last_parm;
3557 if (args == NULL_TREE)
3558 return false;
3560 args = INNERMOST_TEMPLATE_ARGS (args);
3561 nargs = TREE_VEC_LENGTH (args);
3563 if (nargs == 0)
3564 return false;
3566 last_parm = TREE_VEC_ELT (args, nargs - 1);
3568 return ARGUMENT_PACK_P (last_parm);
3571 /* Generate a new name for the parameter pack name NAME (an
3572 IDENTIFIER_NODE) that incorporates its */
3574 static tree
3575 make_ith_pack_parameter_name (tree name, int i)
3577 /* Munge the name to include the parameter index. */
3578 #define NUMBUF_LEN 128
3579 char numbuf[NUMBUF_LEN];
3580 char* newname;
3581 int newname_len;
3583 if (name == NULL_TREE)
3584 return name;
3585 snprintf (numbuf, NUMBUF_LEN, "%i", i);
3586 newname_len = IDENTIFIER_LENGTH (name)
3587 + strlen (numbuf) + 2;
3588 newname = (char*)alloca (newname_len);
3589 snprintf (newname, newname_len,
3590 "%s#%i", IDENTIFIER_POINTER (name), i);
3591 return get_identifier (newname);
3594 /* Return true if T is a primary function, class or alias template
3595 specialization, not including the template pattern. */
3597 bool
3598 primary_template_specialization_p (const_tree t)
3600 if (!t)
3601 return false;
3603 if (VAR_OR_FUNCTION_DECL_P (t))
3604 return (DECL_LANG_SPECIFIC (t)
3605 && DECL_USE_TEMPLATE (t)
3606 && DECL_TEMPLATE_INFO (t)
3607 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t)));
3608 else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
3609 return (CLASSTYPE_TEMPLATE_INFO (t)
3610 && CLASSTYPE_USE_TEMPLATE (t)
3611 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)));
3612 else if (alias_template_specialization_p (t, nt_transparent))
3613 return true;
3614 return false;
3617 /* Return true if PARM is a template template parameter. */
3619 bool
3620 template_template_parameter_p (const_tree parm)
3622 return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
3625 /* Return true iff PARM is a DECL representing a type template
3626 parameter. */
3628 bool
3629 template_type_parameter_p (const_tree parm)
3631 return (parm
3632 && (TREE_CODE (parm) == TYPE_DECL
3633 || TREE_CODE (parm) == TEMPLATE_DECL)
3634 && DECL_TEMPLATE_PARM_P (parm));
3637 /* Return the template parameters of T if T is a
3638 primary template instantiation, NULL otherwise. */
3640 tree
3641 get_primary_template_innermost_parameters (const_tree t)
3643 tree parms = NULL, template_info = NULL;
3645 if ((template_info = get_template_info (t))
3646 && primary_template_specialization_p (t))
3647 parms = INNERMOST_TEMPLATE_PARMS
3648 (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
3650 return parms;
3653 /* Returns the template arguments of T if T is a template instantiation,
3654 NULL otherwise. */
3656 tree
3657 get_template_innermost_arguments (const_tree t)
3659 tree args = NULL, template_info = NULL;
3661 if ((template_info = get_template_info (t))
3662 && TI_ARGS (template_info))
3663 args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
3665 return args;
3668 /* Return the argument pack elements of T if T is a template argument pack,
3669 NULL otherwise. */
3671 tree
3672 get_template_argument_pack_elems (const_tree t)
3674 if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
3675 && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
3676 return NULL;
3678 return ARGUMENT_PACK_ARGS (t);
3681 /* In an ARGUMENT_PACK_SELECT, the actual underlying argument that the
3682 ARGUMENT_PACK_SELECT represents. */
3684 static tree
3685 argument_pack_select_arg (tree t)
3687 tree args = ARGUMENT_PACK_ARGS (ARGUMENT_PACK_SELECT_FROM_PACK (t));
3688 tree arg = TREE_VEC_ELT (args, ARGUMENT_PACK_SELECT_INDEX (t));
3690 /* If the selected argument is an expansion E, that most likely means we were
3691 called from gen_elem_of_pack_expansion_instantiation during the
3692 substituting of an argument pack (of which the Ith element is a pack
3693 expansion, where I is ARGUMENT_PACK_SELECT_INDEX) into a pack expansion.
3694 In this case, the Ith element resulting from this substituting is going to
3695 be a pack expansion, which pattern is the pattern of E. Let's return the
3696 pattern of E, and gen_elem_of_pack_expansion_instantiation will build the
3697 resulting pack expansion from it. */
3698 if (PACK_EXPANSION_P (arg))
3700 /* Make sure we aren't throwing away arg info. */
3701 gcc_assert (!PACK_EXPANSION_EXTRA_ARGS (arg));
3702 arg = PACK_EXPANSION_PATTERN (arg);
3705 return arg;
3708 /* Return a modification of ARGS that's suitable for preserving inside a hash
3709 table. In particular, this replaces each ARGUMENT_PACK_SELECT with its
3710 underlying argument. ARGS is copied (upon modification) iff COW_P. */
3712 static tree
3713 preserve_args (tree args, bool cow_p = true)
3715 if (!args)
3716 return NULL_TREE;
3718 for (int i = 0, len = TREE_VEC_LENGTH (args); i < len; ++i)
3720 tree t = TREE_VEC_ELT (args, i);
3721 tree r;
3722 if (!t)
3723 r = NULL_TREE;
3724 else if (TREE_CODE (t) == ARGUMENT_PACK_SELECT)
3725 r = argument_pack_select_arg (t);
3726 else if (TREE_CODE (t) == TREE_VEC)
3727 r = preserve_args (t, cow_p);
3728 else
3729 r = t;
3730 if (r != t)
3732 if (cow_p)
3734 args = copy_template_args (args);
3735 cow_p = false;
3737 TREE_VEC_ELT (args, i) = r;
3741 return args;
3744 /* True iff FN is a function representing a built-in variadic parameter
3745 pack. */
3747 bool
3748 builtin_pack_fn_p (tree fn)
3750 if (!fn
3751 || TREE_CODE (fn) != FUNCTION_DECL
3752 || !DECL_IS_UNDECLARED_BUILTIN (fn))
3753 return false;
3755 if (id_equal (DECL_NAME (fn), "__integer_pack"))
3756 return true;
3758 return false;
3761 /* True iff CALL is a call to a function representing a built-in variadic
3762 parameter pack. */
3764 static bool
3765 builtin_pack_call_p (tree call)
3767 if (TREE_CODE (call) != CALL_EXPR)
3768 return false;
3769 return builtin_pack_fn_p (CALL_EXPR_FN (call));
3772 /* Return a TREE_VEC for the expansion of __integer_pack(HI). */
3774 static tree
3775 expand_integer_pack (tree call, tree args, tsubst_flags_t complain,
3776 tree in_decl)
3778 tree ohi = CALL_EXPR_ARG (call, 0);
3779 tree hi = tsubst_copy_and_build (ohi, args, complain, in_decl);
3781 if (instantiation_dependent_expression_p (hi))
3783 if (hi != ohi)
3785 call = copy_node (call);
3786 CALL_EXPR_ARG (call, 0) = hi;
3788 tree ex = make_pack_expansion (call, complain);
3789 tree vec = make_tree_vec (1);
3790 TREE_VEC_ELT (vec, 0) = ex;
3791 return vec;
3793 else
3795 hi = instantiate_non_dependent_expr (hi, complain);
3796 hi = cxx_constant_value (hi, complain);
3797 int len = valid_constant_size_p (hi) ? tree_to_shwi (hi) : -1;
3799 /* Calculate the largest value of len that won't make the size of the vec
3800 overflow an int. The compiler will exceed resource limits long before
3801 this, but it seems a decent place to diagnose. */
3802 int max = ((INT_MAX - sizeof (tree_vec)) / sizeof (tree)) + 1;
3804 if (len < 0 || len > max)
3806 if ((complain & tf_error)
3807 && hi != error_mark_node)
3808 error ("argument to %<__integer_pack%> must be between 0 and %d",
3809 max);
3810 return error_mark_node;
3813 tree vec = make_tree_vec (len);
3815 for (int i = 0; i < len; ++i)
3816 TREE_VEC_ELT (vec, i) = size_int (i);
3818 return vec;
3822 /* Return a TREE_VEC for the expansion of built-in template parameter pack
3823 CALL. */
3825 static tree
3826 expand_builtin_pack_call (tree call, tree args, tsubst_flags_t complain,
3827 tree in_decl)
3829 if (!builtin_pack_call_p (call))
3830 return NULL_TREE;
3832 tree fn = CALL_EXPR_FN (call);
3834 if (id_equal (DECL_NAME (fn), "__integer_pack"))
3835 return expand_integer_pack (call, args, complain, in_decl);
3837 return NULL_TREE;
3840 /* Return true if the tree T has the extra args mechanism for
3841 avoiding partial instantiation. */
3843 static bool
3844 has_extra_args_mechanism_p (const_tree t)
3846 return (PACK_EXPANSION_P (t) /* PACK_EXPANSION_EXTRA_ARGS */
3847 || TREE_CODE (t) == REQUIRES_EXPR /* REQUIRES_EXPR_EXTRA_ARGS */
3848 || (TREE_CODE (t) == IF_STMT
3849 && IF_STMT_CONSTEXPR_P (t))); /* IF_STMT_EXTRA_ARGS */
3852 /* Structure used to track the progress of find_parameter_packs_r. */
3853 struct find_parameter_pack_data
3855 /* TREE_LIST that will contain all of the parameter packs found by
3856 the traversal. */
3857 tree* parameter_packs;
3859 /* Set of AST nodes that have been visited by the traversal. */
3860 hash_set<tree> *visited;
3862 /* True iff we're making a type pack expansion. */
3863 bool type_pack_expansion_p;
3865 /* True iff we found a subtree that has the extra args mechanism. */
3866 bool found_extra_args_tree_p = false;
3869 /* Identifies all of the argument packs that occur in a template
3870 argument and appends them to the TREE_LIST inside DATA, which is a
3871 find_parameter_pack_data structure. This is a subroutine of
3872 make_pack_expansion and uses_parameter_packs. */
3873 static tree
3874 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
3876 tree t = *tp;
3877 struct find_parameter_pack_data* ppd =
3878 (struct find_parameter_pack_data*)data;
3879 bool parameter_pack_p = false;
3881 #define WALK_SUBTREE(NODE) \
3882 cp_walk_tree (&(NODE), &find_parameter_packs_r, \
3883 ppd, ppd->visited) \
3885 /* Don't look through typedefs; we are interested in whether a
3886 parameter pack is actually written in the expression/type we're
3887 looking at, not the target type. */
3888 if (TYPE_P (t) && typedef_variant_p (t))
3890 /* But do look at arguments for an alias template. */
3891 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
3892 cp_walk_tree (&TI_ARGS (tinfo),
3893 &find_parameter_packs_r,
3894 ppd, ppd->visited);
3895 *walk_subtrees = 0;
3896 return NULL_TREE;
3899 /* Identify whether this is a parameter pack or not. */
3900 switch (TREE_CODE (t))
3902 case TEMPLATE_PARM_INDEX:
3903 if (TEMPLATE_PARM_PARAMETER_PACK (t))
3904 parameter_pack_p = true;
3905 break;
3907 case TEMPLATE_TYPE_PARM:
3908 t = TYPE_MAIN_VARIANT (t);
3909 /* FALLTHRU */
3910 case TEMPLATE_TEMPLATE_PARM:
3911 /* If the placeholder appears in the decl-specifier-seq of a function
3912 parameter pack (14.6.3), or the type-specifier-seq of a type-id that
3913 is a pack expansion, the invented template parameter is a template
3914 parameter pack. */
3915 if (ppd->type_pack_expansion_p && is_auto (t))
3916 TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
3917 if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3918 parameter_pack_p = true;
3919 break;
3921 case FIELD_DECL:
3922 case PARM_DECL:
3923 if (DECL_PACK_P (t))
3925 /* We don't want to walk into the type of a PARM_DECL,
3926 because we don't want to see the type parameter pack. */
3927 *walk_subtrees = 0;
3928 parameter_pack_p = true;
3930 break;
3932 case VAR_DECL:
3933 if (DECL_PACK_P (t))
3935 /* We don't want to walk into the type of a variadic capture proxy,
3936 because we don't want to see the type parameter pack. */
3937 *walk_subtrees = 0;
3938 parameter_pack_p = true;
3940 else if (variable_template_specialization_p (t))
3942 cp_walk_tree (&DECL_TI_ARGS (t),
3943 find_parameter_packs_r,
3944 ppd, ppd->visited);
3945 *walk_subtrees = 0;
3947 break;
3949 case CALL_EXPR:
3950 if (builtin_pack_call_p (t))
3951 parameter_pack_p = true;
3952 break;
3954 case BASES:
3955 parameter_pack_p = true;
3956 break;
3957 default:
3958 /* Not a parameter pack. */
3959 break;
3962 if (parameter_pack_p)
3964 /* Add this parameter pack to the list. */
3965 *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
3968 if (has_extra_args_mechanism_p (t) && !PACK_EXPANSION_P (t))
3969 ppd->found_extra_args_tree_p = true;
3971 if (TYPE_P (t))
3972 cp_walk_tree (&TYPE_CONTEXT (t),
3973 &find_parameter_packs_r, ppd, ppd->visited);
3975 /* This switch statement will return immediately if we don't find a
3976 parameter pack. ??? Should some of these be in cp_walk_subtrees? */
3977 switch (TREE_CODE (t))
3979 case BOUND_TEMPLATE_TEMPLATE_PARM:
3980 /* Check the template itself. */
3981 cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)),
3982 &find_parameter_packs_r, ppd, ppd->visited);
3983 return NULL_TREE;
3985 case DECL_EXPR:
3987 tree decl = DECL_EXPR_DECL (t);
3988 /* Ignore the declaration of a capture proxy for a parameter pack. */
3989 if (is_capture_proxy (decl))
3990 *walk_subtrees = 0;
3991 if (is_typedef_decl (decl))
3992 /* Since we stop at typedefs above, we need to look through them at
3993 the point of the DECL_EXPR. */
3994 cp_walk_tree (&DECL_ORIGINAL_TYPE (decl),
3995 &find_parameter_packs_r, ppd, ppd->visited);
3996 return NULL_TREE;
3999 case TEMPLATE_DECL:
4000 if (!DECL_TEMPLATE_TEMPLATE_PARM_P (t))
4001 return NULL_TREE;
4002 cp_walk_tree (&TREE_TYPE (t),
4003 &find_parameter_packs_r, ppd, ppd->visited);
4004 return NULL_TREE;
4006 case TYPE_PACK_EXPANSION:
4007 case EXPR_PACK_EXPANSION:
4008 *walk_subtrees = 0;
4009 return NULL_TREE;
4011 case INTEGER_TYPE:
4012 cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r,
4013 ppd, ppd->visited);
4014 *walk_subtrees = 0;
4015 return NULL_TREE;
4017 case IDENTIFIER_NODE:
4018 cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd,
4019 ppd->visited);
4020 *walk_subtrees = 0;
4021 return NULL_TREE;
4023 case LAMBDA_EXPR:
4025 /* Since we defer implicit capture, look in the parms and body. */
4026 tree fn = lambda_function (t);
4027 cp_walk_tree (&TREE_TYPE (fn), &find_parameter_packs_r, ppd,
4028 ppd->visited);
4029 cp_walk_tree (&DECL_SAVED_TREE (fn), &find_parameter_packs_r, ppd,
4030 ppd->visited);
4031 return NULL_TREE;
4034 case DECLTYPE_TYPE:
4036 /* When traversing a DECLTYPE_TYPE_EXPR, we need to set
4037 type_pack_expansion_p to false so that any placeholders
4038 within the expression don't get marked as parameter packs. */
4039 bool type_pack_expansion_p = ppd->type_pack_expansion_p;
4040 ppd->type_pack_expansion_p = false;
4041 cp_walk_tree (&DECLTYPE_TYPE_EXPR (t), &find_parameter_packs_r,
4042 ppd, ppd->visited);
4043 ppd->type_pack_expansion_p = type_pack_expansion_p;
4044 *walk_subtrees = 0;
4045 return NULL_TREE;
4048 case IF_STMT:
4049 cp_walk_tree (&IF_COND (t), &find_parameter_packs_r,
4050 ppd, ppd->visited);
4051 cp_walk_tree (&THEN_CLAUSE (t), &find_parameter_packs_r,
4052 ppd, ppd->visited);
4053 cp_walk_tree (&ELSE_CLAUSE (t), &find_parameter_packs_r,
4054 ppd, ppd->visited);
4055 /* Don't walk into IF_STMT_EXTRA_ARGS. */
4056 *walk_subtrees = 0;
4057 return NULL_TREE;
4059 case TAG_DEFN:
4060 t = TREE_TYPE (t);
4061 if (CLASS_TYPE_P (t))
4063 /* Local class, need to look through the whole definition.
4064 TYPE_BINFO might be unset for a partial instantiation. */
4065 if (TYPE_BINFO (t))
4066 for (tree bb : BINFO_BASE_BINFOS (TYPE_BINFO (t)))
4067 cp_walk_tree (&BINFO_TYPE (bb), &find_parameter_packs_r,
4068 ppd, ppd->visited);
4070 else
4071 /* Enum, look at the values. */
4072 for (tree l = TYPE_VALUES (t); l; l = TREE_CHAIN (l))
4073 cp_walk_tree (&DECL_INITIAL (TREE_VALUE (l)),
4074 &find_parameter_packs_r,
4075 ppd, ppd->visited);
4076 return NULL_TREE;
4078 case FUNCTION_TYPE:
4079 case METHOD_TYPE:
4080 WALK_SUBTREE (TYPE_RAISES_EXCEPTIONS (t));
4081 break;
4083 default:
4084 return NULL_TREE;
4087 #undef WALK_SUBTREE
4089 return NULL_TREE;
4092 /* Determines if the expression or type T uses any parameter packs. */
4093 tree
4094 uses_parameter_packs (tree t)
4096 tree parameter_packs = NULL_TREE;
4097 struct find_parameter_pack_data ppd;
4098 ppd.parameter_packs = &parameter_packs;
4099 ppd.visited = new hash_set<tree>;
4100 ppd.type_pack_expansion_p = false;
4101 cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4102 delete ppd.visited;
4103 return parameter_packs;
4106 /* Turn ARG, which may be an expression, type, or a TREE_LIST
4107 representation a base-class initializer into a parameter pack
4108 expansion. If all goes well, the resulting node will be an
4109 EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
4110 respectively. */
4111 tree
4112 make_pack_expansion (tree arg, tsubst_flags_t complain)
4114 tree result;
4115 tree parameter_packs = NULL_TREE;
4116 bool for_types = false;
4117 struct find_parameter_pack_data ppd;
4119 if (!arg || arg == error_mark_node)
4120 return arg;
4122 if (TREE_CODE (arg) == TREE_LIST && TREE_PURPOSE (arg))
4124 /* A TREE_LIST with a non-null TREE_PURPOSE is for a base
4125 class initializer. In this case, the TREE_PURPOSE will be a
4126 _TYPE node (representing the base class expansion we're
4127 initializing) and the TREE_VALUE will be a TREE_LIST
4128 containing the initialization arguments.
4130 The resulting expansion looks somewhat different from most
4131 expansions. Rather than returning just one _EXPANSION, we
4132 return a TREE_LIST whose TREE_PURPOSE is a
4133 TYPE_PACK_EXPANSION containing the bases that will be
4134 initialized. The TREE_VALUE will be identical to the
4135 original TREE_VALUE, which is a list of arguments that will
4136 be passed to each base. We do not introduce any new pack
4137 expansion nodes into the TREE_VALUE (although it is possible
4138 that some already exist), because the TREE_PURPOSE and
4139 TREE_VALUE all need to be expanded together with the same
4140 _EXPANSION node. Note that the TYPE_PACK_EXPANSION in the
4141 resulting TREE_PURPOSE will mention the parameter packs in
4142 both the bases and the arguments to the bases. */
4143 tree purpose;
4144 tree value;
4145 tree parameter_packs = NULL_TREE;
4147 /* Determine which parameter packs will be used by the base
4148 class expansion. */
4149 ppd.visited = new hash_set<tree>;
4150 ppd.parameter_packs = &parameter_packs;
4151 ppd.type_pack_expansion_p = false;
4152 gcc_assert (TYPE_P (TREE_PURPOSE (arg)));
4153 cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r,
4154 &ppd, ppd.visited);
4156 if (parameter_packs == NULL_TREE)
4158 if (complain & tf_error)
4159 error ("base initializer expansion %qT contains no parameter packs",
4160 arg);
4161 delete ppd.visited;
4162 return error_mark_node;
4165 if (TREE_VALUE (arg) != void_type_node)
4167 /* Collect the sets of parameter packs used in each of the
4168 initialization arguments. */
4169 for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
4171 /* Determine which parameter packs will be expanded in this
4172 argument. */
4173 cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r,
4174 &ppd, ppd.visited);
4178 delete ppd.visited;
4180 /* Create the pack expansion type for the base type. */
4181 purpose = cxx_make_type (TYPE_PACK_EXPANSION);
4182 PACK_EXPANSION_PATTERN (purpose) = TREE_PURPOSE (arg);
4183 PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
4184 PACK_EXPANSION_LOCAL_P (purpose) = at_function_scope_p ();
4186 /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4187 they will rarely be compared to anything. */
4188 SET_TYPE_STRUCTURAL_EQUALITY (purpose);
4190 return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
4193 if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
4194 for_types = true;
4196 /* Build the PACK_EXPANSION_* node. */
4197 result = for_types
4198 ? cxx_make_type (TYPE_PACK_EXPANSION)
4199 : make_node (EXPR_PACK_EXPANSION);
4200 PACK_EXPANSION_PATTERN (result) = arg;
4201 if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
4203 /* Propagate type and const-expression information. */
4204 TREE_TYPE (result) = TREE_TYPE (arg);
4205 TREE_CONSTANT (result) = TREE_CONSTANT (arg);
4206 /* Mark this read now, since the expansion might be length 0. */
4207 mark_exp_read (arg);
4209 else
4210 /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4211 they will rarely be compared to anything. */
4212 SET_TYPE_STRUCTURAL_EQUALITY (result);
4214 /* Determine which parameter packs will be expanded. */
4215 ppd.parameter_packs = &parameter_packs;
4216 ppd.visited = new hash_set<tree>;
4217 ppd.type_pack_expansion_p = TYPE_P (arg);
4218 cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
4219 delete ppd.visited;
4221 /* Make sure we found some parameter packs. */
4222 if (parameter_packs == NULL_TREE)
4224 if (complain & tf_error)
4226 if (TYPE_P (arg))
4227 error ("expansion pattern %qT contains no parameter packs", arg);
4228 else
4229 error ("expansion pattern %qE contains no parameter packs", arg);
4231 return error_mark_node;
4233 PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
4235 PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
4236 if (ppd.found_extra_args_tree_p)
4237 /* If the pattern of this pack expansion contains a subtree that has
4238 the extra args mechanism for avoiding partial instantiation, then
4239 force this pack expansion to also use extra args. Otherwise
4240 partial instantiation of this pack expansion may not lower the
4241 level of some parameter packs within the pattern, which would
4242 confuse tsubst_pack_expansion later (PR101764). */
4243 PACK_EXPANSION_FORCE_EXTRA_ARGS_P (result) = true;
4245 return result;
4248 /* Checks T for any "bare" parameter packs, which have not yet been
4249 expanded, and issues an error if any are found. This operation can
4250 only be done on full expressions or types (e.g., an expression
4251 statement, "if" condition, etc.), because we could have expressions like:
4253 foo(f(g(h(args)))...)
4255 where "args" is a parameter pack. check_for_bare_parameter_packs
4256 should not be called for the subexpressions args, h(args),
4257 g(h(args)), or f(g(h(args))), because we would produce erroneous
4258 error messages.
4260 Returns TRUE and emits an error if there were bare parameter packs,
4261 returns FALSE otherwise. */
4262 bool
4263 check_for_bare_parameter_packs (tree t, location_t loc /* = UNKNOWN_LOCATION */)
4265 tree parameter_packs = NULL_TREE;
4266 struct find_parameter_pack_data ppd;
4268 if (!processing_template_decl || !t || t == error_mark_node)
4269 return false;
4271 if (TREE_CODE (t) == TYPE_DECL)
4272 t = TREE_TYPE (t);
4274 ppd.parameter_packs = &parameter_packs;
4275 ppd.visited = new hash_set<tree>;
4276 ppd.type_pack_expansion_p = false;
4277 cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4278 delete ppd.visited;
4280 if (!parameter_packs)
4281 return false;
4283 if (loc == UNKNOWN_LOCATION)
4284 loc = cp_expr_loc_or_input_loc (t);
4286 /* It's OK for a lambda to have an unexpanded parameter pack from the
4287 containing context, but do complain about unexpanded capture packs. */
4288 tree lam = current_lambda_expr ();
4289 if (lam)
4290 lam = TREE_TYPE (lam);
4292 if (lam && lam != current_class_type)
4294 /* We're in a lambda, but it isn't the innermost class.
4295 This should work, but currently doesn't. */
4296 sorry_at (loc, "unexpanded parameter pack in local class in lambda");
4297 return true;
4300 if (lam && CLASSTYPE_TEMPLATE_INFO (lam))
4301 for (; parameter_packs;
4302 parameter_packs = TREE_CHAIN (parameter_packs))
4304 tree pack = TREE_VALUE (parameter_packs);
4305 if (is_capture_proxy (pack)
4306 || (TREE_CODE (pack) == PARM_DECL
4307 && DECL_CONTEXT (DECL_CONTEXT (pack)) == lam))
4308 break;
4311 if (parameter_packs)
4313 error_at (loc, "parameter packs not expanded with %<...%>:");
4314 while (parameter_packs)
4316 tree pack = TREE_VALUE (parameter_packs);
4317 tree name = NULL_TREE;
4319 if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
4320 || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
4321 name = TYPE_NAME (pack);
4322 else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
4323 name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
4324 else if (TREE_CODE (pack) == CALL_EXPR)
4325 name = DECL_NAME (CALL_EXPR_FN (pack));
4326 else
4327 name = DECL_NAME (pack);
4329 if (name)
4330 inform (loc, " %qD", name);
4331 else
4332 inform (loc, " %s", "<anonymous>");
4334 parameter_packs = TREE_CHAIN (parameter_packs);
4337 return true;
4340 return false;
4343 /* Expand any parameter packs that occur in the template arguments in
4344 ARGS. */
4345 tree
4346 expand_template_argument_pack (tree args)
4348 if (args == error_mark_node)
4349 return error_mark_node;
4351 tree result_args = NULL_TREE;
4352 int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
4353 int num_result_args = -1;
4354 int non_default_args_count = -1;
4356 /* First, determine if we need to expand anything, and the number of
4357 slots we'll need. */
4358 for (in_arg = 0; in_arg < nargs; ++in_arg)
4360 tree arg = TREE_VEC_ELT (args, in_arg);
4361 if (arg == NULL_TREE)
4362 return args;
4363 if (ARGUMENT_PACK_P (arg))
4365 int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
4366 if (num_result_args < 0)
4367 num_result_args = in_arg + num_packed;
4368 else
4369 num_result_args += num_packed;
4371 else
4373 if (num_result_args >= 0)
4374 num_result_args++;
4378 /* If no expansion is necessary, we're done. */
4379 if (num_result_args < 0)
4380 return args;
4382 /* Expand arguments. */
4383 result_args = make_tree_vec (num_result_args);
4384 if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
4385 non_default_args_count =
4386 GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
4387 for (in_arg = 0; in_arg < nargs; ++in_arg)
4389 tree arg = TREE_VEC_ELT (args, in_arg);
4390 if (ARGUMENT_PACK_P (arg))
4392 tree packed = ARGUMENT_PACK_ARGS (arg);
4393 int i, num_packed = TREE_VEC_LENGTH (packed);
4394 for (i = 0; i < num_packed; ++i, ++out_arg)
4395 TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
4396 if (non_default_args_count > 0)
4397 non_default_args_count += num_packed - 1;
4399 else
4401 TREE_VEC_ELT (result_args, out_arg) = arg;
4402 ++out_arg;
4405 if (non_default_args_count >= 0)
4406 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
4407 return result_args;
4410 /* Checks if DECL shadows a template parameter.
4412 [temp.local]: A template-parameter shall not be redeclared within its
4413 scope (including nested scopes).
4415 Emits an error and returns TRUE if the DECL shadows a parameter,
4416 returns FALSE otherwise. */
4418 bool
4419 check_template_shadow (tree decl)
4421 tree olddecl;
4423 /* If we're not in a template, we can't possibly shadow a template
4424 parameter. */
4425 if (!current_template_parms)
4426 return true;
4428 /* Figure out what we're shadowing. */
4429 decl = OVL_FIRST (decl);
4430 olddecl = innermost_non_namespace_value (DECL_NAME (decl));
4432 /* If there's no previous binding for this name, we're not shadowing
4433 anything, let alone a template parameter. */
4434 if (!olddecl)
4435 return true;
4437 /* If we're not shadowing a template parameter, we're done. Note
4438 that OLDDECL might be an OVERLOAD (or perhaps even an
4439 ERROR_MARK), so we can't just blithely assume it to be a _DECL
4440 node. */
4441 if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
4442 return true;
4444 /* We check for decl != olddecl to avoid bogus errors for using a
4445 name inside a class. We check TPFI to avoid duplicate errors for
4446 inline member templates. */
4447 if (decl == olddecl
4448 || (DECL_TEMPLATE_PARM_P (decl)
4449 && TEMPLATE_PARMS_FOR_INLINE (current_template_parms)))
4450 return true;
4452 /* Don't complain about the injected class name, as we've already
4453 complained about the class itself. */
4454 if (DECL_SELF_REFERENCE_P (decl))
4455 return false;
4457 if (DECL_TEMPLATE_PARM_P (decl))
4458 error ("declaration of template parameter %q+D shadows "
4459 "template parameter", decl);
4460 else
4461 error ("declaration of %q+#D shadows template parameter", decl);
4462 inform (DECL_SOURCE_LOCATION (olddecl),
4463 "template parameter %qD declared here", olddecl);
4464 return false;
4467 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
4468 ORIG_LEVEL, DECL, and TYPE. */
4470 static tree
4471 build_template_parm_index (int index,
4472 int level,
4473 int orig_level,
4474 tree decl,
4475 tree type)
4477 tree t = make_node (TEMPLATE_PARM_INDEX);
4478 TEMPLATE_PARM_IDX (t) = index;
4479 TEMPLATE_PARM_LEVEL (t) = level;
4480 TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
4481 TEMPLATE_PARM_DECL (t) = decl;
4482 TREE_TYPE (t) = type;
4483 TREE_CONSTANT (t) = TREE_CONSTANT (decl);
4484 TREE_READONLY (t) = TREE_READONLY (decl);
4486 return t;
4489 struct ctp_hasher : ggc_ptr_hash<tree_node>
4491 static hashval_t hash (tree t)
4493 ++comparing_specializations;
4494 tree_code code = TREE_CODE (t);
4495 hashval_t val = iterative_hash_object (code, 0);
4496 val = iterative_hash_object (TEMPLATE_TYPE_LEVEL (t), val);
4497 val = iterative_hash_object (TEMPLATE_TYPE_IDX (t), val);
4498 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
4499 val = iterative_hash_template_arg (TYPE_TI_ARGS (t), val);
4500 --comparing_specializations;
4501 return val;
4504 static bool equal (tree t, tree u)
4506 ++comparing_specializations;
4507 bool eq = comptypes (t, u, COMPARE_STRUCTURAL);
4508 --comparing_specializations;
4509 return eq;
4513 static GTY (()) hash_table<ctp_hasher> *ctp_table;
4515 /* Find the canonical type parameter for the given template type
4516 parameter. Returns the canonical type parameter, which may be TYPE
4517 if no such parameter existed. */
4519 tree
4520 canonical_type_parameter (tree type)
4522 if (ctp_table == NULL)
4523 ctp_table = hash_table<ctp_hasher>::create_ggc (61);
4525 tree& slot = *ctp_table->find_slot (type, INSERT);
4526 if (slot == NULL_TREE)
4527 slot = type;
4528 return slot;
4531 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
4532 TEMPLATE_PARM_LEVEL has been decreased by LEVELS. If such a
4533 TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
4534 new one is created. */
4536 static tree
4537 reduce_template_parm_level (tree index, tree type, int levels, tree args,
4538 tsubst_flags_t complain)
4540 if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
4541 || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
4542 != TEMPLATE_PARM_LEVEL (index) - levels)
4543 || !(TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM
4544 ? (comp_template_parms
4545 (DECL_TEMPLATE_PARMS (TYPE_NAME (type)),
4546 DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL
4547 (TEMPLATE_PARM_DESCENDANTS (index)))))
4548 : same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index)))))
4550 tree orig_decl = TEMPLATE_PARM_DECL (index);
4552 tree decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
4553 TREE_CODE (orig_decl), DECL_NAME (orig_decl),
4554 type);
4555 TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
4556 TREE_READONLY (decl) = TREE_READONLY (orig_decl);
4557 DECL_VIRTUAL_P (decl) = DECL_VIRTUAL_P (orig_decl);
4558 DECL_ARTIFICIAL (decl) = 1;
4559 SET_DECL_TEMPLATE_PARM_P (decl);
4561 tree tpi = build_template_parm_index (TEMPLATE_PARM_IDX (index),
4562 TEMPLATE_PARM_LEVEL (index) - levels,
4563 TEMPLATE_PARM_ORIG_LEVEL (index),
4564 decl, type);
4565 TEMPLATE_PARM_DESCENDANTS (index) = tpi;
4566 TEMPLATE_PARM_PARAMETER_PACK (tpi)
4567 = TEMPLATE_PARM_PARAMETER_PACK (index);
4569 /* Template template parameters need this. */
4570 tree inner = decl;
4571 if (TREE_CODE (decl) == TEMPLATE_DECL)
4573 inner = build_decl (DECL_SOURCE_LOCATION (decl),
4574 TYPE_DECL, DECL_NAME (decl), type);
4575 DECL_TEMPLATE_RESULT (decl) = inner;
4576 DECL_ARTIFICIAL (inner) = true;
4577 DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
4578 (DECL_TEMPLATE_PARMS (orig_decl), args, complain);
4581 /* Attach the TPI to the decl. */
4582 if (TREE_CODE (inner) == TYPE_DECL)
4583 TEMPLATE_TYPE_PARM_INDEX (type) = tpi;
4584 else
4585 DECL_INITIAL (decl) = tpi;
4588 return TEMPLATE_PARM_DESCENDANTS (index);
4591 /* Process information from new template parameter PARM and append it
4592 to the LIST being built. This new parameter is a non-type
4593 parameter iff IS_NON_TYPE is true. This new parameter is a
4594 parameter pack iff IS_PARAMETER_PACK is true. The location of PARM
4595 is in PARM_LOC. */
4597 tree
4598 process_template_parm (tree list, location_t parm_loc, tree parm,
4599 bool is_non_type, bool is_parameter_pack)
4601 gcc_assert (TREE_CODE (parm) == TREE_LIST);
4602 tree prev = NULL_TREE;
4603 int idx = 0;
4605 if (list)
4607 prev = tree_last (list);
4609 tree p = TREE_VALUE (prev);
4610 if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
4611 idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
4612 else if (TREE_CODE (p) == PARM_DECL)
4613 idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
4615 ++idx;
4618 tree decl = NULL_TREE;
4619 tree defval = TREE_PURPOSE (parm);
4620 tree constr = TREE_TYPE (parm);
4622 if (is_non_type)
4624 parm = TREE_VALUE (parm);
4626 SET_DECL_TEMPLATE_PARM_P (parm);
4628 if (TREE_TYPE (parm) != error_mark_node)
4630 /* [temp.param]
4632 The top-level cv-qualifiers on the template-parameter are
4633 ignored when determining its type. */
4634 TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
4635 if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
4636 TREE_TYPE (parm) = error_mark_node;
4637 else if (uses_parameter_packs (TREE_TYPE (parm))
4638 && !is_parameter_pack
4639 /* If we're in a nested template parameter list, the template
4640 template parameter could be a parameter pack. */
4641 && processing_template_parmlist == 1)
4643 /* This template parameter is not a parameter pack, but it
4644 should be. Complain about "bare" parameter packs. */
4645 check_for_bare_parameter_packs (TREE_TYPE (parm));
4647 /* Recover by calling this a parameter pack. */
4648 is_parameter_pack = true;
4652 /* A template parameter is not modifiable. */
4653 TREE_CONSTANT (parm) = 1;
4654 TREE_READONLY (parm) = 1;
4655 decl = build_decl (parm_loc,
4656 CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
4657 TREE_CONSTANT (decl) = 1;
4658 TREE_READONLY (decl) = 1;
4659 DECL_INITIAL (parm) = DECL_INITIAL (decl)
4660 = build_template_parm_index (idx, current_template_depth,
4661 current_template_depth,
4662 decl, TREE_TYPE (parm));
4664 TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4665 = is_parameter_pack;
4667 else
4669 tree t;
4670 parm = TREE_VALUE (TREE_VALUE (parm));
4672 if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
4674 t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
4675 /* This is for distinguishing between real templates and template
4676 template parameters */
4677 TREE_TYPE (parm) = t;
4679 /* any_template_parm_r expects to be able to get the targs of a
4680 DECL_TEMPLATE_RESULT. */
4681 tree result = DECL_TEMPLATE_RESULT (parm);
4682 TREE_TYPE (result) = t;
4683 tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (parm));
4684 tree tinfo = build_template_info (parm, args);
4685 retrofit_lang_decl (result);
4686 DECL_TEMPLATE_INFO (result) = tinfo;
4688 decl = parm;
4690 else
4692 t = cxx_make_type (TEMPLATE_TYPE_PARM);
4693 /* parm is either IDENTIFIER_NODE or NULL_TREE. */
4694 decl = build_decl (parm_loc,
4695 TYPE_DECL, parm, t);
4698 TYPE_NAME (t) = decl;
4699 TYPE_STUB_DECL (t) = decl;
4700 parm = decl;
4701 TEMPLATE_TYPE_PARM_INDEX (t)
4702 = build_template_parm_index (idx, current_template_depth,
4703 current_template_depth,
4704 decl, TREE_TYPE (parm));
4705 TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
4706 TYPE_CANONICAL (t) = canonical_type_parameter (t);
4708 DECL_ARTIFICIAL (decl) = 1;
4709 SET_DECL_TEMPLATE_PARM_P (decl);
4711 /* Build requirements for the type/template parameter.
4712 This must be done after SET_DECL_TEMPLATE_PARM_P or
4713 process_template_parm could fail. */
4714 tree reqs = finish_shorthand_constraint (parm, constr);
4716 decl = pushdecl (decl);
4717 if (!is_non_type)
4718 parm = decl;
4720 /* Build the parameter node linking the parameter declaration,
4721 its default argument (if any), and its constraints (if any). */
4722 parm = build_tree_list (defval, parm);
4723 TEMPLATE_PARM_CONSTRAINTS (parm) = reqs;
4725 if (prev)
4726 TREE_CHAIN (prev) = parm;
4727 else
4728 list = parm;
4730 return list;
4733 /* The end of a template parameter list has been reached. Process the
4734 tree list into a parameter vector, converting each parameter into a more
4735 useful form. Type parameters are saved as IDENTIFIER_NODEs, and others
4736 as PARM_DECLs. */
4738 tree
4739 end_template_parm_list (tree parms)
4741 tree saved_parmlist = make_tree_vec (list_length (parms));
4743 /* Pop the dummy parameter level and add the real one. We do not
4744 morph the dummy parameter in place, as it might have been
4745 captured by a (nested) template-template-parm. */
4746 current_template_parms = TREE_CHAIN (current_template_parms);
4748 current_template_parms
4749 = tree_cons (size_int (current_template_depth + 1),
4750 saved_parmlist, current_template_parms);
4752 for (unsigned ix = 0; parms; ix++)
4754 tree parm = parms;
4755 parms = TREE_CHAIN (parms);
4756 TREE_CHAIN (parm) = NULL_TREE;
4758 TREE_VEC_ELT (saved_parmlist, ix) = parm;
4761 --processing_template_parmlist;
4763 return saved_parmlist;
4766 // Explicitly indicate the end of the template parameter list. We assume
4767 // that the current template parameters have been constructed and/or
4768 // managed explicitly, as when creating new template template parameters
4769 // from a shorthand constraint.
4770 void
4771 end_template_parm_list ()
4773 --processing_template_parmlist;
4776 /* end_template_decl is called after a template declaration is seen. */
4778 void
4779 end_template_decl (void)
4781 reset_specialization ();
4783 if (! processing_template_decl)
4784 return;
4786 /* This matches the pushlevel in begin_template_parm_list. */
4787 finish_scope ();
4789 --processing_template_decl;
4790 current_template_parms = TREE_CHAIN (current_template_parms);
4793 /* Takes a TEMPLATE_PARM_P or DECL_TEMPLATE_PARM_P node or a TREE_LIST
4794 thereof, and converts it into an argument suitable to be passed to
4795 the type substitution functions. Note that if the TREE_LIST contains
4796 an error_mark node, the returned argument is error_mark_node. */
4798 tree
4799 template_parm_to_arg (tree t)
4801 if (!t)
4802 return NULL_TREE;
4804 if (TREE_CODE (t) == TREE_LIST)
4805 t = TREE_VALUE (t);
4807 if (error_operand_p (t))
4808 return error_mark_node;
4810 if (DECL_P (t) && DECL_TEMPLATE_PARM_P (t))
4812 if (TREE_CODE (t) == TYPE_DECL
4813 || TREE_CODE (t) == TEMPLATE_DECL)
4814 t = TREE_TYPE (t);
4815 else
4816 t = DECL_INITIAL (t);
4819 gcc_assert (TEMPLATE_PARM_P (t));
4821 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
4822 || TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
4824 if (TEMPLATE_TYPE_PARAMETER_PACK (t))
4826 /* Turn this argument into a TYPE_ARGUMENT_PACK
4827 with a single element, which expands T. */
4828 tree vec = make_tree_vec (1);
4829 if (CHECKING_P)
4830 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4832 TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4834 t = cxx_make_type (TYPE_ARGUMENT_PACK);
4835 ARGUMENT_PACK_ARGS (t) = vec;
4838 else
4840 if (TEMPLATE_PARM_PARAMETER_PACK (t))
4842 /* Turn this argument into a NONTYPE_ARGUMENT_PACK
4843 with a single element, which expands T. */
4844 tree vec = make_tree_vec (1);
4845 if (CHECKING_P)
4846 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4848 t = convert_from_reference (t);
4849 TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4851 t = make_node (NONTYPE_ARGUMENT_PACK);
4852 ARGUMENT_PACK_ARGS (t) = vec;
4854 else
4855 t = convert_from_reference (t);
4857 return t;
4860 /* If T looks like a generic template argument produced by template_parm_to_arg,
4861 return the corresponding template parameter, otherwise return NULL_TREE. */
4863 static tree
4864 template_arg_to_parm (tree t)
4866 if (t == NULL_TREE)
4867 return NULL_TREE;
4869 if (ARGUMENT_PACK_P (t))
4871 tree args = ARGUMENT_PACK_ARGS (t);
4872 if (TREE_VEC_LENGTH (args) == 1
4873 && PACK_EXPANSION_P (TREE_VEC_ELT (args, 0)))
4874 t = PACK_EXPANSION_PATTERN (TREE_VEC_ELT (args, 0));
4877 if (REFERENCE_REF_P (t))
4878 t = TREE_OPERAND (t, 0);
4880 if (TEMPLATE_PARM_P (t))
4881 return t;
4882 else
4883 return NULL_TREE;
4886 /* Given a single level of template parameters (a TREE_VEC), return it
4887 as a set of template arguments. */
4889 tree
4890 template_parms_level_to_args (tree parms)
4892 parms = copy_node (parms);
4893 TREE_TYPE (parms) = NULL_TREE;
4894 for (tree& parm : tree_vec_range (parms))
4895 parm = template_parm_to_arg (parm);
4897 if (CHECKING_P)
4898 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (parms, TREE_VEC_LENGTH (parms));
4900 return parms;
4903 /* Given a set of template parameters, return them as a set of template
4904 arguments. The template parameters are represented as a TREE_VEC, in
4905 the form documented in cp-tree.h for template arguments. */
4907 tree
4908 template_parms_to_args (tree parms)
4910 tree header;
4911 tree args = NULL_TREE;
4912 int length = TMPL_PARMS_DEPTH (parms);
4913 int l = length;
4915 /* If there is only one level of template parameters, we do not
4916 create a TREE_VEC of TREE_VECs. Instead, we return a single
4917 TREE_VEC containing the arguments. */
4918 if (length > 1)
4919 args = make_tree_vec (length);
4921 for (header = parms; header; header = TREE_CHAIN (header))
4923 tree a = template_parms_level_to_args (TREE_VALUE (header));
4925 if (length > 1)
4926 TREE_VEC_ELT (args, --l) = a;
4927 else
4928 args = a;
4931 return args;
4934 /* Within the declaration of a template, return the currently active
4935 template parameters as an argument TREE_VEC. */
4937 static tree
4938 current_template_args (void)
4940 return template_parms_to_args (current_template_parms);
4943 /* Return the fully generic arguments for of TMPL, i.e. what
4944 current_template_args would be while parsing it. */
4946 tree
4947 generic_targs_for (tree tmpl)
4949 if (tmpl == NULL_TREE)
4950 return NULL_TREE;
4951 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
4952 || DECL_TEMPLATE_SPECIALIZATION (tmpl))
4953 /* DECL_TEMPLATE_RESULT doesn't have the arguments we want. For a template
4954 template parameter, it has no TEMPLATE_INFO; for a partial
4955 specialization, it has the arguments for the primary template, and we
4956 want the arguments for the partial specialization. */;
4957 else if (tree result = DECL_TEMPLATE_RESULT (tmpl))
4958 if (tree ti = get_template_info (result))
4959 return TI_ARGS (ti);
4960 return template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl));
4963 /* Return the template arguments corresponding to the template parameters of
4964 TMPL's enclosing scope. When TMPL is a member of a partial specialization,
4965 this returns the arguments for the partial specialization as opposed to those
4966 for the primary template, which is the main difference between this function
4967 and simply using e.g. the TYPE_TI_ARGS of TMPL's DECL_CONTEXT. */
4969 tree
4970 outer_template_args (tree tmpl)
4972 tree ti = get_template_info (DECL_TEMPLATE_RESULT (tmpl));
4973 if (!ti)
4974 return NULL_TREE;
4975 tree args = TI_ARGS (ti);
4976 if (!PRIMARY_TEMPLATE_P (tmpl))
4977 return args;
4978 if (TMPL_ARGS_DEPTH (args) == 1)
4979 return NULL_TREE;
4980 return strip_innermost_template_args (args, 1);
4983 /* Update the declared TYPE by doing any lookups which were thought to be
4984 dependent, but are not now that we know the SCOPE of the declarator. */
4986 tree
4987 maybe_update_decl_type (tree orig_type, tree scope)
4989 tree type = orig_type;
4991 if (type == NULL_TREE)
4992 return type;
4994 if (TREE_CODE (orig_type) == TYPE_DECL)
4995 type = TREE_TYPE (type);
4997 if (scope && TYPE_P (scope) && dependent_type_p (scope)
4998 && dependent_type_p (type)
4999 /* Don't bother building up the args in this case. */
5000 && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
5002 /* tsubst in the args corresponding to the template parameters,
5003 including auto if present. Most things will be unchanged, but
5004 make_typename_type and tsubst_qualified_id will resolve
5005 TYPENAME_TYPEs and SCOPE_REFs that were previously dependent. */
5006 tree args = current_template_args ();
5007 tree auto_node = type_uses_auto (type);
5008 tree pushed;
5009 if (auto_node)
5011 tree auto_vec = make_tree_vec (1);
5012 TREE_VEC_ELT (auto_vec, 0) = auto_node;
5013 args = add_to_template_args (args, auto_vec);
5015 pushed = push_scope (scope);
5016 type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
5017 if (pushed)
5018 pop_scope (scope);
5021 if (type == error_mark_node)
5022 return orig_type;
5024 if (TREE_CODE (orig_type) == TYPE_DECL)
5026 if (same_type_p (type, TREE_TYPE (orig_type)))
5027 type = orig_type;
5028 else
5029 type = TYPE_NAME (type);
5031 return type;
5034 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
5035 template PARMS and constraints, CONSTR. If MEMBER_TEMPLATE_P is true,
5036 the new template is a member template. */
5038 static tree
5039 build_template_decl (tree decl, tree parms, bool member_template_p)
5041 gcc_checking_assert (TREE_CODE (decl) != TEMPLATE_DECL);
5043 tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
5044 SET_DECL_LANGUAGE (tmpl, DECL_LANGUAGE (decl));
5045 DECL_TEMPLATE_PARMS (tmpl) = parms;
5046 DECL_TEMPLATE_RESULT (tmpl) = decl;
5047 DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
5048 TREE_TYPE (tmpl) = TREE_TYPE (decl);
5049 DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
5050 DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
5052 /* Propagate module information from the decl. */
5053 DECL_MODULE_EXPORT_P (tmpl) = DECL_MODULE_EXPORT_P (decl);
5055 return tmpl;
5058 struct template_parm_data
5060 /* The level of the template parameters we are currently
5061 processing. */
5062 int level;
5064 /* The index of the specialization argument we are currently
5065 processing. */
5066 int current_arg;
5068 /* An array whose size is the number of template parameters. The
5069 elements are nonzero if the parameter has been used in any one
5070 of the arguments processed so far. */
5071 int* parms;
5073 /* An array whose size is the number of template arguments. The
5074 elements are nonzero if the argument makes use of template
5075 parameters of this level. */
5076 int* arg_uses_template_parms;
5079 /* Subroutine of push_template_decl used to see if each template
5080 parameter in a partial specialization is used in the explicit
5081 argument list. If T is of the LEVEL given in DATA (which is
5082 treated as a template_parm_data*), then DATA->PARMS is marked
5083 appropriately. */
5085 static int
5086 mark_template_parm (tree t, void* data)
5088 int level;
5089 int idx;
5090 struct template_parm_data* tpd = (struct template_parm_data*) data;
5092 template_parm_level_and_index (t, &level, &idx);
5094 if (level == tpd->level)
5096 tpd->parms[idx] = 1;
5097 tpd->arg_uses_template_parms[tpd->current_arg] = 1;
5100 /* In C++17 the type of a non-type argument is a deduced context. */
5101 if (cxx_dialect >= cxx17
5102 && TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5103 for_each_template_parm (TREE_TYPE (t),
5104 &mark_template_parm,
5105 data,
5106 NULL,
5107 /*include_nondeduced_p=*/false);
5109 /* Return zero so that for_each_template_parm will continue the
5110 traversal of the tree; we want to mark *every* template parm. */
5111 return 0;
5114 /* Process the partial specialization DECL. */
5116 static tree
5117 process_partial_specialization (tree decl)
5119 tree type = TREE_TYPE (decl);
5120 tree tinfo = get_template_info (decl);
5121 tree maintmpl = TI_TEMPLATE (tinfo);
5122 tree specargs = TI_ARGS (tinfo);
5123 tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
5124 tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
5125 tree inner_parms;
5126 tree inst;
5127 int nargs = TREE_VEC_LENGTH (inner_args);
5128 int ntparms;
5129 int i;
5130 bool did_error_intro = false;
5131 struct template_parm_data tpd;
5132 struct template_parm_data tpd2;
5134 gcc_assert (current_template_parms);
5136 /* A concept cannot be specialized. */
5137 if (flag_concepts && variable_concept_p (maintmpl))
5139 error ("specialization of variable concept %q#D", maintmpl);
5140 return error_mark_node;
5143 inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
5144 ntparms = TREE_VEC_LENGTH (inner_parms);
5146 /* We check that each of the template parameters given in the
5147 partial specialization is used in the argument list to the
5148 specialization. For example:
5150 template <class T> struct S;
5151 template <class T> struct S<T*>;
5153 The second declaration is OK because `T*' uses the template
5154 parameter T, whereas
5156 template <class T> struct S<int>;
5158 is no good. Even trickier is:
5160 template <class T>
5161 struct S1
5163 template <class U>
5164 struct S2;
5165 template <class U>
5166 struct S2<T>;
5169 The S2<T> declaration is actually invalid; it is a
5170 full-specialization. Of course,
5172 template <class U>
5173 struct S2<T (*)(U)>;
5175 or some such would have been OK. */
5176 tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
5177 tpd.parms = XALLOCAVEC (int, ntparms);
5178 memset (tpd.parms, 0, sizeof (int) * ntparms);
5180 tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5181 memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
5182 for (i = 0; i < nargs; ++i)
5184 tpd.current_arg = i;
5185 for_each_template_parm (TREE_VEC_ELT (inner_args, i),
5186 &mark_template_parm,
5187 &tpd,
5188 NULL,
5189 /*include_nondeduced_p=*/false);
5191 for (i = 0; i < ntparms; ++i)
5192 if (tpd.parms[i] == 0)
5194 /* One of the template parms was not used in a deduced context in the
5195 specialization. */
5196 if (!did_error_intro)
5198 error ("template parameters not deducible in "
5199 "partial specialization:");
5200 did_error_intro = true;
5203 inform (input_location, " %qD",
5204 TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
5207 if (did_error_intro)
5208 return error_mark_node;
5210 /* [temp.class.spec]
5212 The argument list of the specialization shall not be identical to
5213 the implicit argument list of the primary template. */
5214 tree main_args
5215 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
5216 if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args))
5217 && (!flag_concepts
5218 || !strictly_subsumes (current_template_constraints (), maintmpl)))
5220 if (!flag_concepts)
5221 error ("partial specialization %q+D does not specialize "
5222 "any template arguments; to define the primary template, "
5223 "remove the template argument list", decl);
5224 else
5225 error ("partial specialization %q+D does not specialize any "
5226 "template arguments and is not more constrained than "
5227 "the primary template; to define the primary template, "
5228 "remove the template argument list", decl);
5229 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5232 /* A partial specialization that replaces multiple parameters of the
5233 primary template with a pack expansion is less specialized for those
5234 parameters. */
5235 if (nargs < DECL_NTPARMS (maintmpl))
5237 error ("partial specialization is not more specialized than the "
5238 "primary template because it replaces multiple parameters "
5239 "with a pack expansion");
5240 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5241 /* Avoid crash in process_partial_specialization. */
5242 return decl;
5245 else if (nargs > DECL_NTPARMS (maintmpl))
5247 error ("too many arguments for partial specialization %qT", type);
5248 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5249 /* Avoid crash below. */
5250 return decl;
5253 /* If we aren't in a dependent class, we can actually try deduction. */
5254 else if (tpd.level == 1
5255 /* FIXME we should be able to handle a partial specialization of a
5256 partial instantiation, but currently we can't (c++/41727). */
5257 && TMPL_ARGS_DEPTH (specargs) == 1
5258 && !get_partial_spec_bindings (maintmpl, maintmpl, specargs))
5260 auto_diagnostic_group d;
5261 if (pedwarn (input_location, 0,
5262 "partial specialization %qD is not more specialized than",
5263 decl))
5264 inform (DECL_SOURCE_LOCATION (maintmpl), "primary template %qD",
5265 maintmpl);
5268 /* [temp.spec.partial]
5270 The type of a template parameter corresponding to a specialized
5271 non-type argument shall not be dependent on a parameter of the
5272 specialization.
5274 Also, we verify that pack expansions only occur at the
5275 end of the argument list. */
5276 tpd2.parms = 0;
5277 for (i = 0; i < nargs; ++i)
5279 tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
5280 tree arg = TREE_VEC_ELT (inner_args, i);
5281 tree packed_args = NULL_TREE;
5282 int j, len = 1;
5284 if (ARGUMENT_PACK_P (arg))
5286 /* Extract the arguments from the argument pack. We'll be
5287 iterating over these in the following loop. */
5288 packed_args = ARGUMENT_PACK_ARGS (arg);
5289 len = TREE_VEC_LENGTH (packed_args);
5292 for (j = 0; j < len; j++)
5294 if (packed_args)
5295 /* Get the Jth argument in the parameter pack. */
5296 arg = TREE_VEC_ELT (packed_args, j);
5298 if (PACK_EXPANSION_P (arg))
5300 /* Pack expansions must come at the end of the
5301 argument list. */
5302 if ((packed_args && j < len - 1)
5303 || (!packed_args && i < nargs - 1))
5305 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5306 error ("parameter pack argument %qE must be at the "
5307 "end of the template argument list", arg);
5308 else
5309 error ("parameter pack argument %qT must be at the "
5310 "end of the template argument list", arg);
5314 if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5315 /* We only care about the pattern. */
5316 arg = PACK_EXPANSION_PATTERN (arg);
5318 if (/* These first two lines are the `non-type' bit. */
5319 !TYPE_P (arg)
5320 && TREE_CODE (arg) != TEMPLATE_DECL
5321 /* This next two lines are the `argument expression is not just a
5322 simple identifier' condition and also the `specialized
5323 non-type argument' bit. */
5324 && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
5325 && !((REFERENCE_REF_P (arg)
5326 || TREE_CODE (arg) == VIEW_CONVERT_EXPR)
5327 && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
5329 /* Look at the corresponding template parameter,
5330 marking which template parameters its type depends
5331 upon. */
5332 tree type = TREE_TYPE (parm);
5334 if (!tpd2.parms)
5336 /* We haven't yet initialized TPD2. Do so now. */
5337 tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5338 /* The number of parameters here is the number in the
5339 main template, which, as checked in the assertion
5340 above, is NARGS. */
5341 tpd2.parms = XALLOCAVEC (int, nargs);
5342 tpd2.level =
5343 TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
5346 /* Mark the template parameters. But this time, we're
5347 looking for the template parameters of the main
5348 template, not in the specialization. */
5349 tpd2.current_arg = i;
5350 tpd2.arg_uses_template_parms[i] = 0;
5351 memset (tpd2.parms, 0, sizeof (int) * nargs);
5352 for_each_template_parm (type,
5353 &mark_template_parm,
5354 &tpd2,
5355 NULL,
5356 /*include_nondeduced_p=*/false);
5358 if (tpd2.arg_uses_template_parms [i])
5360 /* The type depended on some template parameters.
5361 If they are fully specialized in the
5362 specialization, that's OK. */
5363 int j;
5364 int count = 0;
5365 for (j = 0; j < nargs; ++j)
5366 if (tpd2.parms[j] != 0
5367 && tpd.arg_uses_template_parms [j])
5368 ++count;
5369 if (count != 0)
5370 error_n (input_location, count,
5371 "type %qT of template argument %qE depends "
5372 "on a template parameter",
5373 "type %qT of template argument %qE depends "
5374 "on template parameters",
5375 type,
5376 arg);
5382 /* We should only get here once. */
5383 if (TREE_CODE (decl) == TYPE_DECL)
5384 gcc_assert (!COMPLETE_TYPE_P (type));
5386 // Build the template decl.
5387 tree tmpl = build_template_decl (decl, current_template_parms,
5388 DECL_MEMBER_TEMPLATE_P (maintmpl));
5389 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5390 DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
5391 DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
5393 /* Give template template parms a DECL_CONTEXT of the template
5394 for which they are a parameter. */
5395 for (i = 0; i < ntparms; ++i)
5397 tree parm = TREE_VALUE (TREE_VEC_ELT (inner_parms, i));
5398 if (TREE_CODE (parm) == TEMPLATE_DECL)
5399 DECL_CONTEXT (parm) = tmpl;
5402 if (VAR_P (decl))
5403 /* We didn't register this in check_explicit_specialization so we could
5404 wait until the constraints were set. */
5405 decl = register_specialization (decl, maintmpl, specargs, false, 0);
5406 else
5407 associate_classtype_constraints (type);
5409 DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
5410 = tree_cons (specargs, tmpl,
5411 DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
5412 TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
5414 for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
5415 inst = TREE_CHAIN (inst))
5417 tree instance = TREE_VALUE (inst);
5418 if (TYPE_P (instance)
5419 ? (COMPLETE_TYPE_P (instance)
5420 && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
5421 : DECL_TEMPLATE_INSTANTIATION (instance))
5423 tree spec = most_specialized_partial_spec (instance, tf_none);
5424 tree inst_decl = (DECL_P (instance)
5425 ? instance : TYPE_NAME (instance));
5426 if (!spec)
5427 /* OK */;
5428 else if (spec == error_mark_node)
5429 permerror (input_location,
5430 "declaration of %qD ambiguates earlier template "
5431 "instantiation for %qD", decl, inst_decl);
5432 else if (TREE_VALUE (spec) == tmpl)
5433 permerror (input_location,
5434 "partial specialization of %qD after instantiation "
5435 "of %qD", decl, inst_decl);
5439 return decl;
5442 /* PARM is a template parameter of some form; return the corresponding
5443 TEMPLATE_PARM_INDEX. */
5445 static tree
5446 get_template_parm_index (tree parm)
5448 if (TREE_CODE (parm) == PARM_DECL
5449 || TREE_CODE (parm) == CONST_DECL)
5450 parm = DECL_INITIAL (parm);
5451 else if (TREE_CODE (parm) == TYPE_DECL
5452 || TREE_CODE (parm) == TEMPLATE_DECL)
5453 parm = TREE_TYPE (parm);
5454 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
5455 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM
5456 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
5457 parm = TEMPLATE_TYPE_PARM_INDEX (parm);
5458 gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
5459 return parm;
5462 /* Subroutine of fixed_parameter_pack_p below. Look for any template
5463 parameter packs used by the template parameter PARM. */
5465 static void
5466 fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
5468 /* A type parm can't refer to another parm. */
5469 if (TREE_CODE (parm) == TYPE_DECL || parm == error_mark_node)
5470 return;
5471 else if (TREE_CODE (parm) == PARM_DECL)
5473 cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
5474 ppd, ppd->visited);
5475 return;
5478 gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
5480 tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
5481 for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
5483 tree p = TREE_VALUE (TREE_VEC_ELT (vec, i));
5484 if (template_parameter_pack_p (p))
5485 /* Any packs in the type are expanded by this parameter. */;
5486 else
5487 fixed_parameter_pack_p_1 (p, ppd);
5491 /* PARM is a template parameter pack. Return any parameter packs used in
5492 its type or the type of any of its template parameters. If there are
5493 any such packs, it will be instantiated into a fixed template parameter
5494 list by partial instantiation rather than be fully deduced. */
5496 tree
5497 fixed_parameter_pack_p (tree parm)
5499 /* This can only be true in a member template. */
5500 if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
5501 return NULL_TREE;
5502 /* This can only be true for a parameter pack. */
5503 if (!template_parameter_pack_p (parm))
5504 return NULL_TREE;
5505 /* A type parm can't refer to another parm. */
5506 if (TREE_CODE (parm) == TYPE_DECL)
5507 return NULL_TREE;
5509 tree parameter_packs = NULL_TREE;
5510 struct find_parameter_pack_data ppd;
5511 ppd.parameter_packs = &parameter_packs;
5512 ppd.visited = new hash_set<tree>;
5513 ppd.type_pack_expansion_p = false;
5515 fixed_parameter_pack_p_1 (parm, &ppd);
5517 delete ppd.visited;
5518 return parameter_packs;
5521 /* Check that a template declaration's use of default arguments and
5522 parameter packs is not invalid. Here, PARMS are the template
5523 parameters. IS_PRIMARY is true if DECL is the thing declared by
5524 a primary template. IS_PARTIAL is true if DECL is a partial
5525 specialization.
5527 IS_FRIEND_DECL is nonzero if DECL is either a non-defining friend
5528 function template declaration or a friend class template
5529 declaration. In the function case, 1 indicates a declaration, 2
5530 indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
5531 emitted for extraneous default arguments.
5533 Returns TRUE if there were no errors found, FALSE otherwise. */
5535 bool
5536 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
5537 bool is_partial, int is_friend_decl)
5539 const char *msg;
5540 int last_level_to_check;
5541 tree parm_level;
5542 bool no_errors = true;
5544 /* [temp.param]
5546 A default template-argument shall not be specified in a
5547 function template declaration or a function template definition, nor
5548 in the template-parameter-list of the definition of a member of a
5549 class template. */
5551 if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
5552 || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_DECL_P (decl)))
5553 /* You can't have a function template declaration in a local
5554 scope, nor you can you define a member of a class template in a
5555 local scope. */
5556 return true;
5558 if ((TREE_CODE (decl) == TYPE_DECL
5559 && TREE_TYPE (decl)
5560 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5561 || (TREE_CODE (decl) == FUNCTION_DECL
5562 && LAMBDA_FUNCTION_P (decl)))
5563 /* A lambda doesn't have an explicit declaration; don't complain
5564 about the parms of the enclosing class. */
5565 return true;
5567 if (current_class_type
5568 && !TYPE_BEING_DEFINED (current_class_type)
5569 && DECL_LANG_SPECIFIC (decl)
5570 && DECL_DECLARES_FUNCTION_P (decl)
5571 /* If this is either a friend defined in the scope of the class
5572 or a member function. */
5573 && (DECL_FUNCTION_MEMBER_P (decl)
5574 ? same_type_p (DECL_CONTEXT (decl), current_class_type)
5575 : DECL_FRIEND_CONTEXT (decl)
5576 ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
5577 : false)
5578 /* And, if it was a member function, it really was defined in
5579 the scope of the class. */
5580 && (!DECL_FUNCTION_MEMBER_P (decl)
5581 || DECL_INITIALIZED_IN_CLASS_P (decl)))
5582 /* We already checked these parameters when the template was
5583 declared, so there's no need to do it again now. This function
5584 was defined in class scope, but we're processing its body now
5585 that the class is complete. */
5586 return true;
5588 /* Core issue 226 (C++0x only): the following only applies to class
5589 templates. */
5590 if (is_primary
5591 && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
5593 /* [temp.param]
5595 If a template-parameter has a default template-argument, all
5596 subsequent template-parameters shall have a default
5597 template-argument supplied. */
5598 for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
5600 tree inner_parms = TREE_VALUE (parm_level);
5601 int ntparms = TREE_VEC_LENGTH (inner_parms);
5602 int seen_def_arg_p = 0;
5603 int i;
5605 for (i = 0; i < ntparms; ++i)
5607 tree parm = TREE_VEC_ELT (inner_parms, i);
5609 if (parm == error_mark_node)
5610 continue;
5612 if (TREE_PURPOSE (parm))
5613 seen_def_arg_p = 1;
5614 else if (seen_def_arg_p
5615 && !template_parameter_pack_p (TREE_VALUE (parm)))
5617 error ("no default argument for %qD", TREE_VALUE (parm));
5618 /* For better subsequent error-recovery, we indicate that
5619 there should have been a default argument. */
5620 TREE_PURPOSE (parm) = error_mark_node;
5621 no_errors = false;
5623 else if (!is_partial
5624 && !is_friend_decl
5625 /* Don't complain about an enclosing partial
5626 specialization. */
5627 && parm_level == parms
5628 && (TREE_CODE (decl) == TYPE_DECL || VAR_P (decl))
5629 && i < ntparms - 1
5630 && template_parameter_pack_p (TREE_VALUE (parm))
5631 /* A fixed parameter pack will be partially
5632 instantiated into a fixed length list. */
5633 && !fixed_parameter_pack_p (TREE_VALUE (parm)))
5635 /* A primary class template, primary variable template
5636 (DR 2032), or alias template can only have one
5637 parameter pack, at the end of the template
5638 parameter list. */
5640 error ("parameter pack %q+D must be at the end of the"
5641 " template parameter list", TREE_VALUE (parm));
5643 TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
5644 = error_mark_node;
5645 no_errors = false;
5651 if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
5652 || is_partial
5653 || !is_primary
5654 || is_friend_decl)
5655 /* For an ordinary class template, default template arguments are
5656 allowed at the innermost level, e.g.:
5657 template <class T = int>
5658 struct S {};
5659 but, in a partial specialization, they're not allowed even
5660 there, as we have in [temp.class.spec]:
5662 The template parameter list of a specialization shall not
5663 contain default template argument values.
5665 So, for a partial specialization, or for a function template
5666 (in C++98/C++03), we look at all of them. */
5668 else
5669 /* But, for a primary class template that is not a partial
5670 specialization we look at all template parameters except the
5671 innermost ones. */
5672 parms = TREE_CHAIN (parms);
5674 /* Figure out what error message to issue. */
5675 if (is_friend_decl == 2)
5676 msg = G_("default template arguments may not be used in function template "
5677 "friend re-declaration");
5678 else if (is_friend_decl)
5679 msg = G_("default template arguments may not be used in template "
5680 "friend declarations");
5681 else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
5682 msg = G_("default template arguments may not be used in function templates "
5683 "without %<-std=c++11%> or %<-std=gnu++11%>");
5684 else if (is_partial)
5685 msg = G_("default template arguments may not be used in "
5686 "partial specializations");
5687 else if (current_class_type && CLASSTYPE_IS_TEMPLATE (current_class_type))
5688 msg = G_("default argument for template parameter for class enclosing %qD");
5689 else
5690 /* Per [temp.param]/9, "A default template-argument shall not be
5691 specified in the template-parameter-lists of the definition of
5692 a member of a class template that appears outside of the member's
5693 class.", thus if we aren't handling a member of a class template
5694 there is no need to examine the parameters. */
5695 return true;
5697 if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
5698 /* If we're inside a class definition, there's no need to
5699 examine the parameters to the class itself. On the one
5700 hand, they will be checked when the class is defined, and,
5701 on the other, default arguments are valid in things like:
5702 template <class T = double>
5703 struct S { template <class U> void f(U); };
5704 Here the default argument for `S' has no bearing on the
5705 declaration of `f'. */
5706 last_level_to_check = template_class_depth (current_class_type) + 1;
5707 else
5708 /* Check everything. */
5709 last_level_to_check = 0;
5711 for (parm_level = parms;
5712 parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
5713 parm_level = TREE_CHAIN (parm_level))
5715 tree inner_parms = TREE_VALUE (parm_level);
5716 int i;
5717 int ntparms;
5719 ntparms = TREE_VEC_LENGTH (inner_parms);
5720 for (i = 0; i < ntparms; ++i)
5722 if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
5723 continue;
5725 if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
5727 if (msg)
5729 no_errors = false;
5730 if (is_friend_decl == 2)
5731 return no_errors;
5733 error (msg, decl);
5734 msg = 0;
5737 /* Clear out the default argument so that we are not
5738 confused later. */
5739 TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
5743 /* At this point, if we're still interested in issuing messages,
5744 they must apply to classes surrounding the object declared. */
5745 if (msg)
5746 msg = G_("default argument for template parameter for class "
5747 "enclosing %qD");
5750 return no_errors;
5753 /* Worker for push_template_decl_real, called via
5754 for_each_template_parm. DATA is really an int, indicating the
5755 level of the parameters we are interested in. If T is a template
5756 parameter of that level, return nonzero. */
5758 static int
5759 template_parm_this_level_p (tree t, void* data)
5761 int this_level = *(int *)data;
5762 int level;
5764 if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5765 level = TEMPLATE_PARM_LEVEL (t);
5766 else
5767 level = TEMPLATE_TYPE_LEVEL (t);
5768 return level == this_level;
5771 /* Worker for uses_outer_template_parms, called via for_each_template_parm.
5772 DATA is really an int, indicating the innermost outer level of parameters.
5773 If T is a template parameter of that level or further out, return
5774 nonzero. */
5776 static int
5777 template_parm_outer_level (tree t, void *data)
5779 int this_level = *(int *)data;
5780 int level;
5782 if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5783 level = TEMPLATE_PARM_LEVEL (t);
5784 else
5785 level = TEMPLATE_TYPE_LEVEL (t);
5786 return level <= this_level;
5789 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
5790 parameters given by current_template_args, or reuses a
5791 previously existing one, if appropriate. Returns the DECL, or an
5792 equivalent one, if it is replaced via a call to duplicate_decls.
5794 If IS_FRIEND is true, DECL is a friend declaration. */
5796 tree
5797 push_template_decl (tree decl, bool is_friend)
5799 if (decl == error_mark_node || !current_template_parms)
5800 return error_mark_node;
5802 /* See if this is a partial specialization. */
5803 bool is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
5804 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
5805 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
5806 || (VAR_P (decl)
5807 && DECL_LANG_SPECIFIC (decl)
5808 && DECL_TEMPLATE_SPECIALIZATION (decl)
5809 && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
5811 /* No surprising friend functions. */
5812 gcc_checking_assert (is_friend
5813 || !(TREE_CODE (decl) == FUNCTION_DECL
5814 && DECL_UNIQUE_FRIEND_P (decl)));
5816 tree ctx;
5817 if (is_friend)
5818 /* For a friend, we want the context of the friend, not
5819 the type of which it is a friend. */
5820 ctx = CP_DECL_CONTEXT (decl);
5821 else if (CP_DECL_CONTEXT (decl)
5822 && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
5823 /* In the case of a virtual function, we want the class in which
5824 it is defined. */
5825 ctx = CP_DECL_CONTEXT (decl);
5826 else
5827 /* Otherwise, if we're currently defining some class, the DECL
5828 is assumed to be a member of the class. */
5829 ctx = current_scope ();
5831 if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
5832 ctx = NULL_TREE;
5834 if (!DECL_CONTEXT (decl))
5835 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5837 /* See if this is a primary template. */
5838 bool is_primary = false;
5839 if (is_friend && ctx
5840 && uses_template_parms_level (ctx, current_template_depth))
5841 /* A friend template that specifies a class context, i.e.
5842 template <typename T> friend void A<T>::f();
5843 is not primary. */
5845 else if (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5846 /* Lambdas are not primary. */
5848 else
5849 is_primary = template_parm_scope_p ();
5851 /* True if the template is a member template, in the sense of
5852 [temp.mem]. */
5853 bool member_template_p = false;
5855 if (is_primary)
5857 warning (OPT_Wtemplates, "template %qD declared", decl);
5859 if (DECL_CLASS_SCOPE_P (decl))
5860 member_template_p = true;
5862 if (TREE_CODE (decl) == TYPE_DECL
5863 && IDENTIFIER_ANON_P (DECL_NAME (decl)))
5865 error ("template class without a name");
5866 return error_mark_node;
5868 else if (TREE_CODE (decl) == FUNCTION_DECL)
5870 if (member_template_p)
5872 if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
5873 error ("member template %qD may not have virt-specifiers", decl);
5875 if (DECL_DESTRUCTOR_P (decl))
5877 /* [temp.mem]
5879 A destructor shall not be a member template. */
5880 error_at (DECL_SOURCE_LOCATION (decl),
5881 "destructor %qD declared as member template", decl);
5882 return error_mark_node;
5884 if (IDENTIFIER_NEWDEL_OP_P (DECL_NAME (decl))
5885 && (!prototype_p (TREE_TYPE (decl))
5886 || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
5887 || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5888 || (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5889 == void_list_node)))
5891 /* [basic.stc.dynamic.allocation]
5893 An allocation function can be a function
5894 template. ... Template allocation functions shall
5895 have two or more parameters. */
5896 error ("invalid template declaration of %qD", decl);
5897 return error_mark_node;
5900 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5901 && CLASS_TYPE_P (TREE_TYPE (decl)))
5902 /* Class template. */;
5903 else if (TREE_CODE (decl) == TYPE_DECL
5904 && TYPE_DECL_ALIAS_P (decl))
5905 /* alias-declaration */
5906 gcc_assert (!DECL_ARTIFICIAL (decl));
5907 else if (VAR_P (decl))
5908 /* C++14 variable template. */;
5909 else if (TREE_CODE (decl) == CONCEPT_DECL)
5910 /* C++20 concept definitions. */;
5911 else
5913 error ("template declaration of %q#D", decl);
5914 return error_mark_node;
5918 bool local_p = (!DECL_IMPLICIT_TYPEDEF_P (decl)
5919 && ((ctx && TREE_CODE (ctx) == FUNCTION_DECL)
5920 || (VAR_OR_FUNCTION_DECL_P (decl)
5921 && DECL_LOCAL_DECL_P (decl))));
5923 /* Check to see that the rules regarding the use of default
5924 arguments are not being violated. We check args for a friend
5925 functions when we know whether it's a definition, introducing
5926 declaration or re-declaration. */
5927 if (!local_p && (!is_friend || TREE_CODE (decl) != FUNCTION_DECL))
5928 check_default_tmpl_args (decl, current_template_parms,
5929 is_primary, is_partial, is_friend);
5931 /* Ensure that there are no parameter packs in the type of this
5932 declaration that have not been expanded. */
5933 if (TREE_CODE (decl) == FUNCTION_DECL)
5935 /* Check each of the arguments individually to see if there are
5936 any bare parameter packs. */
5937 tree type = TREE_TYPE (decl);
5938 tree arg = DECL_ARGUMENTS (decl);
5939 tree argtype = TYPE_ARG_TYPES (type);
5941 while (arg && argtype)
5943 if (!DECL_PACK_P (arg)
5944 && check_for_bare_parameter_packs (TREE_TYPE (arg)))
5946 /* This is a PARM_DECL that contains unexpanded parameter
5947 packs. We have already complained about this in the
5948 check_for_bare_parameter_packs call, so just replace
5949 these types with ERROR_MARK_NODE. */
5950 TREE_TYPE (arg) = error_mark_node;
5951 TREE_VALUE (argtype) = error_mark_node;
5954 arg = DECL_CHAIN (arg);
5955 argtype = TREE_CHAIN (argtype);
5958 /* Check for bare parameter packs in the return type and the
5959 exception specifiers. */
5960 if (check_for_bare_parameter_packs (TREE_TYPE (type)))
5961 /* Errors were already issued, set return type to int
5962 as the frontend doesn't expect error_mark_node as
5963 the return type. */
5964 TREE_TYPE (type) = integer_type_node;
5965 if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
5966 TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
5968 else
5970 if (check_for_bare_parameter_packs (is_typedef_decl (decl)
5971 ? DECL_ORIGINAL_TYPE (decl)
5972 : TREE_TYPE (decl)))
5974 TREE_TYPE (decl) = error_mark_node;
5975 return error_mark_node;
5978 if (is_partial && VAR_P (decl)
5979 && check_for_bare_parameter_packs (DECL_TI_ARGS (decl)))
5980 return error_mark_node;
5983 if (is_partial)
5984 return process_partial_specialization (decl);
5986 tree args = current_template_args ();
5987 tree tmpl = NULL_TREE;
5988 bool new_template_p = false;
5989 if (local_p)
5991 /* Does not get a template head. */
5992 tmpl = NULL_TREE;
5993 gcc_checking_assert (!is_primary);
5995 else if (!ctx
5996 || TREE_CODE (ctx) == FUNCTION_DECL
5997 || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
5998 || (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5999 || (is_friend && !(DECL_LANG_SPECIFIC (decl)
6000 && DECL_TEMPLATE_INFO (decl))))
6002 if (DECL_LANG_SPECIFIC (decl)
6003 && DECL_TEMPLATE_INFO (decl)
6004 && DECL_TI_TEMPLATE (decl))
6005 tmpl = DECL_TI_TEMPLATE (decl);
6006 /* If DECL is a TYPE_DECL for a class-template, then there won't
6007 be DECL_LANG_SPECIFIC. The information equivalent to
6008 DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead. */
6009 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
6010 && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
6011 && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
6013 /* Since a template declaration already existed for this
6014 class-type, we must be redeclaring it here. Make sure
6015 that the redeclaration is valid. */
6016 redeclare_class_template (TREE_TYPE (decl),
6017 current_template_parms,
6018 current_template_constraints ());
6019 /* We don't need to create a new TEMPLATE_DECL; just use the
6020 one we already had. */
6021 tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
6023 else
6025 tmpl = build_template_decl (decl, current_template_parms,
6026 member_template_p);
6027 new_template_p = true;
6029 if (DECL_LANG_SPECIFIC (decl)
6030 && DECL_TEMPLATE_SPECIALIZATION (decl))
6032 /* A specialization of a member template of a template
6033 class. */
6034 SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
6035 DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
6036 DECL_TEMPLATE_INFO (decl) = NULL_TREE;
6040 else
6042 tree a, t, current, parms;
6043 int i;
6044 tree tinfo = get_template_info (decl);
6046 if (!tinfo)
6048 error ("template definition of non-template %q#D", decl);
6049 return error_mark_node;
6052 tmpl = TI_TEMPLATE (tinfo);
6054 if (DECL_FUNCTION_TEMPLATE_P (tmpl)
6055 && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
6056 && DECL_TEMPLATE_SPECIALIZATION (decl)
6057 && DECL_MEMBER_TEMPLATE_P (tmpl))
6059 /* The declaration is a specialization of a member
6060 template, declared outside the class. Therefore, the
6061 innermost template arguments will be NULL, so we
6062 replace them with the arguments determined by the
6063 earlier call to check_explicit_specialization. */
6064 args = DECL_TI_ARGS (decl);
6066 tree new_tmpl
6067 = build_template_decl (decl, current_template_parms,
6068 member_template_p);
6069 DECL_TI_TEMPLATE (decl) = new_tmpl;
6070 SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
6071 DECL_TEMPLATE_INFO (new_tmpl)
6072 = build_template_info (tmpl, args);
6074 register_specialization (new_tmpl,
6075 most_general_template (tmpl),
6076 args,
6077 is_friend, 0);
6078 return decl;
6081 /* Make sure the template headers we got make sense. */
6083 parms = DECL_TEMPLATE_PARMS (tmpl);
6084 i = TMPL_PARMS_DEPTH (parms);
6085 if (TMPL_ARGS_DEPTH (args) != i)
6087 error ("expected %d levels of template parms for %q#D, got %d",
6088 i, decl, TMPL_ARGS_DEPTH (args));
6089 DECL_INTERFACE_KNOWN (decl) = 1;
6090 return error_mark_node;
6092 else
6093 for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
6095 a = TMPL_ARGS_LEVEL (args, i);
6096 t = INNERMOST_TEMPLATE_PARMS (parms);
6098 if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
6100 if (current == decl)
6101 error ("got %d template parameters for %q#D",
6102 TREE_VEC_LENGTH (a), decl);
6103 else
6104 error ("got %d template parameters for %q#T",
6105 TREE_VEC_LENGTH (a), current);
6106 error (" but %d required", TREE_VEC_LENGTH (t));
6107 /* Avoid crash in import_export_decl. */
6108 DECL_INTERFACE_KNOWN (decl) = 1;
6109 return error_mark_node;
6112 if (current == decl)
6113 current = ctx;
6114 else if (current == NULL_TREE)
6115 /* Can happen in erroneous input. */
6116 break;
6117 else
6118 current = get_containing_scope (current);
6121 /* Check that the parms are used in the appropriate qualifying scopes
6122 in the declarator. */
6123 if (!comp_template_args
6124 (TI_ARGS (tinfo),
6125 TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
6127 error ("template arguments to %qD do not match original "
6128 "template %qD", decl, DECL_TEMPLATE_RESULT (tmpl));
6129 if (!uses_template_parms (TI_ARGS (tinfo)))
6130 inform (input_location, "use %<template<>%> for"
6131 " an explicit specialization");
6132 /* Avoid crash in import_export_decl. */
6133 DECL_INTERFACE_KNOWN (decl) = 1;
6134 return error_mark_node;
6137 /* Check that the constraints for each enclosing template scope are
6138 consistent with the original declarations. */
6139 if (flag_concepts)
6141 tree decl_parms = DECL_TEMPLATE_PARMS (tmpl);
6142 tree scope_parms = current_template_parms;
6143 if (PRIMARY_TEMPLATE_P (tmpl))
6145 decl_parms = TREE_CHAIN (decl_parms);
6146 scope_parms = TREE_CHAIN (scope_parms);
6148 while (decl_parms)
6150 if (!template_requirements_equivalent_p (decl_parms, scope_parms))
6152 error ("redeclaration of %qD with different constraints",
6153 TPARMS_PRIMARY_TEMPLATE (TREE_VALUE (decl_parms)));
6154 break;
6156 decl_parms = TREE_CHAIN (decl_parms);
6157 scope_parms = TREE_CHAIN (scope_parms);
6162 gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
6164 if (new_template_p)
6166 /* Push template declarations for global functions and types.
6167 Note that we do not try to push a global template friend
6168 declared in a template class; such a thing may well depend on
6169 the template parameters of the class and we'll push it when
6170 instantiating the befriending class. */
6171 if (!ctx
6172 && !(is_friend && template_class_depth (current_class_type) > 0))
6174 tree pushed = pushdecl_namespace_level (tmpl, /*hiding=*/is_friend);
6175 if (pushed == error_mark_node)
6176 return error_mark_node;
6178 /* pushdecl may have found an existing template. */
6179 if (pushed != tmpl)
6181 decl = DECL_TEMPLATE_RESULT (pushed);
6182 tmpl = NULL_TREE;
6185 else if (is_friend)
6187 /* Record this decl as belonging to the current class. It's
6188 not chained onto anything else. */
6189 DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (tmpl) = true;
6190 gcc_checking_assert (!DECL_CHAIN (tmpl));
6191 DECL_CHAIN (tmpl) = current_scope ();
6194 else if (tmpl)
6195 /* The type may have been completed, or (erroneously) changed. */
6196 TREE_TYPE (tmpl) = TREE_TYPE (decl);
6198 if (tmpl)
6200 if (is_primary)
6202 tree parms = DECL_TEMPLATE_PARMS (tmpl);
6204 DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6206 /* Give template template parms a DECL_CONTEXT of the template
6207 for which they are a parameter. */
6208 parms = INNERMOST_TEMPLATE_PARMS (parms);
6209 for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
6211 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6212 if (TREE_CODE (parm) == TEMPLATE_DECL)
6213 DECL_CONTEXT (parm) = tmpl;
6216 if (TREE_CODE (decl) == TYPE_DECL
6217 && TYPE_DECL_ALIAS_P (decl))
6219 if (tree constr
6220 = TEMPLATE_PARMS_CONSTRAINTS (DECL_TEMPLATE_PARMS (tmpl)))
6222 /* ??? Why don't we do this here for all templates? */
6223 constr = build_constraints (constr, NULL_TREE);
6224 set_constraints (decl, constr);
6226 if (complex_alias_template_p (tmpl))
6227 TEMPLATE_DECL_COMPLEX_ALIAS_P (tmpl) = true;
6231 /* The DECL_TI_ARGS of DECL contains full set of arguments
6232 referring wback to its most general template. If TMPL is a
6233 specialization, ARGS may only have the innermost set of
6234 arguments. Add the missing argument levels if necessary. */
6235 if (DECL_TEMPLATE_INFO (tmpl))
6236 args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
6238 tree info = build_template_info (tmpl, args);
6240 if (DECL_IMPLICIT_TYPEDEF_P (decl))
6241 SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
6242 else
6244 retrofit_lang_decl (decl);
6245 DECL_TEMPLATE_INFO (decl) = info;
6249 if (flag_implicit_templates
6250 && !is_friend
6251 && TREE_PUBLIC (decl)
6252 && VAR_OR_FUNCTION_DECL_P (decl))
6253 /* Set DECL_COMDAT on template instantiations; if we force
6254 them to be emitted by explicit instantiation,
6255 mark_needed will tell cgraph to do the right thing. */
6256 DECL_COMDAT (decl) = true;
6258 gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
6260 return decl;
6263 /* FN is an inheriting constructor that inherits from the constructor
6264 template INHERITED; turn FN into a constructor template with a matching
6265 template header. */
6267 tree
6268 add_inherited_template_parms (tree fn, tree inherited)
6270 tree inner_parms
6271 = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
6272 inner_parms = copy_node (inner_parms);
6273 tree parms
6274 = tree_cons (size_int (current_template_depth + 1),
6275 inner_parms, current_template_parms);
6276 tree tmpl = build_template_decl (fn, parms, /*member*/true);
6277 tree args = template_parms_to_args (parms);
6278 DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
6279 DECL_ARTIFICIAL (tmpl) = true;
6280 DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6281 return tmpl;
6284 /* Called when a class template TYPE is redeclared with the indicated
6285 template PARMS, e.g.:
6287 template <class T> struct S;
6288 template <class T> struct S {}; */
6290 bool
6291 redeclare_class_template (tree type, tree parms, tree cons)
6293 tree tmpl;
6294 tree tmpl_parms;
6295 int i;
6297 if (!TYPE_TEMPLATE_INFO (type))
6299 error ("%qT is not a template type", type);
6300 return false;
6303 tmpl = TYPE_TI_TEMPLATE (type);
6304 if (!PRIMARY_TEMPLATE_P (tmpl))
6305 /* The type is nested in some template class. Nothing to worry
6306 about here; there are no new template parameters for the nested
6307 type. */
6308 return true;
6310 if (!parms)
6312 error ("template specifiers not specified in declaration of %qD",
6313 tmpl);
6314 return false;
6317 parms = INNERMOST_TEMPLATE_PARMS (parms);
6318 tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
6320 if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
6322 error_n (input_location, TREE_VEC_LENGTH (parms),
6323 "redeclared with %d template parameter",
6324 "redeclared with %d template parameters",
6325 TREE_VEC_LENGTH (parms));
6326 inform_n (DECL_SOURCE_LOCATION (tmpl), TREE_VEC_LENGTH (tmpl_parms),
6327 "previous declaration %qD used %d template parameter",
6328 "previous declaration %qD used %d template parameters",
6329 tmpl, TREE_VEC_LENGTH (tmpl_parms));
6330 return false;
6333 for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
6335 tree tmpl_parm;
6336 tree parm;
6338 if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
6339 || TREE_VEC_ELT (parms, i) == error_mark_node)
6340 continue;
6342 tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
6343 if (error_operand_p (tmpl_parm))
6344 return false;
6346 parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6348 /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
6349 TEMPLATE_DECL. */
6350 if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
6351 || (TREE_CODE (tmpl_parm) != TYPE_DECL
6352 && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
6353 || (TREE_CODE (tmpl_parm) != PARM_DECL
6354 && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
6355 != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
6356 || (TREE_CODE (tmpl_parm) == PARM_DECL
6357 && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
6358 != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
6360 auto_diagnostic_group d;
6361 error ("template parameter %q+#D", tmpl_parm);
6362 if (DECL_P (parm))
6363 inform (DECL_SOURCE_LOCATION (parm), "redeclared here as %q#D", parm);
6364 else
6365 inform (input_location, "redeclared here");
6366 return false;
6369 /* The parameters can be declared to introduce different
6370 constraints. */
6371 tree p1 = TREE_VEC_ELT (tmpl_parms, i);
6372 tree p2 = TREE_VEC_ELT (parms, i);
6373 if (!template_parameter_constraints_equivalent_p (p1, p2))
6375 auto_diagnostic_group d;
6376 error ("declaration of template parameter %q+#D with different "
6377 "constraints", parm);
6378 inform (DECL_SOURCE_LOCATION (tmpl_parm),
6379 "original declaration appeared here");
6380 return false;
6383 /* Give each template template parm in this redeclaration a
6384 DECL_CONTEXT of the template for which they are a parameter. */
6385 if (TREE_CODE (parm) == TEMPLATE_DECL)
6387 gcc_assert (DECL_CONTEXT (parm) == NULL_TREE);
6388 DECL_CONTEXT (parm) = tmpl;
6392 if (!merge_default_template_args (parms, tmpl_parms, /*class_p=*/true))
6393 return false;
6395 tree ci = get_constraints (tmpl);
6396 tree req1 = ci ? CI_TEMPLATE_REQS (ci) : NULL_TREE;
6397 tree req2 = cons ? CI_TEMPLATE_REQS (cons) : NULL_TREE;
6399 /* Two classes with different constraints declare different entities. */
6400 if (!cp_tree_equal (req1, req2))
6402 auto_diagnostic_group d;
6403 error_at (input_location, "redeclaration of %q#D with different "
6404 "constraints", tmpl);
6405 inform (DECL_SOURCE_LOCATION (tmpl),
6406 "original declaration appeared here");
6407 return false;
6410 return true;
6413 /* The actual substitution part of instantiate_non_dependent_expr,
6414 to be used when the caller has already checked
6415 !instantiation_dependent_uneval_expression_p (expr)
6416 and cleared processing_template_decl. */
6418 tree
6419 instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
6421 return tsubst_copy_and_build (expr,
6422 /*args=*/NULL_TREE,
6423 complain,
6424 /*in_decl=*/NULL_TREE);
6427 /* Instantiate the non-dependent expression EXPR. */
6429 tree
6430 instantiate_non_dependent_expr (tree expr,
6431 tsubst_flags_t complain /* = tf_error */)
6433 if (expr == NULL_TREE)
6434 return NULL_TREE;
6436 if (processing_template_decl)
6438 /* The caller should have checked this already. */
6439 gcc_checking_assert (!instantiation_dependent_uneval_expression_p (expr));
6440 processing_template_decl_sentinel s;
6441 expr = instantiate_non_dependent_expr_internal (expr, complain);
6443 return expr;
6446 /* Like instantiate_non_dependent_expr, but return NULL_TREE if the
6447 expression is dependent or non-constant. */
6449 tree
6450 instantiate_non_dependent_or_null (tree expr)
6452 if (expr == NULL_TREE)
6453 return NULL_TREE;
6454 if (processing_template_decl)
6456 if (!is_nondependent_constant_expression (expr))
6457 expr = NULL_TREE;
6458 else
6460 processing_template_decl_sentinel s;
6461 expr = instantiate_non_dependent_expr_internal (expr, tf_error);
6464 return expr;
6467 /* True iff T is a specialization of a variable template. */
6469 bool
6470 variable_template_specialization_p (tree t)
6472 if (!VAR_P (t) || !DECL_LANG_SPECIFIC (t) || !DECL_TEMPLATE_INFO (t))
6473 return false;
6474 tree tmpl = DECL_TI_TEMPLATE (t);
6475 return variable_template_p (tmpl);
6478 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
6479 template declaration, or a TYPE_DECL for an alias declaration. */
6481 bool
6482 alias_type_or_template_p (tree t)
6484 if (t == NULL_TREE)
6485 return false;
6486 return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
6487 || (TYPE_P (t)
6488 && TYPE_NAME (t)
6489 && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
6490 || DECL_ALIAS_TEMPLATE_P (t));
6493 /* If T is a specialization of an alias template, return it; otherwise return
6494 NULL_TREE. If TRANSPARENT_TYPEDEFS is true, look through other aliases. */
6496 tree
6497 alias_template_specialization_p (const_tree t,
6498 bool transparent_typedefs)
6500 if (!TYPE_P (t))
6501 return NULL_TREE;
6503 /* It's an alias template specialization if it's an alias and its
6504 TYPE_NAME is a specialization of a primary template. */
6505 if (typedef_variant_p (t))
6507 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
6508 if (PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo)))
6509 return CONST_CAST_TREE (t);
6510 if (transparent_typedefs)
6511 return alias_template_specialization_p (DECL_ORIGINAL_TYPE
6512 (TYPE_NAME (t)),
6513 transparent_typedefs);
6516 return NULL_TREE;
6519 /* Data structure for complex_alias_template_*. */
6521 struct uses_all_template_parms_data
6523 int level;
6524 bool *seen;
6527 /* walk_tree callback for complex_alias_template_p. */
6529 static tree
6530 complex_alias_template_r (tree *tp, int *walk_subtrees, void *data_)
6532 tree t = *tp;
6533 auto &data = *(struct uses_all_template_parms_data*)data_;
6535 switch (TREE_CODE (t))
6537 case TEMPLATE_TYPE_PARM:
6538 case TEMPLATE_PARM_INDEX:
6539 case TEMPLATE_TEMPLATE_PARM:
6540 case BOUND_TEMPLATE_TEMPLATE_PARM:
6542 tree idx = get_template_parm_index (t);
6543 if (TEMPLATE_PARM_LEVEL (idx) == data.level)
6544 data.seen[TEMPLATE_PARM_IDX (idx)] = true;
6547 default:;
6550 if (!PACK_EXPANSION_P (t))
6551 return 0;
6553 /* An alias template with a pack expansion that expands a pack from the
6554 enclosing class needs to be considered complex, to avoid confusion with
6555 the same pack being used as an argument to the alias's own template
6556 parameter (91966). */
6557 for (tree pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
6558 pack = TREE_CHAIN (pack))
6560 tree parm_pack = TREE_VALUE (pack);
6561 if (!TEMPLATE_PARM_P (parm_pack))
6562 continue;
6563 int idx, level;
6564 template_parm_level_and_index (parm_pack, &level, &idx);
6565 if (level < data.level)
6566 return t;
6568 /* Consider the expanded packs to be used outside the expansion... */
6569 data.seen[idx] = true;
6572 /* ...but don't walk into the pattern. Consider PR104008:
6574 template <typename T, typename... Ts>
6575 using IsOneOf = disjunction<is_same<T, Ts>...>;
6577 where IsOneOf seemingly uses all of its template parameters in its
6578 expansion (and does not expand a pack from the enclosing class), so the
6579 alias was not marked as complex. However, if it is used like
6580 "IsOneOf<T>", the empty pack for Ts means that T no longer appears in the
6581 expansion. So only Ts is considered used by the pack expansion. */
6582 *walk_subtrees = false;
6584 return 0;
6587 /* An alias template is complex from a SFINAE perspective if a template-id
6588 using that alias can be ill-formed when the expansion is not, as with
6589 the void_t template.
6591 Returns 1 if always complex, 0 if not complex, -1 if complex iff any of the
6592 template arguments are empty packs. */
6594 static bool
6595 complex_alias_template_p (const_tree tmpl)
6597 /* A renaming alias isn't complex. */
6598 if (get_underlying_template (CONST_CAST_TREE (tmpl)) != tmpl)
6599 return false;
6601 /* Any other constrained alias is complex. */
6602 if (get_constraints (tmpl))
6603 return true;
6605 struct uses_all_template_parms_data data;
6606 tree pat = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6607 tree parms = DECL_TEMPLATE_PARMS (tmpl);
6608 data.level = TMPL_PARMS_DEPTH (parms);
6609 int len = TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS (parms));
6610 data.seen = XALLOCAVEC (bool, len);
6611 for (int i = 0; i < len; ++i)
6612 data.seen[i] = false;
6614 if (cp_walk_tree_without_duplicates (&pat, complex_alias_template_r, &data))
6615 return true;
6616 for (int i = 0; i < len; ++i)
6617 if (!data.seen[i])
6618 return true;
6619 return false;
6622 /* If T is a specialization of a complex alias template with dependent
6623 template-arguments, return it; otherwise return NULL_TREE. If T is a
6624 typedef to such a specialization, return the specialization. */
6626 tree
6627 dependent_alias_template_spec_p (const_tree t, bool transparent_typedefs)
6629 if (t == error_mark_node)
6630 return NULL_TREE;
6631 gcc_assert (TYPE_P (t));
6633 if (!typedef_variant_p (t))
6634 return NULL_TREE;
6636 tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t);
6637 if (tinfo
6638 && TEMPLATE_DECL_COMPLEX_ALIAS_P (TI_TEMPLATE (tinfo))
6639 && (any_dependent_template_arguments_p
6640 (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)))))
6641 return CONST_CAST_TREE (t);
6643 if (transparent_typedefs)
6645 tree utype = DECL_ORIGINAL_TYPE (TYPE_NAME (t));
6646 return dependent_alias_template_spec_p (utype, transparent_typedefs);
6649 return NULL_TREE;
6652 /* Return the number of innermost template parameters in TMPL. */
6654 static int
6655 num_innermost_template_parms (const_tree tmpl)
6657 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6658 return TREE_VEC_LENGTH (parms);
6661 /* Return either TMPL or another template that it is equivalent to under DR
6662 1286: An alias that just changes the name of a template is equivalent to
6663 the other template. */
6665 static tree
6666 get_underlying_template (tree tmpl)
6668 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
6669 while (DECL_ALIAS_TEMPLATE_P (tmpl))
6671 /* Determine if the alias is equivalent to an underlying template. */
6672 tree orig_type = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6673 /* The underlying type may have been ill-formed. Don't proceed. */
6674 if (!orig_type)
6675 break;
6676 tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (orig_type);
6677 if (!tinfo)
6678 break;
6680 tree underlying = TI_TEMPLATE (tinfo);
6681 if (!PRIMARY_TEMPLATE_P (underlying)
6682 || (num_innermost_template_parms (tmpl)
6683 != num_innermost_template_parms (underlying)))
6684 break;
6686 /* Does the alias add cv-quals? */
6687 if (TYPE_QUALS (TREE_TYPE (underlying)) != TYPE_QUALS (TREE_TYPE (tmpl)))
6688 break;
6690 tree alias_args = INNERMOST_TEMPLATE_ARGS (generic_targs_for (tmpl));
6691 if (!comp_template_args (TI_ARGS (tinfo), alias_args))
6692 break;
6694 /* Are any default template arguments equivalent? */
6695 tree aparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6696 tree uparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (underlying));
6697 const int nparms = TREE_VEC_LENGTH (aparms);
6698 for (int i = 0; i < nparms; ++i)
6700 tree adefarg = TREE_PURPOSE (TREE_VEC_ELT (aparms, i));
6701 tree udefarg = TREE_PURPOSE (TREE_VEC_ELT (uparms, i));
6702 if (!template_args_equal (adefarg, udefarg))
6703 goto top_break;
6706 /* If TMPL adds or changes any constraints, it isn't equivalent. I think
6707 it's appropriate to treat a less-constrained alias as equivalent. */
6708 if (!at_least_as_constrained (underlying, tmpl))
6709 break;
6711 /* Alias is equivalent. Strip it and repeat. */
6712 tmpl = underlying;
6714 top_break:;
6716 return tmpl;
6719 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
6720 must be a reference-to-function or a pointer-to-function type, as specified
6721 in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
6722 and check that the resulting function has external linkage. */
6724 static tree
6725 convert_nontype_argument_function (tree type, tree expr,
6726 tsubst_flags_t complain)
6728 tree fns = expr;
6729 tree fn, fn_no_ptr;
6730 linkage_kind linkage;
6732 fn = instantiate_type (type, fns, tf_none);
6733 if (fn == error_mark_node)
6734 return error_mark_node;
6736 if (value_dependent_expression_p (fn))
6737 goto accept;
6739 fn_no_ptr = fn;
6740 if (REFERENCE_REF_P (fn_no_ptr))
6741 fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6742 fn_no_ptr = strip_fnptr_conv (fn_no_ptr);
6743 if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
6744 fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6745 if (BASELINK_P (fn_no_ptr))
6746 fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
6748 /* [temp.arg.nontype]/1
6750 A template-argument for a non-type, non-template template-parameter
6751 shall be one of:
6752 [...]
6753 -- the address of an object or function with external [C++11: or
6754 internal] linkage. */
6756 STRIP_ANY_LOCATION_WRAPPER (fn_no_ptr);
6757 if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
6759 if (complain & tf_error)
6761 location_t loc = cp_expr_loc_or_input_loc (expr);
6762 error_at (loc, "%qE is not a valid template argument for type %qT",
6763 expr, type);
6764 if (TYPE_PTR_P (type))
6765 inform (loc, "it must be the address of a function "
6766 "with external linkage");
6767 else
6768 inform (loc, "it must be the name of a function with "
6769 "external linkage");
6771 return NULL_TREE;
6774 linkage = decl_linkage (fn_no_ptr);
6775 if ((cxx_dialect < cxx11 && linkage != lk_external)
6776 || (cxx_dialect < cxx17 && linkage == lk_none))
6778 if (complain & tf_error)
6780 location_t loc = cp_expr_loc_or_input_loc (expr);
6781 if (cxx_dialect >= cxx11)
6782 error_at (loc, "%qE is not a valid template argument for type "
6783 "%qT because %qD has no linkage",
6784 expr, type, fn_no_ptr);
6785 else
6786 error_at (loc, "%qE is not a valid template argument for type "
6787 "%qT because %qD does not have external linkage",
6788 expr, type, fn_no_ptr);
6790 return NULL_TREE;
6793 accept:
6794 if (TYPE_REF_P (type))
6796 if (REFERENCE_REF_P (fn))
6797 fn = TREE_OPERAND (fn, 0);
6798 else
6799 fn = build_address (fn);
6801 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (fn)))
6802 fn = build_nop (type, fn);
6804 return fn;
6807 /* Subroutine of convert_nontype_argument.
6808 Check if EXPR of type TYPE is a valid pointer-to-member constant.
6809 Emit an error otherwise. */
6811 static bool
6812 check_valid_ptrmem_cst_expr (tree type, tree expr,
6813 tsubst_flags_t complain)
6815 tree orig_expr = expr;
6816 STRIP_NOPS (expr);
6817 if (null_ptr_cst_p (expr))
6818 return true;
6819 if (TREE_CODE (expr) == PTRMEM_CST
6820 && same_type_p (TYPE_PTRMEM_CLASS_TYPE (type),
6821 PTRMEM_CST_CLASS (expr)))
6822 return true;
6823 if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
6824 return true;
6825 if (processing_template_decl
6826 && TREE_CODE (expr) == ADDR_EXPR
6827 && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
6828 return true;
6829 if (complain & tf_error)
6831 location_t loc = cp_expr_loc_or_input_loc (orig_expr);
6832 error_at (loc, "%qE is not a valid template argument for type %qT",
6833 orig_expr, type);
6834 if (TREE_CODE (expr) != PTRMEM_CST)
6835 inform (loc, "it must be a pointer-to-member of the form %<&X::Y%>");
6836 else
6837 inform (loc, "because it is a member of %qT", PTRMEM_CST_CLASS (expr));
6839 return false;
6842 /* Returns TRUE iff the address of OP is value-dependent.
6844 14.6.2.4 [temp.dep.temp]:
6845 A non-integral non-type template-argument is dependent if its type is
6846 dependent or it has either of the following forms
6847 qualified-id
6848 & qualified-id
6849 and contains a nested-name-specifier which specifies a class-name that
6850 names a dependent type.
6852 We generalize this to just say that the address of a member of a
6853 dependent class is value-dependent; the above doesn't cover the
6854 address of a static data member named with an unqualified-id. */
6856 static bool
6857 has_value_dependent_address (tree op)
6859 STRIP_ANY_LOCATION_WRAPPER (op);
6861 /* We could use get_inner_reference here, but there's no need;
6862 this is only relevant for template non-type arguments, which
6863 can only be expressed as &id-expression. */
6864 if (DECL_P (op))
6866 tree ctx = CP_DECL_CONTEXT (op);
6868 if (TYPE_P (ctx) && dependent_type_p (ctx))
6869 return true;
6871 if (VAR_P (op)
6872 && TREE_STATIC (op)
6873 && TREE_CODE (ctx) == FUNCTION_DECL
6874 && type_dependent_expression_p (ctx))
6875 return true;
6878 return false;
6881 /* The next set of functions are used for providing helpful explanatory
6882 diagnostics for failed overload resolution. Their messages should be
6883 indented by two spaces for consistency with the messages in
6884 call.cc */
6886 static int
6887 unify_success (bool /*explain_p*/)
6889 return 0;
6892 /* Other failure functions should call this one, to provide a single function
6893 for setting a breakpoint on. */
6895 static int
6896 unify_invalid (bool /*explain_p*/)
6898 return 1;
6901 static int
6902 unify_parameter_deduction_failure (bool explain_p, tree parm)
6904 if (explain_p)
6905 inform (input_location,
6906 " couldn%'t deduce template parameter %qD", parm);
6907 return unify_invalid (explain_p);
6910 static int
6911 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
6913 if (explain_p)
6914 inform (input_location,
6915 " types %qT and %qT have incompatible cv-qualifiers",
6916 parm, arg);
6917 return unify_invalid (explain_p);
6920 static int
6921 unify_type_mismatch (bool explain_p, tree parm, tree arg)
6923 if (explain_p)
6924 inform (input_location, " mismatched types %qT and %qT", parm, arg);
6925 return unify_invalid (explain_p);
6928 static int
6929 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
6931 if (explain_p)
6932 inform (input_location,
6933 " template parameter %qD is not a parameter pack, but "
6934 "argument %qD is",
6935 parm, arg);
6936 return unify_invalid (explain_p);
6939 static int
6940 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
6942 if (explain_p)
6943 inform (input_location,
6944 " template argument %qE does not match "
6945 "pointer-to-member constant %qE",
6946 arg, parm);
6947 return unify_invalid (explain_p);
6950 static int
6951 unify_expression_unequal (bool explain_p, tree parm, tree arg)
6953 if (explain_p)
6954 inform (input_location, " %qE is not equivalent to %qE", parm, arg);
6955 return unify_invalid (explain_p);
6958 static int
6959 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
6961 if (explain_p)
6962 inform (input_location,
6963 " inconsistent parameter pack deduction with %qT and %qT",
6964 old_arg, new_arg);
6965 return unify_invalid (explain_p);
6968 static int
6969 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
6971 if (explain_p)
6973 if (TYPE_P (parm))
6974 inform (input_location,
6975 " deduced conflicting types for parameter %qT (%qT and %qT)",
6976 parm, first, second);
6977 else
6978 inform (input_location,
6979 " deduced conflicting values for non-type parameter "
6980 "%qE (%qE and %qE)", parm, first, second);
6982 return unify_invalid (explain_p);
6985 static int
6986 unify_vla_arg (bool explain_p, tree arg)
6988 if (explain_p)
6989 inform (input_location,
6990 " variable-sized array type %qT is not "
6991 "a valid template argument",
6992 arg);
6993 return unify_invalid (explain_p);
6996 static int
6997 unify_method_type_error (bool explain_p, tree arg)
6999 if (explain_p)
7000 inform (input_location,
7001 " member function type %qT is not a valid template argument",
7002 arg);
7003 return unify_invalid (explain_p);
7006 static int
7007 unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
7009 if (explain_p)
7011 if (least_p)
7012 inform_n (input_location, wanted,
7013 " candidate expects at least %d argument, %d provided",
7014 " candidate expects at least %d arguments, %d provided",
7015 wanted, have);
7016 else
7017 inform_n (input_location, wanted,
7018 " candidate expects %d argument, %d provided",
7019 " candidate expects %d arguments, %d provided",
7020 wanted, have);
7022 return unify_invalid (explain_p);
7025 static int
7026 unify_too_many_arguments (bool explain_p, int have, int wanted)
7028 return unify_arity (explain_p, have, wanted);
7031 static int
7032 unify_too_few_arguments (bool explain_p, int have, int wanted,
7033 bool least_p = false)
7035 return unify_arity (explain_p, have, wanted, least_p);
7038 static int
7039 unify_arg_conversion (bool explain_p, tree to_type,
7040 tree from_type, tree arg)
7042 if (explain_p)
7043 inform (cp_expr_loc_or_input_loc (arg),
7044 " cannot convert %qE (type %qT) to type %qT",
7045 arg, from_type, to_type);
7046 return unify_invalid (explain_p);
7049 static int
7050 unify_no_common_base (bool explain_p, enum template_base_result r,
7051 tree parm, tree arg)
7053 if (explain_p)
7054 switch (r)
7056 case tbr_ambiguous_baseclass:
7057 inform (input_location, " %qT is an ambiguous base class of %qT",
7058 parm, arg);
7059 break;
7060 default:
7061 inform (input_location, " %qT is not derived from %qT", arg, parm);
7062 break;
7064 return unify_invalid (explain_p);
7067 static int
7068 unify_inconsistent_template_template_parameters (bool explain_p)
7070 if (explain_p)
7071 inform (input_location,
7072 " template parameters of a template template argument are "
7073 "inconsistent with other deduced template arguments");
7074 return unify_invalid (explain_p);
7077 static int
7078 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
7080 if (explain_p)
7081 inform (input_location,
7082 " cannot deduce a template for %qT from non-template type %qT",
7083 parm, arg);
7084 return unify_invalid (explain_p);
7087 static int
7088 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
7090 if (explain_p)
7091 inform (input_location,
7092 " template argument %qE does not match %qE", arg, parm);
7093 return unify_invalid (explain_p);
7096 /* Subroutine of convert_nontype_argument, to check whether EXPR, as an
7097 argument for TYPE, points to an unsuitable object.
7099 Also adjust the type of the index in C++20 array subobject references. */
7101 static bool
7102 invalid_tparm_referent_p (tree type, tree expr, tsubst_flags_t complain)
7104 switch (TREE_CODE (expr))
7106 CASE_CONVERT:
7107 return invalid_tparm_referent_p (type, TREE_OPERAND (expr, 0),
7108 complain);
7110 case TARGET_EXPR:
7111 return invalid_tparm_referent_p (type, TARGET_EXPR_INITIAL (expr),
7112 complain);
7114 case CONSTRUCTOR:
7116 for (auto &e: CONSTRUCTOR_ELTS (expr))
7117 if (invalid_tparm_referent_p (TREE_TYPE (e.value), e.value, complain))
7118 return true;
7120 break;
7122 case ADDR_EXPR:
7124 tree decl = TREE_OPERAND (expr, 0);
7126 if (cxx_dialect >= cxx20)
7127 while (TREE_CODE (decl) == COMPONENT_REF
7128 || TREE_CODE (decl) == ARRAY_REF)
7130 tree &op = TREE_OPERAND (decl, 1);
7131 if (TREE_CODE (decl) == ARRAY_REF
7132 && TREE_CODE (op) == INTEGER_CST)
7133 /* Canonicalize array offsets to ptrdiff_t; how they were
7134 written doesn't matter for subobject identity. */
7135 op = fold_convert (ptrdiff_type_node, op);
7136 decl = TREE_OPERAND (decl, 0);
7139 if (!VAR_OR_FUNCTION_DECL_P (decl))
7141 if (complain & tf_error)
7142 error_at (cp_expr_loc_or_input_loc (expr),
7143 "%qE is not a valid template argument of type %qT "
7144 "because %qE is not a variable or function",
7145 expr, type, decl);
7146 return true;
7148 else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
7150 if (complain & tf_error)
7151 error_at (cp_expr_loc_or_input_loc (expr),
7152 "%qE is not a valid template argument of type %qT "
7153 "in C++98 because %qD does not have external linkage",
7154 expr, type, decl);
7155 return true;
7157 else if ((cxx_dialect >= cxx11 && cxx_dialect < cxx17)
7158 && decl_linkage (decl) == lk_none)
7160 if (complain & tf_error)
7161 error_at (cp_expr_loc_or_input_loc (expr),
7162 "%qE is not a valid template argument of type %qT "
7163 "because %qD has no linkage", expr, type, decl);
7164 return true;
7166 /* C++17: For a non-type template-parameter of reference or pointer
7167 type, the value of the constant expression shall not refer to (or
7168 for a pointer type, shall not be the address of):
7169 * a subobject (4.5),
7170 * a temporary object (15.2),
7171 * a string literal (5.13.5),
7172 * the result of a typeid expression (8.2.8), or
7173 * a predefined __func__ variable (11.4.1). */
7174 else if (VAR_P (decl) && DECL_ARTIFICIAL (decl))
7176 if (complain & tf_error)
7177 error ("the address of %qD is not a valid template argument",
7178 decl);
7179 return true;
7181 else if (cxx_dialect < cxx20
7182 && !(same_type_ignoring_top_level_qualifiers_p
7183 (strip_array_types (TREE_TYPE (type)),
7184 strip_array_types (TREE_TYPE (decl)))))
7186 if (complain & tf_error)
7187 error ("the address of the %qT subobject of %qD is not a "
7188 "valid template argument", TREE_TYPE (type), decl);
7189 return true;
7191 else if (!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
7193 if (complain & tf_error)
7194 error ("the address of %qD is not a valid template argument "
7195 "because it does not have static storage duration",
7196 decl);
7197 return true;
7200 break;
7202 default:
7203 if (!INDIRECT_TYPE_P (type))
7204 /* We're only concerned about pointers and references here. */;
7205 else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7206 /* Null pointer values are OK in C++11. */;
7207 else
7209 if (VAR_P (expr))
7211 if (complain & tf_error)
7212 error ("%qD is not a valid template argument "
7213 "because %qD is a variable, not the address of "
7214 "a variable", expr, expr);
7215 return true;
7217 else
7219 if (complain & tf_error)
7220 error ("%qE is not a valid template argument for %qT "
7221 "because it is not the address of a variable",
7222 expr, type);
7223 return true;
7227 return false;
7231 /* Return a VAR_DECL for the C++20 template parameter object corresponding to
7232 template argument EXPR. */
7234 static tree
7235 create_template_parm_object (tree expr, tsubst_flags_t complain)
7237 if (TREE_CODE (expr) == TARGET_EXPR)
7238 expr = TARGET_EXPR_INITIAL (expr);
7240 if (!TREE_CONSTANT (expr))
7242 if ((complain & tf_error)
7243 && require_rvalue_constant_expression (expr))
7244 cxx_constant_value (expr);
7245 return error_mark_node;
7247 if (invalid_tparm_referent_p (TREE_TYPE (expr), expr, complain))
7248 return error_mark_node;
7250 /* This is no longer a compound literal. */
7251 gcc_assert (!TREE_HAS_CONSTRUCTOR (expr));
7253 return get_template_parm_object (expr, mangle_template_parm_object (expr));
7256 /* The template arguments corresponding to template parameter objects of types
7257 that contain pointers to members. */
7259 static GTY(()) hash_map<tree, tree> *tparm_obj_values;
7261 /* Find or build an nttp object for (already-validated) EXPR with name
7262 NAME. */
7264 tree
7265 get_template_parm_object (tree expr, tree name)
7267 tree decl = get_global_binding (name);
7268 if (decl)
7269 return decl;
7271 tree type = cp_build_qualified_type (TREE_TYPE (expr), TYPE_QUAL_CONST);
7272 decl = create_temporary_var (type);
7273 DECL_NTTP_OBJECT_P (decl) = true;
7274 DECL_CONTEXT (decl) = NULL_TREE;
7275 TREE_STATIC (decl) = true;
7276 DECL_DECLARED_CONSTEXPR_P (decl) = true;
7277 TREE_READONLY (decl) = true;
7278 DECL_NAME (decl) = name;
7279 SET_DECL_ASSEMBLER_NAME (decl, name);
7280 comdat_linkage (decl);
7282 if (!zero_init_p (type))
7284 /* If EXPR contains any PTRMEM_CST, they will get clobbered by
7285 lower_var_init before we're done mangling. So store the original
7286 value elsewhere. */
7287 tree copy = unshare_constructor (expr);
7288 hash_map_safe_put<hm_ggc> (tparm_obj_values, decl, copy);
7291 pushdecl_top_level_and_finish (decl, expr);
7293 return decl;
7296 /* Return the actual template argument corresponding to template parameter
7297 object VAR. */
7299 tree
7300 tparm_object_argument (tree var)
7302 if (zero_init_p (TREE_TYPE (var)))
7303 return DECL_INITIAL (var);
7304 return *(tparm_obj_values->get (var));
7307 /* Attempt to convert the non-type template parameter EXPR to the
7308 indicated TYPE. If the conversion is successful, return the
7309 converted value. If the conversion is unsuccessful, return
7310 NULL_TREE if we issued an error message, or error_mark_node if we
7311 did not. We issue error messages for out-and-out bad template
7312 parameters, but not simply because the conversion failed, since we
7313 might be just trying to do argument deduction. Both TYPE and EXPR
7314 must be non-dependent.
7316 The conversion follows the special rules described in
7317 [temp.arg.nontype], and it is much more strict than an implicit
7318 conversion.
7320 This function is called twice for each template argument (see
7321 lookup_template_class for a more accurate description of this
7322 problem). This means that we need to handle expressions which
7323 are not valid in a C++ source, but can be created from the
7324 first call (for instance, casts to perform conversions). These
7325 hacks can go away after we fix the double coercion problem. */
7327 static tree
7328 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
7330 tree expr_type;
7331 location_t loc = cp_expr_loc_or_input_loc (expr);
7333 /* Detect immediately string literals as invalid non-type argument.
7334 This special-case is not needed for correctness (we would easily
7335 catch this later), but only to provide better diagnostic for this
7336 common user mistake. As suggested by DR 100, we do not mention
7337 linkage issues in the diagnostic as this is not the point. */
7338 if (TREE_CODE (expr) == STRING_CST && !CLASS_TYPE_P (type))
7340 if (complain & tf_error)
7341 error ("%qE is not a valid template argument for type %qT "
7342 "because string literals can never be used in this context",
7343 expr, type);
7344 return NULL_TREE;
7347 /* Add the ADDR_EXPR now for the benefit of
7348 value_dependent_expression_p. */
7349 if (TYPE_PTROBV_P (type)
7350 && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
7352 expr = decay_conversion (expr, complain);
7353 if (expr == error_mark_node)
7354 return error_mark_node;
7357 /* If we are in a template, EXPR may be non-dependent, but still
7358 have a syntactic, rather than semantic, form. For example, EXPR
7359 might be a SCOPE_REF, rather than the VAR_DECL to which the
7360 SCOPE_REF refers. Preserving the qualifying scope is necessary
7361 so that access checking can be performed when the template is
7362 instantiated -- but here we need the resolved form so that we can
7363 convert the argument. */
7364 bool non_dep = false;
7365 if (TYPE_REF_OBJ_P (type)
7366 && has_value_dependent_address (expr))
7367 /* If we want the address and it's value-dependent, don't fold. */;
7368 else if (processing_template_decl
7369 && !instantiation_dependent_expression_p (expr))
7370 non_dep = true;
7371 if (error_operand_p (expr))
7372 return error_mark_node;
7373 expr_type = TREE_TYPE (expr);
7375 /* If the argument is non-dependent, perform any conversions in
7376 non-dependent context as well. */
7377 processing_template_decl_sentinel s (non_dep);
7378 if (non_dep)
7379 expr = instantiate_non_dependent_expr_internal (expr, complain);
7381 bool val_dep_p = value_dependent_expression_p (expr);
7382 if (val_dep_p)
7383 expr = canonicalize_expr_argument (expr, complain);
7384 else
7385 STRIP_ANY_LOCATION_WRAPPER (expr);
7387 /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
7388 to a non-type argument of "nullptr". */
7389 if (NULLPTR_TYPE_P (expr_type) && TYPE_PTR_OR_PTRMEM_P (type))
7390 expr = fold_simple (convert (type, expr));
7392 /* In C++11, integral or enumeration non-type template arguments can be
7393 arbitrary constant expressions. Pointer and pointer to
7394 member arguments can be general constant expressions that evaluate
7395 to a null value, but otherwise still need to be of a specific form. */
7396 if (cxx_dialect >= cxx11)
7398 if (TREE_CODE (expr) == PTRMEM_CST && TYPE_PTRMEM_P (type))
7399 /* A PTRMEM_CST is already constant, and a valid template
7400 argument for a parameter of pointer to member type, we just want
7401 to leave it in that form rather than lower it to a
7402 CONSTRUCTOR. */;
7403 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7404 || cxx_dialect >= cxx17)
7406 /* C++17: A template-argument for a non-type template-parameter shall
7407 be a converted constant expression (8.20) of the type of the
7408 template-parameter. */
7409 expr = build_converted_constant_expr (type, expr, complain);
7410 if (expr == error_mark_node)
7411 /* Make sure we return NULL_TREE only if we have really issued
7412 an error, as described above. */
7413 return (complain & tf_error) ? NULL_TREE : error_mark_node;
7414 else if (TREE_CODE (expr) == IMPLICIT_CONV_EXPR)
7416 IMPLICIT_CONV_EXPR_NONTYPE_ARG (expr) = true;
7417 return expr;
7419 expr = maybe_constant_value (expr, NULL_TREE, mce_true);
7420 expr = convert_from_reference (expr);
7421 /* EXPR may have become value-dependent. */
7422 val_dep_p = value_dependent_expression_p (expr);
7424 else if (TYPE_PTR_OR_PTRMEM_P (type))
7426 tree folded = maybe_constant_value (expr, NULL_TREE, mce_true);
7427 if (TYPE_PTR_P (type) ? integer_zerop (folded)
7428 : null_member_pointer_value_p (folded))
7429 expr = folded;
7433 if (TYPE_REF_P (type))
7434 expr = mark_lvalue_use (expr);
7435 else
7436 expr = mark_rvalue_use (expr);
7438 /* HACK: Due to double coercion, we can get a
7439 NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
7440 which is the tree that we built on the first call (see
7441 below when coercing to reference to object or to reference to
7442 function). We just strip everything and get to the arg.
7443 See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
7444 for examples. */
7445 if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
7447 /* Check this before we strip *& to avoid redundancy. */
7448 if (!mark_single_function (expr, complain))
7449 return error_mark_node;
7451 tree probe_type, probe = expr;
7452 if (REFERENCE_REF_P (probe))
7453 probe = TREE_OPERAND (probe, 0);
7454 probe_type = TREE_TYPE (probe);
7455 if (TREE_CODE (probe) == NOP_EXPR)
7457 /* ??? Maybe we could use convert_from_reference here, but we
7458 would need to relax its constraints because the NOP_EXPR
7459 could actually change the type to something more cv-qualified,
7460 and this is not folded by convert_from_reference. */
7461 tree addr = TREE_OPERAND (probe, 0);
7462 if (TYPE_REF_P (probe_type)
7463 && TREE_CODE (addr) == ADDR_EXPR
7464 && TYPE_PTR_P (TREE_TYPE (addr))
7465 && (same_type_ignoring_top_level_qualifiers_p
7466 (TREE_TYPE (probe_type),
7467 TREE_TYPE (TREE_TYPE (addr)))))
7469 expr = TREE_OPERAND (addr, 0);
7470 expr_type = TREE_TYPE (probe_type);
7475 /* [temp.arg.nontype]/5, bullet 1
7477 For a non-type template-parameter of integral or enumeration type,
7478 integral promotions (_conv.prom_) and integral conversions
7479 (_conv.integral_) are applied. */
7480 if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7481 || SCALAR_FLOAT_TYPE_P (type))
7483 if (cxx_dialect < cxx11)
7485 tree t = build_converted_constant_expr (type, expr, complain);
7486 t = maybe_constant_value (t);
7487 if (t != error_mark_node)
7488 expr = t;
7491 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
7492 return error_mark_node;
7494 /* Notice that there are constant expressions like '4 % 0' which
7495 do not fold into integer constants. */
7496 if (!CONSTANT_CLASS_P (expr) && !val_dep_p)
7498 if (complain & tf_error)
7500 int errs = errorcount, warns = warningcount + werrorcount;
7501 if (!require_potential_constant_expression (expr))
7502 expr = error_mark_node;
7503 else
7504 expr = cxx_constant_value (expr);
7505 if (errorcount > errs || warningcount + werrorcount > warns)
7506 inform (loc, "in template argument for type %qT", type);
7507 if (expr == error_mark_node)
7508 return NULL_TREE;
7509 /* else cxx_constant_value complained but gave us
7510 a real constant, so go ahead. */
7511 if (!CONSTANT_CLASS_P (expr))
7513 /* Some assemble time constant expressions like
7514 (intptr_t)&&lab1 - (intptr_t)&&lab2 or
7515 4 + (intptr_t)&&var satisfy reduced_constant_expression_p
7516 as we can emit them into .rodata initializers of
7517 variables, yet they can't fold into an INTEGER_CST at
7518 compile time. Refuse them here. */
7519 gcc_checking_assert (reduced_constant_expression_p (expr));
7520 error_at (loc, "template argument %qE for type %qT not "
7521 "a compile-time constant", expr, type);
7522 return NULL_TREE;
7525 else
7526 return NULL_TREE;
7529 /* Avoid typedef problems. */
7530 if (TREE_TYPE (expr) != type)
7531 expr = fold_convert (type, expr);
7533 /* [temp.arg.nontype]/5, bullet 2
7535 For a non-type template-parameter of type pointer to object,
7536 qualification conversions (_conv.qual_) and the array-to-pointer
7537 conversion (_conv.array_) are applied. */
7538 else if (TYPE_PTROBV_P (type))
7540 tree decayed = expr;
7542 /* Look through any NOP_EXPRs around an ADDR_EXPR, whether they come from
7543 decay_conversion or an explicit cast. If it's a problematic cast,
7544 we'll complain about it below. */
7545 if (TREE_CODE (expr) == NOP_EXPR)
7547 tree probe = expr;
7548 STRIP_NOPS (probe);
7549 if (TREE_CODE (probe) == ADDR_EXPR
7550 && TYPE_PTR_P (TREE_TYPE (probe)))
7552 expr = probe;
7553 expr_type = TREE_TYPE (expr);
7557 /* [temp.arg.nontype]/1 (TC1 version, DR 49):
7559 A template-argument for a non-type, non-template template-parameter
7560 shall be one of: [...]
7562 -- the name of a non-type template-parameter;
7563 -- the address of an object or function with external linkage, [...]
7564 expressed as "& id-expression" where the & is optional if the name
7565 refers to a function or array, or if the corresponding
7566 template-parameter is a reference.
7568 Here, we do not care about functions, as they are invalid anyway
7569 for a parameter of type pointer-to-object. */
7571 if (val_dep_p)
7572 /* Non-type template parameters are OK. */
7574 else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7575 /* Null pointer values are OK in C++11. */;
7576 else if (TREE_CODE (expr) != ADDR_EXPR
7577 && !INDIRECT_TYPE_P (expr_type))
7578 /* Other values, like integer constants, might be valid
7579 non-type arguments of some other type. */
7580 return error_mark_node;
7581 else if (invalid_tparm_referent_p (type, expr, complain))
7582 return NULL_TREE;
7584 expr = decayed;
7586 expr = perform_qualification_conversions (type, expr);
7587 if (expr == error_mark_node)
7588 return error_mark_node;
7590 /* [temp.arg.nontype]/5, bullet 3
7592 For a non-type template-parameter of type reference to object, no
7593 conversions apply. The type referred to by the reference may be more
7594 cv-qualified than the (otherwise identical) type of the
7595 template-argument. The template-parameter is bound directly to the
7596 template-argument, which must be an lvalue. */
7597 else if (TYPE_REF_OBJ_P (type))
7599 if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
7600 expr_type))
7601 return error_mark_node;
7603 if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
7605 if (complain & tf_error)
7606 error ("%qE is not a valid template argument for type %qT "
7607 "because of conflicts in cv-qualification", expr, type);
7608 return NULL_TREE;
7611 if (!lvalue_p (expr))
7613 if (complain & tf_error)
7614 error ("%qE is not a valid template argument for type %qT "
7615 "because it is not an lvalue", expr, type);
7616 return NULL_TREE;
7619 /* [temp.arg.nontype]/1
7621 A template-argument for a non-type, non-template template-parameter
7622 shall be one of: [...]
7624 -- the address of an object or function with external linkage. */
7625 if (INDIRECT_REF_P (expr)
7626 && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
7628 expr = TREE_OPERAND (expr, 0);
7629 if (DECL_P (expr))
7631 if (complain & tf_error)
7632 error ("%q#D is not a valid template argument for type %qT "
7633 "because a reference variable does not have a constant "
7634 "address", expr, type);
7635 return NULL_TREE;
7639 if (TYPE_REF_OBJ_P (TREE_TYPE (expr)) && val_dep_p)
7640 /* OK, dependent reference. We don't want to ask whether a DECL is
7641 itself value-dependent, since what we want here is its address. */;
7642 else
7644 expr = build_address (expr);
7646 if (invalid_tparm_referent_p (type, expr, complain))
7647 return NULL_TREE;
7650 if (!same_type_p (type, TREE_TYPE (expr)))
7651 expr = build_nop (type, expr);
7653 /* [temp.arg.nontype]/5, bullet 4
7655 For a non-type template-parameter of type pointer to function, only
7656 the function-to-pointer conversion (_conv.func_) is applied. If the
7657 template-argument represents a set of overloaded functions (or a
7658 pointer to such), the matching function is selected from the set
7659 (_over.over_). */
7660 else if (TYPE_PTRFN_P (type))
7662 /* If the argument is a template-id, we might not have enough
7663 context information to decay the pointer. */
7664 if (!type_unknown_p (expr_type))
7666 expr = decay_conversion (expr, complain);
7667 if (expr == error_mark_node)
7668 return error_mark_node;
7671 if (cxx_dialect >= cxx11 && integer_zerop (expr))
7672 /* Null pointer values are OK in C++11. */
7673 return perform_qualification_conversions (type, expr);
7675 expr = convert_nontype_argument_function (type, expr, complain);
7676 if (!expr || expr == error_mark_node)
7677 return expr;
7679 /* [temp.arg.nontype]/5, bullet 5
7681 For a non-type template-parameter of type reference to function, no
7682 conversions apply. If the template-argument represents a set of
7683 overloaded functions, the matching function is selected from the set
7684 (_over.over_). */
7685 else if (TYPE_REFFN_P (type))
7687 if (TREE_CODE (expr) == ADDR_EXPR)
7689 if (complain & tf_error)
7691 error ("%qE is not a valid template argument for type %qT "
7692 "because it is a pointer", expr, type);
7693 inform (input_location, "try using %qE instead",
7694 TREE_OPERAND (expr, 0));
7696 return NULL_TREE;
7699 expr = convert_nontype_argument_function (type, expr, complain);
7700 if (!expr || expr == error_mark_node)
7701 return expr;
7703 /* [temp.arg.nontype]/5, bullet 6
7705 For a non-type template-parameter of type pointer to member function,
7706 no conversions apply. If the template-argument represents a set of
7707 overloaded member functions, the matching member function is selected
7708 from the set (_over.over_). */
7709 else if (TYPE_PTRMEMFUNC_P (type))
7711 expr = instantiate_type (type, expr, tf_none);
7712 if (expr == error_mark_node)
7713 return error_mark_node;
7715 /* [temp.arg.nontype] bullet 1 says the pointer to member
7716 expression must be a pointer-to-member constant. */
7717 if (!val_dep_p
7718 && !check_valid_ptrmem_cst_expr (type, expr, complain))
7719 return NULL_TREE;
7721 /* Repeated conversion can't deal with a conversion that turns PTRMEM_CST
7722 into a CONSTRUCTOR, so build up a new PTRMEM_CST instead. */
7723 if (fnptr_conv_p (type, TREE_TYPE (expr)))
7724 expr = make_ptrmem_cst (type, PTRMEM_CST_MEMBER (expr));
7726 /* [temp.arg.nontype]/5, bullet 7
7728 For a non-type template-parameter of type pointer to data member,
7729 qualification conversions (_conv.qual_) are applied. */
7730 else if (TYPE_PTRDATAMEM_P (type))
7732 /* [temp.arg.nontype] bullet 1 says the pointer to member
7733 expression must be a pointer-to-member constant. */
7734 if (!val_dep_p
7735 && !check_valid_ptrmem_cst_expr (type, expr, complain))
7736 return NULL_TREE;
7738 expr = perform_qualification_conversions (type, expr);
7739 if (expr == error_mark_node)
7740 return expr;
7742 else if (NULLPTR_TYPE_P (type))
7744 if (!NULLPTR_TYPE_P (TREE_TYPE (expr)))
7746 if (complain & tf_error)
7747 error ("%qE is not a valid template argument for type %qT "
7748 "because it is of type %qT", expr, type, TREE_TYPE (expr));
7749 return NULL_TREE;
7751 return expr;
7753 else if (CLASS_TYPE_P (type))
7755 /* Replace the argument with a reference to the corresponding template
7756 parameter object. */
7757 if (!val_dep_p)
7758 expr = create_template_parm_object (expr, complain);
7759 if (expr == error_mark_node)
7760 return NULL_TREE;
7762 /* A template non-type parameter must be one of the above. */
7763 else
7764 gcc_unreachable ();
7766 /* Sanity check: did we actually convert the argument to the
7767 right type? */
7768 gcc_assert (same_type_ignoring_top_level_qualifiers_p
7769 (type, TREE_TYPE (expr)));
7770 return convert_from_reference (expr);
7773 /* Subroutine of coerce_template_template_parms, which returns 1 if
7774 PARM_PARM and ARG_PARM match using the rule for the template
7775 parameters of template template parameters. Both PARM and ARG are
7776 template parameters; the rest of the arguments are the same as for
7777 coerce_template_template_parms.
7779 static int
7780 coerce_template_template_parm (tree parm,
7781 tree arg,
7782 tsubst_flags_t complain,
7783 tree in_decl,
7784 tree outer_args)
7786 if (arg == NULL_TREE || error_operand_p (arg)
7787 || parm == NULL_TREE || error_operand_p (parm))
7788 return 0;
7790 if (TREE_CODE (arg) != TREE_CODE (parm))
7791 return 0;
7793 switch (TREE_CODE (parm))
7795 case TEMPLATE_DECL:
7796 /* We encounter instantiations of templates like
7797 template <template <template <class> class> class TT>
7798 class C; */
7800 if (!coerce_template_template_parms
7801 (parm, arg, complain, in_decl, outer_args))
7802 return 0;
7804 /* Fall through. */
7806 case TYPE_DECL:
7807 if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
7808 && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7809 /* Argument is a parameter pack but parameter is not. */
7810 return 0;
7811 break;
7813 case PARM_DECL:
7814 /* The tsubst call is used to handle cases such as
7816 template <int> class C {};
7817 template <class T, template <T> class TT> class D {};
7818 D<int, C> d;
7820 i.e. the parameter list of TT depends on earlier parameters. */
7821 if (!uses_template_parms (TREE_TYPE (arg)))
7823 tree t = tsubst (TREE_TYPE (parm), outer_args, complain, in_decl);
7824 if (!uses_template_parms (t)
7825 && !same_type_p (t, TREE_TYPE (arg)))
7826 return 0;
7829 if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
7830 && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7831 /* Argument is a parameter pack but parameter is not. */
7832 return 0;
7834 break;
7836 default:
7837 gcc_unreachable ();
7840 return 1;
7843 /* Coerce template argument list ARGLIST for use with template
7844 template-parameter TEMPL. */
7846 static tree
7847 coerce_template_args_for_ttp (tree templ, tree arglist,
7848 tsubst_flags_t complain)
7850 /* Consider an example where a template template parameter declared as
7852 template <class T, class U = std::allocator<T> > class TT
7854 The template parameter level of T and U are one level larger than
7855 of TT. To proper process the default argument of U, say when an
7856 instantiation `TT<int>' is seen, we need to build the full
7857 arguments containing {int} as the innermost level. Outer levels,
7858 available when not appearing as default template argument, can be
7859 obtained from the arguments of the enclosing template.
7861 Suppose that TT is later substituted with std::vector. The above
7862 instantiation is `TT<int, std::allocator<T> >' with TT at
7863 level 1, and T at level 2, while the template arguments at level 1
7864 becomes {std::vector} and the inner level 2 is {int}. */
7866 tree outer = DECL_CONTEXT (templ);
7867 if (outer)
7868 outer = generic_targs_for (outer);
7869 else if (current_template_parms)
7871 /* This is an argument of the current template, so we haven't set
7872 DECL_CONTEXT yet. We can also get here when level-lowering a
7873 bound ttp. */
7874 tree relevant_template_parms;
7876 /* Parameter levels that are greater than the level of the given
7877 template template parm are irrelevant. */
7878 relevant_template_parms = current_template_parms;
7879 while (TMPL_PARMS_DEPTH (relevant_template_parms)
7880 != TEMPLATE_TYPE_LEVEL (TREE_TYPE (templ)))
7881 relevant_template_parms = TREE_CHAIN (relevant_template_parms);
7883 outer = template_parms_to_args (relevant_template_parms);
7886 if (outer)
7887 arglist = add_to_template_args (outer, arglist);
7889 tree parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7890 return coerce_template_parms (parmlist, arglist, templ, complain);
7893 /* A cache of template template parameters with match-all default
7894 arguments. */
7895 static GTY((deletable)) hash_map<tree,tree> *defaulted_ttp_cache;
7897 /* T is a bound template template-parameter. Copy its arguments into default
7898 arguments of the template template-parameter's template parameters. */
7900 static tree
7901 add_defaults_to_ttp (tree otmpl)
7903 if (tree *c = hash_map_safe_get (defaulted_ttp_cache, otmpl))
7904 return *c;
7906 tree ntmpl = copy_node (otmpl);
7908 tree ntype = copy_node (TREE_TYPE (otmpl));
7909 TYPE_STUB_DECL (ntype) = TYPE_NAME (ntype) = ntmpl;
7910 TYPE_MAIN_VARIANT (ntype) = ntype;
7911 TYPE_POINTER_TO (ntype) = TYPE_REFERENCE_TO (ntype) = NULL_TREE;
7912 TYPE_NAME (ntype) = ntmpl;
7913 SET_TYPE_STRUCTURAL_EQUALITY (ntype);
7915 tree idx = TEMPLATE_TYPE_PARM_INDEX (ntype)
7916 = copy_node (TEMPLATE_TYPE_PARM_INDEX (ntype));
7917 TEMPLATE_PARM_DECL (idx) = ntmpl;
7918 TREE_TYPE (ntmpl) = TREE_TYPE (idx) = ntype;
7920 tree oparms = DECL_TEMPLATE_PARMS (otmpl);
7921 tree parms = DECL_TEMPLATE_PARMS (ntmpl) = copy_node (oparms);
7922 TREE_CHAIN (parms) = TREE_CHAIN (oparms);
7923 tree vec = TREE_VALUE (parms) = copy_node (TREE_VALUE (parms));
7924 for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
7926 tree o = TREE_VEC_ELT (vec, i);
7927 if (!template_parameter_pack_p (TREE_VALUE (o)))
7929 tree n = TREE_VEC_ELT (vec, i) = copy_node (o);
7930 TREE_PURPOSE (n) = any_targ_node;
7934 hash_map_safe_put<hm_ggc> (defaulted_ttp_cache, otmpl, ntmpl);
7935 return ntmpl;
7938 /* ARG is a bound potential template template-argument, and PARGS is a list
7939 of arguments for the corresponding template template-parameter. Adjust
7940 PARGS as appropriate for application to ARG's template, and if ARG is a
7941 BOUND_TEMPLATE_TEMPLATE_PARM, possibly adjust it to add default template
7942 arguments to the template template parameter. */
7944 static tree
7945 coerce_ttp_args_for_tta (tree& arg, tree pargs, tsubst_flags_t complain)
7947 ++processing_template_decl;
7948 tree arg_tmpl = TYPE_TI_TEMPLATE (arg);
7949 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
7951 /* When comparing two template template-parameters in partial ordering,
7952 rewrite the one currently being used as an argument to have default
7953 arguments for all parameters. */
7954 arg_tmpl = add_defaults_to_ttp (arg_tmpl);
7955 pargs = coerce_template_args_for_ttp (arg_tmpl, pargs, complain);
7956 if (pargs != error_mark_node)
7957 arg = bind_template_template_parm (TREE_TYPE (arg_tmpl),
7958 TYPE_TI_ARGS (arg));
7960 else
7962 tree aparms
7963 = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (arg_tmpl));
7964 pargs = coerce_template_parms (aparms, pargs, arg_tmpl, complain);
7966 --processing_template_decl;
7967 return pargs;
7970 /* Subroutine of unify for the case when PARM is a
7971 BOUND_TEMPLATE_TEMPLATE_PARM. */
7973 static int
7974 unify_bound_ttp_args (tree tparms, tree targs, tree parm, tree& arg,
7975 bool explain_p)
7977 tree parmvec = TYPE_TI_ARGS (parm);
7978 tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
7980 /* The template template parm might be variadic and the argument
7981 not, so flatten both argument lists. */
7982 parmvec = expand_template_argument_pack (parmvec);
7983 argvec = expand_template_argument_pack (argvec);
7985 if (flag_new_ttp)
7987 /* In keeping with P0522R0, adjust P's template arguments
7988 to apply to A's template; then flatten it again. */
7989 tree nparmvec = coerce_ttp_args_for_tta (arg, parmvec, tf_none);
7990 nparmvec = expand_template_argument_pack (nparmvec);
7992 if (unify (tparms, targs, nparmvec, argvec,
7993 UNIFY_ALLOW_NONE, explain_p))
7994 return 1;
7996 /* If the P0522 adjustment eliminated a pack expansion, deduce
7997 empty packs. */
7998 if (flag_new_ttp
7999 && TREE_VEC_LENGTH (nparmvec) < TREE_VEC_LENGTH (parmvec)
8000 && unify_pack_expansion (tparms, targs, parmvec, argvec,
8001 DEDUCE_EXACT, /*sub*/true, explain_p))
8002 return 1;
8004 else
8006 /* Deduce arguments T, i from TT<T> or TT<i>.
8007 We check each element of PARMVEC and ARGVEC individually
8008 rather than the whole TREE_VEC since they can have
8009 different number of elements, which is allowed under N2555. */
8011 int len = TREE_VEC_LENGTH (parmvec);
8013 /* Check if the parameters end in a pack, making them
8014 variadic. */
8015 int parm_variadic_p = 0;
8016 if (len > 0
8017 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
8018 parm_variadic_p = 1;
8020 for (int i = 0; i < len - parm_variadic_p; ++i)
8021 /* If the template argument list of P contains a pack
8022 expansion that is not the last template argument, the
8023 entire template argument list is a non-deduced
8024 context. */
8025 if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
8026 return unify_success (explain_p);
8028 if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
8029 return unify_too_few_arguments (explain_p,
8030 TREE_VEC_LENGTH (argvec), len);
8032 for (int i = 0; i < len - parm_variadic_p; ++i)
8033 if (unify (tparms, targs,
8034 TREE_VEC_ELT (parmvec, i),
8035 TREE_VEC_ELT (argvec, i),
8036 UNIFY_ALLOW_NONE, explain_p))
8037 return 1;
8039 if (parm_variadic_p
8040 && unify_pack_expansion (tparms, targs,
8041 parmvec, argvec,
8042 DEDUCE_EXACT,
8043 /*subr=*/true, explain_p))
8044 return 1;
8047 return 0;
8050 /* Return 1 if PARM_TMPL and ARG_TMPL match using rule for
8051 template template parameters.
8053 Consider the example:
8054 template <class T> class A;
8055 template<template <class U> class TT> class B;
8057 For B<A>, PARM_TMPL is TT, while ARG_TMPL is A,
8058 and OUTER_ARGS contains A. */
8060 static int
8061 coerce_template_template_parms (tree parm_tmpl,
8062 tree arg_tmpl,
8063 tsubst_flags_t complain,
8064 tree in_decl,
8065 tree outer_args)
8067 int nparms, nargs, i;
8068 tree parm, arg;
8069 int variadic_p = 0;
8071 tree parm_parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm_tmpl));
8072 tree arg_parms_full = DECL_TEMPLATE_PARMS (arg_tmpl);
8073 tree arg_parms = INNERMOST_TEMPLATE_PARMS (arg_parms_full);
8075 gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
8076 gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
8078 nparms = TREE_VEC_LENGTH (parm_parms);
8079 nargs = TREE_VEC_LENGTH (arg_parms);
8081 if (flag_new_ttp)
8083 /* P0522R0: A template template-parameter P is at least as specialized as
8084 a template template-argument A if, given the following rewrite to two
8085 function templates, the function template corresponding to P is at
8086 least as specialized as the function template corresponding to A
8087 according to the partial ordering rules for function templates
8088 ([temp.func.order]). Given an invented class template X with the
8089 template parameter list of A (including default arguments):
8091 * Each of the two function templates has the same template parameters,
8092 respectively, as P or A.
8094 * Each function template has a single function parameter whose type is
8095 a specialization of X with template arguments corresponding to the
8096 template parameters from the respective function template where, for
8097 each template parameter PP in the template parameter list of the
8098 function template, a corresponding template argument AA is formed. If
8099 PP declares a parameter pack, then AA is the pack expansion
8100 PP... ([temp.variadic]); otherwise, AA is the id-expression PP.
8102 If the rewrite produces an invalid type, then P is not at least as
8103 specialized as A. */
8105 /* So coerce P's args to apply to A's parms, and then deduce between A's
8106 args and the converted args. If that succeeds, A is at least as
8107 specialized as P, so they match.*/
8108 processing_template_decl_sentinel ptds (/*reset*/false);
8109 ++processing_template_decl;
8111 tree pargs = template_parms_level_to_args (parm_parms);
8113 /* PARM and ARG might be at different template depths, and we want to
8114 pass the right additional levels of args when coercing PARGS to
8115 ARG_PARMS in case we need to do any substitution into non-type
8116 template parameter types.
8118 OUTER_ARGS are not the right outer levels in this case, as they are
8119 the args we're building up for PARM, and for the coercion we want the
8120 args for ARG. If DECL_CONTEXT isn't set for a template template
8121 parameter, we can assume that it's in the current scope. In that case
8122 we might end up adding more levels than needed, but that shouldn't be
8123 a problem; any args we need to refer to are at the right level. */
8124 tree ctx = DECL_CONTEXT (arg_tmpl);
8125 if (!ctx && DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
8126 ctx = current_scope ();
8127 tree scope_args = NULL_TREE;
8128 if (tree tinfo = get_template_info (ctx))
8129 scope_args = TI_ARGS (tinfo);
8130 pargs = add_to_template_args (scope_args, pargs);
8132 pargs = coerce_template_parms (arg_parms, pargs, NULL_TREE, tf_none);
8133 if (pargs != error_mark_node)
8135 tree targs = make_tree_vec (nargs);
8136 tree aargs = template_parms_level_to_args (arg_parms);
8137 if (!unify (arg_parms, targs, aargs, pargs, UNIFY_ALLOW_NONE,
8138 /*explain*/false))
8139 return 1;
8143 /* Determine whether we have a parameter pack at the end of the
8144 template template parameter's template parameter list. */
8145 if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
8147 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
8149 if (error_operand_p (parm))
8150 return 0;
8152 switch (TREE_CODE (parm))
8154 case TEMPLATE_DECL:
8155 case TYPE_DECL:
8156 if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
8157 variadic_p = 1;
8158 break;
8160 case PARM_DECL:
8161 if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
8162 variadic_p = 1;
8163 break;
8165 default:
8166 gcc_unreachable ();
8170 if (nargs != nparms
8171 && !(variadic_p && nargs >= nparms - 1))
8172 return 0;
8174 /* Check all of the template parameters except the parameter pack at
8175 the end (if any). */
8176 for (i = 0; i < nparms - variadic_p; ++i)
8178 if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
8179 || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
8180 continue;
8182 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
8183 arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
8185 if (!coerce_template_template_parm (parm, arg, complain, in_decl,
8186 outer_args))
8187 return 0;
8191 if (variadic_p)
8193 /* Check each of the template parameters in the template
8194 argument against the template parameter pack at the end of
8195 the template template parameter. */
8196 if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
8197 return 0;
8199 parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
8201 for (; i < nargs; ++i)
8203 if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
8204 continue;
8206 arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
8208 if (!coerce_template_template_parm (parm, arg, complain, in_decl,
8209 outer_args))
8210 return 0;
8214 return 1;
8217 /* Verifies that the deduced template arguments (in TARGS) for the
8218 template template parameters (in TPARMS) represent valid bindings,
8219 by comparing the template parameter list of each template argument
8220 to the template parameter list of its corresponding template
8221 template parameter, in accordance with DR150. This
8222 routine can only be called after all template arguments have been
8223 deduced. It will return TRUE if all of the template template
8224 parameter bindings are okay, FALSE otherwise. */
8225 bool
8226 template_template_parm_bindings_ok_p (tree tparms, tree targs)
8228 int i, ntparms = TREE_VEC_LENGTH (tparms);
8229 bool ret = true;
8231 /* We're dealing with template parms in this process. */
8232 ++processing_template_decl;
8234 targs = INNERMOST_TEMPLATE_ARGS (targs);
8236 for (i = 0; i < ntparms; ++i)
8238 tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
8239 tree targ = TREE_VEC_ELT (targs, i);
8241 if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
8243 tree packed_args = NULL_TREE;
8244 int idx, len = 1;
8246 if (ARGUMENT_PACK_P (targ))
8248 /* Look inside the argument pack. */
8249 packed_args = ARGUMENT_PACK_ARGS (targ);
8250 len = TREE_VEC_LENGTH (packed_args);
8253 for (idx = 0; idx < len; ++idx)
8255 if (packed_args)
8256 /* Extract the next argument from the argument
8257 pack. */
8258 targ = TREE_VEC_ELT (packed_args, idx);
8260 if (PACK_EXPANSION_P (targ))
8261 /* Look at the pattern of the pack expansion. */
8262 targ = PACK_EXPANSION_PATTERN (targ);
8264 /* Extract the template parameters from the template
8265 argument. */
8266 if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
8267 targ = TYPE_NAME (targ);
8269 /* Verify that we can coerce the template template
8270 parameters from the template argument to the template
8271 parameter. This requires an exact match. */
8272 if (TREE_CODE (targ) == TEMPLATE_DECL
8273 && !coerce_template_template_parms
8274 (tparm,
8275 targ,
8276 tf_none,
8277 tparm,
8278 targs))
8280 ret = false;
8281 goto out;
8287 out:
8289 --processing_template_decl;
8290 return ret;
8293 /* Since type attributes aren't mangled, we need to strip them from
8294 template type arguments. */
8296 tree
8297 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
8299 if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
8300 return arg;
8301 bool removed_attributes = false;
8302 tree canon = strip_typedefs (arg, &removed_attributes);
8303 if (removed_attributes
8304 && (complain & tf_warning))
8305 warning (OPT_Wignored_attributes,
8306 "ignoring attributes on template argument %qT", arg);
8307 return canon;
8310 /* And from inside dependent non-type arguments like sizeof(Type). */
8312 static tree
8313 canonicalize_expr_argument (tree arg, tsubst_flags_t complain)
8315 if (!arg || arg == error_mark_node)
8316 return arg;
8317 bool removed_attributes = false;
8318 tree canon = strip_typedefs_expr (arg, &removed_attributes);
8319 if (removed_attributes
8320 && (complain & tf_warning))
8321 warning (OPT_Wignored_attributes,
8322 "ignoring attributes in template argument %qE", arg);
8323 return canon;
8326 /* A template declaration can be substituted for a constrained
8327 template template parameter only when the argument is no more
8328 constrained than the parameter. */
8330 static bool
8331 is_compatible_template_arg (tree parm, tree arg)
8333 tree parm_cons = get_constraints (parm);
8335 /* For now, allow constrained template template arguments
8336 and unconstrained template template parameters. */
8337 if (parm_cons == NULL_TREE)
8338 return true;
8340 /* If the template parameter is constrained, we need to rewrite its
8341 constraints in terms of the ARG's template parameters. This ensures
8342 that all of the template parameter types will have the same depth.
8344 Note that this is only valid when coerce_template_template_parm is
8345 true for the innermost template parameters of PARM and ARG. In other
8346 words, because coercion is successful, this conversion will be valid. */
8347 tree new_args = NULL_TREE;
8348 if (parm_cons)
8350 tree aparms = DECL_INNERMOST_TEMPLATE_PARMS (arg);
8351 new_args = template_parms_level_to_args (aparms);
8352 ++processing_template_decl;
8353 parm_cons = tsubst_constraint_info (parm_cons, new_args,
8354 tf_none, NULL_TREE);
8355 --processing_template_decl;
8356 if (parm_cons == error_mark_node)
8357 return false;
8360 return weakly_subsumes (parm_cons, arg);
8363 // Convert a placeholder argument into a binding to the original
8364 // parameter. The original parameter is saved as the TREE_TYPE of
8365 // ARG.
8366 static inline tree
8367 convert_wildcard_argument (tree parm, tree arg)
8369 TREE_TYPE (arg) = parm;
8370 return arg;
8373 /* We can't fully resolve ARG given as a non-type template argument to TYPE,
8374 because one of them is dependent. But we need to represent the
8375 conversion for the benefit of cp_tree_equal. */
8377 static tree
8378 maybe_convert_nontype_argument (tree type, tree arg)
8380 /* Auto parms get no conversion. */
8381 if (type_uses_auto (type))
8382 return arg;
8383 /* We don't need or want to add this conversion now if we're going to use the
8384 argument for deduction. */
8385 if (value_dependent_expression_p (arg))
8386 return arg;
8388 type = cv_unqualified (type);
8389 tree argtype = TREE_TYPE (arg);
8390 if (same_type_p (type, argtype))
8391 return arg;
8393 arg = build1 (IMPLICIT_CONV_EXPR, type, arg);
8394 IMPLICIT_CONV_EXPR_NONTYPE_ARG (arg) = true;
8395 return arg;
8398 /* Convert the indicated template ARG as necessary to match the
8399 indicated template PARM. Returns the converted ARG, or
8400 error_mark_node if the conversion was unsuccessful. Error and
8401 warning messages are issued under control of COMPLAIN. This
8402 conversion is for the Ith parameter in the parameter list. ARGS is
8403 the full set of template arguments deduced so far. */
8405 static tree
8406 convert_template_argument (tree parm,
8407 tree arg,
8408 tree args,
8409 tsubst_flags_t complain,
8410 int i,
8411 tree in_decl)
8413 tree orig_arg;
8414 tree val;
8415 int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
8417 if (parm == error_mark_node || error_operand_p (arg))
8418 return error_mark_node;
8420 /* Trivially convert placeholders. */
8421 if (TREE_CODE (arg) == WILDCARD_DECL)
8422 return convert_wildcard_argument (parm, arg);
8424 if (arg == any_targ_node)
8425 return arg;
8427 if (TREE_CODE (arg) == TREE_LIST
8428 && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
8430 /* The template argument was the name of some
8431 member function. That's usually
8432 invalid, but static members are OK. In any
8433 case, grab the underlying fields/functions
8434 and issue an error later if required. */
8435 TREE_TYPE (arg) = unknown_type_node;
8438 orig_arg = arg;
8440 requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
8441 requires_type = (TREE_CODE (parm) == TYPE_DECL
8442 || requires_tmpl_type);
8444 /* When determining whether an argument pack expansion is a template,
8445 look at the pattern. */
8446 if (PACK_EXPANSION_P (arg))
8447 arg = PACK_EXPANSION_PATTERN (arg);
8449 /* Deal with an injected-class-name used as a template template arg. */
8450 if (requires_tmpl_type && CLASS_TYPE_P (arg))
8452 tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
8453 if (TREE_CODE (t) == TEMPLATE_DECL)
8455 if (cxx_dialect >= cxx11)
8456 /* OK under DR 1004. */;
8457 else if (complain & tf_warning_or_error)
8458 pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
8459 " used as template template argument", TYPE_NAME (arg));
8460 else if (flag_pedantic_errors)
8461 t = arg;
8463 arg = t;
8467 is_tmpl_type =
8468 ((TREE_CODE (arg) == TEMPLATE_DECL
8469 && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
8470 || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
8471 || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8472 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
8474 if (is_tmpl_type
8475 && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8476 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
8477 arg = TYPE_STUB_DECL (arg);
8479 is_type = TYPE_P (arg) || is_tmpl_type;
8481 if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
8482 && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
8484 if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
8486 if (complain & tf_error)
8487 error ("invalid use of destructor %qE as a type", orig_arg);
8488 return error_mark_node;
8491 permerror (input_location,
8492 "to refer to a type member of a template parameter, "
8493 "use %<typename %E%>", orig_arg);
8495 orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
8496 TREE_OPERAND (arg, 1),
8497 typename_type,
8498 complain);
8499 arg = orig_arg;
8500 is_type = 1;
8502 if (is_type != requires_type)
8504 if (in_decl)
8506 if (complain & tf_error)
8508 error ("type/value mismatch at argument %d in template "
8509 "parameter list for %qD",
8510 i + 1, in_decl);
8511 if (is_type)
8513 /* The template argument is a type, but we're expecting
8514 an expression. */
8515 inform (input_location,
8516 " expected a constant of type %qT, got %qT",
8517 TREE_TYPE (parm),
8518 (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
8519 /* [temp.arg]/2: "In a template-argument, an ambiguity
8520 between a type-id and an expression is resolved to a
8521 type-id, regardless of the form of the corresponding
8522 template-parameter." So give the user a clue. */
8523 if (TREE_CODE (arg) == FUNCTION_TYPE)
8524 inform (input_location, " ambiguous template argument "
8525 "for non-type template parameter is treated as "
8526 "function type");
8528 else if (requires_tmpl_type)
8529 inform (input_location,
8530 " expected a class template, got %qE", orig_arg);
8531 else
8532 inform (input_location,
8533 " expected a type, got %qE", orig_arg);
8536 return error_mark_node;
8538 if (is_tmpl_type ^ requires_tmpl_type)
8540 if (in_decl && (complain & tf_error))
8542 error ("type/value mismatch at argument %d in template "
8543 "parameter list for %qD",
8544 i + 1, in_decl);
8545 if (is_tmpl_type)
8546 inform (input_location,
8547 " expected a type, got %qT", DECL_NAME (arg));
8548 else
8549 inform (input_location,
8550 " expected a class template, got %qT", orig_arg);
8552 return error_mark_node;
8555 if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
8556 /* We already did the appropriate conversion when packing args. */
8557 val = orig_arg;
8558 else if (is_type)
8560 if (requires_tmpl_type)
8562 if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
8563 /* The number of argument required is not known yet.
8564 Just accept it for now. */
8565 val = orig_arg;
8566 else
8568 /* Strip alias templates that are equivalent to another
8569 template. */
8570 arg = get_underlying_template (arg);
8572 if (coerce_template_template_parms (parm, arg,
8573 complain, in_decl,
8574 args))
8576 val = arg;
8578 /* TEMPLATE_TEMPLATE_PARM node is preferred over
8579 TEMPLATE_DECL. */
8580 if (val != error_mark_node)
8582 if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
8583 val = TREE_TYPE (val);
8584 if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
8585 val = make_pack_expansion (val, complain);
8588 else
8590 if (in_decl && (complain & tf_error))
8592 error ("type/value mismatch at argument %d in "
8593 "template parameter list for %qD",
8594 i + 1, in_decl);
8595 inform (input_location,
8596 " expected a template of type %qD, got %qT",
8597 parm, orig_arg);
8600 val = error_mark_node;
8603 // Check that the constraints are compatible before allowing the
8604 // substitution.
8605 if (val != error_mark_node)
8606 if (!is_compatible_template_arg (parm, arg))
8608 if (in_decl && (complain & tf_error))
8610 error ("constraint mismatch at argument %d in "
8611 "template parameter list for %qD",
8612 i + 1, in_decl);
8613 inform (input_location, " expected %qD but got %qD",
8614 parm, arg);
8616 val = error_mark_node;
8620 else
8621 val = orig_arg;
8622 /* We only form one instance of each template specialization.
8623 Therefore, if we use a non-canonical variant (i.e., a
8624 typedef), any future messages referring to the type will use
8625 the typedef, which is confusing if those future uses do not
8626 themselves also use the typedef. */
8627 if (TYPE_P (val))
8628 val = canonicalize_type_argument (val, complain);
8630 else
8632 tree t = TREE_TYPE (parm);
8634 if (TEMPLATE_PARM_LEVEL (get_template_parm_index (parm))
8635 > TMPL_ARGS_DEPTH (args))
8636 /* We don't have enough levels of args to do any substitution. This
8637 can happen in the context of -fnew-ttp-matching. */;
8638 else if (tree a = type_uses_auto (t))
8640 t = do_auto_deduction (t, arg, a, complain, adc_unify, args,
8641 LOOKUP_IMPLICIT, /*tmpl=*/in_decl);
8642 if (t == error_mark_node)
8643 return error_mark_node;
8645 else
8646 t = tsubst (t, args, complain, in_decl);
8648 /* Perform array-to-pointer and function-to-pointer conversion
8649 as per [temp.param]/10. */
8650 t = type_decays_to (t);
8652 if (invalid_nontype_parm_type_p (t, complain))
8653 return error_mark_node;
8655 /* Drop top-level cv-qualifiers on the substituted/deduced type of
8656 this non-type template parameter, as per [temp.param]/6. */
8657 t = cv_unqualified (t);
8659 if (t != TREE_TYPE (parm))
8660 t = canonicalize_type_argument (t, complain);
8662 if (!type_dependent_expression_p (orig_arg)
8663 && !uses_template_parms (t))
8664 /* We used to call digest_init here. However, digest_init
8665 will report errors, which we don't want when complain
8666 is zero. More importantly, digest_init will try too
8667 hard to convert things: for example, `0' should not be
8668 converted to pointer type at this point according to
8669 the standard. Accepting this is not merely an
8670 extension, since deciding whether or not these
8671 conversions can occur is part of determining which
8672 function template to call, or whether a given explicit
8673 argument specification is valid. */
8674 val = convert_nontype_argument (t, orig_arg, complain);
8675 else
8677 val = canonicalize_expr_argument (orig_arg, complain);
8678 val = maybe_convert_nontype_argument (t, val);
8682 if (val == NULL_TREE)
8683 val = error_mark_node;
8684 else if (val == error_mark_node && (complain & tf_error))
8685 error_at (cp_expr_loc_or_input_loc (orig_arg),
8686 "could not convert template argument %qE from %qT to %qT",
8687 orig_arg, TREE_TYPE (orig_arg), t);
8689 if (INDIRECT_REF_P (val))
8691 /* Reject template arguments that are references to built-in
8692 functions with no library fallbacks. */
8693 const_tree inner = TREE_OPERAND (val, 0);
8694 const_tree innertype = TREE_TYPE (inner);
8695 if (innertype
8696 && TYPE_REF_P (innertype)
8697 && TREE_CODE (TREE_TYPE (innertype)) == FUNCTION_TYPE
8698 && TREE_OPERAND_LENGTH (inner) > 0
8699 && reject_gcc_builtin (TREE_OPERAND (inner, 0)))
8700 return error_mark_node;
8703 if (TREE_CODE (val) == SCOPE_REF)
8705 /* Strip typedefs from the SCOPE_REF. */
8706 tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
8707 tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
8708 complain);
8709 val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
8710 QUALIFIED_NAME_IS_TEMPLATE (val));
8714 return val;
8717 /* Coerces the remaining template arguments in INNER_ARGS (from
8718 ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
8719 Returns the coerced argument pack. PARM_IDX is the position of this
8720 parameter in the template parameter list. ARGS is the original
8721 template argument list. */
8722 static tree
8723 coerce_template_parameter_pack (tree parms,
8724 int parm_idx,
8725 tree args,
8726 tree inner_args,
8727 int arg_idx,
8728 tree new_args,
8729 int* lost,
8730 tree in_decl,
8731 tsubst_flags_t complain)
8733 tree parm = TREE_VEC_ELT (parms, parm_idx);
8734 int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8735 tree packed_args;
8736 tree argument_pack;
8737 tree packed_parms = NULL_TREE;
8739 if (arg_idx > nargs)
8740 arg_idx = nargs;
8742 if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
8744 /* When the template parameter is a non-type template parameter pack
8745 or template template parameter pack whose type or template
8746 parameters use parameter packs, we know exactly how many arguments
8747 we are looking for. Build a vector of the instantiated decls for
8748 these template parameters in PACKED_PARMS. */
8749 /* We can't use make_pack_expansion here because it would interpret a
8750 _DECL as a use rather than a declaration. */
8751 tree decl = TREE_VALUE (parm);
8752 tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
8753 PACK_EXPANSION_PATTERN (exp) = decl;
8754 PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
8755 SET_TYPE_STRUCTURAL_EQUALITY (exp);
8757 TREE_VEC_LENGTH (args)--;
8758 packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
8759 TREE_VEC_LENGTH (args)++;
8761 if (packed_parms == error_mark_node)
8762 return error_mark_node;
8764 /* If we're doing a partial instantiation of a member template,
8765 verify that all of the types used for the non-type
8766 template parameter pack are, in fact, valid for non-type
8767 template parameters. */
8768 if (arg_idx < nargs
8769 && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
8771 int j, len = TREE_VEC_LENGTH (packed_parms);
8772 for (j = 0; j < len; ++j)
8774 tree t = TREE_VEC_ELT (packed_parms, j);
8775 if (TREE_CODE (t) == PARM_DECL
8776 && invalid_nontype_parm_type_p (TREE_TYPE (t), complain))
8777 return error_mark_node;
8779 /* We don't know how many args we have yet, just
8780 use the unconverted ones for now. */
8781 return NULL_TREE;
8784 packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
8786 /* Check if we have a placeholder pack, which indicates we're
8787 in the context of a introduction list. In that case we want
8788 to match this pack to the single placeholder. */
8789 else if (arg_idx < nargs
8790 && TREE_CODE (TREE_VEC_ELT (inner_args, arg_idx)) == WILDCARD_DECL
8791 && WILDCARD_PACK_P (TREE_VEC_ELT (inner_args, arg_idx)))
8793 nargs = arg_idx + 1;
8794 packed_args = make_tree_vec (1);
8796 else
8797 packed_args = make_tree_vec (nargs - arg_idx);
8799 /* Convert the remaining arguments, which will be a part of the
8800 parameter pack "parm". */
8801 int first_pack_arg = arg_idx;
8802 for (; arg_idx < nargs; ++arg_idx)
8804 tree arg = TREE_VEC_ELT (inner_args, arg_idx);
8805 tree actual_parm = TREE_VALUE (parm);
8806 int pack_idx = arg_idx - first_pack_arg;
8808 if (packed_parms)
8810 /* Once we've packed as many args as we have types, stop. */
8811 if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
8812 break;
8813 else if (PACK_EXPANSION_P (arg))
8814 /* We don't know how many args we have yet, just
8815 use the unconverted ones for now. */
8816 return NULL_TREE;
8817 else
8818 actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
8821 if (arg == error_mark_node)
8823 if (complain & tf_error)
8824 error ("template argument %d is invalid", arg_idx + 1);
8826 else
8827 arg = convert_template_argument (actual_parm,
8828 arg, new_args, complain, parm_idx,
8829 in_decl);
8830 if (arg == error_mark_node)
8831 (*lost)++;
8832 TREE_VEC_ELT (packed_args, pack_idx) = arg;
8835 if (arg_idx - first_pack_arg < TREE_VEC_LENGTH (packed_args)
8836 && TREE_VEC_LENGTH (packed_args) > 0)
8838 if (complain & tf_error)
8839 error ("wrong number of template arguments (%d, should be %d)",
8840 arg_idx - first_pack_arg, TREE_VEC_LENGTH (packed_args));
8841 return error_mark_node;
8844 if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
8845 || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
8846 argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
8847 else
8849 argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
8850 TREE_CONSTANT (argument_pack) = 1;
8853 ARGUMENT_PACK_ARGS (argument_pack) = packed_args;
8854 if (CHECKING_P)
8855 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
8856 TREE_VEC_LENGTH (packed_args));
8857 return argument_pack;
8860 /* Returns the number of pack expansions in the template argument vector
8861 ARGS. */
8863 static int
8864 pack_expansion_args_count (tree args)
8866 int i;
8867 int count = 0;
8868 if (args)
8869 for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
8871 tree elt = TREE_VEC_ELT (args, i);
8872 if (elt && PACK_EXPANSION_P (elt))
8873 ++count;
8875 return count;
8878 /* Convert all template arguments to their appropriate types, and
8879 return a vector containing the innermost resulting template
8880 arguments. If any error occurs, return error_mark_node. Error and
8881 warning messages are issued under control of COMPLAIN.
8883 If PARMS represents all template parameters levels, this function
8884 returns a vector of vectors representing all the resulting argument
8885 levels. Note that in this case, only the innermost arguments are
8886 coerced because the outermost ones are supposed to have been coerced
8887 already. Otherwise, if PARMS represents only (the innermost) vector
8888 of parameters, this function returns a vector containing just the
8889 innermost resulting arguments.
8891 If REQUIRE_ALL_ARGS is false, argument deduction will be performed
8892 for arguments not specified in ARGS. If REQUIRE_ALL_ARGS is true,
8893 arguments not specified in ARGS must have default arguments which
8894 we'll use to fill in ARGS. */
8896 tree
8897 coerce_template_parms (tree parms,
8898 tree args,
8899 tree in_decl,
8900 tsubst_flags_t complain,
8901 bool require_all_args /* = true */)
8903 int nparms, nargs, parm_idx, arg_idx, lost = 0;
8904 tree orig_inner_args;
8905 tree inner_args;
8907 /* When used as a boolean value, indicates whether this is a
8908 variadic template parameter list. Since it's an int, we can also
8909 subtract it from nparms to get the number of non-variadic
8910 parameters. */
8911 int variadic_p = 0;
8912 int variadic_args_p = 0;
8913 int post_variadic_parms = 0;
8915 /* Adjustment to nparms for fixed parameter packs. */
8916 int fixed_pack_adjust = 0;
8917 int fixed_packs = 0;
8918 int missing = 0;
8920 /* Likewise for parameters with default arguments. */
8921 int default_p = 0;
8923 if (args == error_mark_node)
8924 return error_mark_node;
8926 bool return_full_args = false;
8927 if (TREE_CODE (parms) == TREE_LIST)
8929 if (TMPL_PARMS_DEPTH (parms) > 1)
8931 gcc_assert (TMPL_PARMS_DEPTH (parms) == TMPL_ARGS_DEPTH (args));
8932 return_full_args = true;
8934 parms = INNERMOST_TEMPLATE_PARMS (parms);
8937 nparms = TREE_VEC_LENGTH (parms);
8939 /* Determine if there are any parameter packs or default arguments. */
8940 for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
8942 tree parm = TREE_VEC_ELT (parms, parm_idx);
8943 if (variadic_p)
8944 ++post_variadic_parms;
8945 if (template_parameter_pack_p (TREE_VALUE (parm)))
8946 ++variadic_p;
8947 if (TREE_PURPOSE (parm))
8948 ++default_p;
8951 inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
8952 /* If there are no parameters that follow a parameter pack, we need to
8953 expand any argument packs so that we can deduce a parameter pack from
8954 some non-packed args followed by an argument pack, as in variadic85.C.
8955 If there are such parameters, we need to leave argument packs intact
8956 so the arguments are assigned properly. This can happen when dealing
8957 with a nested class inside a partial specialization of a class
8958 template, as in variadic92.C, or when deducing a template parameter pack
8959 from a sub-declarator, as in variadic114.C. */
8960 if (!post_variadic_parms)
8961 inner_args = expand_template_argument_pack (inner_args);
8963 /* Count any pack expansion args. */
8964 variadic_args_p = pack_expansion_args_count (inner_args);
8966 nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8967 if ((nargs - variadic_args_p > nparms && !variadic_p)
8968 || (nargs < nparms - variadic_p
8969 && require_all_args
8970 && !variadic_args_p
8971 && (TREE_VEC_ELT (parms, nargs) != error_mark_node
8972 && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs)))))
8974 bad_nargs:
8975 if (complain & tf_error)
8977 if (variadic_p || default_p)
8979 nparms -= variadic_p + default_p;
8980 error ("wrong number of template arguments "
8981 "(%d, should be at least %d)", nargs, nparms);
8983 else
8984 error ("wrong number of template arguments "
8985 "(%d, should be %d)", nargs, nparms);
8987 if (in_decl)
8988 inform (DECL_SOURCE_LOCATION (in_decl),
8989 "provided for %qD", in_decl);
8992 return error_mark_node;
8994 /* We can't pass a pack expansion to a non-pack parameter of an alias
8995 template (DR 1430). */
8996 else if (in_decl
8997 && (DECL_ALIAS_TEMPLATE_P (in_decl)
8998 || concept_definition_p (in_decl))
8999 && variadic_args_p
9000 && nargs - variadic_args_p < nparms - variadic_p)
9002 if (complain & tf_error)
9004 for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
9006 tree arg = TREE_VEC_ELT (inner_args, i);
9007 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
9009 if (PACK_EXPANSION_P (arg)
9010 && !template_parameter_pack_p (parm))
9012 if (DECL_ALIAS_TEMPLATE_P (in_decl))
9013 error_at (location_of (arg),
9014 "pack expansion argument for non-pack parameter "
9015 "%qD of alias template %qD", parm, in_decl);
9016 else
9017 error_at (location_of (arg),
9018 "pack expansion argument for non-pack parameter "
9019 "%qD of concept %qD", parm, in_decl);
9020 inform (DECL_SOURCE_LOCATION (parm), "declared here");
9021 goto found;
9024 gcc_unreachable ();
9025 found:;
9027 return error_mark_node;
9030 /* We need to evaluate the template arguments, even though this
9031 template-id may be nested within a "sizeof". */
9032 cp_evaluated ev;
9034 tree new_args = add_outermost_template_args (args, make_tree_vec (nparms));
9035 tree& new_inner_args = TMPL_ARGS_LEVEL (new_args, TMPL_ARGS_DEPTH (new_args));
9036 int pack_adjust = 0;
9037 for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
9039 tree arg;
9040 tree parm;
9042 /* Get the Ith template parameter. */
9043 parm = TREE_VEC_ELT (parms, parm_idx);
9045 if (parm == error_mark_node)
9047 TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
9048 continue;
9051 /* Calculate the next argument. */
9052 if (arg_idx < nargs)
9053 arg = TREE_VEC_ELT (inner_args, arg_idx);
9054 else
9055 arg = NULL_TREE;
9057 if (template_parameter_pack_p (TREE_VALUE (parm))
9058 && (arg || require_all_args || !(complain & tf_partial))
9059 && !(arg && ARGUMENT_PACK_P (arg)))
9061 /* Some arguments will be placed in the
9062 template parameter pack PARM. */
9063 arg = coerce_template_parameter_pack (parms, parm_idx, args,
9064 inner_args, arg_idx,
9065 new_args, &lost,
9066 in_decl, complain);
9068 if (arg == NULL_TREE)
9070 /* We don't know how many args we have yet, just use the
9071 unconverted (and still packed) ones for now. */
9072 new_inner_args = orig_inner_args;
9073 arg_idx = nargs;
9074 break;
9077 TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
9079 /* Store this argument. */
9080 if (arg == error_mark_node)
9082 lost++;
9083 /* We are done with all of the arguments. */
9084 arg_idx = nargs;
9085 break;
9087 else
9089 pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
9090 arg_idx += pack_adjust;
9091 if (fixed_parameter_pack_p (TREE_VALUE (parm)))
9093 ++fixed_packs;
9094 fixed_pack_adjust += pack_adjust;
9098 continue;
9100 else if (arg)
9102 if (PACK_EXPANSION_P (arg))
9104 /* "If every valid specialization of a variadic template
9105 requires an empty template parameter pack, the template is
9106 ill-formed, no diagnostic required." So check that the
9107 pattern works with this parameter. */
9108 tree pattern = PACK_EXPANSION_PATTERN (arg);
9109 tree conv = convert_template_argument (TREE_VALUE (parm),
9110 pattern, new_args,
9111 complain, parm_idx,
9112 in_decl);
9113 if (conv == error_mark_node)
9115 if (complain & tf_error)
9116 inform (input_location, "so any instantiation with a "
9117 "non-empty parameter pack would be ill-formed");
9118 ++lost;
9120 else if (TYPE_P (conv) && !TYPE_P (pattern))
9121 /* Recover from missing typename. */
9122 TREE_VEC_ELT (inner_args, arg_idx)
9123 = make_pack_expansion (conv, complain);
9125 /* We don't know how many args we have yet, just
9126 use the unconverted ones for now. */
9127 new_inner_args = inner_args;
9128 arg_idx = nargs;
9129 break;
9132 else if (require_all_args)
9134 /* There must be a default arg in this case. */
9135 arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
9136 complain, in_decl);
9137 /* The position of the first default template argument,
9138 is also the number of non-defaulted arguments in NEW_INNER_ARGS.
9139 Record that. */
9140 if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
9141 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
9142 arg_idx - pack_adjust);
9144 else
9145 break;
9147 if (arg == error_mark_node)
9149 if (complain & tf_error)
9150 error ("template argument %d is invalid", arg_idx + 1);
9152 else if (!arg)
9154 /* This can occur if there was an error in the template
9155 parameter list itself (which we would already have
9156 reported) that we are trying to recover from, e.g., a class
9157 template with a parameter list such as
9158 template<typename..., typename> (cpp0x/variadic150.C). */
9159 ++lost;
9161 /* This can also happen with a fixed parameter pack (71834). */
9162 if (arg_idx >= nargs)
9163 ++missing;
9165 else
9166 arg = convert_template_argument (TREE_VALUE (parm),
9167 arg, new_args, complain,
9168 parm_idx, in_decl);
9170 if (arg == error_mark_node)
9171 lost++;
9173 TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
9176 if (missing || arg_idx < nargs - variadic_args_p)
9178 /* If we had fixed parameter packs, we didn't know how many arguments we
9179 actually needed earlier; now we do. */
9180 nparms += fixed_pack_adjust;
9181 variadic_p -= fixed_packs;
9182 goto bad_nargs;
9185 if (arg_idx < nargs)
9187 /* We had some pack expansion arguments that will only work if the packs
9188 are empty, but wait until instantiation time to complain.
9189 See variadic-ttp3.C. */
9191 /* Except that we can't provide empty packs to alias templates or
9192 concepts when there are no corresponding parameters. Basically,
9193 we can get here with this:
9195 template<typename T> concept C = true;
9197 template<typename... Args>
9198 requires C<Args...>
9199 void f();
9201 When parsing C<Args...>, we try to form a concept check of
9202 C<?, Args...>. Without the extra check for substituting an empty
9203 pack past the last parameter, we can accept the check as valid.
9205 FIXME: This may be valid for alias templates (but I doubt it).
9207 FIXME: The error could be better also. */
9208 if (in_decl && concept_definition_p (in_decl))
9210 if (complain & tf_error)
9211 error_at (location_of (TREE_VEC_ELT (args, arg_idx)),
9212 "too many arguments");
9213 return error_mark_node;
9216 int len = nparms + (nargs - arg_idx);
9217 tree args = make_tree_vec (len);
9218 int i = 0;
9219 for (; i < nparms; ++i)
9220 TREE_VEC_ELT (args, i) = TREE_VEC_ELT (new_inner_args, i);
9221 for (; i < len; ++i, ++arg_idx)
9222 TREE_VEC_ELT (args, i) = TREE_VEC_ELT (inner_args,
9223 arg_idx - pack_adjust);
9224 new_inner_args = args;
9227 if (lost)
9229 gcc_assert (!(complain & tf_error) || seen_error ());
9230 return error_mark_node;
9233 if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
9234 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
9235 TREE_VEC_LENGTH (new_inner_args));
9237 return return_full_args ? new_args : new_inner_args;
9240 /* Returns true if T is a wrapper to make a C++20 template parameter
9241 object const. */
9243 static bool
9244 class_nttp_const_wrapper_p (tree t)
9246 if (cxx_dialect < cxx20)
9247 return false;
9248 return (TREE_CODE (t) == VIEW_CONVERT_EXPR
9249 && CP_TYPE_CONST_P (TREE_TYPE (t))
9250 && TREE_CODE (TREE_OPERAND (t, 0)) == TEMPLATE_PARM_INDEX);
9253 /* Returns 1 if template args OT and NT are equivalent. */
9256 template_args_equal (tree ot, tree nt, bool partial_order /* = false */)
9258 if (nt == ot)
9259 return 1;
9260 if (nt == NULL_TREE || ot == NULL_TREE)
9261 return false;
9262 if (nt == any_targ_node || ot == any_targ_node)
9263 return true;
9265 if (class_nttp_const_wrapper_p (nt))
9266 nt = TREE_OPERAND (nt, 0);
9267 if (class_nttp_const_wrapper_p (ot))
9268 ot = TREE_OPERAND (ot, 0);
9270 /* DR 1558: Don't treat an alias template specialization with dependent
9271 arguments as equivalent to its underlying type when used as a template
9272 argument; we need them to be distinct so that we substitute into the
9273 specialization arguments at instantiation time. And aliases can't be
9274 equivalent without being ==, so we don't need to look any deeper.
9276 During partial ordering, however, we need to treat them normally so we can
9277 order uses of the same alias with different cv-qualification (79960). */
9278 auto cso = make_temp_override (comparing_dependent_aliases);
9279 if (!partial_order)
9280 ++comparing_dependent_aliases;
9282 if (TREE_CODE (nt) == TREE_VEC || TREE_CODE (ot) == TREE_VEC)
9283 /* For member templates */
9284 return TREE_CODE (ot) == TREE_CODE (nt) && comp_template_args (ot, nt);
9285 else if (PACK_EXPANSION_P (ot) || PACK_EXPANSION_P (nt))
9286 return (PACK_EXPANSION_P (ot) && PACK_EXPANSION_P (nt)
9287 && template_args_equal (PACK_EXPANSION_PATTERN (ot),
9288 PACK_EXPANSION_PATTERN (nt))
9289 && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
9290 PACK_EXPANSION_EXTRA_ARGS (nt)));
9291 else if (ARGUMENT_PACK_P (ot) || ARGUMENT_PACK_P (nt))
9292 return cp_tree_equal (ot, nt);
9293 else if (TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
9294 gcc_unreachable ();
9295 else if (TYPE_P (nt) || TYPE_P (ot))
9297 if (!(TYPE_P (nt) && TYPE_P (ot)))
9298 return false;
9299 return same_type_p (ot, nt);
9301 else
9303 /* Try to treat a template non-type argument that has been converted
9304 to the parameter type as equivalent to one that hasn't yet. */
9305 for (enum tree_code code1 = TREE_CODE (ot);
9306 CONVERT_EXPR_CODE_P (code1)
9307 || code1 == NON_LVALUE_EXPR;
9308 code1 = TREE_CODE (ot))
9309 ot = TREE_OPERAND (ot, 0);
9311 for (enum tree_code code2 = TREE_CODE (nt);
9312 CONVERT_EXPR_CODE_P (code2)
9313 || code2 == NON_LVALUE_EXPR;
9314 code2 = TREE_CODE (nt))
9315 nt = TREE_OPERAND (nt, 0);
9317 return cp_tree_equal (ot, nt);
9321 /* Returns true iff the OLDARGS and NEWARGS are in fact identical sets of
9322 template arguments. Returns false otherwise, and updates OLDARG_PTR and
9323 NEWARG_PTR with the offending arguments if they are non-NULL. */
9325 bool
9326 comp_template_args (tree oldargs, tree newargs,
9327 tree *oldarg_ptr /* = NULL */, tree *newarg_ptr /* = NULL */,
9328 bool partial_order /* = false */)
9330 if (oldargs == newargs)
9331 return true;
9333 if (!oldargs || !newargs)
9334 return false;
9336 if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
9337 return false;
9339 for (int i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
9341 tree nt = TREE_VEC_ELT (newargs, i);
9342 tree ot = TREE_VEC_ELT (oldargs, i);
9344 if (! template_args_equal (ot, nt, partial_order))
9346 if (oldarg_ptr != NULL)
9347 *oldarg_ptr = ot;
9348 if (newarg_ptr != NULL)
9349 *newarg_ptr = nt;
9350 return false;
9353 return true;
9356 inline bool
9357 comp_template_args_porder (tree oargs, tree nargs)
9359 return comp_template_args (oargs, nargs, NULL, NULL, true);
9362 /* Implement a freelist interface for objects of type T.
9364 Head is a separate object, rather than a regular member, so that we
9365 can define it as a GTY deletable pointer, which is highly
9366 desirable. A data member could be declared that way, but then the
9367 containing object would implicitly get GTY((user)), which would
9368 prevent us from instantiating freelists as global objects.
9369 Although this way we can create freelist global objects, they're
9370 such thin wrappers that instantiating temporaries at every use
9371 loses nothing and saves permanent storage for the freelist object.
9373 Member functions next, anew, poison and reinit have default
9374 implementations that work for most of the types we're interested
9375 in, but if they don't work for some type, they should be explicitly
9376 specialized. See the comments before them for requirements, and
9377 the example specializations for the tree_list_freelist. */
9378 template <typename T>
9379 class freelist
9381 /* Return the next object in a chain. We could just do type
9382 punning, but if we access the object with its underlying type, we
9383 avoid strict-aliasing trouble. This needs only work between
9384 poison and reinit. */
9385 static T *&next (T *obj) { return obj->next; }
9387 /* Return a newly allocated, uninitialized or minimally-initialized
9388 object of type T. Any initialization performed by anew should
9389 either remain across the life of the object and the execution of
9390 poison, or be redone by reinit. */
9391 static T *anew () { return ggc_alloc<T> (); }
9393 /* Optionally scribble all over the bits holding the object, so that
9394 they become (mostly?) uninitialized memory. This is called while
9395 preparing to make the object part of the free list. */
9396 static void poison (T *obj) {
9397 T *p ATTRIBUTE_UNUSED = obj;
9398 T **q ATTRIBUTE_UNUSED = &next (obj);
9400 #ifdef ENABLE_GC_CHECKING
9401 /* Poison the data, to indicate the data is garbage. */
9402 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, sizeof (*p)));
9403 memset (p, 0xa5, sizeof (*p));
9404 #endif
9405 /* Let valgrind know the object is free. */
9406 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, sizeof (*p)));
9408 /* Let valgrind know the next portion of the object is available,
9409 but uninitialized. */
9410 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9413 /* Bring an object that underwent at least one lifecycle after anew
9414 and before the most recent free and poison, back to a usable
9415 state, reinitializing whatever is needed for it to be
9416 functionally equivalent to an object just allocated and returned
9417 by anew. This may poison or clear the next field, used by
9418 freelist housekeeping after poison was called. */
9419 static void reinit (T *obj) {
9420 T **q ATTRIBUTE_UNUSED = &next (obj);
9422 #ifdef ENABLE_GC_CHECKING
9423 memset (q, 0xa5, sizeof (*q));
9424 #endif
9425 /* Let valgrind know the entire object is available, but
9426 uninitialized. */
9427 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (*obj)));
9430 /* Reference a GTY-deletable pointer that points to the first object
9431 in the free list proper. */
9432 T *&head;
9433 public:
9434 /* Construct a freelist object chaining objects off of HEAD. */
9435 freelist (T *&head) : head(head) {}
9437 /* Add OBJ to the free object list. The former head becomes OBJ's
9438 successor. */
9439 void free (T *obj)
9441 poison (obj);
9442 next (obj) = head;
9443 head = obj;
9446 /* Take an object from the free list, if one is available, or
9447 allocate a new one. Objects taken from the free list should be
9448 regarded as filled with garbage, except for bits that are
9449 configured to be preserved across free and alloc. */
9450 T *alloc ()
9452 if (head)
9454 T *obj = head;
9455 head = next (head);
9456 reinit (obj);
9457 return obj;
9459 else
9460 return anew ();
9464 /* Explicitly specialize the interfaces for freelist<tree_node>: we
9465 want to allocate a TREE_LIST using the usual interface, and ensure
9466 TREE_CHAIN remains functional. Alas, we have to duplicate a bit of
9467 build_tree_list logic in reinit, so this could go out of sync. */
9468 template <>
9469 inline tree &
9470 freelist<tree_node>::next (tree obj)
9472 return TREE_CHAIN (obj);
9474 template <>
9475 inline tree
9476 freelist<tree_node>::anew ()
9478 return build_tree_list (NULL, NULL);
9480 template <>
9481 inline void
9482 freelist<tree_node>::poison (tree obj ATTRIBUTE_UNUSED)
9484 int size ATTRIBUTE_UNUSED = sizeof (tree_list);
9485 tree p ATTRIBUTE_UNUSED = obj;
9486 tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9487 tree *q ATTRIBUTE_UNUSED = &next (obj);
9489 #ifdef ENABLE_GC_CHECKING
9490 gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9492 /* Poison the data, to indicate the data is garbage. */
9493 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, size));
9494 memset (p, 0xa5, size);
9495 #endif
9496 /* Let valgrind know the object is free. */
9497 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, size));
9498 /* But we still want to use the TREE_CODE and TREE_CHAIN parts. */
9499 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9500 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9502 #ifdef ENABLE_GC_CHECKING
9503 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (b, sizeof (*b)));
9504 /* Keep TREE_CHAIN functional. */
9505 TREE_SET_CODE (obj, TREE_LIST);
9506 #else
9507 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9508 #endif
9510 template <>
9511 inline void
9512 freelist<tree_node>::reinit (tree obj ATTRIBUTE_UNUSED)
9514 tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9516 #ifdef ENABLE_GC_CHECKING
9517 gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9518 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9519 memset (obj, 0, sizeof (tree_list));
9520 #endif
9522 /* Let valgrind know the entire object is available, but
9523 uninitialized. */
9524 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9526 #ifdef ENABLE_GC_CHECKING
9527 TREE_SET_CODE (obj, TREE_LIST);
9528 #else
9529 VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9530 #endif
9533 /* Point to the first object in the TREE_LIST freelist. */
9534 static GTY((deletable)) tree tree_list_freelist_head;
9535 /* Return the/an actual TREE_LIST freelist. */
9536 static inline freelist<tree_node>
9537 tree_list_freelist ()
9539 return tree_list_freelist_head;
9542 /* Point to the first object in the tinst_level freelist. */
9543 static GTY((deletable)) tinst_level *tinst_level_freelist_head;
9544 /* Return the/an actual tinst_level freelist. */
9545 static inline freelist<tinst_level>
9546 tinst_level_freelist ()
9548 return tinst_level_freelist_head;
9551 /* Point to the first object in the pending_template freelist. */
9552 static GTY((deletable)) pending_template *pending_template_freelist_head;
9553 /* Return the/an actual pending_template freelist. */
9554 static inline freelist<pending_template>
9555 pending_template_freelist ()
9557 return pending_template_freelist_head;
9560 /* Build the TREE_LIST object out of a split list, store it
9561 permanently, and return it. */
9562 tree
9563 tinst_level::to_list ()
9565 gcc_assert (split_list_p ());
9566 tree ret = tree_list_freelist ().alloc ();
9567 TREE_PURPOSE (ret) = tldcl;
9568 TREE_VALUE (ret) = targs;
9569 tldcl = ret;
9570 targs = NULL;
9571 gcc_assert (tree_list_p ());
9572 return ret;
9575 const unsigned short tinst_level::refcount_infinity;
9577 /* Increment OBJ's refcount unless it is already infinite. */
9578 static tinst_level *
9579 inc_refcount_use (tinst_level *obj)
9581 if (obj && obj->refcount != tinst_level::refcount_infinity)
9582 ++obj->refcount;
9583 return obj;
9586 /* Release storage for OBJ and node, if it's a TREE_LIST. */
9587 void
9588 tinst_level::free (tinst_level *obj)
9590 if (obj->tree_list_p ())
9591 tree_list_freelist ().free (obj->get_node ());
9592 tinst_level_freelist ().free (obj);
9595 /* Decrement OBJ's refcount if not infinite. If it reaches zero, release
9596 OBJ's DECL and OBJ, and start over with the tinst_level object that
9597 used to be referenced by OBJ's NEXT. */
9598 static void
9599 dec_refcount_use (tinst_level *obj)
9601 while (obj
9602 && obj->refcount != tinst_level::refcount_infinity
9603 && !--obj->refcount)
9605 tinst_level *next = obj->next;
9606 tinst_level::free (obj);
9607 obj = next;
9611 /* Modify PTR so that it points to OBJ, adjusting the refcounts of OBJ
9612 and of the former PTR. Omitting the second argument is equivalent
9613 to passing (T*)NULL; this is allowed because passing the
9614 zero-valued integral constant NULL confuses type deduction and/or
9615 overload resolution. */
9616 template <typename T>
9617 static void
9618 set_refcount_ptr (T *& ptr, T *obj = NULL)
9620 T *save = ptr;
9621 ptr = inc_refcount_use (obj);
9622 dec_refcount_use (save);
9625 static void
9626 add_pending_template (tree d)
9628 tree ti = (TYPE_P (d)
9629 ? CLASSTYPE_TEMPLATE_INFO (d)
9630 : DECL_TEMPLATE_INFO (d));
9631 struct pending_template *pt;
9632 int level;
9634 if (TI_PENDING_TEMPLATE_FLAG (ti))
9635 return;
9637 /* We are called both from instantiate_decl, where we've already had a
9638 tinst_level pushed, and instantiate_template, where we haven't.
9639 Compensate. */
9640 gcc_assert (TREE_CODE (d) != TREE_LIST);
9641 level = !current_tinst_level
9642 || current_tinst_level->maybe_get_node () != d;
9644 if (level)
9645 push_tinst_level (d);
9647 pt = pending_template_freelist ().alloc ();
9648 pt->next = NULL;
9649 pt->tinst = NULL;
9650 set_refcount_ptr (pt->tinst, current_tinst_level);
9651 if (last_pending_template)
9652 last_pending_template->next = pt;
9653 else
9654 pending_templates = pt;
9656 last_pending_template = pt;
9658 TI_PENDING_TEMPLATE_FLAG (ti) = 1;
9660 if (level)
9661 pop_tinst_level ();
9665 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
9666 ARGLIST. Valid choices for FNS are given in the cp-tree.def
9667 documentation for TEMPLATE_ID_EXPR. */
9669 tree
9670 lookup_template_function (tree fns, tree arglist)
9672 if (fns == error_mark_node || arglist == error_mark_node)
9673 return error_mark_node;
9675 gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
9677 if (!is_overloaded_fn (fns) && !identifier_p (fns))
9679 error ("%q#D is not a function template", fns);
9680 return error_mark_node;
9683 if (BASELINK_P (fns))
9685 fns = copy_node (fns);
9686 BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
9687 unknown_type_node,
9688 BASELINK_FUNCTIONS (fns),
9689 arglist);
9690 return fns;
9693 return build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, arglist);
9696 /* Within the scope of a template class S<T>, the name S gets bound
9697 (in build_self_reference) to a TYPE_DECL for the class, not a
9698 TEMPLATE_DECL. If DECL is a TYPE_DECL for current_class_type,
9699 or one of its enclosing classes, and that type is a template,
9700 return the associated TEMPLATE_DECL. Otherwise, the original
9701 DECL is returned.
9703 Also handle the case when DECL is a TREE_LIST of ambiguous
9704 injected-class-names from different bases. */
9706 tree
9707 maybe_get_template_decl_from_type_decl (tree decl)
9709 if (decl == NULL_TREE)
9710 return decl;
9712 /* DR 176: A lookup that finds an injected-class-name (10.2
9713 [class.member.lookup]) can result in an ambiguity in certain cases
9714 (for example, if it is found in more than one base class). If all of
9715 the injected-class-names that are found refer to specializations of
9716 the same class template, and if the name is followed by a
9717 template-argument-list, the reference refers to the class template
9718 itself and not a specialization thereof, and is not ambiguous. */
9719 if (TREE_CODE (decl) == TREE_LIST)
9721 tree t, tmpl = NULL_TREE;
9722 for (t = decl; t; t = TREE_CHAIN (t))
9724 tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
9725 if (!tmpl)
9726 tmpl = elt;
9727 else if (tmpl != elt)
9728 break;
9730 if (tmpl && t == NULL_TREE)
9731 return tmpl;
9732 else
9733 return decl;
9736 return (decl != NULL_TREE
9737 && DECL_SELF_REFERENCE_P (decl)
9738 && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
9739 ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
9742 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
9743 parameters, find the desired type.
9745 D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
9747 IN_DECL, if non-NULL, is the template declaration we are trying to
9748 instantiate.
9750 If ENTERING_SCOPE is nonzero, we are about to enter the scope of
9751 the class we are looking up.
9753 Issue error and warning messages under control of COMPLAIN.
9755 If the template class is really a local class in a template
9756 function, then the FUNCTION_CONTEXT is the function in which it is
9757 being instantiated.
9759 ??? Note that this function is currently called *twice* for each
9760 template-id: the first time from the parser, while creating the
9761 incomplete type (finish_template_type), and the second type during the
9762 real instantiation (instantiate_template_class). This is surely something
9763 that we want to avoid. It also causes some problems with argument
9764 coercion (see convert_nontype_argument for more information on this). */
9766 tree
9767 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
9768 int entering_scope, tsubst_flags_t complain)
9770 auto_timevar tv (TV_TEMPLATE_INST);
9772 tree templ = NULL_TREE, parmlist;
9773 tree t;
9774 spec_entry **slot;
9775 spec_entry *entry;
9776 spec_entry elt;
9777 hashval_t hash;
9779 if (identifier_p (d1))
9781 tree value = innermost_non_namespace_value (d1);
9782 if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
9783 templ = value;
9784 else
9786 if (context)
9787 push_decl_namespace (context);
9788 templ = lookup_name (d1);
9789 templ = maybe_get_template_decl_from_type_decl (templ);
9790 if (context)
9791 pop_decl_namespace ();
9794 else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
9796 tree type = TREE_TYPE (d1);
9798 /* If we are declaring a constructor, say A<T>::A<T>, we will get
9799 an implicit typename for the second A. Deal with it. */
9800 if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
9801 type = TREE_TYPE (type);
9803 if (CLASSTYPE_TEMPLATE_INFO (type))
9805 templ = CLASSTYPE_TI_TEMPLATE (type);
9806 d1 = DECL_NAME (templ);
9809 else if (TREE_CODE (d1) == ENUMERAL_TYPE
9810 || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
9812 templ = TYPE_TI_TEMPLATE (d1);
9813 d1 = DECL_NAME (templ);
9815 else if (DECL_TYPE_TEMPLATE_P (d1))
9817 templ = d1;
9818 d1 = DECL_NAME (templ);
9820 else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
9822 templ = d1;
9823 d1 = DECL_NAME (templ);
9826 /* Issue an error message if we didn't find a template. */
9827 if (! templ)
9829 if (complain & tf_error)
9830 error ("%qT is not a template", d1);
9831 return error_mark_node;
9834 if (TREE_CODE (templ) != TEMPLATE_DECL
9835 /* Make sure it's a user visible template, if it was named by
9836 the user. */
9837 || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
9838 && !PRIMARY_TEMPLATE_P (templ)))
9840 if (complain & tf_error)
9842 error ("non-template type %qT used as a template", d1);
9843 if (in_decl)
9844 error ("for template declaration %q+D", in_decl);
9846 return error_mark_node;
9849 complain &= ~tf_user;
9851 /* An alias that just changes the name of a template is equivalent to the
9852 other template, so if any of the arguments are pack expansions, strip
9853 the alias to avoid problems with a pack expansion passed to a non-pack
9854 alias template parameter (DR 1430). */
9855 if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
9856 templ = get_underlying_template (templ);
9858 if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
9860 tree parm;
9861 tree arglist2 = coerce_template_args_for_ttp (templ, arglist, complain);
9862 if (arglist2 == error_mark_node
9863 || (!uses_template_parms (arglist2)
9864 && check_instantiated_args (templ, arglist2, complain)))
9865 return error_mark_node;
9867 parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
9868 return parm;
9870 else
9872 tree template_type = TREE_TYPE (templ);
9873 tree gen_tmpl;
9874 tree type_decl;
9875 tree found = NULL_TREE;
9876 int arg_depth;
9877 int parm_depth;
9878 int is_dependent_type;
9879 int use_partial_inst_tmpl = false;
9881 if (template_type == error_mark_node)
9882 /* An error occurred while building the template TEMPL, and a
9883 diagnostic has most certainly been emitted for that
9884 already. Let's propagate that error. */
9885 return error_mark_node;
9887 gen_tmpl = most_general_template (templ);
9888 if (modules_p ())
9889 lazy_load_pendings (gen_tmpl);
9891 parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
9892 parm_depth = TMPL_PARMS_DEPTH (parmlist);
9893 arg_depth = TMPL_ARGS_DEPTH (arglist);
9895 if (arg_depth == 1 && parm_depth > 1)
9897 /* We've been given an incomplete set of template arguments.
9898 For example, given:
9900 template <class T> struct S1 {
9901 template <class U> struct S2 {};
9902 template <class U> struct S2<U*> {};
9905 we will be called with an ARGLIST of `U*', but the
9906 TEMPLATE will be `template <class T> template
9907 <class U> struct S1<T>::S2'. We must fill in the missing
9908 arguments. */
9909 tree ti = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (templ));
9910 arglist = add_outermost_template_args (TI_ARGS (ti), arglist);
9911 arg_depth = TMPL_ARGS_DEPTH (arglist);
9914 /* Now we should have enough arguments. */
9915 gcc_assert (parm_depth == arg_depth);
9917 /* From here on, we're only interested in the most general
9918 template. */
9920 /* Shortcut looking up the current class scope again. */
9921 if (current_class_type)
9922 if (tree ti = CLASSTYPE_TEMPLATE_INFO (current_class_type))
9923 if (gen_tmpl == most_general_template (TI_TEMPLATE (ti))
9924 && comp_template_args (arglist, TI_ARGS (ti)))
9925 return current_class_type;
9927 /* Calculate the BOUND_ARGS. These will be the args that are
9928 actually tsubst'd into the definition to create the
9929 instantiation. */
9930 arglist = coerce_template_parms (parmlist, arglist, gen_tmpl, complain);
9932 if (arglist == error_mark_node)
9933 /* We were unable to bind the arguments. */
9934 return error_mark_node;
9936 /* In the scope of a template class, explicit references to the
9937 template class refer to the type of the template, not any
9938 instantiation of it. For example, in:
9940 template <class T> class C { void f(C<T>); }
9942 the `C<T>' is just the same as `C'. Outside of the
9943 class, however, such a reference is an instantiation. */
9944 if (entering_scope
9945 || !PRIMARY_TEMPLATE_P (gen_tmpl)
9946 || currently_open_class (template_type))
9948 tree tinfo = TYPE_TEMPLATE_INFO (template_type);
9950 if (tinfo && comp_template_args (TI_ARGS (tinfo), arglist))
9951 return template_type;
9954 /* If we already have this specialization, return it. */
9955 elt.tmpl = gen_tmpl;
9956 elt.args = arglist;
9957 elt.spec = NULL_TREE;
9958 hash = spec_hasher::hash (&elt);
9959 entry = type_specializations->find_with_hash (&elt, hash);
9961 if (entry)
9962 return entry->spec;
9964 /* If the template's constraints are not satisfied,
9965 then we cannot form a valid type.
9967 Note that the check is deferred until after the hash
9968 lookup. This prevents redundant checks on previously
9969 instantiated specializations. */
9970 if (flag_concepts
9971 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl)
9972 && !constraints_satisfied_p (gen_tmpl, arglist))
9974 if (complain & tf_error)
9976 auto_diagnostic_group d;
9977 error ("template constraint failure for %qD", gen_tmpl);
9978 diagnose_constraints (input_location, gen_tmpl, arglist);
9980 return error_mark_node;
9983 is_dependent_type = uses_template_parms (arglist);
9985 /* If the deduced arguments are invalid, then the binding
9986 failed. */
9987 if (!is_dependent_type
9988 && check_instantiated_args (gen_tmpl,
9989 INNERMOST_TEMPLATE_ARGS (arglist),
9990 complain))
9991 return error_mark_node;
9993 if (!is_dependent_type
9994 && !PRIMARY_TEMPLATE_P (gen_tmpl)
9995 && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
9996 && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
9997 /* This occurs when the user has tried to define a tagged type
9998 in a scope that forbids it. We emitted an error during the
9999 parse. We didn't complete the bail out then, so here we
10000 are. */
10001 return error_mark_node;
10003 context = DECL_CONTEXT (gen_tmpl);
10004 if (context && TYPE_P (context))
10006 if (!uses_template_parms (DECL_CONTEXT (templ)))
10007 /* If the context of the partially instantiated template is
10008 already non-dependent, then we might as well use it. */
10009 context = DECL_CONTEXT (templ);
10010 else
10012 context = tsubst_aggr_type (context, arglist,
10013 complain, in_decl, true);
10014 /* Try completing the enclosing context if it's not already so. */
10015 if (context != error_mark_node
10016 && !COMPLETE_TYPE_P (context))
10018 context = complete_type (context);
10019 if (COMPLETE_TYPE_P (context))
10021 /* Completion could have caused us to register the desired
10022 specialization already, so check the table again. */
10023 entry = type_specializations->find_with_hash (&elt, hash);
10024 if (entry)
10025 return entry->spec;
10030 else
10031 context = tsubst (context, arglist, complain, in_decl);
10033 if (context == error_mark_node)
10034 return error_mark_node;
10036 if (!context)
10037 context = global_namespace;
10039 /* Create the type. */
10040 if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10042 /* The user referred to a specialization of an alias
10043 template represented by GEN_TMPL.
10045 [temp.alias]/2 says:
10047 When a template-id refers to the specialization of an
10048 alias template, it is equivalent to the associated
10049 type obtained by substitution of its
10050 template-arguments for the template-parameters in the
10051 type-id of the alias template. */
10053 t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
10054 /* Note that the call above (by indirectly calling
10055 register_specialization in tsubst_decl) registers the
10056 TYPE_DECL representing the specialization of the alias
10057 template. So next time someone substitutes ARGLIST for
10058 the template parms into the alias template (GEN_TMPL),
10059 she'll get that TYPE_DECL back. */
10061 if (t == error_mark_node)
10062 return t;
10064 else if (TREE_CODE (template_type) == ENUMERAL_TYPE)
10066 if (!is_dependent_type)
10068 set_current_access_from_decl (TYPE_NAME (template_type));
10069 t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
10070 tsubst (ENUM_UNDERLYING_TYPE (template_type),
10071 arglist, complain, in_decl),
10072 tsubst_attributes (TYPE_ATTRIBUTES (template_type),
10073 arglist, complain, in_decl),
10074 SCOPED_ENUM_P (template_type), NULL);
10076 if (t == error_mark_node)
10077 return t;
10079 else
10081 /* We don't want to call start_enum for this type, since
10082 the values for the enumeration constants may involve
10083 template parameters. And, no one should be interested
10084 in the enumeration constants for such a type. */
10085 t = cxx_make_type (ENUMERAL_TYPE);
10086 SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
10088 SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
10089 ENUM_FIXED_UNDERLYING_TYPE_P (t)
10090 = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
10092 else if (CLASS_TYPE_P (template_type))
10094 /* Lambda closures are regenerated in tsubst_lambda_expr, not
10095 instantiated here. */
10096 gcc_assert (!LAMBDA_TYPE_P (template_type));
10098 t = make_class_type (TREE_CODE (template_type));
10099 CLASSTYPE_DECLARED_CLASS (t)
10100 = CLASSTYPE_DECLARED_CLASS (template_type);
10101 SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
10103 /* A local class. Make sure the decl gets registered properly. */
10104 if (context == current_function_decl)
10105 if (pushtag (DECL_NAME (gen_tmpl), t)
10106 == error_mark_node)
10107 return error_mark_node;
10109 if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
10110 /* This instantiation is another name for the primary
10111 template type. Set the TYPE_CANONICAL field
10112 appropriately. */
10113 TYPE_CANONICAL (t) = template_type;
10114 else if (any_template_arguments_need_structural_equality_p (arglist))
10115 SET_TYPE_STRUCTURAL_EQUALITY (t);
10117 else
10118 gcc_unreachable ();
10120 /* If we called start_enum or pushtag above, this information
10121 will already be set up. */
10122 type_decl = TYPE_NAME (t);
10123 if (!type_decl)
10125 TYPE_CONTEXT (t) = FROB_CONTEXT (context);
10127 type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
10128 DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
10129 DECL_SOURCE_LOCATION (type_decl)
10130 = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
10133 set_instantiating_module (type_decl);
10134 /* Although GEN_TMPL is the TEMPLATE_DECL, it has the same value
10135 of export flag. We want to propagate this because it might
10136 be a friend declaration that pushes a new hidden binding. */
10137 DECL_MODULE_EXPORT_P (type_decl) = DECL_MODULE_EXPORT_P (gen_tmpl);
10139 if (CLASS_TYPE_P (template_type))
10141 TREE_PRIVATE (type_decl)
10142 = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
10143 TREE_PROTECTED (type_decl)
10144 = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
10145 if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
10147 DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
10148 DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
10152 if (OVERLOAD_TYPE_P (t)
10153 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10155 static const char *tags[] = {"abi_tag", "may_alias"};
10157 for (unsigned ix = 0; ix != 2; ix++)
10159 tree attributes
10160 = lookup_attribute (tags[ix], TYPE_ATTRIBUTES (template_type));
10162 if (attributes)
10163 TYPE_ATTRIBUTES (t)
10164 = tree_cons (TREE_PURPOSE (attributes),
10165 TREE_VALUE (attributes),
10166 TYPE_ATTRIBUTES (t));
10170 /* Let's consider the explicit specialization of a member
10171 of a class template specialization that is implicitly instantiated,
10172 e.g.:
10173 template<class T>
10174 struct S
10176 template<class U> struct M {}; //#0
10179 template<>
10180 template<>
10181 struct S<int>::M<char> //#1
10183 int i;
10185 [temp.expl.spec]/4 says this is valid.
10187 In this case, when we write:
10188 S<int>::M<char> m;
10190 M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
10191 the one of #0.
10193 When we encounter #1, we want to store the partial instantiation
10194 of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
10196 For all cases other than this "explicit specialization of member of a
10197 class template", we just want to store the most general template into
10198 the CLASSTYPE_TI_TEMPLATE of M.
10200 This case of "explicit specialization of member of a class template"
10201 only happens when:
10202 1/ the enclosing class is an instantiation of, and therefore not
10203 the same as, the context of the most general template, and
10204 2/ we aren't looking at the partial instantiation itself, i.e.
10205 the innermost arguments are not the same as the innermost parms of
10206 the most general template.
10208 So it's only when 1/ and 2/ happens that we want to use the partial
10209 instantiation of the member template in lieu of its most general
10210 template. */
10212 if (PRIMARY_TEMPLATE_P (gen_tmpl)
10213 && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
10214 /* the enclosing class must be an instantiation... */
10215 && CLASS_TYPE_P (context)
10216 && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
10218 TREE_VEC_LENGTH (arglist)--;
10219 ++processing_template_decl;
10220 tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (gen_tmpl));
10221 tree partial_inst_args =
10222 tsubst (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)),
10223 arglist, complain, NULL_TREE);
10224 --processing_template_decl;
10225 TREE_VEC_LENGTH (arglist)++;
10226 if (partial_inst_args == error_mark_node)
10227 return error_mark_node;
10228 use_partial_inst_tmpl =
10229 /*...and we must not be looking at the partial instantiation
10230 itself. */
10231 !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
10232 partial_inst_args);
10235 if (!use_partial_inst_tmpl)
10236 /* This case is easy; there are no member templates involved. */
10237 found = gen_tmpl;
10238 else
10240 /* This is a full instantiation of a member template. Find
10241 the partial instantiation of which this is an instance. */
10243 /* Temporarily reduce by one the number of levels in the ARGLIST
10244 so as to avoid comparing the last set of arguments. */
10245 TREE_VEC_LENGTH (arglist)--;
10246 /* We don't use COMPLAIN in the following call because this isn't
10247 the immediate context of deduction. For instance, tf_partial
10248 could be set here as we might be at the beginning of template
10249 argument deduction when any explicitly specified template
10250 arguments are substituted into the function type. tf_partial
10251 could lead into trouble because we wouldn't find the partial
10252 instantiation that might have been created outside tf_partial
10253 context, because the levels of template parameters wouldn't
10254 match, because in a tf_partial context, tsubst doesn't reduce
10255 TEMPLATE_PARM_LEVEL. */
10256 found = tsubst (gen_tmpl, arglist, tf_none, NULL_TREE);
10257 TREE_VEC_LENGTH (arglist)++;
10258 /* FOUND is either a proper class type, or an alias
10259 template specialization. In the later case, it's a
10260 TYPE_DECL, resulting from the substituting of arguments
10261 for parameters in the TYPE_DECL of the alias template
10262 done earlier. So be careful while getting the template
10263 of FOUND. */
10264 found = (TREE_CODE (found) == TEMPLATE_DECL
10265 ? found
10266 : (TREE_CODE (found) == TYPE_DECL
10267 ? DECL_TI_TEMPLATE (found)
10268 : CLASSTYPE_TI_TEMPLATE (found)));
10270 if (DECL_CLASS_TEMPLATE_P (found)
10271 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (found)))
10273 /* If this partial instantiation is specialized, we want to
10274 use it for hash table lookup. */
10275 elt.tmpl = found;
10276 elt.args = arglist = INNERMOST_TEMPLATE_ARGS (arglist);
10277 hash = spec_hasher::hash (&elt);
10281 /* Build template info for the new specialization. */
10282 SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
10284 elt.spec = t;
10285 slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
10286 gcc_checking_assert (*slot == NULL);
10287 entry = ggc_alloc<spec_entry> ();
10288 *entry = elt;
10289 *slot = entry;
10291 /* Note this use of the partial instantiation so we can check it
10292 later in maybe_process_partial_specialization. */
10293 DECL_TEMPLATE_INSTANTIATIONS (found)
10294 = tree_cons (arglist, t,
10295 DECL_TEMPLATE_INSTANTIATIONS (found));
10297 if (TREE_CODE (template_type) == ENUMERAL_TYPE
10298 && !uses_template_parms (current_nonlambda_scope ())
10299 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10300 /* Now that the type has been registered on the instantiations
10301 list, we set up the enumerators. Because the enumeration
10302 constants may involve the enumeration type itself, we make
10303 sure to register the type first, and then create the
10304 constants. That way, doing tsubst_expr for the enumeration
10305 constants won't result in recursive calls here; we'll find
10306 the instantiation and exit above. */
10307 tsubst_enum (template_type, t, arglist);
10309 if (CLASS_TYPE_P (template_type) && is_dependent_type)
10310 /* If the type makes use of template parameters, the
10311 code that generates debugging information will crash. */
10312 DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
10314 /* Possibly limit visibility based on template args. */
10315 TREE_PUBLIC (type_decl) = 1;
10316 determine_visibility (type_decl);
10318 inherit_targ_abi_tags (t);
10320 return t;
10324 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST. */
10326 tree
10327 lookup_template_variable (tree templ, tree arglist)
10329 if (flag_concepts && variable_concept_p (templ))
10330 return build_concept_check (templ, arglist, tf_none);
10332 /* The type of the expression is NULL_TREE since the template-id could refer
10333 to an explicit or partial specialization. */
10334 return build2 (TEMPLATE_ID_EXPR, NULL_TREE, templ, arglist);
10337 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR if it's
10338 not dependent. */
10340 tree
10341 finish_template_variable (tree var, tsubst_flags_t complain)
10343 tree templ = TREE_OPERAND (var, 0);
10344 tree arglist = TREE_OPERAND (var, 1);
10346 /* If the template or arguments are dependent, then we
10347 can't resolve the TEMPLATE_ID_EXPR yet. */
10348 if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (templ)) != 1
10349 || any_dependent_template_arguments_p (arglist))
10350 return var;
10352 tree parms = DECL_TEMPLATE_PARMS (templ);
10353 arglist = coerce_template_parms (parms, arglist, templ, complain);
10354 if (arglist == error_mark_node)
10355 return error_mark_node;
10357 if (flag_concepts && !constraints_satisfied_p (templ, arglist))
10359 if (complain & tf_error)
10361 auto_diagnostic_group d;
10362 error ("use of invalid variable template %qE", var);
10363 diagnose_constraints (location_of (var), templ, arglist);
10365 return error_mark_node;
10368 return instantiate_template (templ, arglist, complain);
10371 /* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
10372 TARGS template args, and instantiate it if it's not dependent. */
10374 tree
10375 lookup_and_finish_template_variable (tree templ, tree targs,
10376 tsubst_flags_t complain)
10378 tree var = lookup_template_variable (templ, targs);
10379 /* We may be called while doing a partial substitution, but the
10380 type of the variable template may be auto, in which case we
10381 will call do_auto_deduction in mark_used (which clears tf_partial)
10382 and the auto must be properly reduced at that time for the
10383 deduction to work. */
10384 complain &= ~tf_partial;
10385 var = finish_template_variable (var, complain);
10386 mark_used (var);
10387 return var;
10390 /* If the set of template parameters PARMS contains a template parameter
10391 at the given LEVEL and INDEX, then return this parameter. Otherwise
10392 return NULL_TREE. */
10394 static tree
10395 corresponding_template_parameter_list (tree parms, int level, int index)
10397 while (TMPL_PARMS_DEPTH (parms) > level)
10398 parms = TREE_CHAIN (parms);
10400 if (TMPL_PARMS_DEPTH (parms) != level
10401 || TREE_VEC_LENGTH (TREE_VALUE (parms)) <= index)
10402 return NULL_TREE;
10404 return TREE_VEC_ELT (TREE_VALUE (parms), index);
10407 /* Return the TREE_LIST for the template parameter from PARMS that positionally
10408 corresponds to the template parameter PARM, or else return NULL_TREE. */
10410 static tree
10411 corresponding_template_parameter_list (tree parms, tree parm)
10413 int level, index;
10414 template_parm_level_and_index (parm, &level, &index);
10415 return corresponding_template_parameter_list (parms, level, index);
10418 /* As above, but pull out the actual parameter. */
10420 static tree
10421 corresponding_template_parameter (tree parms, tree parm)
10423 tree list = corresponding_template_parameter_list (parms, parm);
10424 if (!list)
10425 return NULL_TREE;
10427 tree t = TREE_VALUE (list);
10428 /* As in template_parm_to_arg. */
10429 if (TREE_CODE (t) == TYPE_DECL || TREE_CODE (t) == TEMPLATE_DECL)
10430 t = TREE_TYPE (t);
10431 else
10432 t = DECL_INITIAL (t);
10434 gcc_assert (TEMPLATE_PARM_P (t));
10435 return t;
10438 struct pair_fn_data
10440 tree_fn_t fn;
10441 tree_fn_t any_fn;
10442 void *data;
10443 /* True when we should also visit template parameters that occur in
10444 non-deduced contexts. */
10445 bool include_nondeduced_p;
10446 hash_set<tree> *visited;
10449 /* Called from for_each_template_parm via walk_tree. */
10451 static tree
10452 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
10454 tree t = *tp;
10455 struct pair_fn_data *pfd = (struct pair_fn_data *) d;
10456 tree_fn_t fn = pfd->fn;
10457 void *data = pfd->data;
10458 tree result = NULL_TREE;
10460 #define WALK_SUBTREE(NODE) \
10461 do \
10463 result = for_each_template_parm (NODE, fn, data, pfd->visited, \
10464 pfd->include_nondeduced_p, \
10465 pfd->any_fn); \
10466 if (result) goto out; \
10468 while (0)
10470 if (pfd->any_fn && (*pfd->any_fn)(t, data))
10471 return t;
10473 if (TYPE_P (t)
10474 && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
10475 WALK_SUBTREE (TYPE_CONTEXT (t));
10477 switch (TREE_CODE (t))
10479 case RECORD_TYPE:
10480 if (TYPE_PTRMEMFUNC_P (t))
10481 break;
10482 /* Fall through. */
10484 case UNION_TYPE:
10485 case ENUMERAL_TYPE:
10486 if (!TYPE_TEMPLATE_INFO (t))
10487 *walk_subtrees = 0;
10488 else
10489 WALK_SUBTREE (TYPE_TI_ARGS (t));
10490 break;
10492 case INTEGER_TYPE:
10493 WALK_SUBTREE (TYPE_MIN_VALUE (t));
10494 WALK_SUBTREE (TYPE_MAX_VALUE (t));
10495 break;
10497 case METHOD_TYPE:
10498 /* Since we're not going to walk subtrees, we have to do this
10499 explicitly here. */
10500 WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
10501 /* Fall through. */
10503 case FUNCTION_TYPE:
10504 /* Check the return type. */
10505 WALK_SUBTREE (TREE_TYPE (t));
10507 /* Check the parameter types. Since default arguments are not
10508 instantiated until they are needed, the TYPE_ARG_TYPES may
10509 contain expressions that involve template parameters. But,
10510 no-one should be looking at them yet. And, once they're
10511 instantiated, they don't contain template parameters, so
10512 there's no point in looking at them then, either. */
10514 tree parm;
10516 for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
10517 WALK_SUBTREE (TREE_VALUE (parm));
10519 /* Since we've already handled the TYPE_ARG_TYPES, we don't
10520 want walk_tree walking into them itself. */
10521 *walk_subtrees = 0;
10524 if (flag_noexcept_type)
10526 tree spec = TYPE_RAISES_EXCEPTIONS (t);
10527 if (spec)
10528 WALK_SUBTREE (TREE_PURPOSE (spec));
10530 break;
10532 case TYPEOF_TYPE:
10533 case DECLTYPE_TYPE:
10534 if (pfd->include_nondeduced_p
10535 && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
10536 pfd->visited,
10537 pfd->include_nondeduced_p,
10538 pfd->any_fn))
10539 return error_mark_node;
10540 *walk_subtrees = false;
10541 break;
10543 case TRAIT_TYPE:
10544 if (pfd->include_nondeduced_p)
10546 WALK_SUBTREE (TRAIT_TYPE_TYPE1 (t));
10547 WALK_SUBTREE (TRAIT_TYPE_TYPE2 (t));
10549 *walk_subtrees = false;
10550 break;
10552 case FUNCTION_DECL:
10553 case VAR_DECL:
10554 if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10555 WALK_SUBTREE (DECL_TI_ARGS (t));
10556 break;
10558 case PARM_DECL:
10559 WALK_SUBTREE (TREE_TYPE (t));
10560 break;
10562 case CONST_DECL:
10563 if (DECL_TEMPLATE_PARM_P (t))
10564 WALK_SUBTREE (DECL_INITIAL (t));
10565 if (DECL_CONTEXT (t)
10566 && pfd->include_nondeduced_p)
10567 WALK_SUBTREE (DECL_CONTEXT (t));
10568 break;
10570 case BOUND_TEMPLATE_TEMPLATE_PARM:
10571 /* Record template parameters such as `T' inside `TT<T>'. */
10572 WALK_SUBTREE (TYPE_TI_ARGS (t));
10573 /* Fall through. */
10575 case TEMPLATE_TEMPLATE_PARM:
10576 case TEMPLATE_TYPE_PARM:
10577 case TEMPLATE_PARM_INDEX:
10578 if (fn && (*fn)(t, data))
10579 return t;
10580 else if (!fn)
10581 return t;
10582 break;
10584 case TEMPLATE_DECL:
10585 /* A template template parameter is encountered. */
10586 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10587 WALK_SUBTREE (TREE_TYPE (t));
10589 /* Already substituted template template parameter */
10590 *walk_subtrees = 0;
10591 break;
10593 case TYPENAME_TYPE:
10594 /* A template-id in a TYPENAME_TYPE might be a deduced context after
10595 partial instantiation. */
10596 WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
10597 *walk_subtrees = 0;
10598 break;
10600 case INDIRECT_REF:
10601 case COMPONENT_REF:
10602 /* If there's no type, then this thing must be some expression
10603 involving template parameters. */
10604 if (!fn && !TREE_TYPE (t))
10605 return error_mark_node;
10606 break;
10608 case CONSTRUCTOR:
10609 case TRAIT_EXPR:
10610 case PLUS_EXPR:
10611 case MULT_EXPR:
10612 case SCOPE_REF:
10613 /* These are non-deduced contexts. */
10614 if (!pfd->include_nondeduced_p)
10615 *walk_subtrees = 0;
10616 break;
10618 case MODOP_EXPR:
10619 case CAST_EXPR:
10620 case IMPLICIT_CONV_EXPR:
10621 case REINTERPRET_CAST_EXPR:
10622 case CONST_CAST_EXPR:
10623 case STATIC_CAST_EXPR:
10624 case DYNAMIC_CAST_EXPR:
10625 case ARROW_EXPR:
10626 case DOTSTAR_EXPR:
10627 case TYPEID_EXPR:
10628 case PSEUDO_DTOR_EXPR:
10629 if (!fn)
10630 return error_mark_node;
10631 break;
10633 default:
10634 break;
10637 #undef WALK_SUBTREE
10639 /* We didn't find any template parameters we liked. */
10640 out:
10641 return result;
10644 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
10645 BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
10646 call FN with the parameter and the DATA.
10647 If FN returns nonzero, the iteration is terminated, and
10648 for_each_template_parm returns 1. Otherwise, the iteration
10649 continues. If FN never returns a nonzero value, the value
10650 returned by for_each_template_parm is 0. If FN is NULL, it is
10651 considered to be the function which always returns 1.
10653 If INCLUDE_NONDEDUCED_P, then this routine will also visit template
10654 parameters that occur in non-deduced contexts. When false, only
10655 visits those template parameters that can be deduced. */
10657 static tree
10658 for_each_template_parm (tree t, tree_fn_t fn, void* data,
10659 hash_set<tree> *visited,
10660 bool include_nondeduced_p,
10661 tree_fn_t any_fn)
10663 struct pair_fn_data pfd;
10664 tree result;
10666 /* Set up. */
10667 pfd.fn = fn;
10668 pfd.any_fn = any_fn;
10669 pfd.data = data;
10670 pfd.include_nondeduced_p = include_nondeduced_p;
10672 /* Walk the tree. (Conceptually, we would like to walk without
10673 duplicates, but for_each_template_parm_r recursively calls
10674 for_each_template_parm, so we would need to reorganize a fair
10675 bit to use walk_tree_without_duplicates, so we keep our own
10676 visited list.) */
10677 if (visited)
10678 pfd.visited = visited;
10679 else
10680 pfd.visited = new hash_set<tree>;
10681 result = cp_walk_tree (&t,
10682 for_each_template_parm_r,
10683 &pfd,
10684 pfd.visited);
10686 /* Clean up. */
10687 if (!visited)
10689 delete pfd.visited;
10690 pfd.visited = 0;
10693 return result;
10696 struct find_template_parameter_info
10698 explicit find_template_parameter_info (tree ctx_parms)
10699 : ctx_parms (ctx_parms),
10700 max_depth (TMPL_PARMS_DEPTH (ctx_parms))
10703 hash_set<tree> visited;
10704 hash_set<tree> parms;
10705 tree parm_list = NULL_TREE;
10706 tree *parm_list_tail = &parm_list;
10707 tree ctx_parms;
10708 int max_depth;
10710 tree find_in (tree);
10711 tree find_in_recursive (tree);
10712 bool found (tree);
10713 unsigned num_found () { return parms.elements (); }
10716 /* Appends the declaration of T to the list in DATA. */
10718 static int
10719 keep_template_parm (tree t, void* data)
10721 find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10723 /* Template parameters declared within the expression are not part of
10724 the parameter mapping. For example, in this concept:
10726 template<typename T>
10727 concept C = requires { <expr> } -> same_as<int>;
10729 the return specifier same_as<int> declares a new decltype parameter
10730 that must not be part of the parameter mapping. The same is true
10731 for generic lambda parameters, lambda template parameters, etc. */
10732 int level;
10733 int index;
10734 template_parm_level_and_index (t, &level, &index);
10735 if (level == 0 || level > ftpi->max_depth)
10736 return 0;
10738 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10739 /* We want the underlying TEMPLATE_TEMPLATE_PARM, not the
10740 BOUND_TEMPLATE_TEMPLATE_PARM itself. */
10741 t = TREE_TYPE (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (t));
10743 /* This template parameter might be an argument to a cached dependent
10744 specalization that was formed earlier inside some other template, in
10745 which case the parameter is not among the ones that are in-scope.
10746 Look in CTX_PARMS to find the corresponding in-scope template
10747 parameter, and use it instead. */
10748 if (tree in_scope = corresponding_template_parameter (ftpi->ctx_parms, t))
10749 t = in_scope;
10751 /* Arguments like const T yield parameters like const T. This means that
10752 a template-id like X<T, const T> would yield two distinct parameters:
10753 T and const T. Adjust types to their unqualified versions. */
10754 if (TYPE_P (t))
10755 t = TYPE_MAIN_VARIANT (t);
10756 if (!ftpi->parms.add (t))
10758 /* Append T to PARM_LIST. */
10759 tree node = build_tree_list (NULL_TREE, t);
10760 *ftpi->parm_list_tail = node;
10761 ftpi->parm_list_tail = &TREE_CHAIN (node);
10764 /* Verify the parameter we found has a valid index. */
10765 if (flag_checking)
10767 tree parms = ftpi->ctx_parms;
10768 while (TMPL_PARMS_DEPTH (parms) > level)
10769 parms = TREE_CHAIN (parms);
10770 if (int len = TREE_VEC_LENGTH (TREE_VALUE (parms)))
10771 gcc_assert (index < len);
10774 return 0;
10777 /* Ensure that we recursively examine certain terms that are not normally
10778 visited in for_each_template_parm_r. */
10780 static int
10781 any_template_parm_r (tree t, void *data)
10783 find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10785 #define WALK_SUBTREE(NODE) \
10786 do \
10788 for_each_template_parm (NODE, keep_template_parm, data, \
10789 &ftpi->visited, true, \
10790 any_template_parm_r); \
10792 while (0)
10794 /* A mention of a member alias/typedef is a use of all of its template
10795 arguments, including those from the enclosing class, so we don't use
10796 alias_template_specialization_p here. */
10797 if (TYPE_P (t) && typedef_variant_p (t))
10798 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
10799 WALK_SUBTREE (TI_ARGS (tinfo));
10801 switch (TREE_CODE (t))
10803 case TEMPLATE_TYPE_PARM:
10804 /* Type constraints of a placeholder type may contain parameters. */
10805 if (is_auto (t))
10806 if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
10807 WALK_SUBTREE (constr);
10808 break;
10810 case TEMPLATE_ID_EXPR:
10811 /* Search through references to variable templates. */
10812 WALK_SUBTREE (TREE_OPERAND (t, 0));
10813 WALK_SUBTREE (TREE_OPERAND (t, 1));
10814 break;
10816 case TEMPLATE_PARM_INDEX:
10817 WALK_SUBTREE (TREE_TYPE (t));
10818 break;
10820 case TEMPLATE_DECL:
10821 /* If T is a member template that shares template parameters with
10822 ctx_parms, we need to mark all those parameters for mapping.
10823 To that end, it should suffice to just walk the DECL_CONTEXT of
10824 the template (assuming the template is not overly general). */
10825 WALK_SUBTREE (DECL_CONTEXT (t));
10826 break;
10828 case LAMBDA_EXPR:
10830 /* Look in the parms and body. */
10831 tree fn = lambda_function (t);
10832 WALK_SUBTREE (TREE_TYPE (fn));
10833 WALK_SUBTREE (DECL_SAVED_TREE (fn));
10835 break;
10837 case IDENTIFIER_NODE:
10838 if (IDENTIFIER_CONV_OP_P (t))
10839 /* The conversion-type-id of a conversion operator may be dependent. */
10840 WALK_SUBTREE (TREE_TYPE (t));
10841 break;
10843 case CONVERT_EXPR:
10844 if (is_dummy_object (t))
10845 WALK_SUBTREE (TREE_TYPE (t));
10846 break;
10848 default:
10849 break;
10852 /* Keep walking. */
10853 return 0;
10856 /* Look through T for template parameters. */
10858 tree
10859 find_template_parameter_info::find_in (tree t)
10861 return for_each_template_parm (t, keep_template_parm, this, &visited,
10862 /*include_nondeduced*/true,
10863 any_template_parm_r);
10866 /* As above, but also recursively look into the default arguments of template
10867 parameters we found. Used for alias CTAD. */
10869 tree
10870 find_template_parameter_info::find_in_recursive (tree t)
10872 if (tree r = find_in (t))
10873 return r;
10874 /* Since newly found parms are added to the end of the list, we
10875 can just walk it until we reach the end. */
10876 for (tree pl = parm_list; pl; pl = TREE_CHAIN (pl))
10878 tree parm = TREE_VALUE (pl);
10879 tree list = corresponding_template_parameter_list (ctx_parms, parm);
10880 if (tree r = find_in (TREE_PURPOSE (list)))
10881 return r;
10883 return NULL_TREE;
10886 /* True if PARM was found by a previous call to find_in. PARM can be a
10887 TREE_LIST, a DECL_TEMPLATE_PARM_P, or a TEMPLATE_PARM_P. */
10889 bool
10890 find_template_parameter_info::found (tree parm)
10892 if (TREE_CODE (parm) == TREE_LIST)
10893 parm = TREE_VALUE (parm);
10894 if (TREE_CODE (parm) == TYPE_DECL)
10895 parm = TREE_TYPE (parm);
10896 else
10897 parm = DECL_INITIAL (parm);
10898 gcc_checking_assert (TEMPLATE_PARM_P (parm));
10899 return parms.contains (parm);
10902 /* Returns a list of unique template parameters found within T, where CTX_PARMS
10903 are the template parameters in scope. */
10905 tree
10906 find_template_parameters (tree t, tree ctx_parms)
10908 if (!ctx_parms)
10909 return NULL_TREE;
10911 find_template_parameter_info ftpi (ctx_parms);
10912 ftpi.find_in (t);
10913 return ftpi.parm_list;
10916 /* Returns true if T depends on any template parameter. */
10918 bool
10919 uses_template_parms (tree t)
10921 if (t == NULL_TREE || t == error_mark_node)
10922 return false;
10924 /* Namespaces can't depend on any template parameters. */
10925 if (TREE_CODE (t) == NAMESPACE_DECL)
10926 return false;
10928 processing_template_decl_sentinel ptds (/*reset*/false);
10929 ++processing_template_decl;
10931 if (TYPE_P (t))
10932 return dependent_type_p (t);
10933 else if (TREE_CODE (t) == TREE_VEC)
10934 return any_dependent_template_arguments_p (t);
10935 else if (TREE_CODE (t) == TREE_LIST)
10936 return (uses_template_parms (TREE_VALUE (t))
10937 || uses_template_parms (TREE_CHAIN (t)));
10938 else if (TREE_CODE (t) == TYPE_DECL)
10939 return dependent_type_p (TREE_TYPE (t));
10940 else
10941 return instantiation_dependent_expression_p (t);
10944 /* Returns true if T depends on any template parameter with level LEVEL. */
10946 bool
10947 uses_template_parms_level (tree t, int level)
10949 return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
10950 /*include_nondeduced_p=*/true);
10953 /* Returns true if the signature of DECL depends on any template parameter from
10954 its enclosing class. */
10956 static bool
10957 uses_outer_template_parms (tree decl)
10959 int depth = template_class_depth (CP_DECL_CONTEXT (decl));
10960 if (depth == 0)
10961 return false;
10962 if (for_each_template_parm (TREE_TYPE (decl), template_parm_outer_level,
10963 &depth, NULL, /*include_nondeduced_p=*/true))
10964 return true;
10965 if (PRIMARY_TEMPLATE_P (decl)
10966 || DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
10968 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (decl));
10969 for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
10971 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
10972 tree defarg = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
10973 if (TREE_CODE (parm) == PARM_DECL
10974 && for_each_template_parm (TREE_TYPE (parm),
10975 template_parm_outer_level,
10976 &depth, NULL, /*nondeduced*/true))
10977 return true;
10978 if (TREE_CODE (parm) == TEMPLATE_DECL
10979 && uses_outer_template_parms (parm))
10980 return true;
10981 if (defarg
10982 && for_each_template_parm (defarg, template_parm_outer_level,
10983 &depth, NULL, /*nondeduced*/true))
10984 return true;
10987 if (uses_outer_template_parms_in_constraints (decl))
10988 return true;
10989 return false;
10992 /* Returns true if the constraints of DECL depend on any template parameters
10993 from its enclosing scope. */
10995 bool
10996 uses_outer_template_parms_in_constraints (tree decl)
10998 tree ci = get_constraints (decl);
10999 if (ci)
11000 ci = CI_ASSOCIATED_CONSTRAINTS (ci);
11001 if (!ci)
11002 return false;
11003 int depth = template_class_depth (CP_DECL_CONTEXT (decl));
11004 if (depth == 0)
11005 return false;
11006 return for_each_template_parm (ci, template_parm_outer_level,
11007 &depth, NULL, /*nondeduced*/true);
11010 /* Returns TRUE iff INST is an instantiation we don't need to do in an
11011 ill-formed translation unit, i.e. a variable or function that isn't
11012 usable in a constant expression. */
11014 static inline bool
11015 neglectable_inst_p (tree d)
11017 return (d && DECL_P (d)
11018 && !undeduced_auto_decl (d)
11019 && !(TREE_CODE (d) == FUNCTION_DECL
11020 ? FNDECL_MANIFESTLY_CONST_EVALUATED (d)
11021 : decl_maybe_constant_var_p (d)));
11024 /* Returns TRUE iff we should refuse to instantiate DECL because it's
11025 neglectable and instantiated from within an erroneous instantiation. */
11027 static bool
11028 limit_bad_template_recursion (tree decl)
11030 struct tinst_level *lev = current_tinst_level;
11031 int errs = errorcount + sorrycount;
11032 if (errs == 0 || !neglectable_inst_p (decl))
11033 return false;
11035 /* Avoid instantiating members of an ill-formed class. */
11036 bool refuse
11037 = (DECL_CLASS_SCOPE_P (decl)
11038 && CLASSTYPE_ERRONEOUS (DECL_CONTEXT (decl)));
11040 if (!refuse)
11042 for (; lev; lev = lev->next)
11043 if (neglectable_inst_p (lev->maybe_get_node ()))
11044 break;
11045 refuse = (lev && errs > lev->errors);
11048 if (refuse)
11050 /* Don't warn about it not being defined. */
11051 suppress_warning (decl, OPT_Wunused);
11052 tree clone;
11053 FOR_EACH_CLONE (clone, decl)
11054 suppress_warning (clone, OPT_Wunused);
11056 return refuse;
11059 static int tinst_depth;
11060 extern int max_tinst_depth;
11061 int depth_reached;
11063 static GTY(()) struct tinst_level *last_error_tinst_level;
11065 /* We're starting to instantiate D; record the template instantiation context
11066 at LOC for diagnostics and to restore it later. */
11068 bool
11069 push_tinst_level_loc (tree tldcl, tree targs, location_t loc)
11071 struct tinst_level *new_level;
11073 if (tinst_depth >= max_tinst_depth)
11075 /* Tell error.cc not to try to instantiate any templates. */
11076 at_eof = 2;
11077 fatal_error (input_location,
11078 "template instantiation depth exceeds maximum of %d"
11079 " (use %<-ftemplate-depth=%> to increase the maximum)",
11080 max_tinst_depth);
11081 return false;
11084 /* If the current instantiation caused problems, don't let it instantiate
11085 anything else. Do allow deduction substitution and decls usable in
11086 constant expressions. */
11087 if (!targs && limit_bad_template_recursion (tldcl))
11089 /* Avoid no_linkage_errors and unused function (and all other)
11090 warnings for this decl. */
11091 suppress_warning (tldcl);
11092 return false;
11095 /* When not -quiet, dump template instantiations other than functions, since
11096 announce_function will take care of those. */
11097 if (!quiet_flag && !targs
11098 && TREE_CODE (tldcl) != TREE_LIST
11099 && TREE_CODE (tldcl) != FUNCTION_DECL)
11100 fprintf (stderr, " %s", decl_as_string (tldcl, TFF_DECL_SPECIFIERS));
11102 new_level = tinst_level_freelist ().alloc ();
11103 new_level->tldcl = tldcl;
11104 new_level->targs = targs;
11105 new_level->locus = loc;
11106 new_level->errors = errorcount + sorrycount;
11107 new_level->next = NULL;
11108 new_level->refcount = 0;
11109 new_level->path = new_level->visible = nullptr;
11110 set_refcount_ptr (new_level->next, current_tinst_level);
11111 set_refcount_ptr (current_tinst_level, new_level);
11113 ++tinst_depth;
11114 if (GATHER_STATISTICS && (tinst_depth > depth_reached))
11115 depth_reached = tinst_depth;
11117 return true;
11120 /* We're starting substitution of TMPL<ARGS>; record the template
11121 substitution context for diagnostics and to restore it later. */
11123 bool
11124 push_tinst_level (tree tmpl, tree args)
11126 return push_tinst_level_loc (tmpl, args, input_location);
11129 /* We're starting to instantiate D; record INPUT_LOCATION and the
11130 template instantiation context for diagnostics and to restore it
11131 later. */
11133 bool
11134 push_tinst_level (tree d)
11136 return push_tinst_level_loc (d, input_location);
11139 /* Likewise, but record LOC as the program location. */
11141 bool
11142 push_tinst_level_loc (tree d, location_t loc)
11144 gcc_assert (TREE_CODE (d) != TREE_LIST);
11145 return push_tinst_level_loc (d, NULL, loc);
11148 /* We're done instantiating this template; return to the instantiation
11149 context. */
11151 void
11152 pop_tinst_level (void)
11154 /* Restore the filename and line number stashed away when we started
11155 this instantiation. */
11156 input_location = current_tinst_level->locus;
11157 set_refcount_ptr (current_tinst_level, current_tinst_level->next);
11158 --tinst_depth;
11161 /* We're instantiating a deferred template; restore the template
11162 instantiation context in which the instantiation was requested, which
11163 is one step out from LEVEL. Return the corresponding DECL or TYPE. */
11165 static tree
11166 reopen_tinst_level (struct tinst_level *level)
11168 struct tinst_level *t;
11170 tinst_depth = 0;
11171 for (t = level; t; t = t->next)
11172 ++tinst_depth;
11174 set_refcount_ptr (current_tinst_level, level);
11175 pop_tinst_level ();
11176 if (current_tinst_level)
11177 current_tinst_level->errors = errorcount+sorrycount;
11178 return level->maybe_get_node ();
11181 /* Returns the TINST_LEVEL which gives the original instantiation
11182 context. */
11184 struct tinst_level *
11185 outermost_tinst_level (void)
11187 struct tinst_level *level = current_tinst_level;
11188 if (level)
11189 while (level->next)
11190 level = level->next;
11191 return level;
11194 /* True iff T is a friend function declaration that is not itself a template
11195 and is not defined in a class template. */
11197 bool
11198 non_templated_friend_p (tree t)
11200 if (t && TREE_CODE (t) == FUNCTION_DECL
11201 && DECL_UNIQUE_FRIEND_P (t))
11203 tree ti = DECL_TEMPLATE_INFO (t);
11204 if (!ti)
11205 return true;
11206 /* DECL_FRIEND_CONTEXT is set for a friend defined in class. */
11207 if (DECL_FRIEND_CONTEXT (t))
11208 return false;
11209 /* Non-templated friends in a class template are still represented with a
11210 TEMPLATE_DECL; check that its primary template is the befriending
11211 class. Note that DECL_PRIMARY_TEMPLATE is null for
11212 template <class T> friend A<T>::f(); */
11213 tree tmpl = TI_TEMPLATE (ti);
11214 tree primary = DECL_PRIMARY_TEMPLATE (tmpl);
11215 return (primary && primary != tmpl);
11217 else
11218 return false;
11221 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL. ARGS is the
11222 vector of template arguments, as for tsubst.
11224 Returns an appropriate tsubst'd friend declaration. */
11226 static tree
11227 tsubst_friend_function (tree decl, tree args)
11229 tree new_friend;
11231 if (TREE_CODE (decl) == FUNCTION_DECL
11232 && DECL_TEMPLATE_INSTANTIATION (decl)
11233 && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
11234 /* This was a friend declared with an explicit template
11235 argument list, e.g.:
11237 friend void f<>(T);
11239 to indicate that f was a template instantiation, not a new
11240 function declaration. Now, we have to figure out what
11241 instantiation of what template. */
11243 tree template_id, arglist, fns;
11244 tree new_args;
11245 tree tmpl;
11246 tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
11248 /* Friend functions are looked up in the containing namespace scope.
11249 We must enter that scope, to avoid finding member functions of the
11250 current class with same name. */
11251 push_nested_namespace (ns);
11252 fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
11253 tf_warning_or_error, NULL_TREE);
11254 pop_nested_namespace (ns);
11255 arglist = tsubst (DECL_TI_ARGS (decl), args,
11256 tf_warning_or_error, NULL_TREE);
11257 template_id = lookup_template_function (fns, arglist);
11259 new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11260 tmpl = determine_specialization (template_id, new_friend,
11261 &new_args,
11262 /*need_member_template=*/0,
11263 TREE_VEC_LENGTH (args),
11264 tsk_none);
11265 return instantiate_template (tmpl, new_args, tf_error);
11268 new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11269 if (new_friend == error_mark_node)
11270 return error_mark_node;
11272 /* The NEW_FRIEND will look like an instantiation, to the
11273 compiler, but is not an instantiation from the point of view of
11274 the language. For example, we might have had:
11276 template <class T> struct S {
11277 template <class U> friend void f(T, U);
11280 Then, in S<int>, template <class U> void f(int, U) is not an
11281 instantiation of anything. */
11283 DECL_USE_TEMPLATE (new_friend) = 0;
11284 if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11286 DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (new_friend) = false;
11287 DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
11288 DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
11289 = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
11291 /* Substitute TEMPLATE_PARMS_CONSTRAINTS so that parameter levels will
11292 match in decls_match. */
11293 tree parms = DECL_TEMPLATE_PARMS (new_friend);
11294 tree treqs = TEMPLATE_PARMS_CONSTRAINTS (parms);
11295 treqs = maybe_substitute_reqs_for (treqs, new_friend);
11296 if (treqs != TEMPLATE_PARMS_CONSTRAINTS (parms))
11298 TEMPLATE_PARMS_CONSTRAINTS (parms) = treqs;
11299 /* As well as each TEMPLATE_PARM_CONSTRAINTS. */
11300 tsubst_each_template_parm_constraints (parms, args,
11301 tf_warning_or_error);
11305 /* The mangled name for the NEW_FRIEND is incorrect. The function
11306 is not a template instantiation and should not be mangled like
11307 one. Therefore, we forget the mangling here; we'll recompute it
11308 later if we need it. */
11309 if (TREE_CODE (new_friend) != TEMPLATE_DECL)
11311 SET_DECL_RTL (new_friend, NULL);
11312 SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
11315 if (DECL_NAMESPACE_SCOPE_P (new_friend))
11317 tree old_decl;
11318 tree ns;
11320 /* We must save some information from NEW_FRIEND before calling
11321 duplicate decls since that function will free NEW_FRIEND if
11322 possible. */
11323 tree new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
11324 tree new_friend_result_template_info = NULL_TREE;
11325 bool new_friend_is_defn =
11326 (new_friend_template_info
11327 && (DECL_INITIAL (DECL_TEMPLATE_RESULT
11328 (template_for_substitution (new_friend)))
11329 != NULL_TREE));
11330 tree not_tmpl = new_friend;
11332 if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11334 /* This declaration is a `primary' template. */
11335 DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
11337 not_tmpl = DECL_TEMPLATE_RESULT (new_friend);
11338 new_friend_result_template_info = DECL_TEMPLATE_INFO (not_tmpl);
11340 else if (!constraints_satisfied_p (new_friend))
11341 /* Only define a constrained hidden friend when satisfied. */
11342 return error_mark_node;
11344 /* Inside pushdecl_namespace_level, we will push into the
11345 current namespace. However, the friend function should go
11346 into the namespace of the template. */
11347 ns = decl_namespace_context (new_friend);
11348 push_nested_namespace (ns);
11349 old_decl = pushdecl_namespace_level (new_friend, /*hiding=*/true);
11350 pop_nested_namespace (ns);
11352 if (old_decl == error_mark_node)
11353 return error_mark_node;
11355 if (old_decl != new_friend)
11357 /* This new friend declaration matched an existing
11358 declaration. For example, given:
11360 template <class T> void f(T);
11361 template <class U> class C {
11362 template <class T> friend void f(T) {}
11365 the friend declaration actually provides the definition
11366 of `f', once C has been instantiated for some type. So,
11367 old_decl will be the out-of-class template declaration,
11368 while new_friend is the in-class definition.
11370 But, if `f' was called before this point, the
11371 instantiation of `f' will have DECL_TI_ARGS corresponding
11372 to `T' but not to `U', references to which might appear
11373 in the definition of `f'. Previously, the most general
11374 template for an instantiation of `f' was the out-of-class
11375 version; now it is the in-class version. Therefore, we
11376 run through all specialization of `f', adding to their
11377 DECL_TI_ARGS appropriately. In particular, they need a
11378 new set of outer arguments, corresponding to the
11379 arguments for this class instantiation.
11381 The same situation can arise with something like this:
11383 friend void f(int);
11384 template <class T> class C {
11385 friend void f(T) {}
11388 when `C<int>' is instantiated. Now, `f(int)' is defined
11389 in the class. */
11391 if (!new_friend_is_defn)
11392 /* On the other hand, if the in-class declaration does
11393 *not* provide a definition, then we don't want to alter
11394 existing definitions. We can just leave everything
11395 alone. */
11397 else
11399 tree new_template = TI_TEMPLATE (new_friend_template_info);
11400 tree new_args = TI_ARGS (new_friend_template_info);
11402 /* Overwrite whatever template info was there before, if
11403 any, with the new template information pertaining to
11404 the declaration. */
11405 DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
11407 if (TREE_CODE (old_decl) != TEMPLATE_DECL)
11409 /* We should have called reregister_specialization in
11410 duplicate_decls. */
11411 gcc_assert (retrieve_specialization (new_template,
11412 new_args, 0)
11413 == old_decl);
11415 /* Instantiate it if the global has already been used. */
11416 if (DECL_ODR_USED (old_decl))
11417 instantiate_decl (old_decl, /*defer_ok=*/true,
11418 /*expl_inst_class_mem_p=*/false);
11420 else
11422 tree t;
11424 /* Indicate that the old function template is a partial
11425 instantiation. */
11426 DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
11427 = new_friend_result_template_info;
11429 gcc_assert (new_template
11430 == most_general_template (new_template));
11431 gcc_assert (new_template != old_decl);
11433 /* Reassign any specializations already in the hash table
11434 to the new more general template, and add the
11435 additional template args. */
11436 for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
11437 t != NULL_TREE;
11438 t = TREE_CHAIN (t))
11440 tree spec = TREE_VALUE (t);
11441 spec_entry elt;
11443 elt.tmpl = old_decl;
11444 elt.args = DECL_TI_ARGS (spec);
11445 elt.spec = NULL_TREE;
11447 decl_specializations->remove_elt (&elt);
11449 DECL_TI_ARGS (spec)
11450 = add_outermost_template_args (new_args,
11451 DECL_TI_ARGS (spec));
11453 register_specialization
11454 (spec, new_template, DECL_TI_ARGS (spec), true, 0);
11457 DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
11461 /* The information from NEW_FRIEND has been merged into OLD_DECL
11462 by duplicate_decls. */
11463 new_friend = old_decl;
11466 /* We've just introduced a namespace-scope function in the purview
11467 without necessarily having opened the enclosing namespace, so
11468 make sure the namespace is in the purview now too. */
11469 if (modules_p ()
11470 && DECL_MODULE_PURVIEW_P (STRIP_TEMPLATE (new_friend))
11471 && TREE_CODE (DECL_CONTEXT (new_friend)) == NAMESPACE_DECL)
11472 DECL_MODULE_PURVIEW_P (DECL_CONTEXT (new_friend)) = true;
11474 else
11476 tree context = DECL_CONTEXT (new_friend);
11477 bool dependent_p;
11479 /* In the code
11480 template <class T> class C {
11481 template <class U> friend void C1<U>::f (); // case 1
11482 friend void C2<T>::f (); // case 2
11484 we only need to make sure CONTEXT is a complete type for
11485 case 2. To distinguish between the two cases, we note that
11486 CONTEXT of case 1 remains dependent type after tsubst while
11487 this isn't true for case 2. */
11488 ++processing_template_decl;
11489 dependent_p = dependent_type_p (context);
11490 --processing_template_decl;
11492 if (!dependent_p
11493 && !complete_type_or_else (context, NULL_TREE))
11494 return error_mark_node;
11496 if (COMPLETE_TYPE_P (context))
11498 tree fn = new_friend;
11499 /* do_friend adds the TEMPLATE_DECL for any member friend
11500 template even if it isn't a member template, i.e.
11501 template <class T> friend A<T>::f();
11502 Look through it in that case. */
11503 if (TREE_CODE (fn) == TEMPLATE_DECL
11504 && !PRIMARY_TEMPLATE_P (fn))
11505 fn = DECL_TEMPLATE_RESULT (fn);
11506 /* Check to see that the declaration is really present, and,
11507 possibly obtain an improved declaration. */
11508 fn = check_classfn (context, fn, NULL_TREE);
11510 if (fn)
11511 new_friend = fn;
11515 return new_friend;
11518 /* FRIEND_TMPL is a friend TEMPLATE_DECL. ARGS is the vector of
11519 template arguments, as for tsubst.
11521 Returns an appropriate tsubst'd friend type or error_mark_node on
11522 failure. */
11524 static tree
11525 tsubst_friend_class (tree friend_tmpl, tree args)
11527 tree tmpl;
11529 if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
11531 tmpl = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
11532 return TREE_TYPE (tmpl);
11535 tree context = CP_DECL_CONTEXT (friend_tmpl);
11536 if (TREE_CODE (context) == NAMESPACE_DECL)
11537 push_nested_namespace (context);
11538 else
11540 context = tsubst (context, args, tf_error, NULL_TREE);
11541 push_nested_class (context);
11544 tmpl = lookup_name (DECL_NAME (friend_tmpl), LOOK_where::CLASS_NAMESPACE,
11545 LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND);
11547 if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
11549 /* The friend template has already been declared. Just
11550 check to see that the declarations match, and install any new
11551 default parameters. We must tsubst the default parameters,
11552 of course. We only need the innermost template parameters
11553 because that is all that redeclare_class_template will look
11554 at. */
11555 if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
11556 > TMPL_ARGS_DEPTH (args))
11558 tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
11559 args, tf_warning_or_error);
11560 tsubst_each_template_parm_constraints (parms, args,
11561 tf_warning_or_error);
11562 location_t saved_input_location = input_location;
11563 input_location = DECL_SOURCE_LOCATION (friend_tmpl);
11564 tree cons = get_constraints (friend_tmpl);
11565 ++processing_template_decl;
11566 cons = tsubst_constraint_info (cons, args, tf_warning_or_error,
11567 DECL_FRIEND_CONTEXT (friend_tmpl));
11568 --processing_template_decl;
11569 redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
11570 input_location = saved_input_location;
11573 else
11575 /* The friend template has not already been declared. In this
11576 case, the instantiation of the template class will cause the
11577 injection of this template into the namespace scope. */
11578 tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
11580 if (tmpl != error_mark_node)
11582 /* The new TMPL is not an instantiation of anything, so we
11583 forget its origins. We don't reset CLASSTYPE_TI_TEMPLATE
11584 for the new type because that is supposed to be the
11585 corresponding template decl, i.e., TMPL. */
11586 DECL_USE_TEMPLATE (tmpl) = 0;
11587 DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
11588 CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
11589 CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
11590 = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
11592 /* Substitute into and set the constraints on the new declaration. */
11593 if (tree ci = get_constraints (friend_tmpl))
11595 ++processing_template_decl;
11596 ci = tsubst_constraint_info (ci, args, tf_warning_or_error,
11597 DECL_FRIEND_CONTEXT (friend_tmpl));
11598 --processing_template_decl;
11599 set_constraints (tmpl, ci);
11600 tsubst_each_template_parm_constraints (DECL_TEMPLATE_PARMS (tmpl),
11601 args, tf_warning_or_error);
11604 /* Inject this template into the enclosing namspace scope. */
11605 tmpl = pushdecl_namespace_level (tmpl, /*hiding=*/true);
11609 if (TREE_CODE (context) == NAMESPACE_DECL)
11610 pop_nested_namespace (context);
11611 else
11612 pop_nested_class ();
11614 return TREE_TYPE (tmpl);
11617 /* Returns zero if TYPE cannot be completed later due to circularity.
11618 Otherwise returns one. */
11620 static int
11621 can_complete_type_without_circularity (tree type)
11623 if (type == NULL_TREE || type == error_mark_node)
11624 return 0;
11625 else if (COMPLETE_TYPE_P (type))
11626 return 1;
11627 else if (TREE_CODE (type) == ARRAY_TYPE)
11628 return can_complete_type_without_circularity (TREE_TYPE (type));
11629 else if (CLASS_TYPE_P (type)
11630 && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
11631 return 0;
11632 else
11633 return 1;
11636 static tree tsubst_omp_clauses (tree, enum c_omp_region_type, tree,
11637 tsubst_flags_t, tree);
11639 /* Instantiate the contract statement. */
11641 static tree
11642 tsubst_contract (tree decl, tree t, tree args, tsubst_flags_t complain,
11643 tree in_decl)
11645 tree type = decl ? TREE_TYPE (TREE_TYPE (decl)) : NULL_TREE;
11646 bool auto_p = type_uses_auto (type);
11648 tree r = copy_node (t);
11650 /* Rebuild the result variable. */
11651 if (type && POSTCONDITION_P (t) && POSTCONDITION_IDENTIFIER (t))
11653 tree oldvar = POSTCONDITION_IDENTIFIER (t);
11655 tree newvar = copy_node (oldvar);
11656 TREE_TYPE (newvar) = type;
11657 DECL_CONTEXT (newvar) = decl;
11658 POSTCONDITION_IDENTIFIER (r) = newvar;
11660 /* Make sure the postcondition is valid. */
11661 location_t loc = DECL_SOURCE_LOCATION (oldvar);
11662 if (!auto_p)
11663 if (!check_postcondition_result (decl, type, loc))
11664 return invalidate_contract (r);
11666 /* Make the variable available for lookup. */
11667 register_local_specialization (newvar, oldvar);
11670 /* Instantiate the condition. If the return type is undeduced, process
11671 the expression as if inside a template to avoid spurious type errors. */
11672 if (auto_p)
11673 ++processing_template_decl;
11674 ++processing_contract_condition;
11675 CONTRACT_CONDITION (r)
11676 = tsubst_expr (CONTRACT_CONDITION (t), args, complain, in_decl);
11677 --processing_contract_condition;
11678 if (auto_p)
11679 --processing_template_decl;
11681 /* And the comment. */
11682 CONTRACT_COMMENT (r)
11683 = tsubst_expr (CONTRACT_COMMENT (r), args, complain, in_decl);
11685 return r;
11688 /* Update T by instantiating its contract attribute. */
11690 static void
11691 tsubst_contract_attribute (tree decl, tree t, tree args,
11692 tsubst_flags_t complain, tree in_decl)
11694 /* For non-specializations, adjust the current declaration to the most general
11695 version of in_decl. Because we defer the instantiation of contracts as long
11696 as possible, they are still written in terms of the parameters (and return
11697 type) of the most general template. */
11698 tree tmpl = DECL_TI_TEMPLATE (in_decl);
11699 if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
11700 in_decl = DECL_TEMPLATE_RESULT (most_general_template (in_decl));
11701 local_specialization_stack specs (lss_copy);
11702 register_parameter_specializations (in_decl, decl);
11704 /* Get the contract to be instantiated. */
11705 tree contract = CONTRACT_STATEMENT (t);
11707 /* Use the complete set of template arguments for instantiation. The
11708 contract may not have been instantiated and still refer to outer levels
11709 of template parameters. */
11710 args = DECL_TI_ARGS (decl);
11712 /* For member functions, make this available for semantic analysis. */
11713 tree save_ccp = current_class_ptr;
11714 tree save_ccr = current_class_ref;
11715 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
11717 tree arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
11718 tree this_type = TREE_TYPE (TREE_VALUE (arg_types));
11719 inject_this_parameter (this_type, cp_type_quals (this_type));
11722 contract = tsubst_contract (decl, contract, args, complain, in_decl);
11724 current_class_ptr = save_ccp;
11725 current_class_ref = save_ccr;
11727 /* Rebuild the attribute. */
11728 TREE_VALUE (t) = build_tree_list (NULL_TREE, contract);
11731 /* Rebuild the attribute list for DECL, substituting into contracts
11732 as needed. */
11734 void
11735 tsubst_contract_attributes (tree decl, tree args, tsubst_flags_t complain, tree in_decl)
11737 tree list = copy_list (DECL_ATTRIBUTES (decl));
11738 for (tree attr = list; attr; attr = CONTRACT_CHAIN (attr))
11740 if (cxx_contract_attribute_p (attr))
11741 tsubst_contract_attribute (decl, attr, args, complain, in_decl);
11743 DECL_ATTRIBUTES (decl) = list;
11746 /* Instantiate a single dependent attribute T (a TREE_LIST), and return either
11747 T or a new TREE_LIST, possibly a chain in the case of a pack expansion. */
11749 static tree
11750 tsubst_attribute (tree t, tree *decl_p, tree args,
11751 tsubst_flags_t complain, tree in_decl)
11753 gcc_assert (ATTR_IS_DEPENDENT (t));
11755 /* Note that contract attributes are never substituted from this function.
11756 Their instantiation is triggered by regenerate_from_template_decl when
11757 we instantiate the body of the function. */
11759 tree val = TREE_VALUE (t);
11760 if (val == NULL_TREE)
11761 /* Nothing to do. */;
11762 else if ((flag_openmp || flag_openmp_simd)
11763 && is_attribute_p ("omp declare simd",
11764 get_attribute_name (t)))
11766 tree clauses = TREE_VALUE (val);
11767 clauses = tsubst_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD, args,
11768 complain, in_decl);
11769 c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11770 clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11771 tree parms = DECL_ARGUMENTS (*decl_p);
11772 clauses
11773 = c_omp_declare_simd_clauses_to_numbers (parms, clauses);
11774 if (clauses)
11775 val = build_tree_list (NULL_TREE, clauses);
11776 else
11777 val = NULL_TREE;
11779 else if (flag_openmp
11780 && is_attribute_p ("omp declare variant base",
11781 get_attribute_name (t)))
11783 ++cp_unevaluated_operand;
11784 tree varid = tsubst_expr (TREE_PURPOSE (val), args, complain, in_decl);
11785 --cp_unevaluated_operand;
11786 tree chain = TREE_CHAIN (val);
11787 location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
11788 tree ctx = copy_list (TREE_VALUE (val));
11789 tree simd = get_identifier ("simd");
11790 tree score = get_identifier (" score");
11791 tree condition = get_identifier ("condition");
11792 for (tree t1 = ctx; t1; t1 = TREE_CHAIN (t1))
11794 const char *set = IDENTIFIER_POINTER (TREE_PURPOSE (t1));
11795 TREE_VALUE (t1) = copy_list (TREE_VALUE (t1));
11796 for (tree t2 = TREE_VALUE (t1); t2; t2 = TREE_CHAIN (t2))
11798 if (TREE_PURPOSE (t2) == simd && set[0] == 'c')
11800 tree clauses = TREE_VALUE (t2);
11801 clauses = tsubst_omp_clauses (clauses,
11802 C_ORT_OMP_DECLARE_SIMD, args,
11803 complain, in_decl);
11804 c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11805 clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11806 TREE_VALUE (t2) = clauses;
11808 else
11810 TREE_VALUE (t2) = copy_list (TREE_VALUE (t2));
11811 for (tree t3 = TREE_VALUE (t2); t3; t3 = TREE_CHAIN (t3))
11812 if (TREE_VALUE (t3))
11814 bool allow_string
11815 = ((TREE_PURPOSE (t2) != condition || set[0] != 'u')
11816 && TREE_PURPOSE (t3) != score);
11817 tree v = TREE_VALUE (t3);
11818 if (TREE_CODE (v) == STRING_CST && allow_string)
11819 continue;
11820 v = tsubst_expr (v, args, complain, in_decl);
11821 v = fold_non_dependent_expr (v);
11822 if (!INTEGRAL_TYPE_P (TREE_TYPE (v))
11823 || (TREE_PURPOSE (t3) == score
11824 ? TREE_CODE (v) != INTEGER_CST
11825 : !tree_fits_shwi_p (v)))
11827 location_t loc
11828 = cp_expr_loc_or_loc (TREE_VALUE (t3),
11829 match_loc);
11830 if (TREE_PURPOSE (t3) == score)
11831 error_at (loc, "score argument must be "
11832 "constant integer expression");
11833 else if (allow_string)
11834 error_at (loc, "property must be constant "
11835 "integer expression or string "
11836 "literal");
11837 else
11838 error_at (loc, "property must be constant "
11839 "integer expression");
11840 return NULL_TREE;
11842 else if (TREE_PURPOSE (t3) == score
11843 && tree_int_cst_sgn (v) < 0)
11845 location_t loc
11846 = cp_expr_loc_or_loc (TREE_VALUE (t3),
11847 match_loc);
11848 error_at (loc, "score argument must be "
11849 "non-negative");
11850 return NULL_TREE;
11852 TREE_VALUE (t3) = v;
11857 val = tree_cons (varid, ctx, chain);
11859 /* If the first attribute argument is an identifier, don't
11860 pass it through tsubst. Attributes like mode, format,
11861 cleanup and several target specific attributes expect it
11862 unmodified. */
11863 else if (attribute_takes_identifier_p (get_attribute_name (t)))
11865 tree chain
11866 = tsubst_expr (TREE_CHAIN (val), args, complain, in_decl);
11867 if (chain != TREE_CHAIN (val))
11868 val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
11870 else if (PACK_EXPANSION_P (val))
11872 /* An attribute pack expansion. */
11873 tree purp = TREE_PURPOSE (t);
11874 tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
11875 if (pack == error_mark_node)
11876 return error_mark_node;
11877 int len = TREE_VEC_LENGTH (pack);
11878 tree list = NULL_TREE;
11879 tree *q = &list;
11880 for (int i = 0; i < len; ++i)
11882 tree elt = TREE_VEC_ELT (pack, i);
11883 *q = build_tree_list (purp, elt);
11884 q = &TREE_CHAIN (*q);
11886 return list;
11888 else
11889 val = tsubst_expr (val, args, complain, in_decl);
11891 if (val == error_mark_node)
11892 return error_mark_node;
11893 if (val != TREE_VALUE (t))
11894 return build_tree_list (TREE_PURPOSE (t), val);
11895 return t;
11898 /* Instantiate any dependent attributes in ATTRIBUTES, returning either it
11899 unchanged or a new TREE_LIST chain. */
11901 static tree
11902 tsubst_attributes (tree attributes, tree args,
11903 tsubst_flags_t complain, tree in_decl)
11905 tree last_dep = NULL_TREE;
11907 for (tree t = attributes; t; t = TREE_CHAIN (t))
11908 if (ATTR_IS_DEPENDENT (t))
11910 last_dep = t;
11911 attributes = copy_list (attributes);
11912 break;
11915 if (last_dep)
11916 for (tree *p = &attributes; *p; )
11918 tree t = *p;
11919 if (ATTR_IS_DEPENDENT (t))
11921 tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
11922 if (subst != t)
11924 *p = subst;
11925 while (*p)
11926 p = &TREE_CHAIN (*p);
11927 *p = TREE_CHAIN (t);
11928 continue;
11931 p = &TREE_CHAIN (*p);
11934 return attributes;
11937 /* Apply any attributes which had to be deferred until instantiation
11938 time. DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
11939 ARGS, COMPLAIN, IN_DECL are as tsubst. Returns true normally,
11940 false on error. */
11942 static bool
11943 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
11944 tree args, tsubst_flags_t complain, tree in_decl)
11946 tree t;
11947 tree *p;
11949 if (attributes == NULL_TREE)
11950 return true;
11952 if (DECL_P (*decl_p))
11954 if (TREE_TYPE (*decl_p) == error_mark_node)
11955 return false;
11956 p = &DECL_ATTRIBUTES (*decl_p);
11957 /* DECL_ATTRIBUTES comes from copy_node in tsubst_decl, and is identical
11958 to our attributes parameter. */
11959 gcc_assert (*p == attributes);
11961 else
11963 p = &TYPE_ATTRIBUTES (*decl_p);
11964 /* TYPE_ATTRIBUTES was set up (with abi_tag and may_alias) in
11965 lookup_template_class_1, and should be preserved. */
11966 gcc_assert (*p != attributes);
11967 while (*p)
11968 p = &TREE_CHAIN (*p);
11971 /* save_template_attributes puts the dependent attributes at the beginning of
11972 the list; find the non-dependent ones. */
11973 for (t = attributes; t; t = TREE_CHAIN (t))
11974 if (!ATTR_IS_DEPENDENT (t))
11975 break;
11976 tree nondep = t;
11978 /* Apply any non-dependent attributes. */
11979 *p = nondep;
11981 if (nondep == attributes)
11982 return true;
11984 /* And then any dependent ones. */
11985 tree late_attrs = NULL_TREE;
11986 tree *q = &late_attrs;
11987 for (t = attributes; t != nondep; t = TREE_CHAIN (t))
11989 *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
11990 if (*q == error_mark_node)
11991 return false;
11992 if (*q == t)
11994 *q = copy_node (t);
11995 TREE_CHAIN (*q) = NULL_TREE;
11997 while (*q)
11998 q = &TREE_CHAIN (*q);
12001 /* cplus_decl_attributes can add some attributes implicitly. For templates,
12002 those attributes should have been added already when those templates were
12003 parsed, and shouldn't be added based on from which context they are
12004 first time instantiated. */
12005 auto o1 = make_temp_override (current_optimize_pragma, NULL_TREE);
12006 auto o2 = make_temp_override (optimization_current_node,
12007 optimization_default_node);
12008 auto o3 = make_temp_override (current_target_pragma, NULL_TREE);
12009 auto o4 = make_temp_override (scope_chain->omp_declare_target_attribute,
12010 NULL);
12011 auto o5 = make_temp_override (scope_chain->omp_begin_assumes, NULL);
12013 cplus_decl_attributes (decl_p, late_attrs, attr_flags);
12015 return true;
12018 /* The template TMPL is being instantiated with the template arguments TARGS.
12019 Perform the access checks that we deferred when parsing the template. */
12021 static void
12022 perform_instantiation_time_access_checks (tree tmpl, tree targs)
12024 unsigned i;
12025 deferred_access_check *chk;
12027 if (!CLASS_TYPE_P (tmpl) && TREE_CODE (tmpl) != FUNCTION_DECL)
12028 return;
12030 if (vec<deferred_access_check, va_gc> *access_checks
12031 = TI_DEFERRED_ACCESS_CHECKS (get_template_info (tmpl)))
12032 FOR_EACH_VEC_ELT (*access_checks, i, chk)
12034 tree decl = chk->decl;
12035 tree diag_decl = chk->diag_decl;
12036 tree type_scope = TREE_TYPE (chk->binfo);
12038 if (uses_template_parms (type_scope))
12039 type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
12041 /* Make access check error messages point to the location
12042 of the use of the typedef. */
12043 iloc_sentinel ils (chk->loc);
12044 perform_or_defer_access_check (TYPE_BINFO (type_scope),
12045 decl, diag_decl, tf_warning_or_error);
12049 tree
12050 instantiate_class_template (tree type)
12052 auto_timevar tv (TV_TEMPLATE_INST);
12054 tree templ, args, pattern, t, member;
12055 tree typedecl;
12056 tree pbinfo;
12057 tree base_list;
12058 unsigned int saved_maximum_field_alignment;
12059 tree fn_context;
12061 if (type == error_mark_node)
12062 return error_mark_node;
12064 if (COMPLETE_OR_OPEN_TYPE_P (type)
12065 || (uses_template_parms (type)
12066 && !TYPE_FUNCTION_SCOPE_P (type)))
12067 return type;
12069 /* Figure out which template is being instantiated. */
12070 templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
12071 gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
12073 /* Mark the type as in the process of being defined. */
12074 TYPE_BEING_DEFINED (type) = 1;
12076 /* We may be in the middle of deferred access check. Disable
12077 it now. */
12078 deferring_access_check_sentinel acs (dk_no_deferred);
12080 /* Determine what specialization of the original template to
12081 instantiate. */
12082 t = most_specialized_partial_spec (type, tf_warning_or_error);
12083 if (t == error_mark_node)
12084 return error_mark_node;
12085 else if (t)
12087 /* This TYPE is actually an instantiation of a partial
12088 specialization. We replace the innermost set of ARGS with
12089 the arguments appropriate for substitution. For example,
12090 given:
12092 template <class T> struct S {};
12093 template <class T> struct S<T*> {};
12095 and supposing that we are instantiating S<int*>, ARGS will
12096 presently be {int*} -- but we need {int}. */
12097 pattern = TREE_TYPE (t);
12098 args = TREE_PURPOSE (t);
12100 else
12102 pattern = TREE_TYPE (templ);
12103 args = CLASSTYPE_TI_ARGS (type);
12106 /* If the template we're instantiating is incomplete, then clearly
12107 there's nothing we can do. */
12108 if (!COMPLETE_TYPE_P (pattern))
12110 /* We can try again later. */
12111 TYPE_BEING_DEFINED (type) = 0;
12112 return type;
12115 /* If we've recursively instantiated too many templates, stop. */
12116 if (! push_tinst_level (type))
12117 return type;
12119 int saved_unevaluated_operand = cp_unevaluated_operand;
12120 int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
12122 fn_context = decl_function_context (TYPE_MAIN_DECL (type));
12123 /* Also avoid push_to_top_level for a lambda in an NSDMI. */
12124 if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
12125 fn_context = error_mark_node;
12126 if (!fn_context)
12127 push_to_top_level ();
12128 else
12130 cp_unevaluated_operand = 0;
12131 c_inhibit_evaluation_warnings = 0;
12134 mark_template_arguments_used (templ, CLASSTYPE_TI_ARGS (type));
12136 /* Use #pragma pack from the template context. */
12137 saved_maximum_field_alignment = maximum_field_alignment;
12138 maximum_field_alignment = TYPE_PRECISION (pattern);
12140 SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
12142 /* Set the input location to the most specialized template definition.
12143 This is needed if tsubsting causes an error. */
12144 typedecl = TYPE_MAIN_DECL (pattern);
12145 input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
12146 DECL_SOURCE_LOCATION (typedecl);
12148 set_instantiating_module (TYPE_NAME (type));
12150 TYPE_PACKED (type) = TYPE_PACKED (pattern);
12151 SET_TYPE_ALIGN (type, TYPE_ALIGN (pattern));
12152 TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
12153 CLASSTYPE_NON_AGGREGATE (type) = CLASSTYPE_NON_AGGREGATE (pattern);
12154 if (ANON_AGGR_TYPE_P (pattern))
12155 SET_ANON_AGGR_TYPE_P (type);
12156 if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
12158 CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
12159 CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
12160 /* Adjust visibility for template arguments. */
12161 determine_visibility (TYPE_MAIN_DECL (type));
12163 if (CLASS_TYPE_P (type))
12164 CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
12166 pbinfo = TYPE_BINFO (pattern);
12168 /* We should never instantiate a nested class before its enclosing
12169 class; we need to look up the nested class by name before we can
12170 instantiate it, and that lookup should instantiate the enclosing
12171 class. */
12172 gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
12173 || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
12175 base_list = NULL_TREE;
12176 /* Defer access checking while we substitute into the types named in
12177 the base-clause. */
12178 push_deferring_access_checks (dk_deferred);
12179 if (BINFO_N_BASE_BINFOS (pbinfo))
12181 tree pbase_binfo;
12182 int i;
12184 /* Substitute into each of the bases to determine the actual
12185 basetypes. */
12186 for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
12188 tree base;
12189 tree access = BINFO_BASE_ACCESS (pbinfo, i);
12190 tree expanded_bases = NULL_TREE;
12191 int idx, len = 1;
12193 if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
12195 expanded_bases =
12196 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
12197 args, tf_error, NULL_TREE);
12198 if (expanded_bases == error_mark_node)
12199 continue;
12201 len = TREE_VEC_LENGTH (expanded_bases);
12204 for (idx = 0; idx < len; idx++)
12206 if (expanded_bases)
12207 /* Extract the already-expanded base class. */
12208 base = TREE_VEC_ELT (expanded_bases, idx);
12209 else
12210 /* Substitute to figure out the base class. */
12211 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
12212 NULL_TREE);
12214 if (base == error_mark_node)
12215 continue;
12217 base_list = tree_cons (access, base, base_list);
12218 if (BINFO_VIRTUAL_P (pbase_binfo))
12219 TREE_TYPE (base_list) = integer_type_node;
12223 /* The list is now in reverse order; correct that. */
12224 base_list = nreverse (base_list);
12226 /* Now call xref_basetypes to set up all the base-class
12227 information. */
12228 xref_basetypes (type, base_list);
12230 apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
12231 (int) ATTR_FLAG_TYPE_IN_PLACE,
12232 args, tf_error, NULL_TREE);
12233 fixup_attribute_variants (type);
12235 /* Now that our base classes are set up, enter the scope of the
12236 class, so that name lookups into base classes, etc. will work
12237 correctly. This is precisely analogous to what we do in
12238 begin_class_definition when defining an ordinary non-template
12239 class, except we also need to push the enclosing classes. */
12240 push_nested_class (type);
12242 /* Now check accessibility of the types named in its base-clause,
12243 relative to the scope of the class. */
12244 pop_to_parent_deferring_access_checks ();
12246 /* A vector to hold members marked with attribute used. */
12247 auto_vec<tree> used;
12249 /* Now members are processed in the order of declaration. */
12250 for (member = CLASSTYPE_DECL_LIST (pattern);
12251 member; member = TREE_CHAIN (member))
12253 tree t = TREE_VALUE (member);
12255 if (TREE_PURPOSE (member))
12257 if (TYPE_P (t))
12259 if (LAMBDA_TYPE_P (t))
12260 /* A closure type for a lambda in an NSDMI or default argument.
12261 Ignore it; it will be regenerated when needed. */
12262 continue;
12264 /* If the member is a class template, we've
12265 already substituted its type. */
12266 if (CLASS_TYPE_P (t)
12267 && CLASSTYPE_IS_TEMPLATE (t))
12268 continue;
12270 tree newtag = tsubst (t, args, tf_error, NULL_TREE);
12271 if (newtag == error_mark_node)
12272 continue;
12274 if (TREE_CODE (newtag) != ENUMERAL_TYPE)
12276 tree name = TYPE_IDENTIFIER (t);
12278 /* Now, install the tag. We don't use pushtag
12279 because that does too much work -- creating an
12280 implicit typedef, which we've already done. */
12281 set_identifier_type_value (name, TYPE_NAME (newtag));
12282 maybe_add_class_template_decl_list (type, newtag, false);
12283 TREE_PUBLIC (TYPE_NAME (newtag)) = true;
12284 determine_visibility (TYPE_NAME (newtag));
12287 else if (DECL_DECLARES_FUNCTION_P (t))
12289 tree r;
12291 if (TREE_CODE (t) == TEMPLATE_DECL)
12292 ++processing_template_decl;
12293 r = tsubst (t, args, tf_error, NULL_TREE);
12294 if (TREE_CODE (t) == TEMPLATE_DECL)
12295 --processing_template_decl;
12297 set_current_access_from_decl (r);
12298 finish_member_declaration (r);
12299 /* Instantiate members marked with attribute used. */
12300 if (r != error_mark_node && DECL_PRESERVE_P (r))
12301 used.safe_push (r);
12302 if (TREE_CODE (r) == FUNCTION_DECL
12303 && DECL_OMP_DECLARE_REDUCTION_P (r))
12304 cp_check_omp_declare_reduction (r);
12306 else if ((DECL_CLASS_TEMPLATE_P (t) || DECL_IMPLICIT_TYPEDEF_P (t))
12307 && LAMBDA_TYPE_P (TREE_TYPE (t)))
12308 /* A closure type for a lambda in an NSDMI or default argument.
12309 Ignore it; it will be regenerated when needed. */;
12310 else
12312 /* Build new TYPE_FIELDS. */
12313 if (TREE_CODE (t) == STATIC_ASSERT)
12314 tsubst_expr (t, args, tf_warning_or_error, NULL_TREE);
12315 else if (TREE_CODE (t) != CONST_DECL)
12317 tree r;
12318 tree vec = NULL_TREE;
12319 int len = 1;
12321 gcc_checking_assert (TREE_CODE (t) != CONST_DECL);
12322 /* The file and line for this declaration, to
12323 assist in error message reporting. Since we
12324 called push_tinst_level above, we don't need to
12325 restore these. */
12326 input_location = DECL_SOURCE_LOCATION (t);
12328 if (TREE_CODE (t) == TEMPLATE_DECL)
12329 ++processing_template_decl;
12330 r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
12331 if (TREE_CODE (t) == TEMPLATE_DECL)
12332 --processing_template_decl;
12334 if (TREE_CODE (r) == TREE_VEC)
12336 /* A capture pack became multiple fields. */
12337 vec = r;
12338 len = TREE_VEC_LENGTH (vec);
12341 for (int i = 0; i < len; ++i)
12343 if (vec)
12344 r = TREE_VEC_ELT (vec, i);
12345 if (VAR_P (r))
12347 /* In [temp.inst]:
12349 [t]he initialization (and any associated
12350 side-effects) of a static data member does
12351 not occur unless the static data member is
12352 itself used in a way that requires the
12353 definition of the static data member to
12354 exist.
12356 Therefore, we do not substitute into the
12357 initialized for the static data member here. */
12358 finish_static_data_member_decl
12360 /*init=*/NULL_TREE,
12361 /*init_const_expr_p=*/false,
12362 /*asmspec_tree=*/NULL_TREE,
12363 /*flags=*/0);
12364 /* Instantiate members marked with attribute used. */
12365 if (r != error_mark_node && DECL_PRESERVE_P (r))
12366 used.safe_push (r);
12368 else if (TREE_CODE (r) == FIELD_DECL)
12370 /* Determine whether R has a valid type and can be
12371 completed later. If R is invalid, then its type
12372 is replaced by error_mark_node. */
12373 tree rtype = TREE_TYPE (r);
12374 if (can_complete_type_without_circularity (rtype))
12375 complete_type (rtype);
12377 if (!complete_or_array_type_p (rtype))
12379 /* If R's type couldn't be completed and
12380 it isn't a flexible array member (whose
12381 type is incomplete by definition) give
12382 an error. */
12383 cxx_incomplete_type_error (r, rtype);
12384 TREE_TYPE (r) = error_mark_node;
12386 else if (TREE_CODE (rtype) == ARRAY_TYPE
12387 && TYPE_DOMAIN (rtype) == NULL_TREE
12388 && (TREE_CODE (type) == UNION_TYPE
12389 || TREE_CODE (type) == QUAL_UNION_TYPE))
12391 error ("flexible array member %qD in union", r);
12392 TREE_TYPE (r) = error_mark_node;
12394 else if (!verify_type_context (input_location,
12395 TCTX_FIELD, rtype))
12396 TREE_TYPE (r) = error_mark_node;
12399 /* If it is a TYPE_DECL for a class-scoped
12400 ENUMERAL_TYPE, such a thing will already have
12401 been added to the field list by tsubst_enum
12402 in finish_member_declaration case above. */
12403 if (!(TREE_CODE (r) == TYPE_DECL
12404 && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
12405 && DECL_ARTIFICIAL (r)))
12407 set_current_access_from_decl (r);
12408 finish_member_declaration (r);
12414 else
12416 if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
12417 || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
12419 /* Build new CLASSTYPE_FRIEND_CLASSES. */
12421 tree friend_type = t;
12422 if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12424 /* template <class T> friend class C; */
12425 friend_type = tsubst_friend_class (friend_type, args);
12427 else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
12429 /* template <class T> friend class C::D; */
12430 friend_type = tsubst (friend_type, args,
12431 tf_warning_or_error, NULL_TREE);
12432 if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12433 friend_type = TREE_TYPE (friend_type);
12435 else if (TREE_CODE (friend_type) == TYPENAME_TYPE
12436 || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
12438 /* This could be either
12440 friend class T::C;
12442 when dependent_type_p is false or
12444 template <class U> friend class T::C;
12446 otherwise. */
12447 /* Bump processing_template_decl in case this is something like
12448 template <class T> friend struct A<T>::B. */
12449 ++processing_template_decl;
12450 friend_type = tsubst (friend_type, args,
12451 tf_warning_or_error, NULL_TREE);
12452 --processing_template_decl;
12454 else if (uses_template_parms (friend_type))
12455 /* friend class C<T>; */
12456 friend_type = tsubst (friend_type, args,
12457 tf_warning_or_error, NULL_TREE);
12459 /* Otherwise it's
12461 friend class C;
12463 where C is already declared or
12465 friend class C<int>;
12467 We don't have to do anything in these cases. */
12469 if (friend_type != error_mark_node)
12470 make_friend_class (type, friend_type, /*complain=*/false);
12472 else
12474 /* Build new DECL_FRIENDLIST. */
12475 tree r;
12477 /* The file and line for this declaration, to
12478 assist in error message reporting. Since we
12479 called push_tinst_level above, we don't need to
12480 restore these. */
12481 input_location = DECL_SOURCE_LOCATION (t);
12483 if (TREE_CODE (t) == TEMPLATE_DECL)
12485 ++processing_template_decl;
12486 push_deferring_access_checks (dk_no_check);
12489 r = tsubst_friend_function (t, args);
12490 add_friend (type, r, /*complain=*/false);
12491 if (TREE_CODE (t) == TEMPLATE_DECL)
12493 pop_deferring_access_checks ();
12494 --processing_template_decl;
12500 if (fn_context)
12502 /* Restore these before substituting into the lambda capture
12503 initializers. */
12504 cp_unevaluated_operand = saved_unevaluated_operand;
12505 c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
12508 /* Set the file and line number information to whatever is given for
12509 the class itself. This puts error messages involving generated
12510 implicit functions at a predictable point, and the same point
12511 that would be used for non-template classes. */
12512 input_location = DECL_SOURCE_LOCATION (typedecl);
12514 unreverse_member_declarations (type);
12515 finish_struct_1 (type);
12516 TYPE_BEING_DEFINED (type) = 0;
12518 /* Remember if instantiating this class ran into errors, so we can avoid
12519 instantiating member functions in limit_bad_template_recursion. We set
12520 this flag even if the problem was in another instantiation triggered by
12521 this one, as that will likely also cause trouble for member functions. */
12522 if (errorcount + sorrycount > current_tinst_level->errors)
12523 CLASSTYPE_ERRONEOUS (type) = true;
12525 /* We don't instantiate default arguments for member functions. 14.7.1:
12527 The implicit instantiation of a class template specialization causes
12528 the implicit instantiation of the declarations, but not of the
12529 definitions or default arguments, of the class member functions,
12530 member classes, static data members and member templates.... */
12532 perform_instantiation_time_access_checks (pattern, args);
12533 perform_deferred_access_checks (tf_warning_or_error);
12535 /* Now that we've gone through all the members, instantiate those
12536 marked with attribute used. We must do this in the context of
12537 the class -- not the context we pushed from, as that might be
12538 inside a template and change the behaviour of mark_used. */
12539 for (tree x : used)
12540 mark_used (x);
12542 pop_nested_class ();
12543 maximum_field_alignment = saved_maximum_field_alignment;
12544 if (!fn_context)
12545 pop_from_top_level ();
12546 pop_tinst_level ();
12548 /* The vtable for a template class can be emitted in any translation
12549 unit in which the class is instantiated. When there is no key
12550 method, however, finish_struct_1 will already have added TYPE to
12551 the keyed_classes. */
12552 if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
12553 vec_safe_push (keyed_classes, type);
12555 return type;
12558 tree
12559 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12561 tree r;
12563 if (!t)
12564 r = t;
12565 else if (TYPE_P (t))
12566 r = tsubst (t, args, complain, in_decl);
12567 else
12569 if (!(complain & tf_warning))
12570 ++c_inhibit_evaluation_warnings;
12571 r = tsubst_expr (t, args, complain, in_decl);
12572 if (!(complain & tf_warning))
12573 --c_inhibit_evaluation_warnings;
12576 return r;
12579 /* Given a function parameter pack TMPL_PARM and some function parameters
12580 instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
12581 and set *SPEC_P to point at the next point in the list. */
12583 tree
12584 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
12586 /* Collect all of the extra "packed" parameters into an
12587 argument pack. */
12588 tree argpack;
12589 tree spec_parm = *spec_p;
12590 int len;
12592 for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
12593 if (tmpl_parm
12594 && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
12595 break;
12597 spec_parm = *spec_p;
12598 if (len == 1 && DECL_PACK_P (spec_parm))
12600 /* The instantiation is still a parameter pack; don't wrap it in a
12601 NONTYPE_ARGUMENT_PACK. */
12602 argpack = spec_parm;
12603 spec_parm = DECL_CHAIN (spec_parm);
12605 else
12607 /* Fill in PARMVEC with all of the parameters. */
12608 tree parmvec = make_tree_vec (len);
12609 argpack = make_node (NONTYPE_ARGUMENT_PACK);
12610 for (int i = 0; i < len; i++)
12612 tree elt = spec_parm;
12613 if (DECL_PACK_P (elt))
12614 elt = make_pack_expansion (elt);
12615 TREE_VEC_ELT (parmvec, i) = elt;
12616 spec_parm = DECL_CHAIN (spec_parm);
12619 /* Build the argument packs. */
12620 ARGUMENT_PACK_ARGS (argpack) = parmvec;
12622 *spec_p = spec_parm;
12624 return argpack;
12627 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
12628 NONTYPE_ARGUMENT_PACK. */
12630 static tree
12631 make_fnparm_pack (tree spec_parm)
12633 return extract_fnparm_pack (NULL_TREE, &spec_parm);
12636 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
12637 pack expansion with no extra args, 2 if it has extra args, or 0
12638 if it is not a pack expansion. */
12640 static int
12641 argument_pack_element_is_expansion_p (tree arg_pack, int i)
12643 if (TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12644 /* We're being called before this happens in tsubst_pack_expansion. */
12645 arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12646 tree vec = ARGUMENT_PACK_ARGS (arg_pack);
12647 if (i >= TREE_VEC_LENGTH (vec))
12648 return 0;
12649 tree elt = TREE_VEC_ELT (vec, i);
12650 if (DECL_P (elt))
12651 /* A decl pack is itself an expansion. */
12652 elt = TREE_TYPE (elt);
12653 if (!PACK_EXPANSION_P (elt))
12654 return 0;
12655 if (PACK_EXPANSION_EXTRA_ARGS (elt))
12656 return 2;
12657 return 1;
12661 /* Creates and return an ARGUMENT_PACK_SELECT tree node. */
12663 static tree
12664 make_argument_pack_select (tree arg_pack, unsigned index)
12666 tree aps = make_node (ARGUMENT_PACK_SELECT);
12668 ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
12669 ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12671 return aps;
12674 /* This is a subroutine of tsubst_pack_expansion.
12676 It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
12677 mechanism to store the (non complete list of) arguments of the
12678 substitution and return a non substituted pack expansion, in order
12679 to wait for when we have enough arguments to really perform the
12680 substitution. */
12682 static bool
12683 use_pack_expansion_extra_args_p (tree t,
12684 tree parm_packs,
12685 int arg_pack_len,
12686 bool has_empty_arg)
12688 if (has_empty_arg
12689 && PACK_EXPANSION_FORCE_EXTRA_ARGS_P (t))
12690 return true;
12692 /* If one pack has an expansion and another pack has a normal
12693 argument or if one pack has an empty argument and an another
12694 one hasn't then tsubst_pack_expansion cannot perform the
12695 substitution and need to fall back on the
12696 PACK_EXPANSION_EXTRA mechanism. */
12697 if (parm_packs == NULL_TREE)
12698 return false;
12699 else if (has_empty_arg)
12701 /* If all the actual packs are pack expansions, we can still
12702 subsitute directly. */
12703 for (tree p = parm_packs; p; p = TREE_CHAIN (p))
12705 tree a = TREE_VALUE (p);
12706 if (TREE_CODE (a) == ARGUMENT_PACK_SELECT)
12707 a = ARGUMENT_PACK_SELECT_FROM_PACK (a);
12708 a = ARGUMENT_PACK_ARGS (a);
12709 if (TREE_VEC_LENGTH (a) == 1)
12710 a = TREE_VEC_ELT (a, 0);
12711 if (PACK_EXPANSION_P (a))
12712 continue;
12713 return true;
12715 return false;
12718 for (int i = 0 ; i < arg_pack_len; ++i)
12720 bool has_expansion_arg = false;
12721 bool has_non_expansion_arg = false;
12722 for (tree parm_pack = parm_packs;
12723 parm_pack;
12724 parm_pack = TREE_CHAIN (parm_pack))
12726 tree arg = TREE_VALUE (parm_pack);
12728 int exp = argument_pack_element_is_expansion_p (arg, i);
12729 if (exp == 2)
12730 /* We can't substitute a pack expansion with extra args into
12731 our pattern. */
12732 return true;
12733 else if (exp)
12734 has_expansion_arg = true;
12735 else
12736 has_non_expansion_arg = true;
12739 if (has_expansion_arg && has_non_expansion_arg)
12741 gcc_checking_assert (false);
12742 return true;
12745 return false;
12748 /* [temp.variadic]/6 says that:
12750 The instantiation of a pack expansion [...]
12751 produces a list E1,E2, ..., En, where N is the number of elements
12752 in the pack expansion parameters.
12754 This subroutine of tsubst_pack_expansion produces one of these Ei.
12756 PATTERN is the pattern of the pack expansion. PARM_PACKS is a
12757 TREE_LIST in which each TREE_PURPOSE is a parameter pack of
12758 PATTERN, and each TREE_VALUE is its corresponding argument pack.
12759 INDEX is the index 'i' of the element Ei to produce. ARGS,
12760 COMPLAIN, and IN_DECL are the same parameters as for the
12761 tsubst_pack_expansion function.
12763 The function returns the resulting Ei upon successful completion,
12764 or error_mark_node.
12766 Note that this function possibly modifies the ARGS parameter, so
12767 it's the responsibility of the caller to restore it. */
12769 static tree
12770 gen_elem_of_pack_expansion_instantiation (tree pattern,
12771 tree parm_packs,
12772 unsigned index,
12773 tree args /* This parm gets
12774 modified. */,
12775 tsubst_flags_t complain,
12776 tree in_decl)
12778 tree t;
12779 bool ith_elem_is_expansion = false;
12781 /* For each parameter pack, change the substitution of the parameter
12782 pack to the ith argument in its argument pack, then expand the
12783 pattern. */
12784 for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
12786 tree parm = TREE_PURPOSE (pack);
12787 tree arg_pack = TREE_VALUE (pack);
12788 tree aps; /* instance of ARGUMENT_PACK_SELECT. */
12790 ith_elem_is_expansion |=
12791 argument_pack_element_is_expansion_p (arg_pack, index);
12793 /* Select the Ith argument from the pack. */
12794 if (TREE_CODE (parm) == PARM_DECL
12795 || VAR_P (parm)
12796 || TREE_CODE (parm) == FIELD_DECL)
12798 if (index == 0)
12800 aps = make_argument_pack_select (arg_pack, index);
12801 if (!mark_used (parm, complain) && !(complain & tf_error))
12802 return error_mark_node;
12803 register_local_specialization (aps, parm);
12805 else
12806 aps = retrieve_local_specialization (parm);
12808 else
12810 int idx, level;
12811 template_parm_level_and_index (parm, &level, &idx);
12813 if (index == 0)
12815 aps = make_argument_pack_select (arg_pack, index);
12816 /* Update the corresponding argument. */
12817 TMPL_ARG (args, level, idx) = aps;
12819 else
12820 /* Re-use the ARGUMENT_PACK_SELECT. */
12821 aps = TMPL_ARG (args, level, idx);
12823 ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12826 /* Substitute into the PATTERN with the (possibly altered)
12827 arguments. */
12828 if (pattern == in_decl)
12829 /* Expanding a fixed parameter pack from
12830 coerce_template_parameter_pack. */
12831 t = tsubst_decl (pattern, args, complain);
12832 else if (pattern == error_mark_node)
12833 t = error_mark_node;
12834 else if (!TYPE_P (pattern))
12835 t = tsubst_expr (pattern, args, complain, in_decl);
12836 else
12838 t = tsubst (pattern, args, complain, in_decl);
12839 if (is_auto (t) && !ith_elem_is_expansion)
12840 /* When expanding the fake auto... pack expansion from add_capture, we
12841 need to mark that the expansion is no longer a pack. */
12842 TEMPLATE_TYPE_PARAMETER_PACK (t) = false;
12845 /* If the Ith argument pack element is a pack expansion, then
12846 the Ith element resulting from the substituting is going to
12847 be a pack expansion as well. */
12848 if (ith_elem_is_expansion)
12849 t = make_pack_expansion (t, complain);
12851 return t;
12854 /* When the unexpanded parameter pack in a fold expression expands to an empty
12855 sequence, the value of the expression is as follows; the program is
12856 ill-formed if the operator is not listed in this table.
12858 && true
12859 || false
12860 , void() */
12862 tree
12863 expand_empty_fold (tree t, tsubst_flags_t complain)
12865 tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
12866 if (!FOLD_EXPR_MODIFY_P (t))
12867 switch (code)
12869 case TRUTH_ANDIF_EXPR:
12870 return boolean_true_node;
12871 case TRUTH_ORIF_EXPR:
12872 return boolean_false_node;
12873 case COMPOUND_EXPR:
12874 return void_node;
12875 default:
12876 break;
12879 if (complain & tf_error)
12880 error_at (location_of (t),
12881 "fold of empty expansion over %O", code);
12882 return error_mark_node;
12885 /* Given a fold-expression T and a current LEFT and RIGHT operand,
12886 form an expression that combines the two terms using the
12887 operator of T. */
12889 static tree
12890 fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
12892 tree_code code = FOLD_EXPR_OP (t);
12894 tree lookups = templated_operator_saved_lookups (t);
12896 // Handle compound assignment operators.
12897 if (FOLD_EXPR_MODIFY_P (t))
12898 return build_x_modify_expr (input_location, left, code, right,
12899 lookups, complain);
12901 warning_sentinel s(warn_parentheses);
12902 switch (code)
12904 case COMPOUND_EXPR:
12905 return build_x_compound_expr (input_location, left, right,
12906 lookups, complain);
12907 default:
12908 return build_x_binary_op (input_location, code,
12909 left, TREE_CODE (left),
12910 right, TREE_CODE (right),
12911 lookups, /*overload=*/NULL,
12912 complain);
12916 /* Substitute ARGS into the pack of a fold expression T. */
12918 static inline tree
12919 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12921 return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
12924 /* Substitute ARGS into the pack of a fold expression T. */
12926 static inline tree
12927 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12929 return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl);
12932 /* Expand a PACK of arguments into a grouped as left fold.
12933 Given a pack containing elements A0, A1, ..., An and an
12934 operator @, this builds the expression:
12936 ((A0 @ A1) @ A2) ... @ An
12938 Note that PACK must not be empty.
12940 The operator is defined by the original fold expression T. */
12942 static tree
12943 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
12945 tree left = TREE_VEC_ELT (pack, 0);
12946 for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
12948 tree right = TREE_VEC_ELT (pack, i);
12949 left = fold_expression (t, left, right, complain);
12951 return left;
12954 /* Substitute into a unary left fold expression. */
12956 static tree
12957 tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
12958 tree in_decl)
12960 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12961 if (pack == error_mark_node)
12962 return error_mark_node;
12963 if (PACK_EXPANSION_P (pack))
12965 tree r = copy_node (t);
12966 FOLD_EXPR_PACK (r) = pack;
12967 return r;
12969 if (TREE_VEC_LENGTH (pack) == 0)
12970 return expand_empty_fold (t, complain);
12971 else
12972 return expand_left_fold (t, pack, complain);
12975 /* Substitute into a binary left fold expression.
12977 Do ths by building a single (non-empty) vector of argumnts and
12978 building the expression from those elements. */
12980 static tree
12981 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
12982 tree in_decl)
12984 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12985 if (pack == error_mark_node)
12986 return error_mark_node;
12987 tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
12988 if (init == error_mark_node)
12989 return error_mark_node;
12991 if (PACK_EXPANSION_P (pack))
12993 tree r = copy_node (t);
12994 FOLD_EXPR_PACK (r) = pack;
12995 FOLD_EXPR_INIT (r) = init;
12996 return r;
12999 tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
13000 TREE_VEC_ELT (vec, 0) = init;
13001 for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
13002 TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
13004 return expand_left_fold (t, vec, complain);
13007 /* Expand a PACK of arguments into a grouped as right fold.
13008 Given a pack containing elementns A0, A1, ..., and an
13009 operator @, this builds the expression:
13011 A0@ ... (An-2 @ (An-1 @ An))
13013 Note that PACK must not be empty.
13015 The operator is defined by the original fold expression T. */
13017 tree
13018 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
13020 // Build the expression.
13021 int n = TREE_VEC_LENGTH (pack);
13022 tree right = TREE_VEC_ELT (pack, n - 1);
13023 for (--n; n != 0; --n)
13025 tree left = TREE_VEC_ELT (pack, n - 1);
13026 right = fold_expression (t, left, right, complain);
13028 return right;
13031 /* Substitute into a unary right fold expression. */
13033 static tree
13034 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
13035 tree in_decl)
13037 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13038 if (pack == error_mark_node)
13039 return error_mark_node;
13040 if (PACK_EXPANSION_P (pack))
13042 tree r = copy_node (t);
13043 FOLD_EXPR_PACK (r) = pack;
13044 return r;
13046 if (TREE_VEC_LENGTH (pack) == 0)
13047 return expand_empty_fold (t, complain);
13048 else
13049 return expand_right_fold (t, pack, complain);
13052 /* Substitute into a binary right fold expression.
13054 Do ths by building a single (non-empty) vector of arguments and
13055 building the expression from those elements. */
13057 static tree
13058 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
13059 tree in_decl)
13061 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13062 if (pack == error_mark_node)
13063 return error_mark_node;
13064 tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
13065 if (init == error_mark_node)
13066 return error_mark_node;
13068 if (PACK_EXPANSION_P (pack))
13070 tree r = copy_node (t);
13071 FOLD_EXPR_PACK (r) = pack;
13072 FOLD_EXPR_INIT (r) = init;
13073 return r;
13076 int n = TREE_VEC_LENGTH (pack);
13077 tree vec = make_tree_vec (n + 1);
13078 for (int i = 0; i < n; ++i)
13079 TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
13080 TREE_VEC_ELT (vec, n) = init;
13082 return expand_right_fold (t, vec, complain);
13085 /* Walk through the pattern of a pack expansion, adding everything in
13086 local_specializations to a list. */
13088 class el_data
13090 public:
13091 /* Set of variables declared within the pattern. */
13092 hash_set<tree> internal;
13093 /* Set of AST nodes that have been visited by the traversal. */
13094 hash_set<tree> visited;
13095 /* List of local_specializations used within the pattern. */
13096 tree extra;
13097 tsubst_flags_t complain;
13098 /* True iff we don't want to walk into unevaluated contexts. */
13099 bool skip_unevaluated_operands = false;
13100 /* The unevaluated contexts that we avoided walking. */
13101 auto_vec<tree> skipped_trees;
13103 el_data (tsubst_flags_t c)
13104 : extra (NULL_TREE), complain (c) {}
13106 static tree
13107 extract_locals_r (tree *tp, int *walk_subtrees, void *data_)
13109 el_data &data = *reinterpret_cast<el_data*>(data_);
13110 tree *extra = &data.extra;
13111 tsubst_flags_t complain = data.complain;
13113 if (data.skip_unevaluated_operands
13114 && unevaluated_p (TREE_CODE (*tp)))
13116 data.skipped_trees.safe_push (*tp);
13117 *walk_subtrees = 0;
13118 return NULL_TREE;
13121 if (TYPE_P (*tp) && typedef_variant_p (*tp))
13122 /* Remember local typedefs (85214). */
13123 tp = &TYPE_NAME (*tp);
13125 if (TREE_CODE (*tp) == DECL_EXPR)
13127 tree decl = DECL_EXPR_DECL (*tp);
13128 data.internal.add (decl);
13129 if (VAR_P (decl)
13130 && DECL_DECOMPOSITION_P (decl)
13131 && TREE_TYPE (decl) != error_mark_node)
13133 gcc_assert (DECL_NAME (decl) == NULL_TREE);
13134 for (tree decl2 = DECL_CHAIN (decl);
13135 decl2
13136 && VAR_P (decl2)
13137 && DECL_DECOMPOSITION_P (decl2)
13138 && DECL_NAME (decl2)
13139 && TREE_TYPE (decl2) != error_mark_node;
13140 decl2 = DECL_CHAIN (decl2))
13142 gcc_assert (DECL_DECOMP_BASE (decl2) == decl);
13143 data.internal.add (decl2);
13147 else if (TREE_CODE (*tp) == LAMBDA_EXPR)
13149 /* Since we defer implicit capture, look in the parms and body. */
13150 tree fn = lambda_function (*tp);
13151 cp_walk_tree (&TREE_TYPE (fn), &extract_locals_r, &data,
13152 &data.visited);
13153 cp_walk_tree (&DECL_SAVED_TREE (fn), &extract_locals_r, &data,
13154 &data.visited);
13156 else if (tree spec = retrieve_local_specialization (*tp))
13158 if (data.internal.contains (*tp))
13159 /* Don't mess with variables declared within the pattern. */
13160 return NULL_TREE;
13161 if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
13163 /* Maybe pull out the PARM_DECL for a partial instantiation. */
13164 tree args = ARGUMENT_PACK_ARGS (spec);
13165 if (TREE_VEC_LENGTH (args) == 1)
13167 tree elt = TREE_VEC_ELT (args, 0);
13168 if (PACK_EXPANSION_P (elt))
13169 elt = PACK_EXPANSION_PATTERN (elt);
13170 if (DECL_PACK_P (elt))
13171 spec = elt;
13173 if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
13175 /* Handle lambda capture here, since we aren't doing any
13176 substitution now, and so tsubst_copy won't call
13177 process_outer_var_ref. */
13178 tree args = ARGUMENT_PACK_ARGS (spec);
13179 int len = TREE_VEC_LENGTH (args);
13180 for (int i = 0; i < len; ++i)
13182 tree arg = TREE_VEC_ELT (args, i);
13183 tree carg = arg;
13184 if (outer_automatic_var_p (arg))
13185 carg = process_outer_var_ref (arg, complain);
13186 if (carg != arg)
13188 /* Make a new NONTYPE_ARGUMENT_PACK of the capture
13189 proxies. */
13190 if (i == 0)
13192 spec = copy_node (spec);
13193 args = copy_node (args);
13194 ARGUMENT_PACK_ARGS (spec) = args;
13195 register_local_specialization (spec, *tp);
13197 TREE_VEC_ELT (args, i) = carg;
13202 if (outer_automatic_var_p (spec))
13203 spec = process_outer_var_ref (spec, complain);
13204 *extra = tree_cons (*tp, spec, *extra);
13206 return NULL_TREE;
13208 static tree
13209 extract_local_specs (tree pattern, tsubst_flags_t complain)
13211 el_data data (complain);
13212 /* Walk the pattern twice, ignoring unevaluated operands the first time
13213 around, so that if a local specialization appears in both an evaluated
13214 and unevaluated context we prefer to process it in the evaluated context
13215 (since e.g. process_outer_var_ref is a no-op inside an unevaluated
13216 context). */
13217 data.skip_unevaluated_operands = true;
13218 cp_walk_tree (&pattern, extract_locals_r, &data, &data.visited);
13219 /* Now walk the unevaluated contexts we skipped the first time around. */
13220 data.skip_unevaluated_operands = false;
13221 for (tree t : data.skipped_trees)
13223 data.visited.remove (t);
13224 cp_walk_tree (&t, extract_locals_r, &data, &data.visited);
13226 return data.extra;
13229 /* Extract any uses of local_specializations from PATTERN and add them to ARGS
13230 for use in PACK_EXPANSION_EXTRA_ARGS. */
13232 tree
13233 build_extra_args (tree pattern, tree args, tsubst_flags_t complain)
13235 /* Make a copy of the extra arguments so that they won't get changed
13236 out from under us. */
13237 tree extra = preserve_args (copy_template_args (args), /*cow_p=*/false);
13238 if (local_specializations)
13239 if (tree locals = extract_local_specs (pattern, complain))
13240 extra = tree_cons (NULL_TREE, extra, locals);
13241 return extra;
13244 /* Apply any local specializations from PACK_EXPANSION_EXTRA_ARGS and add the
13245 normal template args to ARGS. */
13247 tree
13248 add_extra_args (tree extra, tree args, tsubst_flags_t complain, tree in_decl)
13250 if (extra && TREE_CODE (extra) == TREE_LIST)
13252 for (tree elt = TREE_CHAIN (extra); elt; elt = TREE_CHAIN (elt))
13254 /* The partial instantiation involved local declarations collected in
13255 extract_local_specs; map from the general template to our local
13256 context. */
13257 tree gen = TREE_PURPOSE (elt);
13258 tree inst = TREE_VALUE (elt);
13259 if (DECL_P (inst))
13260 if (tree local = retrieve_local_specialization (inst))
13261 inst = local;
13262 /* else inst is already a full instantiation of the pack. */
13263 register_local_specialization (inst, gen);
13265 gcc_assert (!TREE_PURPOSE (extra));
13266 extra = TREE_VALUE (extra);
13268 if (uses_template_parms (extra))
13270 /* This can happen after dependent substitution into a
13271 requires-expr or a lambda that uses constexpr if. */
13272 extra = tsubst_template_args (extra, args, complain, in_decl);
13273 args = add_outermost_template_args (args, extra);
13275 else
13276 args = add_to_template_args (extra, args);
13277 return args;
13280 /* Substitute ARGS into T, which is an pack expansion
13281 (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
13282 TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
13283 (if only a partial substitution could be performed) or
13284 ERROR_MARK_NODE if there was an error. */
13285 tree
13286 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
13287 tree in_decl)
13289 tree pattern;
13290 tree pack, packs = NULL_TREE;
13291 bool unsubstituted_packs = false;
13292 int i, len = -1;
13293 tree result;
13294 bool need_local_specializations = false;
13295 int levels;
13297 gcc_assert (PACK_EXPANSION_P (t));
13298 pattern = PACK_EXPANSION_PATTERN (t);
13300 /* Add in any args remembered from an earlier partial instantiation. */
13301 args = add_extra_args (PACK_EXPANSION_EXTRA_ARGS (t), args, complain, in_decl);
13303 levels = TMPL_ARGS_DEPTH (args);
13305 /* Determine the argument packs that will instantiate the parameter
13306 packs used in the expansion expression. While we're at it,
13307 compute the number of arguments to be expanded and make sure it
13308 is consistent. */
13309 for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
13310 pack = TREE_CHAIN (pack))
13312 tree parm_pack = TREE_VALUE (pack);
13313 tree arg_pack = NULL_TREE;
13314 tree orig_arg = NULL_TREE;
13315 int level = 0;
13317 if (TREE_CODE (parm_pack) == BASES)
13319 gcc_assert (parm_pack == pattern);
13320 if (BASES_DIRECT (parm_pack))
13321 return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
13322 args, complain,
13323 in_decl),
13324 complain);
13325 else
13326 return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
13327 args, complain, in_decl),
13328 complain);
13330 else if (builtin_pack_call_p (parm_pack))
13332 if (parm_pack != pattern)
13334 if (complain & tf_error)
13335 sorry ("%qE is not the entire pattern of the pack expansion",
13336 parm_pack);
13337 return error_mark_node;
13339 return expand_builtin_pack_call (parm_pack, args,
13340 complain, in_decl);
13342 else if (TREE_CODE (parm_pack) == PARM_DECL)
13344 /* We know we have correct local_specializations if this
13345 expansion is at function scope, or if we're dealing with a
13346 local parameter in a requires expression; for the latter,
13347 tsubst_requires_expr set it up appropriately. */
13348 if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
13349 arg_pack = retrieve_local_specialization (parm_pack);
13350 else
13351 /* We can't rely on local_specializations for a parameter
13352 name used later in a function declaration (such as in a
13353 late-specified return type). Even if it exists, it might
13354 have the wrong value for a recursive call. */
13355 need_local_specializations = true;
13357 if (!arg_pack)
13359 /* This parameter pack was used in an unevaluated context. Just
13360 make a dummy decl, since it's only used for its type. */
13361 ++cp_unevaluated_operand;
13362 arg_pack = tsubst_decl (parm_pack, args, complain);
13363 --cp_unevaluated_operand;
13364 if (arg_pack && DECL_PACK_P (arg_pack))
13365 /* Partial instantiation of the parm_pack, we can't build
13366 up an argument pack yet. */
13367 arg_pack = NULL_TREE;
13368 else
13369 arg_pack = make_fnparm_pack (arg_pack);
13371 else if (DECL_PACK_P (arg_pack))
13372 /* This argument pack isn't fully instantiated yet. */
13373 arg_pack = NULL_TREE;
13375 else if (is_capture_proxy (parm_pack))
13377 arg_pack = retrieve_local_specialization (parm_pack);
13378 if (DECL_PACK_P (arg_pack))
13379 arg_pack = NULL_TREE;
13381 else
13383 int idx;
13384 template_parm_level_and_index (parm_pack, &level, &idx);
13385 if (level <= levels)
13386 arg_pack = TMPL_ARG (args, level, idx);
13388 if (arg_pack && TREE_CODE (arg_pack) == TEMPLATE_TYPE_PARM
13389 && TEMPLATE_TYPE_PARAMETER_PACK (arg_pack))
13390 arg_pack = NULL_TREE;
13393 orig_arg = arg_pack;
13394 if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
13395 arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
13397 if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
13398 /* This can only happen if we forget to expand an argument
13399 pack somewhere else. Just return an error, silently. */
13401 result = make_tree_vec (1);
13402 TREE_VEC_ELT (result, 0) = error_mark_node;
13403 return result;
13406 if (arg_pack)
13408 int my_len =
13409 TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
13411 /* Don't bother trying to do a partial substitution with
13412 incomplete packs; we'll try again after deduction. */
13413 if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
13414 return t;
13416 if (len < 0)
13417 len = my_len;
13418 else if (len != my_len)
13420 if (!(complain & tf_error))
13421 /* Fail quietly. */;
13422 else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
13423 error ("mismatched argument pack lengths while expanding %qT",
13424 pattern);
13425 else
13426 error ("mismatched argument pack lengths while expanding %qE",
13427 pattern);
13428 return error_mark_node;
13431 /* Keep track of the parameter packs and their corresponding
13432 argument packs. */
13433 packs = tree_cons (parm_pack, arg_pack, packs);
13434 TREE_TYPE (packs) = orig_arg;
13436 else
13438 /* We can't substitute for this parameter pack. We use a flag as
13439 well as the missing_level counter because function parameter
13440 packs don't have a level. */
13441 gcc_assert (processing_template_decl || is_auto (parm_pack));
13442 unsubstituted_packs = true;
13446 /* If the expansion is just T..., return the matching argument pack, unless
13447 we need to call convert_from_reference on all the elements. This is an
13448 important optimization; see c++/68422. */
13449 if (!unsubstituted_packs
13450 && TREE_PURPOSE (packs) == pattern)
13452 tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
13454 /* If the argument pack is a single pack expansion, pull it out. */
13455 if (TREE_VEC_LENGTH (args) == 1
13456 && pack_expansion_args_count (args))
13457 return TREE_VEC_ELT (args, 0);
13459 /* Types need no adjustment, nor does sizeof..., and if we still have
13460 some pack expansion args we won't do anything yet. */
13461 if (TREE_CODE (t) == TYPE_PACK_EXPANSION
13462 || PACK_EXPANSION_SIZEOF_P (t)
13463 || pack_expansion_args_count (args))
13464 return args;
13465 /* Also optimize expression pack expansions if we can tell that the
13466 elements won't have reference type. */
13467 tree type = TREE_TYPE (pattern);
13468 if (type && !TYPE_REF_P (type)
13469 && !PACK_EXPANSION_P (type)
13470 && !WILDCARD_TYPE_P (type))
13471 return args;
13472 /* Otherwise use the normal path so we get convert_from_reference. */
13475 /* We cannot expand this expansion expression, because we don't have
13476 all of the argument packs we need. */
13477 if (use_pack_expansion_extra_args_p (t, packs, len, unsubstituted_packs))
13479 /* We got some full packs, but we can't substitute them in until we
13480 have values for all the packs. So remember these until then. */
13482 t = make_pack_expansion (pattern, complain);
13483 PACK_EXPANSION_EXTRA_ARGS (t)
13484 = build_extra_args (pattern, args, complain);
13485 return t;
13488 /* If NEED_LOCAL_SPECIALIZATIONS then we're in a late-specified return
13489 type, so create our own local specializations map; the current map is
13490 either NULL or (in the case of recursive unification) might have
13491 bindings that we don't want to use or alter. */
13492 local_specialization_stack lss (need_local_specializations
13493 ? lss_blank : lss_nop);
13495 if (unsubstituted_packs)
13497 /* There were no real arguments, we're just replacing a parameter
13498 pack with another version of itself. Substitute into the
13499 pattern and return a PACK_EXPANSION_*. The caller will need to
13500 deal with that. */
13501 if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
13502 result = tsubst_expr (pattern, args, complain, in_decl);
13503 else
13504 result = tsubst (pattern, args, complain, in_decl);
13505 result = make_pack_expansion (result, complain);
13506 PACK_EXPANSION_LOCAL_P (result) = PACK_EXPANSION_LOCAL_P (t);
13507 PACK_EXPANSION_SIZEOF_P (result) = PACK_EXPANSION_SIZEOF_P (t);
13508 if (PACK_EXPANSION_AUTO_P (t))
13510 /* This is a fake auto... pack expansion created in add_capture with
13511 _PACKS that don't appear in the pattern. Copy one over. */
13512 packs = PACK_EXPANSION_PARAMETER_PACKS (t);
13513 pack = retrieve_local_specialization (TREE_VALUE (packs));
13514 gcc_checking_assert (DECL_PACK_P (pack));
13515 PACK_EXPANSION_PARAMETER_PACKS (result)
13516 = build_tree_list (NULL_TREE, pack);
13517 PACK_EXPANSION_AUTO_P (result) = true;
13519 return result;
13522 gcc_assert (len >= 0);
13524 /* For each argument in each argument pack, substitute into the
13525 pattern. */
13526 result = make_tree_vec (len);
13527 tree elem_args = copy_template_args (args);
13528 for (i = 0; i < len; ++i)
13530 t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
13532 elem_args, complain,
13533 in_decl);
13534 TREE_VEC_ELT (result, i) = t;
13535 if (t == error_mark_node)
13537 result = error_mark_node;
13538 break;
13542 /* Update ARGS to restore the substitution from parameter packs to
13543 their argument packs. */
13544 for (pack = packs; pack; pack = TREE_CHAIN (pack))
13546 tree parm = TREE_PURPOSE (pack);
13548 if (TREE_CODE (parm) == PARM_DECL
13549 || VAR_P (parm)
13550 || TREE_CODE (parm) == FIELD_DECL)
13551 register_local_specialization (TREE_TYPE (pack), parm);
13552 else
13554 int idx, level;
13556 if (TREE_VALUE (pack) == NULL_TREE)
13557 continue;
13559 template_parm_level_and_index (parm, &level, &idx);
13561 /* Update the corresponding argument. */
13562 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
13563 TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
13564 TREE_TYPE (pack);
13565 else
13566 TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
13570 /* If the dependent pack arguments were such that we end up with only a
13571 single pack expansion again, there's no need to keep it in a TREE_VEC. */
13572 if (len == 1 && TREE_CODE (result) == TREE_VEC
13573 && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
13574 return TREE_VEC_ELT (result, 0);
13576 return result;
13579 /* Make an argument pack out of the TREE_VEC VEC. */
13581 static tree
13582 make_argument_pack (tree vec)
13584 tree pack;
13586 if (TYPE_P (TREE_VEC_ELT (vec, 0)))
13587 pack = cxx_make_type (TYPE_ARGUMENT_PACK);
13588 else
13590 pack = make_node (NONTYPE_ARGUMENT_PACK);
13591 TREE_CONSTANT (pack) = 1;
13593 ARGUMENT_PACK_ARGS (pack) = vec;
13594 return pack;
13597 /* Return an exact copy of template args T that can be modified
13598 independently. */
13600 static tree
13601 copy_template_args (tree t)
13603 if (t == error_mark_node)
13604 return t;
13606 int len = TREE_VEC_LENGTH (t);
13607 tree new_vec = make_tree_vec (len);
13609 for (int i = 0; i < len; ++i)
13611 tree elt = TREE_VEC_ELT (t, i);
13612 if (elt && TREE_CODE (elt) == TREE_VEC)
13613 elt = copy_template_args (elt);
13614 TREE_VEC_ELT (new_vec, i) = elt;
13617 NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
13618 = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13620 return new_vec;
13623 /* Substitute ARGS into the *_ARGUMENT_PACK orig_arg. */
13625 tree
13626 tsubst_argument_pack (tree orig_arg, tree args, tsubst_flags_t complain,
13627 tree in_decl)
13629 /* This flag is used only during deduction, and we don't expect to
13630 substitute such ARGUMENT_PACKs. */
13631 gcc_assert (!ARGUMENT_PACK_INCOMPLETE_P (orig_arg));
13633 /* Substitute into each of the arguments. */
13634 tree pack_args = tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
13635 args, complain, in_decl);
13636 if (pack_args == error_mark_node)
13637 return error_mark_node;
13639 if (pack_args == ARGUMENT_PACK_ARGS (orig_arg))
13640 return orig_arg;
13642 /* If we're substituting into a generic ARGUMENT_PACK for a variadic
13643 template parameter, we might be able to avoid allocating a new
13644 ARGUMENT_PACK and reuse the corresponding ARGUMENT_PACK from ARGS
13645 if the substituted result is identical to it. */
13646 if (tree parm = template_arg_to_parm (orig_arg))
13648 int level, index;
13649 template_parm_level_and_index (parm, &level, &index);
13650 if (TMPL_ARGS_DEPTH (args) >= level)
13651 if (tree arg = TMPL_ARG (args, level, index))
13652 if (TREE_CODE (arg) == TREE_CODE (orig_arg)
13653 && ARGUMENT_PACK_ARGS (arg) == pack_args)
13655 gcc_assert (!ARGUMENT_PACK_INCOMPLETE_P (arg));
13656 return arg;
13660 tree new_arg;
13661 if (TYPE_P (orig_arg))
13663 new_arg = cxx_make_type (TREE_CODE (orig_arg));
13664 SET_TYPE_STRUCTURAL_EQUALITY (new_arg);
13666 else
13668 new_arg = make_node (TREE_CODE (orig_arg));
13669 TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
13671 ARGUMENT_PACK_ARGS (new_arg) = pack_args;
13672 return new_arg;
13675 /* Substitute ARGS into the vector or list of template arguments T. */
13677 tree
13678 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
13680 if (t == error_mark_node)
13681 return error_mark_node;
13683 /* In "sizeof(X<I>)" we need to evaluate "I". */
13684 cp_evaluated ev;
13686 const int len = TREE_VEC_LENGTH (t);
13687 tree *elts = XALLOCAVEC (tree, len);
13688 int expanded_len_adjust = 0;
13690 /* True iff the substituted result is identical to T. */
13691 bool const_subst_p = true;
13693 for (int i = 0; i < len; i++)
13695 tree orig_arg = TREE_VEC_ELT (t, i);
13696 tree new_arg;
13698 if (!orig_arg)
13699 new_arg = NULL_TREE;
13700 else if (TREE_CODE (orig_arg) == TREE_VEC)
13701 new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
13702 else if (PACK_EXPANSION_P (orig_arg))
13704 /* Substitute into an expansion expression. */
13705 new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
13707 if (TREE_CODE (new_arg) == TREE_VEC)
13708 /* Add to the expanded length adjustment the number of
13709 expanded arguments. We subtract one from this
13710 measurement, because the argument pack expression
13711 itself is already counted as 1 in
13712 LEN. EXPANDED_LEN_ADJUST can actually be negative, if
13713 the argument pack is empty. */
13714 expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
13716 else if (ARGUMENT_PACK_P (orig_arg))
13717 new_arg = tsubst_argument_pack (orig_arg, args, complain, in_decl);
13718 else
13719 new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
13721 if (new_arg == error_mark_node)
13722 return error_mark_node;
13724 elts[i] = new_arg;
13725 if (new_arg != orig_arg)
13726 const_subst_p = false;
13729 if (const_subst_p)
13730 return t;
13732 tree maybe_reuse = NULL_TREE;
13734 /* If ARGS and T are both multi-level, the substituted result may be
13735 identical to ARGS. */
13736 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (t)
13737 && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args)
13738 && TMPL_ARGS_DEPTH (t) == TMPL_ARGS_DEPTH (args))
13739 maybe_reuse = args;
13740 /* If T appears to be a vector of generic template arguments, the
13741 substituted result may be identical to the corresponding level
13742 from ARGS. */
13743 else if (tree parm = template_arg_to_parm (TREE_VEC_ELT (t, 0)))
13745 int level, index;
13746 template_parm_level_and_index (parm, &level, &index);
13747 if (index == 0 && TMPL_ARGS_DEPTH (args) >= level)
13748 maybe_reuse = TMPL_ARGS_LEVEL (args, level);
13751 /* If the substituted result is identical to MAYBE_REUSE, return
13752 it and avoid allocating a new TREE_VEC, as an optimization. */
13753 if (maybe_reuse != NULL_TREE
13754 && TREE_VEC_LENGTH (maybe_reuse) == len
13755 && std::equal (elts, elts+len, TREE_VEC_BEGIN (maybe_reuse)))
13756 return maybe_reuse;
13758 /* If T consists of only a pack expansion for which substitution yielded
13759 a TREE_VEC of the expanded elements, then reuse that TREE_VEC instead
13760 of effectively making a copy. */
13761 if (len == 1
13762 && PACK_EXPANSION_P (TREE_VEC_ELT (t, 0))
13763 && TREE_CODE (elts[0]) == TREE_VEC)
13764 return elts[0];
13766 /* Make space for the expanded arguments coming from template
13767 argument packs. */
13768 tree r = make_tree_vec (len + expanded_len_adjust);
13769 /* T can contain TREE_VECs. That happens if T contains the
13770 arguments for a member template.
13771 In that case each TREE_VEC in T represents a level of template
13772 arguments, and T won't carry any non defaulted argument count.
13773 It will rather be the nested TREE_VECs that will carry one.
13774 In other words, T carries a non defaulted argument count only
13775 if it doesn't contain any nested TREE_VEC. */
13776 if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (t))
13778 int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13779 count += expanded_len_adjust;
13780 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (r, count);
13783 int out = 0;
13784 for (int i = 0; i < len; i++)
13786 tree orig_arg = TREE_VEC_ELT (t, i);
13787 if (orig_arg
13788 && PACK_EXPANSION_P (orig_arg)
13789 && TREE_CODE (elts[i]) == TREE_VEC)
13791 /* Now expand the template argument pack "in place". */
13792 for (int idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
13793 TREE_VEC_ELT (r, out) = TREE_VEC_ELT (elts[i], idx);
13795 else
13797 TREE_VEC_ELT (r, out) = elts[i];
13798 out++;
13801 gcc_assert (out == TREE_VEC_LENGTH (r));
13803 return r;
13806 /* Substitute ARGS into one level PARMS of template parameters. */
13808 static tree
13809 tsubst_template_parms_level (tree parms, tree args, tsubst_flags_t complain)
13811 if (parms == error_mark_node)
13812 return error_mark_node;
13814 tree new_vec = make_tree_vec (TREE_VEC_LENGTH (parms));
13816 for (int i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
13818 tree tuple = TREE_VEC_ELT (parms, i);
13820 if (tuple == error_mark_node)
13821 continue;
13823 TREE_VEC_ELT (new_vec, i) =
13824 tsubst_template_parm (tuple, args, complain);
13827 return new_vec;
13830 /* Return the result of substituting ARGS into the template parameters
13831 given by PARMS. If there are m levels of ARGS and m + n levels of
13832 PARMS, then the result will contain n levels of PARMS. For
13833 example, if PARMS is `template <class T> template <class U>
13834 template <T*, U, class V>' and ARGS is {{int}, {double}} then the
13835 result will be `template <int*, double, class V>'. */
13837 static tree
13838 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
13840 tree r = NULL_TREE;
13841 tree* new_parms;
13843 /* When substituting into a template, we must set
13844 PROCESSING_TEMPLATE_DECL as the template parameters may be
13845 dependent if they are based on one-another, and the dependency
13846 predicates are short-circuit outside of templates. */
13847 ++processing_template_decl;
13849 for (new_parms = &r;
13850 parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
13851 new_parms = &(TREE_CHAIN (*new_parms)),
13852 parms = TREE_CHAIN (parms))
13854 tree new_vec = tsubst_template_parms_level (TREE_VALUE (parms),
13855 args, complain);
13856 *new_parms =
13857 tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
13858 - TMPL_ARGS_DEPTH (args)),
13859 new_vec, NULL_TREE);
13860 TEMPLATE_PARMS_CONSTRAINTS (*new_parms)
13861 = TEMPLATE_PARMS_CONSTRAINTS (parms);
13864 --processing_template_decl;
13866 return r;
13869 /* Return the result of substituting ARGS into one template parameter
13870 given by T. T Must be a TREE_LIST which TREE_VALUE is the template
13871 parameter and which TREE_PURPOSE is the default argument of the
13872 template parameter. */
13874 static tree
13875 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
13877 tree default_value, parm_decl;
13879 if (args == NULL_TREE
13880 || t == NULL_TREE
13881 || t == error_mark_node)
13882 return t;
13884 gcc_assert (TREE_CODE (t) == TREE_LIST);
13886 default_value = TREE_PURPOSE (t);
13887 parm_decl = TREE_VALUE (t);
13889 parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
13890 if (TREE_CODE (parm_decl) == PARM_DECL
13891 && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
13892 parm_decl = error_mark_node;
13893 default_value = tsubst_template_arg (default_value, args,
13894 complain, NULL_TREE);
13896 tree r = build_tree_list (default_value, parm_decl);
13897 TEMPLATE_PARM_CONSTRAINTS (r) = TEMPLATE_PARM_CONSTRAINTS (t);
13898 return r;
13901 /* Substitute in-place the TEMPLATE_PARM_CONSTRAINTS of each template
13902 parameter in PARMS for sake of declaration matching. */
13904 static void
13905 tsubst_each_template_parm_constraints (tree parms, tree args,
13906 tsubst_flags_t complain)
13908 ++processing_template_decl;
13909 for (; parms; parms = TREE_CHAIN (parms))
13911 tree level = TREE_VALUE (parms);
13912 for (tree parm : tree_vec_range (level))
13913 TEMPLATE_PARM_CONSTRAINTS (parm)
13914 = tsubst_constraint (TEMPLATE_PARM_CONSTRAINTS (parm), args,
13915 complain, NULL_TREE);
13917 --processing_template_decl;
13920 /* Substitute the ARGS into the indicated aggregate (or enumeration)
13921 type T. If T is not an aggregate or enumeration type, it is
13922 handled as if by tsubst. IN_DECL is as for tsubst. If
13923 ENTERING_SCOPE is nonzero, T is the context for a template which
13924 we are presently tsubst'ing. Return the substituted value. */
13926 static tree
13927 tsubst_aggr_type (tree t,
13928 tree args,
13929 tsubst_flags_t complain,
13930 tree in_decl,
13931 int entering_scope)
13933 if (t == NULL_TREE)
13934 return NULL_TREE;
13936 /* Handle typedefs via tsubst so that they get consistently reused. */
13937 if (typedef_variant_p (t))
13939 t = tsubst (t, args, complain, in_decl);
13940 if (t == error_mark_node)
13941 return error_mark_node;
13943 /* The effect of entering_scope is that for a dependent specialization
13944 A<T>, lookup_template_class prefers to return A's primary template
13945 type instead of the implicit instantiation. So when entering_scope,
13946 we mirror this behavior by inspecting TYPE_CANONICAL appropriately,
13947 taking advantage of the fact that lookup_template_class links the two
13948 types by setting TYPE_CANONICAL of the latter to the former. */
13949 if (entering_scope
13950 && CLASS_TYPE_P (t)
13951 && dependent_type_p (t)
13952 && TYPE_CANONICAL (t) == TREE_TYPE (TYPE_TI_TEMPLATE (t)))
13953 t = TYPE_CANONICAL (t);
13955 return t;
13958 switch (TREE_CODE (t))
13960 case RECORD_TYPE:
13961 case ENUMERAL_TYPE:
13962 case UNION_TYPE:
13963 return tsubst_aggr_type_1 (t, args, complain, in_decl, entering_scope);
13965 default:
13966 return tsubst (t, args, complain, in_decl);
13970 /* The part of tsubst_aggr_type that's shared with the RECORD_, UNION_
13971 and ENUMERAL_TYPE cases of tsubst. */
13973 static tree
13974 tsubst_aggr_type_1 (tree t,
13975 tree args,
13976 tsubst_flags_t complain,
13977 tree in_decl,
13978 int entering_scope)
13980 if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
13982 complain &= ~tf_qualifying_scope;
13984 /* Figure out what arguments are appropriate for the
13985 type we are trying to find. For example, given:
13987 template <class T> struct S;
13988 template <class T, class U> void f(T, U) { S<U> su; }
13990 and supposing that we are instantiating f<int, double>,
13991 then our ARGS will be {int, double}, but, when looking up
13992 S we only want {double}. */
13993 tree argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
13994 complain, in_decl);
13995 if (argvec == error_mark_node)
13996 return error_mark_node;
13998 tree r = lookup_template_class (t, argvec, in_decl, NULL_TREE,
13999 entering_scope, complain);
14000 return cp_build_qualified_type (r, cp_type_quals (t), complain);
14002 else
14003 /* This is not a template type, so there's nothing to do. */
14004 return t;
14007 /* Map from a FUNCTION_DECL to a vec of default argument instantiations,
14008 indexed in reverse order of the parameters. */
14010 static GTY((cache)) hash_table<tree_vec_map_cache_hasher> *defarg_inst;
14012 /* Return a reference to the vec* of defarg insts for FN. */
14014 static vec<tree,va_gc> *&
14015 defarg_insts_for (tree fn)
14017 if (!defarg_inst)
14018 defarg_inst = hash_table<tree_vec_map_cache_hasher>::create_ggc (13);
14019 tree_vec_map in = { { fn }, nullptr };
14020 tree_vec_map **slot
14021 = defarg_inst->find_slot_with_hash (&in, DECL_UID (fn), INSERT);
14022 if (!*slot)
14024 *slot = ggc_alloc<tree_vec_map> ();
14025 **slot = in;
14027 return (*slot)->to;
14030 /* Substitute into the default argument ARG (a default argument for
14031 FN), which has the indicated TYPE. */
14033 tree
14034 tsubst_default_argument (tree fn, int parmnum, tree type, tree arg,
14035 tsubst_flags_t complain)
14037 int errs = errorcount + sorrycount;
14039 /* This can happen in invalid code. */
14040 if (TREE_CODE (arg) == DEFERRED_PARSE)
14041 return arg;
14043 /* Shortcut {}. */
14044 if (BRACE_ENCLOSED_INITIALIZER_P (arg)
14045 && CONSTRUCTOR_NELTS (arg) == 0)
14046 return arg;
14048 tree parm = FUNCTION_FIRST_USER_PARM (fn);
14049 parm = chain_index (parmnum, parm);
14050 tree parmtype = TREE_TYPE (parm);
14051 if (DECL_BY_REFERENCE (parm))
14052 parmtype = TREE_TYPE (parmtype);
14053 if (parmtype == error_mark_node)
14054 return error_mark_node;
14056 gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, parmtype));
14058 /* Remember the location of the pointer to the vec rather than the location
14059 of the particular element, in case the vec grows in tsubst_expr. */
14060 vec<tree,va_gc> *&defs = defarg_insts_for (fn);
14061 /* Index in reverse order to avoid allocating space for initial parameters
14062 that don't have default arguments. */
14063 unsigned ridx = list_length (parm);
14064 if (vec_safe_length (defs) < ridx)
14065 vec_safe_grow_cleared (defs, ridx);
14066 else if (tree inst = (*defs)[ridx - 1])
14067 return inst;
14069 /* This default argument came from a template. Instantiate the
14070 default argument here, not in tsubst. In the case of
14071 something like:
14073 template <class T>
14074 struct S {
14075 static T t();
14076 void f(T = t());
14079 we must be careful to do name lookup in the scope of S<T>,
14080 rather than in the current class. */
14081 push_to_top_level ();
14082 push_access_scope (fn);
14083 push_deferring_access_checks (dk_no_deferred);
14084 /* So in_immediate_context knows this is a default argument. */
14085 begin_scope (sk_function_parms, fn);
14086 start_lambda_scope (parm);
14088 /* The default argument expression may cause implicitly defined
14089 member functions to be synthesized, which will result in garbage
14090 collection. We must treat this situation as if we were within
14091 the body of function so as to avoid collecting live data on the
14092 stack. */
14093 ++function_depth;
14094 arg = tsubst_expr (arg, DECL_TI_ARGS (fn), complain, NULL_TREE);
14095 --function_depth;
14097 finish_lambda_scope ();
14099 /* Make sure the default argument is reasonable. */
14100 arg = check_default_argument (type, arg, complain);
14102 if (errorcount+sorrycount > errs
14103 && (complain & tf_warning_or_error))
14104 inform (input_location,
14105 " when instantiating default argument for call to %qD", fn);
14107 leave_scope ();
14108 pop_deferring_access_checks ();
14109 pop_access_scope (fn);
14110 pop_from_top_level ();
14112 if (arg != error_mark_node && !cp_unevaluated_operand)
14113 (*defs)[ridx - 1] = arg;
14115 return arg;
14118 /* Substitute into all the default arguments for FN. */
14120 static void
14121 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
14123 tree arg;
14124 tree tmpl_args;
14126 tmpl_args = DECL_TI_ARGS (fn);
14128 /* If this function is not yet instantiated, we certainly don't need
14129 its default arguments. */
14130 if (uses_template_parms (tmpl_args))
14131 return;
14132 /* Don't do this again for clones. */
14133 if (DECL_CLONED_FUNCTION_P (fn))
14134 return;
14136 int i = 0;
14137 for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
14138 arg;
14139 arg = TREE_CHAIN (arg), ++i)
14140 if (TREE_PURPOSE (arg))
14141 TREE_PURPOSE (arg) = tsubst_default_argument (fn, i,
14142 TREE_VALUE (arg),
14143 TREE_PURPOSE (arg),
14144 complain);
14147 /* Hash table mapping a FUNCTION_DECL to its dependent explicit-specifier. */
14148 static GTY((cache)) decl_tree_cache_map *explicit_specifier_map;
14150 /* Store a pair to EXPLICIT_SPECIFIER_MAP. */
14152 void
14153 store_explicit_specifier (tree v, tree t)
14155 if (!explicit_specifier_map)
14156 explicit_specifier_map = decl_tree_cache_map::create_ggc (37);
14157 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (v) = true;
14158 explicit_specifier_map->put (v, t);
14161 /* Lookup an element in EXPLICIT_SPECIFIER_MAP. */
14163 tree
14164 lookup_explicit_specifier (tree v)
14166 return *explicit_specifier_map->get (v);
14169 /* Given T, a FUNCTION_TYPE or METHOD_TYPE, construct and return a corresponding
14170 FUNCTION_TYPE or METHOD_TYPE whose return type is RETURN_TYPE, argument types
14171 are ARG_TYPES, and exception specification is RAISES, and otherwise is
14172 identical to T. */
14174 static tree
14175 rebuild_function_or_method_type (tree t, tree return_type, tree arg_types,
14176 tree raises, tsubst_flags_t complain)
14178 gcc_assert (FUNC_OR_METHOD_TYPE_P (t));
14180 tree new_type;
14181 if (TREE_CODE (t) == FUNCTION_TYPE)
14183 new_type = build_function_type (return_type, arg_types);
14184 new_type = apply_memfn_quals (new_type, type_memfn_quals (t));
14186 else
14188 tree r = TREE_TYPE (TREE_VALUE (arg_types));
14189 /* Don't pick up extra function qualifiers from the basetype. */
14190 r = cp_build_qualified_type (r, type_memfn_quals (t), complain);
14191 if (! MAYBE_CLASS_TYPE_P (r))
14193 /* [temp.deduct]
14195 Type deduction may fail for any of the following
14196 reasons:
14198 -- Attempting to create "pointer to member of T" when T
14199 is not a class type. */
14200 if (complain & tf_error)
14201 error ("creating pointer to member function of non-class type %qT",
14203 return error_mark_node;
14206 new_type = build_method_type_directly (r, return_type,
14207 TREE_CHAIN (arg_types));
14209 new_type = cp_build_type_attribute_variant (new_type, TYPE_ATTRIBUTES (t));
14211 cp_ref_qualifier rqual = type_memfn_rqual (t);
14212 bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
14213 return build_cp_fntype_variant (new_type, rqual, raises, late_return_type_p);
14216 /* Check if the function type of DECL, a FUNCTION_DECL, agrees with the type of
14217 each of its formal parameters. If there is a disagreement then rebuild
14218 DECL's function type according to its formal parameter types, as part of a
14219 resolution for Core issues 1001/1322. */
14221 static void
14222 maybe_rebuild_function_decl_type (tree decl)
14224 bool function_type_needs_rebuilding = false;
14225 if (tree parm_list = FUNCTION_FIRST_USER_PARM (decl))
14227 tree parm_type_list = FUNCTION_FIRST_USER_PARMTYPE (decl);
14228 while (parm_type_list && parm_type_list != void_list_node)
14230 tree parm_type = TREE_VALUE (parm_type_list);
14231 tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
14232 if (!same_type_p (parm_type, formal_parm_type_unqual))
14234 function_type_needs_rebuilding = true;
14235 break;
14238 parm_list = DECL_CHAIN (parm_list);
14239 parm_type_list = TREE_CHAIN (parm_type_list);
14243 if (!function_type_needs_rebuilding)
14244 return;
14246 const tree fntype = TREE_TYPE (decl);
14247 tree parm_list = DECL_ARGUMENTS (decl);
14248 tree old_parm_type_list = TYPE_ARG_TYPES (fntype);
14249 tree new_parm_type_list = NULL_TREE;
14250 tree *q = &new_parm_type_list;
14251 for (int skip = num_artificial_parms_for (decl); skip > 0; skip--)
14253 *q = copy_node (old_parm_type_list);
14254 parm_list = DECL_CHAIN (parm_list);
14255 old_parm_type_list = TREE_CHAIN (old_parm_type_list);
14256 q = &TREE_CHAIN (*q);
14258 while (old_parm_type_list && old_parm_type_list != void_list_node)
14260 *q = copy_node (old_parm_type_list);
14261 tree *new_parm_type = &TREE_VALUE (*q);
14262 tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
14263 if (!same_type_p (*new_parm_type, formal_parm_type_unqual))
14264 *new_parm_type = formal_parm_type_unqual;
14266 parm_list = DECL_CHAIN (parm_list);
14267 old_parm_type_list = TREE_CHAIN (old_parm_type_list);
14268 q = &TREE_CHAIN (*q);
14270 if (old_parm_type_list == void_list_node)
14271 *q = void_list_node;
14273 TREE_TYPE (decl)
14274 = rebuild_function_or_method_type (fntype,
14275 TREE_TYPE (fntype), new_parm_type_list,
14276 TYPE_RAISES_EXCEPTIONS (fntype), tf_none);
14279 /* Subroutine of tsubst_decl for the case when T is a FUNCTION_DECL. */
14281 static tree
14282 tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
14283 tree lambda_fntype)
14285 tree gen_tmpl = NULL_TREE, argvec = NULL_TREE;
14286 hashval_t hash = 0;
14287 tree in_decl = t;
14289 /* Nobody should be tsubst'ing into non-template functions. */
14290 gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE
14291 || DECL_LOCAL_DECL_P (t));
14293 if (DECL_LOCAL_DECL_P (t))
14295 if (tree spec = retrieve_local_specialization (t))
14296 return spec;
14298 else if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
14300 /* If T is not dependent, just return it. */
14301 if (!uses_template_parms (DECL_TI_ARGS (t))
14302 && !LAMBDA_FUNCTION_P (t))
14303 return t;
14305 /* A non-templated friend doesn't get DECL_TEMPLATE_INFO. */
14306 if (non_templated_friend_p (t))
14307 goto friend_case;
14309 /* Calculate the most general template of which R is a
14310 specialization. */
14311 gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
14313 /* We're substituting a lambda function under tsubst_lambda_expr but not
14314 directly from it; find the matching function we're already inside.
14315 But don't do this if T is a generic lambda with a single level of
14316 template parms, as in that case we're doing a normal instantiation. */
14317 if (LAMBDA_FUNCTION_P (t) && !lambda_fntype
14318 && (!generic_lambda_fn_p (t)
14319 || TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)) > 1))
14320 return enclosing_instantiation_of (t);
14322 /* Calculate the complete set of arguments used to
14323 specialize R. */
14324 argvec = tsubst_template_args (DECL_TI_ARGS
14325 (DECL_TEMPLATE_RESULT
14326 (DECL_TI_TEMPLATE (t))),
14327 args, complain, in_decl);
14328 if (argvec == error_mark_node)
14329 return error_mark_node;
14331 /* Check to see if we already have this specialization. */
14332 if (!lambda_fntype)
14334 hash = spec_hasher::hash (gen_tmpl, argvec);
14335 if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
14336 /* The spec for these args might be a partial instantiation of the
14337 template, but here what we want is the FUNCTION_DECL. */
14338 return STRIP_TEMPLATE (spec);
14341 else
14343 /* This special case arises when we have something like this:
14345 template <class T> struct S {
14346 friend void f<int>(int, double);
14349 Here, the DECL_TI_TEMPLATE for the friend declaration
14350 will be an IDENTIFIER_NODE. We are being called from
14351 tsubst_friend_function, and we want only to create a
14352 new decl (R) with appropriate types so that we can call
14353 determine_specialization. */
14354 friend_case:
14355 gen_tmpl = NULL_TREE;
14356 argvec = NULL_TREE;
14359 tree closure = (lambda_fntype ? TYPE_METHOD_BASETYPE (lambda_fntype)
14360 : NULL_TREE);
14361 tree ctx = closure ? closure : DECL_CONTEXT (t);
14362 bool member = ctx && TYPE_P (ctx);
14364 /* If this is a static lambda, remove the 'this' pointer added in
14365 tsubst_lambda_expr now that we know the closure type. */
14366 if (lambda_fntype && DECL_STATIC_FUNCTION_P (t))
14367 lambda_fntype = static_fn_type (lambda_fntype);
14369 if (member && !closure)
14370 ctx = tsubst_aggr_type (ctx, args,
14371 complain, t, /*entering_scope=*/1);
14373 tree type = (lambda_fntype ? lambda_fntype
14374 : tsubst (TREE_TYPE (t), args,
14375 complain | tf_fndecl_type, in_decl));
14376 if (type == error_mark_node)
14377 return error_mark_node;
14379 /* If we hit excessive deduction depth, the type is bogus even if
14380 it isn't error_mark_node, so don't build a decl. */
14381 if (excessive_deduction_depth)
14382 return error_mark_node;
14384 /* We do NOT check for matching decls pushed separately at this
14385 point, as they may not represent instantiations of this
14386 template, and in any case are considered separate under the
14387 discrete model. */
14388 tree r = copy_decl (t);
14389 DECL_USE_TEMPLATE (r) = 0;
14390 TREE_TYPE (r) = type;
14391 /* Clear out the mangled name and RTL for the instantiation. */
14392 SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
14393 SET_DECL_RTL (r, NULL);
14394 /* Leave DECL_INITIAL set on deleted instantiations. */
14395 if (!DECL_DELETED_FN (r))
14396 DECL_INITIAL (r) = NULL_TREE;
14397 DECL_CONTEXT (r) = ctx;
14398 set_instantiating_module (r);
14400 /* Handle explicit(dependent-expr). */
14401 if (DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (t))
14403 tree spec = lookup_explicit_specifier (t);
14404 spec = tsubst_copy_and_build (spec, args, complain, in_decl);
14405 spec = build_explicit_specifier (spec, complain);
14406 if (spec == error_mark_node)
14407 return error_mark_node;
14408 if (instantiation_dependent_expression_p (spec))
14409 store_explicit_specifier (r, spec);
14410 else
14412 DECL_NONCONVERTING_P (r) = (spec == boolean_true_node);
14413 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (r) = false;
14417 /* OpenMP UDRs have the only argument a reference to the declared
14418 type. We want to diagnose if the declared type is a reference,
14419 which is invalid, but as references to references are usually
14420 quietly merged, diagnose it here. */
14421 if (DECL_OMP_DECLARE_REDUCTION_P (t))
14423 tree argtype
14424 = TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
14425 argtype = tsubst (argtype, args, complain, in_decl);
14426 if (TYPE_REF_P (argtype))
14427 error_at (DECL_SOURCE_LOCATION (t),
14428 "reference type %qT in "
14429 "%<#pragma omp declare reduction%>", argtype);
14430 if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
14431 DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
14432 argtype);
14435 if (member && DECL_CONV_FN_P (r))
14436 /* Type-conversion operator. Reconstruct the name, in
14437 case it's the name of one of the template's parameters. */
14438 DECL_NAME (r) = make_conv_op_name (TREE_TYPE (type));
14440 tree parms = DECL_ARGUMENTS (t);
14441 if (closure && !DECL_STATIC_FUNCTION_P (t))
14442 parms = DECL_CHAIN (parms);
14443 parms = tsubst (parms, args, complain, t);
14444 for (tree parm = parms; parm; parm = DECL_CHAIN (parm))
14445 DECL_CONTEXT (parm) = r;
14446 if (closure && !DECL_STATIC_FUNCTION_P (t))
14448 tree tparm = build_this_parm (r, closure, type_memfn_quals (type));
14449 DECL_NAME (tparm) = closure_identifier;
14450 DECL_CHAIN (tparm) = parms;
14451 parms = tparm;
14453 DECL_ARGUMENTS (r) = parms;
14454 DECL_RESULT (r) = NULL_TREE;
14456 maybe_rebuild_function_decl_type (r);
14458 TREE_STATIC (r) = 0;
14459 TREE_PUBLIC (r) = TREE_PUBLIC (t);
14460 DECL_EXTERNAL (r) = 1;
14461 /* If this is an instantiation of a function with internal
14462 linkage, we already know what object file linkage will be
14463 assigned to the instantiation. */
14464 DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
14465 DECL_DEFER_OUTPUT (r) = 0;
14466 DECL_CHAIN (r) = NULL_TREE;
14467 DECL_PENDING_INLINE_INFO (r) = 0;
14468 DECL_PENDING_INLINE_P (r) = 0;
14469 DECL_SAVED_TREE (r) = NULL_TREE;
14470 DECL_STRUCT_FUNCTION (r) = NULL;
14471 TREE_USED (r) = 0;
14472 /* We'll re-clone as appropriate in instantiate_template. */
14473 DECL_CLONED_FUNCTION (r) = NULL_TREE;
14475 /* If we aren't complaining now, return on error before we register
14476 the specialization so that we'll complain eventually. */
14477 if ((complain & tf_error) == 0
14478 && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14479 && !grok_op_properties (r, /*complain=*/false))
14480 return error_mark_node;
14482 /* Associate the constraints directly with the instantiation. We
14483 don't substitute through the constraints; that's only done when
14484 they are checked. */
14485 if (tree ci = get_constraints (t))
14486 set_constraints (r, ci);
14488 if (DECL_FRIEND_CONTEXT (t))
14489 SET_DECL_FRIEND_CONTEXT (r,
14490 tsubst (DECL_FRIEND_CONTEXT (t),
14491 args, complain, in_decl));
14493 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14494 args, complain, in_decl))
14495 return error_mark_node;
14497 /* Set up the DECL_TEMPLATE_INFO for R. There's no need to do
14498 this in the special friend case mentioned above where
14499 GEN_TMPL is NULL. */
14500 if (gen_tmpl && !closure)
14502 DECL_TEMPLATE_INFO (r)
14503 = build_template_info (gen_tmpl, argvec);
14504 SET_DECL_IMPLICIT_INSTANTIATION (r);
14506 tree new_r
14507 = register_specialization (r, gen_tmpl, argvec, false, hash);
14508 if (new_r != r)
14509 /* We instantiated this while substituting into
14510 the type earlier (template/friend54.C). */
14511 return new_r;
14513 /* We're not supposed to instantiate default arguments
14514 until they are called, for a template. But, for a
14515 declaration like:
14517 template <class T> void f ()
14518 { extern void g(int i = T()); }
14520 we should do the substitution when the template is
14521 instantiated. We handle the member function case in
14522 instantiate_class_template since the default arguments
14523 might refer to other members of the class. */
14524 if (!member
14525 && !PRIMARY_TEMPLATE_P (gen_tmpl)
14526 && !uses_template_parms (argvec))
14527 tsubst_default_arguments (r, complain);
14529 else if (DECL_LOCAL_DECL_P (r))
14531 if (!cp_unevaluated_operand)
14532 register_local_specialization (r, t);
14534 else
14535 DECL_TEMPLATE_INFO (r) = NULL_TREE;
14537 /* Copy the list of befriending classes. */
14538 for (tree *friends = &DECL_BEFRIENDING_CLASSES (r);
14539 *friends;
14540 friends = &TREE_CHAIN (*friends))
14542 *friends = copy_node (*friends);
14543 TREE_VALUE (*friends)
14544 = tsubst (TREE_VALUE (*friends), args, complain, in_decl);
14547 if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
14549 maybe_retrofit_in_chrg (r);
14550 if (DECL_CONSTRUCTOR_P (r) && !grok_ctor_properties (ctx, r))
14551 return error_mark_node;
14552 /* If this is an instantiation of a member template, clone it.
14553 If it isn't, that'll be handled by
14554 clone_constructors_and_destructors. */
14555 if (gen_tmpl && PRIMARY_TEMPLATE_P (gen_tmpl))
14556 clone_cdtor (r, /*update_methods=*/false);
14558 else if ((complain & tf_error) != 0
14559 && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14560 && !grok_op_properties (r, /*complain=*/true))
14561 return error_mark_node;
14563 /* Possibly limit visibility based on template args. */
14564 DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
14565 if (DECL_VISIBILITY_SPECIFIED (t))
14567 DECL_VISIBILITY_SPECIFIED (r) = 0;
14568 DECL_ATTRIBUTES (r)
14569 = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
14571 determine_visibility (r);
14572 if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
14573 && !processing_template_decl)
14574 defaulted_late_check (r);
14576 if (flag_openmp)
14577 if (tree attr = lookup_attribute ("omp declare variant base",
14578 DECL_ATTRIBUTES (r)))
14579 omp_declare_variant_finalize (r, attr);
14581 return r;
14584 /* Subroutine of tsubst_decl for the case when T is a TEMPLATE_DECL. */
14586 static tree
14587 tsubst_template_decl (tree t, tree args, tsubst_flags_t complain,
14588 tree lambda_fntype, tree lambda_tparms)
14590 /* We can get here when processing a member function template,
14591 member class template, or template template parameter. */
14592 tree decl = DECL_TEMPLATE_RESULT (t);
14593 tree in_decl = t;
14594 tree spec;
14595 tree tmpl_args;
14596 tree full_args;
14597 tree r;
14598 hashval_t hash = 0;
14600 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
14602 /* Template template parameter is treated here. */
14603 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14604 if (new_type == error_mark_node)
14605 r = error_mark_node;
14606 /* If we get a real template back, return it. This can happen in
14607 the context of most_specialized_partial_spec. */
14608 else if (TREE_CODE (new_type) == TEMPLATE_DECL)
14609 r = new_type;
14610 else
14611 /* The new TEMPLATE_DECL was built in
14612 reduce_template_parm_level. */
14613 r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
14614 return r;
14617 if (!lambda_fntype)
14619 /* We might already have an instance of this template.
14620 The ARGS are for the surrounding class type, so the
14621 full args contain the tsubst'd args for the context,
14622 plus the innermost args from the template decl. */
14623 tmpl_args = DECL_CLASS_TEMPLATE_P (t)
14624 ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
14625 : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
14626 /* Because this is a template, the arguments will still be
14627 dependent, even after substitution. If
14628 PROCESSING_TEMPLATE_DECL is not set, the dependency
14629 predicates will short-circuit. */
14630 ++processing_template_decl;
14631 full_args = tsubst_template_args (tmpl_args, args,
14632 complain, in_decl);
14633 --processing_template_decl;
14634 if (full_args == error_mark_node)
14635 return error_mark_node;
14637 /* If this is a default template template argument,
14638 tsubst might not have changed anything. */
14639 if (full_args == tmpl_args)
14640 return t;
14642 hash = spec_hasher::hash (t, full_args);
14643 spec = retrieve_specialization (t, full_args, hash);
14644 if (spec != NULL_TREE)
14646 if (TYPE_P (spec))
14647 /* Type partial instantiations are stored as the type by
14648 lookup_template_class_1, not here as the template. */
14649 spec = CLASSTYPE_TI_TEMPLATE (spec);
14650 return spec;
14654 /* Make a new template decl. It will be similar to the
14655 original, but will record the current template arguments.
14656 We also create a new function declaration, which is just
14657 like the old one, but points to this new template, rather
14658 than the old one. */
14659 r = copy_decl (t);
14660 gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
14661 DECL_CHAIN (r) = NULL_TREE;
14663 // Build new template info linking to the original template decl.
14664 if (!lambda_fntype)
14666 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
14667 SET_DECL_IMPLICIT_INSTANTIATION (r);
14669 else
14670 DECL_TEMPLATE_INFO (r) = NULL_TREE;
14672 /* The template parameters for this new template are all the
14673 template parameters for the old template, except the
14674 outermost level of parameters. */
14675 auto tparm_guard = make_temp_override (current_template_parms);
14676 DECL_TEMPLATE_PARMS (r)
14677 = current_template_parms
14678 = (lambda_tparms
14679 ? lambda_tparms
14680 : tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
14681 complain));
14683 bool class_p = false;
14684 tree inner = decl;
14685 ++processing_template_decl;
14686 if (TREE_CODE (inner) == FUNCTION_DECL)
14687 inner = tsubst_function_decl (inner, args, complain, lambda_fntype);
14688 else
14690 if (TREE_CODE (inner) == TYPE_DECL && !TYPE_DECL_ALIAS_P (inner))
14692 class_p = true;
14693 inner = TREE_TYPE (inner);
14695 if (class_p)
14696 inner = tsubst_aggr_type (inner, args, complain,
14697 in_decl, /*entering*/1);
14698 else
14699 inner = tsubst (inner, args, complain, in_decl);
14701 --processing_template_decl;
14702 if (inner == error_mark_node)
14703 return error_mark_node;
14705 if (class_p)
14707 /* For a partial specialization, we need to keep pointing to
14708 the primary template. */
14709 if (!DECL_TEMPLATE_SPECIALIZATION (t))
14711 CLASSTYPE_TI_TEMPLATE (inner) = r;
14712 CLASSTYPE_USE_TEMPLATE (inner) = 0;
14715 DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (inner);
14716 inner = TYPE_MAIN_DECL (inner);
14718 else if (lambda_fntype)
14720 tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (r));
14721 DECL_TEMPLATE_INFO (inner) = build_template_info (r, args);
14723 else
14725 DECL_TI_TEMPLATE (inner) = r;
14726 DECL_TI_ARGS (r) = DECL_TI_ARGS (inner);
14729 DECL_TEMPLATE_RESULT (r) = inner;
14730 TREE_TYPE (r) = TREE_TYPE (inner);
14731 DECL_CONTEXT (r) = DECL_CONTEXT (inner);
14733 if (modules_p ())
14735 /* Propagate module information from the decl. */
14736 DECL_MODULE_EXPORT_P (r) = DECL_MODULE_EXPORT_P (inner);
14737 if (DECL_LANG_SPECIFIC (inner))
14738 /* If this is a constrained template, the above tsubst of
14739 inner can find the unconstrained template, which may have
14740 come from an import. This is ok, because we don't
14741 register this instantiation (see below). */
14742 gcc_checking_assert (!DECL_MODULE_IMPORT_P (inner)
14743 || (TEMPLATE_PARMS_CONSTRAINTS
14744 (DECL_TEMPLATE_PARMS (t))));
14747 DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
14748 DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
14750 if (PRIMARY_TEMPLATE_P (t))
14751 DECL_PRIMARY_TEMPLATE (r) = r;
14753 if (TREE_CODE (decl) == FUNCTION_DECL && !lambda_fntype)
14754 /* Record this non-type partial instantiation. */
14755 register_specialization (r, t,
14756 DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
14757 false, hash);
14759 return r;
14762 /* True if FN is the op() for a lambda in an uninstantiated template. */
14764 bool
14765 lambda_fn_in_template_p (tree fn)
14767 if (!fn || !LAMBDA_FUNCTION_P (fn))
14768 return false;
14769 tree closure = DECL_CONTEXT (fn);
14770 return CLASSTYPE_TEMPLATE_INFO (closure) != NULL_TREE;
14773 /* True if FN is the substitution (via tsubst_lambda_expr) of a function for
14774 which the above is true. */
14776 bool
14777 regenerated_lambda_fn_p (tree fn)
14779 if (!fn || !LAMBDA_FUNCTION_P (fn))
14780 return false;
14781 tree closure = DECL_CONTEXT (fn);
14782 tree lam = CLASSTYPE_LAMBDA_EXPR (closure);
14783 return LAMBDA_EXPR_REGEN_INFO (lam) != NULL_TREE;
14786 /* Return the LAMBDA_EXPR from which T was ultimately regenerated.
14787 If T is not a regenerated LAMBDA_EXPR, return T. */
14789 tree
14790 most_general_lambda (tree t)
14792 while (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
14793 t = TI_TEMPLATE (ti);
14794 return t;
14797 /* Return the set of template arguments used to regenerate the lambda T
14798 from its most general lambda. */
14800 tree
14801 lambda_regenerating_args (tree t)
14803 if (LAMBDA_FUNCTION_P (t))
14804 t = CLASSTYPE_LAMBDA_EXPR (DECL_CONTEXT (t));
14805 gcc_assert (TREE_CODE (t) == LAMBDA_EXPR);
14806 if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
14807 return TI_ARGS (ti);
14808 else
14809 return NULL_TREE;
14812 /* We're instantiating a variable from template function TCTX. Return the
14813 corresponding current enclosing scope. We can match them up using
14814 DECL_SOURCE_LOCATION because lambdas only ever have one source location, and
14815 the DECL_SOURCE_LOCATION for a function instantiation is updated to match
14816 the template definition in regenerate_decl_from_template. */
14818 static tree
14819 enclosing_instantiation_of (tree tctx)
14821 tree fn = current_function_decl;
14823 /* We shouldn't ever need to do this for other artificial functions. */
14824 gcc_assert (!DECL_ARTIFICIAL (tctx) || LAMBDA_FUNCTION_P (tctx));
14826 for (; fn; fn = decl_function_context (fn))
14827 if (DECL_SOURCE_LOCATION (fn) == DECL_SOURCE_LOCATION (tctx))
14828 return fn;
14829 gcc_unreachable ();
14832 /* Substitute the ARGS into the T, which is a _DECL. Return the
14833 result of the substitution. Issue error and warning messages under
14834 control of COMPLAIN. */
14836 static tree
14837 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
14839 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
14840 location_t saved_loc;
14841 tree r = NULL_TREE;
14842 tree in_decl = t;
14843 hashval_t hash = 0;
14845 /* Set the filename and linenumber to improve error-reporting. */
14846 saved_loc = input_location;
14847 input_location = DECL_SOURCE_LOCATION (t);
14849 switch (TREE_CODE (t))
14851 case TEMPLATE_DECL:
14852 r = tsubst_template_decl (t, args, complain,
14853 /*lambda_fntype=*/NULL_TREE,
14854 /*lambda_tparms=*/NULL_TREE);
14855 break;
14857 case FUNCTION_DECL:
14858 r = tsubst_function_decl (t, args, complain, /*lambda*/NULL_TREE);
14859 break;
14861 case PARM_DECL:
14863 tree type = NULL_TREE;
14864 int i, len = 1;
14865 tree expanded_types = NULL_TREE;
14866 tree prev_r = NULL_TREE;
14867 tree first_r = NULL_TREE;
14869 if (DECL_PACK_P (t))
14871 /* If there is a local specialization that isn't a
14872 parameter pack, it means that we're doing a "simple"
14873 substitution from inside tsubst_pack_expansion. Just
14874 return the local specialization (which will be a single
14875 parm). */
14876 tree spec = retrieve_local_specialization (t);
14877 if (spec
14878 && TREE_CODE (spec) == PARM_DECL
14879 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
14880 RETURN (spec);
14882 /* Expand the TYPE_PACK_EXPANSION that provides the types for
14883 the parameters in this function parameter pack. */
14884 expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
14885 complain, in_decl);
14886 if (TREE_CODE (expanded_types) == TREE_VEC)
14888 len = TREE_VEC_LENGTH (expanded_types);
14890 /* Zero-length parameter packs are boring. Just substitute
14891 into the chain. */
14892 if (len == 0 && !cp_unevaluated_operand)
14893 RETURN (tsubst (TREE_CHAIN (t), args, complain,
14894 TREE_CHAIN (t)));
14896 else
14898 /* All we did was update the type. Make a note of that. */
14899 type = expanded_types;
14900 expanded_types = NULL_TREE;
14904 /* Loop through all of the parameters we'll build. When T is
14905 a function parameter pack, LEN is the number of expanded
14906 types in EXPANDED_TYPES; otherwise, LEN is 1. */
14907 r = NULL_TREE;
14908 for (i = 0; i < len; ++i)
14910 prev_r = r;
14911 r = copy_node (t);
14912 if (DECL_TEMPLATE_PARM_P (t))
14913 SET_DECL_TEMPLATE_PARM_P (r);
14915 if (expanded_types)
14916 /* We're on the Ith parameter of the function parameter
14917 pack. */
14919 /* Get the Ith type. */
14920 type = TREE_VEC_ELT (expanded_types, i);
14922 /* Rename the parameter to include the index. */
14923 DECL_NAME (r)
14924 = make_ith_pack_parameter_name (DECL_NAME (r), i);
14926 else if (!type)
14927 /* We're dealing with a normal parameter. */
14928 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14930 type = type_decays_to (type);
14931 TREE_TYPE (r) = type;
14932 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14934 if (DECL_INITIAL (r))
14936 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
14937 DECL_INITIAL (r) = TREE_TYPE (r);
14938 else
14939 DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
14940 complain, in_decl);
14943 DECL_CONTEXT (r) = NULL_TREE;
14945 if (!DECL_TEMPLATE_PARM_P (r))
14946 DECL_ARG_TYPE (r) = type_passed_as (type);
14948 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14949 args, complain, in_decl))
14950 return error_mark_node;
14952 /* Keep track of the first new parameter we
14953 generate. That's what will be returned to the
14954 caller. */
14955 if (!first_r)
14956 first_r = r;
14958 /* Build a proper chain of parameters when substituting
14959 into a function parameter pack. */
14960 if (prev_r)
14961 DECL_CHAIN (prev_r) = r;
14964 /* If cp_unevaluated_operand is set, we're just looking for a
14965 single dummy parameter, so don't keep going. */
14966 if (DECL_CHAIN (t) && !cp_unevaluated_operand)
14967 DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
14968 complain, DECL_CHAIN (t));
14970 /* FIRST_R contains the start of the chain we've built. */
14971 r = first_r;
14973 break;
14975 case FIELD_DECL:
14977 tree type = NULL_TREE;
14978 tree vec = NULL_TREE;
14979 tree expanded_types = NULL_TREE;
14980 int len = 1;
14982 if (PACK_EXPANSION_P (TREE_TYPE (t)))
14984 /* This field is a lambda capture pack. Return a TREE_VEC of
14985 the expanded fields to instantiate_class_template_1. */
14986 expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
14987 complain, in_decl);
14988 if (TREE_CODE (expanded_types) == TREE_VEC)
14990 len = TREE_VEC_LENGTH (expanded_types);
14991 vec = make_tree_vec (len);
14993 else
14995 /* All we did was update the type. Make a note of that. */
14996 type = expanded_types;
14997 expanded_types = NULL_TREE;
15001 for (int i = 0; i < len; ++i)
15003 r = copy_decl (t);
15004 if (expanded_types)
15006 type = TREE_VEC_ELT (expanded_types, i);
15007 DECL_NAME (r)
15008 = make_ith_pack_parameter_name (DECL_NAME (r), i);
15010 else if (!type)
15011 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15013 if (type == error_mark_node)
15014 RETURN (error_mark_node);
15015 TREE_TYPE (r) = type;
15016 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
15018 if (DECL_C_BIT_FIELD (r))
15019 /* For bit-fields, DECL_BIT_FIELD_REPRESENTATIVE gives the
15020 number of bits. */
15021 DECL_BIT_FIELD_REPRESENTATIVE (r)
15022 = tsubst_expr (DECL_BIT_FIELD_REPRESENTATIVE (t), args,
15023 complain, in_decl);
15024 if (DECL_INITIAL (t))
15026 /* Set up DECL_TEMPLATE_INFO so that we can get at the
15027 NSDMI in perform_member_init. Still set DECL_INITIAL
15028 so that we know there is one. */
15029 DECL_INITIAL (r) = void_node;
15030 gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
15031 retrofit_lang_decl (r);
15032 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
15034 /* We don't have to set DECL_CONTEXT here; it is set by
15035 finish_member_declaration. */
15036 DECL_CHAIN (r) = NULL_TREE;
15038 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
15039 args, complain, in_decl))
15040 return error_mark_node;
15042 if (vec)
15043 TREE_VEC_ELT (vec, i) = r;
15046 if (vec)
15047 r = vec;
15049 break;
15051 case USING_DECL:
15052 /* We reach here only for member using decls. We also need to check
15053 uses_template_parms because DECL_DEPENDENT_P is not set for a
15054 using-declaration that designates a member of the current
15055 instantiation (c++/53549). */
15056 if (DECL_DEPENDENT_P (t)
15057 || uses_template_parms (USING_DECL_SCOPE (t)))
15059 /* True iff this using-decl was written as a pack expansion
15060 (and a pack appeared in its scope or name). If a pack
15061 appeared in both, we expand the packs separately and
15062 manually merge them. */
15063 bool variadic_p = false;
15065 tree scope = USING_DECL_SCOPE (t);
15066 if (PACK_EXPANSION_P (scope))
15068 scope = tsubst_pack_expansion (scope, args,
15069 complain | tf_qualifying_scope,
15070 in_decl);
15071 variadic_p = true;
15073 else
15074 scope = tsubst_scope (scope, args, complain, in_decl);
15076 tree name = DECL_NAME (t);
15077 if (IDENTIFIER_CONV_OP_P (name)
15078 && PACK_EXPANSION_P (TREE_TYPE (name)))
15080 name = tsubst_pack_expansion (TREE_TYPE (name), args,
15081 complain, in_decl);
15082 if (name == error_mark_node)
15084 r = error_mark_node;
15085 break;
15087 for (tree& elt : tree_vec_range (name))
15088 elt = make_conv_op_name (elt);
15089 variadic_p = true;
15091 else
15092 name = tsubst_copy (name, args, complain, in_decl);
15094 int len;
15095 if (!variadic_p)
15096 len = 1;
15097 else if (TREE_CODE (scope) == TREE_VEC
15098 && TREE_CODE (name) == TREE_VEC)
15100 if (TREE_VEC_LENGTH (scope) != TREE_VEC_LENGTH (name))
15102 error ("mismatched argument pack lengths (%d vs %d)",
15103 TREE_VEC_LENGTH (scope), TREE_VEC_LENGTH (name));
15104 r = error_mark_node;
15105 break;
15107 len = TREE_VEC_LENGTH (scope);
15109 else if (TREE_CODE (scope) == TREE_VEC)
15110 len = TREE_VEC_LENGTH (scope);
15111 else /* TREE_CODE (name) == TREE_VEC */
15112 len = TREE_VEC_LENGTH (name);
15114 r = make_tree_vec (len);
15115 for (int i = 0; i < len; ++i)
15117 tree escope = (TREE_CODE (scope) == TREE_VEC
15118 ? TREE_VEC_ELT (scope, i)
15119 : scope);
15120 tree ename = (TREE_CODE (name) == TREE_VEC
15121 ? TREE_VEC_ELT (name, i)
15122 : name);
15123 tree elt = do_class_using_decl (escope, ename);
15124 if (!elt)
15126 r = error_mark_node;
15127 break;
15129 TREE_PROTECTED (elt) = TREE_PROTECTED (t);
15130 TREE_PRIVATE (elt) = TREE_PRIVATE (t);
15131 TREE_VEC_ELT (r, i) = elt;
15134 if (!variadic_p && r != error_mark_node)
15135 r = TREE_VEC_ELT (r, 0);
15137 else
15139 r = copy_node (t);
15140 DECL_CHAIN (r) = NULL_TREE;
15142 break;
15144 case TYPE_DECL:
15145 case VAR_DECL:
15147 tree argvec = NULL_TREE;
15148 tree gen_tmpl = NULL_TREE;
15149 tree tmpl = NULL_TREE;
15150 tree type = NULL_TREE;
15152 if (TREE_TYPE (t) == error_mark_node)
15153 RETURN (error_mark_node);
15155 if (TREE_CODE (t) == TYPE_DECL
15156 && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
15158 /* If this is the canonical decl, we don't have to
15159 mess with instantiations, and often we can't (for
15160 typename, template type parms and such). Note that
15161 TYPE_NAME is not correct for the above test if
15162 we've copied the type for a typedef. */
15163 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15164 if (type == error_mark_node)
15165 RETURN (error_mark_node);
15166 r = TYPE_NAME (type);
15167 break;
15170 /* Check to see if we already have the specialization we
15171 need. */
15172 tree spec = NULL_TREE;
15173 bool local_p = false;
15174 tree ctx = DECL_CONTEXT (t);
15175 if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t))
15176 && (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t)))
15178 local_p = false;
15179 if (DECL_CLASS_SCOPE_P (t))
15181 ctx = tsubst_aggr_type (ctx, args,
15182 complain,
15183 in_decl, /*entering_scope=*/1);
15184 if (DECL_SELF_REFERENCE_P (t))
15185 /* The context and type of an injected-class-name are
15186 the same, so we don't need to substitute both. */
15187 type = ctx;
15188 /* If CTX is unchanged, then T is in fact the
15189 specialization we want. That situation occurs when
15190 referencing a static data member within in its own
15191 class. We can use pointer equality, rather than
15192 same_type_p, because DECL_CONTEXT is always
15193 canonical... */
15194 if (ctx == DECL_CONTEXT (t)
15195 /* ... unless T is a member template; in which
15196 case our caller can be willing to create a
15197 specialization of that template represented
15198 by T. */
15199 && !(DECL_TI_TEMPLATE (t)
15200 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
15201 spec = t;
15204 if (!spec)
15206 tmpl = DECL_TI_TEMPLATE (t);
15207 gen_tmpl = most_general_template (tmpl);
15208 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
15209 if (argvec != error_mark_node
15210 && PRIMARY_TEMPLATE_P (gen_tmpl)
15211 && TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (argvec))
15212 /* We're fully specializing a template declaration, so
15213 we need to coerce the innermost arguments corresponding to
15214 the template. */
15215 argvec = (coerce_template_parms
15216 (DECL_TEMPLATE_PARMS (gen_tmpl),
15217 argvec, tmpl, complain));
15218 if (argvec == error_mark_node)
15219 RETURN (error_mark_node);
15220 hash = spec_hasher::hash (gen_tmpl, argvec);
15221 spec = retrieve_specialization (gen_tmpl, argvec, hash);
15224 else
15226 if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t)))
15227 /* Subsequent calls to pushdecl will fill this in. */
15228 ctx = NULL_TREE;
15229 /* A local variable. */
15230 local_p = true;
15231 /* Unless this is a reference to a static variable from an
15232 enclosing function, in which case we need to fill it in now. */
15233 if (TREE_STATIC (t))
15235 tree fn = enclosing_instantiation_of (DECL_CONTEXT (t));
15236 if (fn != current_function_decl)
15237 ctx = fn;
15239 spec = retrieve_local_specialization (t);
15241 /* If we already have the specialization we need, there is
15242 nothing more to do. */
15243 if (spec)
15245 r = spec;
15246 break;
15249 /* Create a new node for the specialization we need. */
15250 if (type == NULL_TREE)
15252 if (is_typedef_decl (t))
15253 type = DECL_ORIGINAL_TYPE (t);
15254 else
15255 type = TREE_TYPE (t);
15256 if (VAR_P (t)
15257 && VAR_HAD_UNKNOWN_BOUND (t)
15258 && type != error_mark_node)
15259 type = strip_array_domain (type);
15260 tsubst_flags_t tcomplain = complain;
15261 if (VAR_P (t))
15262 tcomplain |= tf_tst_ok;
15263 type = tsubst (type, args, tcomplain, in_decl);
15264 /* Substituting the type might have recursively instantiated this
15265 same alias (c++/86171). */
15266 if (gen_tmpl && DECL_ALIAS_TEMPLATE_P (gen_tmpl)
15267 && (spec = retrieve_specialization (gen_tmpl, argvec, hash)))
15269 r = spec;
15270 break;
15273 r = copy_decl (t);
15274 if (VAR_P (r))
15276 DECL_INITIALIZED_P (r) = 0;
15277 DECL_TEMPLATE_INSTANTIATED (r) = 0;
15278 if (type == error_mark_node)
15279 RETURN (error_mark_node);
15280 if (TREE_CODE (type) == FUNCTION_TYPE)
15282 /* It may seem that this case cannot occur, since:
15284 typedef void f();
15285 void g() { f x; }
15287 declares a function, not a variable. However:
15289 typedef void f();
15290 template <typename T> void g() { T t; }
15291 template void g<f>();
15293 is an attempt to declare a variable with function
15294 type. */
15295 error ("variable %qD has function type",
15296 /* R is not yet sufficiently initialized, so we
15297 just use its name. */
15298 DECL_NAME (r));
15299 RETURN (error_mark_node);
15301 type = complete_type (type);
15302 /* Wait until cp_finish_decl to set this again, to handle
15303 circular dependency (template/instantiate6.C). */
15304 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
15305 type = check_var_type (DECL_NAME (r), type,
15306 DECL_SOURCE_LOCATION (r));
15307 if (DECL_HAS_VALUE_EXPR_P (t))
15309 tree ve = DECL_VALUE_EXPR (t);
15310 /* If the DECL_VALUE_EXPR is converted to the declared type,
15311 preserve the identity so that gimplify_type_sizes works. */
15312 bool nop = (TREE_CODE (ve) == NOP_EXPR);
15313 if (nop)
15314 ve = TREE_OPERAND (ve, 0);
15315 ve = tsubst_expr (ve, args, complain, in_decl);
15316 if (REFERENCE_REF_P (ve))
15318 gcc_assert (TYPE_REF_P (type));
15319 ve = TREE_OPERAND (ve, 0);
15321 if (nop)
15322 ve = build_nop (type, ve);
15323 else if (DECL_LANG_SPECIFIC (t)
15324 && DECL_OMP_PRIVATIZED_MEMBER (t)
15325 && TREE_CODE (ve) == COMPONENT_REF
15326 && TREE_CODE (TREE_OPERAND (ve, 1)) == FIELD_DECL
15327 && DECL_BIT_FIELD_TYPE (TREE_OPERAND (ve, 1)) == type)
15328 type = TREE_TYPE (ve);
15329 else
15330 gcc_checking_assert (TYPE_MAIN_VARIANT (TREE_TYPE (ve))
15331 == TYPE_MAIN_VARIANT (type));
15332 SET_DECL_VALUE_EXPR (r, ve);
15334 if (CP_DECL_THREAD_LOCAL_P (r)
15335 && !processing_template_decl)
15336 set_decl_tls_model (r, decl_default_tls_model (r));
15338 else if (DECL_SELF_REFERENCE_P (t))
15339 SET_DECL_SELF_REFERENCE_P (r);
15340 TREE_TYPE (r) = type;
15341 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
15342 DECL_CONTEXT (r) = ctx;
15343 /* Clear out the mangled name and RTL for the instantiation. */
15344 SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
15345 if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
15346 SET_DECL_RTL (r, NULL);
15347 set_instantiating_module (r);
15349 /* The initializer must not be expanded until it is required;
15350 see [temp.inst]. */
15351 DECL_INITIAL (r) = NULL_TREE;
15352 DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
15353 if (VAR_P (r))
15355 if (DECL_LANG_SPECIFIC (r))
15356 SET_DECL_DEPENDENT_INIT_P (r, false);
15358 SET_DECL_MODE (r, VOIDmode);
15360 /* Possibly limit visibility based on template args. */
15361 DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
15362 if (DECL_VISIBILITY_SPECIFIED (t))
15364 DECL_VISIBILITY_SPECIFIED (r) = 0;
15365 DECL_ATTRIBUTES (r)
15366 = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
15368 determine_visibility (r);
15371 if (!local_p)
15373 /* A static data member declaration is always marked
15374 external when it is declared in-class, even if an
15375 initializer is present. We mimic the non-template
15376 processing here. */
15377 DECL_EXTERNAL (r) = 1;
15378 if (DECL_NAMESPACE_SCOPE_P (t))
15379 DECL_NOT_REALLY_EXTERN (r) = 1;
15381 DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
15382 SET_DECL_IMPLICIT_INSTANTIATION (r);
15383 if (!error_operand_p (r) || (complain & tf_error))
15384 register_specialization (r, gen_tmpl, argvec, false, hash);
15386 else
15388 if (DECL_LANG_SPECIFIC (r))
15389 DECL_TEMPLATE_INFO (r) = NULL_TREE;
15390 if (!cp_unevaluated_operand)
15391 register_local_specialization (r, t);
15394 DECL_CHAIN (r) = NULL_TREE;
15396 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
15397 /*flags=*/0,
15398 args, complain, in_decl))
15399 return error_mark_node;
15401 /* Preserve a typedef that names a type. */
15402 if (is_typedef_decl (r) && type != error_mark_node)
15404 DECL_ORIGINAL_TYPE (r) = NULL_TREE;
15405 set_underlying_type (r);
15407 /* common_handle_aligned_attribute doesn't apply the alignment
15408 to DECL_ORIGINAL_TYPE. */
15409 if (TYPE_USER_ALIGN (TREE_TYPE (t)))
15410 TREE_TYPE (r) = build_aligned_type (TREE_TYPE (r),
15411 TYPE_ALIGN (TREE_TYPE (t)));
15414 layout_decl (r, 0);
15416 break;
15418 default:
15419 gcc_unreachable ();
15421 #undef RETURN
15423 out:
15424 /* Restore the file and line information. */
15425 input_location = saved_loc;
15427 return r;
15430 /* Substitute into the complete parameter type list PARMS. */
15432 tree
15433 tsubst_function_parms (tree parms,
15434 tree args,
15435 tsubst_flags_t complain,
15436 tree in_decl)
15438 return tsubst_arg_types (parms, args, NULL_TREE, complain, in_decl);
15441 /* Substitute into the ARG_TYPES of a function type.
15442 If END is a TREE_CHAIN, leave it and any following types
15443 un-substituted. */
15445 static tree
15446 tsubst_arg_types (tree arg_types,
15447 tree args,
15448 tree end,
15449 tsubst_flags_t complain,
15450 tree in_decl)
15452 tree type = NULL_TREE;
15453 int len = 1;
15454 tree expanded_args = NULL_TREE;
15456 if (!arg_types || arg_types == void_list_node || arg_types == end)
15457 return arg_types;
15459 if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
15461 /* For a pack expansion, perform substitution on the
15462 entire expression. Later on, we'll handle the arguments
15463 one-by-one. */
15464 expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
15465 args, complain, in_decl);
15467 if (TREE_CODE (expanded_args) == TREE_VEC)
15468 /* So that we'll spin through the parameters, one by one. */
15469 len = TREE_VEC_LENGTH (expanded_args);
15470 else
15472 /* We only partially substituted into the parameter
15473 pack. Our type is TYPE_PACK_EXPANSION. */
15474 type = expanded_args;
15475 expanded_args = NULL_TREE;
15478 else
15479 type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
15481 /* Check if a substituted type is erroneous before substituting into
15482 the rest of the chain. */
15483 for (int i = 0; i < len; i++)
15485 if (expanded_args)
15486 type = TREE_VEC_ELT (expanded_args, i);
15488 if (type == error_mark_node)
15489 return error_mark_node;
15490 if (VOID_TYPE_P (type))
15492 if (complain & tf_error)
15494 error ("invalid parameter type %qT", type);
15495 if (in_decl)
15496 error ("in declaration %q+D", in_decl);
15498 return error_mark_node;
15502 /* We do not substitute into default arguments here. The standard
15503 mandates that they be instantiated only when needed, which is
15504 done in build_over_call. */
15505 tree default_arg = TREE_PURPOSE (arg_types);
15507 /* Except that we do substitute default arguments under tsubst_lambda_expr,
15508 since the new op() won't have any associated template arguments for us
15509 to refer to later. */
15510 if (lambda_fn_in_template_p (in_decl)
15511 || (in_decl && TREE_CODE (in_decl) == FUNCTION_DECL
15512 && DECL_LOCAL_DECL_P (in_decl)))
15513 default_arg = tsubst_copy_and_build (default_arg, args, complain, in_decl);
15515 tree remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
15516 args, end, complain, in_decl);
15517 if (remaining_arg_types == error_mark_node)
15518 return error_mark_node;
15520 for (int i = len-1; i >= 0; i--)
15522 if (expanded_args)
15523 type = TREE_VEC_ELT (expanded_args, i);
15525 /* Do array-to-pointer, function-to-pointer conversion, and ignore
15526 top-level qualifiers as required. */
15527 type = cv_unqualified (type_decays_to (type));
15529 if (default_arg && TREE_CODE (default_arg) == DEFERRED_PARSE)
15531 /* We've instantiated a template before its default arguments
15532 have been parsed. This can happen for a nested template
15533 class, and is not an error unless we require the default
15534 argument in a call of this function. */
15535 remaining_arg_types
15536 = tree_cons (default_arg, type, remaining_arg_types);
15537 vec_safe_push (DEFPARSE_INSTANTIATIONS (default_arg),
15538 remaining_arg_types);
15540 else
15541 remaining_arg_types
15542 = hash_tree_cons (default_arg, type, remaining_arg_types);
15545 return remaining_arg_types;
15548 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE. This routine does
15549 *not* handle the exception-specification for FNTYPE, because the
15550 initial substitution of explicitly provided template parameters
15551 during argument deduction forbids substitution into the
15552 exception-specification:
15554 [temp.deduct]
15556 All references in the function type of the function template to the
15557 corresponding template parameters are replaced by the specified tem-
15558 plate argument values. If a substitution in a template parameter or
15559 in the function type of the function template results in an invalid
15560 type, type deduction fails. [Note: The equivalent substitution in
15561 exception specifications is done only when the function is instanti-
15562 ated, at which point a program is ill-formed if the substitution
15563 results in an invalid type.] */
15565 static tree
15566 tsubst_function_type (tree t,
15567 tree args,
15568 tsubst_flags_t complain,
15569 tree in_decl)
15571 tree return_type;
15572 tree arg_types = NULL_TREE;
15574 /* The TYPE_CONTEXT is not used for function/method types. */
15575 gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
15577 /* DR 1227: Mixing immediate and non-immediate contexts in deduction
15578 failure. */
15579 bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
15581 if (late_return_type_p)
15583 /* Substitute the argument types. */
15584 arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15585 complain, in_decl);
15586 if (arg_types == error_mark_node)
15587 return error_mark_node;
15589 tree save_ccp = current_class_ptr;
15590 tree save_ccr = current_class_ref;
15591 tree this_type = (TREE_CODE (t) == METHOD_TYPE
15592 ? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
15593 bool do_inject = this_type && CLASS_TYPE_P (this_type);
15594 if (do_inject)
15596 /* DR 1207: 'this' is in scope in the trailing return type. */
15597 inject_this_parameter (this_type, cp_type_quals (this_type));
15600 /* Substitute the return type. */
15601 return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15603 if (do_inject)
15605 current_class_ptr = save_ccp;
15606 current_class_ref = save_ccr;
15609 else
15610 /* Substitute the return type. */
15611 return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15613 if (return_type == error_mark_node)
15614 return error_mark_node;
15615 /* DR 486 clarifies that creation of a function type with an
15616 invalid return type is a deduction failure. */
15617 if (TREE_CODE (return_type) == ARRAY_TYPE
15618 || TREE_CODE (return_type) == FUNCTION_TYPE)
15620 if (complain & tf_error)
15622 if (TREE_CODE (return_type) == ARRAY_TYPE)
15623 error ("function returning an array");
15624 else
15625 error ("function returning a function");
15627 return error_mark_node;
15630 if (!late_return_type_p)
15632 /* Substitute the argument types. */
15633 arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15634 complain, in_decl);
15635 if (arg_types == error_mark_node)
15636 return error_mark_node;
15639 /* Construct a new type node and return it. */
15640 return rebuild_function_or_method_type (t, return_type, arg_types,
15641 /*raises=*/NULL_TREE, complain);
15644 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE. Substitute the template
15645 ARGS into that specification, and return the substituted
15646 specification. If there is no specification, return NULL_TREE. */
15648 static tree
15649 tsubst_exception_specification (tree fntype,
15650 tree args,
15651 tsubst_flags_t complain,
15652 tree in_decl,
15653 bool defer_ok)
15655 tree specs;
15656 tree new_specs;
15658 specs = TYPE_RAISES_EXCEPTIONS (fntype);
15659 new_specs = NULL_TREE;
15660 if (specs && TREE_PURPOSE (specs))
15662 /* A noexcept-specifier. */
15663 tree expr = TREE_PURPOSE (specs);
15664 if (TREE_CODE (expr) == INTEGER_CST)
15665 new_specs = expr;
15666 else if (defer_ok)
15668 /* Defer instantiation of noexcept-specifiers to avoid
15669 excessive instantiations (c++/49107). */
15670 new_specs = make_node (DEFERRED_NOEXCEPT);
15671 if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15673 /* We already partially instantiated this member template,
15674 so combine the new args with the old. */
15675 DEFERRED_NOEXCEPT_PATTERN (new_specs)
15676 = DEFERRED_NOEXCEPT_PATTERN (expr);
15677 DEFERRED_NOEXCEPT_ARGS (new_specs)
15678 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
15680 else
15682 DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
15683 DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
15686 else
15688 if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15690 args = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr),
15691 args);
15692 expr = DEFERRED_NOEXCEPT_PATTERN (expr);
15694 new_specs = tsubst_copy_and_build (expr, args, complain, in_decl);
15696 new_specs = build_noexcept_spec (new_specs, complain);
15697 /* We've instantiated a template before a noexcept-specifier
15698 contained therein has been parsed. This can happen for
15699 a nested template class:
15701 struct S {
15702 template<typename> struct B { B() noexcept(...); };
15703 struct A : B<int> { ... use B() ... };
15706 where completing B<int> will trigger instantiating the
15707 noexcept, even though we only parse it at the end of S. */
15708 if (UNPARSED_NOEXCEPT_SPEC_P (specs))
15710 gcc_checking_assert (defer_ok);
15711 vec_safe_push (DEFPARSE_INSTANTIATIONS (expr), new_specs);
15714 else if (specs)
15716 if (! TREE_VALUE (specs))
15717 new_specs = specs;
15718 else
15719 while (specs)
15721 tree spec;
15722 int i, len = 1;
15723 tree expanded_specs = NULL_TREE;
15725 if (PACK_EXPANSION_P (TREE_VALUE (specs)))
15727 /* Expand the pack expansion type. */
15728 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
15729 args, complain,
15730 in_decl);
15732 if (expanded_specs == error_mark_node)
15733 return error_mark_node;
15734 else if (TREE_CODE (expanded_specs) == TREE_VEC)
15735 len = TREE_VEC_LENGTH (expanded_specs);
15736 else
15738 /* We're substituting into a member template, so
15739 we got a TYPE_PACK_EXPANSION back. Add that
15740 expansion and move on. */
15741 gcc_assert (TREE_CODE (expanded_specs)
15742 == TYPE_PACK_EXPANSION);
15743 new_specs = add_exception_specifier (new_specs,
15744 expanded_specs,
15745 complain);
15746 specs = TREE_CHAIN (specs);
15747 continue;
15751 for (i = 0; i < len; ++i)
15753 if (expanded_specs)
15754 spec = TREE_VEC_ELT (expanded_specs, i);
15755 else
15756 spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
15757 if (spec == error_mark_node)
15758 return spec;
15759 new_specs = add_exception_specifier (new_specs, spec,
15760 complain);
15763 specs = TREE_CHAIN (specs);
15766 return new_specs;
15769 /* Substitute through a TREE_LIST of types or expressions, handling pack
15770 expansions. */
15772 tree
15773 tsubst_tree_list (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15775 if (t == void_list_node)
15776 return t;
15778 tree purpose = TREE_PURPOSE (t);
15779 tree purposevec = NULL_TREE;
15780 if (!purpose)
15782 else if (PACK_EXPANSION_P (purpose))
15784 purpose = tsubst_pack_expansion (purpose, args, complain, in_decl);
15785 if (TREE_CODE (purpose) == TREE_VEC)
15786 purposevec = purpose;
15788 else if (TYPE_P (purpose))
15789 purpose = tsubst (purpose, args, complain, in_decl);
15790 else
15791 purpose = tsubst_copy_and_build (purpose, args, complain, in_decl);
15792 if (purpose == error_mark_node || purposevec == error_mark_node)
15793 return error_mark_node;
15795 tree value = TREE_VALUE (t);
15796 tree valuevec = NULL_TREE;
15797 if (!value)
15799 else if (PACK_EXPANSION_P (value))
15801 value = tsubst_pack_expansion (value, args, complain, in_decl);
15802 if (TREE_CODE (value) == TREE_VEC)
15803 valuevec = value;
15805 else if (TYPE_P (value))
15806 value = tsubst (value, args, complain, in_decl);
15807 else
15808 value = tsubst_copy_and_build (value, args, complain, in_decl);
15809 if (value == error_mark_node || valuevec == error_mark_node)
15810 return error_mark_node;
15812 tree chain = TREE_CHAIN (t);
15813 if (!chain)
15815 else if (TREE_CODE (chain) == TREE_LIST)
15816 chain = tsubst_tree_list (chain, args, complain, in_decl);
15817 else if (TYPE_P (chain))
15818 chain = tsubst (chain, args, complain, in_decl);
15819 else
15820 chain = tsubst_copy_and_build (chain, args, complain, in_decl);
15821 if (chain == error_mark_node)
15822 return error_mark_node;
15824 if (purpose == TREE_PURPOSE (t)
15825 && value == TREE_VALUE (t)
15826 && chain == TREE_CHAIN (t))
15827 return t;
15829 int len;
15830 /* Determine the number of arguments. */
15831 if (purposevec)
15833 len = TREE_VEC_LENGTH (purposevec);
15834 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
15836 else if (valuevec)
15837 len = TREE_VEC_LENGTH (valuevec);
15838 else
15839 len = 1;
15841 for (int i = len; i-- > 0; )
15843 if (purposevec)
15844 purpose = TREE_VEC_ELT (purposevec, i);
15845 if (valuevec)
15846 value = TREE_VEC_ELT (valuevec, i);
15848 if (value && TYPE_P (value))
15849 chain = hash_tree_cons (purpose, value, chain);
15850 else
15851 chain = tree_cons (purpose, value, chain);
15854 return chain;
15857 /* Take the tree structure T and replace template parameters used
15858 therein with the argument vector ARGS. IN_DECL is an associated
15859 decl for diagnostics. If an error occurs, returns ERROR_MARK_NODE.
15860 Issue error and warning messages under control of COMPLAIN. Note
15861 that we must be relatively non-tolerant of extensions here, in
15862 order to preserve conformance; if we allow substitutions that
15863 should not be allowed, we may allow argument deductions that should
15864 not succeed, and therefore report ambiguous overload situations
15865 where there are none. In theory, we could allow the substitution,
15866 but indicate that it should have failed, and allow our caller to
15867 make sure that the right thing happens, but we don't try to do this
15868 yet.
15870 This function is used for dealing with types, decls and the like;
15871 for expressions, use tsubst_expr or tsubst_copy. */
15873 tree
15874 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15876 enum tree_code code;
15877 tree type, r = NULL_TREE;
15879 if (t == NULL_TREE || t == error_mark_node
15880 || t == integer_type_node
15881 || t == void_type_node
15882 || t == char_type_node
15883 || t == unknown_type_node
15884 || TREE_CODE (t) == NAMESPACE_DECL
15885 || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
15886 return t;
15888 tsubst_flags_t tst_ok_flag = (complain & tf_tst_ok);
15889 complain &= ~tf_tst_ok;
15891 tsubst_flags_t qualifying_scope_flag = (complain & tf_qualifying_scope);
15892 complain &= ~tf_qualifying_scope;
15894 if (DECL_P (t))
15895 return tsubst_decl (t, args, complain);
15897 if (args == NULL_TREE)
15898 return t;
15900 code = TREE_CODE (t);
15902 gcc_assert (code != IDENTIFIER_NODE);
15903 type = TREE_TYPE (t);
15905 gcc_assert (type != unknown_type_node);
15907 if (tree d = maybe_dependent_member_ref (t, args, complain, in_decl))
15908 return d;
15910 /* Reuse typedefs. We need to do this to handle dependent attributes,
15911 such as attribute aligned. */
15912 if (TYPE_P (t)
15913 && typedef_variant_p (t))
15915 tree decl = TYPE_NAME (t);
15917 if (alias_template_specialization_p (t, nt_opaque))
15919 /* DECL represents an alias template and we want to
15920 instantiate it. */
15921 tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15922 tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15923 r = instantiate_alias_template (tmpl, gen_args, complain);
15925 else if (DECL_CLASS_SCOPE_P (decl)
15926 && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
15927 && uses_template_parms (DECL_CONTEXT (decl)))
15929 tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15930 tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15931 r = retrieve_specialization (tmpl, gen_args, 0);
15933 else if (DECL_FUNCTION_SCOPE_P (decl)
15934 && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
15935 && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
15936 r = retrieve_local_specialization (decl);
15937 else
15938 /* The typedef is from a non-template context. */
15939 return t;
15941 if (r)
15943 r = TREE_TYPE (r);
15944 r = cp_build_qualified_type
15945 (r, cp_type_quals (t) | cp_type_quals (r),
15946 complain | tf_ignore_bad_quals);
15947 return r;
15949 else
15951 /* We don't have an instantiation yet, so drop the typedef. */
15952 int quals = cp_type_quals (t);
15953 t = DECL_ORIGINAL_TYPE (decl);
15954 t = cp_build_qualified_type (t, quals,
15955 complain | tf_ignore_bad_quals);
15959 bool fndecl_type = (complain & tf_fndecl_type);
15960 complain &= ~tf_fndecl_type;
15962 if (type
15963 && code != TYPENAME_TYPE
15964 && code != TEMPLATE_TYPE_PARM
15965 && code != TEMPLATE_PARM_INDEX
15966 && code != IDENTIFIER_NODE
15967 && code != FUNCTION_TYPE
15968 && code != METHOD_TYPE)
15969 type = tsubst (type, args, complain, in_decl);
15970 if (type == error_mark_node)
15971 return error_mark_node;
15973 switch (code)
15975 case RECORD_TYPE:
15976 if (TYPE_PTRMEMFUNC_P (t))
15977 return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
15978 /* Fall through. */
15979 case UNION_TYPE:
15980 case ENUMERAL_TYPE:
15981 return tsubst_aggr_type_1 (t, args, complain, in_decl,
15982 /*entering_scope=*/0);
15984 case ERROR_MARK:
15985 case IDENTIFIER_NODE:
15986 case VOID_TYPE:
15987 case OPAQUE_TYPE:
15988 case REAL_TYPE:
15989 case COMPLEX_TYPE:
15990 case VECTOR_TYPE:
15991 case BOOLEAN_TYPE:
15992 case NULLPTR_TYPE:
15993 case LANG_TYPE:
15994 return t;
15996 case INTEGER_TYPE:
15997 if (t == integer_type_node)
15998 return t;
16000 if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
16001 && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
16002 return t;
16005 tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
16007 max = tsubst_expr (omax, args, complain, in_decl);
16009 /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
16010 needed. */
16011 if (TREE_CODE (max) == NOP_EXPR
16012 && TREE_SIDE_EFFECTS (omax)
16013 && !TREE_TYPE (max))
16014 TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
16016 /* If we're in a partial instantiation, preserve the magic NOP_EXPR
16017 with TREE_SIDE_EFFECTS that indicates this is not an integral
16018 constant expression. */
16019 if (processing_template_decl
16020 && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
16022 gcc_assert (TREE_CODE (max) == NOP_EXPR);
16023 TREE_SIDE_EFFECTS (max) = 1;
16026 return compute_array_index_type (NULL_TREE, max, complain);
16029 case TEMPLATE_TYPE_PARM:
16030 if (template_placeholder_p (t))
16032 tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (t);
16033 tmpl = tsubst_copy (tmpl, args, complain, in_decl);
16034 if (TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
16035 tmpl = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (tmpl);
16037 if (tmpl != CLASS_PLACEHOLDER_TEMPLATE (t))
16038 return make_template_placeholder (tmpl);
16039 else
16040 return t;
16042 /* Fall through. */
16043 case TEMPLATE_TEMPLATE_PARM:
16044 case BOUND_TEMPLATE_TEMPLATE_PARM:
16045 case TEMPLATE_PARM_INDEX:
16047 int idx;
16048 int level;
16049 int levels;
16050 tree arg = NULL_TREE;
16052 r = NULL_TREE;
16054 gcc_assert (TREE_VEC_LENGTH (args) > 0);
16055 template_parm_level_and_index (t, &level, &idx);
16057 levels = TMPL_ARGS_DEPTH (args);
16058 if (level <= levels
16059 && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
16061 arg = TMPL_ARG (args, level, idx);
16063 /* See through ARGUMENT_PACK_SELECT arguments. */
16064 if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
16065 arg = argument_pack_select_arg (arg);
16068 if (arg == error_mark_node)
16069 return error_mark_node;
16070 else if (arg != NULL_TREE)
16072 if (ARGUMENT_PACK_P (arg))
16073 /* If ARG is an argument pack, we don't actually want to
16074 perform a substitution here, because substitutions
16075 for argument packs are only done
16076 element-by-element. We can get to this point when
16077 substituting the type of a non-type template
16078 parameter pack, when that type actually contains
16079 template parameter packs from an outer template, e.g.,
16081 template<typename... Types> struct A {
16082 template<Types... Values> struct B { };
16083 }; */
16084 return t;
16086 if (code == TEMPLATE_TYPE_PARM)
16088 int quals;
16090 /* When building concept checks for the purpose of
16091 deducing placeholders, we can end up with wildcards
16092 where types are expected. Adjust this to the deduced
16093 value. */
16094 if (TREE_CODE (arg) == WILDCARD_DECL)
16095 arg = TREE_TYPE (TREE_TYPE (arg));
16097 gcc_assert (TYPE_P (arg));
16099 quals = cp_type_quals (arg) | cp_type_quals (t);
16101 return cp_build_qualified_type
16102 (arg, quals, complain | tf_ignore_bad_quals);
16104 else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
16106 /* We are processing a type constructed from a
16107 template template parameter. */
16108 tree argvec = tsubst (TYPE_TI_ARGS (t),
16109 args, complain, in_decl);
16110 if (argvec == error_mark_node)
16111 return error_mark_node;
16113 gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
16114 || TREE_CODE (arg) == TEMPLATE_DECL
16115 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
16117 if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
16118 /* Consider this code:
16120 template <template <class> class Template>
16121 struct Internal {
16122 template <class Arg> using Bind = Template<Arg>;
16125 template <template <class> class Template, class Arg>
16126 using Instantiate = Template<Arg>; //#0
16128 template <template <class> class Template,
16129 class Argument>
16130 using Bind =
16131 Instantiate<Internal<Template>::template Bind,
16132 Argument>; //#1
16134 When #1 is parsed, the
16135 BOUND_TEMPLATE_TEMPLATE_PARM representing the
16136 parameter `Template' in #0 matches the
16137 UNBOUND_CLASS_TEMPLATE representing the argument
16138 `Internal<Template>::template Bind'; We then want
16139 to assemble the type `Bind<Argument>' that can't
16140 be fully created right now, because
16141 `Internal<Template>' not being complete, the Bind
16142 template cannot be looked up in that context. So
16143 we need to "store" `Bind<Argument>' for later
16144 when the context of Bind becomes complete. Let's
16145 store that in a TYPENAME_TYPE. */
16146 return make_typename_type (TYPE_CONTEXT (arg),
16147 build_nt (TEMPLATE_ID_EXPR,
16148 TYPE_IDENTIFIER (arg),
16149 argvec),
16150 typename_type,
16151 complain);
16153 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
16154 are resolving nested-types in the signature of a
16155 member function templates. Otherwise ARG is a
16156 TEMPLATE_DECL and is the real template to be
16157 instantiated. */
16158 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16159 arg = TYPE_NAME (arg);
16161 r = lookup_template_class (arg,
16162 argvec, in_decl,
16163 DECL_CONTEXT (arg),
16164 /*entering_scope=*/0,
16165 complain);
16166 return cp_build_qualified_type
16167 (r, cp_type_quals (t) | cp_type_quals (r), complain);
16169 else if (code == TEMPLATE_TEMPLATE_PARM)
16170 return arg;
16171 else
16172 /* TEMPLATE_PARM_INDEX. */
16173 return convert_from_reference (unshare_expr (arg));
16176 if (level == 1)
16177 /* This can happen during the attempted tsubst'ing in
16178 unify. This means that we don't yet have any information
16179 about the template parameter in question. */
16180 return t;
16182 /* Early in template argument deduction substitution, we don't
16183 want to reduce the level of 'auto', or it will be confused
16184 with a normal template parm in subsequent deduction.
16185 Similarly, don't reduce the level of template parameters to
16186 avoid mismatches when deducing their types. */
16187 if (complain & tf_partial)
16188 return t;
16190 /* If we get here, we must have been looking at a parm for a
16191 more deeply nested template. Make a new version of this
16192 template parameter, but with a lower level. */
16193 int quals;
16194 switch (code)
16196 case TEMPLATE_TYPE_PARM:
16197 case TEMPLATE_TEMPLATE_PARM:
16198 quals = cp_type_quals (t);
16199 if (quals)
16201 gcc_checking_assert (code == TEMPLATE_TYPE_PARM);
16202 t = TYPE_MAIN_VARIANT (t);
16205 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
16206 && (arg = TEMPLATE_TYPE_PARM_INDEX (t),
16207 r = TEMPLATE_PARM_DESCENDANTS (arg))
16208 && (TEMPLATE_PARM_LEVEL (r)
16209 == TEMPLATE_PARM_LEVEL (arg) - levels))
16210 /* Cache the simple case of lowering a type parameter. */
16211 r = TREE_TYPE (r);
16212 else
16214 r = copy_type (t);
16215 TEMPLATE_TYPE_PARM_INDEX (r)
16216 = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
16217 r, levels, args, complain);
16218 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
16219 TYPE_MAIN_VARIANT (r) = r;
16220 TYPE_POINTER_TO (r) = NULL_TREE;
16221 TYPE_REFERENCE_TO (r) = NULL_TREE;
16223 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
16224 if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t))
16225 /* Propagate constraints on placeholders since they are
16226 only instantiated during satisfaction. */
16227 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (r) = ci;
16229 if (TYPE_STRUCTURAL_EQUALITY_P (t))
16230 SET_TYPE_STRUCTURAL_EQUALITY (r);
16231 else
16232 TYPE_CANONICAL (r) = canonical_type_parameter (r);
16235 if (quals)
16236 r = cp_build_qualified_type (r, quals,
16237 complain | tf_ignore_bad_quals);
16238 break;
16240 case BOUND_TEMPLATE_TEMPLATE_PARM:
16242 tree tinfo = TYPE_TEMPLATE_INFO (t);
16243 /* We might need to substitute into the types of non-type
16244 template parameters. This also lowers the level of
16245 the ttp appropriately. */
16246 tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
16247 complain, in_decl);
16248 if (tmpl == error_mark_node)
16249 return error_mark_node;
16250 tree argvec = tsubst (TI_ARGS (tinfo), args,
16251 complain, in_decl);
16252 if (argvec == error_mark_node)
16253 return error_mark_node;
16254 r = lookup_template_class (tmpl, argvec, in_decl, NULL_TREE,
16255 /*entering_scope=*/false, complain);
16256 r = cp_build_qualified_type (r, cp_type_quals (t), complain);
16257 break;
16260 case TEMPLATE_PARM_INDEX:
16261 /* OK, now substitute the type of the non-type parameter. We
16262 couldn't do it earlier because it might be an auto parameter,
16263 and we wouldn't need to if we had an argument. */
16264 type = tsubst (type, args, complain, in_decl);
16265 if (type == error_mark_node)
16266 return error_mark_node;
16267 r = reduce_template_parm_level (t, type, levels, args, complain);
16268 break;
16270 default:
16271 gcc_unreachable ();
16274 return r;
16277 case TREE_LIST:
16278 return tsubst_tree_list (t, args, complain, in_decl);
16280 case TREE_BINFO:
16281 /* We should never be tsubsting a binfo. */
16282 gcc_unreachable ();
16284 case TREE_VEC:
16285 /* A vector of template arguments. */
16286 gcc_assert (!type);
16287 return tsubst_template_args (t, args, complain, in_decl);
16289 case POINTER_TYPE:
16290 case REFERENCE_TYPE:
16292 if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
16293 return t;
16295 /* [temp.deduct]
16297 Type deduction may fail for any of the following
16298 reasons:
16300 -- Attempting to create a pointer to reference type.
16301 -- Attempting to create a reference to a reference type or
16302 a reference to void.
16304 Core issue 106 says that creating a reference to a reference
16305 during instantiation is no longer a cause for failure. We
16306 only enforce this check in strict C++98 mode. */
16307 if ((TYPE_REF_P (type)
16308 && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
16309 || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
16311 static location_t last_loc;
16313 /* We keep track of the last time we issued this error
16314 message to avoid spewing a ton of messages during a
16315 single bad template instantiation. */
16316 if (complain & tf_error
16317 && last_loc != input_location)
16319 if (VOID_TYPE_P (type))
16320 error ("forming reference to void");
16321 else if (code == POINTER_TYPE)
16322 error ("forming pointer to reference type %qT", type);
16323 else
16324 error ("forming reference to reference type %qT", type);
16325 last_loc = input_location;
16328 return error_mark_node;
16330 else if (TREE_CODE (type) == FUNCTION_TYPE
16331 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
16332 || type_memfn_rqual (type) != REF_QUAL_NONE))
16334 if (complain & tf_error)
16336 if (code == POINTER_TYPE)
16337 error ("forming pointer to qualified function type %qT",
16338 type);
16339 else
16340 error ("forming reference to qualified function type %qT",
16341 type);
16343 return error_mark_node;
16345 else if (code == POINTER_TYPE)
16347 r = build_pointer_type (type);
16348 if (TREE_CODE (type) == METHOD_TYPE)
16349 r = build_ptrmemfunc_type (r);
16351 else if (TYPE_REF_P (type))
16352 /* In C++0x, during template argument substitution, when there is an
16353 attempt to create a reference to a reference type, reference
16354 collapsing is applied as described in [14.3.1/4 temp.arg.type]:
16356 "If a template-argument for a template-parameter T names a type
16357 that is a reference to a type A, an attempt to create the type
16358 'lvalue reference to cv T' creates the type 'lvalue reference to
16359 A,' while an attempt to create the type type rvalue reference to
16360 cv T' creates the type T"
16362 r = cp_build_reference_type
16363 (TREE_TYPE (type),
16364 TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
16365 else
16366 r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
16367 r = cp_build_qualified_type (r, cp_type_quals (t), complain);
16369 if (r != error_mark_node)
16370 /* Will this ever be needed for TYPE_..._TO values? */
16371 layout_type (r);
16373 return r;
16375 case OFFSET_TYPE:
16377 r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
16378 if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
16380 /* [temp.deduct]
16382 Type deduction may fail for any of the following
16383 reasons:
16385 -- Attempting to create "pointer to member of T" when T
16386 is not a class type. */
16387 if (complain & tf_error)
16388 error ("creating pointer to member of non-class type %qT", r);
16389 return error_mark_node;
16391 if (TYPE_REF_P (type))
16393 if (complain & tf_error)
16394 error ("creating pointer to member reference type %qT", type);
16395 return error_mark_node;
16397 if (VOID_TYPE_P (type))
16399 if (complain & tf_error)
16400 error ("creating pointer to member of type void");
16401 return error_mark_node;
16403 gcc_assert (TREE_CODE (type) != METHOD_TYPE);
16404 if (TREE_CODE (type) == FUNCTION_TYPE)
16406 /* The type of the implicit object parameter gets its
16407 cv-qualifiers from the FUNCTION_TYPE. */
16408 tree memptr;
16409 tree method_type
16410 = build_memfn_type (type, r, type_memfn_quals (type),
16411 type_memfn_rqual (type));
16412 memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
16413 return cp_build_qualified_type (memptr, cp_type_quals (t),
16414 complain);
16416 else
16417 return cp_build_qualified_type (build_ptrmem_type (r, type),
16418 cp_type_quals (t),
16419 complain);
16421 case FUNCTION_TYPE:
16422 case METHOD_TYPE:
16424 tree fntype;
16425 tree specs;
16426 fntype = tsubst_function_type (t, args, complain, in_decl);
16427 if (fntype == error_mark_node)
16428 return error_mark_node;
16430 /* Substitute the exception specification. */
16431 specs = tsubst_exception_specification (t, args, complain, in_decl,
16432 /*defer_ok*/fndecl_type);
16433 if (specs == error_mark_node)
16434 return error_mark_node;
16435 if (specs)
16436 fntype = build_exception_variant (fntype, specs);
16437 return fntype;
16439 case ARRAY_TYPE:
16441 tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
16442 if (domain == error_mark_node)
16443 return error_mark_node;
16445 /* As an optimization, we avoid regenerating the array type if
16446 it will obviously be the same as T. */
16447 if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
16448 return t;
16450 /* These checks should match the ones in create_array_type_for_decl.
16452 [temp.deduct]
16454 The deduction may fail for any of the following reasons:
16456 -- Attempting to create an array with an element type that
16457 is void, a function type, or a reference type, or [DR337]
16458 an abstract class type. */
16459 if (VOID_TYPE_P (type)
16460 || TREE_CODE (type) == FUNCTION_TYPE
16461 || (TREE_CODE (type) == ARRAY_TYPE
16462 && TYPE_DOMAIN (type) == NULL_TREE)
16463 || TYPE_REF_P (type))
16465 if (complain & tf_error)
16466 error ("creating array of %qT", type);
16467 return error_mark_node;
16470 if (!verify_type_context (input_location, TCTX_ARRAY_ELEMENT, type,
16471 !(complain & tf_error)))
16472 return error_mark_node;
16474 r = build_cplus_array_type (type, domain);
16476 if (!valid_array_size_p (input_location, r, in_decl,
16477 (complain & tf_error)))
16478 return error_mark_node;
16480 if (TYPE_USER_ALIGN (t))
16482 SET_TYPE_ALIGN (r, TYPE_ALIGN (t));
16483 TYPE_USER_ALIGN (r) = 1;
16486 return r;
16489 case TYPENAME_TYPE:
16491 tree ctx = TYPE_CONTEXT (t);
16492 if (TREE_CODE (ctx) == TYPE_PACK_EXPANSION)
16494 ctx = tsubst_pack_expansion (ctx, args,
16495 complain | tf_qualifying_scope,
16496 in_decl);
16497 if (ctx == error_mark_node
16498 || TREE_VEC_LENGTH (ctx) > 1)
16499 return error_mark_node;
16500 if (TREE_VEC_LENGTH (ctx) == 0)
16502 if (complain & tf_error)
16503 error ("%qD is instantiated for an empty pack",
16504 TYPENAME_TYPE_FULLNAME (t));
16505 return error_mark_node;
16507 ctx = TREE_VEC_ELT (ctx, 0);
16509 else
16510 ctx = tsubst_aggr_type (ctx, args,
16511 complain | tf_qualifying_scope,
16512 in_decl, /*entering_scope=*/1);
16513 if (ctx == error_mark_node)
16514 return error_mark_node;
16516 tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
16517 complain, in_decl);
16518 if (f == error_mark_node)
16519 return error_mark_node;
16521 if (!MAYBE_CLASS_TYPE_P (ctx))
16523 if (complain & tf_error)
16524 error ("%qT is not a class, struct, or union type", ctx);
16525 return error_mark_node;
16527 else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
16529 /* Normally, make_typename_type does not require that the CTX
16530 have complete type in order to allow things like:
16532 template <class T> struct S { typename S<T>::X Y; };
16534 But, such constructs have already been resolved by this
16535 point, so here CTX really should have complete type, unless
16536 it's a partial instantiation. */
16537 if (!complete_type_or_maybe_complain (ctx, NULL_TREE, complain))
16538 return error_mark_node;
16541 /* FIXME: TYPENAME_IS_CLASS_P conflates 'class' vs 'struct' vs 'union'
16542 tags. TYPENAME_TYPE should probably remember the exact tag that
16543 was written. */
16544 enum tag_types tag_type
16545 = TYPENAME_IS_CLASS_P (t) ? class_type
16546 : TYPENAME_IS_ENUM_P (t) ? enum_type
16547 : typename_type;
16548 tsubst_flags_t tcomplain = complain | tf_keep_type_decl;
16549 tcomplain |= tst_ok_flag | qualifying_scope_flag;
16550 f = make_typename_type (ctx, f, tag_type, tcomplain);
16551 if (f == error_mark_node)
16552 return f;
16553 if (TREE_CODE (f) == TYPE_DECL)
16555 complain |= tf_ignore_bad_quals;
16556 f = TREE_TYPE (f);
16559 if (TREE_CODE (f) != TYPENAME_TYPE)
16561 if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
16563 if (complain & tf_error)
16564 error ("%qT resolves to %qT, which is not an enumeration type",
16565 t, f);
16566 else
16567 return error_mark_node;
16569 else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
16571 if (complain & tf_error)
16572 error ("%qT resolves to %qT, which is not a class type",
16573 t, f);
16574 else
16575 return error_mark_node;
16579 return cp_build_qualified_type
16580 (f, cp_type_quals (f) | cp_type_quals (t), complain);
16583 case UNBOUND_CLASS_TEMPLATE:
16585 tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
16586 in_decl, /*entering_scope=*/1);
16587 tree name = TYPE_IDENTIFIER (t);
16588 tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
16590 if (ctx == error_mark_node || name == error_mark_node)
16591 return error_mark_node;
16593 if (parm_list)
16594 parm_list = tsubst_template_parms (parm_list, args, complain);
16595 return make_unbound_class_template (ctx, name, parm_list, complain);
16598 case TYPEOF_TYPE:
16600 tree type;
16602 ++cp_unevaluated_operand;
16603 ++c_inhibit_evaluation_warnings;
16605 type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args, complain, in_decl);
16607 --cp_unevaluated_operand;
16608 --c_inhibit_evaluation_warnings;
16610 type = finish_typeof (type);
16611 return cp_build_qualified_type (type,
16612 cp_type_quals (t)
16613 | cp_type_quals (type),
16614 complain);
16617 case DECLTYPE_TYPE:
16619 tree type;
16621 ++cp_unevaluated_operand;
16622 ++c_inhibit_evaluation_warnings;
16624 type = tsubst_copy_and_build (DECLTYPE_TYPE_EXPR (t), args,
16625 complain|tf_decltype, in_decl);
16627 --cp_unevaluated_operand;
16628 --c_inhibit_evaluation_warnings;
16630 if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
16631 type = lambda_capture_field_type (type,
16632 false /*explicit_init*/,
16633 DECLTYPE_FOR_REF_CAPTURE (t));
16634 else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
16635 type = lambda_proxy_type (type);
16636 else
16638 bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
16639 if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
16640 && EXPR_P (type))
16641 /* In a template ~id could be either a complement expression
16642 or an unqualified-id naming a destructor; if instantiating
16643 it produces an expression, it's not an id-expression or
16644 member access. */
16645 id = false;
16646 type = finish_decltype_type (type, id, complain);
16648 return cp_build_qualified_type (type,
16649 cp_type_quals (t)
16650 | cp_type_quals (type),
16651 complain | tf_ignore_bad_quals);
16654 case TRAIT_TYPE:
16656 tree type1 = TRAIT_TYPE_TYPE1 (t);
16657 if (TYPE_P (type1))
16658 type1 = tsubst (type1, args, complain, in_decl);
16659 else
16660 type1 = tsubst_copy_and_build (type1, args, complain, in_decl);
16661 tree type2 = tsubst (TRAIT_TYPE_TYPE2 (t), args, complain, in_decl);
16662 type = finish_trait_type (TRAIT_TYPE_KIND (t), type1, type2, complain);
16663 return cp_build_qualified_type (type,
16664 cp_type_quals (t) | cp_type_quals (type),
16665 complain | tf_ignore_bad_quals);
16668 case TYPE_ARGUMENT_PACK:
16669 case NONTYPE_ARGUMENT_PACK:
16670 return tsubst_argument_pack (t, args, complain, in_decl);
16672 case VOID_CST:
16673 case INTEGER_CST:
16674 case REAL_CST:
16675 case STRING_CST:
16676 case PLUS_EXPR:
16677 case MINUS_EXPR:
16678 case NEGATE_EXPR:
16679 case NOP_EXPR:
16680 case INDIRECT_REF:
16681 case ADDR_EXPR:
16682 case CALL_EXPR:
16683 case ARRAY_REF:
16684 case SCOPE_REF:
16685 /* We should use one of the expression tsubsts for these codes. */
16686 gcc_unreachable ();
16688 default:
16689 sorry ("use of %qs in template", get_tree_code_name (code));
16690 return error_mark_node;
16694 /* Convenience wrapper over tsubst for substituting into the LHS
16695 of the :: scope resolution operator. */
16697 static tree
16698 tsubst_scope (tree t, tree args, tsubst_flags_t complain, tree in_decl)
16700 gcc_checking_assert (TYPE_P (t));
16701 return tsubst (t, args, complain | tf_qualifying_scope, in_decl);
16704 /* OLDFNS is a lookup set of member functions from some class template, and
16705 NEWFNS is a lookup set of member functions from NEWTYPE, a specialization
16706 of that class template. Return the subset of NEWFNS which are
16707 specializations of a function from OLDFNS. */
16709 static tree
16710 filter_memfn_lookup (tree oldfns, tree newfns, tree newtype)
16712 /* Record all member functions from the old lookup set OLDFNS into
16713 VISIBLE_SET. */
16714 hash_set<tree> visible_set;
16715 bool seen_dep_using = false;
16716 for (tree fn : lkp_range (oldfns))
16718 if (TREE_CODE (fn) == USING_DECL)
16720 /* Imprecisely handle dependent using-decl by keeping all members
16721 in the new lookup set that are defined in a base class, i.e.
16722 members that could plausibly have been introduced by this
16723 dependent using-decl.
16724 FIXME: Track which members are introduced by a dependent
16725 using-decl precisely, perhaps by performing another lookup
16726 from the substituted USING_DECL_SCOPE. */
16727 gcc_checking_assert (DECL_DEPENDENT_P (fn));
16728 seen_dep_using = true;
16730 else
16731 visible_set.add (fn);
16734 /* Returns true iff (a less specialized version of) FN appeared in
16735 the old lookup set OLDFNS. */
16736 auto visible_p = [newtype, seen_dep_using, &visible_set] (tree fn) {
16737 if (DECL_CONTEXT (fn) != newtype)
16738 /* FN is a member function from a base class, introduced via a
16739 using-decl; if it might have been introduced by a dependent
16740 using-decl then just conservatively keep it, otherwise look
16741 in the old lookup set for FN exactly. */
16742 return seen_dep_using || visible_set.contains (fn);
16743 else if (TREE_CODE (fn) == TEMPLATE_DECL)
16744 /* FN is a member function template from the current class;
16745 look in the old lookup set for the TEMPLATE_DECL from which
16746 it was specialized. */
16747 return visible_set.contains (DECL_TI_TEMPLATE (fn));
16748 else
16749 /* FN is a non-template member function from the current class;
16750 look in the old lookup set for the FUNCTION_DECL from which
16751 it was specialized. */
16752 return visible_set.contains (DECL_TEMPLATE_RESULT
16753 (DECL_TI_TEMPLATE (fn)));
16756 bool lookup_changed_p = false;
16757 for (tree fn : lkp_range (newfns))
16758 if (!visible_p (fn))
16760 lookup_changed_p = true;
16761 break;
16763 if (!lookup_changed_p)
16764 return newfns;
16766 /* Filter out from NEWFNS the member functions that weren't
16767 previously visible according to OLDFNS. */
16768 tree filtered_fns = NULL_TREE;
16769 unsigned filtered_size = 0;
16770 for (tree fn : lkp_range (newfns))
16771 if (visible_p (fn))
16773 filtered_fns = lookup_add (fn, filtered_fns);
16774 filtered_size++;
16776 gcc_checking_assert (seen_dep_using
16777 ? filtered_size >= visible_set.elements ()
16778 : filtered_size == visible_set.elements ());
16780 return filtered_fns;
16783 /* tsubst a BASELINK. OBJECT_TYPE, if non-NULL, is the type of the
16784 expression on the left-hand side of the "." or "->" operator. We
16785 only do the lookup if we had a dependent BASELINK. Otherwise we
16786 adjust it onto the instantiated heirarchy. */
16788 static tree
16789 tsubst_baselink (tree baselink, tree object_type,
16790 tree args, tsubst_flags_t complain, tree in_decl)
16792 bool qualified_p = BASELINK_QUALIFIED_P (baselink);
16793 tree qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
16794 qualifying_scope = tsubst (qualifying_scope, args, complain, in_decl);
16796 tree optype = BASELINK_OPTYPE (baselink);
16797 optype = tsubst (optype, args, complain, in_decl);
16799 tree template_args = NULL_TREE;
16800 bool template_id_p = false;
16801 tree fns = BASELINK_FUNCTIONS (baselink);
16802 if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
16804 template_id_p = true;
16805 template_args = TREE_OPERAND (fns, 1);
16806 fns = TREE_OPERAND (fns, 0);
16807 if (template_args)
16808 template_args = tsubst_template_args (template_args, args,
16809 complain, in_decl);
16812 tree binfo_type = BINFO_TYPE (BASELINK_BINFO (baselink));
16813 binfo_type = tsubst (binfo_type, args, complain, in_decl);
16814 bool dependent_p = (binfo_type != BINFO_TYPE (BASELINK_BINFO (baselink))
16815 || optype != BASELINK_OPTYPE (baselink));
16817 if (dependent_p)
16819 tree name = OVL_NAME (fns);
16820 if (IDENTIFIER_CONV_OP_P (name))
16821 name = make_conv_op_name (optype);
16823 /* See maybe_dependent_member_ref. */
16824 if ((complain & tf_dguide) && dependent_scope_p (qualifying_scope))
16826 if (template_id_p)
16827 name = build2 (TEMPLATE_ID_EXPR, unknown_type_node, name,
16828 template_args);
16829 return build_qualified_name (NULL_TREE, qualifying_scope, name,
16830 /* ::template */false);
16833 if (name == complete_dtor_identifier)
16834 /* Treat as-if non-dependent below. */
16835 dependent_p = false;
16837 bool maybe_incomplete = BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (baselink);
16838 baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1,
16839 complain);
16840 if (maybe_incomplete)
16842 /* Filter out from the new lookup set those functions which didn't
16843 appear in the original lookup set (in a less specialized form).
16844 This is needed to preserve the consistency of member lookup
16845 performed in an incomplete-class context, within which
16846 later-declared members ought to remain invisible. */
16847 BASELINK_FUNCTIONS (baselink)
16848 = filter_memfn_lookup (fns, BASELINK_FUNCTIONS (baselink),
16849 binfo_type);
16850 BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (baselink) = true;
16853 if (!baselink)
16855 if ((complain & tf_error)
16856 && constructor_name_p (name, qualifying_scope))
16857 error ("cannot call constructor %<%T::%D%> directly",
16858 qualifying_scope, name);
16859 return error_mark_node;
16862 fns = BASELINK_FUNCTIONS (baselink);
16864 else
16866 /* We're going to overwrite pieces below, make a duplicate. */
16867 baselink = copy_node (baselink);
16869 if (qualifying_scope != BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink)))
16871 /* The decl we found was from non-dependent scope, but we still need
16872 to update the binfos for the instantiated qualifying_scope. */
16873 BASELINK_ACCESS_BINFO (baselink) = TYPE_BINFO (qualifying_scope);
16874 BASELINK_BINFO (baselink) = lookup_base (qualifying_scope, binfo_type,
16875 ba_unique, nullptr, complain);
16879 /* If lookup found a single function, mark it as used at this point.
16880 (If lookup found multiple functions the one selected later by
16881 overload resolution will be marked as used at that point.) */
16882 if (!template_id_p && !really_overloaded_fn (fns))
16884 tree fn = OVL_FIRST (fns);
16885 bool ok = mark_used (fn, complain);
16886 if (!ok && !(complain & tf_error))
16887 return error_mark_node;
16888 if (ok && BASELINK_P (baselink))
16889 /* We might have instantiated an auto function. */
16890 TREE_TYPE (baselink) = TREE_TYPE (fn);
16893 if (BASELINK_P (baselink))
16895 /* Add back the template arguments, if present. */
16896 if (template_id_p)
16897 BASELINK_FUNCTIONS (baselink)
16898 = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, template_args);
16900 /* Update the conversion operator type. */
16901 BASELINK_OPTYPE (baselink) = optype;
16904 if (!object_type)
16905 object_type = current_class_type;
16907 if (qualified_p || !dependent_p)
16909 baselink = adjust_result_of_qualified_name_lookup (baselink,
16910 qualifying_scope,
16911 object_type);
16912 if (!qualified_p)
16913 /* We need to call adjust_result_of_qualified_name_lookup in case the
16914 destructor names a base class, but we unset BASELINK_QUALIFIED_P
16915 so that we still get virtual function binding. */
16916 BASELINK_QUALIFIED_P (baselink) = false;
16919 return baselink;
16922 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID. DONE is
16923 true if the qualified-id will be a postfix-expression in-and-of
16924 itself; false if more of the postfix-expression follows the
16925 QUALIFIED_ID. ADDRESS_P is true if the qualified-id is the operand
16926 of "&". */
16928 static tree
16929 tsubst_qualified_id (tree qualified_id, tree args,
16930 tsubst_flags_t complain, tree in_decl,
16931 bool done, bool address_p)
16933 tree expr;
16934 tree scope;
16935 tree name;
16936 bool is_template;
16937 tree template_args;
16938 location_t loc = EXPR_LOCATION (qualified_id);
16940 gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
16942 /* Figure out what name to look up. */
16943 name = TREE_OPERAND (qualified_id, 1);
16944 if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
16946 is_template = true;
16947 template_args = TREE_OPERAND (name, 1);
16948 if (template_args)
16949 template_args = tsubst_template_args (template_args, args,
16950 complain, in_decl);
16951 if (template_args == error_mark_node)
16952 return error_mark_node;
16953 name = TREE_OPERAND (name, 0);
16955 else
16957 is_template = false;
16958 template_args = NULL_TREE;
16961 /* Substitute into the qualifying scope. When there are no ARGS, we
16962 are just trying to simplify a non-dependent expression. In that
16963 case the qualifying scope may be dependent, and, in any case,
16964 substituting will not help. */
16965 scope = TREE_OPERAND (qualified_id, 0);
16966 if (args)
16968 scope = tsubst_scope (scope, args, complain, in_decl);
16969 expr = tsubst_copy (name, args, complain, in_decl);
16971 else
16972 expr = name;
16974 if (dependent_scope_p (scope))
16976 if (TREE_CODE (expr) == SCOPE_REF)
16977 /* We built one in tsubst_baselink. */
16978 gcc_checking_assert (same_type_p (scope, TREE_OPERAND (expr, 0)));
16979 else
16981 if (is_template)
16982 expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr,
16983 template_args);
16984 expr = build_qualified_name (NULL_TREE, scope, expr,
16985 QUALIFIED_NAME_IS_TEMPLATE
16986 (qualified_id));
16988 REF_PARENTHESIZED_P (expr) = REF_PARENTHESIZED_P (qualified_id);
16989 return expr;
16992 if (!BASELINK_P (name) && !DECL_P (expr))
16994 if (TREE_CODE (expr) == BIT_NOT_EXPR)
16996 /* A BIT_NOT_EXPR is used to represent a destructor. */
16997 if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
16999 error ("qualifying type %qT does not match destructor name ~%qT",
17000 scope, TREE_OPERAND (expr, 0));
17001 expr = error_mark_node;
17003 else
17004 expr = lookup_qualified_name (scope, complete_dtor_identifier,
17005 LOOK_want::NORMAL, false);
17007 else
17008 expr = lookup_qualified_name (scope, expr, LOOK_want::NORMAL, false);
17009 if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
17010 ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
17012 if (complain & tf_error)
17014 error ("dependent-name %qE is parsed as a non-type, but "
17015 "instantiation yields a type", qualified_id);
17016 inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
17018 return error_mark_node;
17022 if (DECL_P (expr))
17024 if (!check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
17025 scope, complain))
17026 return error_mark_node;
17027 /* Remember that there was a reference to this entity. */
17028 if (!mark_used (expr, complain) && !(complain & tf_error))
17029 return error_mark_node;
17032 if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
17034 if (complain & tf_error)
17035 qualified_name_lookup_error (scope,
17036 TREE_OPERAND (qualified_id, 1),
17037 expr, input_location);
17038 return error_mark_node;
17041 if (is_template)
17043 /* We may be repeating a check already done during parsing, but
17044 if it was well-formed and passed then, it will pass again
17045 now, and if it didn't, we wouldn't have got here. The case
17046 we want to catch is when we couldn't tell then, and can now,
17047 namely when templ prior to substitution was an
17048 identifier. */
17049 if (flag_concepts && check_auto_in_tmpl_args (expr, template_args))
17050 return error_mark_node;
17052 if (variable_template_p (expr))
17053 expr = lookup_and_finish_template_variable (expr, template_args,
17054 complain);
17055 else
17056 expr = lookup_template_function (expr, template_args);
17059 if (expr == error_mark_node && complain & tf_error)
17060 qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
17061 expr, input_location);
17062 else if (TYPE_P (scope))
17064 expr = (adjust_result_of_qualified_name_lookup
17065 (expr, scope, current_nonlambda_class_type ()));
17066 expr = (finish_qualified_id_expr
17067 (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
17068 QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
17069 /*template_arg_p=*/false, complain));
17072 /* Expressions do not generally have reference type. */
17073 if (TREE_CODE (expr) != SCOPE_REF
17074 /* However, if we're about to form a pointer-to-member, we just
17075 want the referenced member referenced. */
17076 && TREE_CODE (expr) != OFFSET_REF)
17077 expr = convert_from_reference (expr);
17079 if (REF_PARENTHESIZED_P (qualified_id))
17080 expr = force_paren_expr (expr);
17082 expr = maybe_wrap_with_location (expr, loc);
17084 return expr;
17087 /* tsubst the initializer for a VAR_DECL. INIT is the unsubstituted
17088 initializer, DECL is the substituted VAR_DECL. Other arguments are as
17089 for tsubst. */
17091 static tree
17092 tsubst_init (tree init, tree decl, tree args,
17093 tsubst_flags_t complain, tree in_decl)
17095 if (!init)
17096 return NULL_TREE;
17098 init = tsubst_expr (init, args, complain, in_decl);
17100 tree type = TREE_TYPE (decl);
17102 if (!init && type != error_mark_node)
17104 if (tree auto_node = type_uses_auto (type))
17106 if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
17108 if (complain & tf_error)
17109 error ("initializer for %q#D expands to an empty list "
17110 "of expressions", decl);
17111 return error_mark_node;
17114 else if (!dependent_type_p (type))
17116 /* If we had an initializer but it
17117 instantiated to nothing,
17118 value-initialize the object. This will
17119 only occur when the initializer was a
17120 pack expansion where the parameter packs
17121 used in that expansion were of length
17122 zero. */
17123 init = build_value_init (type, complain);
17124 if (TREE_CODE (init) == AGGR_INIT_EXPR)
17125 init = get_target_expr (init, complain);
17126 if (TREE_CODE (init) == TARGET_EXPR)
17127 TARGET_EXPR_DIRECT_INIT_P (init) = true;
17131 return init;
17134 /* If T is a reference to a dependent member of the current instantiation C and
17135 we are trying to refer to that member in a partial instantiation of C,
17136 return a SCOPE_REF; otherwise, return NULL_TREE.
17138 This can happen when forming a C++17 deduction guide, as in PR96199. */
17140 static tree
17141 maybe_dependent_member_ref (tree t, tree args, tsubst_flags_t complain,
17142 tree in_decl)
17144 if (!(complain & tf_dguide))
17145 return NULL_TREE;
17147 tree decl = (t && TYPE_P (t)) ? TYPE_NAME (t) : t;
17148 if (!decl || !DECL_P (decl))
17149 return NULL_TREE;
17151 tree ctx = context_for_name_lookup (decl);
17152 if (!CLASS_TYPE_P (ctx))
17153 return NULL_TREE;
17155 ctx = tsubst (ctx, args, complain, in_decl);
17156 if (!dependent_scope_p (ctx))
17157 return NULL_TREE;
17159 if (TYPE_P (t))
17161 if (typedef_variant_p (t))
17162 t = strip_typedefs (t);
17163 tree decl = TYPE_NAME (t);
17164 if (decl)
17165 decl = maybe_dependent_member_ref (decl, args, complain, in_decl);
17166 if (!decl)
17167 return NULL_TREE;
17168 return cp_build_qualified_type (TREE_TYPE (decl), cp_type_quals (t),
17169 complain);
17172 tree name = DECL_NAME (t);
17173 tree fullname = name;
17174 if (instantiates_primary_template_p (t))
17176 tree tinfo = get_template_info (t);
17177 name = DECL_NAME (TI_TEMPLATE (tinfo));
17178 tree targs = INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo));
17179 targs = tsubst_template_args (targs, args, complain, in_decl);
17180 fullname = build_nt (TEMPLATE_ID_EXPR, name, targs);
17183 if (TREE_CODE (t) == TYPE_DECL)
17185 if (TREE_CODE (TREE_TYPE (t)) == TYPENAME_TYPE
17186 && TYPE_NAME (TREE_TYPE (t)) == t)
17187 /* The TYPE_DECL for a typename has DECL_CONTEXT of the typename
17188 scope, but it doesn't need to be rewritten again. */
17189 return NULL_TREE;
17190 tree type = build_typename_type (ctx, name, fullname, typename_type);
17191 return TYPE_NAME (type);
17193 else if (DECL_TYPE_TEMPLATE_P (t))
17194 return make_unbound_class_template (ctx, name,
17195 NULL_TREE, complain);
17196 else
17197 return build_qualified_name (NULL_TREE, ctx, fullname,
17198 TREE_CODE (t) == TEMPLATE_DECL);
17201 /* Like tsubst, but deals with expressions. This function just replaces
17202 template parms; to finish processing the resultant expression, use
17203 tsubst_copy_and_build or tsubst_expr. */
17205 static tree
17206 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
17208 enum tree_code code;
17209 tree r;
17211 if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
17212 return t;
17214 if (TYPE_P (t))
17215 return tsubst (t, args, complain, in_decl);
17217 if (tree d = maybe_dependent_member_ref (t, args, complain, in_decl))
17218 return d;
17220 code = TREE_CODE (t);
17222 switch (code)
17224 case PARM_DECL:
17225 r = retrieve_local_specialization (t);
17227 if (r == NULL_TREE)
17229 /* We get here for a use of 'this' in an NSDMI. */
17230 if (DECL_NAME (t) == this_identifier && current_class_ptr)
17231 return current_class_ptr;
17233 /* This can happen for a parameter name used later in a function
17234 declaration (such as in a late-specified return type). Just
17235 make a dummy decl, since it's only used for its type. */
17236 gcc_assert (cp_unevaluated_operand);
17237 r = tsubst_decl (t, args, complain);
17238 /* Give it the template pattern as its context; its true context
17239 hasn't been instantiated yet and this is good enough for
17240 mangling. */
17241 DECL_CONTEXT (r) = DECL_CONTEXT (t);
17244 if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
17245 r = argument_pack_select_arg (r);
17246 if (!mark_used (r, complain) && !(complain & tf_error))
17247 return error_mark_node;
17248 return r;
17250 case CONST_DECL:
17252 tree enum_type;
17253 tree v;
17255 if (DECL_TEMPLATE_PARM_P (t))
17256 return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
17257 if (!uses_template_parms (DECL_CONTEXT (t)))
17258 return t;
17260 /* Unfortunately, we cannot just call lookup_name here.
17261 Consider:
17263 template <int I> int f() {
17264 enum E { a = I };
17265 struct S { void g() { E e = a; } };
17268 When we instantiate f<7>::S::g(), say, lookup_name is not
17269 clever enough to find f<7>::a. */
17270 enum_type
17271 = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
17272 /*entering_scope=*/0);
17274 for (v = TYPE_VALUES (enum_type);
17275 v != NULL_TREE;
17276 v = TREE_CHAIN (v))
17277 if (TREE_PURPOSE (v) == DECL_NAME (t))
17278 return TREE_VALUE (v);
17280 /* We didn't find the name. That should never happen; if
17281 name-lookup found it during preliminary parsing, we
17282 should find it again here during instantiation. */
17283 gcc_unreachable ();
17285 return t;
17287 case FIELD_DECL:
17288 if (DECL_CONTEXT (t))
17290 tree ctx;
17292 ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
17293 /*entering_scope=*/1);
17294 if (ctx != DECL_CONTEXT (t))
17296 tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
17297 if (!r)
17299 if (complain & tf_error)
17300 error ("using invalid field %qD", t);
17301 return error_mark_node;
17303 return r;
17307 return t;
17309 case VAR_DECL:
17310 case FUNCTION_DECL:
17311 if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
17312 r = tsubst (t, args, complain, in_decl);
17313 else if (DECL_LOCAL_DECL_P (t))
17315 /* Local specialization will usually have been created when
17316 we instantiated the DECL_EXPR_DECL. */
17317 r = retrieve_local_specialization (t);
17318 if (!r)
17320 /* We're in a generic lambda referencing a local extern
17321 from an outer block-scope of a non-template. */
17322 gcc_checking_assert (LAMBDA_FUNCTION_P (current_function_decl));
17323 r = t;
17326 else if (local_variable_p (t)
17327 && uses_template_parms (DECL_CONTEXT (t)))
17329 r = retrieve_local_specialization (t);
17330 if (r == NULL_TREE)
17332 /* First try name lookup to find the instantiation. */
17333 r = lookup_name (DECL_NAME (t));
17334 if (r)
17336 if (!VAR_P (r))
17338 /* During error-recovery we may find a non-variable,
17339 even an OVERLOAD: just bail out and avoid ICEs and
17340 duplicate diagnostics (c++/62207). */
17341 gcc_assert (seen_error ());
17342 return error_mark_node;
17344 if (!is_capture_proxy (r))
17346 /* Make sure the one we found is the one we want. */
17347 tree ctx = enclosing_instantiation_of (DECL_CONTEXT (t));
17348 if (ctx != DECL_CONTEXT (r))
17349 r = NULL_TREE;
17353 if (r)
17354 /* OK */;
17355 else
17357 /* This can happen for a variable used in a
17358 late-specified return type of a local lambda, or for a
17359 local static or constant. Building a new VAR_DECL
17360 should be OK in all those cases. */
17361 r = tsubst_decl (t, args, complain);
17362 if (local_specializations)
17363 /* Avoid infinite recursion (79640). */
17364 register_local_specialization (r, t);
17365 if (decl_maybe_constant_var_p (r))
17367 /* We can't call cp_finish_decl, so handle the
17368 initializer by hand. */
17369 tree init = tsubst_init (DECL_INITIAL (t), r, args,
17370 complain, in_decl);
17371 if (!processing_template_decl)
17372 init = maybe_constant_init (init);
17373 if (processing_template_decl
17374 ? potential_constant_expression (init)
17375 : reduced_constant_expression_p (init))
17376 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
17377 = TREE_CONSTANT (r) = true;
17378 DECL_INITIAL (r) = init;
17379 if (tree auto_node = type_uses_auto (TREE_TYPE (r)))
17380 TREE_TYPE (r)
17381 = do_auto_deduction (TREE_TYPE (r), init, auto_node,
17382 complain, adc_variable_type);
17384 gcc_assert (cp_unevaluated_operand
17385 || processing_contract_condition
17386 || TREE_STATIC (r)
17387 || decl_constant_var_p (r)
17388 || seen_error ());
17389 if (!processing_template_decl
17390 && !TREE_STATIC (r))
17391 r = process_outer_var_ref (r, complain);
17393 /* Remember this for subsequent uses. */
17394 if (local_specializations)
17395 register_local_specialization (r, t);
17397 if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
17398 r = argument_pack_select_arg (r);
17400 else
17401 r = t;
17402 if (!mark_used (r, complain))
17403 return error_mark_node;
17404 return r;
17406 case NAMESPACE_DECL:
17407 return t;
17409 case OVERLOAD:
17410 return t;
17412 case BASELINK:
17413 return tsubst_baselink (t, current_nonlambda_class_type (),
17414 args, complain, in_decl);
17416 case TEMPLATE_DECL:
17417 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
17418 return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
17419 args, complain, in_decl);
17420 else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
17421 return tsubst (t, args, complain, in_decl);
17422 else if (DECL_CLASS_SCOPE_P (t)
17423 && uses_template_parms (DECL_CONTEXT (t)))
17425 /* Template template argument like the following example need
17426 special treatment:
17428 template <template <class> class TT> struct C {};
17429 template <class T> struct D {
17430 template <class U> struct E {};
17431 C<E> c; // #1
17433 D<int> d; // #2
17435 We are processing the template argument `E' in #1 for
17436 the template instantiation #2. Originally, `E' is a
17437 TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT. Now we
17438 have to substitute this with one having context `D<int>'. */
17440 tree context = tsubst_aggr_type (DECL_CONTEXT (t), args, complain,
17441 in_decl, /*entering_scope=*/true);
17442 return lookup_field (context, DECL_NAME(t), 0, false);
17444 else
17445 /* Ordinary template template argument. */
17446 return t;
17448 case NON_LVALUE_EXPR:
17449 case VIEW_CONVERT_EXPR:
17451 /* Handle location wrappers by substituting the wrapped node
17452 first, *then* reusing the resulting type. Doing the type
17453 first ensures that we handle template parameters and
17454 parameter pack expansions. */
17455 if (location_wrapper_p (t))
17457 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args,
17458 complain, in_decl);
17459 return maybe_wrap_with_location (op0, EXPR_LOCATION (t));
17461 tree op = TREE_OPERAND (t, 0);
17462 /* force_paren_expr can also create a VIEW_CONVERT_EXPR. */
17463 if (code == VIEW_CONVERT_EXPR && REF_PARENTHESIZED_P (t))
17465 op = tsubst_copy (op, args, complain, in_decl);
17466 op = build1 (code, TREE_TYPE (op), op);
17467 REF_PARENTHESIZED_P (op) = true;
17468 return op;
17470 /* We shouldn't see any other uses of these in templates
17471 (tsubst_copy_and_build handles C++20 tparm object wrappers). */
17472 gcc_unreachable ();
17475 case CAST_EXPR:
17476 case REINTERPRET_CAST_EXPR:
17477 case CONST_CAST_EXPR:
17478 case STATIC_CAST_EXPR:
17479 case DYNAMIC_CAST_EXPR:
17480 case IMPLICIT_CONV_EXPR:
17481 CASE_CONVERT:
17483 tsubst_flags_t tcomplain = complain;
17484 if (code == CAST_EXPR)
17485 tcomplain |= tf_tst_ok;
17486 tree type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
17487 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17488 return build1 (code, type, op0);
17491 case BIT_CAST_EXPR:
17493 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17494 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17495 r = build_min (BIT_CAST_EXPR, type, op0);
17496 SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
17497 return r;
17500 case SIZEOF_EXPR:
17501 if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
17502 || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
17504 tree expanded, op = TREE_OPERAND (t, 0);
17505 int len = 0;
17507 if (SIZEOF_EXPR_TYPE_P (t))
17508 op = TREE_TYPE (op);
17510 ++cp_unevaluated_operand;
17511 ++c_inhibit_evaluation_warnings;
17512 /* We only want to compute the number of arguments. */
17513 if (PACK_EXPANSION_P (op))
17514 expanded = tsubst_pack_expansion (op, args, complain, in_decl);
17515 else
17516 expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
17517 args, complain, in_decl);
17518 --cp_unevaluated_operand;
17519 --c_inhibit_evaluation_warnings;
17521 if (TREE_CODE (expanded) == TREE_VEC)
17523 len = TREE_VEC_LENGTH (expanded);
17524 /* Set TREE_USED for the benefit of -Wunused. */
17525 for (int i = 0; i < len; i++)
17526 if (DECL_P (TREE_VEC_ELT (expanded, i)))
17527 TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
17530 if (expanded == error_mark_node)
17531 return error_mark_node;
17532 else if (PACK_EXPANSION_P (expanded)
17533 || (TREE_CODE (expanded) == TREE_VEC
17534 && pack_expansion_args_count (expanded)))
17537 if (PACK_EXPANSION_P (expanded))
17538 /* OK. */;
17539 else if (TREE_VEC_LENGTH (expanded) == 1)
17540 expanded = TREE_VEC_ELT (expanded, 0);
17541 else
17542 expanded = make_argument_pack (expanded);
17544 if (TYPE_P (expanded))
17545 return cxx_sizeof_or_alignof_type (input_location,
17546 expanded, SIZEOF_EXPR,
17547 false,
17548 complain & tf_error);
17549 else
17550 return cxx_sizeof_or_alignof_expr (input_location,
17551 expanded, SIZEOF_EXPR,
17552 false,
17553 complain & tf_error);
17555 else
17556 return build_int_cst (size_type_node, len);
17558 if (SIZEOF_EXPR_TYPE_P (t))
17560 r = tsubst (TREE_TYPE (TREE_OPERAND (t, 0)),
17561 args, complain, in_decl);
17562 r = build1 (NOP_EXPR, r, error_mark_node);
17563 r = build1 (SIZEOF_EXPR,
17564 tsubst (TREE_TYPE (t), args, complain, in_decl), r);
17565 SIZEOF_EXPR_TYPE_P (r) = 1;
17566 return r;
17568 /* Fall through */
17570 case INDIRECT_REF:
17571 case NEGATE_EXPR:
17572 case TRUTH_NOT_EXPR:
17573 case BIT_NOT_EXPR:
17574 case ADDR_EXPR:
17575 case UNARY_PLUS_EXPR: /* Unary + */
17576 case ALIGNOF_EXPR:
17577 case AT_ENCODE_EXPR:
17578 case ARROW_EXPR:
17579 case THROW_EXPR:
17580 case TYPEID_EXPR:
17581 case REALPART_EXPR:
17582 case IMAGPART_EXPR:
17583 case PAREN_EXPR:
17585 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17586 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17587 r = build1_loc (EXPR_LOCATION (t), code, type, op0);
17588 if (code == ALIGNOF_EXPR)
17589 ALIGNOF_EXPR_STD_P (r) = ALIGNOF_EXPR_STD_P (t);
17590 /* For addresses of immediate functions ensure we have EXPR_LOCATION
17591 set for possible later diagnostics. */
17592 if (code == ADDR_EXPR
17593 && EXPR_LOCATION (r) == UNKNOWN_LOCATION
17594 && TREE_CODE (op0) == FUNCTION_DECL
17595 && DECL_IMMEDIATE_FUNCTION_P (op0))
17596 SET_EXPR_LOCATION (r, input_location);
17597 return r;
17600 case EXCESS_PRECISION_EXPR:
17602 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17603 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17604 if (TREE_CODE (op0) == EXCESS_PRECISION_EXPR)
17606 gcc_checking_assert (same_type_p (type, TREE_TYPE (op0)));
17607 return op0;
17609 return build1_loc (EXPR_LOCATION (t), code, type, op0);
17612 case COMPONENT_REF:
17614 tree object;
17615 tree name;
17617 object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17618 name = TREE_OPERAND (t, 1);
17619 if (TREE_CODE (name) == BIT_NOT_EXPR)
17621 name = tsubst_copy (TREE_OPERAND (name, 0), args,
17622 complain, in_decl);
17623 name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
17625 else if (TREE_CODE (name) == SCOPE_REF
17626 && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
17628 tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
17629 complain, in_decl);
17630 name = TREE_OPERAND (name, 1);
17631 name = tsubst_copy (TREE_OPERAND (name, 0), args,
17632 complain, in_decl);
17633 name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
17634 name = build_qualified_name (/*type=*/NULL_TREE,
17635 base, name,
17636 /*template_p=*/false);
17638 else if (BASELINK_P (name))
17639 name = tsubst_baselink (name,
17640 non_reference (TREE_TYPE (object)),
17641 args, complain,
17642 in_decl);
17643 else
17644 name = tsubst_copy (name, args, complain, in_decl);
17645 return build_nt (COMPONENT_REF, object, name, NULL_TREE);
17648 case PLUS_EXPR:
17649 case MINUS_EXPR:
17650 case MULT_EXPR:
17651 case TRUNC_DIV_EXPR:
17652 case CEIL_DIV_EXPR:
17653 case FLOOR_DIV_EXPR:
17654 case ROUND_DIV_EXPR:
17655 case EXACT_DIV_EXPR:
17656 case BIT_AND_EXPR:
17657 case BIT_IOR_EXPR:
17658 case BIT_XOR_EXPR:
17659 case TRUNC_MOD_EXPR:
17660 case FLOOR_MOD_EXPR:
17661 case TRUTH_ANDIF_EXPR:
17662 case TRUTH_ORIF_EXPR:
17663 case TRUTH_AND_EXPR:
17664 case TRUTH_OR_EXPR:
17665 case RSHIFT_EXPR:
17666 case LSHIFT_EXPR:
17667 case EQ_EXPR:
17668 case NE_EXPR:
17669 case MAX_EXPR:
17670 case MIN_EXPR:
17671 case LE_EXPR:
17672 case GE_EXPR:
17673 case LT_EXPR:
17674 case GT_EXPR:
17675 case COMPOUND_EXPR:
17676 case DOTSTAR_EXPR:
17677 case MEMBER_REF:
17678 case PREDECREMENT_EXPR:
17679 case PREINCREMENT_EXPR:
17680 case POSTDECREMENT_EXPR:
17681 case POSTINCREMENT_EXPR:
17683 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17684 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17685 return build_nt (code, op0, op1);
17688 case SCOPE_REF:
17690 tree op0 = tsubst_scope (TREE_OPERAND (t, 0), args, complain, in_decl);
17691 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17692 return build_qualified_name (/*type=*/NULL_TREE, op0, op1,
17693 QUALIFIED_NAME_IS_TEMPLATE (t));
17696 case ARRAY_REF:
17698 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17699 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17700 return build_nt (ARRAY_REF, op0, op1, NULL_TREE, NULL_TREE);
17703 case CALL_EXPR:
17705 int n = VL_EXP_OPERAND_LENGTH (t);
17706 tree result = build_vl_exp (CALL_EXPR, n);
17707 int i;
17708 for (i = 0; i < n; i++)
17709 TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
17710 complain, in_decl);
17711 return result;
17714 case COND_EXPR:
17715 case MODOP_EXPR:
17716 case PSEUDO_DTOR_EXPR:
17717 case VEC_PERM_EXPR:
17719 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17720 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17721 tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
17722 r = build_nt (code, op0, op1, op2);
17723 copy_warning (r, t);
17724 return r;
17727 case NEW_EXPR:
17729 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17730 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17731 tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
17732 r = build_nt (code, op0, op1, op2);
17733 NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
17734 return r;
17737 case DELETE_EXPR:
17739 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17740 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17741 r = build_nt (code, op0, op1);
17742 DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
17743 DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
17744 return r;
17747 case TEMPLATE_ID_EXPR:
17749 /* Substituted template arguments */
17750 tree tmpl = TREE_OPERAND (t, 0);
17751 tree targs = TREE_OPERAND (t, 1);
17753 tmpl = tsubst_copy (tmpl, args, complain, in_decl);
17754 if (targs)
17755 targs = tsubst_template_args (targs, args, complain, in_decl);
17757 if (variable_template_p (tmpl))
17758 return lookup_template_variable (tmpl, targs);
17759 else
17760 return lookup_template_function (tmpl, targs);
17763 case TREE_LIST:
17765 tree purpose, value, chain;
17767 if (t == void_list_node)
17768 return t;
17770 purpose = TREE_PURPOSE (t);
17771 if (purpose)
17772 purpose = tsubst_copy (purpose, args, complain, in_decl);
17773 value = TREE_VALUE (t);
17774 if (value)
17775 value = tsubst_copy (value, args, complain, in_decl);
17776 chain = TREE_CHAIN (t);
17777 if (chain && chain != void_type_node)
17778 chain = tsubst_copy (chain, args, complain, in_decl);
17779 if (purpose == TREE_PURPOSE (t)
17780 && value == TREE_VALUE (t)
17781 && chain == TREE_CHAIN (t))
17782 return t;
17783 return tree_cons (purpose, value, chain);
17786 case TEMPLATE_PARM_INDEX:
17787 case TYPE_DECL:
17788 return tsubst (t, args, complain, in_decl);
17790 case USING_DECL:
17791 t = DECL_NAME (t);
17792 /* Fall through. */
17793 case IDENTIFIER_NODE:
17794 if (IDENTIFIER_CONV_OP_P (t))
17796 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17797 return make_conv_op_name (new_type);
17799 else
17800 return t;
17802 case CONSTRUCTOR:
17803 /* This is handled by tsubst_copy_and_build. */
17804 gcc_unreachable ();
17806 case VA_ARG_EXPR:
17808 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17809 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17810 return build_x_va_arg (EXPR_LOCATION (t), op0, type);
17813 case CLEANUP_POINT_EXPR:
17814 /* We shouldn't have built any of these during initial template
17815 generation. Instead, they should be built during instantiation
17816 in response to the saved STMT_IS_FULL_EXPR_P setting. */
17817 gcc_unreachable ();
17819 case OFFSET_REF:
17821 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17822 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17823 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17824 r = build2 (code, type, op0, op1);
17825 PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
17826 if (!mark_used (TREE_OPERAND (r, 1), complain)
17827 && !(complain & tf_error))
17828 return error_mark_node;
17829 return r;
17832 case EXPR_PACK_EXPANSION:
17833 error ("invalid use of pack expansion expression");
17834 return error_mark_node;
17836 case NONTYPE_ARGUMENT_PACK:
17837 error ("use %<...%> to expand argument pack");
17838 return error_mark_node;
17840 case VOID_CST:
17841 gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
17842 return t;
17844 case INTEGER_CST:
17845 case REAL_CST:
17846 case COMPLEX_CST:
17847 case VECTOR_CST:
17849 /* Instantiate any typedefs in the type. */
17850 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17851 r = fold_convert (type, t);
17852 gcc_assert (TREE_CODE (r) == code);
17853 return r;
17856 case STRING_CST:
17858 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17859 r = t;
17860 if (type != TREE_TYPE (t))
17862 r = copy_node (t);
17863 TREE_TYPE (r) = type;
17865 return r;
17868 case PTRMEM_CST:
17869 /* These can sometimes show up in a partial instantiation, but never
17870 involve template parms. */
17871 gcc_assert (!uses_template_parms (t));
17872 return t;
17874 case UNARY_LEFT_FOLD_EXPR:
17875 return tsubst_unary_left_fold (t, args, complain, in_decl);
17876 case UNARY_RIGHT_FOLD_EXPR:
17877 return tsubst_unary_right_fold (t, args, complain, in_decl);
17878 case BINARY_LEFT_FOLD_EXPR:
17879 return tsubst_binary_left_fold (t, args, complain, in_decl);
17880 case BINARY_RIGHT_FOLD_EXPR:
17881 return tsubst_binary_right_fold (t, args, complain, in_decl);
17882 case PREDICT_EXPR:
17883 return t;
17885 case DEBUG_BEGIN_STMT:
17886 /* ??? There's no point in copying it for now, but maybe some
17887 day it will contain more information, such as a pointer back
17888 to the containing function, inlined copy or so. */
17889 return t;
17891 case CO_AWAIT_EXPR:
17892 return tsubst_expr (t, args, complain, in_decl);
17894 default:
17895 /* We shouldn't get here, but keep going if !flag_checking. */
17896 if (flag_checking)
17897 gcc_unreachable ();
17898 return t;
17902 /* Helper function for tsubst_omp_clauses, used for instantiation of
17903 OMP_CLAUSE_DECL of clauses. */
17905 static tree
17906 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
17907 tree in_decl, tree *iterator_cache)
17909 if (decl == NULL_TREE || decl == ridpointers[RID_OMP_ALL_MEMORY])
17910 return decl;
17912 /* Handle OpenMP iterators. */
17913 if (TREE_CODE (decl) == TREE_LIST
17914 && TREE_PURPOSE (decl)
17915 && TREE_CODE (TREE_PURPOSE (decl)) == TREE_VEC)
17917 tree ret;
17918 if (iterator_cache[0] == TREE_PURPOSE (decl))
17919 ret = iterator_cache[1];
17920 else
17922 tree *tp = &ret;
17923 begin_scope (sk_omp, NULL);
17924 for (tree it = TREE_PURPOSE (decl); it; it = TREE_CHAIN (it))
17926 *tp = copy_node (it);
17927 TREE_VEC_ELT (*tp, 0)
17928 = tsubst_decl (TREE_VEC_ELT (it, 0), args, complain);
17929 DECL_CONTEXT (TREE_VEC_ELT (*tp, 0)) = current_function_decl;
17930 pushdecl (TREE_VEC_ELT (*tp, 0));
17931 TREE_VEC_ELT (*tp, 1)
17932 = tsubst_expr (TREE_VEC_ELT (it, 1), args, complain, in_decl);
17933 TREE_VEC_ELT (*tp, 2)
17934 = tsubst_expr (TREE_VEC_ELT (it, 2), args, complain, in_decl);
17935 TREE_VEC_ELT (*tp, 3)
17936 = tsubst_expr (TREE_VEC_ELT (it, 3), args, complain, in_decl);
17937 TREE_CHAIN (*tp) = NULL_TREE;
17938 tp = &TREE_CHAIN (*tp);
17940 TREE_VEC_ELT (ret, 5) = poplevel (1, 1, 0);
17941 iterator_cache[0] = TREE_PURPOSE (decl);
17942 iterator_cache[1] = ret;
17944 return build_tree_list (ret, tsubst_omp_clause_decl (TREE_VALUE (decl),
17945 args, complain,
17946 in_decl, NULL));
17949 /* Handle an OpenMP array section represented as a TREE_LIST (or
17950 OMP_CLAUSE_DOACROSS_KIND). An OMP_CLAUSE_DOACROSS (with a depend
17951 kind of OMP_CLAUSE_DOACROSS_SINK) can also be represented as a
17952 TREE_LIST. We can handle it exactly the same as an array section
17953 (purpose, value, and a chain), even though the nomenclature
17954 (low_bound, length, etc) is different. */
17955 if (TREE_CODE (decl) == TREE_LIST)
17957 tree low_bound
17958 = tsubst_expr (TREE_PURPOSE (decl), args, complain, in_decl);
17959 tree length = tsubst_expr (TREE_VALUE (decl), args, complain, in_decl);
17960 tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
17961 in_decl, NULL);
17962 if (TREE_PURPOSE (decl) == low_bound
17963 && TREE_VALUE (decl) == length
17964 && TREE_CHAIN (decl) == chain)
17965 return decl;
17966 tree ret = tree_cons (low_bound, length, chain);
17967 OMP_CLAUSE_DOACROSS_SINK_NEGATIVE (ret)
17968 = OMP_CLAUSE_DOACROSS_SINK_NEGATIVE (decl);
17969 return ret;
17971 tree ret = tsubst_expr (decl, args, complain, in_decl);
17972 /* Undo convert_from_reference tsubst_expr could have called. */
17973 if (decl
17974 && REFERENCE_REF_P (ret)
17975 && !REFERENCE_REF_P (decl))
17976 ret = TREE_OPERAND (ret, 0);
17977 return ret;
17980 /* Like tsubst_copy, but specifically for OpenMP clauses. */
17982 static tree
17983 tsubst_omp_clauses (tree clauses, enum c_omp_region_type ort,
17984 tree args, tsubst_flags_t complain, tree in_decl)
17986 tree new_clauses = NULL_TREE, nc, oc;
17987 tree linear_no_step = NULL_TREE;
17988 tree iterator_cache[2] = { NULL_TREE, NULL_TREE };
17990 for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
17992 nc = copy_node (oc);
17993 OMP_CLAUSE_CHAIN (nc) = new_clauses;
17994 new_clauses = nc;
17996 switch (OMP_CLAUSE_CODE (nc))
17998 case OMP_CLAUSE_LASTPRIVATE:
17999 if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
18001 OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
18002 tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args,
18003 complain, in_decl);
18004 OMP_CLAUSE_LASTPRIVATE_STMT (nc)
18005 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
18007 /* FALLTHRU */
18008 case OMP_CLAUSE_PRIVATE:
18009 case OMP_CLAUSE_SHARED:
18010 case OMP_CLAUSE_FIRSTPRIVATE:
18011 case OMP_CLAUSE_COPYIN:
18012 case OMP_CLAUSE_COPYPRIVATE:
18013 case OMP_CLAUSE_UNIFORM:
18014 case OMP_CLAUSE_DEPEND:
18015 case OMP_CLAUSE_DOACROSS:
18016 case OMP_CLAUSE_AFFINITY:
18017 case OMP_CLAUSE_FROM:
18018 case OMP_CLAUSE_TO:
18019 case OMP_CLAUSE_MAP:
18020 case OMP_CLAUSE__CACHE_:
18021 case OMP_CLAUSE_NONTEMPORAL:
18022 case OMP_CLAUSE_USE_DEVICE_PTR:
18023 case OMP_CLAUSE_USE_DEVICE_ADDR:
18024 case OMP_CLAUSE_IS_DEVICE_PTR:
18025 case OMP_CLAUSE_HAS_DEVICE_ADDR:
18026 case OMP_CLAUSE_INCLUSIVE:
18027 case OMP_CLAUSE_EXCLUSIVE:
18028 OMP_CLAUSE_DECL (nc)
18029 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
18030 in_decl, iterator_cache);
18031 break;
18032 case OMP_CLAUSE_NUM_TEAMS:
18033 if (OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (oc))
18034 OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (nc)
18035 = tsubst_expr (OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (oc), args,
18036 complain, in_decl);
18037 /* FALLTHRU */
18038 case OMP_CLAUSE_TILE:
18039 case OMP_CLAUSE_IF:
18040 case OMP_CLAUSE_NUM_THREADS:
18041 case OMP_CLAUSE_SCHEDULE:
18042 case OMP_CLAUSE_COLLAPSE:
18043 case OMP_CLAUSE_FINAL:
18044 case OMP_CLAUSE_DEVICE:
18045 case OMP_CLAUSE_DIST_SCHEDULE:
18046 case OMP_CLAUSE_THREAD_LIMIT:
18047 case OMP_CLAUSE_SAFELEN:
18048 case OMP_CLAUSE_SIMDLEN:
18049 case OMP_CLAUSE_NUM_TASKS:
18050 case OMP_CLAUSE_GRAINSIZE:
18051 case OMP_CLAUSE_PRIORITY:
18052 case OMP_CLAUSE_ORDERED:
18053 case OMP_CLAUSE_HINT:
18054 case OMP_CLAUSE_FILTER:
18055 case OMP_CLAUSE_NUM_GANGS:
18056 case OMP_CLAUSE_NUM_WORKERS:
18057 case OMP_CLAUSE_VECTOR_LENGTH:
18058 case OMP_CLAUSE_WORKER:
18059 case OMP_CLAUSE_VECTOR:
18060 case OMP_CLAUSE_ASYNC:
18061 case OMP_CLAUSE_WAIT:
18062 case OMP_CLAUSE_DETACH:
18063 OMP_CLAUSE_OPERAND (nc, 0)
18064 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, in_decl);
18065 break;
18066 case OMP_CLAUSE_REDUCTION:
18067 case OMP_CLAUSE_IN_REDUCTION:
18068 case OMP_CLAUSE_TASK_REDUCTION:
18069 if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
18071 tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
18072 if (TREE_CODE (placeholder) == SCOPE_REF)
18074 tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
18075 complain, in_decl);
18076 OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
18077 = build_qualified_name (NULL_TREE, scope,
18078 TREE_OPERAND (placeholder, 1),
18079 false);
18081 else
18082 gcc_assert (identifier_p (placeholder));
18084 OMP_CLAUSE_DECL (nc)
18085 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
18086 in_decl, NULL);
18087 break;
18088 case OMP_CLAUSE_GANG:
18089 case OMP_CLAUSE_ALIGNED:
18090 OMP_CLAUSE_DECL (nc)
18091 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
18092 in_decl, NULL);
18093 OMP_CLAUSE_OPERAND (nc, 1)
18094 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain, in_decl);
18095 break;
18096 case OMP_CLAUSE_ALLOCATE:
18097 OMP_CLAUSE_DECL (nc)
18098 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
18099 in_decl, NULL);
18100 OMP_CLAUSE_OPERAND (nc, 1)
18101 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain, in_decl);
18102 OMP_CLAUSE_OPERAND (nc, 2)
18103 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 2), args, complain, in_decl);
18104 break;
18105 case OMP_CLAUSE_LINEAR:
18106 OMP_CLAUSE_DECL (nc)
18107 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
18108 in_decl, NULL);
18109 if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
18111 gcc_assert (!linear_no_step);
18112 linear_no_step = nc;
18114 else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
18115 OMP_CLAUSE_LINEAR_STEP (nc)
18116 = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
18117 complain, in_decl, NULL);
18118 else
18119 OMP_CLAUSE_LINEAR_STEP (nc)
18120 = tsubst_expr (OMP_CLAUSE_LINEAR_STEP (oc), args,
18121 complain, in_decl);
18122 break;
18123 case OMP_CLAUSE_NOWAIT:
18124 case OMP_CLAUSE_DEFAULT:
18125 case OMP_CLAUSE_UNTIED:
18126 case OMP_CLAUSE_MERGEABLE:
18127 case OMP_CLAUSE_INBRANCH:
18128 case OMP_CLAUSE_NOTINBRANCH:
18129 case OMP_CLAUSE_PROC_BIND:
18130 case OMP_CLAUSE_FOR:
18131 case OMP_CLAUSE_PARALLEL:
18132 case OMP_CLAUSE_SECTIONS:
18133 case OMP_CLAUSE_TASKGROUP:
18134 case OMP_CLAUSE_NOGROUP:
18135 case OMP_CLAUSE_THREADS:
18136 case OMP_CLAUSE_SIMD:
18137 case OMP_CLAUSE_DEFAULTMAP:
18138 case OMP_CLAUSE_ORDER:
18139 case OMP_CLAUSE_BIND:
18140 case OMP_CLAUSE_INDEPENDENT:
18141 case OMP_CLAUSE_AUTO:
18142 case OMP_CLAUSE_SEQ:
18143 case OMP_CLAUSE_IF_PRESENT:
18144 case OMP_CLAUSE_FINALIZE:
18145 case OMP_CLAUSE_NOHOST:
18146 break;
18147 default:
18148 gcc_unreachable ();
18150 if ((ort & C_ORT_OMP_DECLARE_SIMD) == C_ORT_OMP)
18151 switch (OMP_CLAUSE_CODE (nc))
18153 case OMP_CLAUSE_SHARED:
18154 case OMP_CLAUSE_PRIVATE:
18155 case OMP_CLAUSE_FIRSTPRIVATE:
18156 case OMP_CLAUSE_LASTPRIVATE:
18157 case OMP_CLAUSE_COPYPRIVATE:
18158 case OMP_CLAUSE_LINEAR:
18159 case OMP_CLAUSE_REDUCTION:
18160 case OMP_CLAUSE_IN_REDUCTION:
18161 case OMP_CLAUSE_TASK_REDUCTION:
18162 case OMP_CLAUSE_USE_DEVICE_PTR:
18163 case OMP_CLAUSE_USE_DEVICE_ADDR:
18164 case OMP_CLAUSE_IS_DEVICE_PTR:
18165 case OMP_CLAUSE_HAS_DEVICE_ADDR:
18166 case OMP_CLAUSE_INCLUSIVE:
18167 case OMP_CLAUSE_EXCLUSIVE:
18168 case OMP_CLAUSE_ALLOCATE:
18169 /* tsubst_expr on SCOPE_REF results in returning
18170 finish_non_static_data_member result. Undo that here. */
18171 if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
18172 && (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
18173 == IDENTIFIER_NODE))
18175 tree t = OMP_CLAUSE_DECL (nc);
18176 tree v = t;
18177 while (v)
18178 switch (TREE_CODE (v))
18180 case COMPONENT_REF:
18181 case MEM_REF:
18182 case INDIRECT_REF:
18183 CASE_CONVERT:
18184 case POINTER_PLUS_EXPR:
18185 v = TREE_OPERAND (v, 0);
18186 continue;
18187 case PARM_DECL:
18188 if (DECL_CONTEXT (v) == current_function_decl
18189 && DECL_ARTIFICIAL (v)
18190 && DECL_NAME (v) == this_identifier)
18191 OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
18192 /* FALLTHRU */
18193 default:
18194 v = NULL_TREE;
18195 break;
18198 else if (VAR_P (OMP_CLAUSE_DECL (oc))
18199 && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
18200 && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
18201 && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
18202 && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
18204 tree decl = OMP_CLAUSE_DECL (nc);
18205 if (VAR_P (decl))
18207 retrofit_lang_decl (decl);
18208 DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
18211 break;
18212 default:
18213 break;
18217 new_clauses = nreverse (new_clauses);
18218 if (ort != C_ORT_OMP_DECLARE_SIMD)
18220 new_clauses = finish_omp_clauses (new_clauses, ort);
18221 if (linear_no_step)
18222 for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
18223 if (nc == linear_no_step)
18225 OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
18226 break;
18229 return new_clauses;
18232 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes. */
18234 static tree
18235 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
18236 tree in_decl)
18238 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
18240 tree purpose, value, chain;
18242 if (t == NULL)
18243 return t;
18245 if (TREE_CODE (t) != TREE_LIST)
18246 return tsubst_copy_and_build (t, args, complain, in_decl);
18248 if (t == void_list_node)
18249 return t;
18251 purpose = TREE_PURPOSE (t);
18252 if (purpose)
18253 purpose = RECUR (purpose);
18254 value = TREE_VALUE (t);
18255 if (value)
18257 if (TREE_CODE (value) != LABEL_DECL)
18258 value = RECUR (value);
18259 else
18261 value = lookup_label (DECL_NAME (value));
18262 gcc_assert (TREE_CODE (value) == LABEL_DECL);
18263 TREE_USED (value) = 1;
18266 chain = TREE_CHAIN (t);
18267 if (chain && chain != void_type_node)
18268 chain = RECUR (chain);
18269 return tree_cons (purpose, value, chain);
18270 #undef RECUR
18273 /* Used to temporarily communicate the list of #pragma omp parallel
18274 clauses to #pragma omp for instantiation if they are combined
18275 together. */
18277 static tree *omp_parallel_combined_clauses;
18279 static tree tsubst_decomp_names (tree, tree, tree, tsubst_flags_t, tree,
18280 tree *, unsigned int *);
18282 /* Substitute one OMP_FOR iterator. */
18284 static bool
18285 tsubst_omp_for_iterator (tree t, int i, tree declv, tree &orig_declv,
18286 tree initv, tree condv, tree incrv, tree *clauses,
18287 tree args, tsubst_flags_t complain, tree in_decl)
18289 #define RECUR(NODE) \
18290 tsubst_expr ((NODE), args, complain, in_decl)
18291 tree decl, init, cond = NULL_TREE, incr = NULL_TREE;
18292 bool ret = false;
18294 init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
18295 gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
18297 decl = TREE_OPERAND (init, 0);
18298 init = TREE_OPERAND (init, 1);
18299 tree decl_expr = NULL_TREE;
18300 bool range_for = TREE_VEC_ELT (OMP_FOR_COND (t), i) == global_namespace;
18301 if (range_for)
18303 bool decomp = false;
18304 if (decl != error_mark_node && DECL_HAS_VALUE_EXPR_P (decl))
18306 tree v = DECL_VALUE_EXPR (decl);
18307 if (TREE_CODE (v) == ARRAY_REF
18308 && VAR_P (TREE_OPERAND (v, 0))
18309 && DECL_DECOMPOSITION_P (TREE_OPERAND (v, 0)))
18311 tree decomp_first = NULL_TREE;
18312 unsigned decomp_cnt = 0;
18313 tree d = tsubst_decl (TREE_OPERAND (v, 0), args, complain);
18314 maybe_push_decl (d);
18315 d = tsubst_decomp_names (d, TREE_OPERAND (v, 0), args, complain,
18316 in_decl, &decomp_first, &decomp_cnt);
18317 decomp = true;
18318 if (d == error_mark_node)
18319 decl = error_mark_node;
18320 else
18321 for (unsigned int i = 0; i < decomp_cnt; i++)
18323 if (!DECL_HAS_VALUE_EXPR_P (decomp_first))
18325 tree v = build_nt (ARRAY_REF, d,
18326 size_int (decomp_cnt - i - 1),
18327 NULL_TREE, NULL_TREE);
18328 SET_DECL_VALUE_EXPR (decomp_first, v);
18329 DECL_HAS_VALUE_EXPR_P (decomp_first) = 1;
18331 fit_decomposition_lang_decl (decomp_first, d);
18332 decomp_first = DECL_CHAIN (decomp_first);
18336 decl = tsubst_decl (decl, args, complain);
18337 if (!decomp)
18338 maybe_push_decl (decl);
18340 else if (init && TREE_CODE (init) == DECL_EXPR)
18342 /* We need to jump through some hoops to handle declarations in the
18343 init-statement, since we might need to handle auto deduction,
18344 but we need to keep control of initialization. */
18345 decl_expr = init;
18346 init = DECL_INITIAL (DECL_EXPR_DECL (init));
18347 decl = tsubst_decl (decl, args, complain);
18349 else
18351 if (TREE_CODE (decl) == SCOPE_REF)
18353 decl = RECUR (decl);
18354 if (TREE_CODE (decl) == COMPONENT_REF)
18356 tree v = decl;
18357 while (v)
18358 switch (TREE_CODE (v))
18360 case COMPONENT_REF:
18361 case MEM_REF:
18362 case INDIRECT_REF:
18363 CASE_CONVERT:
18364 case POINTER_PLUS_EXPR:
18365 v = TREE_OPERAND (v, 0);
18366 continue;
18367 case PARM_DECL:
18368 if (DECL_CONTEXT (v) == current_function_decl
18369 && DECL_ARTIFICIAL (v)
18370 && DECL_NAME (v) == this_identifier)
18372 decl = TREE_OPERAND (decl, 1);
18373 decl = omp_privatize_field (decl, false);
18375 /* FALLTHRU */
18376 default:
18377 v = NULL_TREE;
18378 break;
18382 else
18383 decl = RECUR (decl);
18385 if (init && TREE_CODE (init) == TREE_VEC)
18387 init = copy_node (init);
18388 TREE_VEC_ELT (init, 0)
18389 = tsubst_decl (TREE_VEC_ELT (init, 0), args, complain);
18390 TREE_VEC_ELT (init, 1) = RECUR (TREE_VEC_ELT (init, 1));
18391 TREE_VEC_ELT (init, 2) = RECUR (TREE_VEC_ELT (init, 2));
18393 else
18394 init = RECUR (init);
18396 if (orig_declv && OMP_FOR_ORIG_DECLS (t))
18398 tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
18399 if (TREE_CODE (o) == TREE_LIST)
18400 TREE_VEC_ELT (orig_declv, i)
18401 = tree_cons (RECUR (TREE_PURPOSE (o)),
18402 RECUR (TREE_VALUE (o)),
18403 NULL_TREE);
18404 else
18405 TREE_VEC_ELT (orig_declv, i) = RECUR (o);
18408 if (range_for)
18410 tree this_pre_body = NULL_TREE;
18411 tree orig_init = NULL_TREE;
18412 tree orig_decl = NULL_TREE;
18413 cp_convert_omp_range_for (this_pre_body, NULL, decl, orig_decl, init,
18414 orig_init, cond, incr);
18415 if (orig_decl)
18417 if (orig_declv == NULL_TREE)
18418 orig_declv = copy_node (declv);
18419 TREE_VEC_ELT (orig_declv, i) = orig_decl;
18420 ret = true;
18422 else if (orig_declv)
18423 TREE_VEC_ELT (orig_declv, i) = decl;
18426 tree auto_node = type_uses_auto (TREE_TYPE (decl));
18427 if (!range_for && auto_node && init)
18428 TREE_TYPE (decl)
18429 = do_auto_deduction (TREE_TYPE (decl), init, auto_node, complain);
18431 gcc_assert (!type_dependent_expression_p (decl));
18433 if (!CLASS_TYPE_P (TREE_TYPE (decl)) || range_for)
18435 if (decl_expr)
18437 /* Declare the variable, but don't let that initialize it. */
18438 tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
18439 DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
18440 RECUR (decl_expr);
18441 DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
18444 if (!range_for)
18446 cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
18447 if (COMPARISON_CLASS_P (cond)
18448 && TREE_CODE (TREE_OPERAND (cond, 1)) == TREE_VEC)
18450 tree lhs = RECUR (TREE_OPERAND (cond, 0));
18451 tree rhs = copy_node (TREE_OPERAND (cond, 1));
18452 TREE_VEC_ELT (rhs, 0)
18453 = tsubst_decl (TREE_VEC_ELT (rhs, 0), args, complain);
18454 TREE_VEC_ELT (rhs, 1) = RECUR (TREE_VEC_ELT (rhs, 1));
18455 TREE_VEC_ELT (rhs, 2) = RECUR (TREE_VEC_ELT (rhs, 2));
18456 cond = build2 (TREE_CODE (cond), TREE_TYPE (cond),
18457 lhs, rhs);
18459 else
18460 cond = RECUR (cond);
18461 incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
18462 if (TREE_CODE (incr) == MODIFY_EXPR)
18464 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18465 tree rhs = RECUR (TREE_OPERAND (incr, 1));
18466 incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
18467 NOP_EXPR, rhs, NULL_TREE, complain);
18469 else
18470 incr = RECUR (incr);
18471 if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
18472 TREE_VEC_ELT (orig_declv, i) = decl;
18474 TREE_VEC_ELT (declv, i) = decl;
18475 TREE_VEC_ELT (initv, i) = init;
18476 TREE_VEC_ELT (condv, i) = cond;
18477 TREE_VEC_ELT (incrv, i) = incr;
18478 return ret;
18481 if (decl_expr)
18483 /* Declare and initialize the variable. */
18484 RECUR (decl_expr);
18485 init = NULL_TREE;
18487 else if (init)
18489 tree *pc;
18490 int j;
18491 for (j = ((omp_parallel_combined_clauses == NULL
18492 || TREE_CODE (t) == OMP_LOOP) ? 1 : 0); j < 2; j++)
18494 for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
18496 if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
18497 && OMP_CLAUSE_DECL (*pc) == decl)
18498 break;
18499 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
18500 && OMP_CLAUSE_DECL (*pc) == decl)
18502 if (j)
18503 break;
18504 /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES. */
18505 tree c = *pc;
18506 *pc = OMP_CLAUSE_CHAIN (c);
18507 OMP_CLAUSE_CHAIN (c) = *clauses;
18508 *clauses = c;
18510 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
18511 && OMP_CLAUSE_DECL (*pc) == decl)
18513 error ("iteration variable %qD should not be firstprivate",
18514 decl);
18515 *pc = OMP_CLAUSE_CHAIN (*pc);
18517 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
18518 && OMP_CLAUSE_DECL (*pc) == decl)
18520 error ("iteration variable %qD should not be reduction",
18521 decl);
18522 *pc = OMP_CLAUSE_CHAIN (*pc);
18524 else
18525 pc = &OMP_CLAUSE_CHAIN (*pc);
18527 if (*pc)
18528 break;
18530 if (*pc == NULL_TREE)
18532 tree c = build_omp_clause (input_location,
18533 TREE_CODE (t) == OMP_LOOP
18534 ? OMP_CLAUSE_LASTPRIVATE
18535 : OMP_CLAUSE_PRIVATE);
18536 OMP_CLAUSE_DECL (c) = decl;
18537 c = finish_omp_clauses (c, C_ORT_OMP);
18538 if (c)
18540 OMP_CLAUSE_CHAIN (c) = *clauses;
18541 *clauses = c;
18545 cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
18546 if (COMPARISON_CLASS_P (cond))
18548 tree op0 = RECUR (TREE_OPERAND (cond, 0));
18549 tree op1 = RECUR (TREE_OPERAND (cond, 1));
18550 cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
18552 else
18553 cond = RECUR (cond);
18554 incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
18555 switch (TREE_CODE (incr))
18557 case PREINCREMENT_EXPR:
18558 case PREDECREMENT_EXPR:
18559 case POSTINCREMENT_EXPR:
18560 case POSTDECREMENT_EXPR:
18561 incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
18562 RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
18563 break;
18564 case MODIFY_EXPR:
18565 if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
18566 || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
18568 tree rhs = TREE_OPERAND (incr, 1);
18569 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18570 tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
18571 tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
18572 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18573 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
18574 rhs0, rhs1));
18576 else
18577 incr = RECUR (incr);
18578 break;
18579 case MODOP_EXPR:
18580 if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
18581 || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
18583 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18584 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18585 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
18586 TREE_TYPE (decl), lhs,
18587 RECUR (TREE_OPERAND (incr, 2))));
18589 else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
18590 && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
18591 || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
18593 tree rhs = TREE_OPERAND (incr, 2);
18594 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18595 tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
18596 tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
18597 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18598 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
18599 rhs0, rhs1));
18601 else
18602 incr = RECUR (incr);
18603 break;
18604 default:
18605 incr = RECUR (incr);
18606 break;
18609 if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
18610 TREE_VEC_ELT (orig_declv, i) = decl;
18611 TREE_VEC_ELT (declv, i) = decl;
18612 TREE_VEC_ELT (initv, i) = init;
18613 TREE_VEC_ELT (condv, i) = cond;
18614 TREE_VEC_ELT (incrv, i) = incr;
18615 return false;
18616 #undef RECUR
18619 /* Helper function of tsubst_expr, find OMP_TEAMS inside
18620 of OMP_TARGET's body. */
18622 static tree
18623 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
18625 *walk_subtrees = 0;
18626 switch (TREE_CODE (*tp))
18628 case OMP_TEAMS:
18629 return *tp;
18630 case BIND_EXPR:
18631 case STATEMENT_LIST:
18632 *walk_subtrees = 1;
18633 break;
18634 default:
18635 break;
18637 return NULL_TREE;
18640 /* Helper function for tsubst_expr. For decomposition declaration
18641 artificial base DECL, which is tsubsted PATTERN_DECL, tsubst
18642 also the corresponding decls representing the identifiers
18643 of the decomposition declaration. Return DECL if successful
18644 or error_mark_node otherwise, set *FIRST to the first decl
18645 in the list chained through DECL_CHAIN and *CNT to the number
18646 of such decls. */
18648 static tree
18649 tsubst_decomp_names (tree decl, tree pattern_decl, tree args,
18650 tsubst_flags_t complain, tree in_decl, tree *first,
18651 unsigned int *cnt)
18653 tree decl2, decl3, prev = decl;
18654 *cnt = 0;
18655 gcc_assert (DECL_NAME (decl) == NULL_TREE);
18656 for (decl2 = DECL_CHAIN (pattern_decl);
18657 decl2
18658 && VAR_P (decl2)
18659 && DECL_DECOMPOSITION_P (decl2)
18660 && DECL_NAME (decl2);
18661 decl2 = DECL_CHAIN (decl2))
18663 if (TREE_TYPE (decl2) == error_mark_node && *cnt == 0)
18665 gcc_assert (errorcount);
18666 return error_mark_node;
18668 (*cnt)++;
18669 gcc_assert (DECL_DECOMP_BASE (decl2) == pattern_decl);
18670 gcc_assert (DECL_HAS_VALUE_EXPR_P (decl2));
18671 tree v = DECL_VALUE_EXPR (decl2);
18672 DECL_HAS_VALUE_EXPR_P (decl2) = 0;
18673 SET_DECL_VALUE_EXPR (decl2, NULL_TREE);
18674 decl3 = tsubst (decl2, args, complain, in_decl);
18675 SET_DECL_VALUE_EXPR (decl2, v);
18676 DECL_HAS_VALUE_EXPR_P (decl2) = 1;
18677 if (VAR_P (decl3))
18678 DECL_TEMPLATE_INSTANTIATED (decl3) = 1;
18679 else
18681 gcc_assert (errorcount);
18682 decl = error_mark_node;
18683 continue;
18685 maybe_push_decl (decl3);
18686 if (error_operand_p (decl3))
18687 decl = error_mark_node;
18688 else if (decl != error_mark_node
18689 && DECL_CHAIN (decl3) != prev
18690 && decl != prev)
18692 gcc_assert (errorcount);
18693 decl = error_mark_node;
18695 else
18696 prev = decl3;
18698 *first = prev;
18699 return decl;
18702 /* Return the proper local_specialization for init-capture pack DECL. */
18704 static tree
18705 lookup_init_capture_pack (tree decl)
18707 /* We handle normal pack captures by forwarding to the specialization of the
18708 captured parameter. We can't do that for pack init-captures; we need them
18709 to have their own local_specialization. We created the individual
18710 VAR_DECLs (if any) under build_capture_proxy, and we need to collect them
18711 when we process the DECL_EXPR for the pack init-capture in the template.
18712 So, how do we find them? We don't know the capture proxy pack when
18713 building the individual resulting proxies, and we don't know the
18714 individual proxies when instantiating the pack. What we have in common is
18715 the FIELD_DECL.
18717 So...when we instantiate the FIELD_DECL, we stick the result in
18718 local_specializations. Then at the DECL_EXPR we look up that result, see
18719 how many elements it has, synthesize the names, and look them up. */
18721 tree cname = DECL_NAME (decl);
18722 tree val = DECL_VALUE_EXPR (decl);
18723 tree field = TREE_OPERAND (val, 1);
18724 gcc_assert (TREE_CODE (field) == FIELD_DECL);
18725 tree fpack = retrieve_local_specialization (field);
18726 if (fpack == error_mark_node)
18727 return error_mark_node;
18729 int len = 1;
18730 tree vec = NULL_TREE;
18731 tree r = NULL_TREE;
18732 if (TREE_CODE (fpack) == TREE_VEC)
18734 len = TREE_VEC_LENGTH (fpack);
18735 vec = make_tree_vec (len);
18736 r = make_node (NONTYPE_ARGUMENT_PACK);
18737 ARGUMENT_PACK_ARGS (r) = vec;
18739 for (int i = 0; i < len; ++i)
18741 tree ename = vec ? make_ith_pack_parameter_name (cname, i) : cname;
18742 tree elt = lookup_name (ename);
18743 if (vec)
18744 TREE_VEC_ELT (vec, i) = elt;
18745 else
18746 r = elt;
18748 return r;
18751 /* T is an operand of a template tree being substituted. Return whether
18752 T is dependent such that we should suppress some warnings that would
18753 make sense if the substituted expression were written directly, like
18754 template <int I> bool f() { return I == 2; }
18755 We don't want to warn when instantiating f that comparing two constants
18756 always has the same value.
18758 This is a more limited concept of dependence than instantiation-dependent;
18759 here we don't care whether substitution could fail. */
18761 static bool
18762 dependent_operand_p (tree t)
18764 while (TREE_CODE (t) == IMPLICIT_CONV_EXPR)
18765 t = TREE_OPERAND (t, 0);
18766 ++processing_template_decl;
18767 bool r = (potential_constant_expression (t)
18768 ? value_dependent_expression_p (t)
18769 : type_dependent_expression_p (t));
18770 --processing_template_decl;
18771 return r;
18774 /* Like tsubst_copy for expressions, etc. but also does semantic
18775 processing. */
18777 tree
18778 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
18780 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
18781 #define RECUR(NODE) \
18782 tsubst_expr ((NODE), args, complain, in_decl)
18784 tree stmt, tmp;
18785 tree r;
18786 location_t loc;
18788 if (t == NULL_TREE || t == error_mark_node)
18789 return t;
18791 loc = input_location;
18792 if (location_t eloc = cp_expr_location (t))
18793 input_location = eloc;
18794 if (STATEMENT_CODE_P (TREE_CODE (t)))
18795 current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
18797 switch (TREE_CODE (t))
18799 case STATEMENT_LIST:
18801 for (tree stmt : tsi_range (t))
18802 RECUR (stmt);
18803 break;
18806 case CTOR_INITIALIZER:
18807 finish_mem_initializers (tsubst_initializer_list
18808 (TREE_OPERAND (t, 0), args));
18809 break;
18811 case RETURN_EXPR:
18812 finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
18813 break;
18815 case CO_RETURN_EXPR:
18816 finish_co_return_stmt (input_location, RECUR (TREE_OPERAND (t, 0)));
18817 break;
18819 case CO_YIELD_EXPR:
18820 stmt = finish_co_yield_expr (input_location,
18821 RECUR (TREE_OPERAND (t, 0)));
18822 RETURN (stmt);
18824 case CO_AWAIT_EXPR:
18825 stmt = finish_co_await_expr (input_location,
18826 RECUR (TREE_OPERAND (t, 0)));
18827 RETURN (stmt);
18829 case EXPR_STMT:
18830 tmp = RECUR (EXPR_STMT_EXPR (t));
18831 if (EXPR_STMT_STMT_EXPR_RESULT (t))
18832 finish_stmt_expr_expr (tmp, cur_stmt_expr);
18833 else
18834 finish_expr_stmt (tmp);
18835 break;
18837 case USING_STMT:
18838 finish_using_directive (USING_STMT_NAMESPACE (t), /*attribs=*/NULL_TREE);
18839 break;
18841 case PRECONDITION_STMT:
18842 case POSTCONDITION_STMT:
18843 gcc_unreachable ();
18845 case ASSERTION_STMT:
18847 r = tsubst_contract (NULL_TREE, t, args, complain, in_decl);
18848 if (r != error_mark_node)
18849 add_stmt (r);
18850 RETURN (r);
18852 break;
18854 case DECL_EXPR:
18856 tree decl, pattern_decl;
18857 tree init;
18859 pattern_decl = decl = DECL_EXPR_DECL (t);
18860 if (TREE_CODE (decl) == LABEL_DECL)
18861 finish_label_decl (DECL_NAME (decl));
18862 else if (TREE_CODE (decl) == USING_DECL)
18864 tree scope = USING_DECL_SCOPE (decl);
18865 if (DECL_DEPENDENT_P (decl))
18867 scope = tsubst (scope, args, complain, in_decl);
18868 if (!MAYBE_CLASS_TYPE_P (scope)
18869 && TREE_CODE (scope) != ENUMERAL_TYPE)
18871 if (complain & tf_error)
18872 error_at (DECL_SOURCE_LOCATION (decl), "%qT is not a "
18873 "class, namespace, or enumeration", scope);
18874 return error_mark_node;
18876 finish_nonmember_using_decl (scope, DECL_NAME (decl));
18878 else
18880 /* This is a non-dependent using-decl, and we'll have
18881 used the names it found during template parsing. We do
18882 not want to do the lookup again, because we might not
18883 find the things we found then. */
18884 gcc_checking_assert (scope == tsubst (scope, args,
18885 complain, in_decl));
18886 /* We still need to push the bindings so that we can look up
18887 this name later. */
18888 push_using_decl_bindings (DECL_NAME (decl),
18889 USING_DECL_DECLS (decl));
18892 else if (is_capture_proxy (decl)
18893 && !DECL_TEMPLATE_INSTANTIATION (current_function_decl))
18895 /* We're in tsubst_lambda_expr, we've already inserted a new
18896 capture proxy, so look it up and register it. */
18897 tree inst;
18898 if (!DECL_PACK_P (decl))
18900 inst = lookup_name (DECL_NAME (decl), LOOK_where::BLOCK,
18901 LOOK_want::HIDDEN_LAMBDA);
18902 gcc_assert (inst != decl && is_capture_proxy (inst));
18904 else if (is_normal_capture_proxy (decl))
18906 inst = (retrieve_local_specialization
18907 (DECL_CAPTURED_VARIABLE (decl)));
18908 gcc_assert (TREE_CODE (inst) == NONTYPE_ARGUMENT_PACK
18909 || DECL_PACK_P (inst));
18911 else
18912 inst = lookup_init_capture_pack (decl);
18914 register_local_specialization (inst, decl);
18915 break;
18917 else if (DECL_PRETTY_FUNCTION_P (decl))
18918 decl = make_fname_decl (DECL_SOURCE_LOCATION (decl),
18919 DECL_NAME (decl),
18920 true/*DECL_PRETTY_FUNCTION_P (decl)*/);
18921 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
18922 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
18923 /* Don't copy the old closure; we'll create a new one in
18924 tsubst_lambda_expr. */
18925 break;
18926 else
18928 init = DECL_INITIAL (decl);
18929 decl = tsubst (decl, args, complain, in_decl);
18930 if (decl != error_mark_node)
18932 /* By marking the declaration as instantiated, we avoid
18933 trying to instantiate it. Since instantiate_decl can't
18934 handle local variables, and since we've already done
18935 all that needs to be done, that's the right thing to
18936 do. */
18937 if (VAR_P (decl))
18938 DECL_TEMPLATE_INSTANTIATED (decl) = 1;
18939 if (VAR_P (decl) && !DECL_NAME (decl)
18940 && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
18941 /* Anonymous aggregates are a special case. */
18942 finish_anon_union (decl);
18943 else if (is_capture_proxy (DECL_EXPR_DECL (t)))
18945 DECL_CONTEXT (decl) = current_function_decl;
18946 if (DECL_NAME (decl) == this_identifier)
18948 tree lam = DECL_CONTEXT (current_function_decl);
18949 lam = CLASSTYPE_LAMBDA_EXPR (lam);
18950 LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
18952 insert_capture_proxy (decl);
18954 else if (DECL_IMPLICIT_TYPEDEF_P (t))
18955 /* We already did a pushtag. */;
18956 else if (VAR_OR_FUNCTION_DECL_P (decl)
18957 && DECL_LOCAL_DECL_P (decl))
18959 if (TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL)
18960 DECL_CONTEXT (decl) = NULL_TREE;
18961 decl = pushdecl (decl);
18962 if (TREE_CODE (decl) == FUNCTION_DECL
18963 && DECL_OMP_DECLARE_REDUCTION_P (decl)
18964 && cp_check_omp_declare_reduction (decl))
18965 instantiate_body (pattern_decl, args, decl, true);
18967 else
18969 bool const_init = false;
18970 unsigned int cnt = 0;
18971 tree first = NULL_TREE, ndecl = error_mark_node;
18972 tree asmspec_tree = NULL_TREE;
18973 maybe_push_decl (decl);
18975 if (VAR_P (decl)
18976 && DECL_LANG_SPECIFIC (decl)
18977 && DECL_OMP_PRIVATIZED_MEMBER (decl))
18978 break;
18980 if (VAR_P (decl)
18981 && DECL_DECOMPOSITION_P (decl)
18982 && TREE_TYPE (pattern_decl) != error_mark_node)
18983 ndecl = tsubst_decomp_names (decl, pattern_decl, args,
18984 complain, in_decl, &first,
18985 &cnt);
18987 init = tsubst_init (init, decl, args, complain, in_decl);
18989 if (VAR_P (decl))
18990 const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
18991 (pattern_decl));
18993 if (ndecl != error_mark_node)
18994 cp_maybe_mangle_decomp (ndecl, first, cnt);
18996 /* In a non-template function, VLA type declarations are
18997 handled in grokdeclarator; for templates, handle them
18998 now. */
18999 predeclare_vla (decl);
19001 if (VAR_P (decl) && DECL_HARD_REGISTER (pattern_decl))
19003 tree id = DECL_ASSEMBLER_NAME (pattern_decl);
19004 const char *asmspec = IDENTIFIER_POINTER (id);
19005 gcc_assert (asmspec[0] == '*');
19006 asmspec_tree
19007 = build_string (IDENTIFIER_LENGTH (id) - 1,
19008 asmspec + 1);
19009 TREE_TYPE (asmspec_tree) = char_array_type_node;
19012 cp_finish_decl (decl, init, const_init, asmspec_tree, 0);
19014 if (ndecl != error_mark_node)
19015 cp_finish_decomp (ndecl, first, cnt);
19020 break;
19023 case FOR_STMT:
19024 stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
19025 RECUR (FOR_INIT_STMT (t));
19026 finish_init_stmt (stmt);
19027 tmp = RECUR (FOR_COND (t));
19028 finish_for_cond (tmp, stmt, false, 0);
19029 tmp = RECUR (FOR_EXPR (t));
19030 finish_for_expr (tmp, stmt);
19032 bool prev = note_iteration_stmt_body_start ();
19033 RECUR (FOR_BODY (t));
19034 note_iteration_stmt_body_end (prev);
19036 finish_for_stmt (stmt);
19037 break;
19039 case RANGE_FOR_STMT:
19041 /* Construct another range_for, if this is not a final
19042 substitution (for inside a generic lambda of a
19043 template). Otherwise convert to a regular for. */
19044 tree decl, expr;
19045 stmt = (processing_template_decl
19046 ? begin_range_for_stmt (NULL_TREE, NULL_TREE)
19047 : begin_for_stmt (NULL_TREE, NULL_TREE));
19048 RECUR (RANGE_FOR_INIT_STMT (t));
19049 decl = RANGE_FOR_DECL (t);
19050 decl = tsubst (decl, args, complain, in_decl);
19051 maybe_push_decl (decl);
19052 expr = RECUR (RANGE_FOR_EXPR (t));
19054 tree decomp_first = NULL_TREE;
19055 unsigned decomp_cnt = 0;
19056 if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
19057 decl = tsubst_decomp_names (decl, RANGE_FOR_DECL (t), args,
19058 complain, in_decl,
19059 &decomp_first, &decomp_cnt);
19061 if (processing_template_decl)
19063 RANGE_FOR_IVDEP (stmt) = RANGE_FOR_IVDEP (t);
19064 RANGE_FOR_UNROLL (stmt) = RANGE_FOR_UNROLL (t);
19065 finish_range_for_decl (stmt, decl, expr);
19066 if (decomp_first && decl != error_mark_node)
19067 cp_finish_decomp (decl, decomp_first, decomp_cnt);
19069 else
19071 unsigned short unroll = (RANGE_FOR_UNROLL (t)
19072 ? tree_to_uhwi (RANGE_FOR_UNROLL (t)) : 0);
19073 stmt = cp_convert_range_for (stmt, decl, expr,
19074 decomp_first, decomp_cnt,
19075 RANGE_FOR_IVDEP (t), unroll);
19078 bool prev = note_iteration_stmt_body_start ();
19079 RECUR (RANGE_FOR_BODY (t));
19080 note_iteration_stmt_body_end (prev);
19081 finish_for_stmt (stmt);
19083 break;
19085 case WHILE_STMT:
19086 stmt = begin_while_stmt ();
19087 tmp = RECUR (WHILE_COND (t));
19088 finish_while_stmt_cond (tmp, stmt, false, 0);
19090 bool prev = note_iteration_stmt_body_start ();
19091 RECUR (WHILE_BODY (t));
19092 note_iteration_stmt_body_end (prev);
19094 finish_while_stmt (stmt);
19095 break;
19097 case DO_STMT:
19098 stmt = begin_do_stmt ();
19100 bool prev = note_iteration_stmt_body_start ();
19101 RECUR (DO_BODY (t));
19102 note_iteration_stmt_body_end (prev);
19104 finish_do_body (stmt);
19105 tmp = RECUR (DO_COND (t));
19106 finish_do_stmt (tmp, stmt, false, 0);
19107 break;
19109 case IF_STMT:
19110 stmt = begin_if_stmt ();
19111 IF_STMT_CONSTEXPR_P (stmt) = IF_STMT_CONSTEXPR_P (t);
19112 IF_STMT_CONSTEVAL_P (stmt) = IF_STMT_CONSTEVAL_P (t);
19113 if (IF_STMT_CONSTEXPR_P (t))
19114 args = add_extra_args (IF_STMT_EXTRA_ARGS (t), args, complain, in_decl);
19116 tree cond = IF_COND (t);
19117 bool was_dep = dependent_operand_p (cond);
19118 cond = RECUR (cond);
19119 warning_sentinel s1(warn_address, was_dep);
19120 tmp = finish_if_stmt_cond (cond, stmt);
19122 if (IF_STMT_CONSTEXPR_P (t)
19123 && instantiation_dependent_expression_p (tmp))
19125 /* We're partially instantiating a generic lambda, but the condition
19126 of the constexpr if is still dependent. Don't substitute into the
19127 branches now, just remember the template arguments. */
19128 do_poplevel (IF_SCOPE (stmt));
19129 IF_COND (stmt) = IF_COND (t);
19130 THEN_CLAUSE (stmt) = THEN_CLAUSE (t);
19131 ELSE_CLAUSE (stmt) = ELSE_CLAUSE (t);
19132 IF_STMT_EXTRA_ARGS (stmt) = build_extra_args (t, args, complain);
19133 add_stmt (stmt);
19134 break;
19136 if (IF_STMT_CONSTEXPR_P (t) && integer_zerop (tmp))
19137 /* Don't instantiate the THEN_CLAUSE. */;
19138 else if (IF_STMT_CONSTEVAL_P (t))
19140 bool save_in_consteval_if_p = in_consteval_if_p;
19141 in_consteval_if_p = true;
19142 RECUR (THEN_CLAUSE (t));
19143 in_consteval_if_p = save_in_consteval_if_p;
19145 else
19147 tree folded = fold_non_dependent_expr (tmp, complain);
19148 bool inhibit = integer_zerop (folded);
19149 if (inhibit)
19150 ++c_inhibit_evaluation_warnings;
19151 RECUR (THEN_CLAUSE (t));
19152 if (inhibit)
19153 --c_inhibit_evaluation_warnings;
19155 finish_then_clause (stmt);
19157 if (IF_STMT_CONSTEXPR_P (t) && integer_nonzerop (tmp))
19158 /* Don't instantiate the ELSE_CLAUSE. */;
19159 else if (ELSE_CLAUSE (t))
19161 tree folded = fold_non_dependent_expr (tmp, complain);
19162 bool inhibit = integer_nonzerop (folded);
19163 begin_else_clause (stmt);
19164 if (inhibit)
19165 ++c_inhibit_evaluation_warnings;
19166 RECUR (ELSE_CLAUSE (t));
19167 if (inhibit)
19168 --c_inhibit_evaluation_warnings;
19169 finish_else_clause (stmt);
19172 finish_if_stmt (stmt);
19173 break;
19175 case BIND_EXPR:
19176 if (BIND_EXPR_BODY_BLOCK (t))
19177 stmt = begin_function_body ();
19178 else
19179 stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
19180 ? BCS_TRY_BLOCK : 0);
19182 RECUR (BIND_EXPR_BODY (t));
19184 if (BIND_EXPR_BODY_BLOCK (t))
19185 finish_function_body (stmt);
19186 else
19187 finish_compound_stmt (stmt);
19188 break;
19190 case BREAK_STMT:
19191 finish_break_stmt ();
19192 break;
19194 case CONTINUE_STMT:
19195 finish_continue_stmt ();
19196 break;
19198 case SWITCH_STMT:
19199 stmt = begin_switch_stmt ();
19200 tmp = RECUR (SWITCH_STMT_COND (t));
19201 finish_switch_cond (tmp, stmt);
19202 RECUR (SWITCH_STMT_BODY (t));
19203 finish_switch_stmt (stmt);
19204 break;
19206 case CASE_LABEL_EXPR:
19208 tree decl = CASE_LABEL (t);
19209 tree low = RECUR (CASE_LOW (t));
19210 tree high = RECUR (CASE_HIGH (t));
19211 tree l = finish_case_label (EXPR_LOCATION (t), low, high);
19212 if (l && TREE_CODE (l) == CASE_LABEL_EXPR)
19214 tree label = CASE_LABEL (l);
19215 FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
19216 if (DECL_ATTRIBUTES (decl) != NULL_TREE)
19217 cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
19220 break;
19222 case LABEL_EXPR:
19224 tree decl = LABEL_EXPR_LABEL (t);
19225 tree label;
19227 label = finish_label_stmt (DECL_NAME (decl));
19228 if (TREE_CODE (label) == LABEL_DECL)
19229 FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
19230 if (DECL_ATTRIBUTES (decl) != NULL_TREE)
19231 cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
19233 break;
19235 case GOTO_EXPR:
19236 tmp = GOTO_DESTINATION (t);
19237 if (TREE_CODE (tmp) != LABEL_DECL)
19238 /* Computed goto's must be tsubst'd into. On the other hand,
19239 non-computed gotos must not be; the identifier in question
19240 will have no binding. */
19241 tmp = RECUR (tmp);
19242 else
19243 tmp = DECL_NAME (tmp);
19244 finish_goto_stmt (tmp);
19245 break;
19247 case ASM_EXPR:
19249 tree string = RECUR (ASM_STRING (t));
19250 tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
19251 complain, in_decl);
19252 tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
19253 complain, in_decl);
19254 tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
19255 complain, in_decl);
19256 tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
19257 complain, in_decl);
19258 tmp = finish_asm_stmt (EXPR_LOCATION (t), ASM_VOLATILE_P (t), string,
19259 outputs, inputs, clobbers, labels,
19260 ASM_INLINE_P (t));
19261 tree asm_expr = tmp;
19262 if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
19263 asm_expr = TREE_OPERAND (asm_expr, 0);
19264 ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
19266 break;
19268 case TRY_BLOCK:
19269 if (CLEANUP_P (t))
19271 stmt = begin_try_block ();
19272 RECUR (TRY_STMTS (t));
19273 finish_cleanup_try_block (stmt);
19274 finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
19276 else
19278 tree compound_stmt = NULL_TREE;
19280 if (FN_TRY_BLOCK_P (t))
19281 stmt = begin_function_try_block (&compound_stmt);
19282 else
19283 stmt = begin_try_block ();
19285 RECUR (TRY_STMTS (t));
19287 if (FN_TRY_BLOCK_P (t))
19288 finish_function_try_block (stmt);
19289 else
19290 finish_try_block (stmt);
19292 RECUR (TRY_HANDLERS (t));
19293 if (FN_TRY_BLOCK_P (t))
19294 finish_function_handler_sequence (stmt, compound_stmt);
19295 else
19296 finish_handler_sequence (stmt);
19298 break;
19300 case HANDLER:
19302 tree decl = HANDLER_PARMS (t);
19304 if (decl)
19306 decl = tsubst (decl, args, complain, in_decl);
19307 /* Prevent instantiate_decl from trying to instantiate
19308 this variable. We've already done all that needs to be
19309 done. */
19310 if (decl != error_mark_node)
19311 DECL_TEMPLATE_INSTANTIATED (decl) = 1;
19313 stmt = begin_handler ();
19314 finish_handler_parms (decl, stmt);
19315 RECUR (HANDLER_BODY (t));
19316 finish_handler (stmt);
19318 break;
19320 case TAG_DEFN:
19321 tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
19322 if (CLASS_TYPE_P (tmp))
19324 /* Local classes are not independent templates; they are
19325 instantiated along with their containing function. And this
19326 way we don't have to deal with pushing out of one local class
19327 to instantiate a member of another local class. */
19328 /* Closures are handled by the LAMBDA_EXPR. */
19329 gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
19330 complete_type (tmp);
19331 if (dependent_type_p (tmp))
19333 /* This is a partial instantiation, try again when full. */
19334 add_stmt (build_min (TAG_DEFN, tmp));
19335 break;
19337 tree save_ccp = current_class_ptr;
19338 tree save_ccr = current_class_ref;
19339 for (tree fld = TYPE_FIELDS (tmp); fld; fld = DECL_CHAIN (fld))
19340 if ((VAR_P (fld)
19341 || (TREE_CODE (fld) == FUNCTION_DECL
19342 && !DECL_ARTIFICIAL (fld)))
19343 && DECL_TEMPLATE_INSTANTIATION (fld))
19344 instantiate_decl (fld, /*defer_ok=*/false,
19345 /*expl_inst_class=*/false);
19346 else if (TREE_CODE (fld) == FIELD_DECL)
19347 maybe_instantiate_nsdmi_init (fld, tf_warning_or_error);
19348 current_class_ptr = save_ccp;
19349 current_class_ref = save_ccr;
19351 break;
19353 case STATIC_ASSERT:
19355 tree condition;
19357 ++c_inhibit_evaluation_warnings;
19358 condition = tsubst_expr (STATIC_ASSERT_CONDITION (t), args,
19359 complain, in_decl);
19360 --c_inhibit_evaluation_warnings;
19362 finish_static_assert (condition,
19363 STATIC_ASSERT_MESSAGE (t),
19364 STATIC_ASSERT_SOURCE_LOCATION (t),
19365 /*member_p=*/false, /*show_expr_p=*/true);
19367 break;
19369 case OACC_KERNELS:
19370 case OACC_PARALLEL:
19371 case OACC_SERIAL:
19372 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_ACC, args, complain,
19373 in_decl);
19374 stmt = begin_omp_parallel ();
19375 RECUR (OMP_BODY (t));
19376 finish_omp_construct (TREE_CODE (t), stmt, tmp);
19377 break;
19379 case OMP_PARALLEL:
19380 r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
19381 tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), C_ORT_OMP, args,
19382 complain, in_decl);
19383 if (OMP_PARALLEL_COMBINED (t))
19384 omp_parallel_combined_clauses = &tmp;
19385 stmt = begin_omp_parallel ();
19386 RECUR (OMP_PARALLEL_BODY (t));
19387 gcc_assert (omp_parallel_combined_clauses == NULL);
19388 OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
19389 = OMP_PARALLEL_COMBINED (t);
19390 pop_omp_privatization_clauses (r);
19391 break;
19393 case OMP_TASK:
19394 if (OMP_TASK_BODY (t) == NULL_TREE)
19396 tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
19397 complain, in_decl);
19398 t = copy_node (t);
19399 OMP_TASK_CLAUSES (t) = tmp;
19400 add_stmt (t);
19401 break;
19403 r = push_omp_privatization_clauses (false);
19404 tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
19405 complain, in_decl);
19406 stmt = begin_omp_task ();
19407 RECUR (OMP_TASK_BODY (t));
19408 finish_omp_task (tmp, stmt);
19409 pop_omp_privatization_clauses (r);
19410 break;
19412 case OMP_FOR:
19413 case OMP_LOOP:
19414 case OMP_SIMD:
19415 case OMP_DISTRIBUTE:
19416 case OMP_TASKLOOP:
19417 case OACC_LOOP:
19419 tree clauses, body, pre_body;
19420 tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
19421 tree orig_declv = NULL_TREE;
19422 tree incrv = NULL_TREE;
19423 enum c_omp_region_type ort = C_ORT_OMP;
19424 bool any_range_for = false;
19425 int i;
19427 if (TREE_CODE (t) == OACC_LOOP)
19428 ort = C_ORT_ACC;
19430 r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
19431 clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), ort, args, complain,
19432 in_decl);
19433 if (OMP_FOR_INIT (t) != NULL_TREE)
19435 declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19436 if (OMP_FOR_ORIG_DECLS (t))
19437 orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19438 initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19439 condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19440 incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19443 keep_next_level (true);
19444 stmt = begin_omp_structured_block ();
19446 pre_body = push_stmt_list ();
19447 RECUR (OMP_FOR_PRE_BODY (t));
19448 pre_body = pop_stmt_list (pre_body);
19450 if (OMP_FOR_INIT (t) != NULL_TREE)
19451 for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
19452 any_range_for
19453 |= tsubst_omp_for_iterator (t, i, declv, orig_declv, initv,
19454 condv, incrv, &clauses, args,
19455 complain, in_decl);
19456 omp_parallel_combined_clauses = NULL;
19458 if (any_range_for)
19460 gcc_assert (orig_declv);
19461 body = begin_omp_structured_block ();
19462 for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
19463 if (TREE_VEC_ELT (orig_declv, i) != TREE_VEC_ELT (declv, i)
19464 && TREE_CODE (TREE_VEC_ELT (orig_declv, i)) == TREE_LIST
19465 && TREE_CHAIN (TREE_VEC_ELT (orig_declv, i)))
19466 cp_finish_omp_range_for (TREE_VEC_ELT (orig_declv, i),
19467 TREE_VEC_ELT (declv, i));
19469 else
19470 body = push_stmt_list ();
19471 RECUR (OMP_FOR_BODY (t));
19472 if (any_range_for)
19473 body = finish_omp_structured_block (body);
19474 else
19475 body = pop_stmt_list (body);
19477 if (OMP_FOR_INIT (t) != NULL_TREE)
19478 t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
19479 orig_declv, initv, condv, incrv, body, pre_body,
19480 NULL, clauses);
19481 else
19483 t = make_node (TREE_CODE (t));
19484 TREE_TYPE (t) = void_type_node;
19485 OMP_FOR_BODY (t) = body;
19486 OMP_FOR_PRE_BODY (t) = pre_body;
19487 OMP_FOR_CLAUSES (t) = clauses;
19488 SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
19489 add_stmt (t);
19492 add_stmt (finish_omp_for_block (finish_omp_structured_block (stmt),
19493 t));
19494 pop_omp_privatization_clauses (r);
19496 break;
19498 case OMP_SECTIONS:
19499 case OMP_MASKED:
19500 omp_parallel_combined_clauses = NULL;
19501 /* FALLTHRU */
19502 case OMP_SINGLE:
19503 case OMP_SCOPE:
19504 case OMP_TEAMS:
19505 case OMP_CRITICAL:
19506 case OMP_TASKGROUP:
19507 case OMP_SCAN:
19508 r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
19509 && OMP_TEAMS_COMBINED (t));
19510 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_OMP, args, complain,
19511 in_decl);
19512 if (TREE_CODE (t) == OMP_TEAMS)
19514 keep_next_level (true);
19515 stmt = begin_omp_structured_block ();
19516 RECUR (OMP_BODY (t));
19517 stmt = finish_omp_structured_block (stmt);
19519 else
19521 stmt = push_stmt_list ();
19522 RECUR (OMP_BODY (t));
19523 stmt = pop_stmt_list (stmt);
19526 if (TREE_CODE (t) == OMP_CRITICAL
19527 && tmp != NULL_TREE
19528 && integer_nonzerop (OMP_CLAUSE_HINT_EXPR (tmp)))
19530 error_at (OMP_CLAUSE_LOCATION (tmp),
19531 "%<#pragma omp critical%> with %<hint%> clause requires "
19532 "a name, except when %<omp_sync_hint_none%> is used");
19533 RETURN (error_mark_node);
19535 t = copy_node (t);
19536 OMP_BODY (t) = stmt;
19537 OMP_CLAUSES (t) = tmp;
19538 add_stmt (t);
19539 pop_omp_privatization_clauses (r);
19540 break;
19542 case OMP_DEPOBJ:
19543 r = RECUR (OMP_DEPOBJ_DEPOBJ (t));
19544 if (OMP_DEPOBJ_CLAUSES (t) && OMP_DEPOBJ_CLAUSES (t) != error_mark_node)
19546 enum omp_clause_depend_kind kind = OMP_CLAUSE_DEPEND_INVALID;
19547 if (TREE_CODE (OMP_DEPOBJ_CLAUSES (t)) == OMP_CLAUSE)
19549 tmp = tsubst_omp_clauses (OMP_DEPOBJ_CLAUSES (t), C_ORT_OMP,
19550 args, complain, in_decl);
19551 if (tmp == NULL_TREE)
19552 tmp = error_mark_node;
19554 else
19556 kind = (enum omp_clause_depend_kind)
19557 tree_to_uhwi (OMP_DEPOBJ_CLAUSES (t));
19558 tmp = NULL_TREE;
19560 finish_omp_depobj (EXPR_LOCATION (t), r, kind, tmp);
19562 else
19563 finish_omp_depobj (EXPR_LOCATION (t), r,
19564 OMP_CLAUSE_DEPEND_INVALID,
19565 OMP_DEPOBJ_CLAUSES (t));
19566 break;
19568 case OACC_DATA:
19569 case OMP_TARGET_DATA:
19570 case OMP_TARGET:
19571 tmp = tsubst_omp_clauses (OMP_CLAUSES (t),
19572 TREE_CODE (t) == OACC_DATA
19573 ? C_ORT_ACC
19574 : TREE_CODE (t) == OMP_TARGET
19575 ? C_ORT_OMP_TARGET : C_ORT_OMP,
19576 args, complain, in_decl);
19577 keep_next_level (true);
19578 stmt = begin_omp_structured_block ();
19580 RECUR (OMP_BODY (t));
19581 stmt = finish_omp_structured_block (stmt);
19583 t = copy_node (t);
19584 OMP_BODY (t) = stmt;
19585 OMP_CLAUSES (t) = tmp;
19587 if (TREE_CODE (t) == OMP_TARGET)
19588 finish_omp_target_clauses (EXPR_LOCATION (t), OMP_BODY (t),
19589 &OMP_CLAUSES (t));
19591 if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
19593 tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
19594 if (teams)
19595 /* For combined target teams, ensure the num_teams and
19596 thread_limit clause expressions are evaluated on the host,
19597 before entering the target construct. */
19598 for (tree c = OMP_TEAMS_CLAUSES (teams);
19599 c; c = OMP_CLAUSE_CHAIN (c))
19600 if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
19601 || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
19602 for (int i = 0;
19603 i <= (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS); ++i)
19604 if (OMP_CLAUSE_OPERAND (c, i)
19605 && TREE_CODE (OMP_CLAUSE_OPERAND (c, i)) != INTEGER_CST)
19607 tree expr = OMP_CLAUSE_OPERAND (c, i);
19608 expr = force_target_expr (TREE_TYPE (expr), expr,
19609 tf_none);
19610 if (expr == error_mark_node)
19611 continue;
19612 tmp = TARGET_EXPR_SLOT (expr);
19613 add_stmt (expr);
19614 OMP_CLAUSE_OPERAND (c, i) = expr;
19615 tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
19616 OMP_CLAUSE_FIRSTPRIVATE);
19617 OMP_CLAUSE_DECL (tc) = tmp;
19618 OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
19619 OMP_TARGET_CLAUSES (t) = tc;
19622 add_stmt (t);
19623 break;
19625 case OACC_DECLARE:
19626 t = copy_node (t);
19627 tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), C_ORT_ACC, args,
19628 complain, in_decl);
19629 OACC_DECLARE_CLAUSES (t) = tmp;
19630 add_stmt (t);
19631 break;
19633 case OMP_TARGET_UPDATE:
19634 case OMP_TARGET_ENTER_DATA:
19635 case OMP_TARGET_EXIT_DATA:
19636 tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_OMP, args,
19637 complain, in_decl);
19638 t = copy_node (t);
19639 OMP_STANDALONE_CLAUSES (t) = tmp;
19640 add_stmt (t);
19641 break;
19643 case OACC_CACHE:
19644 case OACC_ENTER_DATA:
19645 case OACC_EXIT_DATA:
19646 case OACC_UPDATE:
19647 tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_ACC, args,
19648 complain, in_decl);
19649 t = copy_node (t);
19650 OMP_STANDALONE_CLAUSES (t) = tmp;
19651 add_stmt (t);
19652 break;
19654 case OMP_ORDERED:
19655 tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), C_ORT_OMP, args,
19656 complain, in_decl);
19657 if (OMP_BODY (t))
19659 stmt = push_stmt_list ();
19660 RECUR (OMP_BODY (t));
19661 stmt = pop_stmt_list (stmt);
19663 else
19664 stmt = NULL_TREE;
19666 t = copy_node (t);
19667 OMP_BODY (t) = stmt;
19668 OMP_ORDERED_CLAUSES (t) = tmp;
19669 add_stmt (t);
19670 break;
19672 case OMP_MASTER:
19673 omp_parallel_combined_clauses = NULL;
19674 /* FALLTHRU */
19675 case OMP_SECTION:
19676 stmt = push_stmt_list ();
19677 RECUR (OMP_BODY (t));
19678 stmt = pop_stmt_list (stmt);
19680 t = copy_node (t);
19681 OMP_BODY (t) = stmt;
19682 add_stmt (t);
19683 break;
19685 case OMP_ATOMIC:
19686 gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
19687 tmp = NULL_TREE;
19688 if (TREE_CODE (TREE_OPERAND (t, 0)) == OMP_CLAUSE)
19689 tmp = tsubst_omp_clauses (TREE_OPERAND (t, 0), C_ORT_OMP, args,
19690 complain, in_decl);
19691 if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
19693 tree op1 = TREE_OPERAND (t, 1);
19694 tree rhs1 = NULL_TREE;
19695 tree r = NULL_TREE;
19696 tree lhs, rhs;
19697 if (TREE_CODE (op1) == COMPOUND_EXPR)
19699 rhs1 = RECUR (TREE_OPERAND (op1, 0));
19700 op1 = TREE_OPERAND (op1, 1);
19702 if (TREE_CODE (op1) == COND_EXPR)
19704 gcc_assert (rhs1 == NULL_TREE);
19705 tree c = TREE_OPERAND (op1, 0);
19706 if (TREE_CODE (c) == MODIFY_EXPR)
19708 r = RECUR (TREE_OPERAND (c, 0));
19709 c = TREE_OPERAND (c, 1);
19711 gcc_assert (TREE_CODE (c) == EQ_EXPR);
19712 rhs = RECUR (TREE_OPERAND (c, 1));
19713 lhs = RECUR (TREE_OPERAND (op1, 2));
19714 rhs1 = RECUR (TREE_OPERAND (op1, 1));
19716 else
19718 lhs = RECUR (TREE_OPERAND (op1, 0));
19719 rhs = RECUR (TREE_OPERAND (op1, 1));
19721 finish_omp_atomic (EXPR_LOCATION (t), OMP_ATOMIC, TREE_CODE (op1),
19722 lhs, rhs, NULL_TREE, NULL_TREE, rhs1, r,
19723 tmp, OMP_ATOMIC_MEMORY_ORDER (t),
19724 OMP_ATOMIC_WEAK (t));
19726 else
19728 tree op1 = TREE_OPERAND (t, 1);
19729 tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
19730 tree rhs1 = NULL_TREE, r = NULL_TREE;
19731 enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
19732 enum tree_code opcode = NOP_EXPR;
19733 if (code == OMP_ATOMIC_READ)
19735 v = RECUR (TREE_OPERAND (op1, 0));
19736 lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19738 else if (code == OMP_ATOMIC_CAPTURE_OLD
19739 || code == OMP_ATOMIC_CAPTURE_NEW)
19741 tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
19742 v = RECUR (TREE_OPERAND (op1, 0));
19743 lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19744 if (TREE_CODE (op11) == COMPOUND_EXPR)
19746 rhs1 = RECUR (TREE_OPERAND (op11, 0));
19747 op11 = TREE_OPERAND (op11, 1);
19749 if (TREE_CODE (op11) == COND_EXPR)
19751 gcc_assert (rhs1 == NULL_TREE);
19752 tree c = TREE_OPERAND (op11, 0);
19753 if (TREE_CODE (c) == MODIFY_EXPR)
19755 r = RECUR (TREE_OPERAND (c, 0));
19756 c = TREE_OPERAND (c, 1);
19758 gcc_assert (TREE_CODE (c) == EQ_EXPR);
19759 rhs = RECUR (TREE_OPERAND (c, 1));
19760 lhs = RECUR (TREE_OPERAND (op11, 2));
19761 rhs1 = RECUR (TREE_OPERAND (op11, 1));
19763 else
19765 lhs = RECUR (TREE_OPERAND (op11, 0));
19766 rhs = RECUR (TREE_OPERAND (op11, 1));
19768 opcode = TREE_CODE (op11);
19769 if (opcode == MODIFY_EXPR)
19770 opcode = NOP_EXPR;
19772 else
19774 code = OMP_ATOMIC;
19775 lhs = RECUR (TREE_OPERAND (op1, 0));
19776 rhs = RECUR (TREE_OPERAND (op1, 1));
19778 finish_omp_atomic (EXPR_LOCATION (t), code, opcode, lhs, rhs, v,
19779 lhs1, rhs1, r, tmp,
19780 OMP_ATOMIC_MEMORY_ORDER (t), OMP_ATOMIC_WEAK (t));
19782 break;
19784 case TRANSACTION_EXPR:
19786 int flags = 0;
19787 flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
19788 flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
19790 if (TRANSACTION_EXPR_IS_STMT (t))
19792 tree body = TRANSACTION_EXPR_BODY (t);
19793 tree noex = NULL_TREE;
19794 if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
19796 noex = MUST_NOT_THROW_COND (body);
19797 if (noex == NULL_TREE)
19798 noex = boolean_true_node;
19799 body = TREE_OPERAND (body, 0);
19801 stmt = begin_transaction_stmt (input_location, NULL, flags);
19802 RECUR (body);
19803 finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
19805 else
19807 stmt = build_transaction_expr (EXPR_LOCATION (t),
19808 RECUR (TRANSACTION_EXPR_BODY (t)),
19809 flags, NULL_TREE);
19810 RETURN (stmt);
19813 break;
19815 case MUST_NOT_THROW_EXPR:
19817 tree op0 = RECUR (TREE_OPERAND (t, 0));
19818 tree cond = RECUR (MUST_NOT_THROW_COND (t));
19819 RETURN (build_must_not_throw_expr (op0, cond));
19822 case EXPR_PACK_EXPANSION:
19823 error ("invalid use of pack expansion expression");
19824 RETURN (error_mark_node);
19826 case NONTYPE_ARGUMENT_PACK:
19827 error ("use %<...%> to expand argument pack");
19828 RETURN (error_mark_node);
19830 case COMPOUND_EXPR:
19831 tmp = RECUR (TREE_OPERAND (t, 0));
19832 if (tmp == NULL_TREE)
19833 /* If the first operand was a statement, we're done with it. */
19834 RETURN (RECUR (TREE_OPERAND (t, 1)));
19835 RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
19836 RECUR (TREE_OPERAND (t, 1)),
19837 templated_operator_saved_lookups (t),
19838 complain));
19840 case ANNOTATE_EXPR:
19841 tmp = RECUR (TREE_OPERAND (t, 0));
19842 RETURN (build3_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
19843 TREE_TYPE (tmp), tmp,
19844 RECUR (TREE_OPERAND (t, 1)),
19845 RECUR (TREE_OPERAND (t, 2))));
19847 case PREDICT_EXPR:
19848 RETURN (add_stmt (copy_node (t)));
19850 default:
19851 gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
19853 RETURN (tsubst_copy_and_build (t, args, complain, in_decl));
19856 RETURN (NULL_TREE);
19857 out:
19858 input_location = loc;
19859 return r;
19860 #undef RECUR
19861 #undef RETURN
19864 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
19865 function. For description of the body see comment above
19866 cp_parser_omp_declare_reduction_exprs. */
19868 static void
19869 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19871 if (t == NULL_TREE || t == error_mark_node)
19872 return;
19874 gcc_assert (TREE_CODE (t) == STATEMENT_LIST && current_function_decl);
19876 tree_stmt_iterator tsi;
19877 int i;
19878 tree stmts[7];
19879 memset (stmts, 0, sizeof stmts);
19880 for (i = 0, tsi = tsi_start (t);
19881 i < 7 && !tsi_end_p (tsi);
19882 i++, tsi_next (&tsi))
19883 stmts[i] = tsi_stmt (tsi);
19884 gcc_assert (tsi_end_p (tsi));
19886 if (i >= 3)
19888 gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
19889 && TREE_CODE (stmts[1]) == DECL_EXPR);
19890 tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
19891 args, complain, in_decl);
19892 tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
19893 args, complain, in_decl);
19894 /* tsubsting a local var_decl leaves DECL_CONTEXT null, as we
19895 expect to be pushing it. */
19896 DECL_CONTEXT (omp_out) = current_function_decl;
19897 DECL_CONTEXT (omp_in) = current_function_decl;
19898 keep_next_level (true);
19899 tree block = begin_omp_structured_block ();
19900 tsubst_expr (stmts[2], args, complain, in_decl);
19901 block = finish_omp_structured_block (block);
19902 block = maybe_cleanup_point_expr_void (block);
19903 add_decl_expr (omp_out);
19904 copy_warning (omp_out, DECL_EXPR_DECL (stmts[0]));
19905 add_decl_expr (omp_in);
19906 finish_expr_stmt (block);
19908 if (i >= 6)
19910 gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
19911 && TREE_CODE (stmts[4]) == DECL_EXPR);
19912 tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
19913 args, complain, in_decl);
19914 tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
19915 args, complain, in_decl);
19916 DECL_CONTEXT (omp_priv) = current_function_decl;
19917 DECL_CONTEXT (omp_orig) = current_function_decl;
19918 keep_next_level (true);
19919 tree block = begin_omp_structured_block ();
19920 tsubst_expr (stmts[5], args, complain, in_decl);
19921 block = finish_omp_structured_block (block);
19922 block = maybe_cleanup_point_expr_void (block);
19923 cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
19924 add_decl_expr (omp_priv);
19925 add_decl_expr (omp_orig);
19926 finish_expr_stmt (block);
19927 if (i == 7)
19928 add_decl_expr (omp_orig);
19932 /* T is a postfix-expression that is not being used in a function
19933 call. Return the substituted version of T. */
19935 static tree
19936 tsubst_non_call_postfix_expression (tree t, tree args,
19937 tsubst_flags_t complain,
19938 tree in_decl)
19940 if (TREE_CODE (t) == SCOPE_REF)
19941 t = tsubst_qualified_id (t, args, complain, in_decl,
19942 /*done=*/false, /*address_p=*/false);
19943 else
19944 t = tsubst_copy_and_build (t, args, complain, in_decl);
19946 return t;
19949 /* Subroutine of tsubst_lambda_expr: add the FIELD/INIT capture pair to the
19950 LAMBDA_EXPR_CAPTURE_LIST passed in LIST. Do deduction for a previously
19951 dependent init-capture. EXPLICIT_P is true if the original list had
19952 explicit captures. */
19954 static void
19955 prepend_one_capture (tree field, tree init, tree &list, bool explicit_p,
19956 tsubst_flags_t complain)
19958 if (tree auto_node = type_uses_auto (TREE_TYPE (field)))
19960 tree type = NULL_TREE;
19961 if (!init)
19963 if (complain & tf_error)
19964 error ("empty initializer in lambda init-capture");
19965 init = error_mark_node;
19967 else if (TREE_CODE (init) == TREE_LIST)
19968 init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19969 if (!type)
19970 type = do_auto_deduction (TREE_TYPE (field), init, auto_node, complain);
19971 TREE_TYPE (field) = type;
19972 cp_apply_type_quals_to_decl (cp_type_quals (type), field);
19974 list = tree_cons (field, init, list);
19975 LAMBDA_CAPTURE_EXPLICIT_P (list) = explicit_p;
19978 /* T is a LAMBDA_EXPR. Generate a new LAMBDA_EXPR for the current
19979 instantiation context. Instantiating a pack expansion containing a lambda
19980 might result in multiple lambdas all based on the same lambda in the
19981 template. */
19983 tree
19984 tsubst_lambda_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19986 tree oldfn = lambda_function (t);
19987 in_decl = oldfn;
19989 tree r = build_lambda_expr ();
19991 LAMBDA_EXPR_LOCATION (r)
19992 = LAMBDA_EXPR_LOCATION (t);
19993 LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
19994 = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
19995 LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
19996 if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
19997 LAMBDA_EXPR_REGEN_INFO (r)
19998 = build_template_info (t, add_to_template_args (TI_ARGS (ti),
19999 preserve_args (args)));
20000 else
20001 LAMBDA_EXPR_REGEN_INFO (r)
20002 = build_template_info (t, preserve_args (args));
20004 gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
20005 && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
20007 vec<tree,va_gc>* field_packs = NULL;
20009 for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t); cap;
20010 cap = TREE_CHAIN (cap))
20012 tree ofield = TREE_PURPOSE (cap);
20013 tree init = TREE_VALUE (cap);
20014 if (PACK_EXPANSION_P (init))
20015 init = tsubst_pack_expansion (init, args, complain, in_decl);
20016 else
20017 init = tsubst_copy_and_build (init, args, complain, in_decl);
20019 if (init == error_mark_node)
20020 return error_mark_node;
20022 if (init && TREE_CODE (init) == TREE_LIST)
20023 init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
20025 if (!processing_template_decl
20026 && init && TREE_CODE (init) != TREE_VEC
20027 && variably_modified_type_p (TREE_TYPE (init), NULL_TREE))
20029 /* For a VLA, simply tsubsting the field type won't work, we need to
20030 go through add_capture again. XXX do we want to do this for all
20031 captures? */
20032 tree name = (get_identifier
20033 (IDENTIFIER_POINTER (DECL_NAME (ofield)) + 2));
20034 tree ftype = TREE_TYPE (ofield);
20035 bool by_ref = (TYPE_REF_P (ftype)
20036 || (TREE_CODE (ftype) == DECLTYPE_TYPE
20037 && DECLTYPE_FOR_REF_CAPTURE (ftype)));
20038 add_capture (r, name, init, by_ref, !DECL_NORMAL_CAPTURE_P (ofield));
20039 continue;
20042 if (PACK_EXPANSION_P (ofield))
20043 ofield = PACK_EXPANSION_PATTERN (ofield);
20044 tree field = tsubst_decl (ofield, args, complain);
20046 if (DECL_PACK_P (ofield) && !DECL_NORMAL_CAPTURE_P (ofield))
20048 /* Remember these for when we've pushed local_specializations. */
20049 vec_safe_push (field_packs, ofield);
20050 vec_safe_push (field_packs, field);
20053 if (field == error_mark_node)
20054 return error_mark_node;
20056 if (TREE_CODE (field) == TREE_VEC)
20058 int len = TREE_VEC_LENGTH (field);
20059 gcc_assert (TREE_CODE (init) == TREE_VEC
20060 && TREE_VEC_LENGTH (init) == len);
20061 for (int i = 0; i < len; ++i)
20062 prepend_one_capture (TREE_VEC_ELT (field, i),
20063 TREE_VEC_ELT (init, i),
20064 LAMBDA_EXPR_CAPTURE_LIST (r),
20065 LAMBDA_CAPTURE_EXPLICIT_P (cap),
20066 complain);
20068 else
20070 prepend_one_capture (field, init, LAMBDA_EXPR_CAPTURE_LIST (r),
20071 LAMBDA_CAPTURE_EXPLICIT_P (cap), complain);
20073 if (id_equal (DECL_NAME (field), "__this"))
20074 LAMBDA_EXPR_THIS_CAPTURE (r) = field;
20078 tree type = begin_lambda_type (r);
20079 if (type == error_mark_node)
20080 return error_mark_node;
20082 if (LAMBDA_EXPR_EXTRA_SCOPE (t))
20083 record_lambda_scope (r);
20084 else if (TYPE_NAMESPACE_SCOPE_P (TREE_TYPE (t)))
20085 /* If we're pushed into another scope (PR105652), fix it. */
20086 TYPE_CONTEXT (type) = DECL_CONTEXT (TYPE_NAME (type))
20087 = TYPE_CONTEXT (TREE_TYPE (t));
20088 record_lambda_scope_discriminator (r);
20090 /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set. */
20091 determine_visibility (TYPE_NAME (type));
20093 register_capture_members (LAMBDA_EXPR_CAPTURE_LIST (r));
20095 tree oldtmpl = (generic_lambda_fn_p (oldfn)
20096 ? DECL_TI_TEMPLATE (oldfn)
20097 : NULL_TREE);
20099 tree tparms = NULL_TREE;
20100 if (oldtmpl)
20101 tparms = tsubst_template_parms (DECL_TEMPLATE_PARMS (oldtmpl), args, complain);
20103 tree fntype = static_fn_type (oldfn);
20105 tree saved_ctp = current_template_parms;
20106 if (oldtmpl)
20108 ++processing_template_decl;
20109 current_template_parms = tparms;
20111 fntype = tsubst (fntype, args, complain, in_decl);
20112 if (oldtmpl)
20114 current_template_parms = saved_ctp;
20115 --processing_template_decl;
20118 if (fntype == error_mark_node)
20119 r = error_mark_node;
20120 else
20122 /* The body of a lambda-expression is not a subexpression of the
20123 enclosing expression. Parms are to have DECL_CHAIN tsubsted,
20124 which would be skipped if cp_unevaluated_operand. */
20125 cp_evaluated ev;
20127 /* Fix the type of 'this'. */
20128 fntype = build_memfn_type (fntype, type,
20129 type_memfn_quals (fntype),
20130 type_memfn_rqual (fntype));
20131 tree inst = (oldtmpl
20132 ? tsubst_template_decl (oldtmpl, args, complain,
20133 fntype, tparms)
20134 : tsubst_function_decl (oldfn, args, complain, fntype));
20135 if (inst == error_mark_node)
20137 r = error_mark_node;
20138 goto out;
20140 finish_member_declaration (inst);
20141 record_lambda_scope_sig_discriminator (r, inst);
20143 tree fn = oldtmpl ? DECL_TEMPLATE_RESULT (inst) : inst;
20145 /* Let finish_function set this. */
20146 DECL_DECLARED_CONSTEXPR_P (fn) = false;
20148 bool nested = cfun;
20149 if (nested)
20150 push_function_context ();
20151 else
20152 /* Still increment function_depth so that we don't GC in the
20153 middle of an expression. */
20154 ++function_depth;
20156 local_specialization_stack s (lss_copy);
20158 bool save_in_consteval_if_p = in_consteval_if_p;
20159 in_consteval_if_p = false;
20161 tree body = start_lambda_function (fn, r);
20163 /* Now record them for lookup_init_capture_pack. */
20164 int fplen = vec_safe_length (field_packs);
20165 for (int i = 0; i < fplen; )
20167 tree pack = (*field_packs)[i++];
20168 tree inst = (*field_packs)[i++];
20169 register_local_specialization (inst, pack);
20171 release_tree_vector (field_packs);
20173 register_parameter_specializations (oldfn, fn);
20175 if (oldtmpl)
20177 /* We might not partially instantiate some parts of the function, so
20178 copy these flags from the original template. */
20179 language_function *ol = DECL_STRUCT_FUNCTION (oldfn)->language;
20180 current_function_returns_value = ol->returns_value;
20181 current_function_returns_null = ol->returns_null;
20182 current_function_returns_abnormally = ol->returns_abnormally;
20183 current_function_infinite_loop = ol->infinite_loop;
20186 /* [temp.deduct] A lambda-expression appearing in a function type or a
20187 template parameter is not considered part of the immediate context for
20188 the purposes of template argument deduction. */
20189 complain = tf_warning_or_error;
20191 tree saved = DECL_SAVED_TREE (oldfn);
20192 if (TREE_CODE (saved) == BIND_EXPR && BIND_EXPR_BODY_BLOCK (saved))
20193 /* We already have a body block from start_lambda_function, we don't
20194 need another to confuse NRV (91217). */
20195 saved = BIND_EXPR_BODY (saved);
20197 tsubst_expr (saved, args, complain, r);
20199 finish_lambda_function (body);
20201 in_consteval_if_p = save_in_consteval_if_p;
20203 if (nested)
20204 pop_function_context ();
20205 else
20206 --function_depth;
20208 /* The capture list was built up in reverse order; fix that now. */
20209 LAMBDA_EXPR_CAPTURE_LIST (r)
20210 = nreverse (LAMBDA_EXPR_CAPTURE_LIST (r));
20212 LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
20214 maybe_add_lambda_conv_op (type);
20217 out:
20218 finish_struct (type, /*attr*/NULL_TREE);
20220 insert_pending_capture_proxies ();
20222 return r;
20225 /* Subroutine of maybe_fold_fn_template_args. */
20227 static bool
20228 fold_targs_r (tree targs, tsubst_flags_t complain)
20230 int len = TREE_VEC_LENGTH (targs);
20231 for (int i = 0; i < len; ++i)
20233 tree &elt = TREE_VEC_ELT (targs, i);
20234 if (!elt || TYPE_P (elt)
20235 || TREE_CODE (elt) == TEMPLATE_DECL)
20236 continue;
20237 if (TREE_CODE (elt) == NONTYPE_ARGUMENT_PACK)
20239 if (!fold_targs_r (ARGUMENT_PACK_ARGS (elt), complain))
20240 return false;
20242 else if (/* We can only safely preevaluate scalar prvalues. */
20243 SCALAR_TYPE_P (TREE_TYPE (elt))
20244 && !glvalue_p (elt)
20245 && !TREE_CONSTANT (elt))
20247 elt = cxx_constant_value (elt, complain);
20248 if (elt == error_mark_node)
20249 return false;
20253 return true;
20256 /* Try to do constant evaluation of any explicit template arguments in FN
20257 before overload resolution, to get any errors only once. Return true iff
20258 we didn't have any problems folding. */
20260 static bool
20261 maybe_fold_fn_template_args (tree fn, tsubst_flags_t complain)
20263 if (processing_template_decl || fn == NULL_TREE)
20264 return true;
20265 if (fn == error_mark_node)
20266 return false;
20267 if (TREE_CODE (fn) == OFFSET_REF
20268 || TREE_CODE (fn) == COMPONENT_REF)
20269 fn = TREE_OPERAND (fn, 1);
20270 if (BASELINK_P (fn))
20271 fn = BASELINK_FUNCTIONS (fn);
20272 if (TREE_CODE (fn) != TEMPLATE_ID_EXPR)
20273 return true;
20274 tree targs = TREE_OPERAND (fn, 1);
20275 if (targs == NULL_TREE)
20276 return true;
20277 if (targs == error_mark_node)
20278 return false;
20279 return fold_targs_r (targs, complain);
20282 /* Helper function for tsubst_copy_and_build CALL_EXPR and ARRAY_REF
20283 handling. */
20285 static void
20286 tsubst_copy_and_build_call_args (tree t, tree args, tsubst_flags_t complain,
20287 tree in_decl, releasing_vec &call_args)
20289 unsigned int nargs = call_expr_nargs (t);
20290 for (unsigned int i = 0; i < nargs; ++i)
20292 tree arg = CALL_EXPR_ARG (t, i);
20294 if (!PACK_EXPANSION_P (arg))
20295 vec_safe_push (call_args,
20296 tsubst_copy_and_build (arg, args, complain, in_decl));
20297 else
20299 /* Expand the pack expansion and push each entry onto CALL_ARGS. */
20300 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
20301 if (TREE_CODE (arg) == TREE_VEC)
20303 unsigned int len, j;
20305 len = TREE_VEC_LENGTH (arg);
20306 for (j = 0; j < len; ++j)
20308 tree value = TREE_VEC_ELT (arg, j);
20309 if (value != NULL_TREE)
20310 value = convert_from_reference (value);
20311 vec_safe_push (call_args, value);
20314 else
20315 /* A partial substitution. Add one entry. */
20316 vec_safe_push (call_args, arg);
20321 /* Like tsubst but deals with expressions and performs semantic
20322 analysis. */
20324 tree
20325 tsubst_copy_and_build (tree t,
20326 tree args,
20327 tsubst_flags_t complain,
20328 tree in_decl)
20330 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
20331 #define RECUR(NODE) \
20332 tsubst_copy_and_build (NODE, args, complain, in_decl)
20334 tree retval, op1;
20335 location_t save_loc;
20337 if (t == NULL_TREE || t == error_mark_node)
20338 return t;
20340 save_loc = input_location;
20341 if (location_t eloc = cp_expr_location (t))
20342 input_location = eloc;
20344 /* N3276 decltype magic only applies to calls at the top level or on the
20345 right side of a comma. */
20346 tsubst_flags_t decltype_flag = (complain & tf_decltype);
20347 complain &= ~tf_decltype;
20349 switch (TREE_CODE (t))
20351 case USING_DECL:
20352 t = DECL_NAME (t);
20353 /* Fall through. */
20354 case IDENTIFIER_NODE:
20356 tree decl;
20357 cp_id_kind idk;
20358 const char *error_msg;
20360 if (IDENTIFIER_CONV_OP_P (t))
20362 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20363 t = make_conv_op_name (new_type);
20366 /* Look up the name. */
20367 decl = lookup_name (t);
20369 /* By convention, expressions use ERROR_MARK_NODE to indicate
20370 failure, not NULL_TREE. */
20371 if (decl == NULL_TREE)
20372 decl = error_mark_node;
20374 decl = finish_id_expression (t, decl, NULL_TREE,
20375 &idk,
20376 /*i_c_e_p=*/false,
20377 /*allow_i_c_e_p=*/true,
20378 /*non_i_c_e_p=*/nullptr,
20379 /*template_p=*/false,
20380 /*done=*/true,
20381 /*address_p=*/false,
20382 /*template_arg_p=*/false,
20383 &error_msg,
20384 input_location);
20385 if (error_msg)
20386 error (error_msg);
20387 if (identifier_p (decl))
20389 if (complain & tf_error)
20390 unqualified_name_lookup_error (decl);
20391 decl = error_mark_node;
20393 RETURN (decl);
20396 case TEMPLATE_ID_EXPR:
20398 tree object;
20399 tree templ = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
20400 complain, in_decl);
20401 tree targs = TREE_OPERAND (t, 1);
20403 if (targs)
20404 targs = tsubst_template_args (targs, args, complain, in_decl);
20405 if (targs == error_mark_node)
20406 RETURN (error_mark_node);
20408 if (TREE_CODE (templ) == SCOPE_REF)
20410 tree name = TREE_OPERAND (templ, 1);
20411 tree tid = lookup_template_function (name, targs);
20412 TREE_OPERAND (templ, 1) = tid;
20413 RETURN (templ);
20416 if (concept_definition_p (templ))
20418 tree check = build_concept_check (templ, targs, complain);
20419 if (check == error_mark_node)
20420 RETURN (error_mark_node);
20422 tree id = unpack_concept_check (check);
20424 /* If we built a function concept check, return the underlying
20425 template-id. So we can evaluate it as a function call. */
20426 if (function_concept_p (TREE_OPERAND (id, 0)))
20427 RETURN (id);
20429 RETURN (check);
20432 if (variable_template_p (templ))
20434 tree r = lookup_and_finish_template_variable (templ, targs,
20435 complain);
20436 r = convert_from_reference (r);
20437 r = maybe_wrap_with_location (r, EXPR_LOCATION (t));
20438 RETURN (r);
20441 if (TREE_CODE (templ) == COMPONENT_REF)
20443 object = TREE_OPERAND (templ, 0);
20444 templ = TREE_OPERAND (templ, 1);
20446 else
20447 object = NULL_TREE;
20449 tree tid = lookup_template_function (templ, targs);
20450 protected_set_expr_location (tid, EXPR_LOCATION (t));
20452 if (object)
20453 RETURN (build3 (COMPONENT_REF, TREE_TYPE (tid),
20454 object, tid, NULL_TREE));
20455 else if (identifier_p (templ))
20457 /* C++20 P0846: we can encounter an IDENTIFIER_NODE here when
20458 name lookup found nothing when parsing the template name. */
20459 gcc_assert (cxx_dialect >= cxx20 || seen_error ());
20460 RETURN (tid);
20462 else
20463 RETURN (baselink_for_fns (tid));
20466 case INDIRECT_REF:
20468 tree r = RECUR (TREE_OPERAND (t, 0));
20470 if (REFERENCE_REF_P (t))
20472 /* A type conversion to reference type will be enclosed in
20473 such an indirect ref, but the substitution of the cast
20474 will have also added such an indirect ref. */
20475 r = convert_from_reference (r);
20477 else
20478 r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
20479 templated_operator_saved_lookups (t),
20480 complain|decltype_flag);
20482 if (REF_PARENTHESIZED_P (t))
20483 r = force_paren_expr (r);
20485 RETURN (r);
20488 case NOP_EXPR:
20490 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20491 tree op0 = RECUR (TREE_OPERAND (t, 0));
20492 RETURN (build_nop (type, op0));
20495 case IMPLICIT_CONV_EXPR:
20497 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20498 tree expr = RECUR (TREE_OPERAND (t, 0));
20499 if (dependent_type_p (type) || type_dependent_expression_p (expr))
20501 retval = copy_node (t);
20502 TREE_TYPE (retval) = type;
20503 TREE_OPERAND (retval, 0) = expr;
20504 RETURN (retval);
20506 if (IMPLICIT_CONV_EXPR_NONTYPE_ARG (t))
20507 /* We'll pass this to convert_nontype_argument again, we don't need
20508 to actually perform any conversion here. */
20509 RETURN (expr);
20510 int flags = LOOKUP_IMPLICIT;
20511 if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
20512 flags = LOOKUP_NORMAL;
20513 if (IMPLICIT_CONV_EXPR_BRACED_INIT (t))
20514 flags |= LOOKUP_NO_NARROWING;
20515 RETURN (perform_implicit_conversion_flags (type, expr, complain,
20516 flags));
20519 case CONVERT_EXPR:
20521 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20522 tree op0 = RECUR (TREE_OPERAND (t, 0));
20523 if (op0 == error_mark_node)
20524 RETURN (error_mark_node);
20525 RETURN (build1 (CONVERT_EXPR, type, op0));
20528 case CAST_EXPR:
20529 case REINTERPRET_CAST_EXPR:
20530 case CONST_CAST_EXPR:
20531 case DYNAMIC_CAST_EXPR:
20532 case STATIC_CAST_EXPR:
20534 tree type;
20535 tree op, r = NULL_TREE;
20537 tsubst_flags_t tcomplain = complain;
20538 if (TREE_CODE (t) == CAST_EXPR)
20539 tcomplain |= tf_tst_ok;
20540 type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
20542 op = RECUR (TREE_OPERAND (t, 0));
20544 warning_sentinel s(warn_useless_cast);
20545 warning_sentinel s2(warn_ignored_qualifiers);
20546 warning_sentinel s3(warn_int_in_bool_context);
20547 switch (TREE_CODE (t))
20549 case CAST_EXPR:
20550 r = build_functional_cast (input_location, type, op, complain);
20551 break;
20552 case REINTERPRET_CAST_EXPR:
20553 r = build_reinterpret_cast (input_location, type, op, complain);
20554 break;
20555 case CONST_CAST_EXPR:
20556 r = build_const_cast (input_location, type, op, complain);
20557 break;
20558 case DYNAMIC_CAST_EXPR:
20559 r = build_dynamic_cast (input_location, type, op, complain);
20560 break;
20561 case STATIC_CAST_EXPR:
20562 r = build_static_cast (input_location, type, op, complain);
20563 if (IMPLICIT_RVALUE_P (t))
20564 set_implicit_rvalue_p (r);
20565 break;
20566 default:
20567 gcc_unreachable ();
20570 RETURN (r);
20573 case BIT_CAST_EXPR:
20575 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20576 tree op0 = RECUR (TREE_OPERAND (t, 0));
20577 RETURN (cp_build_bit_cast (EXPR_LOCATION (t), type, op0, complain));
20580 case POSTDECREMENT_EXPR:
20581 case POSTINCREMENT_EXPR:
20582 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20583 args, complain, in_decl);
20584 RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
20585 templated_operator_saved_lookups (t),
20586 complain|decltype_flag));
20588 case PREDECREMENT_EXPR:
20589 case PREINCREMENT_EXPR:
20590 case NEGATE_EXPR:
20591 case BIT_NOT_EXPR:
20592 case ABS_EXPR:
20593 case TRUTH_NOT_EXPR:
20594 case UNARY_PLUS_EXPR: /* Unary + */
20595 case REALPART_EXPR:
20596 case IMAGPART_EXPR:
20597 RETURN (build_x_unary_op (input_location, TREE_CODE (t),
20598 RECUR (TREE_OPERAND (t, 0)),
20599 templated_operator_saved_lookups (t),
20600 complain|decltype_flag));
20602 case EXCESS_PRECISION_EXPR:
20604 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20605 tree op0 = RECUR (TREE_OPERAND (t, 0));
20606 if (TREE_CODE (op0) == EXCESS_PRECISION_EXPR)
20607 RETURN (op0);
20608 RETURN (build1_loc (EXPR_LOCATION (t), EXCESS_PRECISION_EXPR,
20609 type, op0));
20612 case FIX_TRUNC_EXPR:
20613 /* convert_like should have created an IMPLICIT_CONV_EXPR. */
20614 gcc_unreachable ();
20616 case ADDR_EXPR:
20617 op1 = TREE_OPERAND (t, 0);
20618 if (TREE_CODE (op1) == LABEL_DECL)
20619 RETURN (finish_label_address_expr (DECL_NAME (op1),
20620 EXPR_LOCATION (op1)));
20621 if (TREE_CODE (op1) == SCOPE_REF)
20622 op1 = tsubst_qualified_id (op1, args, complain, in_decl,
20623 /*done=*/true, /*address_p=*/true);
20624 else
20625 op1 = tsubst_non_call_postfix_expression (op1, args, complain,
20626 in_decl);
20627 RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
20628 templated_operator_saved_lookups (t),
20629 complain|decltype_flag));
20631 case PLUS_EXPR:
20632 case MINUS_EXPR:
20633 case MULT_EXPR:
20634 case TRUNC_DIV_EXPR:
20635 case CEIL_DIV_EXPR:
20636 case FLOOR_DIV_EXPR:
20637 case ROUND_DIV_EXPR:
20638 case EXACT_DIV_EXPR:
20639 case BIT_AND_EXPR:
20640 case BIT_IOR_EXPR:
20641 case BIT_XOR_EXPR:
20642 case TRUNC_MOD_EXPR:
20643 case FLOOR_MOD_EXPR:
20644 case TRUTH_ANDIF_EXPR:
20645 case TRUTH_ORIF_EXPR:
20646 case TRUTH_AND_EXPR:
20647 case TRUTH_OR_EXPR:
20648 case RSHIFT_EXPR:
20649 case LSHIFT_EXPR:
20650 case EQ_EXPR:
20651 case NE_EXPR:
20652 case MAX_EXPR:
20653 case MIN_EXPR:
20654 case LE_EXPR:
20655 case GE_EXPR:
20656 case LT_EXPR:
20657 case GT_EXPR:
20658 case SPACESHIP_EXPR:
20659 case MEMBER_REF:
20660 case DOTSTAR_EXPR:
20662 /* If either OP0 or OP1 was value- or type-dependent, suppress
20663 warnings that depend on the range of the types involved. */
20664 tree op0 = TREE_OPERAND (t, 0);
20665 tree op1 = TREE_OPERAND (t, 1);
20666 const bool was_dep = (dependent_operand_p (op0)
20667 || dependent_operand_p (op1));
20668 op0 = RECUR (op0);
20669 op1 = RECUR (op1);
20671 warning_sentinel s1(warn_type_limits, was_dep);
20672 warning_sentinel s2(warn_div_by_zero, was_dep);
20673 warning_sentinel s3(warn_logical_op, was_dep);
20674 warning_sentinel s4(warn_tautological_compare, was_dep);
20675 warning_sentinel s5(warn_address, was_dep);
20677 tree r = build_x_binary_op
20678 (input_location, TREE_CODE (t),
20679 op0,
20680 (warning_suppressed_p (TREE_OPERAND (t, 0))
20681 ? ERROR_MARK
20682 : TREE_CODE (TREE_OPERAND (t, 0))),
20683 op1,
20684 (warning_suppressed_p (TREE_OPERAND (t, 1))
20685 ? ERROR_MARK
20686 : TREE_CODE (TREE_OPERAND (t, 1))),
20687 templated_operator_saved_lookups (t),
20688 /*overload=*/NULL,
20689 complain|decltype_flag);
20690 if (EXPR_P (r))
20691 copy_warning (r, t);
20693 RETURN (r);
20696 case POINTER_PLUS_EXPR:
20698 tree op0 = RECUR (TREE_OPERAND (t, 0));
20699 if (op0 == error_mark_node)
20700 RETURN (error_mark_node);
20701 tree op1 = RECUR (TREE_OPERAND (t, 1));
20702 if (op1 == error_mark_node)
20703 RETURN (error_mark_node);
20704 RETURN (fold_build_pointer_plus (op0, op1));
20707 case SCOPE_REF:
20708 RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
20709 /*address_p=*/false));
20711 case BASELINK:
20712 RETURN (tsubst_baselink (t, current_nonlambda_class_type (),
20713 args, complain, in_decl));
20715 case ARRAY_REF:
20716 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20717 args, complain, in_decl);
20718 if (TREE_CODE (TREE_OPERAND (t, 1)) == CALL_EXPR
20719 && (CALL_EXPR_FN (TREE_OPERAND (t, 1))
20720 == ovl_op_identifier (ARRAY_REF)))
20722 tree c = TREE_OPERAND (t, 1);
20723 releasing_vec index_exp_list;
20724 tsubst_copy_and_build_call_args (c, args, complain, in_decl,
20725 index_exp_list);
20727 tree r;
20728 if (vec_safe_length (index_exp_list) == 1
20729 && !PACK_EXPANSION_P (index_exp_list[0]))
20730 r = grok_array_decl (EXPR_LOCATION (t), op1,
20731 index_exp_list[0], NULL,
20732 complain | decltype_flag);
20733 else
20734 r = grok_array_decl (EXPR_LOCATION (t), op1,
20735 NULL_TREE, &index_exp_list,
20736 complain | decltype_flag);
20737 RETURN (r);
20739 RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
20740 RECUR (TREE_OPERAND (t, 1)),
20741 complain|decltype_flag));
20743 case SIZEOF_EXPR:
20744 if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
20745 || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
20746 RETURN (tsubst_copy (t, args, complain, in_decl));
20747 /* Fall through */
20749 case ALIGNOF_EXPR:
20751 tree r;
20753 op1 = TREE_OPERAND (t, 0);
20754 if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
20755 op1 = TREE_TYPE (op1);
20756 bool std_alignof = (TREE_CODE (t) == ALIGNOF_EXPR
20757 && ALIGNOF_EXPR_STD_P (t));
20758 if (!args)
20760 /* When there are no ARGS, we are trying to evaluate a
20761 non-dependent expression from the parser. Trying to do
20762 the substitutions may not work. */
20763 if (!TYPE_P (op1))
20764 op1 = TREE_TYPE (op1);
20766 else
20768 ++cp_unevaluated_operand;
20769 ++c_inhibit_evaluation_warnings;
20770 if (TYPE_P (op1))
20771 op1 = tsubst (op1, args, complain, in_decl);
20772 else
20773 op1 = tsubst_copy_and_build (op1, args, complain, in_decl);
20774 --cp_unevaluated_operand;
20775 --c_inhibit_evaluation_warnings;
20777 if (TYPE_P (op1))
20778 r = cxx_sizeof_or_alignof_type (input_location,
20779 op1, TREE_CODE (t), std_alignof,
20780 complain & tf_error);
20781 else
20782 r = cxx_sizeof_or_alignof_expr (input_location,
20783 op1, TREE_CODE (t), std_alignof,
20784 complain & tf_error);
20785 if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
20787 if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
20789 if (!processing_template_decl && TYPE_P (op1))
20791 r = build_min (SIZEOF_EXPR, size_type_node,
20792 build1 (NOP_EXPR, op1, error_mark_node));
20793 SIZEOF_EXPR_TYPE_P (r) = 1;
20795 else
20796 r = build_min (SIZEOF_EXPR, size_type_node, op1);
20797 TREE_SIDE_EFFECTS (r) = 0;
20798 TREE_READONLY (r) = 1;
20800 SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
20802 RETURN (r);
20805 case AT_ENCODE_EXPR:
20807 op1 = TREE_OPERAND (t, 0);
20808 ++cp_unevaluated_operand;
20809 ++c_inhibit_evaluation_warnings;
20810 op1 = tsubst_copy_and_build (op1, args, complain, in_decl);
20811 --cp_unevaluated_operand;
20812 --c_inhibit_evaluation_warnings;
20813 RETURN (objc_build_encode_expr (op1));
20816 case NOEXCEPT_EXPR:
20817 op1 = TREE_OPERAND (t, 0);
20818 ++cp_unevaluated_operand;
20819 ++c_inhibit_evaluation_warnings;
20820 ++cp_noexcept_operand;
20821 op1 = tsubst_copy_and_build (op1, args, complain, in_decl);
20822 --cp_unevaluated_operand;
20823 --c_inhibit_evaluation_warnings;
20824 --cp_noexcept_operand;
20825 RETURN (finish_noexcept_expr (op1, complain));
20827 case MODOP_EXPR:
20829 warning_sentinel s(warn_div_by_zero);
20830 tree lhs = RECUR (TREE_OPERAND (t, 0));
20831 tree rhs = RECUR (TREE_OPERAND (t, 2));
20833 tree r = build_x_modify_expr
20834 (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
20835 templated_operator_saved_lookups (t),
20836 complain|decltype_flag);
20837 /* TREE_NO_WARNING must be set if either the expression was
20838 parenthesized or it uses an operator such as >>= rather
20839 than plain assignment. In the former case, it was already
20840 set and must be copied. In the latter case,
20841 build_x_modify_expr sets it and it must not be reset
20842 here. */
20843 if (warning_suppressed_p (t, OPT_Wparentheses))
20844 suppress_warning (r, OPT_Wparentheses);
20846 RETURN (r);
20849 case ARROW_EXPR:
20850 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20851 args, complain, in_decl);
20852 /* Remember that there was a reference to this entity. */
20853 if (DECL_P (op1)
20854 && !mark_used (op1, complain) && !(complain & tf_error))
20855 RETURN (error_mark_node);
20856 RETURN (build_x_arrow (input_location, op1, complain));
20858 case NEW_EXPR:
20860 tree placement = RECUR (TREE_OPERAND (t, 0));
20861 tree init = RECUR (TREE_OPERAND (t, 3));
20862 vec<tree, va_gc> *placement_vec;
20863 vec<tree, va_gc> *init_vec;
20864 tree ret;
20865 location_t loc = EXPR_LOCATION (t);
20867 if (placement == NULL_TREE)
20868 placement_vec = NULL;
20869 else if (placement == error_mark_node)
20870 RETURN (error_mark_node);
20871 else
20873 placement_vec = make_tree_vector ();
20874 for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
20875 vec_safe_push (placement_vec, TREE_VALUE (placement));
20878 /* If there was an initializer in the original tree, but it
20879 instantiated to an empty list, then we should pass a
20880 non-NULL empty vector to tell build_new that it was an
20881 empty initializer() rather than no initializer. This can
20882 only happen when the initializer is a pack expansion whose
20883 parameter packs are of length zero. */
20884 if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
20885 init_vec = NULL;
20886 else if (init == error_mark_node)
20887 RETURN (error_mark_node);
20888 else
20890 init_vec = make_tree_vector ();
20891 if (init == void_node)
20892 gcc_assert (init_vec != NULL);
20893 else
20895 for (; init != NULL_TREE; init = TREE_CHAIN (init))
20896 vec_safe_push (init_vec, TREE_VALUE (init));
20900 /* Avoid passing an enclosing decl to valid_array_size_p. */
20901 in_decl = NULL_TREE;
20903 tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
20904 tree op2 = RECUR (TREE_OPERAND (t, 2));
20905 ret = build_new (loc, &placement_vec, op1, op2,
20906 &init_vec, NEW_EXPR_USE_GLOBAL (t),
20907 complain);
20909 if (placement_vec != NULL)
20910 release_tree_vector (placement_vec);
20911 if (init_vec != NULL)
20912 release_tree_vector (init_vec);
20914 RETURN (ret);
20917 case DELETE_EXPR:
20919 tree op0 = RECUR (TREE_OPERAND (t, 0));
20920 tree op1 = RECUR (TREE_OPERAND (t, 1));
20921 RETURN (delete_sanity (input_location, op0, op1,
20922 DELETE_EXPR_USE_VEC (t),
20923 DELETE_EXPR_USE_GLOBAL (t),
20924 complain));
20927 case COMPOUND_EXPR:
20929 tree op0 = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
20930 complain & ~tf_decltype, in_decl);
20931 RETURN (build_x_compound_expr (EXPR_LOCATION (t),
20932 op0,
20933 RECUR (TREE_OPERAND (t, 1)),
20934 templated_operator_saved_lookups (t),
20935 complain|decltype_flag));
20938 case CALL_EXPR:
20940 tree function;
20941 unsigned int nargs;
20942 bool qualified_p;
20943 bool koenig_p;
20944 tree ret;
20946 function = CALL_EXPR_FN (t);
20947 /* Internal function with no arguments. */
20948 if (function == NULL_TREE && call_expr_nargs (t) == 0)
20949 RETURN (t);
20951 /* When we parsed the expression, we determined whether or
20952 not Koenig lookup should be performed. */
20953 koenig_p = KOENIG_LOOKUP_P (t);
20954 if (function == NULL_TREE)
20956 koenig_p = false;
20957 qualified_p = false;
20959 else if (TREE_CODE (function) == SCOPE_REF)
20961 qualified_p = true;
20962 function = tsubst_qualified_id (function, args, complain, in_decl,
20963 /*done=*/false,
20964 /*address_p=*/false);
20966 else if (koenig_p
20967 && (identifier_p (function)
20968 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
20969 && identifier_p (TREE_OPERAND (function, 0)))))
20971 /* Do nothing; calling tsubst_copy_and_build on an identifier
20972 would incorrectly perform unqualified lookup again.
20974 Note that we can also have an IDENTIFIER_NODE if the earlier
20975 unqualified lookup found a dependent local extern declaration
20976 (as per finish_call_expr); in that case koenig_p will be false
20977 and we do want to do the lookup again to find the substituted
20978 declaration. */
20979 qualified_p = false;
20981 if (TREE_CODE (function) == TEMPLATE_ID_EXPR)
20982 /* Use tsubst_copy to substitute through the template arguments
20983 of the template-id without performing unqualified lookup of
20984 the template name. */
20985 function = tsubst_copy (function, args, complain, in_decl);
20987 else
20989 if (TREE_CODE (function) == COMPONENT_REF)
20991 tree op = TREE_OPERAND (function, 1);
20993 qualified_p = (TREE_CODE (op) == SCOPE_REF
20994 || (BASELINK_P (op)
20995 && BASELINK_QUALIFIED_P (op)));
20997 else
20998 qualified_p = false;
21000 if (TREE_CODE (function) == ADDR_EXPR
21001 && TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
21002 /* Avoid error about taking the address of a constructor. */
21003 function = TREE_OPERAND (function, 0);
21005 tsubst_flags_t subcomplain = complain;
21006 if (koenig_p && TREE_CODE (function) == FUNCTION_DECL)
21007 /* When KOENIG_P, we don't want to mark_used the callee before
21008 augmenting the overload set via ADL, so during this initial
21009 substitution we disable mark_used by setting tf_conv (68942). */
21010 subcomplain |= tf_conv;
21011 function = tsubst_copy_and_build (function, args, subcomplain, in_decl);
21013 if (BASELINK_P (function))
21014 qualified_p = true;
21017 nargs = call_expr_nargs (t);
21018 releasing_vec call_args;
21019 tsubst_copy_and_build_call_args (t, args, complain, in_decl,
21020 call_args);
21022 /* Stripped-down processing for a call in a thunk. Specifically, in
21023 the thunk template for a generic lambda. */
21024 if (call_from_lambda_thunk_p (t))
21026 /* Now that we've expanded any packs, the number of call args
21027 might be different. */
21028 unsigned int cargs = call_args->length ();
21029 tree thisarg = NULL_TREE;
21030 if (TREE_CODE (function) == COMPONENT_REF)
21032 thisarg = TREE_OPERAND (function, 0);
21033 if (TREE_CODE (thisarg) == INDIRECT_REF)
21034 thisarg = TREE_OPERAND (thisarg, 0);
21035 function = TREE_OPERAND (function, 1);
21036 if (TREE_CODE (function) == BASELINK)
21037 function = BASELINK_FUNCTIONS (function);
21039 /* We aren't going to do normal overload resolution, so force the
21040 template-id to resolve. */
21041 function = resolve_nondeduced_context (function, complain);
21042 for (unsigned i = 0; i < cargs; ++i)
21044 /* In a thunk, pass through args directly, without any
21045 conversions. */
21046 tree arg = (*call_args)[i];
21047 while (TREE_CODE (arg) != PARM_DECL)
21048 arg = TREE_OPERAND (arg, 0);
21049 (*call_args)[i] = arg;
21051 if (thisarg)
21053 /* If there are no other args, just push 'this'. */
21054 if (cargs == 0)
21055 vec_safe_push (call_args, thisarg);
21056 else
21058 /* Otherwise, shift the other args over to make room. */
21059 tree last = (*call_args)[cargs - 1];
21060 vec_safe_push (call_args, last);
21061 for (int i = cargs - 1; i > 0; --i)
21062 (*call_args)[i] = (*call_args)[i - 1];
21063 (*call_args)[0] = thisarg;
21066 ret = build_call_a (function, call_args->length (),
21067 call_args->address ());
21068 /* The thunk location is not interesting. */
21069 SET_EXPR_LOCATION (ret, UNKNOWN_LOCATION);
21070 CALL_FROM_THUNK_P (ret) = true;
21071 if (CLASS_TYPE_P (TREE_TYPE (ret)))
21072 CALL_EXPR_RETURN_SLOT_OPT (ret) = true;
21074 RETURN (ret);
21077 /* We do not perform argument-dependent lookup if normal
21078 lookup finds a non-function, in accordance with the
21079 resolution of DR 218. */
21080 if (koenig_p
21081 && ((is_overloaded_fn (function)
21082 /* If lookup found a member function, the Koenig lookup is
21083 not appropriate, even if an unqualified-name was used
21084 to denote the function. */
21085 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
21086 || identifier_p (function)
21087 /* C++20 P0846: Lookup found nothing. */
21088 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
21089 && identifier_p (TREE_OPERAND (function, 0))))
21090 /* Only do this when substitution turns a dependent call
21091 into a non-dependent call. */
21092 && type_dependent_expression_p_push (t)
21093 && !any_type_dependent_arguments_p (call_args))
21094 function = perform_koenig_lookup (function, call_args, tf_none);
21096 if (function != NULL_TREE
21097 && (identifier_p (function)
21098 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
21099 && identifier_p (TREE_OPERAND (function, 0))
21100 && !any_dependent_template_arguments_p (TREE_OPERAND
21101 (function, 1))))
21102 && !any_type_dependent_arguments_p (call_args))
21104 bool template_id_p = (TREE_CODE (function) == TEMPLATE_ID_EXPR);
21105 if (template_id_p)
21106 function = TREE_OPERAND (function, 0);
21107 if (koenig_p && (complain & tf_warning_or_error))
21109 /* For backwards compatibility and good diagnostics, try
21110 the unqualified lookup again if we aren't in SFINAE
21111 context. */
21112 tree unq = tsubst_copy_and_build (function, args,
21113 complain, in_decl);
21114 if (unq == error_mark_node)
21115 RETURN (error_mark_node);
21117 if (unq != function)
21119 char const *const msg
21120 = G_("%qD was not declared in this scope, "
21121 "and no declarations were found by "
21122 "argument-dependent lookup at the point "
21123 "of instantiation");
21125 bool in_lambda = (current_class_type
21126 && LAMBDA_TYPE_P (current_class_type));
21127 /* In a lambda fn, we have to be careful to not
21128 introduce new this captures. Legacy code can't
21129 be using lambdas anyway, so it's ok to be
21130 stricter. Be strict with C++20 template-id ADL too.
21131 And be strict if we're already failing anyway. */
21132 bool strict = in_lambda || template_id_p || seen_error();
21133 bool diag = true;
21134 if (strict)
21135 error_at (cp_expr_loc_or_input_loc (t),
21136 msg, function);
21137 else
21138 diag = permerror (cp_expr_loc_or_input_loc (t),
21139 msg, function);
21140 if (diag)
21142 tree fn = unq;
21144 if (INDIRECT_REF_P (fn))
21145 fn = TREE_OPERAND (fn, 0);
21146 if (is_overloaded_fn (fn))
21147 fn = get_first_fn (fn);
21149 if (!DECL_P (fn))
21150 /* Can't say anything more. */;
21151 else if (DECL_CLASS_SCOPE_P (fn))
21153 location_t loc = cp_expr_loc_or_input_loc (t);
21154 inform (loc,
21155 "declarations in dependent base %qT are "
21156 "not found by unqualified lookup",
21157 DECL_CLASS_CONTEXT (fn));
21158 if (current_class_ptr)
21159 inform (loc,
21160 "use %<this->%D%> instead", function);
21161 else
21162 inform (loc,
21163 "use %<%T::%D%> instead",
21164 current_class_name, function);
21166 else
21167 inform (DECL_SOURCE_LOCATION (fn),
21168 "%qD declared here, later in the "
21169 "translation unit", fn);
21170 if (strict)
21171 RETURN (error_mark_node);
21174 function = unq;
21177 if (identifier_p (function))
21179 if (complain & tf_error)
21180 unqualified_name_lookup_error (function);
21181 RETURN (error_mark_node);
21185 /* Remember that there was a reference to this entity. */
21186 if (function != NULL_TREE
21187 && DECL_P (function)
21188 && !mark_used (function, complain) && !(complain & tf_error))
21189 RETURN (error_mark_node);
21191 if (!maybe_fold_fn_template_args (function, complain))
21192 return error_mark_node;
21194 /* Put back tf_decltype for the actual call. */
21195 complain |= decltype_flag;
21197 if (function == NULL_TREE)
21198 switch (CALL_EXPR_IFN (t))
21200 case IFN_LAUNDER:
21201 gcc_assert (nargs == 1);
21202 if (vec_safe_length (call_args) != 1)
21204 error_at (cp_expr_loc_or_input_loc (t),
21205 "wrong number of arguments to "
21206 "%<__builtin_launder%>");
21207 ret = error_mark_node;
21209 else
21210 ret = finish_builtin_launder (cp_expr_loc_or_input_loc (t),
21211 (*call_args)[0], complain);
21212 break;
21214 case IFN_VEC_CONVERT:
21215 gcc_assert (nargs == 1);
21216 if (vec_safe_length (call_args) != 1)
21218 error_at (cp_expr_loc_or_input_loc (t),
21219 "wrong number of arguments to "
21220 "%<__builtin_convertvector%>");
21221 ret = error_mark_node;
21222 break;
21224 ret = cp_build_vec_convert ((*call_args)[0], input_location,
21225 tsubst (TREE_TYPE (t), args,
21226 complain, in_decl),
21227 complain);
21228 if (TREE_CODE (ret) == VIEW_CONVERT_EXPR)
21229 RETURN (ret);
21230 break;
21232 case IFN_SHUFFLEVECTOR:
21234 ret = build_x_shufflevector (input_location, call_args,
21235 complain);
21236 if (ret != error_mark_node)
21237 RETURN (ret);
21238 break;
21241 case IFN_ASSUME:
21242 gcc_assert (nargs == 1);
21243 if (vec_safe_length (call_args) != 1)
21245 error_at (cp_expr_loc_or_input_loc (t),
21246 "wrong number of arguments to "
21247 "%<assume%> attribute");
21248 ret = error_mark_node;
21250 else
21252 tree &arg = (*call_args)[0];
21253 if (!type_dependent_expression_p (arg))
21254 arg = contextual_conv_bool (arg, tf_warning_or_error);
21255 if (error_operand_p (arg))
21257 ret = error_mark_node;
21258 break;
21260 ret = build_assume_call (EXPR_LOCATION (t), arg);
21261 RETURN (ret);
21263 break;
21265 default:
21266 /* Unsupported internal function with arguments. */
21267 gcc_unreachable ();
21269 else if (TREE_CODE (function) == OFFSET_REF
21270 || TREE_CODE (function) == DOTSTAR_EXPR
21271 || TREE_CODE (function) == MEMBER_REF)
21272 ret = build_offset_ref_call_from_tree (function, &call_args,
21273 complain);
21274 else if (TREE_CODE (function) == COMPONENT_REF)
21276 tree instance = TREE_OPERAND (function, 0);
21277 tree fn = TREE_OPERAND (function, 1);
21279 if (processing_template_decl
21280 && (type_dependent_expression_p (instance)
21281 || (!BASELINK_P (fn)
21282 && TREE_CODE (fn) != FIELD_DECL)
21283 || type_dependent_expression_p (fn)
21284 || any_type_dependent_arguments_p (call_args)))
21285 ret = build_min_nt_call_vec (function, call_args);
21286 else if (!BASELINK_P (fn))
21287 ret = finish_call_expr (function, &call_args,
21288 /*disallow_virtual=*/false,
21289 /*koenig_p=*/false,
21290 complain);
21291 else
21292 ret = (build_new_method_call
21293 (instance, fn,
21294 &call_args, NULL_TREE,
21295 qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
21296 /*fn_p=*/NULL,
21297 complain));
21299 else if (concept_check_p (function))
21301 /* FUNCTION is a template-id referring to a concept definition. */
21302 tree id = unpack_concept_check (function);
21303 tree tmpl = TREE_OPERAND (id, 0);
21304 tree args = TREE_OPERAND (id, 1);
21306 /* Calls to standard and variable concepts should have been
21307 previously diagnosed. */
21308 gcc_assert (function_concept_p (tmpl));
21310 /* Ensure the result is wrapped as a call expression. */
21311 ret = build_concept_check (tmpl, args, tf_warning_or_error);
21313 else
21314 ret = finish_call_expr (function, &call_args,
21315 /*disallow_virtual=*/qualified_p,
21316 koenig_p,
21317 complain);
21319 if (ret != error_mark_node)
21321 bool op = CALL_EXPR_OPERATOR_SYNTAX (t);
21322 bool ord = CALL_EXPR_ORDERED_ARGS (t);
21323 bool rev = CALL_EXPR_REVERSE_ARGS (t);
21324 if (op || ord || rev)
21325 if (tree call = extract_call_expr (ret))
21327 CALL_EXPR_OPERATOR_SYNTAX (call) = op;
21328 CALL_EXPR_ORDERED_ARGS (call) = ord;
21329 CALL_EXPR_REVERSE_ARGS (call) = rev;
21331 if (warning_suppressed_p (t, OPT_Wpessimizing_move))
21332 /* This also suppresses -Wredundant-move. */
21333 suppress_warning (ret, OPT_Wpessimizing_move);
21336 RETURN (ret);
21339 case COND_EXPR:
21341 tree cond = RECUR (TREE_OPERAND (t, 0));
21342 cond = mark_rvalue_use (cond);
21343 tree folded_cond = fold_non_dependent_expr (cond, complain);
21344 tree exp1, exp2;
21346 if (TREE_CODE (folded_cond) == INTEGER_CST)
21348 if (integer_zerop (folded_cond))
21350 ++c_inhibit_evaluation_warnings;
21351 exp1 = RECUR (TREE_OPERAND (t, 1));
21352 --c_inhibit_evaluation_warnings;
21353 exp2 = RECUR (TREE_OPERAND (t, 2));
21355 else
21357 exp1 = RECUR (TREE_OPERAND (t, 1));
21358 ++c_inhibit_evaluation_warnings;
21359 exp2 = RECUR (TREE_OPERAND (t, 2));
21360 --c_inhibit_evaluation_warnings;
21362 cond = folded_cond;
21364 else
21366 exp1 = RECUR (TREE_OPERAND (t, 1));
21367 exp2 = RECUR (TREE_OPERAND (t, 2));
21370 warning_sentinel s(warn_duplicated_branches);
21371 RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
21372 cond, exp1, exp2, complain));
21375 case PSEUDO_DTOR_EXPR:
21377 tree op0 = RECUR (TREE_OPERAND (t, 0));
21378 tree op1 = RECUR (TREE_OPERAND (t, 1));
21379 tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
21380 RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
21381 input_location));
21384 case TREE_LIST:
21385 RETURN (tsubst_tree_list (t, args, complain, in_decl));
21387 case COMPONENT_REF:
21389 tree object;
21390 tree object_type;
21391 tree member;
21392 tree r;
21394 object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
21395 args, complain, in_decl);
21396 /* Remember that there was a reference to this entity. */
21397 if (DECL_P (object)
21398 && !mark_used (object, complain) && !(complain & tf_error))
21399 RETURN (error_mark_node);
21400 object_type = TREE_TYPE (object);
21402 member = TREE_OPERAND (t, 1);
21403 if (BASELINK_P (member))
21404 member = tsubst_baselink (member,
21405 non_reference (TREE_TYPE (object)),
21406 args, complain, in_decl);
21407 else
21408 member = tsubst_copy (member, args, complain, in_decl);
21409 if (member == error_mark_node)
21410 RETURN (error_mark_node);
21412 if (object_type && TYPE_PTRMEMFUNC_P (object_type)
21413 && TREE_CODE (member) == FIELD_DECL)
21415 r = build_ptrmemfunc_access_expr (object, DECL_NAME (member));
21416 RETURN (r);
21418 else if (TREE_CODE (member) == FIELD_DECL)
21420 r = finish_non_static_data_member (member, object, NULL_TREE,
21421 complain);
21422 if (TREE_CODE (r) == COMPONENT_REF)
21423 REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
21424 RETURN (r);
21426 else if (type_dependent_expression_p (object))
21427 /* We can't do much here. */;
21428 else if (!CLASS_TYPE_P (object_type))
21430 if (scalarish_type_p (object_type))
21432 tree s = NULL_TREE;
21433 tree dtor = member;
21435 if (TREE_CODE (dtor) == SCOPE_REF)
21437 s = TREE_OPERAND (dtor, 0);
21438 dtor = TREE_OPERAND (dtor, 1);
21440 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
21442 dtor = TREE_OPERAND (dtor, 0);
21443 if (TYPE_P (dtor))
21444 RETURN (finish_pseudo_destructor_expr
21445 (object, s, dtor, input_location));
21449 else if (TREE_CODE (member) == SCOPE_REF
21450 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
21452 /* Lookup the template functions now that we know what the
21453 scope is. */
21454 tree scope = TREE_OPERAND (member, 0);
21455 tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
21456 tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
21457 member = lookup_qualified_name (scope, tmpl, LOOK_want::NORMAL,
21458 /*complain=*/false);
21459 if (BASELINK_P (member))
21461 BASELINK_FUNCTIONS (member)
21462 = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
21463 args);
21464 member = (adjust_result_of_qualified_name_lookup
21465 (member, BINFO_TYPE (BASELINK_BINFO (member)),
21466 object_type));
21468 else
21470 qualified_name_lookup_error (scope, tmpl, member,
21471 input_location);
21472 RETURN (error_mark_node);
21475 else if (TREE_CODE (member) == SCOPE_REF
21476 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
21477 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
21479 if (complain & tf_error)
21481 if (TYPE_P (TREE_OPERAND (member, 0)))
21482 error ("%qT is not a class or namespace",
21483 TREE_OPERAND (member, 0));
21484 else
21485 error ("%qD is not a class or namespace",
21486 TREE_OPERAND (member, 0));
21488 RETURN (error_mark_node);
21491 r = finish_class_member_access_expr (object, member,
21492 /*template_p=*/false,
21493 complain);
21494 if (REF_PARENTHESIZED_P (t))
21495 r = force_paren_expr (r);
21496 RETURN (r);
21499 case THROW_EXPR:
21500 RETURN (build_throw
21501 (input_location, RECUR (TREE_OPERAND (t, 0))));
21503 case CONSTRUCTOR:
21505 vec<constructor_elt, va_gc> *n;
21506 constructor_elt *ce;
21507 unsigned HOST_WIDE_INT idx;
21508 bool process_index_p;
21509 int newlen;
21510 bool need_copy_p = false;
21511 tree r;
21513 tsubst_flags_t tcomplain = complain;
21514 if (COMPOUND_LITERAL_P (t))
21515 tcomplain |= tf_tst_ok;
21516 tree type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
21517 if (type == error_mark_node)
21518 RETURN (error_mark_node);
21520 /* We do not want to process the index of aggregate
21521 initializers as they are identifier nodes which will be
21522 looked up by digest_init. */
21523 process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
21525 if (null_member_pointer_value_p (t))
21527 gcc_assert (same_type_p (type, TREE_TYPE (t)));
21528 RETURN (t);
21531 n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
21532 newlen = vec_safe_length (n);
21533 FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
21535 if (ce->index && process_index_p
21536 /* An identifier index is looked up in the type
21537 being initialized, not the current scope. */
21538 && TREE_CODE (ce->index) != IDENTIFIER_NODE)
21539 ce->index = RECUR (ce->index);
21541 if (PACK_EXPANSION_P (ce->value))
21543 /* Substitute into the pack expansion. */
21544 ce->value = tsubst_pack_expansion (ce->value, args, complain,
21545 in_decl);
21547 if (ce->value == error_mark_node
21548 || PACK_EXPANSION_P (ce->value))
21550 else if (TREE_VEC_LENGTH (ce->value) == 1)
21551 /* Just move the argument into place. */
21552 ce->value = TREE_VEC_ELT (ce->value, 0);
21553 else
21555 /* Update the length of the final CONSTRUCTOR
21556 arguments vector, and note that we will need to
21557 copy.*/
21558 newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
21559 need_copy_p = true;
21562 else
21563 ce->value = RECUR (ce->value);
21566 if (need_copy_p)
21568 vec<constructor_elt, va_gc> *old_n = n;
21570 vec_alloc (n, newlen);
21571 FOR_EACH_VEC_ELT (*old_n, idx, ce)
21573 if (TREE_CODE (ce->value) == TREE_VEC)
21575 int i, len = TREE_VEC_LENGTH (ce->value);
21576 for (i = 0; i < len; ++i)
21577 CONSTRUCTOR_APPEND_ELT (n, 0,
21578 TREE_VEC_ELT (ce->value, i));
21580 else
21581 CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
21585 r = build_constructor (init_list_type_node, n);
21586 CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
21587 CONSTRUCTOR_IS_DESIGNATED_INIT (r)
21588 = CONSTRUCTOR_IS_DESIGNATED_INIT (t);
21590 if (TREE_HAS_CONSTRUCTOR (t))
21592 fcl_t cl = fcl_functional;
21593 if (CONSTRUCTOR_C99_COMPOUND_LITERAL (t))
21594 cl = fcl_c99;
21595 RETURN (finish_compound_literal (type, r, complain, cl));
21598 TREE_TYPE (r) = type;
21599 RETURN (r);
21602 case TYPEID_EXPR:
21604 tree operand_0 = TREE_OPERAND (t, 0);
21605 if (TYPE_P (operand_0))
21607 operand_0 = tsubst (operand_0, args, complain, in_decl);
21608 RETURN (get_typeid (operand_0, complain));
21610 else
21612 operand_0 = RECUR (operand_0);
21613 RETURN (build_typeid (operand_0, complain));
21617 case VAR_DECL:
21618 if (!args)
21619 RETURN (t);
21620 /* Fall through */
21622 case PARM_DECL:
21624 tree r = tsubst_copy (t, args, complain, in_decl);
21625 /* ??? We're doing a subset of finish_id_expression here. */
21626 if (tree wrap = maybe_get_tls_wrapper_call (r))
21627 /* Replace an evaluated use of the thread_local variable with
21628 a call to its wrapper. */
21629 r = wrap;
21630 else if (outer_automatic_var_p (r))
21631 r = process_outer_var_ref (r, complain);
21633 if (!TYPE_REF_P (TREE_TYPE (t)))
21634 /* If the original type was a reference, we'll be wrapped in
21635 the appropriate INDIRECT_REF. */
21636 r = convert_from_reference (r);
21637 RETURN (r);
21640 case VA_ARG_EXPR:
21642 tree op0 = RECUR (TREE_OPERAND (t, 0));
21643 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21644 RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
21647 case OFFSETOF_EXPR:
21649 tree object_ptr
21650 = tsubst_copy_and_build (TREE_OPERAND (t, 1), args,
21651 complain, in_decl);
21652 RETURN (finish_offsetof (object_ptr,
21653 RECUR (TREE_OPERAND (t, 0)),
21654 EXPR_LOCATION (t)));
21657 case ADDRESSOF_EXPR:
21658 RETURN (cp_build_addressof (EXPR_LOCATION (t),
21659 RECUR (TREE_OPERAND (t, 0)), complain));
21661 case TRAIT_EXPR:
21663 tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
21664 complain, in_decl);
21665 tree type2 = tsubst (TRAIT_EXPR_TYPE2 (t), args,
21666 complain, in_decl);
21667 RETURN (finish_trait_expr (TRAIT_EXPR_LOCATION (t),
21668 TRAIT_EXPR_KIND (t), type1, type2));
21671 case STMT_EXPR:
21673 tree old_stmt_expr = cur_stmt_expr;
21674 tree stmt_expr = begin_stmt_expr ();
21676 cur_stmt_expr = stmt_expr;
21677 tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl);
21678 stmt_expr = finish_stmt_expr (stmt_expr, false);
21679 cur_stmt_expr = old_stmt_expr;
21681 /* If the resulting list of expression statement is empty,
21682 fold it further into void_node. */
21683 if (empty_expr_stmt_p (stmt_expr))
21684 stmt_expr = void_node;
21686 RETURN (stmt_expr);
21689 case LAMBDA_EXPR:
21691 if (complain & tf_partial)
21693 /* We don't have a full set of template arguments yet; don't touch
21694 the lambda at all. */
21695 gcc_assert (processing_template_decl);
21696 return t;
21698 tree r = tsubst_lambda_expr (t, args, complain, in_decl);
21700 RETURN (build_lambda_object (r));
21703 case TRANSACTION_EXPR:
21704 RETURN (tsubst_expr (t, args, complain, in_decl));
21706 case PAREN_EXPR:
21707 if (REF_PARENTHESIZED_P (t))
21708 RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
21709 else
21710 /* Recreate the PAREN_EXPR from __builtin_assoc_barrier. */
21712 tree op0 = RECUR (TREE_OPERAND (t, 0));
21713 RETURN (build1_loc (input_location, PAREN_EXPR,
21714 TREE_TYPE (op0), op0));
21717 case VEC_PERM_EXPR:
21719 tree op0 = RECUR (TREE_OPERAND (t, 0));
21720 tree op1 = RECUR (TREE_OPERAND (t, 1));
21721 tree op2 = RECUR (TREE_OPERAND (t, 2));
21722 RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
21723 complain));
21726 case REQUIRES_EXPR:
21728 tree r = tsubst_requires_expr (t, args, tf_none, in_decl);
21729 RETURN (r);
21732 case RANGE_EXPR:
21733 /* No need to substitute further, a RANGE_EXPR will always be built
21734 with constant operands. */
21735 RETURN (t);
21737 case NON_LVALUE_EXPR:
21738 case VIEW_CONVERT_EXPR:
21740 tree op = RECUR (TREE_OPERAND (t, 0));
21742 if (location_wrapper_p (t))
21743 /* We need to do this here as well as in tsubst_copy so we get the
21744 other tsubst_copy_and_build semantics for a PARM_DECL operand. */
21745 RETURN (maybe_wrap_with_location (op, EXPR_LOCATION (t)));
21747 gcc_checking_assert (TREE_CODE (t) == VIEW_CONVERT_EXPR);
21748 if (REF_PARENTHESIZED_P (t))
21749 /* force_paren_expr can also create a VIEW_CONVERT_EXPR. */
21750 RETURN (finish_parenthesized_expr (op));
21752 /* Otherwise, we're dealing with a wrapper to make a C++20 template
21753 parameter object const. */
21754 if (TREE_TYPE (op) == NULL_TREE
21755 || !CP_TYPE_CONST_P (TREE_TYPE (op)))
21757 /* The template argument is not const, presumably because
21758 it is still dependent, and so not the const template parm
21759 object. */
21760 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21761 if (TREE_CODE (op) == CONSTRUCTOR
21762 || TREE_CODE (op) == IMPLICIT_CONV_EXPR)
21764 /* Don't add a wrapper to these. */
21765 op = copy_node (op);
21766 TREE_TYPE (op) = type;
21768 else
21769 /* Do add a wrapper otherwise (in particular, if op is
21770 another TEMPLATE_PARM_INDEX). */
21771 op = build1 (VIEW_CONVERT_EXPR, type, op);
21773 RETURN (op);
21776 default:
21777 /* Handle Objective-C++ constructs, if appropriate. */
21779 tree subst
21780 = objcp_tsubst_copy_and_build (t, args, complain, in_decl);
21781 if (subst)
21782 RETURN (subst);
21784 RETURN (tsubst_copy (t, args, complain, in_decl));
21787 #undef RECUR
21788 #undef RETURN
21789 out:
21790 input_location = save_loc;
21791 return retval;
21794 /* Verify that the instantiated ARGS are valid. For type arguments,
21795 make sure that the type's linkage is ok. For non-type arguments,
21796 make sure they are constants if they are integral or enumerations.
21797 Emit an error under control of COMPLAIN, and return TRUE on error. */
21799 static bool
21800 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
21802 if (dependent_template_arg_p (t))
21803 return false;
21804 if (ARGUMENT_PACK_P (t))
21806 tree vec = ARGUMENT_PACK_ARGS (t);
21807 int len = TREE_VEC_LENGTH (vec);
21808 bool result = false;
21809 int i;
21811 for (i = 0; i < len; ++i)
21812 if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
21813 result = true;
21814 return result;
21816 else if (TYPE_P (t))
21818 /* [basic.link]: A name with no linkage (notably, the name
21819 of a class or enumeration declared in a local scope)
21820 shall not be used to declare an entity with linkage.
21821 This implies that names with no linkage cannot be used as
21822 template arguments
21824 DR 757 relaxes this restriction for C++0x. */
21825 tree nt = (cxx_dialect > cxx98 ? NULL_TREE
21826 : no_linkage_check (t, /*relaxed_p=*/false));
21828 if (nt)
21830 /* DR 488 makes use of a type with no linkage cause
21831 type deduction to fail. */
21832 if (complain & tf_error)
21834 if (TYPE_UNNAMED_P (nt))
21835 error ("%qT is/uses unnamed type", t);
21836 else
21837 error ("template argument for %qD uses local type %qT",
21838 tmpl, t);
21840 return true;
21842 /* In order to avoid all sorts of complications, we do not
21843 allow variably-modified types as template arguments. */
21844 else if (variably_modified_type_p (t, NULL_TREE))
21846 if (complain & tf_error)
21847 error ("%qT is a variably modified type", t);
21848 return true;
21851 /* Class template and alias template arguments should be OK. */
21852 else if (DECL_TYPE_TEMPLATE_P (t))
21854 /* A non-type argument of integral or enumerated type must be a
21855 constant. */
21856 else if (TREE_TYPE (t)
21857 && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
21858 && !REFERENCE_REF_P (t)
21859 && !TREE_CONSTANT (t))
21861 if (complain & tf_error)
21862 error ("integral expression %qE is not constant", t);
21863 return true;
21865 return false;
21868 static bool
21869 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
21871 int ix, len = DECL_NTPARMS (tmpl);
21872 bool result = false;
21874 for (ix = 0; ix != len; ix++)
21876 if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
21877 result = true;
21879 if (result && (complain & tf_error))
21880 error (" trying to instantiate %qD", tmpl);
21881 return result;
21884 /* Call mark_used on each entity within the non-type template arguments in
21885 ARGS for an instantiation of TMPL, to ensure that each such entity is
21886 considered odr-used (and therefore marked for instantiation) regardless of
21887 whether the specialization was first formed in a template context (which
21888 inhibits mark_used).
21890 This function assumes push_to_top_level has been called beforehand. */
21892 static void
21893 mark_template_arguments_used (tree tmpl, tree args)
21895 /* It suffices to do this only when instantiating a primary template. */
21896 if (TREE_CODE (tmpl) != TEMPLATE_DECL || !PRIMARY_TEMPLATE_P (tmpl))
21897 return;
21899 /* We already marked outer arguments when specializing the context. */
21900 args = INNERMOST_TEMPLATE_ARGS (args);
21902 for (tree arg : tree_vec_range (args))
21904 /* A (pointer/reference to) function or variable NTTP argument. */
21905 if (TREE_CODE (arg) == ADDR_EXPR
21906 || TREE_CODE (arg) == INDIRECT_REF)
21908 while (TREE_CODE (arg) == ADDR_EXPR
21909 || REFERENCE_REF_P (arg)
21910 || CONVERT_EXPR_P (arg))
21911 arg = TREE_OPERAND (arg, 0);
21912 if (VAR_OR_FUNCTION_DECL_P (arg))
21914 /* Pass tf_none to avoid duplicate diagnostics: if this call
21915 fails then an earlier call to mark_used for this argument
21916 must have also failed and emitted a diagnostic. */
21917 bool ok = mark_used (arg, tf_none);
21918 gcc_checking_assert (ok || seen_error ());
21921 /* A class NTTP argument. */
21922 else if (VAR_P (arg)
21923 && DECL_NTTP_OBJECT_P (arg))
21925 auto mark_used_r = [](tree *tp, int *, void *) {
21926 if (VAR_OR_FUNCTION_DECL_P (*tp))
21928 bool ok = mark_used (*tp, tf_none);
21929 gcc_checking_assert (ok || seen_error ());
21931 return NULL_TREE;
21933 cp_walk_tree_without_duplicates (&DECL_INITIAL (arg),
21934 mark_used_r, nullptr);
21939 /* We're out of SFINAE context now, so generate diagnostics for the access
21940 errors we saw earlier when instantiating D from TMPL and ARGS. */
21942 static void
21943 recheck_decl_substitution (tree d, tree tmpl, tree args)
21945 tree pattern = DECL_TEMPLATE_RESULT (tmpl);
21946 tree type = TREE_TYPE (pattern);
21947 location_t loc = input_location;
21949 push_access_scope (d);
21950 push_deferring_access_checks (dk_no_deferred);
21951 input_location = DECL_SOURCE_LOCATION (pattern);
21952 tsubst (type, args, tf_warning_or_error, d);
21953 input_location = loc;
21954 pop_deferring_access_checks ();
21955 pop_access_scope (d);
21958 /* Instantiate the indicated variable, function, or alias template TMPL with
21959 the template arguments in TARG_PTR. */
21961 tree
21962 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
21964 auto_timevar tv (TV_TEMPLATE_INST);
21966 tree targ_ptr = orig_args;
21967 tree fndecl;
21968 tree gen_tmpl;
21969 tree spec;
21970 bool access_ok = true;
21972 if (tmpl == error_mark_node)
21973 return error_mark_node;
21975 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
21977 if (modules_p ())
21978 lazy_load_pendings (tmpl);
21980 /* If this function is a clone, handle it specially. */
21981 if (DECL_CLONED_FUNCTION_P (tmpl))
21983 tree spec;
21984 tree clone;
21986 /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
21987 DECL_CLONED_FUNCTION. */
21988 spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
21989 targ_ptr, complain);
21990 if (spec == error_mark_node)
21991 return error_mark_node;
21993 /* Look for the clone. */
21994 FOR_EACH_CLONE (clone, spec)
21995 if (DECL_NAME (clone) == DECL_NAME (tmpl))
21996 return clone;
21997 /* We should always have found the clone by now. */
21998 gcc_unreachable ();
21999 return NULL_TREE;
22002 if (targ_ptr == error_mark_node)
22003 return error_mark_node;
22005 /* Check to see if we already have this specialization. */
22006 gen_tmpl = most_general_template (tmpl);
22007 if (TMPL_ARGS_DEPTH (targ_ptr)
22008 < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)))
22009 /* targ_ptr only has the innermost template args, so add the outer ones
22010 from tmpl, which could be either a partial instantiation or gen_tmpl (in
22011 the case of a non-dependent call within a template definition). */
22012 targ_ptr = (add_outermost_template_args
22013 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (tmpl)),
22014 targ_ptr));
22016 /* It would be nice to avoid hashing here and then again in tsubst_decl,
22017 but it doesn't seem to be on the hot path. */
22018 spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
22020 gcc_checking_assert (tmpl == gen_tmpl
22021 || ((fndecl
22022 = retrieve_specialization (tmpl, orig_args, 0))
22023 == spec)
22024 || fndecl == NULL_TREE);
22026 if (spec != NULL_TREE)
22028 if (FNDECL_HAS_ACCESS_ERRORS (spec))
22030 if (complain & tf_error)
22031 recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
22032 return error_mark_node;
22034 return spec;
22037 if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
22038 complain))
22039 return error_mark_node;
22041 /* We are building a FUNCTION_DECL, during which the access of its
22042 parameters and return types have to be checked. However this
22043 FUNCTION_DECL which is the desired context for access checking
22044 is not built yet. We solve this chicken-and-egg problem by
22045 deferring all checks until we have the FUNCTION_DECL. */
22046 push_deferring_access_checks (dk_deferred);
22048 /* Instantiation of the function happens in the context of the function
22049 template, not the context of the overload resolution we're doing. */
22050 push_to_top_level ();
22051 /* If there are dependent arguments, e.g. because we're doing partial
22052 ordering, make sure processing_template_decl stays set. */
22053 if (uses_template_parms (targ_ptr))
22054 ++processing_template_decl;
22055 if (DECL_CLASS_SCOPE_P (gen_tmpl))
22057 tree ctx;
22058 if (!uses_template_parms (DECL_CONTEXT (tmpl)))
22059 /* If the context of the partially instantiated template is
22060 already non-dependent, then we might as well use it. */
22061 ctx = DECL_CONTEXT (tmpl);
22062 else
22063 ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
22064 complain, gen_tmpl, true);
22065 push_nested_class (ctx);
22068 tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
22070 fndecl = NULL_TREE;
22071 if (VAR_P (pattern))
22073 /* We need to determine if we're using a partial or explicit
22074 specialization now, because the type of the variable could be
22075 different. */
22076 tree tid = lookup_template_variable (tmpl, targ_ptr);
22077 tree elt = most_specialized_partial_spec (tid, complain);
22078 if (elt == error_mark_node)
22079 pattern = error_mark_node;
22080 else if (elt)
22082 tree partial_tmpl = TREE_VALUE (elt);
22083 tree partial_args = TREE_PURPOSE (elt);
22084 tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
22085 fndecl = tsubst (partial_pat, partial_args, complain, gen_tmpl);
22089 /* Substitute template parameters to obtain the specialization. */
22090 if (fndecl == NULL_TREE)
22091 fndecl = tsubst (pattern, targ_ptr, complain, gen_tmpl);
22092 if (DECL_CLASS_SCOPE_P (gen_tmpl))
22093 pop_nested_class ();
22094 pop_from_top_level ();
22096 if (fndecl == error_mark_node)
22098 pop_deferring_access_checks ();
22099 return error_mark_node;
22102 /* The DECL_TI_TEMPLATE should always be the immediate parent
22103 template, not the most general template. */
22104 DECL_TI_TEMPLATE (fndecl) = tmpl;
22105 DECL_TI_ARGS (fndecl) = targ_ptr;
22107 set_instantiating_module (fndecl);
22109 /* Now we know the specialization, compute access previously
22110 deferred. Do no access control for inheriting constructors,
22111 as we already checked access for the inherited constructor. */
22112 if (!(flag_new_inheriting_ctors
22113 && DECL_INHERITED_CTOR (fndecl)))
22115 push_access_scope (fndecl);
22116 if (!perform_deferred_access_checks (complain))
22117 access_ok = false;
22118 pop_access_scope (fndecl);
22120 pop_deferring_access_checks ();
22122 /* If we've just instantiated the main entry point for a function,
22123 instantiate all the alternate entry points as well. We do this
22124 by cloning the instantiation of the main entry point, not by
22125 instantiating the template clones. */
22126 if (tree chain = DECL_CHAIN (gen_tmpl))
22127 if (DECL_P (chain) && DECL_CLONED_FUNCTION_P (chain))
22128 clone_cdtor (fndecl, /*update_methods=*/false);
22130 if (!access_ok)
22132 if (!(complain & tf_error))
22134 /* Remember to reinstantiate when we're out of SFINAE so the user
22135 can see the errors. */
22136 FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
22138 return error_mark_node;
22141 return fndecl;
22144 /* Instantiate the alias template TMPL with ARGS. Also push a template
22145 instantiation level, which instantiate_template doesn't do because
22146 functions and variables have sufficient context established by the
22147 callers. */
22149 static tree
22150 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
22152 if (tmpl == error_mark_node || args == error_mark_node)
22153 return error_mark_node;
22155 args = coerce_template_parms (DECL_TEMPLATE_PARMS (tmpl),
22156 args, tmpl, complain);
22157 if (args == error_mark_node)
22158 return error_mark_node;
22160 /* FIXME check for satisfaction in check_instantiated_args. */
22161 if (!constraints_satisfied_p (tmpl, args))
22163 if (complain & tf_error)
22165 auto_diagnostic_group d;
22166 error ("template constraint failure for %qD", tmpl);
22167 diagnose_constraints (input_location, tmpl, args);
22169 return error_mark_node;
22172 if (!push_tinst_level (tmpl, args))
22173 return error_mark_node;
22174 tree r = instantiate_template (tmpl, args, complain);
22175 pop_tinst_level ();
22177 if (tree d = dependent_alias_template_spec_p (TREE_TYPE (r), nt_opaque))
22179 /* An alias template specialization can be dependent
22180 even if its underlying type is not. */
22181 TYPE_DEPENDENT_P (d) = true;
22182 TYPE_DEPENDENT_P_VALID (d) = true;
22183 /* Sometimes a dependent alias spec is equivalent to its expansion,
22184 sometimes not. So always use structural_comptypes. */
22185 SET_TYPE_STRUCTURAL_EQUALITY (d);
22188 return r;
22191 /* PARM is a template parameter pack for FN. Returns true iff
22192 PARM is used in a deducible way in the argument list of FN. */
22194 static bool
22195 pack_deducible_p (tree parm, tree fn)
22197 tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
22198 for (; t; t = TREE_CHAIN (t))
22200 tree type = TREE_VALUE (t);
22201 tree packs;
22202 if (!PACK_EXPANSION_P (type))
22203 continue;
22204 for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
22205 packs; packs = TREE_CHAIN (packs))
22206 if (template_args_equal (TREE_VALUE (packs), parm))
22208 /* The template parameter pack is used in a function parameter
22209 pack. If this is the end of the parameter list, the
22210 template parameter pack is deducible. */
22211 if (TREE_CHAIN (t) == void_list_node)
22212 return true;
22213 else
22214 /* Otherwise, not. Well, it could be deduced from
22215 a non-pack parameter, but doing so would end up with
22216 a deduction mismatch, so don't bother. */
22217 return false;
22220 /* The template parameter pack isn't used in any function parameter
22221 packs, but it might be used deeper, e.g. tuple<Args...>. */
22222 return true;
22225 /* Subroutine of fn_type_unification: check non-dependent parms for
22226 convertibility. */
22228 static int
22229 check_non_deducible_conversions (tree parms, const tree *args, unsigned nargs,
22230 tree fn, unification_kind_t strict, int flags,
22231 struct conversion **convs, bool explain_p)
22233 /* Non-constructor methods need to leave a conversion for 'this', which
22234 isn't included in nargs here. */
22235 unsigned offset = (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
22236 && !DECL_CONSTRUCTOR_P (fn));
22238 for (unsigned ia = 0;
22239 parms && parms != void_list_node && ia < nargs; )
22241 tree parm = TREE_VALUE (parms);
22243 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
22244 && (!TREE_CHAIN (parms)
22245 || TREE_CHAIN (parms) == void_list_node))
22246 /* For a function parameter pack that occurs at the end of the
22247 parameter-declaration-list, the type A of each remaining
22248 argument of the call is compared with the type P of the
22249 declarator-id of the function parameter pack. */
22250 break;
22252 parms = TREE_CHAIN (parms);
22254 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
22255 /* For a function parameter pack that does not occur at the
22256 end of the parameter-declaration-list, the type of the
22257 parameter pack is a non-deduced context. */
22258 continue;
22260 if (!uses_template_parms (parm))
22262 tree arg = args[ia];
22263 conversion **conv_p = convs ? &convs[ia+offset] : NULL;
22264 int lflags = conv_flags (ia, nargs, fn, arg, flags);
22266 if (check_non_deducible_conversion (parm, arg, strict, lflags,
22267 conv_p, explain_p))
22268 return 1;
22271 ++ia;
22274 return 0;
22277 /* The FN is a TEMPLATE_DECL for a function. ARGS is an array with
22278 NARGS elements of the arguments that are being used when calling
22279 it. TARGS is a vector into which the deduced template arguments
22280 are placed.
22282 Returns either a FUNCTION_DECL for the matching specialization of FN or
22283 NULL_TREE if no suitable specialization can be found. If EXPLAIN_P is
22284 true, diagnostics will be printed to explain why it failed.
22286 If FN is a conversion operator, or we are trying to produce a specific
22287 specialization, RETURN_TYPE is the return type desired.
22289 The EXPLICIT_TARGS are explicit template arguments provided via a
22290 template-id.
22292 The parameter STRICT is one of:
22294 DEDUCE_CALL:
22295 We are deducing arguments for a function call, as in
22296 [temp.deduct.call]. If RETURN_TYPE is non-null, we are
22297 deducing arguments for a call to the result of a conversion
22298 function template, as in [over.call.object].
22300 DEDUCE_CONV:
22301 We are deducing arguments for a conversion function, as in
22302 [temp.deduct.conv].
22304 DEDUCE_EXACT:
22305 We are deducing arguments when doing an explicit instantiation
22306 as in [temp.explicit], when determining an explicit specialization
22307 as in [temp.expl.spec], or when taking the address of a function
22308 template, as in [temp.deduct.funcaddr]. */
22310 tree
22311 fn_type_unification (tree fn,
22312 tree explicit_targs,
22313 tree targs,
22314 const tree *args,
22315 unsigned int nargs,
22316 tree return_type,
22317 unification_kind_t strict,
22318 int flags,
22319 struct conversion **convs,
22320 bool explain_p,
22321 bool decltype_p)
22323 tree parms;
22324 tree fntype;
22325 tree decl = NULL_TREE;
22326 tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
22327 bool ok;
22328 static int deduction_depth;
22329 /* type_unification_real will pass back any access checks from default
22330 template argument substitution. */
22331 vec<deferred_access_check, va_gc> *checks = NULL;
22332 /* We don't have all the template args yet. */
22333 bool incomplete = true;
22335 tree orig_fn = fn;
22336 if (flag_new_inheriting_ctors)
22337 fn = strip_inheriting_ctors (fn);
22339 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
22340 tree r = error_mark_node;
22342 tree full_targs = targs;
22343 if (TMPL_ARGS_DEPTH (targs)
22344 < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (fn)))
22345 full_targs = (add_outermost_template_args
22346 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (fn)),
22347 targs));
22349 if (decltype_p)
22350 complain |= tf_decltype;
22352 /* In C++0x, it's possible to have a function template whose type depends
22353 on itself recursively. This is most obvious with decltype, but can also
22354 occur with enumeration scope (c++/48969). So we need to catch infinite
22355 recursion and reject the substitution at deduction time; this function
22356 will return error_mark_node for any repeated substitution.
22358 This also catches excessive recursion such as when f<N> depends on
22359 f<N-1> across all integers, and returns error_mark_node for all the
22360 substitutions back up to the initial one.
22362 This is, of course, not reentrant. */
22363 if (excessive_deduction_depth)
22364 return error_mark_node;
22365 ++deduction_depth;
22367 gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
22369 fntype = TREE_TYPE (fn);
22370 if (explicit_targs)
22372 /* [temp.deduct]
22374 The specified template arguments must match the template
22375 parameters in kind (i.e., type, nontype, template), and there
22376 must not be more arguments than there are parameters;
22377 otherwise type deduction fails.
22379 Nontype arguments must match the types of the corresponding
22380 nontype template parameters, or must be convertible to the
22381 types of the corresponding nontype parameters as specified in
22382 _temp.arg.nontype_, otherwise type deduction fails.
22384 All references in the function type of the function template
22385 to the corresponding template parameters are replaced by the
22386 specified template argument values. If a substitution in a
22387 template parameter or in the function type of the function
22388 template results in an invalid type, type deduction fails. */
22389 int i, len = TREE_VEC_LENGTH (tparms);
22390 location_t loc = input_location;
22391 incomplete = false;
22393 if (explicit_targs == error_mark_node)
22394 goto fail;
22396 if (TMPL_ARGS_DEPTH (explicit_targs)
22397 < TMPL_ARGS_DEPTH (full_targs))
22398 explicit_targs = add_outermost_template_args (full_targs,
22399 explicit_targs);
22401 /* Adjust any explicit template arguments before entering the
22402 substitution context. */
22403 explicit_targs
22404 = (coerce_template_parms (tparms, explicit_targs, fn,
22405 complain|tf_partial,
22406 /*require_all_args=*/false));
22407 if (explicit_targs == error_mark_node)
22408 goto fail;
22410 /* Substitute the explicit args into the function type. This is
22411 necessary so that, for instance, explicitly declared function
22412 arguments can match null pointed constants. If we were given
22413 an incomplete set of explicit args, we must not do semantic
22414 processing during substitution as we could create partial
22415 instantiations. */
22416 for (i = 0; i < len; i++)
22418 tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
22419 bool parameter_pack = false;
22420 tree targ = TREE_VEC_ELT (explicit_targs, i);
22422 /* Dig out the actual parm. */
22423 if (TREE_CODE (parm) == TYPE_DECL
22424 || TREE_CODE (parm) == TEMPLATE_DECL)
22426 parm = TREE_TYPE (parm);
22427 parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
22429 else if (TREE_CODE (parm) == PARM_DECL)
22431 parm = DECL_INITIAL (parm);
22432 parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
22435 if (targ == NULL_TREE)
22436 /* No explicit argument for this template parameter. */
22437 incomplete = true;
22438 else if (parameter_pack && pack_deducible_p (parm, fn))
22440 /* Mark the argument pack as "incomplete". We could
22441 still deduce more arguments during unification.
22442 We remove this mark in type_unification_real. */
22443 ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
22444 ARGUMENT_PACK_EXPLICIT_ARGS (targ)
22445 = ARGUMENT_PACK_ARGS (targ);
22447 /* We have some incomplete argument packs. */
22448 incomplete = true;
22452 if (incomplete)
22454 if (!push_tinst_level (fn, explicit_targs))
22456 excessive_deduction_depth = true;
22457 goto fail;
22459 ++processing_template_decl;
22460 input_location = DECL_SOURCE_LOCATION (fn);
22461 /* Ignore any access checks; we'll see them again in
22462 instantiate_template and they might have the wrong
22463 access path at this point. */
22464 push_deferring_access_checks (dk_deferred);
22465 tsubst_flags_t ecomplain = complain | tf_partial | tf_fndecl_type;
22466 fntype = tsubst (TREE_TYPE (fn), explicit_targs, ecomplain, NULL_TREE);
22467 pop_deferring_access_checks ();
22468 input_location = loc;
22469 --processing_template_decl;
22470 pop_tinst_level ();
22472 if (fntype == error_mark_node)
22473 goto fail;
22476 /* Place the explicitly specified arguments in TARGS. */
22477 explicit_targs = INNERMOST_TEMPLATE_ARGS (explicit_targs);
22478 for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
22479 TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
22480 if (!incomplete && CHECKING_P
22481 && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
22482 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
22483 (targs, NUM_TMPL_ARGS (explicit_targs));
22486 if (return_type && strict != DEDUCE_CALL)
22488 tree *new_args = XALLOCAVEC (tree, nargs + 1);
22489 new_args[0] = return_type;
22490 memcpy (new_args + 1, args, nargs * sizeof (tree));
22491 args = new_args;
22492 ++nargs;
22495 if (!incomplete)
22496 goto deduced;
22498 /* Never do unification on the 'this' parameter. */
22499 parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
22501 if (return_type && strict == DEDUCE_CALL)
22503 /* We're deducing for a call to the result of a template conversion
22504 function. The parms we really want are in return_type. */
22505 if (INDIRECT_TYPE_P (return_type))
22506 return_type = TREE_TYPE (return_type);
22507 parms = TYPE_ARG_TYPES (return_type);
22509 else if (return_type)
22511 parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
22514 /* We allow incomplete unification without an error message here
22515 because the standard doesn't seem to explicitly prohibit it. Our
22516 callers must be ready to deal with unification failures in any
22517 event. */
22519 /* If we aren't explaining yet, push tinst context so we can see where
22520 any errors (e.g. from class instantiations triggered by instantiation
22521 of default template arguments) come from. If we are explaining, this
22522 context is redundant. */
22523 if (!explain_p && !push_tinst_level (fn, targs))
22525 excessive_deduction_depth = true;
22526 goto fail;
22529 ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
22530 full_targs, parms, args, nargs, /*subr=*/0,
22531 strict, &checks, explain_p);
22532 if (!explain_p)
22533 pop_tinst_level ();
22534 if (!ok)
22535 goto fail;
22537 /* Now that we have bindings for all of the template arguments,
22538 ensure that the arguments deduced for the template template
22539 parameters have compatible template parameter lists. We cannot
22540 check this property before we have deduced all template
22541 arguments, because the template parameter types of a template
22542 template parameter might depend on prior template parameters
22543 deduced after the template template parameter. The following
22544 ill-formed example illustrates this issue:
22546 template<typename T, template<T> class C> void f(C<5>, T);
22548 template<int N> struct X {};
22550 void g() {
22551 f(X<5>(), 5l); // error: template argument deduction fails
22554 The template parameter list of 'C' depends on the template type
22555 parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
22556 'long'. Thus, we can't check that 'C' cannot bind to 'X' at the
22557 time that we deduce 'C'. */
22558 if (!template_template_parm_bindings_ok_p
22559 (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
22561 unify_inconsistent_template_template_parameters (explain_p);
22562 goto fail;
22565 deduced:
22567 /* CWG2369: Check satisfaction before non-deducible conversions. */
22568 if (!constraints_satisfied_p (fn, targs))
22570 if (explain_p)
22571 diagnose_constraints (DECL_SOURCE_LOCATION (fn), fn, targs);
22572 goto fail;
22575 /* DR 1391: All parameters have args, now check non-dependent parms for
22576 convertibility. We don't do this if all args were explicitly specified,
22577 as the standard says that we substitute explicit args immediately. */
22578 if (incomplete
22579 && check_non_deducible_conversions (parms, args, nargs, fn, strict, flags,
22580 convs, explain_p))
22581 goto fail;
22583 /* All is well so far. Now, check:
22585 [temp.deduct]
22587 When all template arguments have been deduced, all uses of
22588 template parameters in nondeduced contexts are replaced with
22589 the corresponding deduced argument values. If the
22590 substitution results in an invalid type, as described above,
22591 type deduction fails. */
22592 if (!push_tinst_level (fn, targs))
22594 excessive_deduction_depth = true;
22595 goto fail;
22598 /* Also collect access checks from the instantiation. */
22599 reopen_deferring_access_checks (checks);
22601 decl = instantiate_template (fn, targs, complain);
22603 checks = get_deferred_access_checks ();
22604 pop_deferring_access_checks ();
22606 pop_tinst_level ();
22608 if (decl == error_mark_node)
22609 goto fail;
22611 /* Now perform any access checks encountered during substitution. */
22612 push_access_scope (decl);
22613 ok = perform_access_checks (checks, complain);
22614 pop_access_scope (decl);
22615 if (!ok)
22616 goto fail;
22618 /* If we're looking for an exact match, check that what we got
22619 is indeed an exact match. It might not be if some template
22620 parameters are used in non-deduced contexts. But don't check
22621 for an exact match if we have dependent template arguments;
22622 in that case we're doing partial ordering, and we already know
22623 that we have two candidates that will provide the actual type. */
22624 if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
22626 tree substed = TREE_TYPE (decl);
22627 unsigned int i;
22629 tree sarg
22630 = skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
22631 if (return_type)
22632 sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
22633 for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
22634 if (!same_type_p (args[i], TREE_VALUE (sarg)))
22636 unify_type_mismatch (explain_p, args[i],
22637 TREE_VALUE (sarg));
22638 goto fail;
22640 if ((i < nargs || sarg)
22641 /* add_candidates uses DEDUCE_EXACT for x.operator foo(), but args
22642 doesn't contain the trailing void, and conv fns are always (). */
22643 && !DECL_CONV_FN_P (decl))
22645 unsigned nsargs = i + list_length (sarg);
22646 unify_arity (explain_p, nargs, nsargs);
22647 goto fail;
22651 /* After doing deduction with the inherited constructor, actually return an
22652 instantiation of the inheriting constructor. */
22653 if (orig_fn != fn)
22654 decl = instantiate_template (orig_fn, targs, complain);
22656 r = decl;
22658 fail:
22659 --deduction_depth;
22660 if (excessive_deduction_depth)
22662 if (deduction_depth == 0)
22663 /* Reset once we're all the way out. */
22664 excessive_deduction_depth = false;
22667 return r;
22670 /* Returns true iff PARM is a forwarding reference in the context of
22671 template argument deduction for TMPL. */
22673 static bool
22674 forwarding_reference_p (tree parm, tree tmpl)
22676 /* [temp.deduct.call], "A forwarding reference is an rvalue reference to a
22677 cv-unqualified template parameter ..." */
22678 if (TYPE_REF_P (parm)
22679 && TYPE_REF_IS_RVALUE (parm)
22680 && TREE_CODE (TREE_TYPE (parm)) == TEMPLATE_TYPE_PARM
22681 && cp_type_quals (TREE_TYPE (parm)) == TYPE_UNQUALIFIED)
22683 parm = TREE_TYPE (parm);
22684 /* [temp.deduct.call], "... that does not represent a template parameter
22685 of a class template (during class template argument deduction)." */
22686 if (tmpl
22687 && deduction_guide_p (tmpl)
22688 && DECL_ARTIFICIAL (tmpl))
22690 /* Since the template parameters of a synthesized guide consist of
22691 the template parameters of the class template followed by those of
22692 the constructor (if any), we can tell if PARM represents a template
22693 parameter of the class template by comparing its index with the
22694 arity of the class template. */
22695 tree ctmpl = CLASSTYPE_TI_TEMPLATE (TREE_TYPE (TREE_TYPE (tmpl)));
22696 if (TEMPLATE_TYPE_IDX (parm)
22697 < TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (ctmpl)))
22698 return false;
22700 return true;
22702 return false;
22705 /* Adjust types before performing type deduction, as described in
22706 [temp.deduct.call] and [temp.deduct.conv]. The rules in these two
22707 sections are symmetric. PARM is the type of a function parameter
22708 or the return type of the conversion function. ARG is the type of
22709 the argument passed to the call, or the type of the value
22710 initialized with the result of the conversion function.
22711 ARG_EXPR is the original argument expression, which may be null. */
22713 static int
22714 maybe_adjust_types_for_deduction (tree tparms,
22715 unification_kind_t strict,
22716 tree* parm,
22717 tree* arg,
22718 tree arg_expr)
22720 int result = 0;
22722 switch (strict)
22724 case DEDUCE_CALL:
22725 break;
22727 case DEDUCE_CONV:
22728 /* Swap PARM and ARG throughout the remainder of this
22729 function; the handling is precisely symmetric since PARM
22730 will initialize ARG rather than vice versa. */
22731 std::swap (parm, arg);
22732 break;
22734 case DEDUCE_EXACT:
22735 /* Core issue #873: Do the DR606 thing (see below) for these cases,
22736 too, but here handle it by stripping the reference from PARM
22737 rather than by adding it to ARG. */
22738 if (forwarding_reference_p (*parm, TPARMS_PRIMARY_TEMPLATE (tparms))
22739 && TYPE_REF_P (*arg)
22740 && !TYPE_REF_IS_RVALUE (*arg))
22741 *parm = TREE_TYPE (*parm);
22742 /* Nothing else to do in this case. */
22743 return 0;
22745 default:
22746 gcc_unreachable ();
22749 if (!TYPE_REF_P (*parm))
22751 /* [temp.deduct.call]
22753 If P is not a reference type:
22755 --If A is an array type, the pointer type produced by the
22756 array-to-pointer standard conversion (_conv.array_) is
22757 used in place of A for type deduction; otherwise,
22759 --If A is a function type, the pointer type produced by
22760 the function-to-pointer standard conversion
22761 (_conv.func_) is used in place of A for type deduction;
22762 otherwise,
22764 --If A is a cv-qualified type, the top level
22765 cv-qualifiers of A's type are ignored for type
22766 deduction. */
22767 if (TREE_CODE (*arg) == ARRAY_TYPE)
22768 *arg = build_pointer_type (TREE_TYPE (*arg));
22769 else if (TREE_CODE (*arg) == FUNCTION_TYPE)
22770 *arg = build_pointer_type (*arg);
22771 else
22772 *arg = TYPE_MAIN_VARIANT (*arg);
22775 /* [temp.deduct.call], "If P is a forwarding reference and the argument is
22776 an lvalue, the type 'lvalue reference to A' is used in place of A for
22777 type deduction." */
22778 if (forwarding_reference_p (*parm, TPARMS_PRIMARY_TEMPLATE (tparms))
22779 && (arg_expr ? lvalue_p (arg_expr)
22780 /* try_one_overload doesn't provide an arg_expr, but
22781 functions are always lvalues. */
22782 : TREE_CODE (*arg) == FUNCTION_TYPE))
22783 *arg = build_reference_type (*arg);
22785 /* [temp.deduct.call]
22787 If P is a cv-qualified type, the top level cv-qualifiers
22788 of P's type are ignored for type deduction. If P is a
22789 reference type, the type referred to by P is used for
22790 type deduction. */
22791 *parm = TYPE_MAIN_VARIANT (*parm);
22792 if (TYPE_REF_P (*parm))
22794 *parm = TREE_TYPE (*parm);
22795 result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
22798 /* DR 322. For conversion deduction, remove a reference type on parm
22799 too (which has been swapped into ARG). */
22800 if (strict == DEDUCE_CONV && TYPE_REF_P (*arg))
22801 *arg = TREE_TYPE (*arg);
22803 return result;
22806 /* Subroutine of fn_type_unification. PARM is a function parameter of a
22807 template which doesn't contain any deducible template parameters; check if
22808 ARG is a suitable match for it. STRICT, FLAGS and EXPLAIN_P are as in
22809 unify_one_argument. */
22811 static int
22812 check_non_deducible_conversion (tree parm, tree arg, unification_kind_t strict,
22813 int flags, struct conversion **conv_p,
22814 bool explain_p)
22816 tree type;
22818 if (!TYPE_P (arg))
22819 type = TREE_TYPE (arg);
22820 else
22821 type = arg;
22823 if (same_type_p (parm, type))
22824 return unify_success (explain_p);
22826 tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
22827 if (strict == DEDUCE_CONV)
22829 if (can_convert_arg (type, parm, NULL_TREE, flags, complain))
22830 return unify_success (explain_p);
22832 else if (strict == DEDUCE_CALL)
22834 bool ok = false;
22835 tree conv_arg = TYPE_P (arg) ? NULL_TREE : arg;
22836 if (conv_p)
22837 /* Avoid recalculating this in add_function_candidate. */
22838 ok = (*conv_p
22839 = good_conversion (parm, type, conv_arg, flags, complain));
22840 else
22841 ok = can_convert_arg (parm, type, conv_arg, flags, complain);
22842 if (ok)
22843 return unify_success (explain_p);
22846 if (strict == DEDUCE_EXACT)
22847 return unify_type_mismatch (explain_p, parm, arg);
22848 else
22849 return unify_arg_conversion (explain_p, parm, type, arg);
22852 static bool uses_deducible_template_parms (tree type);
22854 /* Returns true iff the expression EXPR is one from which a template
22855 argument can be deduced. In other words, if it's an undecorated
22856 use of a template non-type parameter. */
22858 static bool
22859 deducible_expression (tree expr)
22861 /* Strip implicit conversions and implicit INDIRECT_REFs. */
22862 while (CONVERT_EXPR_P (expr)
22863 || TREE_CODE (expr) == VIEW_CONVERT_EXPR
22864 || REFERENCE_REF_P (expr))
22865 expr = TREE_OPERAND (expr, 0);
22866 return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
22869 /* Returns true iff the array domain DOMAIN uses a template parameter in a
22870 deducible way; that is, if it has a max value of <PARM> - 1. */
22872 static bool
22873 deducible_array_bound (tree domain)
22875 if (domain == NULL_TREE)
22876 return false;
22878 tree max = TYPE_MAX_VALUE (domain);
22879 if (TREE_CODE (max) != MINUS_EXPR)
22880 return false;
22882 return deducible_expression (TREE_OPERAND (max, 0));
22885 /* Returns true iff the template arguments ARGS use a template parameter
22886 in a deducible way. */
22888 static bool
22889 deducible_template_args (tree args)
22891 for (tree elt : tree_vec_range (args))
22893 bool deducible;
22894 if (ARGUMENT_PACK_P (elt))
22895 deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
22896 else
22898 if (PACK_EXPANSION_P (elt))
22899 elt = PACK_EXPANSION_PATTERN (elt);
22900 if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
22901 deducible = true;
22902 else if (TYPE_P (elt))
22903 deducible = uses_deducible_template_parms (elt);
22904 else
22905 deducible = deducible_expression (elt);
22907 if (deducible)
22908 return true;
22910 return false;
22913 /* Returns true iff TYPE contains any deducible references to template
22914 parameters, as per 14.8.2.5. */
22916 static bool
22917 uses_deducible_template_parms (tree type)
22919 if (PACK_EXPANSION_P (type))
22920 type = PACK_EXPANSION_PATTERN (type);
22922 /* T
22923 cv-list T
22924 TT<T>
22925 TT<i>
22926 TT<> */
22927 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
22928 || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
22929 return true;
22931 /* T*
22933 T&& */
22934 if (INDIRECT_TYPE_P (type))
22935 return uses_deducible_template_parms (TREE_TYPE (type));
22937 /* T[integer-constant ]
22938 type [i] */
22939 if (TREE_CODE (type) == ARRAY_TYPE)
22940 return (uses_deducible_template_parms (TREE_TYPE (type))
22941 || deducible_array_bound (TYPE_DOMAIN (type)));
22943 /* T type ::*
22944 type T::*
22945 T T::*
22946 T (type ::*)()
22947 type (T::*)()
22948 type (type ::*)(T)
22949 type (T::*)(T)
22950 T (type ::*)(T)
22951 T (T::*)()
22952 T (T::*)(T) */
22953 if (TYPE_PTRMEM_P (type))
22954 return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
22955 || (uses_deducible_template_parms
22956 (TYPE_PTRMEM_POINTED_TO_TYPE (type))));
22958 /* template-name <T> (where template-name refers to a class template)
22959 template-name <i> (where template-name refers to a class template) */
22960 if (CLASS_TYPE_P (type)
22961 && CLASSTYPE_TEMPLATE_INFO (type)
22962 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
22963 return deducible_template_args (INNERMOST_TEMPLATE_ARGS
22964 (CLASSTYPE_TI_ARGS (type)));
22966 /* type (T)
22968 T(T) */
22969 if (FUNC_OR_METHOD_TYPE_P (type))
22971 if (uses_deducible_template_parms (TREE_TYPE (type)))
22972 return true;
22973 tree parm = TYPE_ARG_TYPES (type);
22974 if (TREE_CODE (type) == METHOD_TYPE)
22975 parm = TREE_CHAIN (parm);
22976 for (; parm; parm = TREE_CHAIN (parm))
22977 if (uses_deducible_template_parms (TREE_VALUE (parm)))
22978 return true;
22979 if (flag_noexcept_type
22980 && TYPE_RAISES_EXCEPTIONS (type)
22981 && TREE_PURPOSE (TYPE_RAISES_EXCEPTIONS (type))
22982 && deducible_expression (TREE_PURPOSE (TYPE_RAISES_EXCEPTIONS (type))))
22983 return true;
22986 return false;
22989 /* Subroutine of type_unification_real and unify_pack_expansion to
22990 handle unification of a single P/A pair. Parameters are as
22991 for those functions. */
22993 static int
22994 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
22995 int subr, unification_kind_t strict,
22996 bool explain_p)
22998 tree arg_expr = NULL_TREE;
22999 int arg_strict;
23001 if (arg == error_mark_node || parm == error_mark_node)
23002 return unify_invalid (explain_p);
23003 if (arg == unknown_type_node)
23004 /* We can't deduce anything from this, but we might get all the
23005 template args from other function args. */
23006 return unify_success (explain_p);
23008 /* Implicit conversions (Clause 4) will be performed on a function
23009 argument to convert it to the type of the corresponding function
23010 parameter if the parameter type contains no template-parameters that
23011 participate in template argument deduction. */
23012 if (strict != DEDUCE_EXACT
23013 && TYPE_P (parm) && !uses_deducible_template_parms (parm))
23014 /* For function parameters with no deducible template parameters,
23015 just return. We'll check non-dependent conversions later. */
23016 return unify_success (explain_p);
23018 switch (strict)
23020 case DEDUCE_CALL:
23021 arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
23022 | UNIFY_ALLOW_MORE_CV_QUAL
23023 | UNIFY_ALLOW_DERIVED);
23024 break;
23026 case DEDUCE_CONV:
23027 arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
23028 break;
23030 case DEDUCE_EXACT:
23031 arg_strict = UNIFY_ALLOW_NONE;
23032 break;
23034 default:
23035 gcc_unreachable ();
23038 /* We only do these transformations if this is the top-level
23039 parameter_type_list in a call or declaration matching; in other
23040 situations (nested function declarators, template argument lists) we
23041 won't be comparing a type to an expression, and we don't do any type
23042 adjustments. */
23043 if (!subr)
23045 if (!TYPE_P (arg))
23047 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
23048 if (type_unknown_p (arg))
23050 /* [temp.deduct.type] A template-argument can be
23051 deduced from a pointer to function or pointer
23052 to member function argument if the set of
23053 overloaded functions does not contain function
23054 templates and at most one of a set of
23055 overloaded functions provides a unique
23056 match. */
23057 resolve_overloaded_unification (tparms, targs, parm,
23058 arg, strict,
23059 arg_strict, explain_p);
23060 /* If a unique match was not found, this is a
23061 non-deduced context, so we still succeed. */
23062 return unify_success (explain_p);
23065 arg_expr = arg;
23066 arg = unlowered_expr_type (arg);
23067 if (arg == error_mark_node)
23068 return unify_invalid (explain_p);
23071 arg_strict |= maybe_adjust_types_for_deduction (tparms, strict,
23072 &parm, &arg, arg_expr);
23074 else
23075 if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
23076 != (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
23077 return unify_template_argument_mismatch (explain_p, parm, arg);
23079 /* For deduction from an init-list we need the actual list. */
23080 if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
23081 arg = arg_expr;
23082 return unify (tparms, targs, parm, arg, arg_strict, explain_p);
23085 /* for_each_template_parm callback that always returns 0. */
23087 static int
23088 zero_r (tree, void *)
23090 return 0;
23093 /* for_each_template_parm any_fn callback to handle deduction of a template
23094 type argument from the type of an array bound. */
23096 static int
23097 array_deduction_r (tree t, void *data)
23099 tree_pair_p d = (tree_pair_p)data;
23100 tree &tparms = d->purpose;
23101 tree &targs = d->value;
23103 if (TREE_CODE (t) == ARRAY_TYPE)
23104 if (tree dom = TYPE_DOMAIN (t))
23105 if (tree max = TYPE_MAX_VALUE (dom))
23107 if (TREE_CODE (max) == MINUS_EXPR)
23108 max = TREE_OPERAND (max, 0);
23109 if (TREE_CODE (max) == TEMPLATE_PARM_INDEX)
23110 unify (tparms, targs, TREE_TYPE (max), size_type_node,
23111 UNIFY_ALLOW_NONE, /*explain*/false);
23114 /* Keep walking. */
23115 return 0;
23118 /* Try to deduce any not-yet-deduced template type arguments from the type of
23119 an array bound. This is handled separately from unify because 14.8.2.5 says
23120 "The type of a type parameter is only deduced from an array bound if it is
23121 not otherwise deduced." */
23123 static void
23124 try_array_deduction (tree tparms, tree targs, tree parm)
23126 tree_pair_s data = { tparms, targs };
23127 hash_set<tree> visited;
23128 for_each_template_parm (parm, zero_r, &data, &visited,
23129 /*nondeduced*/false, array_deduction_r);
23132 /* Most parms like fn_type_unification.
23134 If SUBR is 1, we're being called recursively (to unify the
23135 arguments of a function or method parameter of a function
23136 template).
23138 CHECKS is a pointer to a vector of access checks encountered while
23139 substituting default template arguments. */
23141 static int
23142 type_unification_real (tree tparms,
23143 tree full_targs,
23144 tree xparms,
23145 const tree *xargs,
23146 unsigned int xnargs,
23147 int subr,
23148 unification_kind_t strict,
23149 vec<deferred_access_check, va_gc> **checks,
23150 bool explain_p)
23152 tree parm, arg;
23153 int i;
23154 int ntparms = TREE_VEC_LENGTH (tparms);
23155 int saw_undeduced = 0;
23156 tree parms;
23157 const tree *args;
23158 unsigned int nargs;
23159 unsigned int ia;
23161 gcc_assert (TREE_CODE (tparms) == TREE_VEC);
23162 gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
23163 gcc_assert (ntparms > 0);
23165 tree targs = INNERMOST_TEMPLATE_ARGS (full_targs);
23167 /* Reset the number of non-defaulted template arguments contained
23168 in TARGS. */
23169 NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
23171 again:
23172 parms = xparms;
23173 args = xargs;
23174 nargs = xnargs;
23176 /* Only fn_type_unification cares about terminal void. */
23177 if (nargs && args[nargs-1] == void_type_node)
23178 --nargs;
23180 ia = 0;
23181 while (parms && parms != void_list_node
23182 && ia < nargs)
23184 parm = TREE_VALUE (parms);
23186 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
23187 && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
23188 /* For a function parameter pack that occurs at the end of the
23189 parameter-declaration-list, the type A of each remaining
23190 argument of the call is compared with the type P of the
23191 declarator-id of the function parameter pack. */
23192 break;
23194 parms = TREE_CHAIN (parms);
23196 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
23197 /* For a function parameter pack that does not occur at the
23198 end of the parameter-declaration-list, the type of the
23199 parameter pack is a non-deduced context. */
23200 continue;
23202 arg = args[ia];
23203 ++ia;
23205 if (unify_one_argument (tparms, full_targs, parm, arg, subr, strict,
23206 explain_p))
23207 return 1;
23210 if (parms
23211 && parms != void_list_node
23212 && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
23214 /* Unify the remaining arguments with the pack expansion type. */
23215 tree argvec;
23216 tree parmvec = make_tree_vec (1);
23218 /* Allocate a TREE_VEC and copy in all of the arguments */
23219 argvec = make_tree_vec (nargs - ia);
23220 for (i = 0; ia < nargs; ++ia, ++i)
23221 TREE_VEC_ELT (argvec, i) = args[ia];
23223 /* Copy the parameter into parmvec. */
23224 TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
23225 if (unify_pack_expansion (tparms, full_targs, parmvec, argvec, strict,
23226 /*subr=*/subr, explain_p))
23227 return 1;
23229 /* Advance to the end of the list of parameters. */
23230 parms = TREE_CHAIN (parms);
23233 /* Fail if we've reached the end of the parm list, and more args
23234 are present, and the parm list isn't variadic. */
23235 if (ia < nargs && parms == void_list_node)
23236 return unify_too_many_arguments (explain_p, nargs, ia);
23237 /* Fail if parms are left and they don't have default values and
23238 they aren't all deduced as empty packs (c++/57397). This is
23239 consistent with sufficient_parms_p. */
23240 if (parms && parms != void_list_node
23241 && TREE_PURPOSE (parms) == NULL_TREE)
23243 unsigned int count = nargs;
23244 tree p = parms;
23245 bool type_pack_p;
23248 type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
23249 if (!type_pack_p)
23250 count++;
23251 p = TREE_CHAIN (p);
23253 while (p && p != void_list_node);
23254 if (count != nargs)
23255 return unify_too_few_arguments (explain_p, ia, count,
23256 type_pack_p);
23259 if (!subr)
23261 tsubst_flags_t complain = (explain_p
23262 ? tf_warning_or_error
23263 : tf_none);
23264 bool tried_array_deduction = (cxx_dialect < cxx17);
23266 for (i = 0; i < ntparms; i++)
23268 tree targ = TREE_VEC_ELT (targs, i);
23269 tree tparm = TREE_VEC_ELT (tparms, i);
23271 /* Clear the "incomplete" flags on all argument packs now so that
23272 substituting them into later default arguments works. */
23273 if (targ && ARGUMENT_PACK_P (targ))
23275 ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
23276 ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
23279 if (targ || tparm == error_mark_node)
23280 continue;
23281 tparm = TREE_VALUE (tparm);
23283 if (TREE_CODE (tparm) == TYPE_DECL
23284 && !tried_array_deduction)
23286 try_array_deduction (tparms, targs, xparms);
23287 tried_array_deduction = true;
23288 if (TREE_VEC_ELT (targs, i))
23289 continue;
23292 /* If this is an undeduced nontype parameter that depends on
23293 a type parameter, try another pass; its type may have been
23294 deduced from a later argument than the one from which
23295 this parameter can be deduced. */
23296 if (TREE_CODE (tparm) == PARM_DECL
23297 && !is_auto (TREE_TYPE (tparm))
23298 && uses_template_parms (TREE_TYPE (tparm))
23299 && saw_undeduced < 2)
23301 saw_undeduced = 1;
23302 continue;
23305 /* Core issue #226 (C++0x) [temp.deduct]:
23307 If a template argument has not been deduced, its
23308 default template argument, if any, is used.
23310 When we are in C++98 mode, TREE_PURPOSE will either
23311 be NULL_TREE or ERROR_MARK_NODE, so we do not need
23312 to explicitly check cxx_dialect here. */
23313 if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
23314 /* OK, there is a default argument. Wait until after the
23315 conversion check to do substitution. */
23316 continue;
23318 /* If the type parameter is a parameter pack, then it will
23319 be deduced to an empty parameter pack. */
23320 if (template_parameter_pack_p (tparm))
23322 tree arg;
23324 if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
23326 arg = make_node (NONTYPE_ARGUMENT_PACK);
23327 TREE_CONSTANT (arg) = 1;
23329 else
23330 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
23332 ARGUMENT_PACK_ARGS (arg) = make_tree_vec (0);
23334 TREE_VEC_ELT (targs, i) = arg;
23335 continue;
23338 return unify_parameter_deduction_failure (explain_p, tparm);
23341 /* During partial ordering, we deduce dependent template args. */
23342 bool any_dependent_targs = false;
23344 /* Now substitute into the default template arguments. */
23345 for (i = 0; i < ntparms; i++)
23347 tree targ = TREE_VEC_ELT (targs, i);
23348 tree tparm = TREE_VEC_ELT (tparms, i);
23350 if (targ)
23352 if (!any_dependent_targs && dependent_template_arg_p (targ))
23353 any_dependent_targs = true;
23354 continue;
23356 if (tparm == error_mark_node)
23357 continue;
23359 tree parm = TREE_VALUE (tparm);
23360 tree arg = TREE_PURPOSE (tparm);
23361 reopen_deferring_access_checks (*checks);
23362 location_t save_loc = input_location;
23363 if (DECL_P (parm))
23364 input_location = DECL_SOURCE_LOCATION (parm);
23366 if (saw_undeduced == 1
23367 && TREE_CODE (parm) == PARM_DECL
23368 && !is_auto (TREE_TYPE (parm))
23369 && uses_template_parms (TREE_TYPE (parm)))
23371 /* The type of this non-type parameter depends on undeduced
23372 parameters. Don't try to use its default argument yet,
23373 since we might deduce an argument for it on the next pass,
23374 but do check whether the arguments we already have cause
23375 substitution failure, so that that happens before we try
23376 later default arguments (78489). */
23377 ++processing_template_decl;
23378 tree type = tsubst (TREE_TYPE (parm), full_targs, complain,
23379 NULL_TREE);
23380 --processing_template_decl;
23381 if (type == error_mark_node)
23382 arg = error_mark_node;
23383 else
23384 arg = NULL_TREE;
23386 else
23388 /* Even if the call is happening in template context, getting
23389 here means it's non-dependent, and a default argument is
23390 considered a separate definition under [temp.decls], so we can
23391 do this substitution without processing_template_decl. This
23392 is important if the default argument contains something that
23393 might be instantiation-dependent like access (87480). */
23394 processing_template_decl_sentinel s (!any_dependent_targs);
23395 tree substed = NULL_TREE;
23396 if (saw_undeduced == 1 && !any_dependent_targs)
23398 /* First instatiate in template context, in case we still
23399 depend on undeduced template parameters. */
23400 ++processing_template_decl;
23401 substed = tsubst_template_arg (arg, full_targs, complain,
23402 NULL_TREE);
23403 --processing_template_decl;
23404 if (substed != error_mark_node
23405 && !uses_template_parms (substed))
23406 /* We replaced all the tparms, substitute again out of
23407 template context. */
23408 substed = NULL_TREE;
23410 if (!substed)
23411 substed = tsubst_template_arg (arg, full_targs, complain,
23412 NULL_TREE);
23414 if (!uses_template_parms (substed))
23415 arg = convert_template_argument (parm, substed, full_targs,
23416 complain, i, NULL_TREE);
23417 else if (saw_undeduced == 1)
23418 arg = NULL_TREE;
23419 else if (!any_dependent_targs)
23420 arg = error_mark_node;
23423 input_location = save_loc;
23424 *checks = get_deferred_access_checks ();
23425 pop_deferring_access_checks ();
23427 if (arg == error_mark_node)
23428 return 1;
23429 else if (arg)
23431 TREE_VEC_ELT (targs, i) = arg;
23432 /* The position of the first default template argument,
23433 is also the number of non-defaulted arguments in TARGS.
23434 Record that. */
23435 if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
23436 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
23440 if (saw_undeduced++ == 1)
23441 goto again;
23444 if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
23445 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
23447 return unify_success (explain_p);
23450 /* Subroutine of type_unification_real. Args are like the variables
23451 at the call site. ARG is an overloaded function (or template-id);
23452 we try deducing template args from each of the overloads, and if
23453 only one succeeds, we go with that. Modifies TARGS and returns
23454 true on success. */
23456 static bool
23457 resolve_overloaded_unification (tree tparms,
23458 tree targs,
23459 tree parm,
23460 tree arg,
23461 unification_kind_t strict,
23462 int sub_strict,
23463 bool explain_p)
23465 tree tempargs = copy_node (targs);
23466 int good = 0;
23467 tree goodfn = NULL_TREE;
23468 bool addr_p;
23470 if (TREE_CODE (arg) == ADDR_EXPR)
23472 arg = TREE_OPERAND (arg, 0);
23473 addr_p = true;
23475 else
23476 addr_p = false;
23478 if (TREE_CODE (arg) == COMPONENT_REF)
23479 /* Handle `&x' where `x' is some static or non-static member
23480 function name. */
23481 arg = TREE_OPERAND (arg, 1);
23483 if (TREE_CODE (arg) == OFFSET_REF)
23484 arg = TREE_OPERAND (arg, 1);
23486 /* Strip baselink information. */
23487 if (BASELINK_P (arg))
23488 arg = BASELINK_FUNCTIONS (arg);
23490 if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
23492 /* If we got some explicit template args, we need to plug them into
23493 the affected templates before we try to unify, in case the
23494 explicit args will completely resolve the templates in question. */
23496 int ok = 0;
23497 tree expl_subargs = TREE_OPERAND (arg, 1);
23498 arg = TREE_OPERAND (arg, 0);
23500 for (lkp_iterator iter (arg); iter; ++iter)
23502 tree fn = *iter;
23503 tree subargs, elem;
23505 if (TREE_CODE (fn) != TEMPLATE_DECL)
23506 continue;
23508 subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
23509 expl_subargs, NULL_TREE, tf_none);
23510 if (subargs != error_mark_node
23511 && !any_dependent_template_arguments_p (subargs))
23513 fn = instantiate_template (fn, subargs, tf_none);
23514 if (!constraints_satisfied_p (fn))
23515 continue;
23516 if (undeduced_auto_decl (fn))
23518 /* Instantiate the function to deduce its return type. */
23519 ++function_depth;
23520 instantiate_decl (fn, /*defer*/false, /*class*/false);
23521 --function_depth;
23524 if (flag_noexcept_type)
23525 maybe_instantiate_noexcept (fn, tf_none);
23527 elem = TREE_TYPE (fn);
23528 if (try_one_overload (tparms, targs, tempargs, parm,
23529 elem, strict, sub_strict, addr_p, explain_p)
23530 && (!goodfn || !same_type_p (goodfn, elem)))
23532 goodfn = elem;
23533 ++good;
23536 else if (subargs)
23537 ++ok;
23539 /* If no templates (or more than one) are fully resolved by the
23540 explicit arguments, this template-id is a non-deduced context; it
23541 could still be OK if we deduce all template arguments for the
23542 enclosing call through other arguments. */
23543 if (good != 1)
23544 good = ok;
23546 else if (!OVL_P (arg))
23547 /* If ARG is, for example, "(0, &f)" then its type will be unknown
23548 -- but the deduction does not succeed because the expression is
23549 not just the function on its own. */
23550 return false;
23551 else
23552 for (lkp_iterator iter (arg); iter; ++iter)
23554 tree fn = *iter;
23555 if (try_one_overload (tparms, targs, tempargs, parm, TREE_TYPE (fn),
23556 strict, sub_strict, addr_p, explain_p)
23557 && (!goodfn || !decls_match (goodfn, fn)))
23559 goodfn = fn;
23560 ++good;
23564 /* [temp.deduct.type] A template-argument can be deduced from a pointer
23565 to function or pointer to member function argument if the set of
23566 overloaded functions does not contain function templates and at most
23567 one of a set of overloaded functions provides a unique match.
23569 So if we found multiple possibilities, we return success but don't
23570 deduce anything. */
23572 if (good == 1)
23574 int i = TREE_VEC_LENGTH (targs);
23575 for (; i--; )
23576 if (TREE_VEC_ELT (tempargs, i))
23578 tree old = TREE_VEC_ELT (targs, i);
23579 tree new_ = TREE_VEC_ELT (tempargs, i);
23580 if (new_ && old && ARGUMENT_PACK_P (old)
23581 && ARGUMENT_PACK_EXPLICIT_ARGS (old))
23582 /* Don't forget explicit template arguments in a pack. */
23583 ARGUMENT_PACK_EXPLICIT_ARGS (new_)
23584 = ARGUMENT_PACK_EXPLICIT_ARGS (old);
23585 TREE_VEC_ELT (targs, i) = new_;
23588 if (good)
23589 return true;
23591 return false;
23594 /* Core DR 115: In contexts where deduction is done and fails, or in
23595 contexts where deduction is not done, if a template argument list is
23596 specified and it, along with any default template arguments, identifies
23597 a single function template specialization, then the template-id is an
23598 lvalue for the function template specialization. */
23600 tree
23601 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
23603 tree expr, offset, baselink;
23604 bool addr;
23606 if (!type_unknown_p (orig_expr))
23607 return orig_expr;
23609 expr = orig_expr;
23610 addr = false;
23611 offset = NULL_TREE;
23612 baselink = NULL_TREE;
23614 if (TREE_CODE (expr) == ADDR_EXPR)
23616 expr = TREE_OPERAND (expr, 0);
23617 addr = true;
23619 if (TREE_CODE (expr) == OFFSET_REF)
23621 offset = expr;
23622 expr = TREE_OPERAND (expr, 1);
23624 if (BASELINK_P (expr))
23626 baselink = expr;
23627 expr = BASELINK_FUNCTIONS (expr);
23630 if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
23632 int good = 0;
23633 tree goodfn = NULL_TREE;
23635 /* If we got some explicit template args, we need to plug them into
23636 the affected templates before we try to unify, in case the
23637 explicit args will completely resolve the templates in question. */
23639 tree expl_subargs = TREE_OPERAND (expr, 1);
23640 tree arg = TREE_OPERAND (expr, 0);
23641 tree badfn = NULL_TREE;
23642 tree badargs = NULL_TREE;
23644 for (lkp_iterator iter (arg); iter; ++iter)
23646 tree fn = *iter;
23647 tree subargs, elem;
23649 if (TREE_CODE (fn) != TEMPLATE_DECL)
23650 continue;
23652 subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
23653 expl_subargs, NULL_TREE, tf_none);
23654 if (subargs != error_mark_node
23655 && !any_dependent_template_arguments_p (subargs))
23657 elem = instantiate_template (fn, subargs, tf_none);
23658 if (elem == error_mark_node)
23660 badfn = fn;
23661 badargs = subargs;
23663 else if (elem && (!goodfn || !decls_match (goodfn, elem))
23664 && constraints_satisfied_p (elem))
23666 goodfn = elem;
23667 ++good;
23671 if (good == 1)
23673 mark_used (goodfn);
23674 expr = goodfn;
23675 if (baselink)
23676 expr = build_baselink (BASELINK_BINFO (baselink),
23677 BASELINK_ACCESS_BINFO (baselink),
23678 expr, BASELINK_OPTYPE (baselink));
23679 if (offset)
23681 tree base
23682 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
23683 expr = build_offset_ref (base, expr, addr, complain);
23685 if (addr)
23686 expr = cp_build_addr_expr (expr, complain);
23687 return expr;
23689 else if (good == 0 && badargs && (complain & tf_error))
23690 /* There were no good options and at least one bad one, so let the
23691 user know what the problem is. */
23692 instantiate_template (badfn, badargs, complain);
23694 return orig_expr;
23697 /* As above, but error out if the expression remains overloaded. */
23699 tree
23700 resolve_nondeduced_context_or_error (tree exp, tsubst_flags_t complain)
23702 exp = resolve_nondeduced_context (exp, complain);
23703 if (type_unknown_p (exp))
23705 if (complain & tf_error)
23706 cxx_incomplete_type_error (exp, TREE_TYPE (exp));
23707 return error_mark_node;
23709 return exp;
23712 /* Subroutine of resolve_overloaded_unification; does deduction for a single
23713 overload. Fills TARGS with any deduced arguments, or error_mark_node if
23714 different overloads deduce different arguments for a given parm.
23715 ADDR_P is true if the expression for which deduction is being
23716 performed was of the form "& fn" rather than simply "fn".
23718 Returns 1 on success. */
23720 static int
23721 try_one_overload (tree tparms,
23722 tree orig_targs,
23723 tree targs,
23724 tree parm,
23725 tree arg,
23726 unification_kind_t strict,
23727 int sub_strict,
23728 bool addr_p,
23729 bool explain_p)
23731 int nargs;
23732 tree tempargs;
23733 int i;
23735 if (arg == error_mark_node)
23736 return 0;
23738 /* [temp.deduct.type] A template-argument can be deduced from a pointer
23739 to function or pointer to member function argument if the set of
23740 overloaded functions does not contain function templates and at most
23741 one of a set of overloaded functions provides a unique match.
23743 So if this is a template, just return success. */
23745 if (uses_template_parms (arg))
23746 return 1;
23748 if (TREE_CODE (arg) == METHOD_TYPE)
23749 arg = build_ptrmemfunc_type (build_pointer_type (arg));
23750 else if (addr_p)
23751 arg = build_pointer_type (arg);
23753 sub_strict |= maybe_adjust_types_for_deduction (tparms, strict,
23754 &parm, &arg, NULL_TREE);
23756 /* We don't copy orig_targs for this because if we have already deduced
23757 some template args from previous args, unify would complain when we
23758 try to deduce a template parameter for the same argument, even though
23759 there isn't really a conflict. */
23760 nargs = TREE_VEC_LENGTH (targs);
23761 tempargs = make_tree_vec (nargs);
23763 if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
23764 return 0;
23766 /* First make sure we didn't deduce anything that conflicts with
23767 explicitly specified args. */
23768 for (i = nargs; i--; )
23770 tree elt = TREE_VEC_ELT (tempargs, i);
23771 tree oldelt = TREE_VEC_ELT (orig_targs, i);
23773 if (!elt)
23774 /*NOP*/;
23775 else if (uses_template_parms (elt))
23776 /* Since we're unifying against ourselves, we will fill in
23777 template args used in the function parm list with our own
23778 template parms. Discard them. */
23779 TREE_VEC_ELT (tempargs, i) = NULL_TREE;
23780 else if (oldelt && ARGUMENT_PACK_P (oldelt))
23782 /* Check that the argument at each index of the deduced argument pack
23783 is equivalent to the corresponding explicitly specified argument.
23784 We may have deduced more arguments than were explicitly specified,
23785 and that's OK. */
23787 /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
23788 that's wrong if we deduce the same argument pack from multiple
23789 function arguments: it's only incomplete the first time. */
23791 tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
23792 tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
23794 if (TREE_VEC_LENGTH (deduced_pack)
23795 < TREE_VEC_LENGTH (explicit_pack))
23796 return 0;
23798 for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
23799 if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
23800 TREE_VEC_ELT (deduced_pack, j)))
23801 return 0;
23803 else if (oldelt && !template_args_equal (oldelt, elt))
23804 return 0;
23807 for (i = nargs; i--; )
23809 tree elt = TREE_VEC_ELT (tempargs, i);
23811 if (elt)
23812 TREE_VEC_ELT (targs, i) = elt;
23815 return 1;
23818 /* PARM is a template class (perhaps with unbound template
23819 parameters). ARG is a fully instantiated type. If ARG can be
23820 bound to PARM, return ARG, otherwise return NULL_TREE. TPARMS and
23821 TARGS are as for unify. */
23823 static tree
23824 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
23825 bool explain_p)
23827 if (!CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
23828 return NULL_TREE;
23829 else if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23830 /* Matches anything. */;
23831 else if (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
23832 != most_general_template (CLASSTYPE_TI_TEMPLATE (parm)))
23833 return NULL_TREE;
23835 /* We need to make a new template argument vector for the call to
23836 unify. If we used TARGS, we'd clutter it up with the result of
23837 the attempted unification, even if this class didn't work out.
23838 We also don't want to commit ourselves to all the unifications
23839 we've already done, since unification is supposed to be done on
23840 an argument-by-argument basis. In other words, consider the
23841 following pathological case:
23843 template <int I, int J, int K>
23844 struct S {};
23846 template <int I, int J>
23847 struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
23849 template <int I, int J, int K>
23850 void f(S<I, J, K>, S<I, I, I>);
23852 void g() {
23853 S<0, 0, 0> s0;
23854 S<0, 1, 2> s2;
23856 f(s0, s2);
23859 Now, by the time we consider the unification involving `s2', we
23860 already know that we must have `f<0, 0, 0>'. But, even though
23861 `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
23862 because there are two ways to unify base classes of S<0, 1, 2>
23863 with S<I, I, I>. If we kept the already deduced knowledge, we
23864 would reject the possibility I=1. */
23865 targs = copy_template_args (targs);
23866 for (tree& targ : tree_vec_range (INNERMOST_TEMPLATE_ARGS (targs)))
23867 targ = NULL_TREE;
23869 int err;
23870 if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23871 err = unify_bound_ttp_args (tparms, targs, parm, arg, explain_p);
23872 else
23873 err = unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
23874 CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p);
23876 return err ? NULL_TREE : arg;
23879 /* Given a template type PARM and a class type ARG, find the unique
23880 base type in ARG that is an instance of PARM. We do not examine
23881 ARG itself; only its base-classes. If there is not exactly one
23882 appropriate base class, return NULL_TREE. PARM may be the type of
23883 a partial specialization, as well as a plain template type. Used
23884 by unify. */
23886 static enum template_base_result
23887 get_template_base (tree tparms, tree targs, tree parm, tree arg,
23888 bool explain_p, tree *result)
23890 tree rval = NULL_TREE;
23891 tree binfo;
23893 gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
23895 binfo = TYPE_BINFO (complete_type (arg));
23896 if (!binfo)
23898 /* The type could not be completed. */
23899 *result = NULL_TREE;
23900 return tbr_incomplete_type;
23903 /* Walk in inheritance graph order. The search order is not
23904 important, and this avoids multiple walks of virtual bases. */
23905 for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
23907 tree r = try_class_unification (tparms, targs, parm,
23908 BINFO_TYPE (binfo), explain_p);
23910 if (r)
23912 /* If there is more than one satisfactory baseclass, then:
23914 [temp.deduct.call]
23916 If they yield more than one possible deduced A, the type
23917 deduction fails.
23919 applies. */
23920 if (rval && !same_type_p (r, rval))
23922 /* [temp.deduct.call]/4.3: If there is a class C that is a
23923 (direct or indirect) base class of D and derived (directly or
23924 indirectly) from a class B and that would be a valid deduced
23925 A, the deduced A cannot be B or pointer to B, respectively. */
23926 if (DERIVED_FROM_P (r, rval))
23927 /* Ignore r. */
23928 continue;
23929 else if (DERIVED_FROM_P (rval, r))
23930 /* Ignore rval. */;
23931 else
23933 *result = NULL_TREE;
23934 return tbr_ambiguous_baseclass;
23938 rval = r;
23942 *result = rval;
23943 return tbr_success;
23946 /* Returns the level of DECL, which declares a template parameter. */
23948 static int
23949 template_decl_level (tree decl)
23951 switch (TREE_CODE (decl))
23953 case TYPE_DECL:
23954 case TEMPLATE_DECL:
23955 return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
23957 case PARM_DECL:
23958 return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
23960 default:
23961 gcc_unreachable ();
23963 return 0;
23966 /* Decide whether ARG can be unified with PARM, considering only the
23967 cv-qualifiers of each type, given STRICT as documented for unify.
23968 Returns nonzero iff the unification is OK on that basis. */
23970 static int
23971 check_cv_quals_for_unify (int strict, tree arg, tree parm)
23973 int arg_quals = cp_type_quals (arg);
23974 int parm_quals = cp_type_quals (parm);
23976 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
23977 && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
23979 /* Although a CVR qualifier is ignored when being applied to a
23980 substituted template parameter ([8.3.2]/1 for example), that
23981 does not allow us to unify "const T" with "int&" because both
23982 types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
23983 It is ok when we're allowing additional CV qualifiers
23984 at the outer level [14.8.2.1]/3,1st bullet. */
23985 if ((TYPE_REF_P (arg)
23986 || FUNC_OR_METHOD_TYPE_P (arg))
23987 && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
23988 return 0;
23990 if ((!INDIRECT_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
23991 && (parm_quals & TYPE_QUAL_RESTRICT))
23992 return 0;
23995 if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
23996 && (arg_quals & parm_quals) != parm_quals)
23997 return 0;
23999 if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
24000 && (parm_quals & arg_quals) != arg_quals)
24001 return 0;
24003 return 1;
24006 /* Determines the LEVEL and INDEX for the template parameter PARM. */
24007 void
24008 template_parm_level_and_index (tree parm, int* level, int* index)
24010 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
24011 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24012 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24014 *index = TEMPLATE_TYPE_IDX (parm);
24015 *level = TEMPLATE_TYPE_LEVEL (parm);
24017 else
24019 *index = TEMPLATE_PARM_IDX (parm);
24020 *level = TEMPLATE_PARM_LEVEL (parm);
24024 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP) \
24025 do { \
24026 if (unify (TP, TA, P, A, S, EP)) \
24027 return 1; \
24028 } while (0)
24030 /* Unifies the remaining arguments in PACKED_ARGS with the pack
24031 expansion at the end of PACKED_PARMS. Returns 0 if the type
24032 deduction succeeds, 1 otherwise. STRICT is the same as in
24033 fn_type_unification. CALL_ARGS_P is true iff PACKED_ARGS is actually a
24034 function call argument list. We'll need to adjust the arguments to make them
24035 types. SUBR tells us if this is from a recursive call to
24036 type_unification_real, or for comparing two template argument
24037 lists. */
24039 static int
24040 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
24041 tree packed_args, unification_kind_t strict,
24042 bool subr, bool explain_p)
24044 tree parm
24045 = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
24046 tree pattern = PACK_EXPANSION_PATTERN (parm);
24047 tree pack, packs = NULL_TREE;
24048 int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
24050 /* Add in any args remembered from an earlier partial instantiation. */
24051 targs = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (parm), targs);
24052 int levels = TMPL_ARGS_DEPTH (targs);
24054 packed_args = expand_template_argument_pack (packed_args);
24056 int len = TREE_VEC_LENGTH (packed_args);
24058 /* Determine the parameter packs we will be deducing from the
24059 pattern, and record their current deductions. */
24060 for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
24061 pack; pack = TREE_CHAIN (pack))
24063 tree parm_pack = TREE_VALUE (pack);
24064 int idx, level;
24066 /* Only template parameter packs can be deduced, not e.g. function
24067 parameter packs or __bases or __integer_pack. */
24068 if (!TEMPLATE_PARM_P (parm_pack))
24069 continue;
24071 /* Determine the index and level of this parameter pack. */
24072 template_parm_level_and_index (parm_pack, &level, &idx);
24073 if (level > levels)
24074 continue;
24076 /* Keep track of the parameter packs and their corresponding
24077 argument packs. */
24078 packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
24079 TREE_TYPE (packs) = make_tree_vec (len - start);
24082 /* Loop through all of the arguments that have not yet been
24083 unified and unify each with the pattern. */
24084 for (i = start; i < len; i++)
24086 tree parm;
24087 bool any_explicit = false;
24088 tree arg = TREE_VEC_ELT (packed_args, i);
24090 /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
24091 or the element of its argument pack at the current index if
24092 this argument was explicitly specified. */
24093 for (pack = packs; pack; pack = TREE_CHAIN (pack))
24095 int idx, level;
24096 tree arg, pargs;
24097 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
24099 arg = NULL_TREE;
24100 if (TREE_VALUE (pack)
24101 && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
24102 && (i - start < TREE_VEC_LENGTH (pargs)))
24104 any_explicit = true;
24105 arg = TREE_VEC_ELT (pargs, i - start);
24107 TMPL_ARG (targs, level, idx) = arg;
24110 /* If we had explicit template arguments, substitute them into the
24111 pattern before deduction. */
24112 if (any_explicit)
24114 /* Some arguments might still be unspecified or dependent. */
24115 bool dependent;
24116 ++processing_template_decl;
24117 dependent = any_dependent_template_arguments_p (targs);
24118 if (!dependent)
24119 --processing_template_decl;
24120 parm = tsubst (pattern, targs,
24121 explain_p ? tf_warning_or_error : tf_none,
24122 NULL_TREE);
24123 if (dependent)
24124 --processing_template_decl;
24125 if (parm == error_mark_node)
24126 return 1;
24128 else
24129 parm = pattern;
24131 /* Unify the pattern with the current argument. */
24132 if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
24133 explain_p))
24134 return 1;
24136 /* For each parameter pack, collect the deduced value. */
24137 for (pack = packs; pack; pack = TREE_CHAIN (pack))
24139 int idx, level;
24140 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
24142 TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
24143 TMPL_ARG (targs, level, idx);
24147 /* Verify that the results of unification with the parameter packs
24148 produce results consistent with what we've seen before, and make
24149 the deduced argument packs available. */
24150 for (pack = packs; pack; pack = TREE_CHAIN (pack))
24152 tree old_pack = TREE_VALUE (pack);
24153 tree new_args = TREE_TYPE (pack);
24154 int i, len = TREE_VEC_LENGTH (new_args);
24155 int idx, level;
24156 bool nondeduced_p = false;
24158 /* By default keep the original deduced argument pack.
24159 If necessary, more specific code is going to update the
24160 resulting deduced argument later down in this function. */
24161 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
24162 TMPL_ARG (targs, level, idx) = old_pack;
24164 /* If NEW_ARGS contains any NULL_TREE entries, we didn't
24165 actually deduce anything. */
24166 for (i = 0; i < len && !nondeduced_p; ++i)
24167 if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
24168 nondeduced_p = true;
24169 if (nondeduced_p)
24170 continue;
24172 if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
24174 /* If we had fewer function args than explicit template args,
24175 just use the explicits. */
24176 tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
24177 int explicit_len = TREE_VEC_LENGTH (explicit_args);
24178 if (len < explicit_len)
24179 new_args = explicit_args;
24182 if (!old_pack)
24184 tree result;
24185 /* Build the deduced *_ARGUMENT_PACK. */
24186 if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
24188 result = make_node (NONTYPE_ARGUMENT_PACK);
24189 TREE_CONSTANT (result) = 1;
24191 else
24192 result = cxx_make_type (TYPE_ARGUMENT_PACK);
24194 ARGUMENT_PACK_ARGS (result) = new_args;
24196 /* Note the deduced argument packs for this parameter
24197 pack. */
24198 TMPL_ARG (targs, level, idx) = result;
24200 else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
24201 && (ARGUMENT_PACK_ARGS (old_pack)
24202 == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
24204 /* We only had the explicitly-provided arguments before, but
24205 now we have a complete set of arguments. */
24206 tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
24208 ARGUMENT_PACK_ARGS (old_pack) = new_args;
24209 ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
24210 ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
24212 else
24214 tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
24215 tree old_args = ARGUMENT_PACK_ARGS (old_pack);
24216 temp_override<int> ovl (TREE_VEC_LENGTH (old_args));
24217 /* During template argument deduction for the aggregate deduction
24218 candidate, the number of elements in a trailing parameter pack
24219 is only deduced from the number of remaining function
24220 arguments if it is not otherwise deduced. */
24221 if (cxx_dialect >= cxx20
24222 && TREE_VEC_LENGTH (new_args) < TREE_VEC_LENGTH (old_args)
24223 /* FIXME This isn't set properly for partial instantiations. */
24224 && TPARMS_PRIMARY_TEMPLATE (tparms)
24225 && builtin_guide_p (TPARMS_PRIMARY_TEMPLATE (tparms)))
24226 TREE_VEC_LENGTH (old_args) = TREE_VEC_LENGTH (new_args);
24227 if (!comp_template_args (old_args, new_args,
24228 &bad_old_arg, &bad_new_arg))
24229 /* Inconsistent unification of this parameter pack. */
24230 return unify_parameter_pack_inconsistent (explain_p,
24231 bad_old_arg,
24232 bad_new_arg);
24236 return unify_success (explain_p);
24239 /* Handle unification of the domain of an array. PARM_DOM and ARG_DOM are
24240 INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs. The other
24241 parameters and return value are as for unify. */
24243 static int
24244 unify_array_domain (tree tparms, tree targs,
24245 tree parm_dom, tree arg_dom,
24246 bool explain_p)
24248 tree parm_max;
24249 tree arg_max;
24250 bool parm_cst;
24251 bool arg_cst;
24253 /* Our representation of array types uses "N - 1" as the
24254 TYPE_MAX_VALUE for an array with "N" elements, if "N" is
24255 not an integer constant. We cannot unify arbitrarily
24256 complex expressions, so we eliminate the MINUS_EXPRs
24257 here. */
24258 parm_max = TYPE_MAX_VALUE (parm_dom);
24259 parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
24260 if (!parm_cst)
24262 gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
24263 parm_max = TREE_OPERAND (parm_max, 0);
24265 arg_max = TYPE_MAX_VALUE (arg_dom);
24266 arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
24267 if (!arg_cst)
24269 /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
24270 trying to unify the type of a variable with the type
24271 of a template parameter. For example:
24273 template <unsigned int N>
24274 void f (char (&) [N]);
24275 int g();
24276 void h(int i) {
24277 char a[g(i)];
24278 f(a);
24281 Here, the type of the ARG will be "int [g(i)]", and
24282 may be a SAVE_EXPR, etc. */
24283 if (TREE_CODE (arg_max) != MINUS_EXPR)
24284 return unify_vla_arg (explain_p, arg_dom);
24285 arg_max = TREE_OPERAND (arg_max, 0);
24288 /* If only one of the bounds used a MINUS_EXPR, compensate
24289 by adding one to the other bound. */
24290 if (parm_cst && !arg_cst)
24291 parm_max = fold_build2_loc (input_location, PLUS_EXPR,
24292 integer_type_node,
24293 parm_max,
24294 integer_one_node);
24295 else if (arg_cst && !parm_cst)
24296 arg_max = fold_build2_loc (input_location, PLUS_EXPR,
24297 integer_type_node,
24298 arg_max,
24299 integer_one_node);
24301 return unify (tparms, targs, parm_max, arg_max,
24302 UNIFY_ALLOW_INTEGER, explain_p);
24305 /* Returns whether T, a P or A in unify, is a type, template or expression. */
24307 enum pa_kind_t { pa_type, pa_tmpl, pa_expr };
24309 static pa_kind_t
24310 pa_kind (tree t)
24312 if (PACK_EXPANSION_P (t))
24313 t = PACK_EXPANSION_PATTERN (t);
24314 if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
24315 || TREE_CODE (t) == UNBOUND_CLASS_TEMPLATE
24316 || DECL_TYPE_TEMPLATE_P (t))
24317 return pa_tmpl;
24318 else if (TYPE_P (t))
24319 return pa_type;
24320 else
24321 return pa_expr;
24324 /* Deduce the value of template parameters. TPARMS is the (innermost)
24325 set of template parameters to a template. TARGS is the bindings
24326 for those template parameters, as determined thus far; TARGS may
24327 include template arguments for outer levels of template parameters
24328 as well. PARM is a parameter to a template function, or a
24329 subcomponent of that parameter; ARG is the corresponding argument.
24330 This function attempts to match PARM with ARG in a manner
24331 consistent with the existing assignments in TARGS. If more values
24332 are deduced, then TARGS is updated.
24334 Returns 0 if the type deduction succeeds, 1 otherwise. The
24335 parameter STRICT is a bitwise or of the following flags:
24337 UNIFY_ALLOW_NONE:
24338 Require an exact match between PARM and ARG.
24339 UNIFY_ALLOW_MORE_CV_QUAL:
24340 Allow the deduced ARG to be more cv-qualified (by qualification
24341 conversion) than ARG.
24342 UNIFY_ALLOW_LESS_CV_QUAL:
24343 Allow the deduced ARG to be less cv-qualified than ARG.
24344 UNIFY_ALLOW_DERIVED:
24345 Allow the deduced ARG to be a template base class of ARG,
24346 or a pointer to a template base class of the type pointed to by
24347 ARG.
24348 UNIFY_ALLOW_INTEGER:
24349 Allow any integral type to be deduced. See the TEMPLATE_PARM_INDEX
24350 case for more information.
24351 UNIFY_ALLOW_OUTER_LEVEL:
24352 This is the outermost level of a deduction. Used to determine validity
24353 of qualification conversions. A valid qualification conversion must
24354 have const qualified pointers leading up to the inner type which
24355 requires additional CV quals, except at the outer level, where const
24356 is not required [conv.qual]. It would be normal to set this flag in
24357 addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
24358 UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
24359 This is the outermost level of a deduction, and PARM can be more CV
24360 qualified at this point.
24361 UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
24362 This is the outermost level of a deduction, and PARM can be less CV
24363 qualified at this point. */
24365 static int
24366 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
24367 bool explain_p)
24369 int idx;
24370 tree targ;
24371 tree tparm;
24372 int strict_in = strict;
24373 tsubst_flags_t complain = (explain_p
24374 ? tf_warning_or_error
24375 : tf_none);
24377 /* I don't think this will do the right thing with respect to types.
24378 But the only case I've seen it in so far has been array bounds, where
24379 signedness is the only information lost, and I think that will be
24380 okay. VIEW_CONVERT_EXPR can appear with class NTTP, thanks to
24381 finish_id_expression_1, and are also OK. */
24382 while (CONVERT_EXPR_P (parm) || TREE_CODE (parm) == VIEW_CONVERT_EXPR)
24383 parm = TREE_OPERAND (parm, 0);
24385 if (arg == error_mark_node)
24386 return unify_invalid (explain_p);
24387 if (arg == unknown_type_node
24388 || arg == init_list_type_node)
24389 /* We can't deduce anything from this, but we might get all the
24390 template args from other function args. */
24391 return unify_success (explain_p);
24393 if (parm == any_targ_node || arg == any_targ_node)
24394 return unify_success (explain_p);
24396 /* If PARM uses template parameters, then we can't bail out here,
24397 even if ARG == PARM, since we won't record unifications for the
24398 template parameters. We might need them if we're trying to
24399 figure out which of two things is more specialized. */
24400 if (arg == parm && !uses_template_parms (parm))
24401 return unify_success (explain_p);
24403 /* Handle init lists early, so the rest of the function can assume
24404 we're dealing with a type. */
24405 if (BRACE_ENCLOSED_INITIALIZER_P (arg))
24407 tree elttype;
24408 tree orig_parm = parm;
24410 if (!is_std_init_list (parm)
24411 && TREE_CODE (parm) != ARRAY_TYPE)
24412 /* We can only deduce from an initializer list argument if the
24413 parameter is std::initializer_list or an array; otherwise this
24414 is a non-deduced context. */
24415 return unify_success (explain_p);
24417 if (TREE_CODE (parm) == ARRAY_TYPE)
24418 elttype = TREE_TYPE (parm);
24419 else
24421 elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
24422 /* Deduction is defined in terms of a single type, so just punt
24423 on the (bizarre) std::initializer_list<T...>. */
24424 if (PACK_EXPANSION_P (elttype))
24425 return unify_success (explain_p);
24428 if (strict != DEDUCE_EXACT
24429 && TYPE_P (elttype)
24430 && !uses_deducible_template_parms (elttype))
24431 /* If ELTTYPE has no deducible template parms, skip deduction from
24432 the list elements. */;
24433 else
24434 for (auto &e: CONSTRUCTOR_ELTS (arg))
24436 tree elt = e.value;
24437 int elt_strict = strict;
24439 if (elt == error_mark_node)
24440 return unify_invalid (explain_p);
24442 if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
24444 tree type = TREE_TYPE (elt);
24445 if (type == error_mark_node)
24446 return unify_invalid (explain_p);
24447 /* It should only be possible to get here for a call. */
24448 gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
24449 elt_strict |= maybe_adjust_types_for_deduction
24450 (tparms, DEDUCE_CALL, &elttype, &type, elt);
24451 elt = type;
24454 RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
24455 explain_p);
24458 if (TREE_CODE (parm) == ARRAY_TYPE
24459 && deducible_array_bound (TYPE_DOMAIN (parm)))
24461 /* Also deduce from the length of the initializer list. */
24462 tree max = size_int (CONSTRUCTOR_NELTS (arg));
24463 tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
24464 if (idx == error_mark_node)
24465 return unify_invalid (explain_p);
24466 return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
24467 idx, explain_p);
24470 /* If the std::initializer_list<T> deduction worked, replace the
24471 deduced A with std::initializer_list<A>. */
24472 if (orig_parm != parm)
24474 idx = TEMPLATE_TYPE_IDX (orig_parm);
24475 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24476 targ = listify (targ);
24477 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
24479 return unify_success (explain_p);
24482 /* If parm and arg aren't the same kind of thing (template, type, or
24483 expression), fail early. */
24484 if (pa_kind (parm) != pa_kind (arg))
24485 return unify_invalid (explain_p);
24487 /* Immediately reject some pairs that won't unify because of
24488 cv-qualification mismatches. */
24489 if (TREE_CODE (arg) == TREE_CODE (parm)
24490 && TYPE_P (arg)
24491 /* It is the elements of the array which hold the cv quals of an array
24492 type, and the elements might be template type parms. We'll check
24493 when we recurse. */
24494 && TREE_CODE (arg) != ARRAY_TYPE
24495 /* We check the cv-qualifiers when unifying with template type
24496 parameters below. We want to allow ARG `const T' to unify with
24497 PARM `T' for example, when computing which of two templates
24498 is more specialized, for example. */
24499 && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
24500 && !check_cv_quals_for_unify (strict_in, arg, parm))
24501 return unify_cv_qual_mismatch (explain_p, parm, arg);
24503 if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
24504 && TYPE_P (parm) && !CP_TYPE_CONST_P (parm)
24505 && !FUNC_OR_METHOD_TYPE_P (parm))
24506 strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
24507 /* PMFs recurse at the same level, so don't strip this yet. */
24508 if (!TYPE_PTRMEMFUNC_P (parm))
24509 strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
24510 strict &= ~UNIFY_ALLOW_DERIVED;
24511 strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
24512 strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
24514 switch (TREE_CODE (parm))
24516 case TYPENAME_TYPE:
24517 case SCOPE_REF:
24518 case UNBOUND_CLASS_TEMPLATE:
24519 /* In a type which contains a nested-name-specifier, template
24520 argument values cannot be deduced for template parameters used
24521 within the nested-name-specifier. */
24522 return unify_success (explain_p);
24524 case TEMPLATE_TYPE_PARM:
24525 case TEMPLATE_TEMPLATE_PARM:
24526 case BOUND_TEMPLATE_TEMPLATE_PARM:
24527 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
24528 if (error_operand_p (tparm))
24529 return unify_invalid (explain_p);
24531 if (TEMPLATE_TYPE_LEVEL (parm)
24532 != template_decl_level (tparm))
24533 /* The PARM is not one we're trying to unify. Just check
24534 to see if it matches ARG. */
24536 if (TREE_CODE (arg) == TREE_CODE (parm)
24537 && (is_auto (parm) ? is_auto (arg)
24538 : same_type_p (parm, arg)))
24539 return unify_success (explain_p);
24540 else
24541 return unify_type_mismatch (explain_p, parm, arg);
24543 idx = TEMPLATE_TYPE_IDX (parm);
24544 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24545 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
24546 if (error_operand_p (tparm))
24547 return unify_invalid (explain_p);
24549 /* Check for mixed types and values. */
24550 if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
24551 && TREE_CODE (tparm) != TYPE_DECL)
24552 || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24553 && TREE_CODE (tparm) != TEMPLATE_DECL))
24554 gcc_unreachable ();
24556 if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24558 if ((strict_in & UNIFY_ALLOW_DERIVED)
24559 && CLASS_TYPE_P (arg))
24561 /* First try to match ARG directly. */
24562 tree t = try_class_unification (tparms, targs, parm, arg,
24563 explain_p);
24564 if (!t)
24566 /* Otherwise, look for a suitable base of ARG, as below. */
24567 enum template_base_result r;
24568 r = get_template_base (tparms, targs, parm, arg,
24569 explain_p, &t);
24570 if (!t)
24571 return unify_no_common_base (explain_p, r, parm, arg);
24572 arg = t;
24575 /* ARG must be constructed from a template class or a template
24576 template parameter. */
24577 else if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
24578 && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
24579 return unify_template_deduction_failure (explain_p, parm, arg);
24581 /* Deduce arguments T, i from TT<T> or TT<i>. */
24582 if (unify_bound_ttp_args (tparms, targs, parm, arg, explain_p))
24583 return 1;
24585 arg = TYPE_TI_TEMPLATE (arg);
24586 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
24587 /* If the template is a template template parameter, use the
24588 TEMPLATE_TEMPLATE_PARM for matching. */
24589 arg = TREE_TYPE (arg);
24591 /* Fall through to deduce template name. */
24594 if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24595 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24597 /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>. */
24599 /* Simple cases: Value already set, does match or doesn't. */
24600 if (targ != NULL_TREE && template_args_equal (targ, arg))
24601 return unify_success (explain_p);
24602 else if (targ)
24603 return unify_inconsistency (explain_p, parm, targ, arg);
24605 else
24607 /* If PARM is `const T' and ARG is only `int', we don't have
24608 a match unless we are allowing additional qualification.
24609 If ARG is `const int' and PARM is just `T' that's OK;
24610 that binds `const int' to `T'. */
24611 if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
24612 arg, parm))
24613 return unify_cv_qual_mismatch (explain_p, parm, arg);
24615 /* Consider the case where ARG is `const volatile int' and
24616 PARM is `const T'. Then, T should be `volatile int'. */
24617 arg = cp_build_qualified_type
24618 (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
24619 if (arg == error_mark_node)
24620 return unify_invalid (explain_p);
24622 /* Simple cases: Value already set, does match or doesn't. */
24623 if (targ != NULL_TREE && same_type_p (targ, arg))
24624 return unify_success (explain_p);
24625 else if (targ)
24626 return unify_inconsistency (explain_p, parm, targ, arg);
24628 /* Make sure that ARG is not a variable-sized array. (Note
24629 that were talking about variable-sized arrays (like
24630 `int[n]'), rather than arrays of unknown size (like
24631 `int[]').) We'll get very confused by such a type since
24632 the bound of the array is not constant, and therefore
24633 not mangleable. Besides, such types are not allowed in
24634 ISO C++, so we can do as we please here. We do allow
24635 them for 'auto' deduction, since that isn't ABI-exposed. */
24636 if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
24637 return unify_vla_arg (explain_p, arg);
24639 /* Strip typedefs as in convert_template_argument. */
24640 arg = canonicalize_type_argument (arg, tf_none);
24643 /* If ARG is a parameter pack or an expansion, we cannot unify
24644 against it unless PARM is also a parameter pack. */
24645 if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
24646 && !template_parameter_pack_p (parm))
24647 return unify_parameter_pack_mismatch (explain_p, parm, arg);
24649 /* If the argument deduction results is a METHOD_TYPE,
24650 then there is a problem.
24651 METHOD_TYPE doesn't map to any real C++ type the result of
24652 the deduction cannot be of that type. */
24653 if (TREE_CODE (arg) == METHOD_TYPE)
24654 return unify_method_type_error (explain_p, arg);
24656 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
24657 return unify_success (explain_p);
24659 case TEMPLATE_PARM_INDEX:
24660 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
24661 if (error_operand_p (tparm))
24662 return unify_invalid (explain_p);
24664 if (TEMPLATE_PARM_LEVEL (parm)
24665 != template_decl_level (tparm))
24667 /* The PARM is not one we're trying to unify. Just check
24668 to see if it matches ARG. */
24669 int result = !(TREE_CODE (arg) == TREE_CODE (parm)
24670 && cp_tree_equal (parm, arg));
24671 if (result)
24672 unify_expression_unequal (explain_p, parm, arg);
24673 return result;
24676 idx = TEMPLATE_PARM_IDX (parm);
24677 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24679 if (targ)
24681 if ((strict & UNIFY_ALLOW_INTEGER)
24682 && TREE_TYPE (targ) && TREE_TYPE (arg)
24683 && CP_INTEGRAL_TYPE_P (TREE_TYPE (targ)))
24684 /* We're deducing from an array bound, the type doesn't matter.
24685 This conversion should match the one below. */
24686 arg = fold (build_nop (TREE_TYPE (targ), arg));
24687 int x = !cp_tree_equal (targ, arg);
24688 if (x)
24689 unify_inconsistency (explain_p, parm, targ, arg);
24690 return x;
24693 /* [temp.deduct.type] If, in the declaration of a function template
24694 with a non-type template-parameter, the non-type
24695 template-parameter is used in an expression in the function
24696 parameter-list and, if the corresponding template-argument is
24697 deduced, the template-argument type shall match the type of the
24698 template-parameter exactly, except that a template-argument
24699 deduced from an array bound may be of any integral type.
24700 The non-type parameter might use already deduced type parameters. */
24701 tparm = TREE_TYPE (parm);
24702 if (TEMPLATE_PARM_LEVEL (parm) > TMPL_ARGS_DEPTH (targs))
24703 /* We don't have enough levels of args to do any substitution. This
24704 can happen in the context of -fnew-ttp-matching. */;
24705 else
24707 ++processing_template_decl;
24708 tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
24709 --processing_template_decl;
24711 if (tree a = type_uses_auto (tparm))
24713 tparm = do_auto_deduction (tparm, arg, a,
24714 complain, adc_unify, targs,
24715 LOOKUP_NORMAL,
24716 TPARMS_PRIMARY_TEMPLATE (tparms));
24717 if (tparm == error_mark_node)
24718 return 1;
24722 if (!TREE_TYPE (arg)
24723 || TREE_CODE (TREE_TYPE (arg)) == DEPENDENT_OPERATOR_TYPE)
24724 /* Template-parameter dependent expression. Just accept it for now.
24725 It will later be processed in convert_template_argument. */
24727 else if (same_type_ignoring_top_level_qualifiers_p
24728 (non_reference (TREE_TYPE (arg)),
24729 non_reference (tparm)))
24730 /* OK. Ignore top-level quals here because a class-type template
24731 parameter object is const. */;
24732 else if ((strict & UNIFY_ALLOW_INTEGER)
24733 && CP_INTEGRAL_TYPE_P (tparm))
24734 /* Convert the ARG to the type of PARM; the deduced non-type
24735 template argument must exactly match the types of the
24736 corresponding parameter. This conversion should match the
24737 one above. */
24738 arg = fold (build_nop (tparm, arg));
24739 else if (uses_template_parms (tparm))
24741 /* We haven't deduced the type of this parameter yet. */
24742 if (cxx_dialect >= cxx17
24743 /* We deduce from array bounds in try_array_deduction. */
24744 && !(strict & UNIFY_ALLOW_INTEGER)
24745 && TEMPLATE_PARM_LEVEL (parm) <= TMPL_ARGS_DEPTH (targs))
24747 /* Deduce it from the non-type argument. As above, ignore
24748 top-level quals here too. */
24749 tree atype = cv_unqualified (TREE_TYPE (arg));
24750 RECUR_AND_CHECK_FAILURE (tparms, targs,
24751 tparm, atype,
24752 UNIFY_ALLOW_NONE, explain_p);
24753 /* Now check whether the type of this parameter is still
24754 dependent, and give up if so. */
24755 ++processing_template_decl;
24756 tparm = tsubst (TREE_TYPE (parm), targs, tf_none, NULL_TREE);
24757 --processing_template_decl;
24758 if (uses_template_parms (tparm))
24759 return unify_success (explain_p);
24761 else
24762 /* Try again later. */
24763 return unify_success (explain_p);
24765 else
24766 return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
24768 /* If ARG is a parameter pack or an expansion, we cannot unify
24769 against it unless PARM is also a parameter pack. */
24770 if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
24771 && !TEMPLATE_PARM_PARAMETER_PACK (parm))
24772 return unify_parameter_pack_mismatch (explain_p, parm, arg);
24775 bool removed_attr = false;
24776 arg = strip_typedefs_expr (arg, &removed_attr);
24778 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
24779 return unify_success (explain_p);
24781 case PTRMEM_CST:
24783 /* A pointer-to-member constant can be unified only with
24784 another constant. */
24785 if (TREE_CODE (arg) != PTRMEM_CST)
24786 return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
24788 /* Just unify the class member. It would be useless (and possibly
24789 wrong, depending on the strict flags) to unify also
24790 PTRMEM_CST_CLASS, because we want to be sure that both parm and
24791 arg refer to the same variable, even if through different
24792 classes. For instance:
24794 struct A { int x; };
24795 struct B : A { };
24797 Unification of &A::x and &B::x must succeed. */
24798 return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
24799 PTRMEM_CST_MEMBER (arg), strict, explain_p);
24802 case POINTER_TYPE:
24804 if (!TYPE_PTR_P (arg))
24805 return unify_type_mismatch (explain_p, parm, arg);
24807 /* [temp.deduct.call]
24809 A can be another pointer or pointer to member type that can
24810 be converted to the deduced A via a qualification
24811 conversion (_conv.qual_).
24813 We pass down STRICT here rather than UNIFY_ALLOW_NONE.
24814 This will allow for additional cv-qualification of the
24815 pointed-to types if appropriate. */
24817 if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
24818 /* The derived-to-base conversion only persists through one
24819 level of pointers. */
24820 strict |= (strict_in & UNIFY_ALLOW_DERIVED);
24822 return unify (tparms, targs, TREE_TYPE (parm),
24823 TREE_TYPE (arg), strict, explain_p);
24826 case REFERENCE_TYPE:
24827 if (!TYPE_REF_P (arg))
24828 return unify_type_mismatch (explain_p, parm, arg);
24829 return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24830 strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
24832 case ARRAY_TYPE:
24833 if (TREE_CODE (arg) != ARRAY_TYPE)
24834 return unify_type_mismatch (explain_p, parm, arg);
24835 if ((TYPE_DOMAIN (parm) == NULL_TREE)
24836 != (TYPE_DOMAIN (arg) == NULL_TREE))
24837 return unify_type_mismatch (explain_p, parm, arg);
24838 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24839 strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
24840 if (TYPE_DOMAIN (parm) != NULL_TREE)
24841 return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
24842 TYPE_DOMAIN (arg), explain_p);
24843 return unify_success (explain_p);
24845 case REAL_TYPE:
24846 case COMPLEX_TYPE:
24847 case VECTOR_TYPE:
24848 case INTEGER_TYPE:
24849 case BOOLEAN_TYPE:
24850 case ENUMERAL_TYPE:
24851 case VOID_TYPE:
24852 case OPAQUE_TYPE:
24853 case NULLPTR_TYPE:
24854 if (TREE_CODE (arg) != TREE_CODE (parm))
24855 return unify_type_mismatch (explain_p, parm, arg);
24857 /* We have already checked cv-qualification at the top of the
24858 function. */
24859 if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
24860 return unify_type_mismatch (explain_p, parm, arg);
24862 /* As far as unification is concerned, this wins. Later checks
24863 will invalidate it if necessary. */
24864 return unify_success (explain_p);
24866 /* Types INTEGER_CST and MINUS_EXPR can come from array bounds. */
24867 /* Type INTEGER_CST can come from ordinary constant template args. */
24868 case INTEGER_CST:
24869 while (CONVERT_EXPR_P (arg))
24870 arg = TREE_OPERAND (arg, 0);
24872 if (TREE_CODE (arg) != INTEGER_CST)
24873 return unify_template_argument_mismatch (explain_p, parm, arg);
24874 return (tree_int_cst_equal (parm, arg)
24875 ? unify_success (explain_p)
24876 : unify_template_argument_mismatch (explain_p, parm, arg));
24878 case TREE_VEC:
24880 int i, len, argslen;
24881 int parm_variadic_p = 0;
24883 if (TREE_CODE (arg) != TREE_VEC)
24884 return unify_template_argument_mismatch (explain_p, parm, arg);
24886 len = TREE_VEC_LENGTH (parm);
24887 argslen = TREE_VEC_LENGTH (arg);
24889 /* Check for pack expansions in the parameters. */
24890 for (i = 0; i < len; ++i)
24892 if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
24894 if (i == len - 1)
24895 /* We can unify against something with a trailing
24896 parameter pack. */
24897 parm_variadic_p = 1;
24898 else
24899 /* [temp.deduct.type]/9: If the template argument list of
24900 P contains a pack expansion that is not the last
24901 template argument, the entire template argument list
24902 is a non-deduced context. */
24903 return unify_success (explain_p);
24907 /* If we don't have enough arguments to satisfy the parameters
24908 (not counting the pack expression at the end), or we have
24909 too many arguments for a parameter list that doesn't end in
24910 a pack expression, we can't unify. */
24911 if (parm_variadic_p
24912 ? argslen < len - parm_variadic_p
24913 : argslen != len)
24914 return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
24916 /* Unify all of the parameters that precede the (optional)
24917 pack expression. */
24918 for (i = 0; i < len - parm_variadic_p; ++i)
24920 RECUR_AND_CHECK_FAILURE (tparms, targs,
24921 TREE_VEC_ELT (parm, i),
24922 TREE_VEC_ELT (arg, i),
24923 UNIFY_ALLOW_NONE, explain_p);
24925 if (parm_variadic_p)
24926 return unify_pack_expansion (tparms, targs, parm, arg,
24927 DEDUCE_EXACT,
24928 /*subr=*/true, explain_p);
24929 return unify_success (explain_p);
24932 case RECORD_TYPE:
24933 case UNION_TYPE:
24934 if (TREE_CODE (arg) != TREE_CODE (parm))
24935 return unify_type_mismatch (explain_p, parm, arg);
24937 if (TYPE_PTRMEMFUNC_P (parm))
24939 if (!TYPE_PTRMEMFUNC_P (arg))
24940 return unify_type_mismatch (explain_p, parm, arg);
24942 return unify (tparms, targs,
24943 TYPE_PTRMEMFUNC_FN_TYPE (parm),
24944 TYPE_PTRMEMFUNC_FN_TYPE (arg),
24945 strict, explain_p);
24947 else if (TYPE_PTRMEMFUNC_P (arg))
24948 return unify_type_mismatch (explain_p, parm, arg);
24950 if (CLASSTYPE_TEMPLATE_INFO (parm))
24952 tree t = NULL_TREE;
24954 if (strict_in & UNIFY_ALLOW_DERIVED)
24956 /* First, we try to unify the PARM and ARG directly. */
24957 t = try_class_unification (tparms, targs,
24958 parm, arg, explain_p);
24960 if (!t)
24962 /* Fallback to the special case allowed in
24963 [temp.deduct.call]:
24965 If P is a class, and P has the form
24966 template-id, then A can be a derived class of
24967 the deduced A. Likewise, if P is a pointer to
24968 a class of the form template-id, A can be a
24969 pointer to a derived class pointed to by the
24970 deduced A. */
24971 enum template_base_result r;
24972 r = get_template_base (tparms, targs, parm, arg,
24973 explain_p, &t);
24975 if (!t)
24977 /* Don't give the derived diagnostic if we're
24978 already dealing with the same template. */
24979 bool same_template
24980 = (CLASSTYPE_TEMPLATE_INFO (arg)
24981 && (CLASSTYPE_TI_TEMPLATE (parm)
24982 == CLASSTYPE_TI_TEMPLATE (arg)));
24983 return unify_no_common_base (explain_p && !same_template,
24984 r, parm, arg);
24988 else if (CLASSTYPE_TEMPLATE_INFO (arg)
24989 && (CLASSTYPE_TI_TEMPLATE (parm)
24990 == CLASSTYPE_TI_TEMPLATE (arg)))
24991 /* Perhaps PARM is something like S<U> and ARG is S<int>.
24992 Then, we should unify `int' and `U'. */
24993 t = arg;
24994 else
24995 /* There's no chance of unification succeeding. */
24996 return unify_type_mismatch (explain_p, parm, arg);
24998 return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
24999 CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
25001 else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
25002 return unify_type_mismatch (explain_p, parm, arg);
25003 return unify_success (explain_p);
25005 case METHOD_TYPE:
25006 case FUNCTION_TYPE:
25008 unsigned int nargs;
25009 tree *args;
25010 tree a;
25011 unsigned int i;
25013 if (TREE_CODE (arg) != TREE_CODE (parm))
25014 return unify_type_mismatch (explain_p, parm, arg);
25016 /* CV qualifications for methods can never be deduced, they must
25017 match exactly. We need to check them explicitly here,
25018 because type_unification_real treats them as any other
25019 cv-qualified parameter. */
25020 if (TREE_CODE (parm) == METHOD_TYPE
25021 && (!check_cv_quals_for_unify
25022 (UNIFY_ALLOW_NONE,
25023 class_of_this_parm (arg),
25024 class_of_this_parm (parm))))
25025 return unify_cv_qual_mismatch (explain_p, parm, arg);
25026 if (TREE_CODE (arg) == FUNCTION_TYPE
25027 && type_memfn_quals (parm) != type_memfn_quals (arg))
25028 return unify_cv_qual_mismatch (explain_p, parm, arg);
25029 if (type_memfn_rqual (parm) != type_memfn_rqual (arg))
25030 return unify_type_mismatch (explain_p, parm, arg);
25032 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
25033 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
25035 nargs = list_length (TYPE_ARG_TYPES (arg));
25036 args = XALLOCAVEC (tree, nargs);
25037 for (a = TYPE_ARG_TYPES (arg), i = 0;
25038 a != NULL_TREE && a != void_list_node;
25039 a = TREE_CHAIN (a), ++i)
25040 args[i] = TREE_VALUE (a);
25041 nargs = i;
25043 if (type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
25044 args, nargs, 1, DEDUCE_EXACT,
25045 NULL, explain_p))
25046 return 1;
25048 if (flag_noexcept_type)
25050 tree pspec = TYPE_RAISES_EXCEPTIONS (parm);
25051 tree aspec = canonical_eh_spec (TYPE_RAISES_EXCEPTIONS (arg));
25052 if (pspec == NULL_TREE) pspec = noexcept_false_spec;
25053 if (aspec == NULL_TREE) aspec = noexcept_false_spec;
25054 if (TREE_PURPOSE (pspec) && TREE_PURPOSE (aspec)
25055 && uses_template_parms (TREE_PURPOSE (pspec)))
25056 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_PURPOSE (pspec),
25057 TREE_PURPOSE (aspec),
25058 UNIFY_ALLOW_NONE, explain_p);
25059 else
25061 bool pn = nothrow_spec_p (pspec);
25062 bool an = nothrow_spec_p (aspec);
25063 /* Here "less cv-qual" means the deduced arg (i.e. parm) has
25064 /more/ noexcept, since function pointer conversions are the
25065 reverse of qualification conversions. */
25066 if (an == pn
25067 || (an < pn && (strict & UNIFY_ALLOW_LESS_CV_QUAL))
25068 || (an > pn && (strict & UNIFY_ALLOW_MORE_CV_QUAL)))
25069 /* OK. */;
25070 else
25071 return unify_type_mismatch (explain_p, parm, arg);
25074 if (flag_tm)
25076 /* As for noexcept. */
25077 bool pn = tx_safe_fn_type_p (parm);
25078 bool an = tx_safe_fn_type_p (arg);
25079 if (an == pn
25080 || (an < pn && (strict & UNIFY_ALLOW_LESS_CV_QUAL))
25081 || (an > pn && (strict & UNIFY_ALLOW_MORE_CV_QUAL)))
25082 /* OK. */;
25083 else
25084 return unify_type_mismatch (explain_p, parm, arg);
25087 return 0;
25090 case OFFSET_TYPE:
25091 /* Unify a pointer to member with a pointer to member function, which
25092 deduces the type of the member as a function type. */
25093 if (TYPE_PTRMEMFUNC_P (arg))
25095 /* Check top-level cv qualifiers */
25096 if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
25097 return unify_cv_qual_mismatch (explain_p, parm, arg);
25099 RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
25100 TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
25101 UNIFY_ALLOW_NONE, explain_p);
25103 /* Determine the type of the function we are unifying against. */
25104 tree fntype = static_fn_type (arg);
25106 return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
25109 if (TREE_CODE (arg) != OFFSET_TYPE)
25110 return unify_type_mismatch (explain_p, parm, arg);
25111 RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
25112 TYPE_OFFSET_BASETYPE (arg),
25113 UNIFY_ALLOW_NONE, explain_p);
25114 return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
25115 strict, explain_p);
25117 case CONST_DECL:
25118 if (DECL_TEMPLATE_PARM_P (parm))
25119 return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
25120 if (arg != scalar_constant_value (parm))
25121 return unify_template_argument_mismatch (explain_p, parm, arg);
25122 return unify_success (explain_p);
25124 case FIELD_DECL:
25125 case TEMPLATE_DECL:
25126 /* Matched cases are handled by the ARG == PARM test above. */
25127 return unify_template_argument_mismatch (explain_p, parm, arg);
25129 case VAR_DECL:
25130 /* We might get a variable as a non-type template argument in parm if the
25131 corresponding parameter is type-dependent. Make any necessary
25132 adjustments based on whether arg is a reference. */
25133 if (CONSTANT_CLASS_P (arg))
25134 parm = fold_non_dependent_expr (parm, complain);
25135 else if (REFERENCE_REF_P (arg))
25137 tree sub = TREE_OPERAND (arg, 0);
25138 STRIP_NOPS (sub);
25139 if (TREE_CODE (sub) == ADDR_EXPR)
25140 arg = TREE_OPERAND (sub, 0);
25142 /* Now use the normal expression code to check whether they match. */
25143 goto expr;
25145 case TYPE_ARGUMENT_PACK:
25146 case NONTYPE_ARGUMENT_PACK:
25147 return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
25148 ARGUMENT_PACK_ARGS (arg), strict, explain_p);
25150 case TYPEOF_TYPE:
25151 case DECLTYPE_TYPE:
25152 case TRAIT_TYPE:
25153 /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
25154 or TRAIT_TYPE nodes. */
25155 return unify_success (explain_p);
25157 case ERROR_MARK:
25158 /* Unification fails if we hit an error node. */
25159 return unify_invalid (explain_p);
25161 case INDIRECT_REF:
25162 if (REFERENCE_REF_P (parm))
25164 bool pexp = PACK_EXPANSION_P (arg);
25165 if (pexp)
25166 arg = PACK_EXPANSION_PATTERN (arg);
25167 if (REFERENCE_REF_P (arg))
25168 arg = TREE_OPERAND (arg, 0);
25169 if (pexp)
25170 arg = make_pack_expansion (arg, complain);
25171 return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
25172 strict, explain_p);
25174 /* FALLTHRU */
25176 default:
25177 /* An unresolved overload is a nondeduced context. */
25178 if (is_overloaded_fn (parm) || type_unknown_p (parm))
25179 return unify_success (explain_p);
25180 gcc_assert (EXPR_P (parm)
25181 || TREE_CODE (parm) == CONSTRUCTOR
25182 || TREE_CODE (parm) == TRAIT_EXPR);
25183 expr:
25184 /* We must be looking at an expression. This can happen with
25185 something like:
25187 template <int I>
25188 void foo(S<I>, S<I + 2>);
25192 template<typename T>
25193 void foo(A<T, T{}>);
25195 This is a "non-deduced context":
25197 [deduct.type]
25199 The non-deduced contexts are:
25201 --A non-type template argument or an array bound in which
25202 a subexpression references a template parameter.
25204 In these cases, we assume deduction succeeded, but don't
25205 actually infer any unifications. */
25207 if (!uses_template_parms (parm)
25208 && !template_args_equal (parm, arg))
25209 return unify_expression_unequal (explain_p, parm, arg);
25210 else
25211 return unify_success (explain_p);
25214 #undef RECUR_AND_CHECK_FAILURE
25216 /* Note that DECL can be defined in this translation unit, if
25217 required. */
25219 static void
25220 mark_definable (tree decl)
25222 tree clone;
25223 DECL_NOT_REALLY_EXTERN (decl) = 1;
25224 FOR_EACH_CLONE (clone, decl)
25225 DECL_NOT_REALLY_EXTERN (clone) = 1;
25228 /* Called if RESULT is explicitly instantiated, or is a member of an
25229 explicitly instantiated class. */
25231 void
25232 mark_decl_instantiated (tree result, int extern_p)
25234 SET_DECL_EXPLICIT_INSTANTIATION (result);
25236 /* If this entity has already been written out, it's too late to
25237 make any modifications. */
25238 if (TREE_ASM_WRITTEN (result))
25239 return;
25241 /* consteval functions are never emitted. */
25242 if (TREE_CODE (result) == FUNCTION_DECL
25243 && DECL_IMMEDIATE_FUNCTION_P (result))
25244 return;
25246 /* For anonymous namespace we don't need to do anything. */
25247 if (decl_internal_context_p (result))
25249 gcc_assert (!TREE_PUBLIC (result));
25250 return;
25253 if (TREE_CODE (result) != FUNCTION_DECL)
25254 /* The TREE_PUBLIC flag for function declarations will have been
25255 set correctly by tsubst. */
25256 TREE_PUBLIC (result) = 1;
25258 if (extern_p)
25260 DECL_EXTERNAL (result) = 1;
25261 DECL_NOT_REALLY_EXTERN (result) = 0;
25263 else
25265 mark_definable (result);
25266 mark_needed (result);
25267 /* Always make artificials weak. */
25268 if (DECL_ARTIFICIAL (result) && flag_weak)
25269 comdat_linkage (result);
25270 /* For WIN32 we also want to put explicit instantiations in
25271 linkonce sections. */
25272 else if (TREE_PUBLIC (result))
25273 maybe_make_one_only (result);
25274 if (TREE_CODE (result) == FUNCTION_DECL
25275 && DECL_TEMPLATE_INSTANTIATED (result))
25276 /* If the function has already been instantiated, clear DECL_EXTERNAL,
25277 since start_preparsed_function wouldn't have if we had an earlier
25278 extern explicit instantiation. */
25279 DECL_EXTERNAL (result) = 0;
25282 /* If EXTERN_P, then this function will not be emitted -- unless
25283 followed by an explicit instantiation, at which point its linkage
25284 will be adjusted. If !EXTERN_P, then this function will be
25285 emitted here. In neither circumstance do we want
25286 import_export_decl to adjust the linkage. */
25287 DECL_INTERFACE_KNOWN (result) = 1;
25290 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
25291 important template arguments. If any are missing, we check whether
25292 they're important by using error_mark_node for substituting into any
25293 args that were used for partial ordering (the ones between ARGS and END)
25294 and seeing if it bubbles up. */
25296 static bool
25297 check_undeduced_parms (tree targs, tree args, tree end)
25299 bool found = false;
25300 for (tree& targ : tree_vec_range (targs))
25301 if (targ == NULL_TREE)
25303 found = true;
25304 targ = error_mark_node;
25306 if (found)
25308 tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
25309 if (substed == error_mark_node)
25310 return true;
25312 return false;
25315 /* Given two function templates PAT1 and PAT2, return:
25317 1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
25318 -1 if PAT2 is more specialized than PAT1.
25319 0 if neither is more specialized.
25321 LEN indicates the number of parameters we should consider
25322 (defaulted parameters should not be considered).
25324 The 1998 std underspecified function template partial ordering, and
25325 DR214 addresses the issue. We take pairs of arguments, one from
25326 each of the templates, and deduce them against each other. One of
25327 the templates will be more specialized if all the *other*
25328 template's arguments deduce against its arguments and at least one
25329 of its arguments *does* *not* deduce against the other template's
25330 corresponding argument. Deduction is done as for class templates.
25331 The arguments used in deduction have reference and top level cv
25332 qualifiers removed. Iff both arguments were originally reference
25333 types *and* deduction succeeds in both directions, an lvalue reference
25334 wins against an rvalue reference and otherwise the template
25335 with the more cv-qualified argument wins for that pairing (if
25336 neither is more cv-qualified, they both are equal). Unlike regular
25337 deduction, after all the arguments have been deduced in this way,
25338 we do *not* verify the deduced template argument values can be
25339 substituted into non-deduced contexts.
25341 The logic can be a bit confusing here, because we look at deduce1 and
25342 targs1 to see if pat2 is at least as specialized, and vice versa; if we
25343 can find template arguments for pat1 to make arg1 look like arg2, that
25344 means that arg2 is at least as specialized as arg1. */
25347 more_specialized_fn (tree pat1, tree pat2, int len)
25349 tree decl1 = DECL_TEMPLATE_RESULT (pat1);
25350 tree decl2 = DECL_TEMPLATE_RESULT (pat2);
25351 tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
25352 tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
25353 tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
25354 tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
25355 tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
25356 tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
25357 tree origs1, origs2;
25358 bool lose1 = false;
25359 bool lose2 = false;
25361 /* Remove the this parameter from non-static member functions. If
25362 one is a non-static member function and the other is not a static
25363 member function, remove the first parameter from that function
25364 also. This situation occurs for operator functions where we
25365 locate both a member function (with this pointer) and non-member
25366 operator (with explicit first operand). */
25367 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
25369 len--; /* LEN is the number of significant arguments for DECL1 */
25370 args1 = TREE_CHAIN (args1);
25371 if (!DECL_STATIC_FUNCTION_P (decl2))
25372 args2 = TREE_CHAIN (args2);
25374 else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
25376 args2 = TREE_CHAIN (args2);
25377 if (!DECL_STATIC_FUNCTION_P (decl1))
25379 len--;
25380 args1 = TREE_CHAIN (args1);
25384 /* If only one is a conversion operator, they are unordered. */
25385 if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
25386 return 0;
25388 /* Consider the return type for a conversion function */
25389 if (DECL_CONV_FN_P (decl1))
25391 args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
25392 args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
25393 len++;
25396 processing_template_decl++;
25398 origs1 = args1;
25399 origs2 = args2;
25401 while (len--
25402 /* Stop when an ellipsis is seen. */
25403 && args1 != NULL_TREE && args2 != NULL_TREE)
25405 tree arg1 = TREE_VALUE (args1);
25406 tree arg2 = TREE_VALUE (args2);
25407 int deduce1, deduce2;
25408 int quals1 = -1;
25409 int quals2 = -1;
25410 int ref1 = 0;
25411 int ref2 = 0;
25413 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
25414 && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25416 /* When both arguments are pack expansions, we need only
25417 unify the patterns themselves. */
25418 arg1 = PACK_EXPANSION_PATTERN (arg1);
25419 arg2 = PACK_EXPANSION_PATTERN (arg2);
25421 /* This is the last comparison we need to do. */
25422 len = 0;
25425 if (TYPE_REF_P (arg1))
25427 ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
25428 arg1 = TREE_TYPE (arg1);
25429 quals1 = cp_type_quals (arg1);
25432 if (TYPE_REF_P (arg2))
25434 ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
25435 arg2 = TREE_TYPE (arg2);
25436 quals2 = cp_type_quals (arg2);
25439 arg1 = TYPE_MAIN_VARIANT (arg1);
25440 arg2 = TYPE_MAIN_VARIANT (arg2);
25442 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
25444 int i, len2 = remaining_arguments (args2);
25445 tree parmvec = make_tree_vec (1);
25446 tree argvec = make_tree_vec (len2);
25447 tree ta = args2;
25449 /* Setup the parameter vector, which contains only ARG1. */
25450 TREE_VEC_ELT (parmvec, 0) = arg1;
25452 /* Setup the argument vector, which contains the remaining
25453 arguments. */
25454 for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
25455 TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
25457 deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
25458 argvec, DEDUCE_EXACT,
25459 /*subr=*/true, /*explain_p=*/false)
25460 == 0);
25462 /* We cannot deduce in the other direction, because ARG1 is
25463 a pack expansion but ARG2 is not. */
25464 deduce2 = 0;
25466 else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25468 int i, len1 = remaining_arguments (args1);
25469 tree parmvec = make_tree_vec (1);
25470 tree argvec = make_tree_vec (len1);
25471 tree ta = args1;
25473 /* Setup the parameter vector, which contains only ARG1. */
25474 TREE_VEC_ELT (parmvec, 0) = arg2;
25476 /* Setup the argument vector, which contains the remaining
25477 arguments. */
25478 for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
25479 TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
25481 deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
25482 argvec, DEDUCE_EXACT,
25483 /*subr=*/true, /*explain_p=*/false)
25484 == 0);
25486 /* We cannot deduce in the other direction, because ARG2 is
25487 a pack expansion but ARG1 is not.*/
25488 deduce1 = 0;
25491 else
25493 /* The normal case, where neither argument is a pack
25494 expansion. */
25495 deduce1 = (unify (tparms1, targs1, arg1, arg2,
25496 UNIFY_ALLOW_NONE, /*explain_p=*/false)
25497 == 0);
25498 deduce2 = (unify (tparms2, targs2, arg2, arg1,
25499 UNIFY_ALLOW_NONE, /*explain_p=*/false)
25500 == 0);
25503 /* If we couldn't deduce arguments for tparms1 to make arg1 match
25504 arg2, then arg2 is not as specialized as arg1. */
25505 if (!deduce1)
25506 lose2 = true;
25507 if (!deduce2)
25508 lose1 = true;
25510 /* "If, for a given type, deduction succeeds in both directions
25511 (i.e., the types are identical after the transformations above)
25512 and both P and A were reference types (before being replaced with
25513 the type referred to above):
25514 - if the type from the argument template was an lvalue reference and
25515 the type from the parameter template was not, the argument type is
25516 considered to be more specialized than the other; otherwise,
25517 - if the type from the argument template is more cv-qualified
25518 than the type from the parameter template (as described above),
25519 the argument type is considered to be more specialized than the other;
25520 otherwise,
25521 - neither type is more specialized than the other." */
25523 if (deduce1 && deduce2)
25525 if (ref1 && ref2 && ref1 != ref2)
25527 if (ref1 > ref2)
25528 lose1 = true;
25529 else
25530 lose2 = true;
25532 else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
25534 if ((quals1 & quals2) == quals2)
25535 lose2 = true;
25536 if ((quals1 & quals2) == quals1)
25537 lose1 = true;
25541 if (lose1 && lose2)
25542 /* We've failed to deduce something in either direction.
25543 These must be unordered. */
25544 break;
25546 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
25547 || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25548 /* We have already processed all of the arguments in our
25549 handing of the pack expansion type. */
25550 len = 0;
25552 args1 = TREE_CHAIN (args1);
25553 args2 = TREE_CHAIN (args2);
25556 /* "In most cases, all template parameters must have values in order for
25557 deduction to succeed, but for partial ordering purposes a template
25558 parameter may remain without a value provided it is not used in the
25559 types being used for partial ordering."
25561 Thus, if we are missing any of the targs1 we need to substitute into
25562 origs1, then pat2 is not as specialized as pat1. This can happen when
25563 there is a nondeduced context. */
25564 if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
25565 lose2 = true;
25566 if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
25567 lose1 = true;
25569 processing_template_decl--;
25571 /* If both deductions succeed, the partial ordering selects the more
25572 constrained template. */
25573 /* P2113: If the corresponding template-parameters of the
25574 template-parameter-lists are not equivalent ([temp.over.link]) or if
25575 the function parameters that positionally correspond between the two
25576 templates are not of the same type, neither template is more
25577 specialized than the other. */
25578 if (!lose1 && !lose2
25579 && comp_template_parms (DECL_TEMPLATE_PARMS (pat1),
25580 DECL_TEMPLATE_PARMS (pat2))
25581 && compparms (origs1, origs2))
25583 int winner = more_constrained (decl1, decl2);
25584 if (winner > 0)
25585 lose2 = true;
25586 else if (winner < 0)
25587 lose1 = true;
25590 /* All things being equal, if the next argument is a pack expansion
25591 for one function but not for the other, prefer the
25592 non-variadic function. FIXME this is bogus; see c++/41958. */
25593 if (lose1 == lose2
25594 && args1 && TREE_VALUE (args1)
25595 && args2 && TREE_VALUE (args2))
25597 lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
25598 lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
25601 if (lose1 == lose2)
25602 return 0;
25603 else if (!lose1)
25604 return 1;
25605 else
25606 return -1;
25609 /* Determine which of two partial specializations of TMPL is more
25610 specialized.
25612 PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
25613 to the first partial specialization. The TREE_PURPOSE is the
25614 innermost set of template parameters for the partial
25615 specialization. PAT2 is similar, but for the second template.
25617 Return 1 if the first partial specialization is more specialized;
25618 -1 if the second is more specialized; 0 if neither is more
25619 specialized.
25621 See [temp.class.order] for information about determining which of
25622 two templates is more specialized. */
25624 static int
25625 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
25627 tree targs;
25628 int winner = 0;
25629 bool any_deductions = false;
25631 tree tmpl1 = TREE_VALUE (pat1);
25632 tree tmpl2 = TREE_VALUE (pat2);
25633 tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
25634 tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
25636 /* Just like what happens for functions, if we are ordering between
25637 different template specializations, we may encounter dependent
25638 types in the arguments, and we need our dependency check functions
25639 to behave correctly. */
25640 ++processing_template_decl;
25641 targs = get_partial_spec_bindings (tmpl, tmpl1, specargs2);
25642 if (targs)
25644 --winner;
25645 any_deductions = true;
25648 targs = get_partial_spec_bindings (tmpl, tmpl2, specargs1);
25649 if (targs)
25651 ++winner;
25652 any_deductions = true;
25654 --processing_template_decl;
25656 /* If both deductions succeed, the partial ordering selects the more
25657 constrained template. */
25658 if (!winner && any_deductions)
25659 winner = more_constrained (tmpl1, tmpl2);
25661 /* In the case of a tie where at least one of the templates
25662 has a parameter pack at the end, the template with the most
25663 non-packed parameters wins. */
25664 if (winner == 0
25665 && any_deductions
25666 && (template_args_variadic_p (TREE_PURPOSE (pat1))
25667 || template_args_variadic_p (TREE_PURPOSE (pat2))))
25669 tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
25670 tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
25671 int len1 = TREE_VEC_LENGTH (args1);
25672 int len2 = TREE_VEC_LENGTH (args2);
25674 /* We don't count the pack expansion at the end. */
25675 if (template_args_variadic_p (TREE_PURPOSE (pat1)))
25676 --len1;
25677 if (template_args_variadic_p (TREE_PURPOSE (pat2)))
25678 --len2;
25680 if (len1 > len2)
25681 return 1;
25682 else if (len1 < len2)
25683 return -1;
25686 return winner;
25689 /* Return the template arguments that will produce the function signature
25690 DECL from the function template FN, with the explicit template
25691 arguments EXPLICIT_ARGS. If CHECK_RETTYPE is true, the return type must
25692 also match. Return NULL_TREE if no satisfactory arguments could be
25693 found. */
25695 static tree
25696 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
25698 int ntparms = DECL_NTPARMS (fn);
25699 tree targs = make_tree_vec (ntparms);
25700 tree decl_type = TREE_TYPE (decl);
25701 tree decl_arg_types;
25702 tree *args;
25703 unsigned int nargs, ix;
25704 tree arg;
25706 gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
25708 /* Never do unification on the 'this' parameter. */
25709 decl_arg_types = skip_artificial_parms_for (decl,
25710 TYPE_ARG_TYPES (decl_type));
25712 nargs = list_length (decl_arg_types);
25713 args = XALLOCAVEC (tree, nargs);
25714 for (arg = decl_arg_types, ix = 0;
25715 arg != NULL_TREE;
25716 arg = TREE_CHAIN (arg), ++ix)
25717 args[ix] = TREE_VALUE (arg);
25719 if (fn_type_unification (fn, explicit_args, targs,
25720 args, ix,
25721 (check_rettype || DECL_CONV_FN_P (fn)
25722 ? TREE_TYPE (decl_type) : NULL_TREE),
25723 DEDUCE_EXACT, LOOKUP_NORMAL, NULL,
25724 /*explain_p=*/false,
25725 /*decltype*/false)
25726 == error_mark_node)
25727 return NULL_TREE;
25729 return targs;
25732 /* Return the innermost template arguments that, when applied to a partial
25733 specialization SPEC_TMPL of TMPL, yield the ARGS.
25735 For example, suppose we have:
25737 template <class T, class U> struct S {};
25738 template <class T> struct S<T*, int> {};
25740 Then, suppose we want to get `S<double*, int>'. SPEC_TMPL will be the
25741 partial specialization and the ARGS will be {double*, int}. The resulting
25742 vector will be {double}, indicating that `T' is bound to `double'. */
25744 static tree
25745 get_partial_spec_bindings (tree tmpl, tree spec_tmpl, tree args)
25747 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
25748 tree spec_args
25749 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (spec_tmpl)));
25750 int i, ntparms = TREE_VEC_LENGTH (tparms);
25751 tree deduced_args;
25752 tree innermost_deduced_args;
25754 innermost_deduced_args = make_tree_vec (ntparms);
25755 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
25757 deduced_args = copy_node (args);
25758 SET_TMPL_ARGS_LEVEL (deduced_args,
25759 TMPL_ARGS_DEPTH (deduced_args),
25760 innermost_deduced_args);
25762 else
25763 deduced_args = innermost_deduced_args;
25765 bool tried_array_deduction = (cxx_dialect < cxx17);
25766 again:
25767 if (unify (tparms, deduced_args,
25768 INNERMOST_TEMPLATE_ARGS (spec_args),
25769 INNERMOST_TEMPLATE_ARGS (args),
25770 UNIFY_ALLOW_NONE, /*explain_p=*/false))
25771 return NULL_TREE;
25773 for (i = 0; i < ntparms; ++i)
25774 if (! TREE_VEC_ELT (innermost_deduced_args, i))
25776 if (!tried_array_deduction)
25778 try_array_deduction (tparms, innermost_deduced_args,
25779 INNERMOST_TEMPLATE_ARGS (spec_args));
25780 tried_array_deduction = true;
25781 if (TREE_VEC_ELT (innermost_deduced_args, i))
25782 goto again;
25784 return NULL_TREE;
25787 if (!push_tinst_level (spec_tmpl, deduced_args))
25789 excessive_deduction_depth = true;
25790 return NULL_TREE;
25793 /* Verify that nondeduced template arguments agree with the type
25794 obtained from argument deduction.
25796 For example:
25798 struct A { typedef int X; };
25799 template <class T, class U> struct C {};
25800 template <class T> struct C<T, typename T::X> {};
25802 Then with the instantiation `C<A, int>', we can deduce that
25803 `T' is `A' but unify () does not check whether `typename T::X'
25804 is `int'. */
25805 spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
25807 if (spec_args != error_mark_node)
25808 spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
25809 INNERMOST_TEMPLATE_ARGS (spec_args),
25810 tmpl, tf_none, false);
25812 pop_tinst_level ();
25814 if (spec_args == error_mark_node
25815 /* We only need to check the innermost arguments; the other
25816 arguments will always agree. */
25817 || !comp_template_args_porder (INNERMOST_TEMPLATE_ARGS (spec_args),
25818 INNERMOST_TEMPLATE_ARGS (args)))
25819 return NULL_TREE;
25821 /* Now that we have bindings for all of the template arguments,
25822 ensure that the arguments deduced for the template template
25823 parameters have compatible template parameter lists. See the use
25824 of template_template_parm_bindings_ok_p in fn_type_unification
25825 for more information. */
25826 if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
25827 return NULL_TREE;
25829 return deduced_args;
25832 // Compare two function templates T1 and T2 by deducing bindings
25833 // from one against the other. If both deductions succeed, compare
25834 // constraints to see which is more constrained.
25835 static int
25836 more_specialized_inst (tree t1, tree t2)
25838 int fate = 0;
25839 int count = 0;
25841 if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
25843 --fate;
25844 ++count;
25847 if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
25849 ++fate;
25850 ++count;
25853 // If both deductions succeed, then one may be more constrained.
25854 if (count == 2 && fate == 0)
25855 fate = more_constrained (t1, t2);
25857 return fate;
25860 /* TEMPLATES is a TREE_LIST. Each TREE_VALUE is a TEMPLATE_DECL.
25861 Return the TREE_LIST node with the most specialized template, if
25862 any. If there is no most specialized template, the error_mark_node
25863 is returned.
25865 Note that this function does not look at, or modify, the
25866 TREE_PURPOSE or TREE_TYPE of any of the nodes. Since the node
25867 returned is one of the elements of INSTANTIATIONS, callers may
25868 store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
25869 and retrieve it from the value returned. */
25871 tree
25872 most_specialized_instantiation (tree templates)
25874 tree fn, champ;
25876 ++processing_template_decl;
25878 champ = templates;
25879 for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
25881 gcc_assert (TREE_VALUE (champ) != TREE_VALUE (fn));
25882 int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
25883 if (fate == -1)
25884 champ = fn;
25885 else if (!fate)
25887 /* Equally specialized, move to next function. If there
25888 is no next function, nothing's most specialized. */
25889 fn = TREE_CHAIN (fn);
25890 champ = fn;
25891 if (!fn)
25892 break;
25896 if (champ)
25897 /* Now verify that champ is better than everything earlier in the
25898 instantiation list. */
25899 for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
25900 if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
25902 champ = NULL_TREE;
25903 break;
25907 processing_template_decl--;
25909 if (!champ)
25910 return error_mark_node;
25912 return champ;
25915 /* If DECL is a specialization of some template, return the most
25916 general such template. Otherwise, returns NULL_TREE.
25918 For example, given:
25920 template <class T> struct S { template <class U> void f(U); };
25922 if TMPL is `template <class U> void S<int>::f(U)' this will return
25923 the full template. This function will not trace past partial
25924 specializations, however. For example, given in addition:
25926 template <class T> struct S<T*> { template <class U> void f(U); };
25928 if TMPL is `template <class U> void S<int*>::f(U)' this will return
25929 `template <class T> template <class U> S<T*>::f(U)'. */
25931 tree
25932 most_general_template (tree decl)
25934 if (TREE_CODE (decl) != TEMPLATE_DECL)
25936 if (tree tinfo = get_template_info (decl))
25937 decl = TI_TEMPLATE (tinfo);
25938 /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
25939 template friend, or a FIELD_DECL for a capture pack. */
25940 if (TREE_CODE (decl) != TEMPLATE_DECL)
25941 return NULL_TREE;
25944 /* Look for more and more general templates. */
25945 while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
25947 /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
25948 (See cp-tree.h for details.) */
25949 if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
25950 break;
25952 if (CLASS_TYPE_P (TREE_TYPE (decl))
25953 && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
25954 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
25955 break;
25957 /* Stop if we run into an explicitly specialized class template. */
25958 if (!DECL_NAMESPACE_SCOPE_P (decl)
25959 && DECL_CONTEXT (decl)
25960 && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
25961 break;
25963 decl = DECL_TI_TEMPLATE (decl);
25966 return decl;
25969 /* Return the most specialized of the template partial specializations
25970 which can produce TARGET, a specialization of some class or variable
25971 template. The value returned is actually a TREE_LIST; the TREE_VALUE is
25972 a TEMPLATE_DECL node corresponding to the partial specialization, while
25973 the TREE_PURPOSE is the set of template arguments that must be
25974 substituted into the template pattern in order to generate TARGET.
25976 If the choice of partial specialization is ambiguous, a diagnostic
25977 is issued, and the error_mark_node is returned. If there are no
25978 partial specializations matching TARGET, then NULL_TREE is
25979 returned, indicating that the primary template should be used. */
25981 tree
25982 most_specialized_partial_spec (tree target, tsubst_flags_t complain)
25984 tree tmpl, args, decl;
25985 if (TYPE_P (target))
25987 tree tinfo = CLASSTYPE_TEMPLATE_INFO (target);
25988 tmpl = TI_TEMPLATE (tinfo);
25989 args = TI_ARGS (tinfo);
25990 decl = TYPE_NAME (target);
25992 else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
25994 tmpl = TREE_OPERAND (target, 0);
25995 args = TREE_OPERAND (target, 1);
25996 decl = DECL_TEMPLATE_RESULT (tmpl);
25998 else if (VAR_P (target))
26000 tree tinfo = DECL_TEMPLATE_INFO (target);
26001 tmpl = TI_TEMPLATE (tinfo);
26002 args = TI_ARGS (tinfo);
26003 decl = target;
26005 else
26006 gcc_unreachable ();
26008 tree main_tmpl = most_general_template (tmpl);
26009 tree specs = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl);
26010 if (!specs)
26011 /* There are no partial specializations of this template. */
26012 return NULL_TREE;
26014 push_access_scope_guard pas (decl);
26015 deferring_access_check_sentinel acs (dk_no_deferred);
26017 /* For determining which partial specialization to use, only the
26018 innermost args are interesting. */
26019 tree outer_args = NULL_TREE;
26020 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
26022 outer_args = strip_innermost_template_args (args, 1);
26023 args = INNERMOST_TEMPLATE_ARGS (args);
26026 /* The caller hasn't called push_to_top_level yet, but we need
26027 get_partial_spec_bindings to be done in non-template context so that we'll
26028 fully resolve everything. */
26029 processing_template_decl_sentinel ptds;
26031 tree list = NULL_TREE;
26032 for (tree t = specs; t; t = TREE_CHAIN (t))
26034 const tree ospec_tmpl = TREE_VALUE (t);
26036 tree spec_tmpl;
26037 if (outer_args)
26039 /* Substitute in the template args from the enclosing class. */
26040 ++processing_template_decl;
26041 spec_tmpl = tsubst (ospec_tmpl, outer_args, tf_none, NULL_TREE);
26042 --processing_template_decl;
26043 if (spec_tmpl == error_mark_node)
26044 return error_mark_node;
26046 else
26047 spec_tmpl = ospec_tmpl;
26049 tree spec_args = get_partial_spec_bindings (tmpl, spec_tmpl, args);
26050 if (spec_args)
26052 if (outer_args)
26053 spec_args = add_to_template_args (outer_args, spec_args);
26055 /* Keep the candidate only if its constraints are satisfied. */
26056 if (constraints_satisfied_p (ospec_tmpl, spec_args))
26058 list = tree_cons (spec_args, ospec_tmpl, list);
26059 TREE_TYPE (list) = TREE_TYPE (t);
26064 if (! list)
26065 return NULL_TREE;
26067 tree champ = list;
26068 bool ambiguous_p = false;
26069 for (tree t = TREE_CHAIN (list); t; t = TREE_CHAIN (t))
26071 int fate = more_specialized_partial_spec (tmpl, champ, t);
26072 if (fate == 1)
26074 else
26076 if (fate == 0)
26078 t = TREE_CHAIN (t);
26079 if (! t)
26081 ambiguous_p = true;
26082 break;
26085 champ = t;
26089 if (!ambiguous_p)
26090 for (tree t = list; t && t != champ; t = TREE_CHAIN (t))
26092 int fate = more_specialized_partial_spec (tmpl, champ, t);
26093 if (fate != 1)
26095 ambiguous_p = true;
26096 break;
26100 if (ambiguous_p)
26102 const char *str;
26103 char *spaces = NULL;
26104 if (!(complain & tf_error))
26105 return error_mark_node;
26106 if (TYPE_P (target))
26107 error ("ambiguous template instantiation for %q#T", target);
26108 else
26109 error ("ambiguous template instantiation for %q#D", target);
26110 str = ngettext ("candidate is:", "candidates are:", list_length (list));
26111 for (tree t = list; t; t = TREE_CHAIN (t))
26113 tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
26114 inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
26115 "%s %#qS", spaces ? spaces : str, subst);
26116 spaces = spaces ? spaces : get_spaces (str);
26118 free (spaces);
26119 return error_mark_node;
26122 return champ;
26125 /* Explicitly instantiate DECL. */
26127 void
26128 do_decl_instantiation (tree decl, tree storage)
26130 tree result = NULL_TREE;
26131 int extern_p = 0;
26133 if (!decl || decl == error_mark_node)
26134 /* An error occurred, for which grokdeclarator has already issued
26135 an appropriate message. */
26136 return;
26137 else if (! DECL_LANG_SPECIFIC (decl))
26139 error ("explicit instantiation of non-template %q#D", decl);
26140 return;
26142 else if (DECL_DECLARED_CONCEPT_P (decl))
26144 if (VAR_P (decl))
26145 error ("explicit instantiation of variable concept %q#D", decl);
26146 else
26147 error ("explicit instantiation of function concept %q#D", decl);
26148 return;
26151 bool var_templ = (DECL_TEMPLATE_INFO (decl)
26152 && variable_template_p (DECL_TI_TEMPLATE (decl)));
26154 if (VAR_P (decl) && !var_templ)
26156 /* There is an asymmetry here in the way VAR_DECLs and
26157 FUNCTION_DECLs are handled by grokdeclarator. In the case of
26158 the latter, the DECL we get back will be marked as a
26159 template instantiation, and the appropriate
26160 DECL_TEMPLATE_INFO will be set up. This does not happen for
26161 VAR_DECLs so we do the lookup here. Probably, grokdeclarator
26162 should handle VAR_DECLs as it currently handles
26163 FUNCTION_DECLs. */
26164 if (!DECL_CLASS_SCOPE_P (decl))
26166 error ("%qD is not a static data member of a class template", decl);
26167 return;
26169 result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
26170 if (!result || !VAR_P (result))
26172 error ("no matching template for %qD found", decl);
26173 return;
26175 if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
26177 error ("type %qT for explicit instantiation %qD does not match "
26178 "declared type %qT", TREE_TYPE (result), decl,
26179 TREE_TYPE (decl));
26180 return;
26183 else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
26185 error ("explicit instantiation of %q#D", decl);
26186 return;
26188 else
26189 result = decl;
26191 /* Check for various error cases. Note that if the explicit
26192 instantiation is valid the RESULT will currently be marked as an
26193 *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
26194 until we get here. */
26196 if (DECL_TEMPLATE_SPECIALIZATION (result))
26198 /* DR 259 [temp.spec].
26200 Both an explicit instantiation and a declaration of an explicit
26201 specialization shall not appear in a program unless the explicit
26202 instantiation follows a declaration of the explicit specialization.
26204 For a given set of template parameters, if an explicit
26205 instantiation of a template appears after a declaration of an
26206 explicit specialization for that template, the explicit
26207 instantiation has no effect. */
26208 return;
26210 else if (DECL_EXPLICIT_INSTANTIATION (result))
26212 /* [temp.spec]
26214 No program shall explicitly instantiate any template more
26215 than once.
26217 We check DECL_NOT_REALLY_EXTERN so as not to complain when
26218 the first instantiation was `extern' and the second is not,
26219 and EXTERN_P for the opposite case. */
26220 if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
26221 permerror (input_location, "duplicate explicit instantiation of %q#D", result);
26222 /* If an "extern" explicit instantiation follows an ordinary
26223 explicit instantiation, the template is instantiated. */
26224 if (extern_p)
26225 return;
26227 else if (!DECL_IMPLICIT_INSTANTIATION (result))
26229 error ("no matching template for %qD found", result);
26230 return;
26232 else if (!DECL_TEMPLATE_INFO (result))
26234 permerror (input_location, "explicit instantiation of non-template %q#D", result);
26235 return;
26238 if (storage == NULL_TREE)
26240 else if (storage == ridpointers[(int) RID_EXTERN])
26242 if (cxx_dialect == cxx98)
26243 pedwarn (input_location, OPT_Wpedantic,
26244 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
26245 "instantiations");
26246 extern_p = 1;
26248 else
26249 error ("storage class %qD applied to template instantiation", storage);
26251 check_explicit_instantiation_namespace (result);
26252 mark_decl_instantiated (result, extern_p);
26253 if (! extern_p)
26254 instantiate_decl (result, /*defer_ok=*/true,
26255 /*expl_inst_class_mem_p=*/false);
26258 static void
26259 mark_class_instantiated (tree t, int extern_p)
26261 SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
26262 SET_CLASSTYPE_INTERFACE_KNOWN (t);
26263 CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
26264 TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
26265 if (! extern_p)
26267 CLASSTYPE_DEBUG_REQUESTED (t) = 1;
26268 rest_of_type_compilation (t, 1);
26272 /* Perform an explicit instantiation of template class T. STORAGE, if
26273 non-null, is the RID for extern, inline or static. COMPLAIN is
26274 nonzero if this is called from the parser, zero if called recursively,
26275 since the standard is unclear (as detailed below). */
26277 void
26278 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
26280 if (!(CLASS_TYPE_P (t) && CLASSTYPE_TEMPLATE_INFO (t)))
26282 if (tree ti = TYPE_TEMPLATE_INFO (t))
26283 error ("explicit instantiation of non-class template %qD",
26284 TI_TEMPLATE (ti));
26285 else
26286 error ("explicit instantiation of non-template type %qT", t);
26287 return;
26290 complete_type (t);
26292 if (!COMPLETE_TYPE_P (t))
26294 if (complain & tf_error)
26295 error ("explicit instantiation of %q#T before definition of template",
26297 return;
26300 /* At most one of these will be true. */
26301 bool extern_p = false;
26302 bool nomem_p = false;
26303 bool static_p = false;
26305 if (storage != NULL_TREE)
26307 if (storage == ridpointers[(int) RID_EXTERN])
26309 if (cxx_dialect == cxx98)
26310 pedwarn (input_location, OPT_Wpedantic,
26311 "ISO C++ 1998 forbids the use of %<extern%> on "
26312 "explicit instantiations");
26314 else
26315 pedwarn (input_location, OPT_Wpedantic,
26316 "ISO C++ forbids the use of %qE"
26317 " on explicit instantiations", storage);
26319 if (storage == ridpointers[(int) RID_INLINE])
26320 nomem_p = true;
26321 else if (storage == ridpointers[(int) RID_EXTERN])
26322 extern_p = true;
26323 else if (storage == ridpointers[(int) RID_STATIC])
26324 static_p = true;
26325 else
26326 error ("storage class %qD applied to template instantiation",
26327 storage);
26330 if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
26331 /* DR 259 [temp.spec].
26333 Both an explicit instantiation and a declaration of an explicit
26334 specialization shall not appear in a program unless the
26335 explicit instantiation follows a declaration of the explicit
26336 specialization.
26338 For a given set of template parameters, if an explicit
26339 instantiation of a template appears after a declaration of an
26340 explicit specialization for that template, the explicit
26341 instantiation has no effect. */
26342 return;
26344 if (CLASSTYPE_EXPLICIT_INSTANTIATION (t) && !CLASSTYPE_INTERFACE_ONLY (t))
26346 /* We've already instantiated the template. */
26348 /* [temp.spec]
26350 No program shall explicitly instantiate any template more
26351 than once.
26353 If EXTERN_P then this is ok. */
26354 if (!extern_p && (complain & tf_error))
26355 permerror (input_location,
26356 "duplicate explicit instantiation of %q#T", t);
26358 return;
26361 check_explicit_instantiation_namespace (TYPE_NAME (t));
26362 mark_class_instantiated (t, extern_p);
26364 if (nomem_p)
26365 return;
26367 /* In contrast to implicit instantiation, where only the
26368 declarations, and not the definitions, of members are
26369 instantiated, we have here:
26371 [temp.explicit]
26373 An explicit instantiation that names a class template
26374 specialization is also an explicit instantiation of the same
26375 kind (declaration or definition) of each of its members (not
26376 including members inherited from base classes and members
26377 that are templates) that has not been previously explicitly
26378 specialized in the translation unit containing the explicit
26379 instantiation, provided that the associated constraints, if
26380 any, of that member are satisfied by the template arguments
26381 of the explicit instantiation. */
26382 for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
26383 if ((VAR_P (fld)
26384 || (TREE_CODE (fld) == FUNCTION_DECL
26385 && !static_p
26386 && user_provided_p (fld)))
26387 && DECL_TEMPLATE_INSTANTIATION (fld)
26388 && constraints_satisfied_p (fld))
26390 mark_decl_instantiated (fld, extern_p);
26391 if (! extern_p)
26392 instantiate_decl (fld, /*defer_ok=*/true,
26393 /*expl_inst_class_mem_p=*/true);
26395 else if (DECL_IMPLICIT_TYPEDEF_P (fld))
26397 tree type = TREE_TYPE (fld);
26399 if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
26400 && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
26401 do_type_instantiation (type, storage, 0);
26405 /* Given a function DECL, which is a specialization of TMPL, modify
26406 DECL to be a re-instantiation of TMPL with the same template
26407 arguments. TMPL should be the template into which tsubst'ing
26408 should occur for DECL, not the most general template.
26410 One reason for doing this is a scenario like this:
26412 template <class T>
26413 void f(const T&, int i);
26415 void g() { f(3, 7); }
26417 template <class T>
26418 void f(const T& t, const int i) { }
26420 Note that when the template is first instantiated, with
26421 instantiate_template, the resulting DECL will have no name for the
26422 first parameter, and the wrong type for the second. So, when we go
26423 to instantiate the DECL, we regenerate it. */
26425 static void
26426 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
26428 /* The arguments used to instantiate DECL, from the most general
26429 template. */
26430 tree code_pattern = DECL_TEMPLATE_RESULT (tmpl);
26432 /* Make sure that we can see identifiers, and compute access correctly. */
26433 push_access_scope (decl);
26435 if (TREE_CODE (decl) == FUNCTION_DECL)
26437 tree specs;
26438 int args_depth;
26439 int parms_depth;
26441 /* Don't bother with this for unique friends that can't be redeclared and
26442 might change type if regenerated (PR69836). */
26443 if (DECL_UNIQUE_FRIEND_P (decl))
26444 goto done;
26446 /* Use the source location of the definition. */
26447 DECL_SOURCE_LOCATION (decl) = DECL_SOURCE_LOCATION (tmpl);
26449 args_depth = TMPL_ARGS_DEPTH (args);
26450 parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
26451 if (args_depth > parms_depth)
26452 args = get_innermost_template_args (args, parms_depth);
26454 /* Instantiate a dynamic exception-specification. noexcept will be
26455 handled below. */
26456 if (tree raises = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (code_pattern)))
26457 if (TREE_VALUE (raises))
26459 specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
26460 args, tf_error, NULL_TREE,
26461 /*defer_ok*/false);
26462 if (specs && specs != error_mark_node)
26463 TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
26464 specs);
26467 /* Merge parameter declarations. */
26468 if (tree pattern_parm
26469 = skip_artificial_parms_for (code_pattern,
26470 DECL_ARGUMENTS (code_pattern)))
26472 tree *p = &DECL_ARGUMENTS (decl);
26473 for (int skip = num_artificial_parms_for (decl); skip; --skip)
26474 p = &DECL_CHAIN (*p);
26475 *p = tsubst_decl (pattern_parm, args, tf_error);
26476 for (tree t = *p; t; t = DECL_CHAIN (t))
26477 DECL_CONTEXT (t) = decl;
26480 if (DECL_CONTRACTS (decl))
26482 /* If we're regenerating a specialization, the contracts will have
26483 been copied from the most general template. Replace those with
26484 the ones from the actual specialization. */
26485 tree tmpl = DECL_TI_TEMPLATE (decl);
26486 if (DECL_TEMPLATE_SPECIALIZATION (tmpl))
26488 remove_contract_attributes (decl);
26489 copy_contract_attributes (decl, code_pattern);
26492 tsubst_contract_attributes (decl, args, tf_warning_or_error, code_pattern);
26495 /* Merge additional specifiers from the CODE_PATTERN. */
26496 if (DECL_DECLARED_INLINE_P (code_pattern)
26497 && !DECL_DECLARED_INLINE_P (decl))
26498 DECL_DECLARED_INLINE_P (decl) = 1;
26500 maybe_instantiate_noexcept (decl, tf_error);
26502 else if (VAR_P (decl))
26504 start_lambda_scope (decl);
26505 DECL_INITIAL (decl) =
26506 tsubst_init (DECL_INITIAL (code_pattern), decl, args,
26507 tf_error, DECL_TI_TEMPLATE (decl));
26508 finish_lambda_scope ();
26509 if (VAR_HAD_UNKNOWN_BOUND (decl))
26510 TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
26511 tf_error, DECL_TI_TEMPLATE (decl));
26513 else
26514 gcc_unreachable ();
26516 done:
26517 pop_access_scope (decl);
26520 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
26521 substituted to get DECL. */
26523 tree
26524 template_for_substitution (tree decl)
26526 tree tmpl = DECL_TI_TEMPLATE (decl);
26528 /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
26529 for the instantiation. This is not always the most general
26530 template. Consider, for example:
26532 template <class T>
26533 struct S { template <class U> void f();
26534 template <> void f<int>(); };
26536 and an instantiation of S<double>::f<int>. We want TD to be the
26537 specialization S<T>::f<int>, not the more general S<T>::f<U>. */
26538 while (/* An instantiation cannot have a definition, so we need a
26539 more general template. */
26540 DECL_TEMPLATE_INSTANTIATION (tmpl)
26541 /* We must also deal with friend templates. Given:
26543 template <class T> struct S {
26544 template <class U> friend void f() {};
26547 S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
26548 so far as the language is concerned, but that's still
26549 where we get the pattern for the instantiation from. On
26550 other hand, if the definition comes outside the class, say:
26552 template <class T> struct S {
26553 template <class U> friend void f();
26555 template <class U> friend void f() {}
26557 we don't need to look any further. That's what the check for
26558 DECL_INITIAL is for. */
26559 || (TREE_CODE (decl) == FUNCTION_DECL
26560 && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
26561 && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
26563 /* The present template, TD, should not be a definition. If it
26564 were a definition, we should be using it! Note that we
26565 cannot restructure the loop to just keep going until we find
26566 a template with a definition, since that might go too far if
26567 a specialization was declared, but not defined. */
26569 /* Fetch the more general template. */
26570 tmpl = DECL_TI_TEMPLATE (tmpl);
26573 return tmpl;
26576 /* Returns true if we need to instantiate this template instance even if we
26577 know we aren't going to emit it. */
26579 bool
26580 always_instantiate_p (tree decl)
26582 /* We always instantiate inline functions so that we can inline them. An
26583 explicit instantiation declaration prohibits implicit instantiation of
26584 non-inline functions. With high levels of optimization, we would
26585 normally inline non-inline functions -- but we're not allowed to do
26586 that for "extern template" functions. Therefore, we check
26587 DECL_DECLARED_INLINE_P, rather than possibly_inlined_p. */
26588 return ((TREE_CODE (decl) == FUNCTION_DECL
26589 && (DECL_DECLARED_INLINE_P (decl)
26590 || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
26591 /* And we need to instantiate static data members so that
26592 their initializers are available in integral constant
26593 expressions. */
26594 || (VAR_P (decl)
26595 && decl_maybe_constant_var_p (decl)));
26598 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
26599 instantiate it now, modifying TREE_TYPE (fn). Returns false on
26600 error, true otherwise. */
26602 bool
26603 maybe_instantiate_noexcept (tree fn, tsubst_flags_t complain)
26605 if (fn == error_mark_node)
26606 return false;
26608 /* Don't instantiate a noexcept-specification from template context. */
26609 if (processing_template_decl
26610 && (!flag_noexcept_type || type_dependent_expression_p (fn)))
26611 return true;
26613 tree fntype = TREE_TYPE (fn);
26614 tree spec = TYPE_RAISES_EXCEPTIONS (fntype);
26616 if ((!spec || UNEVALUATED_NOEXCEPT_SPEC_P (spec))
26617 && DECL_MAYBE_DELETED (fn))
26619 if (fn == current_function_decl)
26620 /* We're in start_preparsed_function, keep going. */
26621 return true;
26623 ++function_depth;
26624 maybe_synthesize_method (fn);
26625 --function_depth;
26626 return !DECL_DELETED_FN (fn);
26629 if (!spec || !TREE_PURPOSE (spec))
26630 return true;
26632 tree noex = TREE_PURPOSE (spec);
26633 if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
26634 && TREE_CODE (noex) != DEFERRED_PARSE)
26635 return true;
26637 tree orig_fn = NULL_TREE;
26638 /* For a member friend template we can get a TEMPLATE_DECL. Let's use
26639 its FUNCTION_DECL for the rest of this function -- push_access_scope
26640 doesn't accept TEMPLATE_DECLs. */
26641 if (DECL_FUNCTION_TEMPLATE_P (fn))
26643 orig_fn = fn;
26644 fn = DECL_TEMPLATE_RESULT (fn);
26647 if (DECL_CLONED_FUNCTION_P (fn))
26649 tree prime = DECL_CLONED_FUNCTION (fn);
26650 if (!maybe_instantiate_noexcept (prime, complain))
26651 return false;
26652 spec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (prime));
26654 else if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
26656 static hash_set<tree>* fns = new hash_set<tree>;
26657 bool added = false;
26658 if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
26660 spec = get_defaulted_eh_spec (fn, complain);
26661 if (spec == error_mark_node)
26662 /* This might have failed because of an unparsed DMI, so
26663 let's try again later. */
26664 return false;
26666 else if (!(added = !fns->add (fn)))
26668 /* If hash_set::add returns true, the element was already there. */
26669 location_t loc = cp_expr_loc_or_loc (DEFERRED_NOEXCEPT_PATTERN (noex),
26670 DECL_SOURCE_LOCATION (fn));
26671 error_at (loc,
26672 "exception specification of %qD depends on itself",
26673 fn);
26674 spec = noexcept_false_spec;
26676 else if (push_tinst_level (fn))
26678 push_to_top_level ();
26679 push_access_scope (fn);
26680 push_deferring_access_checks (dk_no_deferred);
26681 input_location = DECL_SOURCE_LOCATION (fn);
26683 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
26684 && !DECL_LOCAL_DECL_P (fn))
26686 /* If needed, set current_class_ptr for the benefit of
26687 tsubst_copy/PARM_DECL. */
26688 tree this_parm = DECL_ARGUMENTS (fn);
26689 current_class_ptr = NULL_TREE;
26690 current_class_ref = cp_build_fold_indirect_ref (this_parm);
26691 current_class_ptr = this_parm;
26694 /* If this function is represented by a TEMPLATE_DECL, then
26695 the deferred noexcept-specification might still contain
26696 dependent types, even after substitution. And we need the
26697 dependency check functions to work in build_noexcept_spec. */
26698 if (orig_fn)
26699 ++processing_template_decl;
26701 /* Do deferred instantiation of the noexcept-specifier. */
26702 noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
26703 DEFERRED_NOEXCEPT_ARGS (noex),
26704 tf_warning_or_error, fn);
26706 /* Build up the noexcept-specification. */
26707 spec = build_noexcept_spec (noex, tf_warning_or_error);
26709 if (orig_fn)
26710 --processing_template_decl;
26712 pop_deferring_access_checks ();
26713 pop_access_scope (fn);
26714 pop_tinst_level ();
26715 pop_from_top_level ();
26717 else
26718 spec = noexcept_false_spec;
26720 if (added)
26721 fns->remove (fn);
26724 if (spec == error_mark_node)
26726 /* This failed with a hard error, so let's go with false. */
26727 gcc_assert (seen_error ());
26728 spec = noexcept_false_spec;
26731 TREE_TYPE (fn) = build_exception_variant (fntype, spec);
26732 if (orig_fn)
26733 TREE_TYPE (orig_fn) = TREE_TYPE (fn);
26735 return true;
26738 /* We're starting to process the function INST, an instantiation of PATTERN;
26739 add their parameters to local_specializations. */
26741 void
26742 register_parameter_specializations (tree pattern, tree inst)
26744 tree tmpl_parm = DECL_ARGUMENTS (pattern);
26745 tree spec_parm = DECL_ARGUMENTS (inst);
26746 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (inst))
26748 register_local_specialization (spec_parm, tmpl_parm);
26749 spec_parm = skip_artificial_parms_for (inst, spec_parm);
26750 tmpl_parm = skip_artificial_parms_for (pattern, tmpl_parm);
26752 for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
26754 if (!DECL_PACK_P (tmpl_parm))
26756 register_local_specialization (spec_parm, tmpl_parm);
26757 spec_parm = DECL_CHAIN (spec_parm);
26759 else
26761 /* Register the (value) argument pack as a specialization of
26762 TMPL_PARM, then move on. */
26763 tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
26764 register_local_specialization (argpack, tmpl_parm);
26767 gcc_assert (!spec_parm);
26770 /* Instantiate the body of D using PATTERN with ARGS. We have
26771 already determined PATTERN is the correct template to use.
26772 NESTED_P is true if this is a nested function, in which case
26773 PATTERN will be a FUNCTION_DECL not a TEMPLATE_DECL. */
26775 static void
26776 instantiate_body (tree pattern, tree args, tree d, bool nested_p)
26778 tree td = NULL_TREE;
26779 tree code_pattern = pattern;
26781 if (!nested_p)
26783 td = pattern;
26784 code_pattern = DECL_TEMPLATE_RESULT (td);
26786 else
26787 /* Only OMP reductions are nested. */
26788 gcc_checking_assert (DECL_OMP_DECLARE_REDUCTION_P (code_pattern));
26790 vec<tree> omp_privatization_save;
26791 if (current_function_decl)
26792 save_omp_privatization_clauses (omp_privatization_save);
26794 bool push_to_top = maybe_push_to_top_level (d);
26796 mark_template_arguments_used (pattern, args);
26798 if (VAR_P (d))
26800 /* The variable might be a lambda's extra scope, and that
26801 lambda's visibility depends on D's. */
26802 maybe_commonize_var (d);
26803 determine_visibility (d);
26806 /* Mark D as instantiated so that recursive calls to
26807 instantiate_decl do not try to instantiate it again. */
26808 DECL_TEMPLATE_INSTANTIATED (d) = 1;
26810 if (td)
26811 /* Regenerate the declaration in case the template has been modified
26812 by a subsequent redeclaration. */
26813 regenerate_decl_from_template (d, td, args);
26815 /* We already set the file and line above. Reset them now in case
26816 they changed as a result of calling regenerate_decl_from_template. */
26817 input_location = DECL_SOURCE_LOCATION (d);
26819 if (VAR_P (d))
26821 /* Clear out DECL_RTL; whatever was there before may not be right
26822 since we've reset the type of the declaration. */
26823 SET_DECL_RTL (d, NULL);
26824 DECL_IN_AGGR_P (d) = 0;
26826 /* The initializer is placed in DECL_INITIAL by
26827 regenerate_decl_from_template so we don't need to
26828 push/pop_access_scope again here. Pull it out so that
26829 cp_finish_decl can process it. */
26830 bool const_init = false;
26831 tree init = DECL_INITIAL (d);
26832 DECL_INITIAL (d) = NULL_TREE;
26833 DECL_INITIALIZED_P (d) = 0;
26835 /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
26836 initializer. That function will defer actual emission until
26837 we have a chance to determine linkage. */
26838 DECL_EXTERNAL (d) = 0;
26840 /* Enter the scope of D so that access-checking works correctly. */
26841 bool enter_context = DECL_CLASS_SCOPE_P (d);
26842 if (enter_context)
26843 push_nested_class (DECL_CONTEXT (d));
26845 const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
26846 cp_finish_decl (d, init, const_init, NULL_TREE, 0);
26848 if (enter_context)
26849 pop_nested_class ();
26851 else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
26852 synthesize_method (d);
26853 else if (TREE_CODE (d) == FUNCTION_DECL)
26855 /* Set up the list of local specializations. */
26856 local_specialization_stack lss (push_to_top ? lss_blank : lss_copy);
26857 tree block = NULL_TREE;
26859 /* Set up context. */
26860 if (nested_p)
26861 block = push_stmt_list ();
26862 else
26864 start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
26866 perform_instantiation_time_access_checks (code_pattern, args);
26869 /* Create substitution entries for the parameters. */
26870 register_parameter_specializations (code_pattern, d);
26872 /* Substitute into the body of the function. */
26873 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
26874 tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
26875 tf_warning_or_error, d);
26876 else
26878 tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
26879 tf_warning_or_error, DECL_TI_TEMPLATE (d));
26881 /* Set the current input_location to the end of the function
26882 so that finish_function knows where we are. */
26883 input_location
26884 = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
26886 /* Remember if we saw an infinite loop in the template. */
26887 current_function_infinite_loop
26888 = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
26891 /* Finish the function. */
26892 if (nested_p)
26893 DECL_SAVED_TREE (d) = pop_stmt_list (block);
26894 else
26896 d = finish_function (/*inline_p=*/false);
26897 expand_or_defer_fn (d);
26900 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
26901 cp_check_omp_declare_reduction (d);
26904 /* We're not deferring instantiation any more. */
26905 if (!nested_p)
26906 TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
26908 maybe_pop_from_top_level (push_to_top);
26910 if (current_function_decl)
26911 restore_omp_privatization_clauses (omp_privatization_save);
26914 /* Produce the definition of D, a _DECL generated from a template. If
26915 DEFER_OK is true, then we don't have to actually do the
26916 instantiation now; we just have to do it sometime. Normally it is
26917 an error if this is an explicit instantiation but D is undefined.
26918 EXPL_INST_CLASS_MEM_P is true iff D is a member of an explicitly
26919 instantiated class template. */
26921 tree
26922 instantiate_decl (tree d, bool defer_ok, bool expl_inst_class_mem_p)
26924 tree tmpl = DECL_TI_TEMPLATE (d);
26925 tree gen_args;
26926 tree args;
26927 tree td;
26928 tree code_pattern;
26929 tree spec;
26930 tree gen_tmpl;
26931 bool pattern_defined;
26932 location_t saved_loc = input_location;
26933 int saved_unevaluated_operand = cp_unevaluated_operand;
26934 int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
26935 bool external_p;
26936 bool deleted_p;
26938 /* This function should only be used to instantiate templates for
26939 functions and static member variables. */
26940 gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
26942 /* A concept is never instantiated. */
26943 gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
26945 gcc_checking_assert (!DECL_FUNCTION_SCOPE_P (d));
26947 if (modules_p ())
26948 /* We may have a pending instantiation of D itself. */
26949 lazy_load_pendings (d);
26951 /* Variables are never deferred; if instantiation is required, they
26952 are instantiated right away. That allows for better code in the
26953 case that an expression refers to the value of the variable --
26954 if the variable has a constant value the referring expression can
26955 take advantage of that fact. */
26956 if (VAR_P (d))
26957 defer_ok = false;
26959 /* Don't instantiate cloned functions. Instead, instantiate the
26960 functions they cloned. */
26961 if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
26962 d = DECL_CLONED_FUNCTION (d);
26964 if (DECL_TEMPLATE_INSTANTIATED (d)
26965 || TREE_TYPE (d) == error_mark_node
26966 || (TREE_CODE (d) == FUNCTION_DECL
26967 && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
26968 || DECL_TEMPLATE_SPECIALIZATION (d))
26969 /* D has already been instantiated or explicitly specialized, so
26970 there's nothing for us to do here.
26972 It might seem reasonable to check whether or not D is an explicit
26973 instantiation, and, if so, stop here. But when an explicit
26974 instantiation is deferred until the end of the compilation,
26975 DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
26976 the instantiation. */
26977 return d;
26979 /* Check to see whether we know that this template will be
26980 instantiated in some other file, as with "extern template"
26981 extension. */
26982 external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
26984 /* In general, we do not instantiate such templates. */
26985 if (external_p && !always_instantiate_p (d))
26986 return d;
26988 gen_tmpl = most_general_template (tmpl);
26989 gen_args = DECL_TI_ARGS (d);
26991 /* We should already have the extra args. */
26992 gcc_checking_assert (tmpl == gen_tmpl
26993 || (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
26994 == TMPL_ARGS_DEPTH (gen_args)));
26995 /* And what's in the hash table should match D. */
26996 gcc_checking_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0))
26997 == d
26998 || spec == NULL_TREE);
27000 /* This needs to happen before any tsubsting. */
27001 if (! push_tinst_level (d))
27002 return d;
27004 auto_timevar tv (TV_TEMPLATE_INST);
27006 /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
27007 for the instantiation. */
27008 td = template_for_substitution (d);
27009 args = gen_args;
27011 if (variable_template_specialization_p (d))
27013 /* Look up an explicit specialization, if any. */
27014 tree elt = most_specialized_partial_spec (d, tf_warning_or_error);
27015 if (elt && elt != error_mark_node)
27017 td = TREE_VALUE (elt);
27018 args = TREE_PURPOSE (elt);
27022 code_pattern = DECL_TEMPLATE_RESULT (td);
27024 /* We should never be trying to instantiate a member of a class
27025 template or partial specialization. */
27026 gcc_assert (d != code_pattern);
27028 if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
27029 || DECL_TEMPLATE_SPECIALIZATION (td))
27030 /* In the case of a friend template whose definition is provided
27031 outside the class, we may have too many arguments. Drop the
27032 ones we don't need. The same is true for specializations. */
27033 args = get_innermost_template_args
27034 (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
27036 if (TREE_CODE (d) == FUNCTION_DECL)
27038 deleted_p = DECL_DELETED_FN (code_pattern);
27039 pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
27040 && DECL_INITIAL (code_pattern) != error_mark_node)
27041 || DECL_DEFAULTED_FN (code_pattern)
27042 || deleted_p);
27044 else
27046 deleted_p = false;
27047 if (DECL_CLASS_SCOPE_P (code_pattern))
27048 pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
27049 else
27050 pattern_defined = ! DECL_EXTERNAL (code_pattern);
27053 /* We may be in the middle of deferred access check. Disable it now. */
27054 push_deferring_access_checks (dk_no_deferred);
27056 /* Unless an explicit instantiation directive has already determined
27057 the linkage of D, remember that a definition is available for
27058 this entity. */
27059 if (pattern_defined
27060 && !DECL_INTERFACE_KNOWN (d)
27061 && !DECL_NOT_REALLY_EXTERN (d))
27062 mark_definable (d);
27064 DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
27065 DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
27066 input_location = DECL_SOURCE_LOCATION (d);
27068 /* If D is a member of an explicitly instantiated class template,
27069 and no definition is available, treat it like an implicit
27070 instantiation. */
27071 if (!pattern_defined && expl_inst_class_mem_p
27072 && DECL_EXPLICIT_INSTANTIATION (d))
27074 /* Leave linkage flags alone on instantiations with anonymous
27075 visibility. */
27076 if (TREE_PUBLIC (d))
27078 DECL_NOT_REALLY_EXTERN (d) = 0;
27079 DECL_INTERFACE_KNOWN (d) = 0;
27081 SET_DECL_IMPLICIT_INSTANTIATION (d);
27084 /* Defer all other templates, unless we have been explicitly
27085 forbidden from doing so. */
27086 if (/* If there is no definition, we cannot instantiate the
27087 template. */
27088 ! pattern_defined
27089 /* If it's OK to postpone instantiation, do so. */
27090 || defer_ok
27091 /* If this is a static data member that will be defined
27092 elsewhere, we don't want to instantiate the entire data
27093 member, but we do want to instantiate the initializer so that
27094 we can substitute that elsewhere. */
27095 || (external_p && VAR_P (d))
27096 /* Handle here a deleted function too, avoid generating
27097 its body (c++/61080). */
27098 || deleted_p)
27100 /* The definition of the static data member is now required so
27101 we must substitute the initializer. */
27102 if (VAR_P (d)
27103 && !DECL_INITIAL (d)
27104 && DECL_INITIAL (code_pattern))
27106 tree ns;
27107 tree init;
27108 bool const_init = false;
27109 bool enter_context = DECL_CLASS_SCOPE_P (d);
27111 ns = decl_namespace_context (d);
27112 push_nested_namespace (ns);
27113 if (enter_context)
27114 push_nested_class (DECL_CONTEXT (d));
27115 init = tsubst_expr (DECL_INITIAL (code_pattern),
27116 args,
27117 tf_warning_or_error, NULL_TREE);
27118 /* If instantiating the initializer involved instantiating this
27119 again, don't call cp_finish_decl twice. */
27120 if (!DECL_INITIAL (d))
27122 /* Make sure the initializer is still constant, in case of
27123 circular dependency (template/instantiate6.C). */
27124 const_init
27125 = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
27126 cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
27127 /*asmspec_tree=*/NULL_TREE, 0);
27129 if (enter_context)
27130 pop_nested_class ();
27131 pop_nested_namespace (ns);
27134 /* We restore the source position here because it's used by
27135 add_pending_template. */
27136 input_location = saved_loc;
27138 if (at_eof && !pattern_defined
27139 && DECL_EXPLICIT_INSTANTIATION (d)
27140 && DECL_NOT_REALLY_EXTERN (d))
27141 /* [temp.explicit]
27143 The definition of a non-exported function template, a
27144 non-exported member function template, or a non-exported
27145 member function or static data member of a class template
27146 shall be present in every translation unit in which it is
27147 explicitly instantiated. */
27148 permerror (input_location, "explicit instantiation of %qD "
27149 "but no definition available", d);
27151 /* If we're in unevaluated context, we just wanted to get the
27152 constant value; this isn't an odr use, so don't queue
27153 a full instantiation. */
27154 if (!cp_unevaluated_operand
27155 /* ??? Historically, we have instantiated inline functions, even
27156 when marked as "extern template". */
27157 && !(external_p && VAR_P (d)))
27158 add_pending_template (d);
27160 else
27162 set_instantiating_module (d);
27163 if (variable_template_p (gen_tmpl))
27164 note_variable_template_instantiation (d);
27165 instantiate_body (td, args, d, false);
27168 pop_deferring_access_checks ();
27169 pop_tinst_level ();
27170 input_location = saved_loc;
27171 cp_unevaluated_operand = saved_unevaluated_operand;
27172 c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
27174 return d;
27177 /* Run through the list of templates that we wish we could
27178 instantiate, and instantiate any we can. RETRIES is the
27179 number of times we retry pending template instantiation. */
27181 void
27182 instantiate_pending_templates (int retries)
27184 int reconsider;
27185 location_t saved_loc = input_location;
27187 /* Instantiating templates may trigger vtable generation. This in turn
27188 may require further template instantiations. We place a limit here
27189 to avoid infinite loop. */
27190 if (pending_templates && retries >= max_tinst_depth)
27192 tree decl = pending_templates->tinst->maybe_get_node ();
27194 fatal_error (input_location,
27195 "template instantiation depth exceeds maximum of %d"
27196 " instantiating %q+D, possibly from virtual table generation"
27197 " (use %<-ftemplate-depth=%> to increase the maximum)",
27198 max_tinst_depth, decl);
27199 if (TREE_CODE (decl) == FUNCTION_DECL)
27200 /* Pretend that we defined it. */
27201 DECL_INITIAL (decl) = error_mark_node;
27202 return;
27207 struct pending_template **t = &pending_templates;
27208 struct pending_template *last = NULL;
27209 reconsider = 0;
27210 while (*t)
27212 tree instantiation = reopen_tinst_level ((*t)->tinst);
27213 bool complete = false;
27215 if (TYPE_P (instantiation))
27217 if (!COMPLETE_TYPE_P (instantiation))
27219 instantiate_class_template (instantiation);
27220 if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
27221 for (tree fld = TYPE_FIELDS (instantiation);
27222 fld; fld = TREE_CHAIN (fld))
27223 if ((VAR_P (fld)
27224 || (TREE_CODE (fld) == FUNCTION_DECL
27225 && !DECL_ARTIFICIAL (fld)))
27226 && DECL_TEMPLATE_INSTANTIATION (fld))
27227 instantiate_decl (fld,
27228 /*defer_ok=*/false,
27229 /*expl_inst_class_mem_p=*/false);
27231 if (COMPLETE_TYPE_P (instantiation))
27232 reconsider = 1;
27235 complete = COMPLETE_TYPE_P (instantiation);
27237 else
27239 if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
27240 && !DECL_TEMPLATE_INSTANTIATED (instantiation))
27242 instantiation
27243 = instantiate_decl (instantiation,
27244 /*defer_ok=*/false,
27245 /*expl_inst_class_mem_p=*/false);
27246 if (DECL_TEMPLATE_INSTANTIATED (instantiation))
27247 reconsider = 1;
27250 complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
27251 || DECL_TEMPLATE_INSTANTIATED (instantiation));
27254 if (complete)
27256 /* If INSTANTIATION has been instantiated, then we don't
27257 need to consider it again in the future. */
27258 struct pending_template *drop = *t;
27259 *t = (*t)->next;
27260 set_refcount_ptr (drop->tinst);
27261 pending_template_freelist ().free (drop);
27263 else
27265 last = *t;
27266 t = &(*t)->next;
27268 tinst_depth = 0;
27269 set_refcount_ptr (current_tinst_level);
27271 last_pending_template = last;
27273 while (reconsider);
27275 input_location = saved_loc;
27278 /* Substitute ARGVEC into T, which is a list of initializers for
27279 either base class or a non-static data member. The TREE_PURPOSEs
27280 are DECLs, and the TREE_VALUEs are the initializer values. Used by
27281 instantiate_decl. */
27283 static tree
27284 tsubst_initializer_list (tree t, tree argvec)
27286 tree inits = NULL_TREE;
27287 tree target_ctor = error_mark_node;
27289 for (; t; t = TREE_CHAIN (t))
27291 tree decl;
27292 tree init;
27293 tree expanded_bases = NULL_TREE;
27294 tree expanded_arguments = NULL_TREE;
27295 int i, len = 1;
27297 if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
27299 tree expr;
27300 tree arg;
27302 /* Expand the base class expansion type into separate base
27303 classes. */
27304 expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
27305 tf_warning_or_error,
27306 NULL_TREE);
27307 if (expanded_bases == error_mark_node)
27308 continue;
27310 /* We'll be building separate TREE_LISTs of arguments for
27311 each base. */
27312 len = TREE_VEC_LENGTH (expanded_bases);
27313 expanded_arguments = make_tree_vec (len);
27314 for (i = 0; i < len; i++)
27315 TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
27317 /* Build a dummy EXPR_PACK_EXPANSION that will be used to
27318 expand each argument in the TREE_VALUE of t. */
27319 expr = make_node (EXPR_PACK_EXPANSION);
27320 PACK_EXPANSION_LOCAL_P (expr) = true;
27321 PACK_EXPANSION_PARAMETER_PACKS (expr) =
27322 PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
27324 if (TREE_VALUE (t) == void_type_node)
27325 /* VOID_TYPE_NODE is used to indicate
27326 value-initialization. */
27328 for (i = 0; i < len; i++)
27329 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
27331 else
27333 /* Substitute parameter packs into each argument in the
27334 TREE_LIST. */
27335 in_base_initializer = 1;
27336 for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
27338 tree expanded_exprs;
27340 /* Expand the argument. */
27341 tree value;
27342 if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
27343 value = TREE_VALUE (arg);
27344 else
27346 value = expr;
27347 PACK_EXPANSION_PATTERN (value) = TREE_VALUE (arg);
27349 expanded_exprs
27350 = tsubst_pack_expansion (value, argvec,
27351 tf_warning_or_error,
27352 NULL_TREE);
27353 if (expanded_exprs == error_mark_node)
27354 continue;
27356 /* Prepend each of the expanded expressions to the
27357 corresponding TREE_LIST in EXPANDED_ARGUMENTS. */
27358 for (i = 0; i < len; i++)
27359 if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
27360 for (int j = 0; j < TREE_VEC_LENGTH (expanded_exprs); j++)
27361 TREE_VEC_ELT (expanded_arguments, i)
27362 = tree_cons (NULL_TREE,
27363 TREE_VEC_ELT (expanded_exprs, j),
27364 TREE_VEC_ELT (expanded_arguments, i));
27365 else
27366 TREE_VEC_ELT (expanded_arguments, i)
27367 = tree_cons (NULL_TREE,
27368 TREE_VEC_ELT (expanded_exprs, i),
27369 TREE_VEC_ELT (expanded_arguments, i));
27371 in_base_initializer = 0;
27373 /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
27374 since we built them backwards. */
27375 for (i = 0; i < len; i++)
27377 TREE_VEC_ELT (expanded_arguments, i) =
27378 nreverse (TREE_VEC_ELT (expanded_arguments, i));
27383 for (i = 0; i < len; ++i)
27385 if (expanded_bases)
27387 decl = TREE_VEC_ELT (expanded_bases, i);
27388 decl = expand_member_init (decl);
27389 init = TREE_VEC_ELT (expanded_arguments, i);
27391 else
27393 tree tmp;
27394 decl = tsubst_copy (TREE_PURPOSE (t), argvec,
27395 tf_warning_or_error, NULL_TREE);
27397 decl = expand_member_init (decl);
27398 if (decl && !DECL_P (decl))
27399 in_base_initializer = 1;
27401 init = TREE_VALUE (t);
27402 tmp = init;
27403 if (init != void_type_node)
27404 init = tsubst_expr (init, argvec,
27405 tf_warning_or_error, NULL_TREE);
27406 if (init == NULL_TREE && tmp != NULL_TREE)
27407 /* If we had an initializer but it instantiated to nothing,
27408 value-initialize the object. This will only occur when
27409 the initializer was a pack expansion where the parameter
27410 packs used in that expansion were of length zero. */
27411 init = void_type_node;
27412 in_base_initializer = 0;
27415 if (target_ctor != error_mark_node
27416 && init != error_mark_node)
27418 error ("mem-initializer for %qD follows constructor delegation",
27419 decl);
27420 return inits;
27422 /* Look for a target constructor. */
27423 if (init != error_mark_node
27424 && decl && CLASS_TYPE_P (decl)
27425 && same_type_p (decl, current_class_type))
27427 maybe_warn_cpp0x (CPP0X_DELEGATING_CTORS);
27428 if (inits)
27430 error ("constructor delegation follows mem-initializer for %qD",
27431 TREE_PURPOSE (inits));
27432 continue;
27434 target_ctor = init;
27437 if (decl)
27439 init = build_tree_list (decl, init);
27440 /* Carry over the dummy TREE_TYPE node containing the source
27441 location. */
27442 TREE_TYPE (init) = TREE_TYPE (t);
27443 TREE_CHAIN (init) = inits;
27444 inits = init;
27448 return inits;
27451 /* Instantiate an enumerated type. TAG is the template type, NEWTAG
27452 is the instantiation (which should have been created with
27453 start_enum) and ARGS are the template arguments to use. */
27455 static void
27456 tsubst_enum (tree tag, tree newtag, tree args)
27458 tree e;
27460 if (SCOPED_ENUM_P (newtag))
27461 begin_scope (sk_scoped_enum, newtag);
27463 for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
27465 tree value;
27466 tree decl = TREE_VALUE (e);
27468 /* Note that in a template enum, the TREE_VALUE is the
27469 CONST_DECL, not the corresponding INTEGER_CST. */
27470 value = tsubst_expr (DECL_INITIAL (decl),
27471 args, tf_warning_or_error, NULL_TREE);
27473 /* Give this enumeration constant the correct access. */
27474 set_current_access_from_decl (decl);
27476 /* Actually build the enumerator itself. Here we're assuming that
27477 enumerators can't have dependent attributes. */
27478 tree newdecl = build_enumerator (DECL_NAME (decl), value, newtag,
27479 DECL_ATTRIBUTES (decl),
27480 DECL_SOURCE_LOCATION (decl));
27481 /* Attribute deprecated without an argument isn't sticky: it'll
27482 melt into a tree flag, so we need to propagate the flag here,
27483 since we just created a new enumerator. */
27484 TREE_DEPRECATED (newdecl) = TREE_DEPRECATED (decl);
27485 TREE_UNAVAILABLE (newdecl) = TREE_UNAVAILABLE (decl);
27488 if (SCOPED_ENUM_P (newtag))
27489 finish_scope ();
27491 finish_enum_value_list (newtag);
27492 finish_enum (newtag);
27494 DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
27495 = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
27496 TREE_DEPRECATED (newtag) = TREE_DEPRECATED (tag);
27497 TREE_UNAVAILABLE (newtag) = TREE_UNAVAILABLE (tag);
27500 /* DECL is a FUNCTION_DECL that is a template specialization. Return
27501 its type -- but without substituting the innermost set of template
27502 arguments. So, innermost set of template parameters will appear in
27503 the type. */
27505 tree
27506 get_mostly_instantiated_function_type (tree decl)
27508 /* For a function, DECL_TI_TEMPLATE is partially instantiated. */
27509 return TREE_TYPE (DECL_TI_TEMPLATE (decl));
27512 /* Return truthvalue if we're processing a template different from
27513 the last one involved in diagnostics. */
27514 bool
27515 problematic_instantiation_changed (void)
27517 return current_tinst_level != last_error_tinst_level;
27520 /* Remember current template involved in diagnostics. */
27521 void
27522 record_last_problematic_instantiation (void)
27524 set_refcount_ptr (last_error_tinst_level, current_tinst_level);
27527 struct tinst_level *
27528 current_instantiation (void)
27530 return current_tinst_level;
27533 /* Return TRUE if current_function_decl is being instantiated, false
27534 otherwise. */
27536 bool
27537 instantiating_current_function_p (void)
27539 return (current_instantiation ()
27540 && (current_instantiation ()->maybe_get_node ()
27541 == current_function_decl));
27544 /* [temp.param] Check that template non-type parm TYPE is of an allowable
27545 type. Return false for ok, true for disallowed. Issue error and
27546 inform messages under control of COMPLAIN. */
27548 static bool
27549 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
27551 if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
27552 return false;
27553 else if (TYPE_PTR_P (type))
27554 return false;
27555 else if (TYPE_REF_P (type)
27556 && !TYPE_REF_IS_RVALUE (type))
27557 return false;
27558 else if (TYPE_PTRMEM_P (type))
27559 return false;
27560 else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
27562 if (CLASS_PLACEHOLDER_TEMPLATE (type) && cxx_dialect < cxx20)
27564 if (complain & tf_error)
27565 error ("non-type template parameters of deduced class type only "
27566 "available with %<-std=c++20%> or %<-std=gnu++20%>");
27567 return true;
27569 return false;
27571 else if (TREE_CODE (type) == NULLPTR_TYPE)
27572 return false;
27573 else if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM
27574 && cxx_dialect < cxx11)
27575 /* Fall through; before C++11 alias templates, a bound ttp
27576 always instantiates into a class type. */;
27577 else if (WILDCARD_TYPE_P (type))
27578 /* Any other wildcard type not already handled above is allowed. */
27579 return false;
27580 else if (TREE_CODE (type) == COMPLEX_TYPE)
27581 /* Fall through. */;
27582 else if (VOID_TYPE_P (type))
27583 /* Fall through. */;
27584 else if (cxx_dialect >= cxx20)
27586 if (dependent_type_p (type))
27587 return false;
27588 if (!complete_type_or_maybe_complain (type, NULL_TREE, complain))
27589 return true;
27590 if (structural_type_p (type))
27591 return false;
27592 if (complain & tf_error)
27594 auto_diagnostic_group d;
27595 error ("%qT is not a valid type for a template non-type "
27596 "parameter because it is not structural", type);
27597 structural_type_p (type, true);
27599 return true;
27601 else if (CLASS_TYPE_P (type))
27603 if (complain & tf_error)
27604 error ("non-type template parameters of class type only available "
27605 "with %<-std=c++20%> or %<-std=gnu++20%>");
27606 return true;
27609 if (complain & tf_error)
27611 if (type == error_mark_node)
27612 inform (input_location, "invalid template non-type parameter");
27613 else
27614 error ("%q#T is not a valid type for a template non-type parameter",
27615 type);
27617 return true;
27620 /* Returns true iff the noexcept-specifier for TYPE is value-dependent. */
27622 static bool
27623 value_dependent_noexcept_spec_p (tree type)
27625 if (tree spec = TYPE_RAISES_EXCEPTIONS (type))
27626 if (tree noex = TREE_PURPOSE (spec))
27627 /* Treat DEFERRED_NOEXCEPT as non-dependent, since it doesn't
27628 affect overload resolution and treating it as dependent breaks
27629 things. Same for an unparsed noexcept expression. */
27630 if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
27631 && TREE_CODE (noex) != DEFERRED_PARSE
27632 && value_dependent_expression_p (noex))
27633 return true;
27635 return false;
27638 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
27639 Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
27641 static bool
27642 dependent_type_p_r (tree type)
27644 tree scope;
27646 /* [temp.dep.type]
27648 A type is dependent if it is:
27650 -- a template parameter. Template template parameters are types
27651 for us (since TYPE_P holds true for them) so we handle
27652 them here. */
27653 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
27654 || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
27655 return true;
27656 /* -- a qualified-id with a nested-name-specifier which contains a
27657 class-name that names a dependent type or whose unqualified-id
27658 names a dependent type. */
27659 if (TREE_CODE (type) == TYPENAME_TYPE)
27660 return true;
27662 /* An alias template specialization can be dependent even if the
27663 resulting type is not. */
27664 if (dependent_alias_template_spec_p (type, nt_transparent))
27665 return true;
27667 /* -- a cv-qualified type where the cv-unqualified type is
27668 dependent.
27669 No code is necessary for this bullet; the code below handles
27670 cv-qualified types, and we don't want to strip aliases with
27671 TYPE_MAIN_VARIANT because of DR 1558. */
27672 /* -- a compound type constructed from any dependent type. */
27673 if (TYPE_PTRMEM_P (type))
27674 return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
27675 || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
27676 (type)));
27677 else if (INDIRECT_TYPE_P (type))
27678 return dependent_type_p (TREE_TYPE (type));
27679 else if (FUNC_OR_METHOD_TYPE_P (type))
27681 tree arg_type;
27683 if (dependent_type_p (TREE_TYPE (type)))
27684 return true;
27685 for (arg_type = TYPE_ARG_TYPES (type);
27686 arg_type;
27687 arg_type = TREE_CHAIN (arg_type))
27688 if (dependent_type_p (TREE_VALUE (arg_type)))
27689 return true;
27690 if (cxx_dialect >= cxx17
27691 && value_dependent_noexcept_spec_p (type))
27692 /* A value-dependent noexcept-specifier makes the type dependent. */
27693 return true;
27694 return false;
27696 /* -- an array type constructed from any dependent type or whose
27697 size is specified by a constant expression that is
27698 value-dependent.
27700 We checked for type- and value-dependence of the bounds in
27701 compute_array_index_type, so TYPE_DEPENDENT_P is already set. */
27702 if (TREE_CODE (type) == ARRAY_TYPE)
27704 if (TYPE_DOMAIN (type)
27705 && dependent_type_p (TYPE_DOMAIN (type)))
27706 return true;
27707 return dependent_type_p (TREE_TYPE (type));
27710 /* -- a template-id in which either the template name is a template
27711 parameter ... */
27712 if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
27713 return true;
27714 /* ... or any of the template arguments is a dependent type or
27715 an expression that is type-dependent or value-dependent. */
27716 else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
27717 && (any_dependent_template_arguments_p
27718 (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
27719 return true;
27721 /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and TRAIT_TYPEs are
27722 dependent; if the argument of the `typeof' expression is not
27723 type-dependent, then it should already been have resolved. */
27724 if (TREE_CODE (type) == TYPEOF_TYPE
27725 || TREE_CODE (type) == DECLTYPE_TYPE
27726 || TREE_CODE (type) == TRAIT_TYPE)
27727 return true;
27729 /* A template argument pack is dependent if any of its packed
27730 arguments are. */
27731 if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
27733 tree args = ARGUMENT_PACK_ARGS (type);
27734 for (tree arg : tree_vec_range (args))
27735 if (dependent_template_arg_p (arg))
27736 return true;
27739 /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
27740 be template parameters. */
27741 if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
27742 return true;
27744 if (TREE_CODE (type) == DEPENDENT_OPERATOR_TYPE)
27745 return true;
27747 if (any_dependent_type_attributes_p (TYPE_ATTRIBUTES (type)))
27748 return true;
27750 /* The standard does not specifically mention types that are local
27751 to template functions or local classes, but they should be
27752 considered dependent too. For example:
27754 template <int I> void f() {
27755 enum E { a = I };
27756 S<sizeof (E)> s;
27759 The size of `E' cannot be known until the value of `I' has been
27760 determined. Therefore, `E' must be considered dependent. */
27761 scope = TYPE_CONTEXT (type);
27762 if (scope && TYPE_P (scope))
27763 return dependent_type_p (scope);
27764 /* Don't use type_dependent_expression_p here, as it can lead
27765 to infinite recursion trying to determine whether a lambda
27766 nested in a lambda is dependent (c++/47687). */
27767 else if (scope && TREE_CODE (scope) == FUNCTION_DECL
27768 && DECL_LANG_SPECIFIC (scope)
27769 && DECL_TEMPLATE_INFO (scope)
27770 && (any_dependent_template_arguments_p
27771 (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
27772 return true;
27774 /* Other types are non-dependent. */
27775 return false;
27778 /* Returns TRUE if TYPE is dependent, in the sense of
27779 [temp.dep.type]. Note that a NULL type is considered dependent. */
27781 bool
27782 dependent_type_p (tree type)
27784 /* If there are no template parameters in scope, then there can't be
27785 any dependent types. */
27786 if (!processing_template_decl)
27788 /* If we are not processing a template, then nobody should be
27789 providing us with a dependent type. */
27790 gcc_assert (type);
27791 gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
27792 return false;
27795 /* If the type is NULL, we have not computed a type for the entity
27796 in question; in that case, the type is dependent. */
27797 if (!type)
27798 return true;
27800 /* Erroneous types can be considered non-dependent. */
27801 if (type == error_mark_node)
27802 return false;
27804 /* If we have not already computed the appropriate value for TYPE,
27805 do so now. */
27806 if (!TYPE_DEPENDENT_P_VALID (type))
27808 TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
27809 TYPE_DEPENDENT_P_VALID (type) = 1;
27812 return TYPE_DEPENDENT_P (type);
27815 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
27816 lookup. In other words, a dependent type that is not the current
27817 instantiation. */
27819 bool
27820 dependent_scope_p (tree scope)
27822 return (scope && TYPE_P (scope) && dependent_type_p (scope)
27823 && !currently_open_class (scope));
27826 /* True if we might find more declarations in SCOPE during instantiation than
27827 we can when parsing the template. */
27829 bool
27830 dependentish_scope_p (tree scope)
27832 return dependent_scope_p (scope) || any_dependent_bases_p (scope);
27835 /* T is a SCOPE_REF. Return whether it represents a non-static member of
27836 an unknown base of 'this' (and is therefore instantiation-dependent). */
27838 static bool
27839 unknown_base_ref_p (tree t)
27841 if (!current_class_ptr)
27842 return false;
27844 tree mem = TREE_OPERAND (t, 1);
27845 if (shared_member_p (mem))
27846 return false;
27848 tree cur = current_nonlambda_class_type ();
27849 if (!any_dependent_bases_p (cur))
27850 return false;
27852 tree ctx = TREE_OPERAND (t, 0);
27853 if (DERIVED_FROM_P (ctx, cur))
27854 return false;
27856 return true;
27859 /* T is a SCOPE_REF; return whether we need to consider it
27860 instantiation-dependent so that we can check access at instantiation
27861 time even though we know which member it resolves to. */
27863 static bool
27864 instantiation_dependent_scope_ref_p (tree t)
27866 if (DECL_P (TREE_OPERAND (t, 1))
27867 && CLASS_TYPE_P (TREE_OPERAND (t, 0))
27868 && !dependent_scope_p (TREE_OPERAND (t, 0))
27869 && !unknown_base_ref_p (t)
27870 && accessible_in_template_p (TREE_OPERAND (t, 0),
27871 TREE_OPERAND (t, 1)))
27872 return false;
27873 else
27874 return true;
27877 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
27878 [temp.dep.constexpr]. EXPRESSION is already known to be a constant
27879 expression. */
27881 /* Note that this predicate is not appropriate for general expressions;
27882 only constant expressions (that satisfy potential_constant_expression)
27883 can be tested for value dependence. */
27885 bool
27886 value_dependent_expression_p (tree expression)
27888 if (!processing_template_decl || expression == NULL_TREE)
27889 return false;
27891 /* A type-dependent expression is also value-dependent. */
27892 if (type_dependent_expression_p (expression))
27893 return true;
27895 switch (TREE_CODE (expression))
27897 case BASELINK:
27898 /* A dependent member function of the current instantiation. */
27899 return dependent_type_p (BINFO_TYPE (BASELINK_BINFO (expression)));
27901 case FUNCTION_DECL:
27902 /* A dependent member function of the current instantiation. */
27903 if (DECL_CLASS_SCOPE_P (expression)
27904 && dependent_type_p (DECL_CONTEXT (expression)))
27905 return true;
27906 break;
27908 case IDENTIFIER_NODE:
27909 /* A name that has not been looked up -- must be dependent. */
27910 return true;
27912 case TEMPLATE_PARM_INDEX:
27913 /* A non-type template parm. */
27914 return true;
27916 case CONST_DECL:
27917 /* A non-type template parm. */
27918 if (DECL_TEMPLATE_PARM_P (expression))
27919 return true;
27920 return value_dependent_expression_p (DECL_INITIAL (expression));
27922 case VAR_DECL:
27923 /* A constant with literal type and is initialized
27924 with an expression that is value-dependent. */
27925 if (DECL_DEPENDENT_INIT_P (expression))
27926 return true;
27927 if (DECL_HAS_VALUE_EXPR_P (expression))
27929 tree value_expr = DECL_VALUE_EXPR (expression);
27930 if (value_dependent_expression_p (value_expr)
27931 /* __PRETTY_FUNCTION__ inside a template function is dependent
27932 on the name of the function. */
27933 || (DECL_PRETTY_FUNCTION_P (expression)
27934 /* It might be used in a template, but not a template
27935 function, in which case its DECL_VALUE_EXPR will be
27936 "top level". */
27937 && value_expr == error_mark_node))
27938 return true;
27940 else if (TYPE_REF_P (TREE_TYPE (expression)))
27941 /* FIXME cp_finish_decl doesn't fold reference initializers. */
27942 return true;
27943 return false;
27945 case DYNAMIC_CAST_EXPR:
27946 case STATIC_CAST_EXPR:
27947 case CONST_CAST_EXPR:
27948 case REINTERPRET_CAST_EXPR:
27949 case CAST_EXPR:
27950 case IMPLICIT_CONV_EXPR:
27951 /* These expressions are value-dependent if the type to which
27952 the cast occurs is dependent or the expression being casted
27953 is value-dependent. */
27955 tree type = TREE_TYPE (expression);
27957 if (dependent_type_p (type))
27958 return true;
27960 /* A functional cast has a list of operands. */
27961 expression = TREE_OPERAND (expression, 0);
27962 if (!expression)
27964 /* If there are no operands, it must be an expression such
27965 as "int()". This should not happen for aggregate types
27966 because it would form non-constant expressions. */
27967 gcc_assert (cxx_dialect >= cxx11
27968 || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
27970 return false;
27973 if (TREE_CODE (expression) == TREE_LIST)
27974 return any_value_dependent_elements_p (expression);
27976 if (TREE_CODE (type) == REFERENCE_TYPE
27977 && has_value_dependent_address (expression))
27978 return true;
27980 return value_dependent_expression_p (expression);
27983 case SIZEOF_EXPR:
27984 if (SIZEOF_EXPR_TYPE_P (expression))
27985 return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
27986 /* FALLTHRU */
27987 case ALIGNOF_EXPR:
27988 case TYPEID_EXPR:
27989 /* A `sizeof' expression is value-dependent if the operand is
27990 type-dependent or is a pack expansion. */
27991 expression = TREE_OPERAND (expression, 0);
27992 if (PACK_EXPANSION_P (expression))
27993 return true;
27994 else if (TYPE_P (expression))
27995 return dependent_type_p (expression);
27996 return instantiation_dependent_uneval_expression_p (expression);
27998 case AT_ENCODE_EXPR:
27999 /* An 'encode' expression is value-dependent if the operand is
28000 type-dependent. */
28001 expression = TREE_OPERAND (expression, 0);
28002 return dependent_type_p (expression);
28004 case NOEXCEPT_EXPR:
28005 expression = TREE_OPERAND (expression, 0);
28006 return instantiation_dependent_uneval_expression_p (expression);
28008 case SCOPE_REF:
28009 /* All instantiation-dependent expressions should also be considered
28010 value-dependent. */
28011 return instantiation_dependent_scope_ref_p (expression);
28013 case COMPONENT_REF:
28014 return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
28015 || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
28017 case NONTYPE_ARGUMENT_PACK:
28018 /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
28019 is value-dependent. */
28020 for (tree arg : tree_vec_range (ARGUMENT_PACK_ARGS (expression)))
28021 if (value_dependent_expression_p (arg))
28022 return true;
28023 return false;
28025 case TRAIT_EXPR:
28027 if (dependent_type_p (TRAIT_EXPR_TYPE1 (expression)))
28028 return true;
28030 tree type2 = TRAIT_EXPR_TYPE2 (expression);
28031 if (!type2)
28032 return false;
28034 if (TREE_CODE (type2) != TREE_VEC)
28035 return dependent_type_p (type2);
28037 for (tree arg : tree_vec_range (type2))
28038 if (dependent_type_p (arg))
28039 return true;
28041 return false;
28044 case MODOP_EXPR:
28045 return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
28046 || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
28048 case ARRAY_REF:
28049 return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
28050 || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
28052 case ADDR_EXPR:
28054 tree op = TREE_OPERAND (expression, 0);
28055 return (value_dependent_expression_p (op)
28056 || has_value_dependent_address (op));
28059 case REQUIRES_EXPR:
28060 /* Treat all requires-expressions as value-dependent so
28061 we don't try to fold them. */
28062 return true;
28064 case TYPE_REQ:
28065 return dependent_type_p (TREE_OPERAND (expression, 0));
28067 case CALL_EXPR:
28069 if (value_dependent_expression_p (CALL_EXPR_FN (expression)))
28070 return true;
28071 tree fn = get_callee_fndecl (expression);
28072 int i, nargs;
28073 nargs = call_expr_nargs (expression);
28074 for (i = 0; i < nargs; ++i)
28076 tree op = CALL_EXPR_ARG (expression, i);
28077 /* In a call to a constexpr member function, look through the
28078 implicit ADDR_EXPR on the object argument so that it doesn't
28079 cause the call to be considered value-dependent. We also
28080 look through it in potential_constant_expression. */
28081 if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
28082 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
28083 && TREE_CODE (op) == ADDR_EXPR)
28084 op = TREE_OPERAND (op, 0);
28085 if (value_dependent_expression_p (op))
28086 return true;
28088 return false;
28091 case TEMPLATE_ID_EXPR:
28092 return concept_definition_p (TREE_OPERAND (expression, 0))
28093 && any_dependent_template_arguments_p (TREE_OPERAND (expression, 1));
28095 case CONSTRUCTOR:
28097 unsigned ix;
28098 tree val;
28099 if (dependent_type_p (TREE_TYPE (expression)))
28100 return true;
28101 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
28102 if (value_dependent_expression_p (val))
28103 return true;
28104 return false;
28107 case STMT_EXPR:
28108 /* Treat a GNU statement expression as dependent to avoid crashing
28109 under instantiate_non_dependent_expr; it can't be constant. */
28110 return true;
28112 case NEW_EXPR:
28113 case VEC_NEW_EXPR:
28114 /* The second operand is a type, which type_dependent_expression_p
28115 (and therefore value_dependent_expression_p) doesn't want to see. */
28116 return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
28117 || value_dependent_expression_p (TREE_OPERAND (expression, 2))
28118 || value_dependent_expression_p (TREE_OPERAND (expression, 3)));
28120 default:
28121 /* A constant expression is value-dependent if any subexpression is
28122 value-dependent. */
28123 switch (TREE_CODE_CLASS (TREE_CODE (expression)))
28125 case tcc_reference:
28126 case tcc_unary:
28127 case tcc_comparison:
28128 case tcc_binary:
28129 case tcc_expression:
28130 case tcc_vl_exp:
28132 int i, len = cp_tree_operand_length (expression);
28134 for (i = 0; i < len; i++)
28136 tree t = TREE_OPERAND (expression, i);
28138 /* In some cases, some of the operands may be missing.
28139 (For example, in the case of PREDECREMENT_EXPR, the
28140 amount to increment by may be missing.) That doesn't
28141 make the expression dependent. */
28142 if (t && value_dependent_expression_p (t))
28143 return true;
28146 break;
28147 default:
28148 break;
28150 break;
28153 /* The expression is not value-dependent. */
28154 return false;
28157 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
28158 [temp.dep.expr]. Note that an expression with no type is
28159 considered dependent. Other parts of the compiler arrange for an
28160 expression with type-dependent subexpressions to have no type, so
28161 this function doesn't have to be fully recursive. */
28163 bool
28164 type_dependent_expression_p (tree expression)
28166 if (!processing_template_decl)
28167 return false;
28169 if (expression == NULL_TREE || expression == error_mark_node)
28170 return false;
28172 gcc_checking_assert (!TYPE_P (expression));
28174 STRIP_ANY_LOCATION_WRAPPER (expression);
28176 /* An unresolved name is always dependent. */
28177 if (identifier_p (expression)
28178 || TREE_CODE (expression) == USING_DECL
28179 || TREE_CODE (expression) == WILDCARD_DECL)
28180 return true;
28182 /* A lambda-expression in template context is dependent. dependent_type_p is
28183 true for a lambda in the scope of a class or function template, but that
28184 doesn't cover all template contexts, like a default template argument. */
28185 if (TREE_CODE (expression) == LAMBDA_EXPR)
28186 return true;
28188 /* A fold expression is type-dependent. */
28189 if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
28190 || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
28191 || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
28192 || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
28193 return true;
28195 /* Some expression forms are never type-dependent. */
28196 if (TREE_CODE (expression) == SIZEOF_EXPR
28197 || TREE_CODE (expression) == ALIGNOF_EXPR
28198 || TREE_CODE (expression) == AT_ENCODE_EXPR
28199 || TREE_CODE (expression) == NOEXCEPT_EXPR
28200 || TREE_CODE (expression) == TRAIT_EXPR
28201 || TREE_CODE (expression) == TYPEID_EXPR
28202 || TREE_CODE (expression) == DELETE_EXPR
28203 || TREE_CODE (expression) == VEC_DELETE_EXPR
28204 || TREE_CODE (expression) == THROW_EXPR
28205 || TREE_CODE (expression) == REQUIRES_EXPR)
28206 return false;
28208 /* The types of these expressions depends only on the type to which
28209 the cast occurs. */
28210 if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
28211 || TREE_CODE (expression) == STATIC_CAST_EXPR
28212 || TREE_CODE (expression) == CONST_CAST_EXPR
28213 || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
28214 || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
28215 || TREE_CODE (expression) == CAST_EXPR)
28216 return dependent_type_p (TREE_TYPE (expression));
28218 /* The types of these expressions depends only on the type created
28219 by the expression. */
28220 if (TREE_CODE (expression) == NEW_EXPR
28221 || TREE_CODE (expression) == VEC_NEW_EXPR)
28223 /* For NEW_EXPR tree nodes created inside a template, either
28224 the object type itself or a TREE_LIST may appear as the
28225 operand 1. */
28226 tree type = TREE_OPERAND (expression, 1);
28227 if (TREE_CODE (type) == TREE_LIST)
28228 /* This is an array type. We need to check array dimensions
28229 as well. */
28230 return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
28231 || value_dependent_expression_p
28232 (TREE_OPERAND (TREE_VALUE (type), 1));
28233 /* Array type whose dimension has to be deduced. */
28234 else if (TREE_CODE (type) == ARRAY_TYPE
28235 && TREE_OPERAND (expression, 2) == NULL_TREE)
28236 return true;
28237 else
28238 return dependent_type_p (type);
28241 if (TREE_CODE (expression) == SCOPE_REF)
28243 tree scope = TREE_OPERAND (expression, 0);
28244 tree name = TREE_OPERAND (expression, 1);
28246 /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
28247 contains an identifier associated by name lookup with one or more
28248 declarations declared with a dependent type, or...a
28249 nested-name-specifier or qualified-id that names a member of an
28250 unknown specialization. */
28251 return (type_dependent_expression_p (name)
28252 || dependent_scope_p (scope));
28255 if (TREE_CODE (expression) == TEMPLATE_DECL
28256 && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
28257 return uses_outer_template_parms (expression);
28259 if (TREE_CODE (expression) == STMT_EXPR)
28260 expression = stmt_expr_value_expr (expression);
28262 if (BRACE_ENCLOSED_INITIALIZER_P (expression))
28264 for (auto &elt : CONSTRUCTOR_ELTS (expression))
28265 if (type_dependent_expression_p (elt.value))
28266 return true;
28267 return false;
28270 /* A static data member of the current instantiation with incomplete
28271 array type is type-dependent, as the definition and specializations
28272 can have different bounds. */
28273 if (VAR_P (expression)
28274 && DECL_CLASS_SCOPE_P (expression)
28275 && dependent_type_p (DECL_CONTEXT (expression))
28276 && VAR_HAD_UNKNOWN_BOUND (expression))
28277 return true;
28279 /* An array of unknown bound depending on a variadic parameter, eg:
28281 template<typename... Args>
28282 void foo (Args... args)
28284 int arr[] = { args... };
28287 template<int... vals>
28288 void bar ()
28290 int arr[] = { vals... };
28293 If the array has no length and has an initializer, it must be that
28294 we couldn't determine its length in cp_complete_array_type because
28295 it is dependent. */
28296 if (((VAR_P (expression) && DECL_INITIAL (expression))
28297 || COMPOUND_LITERAL_P (expression))
28298 && TREE_TYPE (expression) != NULL_TREE
28299 && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
28300 && !TYPE_DOMAIN (TREE_TYPE (expression)))
28301 return true;
28303 /* Pull a FUNCTION_DECL out of a BASELINK if we can. */
28304 if (BASELINK_P (expression))
28306 if (BASELINK_OPTYPE (expression)
28307 && dependent_type_p (BASELINK_OPTYPE (expression)))
28308 return true;
28309 expression = BASELINK_FUNCTIONS (expression);
28312 /* A function or variable template-id is type-dependent if it has any
28313 dependent template arguments. */
28314 if (VAR_OR_FUNCTION_DECL_P (expression)
28315 && DECL_LANG_SPECIFIC (expression)
28316 && DECL_TEMPLATE_INFO (expression))
28318 /* Consider the innermost template arguments, since those are the ones
28319 that come from the template-id; the template arguments for the
28320 enclosing class do not make it type-dependent unless they are used in
28321 the type of the decl. */
28322 if (instantiates_primary_template_p (expression)
28323 && (any_dependent_template_arguments_p
28324 (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
28325 return true;
28328 /* Otherwise, if the function decl isn't from a dependent scope, it can't be
28329 type-dependent. Checking this is important for functions with auto return
28330 type, which looks like a dependent type. */
28331 if (TREE_CODE (expression) == FUNCTION_DECL
28332 && !(DECL_CLASS_SCOPE_P (expression)
28333 && dependent_type_p (DECL_CONTEXT (expression)))
28334 && !(DECL_LANG_SPECIFIC (expression)
28335 && DECL_UNIQUE_FRIEND_P (expression)
28336 && (!DECL_FRIEND_CONTEXT (expression)
28337 || dependent_type_p (DECL_FRIEND_CONTEXT (expression))))
28338 && !DECL_LOCAL_DECL_P (expression))
28340 gcc_assert (!dependent_type_p (TREE_TYPE (expression))
28341 || undeduced_auto_decl (expression));
28342 return false;
28345 /* Otherwise, its constraints could still depend on outer template parameters
28346 from its (dependent) scope. */
28347 if (TREE_CODE (expression) == FUNCTION_DECL
28348 /* As an optimization, check this cheaper sufficient condition first.
28349 (At this point we've established that we're looking at a member of
28350 a dependent class, so it makes sense to start treating say undeduced
28351 auto as dependent.) */
28352 && !dependent_type_p (TREE_TYPE (expression))
28353 && uses_outer_template_parms_in_constraints (expression))
28354 return true;
28356 /* Always dependent, on the number of arguments if nothing else. */
28357 if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
28358 return true;
28360 if (TREE_TYPE (expression) == unknown_type_node)
28362 if (TREE_CODE (expression) == ADDR_EXPR)
28363 return type_dependent_expression_p (TREE_OPERAND (expression, 0));
28364 if (TREE_CODE (expression) == COMPONENT_REF
28365 || TREE_CODE (expression) == OFFSET_REF)
28367 if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
28368 return true;
28369 expression = TREE_OPERAND (expression, 1);
28370 if (identifier_p (expression))
28371 return false;
28373 /* SCOPE_REF with non-null TREE_TYPE is always non-dependent. */
28374 if (TREE_CODE (expression) == SCOPE_REF)
28375 return false;
28377 /* CO_AWAIT/YIELD_EXPR with unknown type is always dependent. */
28378 if (TREE_CODE (expression) == CO_AWAIT_EXPR
28379 || TREE_CODE (expression) == CO_YIELD_EXPR)
28380 return true;
28382 if (BASELINK_P (expression))
28384 if (BASELINK_OPTYPE (expression)
28385 && dependent_type_p (BASELINK_OPTYPE (expression)))
28386 return true;
28387 expression = BASELINK_FUNCTIONS (expression);
28390 if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
28392 if (any_dependent_template_arguments_p
28393 (TREE_OPERAND (expression, 1)))
28394 return true;
28395 expression = TREE_OPERAND (expression, 0);
28396 if (identifier_p (expression))
28397 return true;
28400 gcc_assert (OVL_P (expression));
28402 for (lkp_iterator iter (expression); iter; ++iter)
28403 if (type_dependent_expression_p (*iter))
28404 return true;
28406 return false;
28409 /* The type of a non-type template parm declared with a placeholder type
28410 depends on the corresponding template argument, even though
28411 placeholders are not normally considered dependent. */
28412 if (TREE_CODE (expression) == TEMPLATE_PARM_INDEX
28413 && is_auto (TREE_TYPE (expression)))
28414 return true;
28416 gcc_assert (TREE_CODE (expression) != TYPE_DECL);
28418 /* Dependent type attributes might not have made it from the decl to
28419 the type yet. */
28420 if (DECL_P (expression)
28421 && any_dependent_type_attributes_p (DECL_ATTRIBUTES (expression)))
28422 return true;
28424 return (dependent_type_p (TREE_TYPE (expression)));
28427 /* [temp.dep.expr]/5: A class member access expression (5.2.5) is
28428 type-dependent if the expression refers to a member of the current
28429 instantiation and the type of the referenced member is dependent, or the
28430 class member access expression refers to a member of an unknown
28431 specialization.
28433 This function returns true if the OBJECT in such a class member access
28434 expression is of an unknown specialization. */
28436 bool
28437 type_dependent_object_expression_p (tree object)
28439 /* An IDENTIFIER_NODE can sometimes have a TREE_TYPE, but it's still
28440 dependent. */
28441 if (TREE_CODE (object) == IDENTIFIER_NODE)
28442 return true;
28443 tree scope = TREE_TYPE (object);
28444 return (!scope || dependent_scope_p (scope));
28447 /* walk_tree callback function for instantiation_dependent_expression_p,
28448 below. Returns non-zero if a dependent subexpression is found. */
28450 static tree
28451 instantiation_dependent_r (tree *tp, int *walk_subtrees,
28452 void * /*data*/)
28454 if (TYPE_P (*tp))
28456 /* We don't have to worry about decltype currently because decltype
28457 of an instantiation-dependent expr is a dependent type. This
28458 might change depending on the resolution of DR 1172. */
28459 *walk_subtrees = false;
28460 return NULL_TREE;
28462 enum tree_code code = TREE_CODE (*tp);
28463 switch (code)
28465 /* Don't treat an argument list as dependent just because it has no
28466 TREE_TYPE. */
28467 case TREE_LIST:
28468 case TREE_VEC:
28469 case NONTYPE_ARGUMENT_PACK:
28470 return NULL_TREE;
28472 case TEMPLATE_PARM_INDEX:
28473 if (dependent_type_p (TREE_TYPE (*tp)))
28474 return *tp;
28475 if (TEMPLATE_PARM_PARAMETER_PACK (*tp))
28476 return *tp;
28477 /* We'll check value-dependence separately. */
28478 return NULL_TREE;
28480 /* Handle expressions with type operands. */
28481 case SIZEOF_EXPR:
28482 case ALIGNOF_EXPR:
28483 case TYPEID_EXPR:
28484 case AT_ENCODE_EXPR:
28486 tree op = TREE_OPERAND (*tp, 0);
28487 if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
28488 op = TREE_TYPE (op);
28489 if (TYPE_P (op))
28491 if (dependent_type_p (op))
28492 return *tp;
28493 else
28495 *walk_subtrees = false;
28496 return NULL_TREE;
28499 break;
28502 case COMPONENT_REF:
28503 if (identifier_p (TREE_OPERAND (*tp, 1)))
28504 /* In a template, finish_class_member_access_expr creates a
28505 COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
28506 type-dependent, so that we can check access control at
28507 instantiation time (PR 42277). See also Core issue 1273. */
28508 return *tp;
28509 break;
28511 case SCOPE_REF:
28512 if (instantiation_dependent_scope_ref_p (*tp))
28513 return *tp;
28514 else
28515 break;
28517 /* Treat statement-expressions as dependent. */
28518 case BIND_EXPR:
28519 return *tp;
28521 /* Treat requires-expressions as dependent. */
28522 case REQUIRES_EXPR:
28523 return *tp;
28525 case CONSTRUCTOR:
28526 if (CONSTRUCTOR_IS_DEPENDENT (*tp))
28527 return *tp;
28528 break;
28530 case TEMPLATE_DECL:
28531 case FUNCTION_DECL:
28532 /* Before C++17, a noexcept-specifier isn't part of the function type
28533 so it doesn't affect type dependence, but we still want to consider it
28534 for instantiation dependence. */
28535 if (cxx_dialect < cxx17
28536 && DECL_DECLARES_FUNCTION_P (*tp)
28537 && value_dependent_noexcept_spec_p (TREE_TYPE (*tp)))
28538 return *tp;
28539 break;
28541 default:
28542 break;
28545 if (type_dependent_expression_p (*tp))
28546 return *tp;
28547 else
28548 return NULL_TREE;
28551 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
28552 sense defined by the ABI:
28554 "An expression is instantiation-dependent if it is type-dependent
28555 or value-dependent, or it has a subexpression that is type-dependent
28556 or value-dependent."
28558 Except don't actually check value-dependence for unevaluated expressions,
28559 because in sizeof(i) we don't care about the value of i. Checking
28560 type-dependence will in turn check value-dependence of array bounds/template
28561 arguments as needed. */
28563 bool
28564 instantiation_dependent_uneval_expression_p (tree expression)
28566 tree result;
28568 if (!processing_template_decl)
28569 return false;
28571 if (expression == error_mark_node)
28572 return false;
28574 result = cp_walk_tree_without_duplicates (&expression,
28575 instantiation_dependent_r, NULL);
28576 return result != NULL_TREE;
28579 /* As above, but also check value-dependence of the expression as a whole. */
28581 bool
28582 instantiation_dependent_expression_p (tree expression)
28584 return (instantiation_dependent_uneval_expression_p (expression)
28585 || (processing_template_decl
28586 && potential_constant_expression (expression)
28587 && value_dependent_expression_p (expression)));
28590 /* Like type_dependent_expression_p, but it also works while not processing
28591 a template definition, i.e. during substitution or mangling. */
28593 bool
28594 type_dependent_expression_p_push (tree expr)
28596 bool b;
28597 ++processing_template_decl;
28598 b = type_dependent_expression_p (expr);
28599 --processing_template_decl;
28600 return b;
28603 /* Returns TRUE if ARGS contains a type-dependent expression. */
28605 bool
28606 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
28608 if (!processing_template_decl || !args)
28609 return false;
28611 for (tree arg : *args)
28612 if (type_dependent_expression_p (arg))
28613 return true;
28615 return false;
28618 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
28619 expressions) contains any type-dependent expressions. */
28621 bool
28622 any_type_dependent_elements_p (const_tree list)
28624 for (; list; list = TREE_CHAIN (list))
28625 if (type_dependent_expression_p (TREE_VALUE (list)))
28626 return true;
28628 return false;
28631 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
28632 expressions) contains any value-dependent expressions. */
28634 bool
28635 any_value_dependent_elements_p (const_tree list)
28637 for (; list; list = TREE_CHAIN (list))
28638 if (value_dependent_expression_p (TREE_VALUE (list)))
28639 return true;
28641 return false;
28644 /* Returns TRUE if the ARG (a template argument) is dependent. */
28646 bool
28647 dependent_template_arg_p (tree arg)
28649 if (!processing_template_decl)
28650 return false;
28652 /* Assume a template argument that was wrongly written by the user
28653 is dependent. This is consistent with what
28654 any_dependent_template_arguments_p [that calls this function]
28655 does. */
28656 if (!arg || arg == error_mark_node)
28657 return true;
28659 if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
28660 arg = argument_pack_select_arg (arg);
28662 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
28663 return true;
28664 if (TREE_CODE (arg) == TEMPLATE_DECL)
28666 if (DECL_TEMPLATE_PARM_P (arg))
28667 return true;
28668 /* A member template of a dependent class is not necessarily
28669 type-dependent, but it is a dependent template argument because it
28670 will be a member of an unknown specialization to that template. */
28671 tree scope = CP_DECL_CONTEXT (arg);
28672 return TYPE_P (scope) && dependent_type_p (scope);
28674 else if (ARGUMENT_PACK_P (arg))
28676 tree args = ARGUMENT_PACK_ARGS (arg);
28677 for (tree arg : tree_vec_range (args))
28678 if (dependent_template_arg_p (arg))
28679 return true;
28680 return false;
28682 else if (TYPE_P (arg))
28683 return dependent_type_p (arg);
28684 else
28685 return value_dependent_expression_p (arg);
28688 /* Identify any expressions that use function parms. */
28690 static tree
28691 find_parm_usage_r (tree *tp, int *walk_subtrees, void*)
28693 tree t = *tp;
28694 if (TREE_CODE (t) == PARM_DECL)
28696 *walk_subtrees = 0;
28697 return t;
28699 return NULL_TREE;
28702 /* Returns true if a type specialization formed using the template
28703 arguments ARGS needs to use structural equality. */
28705 bool
28706 any_template_arguments_need_structural_equality_p (tree args)
28708 int i;
28709 int j;
28711 if (!args)
28712 return false;
28713 if (args == error_mark_node)
28714 return true;
28716 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
28718 tree level = TMPL_ARGS_LEVEL (args, i + 1);
28719 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
28721 tree arg = TREE_VEC_ELT (level, j);
28722 tree packed_args = NULL_TREE;
28723 int k, len = 1;
28725 if (ARGUMENT_PACK_P (arg))
28727 /* Look inside the argument pack. */
28728 packed_args = ARGUMENT_PACK_ARGS (arg);
28729 len = TREE_VEC_LENGTH (packed_args);
28732 for (k = 0; k < len; ++k)
28734 if (packed_args)
28735 arg = TREE_VEC_ELT (packed_args, k);
28737 if (error_operand_p (arg))
28738 return true;
28739 else if (TREE_CODE (arg) == TEMPLATE_DECL)
28740 continue;
28741 else if (arg == any_targ_node)
28742 /* An any_targ_node argument (added by add_defaults_to_ttp)
28743 makes the corresponding specialization not canonicalizable,
28744 since template_args_equal always return true for it. We
28745 may see this when called from bind_template_template_parm. */
28746 return true;
28747 /* Checking current_function_decl because this structural
28748 comparison is only necessary for redeclaration. */
28749 else if (!current_function_decl
28750 && dependent_template_arg_p (arg)
28751 && (cp_walk_tree_without_duplicates
28752 (&arg, find_parm_usage_r, NULL)))
28753 /* The identity of a class template specialization that uses
28754 a function parameter depends on the identity of the function.
28755 And if this specialization appeared in the trailing return
28756 type thereof, we don't know the identity of the function
28757 (e.g. if it's a redeclaration or a new function) until we
28758 form its signature and go through duplicate_decls. Thus
28759 it's unsafe to decide on a canonical type now (which depends
28760 on the DECL_CONTEXT of the function parameter, which can get
28761 mutated after the fact by duplicate_decls), so just require
28762 structural equality in this case (PR52830). */
28763 return true;
28768 return false;
28771 /* Returns true if ARGS (a collection of template arguments) contains
28772 any dependent arguments. */
28774 bool
28775 any_dependent_template_arguments_p (const_tree args)
28777 if (args == error_mark_node)
28778 return true;
28779 if (!processing_template_decl || !args)
28780 return false;
28782 for (int i = 0, depth = TMPL_ARGS_DEPTH (args); i < depth; ++i)
28784 const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
28785 for (tree arg : tree_vec_range (CONST_CAST_TREE (level)))
28786 if (dependent_template_arg_p (arg))
28787 return true;
28790 return false;
28793 /* Returns true if ARGS contains any errors. */
28795 bool
28796 any_erroneous_template_args_p (const_tree args)
28798 int i;
28799 int j;
28801 if (args == error_mark_node)
28802 return true;
28804 if (args && TREE_CODE (args) != TREE_VEC)
28806 if (tree ti = get_template_info (args))
28807 args = TI_ARGS (ti);
28808 else
28809 args = NULL_TREE;
28812 if (!args)
28813 return false;
28815 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
28817 const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
28818 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
28819 if (error_operand_p (TREE_VEC_ELT (level, j)))
28820 return true;
28823 return false;
28826 /* Returns TRUE if the template TMPL is type-dependent. */
28828 bool
28829 dependent_template_p (tree tmpl)
28831 if (TREE_CODE (tmpl) == OVERLOAD)
28833 for (lkp_iterator iter (tmpl); iter; ++iter)
28834 if (dependent_template_p (*iter))
28835 return true;
28836 return false;
28839 /* Template template parameters are dependent. */
28840 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
28841 || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
28842 return true;
28843 /* So are names that have not been looked up. */
28844 if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
28845 return true;
28846 return false;
28849 /* Returns TRUE if the specialization TMPL<ARGS> is dependent. */
28851 bool
28852 dependent_template_id_p (tree tmpl, tree args)
28854 return (dependent_template_p (tmpl)
28855 || any_dependent_template_arguments_p (args));
28858 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
28859 are dependent. */
28861 bool
28862 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
28864 int i;
28866 if (!processing_template_decl)
28867 return false;
28869 for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
28871 tree decl = TREE_VEC_ELT (declv, i);
28872 tree init = TREE_VEC_ELT (initv, i);
28873 tree cond = TREE_VEC_ELT (condv, i);
28874 tree incr = TREE_VEC_ELT (incrv, i);
28876 if (type_dependent_expression_p (decl)
28877 || TREE_CODE (decl) == SCOPE_REF)
28878 return true;
28880 if (init && type_dependent_expression_p (init))
28881 return true;
28883 if (cond == global_namespace)
28884 return true;
28886 if (type_dependent_expression_p (cond))
28887 return true;
28889 if (COMPARISON_CLASS_P (cond)
28890 && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
28891 || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
28892 return true;
28894 if (TREE_CODE (incr) == MODOP_EXPR)
28896 if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
28897 || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
28898 return true;
28900 else if (type_dependent_expression_p (incr))
28901 return true;
28902 else if (TREE_CODE (incr) == MODIFY_EXPR)
28904 if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
28905 return true;
28906 else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
28908 tree t = TREE_OPERAND (incr, 1);
28909 if (type_dependent_expression_p (TREE_OPERAND (t, 0))
28910 || type_dependent_expression_p (TREE_OPERAND (t, 1)))
28911 return true;
28913 /* If this loop has a class iterator with != comparison
28914 with increment other than i++/++i/i--/--i, make sure the
28915 increment is constant. */
28916 if (CLASS_TYPE_P (TREE_TYPE (decl))
28917 && TREE_CODE (cond) == NE_EXPR)
28919 if (TREE_OPERAND (t, 0) == decl)
28920 t = TREE_OPERAND (t, 1);
28921 else
28922 t = TREE_OPERAND (t, 0);
28923 if (TREE_CODE (t) != INTEGER_CST)
28924 return true;
28930 return false;
28933 /* TYPE is a TYPENAME_TYPE. Returns the ordinary TYPE to which the
28934 TYPENAME_TYPE corresponds. Returns the original TYPENAME_TYPE if
28935 no such TYPE can be found. Note that this function peers inside
28936 uninstantiated templates and therefore should be used only in
28937 extremely limited situations. ONLY_CURRENT_P restricts this
28938 peering to the currently open classes hierarchy (which is required
28939 when comparing types). */
28941 tree
28942 resolve_typename_type (tree type, bool only_current_p)
28944 tree scope;
28945 tree name;
28946 tree decl;
28947 int quals;
28948 tree pushed_scope;
28949 tree result;
28951 gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
28953 scope = TYPE_CONTEXT (type);
28954 /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope. */
28955 gcc_checking_assert (uses_template_parms (scope));
28957 /* Usually the non-qualified identifier of a TYPENAME_TYPE is
28958 TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of a
28959 TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL
28960 representing the typedef. In that case TYPE_IDENTIFIER (type) is
28961 not the non-qualified identifier of the TYPENAME_TYPE anymore.
28962 So by getting the TYPE_IDENTIFIER of the _main declaration_ of
28963 the TYPENAME_TYPE instead, we avoid messing up with a possible
28964 typedef variant case. */
28965 name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
28967 /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
28968 it first before we can figure out what NAME refers to. */
28969 if (TREE_CODE (scope) == TYPENAME_TYPE)
28971 if (TYPENAME_IS_RESOLVING_P (scope))
28972 /* Given a class template A with a dependent base with nested type C,
28973 typedef typename A::C::C C will land us here, as trying to resolve
28974 the initial A::C leads to the local C typedef, which leads back to
28975 A::C::C. So we break the recursion now. */
28976 return type;
28977 else
28978 scope = resolve_typename_type (scope, only_current_p);
28980 /* If we don't know what SCOPE refers to, then we cannot resolve the
28981 TYPENAME_TYPE. */
28982 if (!CLASS_TYPE_P (scope))
28983 return type;
28984 /* If this is a typedef, we don't want to look inside (c++/11987). */
28985 if (typedef_variant_p (type))
28986 return type;
28987 /* If SCOPE isn't the template itself, it will not have a valid
28988 TYPE_FIELDS list. */
28989 if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
28990 /* scope is either the template itself or a compatible instantiation
28991 like X<T>, so look up the name in the original template. */
28992 scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
28993 /* If scope has no fields, it can't be a current instantiation. Check this
28994 before currently_open_class to avoid infinite recursion (71515). */
28995 if (!TYPE_FIELDS (scope))
28996 return type;
28997 /* If the SCOPE is not the current instantiation, there's no reason
28998 to look inside it. */
28999 if (only_current_p && !currently_open_class (scope))
29000 return type;
29001 /* Enter the SCOPE so that name lookup will be resolved as if we
29002 were in the class definition. In particular, SCOPE will no
29003 longer be considered a dependent type. */
29004 pushed_scope = push_scope (scope);
29005 /* Look up the declaration. */
29006 decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
29007 tf_warning_or_error);
29009 result = NULL_TREE;
29011 /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
29012 find a TEMPLATE_DECL. Otherwise, we want to find a TYPE_DECL. */
29013 tree fullname = TYPENAME_TYPE_FULLNAME (type);
29014 if (!decl)
29015 /*nop*/;
29016 else if (identifier_p (fullname)
29017 && TREE_CODE (decl) == TYPE_DECL)
29019 result = TREE_TYPE (decl);
29020 if (result == error_mark_node)
29021 result = NULL_TREE;
29023 else if (TREE_CODE (fullname) == TEMPLATE_ID_EXPR
29024 && DECL_CLASS_TEMPLATE_P (decl))
29026 /* Obtain the template and the arguments. */
29027 tree tmpl = TREE_OPERAND (fullname, 0);
29028 if (TREE_CODE (tmpl) == IDENTIFIER_NODE)
29030 /* We get here with a plain identifier because a previous tentative
29031 parse of the nested-name-specifier as part of a ptr-operator saw
29032 ::template X<A>. The use of ::template is necessary in a
29033 ptr-operator, but wrong in a declarator-id.
29035 [temp.names]: In a qualified-id of a declarator-id, the keyword
29036 template shall not appear at the top level. */
29037 pedwarn (cp_expr_loc_or_input_loc (fullname), OPT_Wpedantic,
29038 "keyword %<template%> not allowed in declarator-id");
29039 tmpl = decl;
29041 tree args = TREE_OPERAND (fullname, 1);
29042 /* Instantiate the template. */
29043 result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
29044 /*entering_scope=*/true,
29045 tf_error | tf_user);
29046 if (result == error_mark_node)
29047 result = NULL_TREE;
29050 /* Leave the SCOPE. */
29051 if (pushed_scope)
29052 pop_scope (pushed_scope);
29054 /* If we failed to resolve it, return the original typename. */
29055 if (!result)
29056 return type;
29058 /* If lookup found a typename type, resolve that too. */
29059 if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
29061 /* Ill-formed programs can cause infinite recursion here, so we
29062 must catch that. */
29063 TYPENAME_IS_RESOLVING_P (result) = 1;
29064 result = resolve_typename_type (result, only_current_p);
29065 TYPENAME_IS_RESOLVING_P (result) = 0;
29068 /* Qualify the resulting type. */
29069 quals = cp_type_quals (type);
29070 if (quals)
29071 result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
29073 return result;
29076 /* EXPR is an expression which is not type-dependent. Return a proxy
29077 for EXPR that can be used to compute the types of larger
29078 expressions containing EXPR. */
29080 tree
29081 build_non_dependent_expr (tree expr)
29083 tree orig_expr = expr;
29084 tree inner_expr;
29086 /* When checking, try to get a constant value for all non-dependent
29087 expressions in order to expose bugs in *_dependent_expression_p
29088 and constexpr. This can affect code generation, see PR70704, so
29089 only do this for -fchecking=2. */
29090 if (flag_checking > 1
29091 && cxx_dialect >= cxx11
29092 /* Don't do this during nsdmi parsing as it can lead to
29093 unexpected recursive instantiations. */
29094 && !parsing_nsdmi ()
29095 /* Don't do this during concept processing either and for
29096 the same reason. */
29097 && !processing_constraint_expression_p ())
29098 fold_non_dependent_expr (expr, tf_none);
29100 STRIP_ANY_LOCATION_WRAPPER (expr);
29102 /* Preserve OVERLOADs; the functions must be available to resolve
29103 types. */
29104 inner_expr = expr;
29105 if (TREE_CODE (inner_expr) == STMT_EXPR)
29106 inner_expr = stmt_expr_value_expr (inner_expr);
29107 if (TREE_CODE (inner_expr) == ADDR_EXPR)
29108 inner_expr = TREE_OPERAND (inner_expr, 0);
29109 if (TREE_CODE (inner_expr) == COMPONENT_REF)
29110 inner_expr = TREE_OPERAND (inner_expr, 1);
29111 if (is_overloaded_fn (inner_expr)
29112 || TREE_CODE (inner_expr) == OFFSET_REF)
29113 return orig_expr;
29114 /* There is no need to return a proxy for a variable, parameter
29115 or enumerator. */
29116 if (VAR_P (expr) || TREE_CODE (expr) == PARM_DECL
29117 || TREE_CODE (expr) == CONST_DECL)
29118 return orig_expr;
29119 /* Preserve string constants; conversions from string constants to
29120 "char *" are allowed, even though normally a "const char *"
29121 cannot be used to initialize a "char *". */
29122 if (TREE_CODE (expr) == STRING_CST)
29123 return orig_expr;
29124 /* Preserve void and arithmetic constants, as an optimization -- there is no
29125 reason to create a new node. */
29126 if (TREE_CODE (expr) == VOID_CST
29127 || TREE_CODE (expr) == INTEGER_CST
29128 || TREE_CODE (expr) == REAL_CST)
29129 return orig_expr;
29130 /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
29131 There is at least one place where we want to know that a
29132 particular expression is a throw-expression: when checking a ?:
29133 expression, there are special rules if the second or third
29134 argument is a throw-expression. */
29135 if (TREE_CODE (expr) == THROW_EXPR)
29136 return orig_expr;
29138 /* Don't wrap an initializer list, we need to be able to look inside. */
29139 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
29140 return orig_expr;
29142 /* Don't wrap a dummy object, we need to be able to test for it. */
29143 if (is_dummy_object (expr))
29144 return orig_expr;
29146 if (TREE_CODE (expr) == COND_EXPR)
29147 return build3 (COND_EXPR,
29148 TREE_TYPE (expr),
29149 build_non_dependent_expr (TREE_OPERAND (expr, 0)),
29150 (TREE_OPERAND (expr, 1)
29151 ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
29152 : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
29153 build_non_dependent_expr (TREE_OPERAND (expr, 2)));
29154 if (TREE_CODE (expr) == COMPOUND_EXPR)
29155 return build2 (COMPOUND_EXPR,
29156 TREE_TYPE (expr),
29157 TREE_OPERAND (expr, 0),
29158 build_non_dependent_expr (TREE_OPERAND (expr, 1)));
29160 /* If the type is unknown, it can't really be non-dependent */
29161 gcc_assert (TREE_TYPE (expr) != unknown_type_node);
29163 /* Otherwise, build a NON_DEPENDENT_EXPR. */
29164 return build1_loc (EXPR_LOCATION (orig_expr), NON_DEPENDENT_EXPR,
29165 TREE_TYPE (expr), expr);
29168 /* ARGS is a vector of expressions as arguments to a function call.
29169 Replace the arguments with equivalent non-dependent expressions.
29170 This modifies ARGS in place. */
29172 void
29173 make_args_non_dependent (vec<tree, va_gc> *args)
29175 unsigned int ix;
29176 tree arg;
29178 FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
29180 tree newarg = build_non_dependent_expr (arg);
29181 if (newarg != arg)
29182 (*args)[ix] = newarg;
29186 /* Returns a type which represents 'auto' or 'decltype(auto)'. We use a
29187 TEMPLATE_TYPE_PARM with a level one deeper than the actual template parms,
29188 by default. If set_canonical is true, we set TYPE_CANONICAL on it. */
29190 static tree
29191 make_auto_1 (tree name, bool set_canonical, int level = -1)
29193 if (level == -1)
29194 level = current_template_depth + 1;
29195 tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
29196 TYPE_NAME (au) = build_decl (input_location, TYPE_DECL, name, au);
29197 TYPE_STUB_DECL (au) = TYPE_NAME (au);
29198 TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
29199 (0, level, level, TYPE_NAME (au), NULL_TREE);
29200 if (set_canonical)
29201 TYPE_CANONICAL (au) = canonical_type_parameter (au);
29202 DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
29203 SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
29204 if (name == decltype_auto_identifier)
29205 AUTO_IS_DECLTYPE (au) = true;
29207 return au;
29210 tree
29211 make_decltype_auto (void)
29213 return make_auto_1 (decltype_auto_identifier, true);
29216 tree
29217 make_auto (void)
29219 return make_auto_1 (auto_identifier, true);
29222 /* Return a C++17 deduction placeholder for class template TMPL.
29223 There are represented as an 'auto' with the special level 0 and
29224 CLASS_PLACEHOLDER_TEMPLATE set. */
29226 tree
29227 make_template_placeholder (tree tmpl)
29229 tree t = make_auto_1 (auto_identifier, false, /*level=*/0);
29230 CLASS_PLACEHOLDER_TEMPLATE (t) = tmpl;
29231 /* Our canonical type depends on the placeholder. */
29232 TYPE_CANONICAL (t) = canonical_type_parameter (t);
29233 return t;
29236 /* True iff T is a C++17 class template deduction placeholder. */
29238 bool
29239 template_placeholder_p (tree t)
29241 return is_auto (t) && CLASS_PLACEHOLDER_TEMPLATE (t);
29244 /* Make a "constrained auto" type-specifier. This is an auto or
29245 decltype(auto) type with constraints that must be associated after
29246 deduction. The constraint is formed from the given concept CON
29247 and its optional sequence of template arguments ARGS.
29249 TYPE must be the result of make_auto_type or make_decltype_auto_type. */
29251 static tree
29252 make_constrained_placeholder_type (tree type, tree con, tree args)
29254 /* Build the constraint. */
29255 tree tmpl = DECL_TI_TEMPLATE (con);
29256 tree expr = tmpl;
29257 if (TREE_CODE (con) == FUNCTION_DECL)
29258 expr = ovl_make (tmpl);
29259 ++processing_template_decl;
29260 expr = build_concept_check (expr, type, args, tf_warning_or_error);
29261 --processing_template_decl;
29263 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (type)
29264 = build_tree_list (current_template_parms, expr);
29266 /* Our canonical type depends on the constraint. */
29267 TYPE_CANONICAL (type) = canonical_type_parameter (type);
29269 /* Attach the constraint to the type declaration. */
29270 return TYPE_NAME (type);
29273 /* Make a "constrained auto" type-specifier. */
29275 tree
29276 make_constrained_auto (tree con, tree args)
29278 tree type = make_auto_1 (auto_identifier, false);
29279 return make_constrained_placeholder_type (type, con, args);
29282 /* Make a "constrained decltype(auto)" type-specifier. */
29284 tree
29285 make_constrained_decltype_auto (tree con, tree args)
29287 tree type = make_auto_1 (decltype_auto_identifier, false);
29288 return make_constrained_placeholder_type (type, con, args);
29291 /* Returns true if the placeholder type constraint T has any dependent
29292 (explicit) template arguments. */
29294 static bool
29295 placeholder_type_constraint_dependent_p (tree t)
29297 tree id = unpack_concept_check (t);
29298 tree args = TREE_OPERAND (id, 1);
29299 tree first = TREE_VEC_ELT (args, 0);
29300 if (ARGUMENT_PACK_P (first))
29302 args = expand_template_argument_pack (args);
29303 first = TREE_VEC_ELT (args, 0);
29305 gcc_checking_assert (TREE_CODE (first) == WILDCARD_DECL
29306 || is_auto (first));
29307 for (int i = 1; i < TREE_VEC_LENGTH (args); ++i)
29308 if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
29309 return true;
29310 return false;
29313 /* Build and return a concept definition. Like other templates, the
29314 CONCEPT_DECL node is wrapped by a TEMPLATE_DECL. This returns the
29315 the TEMPLATE_DECL. */
29317 tree
29318 finish_concept_definition (cp_expr id, tree init, tree attrs)
29320 gcc_assert (identifier_p (id));
29321 gcc_assert (processing_template_decl);
29323 location_t loc = id.get_location();
29325 /* A concept-definition shall not have associated constraints. */
29326 if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
29328 error_at (loc, "a concept cannot be constrained");
29329 TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
29332 /* A concept-definition shall appear in namespace scope. Templates
29333 aren't allowed in block scope, so we only need to check for class
29334 scope. */
29335 if (TYPE_P (current_scope()) || !DECL_NAMESPACE_SCOPE_P (current_scope ()))
29337 error_at (loc, "concept %qE not in namespace scope", *id);
29338 return error_mark_node;
29341 if (current_template_depth > 1)
29343 error_at (loc, "concept %qE has multiple template parameter lists", *id);
29344 return error_mark_node;
29347 /* Initially build the concept declaration; its type is bool. */
29348 tree decl = build_lang_decl_loc (loc, CONCEPT_DECL, *id, boolean_type_node);
29349 DECL_CONTEXT (decl) = current_scope ();
29350 DECL_INITIAL (decl) = init;
29352 if (attrs)
29353 cplus_decl_attributes (&decl, attrs, 0);
29355 set_originating_module (decl, false);
29357 /* Push the enclosing template. */
29358 return push_template_decl (decl);
29361 /* Given type ARG, return std::initializer_list<ARG>. */
29363 static tree
29364 listify (tree arg)
29366 tree std_init_list = lookup_qualified_name (std_node, init_list_identifier);
29368 if (std_init_list == error_mark_node
29369 || !DECL_CLASS_TEMPLATE_P (std_init_list))
29371 gcc_rich_location richloc (input_location);
29372 maybe_add_include_fixit (&richloc, "<initializer_list>", false);
29373 error_at (&richloc,
29374 "deducing from brace-enclosed initializer list"
29375 " requires %<#include <initializer_list>%>");
29377 return error_mark_node;
29379 tree argvec = make_tree_vec (1);
29380 TREE_VEC_ELT (argvec, 0) = arg;
29382 return lookup_template_class (std_init_list, argvec, NULL_TREE,
29383 NULL_TREE, 0, tf_warning_or_error);
29386 /* Replace auto in TYPE with std::initializer_list<auto>. */
29388 static tree
29389 listify_autos (tree type, tree auto_node)
29391 tree init_auto = listify (strip_top_quals (auto_node));
29392 tree argvec = make_tree_vec (1);
29393 TREE_VEC_ELT (argvec, 0) = init_auto;
29394 if (processing_template_decl)
29395 argvec = add_to_template_args (current_template_args (), argvec);
29396 return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
29399 /* Hash traits for hashing possibly constrained 'auto'
29400 TEMPLATE_TYPE_PARMs for use by do_auto_deduction. */
29402 struct auto_hash : default_hash_traits<tree>
29404 static inline hashval_t hash (tree);
29405 static inline bool equal (tree, tree);
29408 /* Hash the 'auto' T. */
29410 inline hashval_t
29411 auto_hash::hash (tree t)
29413 if (tree c = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (t)))
29414 /* Matching constrained-type-specifiers denote the same template
29415 parameter, so hash the constraint. */
29416 return hash_placeholder_constraint (c);
29417 else
29418 /* But unconstrained autos are all separate, so just hash the pointer. */
29419 return iterative_hash_object (t, 0);
29422 /* Compare two 'auto's. */
29424 inline bool
29425 auto_hash::equal (tree t1, tree t2)
29427 if (t1 == t2)
29428 return true;
29430 tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
29431 tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
29433 /* Two unconstrained autos are distinct. */
29434 if (!c1 || !c2)
29435 return false;
29437 return equivalent_placeholder_constraints (c1, c2);
29440 /* for_each_template_parm callback for extract_autos: if t is a (possibly
29441 constrained) auto, add it to the vector. */
29443 static int
29444 extract_autos_r (tree t, void *data)
29446 hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
29447 if (is_auto (t) && !template_placeholder_p (t))
29449 /* All the autos were built with index 0; fix that up now. */
29450 tree *p = hash.find_slot (t, INSERT);
29451 int idx;
29452 if (*p)
29453 /* If this is a repeated constrained-type-specifier, use the index we
29454 chose before. */
29455 idx = TEMPLATE_TYPE_IDX (*p);
29456 else
29458 /* Otherwise this is new, so use the current count. */
29459 *p = t;
29460 idx = hash.elements () - 1;
29462 if (idx != TEMPLATE_TYPE_IDX (t))
29464 gcc_checking_assert (TEMPLATE_TYPE_IDX (t) == 0);
29465 gcc_checking_assert (TYPE_CANONICAL (t) != t);
29466 TEMPLATE_TYPE_IDX (t) = idx;
29467 TYPE_CANONICAL (t) = canonical_type_parameter (t);
29471 /* Always keep walking. */
29472 return 0;
29475 /* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
29476 says they can appear anywhere in the type. */
29478 static tree
29479 extract_autos (tree type)
29481 hash_set<tree> visited;
29482 hash_table<auto_hash> hash (2);
29484 for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
29486 tree tree_vec = make_tree_vec (hash.elements());
29487 for (tree elt : hash)
29489 unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
29490 TREE_VEC_ELT (tree_vec, i)
29491 = build_tree_list (NULL_TREE, TYPE_NAME (elt));
29494 return tree_vec;
29497 /* The stem for deduction guide names. */
29498 const char *const dguide_base = "__dguide_";
29500 /* Return the name for a deduction guide for class template TMPL. */
29502 tree
29503 dguide_name (tree tmpl)
29505 tree type = (TYPE_P (tmpl) ? tmpl : TREE_TYPE (tmpl));
29506 tree tname = TYPE_IDENTIFIER (type);
29507 char *buf = (char *) alloca (1 + strlen (dguide_base)
29508 + IDENTIFIER_LENGTH (tname));
29509 memcpy (buf, dguide_base, strlen (dguide_base));
29510 memcpy (buf + strlen (dguide_base), IDENTIFIER_POINTER (tname),
29511 IDENTIFIER_LENGTH (tname) + 1);
29512 tree dname = get_identifier (buf);
29513 TREE_TYPE (dname) = type;
29514 return dname;
29517 /* True if NAME is the name of a deduction guide. */
29519 bool
29520 dguide_name_p (tree name)
29522 return (TREE_CODE (name) == IDENTIFIER_NODE
29523 && TREE_TYPE (name)
29524 && startswith (IDENTIFIER_POINTER (name), dguide_base));
29527 /* True if FN is a deduction guide. */
29529 bool
29530 deduction_guide_p (const_tree fn)
29532 if (DECL_P (fn))
29533 if (tree name = DECL_NAME (fn))
29534 return dguide_name_p (name);
29535 return false;
29538 /* True if FN is the copy deduction guide, i.e. A(A)->A. */
29540 bool
29541 copy_guide_p (const_tree fn)
29543 gcc_assert (deduction_guide_p (fn));
29544 if (!DECL_ARTIFICIAL (fn))
29545 return false;
29546 tree parms = FUNCTION_FIRST_USER_PARMTYPE (DECL_TI_TEMPLATE (fn));
29547 return (TREE_CHAIN (parms) == void_list_node
29548 && same_type_p (TREE_VALUE (parms), TREE_TYPE (DECL_NAME (fn))));
29551 /* True if FN is a guide generated from a constructor template. */
29553 bool
29554 template_guide_p (const_tree fn)
29556 gcc_assert (deduction_guide_p (fn));
29557 if (!DECL_ARTIFICIAL (fn))
29558 return false;
29559 tree tmpl = DECL_TI_TEMPLATE (fn);
29560 if (tree org = DECL_ABSTRACT_ORIGIN (tmpl))
29561 return PRIMARY_TEMPLATE_P (org);
29562 return false;
29565 /* True if FN is an aggregate initialization guide or the copy deduction
29566 guide. */
29568 bool
29569 builtin_guide_p (const_tree fn)
29571 if (!deduction_guide_p (fn))
29572 return false;
29573 if (!DECL_ARTIFICIAL (fn))
29574 /* Explicitly declared. */
29575 return false;
29576 if (DECL_ABSTRACT_ORIGIN (fn))
29577 /* Derived from a constructor. */
29578 return false;
29579 return true;
29582 /* OLDDECL is a _DECL for a template parameter. Return a similar parameter at
29583 LEVEL:INDEX, using tsubst_args and complain for substitution into non-type
29584 template parameter types. Note that the handling of template template
29585 parameters relies on current_template_parms being set appropriately for the
29586 new template. */
29588 static tree
29589 rewrite_template_parm (tree olddecl, unsigned index, unsigned level,
29590 tree tsubst_args, tsubst_flags_t complain)
29592 if (olddecl == error_mark_node)
29593 return error_mark_node;
29595 tree oldidx = get_template_parm_index (olddecl);
29597 tree newtype;
29598 if (TREE_CODE (olddecl) == TYPE_DECL
29599 || TREE_CODE (olddecl) == TEMPLATE_DECL)
29601 tree oldtype = TREE_TYPE (olddecl);
29602 newtype = cxx_make_type (TREE_CODE (oldtype));
29603 TYPE_MAIN_VARIANT (newtype) = newtype;
29605 else
29607 newtype = TREE_TYPE (olddecl);
29608 if (type_uses_auto (newtype))
29610 // Substitute once to fix references to other template parameters.
29611 newtype = tsubst (newtype, tsubst_args,
29612 complain|tf_partial, NULL_TREE);
29613 // Now substitute again to reduce the level of the auto.
29614 newtype = tsubst (newtype, current_template_args (),
29615 complain, NULL_TREE);
29617 else
29618 newtype = tsubst (newtype, tsubst_args,
29619 complain, NULL_TREE);
29622 tree newdecl
29623 = build_decl (DECL_SOURCE_LOCATION (olddecl), TREE_CODE (olddecl),
29624 DECL_NAME (olddecl), newtype);
29625 SET_DECL_TEMPLATE_PARM_P (newdecl);
29627 tree newidx;
29628 if (TREE_CODE (olddecl) == TYPE_DECL
29629 || TREE_CODE (olddecl) == TEMPLATE_DECL)
29631 newidx = TEMPLATE_TYPE_PARM_INDEX (newtype)
29632 = build_template_parm_index (index, level, level,
29633 newdecl, newtype);
29634 TEMPLATE_PARM_PARAMETER_PACK (newidx)
29635 = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
29636 TYPE_STUB_DECL (newtype) = TYPE_NAME (newtype) = newdecl;
29638 if (TREE_CODE (olddecl) == TEMPLATE_DECL)
29640 DECL_TEMPLATE_RESULT (newdecl)
29641 = build_decl (DECL_SOURCE_LOCATION (olddecl), TYPE_DECL,
29642 DECL_NAME (olddecl), newtype);
29643 DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (newdecl)) = true;
29644 // First create a copy (ttargs) of tsubst_args with an
29645 // additional level for the template template parameter's own
29646 // template parameters (ttparms).
29647 tree ttparms = (INNERMOST_TEMPLATE_PARMS
29648 (DECL_TEMPLATE_PARMS (olddecl)));
29649 const int depth = TMPL_ARGS_DEPTH (tsubst_args);
29650 tree ttargs = make_tree_vec (depth + 1);
29651 for (int i = 0; i < depth; ++i)
29652 TREE_VEC_ELT (ttargs, i) = TMPL_ARGS_LEVEL (tsubst_args, i + 1);
29653 TREE_VEC_ELT (ttargs, depth)
29654 = template_parms_level_to_args (ttparms);
29655 // Substitute ttargs into ttparms to fix references to
29656 // other template parameters.
29657 ttparms = tsubst_template_parms_level (ttparms, ttargs,
29658 complain|tf_partial);
29659 // Now substitute again with args based on tparms, to reduce
29660 // the level of the ttparms.
29661 ttargs = current_template_args ();
29662 ttparms = tsubst_template_parms_level (ttparms, ttargs,
29663 complain);
29664 // Finally, tack the adjusted parms onto tparms.
29665 ttparms = tree_cons (size_int (level + 1), ttparms,
29666 copy_node (current_template_parms));
29667 // As with all template template parms, the parameter list captured
29668 // by this template template parm that corresponds to its own level
29669 // should be empty. This avoids infinite recursion when structurally
29670 // comparing two such rewritten template template parms (PR102479).
29671 gcc_assert (!TREE_VEC_LENGTH
29672 (TREE_VALUE (TREE_CHAIN (DECL_TEMPLATE_PARMS (olddecl)))));
29673 gcc_assert (TMPL_PARMS_DEPTH (TREE_CHAIN (ttparms)) == level);
29674 TREE_VALUE (TREE_CHAIN (ttparms)) = make_tree_vec (0);
29675 // All done.
29676 DECL_TEMPLATE_PARMS (newdecl) = ttparms;
29679 if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (olddecl)))
29680 SET_TYPE_STRUCTURAL_EQUALITY (newtype);
29681 else
29682 TYPE_CANONICAL (newtype) = canonical_type_parameter (newtype);
29684 else
29686 tree oldconst = TEMPLATE_PARM_DECL (oldidx);
29687 tree newconst
29688 = build_decl (DECL_SOURCE_LOCATION (oldconst),
29689 TREE_CODE (oldconst),
29690 DECL_NAME (oldconst), newtype);
29691 TREE_CONSTANT (newconst) = TREE_CONSTANT (newdecl)
29692 = TREE_READONLY (newconst) = TREE_READONLY (newdecl) = true;
29693 SET_DECL_TEMPLATE_PARM_P (newconst);
29694 newidx = build_template_parm_index (index, level, level,
29695 newconst, newtype);
29696 TEMPLATE_PARM_PARAMETER_PACK (newidx)
29697 = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
29698 DECL_INITIAL (newdecl) = DECL_INITIAL (newconst) = newidx;
29701 return newdecl;
29704 /* As rewrite_template_parm, but for the whole TREE_LIST representing a
29705 template parameter. */
29707 static tree
29708 rewrite_tparm_list (tree oldelt, unsigned index, unsigned level,
29709 tree targs, unsigned targs_index, tsubst_flags_t complain)
29711 tree olddecl = TREE_VALUE (oldelt);
29712 tree newdecl = rewrite_template_parm (olddecl, index, level,
29713 targs, complain);
29714 if (newdecl == error_mark_node)
29715 return error_mark_node;
29716 tree newdef = tsubst_template_arg (TREE_PURPOSE (oldelt),
29717 targs, complain, NULL_TREE);
29718 tree list = build_tree_list (newdef, newdecl);
29719 TEMPLATE_PARM_CONSTRAINTS (list)
29720 = tsubst_constraint_info (TEMPLATE_PARM_CONSTRAINTS (oldelt),
29721 targs, complain, NULL_TREE);
29722 int depth = TMPL_ARGS_DEPTH (targs);
29723 TMPL_ARG (targs, depth, targs_index) = template_parm_to_arg (list);
29724 return list;
29727 /* Returns a C++17 class deduction guide template based on the constructor
29728 CTOR. As a special case, CTOR can be a RECORD_TYPE for an implicit default
29729 guide, REFERENCE_TYPE for an implicit copy/move guide, or TREE_LIST for an
29730 aggregate initialization guide. OUTER_ARGS are the template arguments
29731 for the enclosing scope of the class. */
29733 static tree
29734 build_deduction_guide (tree type, tree ctor, tree outer_args, tsubst_flags_t complain)
29736 tree tparms, targs, fparms, fargs, ci;
29737 bool memtmpl = false;
29738 bool explicit_p;
29739 location_t loc;
29740 tree fn_tmpl = NULL_TREE;
29742 if (outer_args)
29744 ++processing_template_decl;
29745 type = tsubst (type, outer_args, complain, CLASSTYPE_TI_TEMPLATE (type));
29746 --processing_template_decl;
29749 if (!DECL_DECLARES_FUNCTION_P (ctor))
29751 if (TYPE_P (ctor))
29753 bool copy_p = TYPE_REF_P (ctor);
29754 if (copy_p)
29755 fparms = tree_cons (NULL_TREE, type, void_list_node);
29756 else
29757 fparms = void_list_node;
29759 else if (TREE_CODE (ctor) == TREE_LIST)
29760 fparms = ctor;
29761 else
29762 gcc_unreachable ();
29764 tree ctmpl = CLASSTYPE_TI_TEMPLATE (type);
29765 tparms = DECL_TEMPLATE_PARMS (ctmpl);
29766 targs = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
29767 ci = NULL_TREE;
29768 fargs = NULL_TREE;
29769 loc = DECL_SOURCE_LOCATION (ctmpl);
29770 explicit_p = false;
29772 else
29774 ++processing_template_decl;
29775 bool ok = true;
29777 complain |= tf_dguide;
29779 fn_tmpl
29780 = (TREE_CODE (ctor) == TEMPLATE_DECL ? ctor
29781 : DECL_TI_TEMPLATE (ctor));
29782 if (outer_args)
29783 fn_tmpl = tsubst (fn_tmpl, outer_args, complain, ctor);
29784 ctor = DECL_TEMPLATE_RESULT (fn_tmpl);
29786 tparms = DECL_TEMPLATE_PARMS (fn_tmpl);
29787 /* If type is a member class template, DECL_TI_ARGS (ctor) will have
29788 fully specialized args for the enclosing class. Strip those off, as
29789 the deduction guide won't have those template parameters. */
29790 targs = get_innermost_template_args (DECL_TI_ARGS (ctor),
29791 TMPL_PARMS_DEPTH (tparms));
29792 /* Discard the 'this' parameter. */
29793 fparms = FUNCTION_ARG_CHAIN (ctor);
29794 fargs = TREE_CHAIN (DECL_ARGUMENTS (ctor));
29795 ci = get_constraints (ctor);
29796 loc = DECL_SOURCE_LOCATION (ctor);
29797 explicit_p = DECL_NONCONVERTING_P (ctor);
29799 if (PRIMARY_TEMPLATE_P (fn_tmpl))
29801 memtmpl = true;
29803 /* For a member template constructor, we need to flatten the two
29804 template parameter lists into one, and then adjust the function
29805 signature accordingly. This gets...complicated. */
29806 tree save_parms = current_template_parms;
29808 /* For a member template we should have two levels of parms/args, one
29809 for the class and one for the constructor. We stripped
29810 specialized args for further enclosing classes above. */
29811 const int depth = 2;
29812 gcc_assert (TMPL_ARGS_DEPTH (targs) == depth);
29814 /* Template args for translating references to the two-level template
29815 parameters into references to the one-level template parameters we
29816 are creating. */
29817 tree tsubst_args = copy_node (targs);
29818 TMPL_ARGS_LEVEL (tsubst_args, depth)
29819 = copy_node (TMPL_ARGS_LEVEL (tsubst_args, depth));
29821 /* Template parms for the constructor template. */
29822 tree ftparms = TREE_VALUE (tparms);
29823 unsigned flen = TREE_VEC_LENGTH (ftparms);
29824 /* Template parms for the class template. */
29825 tparms = TREE_CHAIN (tparms);
29826 tree ctparms = TREE_VALUE (tparms);
29827 unsigned clen = TREE_VEC_LENGTH (ctparms);
29828 /* Template parms for the deduction guide start as a copy of the
29829 template parms for the class. We set current_template_parms for
29830 lookup_template_class_1. */
29831 current_template_parms = tparms = copy_node (tparms);
29832 tree new_vec = TREE_VALUE (tparms) = make_tree_vec (flen + clen);
29833 for (unsigned i = 0; i < clen; ++i)
29834 TREE_VEC_ELT (new_vec, i) = TREE_VEC_ELT (ctparms, i);
29836 /* Now we need to rewrite the constructor parms to append them to the
29837 class parms. */
29838 for (unsigned i = 0; i < flen; ++i)
29840 unsigned index = i + clen;
29841 unsigned level = 1;
29842 tree oldelt = TREE_VEC_ELT (ftparms, i);
29843 tree newelt
29844 = rewrite_tparm_list (oldelt, index, level,
29845 tsubst_args, i, complain);
29846 if (newelt == error_mark_node)
29847 ok = false;
29848 TREE_VEC_ELT (new_vec, index) = newelt;
29851 /* Now we have a final set of template parms to substitute into the
29852 function signature. */
29853 targs = template_parms_to_args (tparms);
29854 fparms = tsubst_arg_types (fparms, tsubst_args, NULL_TREE,
29855 complain, ctor);
29856 if (fparms == error_mark_node)
29857 ok = false;
29858 if (ci)
29860 if (outer_args)
29861 /* FIXME: We'd like to avoid substituting outer template
29862 arguments into the constraint ahead of time, but the
29863 construction of tsubst_args assumes that outer arguments
29864 are already substituted in. */
29865 ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
29866 ci = tsubst_constraint_info (ci, tsubst_args, complain, ctor);
29869 /* Parms are to have DECL_CHAIN tsubsted, which would be skipped if
29870 cp_unevaluated_operand. */
29871 cp_evaluated ev;
29872 fargs = tsubst (fargs, tsubst_args, complain, ctor);
29873 current_template_parms = save_parms;
29875 else
29877 /* Substitute in the same arguments to rewrite class members into
29878 references to members of an unknown specialization. */
29879 cp_evaluated ev;
29880 fparms = tsubst_arg_types (fparms, targs, NULL_TREE, complain, ctor);
29881 fargs = tsubst (fargs, targs, complain, ctor);
29882 if (ci)
29884 if (outer_args)
29885 /* FIXME: As above. */
29886 ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
29887 ci = tsubst_constraint_info (ci, targs, complain, ctor);
29891 --processing_template_decl;
29892 if (!ok)
29893 return error_mark_node;
29896 if (!memtmpl)
29898 /* Copy the parms so we can set DECL_PRIMARY_TEMPLATE. */
29899 tparms = copy_node (tparms);
29900 INNERMOST_TEMPLATE_PARMS (tparms)
29901 = copy_node (INNERMOST_TEMPLATE_PARMS (tparms));
29904 tree fntype = build_function_type (type, fparms);
29905 tree ded_fn = build_lang_decl_loc (loc,
29906 FUNCTION_DECL,
29907 dguide_name (type), fntype);
29908 DECL_ARGUMENTS (ded_fn) = fargs;
29909 DECL_ARTIFICIAL (ded_fn) = true;
29910 DECL_NONCONVERTING_P (ded_fn) = explicit_p;
29911 tree ded_tmpl = build_template_decl (ded_fn, tparms, /*member*/false);
29912 DECL_ARTIFICIAL (ded_tmpl) = true;
29913 DECL_TEMPLATE_INFO (ded_fn) = build_template_info (ded_tmpl, targs);
29914 DECL_PRIMARY_TEMPLATE (ded_tmpl) = ded_tmpl;
29915 if (DECL_P (ctor))
29916 DECL_ABSTRACT_ORIGIN (ded_tmpl) = fn_tmpl;
29917 if (ci)
29918 set_constraints (ded_tmpl, ci);
29920 return ded_tmpl;
29923 /* Add to LIST the member types for the reshaped initializer CTOR. */
29925 static tree
29926 collect_ctor_idx_types (tree ctor, tree list, tree elt = NULL_TREE)
29928 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (ctor);
29929 tree idx, val; unsigned i;
29930 FOR_EACH_CONSTRUCTOR_ELT (v, i, idx, val)
29932 tree ftype = elt ? elt : TREE_TYPE (idx);
29933 if (BRACE_ENCLOSED_INITIALIZER_P (val)
29934 && CONSTRUCTOR_BRACES_ELIDED_P (val))
29936 tree subelt = NULL_TREE;
29937 if (TREE_CODE (ftype) == ARRAY_TYPE)
29938 subelt = TREE_TYPE (ftype);
29939 list = collect_ctor_idx_types (val, list, subelt);
29940 continue;
29942 tree arg = NULL_TREE;
29943 if (i == v->length() - 1
29944 && PACK_EXPANSION_P (ftype))
29945 /* Give the trailing pack expansion parameter a default argument to
29946 match aggregate initialization behavior, even if we deduce the
29947 length of the pack separately to more than we have initializers. */
29948 arg = build_constructor (init_list_type_node, NULL);
29949 /* if ei is of array type and xi is a braced-init-list or string literal,
29950 Ti is an rvalue reference to the declared type of ei */
29951 STRIP_ANY_LOCATION_WRAPPER (val);
29952 if (TREE_CODE (ftype) == ARRAY_TYPE
29953 && (BRACE_ENCLOSED_INITIALIZER_P (val)
29954 || TREE_CODE (val) == STRING_CST))
29956 if (TREE_CODE (val) == STRING_CST)
29957 ftype = cp_build_qualified_type
29958 (ftype, cp_type_quals (ftype) | TYPE_QUAL_CONST);
29959 ftype = (cp_build_reference_type
29960 (ftype, BRACE_ENCLOSED_INITIALIZER_P (val)));
29962 list = tree_cons (arg, ftype, list);
29965 return list;
29968 /* Return whether ETYPE is, or is derived from, a specialization of TMPL. */
29970 static bool
29971 is_spec_or_derived (tree etype, tree tmpl)
29973 if (!etype || !CLASS_TYPE_P (etype))
29974 return false;
29976 etype = cv_unqualified (etype);
29977 tree type = TREE_TYPE (tmpl);
29978 tree tparms = (INNERMOST_TEMPLATE_PARMS
29979 (DECL_TEMPLATE_PARMS (tmpl)));
29980 tree targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
29981 int err = unify (tparms, targs, type, etype,
29982 UNIFY_ALLOW_DERIVED, /*explain*/false);
29983 ggc_free (targs);
29984 return !err;
29987 static tree alias_ctad_tweaks (tree, tree);
29989 /* Return a C++20 aggregate deduction candidate for TYPE initialized from
29990 INIT. */
29992 static tree
29993 maybe_aggr_guide (tree tmpl, tree init, vec<tree,va_gc> *args)
29995 if (cxx_dialect < cxx20)
29996 return NULL_TREE;
29998 if (init == NULL_TREE)
29999 return NULL_TREE;
30001 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30003 tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30004 tree tinfo = get_template_info (under);
30005 if (tree guide = maybe_aggr_guide (TI_TEMPLATE (tinfo), init, args))
30006 return alias_ctad_tweaks (tmpl, guide);
30007 return NULL_TREE;
30010 /* We might be creating a guide for a class member template, e.g.,
30012 template<typename U> struct A {
30013 template<typename T> struct B { T t; };
30016 At this point, A will have been instantiated. Below, we need to
30017 use both A<U>::B<T> (TEMPLATE_TYPE) and A<int>::B<T> (TYPE) types. */
30018 const bool member_template_p
30019 = (DECL_TEMPLATE_INFO (tmpl)
30020 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (tmpl)));
30021 tree type = TREE_TYPE (tmpl);
30022 tree template_type = (member_template_p
30023 ? TREE_TYPE (DECL_TI_TEMPLATE (tmpl))
30024 : type);
30025 if (!CP_AGGREGATE_TYPE_P (template_type))
30026 return NULL_TREE;
30028 /* No aggregate candidate for copy-initialization. */
30029 if (args->length() == 1)
30031 tree val = (*args)[0];
30032 if (is_spec_or_derived (TREE_TYPE (val), tmpl))
30033 return NULL_TREE;
30036 /* If we encounter a problem, we just won't add the candidate. */
30037 tsubst_flags_t complain = tf_none;
30039 tree parms = NULL_TREE;
30040 if (BRACE_ENCLOSED_INITIALIZER_P (init))
30042 init = reshape_init (template_type, init, complain);
30043 if (init == error_mark_node)
30044 return NULL_TREE;
30045 parms = collect_ctor_idx_types (init, parms);
30046 /* If we're creating a deduction guide for a member class template,
30047 we've used the original template pattern type for the reshape_init
30048 above; this is done because we want PARMS to be a template parameter
30049 type, something that can be deduced when used as a function template
30050 parameter. At this point the outer class template has already been
30051 partially instantiated (we deferred the deduction until the enclosing
30052 scope is non-dependent). Therefore we have to partially instantiate
30053 PARMS, so that its template level is properly reduced and we don't get
30054 mismatches when deducing types using the guide with PARMS. */
30055 if (member_template_p)
30057 ++processing_template_decl;
30058 parms = tsubst (parms, DECL_TI_ARGS (tmpl), complain, init);
30059 --processing_template_decl;
30062 else if (TREE_CODE (init) == TREE_LIST)
30064 int len = list_length (init);
30065 for (tree field = TYPE_FIELDS (type);
30066 len;
30067 --len, field = DECL_CHAIN (field))
30069 field = next_aggregate_field (field);
30070 if (!field)
30071 return NULL_TREE;
30072 tree ftype = finish_decltype_type (field, true, complain);
30073 parms = tree_cons (NULL_TREE, ftype, parms);
30076 else
30077 /* Aggregate initialization doesn't apply to an initializer expression. */
30078 return NULL_TREE;
30080 if (parms)
30082 tree last = parms;
30083 parms = nreverse (parms);
30084 TREE_CHAIN (last) = void_list_node;
30085 tree guide = build_deduction_guide (type, parms, NULL_TREE, complain);
30086 return guide;
30089 return NULL_TREE;
30092 /* UGUIDES are the deduction guides for the underlying template of alias
30093 template TMPL; adjust them to be deduction guides for TMPL. */
30095 static tree
30096 alias_ctad_tweaks (tree tmpl, tree uguides)
30098 /* [over.match.class.deduct]: When resolving a placeholder for a deduced
30099 class type (9.2.8.2) where the template-name names an alias template A,
30100 the defining-type-id of A must be of the form
30102 typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
30104 as specified in 9.2.8.2. The guides of A are the set of functions or
30105 function templates formed as follows. For each function or function
30106 template f in the guides of the template named by the simple-template-id
30107 of the defining-type-id, the template arguments of the return type of f
30108 are deduced from the defining-type-id of A according to the process in
30109 13.10.2.5 with the exception that deduction does not fail if not all
30110 template arguments are deduced. Let g denote the result of substituting
30111 these deductions into f. If substitution succeeds, form a function or
30112 function template f' with the following properties and add it to the set
30113 of guides of A:
30115 * The function type of f' is the function type of g.
30117 * If f is a function template, f' is a function template whose template
30118 parameter list consists of all the template parameters of A (including
30119 their default template arguments) that appear in the above deductions or
30120 (recursively) in their default template arguments, followed by the
30121 template parameters of f that were not deduced (including their default
30122 template arguments), otherwise f' is not a function template.
30124 * The associated constraints (13.5.2) are the conjunction of the
30125 associated constraints of g and a constraint that is satisfied if and only
30126 if the arguments of A are deducible (see below) from the return type.
30128 * If f is a copy deduction candidate (12.4.1.8), then f' is considered to
30129 be so as well.
30131 * If f was generated from a deduction-guide (12.4.1.8), then f' is
30132 considered to be so as well.
30134 * The explicit-specifier of f' is the explicit-specifier of g (if
30135 any). */
30137 tsubst_flags_t complain = tf_warning_or_error;
30138 tree atype = TREE_TYPE (tmpl);
30139 tree aguides = NULL_TREE;
30140 tree fullatparms = DECL_TEMPLATE_PARMS (tmpl);
30141 tree atparms = INNERMOST_TEMPLATE_PARMS (fullatparms);
30142 unsigned natparms = TREE_VEC_LENGTH (atparms);
30143 tree utype = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30144 for (ovl_iterator iter (uguides); iter; ++iter)
30146 tree f = *iter;
30147 tree in_decl = f;
30148 location_t loc = DECL_SOURCE_LOCATION (f);
30149 tree ret = TREE_TYPE (TREE_TYPE (f));
30150 tree fprime = f;
30151 if (TREE_CODE (f) == TEMPLATE_DECL)
30153 processing_template_decl_sentinel ptds (/*reset*/false);
30154 ++processing_template_decl;
30156 /* Deduce template arguments for f from the type-id of A. */
30157 tree ftparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (f));
30158 unsigned len = TREE_VEC_LENGTH (ftparms);
30159 tree targs = make_tree_vec (len);
30160 int err = unify (ftparms, targs, ret, utype, UNIFY_ALLOW_NONE, false);
30161 if (err)
30162 /* CWG2664: Discard any deductions, still build the guide. */
30163 for (unsigned i = 0; i < len; ++i)
30164 TREE_VEC_ELT (targs, i) = NULL_TREE;
30166 /* The number of parms for f' is the number of parms of A used in
30167 the deduced arguments plus non-deduced parms of f. */
30168 unsigned ndlen = 0;
30169 unsigned j;
30170 for (unsigned i = 0; i < len; ++i)
30171 if (TREE_VEC_ELT (targs, i) == NULL_TREE)
30172 ++ndlen;
30173 find_template_parameter_info ftpi (fullatparms);
30174 ftpi.find_in_recursive (targs);
30175 unsigned nusedatparms = ftpi.num_found ();
30176 unsigned nfparms = nusedatparms + ndlen;
30177 tree gtparms = make_tree_vec (nfparms);
30179 /* Set current_template_parms as in build_deduction_guide. */
30180 auto ctp = make_temp_override (current_template_parms);
30181 current_template_parms = copy_node (DECL_TEMPLATE_PARMS (tmpl));
30182 TREE_VALUE (current_template_parms) = gtparms;
30184 j = 0;
30185 unsigned level = 1;
30187 /* First copy over the used parms of A. */
30188 tree atargs = make_tree_vec (natparms);
30189 for (unsigned i = 0; i < natparms; ++i)
30191 tree elt = TREE_VEC_ELT (atparms, i);
30192 if (ftpi.found (elt))
30194 unsigned index = j++;
30195 tree nelt = rewrite_tparm_list (elt, index, level,
30196 atargs, i, complain);
30197 TREE_VEC_ELT (gtparms, index) = nelt;
30200 gcc_checking_assert (j == nusedatparms);
30202 /* Adjust the deduced template args for f to refer to the A parms
30203 with their new indexes. */
30204 if (nusedatparms && nusedatparms != natparms)
30205 targs = tsubst_template_args (targs, atargs, complain, in_decl);
30207 /* Now rewrite the non-deduced parms of f. */
30208 for (unsigned i = 0; ndlen && i < len; ++i)
30209 if (TREE_VEC_ELT (targs, i) == NULL_TREE)
30211 --ndlen;
30212 unsigned index = j++;
30213 tree oldlist = TREE_VEC_ELT (ftparms, i);
30214 tree list = rewrite_tparm_list (oldlist, index, level,
30215 targs, i, complain);
30216 TREE_VEC_ELT (gtparms, index) = list;
30218 gtparms = build_tree_list (size_one_node, gtparms);
30220 /* Substitute the deduced arguments plus the rewritten template
30221 parameters into f to get g. This covers the type, copyness,
30222 guideness, and explicit-specifier. */
30223 tree g;
30225 /* Parms are to have DECL_CHAIN tsubsted, which would be skipped
30226 if cp_unevaluated_operand. */
30227 cp_evaluated ev;
30228 g = tsubst_decl (DECL_TEMPLATE_RESULT (f), targs, complain);
30230 if (g == error_mark_node)
30231 continue;
30232 if (nfparms == 0)
30234 /* The targs are all non-dependent, so g isn't a template. */
30235 fprime = g;
30236 ret = TREE_TYPE (TREE_TYPE (fprime));
30237 goto non_template;
30239 DECL_USE_TEMPLATE (g) = 0;
30240 fprime = build_template_decl (g, gtparms, false);
30241 DECL_TEMPLATE_RESULT (fprime) = g;
30242 TREE_TYPE (fprime) = TREE_TYPE (g);
30243 tree gtargs = template_parms_to_args (gtparms);
30244 DECL_TEMPLATE_INFO (g) = build_template_info (fprime, gtargs);
30245 DECL_PRIMARY_TEMPLATE (fprime) = fprime;
30247 /* Substitute the associated constraints. */
30248 tree ci = get_constraints (f);
30249 if (ci)
30250 ci = tsubst_constraint_info (ci, targs, complain, in_decl);
30251 if (ci == error_mark_node)
30252 continue;
30254 /* Add a constraint that the return type matches the instantiation of
30255 A with the same template arguments. */
30256 ret = TREE_TYPE (TREE_TYPE (fprime));
30257 if (!same_type_p (atype, ret)
30258 /* FIXME this should mean they don't compare as equivalent. */
30259 || dependent_alias_template_spec_p (atype, nt_opaque))
30261 tree same = finish_trait_expr (loc, CPTK_IS_DEDUCIBLE, tmpl, ret);
30262 ci = append_constraint (ci, same);
30265 if (ci)
30267 remove_constraints (fprime);
30268 set_constraints (fprime, ci);
30271 else
30273 /* For a non-template deduction guide, if the arguments of A aren't
30274 deducible from the return type, don't add the candidate. */
30275 non_template:
30276 if (!type_targs_deducible_from (tmpl, ret))
30277 continue;
30280 aguides = lookup_add (fprime, aguides);
30283 return aguides;
30286 /* True iff template arguments for TMPL can be deduced from TYPE.
30287 Used to implement CPTK_IS_DEDUCIBLE for alias CTAD according to
30288 [over.match.class.deduct].
30290 This check is specified in terms of partial specialization, so the behavior
30291 should be parallel to that of get_partial_spec_bindings. */
30293 bool
30294 type_targs_deducible_from (tree tmpl, tree type)
30296 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
30297 int len = TREE_VEC_LENGTH (tparms);
30298 tree targs = make_tree_vec (len);
30299 bool tried_array_deduction = (cxx_dialect < cxx17);
30301 /* If tmpl is a class template, this is trivial: it's deducible if TYPE is a
30302 specialization of TMPL. */
30303 if (DECL_CLASS_TEMPLATE_P (tmpl))
30304 return (CLASS_TYPE_P (type)
30305 && CLASSTYPE_TEMPLATE_INFO (type)
30306 && CLASSTYPE_TI_TEMPLATE (type) == tmpl);
30308 /* Otherwise it's an alias template. */
30309 again:
30310 if (unify (tparms, targs, TREE_TYPE (tmpl), type,
30311 UNIFY_ALLOW_NONE, false))
30312 return false;
30314 /* We don't fail on an undeduced targ the second time through (like
30315 get_partial_spec_bindings) because we're going to try defaults. */
30316 for (int i = 0; i < len; ++i)
30317 if (! TREE_VEC_ELT (targs, i))
30319 tree tparm = TREE_VEC_ELT (tparms, i);
30320 tparm = TREE_VALUE (tparm);
30322 if (!tried_array_deduction
30323 && TREE_CODE (tparm) == TYPE_DECL)
30325 try_array_deduction (tparms, targs, TREE_TYPE (tmpl));
30326 tried_array_deduction = true;
30327 if (TREE_VEC_ELT (targs, i))
30328 goto again;
30330 /* If the type parameter is a parameter pack, then it will be deduced
30331 to an empty parameter pack. This is another case that doesn't model
30332 well as partial specialization. */
30333 if (template_parameter_pack_p (tparm))
30335 tree arg;
30336 if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
30338 arg = make_node (NONTYPE_ARGUMENT_PACK);
30339 TREE_CONSTANT (arg) = 1;
30341 else
30342 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
30343 ARGUMENT_PACK_ARGS (arg) = make_tree_vec (0);
30344 TREE_VEC_ELT (targs, i) = arg;
30348 /* Maybe add in default template args. This seems like a flaw in the
30349 specification in terms of partial specialization, since it says the
30350 partial specialization has the the template parameter list of A, but a
30351 partial specialization can't have default targs. */
30352 targs = coerce_template_parms (tparms, targs, tmpl, tf_none);
30353 if (targs == error_mark_node)
30354 return false;
30356 /* I believe we don't need the template_template_parm_bindings_ok_p call
30357 because coerce_template_parms did coerce_template_template_parms. */
30359 return constraints_satisfied_p (tmpl, targs);
30362 /* Return artificial deduction guides built from the constructors of class
30363 template TMPL. */
30365 static tree
30366 ctor_deduction_guides_for (tree tmpl, tsubst_flags_t complain)
30368 tree outer_args = outer_template_args (tmpl);
30369 tree type = TREE_TYPE (most_general_template (tmpl));
30371 tree cands = NULL_TREE;
30373 for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (type)); iter; ++iter)
30375 /* Skip inherited constructors. */
30376 if (iter.using_p ())
30377 continue;
30379 tree guide = build_deduction_guide (type, *iter, outer_args, complain);
30380 cands = lookup_add (guide, cands);
30383 /* Add implicit default constructor deduction guide. */
30384 if (!TYPE_HAS_USER_CONSTRUCTOR (type))
30386 tree guide = build_deduction_guide (type, type, outer_args,
30387 complain);
30388 cands = lookup_add (guide, cands);
30391 /* Add copy guide. */
30393 tree gtype = build_reference_type (type);
30394 tree guide = build_deduction_guide (type, gtype, outer_args,
30395 complain);
30396 cands = lookup_add (guide, cands);
30399 return cands;
30402 static GTY((deletable)) hash_map<tree, tree_pair_p> *dguide_cache;
30404 /* Return the non-aggregate deduction guides for deducible template TMPL. The
30405 aggregate candidate is added separately because it depends on the
30406 initializer. Set ANY_DGUIDES_P if we find a non-implicit deduction
30407 guide. */
30409 static tree
30410 deduction_guides_for (tree tmpl, bool &any_dguides_p, tsubst_flags_t complain)
30412 tree guides = NULL_TREE;
30413 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30415 tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30416 tree tinfo = get_template_info (under);
30417 guides = deduction_guides_for (TI_TEMPLATE (tinfo), any_dguides_p,
30418 complain);
30420 else
30422 guides = lookup_qualified_name (CP_DECL_CONTEXT (tmpl),
30423 dguide_name (tmpl),
30424 LOOK_want::NORMAL, /*complain*/false);
30425 if (guides == error_mark_node)
30426 guides = NULL_TREE;
30427 else
30428 any_dguides_p = true;
30431 /* Cache the deduction guides for a template. We also remember the result of
30432 lookup, and rebuild everything if it changes; should be very rare. */
30433 tree_pair_p cache = NULL;
30434 if (tree_pair_p &r
30435 = hash_map_safe_get_or_insert<hm_ggc> (dguide_cache, tmpl))
30437 cache = r;
30438 if (cache->purpose == guides)
30439 return cache->value;
30441 else
30443 r = cache = ggc_cleared_alloc<tree_pair_s> ();
30444 cache->purpose = guides;
30447 tree cands = NULL_TREE;
30448 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30449 cands = alias_ctad_tweaks (tmpl, guides);
30450 else
30452 cands = ctor_deduction_guides_for (tmpl, complain);
30453 for (ovl_iterator it (guides); it; ++it)
30454 cands = lookup_add (*it, cands);
30457 cache->value = cands;
30458 return cands;
30461 /* Return whether TMPL is a (class template argument-) deducible template. */
30463 bool
30464 ctad_template_p (tree tmpl)
30466 /* A deducible template is either a class template or is an alias template
30467 whose defining-type-id is of the form
30469 typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
30471 where the nested-name-specifier (if any) is non-dependent and the
30472 template-name of the simple-template-id names a deducible template. */
30474 if (DECL_CLASS_TEMPLATE_P (tmpl)
30475 || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
30476 return true;
30477 if (!DECL_ALIAS_TEMPLATE_P (tmpl))
30478 return false;
30479 tree orig = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30480 if (tree tinfo = get_template_info (orig))
30481 return ctad_template_p (TI_TEMPLATE (tinfo));
30482 return false;
30485 /* Deduce template arguments for the class template placeholder PTYPE for
30486 template TMPL based on the initializer INIT, and return the resulting
30487 type. */
30489 static tree
30490 do_class_deduction (tree ptype, tree tmpl, tree init,
30491 int flags, tsubst_flags_t complain)
30493 /* We should have handled this in the caller. */
30494 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
30495 return ptype;
30497 /* If the class was erroneous, don't try to deduce, because that
30498 can generate a lot of diagnostic. */
30499 if (TREE_TYPE (tmpl)
30500 && TYPE_LANG_SPECIFIC (TREE_TYPE (tmpl))
30501 && CLASSTYPE_ERRONEOUS (TREE_TYPE (tmpl)))
30502 return ptype;
30504 /* Wait until the enclosing scope is non-dependent. */
30505 if (DECL_CLASS_SCOPE_P (tmpl)
30506 && dependent_type_p (DECL_CONTEXT (tmpl)))
30507 return ptype;
30509 /* Initializing one placeholder from another. */
30510 if (init
30511 && (TREE_CODE (init) == TEMPLATE_PARM_INDEX
30512 || (TREE_CODE (init) == EXPR_PACK_EXPANSION
30513 && (TREE_CODE (PACK_EXPANSION_PATTERN (init))
30514 == TEMPLATE_PARM_INDEX)))
30515 && is_auto (TREE_TYPE (init))
30516 && CLASS_PLACEHOLDER_TEMPLATE (TREE_TYPE (init)) == tmpl)
30517 return cp_build_qualified_type (TREE_TYPE (init), cp_type_quals (ptype));
30519 if (!ctad_template_p (tmpl))
30521 if (complain & tf_error)
30522 error ("non-deducible template %qT used without template arguments", tmpl);
30523 return error_mark_node;
30525 else if (cxx_dialect < cxx20 && DECL_ALIAS_TEMPLATE_P (tmpl))
30527 if (complain & tf_error)
30529 /* Be permissive with equivalent alias templates. */
30530 tree u = get_underlying_template (tmpl);
30531 diagnostic_t dk = (u == tmpl) ? DK_ERROR : DK_PEDWARN;
30532 bool complained
30533 = emit_diagnostic (dk, input_location, 0,
30534 "alias template deduction only available "
30535 "with %<-std=c++20%> or %<-std=gnu++20%>");
30536 if (u == tmpl)
30537 return error_mark_node;
30538 else if (complained)
30540 inform (input_location, "use %qD directly instead", u);
30541 tmpl = u;
30544 else
30545 return error_mark_node;
30548 /* Wait until the initializer is non-dependent. */
30549 if (type_dependent_expression_p (init))
30550 return ptype;
30552 /* Don't bother with the alias rules for an equivalent template. */
30553 tmpl = get_underlying_template (tmpl);
30555 tree type = TREE_TYPE (tmpl);
30557 bool try_list_cand = false;
30558 bool list_init_p = false;
30560 releasing_vec rv_args = NULL;
30561 vec<tree,va_gc> *&args = *&rv_args;
30562 if (init == NULL_TREE)
30563 args = make_tree_vector ();
30564 else if (BRACE_ENCLOSED_INITIALIZER_P (init))
30566 list_init_p = true;
30567 try_list_cand = true;
30568 if (CONSTRUCTOR_NELTS (init) == 1
30569 && !CONSTRUCTOR_IS_DESIGNATED_INIT (init))
30571 /* As an exception, the first phase in 16.3.1.7 (considering the
30572 initializer list as a single argument) is omitted if the
30573 initializer list consists of a single expression of type cv U,
30574 where U is a specialization of C or a class derived from a
30575 specialization of C. */
30576 tree elt = CONSTRUCTOR_ELT (init, 0)->value;
30577 if (is_spec_or_derived (TREE_TYPE (elt), tmpl))
30578 try_list_cand = false;
30580 if (try_list_cand || is_std_init_list (type))
30581 args = make_tree_vector_single (init);
30582 else
30583 args = make_tree_vector_from_ctor (init);
30585 else if (TREE_CODE (init) == TREE_LIST)
30586 args = make_tree_vector_from_list (init);
30587 else
30588 args = make_tree_vector_single (init);
30590 /* Do this now to avoid problems with erroneous args later on. */
30591 args = resolve_args (args, complain);
30592 if (args == NULL)
30593 return error_mark_node;
30595 bool any_dguides_p = false;
30596 tree cands = deduction_guides_for (tmpl, any_dguides_p, complain);
30597 if (cands == error_mark_node)
30598 return error_mark_node;
30600 /* Prune explicit deduction guides in copy-initialization context (but
30601 not copy-list-initialization). */
30602 bool elided = false;
30603 if (!list_init_p && (flags & LOOKUP_ONLYCONVERTING))
30605 for (lkp_iterator iter (cands); !elided && iter; ++iter)
30606 if (DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
30607 elided = true;
30609 if (elided)
30611 /* Found a nonconverting guide, prune the candidates. */
30612 tree pruned = NULL_TREE;
30613 for (lkp_iterator iter (cands); iter; ++iter)
30614 if (!DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
30615 pruned = lookup_add (*iter, pruned);
30617 cands = pruned;
30621 if (!any_dguides_p)
30622 if (tree guide = maybe_aggr_guide (tmpl, init, args))
30623 cands = lookup_add (guide, cands);
30625 tree fndecl = error_mark_node;
30627 /* If this is list-initialization and the class has a list guide, first
30628 try deducing from the list as a single argument, as [over.match.list]. */
30629 if (try_list_cand)
30631 tree list_cands = NULL_TREE;
30632 for (tree dg : lkp_range (cands))
30633 if (is_list_ctor (dg))
30634 list_cands = lookup_add (dg, list_cands);
30635 if (list_cands)
30636 fndecl = perform_dguide_overload_resolution (list_cands, args, tf_none);
30637 if (fndecl == error_mark_node)
30639 /* That didn't work, now try treating the list as a sequence of
30640 arguments. */
30641 release_tree_vector (args);
30642 args = make_tree_vector_from_ctor (init);
30643 args = resolve_args (args, complain);
30644 if (args == NULL)
30645 return error_mark_node;
30649 if (elided && !cands)
30651 error ("cannot deduce template arguments for copy-initialization"
30652 " of %qT, as it has no non-explicit deduction guides or "
30653 "user-declared constructors", type);
30654 return error_mark_node;
30656 else if (!cands && fndecl == error_mark_node)
30658 error ("cannot deduce template arguments of %qT, as it has no viable "
30659 "deduction guides", type);
30660 return error_mark_node;
30663 if (fndecl == error_mark_node)
30664 fndecl = perform_dguide_overload_resolution (cands, args, tf_none);
30666 if (fndecl == error_mark_node)
30668 if (complain & tf_warning_or_error)
30670 error ("class template argument deduction failed:");
30671 perform_dguide_overload_resolution (cands, args, complain);
30672 if (elided)
30673 inform (input_location, "explicit deduction guides not considered "
30674 "for copy-initialization");
30676 return error_mark_node;
30678 /* [over.match.list]/1: In copy-list-initialization, if an explicit
30679 constructor is chosen, the initialization is ill-formed. */
30680 else if (flags & LOOKUP_ONLYCONVERTING)
30682 if (DECL_NONCONVERTING_P (fndecl))
30684 if (complain & tf_warning_or_error)
30686 // TODO: Pass down location from cp_finish_decl.
30687 error ("class template argument deduction for %qT failed: "
30688 "explicit deduction guide selected in "
30689 "copy-list-initialization", type);
30690 inform (DECL_SOURCE_LOCATION (fndecl),
30691 "explicit deduction guide declared here");
30694 return error_mark_node;
30698 /* If CTAD succeeded but the type doesn't have any explicit deduction
30699 guides, this deduction might not be what the user intended. */
30700 if (fndecl != error_mark_node && !any_dguides_p && (complain & tf_warning))
30702 if ((!DECL_IN_SYSTEM_HEADER (fndecl)
30703 || global_dc->dc_warn_system_headers)
30704 && warning (OPT_Wctad_maybe_unsupported,
30705 "%qT may not intend to support class template argument "
30706 "deduction", type))
30707 inform (input_location, "add a deduction guide to suppress this "
30708 "warning");
30711 return cp_build_qualified_type (TREE_TYPE (TREE_TYPE (fndecl)),
30712 cp_type_quals (ptype));
30715 /* Return true if INIT is an unparenthesized id-expression or an
30716 unparenthesized class member access. Used for the argument of
30717 decltype(auto). */
30719 bool
30720 unparenthesized_id_or_class_member_access_p (tree init)
30722 STRIP_ANY_LOCATION_WRAPPER (init);
30724 /* We need to be able to tell '(r)' and 'r' apart (when it's of
30725 reference type). Only the latter is an id-expression. */
30726 if (REFERENCE_REF_P (init)
30727 && !REF_PARENTHESIZED_P (init))
30728 init = TREE_OPERAND (init, 0);
30729 return (DECL_P (init)
30730 || ((TREE_CODE (init) == COMPONENT_REF
30731 || TREE_CODE (init) == SCOPE_REF)
30732 && !REF_PARENTHESIZED_P (init)));
30735 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
30736 from INIT. AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
30737 The CONTEXT determines the context in which auto deduction is performed
30738 and is used to control error diagnostics. FLAGS are the LOOKUP_* flags.
30740 OUTER_TARGS is used during template argument deduction (context == adc_unify)
30741 to properly substitute the result. It's also used in the adc_unify and
30742 adc_requirement contexts to communicate the necessary template arguments
30743 to satisfaction. OUTER_TARGS is ignored in other contexts.
30745 Additionally for adc_unify contexts TMPL is the template for which TYPE
30746 is a template parameter type.
30748 For partial-concept-ids, extra args from OUTER_TARGS, TMPL and the current
30749 scope may be appended to the list of deduced template arguments prior to
30750 determining constraint satisfaction as appropriate. */
30752 tree
30753 do_auto_deduction (tree type, tree init, tree auto_node,
30754 tsubst_flags_t complain /* = tf_warning_or_error */,
30755 auto_deduction_context context /* = adc_unspecified */,
30756 tree outer_targs /* = NULL_TREE */,
30757 int flags /* = LOOKUP_NORMAL */,
30758 tree tmpl /* = NULL_TREE */)
30760 if (type == error_mark_node || init == error_mark_node)
30761 return error_mark_node;
30763 if (init && type_dependent_expression_p (init)
30764 && context != adc_unify)
30765 /* Defining a subset of type-dependent expressions that we can deduce
30766 from ahead of time isn't worth the trouble. */
30767 return type;
30769 /* Similarly, we can't deduce from another undeduced decl. */
30770 if (init && undeduced_auto_decl (init))
30771 return type;
30773 /* We may be doing a partial substitution, but we still want to replace
30774 auto_node. */
30775 complain &= ~tf_partial;
30777 if (init && BRACE_ENCLOSED_INITIALIZER_P (init))
30779 /* We don't recurse here because we can't deduce from a nested
30780 initializer_list. */
30781 if (CONSTRUCTOR_ELTS (init))
30782 for (constructor_elt &elt : CONSTRUCTOR_ELTS (init))
30783 elt.value = resolve_nondeduced_context (elt.value, complain);
30785 else if (init)
30786 init = resolve_nondeduced_context (init, complain);
30788 /* In C++23, we must deduce the type to int&& for code like
30789 decltype(auto) f(int&& x) { return (x); }
30791 auto&& f(int x) { return x; }
30792 so we use treat_lvalue_as_rvalue_p. But don't do it for
30793 decltype(auto) f(int x) { return x; }
30794 where we should deduce 'int' rather than 'int&&'; transmogrifying
30795 INIT to an rvalue would break that. */
30796 tree r;
30797 if (cxx_dialect >= cxx23
30798 && context == adc_return_type
30799 && (!AUTO_IS_DECLTYPE (auto_node)
30800 || !unparenthesized_id_or_class_member_access_p (init))
30801 && (r = treat_lvalue_as_rvalue_p (maybe_undo_parenthesized_ref (init),
30802 /*return*/true)))
30803 init = r;
30805 if (tree ctmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
30806 /* C++17 class template argument deduction. */
30807 return do_class_deduction (type, ctmpl, init, flags, complain);
30809 if (init == NULL_TREE || TREE_TYPE (init) == NULL_TREE)
30810 /* Nothing we can do with this, even in deduction context. */
30811 return type;
30813 location_t loc = cp_expr_loc_or_input_loc (init);
30815 /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
30816 with either a new invented type template parameter U or, if the
30817 initializer is a braced-init-list (8.5.4), with
30818 std::initializer_list<U>. */
30819 if (BRACE_ENCLOSED_INITIALIZER_P (init))
30821 if (!DIRECT_LIST_INIT_P (init))
30822 type = listify_autos (type, auto_node);
30823 else if (CONSTRUCTOR_NELTS (init) == 1)
30824 init = CONSTRUCTOR_ELT (init, 0)->value;
30825 else
30827 if (complain & tf_warning_or_error)
30829 if (permerror (loc, "direct-list-initialization of "
30830 "%<auto%> requires exactly one element"))
30831 inform (loc,
30832 "for deduction to %<std::initializer_list%>, use copy-"
30833 "list-initialization (i.e. add %<=%> before the %<{%>)");
30835 type = listify_autos (type, auto_node);
30839 if (type == error_mark_node || init == error_mark_node)
30840 return error_mark_node;
30842 tree targs;
30843 if (context == adc_decomp_type
30844 && auto_node == type
30845 && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
30847 /* [dcl.struct.bind]/1 - if decomposition declaration has no ref-qualifiers
30848 and initializer has array type, deduce cv-qualified array type. */
30849 targs = make_tree_vec (1);
30850 TREE_VEC_ELT (targs, 0) = TREE_TYPE (init);
30852 else if (AUTO_IS_DECLTYPE (auto_node))
30854 const bool id = unparenthesized_id_or_class_member_access_p (init);
30855 tree deduced = finish_decltype_type (init, id, complain);
30856 deduced = canonicalize_type_argument (deduced, complain);
30857 if (deduced == error_mark_node)
30858 return error_mark_node;
30859 targs = make_tree_vec (1);
30860 TREE_VEC_ELT (targs, 0) = deduced;
30862 else
30864 if (error_operand_p (init))
30865 return error_mark_node;
30867 tree parms = build_tree_list (NULL_TREE, type);
30868 tree tparms;
30870 if (flag_concepts_ts)
30871 tparms = extract_autos (type);
30872 else
30874 tparms = make_tree_vec (1);
30875 TREE_VEC_ELT (tparms, 0)
30876 = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
30879 targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
30880 int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
30881 DEDUCE_CALL,
30882 NULL, /*explain_p=*/false);
30883 if (val > 0)
30885 if (processing_template_decl)
30886 /* Try again at instantiation time. */
30887 return type;
30888 if (type && type != error_mark_node
30889 && (complain & tf_error))
30890 /* If type is error_mark_node a diagnostic must have been
30891 emitted by now. Also, having a mention to '<type error>'
30892 in the diagnostic is not really useful to the user. */
30894 if (cfun
30895 && FNDECL_USED_AUTO (current_function_decl)
30896 && (auto_node
30897 == DECL_SAVED_AUTO_RETURN_TYPE (current_function_decl))
30898 && LAMBDA_FUNCTION_P (current_function_decl))
30899 error_at (loc, "unable to deduce lambda return type from %qE",
30900 init);
30901 else
30902 error_at (loc, "unable to deduce %qT from %qE", type, init);
30903 type_unification_real (tparms, targs, parms, &init, 1, 0,
30904 DEDUCE_CALL,
30905 NULL, /*explain_p=*/true);
30907 return error_mark_node;
30911 /* Check any placeholder constraints against the deduced type. */
30912 if (processing_template_decl && context == adc_unify)
30913 /* Constraints will be checked after deduction. */;
30914 else if (tree constr = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (auto_node)))
30916 if (processing_template_decl)
30918 gcc_checking_assert (context == adc_variable_type
30919 || context == adc_return_type
30920 || context == adc_decomp_type);
30921 gcc_checking_assert (!type_dependent_expression_p (init));
30922 /* If the constraint is dependent, we need to wait until
30923 instantiation time to resolve the placeholder. */
30924 if (placeholder_type_constraint_dependent_p (constr))
30925 return type;
30928 if (context == adc_return_type
30929 || context == adc_variable_type
30930 || context == adc_decomp_type)
30931 if (tree fn = current_function_decl)
30932 if (DECL_TEMPLATE_INFO (fn) || LAMBDA_FUNCTION_P (fn))
30934 outer_targs = DECL_TEMPLATE_INFO (fn)
30935 ? DECL_TI_ARGS (fn) : NULL_TREE;
30936 if (LAMBDA_FUNCTION_P (fn))
30938 /* As in satisfy_declaration_constraints. */
30939 tree regen_args = lambda_regenerating_args (fn);
30940 if (outer_targs)
30941 outer_targs = add_to_template_args (regen_args, outer_targs);
30942 else
30943 outer_targs = regen_args;
30947 tree full_targs = outer_targs;
30948 if (context == adc_unify && tmpl)
30949 full_targs = add_outermost_template_args (tmpl, full_targs);
30950 full_targs = add_to_template_args (full_targs, targs);
30952 /* HACK: Compensate for callers not always communicating all levels of
30953 outer template arguments by filling in the outermost missing levels
30954 with dummy levels before checking satisfaction. We'll still crash
30955 if the constraint depends on a template argument belonging to one of
30956 these missing levels, but this hack otherwise allows us to handle a
30957 large subset of possible constraints (including all non-dependent
30958 constraints). */
30959 if (int missing_levels = (TEMPLATE_TYPE_ORIG_LEVEL (auto_node)
30960 - TMPL_ARGS_DEPTH (full_targs)))
30962 tree dummy_levels = make_tree_vec (missing_levels);
30963 for (int i = 0; i < missing_levels; ++i)
30964 TREE_VEC_ELT (dummy_levels, i) = make_tree_vec (0);
30965 full_targs = add_to_template_args (dummy_levels, full_targs);
30968 if (!constraints_satisfied_p (auto_node, full_targs))
30970 if (complain & tf_warning_or_error)
30972 auto_diagnostic_group d;
30973 switch (context)
30975 case adc_unspecified:
30976 case adc_unify:
30977 error_at (loc, "placeholder constraints not satisfied");
30978 break;
30979 case adc_variable_type:
30980 case adc_decomp_type:
30981 error_at (loc, "deduced initializer does not satisfy "
30982 "placeholder constraints");
30983 break;
30984 case adc_return_type:
30985 error_at (loc, "deduced return type does not satisfy "
30986 "placeholder constraints");
30987 break;
30988 case adc_requirement:
30989 error_at (loc, "deduced expression type does not satisfy "
30990 "placeholder constraints");
30991 break;
30993 diagnose_constraints (loc, auto_node, full_targs);
30995 return error_mark_node;
30999 if (TEMPLATE_TYPE_LEVEL (auto_node) == 1)
31000 /* The outer template arguments are already substituted into type
31001 (but we still may have used them for constraint checking above). */;
31002 else if (context == adc_unify)
31003 targs = add_to_template_args (outer_targs, targs);
31004 else if (processing_template_decl)
31005 targs = add_to_template_args (current_template_args (), targs);
31006 return tsubst (type, targs, complain, NULL_TREE);
31009 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
31010 result. */
31012 tree
31013 splice_late_return_type (tree type, tree late_return_type)
31015 if (late_return_type)
31017 gcc_assert (is_auto (type) || seen_error ());
31018 return late_return_type;
31021 if (tree auto_node = find_type_usage (type, is_auto))
31022 if (TEMPLATE_TYPE_LEVEL (auto_node) <= current_template_depth)
31024 /* In an abbreviated function template we didn't know we were dealing
31025 with a function template when we saw the auto return type, so rebuild
31026 the return type using an auto with the correct level. */
31027 tree new_auto = make_auto_1 (TYPE_IDENTIFIER (auto_node), false);
31028 tree auto_vec = make_tree_vec (1);
31029 TREE_VEC_ELT (auto_vec, 0) = new_auto;
31030 tree targs = add_outermost_template_args (current_template_args (),
31031 auto_vec);
31032 /* Also rebuild the constraint info in terms of the new auto. */
31033 if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (auto_node))
31034 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (new_auto)
31035 = build_tree_list (current_template_parms,
31036 tsubst_constraint (TREE_VALUE (ci), targs,
31037 tf_none, NULL_TREE));
31038 TYPE_CANONICAL (new_auto) = canonical_type_parameter (new_auto);
31039 return tsubst (type, targs, tf_none, NULL_TREE);
31041 return type;
31044 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
31045 'decltype(auto)' or a deduced class template. */
31047 bool
31048 is_auto (const_tree type)
31050 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
31051 && (TYPE_IDENTIFIER (type) == auto_identifier
31052 || TYPE_IDENTIFIER (type) == decltype_auto_identifier))
31053 return true;
31054 else
31055 return false;
31058 /* for_each_template_parm callback for type_uses_auto. */
31061 is_auto_r (tree tp, void */*data*/)
31063 return is_auto (tp);
31066 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
31067 a use of `auto'. Returns NULL_TREE otherwise. */
31069 tree
31070 type_uses_auto (tree type)
31072 if (type == NULL_TREE)
31073 return NULL_TREE;
31074 else if (flag_concepts_ts)
31076 /* The Concepts TS allows multiple autos in one type-specifier; just
31077 return the first one we find, do_auto_deduction will collect all of
31078 them. */
31079 if (uses_template_parms (type))
31080 return for_each_template_parm (type, is_auto_r, /*data*/NULL,
31081 /*visited*/NULL, /*nondeduced*/false);
31082 else
31083 return NULL_TREE;
31085 else
31086 return find_type_usage (type, is_auto);
31089 /* Report ill-formed occurrences of auto types in ARGUMENTS. If
31090 concepts are enabled, auto is acceptable in template arguments, but
31091 only when TEMPL identifies a template class. Return TRUE if any
31092 such errors were reported. */
31094 bool
31095 check_auto_in_tmpl_args (tree tmpl, tree args)
31097 if (!flag_concepts_ts)
31098 /* Only the concepts TS allows 'auto' as a type-id; it'd otherwise
31099 have already been rejected by the parser more generally. */
31100 return false;
31102 /* If there were previous errors, nevermind. */
31103 if (!args || TREE_CODE (args) != TREE_VEC)
31104 return false;
31106 /* If TMPL is an identifier, we're parsing and we can't tell yet
31107 whether TMPL is supposed to be a type, a function or a variable.
31108 We'll only be able to tell during template substitution, so we
31109 expect to be called again then. If concepts are enabled and we
31110 know we have a type, we're ok. */
31111 if (identifier_p (tmpl)
31112 || (DECL_P (tmpl)
31113 && (DECL_TYPE_TEMPLATE_P (tmpl)
31114 || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))))
31115 return false;
31117 /* Quickly search for any occurrences of auto; usually there won't
31118 be any, and then we'll avoid allocating the vector. */
31119 if (!type_uses_auto (args))
31120 return false;
31122 bool errors = false;
31124 tree vec = extract_autos (args);
31125 for (int i = 0; i < TREE_VEC_LENGTH (vec); i++)
31127 tree xauto = TREE_VALUE (TREE_VEC_ELT (vec, i));
31128 error_at (DECL_SOURCE_LOCATION (xauto),
31129 "invalid use of %qT in template argument", xauto);
31130 errors = true;
31133 return errors;
31136 /* Recursively walk over && expressions searching for EXPR. Return a reference
31137 to that expression. */
31139 static tree *find_template_requirement (tree *t, tree key)
31141 if (*t == key)
31142 return t;
31143 if (TREE_CODE (*t) == TRUTH_ANDIF_EXPR)
31145 if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 0), key))
31146 return p;
31147 if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 1), key))
31148 return p;
31150 return 0;
31153 /* Convert the generic type parameters in PARM that match the types given in the
31154 range [START_IDX, END_IDX) from the current_template_parms into generic type
31155 packs. */
31157 tree
31158 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
31160 tree current = current_template_parms;
31161 int depth = TMPL_PARMS_DEPTH (current);
31162 current = INNERMOST_TEMPLATE_PARMS (current);
31163 tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
31165 for (int i = 0; i < start_idx; ++i)
31166 TREE_VEC_ELT (replacement, i)
31167 = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
31169 for (int i = start_idx; i < end_idx; ++i)
31171 /* Create a distinct parameter pack type from the current parm and add it
31172 to the replacement args to tsubst below into the generic function
31173 parameter. */
31174 tree node = TREE_VEC_ELT (current, i);
31175 tree o = TREE_TYPE (TREE_VALUE (node));
31176 tree t = copy_type (o);
31177 TEMPLATE_TYPE_PARM_INDEX (t)
31178 = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
31179 t, 0, 0, tf_none);
31180 TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
31181 TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
31182 TYPE_MAIN_VARIANT (t) = t;
31183 TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
31184 TYPE_CANONICAL (t) = canonical_type_parameter (t);
31185 TREE_VEC_ELT (replacement, i) = t;
31187 /* Replace the current template parameter with new pack. */
31188 TREE_VALUE (node) = TREE_CHAIN (t);
31190 /* Surgically adjust the associated constraint of adjusted parameter
31191 and it's corresponding contribution to the current template
31192 requirements. */
31193 if (tree constr = TEMPLATE_PARM_CONSTRAINTS (node))
31195 tree id = unpack_concept_check (constr);
31196 TREE_VEC_ELT (TREE_OPERAND (id, 1), 0) = t;
31197 tree fold = finish_left_unary_fold_expr (constr, TRUTH_ANDIF_EXPR);
31198 TEMPLATE_PARM_CONSTRAINTS (node) = fold;
31200 /* If there was a constraint, we also need to replace that in
31201 the template requirements, which we've already built. */
31202 tree *reqs = &TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
31203 reqs = find_template_requirement (reqs, constr);
31204 *reqs = fold;
31208 for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
31209 TREE_VEC_ELT (replacement, i)
31210 = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
31212 /* If there are more levels then build up the replacement with the outer
31213 template parms. */
31214 if (depth > 1)
31215 replacement = add_to_template_args (template_parms_to_args
31216 (TREE_CHAIN (current_template_parms)),
31217 replacement);
31219 return tsubst (parm, replacement, tf_none, NULL_TREE);
31222 /* __integer_pack(N) in a pack expansion expands to a sequence of numbers from
31223 0..N-1. */
31225 void
31226 declare_integer_pack (void)
31228 tree ipfn = push_library_fn (get_identifier ("__integer_pack"),
31229 build_function_type_list (integer_type_node,
31230 integer_type_node,
31231 NULL_TREE),
31232 NULL_TREE, ECF_CONST);
31233 DECL_DECLARED_CONSTEXPR_P (ipfn) = true;
31234 set_decl_built_in_function (ipfn, BUILT_IN_FRONTEND,
31235 CP_BUILT_IN_INTEGER_PACK);
31238 /* Walk the decl or type specialization table calling FN on each
31239 entry. */
31241 void
31242 walk_specializations (bool decls_p,
31243 void (*fn) (bool decls_p, spec_entry *entry, void *data),
31244 void *data)
31246 spec_hash_table *table = decls_p ? decl_specializations
31247 : type_specializations;
31248 spec_hash_table::iterator end (table->end ());
31249 for (spec_hash_table::iterator iter (table->begin ()); iter != end; ++iter)
31250 fn (decls_p, *iter, data);
31253 /* Lookup the specialization of *ELT, in the decl or type
31254 specialization table. Return the SPEC that's already there, or
31255 NULL if nothing. */
31257 tree
31258 match_mergeable_specialization (bool decl_p, spec_entry *elt)
31260 hash_table<spec_hasher> *specializations
31261 = decl_p ? decl_specializations : type_specializations;
31262 hashval_t hash = spec_hasher::hash (elt);
31263 auto *slot = specializations->find_slot_with_hash (elt, hash, NO_INSERT);
31265 if (slot)
31266 return (*slot)->spec;
31268 return NULL_TREE;
31271 /* Return flags encoding whether SPEC is on the instantiation and/or
31272 specialization lists of TMPL. */
31274 unsigned
31275 get_mergeable_specialization_flags (tree tmpl, tree decl)
31277 unsigned flags = 0;
31279 for (tree inst = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
31280 inst; inst = TREE_CHAIN (inst))
31281 if (TREE_VALUE (inst) == decl)
31283 flags |= 1;
31284 break;
31287 if (CLASS_TYPE_P (TREE_TYPE (decl))
31288 && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl))
31289 && CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)) == 2)
31290 /* Only need to search if DECL is a partial specialization. */
31291 for (tree part = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
31292 part; part = TREE_CHAIN (part))
31293 if (TREE_VALUE (part) == decl)
31295 flags |= 2;
31296 break;
31299 return flags;
31302 /* Add a new specialization described by SPEC. DECL is the
31303 maybe-template decl and FLAGS is as returned from
31304 get_mergeable_specialization_flags. */
31306 void
31307 add_mergeable_specialization (bool decl_p, bool alias_p, spec_entry *elt,
31308 tree decl, unsigned flags)
31310 hashval_t hash = spec_hasher::hash (elt);
31311 if (decl_p)
31313 auto *slot = decl_specializations->find_slot_with_hash (elt, hash, INSERT);
31315 gcc_checking_assert (!*slot);
31316 auto entry = ggc_alloc<spec_entry> ();
31317 *entry = *elt;
31318 *slot = entry;
31320 if (alias_p)
31322 elt->spec = TREE_TYPE (elt->spec);
31323 gcc_checking_assert (elt->spec);
31327 if (!decl_p || alias_p)
31329 auto *slot = type_specializations->find_slot_with_hash (elt, hash, INSERT);
31331 /* We don't distinguish different constrained partial type
31332 specializations, so there could be duplicates. Everything else
31333 must be new. */
31334 if (!(flags & 2 && *slot))
31336 gcc_checking_assert (!*slot);
31338 auto entry = ggc_alloc<spec_entry> ();
31339 *entry = *elt;
31340 *slot = entry;
31344 if (flags & 1)
31345 DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl)
31346 = tree_cons (elt->args, decl, DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl));
31348 if (flags & 2)
31350 /* A partial specialization. */
31351 tree cons = tree_cons (elt->args, decl,
31352 DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl));
31353 TREE_TYPE (cons) = decl_p ? TREE_TYPE (elt->spec) : elt->spec;
31354 DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl) = cons;
31358 /* Set up the hash tables for template instantiations. */
31360 void
31361 init_template_processing (void)
31363 decl_specializations = hash_table<spec_hasher>::create_ggc (37);
31364 type_specializations = hash_table<spec_hasher>::create_ggc (37);
31366 if (cxx_dialect >= cxx11)
31367 declare_integer_pack ();
31370 /* Print stats about the template hash tables for -fstats. */
31372 void
31373 print_template_statistics (void)
31375 fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
31376 "%f collisions\n", (long) decl_specializations->size (),
31377 (long) decl_specializations->elements (),
31378 decl_specializations->collisions ());
31379 fprintf (stderr, "type_specializations: size %ld, %ld elements, "
31380 "%f collisions\n", (long) type_specializations->size (),
31381 (long) type_specializations->elements (),
31382 type_specializations->collisions ());
31385 #if CHECKING_P
31387 namespace selftest {
31389 /* Verify that build_non_dependent_expr () works, for various expressions,
31390 and that location wrappers don't affect the results. */
31392 static void
31393 test_build_non_dependent_expr ()
31395 location_t loc = BUILTINS_LOCATION;
31397 /* Verify constants, without and with location wrappers. */
31398 tree int_cst = build_int_cst (integer_type_node, 42);
31399 ASSERT_EQ (int_cst, build_non_dependent_expr (int_cst));
31401 tree wrapped_int_cst = maybe_wrap_with_location (int_cst, loc);
31402 ASSERT_TRUE (location_wrapper_p (wrapped_int_cst));
31403 ASSERT_EQ (wrapped_int_cst, build_non_dependent_expr (wrapped_int_cst));
31405 tree string_lit = build_string (4, "foo");
31406 TREE_TYPE (string_lit) = char_array_type_node;
31407 string_lit = fix_string_type (string_lit);
31408 ASSERT_EQ (string_lit, build_non_dependent_expr (string_lit));
31410 tree wrapped_string_lit = maybe_wrap_with_location (string_lit, loc);
31411 ASSERT_TRUE (location_wrapper_p (wrapped_string_lit));
31412 ASSERT_EQ (wrapped_string_lit,
31413 build_non_dependent_expr (wrapped_string_lit));
31416 /* Verify that type_dependent_expression_p () works correctly, even
31417 in the presence of location wrapper nodes. */
31419 static void
31420 test_type_dependent_expression_p ()
31422 location_t loc = BUILTINS_LOCATION;
31424 tree name = get_identifier ("foo");
31426 /* If no templates are involved, nothing is type-dependent. */
31427 gcc_assert (!processing_template_decl);
31428 ASSERT_FALSE (type_dependent_expression_p (name));
31430 ++processing_template_decl;
31432 /* Within a template, an unresolved name is always type-dependent. */
31433 ASSERT_TRUE (type_dependent_expression_p (name));
31435 /* Ensure it copes with NULL_TREE and errors. */
31436 ASSERT_FALSE (type_dependent_expression_p (NULL_TREE));
31437 ASSERT_FALSE (type_dependent_expression_p (error_mark_node));
31439 /* A USING_DECL in a template should be type-dependent, even if wrapped
31440 with a location wrapper (PR c++/83799). */
31441 tree using_decl = build_lang_decl (USING_DECL, name, NULL_TREE);
31442 TREE_TYPE (using_decl) = integer_type_node;
31443 ASSERT_TRUE (type_dependent_expression_p (using_decl));
31444 tree wrapped_using_decl = maybe_wrap_with_location (using_decl, loc);
31445 ASSERT_TRUE (location_wrapper_p (wrapped_using_decl));
31446 ASSERT_TRUE (type_dependent_expression_p (wrapped_using_decl));
31448 --processing_template_decl;
31451 /* Run all of the selftests within this file. */
31453 void
31454 cp_pt_cc_tests ()
31456 test_build_non_dependent_expr ();
31457 test_type_dependent_expression_p ();
31460 } // namespace selftest
31462 #endif /* #if CHECKING_P */
31464 #include "gt-cp-pt.h"