c++: extend lookup_template_class shortcut [PR110122]
[official-gcc.git] / gcc / cp / pt.cc
blob2345a18becc1160b9d12f3d88cccb66c8917373c
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 for (tree cur = current_nonlambda_class_type ();
9922 cur != NULL_TREE;
9923 cur = get_containing_scope (cur))
9925 if (!CLASS_TYPE_P (cur))
9926 continue;
9928 tree ti = CLASSTYPE_TEMPLATE_INFO (cur);
9929 if (!ti || arg_depth > TMPL_ARGS_DEPTH (TI_ARGS (ti)))
9930 break;
9932 if (gen_tmpl == most_general_template (TI_TEMPLATE (ti))
9933 && comp_template_args (arglist, TI_ARGS (ti)))
9934 return cur;
9937 /* Calculate the BOUND_ARGS. These will be the args that are
9938 actually tsubst'd into the definition to create the
9939 instantiation. */
9940 if (PRIMARY_TEMPLATE_P (gen_tmpl))
9941 arglist = coerce_template_parms (parmlist, arglist, gen_tmpl, complain);
9943 if (arglist == error_mark_node)
9944 /* We were unable to bind the arguments. */
9945 return error_mark_node;
9947 /* In the scope of a template class, explicit references to the
9948 template class refer to the type of the template, not any
9949 instantiation of it. For example, in:
9951 template <class T> class C { void f(C<T>); }
9953 the `C<T>' is just the same as `C'. Outside of the
9954 class, however, such a reference is an instantiation. */
9955 if (entering_scope
9956 || !PRIMARY_TEMPLATE_P (gen_tmpl)
9957 || currently_open_class (template_type))
9959 tree tinfo = TYPE_TEMPLATE_INFO (template_type);
9961 if (tinfo && comp_template_args (TI_ARGS (tinfo), arglist))
9962 return template_type;
9965 /* If we already have this specialization, return it. */
9966 elt.tmpl = gen_tmpl;
9967 elt.args = arglist;
9968 elt.spec = NULL_TREE;
9969 hash = spec_hasher::hash (&elt);
9970 entry = type_specializations->find_with_hash (&elt, hash);
9972 if (entry)
9973 return entry->spec;
9975 /* If the template's constraints are not satisfied,
9976 then we cannot form a valid type.
9978 Note that the check is deferred until after the hash
9979 lookup. This prevents redundant checks on previously
9980 instantiated specializations. */
9981 if (flag_concepts
9982 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl)
9983 && !constraints_satisfied_p (gen_tmpl, arglist))
9985 if (complain & tf_error)
9987 auto_diagnostic_group d;
9988 error ("template constraint failure for %qD", gen_tmpl);
9989 diagnose_constraints (input_location, gen_tmpl, arglist);
9991 return error_mark_node;
9994 is_dependent_type = uses_template_parms (arglist);
9996 /* If the deduced arguments are invalid, then the binding
9997 failed. */
9998 if (!is_dependent_type
9999 && check_instantiated_args (gen_tmpl,
10000 INNERMOST_TEMPLATE_ARGS (arglist),
10001 complain))
10002 return error_mark_node;
10004 if (!is_dependent_type
10005 && !PRIMARY_TEMPLATE_P (gen_tmpl)
10006 && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
10007 && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
10008 /* This occurs when the user has tried to define a tagged type
10009 in a scope that forbids it. We emitted an error during the
10010 parse. We didn't complete the bail out then, so here we
10011 are. */
10012 return error_mark_node;
10014 context = DECL_CONTEXT (gen_tmpl);
10015 if (context && TYPE_P (context))
10017 if (!uses_template_parms (DECL_CONTEXT (templ)))
10018 /* If the context of the partially instantiated template is
10019 already non-dependent, then we might as well use it. */
10020 context = DECL_CONTEXT (templ);
10021 else
10023 context = tsubst_aggr_type (context, arglist,
10024 complain, in_decl, true);
10025 /* Try completing the enclosing context if it's not already so. */
10026 if (context != error_mark_node
10027 && !COMPLETE_TYPE_P (context))
10029 context = complete_type (context);
10030 if (COMPLETE_TYPE_P (context))
10032 /* Completion could have caused us to register the desired
10033 specialization already, so check the table again. */
10034 entry = type_specializations->find_with_hash (&elt, hash);
10035 if (entry)
10036 return entry->spec;
10041 else
10042 context = tsubst (context, arglist, complain, in_decl);
10044 if (context == error_mark_node)
10045 return error_mark_node;
10047 if (!context)
10048 context = global_namespace;
10050 /* Create the type. */
10051 if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10053 /* The user referred to a specialization of an alias
10054 template represented by GEN_TMPL.
10056 [temp.alias]/2 says:
10058 When a template-id refers to the specialization of an
10059 alias template, it is equivalent to the associated
10060 type obtained by substitution of its
10061 template-arguments for the template-parameters in the
10062 type-id of the alias template. */
10064 t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
10065 /* Note that the call above (by indirectly calling
10066 register_specialization in tsubst_decl) registers the
10067 TYPE_DECL representing the specialization of the alias
10068 template. So next time someone substitutes ARGLIST for
10069 the template parms into the alias template (GEN_TMPL),
10070 she'll get that TYPE_DECL back. */
10072 if (t == error_mark_node)
10073 return t;
10075 else if (TREE_CODE (template_type) == ENUMERAL_TYPE)
10077 if (!is_dependent_type)
10079 set_current_access_from_decl (TYPE_NAME (template_type));
10080 t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
10081 tsubst (ENUM_UNDERLYING_TYPE (template_type),
10082 arglist, complain, in_decl),
10083 tsubst_attributes (TYPE_ATTRIBUTES (template_type),
10084 arglist, complain, in_decl),
10085 SCOPED_ENUM_P (template_type), NULL);
10087 if (t == error_mark_node)
10088 return t;
10090 else
10092 /* We don't want to call start_enum for this type, since
10093 the values for the enumeration constants may involve
10094 template parameters. And, no one should be interested
10095 in the enumeration constants for such a type. */
10096 t = cxx_make_type (ENUMERAL_TYPE);
10097 SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
10099 SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
10100 ENUM_FIXED_UNDERLYING_TYPE_P (t)
10101 = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
10103 else if (CLASS_TYPE_P (template_type))
10105 /* Lambda closures are regenerated in tsubst_lambda_expr, not
10106 instantiated here. */
10107 gcc_assert (!LAMBDA_TYPE_P (template_type));
10109 t = make_class_type (TREE_CODE (template_type));
10110 CLASSTYPE_DECLARED_CLASS (t)
10111 = CLASSTYPE_DECLARED_CLASS (template_type);
10112 SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
10114 /* A local class. Make sure the decl gets registered properly. */
10115 if (context == current_function_decl)
10116 if (pushtag (DECL_NAME (gen_tmpl), t)
10117 == error_mark_node)
10118 return error_mark_node;
10120 if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
10121 /* This instantiation is another name for the primary
10122 template type. Set the TYPE_CANONICAL field
10123 appropriately. */
10124 TYPE_CANONICAL (t) = template_type;
10125 else if (any_template_arguments_need_structural_equality_p (arglist))
10126 SET_TYPE_STRUCTURAL_EQUALITY (t);
10128 else
10129 gcc_unreachable ();
10131 /* If we called start_enum or pushtag above, this information
10132 will already be set up. */
10133 type_decl = TYPE_NAME (t);
10134 if (!type_decl)
10136 TYPE_CONTEXT (t) = FROB_CONTEXT (context);
10138 type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
10139 DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
10140 DECL_SOURCE_LOCATION (type_decl)
10141 = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
10144 set_instantiating_module (type_decl);
10145 /* Although GEN_TMPL is the TEMPLATE_DECL, it has the same value
10146 of export flag. We want to propagate this because it might
10147 be a friend declaration that pushes a new hidden binding. */
10148 DECL_MODULE_EXPORT_P (type_decl) = DECL_MODULE_EXPORT_P (gen_tmpl);
10150 if (CLASS_TYPE_P (template_type))
10152 TREE_PRIVATE (type_decl)
10153 = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
10154 TREE_PROTECTED (type_decl)
10155 = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
10156 if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
10158 DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
10159 DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
10163 if (OVERLOAD_TYPE_P (t)
10164 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10166 static const char *tags[] = {"abi_tag", "may_alias"};
10168 for (unsigned ix = 0; ix != 2; ix++)
10170 tree attributes
10171 = lookup_attribute (tags[ix], TYPE_ATTRIBUTES (template_type));
10173 if (attributes)
10174 TYPE_ATTRIBUTES (t)
10175 = tree_cons (TREE_PURPOSE (attributes),
10176 TREE_VALUE (attributes),
10177 TYPE_ATTRIBUTES (t));
10181 /* Let's consider the explicit specialization of a member
10182 of a class template specialization that is implicitly instantiated,
10183 e.g.:
10184 template<class T>
10185 struct S
10187 template<class U> struct M {}; //#0
10190 template<>
10191 template<>
10192 struct S<int>::M<char> //#1
10194 int i;
10196 [temp.expl.spec]/4 says this is valid.
10198 In this case, when we write:
10199 S<int>::M<char> m;
10201 M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
10202 the one of #0.
10204 When we encounter #1, we want to store the partial instantiation
10205 of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
10207 For all cases other than this "explicit specialization of member of a
10208 class template", we just want to store the most general template into
10209 the CLASSTYPE_TI_TEMPLATE of M.
10211 This case of "explicit specialization of member of a class template"
10212 only happens when:
10213 1/ the enclosing class is an instantiation of, and therefore not
10214 the same as, the context of the most general template, and
10215 2/ we aren't looking at the partial instantiation itself, i.e.
10216 the innermost arguments are not the same as the innermost parms of
10217 the most general template.
10219 So it's only when 1/ and 2/ happens that we want to use the partial
10220 instantiation of the member template in lieu of its most general
10221 template. */
10223 if (PRIMARY_TEMPLATE_P (gen_tmpl)
10224 && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
10225 /* the enclosing class must be an instantiation... */
10226 && CLASS_TYPE_P (context)
10227 && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
10229 TREE_VEC_LENGTH (arglist)--;
10230 ++processing_template_decl;
10231 tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (gen_tmpl));
10232 tree partial_inst_args =
10233 tsubst (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)),
10234 arglist, complain, NULL_TREE);
10235 --processing_template_decl;
10236 TREE_VEC_LENGTH (arglist)++;
10237 if (partial_inst_args == error_mark_node)
10238 return error_mark_node;
10239 use_partial_inst_tmpl =
10240 /*...and we must not be looking at the partial instantiation
10241 itself. */
10242 !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
10243 partial_inst_args);
10246 if (!use_partial_inst_tmpl)
10247 /* This case is easy; there are no member templates involved. */
10248 found = gen_tmpl;
10249 else
10251 /* This is a full instantiation of a member template. Find
10252 the partial instantiation of which this is an instance. */
10254 /* Temporarily reduce by one the number of levels in the ARGLIST
10255 so as to avoid comparing the last set of arguments. */
10256 TREE_VEC_LENGTH (arglist)--;
10257 /* We don't use COMPLAIN in the following call because this isn't
10258 the immediate context of deduction. For instance, tf_partial
10259 could be set here as we might be at the beginning of template
10260 argument deduction when any explicitly specified template
10261 arguments are substituted into the function type. tf_partial
10262 could lead into trouble because we wouldn't find the partial
10263 instantiation that might have been created outside tf_partial
10264 context, because the levels of template parameters wouldn't
10265 match, because in a tf_partial context, tsubst doesn't reduce
10266 TEMPLATE_PARM_LEVEL. */
10267 found = tsubst (gen_tmpl, arglist, tf_none, NULL_TREE);
10268 TREE_VEC_LENGTH (arglist)++;
10269 /* FOUND is either a proper class type, or an alias
10270 template specialization. In the later case, it's a
10271 TYPE_DECL, resulting from the substituting of arguments
10272 for parameters in the TYPE_DECL of the alias template
10273 done earlier. So be careful while getting the template
10274 of FOUND. */
10275 found = (TREE_CODE (found) == TEMPLATE_DECL
10276 ? found
10277 : (TREE_CODE (found) == TYPE_DECL
10278 ? DECL_TI_TEMPLATE (found)
10279 : CLASSTYPE_TI_TEMPLATE (found)));
10281 if (DECL_CLASS_TEMPLATE_P (found)
10282 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (found)))
10284 /* If this partial instantiation is specialized, we want to
10285 use it for hash table lookup. */
10286 elt.tmpl = found;
10287 elt.args = arglist = INNERMOST_TEMPLATE_ARGS (arglist);
10288 hash = spec_hasher::hash (&elt);
10292 /* Build template info for the new specialization. */
10293 SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
10295 elt.spec = t;
10296 slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
10297 gcc_checking_assert (*slot == NULL);
10298 entry = ggc_alloc<spec_entry> ();
10299 *entry = elt;
10300 *slot = entry;
10302 /* Note this use of the partial instantiation so we can check it
10303 later in maybe_process_partial_specialization. */
10304 DECL_TEMPLATE_INSTANTIATIONS (found)
10305 = tree_cons (arglist, t,
10306 DECL_TEMPLATE_INSTANTIATIONS (found));
10308 if (TREE_CODE (template_type) == ENUMERAL_TYPE
10309 && !uses_template_parms (current_nonlambda_scope ())
10310 && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10311 /* Now that the type has been registered on the instantiations
10312 list, we set up the enumerators. Because the enumeration
10313 constants may involve the enumeration type itself, we make
10314 sure to register the type first, and then create the
10315 constants. That way, doing tsubst_expr for the enumeration
10316 constants won't result in recursive calls here; we'll find
10317 the instantiation and exit above. */
10318 tsubst_enum (template_type, t, arglist);
10320 if (CLASS_TYPE_P (template_type) && is_dependent_type)
10321 /* If the type makes use of template parameters, the
10322 code that generates debugging information will crash. */
10323 DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
10325 /* Possibly limit visibility based on template args. */
10326 TREE_PUBLIC (type_decl) = 1;
10327 determine_visibility (type_decl);
10329 inherit_targ_abi_tags (t);
10331 return t;
10335 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST. */
10337 tree
10338 lookup_template_variable (tree templ, tree arglist)
10340 if (flag_concepts && variable_concept_p (templ))
10341 return build_concept_check (templ, arglist, tf_none);
10343 /* The type of the expression is NULL_TREE since the template-id could refer
10344 to an explicit or partial specialization. */
10345 return build2 (TEMPLATE_ID_EXPR, NULL_TREE, templ, arglist);
10348 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR if it's
10349 not dependent. */
10351 tree
10352 finish_template_variable (tree var, tsubst_flags_t complain)
10354 tree templ = TREE_OPERAND (var, 0);
10355 tree arglist = TREE_OPERAND (var, 1);
10357 /* If the template or arguments are dependent, then we
10358 can't resolve the TEMPLATE_ID_EXPR yet. */
10359 if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (templ)) != 1
10360 || any_dependent_template_arguments_p (arglist))
10361 return var;
10363 tree parms = DECL_TEMPLATE_PARMS (templ);
10364 arglist = coerce_template_parms (parms, arglist, templ, complain);
10365 if (arglist == error_mark_node)
10366 return error_mark_node;
10368 if (flag_concepts && !constraints_satisfied_p (templ, arglist))
10370 if (complain & tf_error)
10372 auto_diagnostic_group d;
10373 error ("use of invalid variable template %qE", var);
10374 diagnose_constraints (location_of (var), templ, arglist);
10376 return error_mark_node;
10379 return instantiate_template (templ, arglist, complain);
10382 /* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
10383 TARGS template args, and instantiate it if it's not dependent. */
10385 tree
10386 lookup_and_finish_template_variable (tree templ, tree targs,
10387 tsubst_flags_t complain)
10389 tree var = lookup_template_variable (templ, targs);
10390 /* We may be called while doing a partial substitution, but the
10391 type of the variable template may be auto, in which case we
10392 will call do_auto_deduction in mark_used (which clears tf_partial)
10393 and the auto must be properly reduced at that time for the
10394 deduction to work. */
10395 complain &= ~tf_partial;
10396 var = finish_template_variable (var, complain);
10397 mark_used (var);
10398 return var;
10401 /* If the set of template parameters PARMS contains a template parameter
10402 at the given LEVEL and INDEX, then return this parameter. Otherwise
10403 return NULL_TREE. */
10405 static tree
10406 corresponding_template_parameter_list (tree parms, int level, int index)
10408 while (TMPL_PARMS_DEPTH (parms) > level)
10409 parms = TREE_CHAIN (parms);
10411 if (TMPL_PARMS_DEPTH (parms) != level
10412 || TREE_VEC_LENGTH (TREE_VALUE (parms)) <= index)
10413 return NULL_TREE;
10415 return TREE_VEC_ELT (TREE_VALUE (parms), index);
10418 /* Return the TREE_LIST for the template parameter from PARMS that positionally
10419 corresponds to the template parameter PARM, or else return NULL_TREE. */
10421 static tree
10422 corresponding_template_parameter_list (tree parms, tree parm)
10424 int level, index;
10425 template_parm_level_and_index (parm, &level, &index);
10426 return corresponding_template_parameter_list (parms, level, index);
10429 /* As above, but pull out the actual parameter. */
10431 static tree
10432 corresponding_template_parameter (tree parms, tree parm)
10434 tree list = corresponding_template_parameter_list (parms, parm);
10435 if (!list)
10436 return NULL_TREE;
10438 tree t = TREE_VALUE (list);
10439 /* As in template_parm_to_arg. */
10440 if (TREE_CODE (t) == TYPE_DECL || TREE_CODE (t) == TEMPLATE_DECL)
10441 t = TREE_TYPE (t);
10442 else
10443 t = DECL_INITIAL (t);
10445 gcc_assert (TEMPLATE_PARM_P (t));
10446 return t;
10449 struct pair_fn_data
10451 tree_fn_t fn;
10452 tree_fn_t any_fn;
10453 void *data;
10454 /* True when we should also visit template parameters that occur in
10455 non-deduced contexts. */
10456 bool include_nondeduced_p;
10457 hash_set<tree> *visited;
10460 /* Called from for_each_template_parm via walk_tree. */
10462 static tree
10463 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
10465 tree t = *tp;
10466 struct pair_fn_data *pfd = (struct pair_fn_data *) d;
10467 tree_fn_t fn = pfd->fn;
10468 void *data = pfd->data;
10469 tree result = NULL_TREE;
10471 #define WALK_SUBTREE(NODE) \
10472 do \
10474 result = for_each_template_parm (NODE, fn, data, pfd->visited, \
10475 pfd->include_nondeduced_p, \
10476 pfd->any_fn); \
10477 if (result) goto out; \
10479 while (0)
10481 if (pfd->any_fn && (*pfd->any_fn)(t, data))
10482 return t;
10484 if (TYPE_P (t)
10485 && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
10486 WALK_SUBTREE (TYPE_CONTEXT (t));
10488 switch (TREE_CODE (t))
10490 case RECORD_TYPE:
10491 if (TYPE_PTRMEMFUNC_P (t))
10492 break;
10493 /* Fall through. */
10495 case UNION_TYPE:
10496 case ENUMERAL_TYPE:
10497 if (!TYPE_TEMPLATE_INFO (t))
10498 *walk_subtrees = 0;
10499 else
10500 WALK_SUBTREE (TYPE_TI_ARGS (t));
10501 break;
10503 case INTEGER_TYPE:
10504 WALK_SUBTREE (TYPE_MIN_VALUE (t));
10505 WALK_SUBTREE (TYPE_MAX_VALUE (t));
10506 break;
10508 case METHOD_TYPE:
10509 /* Since we're not going to walk subtrees, we have to do this
10510 explicitly here. */
10511 WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
10512 /* Fall through. */
10514 case FUNCTION_TYPE:
10515 /* Check the return type. */
10516 WALK_SUBTREE (TREE_TYPE (t));
10518 /* Check the parameter types. Since default arguments are not
10519 instantiated until they are needed, the TYPE_ARG_TYPES may
10520 contain expressions that involve template parameters. But,
10521 no-one should be looking at them yet. And, once they're
10522 instantiated, they don't contain template parameters, so
10523 there's no point in looking at them then, either. */
10525 tree parm;
10527 for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
10528 WALK_SUBTREE (TREE_VALUE (parm));
10530 /* Since we've already handled the TYPE_ARG_TYPES, we don't
10531 want walk_tree walking into them itself. */
10532 *walk_subtrees = 0;
10535 if (flag_noexcept_type)
10537 tree spec = TYPE_RAISES_EXCEPTIONS (t);
10538 if (spec)
10539 WALK_SUBTREE (TREE_PURPOSE (spec));
10541 break;
10543 case TYPEOF_TYPE:
10544 case DECLTYPE_TYPE:
10545 if (pfd->include_nondeduced_p
10546 && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
10547 pfd->visited,
10548 pfd->include_nondeduced_p,
10549 pfd->any_fn))
10550 return error_mark_node;
10551 *walk_subtrees = false;
10552 break;
10554 case TRAIT_TYPE:
10555 if (pfd->include_nondeduced_p)
10557 WALK_SUBTREE (TRAIT_TYPE_TYPE1 (t));
10558 WALK_SUBTREE (TRAIT_TYPE_TYPE2 (t));
10560 *walk_subtrees = false;
10561 break;
10563 case FUNCTION_DECL:
10564 case VAR_DECL:
10565 if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10566 WALK_SUBTREE (DECL_TI_ARGS (t));
10567 break;
10569 case PARM_DECL:
10570 WALK_SUBTREE (TREE_TYPE (t));
10571 break;
10573 case CONST_DECL:
10574 if (DECL_TEMPLATE_PARM_P (t))
10575 WALK_SUBTREE (DECL_INITIAL (t));
10576 if (DECL_CONTEXT (t)
10577 && pfd->include_nondeduced_p)
10578 WALK_SUBTREE (DECL_CONTEXT (t));
10579 break;
10581 case BOUND_TEMPLATE_TEMPLATE_PARM:
10582 /* Record template parameters such as `T' inside `TT<T>'. */
10583 WALK_SUBTREE (TYPE_TI_ARGS (t));
10584 /* Fall through. */
10586 case TEMPLATE_TEMPLATE_PARM:
10587 case TEMPLATE_TYPE_PARM:
10588 case TEMPLATE_PARM_INDEX:
10589 if (fn && (*fn)(t, data))
10590 return t;
10591 else if (!fn)
10592 return t;
10593 break;
10595 case TEMPLATE_DECL:
10596 /* A template template parameter is encountered. */
10597 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10598 WALK_SUBTREE (TREE_TYPE (t));
10600 /* Already substituted template template parameter */
10601 *walk_subtrees = 0;
10602 break;
10604 case TYPENAME_TYPE:
10605 /* A template-id in a TYPENAME_TYPE might be a deduced context after
10606 partial instantiation. */
10607 WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
10608 *walk_subtrees = 0;
10609 break;
10611 case INDIRECT_REF:
10612 case COMPONENT_REF:
10613 /* If there's no type, then this thing must be some expression
10614 involving template parameters. */
10615 if (!fn && !TREE_TYPE (t))
10616 return error_mark_node;
10617 break;
10619 case CONSTRUCTOR:
10620 case TRAIT_EXPR:
10621 case PLUS_EXPR:
10622 case MULT_EXPR:
10623 case SCOPE_REF:
10624 /* These are non-deduced contexts. */
10625 if (!pfd->include_nondeduced_p)
10626 *walk_subtrees = 0;
10627 break;
10629 case MODOP_EXPR:
10630 case CAST_EXPR:
10631 case IMPLICIT_CONV_EXPR:
10632 case REINTERPRET_CAST_EXPR:
10633 case CONST_CAST_EXPR:
10634 case STATIC_CAST_EXPR:
10635 case DYNAMIC_CAST_EXPR:
10636 case ARROW_EXPR:
10637 case DOTSTAR_EXPR:
10638 case TYPEID_EXPR:
10639 case PSEUDO_DTOR_EXPR:
10640 if (!fn)
10641 return error_mark_node;
10642 break;
10644 default:
10645 break;
10648 #undef WALK_SUBTREE
10650 /* We didn't find any template parameters we liked. */
10651 out:
10652 return result;
10655 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
10656 BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
10657 call FN with the parameter and the DATA.
10658 If FN returns nonzero, the iteration is terminated, and
10659 for_each_template_parm returns 1. Otherwise, the iteration
10660 continues. If FN never returns a nonzero value, the value
10661 returned by for_each_template_parm is 0. If FN is NULL, it is
10662 considered to be the function which always returns 1.
10664 If INCLUDE_NONDEDUCED_P, then this routine will also visit template
10665 parameters that occur in non-deduced contexts. When false, only
10666 visits those template parameters that can be deduced. */
10668 static tree
10669 for_each_template_parm (tree t, tree_fn_t fn, void* data,
10670 hash_set<tree> *visited,
10671 bool include_nondeduced_p,
10672 tree_fn_t any_fn)
10674 struct pair_fn_data pfd;
10675 tree result;
10677 /* Set up. */
10678 pfd.fn = fn;
10679 pfd.any_fn = any_fn;
10680 pfd.data = data;
10681 pfd.include_nondeduced_p = include_nondeduced_p;
10683 /* Walk the tree. (Conceptually, we would like to walk without
10684 duplicates, but for_each_template_parm_r recursively calls
10685 for_each_template_parm, so we would need to reorganize a fair
10686 bit to use walk_tree_without_duplicates, so we keep our own
10687 visited list.) */
10688 if (visited)
10689 pfd.visited = visited;
10690 else
10691 pfd.visited = new hash_set<tree>;
10692 result = cp_walk_tree (&t,
10693 for_each_template_parm_r,
10694 &pfd,
10695 pfd.visited);
10697 /* Clean up. */
10698 if (!visited)
10700 delete pfd.visited;
10701 pfd.visited = 0;
10704 return result;
10707 struct find_template_parameter_info
10709 explicit find_template_parameter_info (tree ctx_parms)
10710 : ctx_parms (ctx_parms),
10711 max_depth (TMPL_PARMS_DEPTH (ctx_parms))
10714 hash_set<tree> visited;
10715 hash_set<tree> parms;
10716 tree parm_list = NULL_TREE;
10717 tree *parm_list_tail = &parm_list;
10718 tree ctx_parms;
10719 int max_depth;
10721 tree find_in (tree);
10722 tree find_in_recursive (tree);
10723 bool found (tree);
10724 unsigned num_found () { return parms.elements (); }
10727 /* Appends the declaration of T to the list in DATA. */
10729 static int
10730 keep_template_parm (tree t, void* data)
10732 find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10734 /* Template parameters declared within the expression are not part of
10735 the parameter mapping. For example, in this concept:
10737 template<typename T>
10738 concept C = requires { <expr> } -> same_as<int>;
10740 the return specifier same_as<int> declares a new decltype parameter
10741 that must not be part of the parameter mapping. The same is true
10742 for generic lambda parameters, lambda template parameters, etc. */
10743 int level;
10744 int index;
10745 template_parm_level_and_index (t, &level, &index);
10746 if (level == 0 || level > ftpi->max_depth)
10747 return 0;
10749 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10750 /* We want the underlying TEMPLATE_TEMPLATE_PARM, not the
10751 BOUND_TEMPLATE_TEMPLATE_PARM itself. */
10752 t = TREE_TYPE (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (t));
10754 /* This template parameter might be an argument to a cached dependent
10755 specalization that was formed earlier inside some other template, in
10756 which case the parameter is not among the ones that are in-scope.
10757 Look in CTX_PARMS to find the corresponding in-scope template
10758 parameter, and use it instead. */
10759 if (tree in_scope = corresponding_template_parameter (ftpi->ctx_parms, t))
10760 t = in_scope;
10762 /* Arguments like const T yield parameters like const T. This means that
10763 a template-id like X<T, const T> would yield two distinct parameters:
10764 T and const T. Adjust types to their unqualified versions. */
10765 if (TYPE_P (t))
10766 t = TYPE_MAIN_VARIANT (t);
10767 if (!ftpi->parms.add (t))
10769 /* Append T to PARM_LIST. */
10770 tree node = build_tree_list (NULL_TREE, t);
10771 *ftpi->parm_list_tail = node;
10772 ftpi->parm_list_tail = &TREE_CHAIN (node);
10775 /* Verify the parameter we found has a valid index. */
10776 if (flag_checking)
10778 tree parms = ftpi->ctx_parms;
10779 while (TMPL_PARMS_DEPTH (parms) > level)
10780 parms = TREE_CHAIN (parms);
10781 if (int len = TREE_VEC_LENGTH (TREE_VALUE (parms)))
10782 gcc_assert (index < len);
10785 return 0;
10788 /* Ensure that we recursively examine certain terms that are not normally
10789 visited in for_each_template_parm_r. */
10791 static int
10792 any_template_parm_r (tree t, void *data)
10794 find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10796 #define WALK_SUBTREE(NODE) \
10797 do \
10799 for_each_template_parm (NODE, keep_template_parm, data, \
10800 &ftpi->visited, true, \
10801 any_template_parm_r); \
10803 while (0)
10805 /* A mention of a member alias/typedef is a use of all of its template
10806 arguments, including those from the enclosing class, so we don't use
10807 alias_template_specialization_p here. */
10808 if (TYPE_P (t) && typedef_variant_p (t))
10809 if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
10810 WALK_SUBTREE (TI_ARGS (tinfo));
10812 switch (TREE_CODE (t))
10814 case TEMPLATE_TYPE_PARM:
10815 /* Type constraints of a placeholder type may contain parameters. */
10816 if (is_auto (t))
10817 if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
10818 WALK_SUBTREE (constr);
10819 break;
10821 case TEMPLATE_ID_EXPR:
10822 /* Search through references to variable templates. */
10823 WALK_SUBTREE (TREE_OPERAND (t, 0));
10824 WALK_SUBTREE (TREE_OPERAND (t, 1));
10825 break;
10827 case TEMPLATE_PARM_INDEX:
10828 WALK_SUBTREE (TREE_TYPE (t));
10829 break;
10831 case TEMPLATE_DECL:
10832 /* If T is a member template that shares template parameters with
10833 ctx_parms, we need to mark all those parameters for mapping.
10834 To that end, it should suffice to just walk the DECL_CONTEXT of
10835 the template (assuming the template is not overly general). */
10836 WALK_SUBTREE (DECL_CONTEXT (t));
10837 break;
10839 case LAMBDA_EXPR:
10841 /* Look in the parms and body. */
10842 tree fn = lambda_function (t);
10843 WALK_SUBTREE (TREE_TYPE (fn));
10844 WALK_SUBTREE (DECL_SAVED_TREE (fn));
10846 break;
10848 case IDENTIFIER_NODE:
10849 if (IDENTIFIER_CONV_OP_P (t))
10850 /* The conversion-type-id of a conversion operator may be dependent. */
10851 WALK_SUBTREE (TREE_TYPE (t));
10852 break;
10854 case CONVERT_EXPR:
10855 if (is_dummy_object (t))
10856 WALK_SUBTREE (TREE_TYPE (t));
10857 break;
10859 default:
10860 break;
10863 /* Keep walking. */
10864 return 0;
10867 /* Look through T for template parameters. */
10869 tree
10870 find_template_parameter_info::find_in (tree t)
10872 return for_each_template_parm (t, keep_template_parm, this, &visited,
10873 /*include_nondeduced*/true,
10874 any_template_parm_r);
10877 /* As above, but also recursively look into the default arguments of template
10878 parameters we found. Used for alias CTAD. */
10880 tree
10881 find_template_parameter_info::find_in_recursive (tree t)
10883 if (tree r = find_in (t))
10884 return r;
10885 /* Since newly found parms are added to the end of the list, we
10886 can just walk it until we reach the end. */
10887 for (tree pl = parm_list; pl; pl = TREE_CHAIN (pl))
10889 tree parm = TREE_VALUE (pl);
10890 tree list = corresponding_template_parameter_list (ctx_parms, parm);
10891 if (tree r = find_in (TREE_PURPOSE (list)))
10892 return r;
10894 return NULL_TREE;
10897 /* True if PARM was found by a previous call to find_in. PARM can be a
10898 TREE_LIST, a DECL_TEMPLATE_PARM_P, or a TEMPLATE_PARM_P. */
10900 bool
10901 find_template_parameter_info::found (tree parm)
10903 if (TREE_CODE (parm) == TREE_LIST)
10904 parm = TREE_VALUE (parm);
10905 if (TREE_CODE (parm) == TYPE_DECL)
10906 parm = TREE_TYPE (parm);
10907 else
10908 parm = DECL_INITIAL (parm);
10909 gcc_checking_assert (TEMPLATE_PARM_P (parm));
10910 return parms.contains (parm);
10913 /* Returns a list of unique template parameters found within T, where CTX_PARMS
10914 are the template parameters in scope. */
10916 tree
10917 find_template_parameters (tree t, tree ctx_parms)
10919 if (!ctx_parms)
10920 return NULL_TREE;
10922 find_template_parameter_info ftpi (ctx_parms);
10923 ftpi.find_in (t);
10924 return ftpi.parm_list;
10927 /* Returns true if T depends on any template parameter. */
10929 bool
10930 uses_template_parms (tree t)
10932 if (t == NULL_TREE || t == error_mark_node)
10933 return false;
10935 /* Namespaces can't depend on any template parameters. */
10936 if (TREE_CODE (t) == NAMESPACE_DECL)
10937 return false;
10939 processing_template_decl_sentinel ptds (/*reset*/false);
10940 ++processing_template_decl;
10942 if (TYPE_P (t))
10943 return dependent_type_p (t);
10944 else if (TREE_CODE (t) == TREE_VEC)
10945 return any_dependent_template_arguments_p (t);
10946 else if (TREE_CODE (t) == TREE_LIST)
10947 return (uses_template_parms (TREE_VALUE (t))
10948 || uses_template_parms (TREE_CHAIN (t)));
10949 else if (TREE_CODE (t) == TYPE_DECL)
10950 return dependent_type_p (TREE_TYPE (t));
10951 else
10952 return instantiation_dependent_expression_p (t);
10955 /* Returns true if T depends on any template parameter with level LEVEL. */
10957 bool
10958 uses_template_parms_level (tree t, int level)
10960 return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
10961 /*include_nondeduced_p=*/true);
10964 /* Returns true if the signature of DECL depends on any template parameter from
10965 its enclosing class. */
10967 static bool
10968 uses_outer_template_parms (tree decl)
10970 int depth = template_class_depth (CP_DECL_CONTEXT (decl));
10971 if (depth == 0)
10972 return false;
10973 if (for_each_template_parm (TREE_TYPE (decl), template_parm_outer_level,
10974 &depth, NULL, /*include_nondeduced_p=*/true))
10975 return true;
10976 if (PRIMARY_TEMPLATE_P (decl)
10977 || DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
10979 tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (decl));
10980 for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
10982 tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
10983 tree defarg = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
10984 if (TREE_CODE (parm) == PARM_DECL
10985 && for_each_template_parm (TREE_TYPE (parm),
10986 template_parm_outer_level,
10987 &depth, NULL, /*nondeduced*/true))
10988 return true;
10989 if (TREE_CODE (parm) == TEMPLATE_DECL
10990 && uses_outer_template_parms (parm))
10991 return true;
10992 if (defarg
10993 && for_each_template_parm (defarg, template_parm_outer_level,
10994 &depth, NULL, /*nondeduced*/true))
10995 return true;
10998 if (uses_outer_template_parms_in_constraints (decl))
10999 return true;
11000 return false;
11003 /* Returns true if the constraints of DECL depend on any template parameters
11004 from its enclosing scope. */
11006 bool
11007 uses_outer_template_parms_in_constraints (tree decl)
11009 tree ci = get_constraints (decl);
11010 if (ci)
11011 ci = CI_ASSOCIATED_CONSTRAINTS (ci);
11012 if (!ci)
11013 return false;
11014 int depth = template_class_depth (CP_DECL_CONTEXT (decl));
11015 if (depth == 0)
11016 return false;
11017 return for_each_template_parm (ci, template_parm_outer_level,
11018 &depth, NULL, /*nondeduced*/true);
11021 /* Returns TRUE iff INST is an instantiation we don't need to do in an
11022 ill-formed translation unit, i.e. a variable or function that isn't
11023 usable in a constant expression. */
11025 static inline bool
11026 neglectable_inst_p (tree d)
11028 return (d && DECL_P (d)
11029 && !undeduced_auto_decl (d)
11030 && !(TREE_CODE (d) == FUNCTION_DECL
11031 ? FNDECL_MANIFESTLY_CONST_EVALUATED (d)
11032 : decl_maybe_constant_var_p (d)));
11035 /* Returns TRUE iff we should refuse to instantiate DECL because it's
11036 neglectable and instantiated from within an erroneous instantiation. */
11038 static bool
11039 limit_bad_template_recursion (tree decl)
11041 struct tinst_level *lev = current_tinst_level;
11042 int errs = errorcount + sorrycount;
11043 if (errs == 0 || !neglectable_inst_p (decl))
11044 return false;
11046 /* Avoid instantiating members of an ill-formed class. */
11047 bool refuse
11048 = (DECL_CLASS_SCOPE_P (decl)
11049 && CLASSTYPE_ERRONEOUS (DECL_CONTEXT (decl)));
11051 if (!refuse)
11053 for (; lev; lev = lev->next)
11054 if (neglectable_inst_p (lev->maybe_get_node ()))
11055 break;
11056 refuse = (lev && errs > lev->errors);
11059 if (refuse)
11061 /* Don't warn about it not being defined. */
11062 suppress_warning (decl, OPT_Wunused);
11063 tree clone;
11064 FOR_EACH_CLONE (clone, decl)
11065 suppress_warning (clone, OPT_Wunused);
11067 return refuse;
11070 static int tinst_depth;
11071 extern int max_tinst_depth;
11072 int depth_reached;
11074 static GTY(()) struct tinst_level *last_error_tinst_level;
11076 /* We're starting to instantiate D; record the template instantiation context
11077 at LOC for diagnostics and to restore it later. */
11079 bool
11080 push_tinst_level_loc (tree tldcl, tree targs, location_t loc)
11082 struct tinst_level *new_level;
11084 if (tinst_depth >= max_tinst_depth)
11086 /* Tell error.cc not to try to instantiate any templates. */
11087 at_eof = 2;
11088 fatal_error (input_location,
11089 "template instantiation depth exceeds maximum of %d"
11090 " (use %<-ftemplate-depth=%> to increase the maximum)",
11091 max_tinst_depth);
11092 return false;
11095 /* If the current instantiation caused problems, don't let it instantiate
11096 anything else. Do allow deduction substitution and decls usable in
11097 constant expressions. */
11098 if (!targs && limit_bad_template_recursion (tldcl))
11100 /* Avoid no_linkage_errors and unused function (and all other)
11101 warnings for this decl. */
11102 suppress_warning (tldcl);
11103 return false;
11106 /* When not -quiet, dump template instantiations other than functions, since
11107 announce_function will take care of those. */
11108 if (!quiet_flag && !targs
11109 && TREE_CODE (tldcl) != TREE_LIST
11110 && TREE_CODE (tldcl) != FUNCTION_DECL)
11111 fprintf (stderr, " %s", decl_as_string (tldcl, TFF_DECL_SPECIFIERS));
11113 new_level = tinst_level_freelist ().alloc ();
11114 new_level->tldcl = tldcl;
11115 new_level->targs = targs;
11116 new_level->locus = loc;
11117 new_level->errors = errorcount + sorrycount;
11118 new_level->next = NULL;
11119 new_level->refcount = 0;
11120 new_level->path = new_level->visible = nullptr;
11121 set_refcount_ptr (new_level->next, current_tinst_level);
11122 set_refcount_ptr (current_tinst_level, new_level);
11124 ++tinst_depth;
11125 if (GATHER_STATISTICS && (tinst_depth > depth_reached))
11126 depth_reached = tinst_depth;
11128 return true;
11131 /* We're starting substitution of TMPL<ARGS>; record the template
11132 substitution context for diagnostics and to restore it later. */
11134 bool
11135 push_tinst_level (tree tmpl, tree args)
11137 return push_tinst_level_loc (tmpl, args, input_location);
11140 /* We're starting to instantiate D; record INPUT_LOCATION and the
11141 template instantiation context for diagnostics and to restore it
11142 later. */
11144 bool
11145 push_tinst_level (tree d)
11147 return push_tinst_level_loc (d, input_location);
11150 /* Likewise, but record LOC as the program location. */
11152 bool
11153 push_tinst_level_loc (tree d, location_t loc)
11155 gcc_assert (TREE_CODE (d) != TREE_LIST);
11156 return push_tinst_level_loc (d, NULL, loc);
11159 /* We're done instantiating this template; return to the instantiation
11160 context. */
11162 void
11163 pop_tinst_level (void)
11165 /* Restore the filename and line number stashed away when we started
11166 this instantiation. */
11167 input_location = current_tinst_level->locus;
11168 set_refcount_ptr (current_tinst_level, current_tinst_level->next);
11169 --tinst_depth;
11172 /* We're instantiating a deferred template; restore the template
11173 instantiation context in which the instantiation was requested, which
11174 is one step out from LEVEL. Return the corresponding DECL or TYPE. */
11176 static tree
11177 reopen_tinst_level (struct tinst_level *level)
11179 struct tinst_level *t;
11181 tinst_depth = 0;
11182 for (t = level; t; t = t->next)
11183 ++tinst_depth;
11185 set_refcount_ptr (current_tinst_level, level);
11186 pop_tinst_level ();
11187 if (current_tinst_level)
11188 current_tinst_level->errors = errorcount+sorrycount;
11189 return level->maybe_get_node ();
11192 /* Returns the TINST_LEVEL which gives the original instantiation
11193 context. */
11195 struct tinst_level *
11196 outermost_tinst_level (void)
11198 struct tinst_level *level = current_tinst_level;
11199 if (level)
11200 while (level->next)
11201 level = level->next;
11202 return level;
11205 /* True iff T is a friend function declaration that is not itself a template
11206 and is not defined in a class template. */
11208 bool
11209 non_templated_friend_p (tree t)
11211 if (t && TREE_CODE (t) == FUNCTION_DECL
11212 && DECL_UNIQUE_FRIEND_P (t))
11214 tree ti = DECL_TEMPLATE_INFO (t);
11215 if (!ti)
11216 return true;
11217 /* DECL_FRIEND_CONTEXT is set for a friend defined in class. */
11218 if (DECL_FRIEND_CONTEXT (t))
11219 return false;
11220 /* Non-templated friends in a class template are still represented with a
11221 TEMPLATE_DECL; check that its primary template is the befriending
11222 class. Note that DECL_PRIMARY_TEMPLATE is null for
11223 template <class T> friend A<T>::f(); */
11224 tree tmpl = TI_TEMPLATE (ti);
11225 tree primary = DECL_PRIMARY_TEMPLATE (tmpl);
11226 return (primary && primary != tmpl);
11228 else
11229 return false;
11232 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL. ARGS is the
11233 vector of template arguments, as for tsubst.
11235 Returns an appropriate tsubst'd friend declaration. */
11237 static tree
11238 tsubst_friend_function (tree decl, tree args)
11240 tree new_friend;
11242 if (TREE_CODE (decl) == FUNCTION_DECL
11243 && DECL_TEMPLATE_INSTANTIATION (decl)
11244 && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
11245 /* This was a friend declared with an explicit template
11246 argument list, e.g.:
11248 friend void f<>(T);
11250 to indicate that f was a template instantiation, not a new
11251 function declaration. Now, we have to figure out what
11252 instantiation of what template. */
11254 tree template_id, arglist, fns;
11255 tree new_args;
11256 tree tmpl;
11257 tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
11259 /* Friend functions are looked up in the containing namespace scope.
11260 We must enter that scope, to avoid finding member functions of the
11261 current class with same name. */
11262 push_nested_namespace (ns);
11263 fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
11264 tf_warning_or_error, NULL_TREE);
11265 pop_nested_namespace (ns);
11266 arglist = tsubst (DECL_TI_ARGS (decl), args,
11267 tf_warning_or_error, NULL_TREE);
11268 template_id = lookup_template_function (fns, arglist);
11270 new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11271 tmpl = determine_specialization (template_id, new_friend,
11272 &new_args,
11273 /*need_member_template=*/0,
11274 TREE_VEC_LENGTH (args),
11275 tsk_none);
11276 return instantiate_template (tmpl, new_args, tf_error);
11279 new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
11280 if (new_friend == error_mark_node)
11281 return error_mark_node;
11283 /* The NEW_FRIEND will look like an instantiation, to the
11284 compiler, but is not an instantiation from the point of view of
11285 the language. For example, we might have had:
11287 template <class T> struct S {
11288 template <class U> friend void f(T, U);
11291 Then, in S<int>, template <class U> void f(int, U) is not an
11292 instantiation of anything. */
11294 DECL_USE_TEMPLATE (new_friend) = 0;
11295 if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11297 DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (new_friend) = false;
11298 DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
11299 DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
11300 = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
11302 /* Substitute TEMPLATE_PARMS_CONSTRAINTS so that parameter levels will
11303 match in decls_match. */
11304 tree parms = DECL_TEMPLATE_PARMS (new_friend);
11305 tree treqs = TEMPLATE_PARMS_CONSTRAINTS (parms);
11306 treqs = maybe_substitute_reqs_for (treqs, new_friend);
11307 if (treqs != TEMPLATE_PARMS_CONSTRAINTS (parms))
11309 TEMPLATE_PARMS_CONSTRAINTS (parms) = treqs;
11310 /* As well as each TEMPLATE_PARM_CONSTRAINTS. */
11311 tsubst_each_template_parm_constraints (parms, args,
11312 tf_warning_or_error);
11316 /* The mangled name for the NEW_FRIEND is incorrect. The function
11317 is not a template instantiation and should not be mangled like
11318 one. Therefore, we forget the mangling here; we'll recompute it
11319 later if we need it. */
11320 if (TREE_CODE (new_friend) != TEMPLATE_DECL)
11322 SET_DECL_RTL (new_friend, NULL);
11323 SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
11326 if (DECL_NAMESPACE_SCOPE_P (new_friend))
11328 tree old_decl;
11329 tree ns;
11331 /* We must save some information from NEW_FRIEND before calling
11332 duplicate decls since that function will free NEW_FRIEND if
11333 possible. */
11334 tree new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
11335 tree new_friend_result_template_info = NULL_TREE;
11336 bool new_friend_is_defn =
11337 (new_friend_template_info
11338 && (DECL_INITIAL (DECL_TEMPLATE_RESULT
11339 (template_for_substitution (new_friend)))
11340 != NULL_TREE));
11341 tree not_tmpl = new_friend;
11343 if (TREE_CODE (new_friend) == TEMPLATE_DECL)
11345 /* This declaration is a `primary' template. */
11346 DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
11348 not_tmpl = DECL_TEMPLATE_RESULT (new_friend);
11349 new_friend_result_template_info = DECL_TEMPLATE_INFO (not_tmpl);
11351 else if (!constraints_satisfied_p (new_friend))
11352 /* Only define a constrained hidden friend when satisfied. */
11353 return error_mark_node;
11355 /* Inside pushdecl_namespace_level, we will push into the
11356 current namespace. However, the friend function should go
11357 into the namespace of the template. */
11358 ns = decl_namespace_context (new_friend);
11359 push_nested_namespace (ns);
11360 old_decl = pushdecl_namespace_level (new_friend, /*hiding=*/true);
11361 pop_nested_namespace (ns);
11363 if (old_decl == error_mark_node)
11364 return error_mark_node;
11366 if (old_decl != new_friend)
11368 /* This new friend declaration matched an existing
11369 declaration. For example, given:
11371 template <class T> void f(T);
11372 template <class U> class C {
11373 template <class T> friend void f(T) {}
11376 the friend declaration actually provides the definition
11377 of `f', once C has been instantiated for some type. So,
11378 old_decl will be the out-of-class template declaration,
11379 while new_friend is the in-class definition.
11381 But, if `f' was called before this point, the
11382 instantiation of `f' will have DECL_TI_ARGS corresponding
11383 to `T' but not to `U', references to which might appear
11384 in the definition of `f'. Previously, the most general
11385 template for an instantiation of `f' was the out-of-class
11386 version; now it is the in-class version. Therefore, we
11387 run through all specialization of `f', adding to their
11388 DECL_TI_ARGS appropriately. In particular, they need a
11389 new set of outer arguments, corresponding to the
11390 arguments for this class instantiation.
11392 The same situation can arise with something like this:
11394 friend void f(int);
11395 template <class T> class C {
11396 friend void f(T) {}
11399 when `C<int>' is instantiated. Now, `f(int)' is defined
11400 in the class. */
11402 if (!new_friend_is_defn)
11403 /* On the other hand, if the in-class declaration does
11404 *not* provide a definition, then we don't want to alter
11405 existing definitions. We can just leave everything
11406 alone. */
11408 else
11410 tree new_template = TI_TEMPLATE (new_friend_template_info);
11411 tree new_args = TI_ARGS (new_friend_template_info);
11413 /* Overwrite whatever template info was there before, if
11414 any, with the new template information pertaining to
11415 the declaration. */
11416 DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
11418 if (TREE_CODE (old_decl) != TEMPLATE_DECL)
11420 /* We should have called reregister_specialization in
11421 duplicate_decls. */
11422 gcc_assert (retrieve_specialization (new_template,
11423 new_args, 0)
11424 == old_decl);
11426 /* Instantiate it if the global has already been used. */
11427 if (DECL_ODR_USED (old_decl))
11428 instantiate_decl (old_decl, /*defer_ok=*/true,
11429 /*expl_inst_class_mem_p=*/false);
11431 else
11433 tree t;
11435 /* Indicate that the old function template is a partial
11436 instantiation. */
11437 DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
11438 = new_friend_result_template_info;
11440 gcc_assert (new_template
11441 == most_general_template (new_template));
11442 gcc_assert (new_template != old_decl);
11444 /* Reassign any specializations already in the hash table
11445 to the new more general template, and add the
11446 additional template args. */
11447 for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
11448 t != NULL_TREE;
11449 t = TREE_CHAIN (t))
11451 tree spec = TREE_VALUE (t);
11452 spec_entry elt;
11454 elt.tmpl = old_decl;
11455 elt.args = DECL_TI_ARGS (spec);
11456 elt.spec = NULL_TREE;
11458 decl_specializations->remove_elt (&elt);
11460 DECL_TI_ARGS (spec)
11461 = add_outermost_template_args (new_args,
11462 DECL_TI_ARGS (spec));
11464 register_specialization
11465 (spec, new_template, DECL_TI_ARGS (spec), true, 0);
11468 DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
11472 /* The information from NEW_FRIEND has been merged into OLD_DECL
11473 by duplicate_decls. */
11474 new_friend = old_decl;
11477 /* We've just introduced a namespace-scope function in the purview
11478 without necessarily having opened the enclosing namespace, so
11479 make sure the namespace is in the purview now too. */
11480 if (modules_p ()
11481 && DECL_MODULE_PURVIEW_P (STRIP_TEMPLATE (new_friend))
11482 && TREE_CODE (DECL_CONTEXT (new_friend)) == NAMESPACE_DECL)
11483 DECL_MODULE_PURVIEW_P (DECL_CONTEXT (new_friend)) = true;
11485 else
11487 tree context = DECL_CONTEXT (new_friend);
11488 bool dependent_p;
11490 /* In the code
11491 template <class T> class C {
11492 template <class U> friend void C1<U>::f (); // case 1
11493 friend void C2<T>::f (); // case 2
11495 we only need to make sure CONTEXT is a complete type for
11496 case 2. To distinguish between the two cases, we note that
11497 CONTEXT of case 1 remains dependent type after tsubst while
11498 this isn't true for case 2. */
11499 ++processing_template_decl;
11500 dependent_p = dependent_type_p (context);
11501 --processing_template_decl;
11503 if (!dependent_p
11504 && !complete_type_or_else (context, NULL_TREE))
11505 return error_mark_node;
11507 if (COMPLETE_TYPE_P (context))
11509 tree fn = new_friend;
11510 /* do_friend adds the TEMPLATE_DECL for any member friend
11511 template even if it isn't a member template, i.e.
11512 template <class T> friend A<T>::f();
11513 Look through it in that case. */
11514 if (TREE_CODE (fn) == TEMPLATE_DECL
11515 && !PRIMARY_TEMPLATE_P (fn))
11516 fn = DECL_TEMPLATE_RESULT (fn);
11517 /* Check to see that the declaration is really present, and,
11518 possibly obtain an improved declaration. */
11519 fn = check_classfn (context, fn, NULL_TREE);
11521 if (fn)
11522 new_friend = fn;
11526 return new_friend;
11529 /* FRIEND_TMPL is a friend TEMPLATE_DECL. ARGS is the vector of
11530 template arguments, as for tsubst.
11532 Returns an appropriate tsubst'd friend type or error_mark_node on
11533 failure. */
11535 static tree
11536 tsubst_friend_class (tree friend_tmpl, tree args)
11538 tree tmpl;
11540 if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
11542 tmpl = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
11543 return TREE_TYPE (tmpl);
11546 tree context = CP_DECL_CONTEXT (friend_tmpl);
11547 if (TREE_CODE (context) == NAMESPACE_DECL)
11548 push_nested_namespace (context);
11549 else
11551 context = tsubst (context, args, tf_error, NULL_TREE);
11552 push_nested_class (context);
11555 tmpl = lookup_name (DECL_NAME (friend_tmpl), LOOK_where::CLASS_NAMESPACE,
11556 LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND);
11558 if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
11560 /* The friend template has already been declared. Just
11561 check to see that the declarations match, and install any new
11562 default parameters. We must tsubst the default parameters,
11563 of course. We only need the innermost template parameters
11564 because that is all that redeclare_class_template will look
11565 at. */
11566 if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
11567 > TMPL_ARGS_DEPTH (args))
11569 tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
11570 args, tf_warning_or_error);
11571 tsubst_each_template_parm_constraints (parms, args,
11572 tf_warning_or_error);
11573 location_t saved_input_location = input_location;
11574 input_location = DECL_SOURCE_LOCATION (friend_tmpl);
11575 tree cons = get_constraints (friend_tmpl);
11576 ++processing_template_decl;
11577 cons = tsubst_constraint_info (cons, args, tf_warning_or_error,
11578 DECL_FRIEND_CONTEXT (friend_tmpl));
11579 --processing_template_decl;
11580 redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
11581 input_location = saved_input_location;
11584 else
11586 /* The friend template has not already been declared. In this
11587 case, the instantiation of the template class will cause the
11588 injection of this template into the namespace scope. */
11589 tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
11591 if (tmpl != error_mark_node)
11593 /* The new TMPL is not an instantiation of anything, so we
11594 forget its origins. We don't reset CLASSTYPE_TI_TEMPLATE
11595 for the new type because that is supposed to be the
11596 corresponding template decl, i.e., TMPL. */
11597 DECL_USE_TEMPLATE (tmpl) = 0;
11598 DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
11599 CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
11600 CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
11601 = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
11603 /* Substitute into and set the constraints on the new declaration. */
11604 if (tree ci = get_constraints (friend_tmpl))
11606 ++processing_template_decl;
11607 ci = tsubst_constraint_info (ci, args, tf_warning_or_error,
11608 DECL_FRIEND_CONTEXT (friend_tmpl));
11609 --processing_template_decl;
11610 set_constraints (tmpl, ci);
11611 tsubst_each_template_parm_constraints (DECL_TEMPLATE_PARMS (tmpl),
11612 args, tf_warning_or_error);
11615 /* Inject this template into the enclosing namspace scope. */
11616 tmpl = pushdecl_namespace_level (tmpl, /*hiding=*/true);
11620 if (TREE_CODE (context) == NAMESPACE_DECL)
11621 pop_nested_namespace (context);
11622 else
11623 pop_nested_class ();
11625 return TREE_TYPE (tmpl);
11628 /* Returns zero if TYPE cannot be completed later due to circularity.
11629 Otherwise returns one. */
11631 static int
11632 can_complete_type_without_circularity (tree type)
11634 if (type == NULL_TREE || type == error_mark_node)
11635 return 0;
11636 else if (COMPLETE_TYPE_P (type))
11637 return 1;
11638 else if (TREE_CODE (type) == ARRAY_TYPE)
11639 return can_complete_type_without_circularity (TREE_TYPE (type));
11640 else if (CLASS_TYPE_P (type)
11641 && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
11642 return 0;
11643 else
11644 return 1;
11647 static tree tsubst_omp_clauses (tree, enum c_omp_region_type, tree,
11648 tsubst_flags_t, tree);
11650 /* Instantiate the contract statement. */
11652 static tree
11653 tsubst_contract (tree decl, tree t, tree args, tsubst_flags_t complain,
11654 tree in_decl)
11656 tree type = decl ? TREE_TYPE (TREE_TYPE (decl)) : NULL_TREE;
11657 bool auto_p = type_uses_auto (type);
11659 tree r = copy_node (t);
11661 /* Rebuild the result variable. */
11662 if (type && POSTCONDITION_P (t) && POSTCONDITION_IDENTIFIER (t))
11664 tree oldvar = POSTCONDITION_IDENTIFIER (t);
11666 tree newvar = copy_node (oldvar);
11667 TREE_TYPE (newvar) = type;
11668 DECL_CONTEXT (newvar) = decl;
11669 POSTCONDITION_IDENTIFIER (r) = newvar;
11671 /* Make sure the postcondition is valid. */
11672 location_t loc = DECL_SOURCE_LOCATION (oldvar);
11673 if (!auto_p)
11674 if (!check_postcondition_result (decl, type, loc))
11675 return invalidate_contract (r);
11677 /* Make the variable available for lookup. */
11678 register_local_specialization (newvar, oldvar);
11681 /* Instantiate the condition. If the return type is undeduced, process
11682 the expression as if inside a template to avoid spurious type errors. */
11683 if (auto_p)
11684 ++processing_template_decl;
11685 ++processing_contract_condition;
11686 CONTRACT_CONDITION (r)
11687 = tsubst_expr (CONTRACT_CONDITION (t), args, complain, in_decl);
11688 --processing_contract_condition;
11689 if (auto_p)
11690 --processing_template_decl;
11692 /* And the comment. */
11693 CONTRACT_COMMENT (r)
11694 = tsubst_expr (CONTRACT_COMMENT (r), args, complain, in_decl);
11696 return r;
11699 /* Update T by instantiating its contract attribute. */
11701 static void
11702 tsubst_contract_attribute (tree decl, tree t, tree args,
11703 tsubst_flags_t complain, tree in_decl)
11705 /* For non-specializations, adjust the current declaration to the most general
11706 version of in_decl. Because we defer the instantiation of contracts as long
11707 as possible, they are still written in terms of the parameters (and return
11708 type) of the most general template. */
11709 tree tmpl = DECL_TI_TEMPLATE (in_decl);
11710 if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
11711 in_decl = DECL_TEMPLATE_RESULT (most_general_template (in_decl));
11712 local_specialization_stack specs (lss_copy);
11713 register_parameter_specializations (in_decl, decl);
11715 /* Get the contract to be instantiated. */
11716 tree contract = CONTRACT_STATEMENT (t);
11718 /* Use the complete set of template arguments for instantiation. The
11719 contract may not have been instantiated and still refer to outer levels
11720 of template parameters. */
11721 args = DECL_TI_ARGS (decl);
11723 /* For member functions, make this available for semantic analysis. */
11724 tree save_ccp = current_class_ptr;
11725 tree save_ccr = current_class_ref;
11726 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
11728 tree arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
11729 tree this_type = TREE_TYPE (TREE_VALUE (arg_types));
11730 inject_this_parameter (this_type, cp_type_quals (this_type));
11733 contract = tsubst_contract (decl, contract, args, complain, in_decl);
11735 current_class_ptr = save_ccp;
11736 current_class_ref = save_ccr;
11738 /* Rebuild the attribute. */
11739 TREE_VALUE (t) = build_tree_list (NULL_TREE, contract);
11742 /* Rebuild the attribute list for DECL, substituting into contracts
11743 as needed. */
11745 void
11746 tsubst_contract_attributes (tree decl, tree args, tsubst_flags_t complain, tree in_decl)
11748 tree list = copy_list (DECL_ATTRIBUTES (decl));
11749 for (tree attr = list; attr; attr = CONTRACT_CHAIN (attr))
11751 if (cxx_contract_attribute_p (attr))
11752 tsubst_contract_attribute (decl, attr, args, complain, in_decl);
11754 DECL_ATTRIBUTES (decl) = list;
11757 /* Instantiate a single dependent attribute T (a TREE_LIST), and return either
11758 T or a new TREE_LIST, possibly a chain in the case of a pack expansion. */
11760 static tree
11761 tsubst_attribute (tree t, tree *decl_p, tree args,
11762 tsubst_flags_t complain, tree in_decl)
11764 gcc_assert (ATTR_IS_DEPENDENT (t));
11766 /* Note that contract attributes are never substituted from this function.
11767 Their instantiation is triggered by regenerate_from_template_decl when
11768 we instantiate the body of the function. */
11770 tree val = TREE_VALUE (t);
11771 if (val == NULL_TREE)
11772 /* Nothing to do. */;
11773 else if ((flag_openmp || flag_openmp_simd)
11774 && is_attribute_p ("omp declare simd",
11775 get_attribute_name (t)))
11777 tree clauses = TREE_VALUE (val);
11778 clauses = tsubst_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD, args,
11779 complain, in_decl);
11780 c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11781 clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11782 tree parms = DECL_ARGUMENTS (*decl_p);
11783 clauses
11784 = c_omp_declare_simd_clauses_to_numbers (parms, clauses);
11785 if (clauses)
11786 val = build_tree_list (NULL_TREE, clauses);
11787 else
11788 val = NULL_TREE;
11790 else if (flag_openmp
11791 && is_attribute_p ("omp declare variant base",
11792 get_attribute_name (t)))
11794 ++cp_unevaluated_operand;
11795 tree varid = tsubst_expr (TREE_PURPOSE (val), args, complain, in_decl);
11796 --cp_unevaluated_operand;
11797 tree chain = TREE_CHAIN (val);
11798 location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
11799 tree ctx = copy_list (TREE_VALUE (val));
11800 tree simd = get_identifier ("simd");
11801 tree score = get_identifier (" score");
11802 tree condition = get_identifier ("condition");
11803 for (tree t1 = ctx; t1; t1 = TREE_CHAIN (t1))
11805 const char *set = IDENTIFIER_POINTER (TREE_PURPOSE (t1));
11806 TREE_VALUE (t1) = copy_list (TREE_VALUE (t1));
11807 for (tree t2 = TREE_VALUE (t1); t2; t2 = TREE_CHAIN (t2))
11809 if (TREE_PURPOSE (t2) == simd && set[0] == 'c')
11811 tree clauses = TREE_VALUE (t2);
11812 clauses = tsubst_omp_clauses (clauses,
11813 C_ORT_OMP_DECLARE_SIMD, args,
11814 complain, in_decl);
11815 c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11816 clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11817 TREE_VALUE (t2) = clauses;
11819 else
11821 TREE_VALUE (t2) = copy_list (TREE_VALUE (t2));
11822 for (tree t3 = TREE_VALUE (t2); t3; t3 = TREE_CHAIN (t3))
11823 if (TREE_VALUE (t3))
11825 bool allow_string
11826 = ((TREE_PURPOSE (t2) != condition || set[0] != 'u')
11827 && TREE_PURPOSE (t3) != score);
11828 tree v = TREE_VALUE (t3);
11829 if (TREE_CODE (v) == STRING_CST && allow_string)
11830 continue;
11831 v = tsubst_expr (v, args, complain, in_decl);
11832 v = fold_non_dependent_expr (v);
11833 if (!INTEGRAL_TYPE_P (TREE_TYPE (v))
11834 || (TREE_PURPOSE (t3) == score
11835 ? TREE_CODE (v) != INTEGER_CST
11836 : !tree_fits_shwi_p (v)))
11838 location_t loc
11839 = cp_expr_loc_or_loc (TREE_VALUE (t3),
11840 match_loc);
11841 if (TREE_PURPOSE (t3) == score)
11842 error_at (loc, "score argument must be "
11843 "constant integer expression");
11844 else if (allow_string)
11845 error_at (loc, "property must be constant "
11846 "integer expression or string "
11847 "literal");
11848 else
11849 error_at (loc, "property must be constant "
11850 "integer expression");
11851 return NULL_TREE;
11853 else if (TREE_PURPOSE (t3) == score
11854 && tree_int_cst_sgn (v) < 0)
11856 location_t loc
11857 = cp_expr_loc_or_loc (TREE_VALUE (t3),
11858 match_loc);
11859 error_at (loc, "score argument must be "
11860 "non-negative");
11861 return NULL_TREE;
11863 TREE_VALUE (t3) = v;
11868 val = tree_cons (varid, ctx, chain);
11870 /* If the first attribute argument is an identifier, don't
11871 pass it through tsubst. Attributes like mode, format,
11872 cleanup and several target specific attributes expect it
11873 unmodified. */
11874 else if (attribute_takes_identifier_p (get_attribute_name (t)))
11876 tree chain
11877 = tsubst_expr (TREE_CHAIN (val), args, complain, in_decl);
11878 if (chain != TREE_CHAIN (val))
11879 val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
11881 else if (PACK_EXPANSION_P (val))
11883 /* An attribute pack expansion. */
11884 tree purp = TREE_PURPOSE (t);
11885 tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
11886 if (pack == error_mark_node)
11887 return error_mark_node;
11888 int len = TREE_VEC_LENGTH (pack);
11889 tree list = NULL_TREE;
11890 tree *q = &list;
11891 for (int i = 0; i < len; ++i)
11893 tree elt = TREE_VEC_ELT (pack, i);
11894 *q = build_tree_list (purp, elt);
11895 q = &TREE_CHAIN (*q);
11897 return list;
11899 else
11900 val = tsubst_expr (val, args, complain, in_decl);
11902 if (val == error_mark_node)
11903 return error_mark_node;
11904 if (val != TREE_VALUE (t))
11905 return build_tree_list (TREE_PURPOSE (t), val);
11906 return t;
11909 /* Instantiate any dependent attributes in ATTRIBUTES, returning either it
11910 unchanged or a new TREE_LIST chain. */
11912 static tree
11913 tsubst_attributes (tree attributes, tree args,
11914 tsubst_flags_t complain, tree in_decl)
11916 tree last_dep = NULL_TREE;
11918 for (tree t = attributes; t; t = TREE_CHAIN (t))
11919 if (ATTR_IS_DEPENDENT (t))
11921 last_dep = t;
11922 attributes = copy_list (attributes);
11923 break;
11926 if (last_dep)
11927 for (tree *p = &attributes; *p; )
11929 tree t = *p;
11930 if (ATTR_IS_DEPENDENT (t))
11932 tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
11933 if (subst != t)
11935 *p = subst;
11936 while (*p)
11937 p = &TREE_CHAIN (*p);
11938 *p = TREE_CHAIN (t);
11939 continue;
11942 p = &TREE_CHAIN (*p);
11945 return attributes;
11948 /* Apply any attributes which had to be deferred until instantiation
11949 time. DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
11950 ARGS, COMPLAIN, IN_DECL are as tsubst. Returns true normally,
11951 false on error. */
11953 static bool
11954 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
11955 tree args, tsubst_flags_t complain, tree in_decl)
11957 tree t;
11958 tree *p;
11960 if (attributes == NULL_TREE)
11961 return true;
11963 if (DECL_P (*decl_p))
11965 if (TREE_TYPE (*decl_p) == error_mark_node)
11966 return false;
11967 p = &DECL_ATTRIBUTES (*decl_p);
11968 /* DECL_ATTRIBUTES comes from copy_node in tsubst_decl, and is identical
11969 to our attributes parameter. */
11970 gcc_assert (*p == attributes);
11972 else
11974 p = &TYPE_ATTRIBUTES (*decl_p);
11975 /* TYPE_ATTRIBUTES was set up (with abi_tag and may_alias) in
11976 lookup_template_class_1, and should be preserved. */
11977 gcc_assert (*p != attributes);
11978 while (*p)
11979 p = &TREE_CHAIN (*p);
11982 /* save_template_attributes puts the dependent attributes at the beginning of
11983 the list; find the non-dependent ones. */
11984 for (t = attributes; t; t = TREE_CHAIN (t))
11985 if (!ATTR_IS_DEPENDENT (t))
11986 break;
11987 tree nondep = t;
11989 /* Apply any non-dependent attributes. */
11990 *p = nondep;
11992 if (nondep == attributes)
11993 return true;
11995 /* And then any dependent ones. */
11996 tree late_attrs = NULL_TREE;
11997 tree *q = &late_attrs;
11998 for (t = attributes; t != nondep; t = TREE_CHAIN (t))
12000 *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
12001 if (*q == error_mark_node)
12002 return false;
12003 if (*q == t)
12005 *q = copy_node (t);
12006 TREE_CHAIN (*q) = NULL_TREE;
12008 while (*q)
12009 q = &TREE_CHAIN (*q);
12012 /* cplus_decl_attributes can add some attributes implicitly. For templates,
12013 those attributes should have been added already when those templates were
12014 parsed, and shouldn't be added based on from which context they are
12015 first time instantiated. */
12016 auto o1 = make_temp_override (current_optimize_pragma, NULL_TREE);
12017 auto o2 = make_temp_override (optimization_current_node,
12018 optimization_default_node);
12019 auto o3 = make_temp_override (current_target_pragma, NULL_TREE);
12020 auto o4 = make_temp_override (scope_chain->omp_declare_target_attribute,
12021 NULL);
12022 auto o5 = make_temp_override (scope_chain->omp_begin_assumes, NULL);
12024 cplus_decl_attributes (decl_p, late_attrs, attr_flags);
12026 return true;
12029 /* The template TMPL is being instantiated with the template arguments TARGS.
12030 Perform the access checks that we deferred when parsing the template. */
12032 static void
12033 perform_instantiation_time_access_checks (tree tmpl, tree targs)
12035 unsigned i;
12036 deferred_access_check *chk;
12038 if (!CLASS_TYPE_P (tmpl) && TREE_CODE (tmpl) != FUNCTION_DECL)
12039 return;
12041 if (vec<deferred_access_check, va_gc> *access_checks
12042 = TI_DEFERRED_ACCESS_CHECKS (get_template_info (tmpl)))
12043 FOR_EACH_VEC_ELT (*access_checks, i, chk)
12045 tree decl = chk->decl;
12046 tree diag_decl = chk->diag_decl;
12047 tree type_scope = TREE_TYPE (chk->binfo);
12049 if (uses_template_parms (type_scope))
12050 type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
12052 /* Make access check error messages point to the location
12053 of the use of the typedef. */
12054 iloc_sentinel ils (chk->loc);
12055 perform_or_defer_access_check (TYPE_BINFO (type_scope),
12056 decl, diag_decl, tf_warning_or_error);
12060 tree
12061 instantiate_class_template (tree type)
12063 auto_timevar tv (TV_TEMPLATE_INST);
12065 tree templ, args, pattern, t, member;
12066 tree typedecl;
12067 tree pbinfo;
12068 tree base_list;
12069 unsigned int saved_maximum_field_alignment;
12070 tree fn_context;
12072 if (type == error_mark_node)
12073 return error_mark_node;
12075 if (COMPLETE_OR_OPEN_TYPE_P (type)
12076 || (uses_template_parms (type)
12077 && !TYPE_FUNCTION_SCOPE_P (type)))
12078 return type;
12080 /* Figure out which template is being instantiated. */
12081 templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
12082 gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
12084 /* Mark the type as in the process of being defined. */
12085 TYPE_BEING_DEFINED (type) = 1;
12087 /* We may be in the middle of deferred access check. Disable
12088 it now. */
12089 deferring_access_check_sentinel acs (dk_no_deferred);
12091 /* Determine what specialization of the original template to
12092 instantiate. */
12093 t = most_specialized_partial_spec (type, tf_warning_or_error);
12094 if (t == error_mark_node)
12095 return error_mark_node;
12096 else if (t)
12098 /* This TYPE is actually an instantiation of a partial
12099 specialization. We replace the innermost set of ARGS with
12100 the arguments appropriate for substitution. For example,
12101 given:
12103 template <class T> struct S {};
12104 template <class T> struct S<T*> {};
12106 and supposing that we are instantiating S<int*>, ARGS will
12107 presently be {int*} -- but we need {int}. */
12108 pattern = TREE_TYPE (t);
12109 args = TREE_PURPOSE (t);
12111 else
12113 pattern = TREE_TYPE (templ);
12114 args = CLASSTYPE_TI_ARGS (type);
12117 /* If the template we're instantiating is incomplete, then clearly
12118 there's nothing we can do. */
12119 if (!COMPLETE_TYPE_P (pattern))
12121 /* We can try again later. */
12122 TYPE_BEING_DEFINED (type) = 0;
12123 return type;
12126 /* If we've recursively instantiated too many templates, stop. */
12127 if (! push_tinst_level (type))
12128 return type;
12130 int saved_unevaluated_operand = cp_unevaluated_operand;
12131 int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
12133 fn_context = decl_function_context (TYPE_MAIN_DECL (type));
12134 /* Also avoid push_to_top_level for a lambda in an NSDMI. */
12135 if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
12136 fn_context = error_mark_node;
12137 if (!fn_context)
12138 push_to_top_level ();
12139 else
12141 cp_unevaluated_operand = 0;
12142 c_inhibit_evaluation_warnings = 0;
12145 mark_template_arguments_used (templ, CLASSTYPE_TI_ARGS (type));
12147 /* Use #pragma pack from the template context. */
12148 saved_maximum_field_alignment = maximum_field_alignment;
12149 maximum_field_alignment = TYPE_PRECISION (pattern);
12151 SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
12153 /* Set the input location to the most specialized template definition.
12154 This is needed if tsubsting causes an error. */
12155 typedecl = TYPE_MAIN_DECL (pattern);
12156 input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
12157 DECL_SOURCE_LOCATION (typedecl);
12159 set_instantiating_module (TYPE_NAME (type));
12161 TYPE_PACKED (type) = TYPE_PACKED (pattern);
12162 SET_TYPE_ALIGN (type, TYPE_ALIGN (pattern));
12163 TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
12164 CLASSTYPE_NON_AGGREGATE (type) = CLASSTYPE_NON_AGGREGATE (pattern);
12165 if (ANON_AGGR_TYPE_P (pattern))
12166 SET_ANON_AGGR_TYPE_P (type);
12167 if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
12169 CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
12170 CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
12171 /* Adjust visibility for template arguments. */
12172 determine_visibility (TYPE_MAIN_DECL (type));
12174 if (CLASS_TYPE_P (type))
12175 CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
12177 pbinfo = TYPE_BINFO (pattern);
12179 /* We should never instantiate a nested class before its enclosing
12180 class; we need to look up the nested class by name before we can
12181 instantiate it, and that lookup should instantiate the enclosing
12182 class. */
12183 gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
12184 || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
12186 base_list = NULL_TREE;
12187 /* Defer access checking while we substitute into the types named in
12188 the base-clause. */
12189 push_deferring_access_checks (dk_deferred);
12190 if (BINFO_N_BASE_BINFOS (pbinfo))
12192 tree pbase_binfo;
12193 int i;
12195 /* Substitute into each of the bases to determine the actual
12196 basetypes. */
12197 for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
12199 tree base;
12200 tree access = BINFO_BASE_ACCESS (pbinfo, i);
12201 tree expanded_bases = NULL_TREE;
12202 int idx, len = 1;
12204 if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
12206 expanded_bases =
12207 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
12208 args, tf_error, NULL_TREE);
12209 if (expanded_bases == error_mark_node)
12210 continue;
12212 len = TREE_VEC_LENGTH (expanded_bases);
12215 for (idx = 0; idx < len; idx++)
12217 if (expanded_bases)
12218 /* Extract the already-expanded base class. */
12219 base = TREE_VEC_ELT (expanded_bases, idx);
12220 else
12221 /* Substitute to figure out the base class. */
12222 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
12223 NULL_TREE);
12225 if (base == error_mark_node)
12226 continue;
12228 base_list = tree_cons (access, base, base_list);
12229 if (BINFO_VIRTUAL_P (pbase_binfo))
12230 TREE_TYPE (base_list) = integer_type_node;
12234 /* The list is now in reverse order; correct that. */
12235 base_list = nreverse (base_list);
12237 /* Now call xref_basetypes to set up all the base-class
12238 information. */
12239 xref_basetypes (type, base_list);
12241 apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
12242 (int) ATTR_FLAG_TYPE_IN_PLACE,
12243 args, tf_error, NULL_TREE);
12244 fixup_attribute_variants (type);
12246 /* Now that our base classes are set up, enter the scope of the
12247 class, so that name lookups into base classes, etc. will work
12248 correctly. This is precisely analogous to what we do in
12249 begin_class_definition when defining an ordinary non-template
12250 class, except we also need to push the enclosing classes. */
12251 push_nested_class (type);
12253 /* Now check accessibility of the types named in its base-clause,
12254 relative to the scope of the class. */
12255 pop_to_parent_deferring_access_checks ();
12257 /* A vector to hold members marked with attribute used. */
12258 auto_vec<tree> used;
12260 /* Now members are processed in the order of declaration. */
12261 for (member = CLASSTYPE_DECL_LIST (pattern);
12262 member; member = TREE_CHAIN (member))
12264 tree t = TREE_VALUE (member);
12266 if (TREE_PURPOSE (member))
12268 if (TYPE_P (t))
12270 if (LAMBDA_TYPE_P (t))
12271 /* A closure type for a lambda in an NSDMI or default argument.
12272 Ignore it; it will be regenerated when needed. */
12273 continue;
12275 /* If the member is a class template, we've
12276 already substituted its type. */
12277 if (CLASS_TYPE_P (t)
12278 && CLASSTYPE_IS_TEMPLATE (t))
12279 continue;
12281 tree newtag = tsubst (t, args, tf_error, NULL_TREE);
12282 if (newtag == error_mark_node)
12283 continue;
12285 if (TREE_CODE (newtag) != ENUMERAL_TYPE)
12287 tree name = TYPE_IDENTIFIER (t);
12289 /* Now, install the tag. We don't use pushtag
12290 because that does too much work -- creating an
12291 implicit typedef, which we've already done. */
12292 set_identifier_type_value (name, TYPE_NAME (newtag));
12293 maybe_add_class_template_decl_list (type, newtag, false);
12294 TREE_PUBLIC (TYPE_NAME (newtag)) = true;
12295 determine_visibility (TYPE_NAME (newtag));
12298 else if (DECL_DECLARES_FUNCTION_P (t))
12300 tree r;
12302 if (TREE_CODE (t) == TEMPLATE_DECL)
12303 ++processing_template_decl;
12304 r = tsubst (t, args, tf_error, NULL_TREE);
12305 if (TREE_CODE (t) == TEMPLATE_DECL)
12306 --processing_template_decl;
12308 set_current_access_from_decl (r);
12309 finish_member_declaration (r);
12310 /* Instantiate members marked with attribute used. */
12311 if (r != error_mark_node && DECL_PRESERVE_P (r))
12312 used.safe_push (r);
12313 if (TREE_CODE (r) == FUNCTION_DECL
12314 && DECL_OMP_DECLARE_REDUCTION_P (r))
12315 cp_check_omp_declare_reduction (r);
12317 else if ((DECL_CLASS_TEMPLATE_P (t) || DECL_IMPLICIT_TYPEDEF_P (t))
12318 && LAMBDA_TYPE_P (TREE_TYPE (t)))
12319 /* A closure type for a lambda in an NSDMI or default argument.
12320 Ignore it; it will be regenerated when needed. */;
12321 else
12323 /* Build new TYPE_FIELDS. */
12324 if (TREE_CODE (t) == STATIC_ASSERT)
12325 tsubst_expr (t, args, tf_warning_or_error, NULL_TREE);
12326 else if (TREE_CODE (t) != CONST_DECL)
12328 tree r;
12329 tree vec = NULL_TREE;
12330 int len = 1;
12332 gcc_checking_assert (TREE_CODE (t) != CONST_DECL);
12333 /* The file and line for this declaration, to
12334 assist in error message reporting. Since we
12335 called push_tinst_level above, we don't need to
12336 restore these. */
12337 input_location = DECL_SOURCE_LOCATION (t);
12339 if (TREE_CODE (t) == TEMPLATE_DECL)
12340 ++processing_template_decl;
12341 r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
12342 if (TREE_CODE (t) == TEMPLATE_DECL)
12343 --processing_template_decl;
12345 if (TREE_CODE (r) == TREE_VEC)
12347 /* A capture pack became multiple fields. */
12348 vec = r;
12349 len = TREE_VEC_LENGTH (vec);
12352 for (int i = 0; i < len; ++i)
12354 if (vec)
12355 r = TREE_VEC_ELT (vec, i);
12356 if (VAR_P (r))
12358 /* In [temp.inst]:
12360 [t]he initialization (and any associated
12361 side-effects) of a static data member does
12362 not occur unless the static data member is
12363 itself used in a way that requires the
12364 definition of the static data member to
12365 exist.
12367 Therefore, we do not substitute into the
12368 initialized for the static data member here. */
12369 finish_static_data_member_decl
12371 /*init=*/NULL_TREE,
12372 /*init_const_expr_p=*/false,
12373 /*asmspec_tree=*/NULL_TREE,
12374 /*flags=*/0);
12375 /* Instantiate members marked with attribute used. */
12376 if (r != error_mark_node && DECL_PRESERVE_P (r))
12377 used.safe_push (r);
12379 else if (TREE_CODE (r) == FIELD_DECL)
12381 /* Determine whether R has a valid type and can be
12382 completed later. If R is invalid, then its type
12383 is replaced by error_mark_node. */
12384 tree rtype = TREE_TYPE (r);
12385 if (can_complete_type_without_circularity (rtype))
12386 complete_type (rtype);
12388 if (!complete_or_array_type_p (rtype))
12390 /* If R's type couldn't be completed and
12391 it isn't a flexible array member (whose
12392 type is incomplete by definition) give
12393 an error. */
12394 cxx_incomplete_type_error (r, rtype);
12395 TREE_TYPE (r) = error_mark_node;
12397 else if (TREE_CODE (rtype) == ARRAY_TYPE
12398 && TYPE_DOMAIN (rtype) == NULL_TREE
12399 && (TREE_CODE (type) == UNION_TYPE
12400 || TREE_CODE (type) == QUAL_UNION_TYPE))
12402 error ("flexible array member %qD in union", r);
12403 TREE_TYPE (r) = error_mark_node;
12405 else if (!verify_type_context (input_location,
12406 TCTX_FIELD, rtype))
12407 TREE_TYPE (r) = error_mark_node;
12410 /* If it is a TYPE_DECL for a class-scoped
12411 ENUMERAL_TYPE, such a thing will already have
12412 been added to the field list by tsubst_enum
12413 in finish_member_declaration case above. */
12414 if (!(TREE_CODE (r) == TYPE_DECL
12415 && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
12416 && DECL_ARTIFICIAL (r)))
12418 set_current_access_from_decl (r);
12419 finish_member_declaration (r);
12425 else
12427 if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
12428 || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
12430 /* Build new CLASSTYPE_FRIEND_CLASSES. */
12432 tree friend_type = t;
12433 if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12435 /* template <class T> friend class C; */
12436 friend_type = tsubst_friend_class (friend_type, args);
12438 else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
12440 /* template <class T> friend class C::D; */
12441 friend_type = tsubst (friend_type, args,
12442 tf_warning_or_error, NULL_TREE);
12443 if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12444 friend_type = TREE_TYPE (friend_type);
12446 else if (TREE_CODE (friend_type) == TYPENAME_TYPE
12447 || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
12449 /* This could be either
12451 friend class T::C;
12453 when dependent_type_p is false or
12455 template <class U> friend class T::C;
12457 otherwise. */
12458 /* Bump processing_template_decl in case this is something like
12459 template <class T> friend struct A<T>::B. */
12460 ++processing_template_decl;
12461 friend_type = tsubst (friend_type, args,
12462 tf_warning_or_error, NULL_TREE);
12463 --processing_template_decl;
12465 else if (uses_template_parms (friend_type))
12466 /* friend class C<T>; */
12467 friend_type = tsubst (friend_type, args,
12468 tf_warning_or_error, NULL_TREE);
12470 /* Otherwise it's
12472 friend class C;
12474 where C is already declared or
12476 friend class C<int>;
12478 We don't have to do anything in these cases. */
12480 if (friend_type != error_mark_node)
12481 make_friend_class (type, friend_type, /*complain=*/false);
12483 else
12485 /* Build new DECL_FRIENDLIST. */
12486 tree r;
12488 /* The file and line for this declaration, to
12489 assist in error message reporting. Since we
12490 called push_tinst_level above, we don't need to
12491 restore these. */
12492 input_location = DECL_SOURCE_LOCATION (t);
12494 if (TREE_CODE (t) == TEMPLATE_DECL)
12496 ++processing_template_decl;
12497 push_deferring_access_checks (dk_no_check);
12500 r = tsubst_friend_function (t, args);
12501 add_friend (type, r, /*complain=*/false);
12502 if (TREE_CODE (t) == TEMPLATE_DECL)
12504 pop_deferring_access_checks ();
12505 --processing_template_decl;
12511 if (fn_context)
12513 /* Restore these before substituting into the lambda capture
12514 initializers. */
12515 cp_unevaluated_operand = saved_unevaluated_operand;
12516 c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
12519 /* Set the file and line number information to whatever is given for
12520 the class itself. This puts error messages involving generated
12521 implicit functions at a predictable point, and the same point
12522 that would be used for non-template classes. */
12523 input_location = DECL_SOURCE_LOCATION (typedecl);
12525 unreverse_member_declarations (type);
12526 finish_struct_1 (type);
12527 TYPE_BEING_DEFINED (type) = 0;
12529 /* Remember if instantiating this class ran into errors, so we can avoid
12530 instantiating member functions in limit_bad_template_recursion. We set
12531 this flag even if the problem was in another instantiation triggered by
12532 this one, as that will likely also cause trouble for member functions. */
12533 if (errorcount + sorrycount > current_tinst_level->errors)
12534 CLASSTYPE_ERRONEOUS (type) = true;
12536 /* We don't instantiate default arguments for member functions. 14.7.1:
12538 The implicit instantiation of a class template specialization causes
12539 the implicit instantiation of the declarations, but not of the
12540 definitions or default arguments, of the class member functions,
12541 member classes, static data members and member templates.... */
12543 perform_instantiation_time_access_checks (pattern, args);
12544 perform_deferred_access_checks (tf_warning_or_error);
12546 /* Now that we've gone through all the members, instantiate those
12547 marked with attribute used. We must do this in the context of
12548 the class -- not the context we pushed from, as that might be
12549 inside a template and change the behaviour of mark_used. */
12550 for (tree x : used)
12551 mark_used (x);
12553 pop_nested_class ();
12554 maximum_field_alignment = saved_maximum_field_alignment;
12555 if (!fn_context)
12556 pop_from_top_level ();
12557 pop_tinst_level ();
12559 /* The vtable for a template class can be emitted in any translation
12560 unit in which the class is instantiated. When there is no key
12561 method, however, finish_struct_1 will already have added TYPE to
12562 the keyed_classes. */
12563 if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
12564 vec_safe_push (keyed_classes, type);
12566 return type;
12569 tree
12570 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12572 tree r;
12574 if (!t)
12575 r = t;
12576 else if (TYPE_P (t))
12577 r = tsubst (t, args, complain, in_decl);
12578 else
12580 if (!(complain & tf_warning))
12581 ++c_inhibit_evaluation_warnings;
12582 r = tsubst_expr (t, args, complain, in_decl);
12583 if (!(complain & tf_warning))
12584 --c_inhibit_evaluation_warnings;
12587 return r;
12590 /* Given a function parameter pack TMPL_PARM and some function parameters
12591 instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
12592 and set *SPEC_P to point at the next point in the list. */
12594 tree
12595 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
12597 /* Collect all of the extra "packed" parameters into an
12598 argument pack. */
12599 tree argpack;
12600 tree spec_parm = *spec_p;
12601 int len;
12603 for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
12604 if (tmpl_parm
12605 && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
12606 break;
12608 spec_parm = *spec_p;
12609 if (len == 1 && DECL_PACK_P (spec_parm))
12611 /* The instantiation is still a parameter pack; don't wrap it in a
12612 NONTYPE_ARGUMENT_PACK. */
12613 argpack = spec_parm;
12614 spec_parm = DECL_CHAIN (spec_parm);
12616 else
12618 /* Fill in PARMVEC with all of the parameters. */
12619 tree parmvec = make_tree_vec (len);
12620 argpack = make_node (NONTYPE_ARGUMENT_PACK);
12621 for (int i = 0; i < len; i++)
12623 tree elt = spec_parm;
12624 if (DECL_PACK_P (elt))
12625 elt = make_pack_expansion (elt);
12626 TREE_VEC_ELT (parmvec, i) = elt;
12627 spec_parm = DECL_CHAIN (spec_parm);
12630 /* Build the argument packs. */
12631 ARGUMENT_PACK_ARGS (argpack) = parmvec;
12633 *spec_p = spec_parm;
12635 return argpack;
12638 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
12639 NONTYPE_ARGUMENT_PACK. */
12641 static tree
12642 make_fnparm_pack (tree spec_parm)
12644 return extract_fnparm_pack (NULL_TREE, &spec_parm);
12647 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
12648 pack expansion with no extra args, 2 if it has extra args, or 0
12649 if it is not a pack expansion. */
12651 static int
12652 argument_pack_element_is_expansion_p (tree arg_pack, int i)
12654 if (TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12655 /* We're being called before this happens in tsubst_pack_expansion. */
12656 arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12657 tree vec = ARGUMENT_PACK_ARGS (arg_pack);
12658 if (i >= TREE_VEC_LENGTH (vec))
12659 return 0;
12660 tree elt = TREE_VEC_ELT (vec, i);
12661 if (DECL_P (elt))
12662 /* A decl pack is itself an expansion. */
12663 elt = TREE_TYPE (elt);
12664 if (!PACK_EXPANSION_P (elt))
12665 return 0;
12666 if (PACK_EXPANSION_EXTRA_ARGS (elt))
12667 return 2;
12668 return 1;
12672 /* Creates and return an ARGUMENT_PACK_SELECT tree node. */
12674 static tree
12675 make_argument_pack_select (tree arg_pack, unsigned index)
12677 tree aps = make_node (ARGUMENT_PACK_SELECT);
12679 ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
12680 ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12682 return aps;
12685 /* This is a subroutine of tsubst_pack_expansion.
12687 It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
12688 mechanism to store the (non complete list of) arguments of the
12689 substitution and return a non substituted pack expansion, in order
12690 to wait for when we have enough arguments to really perform the
12691 substitution. */
12693 static bool
12694 use_pack_expansion_extra_args_p (tree t,
12695 tree parm_packs,
12696 int arg_pack_len,
12697 bool has_empty_arg)
12699 if (has_empty_arg
12700 && PACK_EXPANSION_FORCE_EXTRA_ARGS_P (t))
12701 return true;
12703 /* If one pack has an expansion and another pack has a normal
12704 argument or if one pack has an empty argument and an another
12705 one hasn't then tsubst_pack_expansion cannot perform the
12706 substitution and need to fall back on the
12707 PACK_EXPANSION_EXTRA mechanism. */
12708 if (parm_packs == NULL_TREE)
12709 return false;
12710 else if (has_empty_arg)
12712 /* If all the actual packs are pack expansions, we can still
12713 subsitute directly. */
12714 for (tree p = parm_packs; p; p = TREE_CHAIN (p))
12716 tree a = TREE_VALUE (p);
12717 if (TREE_CODE (a) == ARGUMENT_PACK_SELECT)
12718 a = ARGUMENT_PACK_SELECT_FROM_PACK (a);
12719 a = ARGUMENT_PACK_ARGS (a);
12720 if (TREE_VEC_LENGTH (a) == 1)
12721 a = TREE_VEC_ELT (a, 0);
12722 if (PACK_EXPANSION_P (a))
12723 continue;
12724 return true;
12726 return false;
12729 for (int i = 0 ; i < arg_pack_len; ++i)
12731 bool has_expansion_arg = false;
12732 bool has_non_expansion_arg = false;
12733 for (tree parm_pack = parm_packs;
12734 parm_pack;
12735 parm_pack = TREE_CHAIN (parm_pack))
12737 tree arg = TREE_VALUE (parm_pack);
12739 int exp = argument_pack_element_is_expansion_p (arg, i);
12740 if (exp == 2)
12741 /* We can't substitute a pack expansion with extra args into
12742 our pattern. */
12743 return true;
12744 else if (exp)
12745 has_expansion_arg = true;
12746 else
12747 has_non_expansion_arg = true;
12750 if (has_expansion_arg && has_non_expansion_arg)
12752 gcc_checking_assert (false);
12753 return true;
12756 return false;
12759 /* [temp.variadic]/6 says that:
12761 The instantiation of a pack expansion [...]
12762 produces a list E1,E2, ..., En, where N is the number of elements
12763 in the pack expansion parameters.
12765 This subroutine of tsubst_pack_expansion produces one of these Ei.
12767 PATTERN is the pattern of the pack expansion. PARM_PACKS is a
12768 TREE_LIST in which each TREE_PURPOSE is a parameter pack of
12769 PATTERN, and each TREE_VALUE is its corresponding argument pack.
12770 INDEX is the index 'i' of the element Ei to produce. ARGS,
12771 COMPLAIN, and IN_DECL are the same parameters as for the
12772 tsubst_pack_expansion function.
12774 The function returns the resulting Ei upon successful completion,
12775 or error_mark_node.
12777 Note that this function possibly modifies the ARGS parameter, so
12778 it's the responsibility of the caller to restore it. */
12780 static tree
12781 gen_elem_of_pack_expansion_instantiation (tree pattern,
12782 tree parm_packs,
12783 unsigned index,
12784 tree args /* This parm gets
12785 modified. */,
12786 tsubst_flags_t complain,
12787 tree in_decl)
12789 tree t;
12790 bool ith_elem_is_expansion = false;
12792 /* For each parameter pack, change the substitution of the parameter
12793 pack to the ith argument in its argument pack, then expand the
12794 pattern. */
12795 for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
12797 tree parm = TREE_PURPOSE (pack);
12798 tree arg_pack = TREE_VALUE (pack);
12799 tree aps; /* instance of ARGUMENT_PACK_SELECT. */
12801 ith_elem_is_expansion |=
12802 argument_pack_element_is_expansion_p (arg_pack, index);
12804 /* Select the Ith argument from the pack. */
12805 if (TREE_CODE (parm) == PARM_DECL
12806 || VAR_P (parm)
12807 || TREE_CODE (parm) == FIELD_DECL)
12809 if (index == 0)
12811 aps = make_argument_pack_select (arg_pack, index);
12812 if (!mark_used (parm, complain) && !(complain & tf_error))
12813 return error_mark_node;
12814 register_local_specialization (aps, parm);
12816 else
12817 aps = retrieve_local_specialization (parm);
12819 else
12821 int idx, level;
12822 template_parm_level_and_index (parm, &level, &idx);
12824 if (index == 0)
12826 aps = make_argument_pack_select (arg_pack, index);
12827 /* Update the corresponding argument. */
12828 TMPL_ARG (args, level, idx) = aps;
12830 else
12831 /* Re-use the ARGUMENT_PACK_SELECT. */
12832 aps = TMPL_ARG (args, level, idx);
12834 ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12837 /* Substitute into the PATTERN with the (possibly altered)
12838 arguments. */
12839 if (pattern == in_decl)
12840 /* Expanding a fixed parameter pack from
12841 coerce_template_parameter_pack. */
12842 t = tsubst_decl (pattern, args, complain);
12843 else if (pattern == error_mark_node)
12844 t = error_mark_node;
12845 else if (!TYPE_P (pattern))
12846 t = tsubst_expr (pattern, args, complain, in_decl);
12847 else
12849 t = tsubst (pattern, args, complain, in_decl);
12850 if (is_auto (t) && !ith_elem_is_expansion)
12851 /* When expanding the fake auto... pack expansion from add_capture, we
12852 need to mark that the expansion is no longer a pack. */
12853 TEMPLATE_TYPE_PARAMETER_PACK (t) = false;
12856 /* If the Ith argument pack element is a pack expansion, then
12857 the Ith element resulting from the substituting is going to
12858 be a pack expansion as well. */
12859 if (ith_elem_is_expansion)
12860 t = make_pack_expansion (t, complain);
12862 return t;
12865 /* When the unexpanded parameter pack in a fold expression expands to an empty
12866 sequence, the value of the expression is as follows; the program is
12867 ill-formed if the operator is not listed in this table.
12869 && true
12870 || false
12871 , void() */
12873 tree
12874 expand_empty_fold (tree t, tsubst_flags_t complain)
12876 tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
12877 if (!FOLD_EXPR_MODIFY_P (t))
12878 switch (code)
12880 case TRUTH_ANDIF_EXPR:
12881 return boolean_true_node;
12882 case TRUTH_ORIF_EXPR:
12883 return boolean_false_node;
12884 case COMPOUND_EXPR:
12885 return void_node;
12886 default:
12887 break;
12890 if (complain & tf_error)
12891 error_at (location_of (t),
12892 "fold of empty expansion over %O", code);
12893 return error_mark_node;
12896 /* Given a fold-expression T and a current LEFT and RIGHT operand,
12897 form an expression that combines the two terms using the
12898 operator of T. */
12900 static tree
12901 fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
12903 tree_code code = FOLD_EXPR_OP (t);
12905 tree lookups = templated_operator_saved_lookups (t);
12907 // Handle compound assignment operators.
12908 if (FOLD_EXPR_MODIFY_P (t))
12909 return build_x_modify_expr (input_location, left, code, right,
12910 lookups, complain);
12912 warning_sentinel s(warn_parentheses);
12913 switch (code)
12915 case COMPOUND_EXPR:
12916 return build_x_compound_expr (input_location, left, right,
12917 lookups, complain);
12918 default:
12919 return build_x_binary_op (input_location, code,
12920 left, TREE_CODE (left),
12921 right, TREE_CODE (right),
12922 lookups, /*overload=*/NULL,
12923 complain);
12927 /* Substitute ARGS into the pack of a fold expression T. */
12929 static inline tree
12930 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12932 return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
12935 /* Substitute ARGS into the pack of a fold expression T. */
12937 static inline tree
12938 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12940 return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl);
12943 /* Expand a PACK of arguments into a grouped as left fold.
12944 Given a pack containing elements A0, A1, ..., An and an
12945 operator @, this builds the expression:
12947 ((A0 @ A1) @ A2) ... @ An
12949 Note that PACK must not be empty.
12951 The operator is defined by the original fold expression T. */
12953 static tree
12954 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
12956 tree left = TREE_VEC_ELT (pack, 0);
12957 for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
12959 tree right = TREE_VEC_ELT (pack, i);
12960 left = fold_expression (t, left, right, complain);
12962 return left;
12965 /* Substitute into a unary left fold expression. */
12967 static tree
12968 tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
12969 tree in_decl)
12971 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12972 if (pack == error_mark_node)
12973 return error_mark_node;
12974 if (PACK_EXPANSION_P (pack))
12976 tree r = copy_node (t);
12977 FOLD_EXPR_PACK (r) = pack;
12978 return r;
12980 if (TREE_VEC_LENGTH (pack) == 0)
12981 return expand_empty_fold (t, complain);
12982 else
12983 return expand_left_fold (t, pack, complain);
12986 /* Substitute into a binary left fold expression.
12988 Do ths by building a single (non-empty) vector of argumnts and
12989 building the expression from those elements. */
12991 static tree
12992 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
12993 tree in_decl)
12995 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12996 if (pack == error_mark_node)
12997 return error_mark_node;
12998 tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
12999 if (init == error_mark_node)
13000 return error_mark_node;
13002 if (PACK_EXPANSION_P (pack))
13004 tree r = copy_node (t);
13005 FOLD_EXPR_PACK (r) = pack;
13006 FOLD_EXPR_INIT (r) = init;
13007 return r;
13010 tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
13011 TREE_VEC_ELT (vec, 0) = init;
13012 for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
13013 TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
13015 return expand_left_fold (t, vec, complain);
13018 /* Expand a PACK of arguments into a grouped as right fold.
13019 Given a pack containing elementns A0, A1, ..., and an
13020 operator @, this builds the expression:
13022 A0@ ... (An-2 @ (An-1 @ An))
13024 Note that PACK must not be empty.
13026 The operator is defined by the original fold expression T. */
13028 tree
13029 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
13031 // Build the expression.
13032 int n = TREE_VEC_LENGTH (pack);
13033 tree right = TREE_VEC_ELT (pack, n - 1);
13034 for (--n; n != 0; --n)
13036 tree left = TREE_VEC_ELT (pack, n - 1);
13037 right = fold_expression (t, left, right, complain);
13039 return right;
13042 /* Substitute into a unary right fold expression. */
13044 static tree
13045 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
13046 tree in_decl)
13048 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13049 if (pack == error_mark_node)
13050 return error_mark_node;
13051 if (PACK_EXPANSION_P (pack))
13053 tree r = copy_node (t);
13054 FOLD_EXPR_PACK (r) = pack;
13055 return r;
13057 if (TREE_VEC_LENGTH (pack) == 0)
13058 return expand_empty_fold (t, complain);
13059 else
13060 return expand_right_fold (t, pack, complain);
13063 /* Substitute into a binary right fold expression.
13065 Do ths by building a single (non-empty) vector of arguments and
13066 building the expression from those elements. */
13068 static tree
13069 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
13070 tree in_decl)
13072 tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
13073 if (pack == error_mark_node)
13074 return error_mark_node;
13075 tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
13076 if (init == error_mark_node)
13077 return error_mark_node;
13079 if (PACK_EXPANSION_P (pack))
13081 tree r = copy_node (t);
13082 FOLD_EXPR_PACK (r) = pack;
13083 FOLD_EXPR_INIT (r) = init;
13084 return r;
13087 int n = TREE_VEC_LENGTH (pack);
13088 tree vec = make_tree_vec (n + 1);
13089 for (int i = 0; i < n; ++i)
13090 TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
13091 TREE_VEC_ELT (vec, n) = init;
13093 return expand_right_fold (t, vec, complain);
13096 /* Walk through the pattern of a pack expansion, adding everything in
13097 local_specializations to a list. */
13099 class el_data
13101 public:
13102 /* Set of variables declared within the pattern. */
13103 hash_set<tree> internal;
13104 /* Set of AST nodes that have been visited by the traversal. */
13105 hash_set<tree> visited;
13106 /* List of local_specializations used within the pattern. */
13107 tree extra;
13108 tsubst_flags_t complain;
13109 /* True iff we don't want to walk into unevaluated contexts. */
13110 bool skip_unevaluated_operands = false;
13111 /* The unevaluated contexts that we avoided walking. */
13112 auto_vec<tree> skipped_trees;
13114 el_data (tsubst_flags_t c)
13115 : extra (NULL_TREE), complain (c) {}
13117 static tree
13118 extract_locals_r (tree *tp, int *walk_subtrees, void *data_)
13120 el_data &data = *reinterpret_cast<el_data*>(data_);
13121 tree *extra = &data.extra;
13122 tsubst_flags_t complain = data.complain;
13124 if (data.skip_unevaluated_operands
13125 && unevaluated_p (TREE_CODE (*tp)))
13127 data.skipped_trees.safe_push (*tp);
13128 *walk_subtrees = 0;
13129 return NULL_TREE;
13132 if (TYPE_P (*tp) && typedef_variant_p (*tp))
13133 /* Remember local typedefs (85214). */
13134 tp = &TYPE_NAME (*tp);
13136 if (TREE_CODE (*tp) == DECL_EXPR)
13138 tree decl = DECL_EXPR_DECL (*tp);
13139 data.internal.add (decl);
13140 if (VAR_P (decl)
13141 && DECL_DECOMPOSITION_P (decl)
13142 && TREE_TYPE (decl) != error_mark_node)
13144 gcc_assert (DECL_NAME (decl) == NULL_TREE);
13145 for (tree decl2 = DECL_CHAIN (decl);
13146 decl2
13147 && VAR_P (decl2)
13148 && DECL_DECOMPOSITION_P (decl2)
13149 && DECL_NAME (decl2)
13150 && TREE_TYPE (decl2) != error_mark_node;
13151 decl2 = DECL_CHAIN (decl2))
13153 gcc_assert (DECL_DECOMP_BASE (decl2) == decl);
13154 data.internal.add (decl2);
13158 else if (TREE_CODE (*tp) == LAMBDA_EXPR)
13160 /* Since we defer implicit capture, look in the parms and body. */
13161 tree fn = lambda_function (*tp);
13162 cp_walk_tree (&TREE_TYPE (fn), &extract_locals_r, &data,
13163 &data.visited);
13164 cp_walk_tree (&DECL_SAVED_TREE (fn), &extract_locals_r, &data,
13165 &data.visited);
13167 else if (tree spec = retrieve_local_specialization (*tp))
13169 if (data.internal.contains (*tp))
13170 /* Don't mess with variables declared within the pattern. */
13171 return NULL_TREE;
13172 if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
13174 /* Maybe pull out the PARM_DECL for a partial instantiation. */
13175 tree args = ARGUMENT_PACK_ARGS (spec);
13176 if (TREE_VEC_LENGTH (args) == 1)
13178 tree elt = TREE_VEC_ELT (args, 0);
13179 if (PACK_EXPANSION_P (elt))
13180 elt = PACK_EXPANSION_PATTERN (elt);
13181 if (DECL_PACK_P (elt))
13182 spec = elt;
13184 if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
13186 /* Handle lambda capture here, since we aren't doing any
13187 substitution now, and so tsubst_copy won't call
13188 process_outer_var_ref. */
13189 tree args = ARGUMENT_PACK_ARGS (spec);
13190 int len = TREE_VEC_LENGTH (args);
13191 for (int i = 0; i < len; ++i)
13193 tree arg = TREE_VEC_ELT (args, i);
13194 tree carg = arg;
13195 if (outer_automatic_var_p (arg))
13196 carg = process_outer_var_ref (arg, complain);
13197 if (carg != arg)
13199 /* Make a new NONTYPE_ARGUMENT_PACK of the capture
13200 proxies. */
13201 if (i == 0)
13203 spec = copy_node (spec);
13204 args = copy_node (args);
13205 ARGUMENT_PACK_ARGS (spec) = args;
13206 register_local_specialization (spec, *tp);
13208 TREE_VEC_ELT (args, i) = carg;
13213 if (outer_automatic_var_p (spec))
13214 spec = process_outer_var_ref (spec, complain);
13215 *extra = tree_cons (*tp, spec, *extra);
13217 return NULL_TREE;
13219 static tree
13220 extract_local_specs (tree pattern, tsubst_flags_t complain)
13222 el_data data (complain);
13223 /* Walk the pattern twice, ignoring unevaluated operands the first time
13224 around, so that if a local specialization appears in both an evaluated
13225 and unevaluated context we prefer to process it in the evaluated context
13226 (since e.g. process_outer_var_ref is a no-op inside an unevaluated
13227 context). */
13228 data.skip_unevaluated_operands = true;
13229 cp_walk_tree (&pattern, extract_locals_r, &data, &data.visited);
13230 /* Now walk the unevaluated contexts we skipped the first time around. */
13231 data.skip_unevaluated_operands = false;
13232 for (tree t : data.skipped_trees)
13234 data.visited.remove (t);
13235 cp_walk_tree (&t, extract_locals_r, &data, &data.visited);
13237 return data.extra;
13240 /* Extract any uses of local_specializations from PATTERN and add them to ARGS
13241 for use in PACK_EXPANSION_EXTRA_ARGS. */
13243 tree
13244 build_extra_args (tree pattern, tree args, tsubst_flags_t complain)
13246 /* Make a copy of the extra arguments so that they won't get changed
13247 out from under us. */
13248 tree extra = preserve_args (copy_template_args (args), /*cow_p=*/false);
13249 if (local_specializations)
13250 if (tree locals = extract_local_specs (pattern, complain))
13251 extra = tree_cons (NULL_TREE, extra, locals);
13252 return extra;
13255 /* Apply any local specializations from PACK_EXPANSION_EXTRA_ARGS and add the
13256 normal template args to ARGS. */
13258 tree
13259 add_extra_args (tree extra, tree args, tsubst_flags_t complain, tree in_decl)
13261 if (extra && TREE_CODE (extra) == TREE_LIST)
13263 for (tree elt = TREE_CHAIN (extra); elt; elt = TREE_CHAIN (elt))
13265 /* The partial instantiation involved local declarations collected in
13266 extract_local_specs; map from the general template to our local
13267 context. */
13268 tree gen = TREE_PURPOSE (elt);
13269 tree inst = TREE_VALUE (elt);
13270 if (DECL_P (inst))
13271 if (tree local = retrieve_local_specialization (inst))
13272 inst = local;
13273 /* else inst is already a full instantiation of the pack. */
13274 register_local_specialization (inst, gen);
13276 gcc_assert (!TREE_PURPOSE (extra));
13277 extra = TREE_VALUE (extra);
13279 if (uses_template_parms (extra))
13281 /* This can happen after dependent substitution into a
13282 requires-expr or a lambda that uses constexpr if. */
13283 extra = tsubst_template_args (extra, args, complain, in_decl);
13284 args = add_outermost_template_args (args, extra);
13286 else
13287 args = add_to_template_args (extra, args);
13288 return args;
13291 /* Substitute ARGS into T, which is an pack expansion
13292 (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
13293 TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
13294 (if only a partial substitution could be performed) or
13295 ERROR_MARK_NODE if there was an error. */
13296 tree
13297 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
13298 tree in_decl)
13300 tree pattern;
13301 tree pack, packs = NULL_TREE;
13302 bool unsubstituted_packs = false;
13303 int i, len = -1;
13304 tree result;
13305 bool need_local_specializations = false;
13306 int levels;
13308 gcc_assert (PACK_EXPANSION_P (t));
13309 pattern = PACK_EXPANSION_PATTERN (t);
13311 /* Add in any args remembered from an earlier partial instantiation. */
13312 args = add_extra_args (PACK_EXPANSION_EXTRA_ARGS (t), args, complain, in_decl);
13314 levels = TMPL_ARGS_DEPTH (args);
13316 /* Determine the argument packs that will instantiate the parameter
13317 packs used in the expansion expression. While we're at it,
13318 compute the number of arguments to be expanded and make sure it
13319 is consistent. */
13320 for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
13321 pack = TREE_CHAIN (pack))
13323 tree parm_pack = TREE_VALUE (pack);
13324 tree arg_pack = NULL_TREE;
13325 tree orig_arg = NULL_TREE;
13326 int level = 0;
13328 if (TREE_CODE (parm_pack) == BASES)
13330 gcc_assert (parm_pack == pattern);
13331 if (BASES_DIRECT (parm_pack))
13332 return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
13333 args, complain,
13334 in_decl),
13335 complain);
13336 else
13337 return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
13338 args, complain, in_decl),
13339 complain);
13341 else if (builtin_pack_call_p (parm_pack))
13343 if (parm_pack != pattern)
13345 if (complain & tf_error)
13346 sorry ("%qE is not the entire pattern of the pack expansion",
13347 parm_pack);
13348 return error_mark_node;
13350 return expand_builtin_pack_call (parm_pack, args,
13351 complain, in_decl);
13353 else if (TREE_CODE (parm_pack) == PARM_DECL)
13355 /* We know we have correct local_specializations if this
13356 expansion is at function scope, or if we're dealing with a
13357 local parameter in a requires expression; for the latter,
13358 tsubst_requires_expr set it up appropriately. */
13359 if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
13360 arg_pack = retrieve_local_specialization (parm_pack);
13361 else
13362 /* We can't rely on local_specializations for a parameter
13363 name used later in a function declaration (such as in a
13364 late-specified return type). Even if it exists, it might
13365 have the wrong value for a recursive call. */
13366 need_local_specializations = true;
13368 if (!arg_pack)
13370 /* This parameter pack was used in an unevaluated context. Just
13371 make a dummy decl, since it's only used for its type. */
13372 ++cp_unevaluated_operand;
13373 arg_pack = tsubst_decl (parm_pack, args, complain);
13374 --cp_unevaluated_operand;
13375 if (arg_pack && DECL_PACK_P (arg_pack))
13376 /* Partial instantiation of the parm_pack, we can't build
13377 up an argument pack yet. */
13378 arg_pack = NULL_TREE;
13379 else
13380 arg_pack = make_fnparm_pack (arg_pack);
13382 else if (DECL_PACK_P (arg_pack))
13383 /* This argument pack isn't fully instantiated yet. */
13384 arg_pack = NULL_TREE;
13386 else if (is_capture_proxy (parm_pack))
13388 arg_pack = retrieve_local_specialization (parm_pack);
13389 if (DECL_PACK_P (arg_pack))
13390 arg_pack = NULL_TREE;
13392 else
13394 int idx;
13395 template_parm_level_and_index (parm_pack, &level, &idx);
13396 if (level <= levels)
13397 arg_pack = TMPL_ARG (args, level, idx);
13399 if (arg_pack && TREE_CODE (arg_pack) == TEMPLATE_TYPE_PARM
13400 && TEMPLATE_TYPE_PARAMETER_PACK (arg_pack))
13401 arg_pack = NULL_TREE;
13404 orig_arg = arg_pack;
13405 if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
13406 arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
13408 if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
13409 /* This can only happen if we forget to expand an argument
13410 pack somewhere else. Just return an error, silently. */
13412 result = make_tree_vec (1);
13413 TREE_VEC_ELT (result, 0) = error_mark_node;
13414 return result;
13417 if (arg_pack)
13419 int my_len =
13420 TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
13422 /* Don't bother trying to do a partial substitution with
13423 incomplete packs; we'll try again after deduction. */
13424 if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
13425 return t;
13427 if (len < 0)
13428 len = my_len;
13429 else if (len != my_len)
13431 if (!(complain & tf_error))
13432 /* Fail quietly. */;
13433 else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
13434 error ("mismatched argument pack lengths while expanding %qT",
13435 pattern);
13436 else
13437 error ("mismatched argument pack lengths while expanding %qE",
13438 pattern);
13439 return error_mark_node;
13442 /* Keep track of the parameter packs and their corresponding
13443 argument packs. */
13444 packs = tree_cons (parm_pack, arg_pack, packs);
13445 TREE_TYPE (packs) = orig_arg;
13447 else
13449 /* We can't substitute for this parameter pack. We use a flag as
13450 well as the missing_level counter because function parameter
13451 packs don't have a level. */
13452 gcc_assert (processing_template_decl || is_auto (parm_pack));
13453 unsubstituted_packs = true;
13457 /* If the expansion is just T..., return the matching argument pack, unless
13458 we need to call convert_from_reference on all the elements. This is an
13459 important optimization; see c++/68422. */
13460 if (!unsubstituted_packs
13461 && TREE_PURPOSE (packs) == pattern)
13463 tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
13465 /* If the argument pack is a single pack expansion, pull it out. */
13466 if (TREE_VEC_LENGTH (args) == 1
13467 && pack_expansion_args_count (args))
13468 return TREE_VEC_ELT (args, 0);
13470 /* Types need no adjustment, nor does sizeof..., and if we still have
13471 some pack expansion args we won't do anything yet. */
13472 if (TREE_CODE (t) == TYPE_PACK_EXPANSION
13473 || PACK_EXPANSION_SIZEOF_P (t)
13474 || pack_expansion_args_count (args))
13475 return args;
13476 /* Also optimize expression pack expansions if we can tell that the
13477 elements won't have reference type. */
13478 tree type = TREE_TYPE (pattern);
13479 if (type && !TYPE_REF_P (type)
13480 && !PACK_EXPANSION_P (type)
13481 && !WILDCARD_TYPE_P (type))
13482 return args;
13483 /* Otherwise use the normal path so we get convert_from_reference. */
13486 /* We cannot expand this expansion expression, because we don't have
13487 all of the argument packs we need. */
13488 if (use_pack_expansion_extra_args_p (t, packs, len, unsubstituted_packs))
13490 /* We got some full packs, but we can't substitute them in until we
13491 have values for all the packs. So remember these until then. */
13493 t = make_pack_expansion (pattern, complain);
13494 PACK_EXPANSION_EXTRA_ARGS (t)
13495 = build_extra_args (pattern, args, complain);
13496 return t;
13499 /* If NEED_LOCAL_SPECIALIZATIONS then we're in a late-specified return
13500 type, so create our own local specializations map; the current map is
13501 either NULL or (in the case of recursive unification) might have
13502 bindings that we don't want to use or alter. */
13503 local_specialization_stack lss (need_local_specializations
13504 ? lss_blank : lss_nop);
13506 if (unsubstituted_packs)
13508 /* There were no real arguments, we're just replacing a parameter
13509 pack with another version of itself. Substitute into the
13510 pattern and return a PACK_EXPANSION_*. The caller will need to
13511 deal with that. */
13512 if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
13513 result = tsubst_expr (pattern, args, complain, in_decl);
13514 else
13515 result = tsubst (pattern, args, complain, in_decl);
13516 result = make_pack_expansion (result, complain);
13517 PACK_EXPANSION_LOCAL_P (result) = PACK_EXPANSION_LOCAL_P (t);
13518 PACK_EXPANSION_SIZEOF_P (result) = PACK_EXPANSION_SIZEOF_P (t);
13519 if (PACK_EXPANSION_AUTO_P (t))
13521 /* This is a fake auto... pack expansion created in add_capture with
13522 _PACKS that don't appear in the pattern. Copy one over. */
13523 packs = PACK_EXPANSION_PARAMETER_PACKS (t);
13524 pack = retrieve_local_specialization (TREE_VALUE (packs));
13525 gcc_checking_assert (DECL_PACK_P (pack));
13526 PACK_EXPANSION_PARAMETER_PACKS (result)
13527 = build_tree_list (NULL_TREE, pack);
13528 PACK_EXPANSION_AUTO_P (result) = true;
13530 return result;
13533 gcc_assert (len >= 0);
13535 /* For each argument in each argument pack, substitute into the
13536 pattern. */
13537 result = make_tree_vec (len);
13538 tree elem_args = copy_template_args (args);
13539 for (i = 0; i < len; ++i)
13541 t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
13543 elem_args, complain,
13544 in_decl);
13545 TREE_VEC_ELT (result, i) = t;
13546 if (t == error_mark_node)
13548 result = error_mark_node;
13549 break;
13553 /* Update ARGS to restore the substitution from parameter packs to
13554 their argument packs. */
13555 for (pack = packs; pack; pack = TREE_CHAIN (pack))
13557 tree parm = TREE_PURPOSE (pack);
13559 if (TREE_CODE (parm) == PARM_DECL
13560 || VAR_P (parm)
13561 || TREE_CODE (parm) == FIELD_DECL)
13562 register_local_specialization (TREE_TYPE (pack), parm);
13563 else
13565 int idx, level;
13567 if (TREE_VALUE (pack) == NULL_TREE)
13568 continue;
13570 template_parm_level_and_index (parm, &level, &idx);
13572 /* Update the corresponding argument. */
13573 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
13574 TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
13575 TREE_TYPE (pack);
13576 else
13577 TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
13581 /* If the dependent pack arguments were such that we end up with only a
13582 single pack expansion again, there's no need to keep it in a TREE_VEC. */
13583 if (len == 1 && TREE_CODE (result) == TREE_VEC
13584 && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
13585 return TREE_VEC_ELT (result, 0);
13587 return result;
13590 /* Make an argument pack out of the TREE_VEC VEC. */
13592 static tree
13593 make_argument_pack (tree vec)
13595 tree pack;
13597 if (TYPE_P (TREE_VEC_ELT (vec, 0)))
13598 pack = cxx_make_type (TYPE_ARGUMENT_PACK);
13599 else
13601 pack = make_node (NONTYPE_ARGUMENT_PACK);
13602 TREE_CONSTANT (pack) = 1;
13604 ARGUMENT_PACK_ARGS (pack) = vec;
13605 return pack;
13608 /* Return an exact copy of template args T that can be modified
13609 independently. */
13611 static tree
13612 copy_template_args (tree t)
13614 if (t == error_mark_node)
13615 return t;
13617 int len = TREE_VEC_LENGTH (t);
13618 tree new_vec = make_tree_vec (len);
13620 for (int i = 0; i < len; ++i)
13622 tree elt = TREE_VEC_ELT (t, i);
13623 if (elt && TREE_CODE (elt) == TREE_VEC)
13624 elt = copy_template_args (elt);
13625 TREE_VEC_ELT (new_vec, i) = elt;
13628 NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
13629 = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13631 return new_vec;
13634 /* Substitute ARGS into the *_ARGUMENT_PACK orig_arg. */
13636 tree
13637 tsubst_argument_pack (tree orig_arg, tree args, tsubst_flags_t complain,
13638 tree in_decl)
13640 /* This flag is used only during deduction, and we don't expect to
13641 substitute such ARGUMENT_PACKs. */
13642 gcc_assert (!ARGUMENT_PACK_INCOMPLETE_P (orig_arg));
13644 /* Substitute into each of the arguments. */
13645 tree pack_args = tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
13646 args, complain, in_decl);
13647 if (pack_args == error_mark_node)
13648 return error_mark_node;
13650 if (pack_args == ARGUMENT_PACK_ARGS (orig_arg))
13651 return orig_arg;
13653 /* If we're substituting into a generic ARGUMENT_PACK for a variadic
13654 template parameter, we might be able to avoid allocating a new
13655 ARGUMENT_PACK and reuse the corresponding ARGUMENT_PACK from ARGS
13656 if the substituted result is identical to it. */
13657 if (tree parm = template_arg_to_parm (orig_arg))
13659 int level, index;
13660 template_parm_level_and_index (parm, &level, &index);
13661 if (TMPL_ARGS_DEPTH (args) >= level)
13662 if (tree arg = TMPL_ARG (args, level, index))
13663 if (TREE_CODE (arg) == TREE_CODE (orig_arg)
13664 && ARGUMENT_PACK_ARGS (arg) == pack_args)
13666 gcc_assert (!ARGUMENT_PACK_INCOMPLETE_P (arg));
13667 return arg;
13671 tree new_arg;
13672 if (TYPE_P (orig_arg))
13674 new_arg = cxx_make_type (TREE_CODE (orig_arg));
13675 SET_TYPE_STRUCTURAL_EQUALITY (new_arg);
13677 else
13679 new_arg = make_node (TREE_CODE (orig_arg));
13680 TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
13682 ARGUMENT_PACK_ARGS (new_arg) = pack_args;
13683 return new_arg;
13686 /* Substitute ARGS into the vector or list of template arguments T. */
13688 tree
13689 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
13691 if (t == error_mark_node)
13692 return error_mark_node;
13694 /* In "sizeof(X<I>)" we need to evaluate "I". */
13695 cp_evaluated ev;
13697 const int len = TREE_VEC_LENGTH (t);
13698 tree *elts = XALLOCAVEC (tree, len);
13699 int expanded_len_adjust = 0;
13701 /* True iff the substituted result is identical to T. */
13702 bool const_subst_p = true;
13704 for (int i = 0; i < len; i++)
13706 tree orig_arg = TREE_VEC_ELT (t, i);
13707 tree new_arg;
13709 if (!orig_arg)
13710 new_arg = NULL_TREE;
13711 else if (TREE_CODE (orig_arg) == TREE_VEC)
13712 new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
13713 else if (PACK_EXPANSION_P (orig_arg))
13715 /* Substitute into an expansion expression. */
13716 new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
13718 if (TREE_CODE (new_arg) == TREE_VEC)
13719 /* Add to the expanded length adjustment the number of
13720 expanded arguments. We subtract one from this
13721 measurement, because the argument pack expression
13722 itself is already counted as 1 in
13723 LEN. EXPANDED_LEN_ADJUST can actually be negative, if
13724 the argument pack is empty. */
13725 expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
13727 else if (ARGUMENT_PACK_P (orig_arg))
13728 new_arg = tsubst_argument_pack (orig_arg, args, complain, in_decl);
13729 else
13730 new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
13732 if (new_arg == error_mark_node)
13733 return error_mark_node;
13735 elts[i] = new_arg;
13736 if (new_arg != orig_arg)
13737 const_subst_p = false;
13740 if (const_subst_p)
13741 return t;
13743 tree maybe_reuse = NULL_TREE;
13745 /* If ARGS and T are both multi-level, the substituted result may be
13746 identical to ARGS. */
13747 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (t)
13748 && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args)
13749 && TMPL_ARGS_DEPTH (t) == TMPL_ARGS_DEPTH (args))
13750 maybe_reuse = args;
13751 /* If T appears to be a vector of generic template arguments, the
13752 substituted result may be identical to the corresponding level
13753 from ARGS. */
13754 else if (tree parm = template_arg_to_parm (TREE_VEC_ELT (t, 0)))
13756 int level, index;
13757 template_parm_level_and_index (parm, &level, &index);
13758 if (index == 0 && TMPL_ARGS_DEPTH (args) >= level)
13759 maybe_reuse = TMPL_ARGS_LEVEL (args, level);
13762 /* If the substituted result is identical to MAYBE_REUSE, return
13763 it and avoid allocating a new TREE_VEC, as an optimization. */
13764 if (maybe_reuse != NULL_TREE
13765 && TREE_VEC_LENGTH (maybe_reuse) == len
13766 && std::equal (elts, elts+len, TREE_VEC_BEGIN (maybe_reuse)))
13767 return maybe_reuse;
13769 /* If T consists of only a pack expansion for which substitution yielded
13770 a TREE_VEC of the expanded elements, then reuse that TREE_VEC instead
13771 of effectively making a copy. */
13772 if (len == 1
13773 && PACK_EXPANSION_P (TREE_VEC_ELT (t, 0))
13774 && TREE_CODE (elts[0]) == TREE_VEC)
13775 return elts[0];
13777 /* Make space for the expanded arguments coming from template
13778 argument packs. */
13779 tree r = make_tree_vec (len + expanded_len_adjust);
13780 /* T can contain TREE_VECs. That happens if T contains the
13781 arguments for a member template.
13782 In that case each TREE_VEC in T represents a level of template
13783 arguments, and T won't carry any non defaulted argument count.
13784 It will rather be the nested TREE_VECs that will carry one.
13785 In other words, T carries a non defaulted argument count only
13786 if it doesn't contain any nested TREE_VEC. */
13787 if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (t))
13789 int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13790 count += expanded_len_adjust;
13791 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (r, count);
13794 int out = 0;
13795 for (int i = 0; i < len; i++)
13797 tree orig_arg = TREE_VEC_ELT (t, i);
13798 if (orig_arg
13799 && PACK_EXPANSION_P (orig_arg)
13800 && TREE_CODE (elts[i]) == TREE_VEC)
13802 /* Now expand the template argument pack "in place". */
13803 for (int idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
13804 TREE_VEC_ELT (r, out) = TREE_VEC_ELT (elts[i], idx);
13806 else
13808 TREE_VEC_ELT (r, out) = elts[i];
13809 out++;
13812 gcc_assert (out == TREE_VEC_LENGTH (r));
13814 return r;
13817 /* Substitute ARGS into one level PARMS of template parameters. */
13819 static tree
13820 tsubst_template_parms_level (tree parms, tree args, tsubst_flags_t complain)
13822 if (parms == error_mark_node)
13823 return error_mark_node;
13825 tree new_vec = make_tree_vec (TREE_VEC_LENGTH (parms));
13827 for (int i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
13829 tree tuple = TREE_VEC_ELT (parms, i);
13831 if (tuple == error_mark_node)
13832 continue;
13834 TREE_VEC_ELT (new_vec, i) =
13835 tsubst_template_parm (tuple, args, complain);
13838 return new_vec;
13841 /* Return the result of substituting ARGS into the template parameters
13842 given by PARMS. If there are m levels of ARGS and m + n levels of
13843 PARMS, then the result will contain n levels of PARMS. For
13844 example, if PARMS is `template <class T> template <class U>
13845 template <T*, U, class V>' and ARGS is {{int}, {double}} then the
13846 result will be `template <int*, double, class V>'. */
13848 static tree
13849 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
13851 tree r = NULL_TREE;
13852 tree* new_parms;
13854 /* When substituting into a template, we must set
13855 PROCESSING_TEMPLATE_DECL as the template parameters may be
13856 dependent if they are based on one-another, and the dependency
13857 predicates are short-circuit outside of templates. */
13858 ++processing_template_decl;
13860 for (new_parms = &r;
13861 parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
13862 new_parms = &(TREE_CHAIN (*new_parms)),
13863 parms = TREE_CHAIN (parms))
13865 tree new_vec = tsubst_template_parms_level (TREE_VALUE (parms),
13866 args, complain);
13867 *new_parms =
13868 tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
13869 - TMPL_ARGS_DEPTH (args)),
13870 new_vec, NULL_TREE);
13871 TEMPLATE_PARMS_CONSTRAINTS (*new_parms)
13872 = TEMPLATE_PARMS_CONSTRAINTS (parms);
13875 --processing_template_decl;
13877 return r;
13880 /* Return the result of substituting ARGS into one template parameter
13881 given by T. T Must be a TREE_LIST which TREE_VALUE is the template
13882 parameter and which TREE_PURPOSE is the default argument of the
13883 template parameter. */
13885 static tree
13886 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
13888 tree default_value, parm_decl;
13890 if (args == NULL_TREE
13891 || t == NULL_TREE
13892 || t == error_mark_node)
13893 return t;
13895 gcc_assert (TREE_CODE (t) == TREE_LIST);
13897 default_value = TREE_PURPOSE (t);
13898 parm_decl = TREE_VALUE (t);
13900 parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
13901 if (TREE_CODE (parm_decl) == PARM_DECL
13902 && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
13903 parm_decl = error_mark_node;
13904 default_value = tsubst_template_arg (default_value, args,
13905 complain, NULL_TREE);
13907 tree r = build_tree_list (default_value, parm_decl);
13908 TEMPLATE_PARM_CONSTRAINTS (r) = TEMPLATE_PARM_CONSTRAINTS (t);
13909 return r;
13912 /* Substitute in-place the TEMPLATE_PARM_CONSTRAINTS of each template
13913 parameter in PARMS for sake of declaration matching. */
13915 static void
13916 tsubst_each_template_parm_constraints (tree parms, tree args,
13917 tsubst_flags_t complain)
13919 ++processing_template_decl;
13920 for (; parms; parms = TREE_CHAIN (parms))
13922 tree level = TREE_VALUE (parms);
13923 for (tree parm : tree_vec_range (level))
13924 TEMPLATE_PARM_CONSTRAINTS (parm)
13925 = tsubst_constraint (TEMPLATE_PARM_CONSTRAINTS (parm), args,
13926 complain, NULL_TREE);
13928 --processing_template_decl;
13931 /* Substitute the ARGS into the indicated aggregate (or enumeration)
13932 type T. If T is not an aggregate or enumeration type, it is
13933 handled as if by tsubst. IN_DECL is as for tsubst. If
13934 ENTERING_SCOPE is nonzero, T is the context for a template which
13935 we are presently tsubst'ing. Return the substituted value. */
13937 static tree
13938 tsubst_aggr_type (tree t,
13939 tree args,
13940 tsubst_flags_t complain,
13941 tree in_decl,
13942 int entering_scope)
13944 if (t == NULL_TREE)
13945 return NULL_TREE;
13947 /* Handle typedefs via tsubst so that they get consistently reused. */
13948 if (typedef_variant_p (t))
13950 t = tsubst (t, args, complain, in_decl);
13951 if (t == error_mark_node)
13952 return error_mark_node;
13954 /* The effect of entering_scope is that for a dependent specialization
13955 A<T>, lookup_template_class prefers to return A's primary template
13956 type instead of the implicit instantiation. So when entering_scope,
13957 we mirror this behavior by inspecting TYPE_CANONICAL appropriately,
13958 taking advantage of the fact that lookup_template_class links the two
13959 types by setting TYPE_CANONICAL of the latter to the former. */
13960 if (entering_scope
13961 && CLASS_TYPE_P (t)
13962 && dependent_type_p (t)
13963 && TYPE_CANONICAL (t) == TREE_TYPE (TYPE_TI_TEMPLATE (t)))
13964 t = TYPE_CANONICAL (t);
13966 return t;
13969 switch (TREE_CODE (t))
13971 case RECORD_TYPE:
13972 case ENUMERAL_TYPE:
13973 case UNION_TYPE:
13974 return tsubst_aggr_type_1 (t, args, complain, in_decl, entering_scope);
13976 default:
13977 return tsubst (t, args, complain, in_decl);
13981 /* The part of tsubst_aggr_type that's shared with the RECORD_, UNION_
13982 and ENUMERAL_TYPE cases of tsubst. */
13984 static tree
13985 tsubst_aggr_type_1 (tree t,
13986 tree args,
13987 tsubst_flags_t complain,
13988 tree in_decl,
13989 int entering_scope)
13991 if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
13993 complain &= ~tf_qualifying_scope;
13995 /* Figure out what arguments are appropriate for the
13996 type we are trying to find. For example, given:
13998 template <class T> struct S;
13999 template <class T, class U> void f(T, U) { S<U> su; }
14001 and supposing that we are instantiating f<int, double>,
14002 then our ARGS will be {int, double}, but, when looking up
14003 S we only want {double}. */
14004 tree argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
14005 complain, in_decl);
14006 if (argvec == error_mark_node)
14007 return error_mark_node;
14009 tree r = lookup_template_class (t, argvec, in_decl, NULL_TREE,
14010 entering_scope, complain);
14011 return cp_build_qualified_type (r, cp_type_quals (t), complain);
14013 else
14014 /* This is not a template type, so there's nothing to do. */
14015 return t;
14018 /* Map from a FUNCTION_DECL to a vec of default argument instantiations,
14019 indexed in reverse order of the parameters. */
14021 static GTY((cache)) hash_table<tree_vec_map_cache_hasher> *defarg_inst;
14023 /* Return a reference to the vec* of defarg insts for FN. */
14025 static vec<tree,va_gc> *&
14026 defarg_insts_for (tree fn)
14028 if (!defarg_inst)
14029 defarg_inst = hash_table<tree_vec_map_cache_hasher>::create_ggc (13);
14030 tree_vec_map in = { { fn }, nullptr };
14031 tree_vec_map **slot
14032 = defarg_inst->find_slot_with_hash (&in, DECL_UID (fn), INSERT);
14033 if (!*slot)
14035 *slot = ggc_alloc<tree_vec_map> ();
14036 **slot = in;
14038 return (*slot)->to;
14041 /* Substitute into the default argument ARG (a default argument for
14042 FN), which has the indicated TYPE. */
14044 tree
14045 tsubst_default_argument (tree fn, int parmnum, tree type, tree arg,
14046 tsubst_flags_t complain)
14048 int errs = errorcount + sorrycount;
14050 /* This can happen in invalid code. */
14051 if (TREE_CODE (arg) == DEFERRED_PARSE)
14052 return arg;
14054 /* Shortcut {}. */
14055 if (BRACE_ENCLOSED_INITIALIZER_P (arg)
14056 && CONSTRUCTOR_NELTS (arg) == 0)
14057 return arg;
14059 tree parm = FUNCTION_FIRST_USER_PARM (fn);
14060 parm = chain_index (parmnum, parm);
14061 tree parmtype = TREE_TYPE (parm);
14062 if (DECL_BY_REFERENCE (parm))
14063 parmtype = TREE_TYPE (parmtype);
14064 if (parmtype == error_mark_node)
14065 return error_mark_node;
14067 gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, parmtype));
14069 /* Remember the location of the pointer to the vec rather than the location
14070 of the particular element, in case the vec grows in tsubst_expr. */
14071 vec<tree,va_gc> *&defs = defarg_insts_for (fn);
14072 /* Index in reverse order to avoid allocating space for initial parameters
14073 that don't have default arguments. */
14074 unsigned ridx = list_length (parm);
14075 if (vec_safe_length (defs) < ridx)
14076 vec_safe_grow_cleared (defs, ridx);
14077 else if (tree inst = (*defs)[ridx - 1])
14078 return inst;
14080 /* This default argument came from a template. Instantiate the
14081 default argument here, not in tsubst. In the case of
14082 something like:
14084 template <class T>
14085 struct S {
14086 static T t();
14087 void f(T = t());
14090 we must be careful to do name lookup in the scope of S<T>,
14091 rather than in the current class. */
14092 push_to_top_level ();
14093 push_access_scope (fn);
14094 push_deferring_access_checks (dk_no_deferred);
14095 /* So in_immediate_context knows this is a default argument. */
14096 begin_scope (sk_function_parms, fn);
14097 start_lambda_scope (parm);
14099 /* The default argument expression may cause implicitly defined
14100 member functions to be synthesized, which will result in garbage
14101 collection. We must treat this situation as if we were within
14102 the body of function so as to avoid collecting live data on the
14103 stack. */
14104 ++function_depth;
14105 arg = tsubst_expr (arg, DECL_TI_ARGS (fn), complain, NULL_TREE);
14106 --function_depth;
14108 finish_lambda_scope ();
14110 /* Make sure the default argument is reasonable. */
14111 arg = check_default_argument (type, arg, complain);
14113 if (errorcount+sorrycount > errs
14114 && (complain & tf_warning_or_error))
14115 inform (input_location,
14116 " when instantiating default argument for call to %qD", fn);
14118 leave_scope ();
14119 pop_deferring_access_checks ();
14120 pop_access_scope (fn);
14121 pop_from_top_level ();
14123 if (arg != error_mark_node && !cp_unevaluated_operand)
14124 (*defs)[ridx - 1] = arg;
14126 return arg;
14129 /* Substitute into all the default arguments for FN. */
14131 static void
14132 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
14134 tree arg;
14135 tree tmpl_args;
14137 tmpl_args = DECL_TI_ARGS (fn);
14139 /* If this function is not yet instantiated, we certainly don't need
14140 its default arguments. */
14141 if (uses_template_parms (tmpl_args))
14142 return;
14143 /* Don't do this again for clones. */
14144 if (DECL_CLONED_FUNCTION_P (fn))
14145 return;
14147 int i = 0;
14148 for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
14149 arg;
14150 arg = TREE_CHAIN (arg), ++i)
14151 if (TREE_PURPOSE (arg))
14152 TREE_PURPOSE (arg) = tsubst_default_argument (fn, i,
14153 TREE_VALUE (arg),
14154 TREE_PURPOSE (arg),
14155 complain);
14158 /* Hash table mapping a FUNCTION_DECL to its dependent explicit-specifier. */
14159 static GTY((cache)) decl_tree_cache_map *explicit_specifier_map;
14161 /* Store a pair to EXPLICIT_SPECIFIER_MAP. */
14163 void
14164 store_explicit_specifier (tree v, tree t)
14166 if (!explicit_specifier_map)
14167 explicit_specifier_map = decl_tree_cache_map::create_ggc (37);
14168 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (v) = true;
14169 explicit_specifier_map->put (v, t);
14172 /* Lookup an element in EXPLICIT_SPECIFIER_MAP. */
14174 tree
14175 lookup_explicit_specifier (tree v)
14177 return *explicit_specifier_map->get (v);
14180 /* Given T, a FUNCTION_TYPE or METHOD_TYPE, construct and return a corresponding
14181 FUNCTION_TYPE or METHOD_TYPE whose return type is RETURN_TYPE, argument types
14182 are ARG_TYPES, and exception specification is RAISES, and otherwise is
14183 identical to T. */
14185 static tree
14186 rebuild_function_or_method_type (tree t, tree return_type, tree arg_types,
14187 tree raises, tsubst_flags_t complain)
14189 gcc_assert (FUNC_OR_METHOD_TYPE_P (t));
14191 tree new_type;
14192 if (TREE_CODE (t) == FUNCTION_TYPE)
14194 new_type = build_function_type (return_type, arg_types);
14195 new_type = apply_memfn_quals (new_type, type_memfn_quals (t));
14197 else
14199 tree r = TREE_TYPE (TREE_VALUE (arg_types));
14200 /* Don't pick up extra function qualifiers from the basetype. */
14201 r = cp_build_qualified_type (r, type_memfn_quals (t), complain);
14202 if (! MAYBE_CLASS_TYPE_P (r))
14204 /* [temp.deduct]
14206 Type deduction may fail for any of the following
14207 reasons:
14209 -- Attempting to create "pointer to member of T" when T
14210 is not a class type. */
14211 if (complain & tf_error)
14212 error ("creating pointer to member function of non-class type %qT",
14214 return error_mark_node;
14217 new_type = build_method_type_directly (r, return_type,
14218 TREE_CHAIN (arg_types));
14220 new_type = cp_build_type_attribute_variant (new_type, TYPE_ATTRIBUTES (t));
14222 cp_ref_qualifier rqual = type_memfn_rqual (t);
14223 bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
14224 return build_cp_fntype_variant (new_type, rqual, raises, late_return_type_p);
14227 /* Check if the function type of DECL, a FUNCTION_DECL, agrees with the type of
14228 each of its formal parameters. If there is a disagreement then rebuild
14229 DECL's function type according to its formal parameter types, as part of a
14230 resolution for Core issues 1001/1322. */
14232 static void
14233 maybe_rebuild_function_decl_type (tree decl)
14235 bool function_type_needs_rebuilding = false;
14236 if (tree parm_list = FUNCTION_FIRST_USER_PARM (decl))
14238 tree parm_type_list = FUNCTION_FIRST_USER_PARMTYPE (decl);
14239 while (parm_type_list && parm_type_list != void_list_node)
14241 tree parm_type = TREE_VALUE (parm_type_list);
14242 tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
14243 if (!same_type_p (parm_type, formal_parm_type_unqual))
14245 function_type_needs_rebuilding = true;
14246 break;
14249 parm_list = DECL_CHAIN (parm_list);
14250 parm_type_list = TREE_CHAIN (parm_type_list);
14254 if (!function_type_needs_rebuilding)
14255 return;
14257 const tree fntype = TREE_TYPE (decl);
14258 tree parm_list = DECL_ARGUMENTS (decl);
14259 tree old_parm_type_list = TYPE_ARG_TYPES (fntype);
14260 tree new_parm_type_list = NULL_TREE;
14261 tree *q = &new_parm_type_list;
14262 for (int skip = num_artificial_parms_for (decl); skip > 0; skip--)
14264 *q = copy_node (old_parm_type_list);
14265 parm_list = DECL_CHAIN (parm_list);
14266 old_parm_type_list = TREE_CHAIN (old_parm_type_list);
14267 q = &TREE_CHAIN (*q);
14269 while (old_parm_type_list && old_parm_type_list != void_list_node)
14271 *q = copy_node (old_parm_type_list);
14272 tree *new_parm_type = &TREE_VALUE (*q);
14273 tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
14274 if (!same_type_p (*new_parm_type, formal_parm_type_unqual))
14275 *new_parm_type = formal_parm_type_unqual;
14277 parm_list = DECL_CHAIN (parm_list);
14278 old_parm_type_list = TREE_CHAIN (old_parm_type_list);
14279 q = &TREE_CHAIN (*q);
14281 if (old_parm_type_list == void_list_node)
14282 *q = void_list_node;
14284 TREE_TYPE (decl)
14285 = rebuild_function_or_method_type (fntype,
14286 TREE_TYPE (fntype), new_parm_type_list,
14287 TYPE_RAISES_EXCEPTIONS (fntype), tf_none);
14290 /* Subroutine of tsubst_decl for the case when T is a FUNCTION_DECL. */
14292 static tree
14293 tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
14294 tree lambda_fntype)
14296 tree gen_tmpl = NULL_TREE, argvec = NULL_TREE;
14297 hashval_t hash = 0;
14298 tree in_decl = t;
14300 /* Nobody should be tsubst'ing into non-template functions. */
14301 gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE
14302 || DECL_LOCAL_DECL_P (t));
14304 if (DECL_LOCAL_DECL_P (t))
14306 if (tree spec = retrieve_local_specialization (t))
14307 return spec;
14309 else if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
14311 /* If T is not dependent, just return it. */
14312 if (!uses_template_parms (DECL_TI_ARGS (t))
14313 && !LAMBDA_FUNCTION_P (t))
14314 return t;
14316 /* A non-templated friend doesn't get DECL_TEMPLATE_INFO. */
14317 if (non_templated_friend_p (t))
14318 goto friend_case;
14320 /* Calculate the most general template of which R is a
14321 specialization. */
14322 gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
14324 /* We're substituting a lambda function under tsubst_lambda_expr but not
14325 directly from it; find the matching function we're already inside.
14326 But don't do this if T is a generic lambda with a single level of
14327 template parms, as in that case we're doing a normal instantiation. */
14328 if (LAMBDA_FUNCTION_P (t) && !lambda_fntype
14329 && (!generic_lambda_fn_p (t)
14330 || TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)) > 1))
14331 return enclosing_instantiation_of (t);
14333 /* Calculate the complete set of arguments used to
14334 specialize R. */
14335 argvec = tsubst_template_args (DECL_TI_ARGS
14336 (DECL_TEMPLATE_RESULT
14337 (DECL_TI_TEMPLATE (t))),
14338 args, complain, in_decl);
14339 if (argvec == error_mark_node)
14340 return error_mark_node;
14342 /* Check to see if we already have this specialization. */
14343 if (!lambda_fntype)
14345 hash = spec_hasher::hash (gen_tmpl, argvec);
14346 if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
14347 /* The spec for these args might be a partial instantiation of the
14348 template, but here what we want is the FUNCTION_DECL. */
14349 return STRIP_TEMPLATE (spec);
14352 else
14354 /* This special case arises when we have something like this:
14356 template <class T> struct S {
14357 friend void f<int>(int, double);
14360 Here, the DECL_TI_TEMPLATE for the friend declaration
14361 will be an IDENTIFIER_NODE. We are being called from
14362 tsubst_friend_function, and we want only to create a
14363 new decl (R) with appropriate types so that we can call
14364 determine_specialization. */
14365 friend_case:
14366 gen_tmpl = NULL_TREE;
14367 argvec = NULL_TREE;
14370 tree closure = (lambda_fntype ? TYPE_METHOD_BASETYPE (lambda_fntype)
14371 : NULL_TREE);
14372 tree ctx = closure ? closure : DECL_CONTEXT (t);
14373 bool member = ctx && TYPE_P (ctx);
14375 /* If this is a static lambda, remove the 'this' pointer added in
14376 tsubst_lambda_expr now that we know the closure type. */
14377 if (lambda_fntype && DECL_STATIC_FUNCTION_P (t))
14378 lambda_fntype = static_fn_type (lambda_fntype);
14380 if (member && !closure)
14381 ctx = tsubst_aggr_type (ctx, args,
14382 complain, t, /*entering_scope=*/1);
14384 tree type = (lambda_fntype ? lambda_fntype
14385 : tsubst (TREE_TYPE (t), args,
14386 complain | tf_fndecl_type, in_decl));
14387 if (type == error_mark_node)
14388 return error_mark_node;
14390 /* If we hit excessive deduction depth, the type is bogus even if
14391 it isn't error_mark_node, so don't build a decl. */
14392 if (excessive_deduction_depth)
14393 return error_mark_node;
14395 /* We do NOT check for matching decls pushed separately at this
14396 point, as they may not represent instantiations of this
14397 template, and in any case are considered separate under the
14398 discrete model. */
14399 tree r = copy_decl (t);
14400 DECL_USE_TEMPLATE (r) = 0;
14401 TREE_TYPE (r) = type;
14402 /* Clear out the mangled name and RTL for the instantiation. */
14403 SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
14404 SET_DECL_RTL (r, NULL);
14405 /* Leave DECL_INITIAL set on deleted instantiations. */
14406 if (!DECL_DELETED_FN (r))
14407 DECL_INITIAL (r) = NULL_TREE;
14408 DECL_CONTEXT (r) = ctx;
14409 set_instantiating_module (r);
14411 /* Handle explicit(dependent-expr). */
14412 if (DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (t))
14414 tree spec = lookup_explicit_specifier (t);
14415 spec = tsubst_copy_and_build (spec, args, complain, in_decl);
14416 spec = build_explicit_specifier (spec, complain);
14417 if (spec == error_mark_node)
14418 return error_mark_node;
14419 if (instantiation_dependent_expression_p (spec))
14420 store_explicit_specifier (r, spec);
14421 else
14423 DECL_NONCONVERTING_P (r) = (spec == boolean_true_node);
14424 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (r) = false;
14428 /* OpenMP UDRs have the only argument a reference to the declared
14429 type. We want to diagnose if the declared type is a reference,
14430 which is invalid, but as references to references are usually
14431 quietly merged, diagnose it here. */
14432 if (DECL_OMP_DECLARE_REDUCTION_P (t))
14434 tree argtype
14435 = TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
14436 argtype = tsubst (argtype, args, complain, in_decl);
14437 if (TYPE_REF_P (argtype))
14438 error_at (DECL_SOURCE_LOCATION (t),
14439 "reference type %qT in "
14440 "%<#pragma omp declare reduction%>", argtype);
14441 if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
14442 DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
14443 argtype);
14446 if (member && DECL_CONV_FN_P (r))
14447 /* Type-conversion operator. Reconstruct the name, in
14448 case it's the name of one of the template's parameters. */
14449 DECL_NAME (r) = make_conv_op_name (TREE_TYPE (type));
14451 tree parms = DECL_ARGUMENTS (t);
14452 if (closure && !DECL_STATIC_FUNCTION_P (t))
14453 parms = DECL_CHAIN (parms);
14454 parms = tsubst (parms, args, complain, t);
14455 for (tree parm = parms; parm; parm = DECL_CHAIN (parm))
14456 DECL_CONTEXT (parm) = r;
14457 if (closure && !DECL_STATIC_FUNCTION_P (t))
14459 tree tparm = build_this_parm (r, closure, type_memfn_quals (type));
14460 DECL_NAME (tparm) = closure_identifier;
14461 DECL_CHAIN (tparm) = parms;
14462 parms = tparm;
14464 DECL_ARGUMENTS (r) = parms;
14465 DECL_RESULT (r) = NULL_TREE;
14467 maybe_rebuild_function_decl_type (r);
14469 TREE_STATIC (r) = 0;
14470 TREE_PUBLIC (r) = TREE_PUBLIC (t);
14471 DECL_EXTERNAL (r) = 1;
14472 /* If this is an instantiation of a function with internal
14473 linkage, we already know what object file linkage will be
14474 assigned to the instantiation. */
14475 DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
14476 DECL_DEFER_OUTPUT (r) = 0;
14477 DECL_CHAIN (r) = NULL_TREE;
14478 DECL_PENDING_INLINE_INFO (r) = 0;
14479 DECL_PENDING_INLINE_P (r) = 0;
14480 DECL_SAVED_TREE (r) = NULL_TREE;
14481 DECL_STRUCT_FUNCTION (r) = NULL;
14482 TREE_USED (r) = 0;
14483 /* We'll re-clone as appropriate in instantiate_template. */
14484 DECL_CLONED_FUNCTION (r) = NULL_TREE;
14486 /* If we aren't complaining now, return on error before we register
14487 the specialization so that we'll complain eventually. */
14488 if ((complain & tf_error) == 0
14489 && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14490 && !grok_op_properties (r, /*complain=*/false))
14491 return error_mark_node;
14493 /* Associate the constraints directly with the instantiation. We
14494 don't substitute through the constraints; that's only done when
14495 they are checked. */
14496 if (tree ci = get_constraints (t))
14497 set_constraints (r, ci);
14499 if (DECL_FRIEND_CONTEXT (t))
14500 SET_DECL_FRIEND_CONTEXT (r,
14501 tsubst (DECL_FRIEND_CONTEXT (t),
14502 args, complain, in_decl));
14504 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14505 args, complain, in_decl))
14506 return error_mark_node;
14508 /* Set up the DECL_TEMPLATE_INFO for R. There's no need to do
14509 this in the special friend case mentioned above where
14510 GEN_TMPL is NULL. */
14511 if (gen_tmpl && !closure)
14513 DECL_TEMPLATE_INFO (r)
14514 = build_template_info (gen_tmpl, argvec);
14515 SET_DECL_IMPLICIT_INSTANTIATION (r);
14517 tree new_r
14518 = register_specialization (r, gen_tmpl, argvec, false, hash);
14519 if (new_r != r)
14520 /* We instantiated this while substituting into
14521 the type earlier (template/friend54.C). */
14522 return new_r;
14524 /* We're not supposed to instantiate default arguments
14525 until they are called, for a template. But, for a
14526 declaration like:
14528 template <class T> void f ()
14529 { extern void g(int i = T()); }
14531 we should do the substitution when the template is
14532 instantiated. We handle the member function case in
14533 instantiate_class_template since the default arguments
14534 might refer to other members of the class. */
14535 if (!member
14536 && !PRIMARY_TEMPLATE_P (gen_tmpl)
14537 && !uses_template_parms (argvec))
14538 tsubst_default_arguments (r, complain);
14540 else if (DECL_LOCAL_DECL_P (r))
14542 if (!cp_unevaluated_operand)
14543 register_local_specialization (r, t);
14545 else
14546 DECL_TEMPLATE_INFO (r) = NULL_TREE;
14548 /* Copy the list of befriending classes. */
14549 for (tree *friends = &DECL_BEFRIENDING_CLASSES (r);
14550 *friends;
14551 friends = &TREE_CHAIN (*friends))
14553 *friends = copy_node (*friends);
14554 TREE_VALUE (*friends)
14555 = tsubst (TREE_VALUE (*friends), args, complain, in_decl);
14558 if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
14560 maybe_retrofit_in_chrg (r);
14561 if (DECL_CONSTRUCTOR_P (r) && !grok_ctor_properties (ctx, r))
14562 return error_mark_node;
14563 /* If this is an instantiation of a member template, clone it.
14564 If it isn't, that'll be handled by
14565 clone_constructors_and_destructors. */
14566 if (gen_tmpl && PRIMARY_TEMPLATE_P (gen_tmpl))
14567 clone_cdtor (r, /*update_methods=*/false);
14569 else if ((complain & tf_error) != 0
14570 && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14571 && !grok_op_properties (r, /*complain=*/true))
14572 return error_mark_node;
14574 /* Possibly limit visibility based on template args. */
14575 DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
14576 if (DECL_VISIBILITY_SPECIFIED (t))
14578 DECL_VISIBILITY_SPECIFIED (r) = 0;
14579 DECL_ATTRIBUTES (r)
14580 = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
14582 determine_visibility (r);
14583 if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
14584 && !processing_template_decl)
14585 defaulted_late_check (r);
14587 if (flag_openmp)
14588 if (tree attr = lookup_attribute ("omp declare variant base",
14589 DECL_ATTRIBUTES (r)))
14590 omp_declare_variant_finalize (r, attr);
14592 return r;
14595 /* Subroutine of tsubst_decl for the case when T is a TEMPLATE_DECL. */
14597 static tree
14598 tsubst_template_decl (tree t, tree args, tsubst_flags_t complain,
14599 tree lambda_fntype, tree lambda_tparms)
14601 /* We can get here when processing a member function template,
14602 member class template, or template template parameter. */
14603 tree decl = DECL_TEMPLATE_RESULT (t);
14604 tree in_decl = t;
14605 tree spec;
14606 tree tmpl_args;
14607 tree full_args;
14608 tree r;
14609 hashval_t hash = 0;
14611 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
14613 /* Template template parameter is treated here. */
14614 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14615 if (new_type == error_mark_node)
14616 r = error_mark_node;
14617 /* If we get a real template back, return it. This can happen in
14618 the context of most_specialized_partial_spec. */
14619 else if (TREE_CODE (new_type) == TEMPLATE_DECL)
14620 r = new_type;
14621 else
14622 /* The new TEMPLATE_DECL was built in
14623 reduce_template_parm_level. */
14624 r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
14625 return r;
14628 if (!lambda_fntype)
14630 /* We might already have an instance of this template.
14631 The ARGS are for the surrounding class type, so the
14632 full args contain the tsubst'd args for the context,
14633 plus the innermost args from the template decl. */
14634 tmpl_args = DECL_CLASS_TEMPLATE_P (t)
14635 ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
14636 : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
14637 /* Because this is a template, the arguments will still be
14638 dependent, even after substitution. If
14639 PROCESSING_TEMPLATE_DECL is not set, the dependency
14640 predicates will short-circuit. */
14641 ++processing_template_decl;
14642 full_args = tsubst_template_args (tmpl_args, args,
14643 complain, in_decl);
14644 --processing_template_decl;
14645 if (full_args == error_mark_node)
14646 return error_mark_node;
14648 /* If this is a default template template argument,
14649 tsubst might not have changed anything. */
14650 if (full_args == tmpl_args)
14651 return t;
14653 hash = spec_hasher::hash (t, full_args);
14654 spec = retrieve_specialization (t, full_args, hash);
14655 if (spec != NULL_TREE)
14657 if (TYPE_P (spec))
14658 /* Type partial instantiations are stored as the type by
14659 lookup_template_class_1, not here as the template. */
14660 spec = CLASSTYPE_TI_TEMPLATE (spec);
14661 return spec;
14665 /* Make a new template decl. It will be similar to the
14666 original, but will record the current template arguments.
14667 We also create a new function declaration, which is just
14668 like the old one, but points to this new template, rather
14669 than the old one. */
14670 r = copy_decl (t);
14671 gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
14672 DECL_CHAIN (r) = NULL_TREE;
14674 // Build new template info linking to the original template decl.
14675 if (!lambda_fntype)
14677 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
14678 SET_DECL_IMPLICIT_INSTANTIATION (r);
14680 else
14681 DECL_TEMPLATE_INFO (r) = NULL_TREE;
14683 /* The template parameters for this new template are all the
14684 template parameters for the old template, except the
14685 outermost level of parameters. */
14686 auto tparm_guard = make_temp_override (current_template_parms);
14687 DECL_TEMPLATE_PARMS (r)
14688 = current_template_parms
14689 = (lambda_tparms
14690 ? lambda_tparms
14691 : tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
14692 complain));
14694 bool class_p = false;
14695 tree inner = decl;
14696 ++processing_template_decl;
14697 if (TREE_CODE (inner) == FUNCTION_DECL)
14698 inner = tsubst_function_decl (inner, args, complain, lambda_fntype);
14699 else
14701 if (TREE_CODE (inner) == TYPE_DECL && !TYPE_DECL_ALIAS_P (inner))
14703 class_p = true;
14704 inner = TREE_TYPE (inner);
14706 if (class_p)
14707 inner = tsubst_aggr_type (inner, args, complain,
14708 in_decl, /*entering*/1);
14709 else
14710 inner = tsubst (inner, args, complain, in_decl);
14712 --processing_template_decl;
14713 if (inner == error_mark_node)
14714 return error_mark_node;
14716 if (class_p)
14718 /* For a partial specialization, we need to keep pointing to
14719 the primary template. */
14720 if (!DECL_TEMPLATE_SPECIALIZATION (t))
14722 CLASSTYPE_TI_TEMPLATE (inner) = r;
14723 CLASSTYPE_USE_TEMPLATE (inner) = 0;
14726 DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (inner);
14727 inner = TYPE_MAIN_DECL (inner);
14729 else if (lambda_fntype)
14731 tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (r));
14732 DECL_TEMPLATE_INFO (inner) = build_template_info (r, args);
14734 else
14736 DECL_TI_TEMPLATE (inner) = r;
14737 DECL_TI_ARGS (r) = DECL_TI_ARGS (inner);
14740 DECL_TEMPLATE_RESULT (r) = inner;
14741 TREE_TYPE (r) = TREE_TYPE (inner);
14742 DECL_CONTEXT (r) = DECL_CONTEXT (inner);
14744 if (modules_p ())
14746 /* Propagate module information from the decl. */
14747 DECL_MODULE_EXPORT_P (r) = DECL_MODULE_EXPORT_P (inner);
14748 if (DECL_LANG_SPECIFIC (inner))
14749 /* If this is a constrained template, the above tsubst of
14750 inner can find the unconstrained template, which may have
14751 come from an import. This is ok, because we don't
14752 register this instantiation (see below). */
14753 gcc_checking_assert (!DECL_MODULE_IMPORT_P (inner)
14754 || (TEMPLATE_PARMS_CONSTRAINTS
14755 (DECL_TEMPLATE_PARMS (t))));
14758 DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
14759 DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
14761 if (PRIMARY_TEMPLATE_P (t))
14762 DECL_PRIMARY_TEMPLATE (r) = r;
14764 if (TREE_CODE (decl) == FUNCTION_DECL && !lambda_fntype)
14765 /* Record this non-type partial instantiation. */
14766 register_specialization (r, t,
14767 DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
14768 false, hash);
14770 return r;
14773 /* True if FN is the op() for a lambda in an uninstantiated template. */
14775 bool
14776 lambda_fn_in_template_p (tree fn)
14778 if (!fn || !LAMBDA_FUNCTION_P (fn))
14779 return false;
14780 tree closure = DECL_CONTEXT (fn);
14781 return CLASSTYPE_TEMPLATE_INFO (closure) != NULL_TREE;
14784 /* True if FN is the substitution (via tsubst_lambda_expr) of a function for
14785 which the above is true. */
14787 bool
14788 regenerated_lambda_fn_p (tree fn)
14790 if (!fn || !LAMBDA_FUNCTION_P (fn))
14791 return false;
14792 tree closure = DECL_CONTEXT (fn);
14793 tree lam = CLASSTYPE_LAMBDA_EXPR (closure);
14794 return LAMBDA_EXPR_REGEN_INFO (lam) != NULL_TREE;
14797 /* Return the LAMBDA_EXPR from which T was ultimately regenerated.
14798 If T is not a regenerated LAMBDA_EXPR, return T. */
14800 tree
14801 most_general_lambda (tree t)
14803 while (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
14804 t = TI_TEMPLATE (ti);
14805 return t;
14808 /* Return the set of template arguments used to regenerate the lambda T
14809 from its most general lambda. */
14811 tree
14812 lambda_regenerating_args (tree t)
14814 if (LAMBDA_FUNCTION_P (t))
14815 t = CLASSTYPE_LAMBDA_EXPR (DECL_CONTEXT (t));
14816 gcc_assert (TREE_CODE (t) == LAMBDA_EXPR);
14817 if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
14818 return TI_ARGS (ti);
14819 else
14820 return NULL_TREE;
14823 /* We're instantiating a variable from template function TCTX. Return the
14824 corresponding current enclosing scope. We can match them up using
14825 DECL_SOURCE_LOCATION because lambdas only ever have one source location, and
14826 the DECL_SOURCE_LOCATION for a function instantiation is updated to match
14827 the template definition in regenerate_decl_from_template. */
14829 static tree
14830 enclosing_instantiation_of (tree tctx)
14832 tree fn = current_function_decl;
14834 /* We shouldn't ever need to do this for other artificial functions. */
14835 gcc_assert (!DECL_ARTIFICIAL (tctx) || LAMBDA_FUNCTION_P (tctx));
14837 for (; fn; fn = decl_function_context (fn))
14838 if (DECL_SOURCE_LOCATION (fn) == DECL_SOURCE_LOCATION (tctx))
14839 return fn;
14840 gcc_unreachable ();
14843 /* Substitute the ARGS into the T, which is a _DECL. Return the
14844 result of the substitution. Issue error and warning messages under
14845 control of COMPLAIN. */
14847 static tree
14848 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
14850 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
14851 location_t saved_loc;
14852 tree r = NULL_TREE;
14853 tree in_decl = t;
14854 hashval_t hash = 0;
14856 /* Set the filename and linenumber to improve error-reporting. */
14857 saved_loc = input_location;
14858 input_location = DECL_SOURCE_LOCATION (t);
14860 switch (TREE_CODE (t))
14862 case TEMPLATE_DECL:
14863 r = tsubst_template_decl (t, args, complain,
14864 /*lambda_fntype=*/NULL_TREE,
14865 /*lambda_tparms=*/NULL_TREE);
14866 break;
14868 case FUNCTION_DECL:
14869 r = tsubst_function_decl (t, args, complain, /*lambda*/NULL_TREE);
14870 break;
14872 case PARM_DECL:
14874 tree type = NULL_TREE;
14875 int i, len = 1;
14876 tree expanded_types = NULL_TREE;
14877 tree prev_r = NULL_TREE;
14878 tree first_r = NULL_TREE;
14880 if (DECL_PACK_P (t))
14882 /* If there is a local specialization that isn't a
14883 parameter pack, it means that we're doing a "simple"
14884 substitution from inside tsubst_pack_expansion. Just
14885 return the local specialization (which will be a single
14886 parm). */
14887 tree spec = retrieve_local_specialization (t);
14888 if (spec
14889 && TREE_CODE (spec) == PARM_DECL
14890 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
14891 RETURN (spec);
14893 /* Expand the TYPE_PACK_EXPANSION that provides the types for
14894 the parameters in this function parameter pack. */
14895 expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
14896 complain, in_decl);
14897 if (TREE_CODE (expanded_types) == TREE_VEC)
14899 len = TREE_VEC_LENGTH (expanded_types);
14901 /* Zero-length parameter packs are boring. Just substitute
14902 into the chain. */
14903 if (len == 0 && !cp_unevaluated_operand)
14904 RETURN (tsubst (TREE_CHAIN (t), args, complain,
14905 TREE_CHAIN (t)));
14907 else
14909 /* All we did was update the type. Make a note of that. */
14910 type = expanded_types;
14911 expanded_types = NULL_TREE;
14915 /* Loop through all of the parameters we'll build. When T is
14916 a function parameter pack, LEN is the number of expanded
14917 types in EXPANDED_TYPES; otherwise, LEN is 1. */
14918 r = NULL_TREE;
14919 for (i = 0; i < len; ++i)
14921 prev_r = r;
14922 r = copy_node (t);
14923 if (DECL_TEMPLATE_PARM_P (t))
14924 SET_DECL_TEMPLATE_PARM_P (r);
14926 if (expanded_types)
14927 /* We're on the Ith parameter of the function parameter
14928 pack. */
14930 /* Get the Ith type. */
14931 type = TREE_VEC_ELT (expanded_types, i);
14933 /* Rename the parameter to include the index. */
14934 DECL_NAME (r)
14935 = make_ith_pack_parameter_name (DECL_NAME (r), i);
14937 else if (!type)
14938 /* We're dealing with a normal parameter. */
14939 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14941 type = type_decays_to (type);
14942 TREE_TYPE (r) = type;
14943 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14945 if (DECL_INITIAL (r))
14947 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
14948 DECL_INITIAL (r) = TREE_TYPE (r);
14949 else
14950 DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
14951 complain, in_decl);
14954 DECL_CONTEXT (r) = NULL_TREE;
14956 if (!DECL_TEMPLATE_PARM_P (r))
14957 DECL_ARG_TYPE (r) = type_passed_as (type);
14959 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14960 args, complain, in_decl))
14961 return error_mark_node;
14963 /* Keep track of the first new parameter we
14964 generate. That's what will be returned to the
14965 caller. */
14966 if (!first_r)
14967 first_r = r;
14969 /* Build a proper chain of parameters when substituting
14970 into a function parameter pack. */
14971 if (prev_r)
14972 DECL_CHAIN (prev_r) = r;
14975 /* If cp_unevaluated_operand is set, we're just looking for a
14976 single dummy parameter, so don't keep going. */
14977 if (DECL_CHAIN (t) && !cp_unevaluated_operand)
14978 DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
14979 complain, DECL_CHAIN (t));
14981 /* FIRST_R contains the start of the chain we've built. */
14982 r = first_r;
14984 break;
14986 case FIELD_DECL:
14988 tree type = NULL_TREE;
14989 tree vec = NULL_TREE;
14990 tree expanded_types = NULL_TREE;
14991 int len = 1;
14993 if (PACK_EXPANSION_P (TREE_TYPE (t)))
14995 /* This field is a lambda capture pack. Return a TREE_VEC of
14996 the expanded fields to instantiate_class_template_1. */
14997 expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
14998 complain, in_decl);
14999 if (TREE_CODE (expanded_types) == TREE_VEC)
15001 len = TREE_VEC_LENGTH (expanded_types);
15002 vec = make_tree_vec (len);
15004 else
15006 /* All we did was update the type. Make a note of that. */
15007 type = expanded_types;
15008 expanded_types = NULL_TREE;
15012 for (int i = 0; i < len; ++i)
15014 r = copy_decl (t);
15015 if (expanded_types)
15017 type = TREE_VEC_ELT (expanded_types, i);
15018 DECL_NAME (r)
15019 = make_ith_pack_parameter_name (DECL_NAME (r), i);
15021 else if (!type)
15022 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15024 if (type == error_mark_node)
15025 RETURN (error_mark_node);
15026 TREE_TYPE (r) = type;
15027 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
15029 if (DECL_C_BIT_FIELD (r))
15030 /* For bit-fields, DECL_BIT_FIELD_REPRESENTATIVE gives the
15031 number of bits. */
15032 DECL_BIT_FIELD_REPRESENTATIVE (r)
15033 = tsubst_expr (DECL_BIT_FIELD_REPRESENTATIVE (t), args,
15034 complain, in_decl);
15035 if (DECL_INITIAL (t))
15037 /* Set up DECL_TEMPLATE_INFO so that we can get at the
15038 NSDMI in perform_member_init. Still set DECL_INITIAL
15039 so that we know there is one. */
15040 DECL_INITIAL (r) = void_node;
15041 gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
15042 retrofit_lang_decl (r);
15043 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
15045 /* We don't have to set DECL_CONTEXT here; it is set by
15046 finish_member_declaration. */
15047 DECL_CHAIN (r) = NULL_TREE;
15049 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
15050 args, complain, in_decl))
15051 return error_mark_node;
15053 if (vec)
15054 TREE_VEC_ELT (vec, i) = r;
15057 if (vec)
15058 r = vec;
15060 break;
15062 case USING_DECL:
15063 /* We reach here only for member using decls. We also need to check
15064 uses_template_parms because DECL_DEPENDENT_P is not set for a
15065 using-declaration that designates a member of the current
15066 instantiation (c++/53549). */
15067 if (DECL_DEPENDENT_P (t)
15068 || uses_template_parms (USING_DECL_SCOPE (t)))
15070 /* True iff this using-decl was written as a pack expansion
15071 (and a pack appeared in its scope or name). If a pack
15072 appeared in both, we expand the packs separately and
15073 manually merge them. */
15074 bool variadic_p = false;
15076 tree scope = USING_DECL_SCOPE (t);
15077 if (PACK_EXPANSION_P (scope))
15079 scope = tsubst_pack_expansion (scope, args,
15080 complain | tf_qualifying_scope,
15081 in_decl);
15082 variadic_p = true;
15084 else
15085 scope = tsubst_scope (scope, args, complain, in_decl);
15087 tree name = DECL_NAME (t);
15088 if (IDENTIFIER_CONV_OP_P (name)
15089 && PACK_EXPANSION_P (TREE_TYPE (name)))
15091 name = tsubst_pack_expansion (TREE_TYPE (name), args,
15092 complain, in_decl);
15093 if (name == error_mark_node)
15095 r = error_mark_node;
15096 break;
15098 for (tree& elt : tree_vec_range (name))
15099 elt = make_conv_op_name (elt);
15100 variadic_p = true;
15102 else
15103 name = tsubst_copy (name, args, complain, in_decl);
15105 int len;
15106 if (!variadic_p)
15107 len = 1;
15108 else if (TREE_CODE (scope) == TREE_VEC
15109 && TREE_CODE (name) == TREE_VEC)
15111 if (TREE_VEC_LENGTH (scope) != TREE_VEC_LENGTH (name))
15113 error ("mismatched argument pack lengths (%d vs %d)",
15114 TREE_VEC_LENGTH (scope), TREE_VEC_LENGTH (name));
15115 r = error_mark_node;
15116 break;
15118 len = TREE_VEC_LENGTH (scope);
15120 else if (TREE_CODE (scope) == TREE_VEC)
15121 len = TREE_VEC_LENGTH (scope);
15122 else /* TREE_CODE (name) == TREE_VEC */
15123 len = TREE_VEC_LENGTH (name);
15125 r = make_tree_vec (len);
15126 for (int i = 0; i < len; ++i)
15128 tree escope = (TREE_CODE (scope) == TREE_VEC
15129 ? TREE_VEC_ELT (scope, i)
15130 : scope);
15131 tree ename = (TREE_CODE (name) == TREE_VEC
15132 ? TREE_VEC_ELT (name, i)
15133 : name);
15134 tree elt = do_class_using_decl (escope, ename);
15135 if (!elt)
15137 r = error_mark_node;
15138 break;
15140 TREE_PROTECTED (elt) = TREE_PROTECTED (t);
15141 TREE_PRIVATE (elt) = TREE_PRIVATE (t);
15142 TREE_VEC_ELT (r, i) = elt;
15145 if (!variadic_p && r != error_mark_node)
15146 r = TREE_VEC_ELT (r, 0);
15148 else
15150 r = copy_node (t);
15151 DECL_CHAIN (r) = NULL_TREE;
15153 break;
15155 case TYPE_DECL:
15156 case VAR_DECL:
15158 tree argvec = NULL_TREE;
15159 tree gen_tmpl = NULL_TREE;
15160 tree tmpl = NULL_TREE;
15161 tree type = NULL_TREE;
15163 if (TREE_TYPE (t) == error_mark_node)
15164 RETURN (error_mark_node);
15166 if (TREE_CODE (t) == TYPE_DECL
15167 && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
15169 /* If this is the canonical decl, we don't have to
15170 mess with instantiations, and often we can't (for
15171 typename, template type parms and such). Note that
15172 TYPE_NAME is not correct for the above test if
15173 we've copied the type for a typedef. */
15174 type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15175 if (type == error_mark_node)
15176 RETURN (error_mark_node);
15177 r = TYPE_NAME (type);
15178 break;
15181 /* Check to see if we already have the specialization we
15182 need. */
15183 tree spec = NULL_TREE;
15184 bool local_p = false;
15185 tree ctx = DECL_CONTEXT (t);
15186 if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t))
15187 && (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t)))
15189 local_p = false;
15190 if (DECL_CLASS_SCOPE_P (t))
15192 ctx = tsubst_aggr_type (ctx, args,
15193 complain,
15194 in_decl, /*entering_scope=*/1);
15195 if (DECL_SELF_REFERENCE_P (t))
15196 /* The context and type of an injected-class-name are
15197 the same, so we don't need to substitute both. */
15198 type = ctx;
15199 /* If CTX is unchanged, then T is in fact the
15200 specialization we want. That situation occurs when
15201 referencing a static data member within in its own
15202 class. We can use pointer equality, rather than
15203 same_type_p, because DECL_CONTEXT is always
15204 canonical... */
15205 if (ctx == DECL_CONTEXT (t)
15206 /* ... unless T is a member template; in which
15207 case our caller can be willing to create a
15208 specialization of that template represented
15209 by T. */
15210 && !(DECL_TI_TEMPLATE (t)
15211 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
15212 spec = t;
15215 if (!spec)
15217 tmpl = DECL_TI_TEMPLATE (t);
15218 gen_tmpl = most_general_template (tmpl);
15219 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
15220 if (argvec != error_mark_node
15221 && PRIMARY_TEMPLATE_P (gen_tmpl)
15222 && TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (argvec))
15223 /* We're fully specializing a template declaration, so
15224 we need to coerce the innermost arguments corresponding to
15225 the template. */
15226 argvec = (coerce_template_parms
15227 (DECL_TEMPLATE_PARMS (gen_tmpl),
15228 argvec, tmpl, complain));
15229 if (argvec == error_mark_node)
15230 RETURN (error_mark_node);
15231 hash = spec_hasher::hash (gen_tmpl, argvec);
15232 spec = retrieve_specialization (gen_tmpl, argvec, hash);
15235 else
15237 if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t)))
15238 /* Subsequent calls to pushdecl will fill this in. */
15239 ctx = NULL_TREE;
15240 /* A local variable. */
15241 local_p = true;
15242 /* Unless this is a reference to a static variable from an
15243 enclosing function, in which case we need to fill it in now. */
15244 if (TREE_STATIC (t))
15246 tree fn = enclosing_instantiation_of (DECL_CONTEXT (t));
15247 if (fn != current_function_decl)
15248 ctx = fn;
15250 spec = retrieve_local_specialization (t);
15252 /* If we already have the specialization we need, there is
15253 nothing more to do. */
15254 if (spec)
15256 r = spec;
15257 break;
15260 /* Create a new node for the specialization we need. */
15261 if (type == NULL_TREE)
15263 if (is_typedef_decl (t))
15264 type = DECL_ORIGINAL_TYPE (t);
15265 else
15266 type = TREE_TYPE (t);
15267 if (VAR_P (t)
15268 && VAR_HAD_UNKNOWN_BOUND (t)
15269 && type != error_mark_node)
15270 type = strip_array_domain (type);
15271 tsubst_flags_t tcomplain = complain;
15272 if (VAR_P (t))
15273 tcomplain |= tf_tst_ok;
15274 type = tsubst (type, args, tcomplain, in_decl);
15275 /* Substituting the type might have recursively instantiated this
15276 same alias (c++/86171). */
15277 if (gen_tmpl && DECL_ALIAS_TEMPLATE_P (gen_tmpl)
15278 && (spec = retrieve_specialization (gen_tmpl, argvec, hash)))
15280 r = spec;
15281 break;
15284 r = copy_decl (t);
15285 if (VAR_P (r))
15287 DECL_INITIALIZED_P (r) = 0;
15288 DECL_TEMPLATE_INSTANTIATED (r) = 0;
15289 if (type == error_mark_node)
15290 RETURN (error_mark_node);
15291 if (TREE_CODE (type) == FUNCTION_TYPE)
15293 /* It may seem that this case cannot occur, since:
15295 typedef void f();
15296 void g() { f x; }
15298 declares a function, not a variable. However:
15300 typedef void f();
15301 template <typename T> void g() { T t; }
15302 template void g<f>();
15304 is an attempt to declare a variable with function
15305 type. */
15306 error ("variable %qD has function type",
15307 /* R is not yet sufficiently initialized, so we
15308 just use its name. */
15309 DECL_NAME (r));
15310 RETURN (error_mark_node);
15312 type = complete_type (type);
15313 /* Wait until cp_finish_decl to set this again, to handle
15314 circular dependency (template/instantiate6.C). */
15315 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
15316 type = check_var_type (DECL_NAME (r), type,
15317 DECL_SOURCE_LOCATION (r));
15318 if (DECL_HAS_VALUE_EXPR_P (t))
15320 tree ve = DECL_VALUE_EXPR (t);
15321 /* If the DECL_VALUE_EXPR is converted to the declared type,
15322 preserve the identity so that gimplify_type_sizes works. */
15323 bool nop = (TREE_CODE (ve) == NOP_EXPR);
15324 if (nop)
15325 ve = TREE_OPERAND (ve, 0);
15326 ve = tsubst_expr (ve, args, complain, in_decl);
15327 if (REFERENCE_REF_P (ve))
15329 gcc_assert (TYPE_REF_P (type));
15330 ve = TREE_OPERAND (ve, 0);
15332 if (nop)
15333 ve = build_nop (type, ve);
15334 else if (DECL_LANG_SPECIFIC (t)
15335 && DECL_OMP_PRIVATIZED_MEMBER (t)
15336 && TREE_CODE (ve) == COMPONENT_REF
15337 && TREE_CODE (TREE_OPERAND (ve, 1)) == FIELD_DECL
15338 && DECL_BIT_FIELD_TYPE (TREE_OPERAND (ve, 1)) == type)
15339 type = TREE_TYPE (ve);
15340 else
15341 gcc_checking_assert (TYPE_MAIN_VARIANT (TREE_TYPE (ve))
15342 == TYPE_MAIN_VARIANT (type));
15343 SET_DECL_VALUE_EXPR (r, ve);
15345 if (CP_DECL_THREAD_LOCAL_P (r)
15346 && !processing_template_decl)
15347 set_decl_tls_model (r, decl_default_tls_model (r));
15349 else if (DECL_SELF_REFERENCE_P (t))
15350 SET_DECL_SELF_REFERENCE_P (r);
15351 TREE_TYPE (r) = type;
15352 cp_apply_type_quals_to_decl (cp_type_quals (type), r);
15353 DECL_CONTEXT (r) = ctx;
15354 /* Clear out the mangled name and RTL for the instantiation. */
15355 SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
15356 if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
15357 SET_DECL_RTL (r, NULL);
15358 set_instantiating_module (r);
15360 /* The initializer must not be expanded until it is required;
15361 see [temp.inst]. */
15362 DECL_INITIAL (r) = NULL_TREE;
15363 DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
15364 if (VAR_P (r))
15366 if (DECL_LANG_SPECIFIC (r))
15367 SET_DECL_DEPENDENT_INIT_P (r, false);
15369 SET_DECL_MODE (r, VOIDmode);
15371 /* Possibly limit visibility based on template args. */
15372 DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
15373 if (DECL_VISIBILITY_SPECIFIED (t))
15375 DECL_VISIBILITY_SPECIFIED (r) = 0;
15376 DECL_ATTRIBUTES (r)
15377 = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
15379 determine_visibility (r);
15382 if (!local_p)
15384 /* A static data member declaration is always marked
15385 external when it is declared in-class, even if an
15386 initializer is present. We mimic the non-template
15387 processing here. */
15388 DECL_EXTERNAL (r) = 1;
15389 if (DECL_NAMESPACE_SCOPE_P (t))
15390 DECL_NOT_REALLY_EXTERN (r) = 1;
15392 DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
15393 SET_DECL_IMPLICIT_INSTANTIATION (r);
15394 if (!error_operand_p (r) || (complain & tf_error))
15395 register_specialization (r, gen_tmpl, argvec, false, hash);
15397 else
15399 if (DECL_LANG_SPECIFIC (r))
15400 DECL_TEMPLATE_INFO (r) = NULL_TREE;
15401 if (!cp_unevaluated_operand)
15402 register_local_specialization (r, t);
15405 DECL_CHAIN (r) = NULL_TREE;
15407 if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
15408 /*flags=*/0,
15409 args, complain, in_decl))
15410 return error_mark_node;
15412 /* Preserve a typedef that names a type. */
15413 if (is_typedef_decl (r) && type != error_mark_node)
15415 DECL_ORIGINAL_TYPE (r) = NULL_TREE;
15416 set_underlying_type (r);
15418 /* common_handle_aligned_attribute doesn't apply the alignment
15419 to DECL_ORIGINAL_TYPE. */
15420 if (TYPE_USER_ALIGN (TREE_TYPE (t)))
15421 TREE_TYPE (r) = build_aligned_type (TREE_TYPE (r),
15422 TYPE_ALIGN (TREE_TYPE (t)));
15425 layout_decl (r, 0);
15427 break;
15429 default:
15430 gcc_unreachable ();
15432 #undef RETURN
15434 out:
15435 /* Restore the file and line information. */
15436 input_location = saved_loc;
15438 return r;
15441 /* Substitute into the complete parameter type list PARMS. */
15443 tree
15444 tsubst_function_parms (tree parms,
15445 tree args,
15446 tsubst_flags_t complain,
15447 tree in_decl)
15449 return tsubst_arg_types (parms, args, NULL_TREE, complain, in_decl);
15452 /* Substitute into the ARG_TYPES of a function type.
15453 If END is a TREE_CHAIN, leave it and any following types
15454 un-substituted. */
15456 static tree
15457 tsubst_arg_types (tree arg_types,
15458 tree args,
15459 tree end,
15460 tsubst_flags_t complain,
15461 tree in_decl)
15463 tree type = NULL_TREE;
15464 int len = 1;
15465 tree expanded_args = NULL_TREE;
15467 if (!arg_types || arg_types == void_list_node || arg_types == end)
15468 return arg_types;
15470 if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
15472 /* For a pack expansion, perform substitution on the
15473 entire expression. Later on, we'll handle the arguments
15474 one-by-one. */
15475 expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
15476 args, complain, in_decl);
15478 if (TREE_CODE (expanded_args) == TREE_VEC)
15479 /* So that we'll spin through the parameters, one by one. */
15480 len = TREE_VEC_LENGTH (expanded_args);
15481 else
15483 /* We only partially substituted into the parameter
15484 pack. Our type is TYPE_PACK_EXPANSION. */
15485 type = expanded_args;
15486 expanded_args = NULL_TREE;
15489 else
15490 type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
15492 /* Check if a substituted type is erroneous before substituting into
15493 the rest of the chain. */
15494 for (int i = 0; i < len; i++)
15496 if (expanded_args)
15497 type = TREE_VEC_ELT (expanded_args, i);
15499 if (type == error_mark_node)
15500 return error_mark_node;
15501 if (VOID_TYPE_P (type))
15503 if (complain & tf_error)
15505 error ("invalid parameter type %qT", type);
15506 if (in_decl)
15507 error ("in declaration %q+D", in_decl);
15509 return error_mark_node;
15513 /* We do not substitute into default arguments here. The standard
15514 mandates that they be instantiated only when needed, which is
15515 done in build_over_call. */
15516 tree default_arg = TREE_PURPOSE (arg_types);
15518 /* Except that we do substitute default arguments under tsubst_lambda_expr,
15519 since the new op() won't have any associated template arguments for us
15520 to refer to later. */
15521 if (lambda_fn_in_template_p (in_decl)
15522 || (in_decl && TREE_CODE (in_decl) == FUNCTION_DECL
15523 && DECL_LOCAL_DECL_P (in_decl)))
15524 default_arg = tsubst_copy_and_build (default_arg, args, complain, in_decl);
15526 tree remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
15527 args, end, complain, in_decl);
15528 if (remaining_arg_types == error_mark_node)
15529 return error_mark_node;
15531 for (int i = len-1; i >= 0; i--)
15533 if (expanded_args)
15534 type = TREE_VEC_ELT (expanded_args, i);
15536 /* Do array-to-pointer, function-to-pointer conversion, and ignore
15537 top-level qualifiers as required. */
15538 type = cv_unqualified (type_decays_to (type));
15540 if (default_arg && TREE_CODE (default_arg) == DEFERRED_PARSE)
15542 /* We've instantiated a template before its default arguments
15543 have been parsed. This can happen for a nested template
15544 class, and is not an error unless we require the default
15545 argument in a call of this function. */
15546 remaining_arg_types
15547 = tree_cons (default_arg, type, remaining_arg_types);
15548 vec_safe_push (DEFPARSE_INSTANTIATIONS (default_arg),
15549 remaining_arg_types);
15551 else
15552 remaining_arg_types
15553 = hash_tree_cons (default_arg, type, remaining_arg_types);
15556 return remaining_arg_types;
15559 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE. This routine does
15560 *not* handle the exception-specification for FNTYPE, because the
15561 initial substitution of explicitly provided template parameters
15562 during argument deduction forbids substitution into the
15563 exception-specification:
15565 [temp.deduct]
15567 All references in the function type of the function template to the
15568 corresponding template parameters are replaced by the specified tem-
15569 plate argument values. If a substitution in a template parameter or
15570 in the function type of the function template results in an invalid
15571 type, type deduction fails. [Note: The equivalent substitution in
15572 exception specifications is done only when the function is instanti-
15573 ated, at which point a program is ill-formed if the substitution
15574 results in an invalid type.] */
15576 static tree
15577 tsubst_function_type (tree t,
15578 tree args,
15579 tsubst_flags_t complain,
15580 tree in_decl)
15582 tree return_type;
15583 tree arg_types = NULL_TREE;
15585 /* The TYPE_CONTEXT is not used for function/method types. */
15586 gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
15588 /* DR 1227: Mixing immediate and non-immediate contexts in deduction
15589 failure. */
15590 bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
15592 if (late_return_type_p)
15594 /* Substitute the argument types. */
15595 arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15596 complain, in_decl);
15597 if (arg_types == error_mark_node)
15598 return error_mark_node;
15600 tree save_ccp = current_class_ptr;
15601 tree save_ccr = current_class_ref;
15602 tree this_type = (TREE_CODE (t) == METHOD_TYPE
15603 ? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
15604 bool do_inject = this_type && CLASS_TYPE_P (this_type);
15605 if (do_inject)
15607 /* DR 1207: 'this' is in scope in the trailing return type. */
15608 inject_this_parameter (this_type, cp_type_quals (this_type));
15611 /* Substitute the return type. */
15612 return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15614 if (do_inject)
15616 current_class_ptr = save_ccp;
15617 current_class_ref = save_ccr;
15620 else
15621 /* Substitute the return type. */
15622 return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15624 if (return_type == error_mark_node)
15625 return error_mark_node;
15626 /* DR 486 clarifies that creation of a function type with an
15627 invalid return type is a deduction failure. */
15628 if (TREE_CODE (return_type) == ARRAY_TYPE
15629 || TREE_CODE (return_type) == FUNCTION_TYPE)
15631 if (complain & tf_error)
15633 if (TREE_CODE (return_type) == ARRAY_TYPE)
15634 error ("function returning an array");
15635 else
15636 error ("function returning a function");
15638 return error_mark_node;
15641 if (!late_return_type_p)
15643 /* Substitute the argument types. */
15644 arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15645 complain, in_decl);
15646 if (arg_types == error_mark_node)
15647 return error_mark_node;
15650 /* Construct a new type node and return it. */
15651 return rebuild_function_or_method_type (t, return_type, arg_types,
15652 /*raises=*/NULL_TREE, complain);
15655 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE. Substitute the template
15656 ARGS into that specification, and return the substituted
15657 specification. If there is no specification, return NULL_TREE. */
15659 static tree
15660 tsubst_exception_specification (tree fntype,
15661 tree args,
15662 tsubst_flags_t complain,
15663 tree in_decl,
15664 bool defer_ok)
15666 tree specs;
15667 tree new_specs;
15669 specs = TYPE_RAISES_EXCEPTIONS (fntype);
15670 new_specs = NULL_TREE;
15671 if (specs && TREE_PURPOSE (specs))
15673 /* A noexcept-specifier. */
15674 tree expr = TREE_PURPOSE (specs);
15675 if (TREE_CODE (expr) == INTEGER_CST)
15676 new_specs = expr;
15677 else if (defer_ok)
15679 /* Defer instantiation of noexcept-specifiers to avoid
15680 excessive instantiations (c++/49107). */
15681 new_specs = make_node (DEFERRED_NOEXCEPT);
15682 if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15684 /* We already partially instantiated this member template,
15685 so combine the new args with the old. */
15686 DEFERRED_NOEXCEPT_PATTERN (new_specs)
15687 = DEFERRED_NOEXCEPT_PATTERN (expr);
15688 DEFERRED_NOEXCEPT_ARGS (new_specs)
15689 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
15691 else
15693 DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
15694 DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
15697 else
15699 if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15701 args = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr),
15702 args);
15703 expr = DEFERRED_NOEXCEPT_PATTERN (expr);
15705 new_specs = tsubst_copy_and_build (expr, args, complain, in_decl);
15707 new_specs = build_noexcept_spec (new_specs, complain);
15708 /* We've instantiated a template before a noexcept-specifier
15709 contained therein has been parsed. This can happen for
15710 a nested template class:
15712 struct S {
15713 template<typename> struct B { B() noexcept(...); };
15714 struct A : B<int> { ... use B() ... };
15717 where completing B<int> will trigger instantiating the
15718 noexcept, even though we only parse it at the end of S. */
15719 if (UNPARSED_NOEXCEPT_SPEC_P (specs))
15721 gcc_checking_assert (defer_ok);
15722 vec_safe_push (DEFPARSE_INSTANTIATIONS (expr), new_specs);
15725 else if (specs)
15727 if (! TREE_VALUE (specs))
15728 new_specs = specs;
15729 else
15730 while (specs)
15732 tree spec;
15733 int i, len = 1;
15734 tree expanded_specs = NULL_TREE;
15736 if (PACK_EXPANSION_P (TREE_VALUE (specs)))
15738 /* Expand the pack expansion type. */
15739 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
15740 args, complain,
15741 in_decl);
15743 if (expanded_specs == error_mark_node)
15744 return error_mark_node;
15745 else if (TREE_CODE (expanded_specs) == TREE_VEC)
15746 len = TREE_VEC_LENGTH (expanded_specs);
15747 else
15749 /* We're substituting into a member template, so
15750 we got a TYPE_PACK_EXPANSION back. Add that
15751 expansion and move on. */
15752 gcc_assert (TREE_CODE (expanded_specs)
15753 == TYPE_PACK_EXPANSION);
15754 new_specs = add_exception_specifier (new_specs,
15755 expanded_specs,
15756 complain);
15757 specs = TREE_CHAIN (specs);
15758 continue;
15762 for (i = 0; i < len; ++i)
15764 if (expanded_specs)
15765 spec = TREE_VEC_ELT (expanded_specs, i);
15766 else
15767 spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
15768 if (spec == error_mark_node)
15769 return spec;
15770 new_specs = add_exception_specifier (new_specs, spec,
15771 complain);
15774 specs = TREE_CHAIN (specs);
15777 return new_specs;
15780 /* Substitute through a TREE_LIST of types or expressions, handling pack
15781 expansions. */
15783 tree
15784 tsubst_tree_list (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15786 if (t == void_list_node)
15787 return t;
15789 tree purpose = TREE_PURPOSE (t);
15790 tree purposevec = NULL_TREE;
15791 if (!purpose)
15793 else if (PACK_EXPANSION_P (purpose))
15795 purpose = tsubst_pack_expansion (purpose, args, complain, in_decl);
15796 if (TREE_CODE (purpose) == TREE_VEC)
15797 purposevec = purpose;
15799 else if (TYPE_P (purpose))
15800 purpose = tsubst (purpose, args, complain, in_decl);
15801 else
15802 purpose = tsubst_copy_and_build (purpose, args, complain, in_decl);
15803 if (purpose == error_mark_node || purposevec == error_mark_node)
15804 return error_mark_node;
15806 tree value = TREE_VALUE (t);
15807 tree valuevec = NULL_TREE;
15808 if (!value)
15810 else if (PACK_EXPANSION_P (value))
15812 value = tsubst_pack_expansion (value, args, complain, in_decl);
15813 if (TREE_CODE (value) == TREE_VEC)
15814 valuevec = value;
15816 else if (TYPE_P (value))
15817 value = tsubst (value, args, complain, in_decl);
15818 else
15819 value = tsubst_copy_and_build (value, args, complain, in_decl);
15820 if (value == error_mark_node || valuevec == error_mark_node)
15821 return error_mark_node;
15823 tree chain = TREE_CHAIN (t);
15824 if (!chain)
15826 else if (TREE_CODE (chain) == TREE_LIST)
15827 chain = tsubst_tree_list (chain, args, complain, in_decl);
15828 else if (TYPE_P (chain))
15829 chain = tsubst (chain, args, complain, in_decl);
15830 else
15831 chain = tsubst_copy_and_build (chain, args, complain, in_decl);
15832 if (chain == error_mark_node)
15833 return error_mark_node;
15835 if (purpose == TREE_PURPOSE (t)
15836 && value == TREE_VALUE (t)
15837 && chain == TREE_CHAIN (t))
15838 return t;
15840 int len;
15841 /* Determine the number of arguments. */
15842 if (purposevec)
15844 len = TREE_VEC_LENGTH (purposevec);
15845 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
15847 else if (valuevec)
15848 len = TREE_VEC_LENGTH (valuevec);
15849 else
15850 len = 1;
15852 for (int i = len; i-- > 0; )
15854 if (purposevec)
15855 purpose = TREE_VEC_ELT (purposevec, i);
15856 if (valuevec)
15857 value = TREE_VEC_ELT (valuevec, i);
15859 if (value && TYPE_P (value))
15860 chain = hash_tree_cons (purpose, value, chain);
15861 else
15862 chain = tree_cons (purpose, value, chain);
15865 return chain;
15868 /* Take the tree structure T and replace template parameters used
15869 therein with the argument vector ARGS. IN_DECL is an associated
15870 decl for diagnostics. If an error occurs, returns ERROR_MARK_NODE.
15871 Issue error and warning messages under control of COMPLAIN. Note
15872 that we must be relatively non-tolerant of extensions here, in
15873 order to preserve conformance; if we allow substitutions that
15874 should not be allowed, we may allow argument deductions that should
15875 not succeed, and therefore report ambiguous overload situations
15876 where there are none. In theory, we could allow the substitution,
15877 but indicate that it should have failed, and allow our caller to
15878 make sure that the right thing happens, but we don't try to do this
15879 yet.
15881 This function is used for dealing with types, decls and the like;
15882 for expressions, use tsubst_expr or tsubst_copy. */
15884 tree
15885 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15887 enum tree_code code;
15888 tree type, r = NULL_TREE;
15890 if (t == NULL_TREE || t == error_mark_node
15891 || t == integer_type_node
15892 || t == void_type_node
15893 || t == char_type_node
15894 || t == unknown_type_node
15895 || TREE_CODE (t) == NAMESPACE_DECL
15896 || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
15897 return t;
15899 tsubst_flags_t tst_ok_flag = (complain & tf_tst_ok);
15900 complain &= ~tf_tst_ok;
15902 tsubst_flags_t qualifying_scope_flag = (complain & tf_qualifying_scope);
15903 complain &= ~tf_qualifying_scope;
15905 if (DECL_P (t))
15906 return tsubst_decl (t, args, complain);
15908 if (args == NULL_TREE)
15909 return t;
15911 code = TREE_CODE (t);
15913 gcc_assert (code != IDENTIFIER_NODE);
15914 type = TREE_TYPE (t);
15916 gcc_assert (type != unknown_type_node);
15918 if (tree d = maybe_dependent_member_ref (t, args, complain, in_decl))
15919 return d;
15921 /* Reuse typedefs. We need to do this to handle dependent attributes,
15922 such as attribute aligned. */
15923 if (TYPE_P (t)
15924 && typedef_variant_p (t))
15926 tree decl = TYPE_NAME (t);
15928 if (alias_template_specialization_p (t, nt_opaque))
15930 /* DECL represents an alias template and we want to
15931 instantiate it. */
15932 tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15933 tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15934 r = instantiate_alias_template (tmpl, gen_args, complain);
15936 else if (DECL_CLASS_SCOPE_P (decl)
15937 && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
15938 && uses_template_parms (DECL_CONTEXT (decl)))
15940 tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15941 tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15942 r = retrieve_specialization (tmpl, gen_args, 0);
15944 else if (DECL_FUNCTION_SCOPE_P (decl)
15945 && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
15946 && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
15947 r = retrieve_local_specialization (decl);
15948 else
15949 /* The typedef is from a non-template context. */
15950 return t;
15952 if (r)
15954 r = TREE_TYPE (r);
15955 r = cp_build_qualified_type
15956 (r, cp_type_quals (t) | cp_type_quals (r),
15957 complain | tf_ignore_bad_quals);
15958 return r;
15960 else
15962 /* We don't have an instantiation yet, so drop the typedef. */
15963 int quals = cp_type_quals (t);
15964 t = DECL_ORIGINAL_TYPE (decl);
15965 t = cp_build_qualified_type (t, quals,
15966 complain | tf_ignore_bad_quals);
15970 bool fndecl_type = (complain & tf_fndecl_type);
15971 complain &= ~tf_fndecl_type;
15973 if (type
15974 && code != TYPENAME_TYPE
15975 && code != TEMPLATE_TYPE_PARM
15976 && code != TEMPLATE_PARM_INDEX
15977 && code != IDENTIFIER_NODE
15978 && code != FUNCTION_TYPE
15979 && code != METHOD_TYPE)
15980 type = tsubst (type, args, complain, in_decl);
15981 if (type == error_mark_node)
15982 return error_mark_node;
15984 switch (code)
15986 case RECORD_TYPE:
15987 if (TYPE_PTRMEMFUNC_P (t))
15988 return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
15989 /* Fall through. */
15990 case UNION_TYPE:
15991 case ENUMERAL_TYPE:
15992 return tsubst_aggr_type_1 (t, args, complain, in_decl,
15993 /*entering_scope=*/0);
15995 case ERROR_MARK:
15996 case IDENTIFIER_NODE:
15997 case VOID_TYPE:
15998 case OPAQUE_TYPE:
15999 case REAL_TYPE:
16000 case COMPLEX_TYPE:
16001 case VECTOR_TYPE:
16002 case BOOLEAN_TYPE:
16003 case NULLPTR_TYPE:
16004 case LANG_TYPE:
16005 return t;
16007 case INTEGER_TYPE:
16008 if (t == integer_type_node)
16009 return t;
16011 if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
16012 && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
16013 return t;
16016 tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
16018 max = tsubst_expr (omax, args, complain, in_decl);
16020 /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
16021 needed. */
16022 if (TREE_CODE (max) == NOP_EXPR
16023 && TREE_SIDE_EFFECTS (omax)
16024 && !TREE_TYPE (max))
16025 TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
16027 /* If we're in a partial instantiation, preserve the magic NOP_EXPR
16028 with TREE_SIDE_EFFECTS that indicates this is not an integral
16029 constant expression. */
16030 if (processing_template_decl
16031 && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
16033 gcc_assert (TREE_CODE (max) == NOP_EXPR);
16034 TREE_SIDE_EFFECTS (max) = 1;
16037 return compute_array_index_type (NULL_TREE, max, complain);
16040 case TEMPLATE_TYPE_PARM:
16041 if (template_placeholder_p (t))
16043 tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (t);
16044 tmpl = tsubst_copy (tmpl, args, complain, in_decl);
16045 if (TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
16046 tmpl = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (tmpl);
16048 if (tmpl != CLASS_PLACEHOLDER_TEMPLATE (t))
16049 return make_template_placeholder (tmpl);
16050 else
16051 return t;
16053 /* Fall through. */
16054 case TEMPLATE_TEMPLATE_PARM:
16055 case BOUND_TEMPLATE_TEMPLATE_PARM:
16056 case TEMPLATE_PARM_INDEX:
16058 int idx;
16059 int level;
16060 int levels;
16061 tree arg = NULL_TREE;
16063 r = NULL_TREE;
16065 gcc_assert (TREE_VEC_LENGTH (args) > 0);
16066 template_parm_level_and_index (t, &level, &idx);
16068 levels = TMPL_ARGS_DEPTH (args);
16069 if (level <= levels
16070 && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
16072 arg = TMPL_ARG (args, level, idx);
16074 /* See through ARGUMENT_PACK_SELECT arguments. */
16075 if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
16076 arg = argument_pack_select_arg (arg);
16079 if (arg == error_mark_node)
16080 return error_mark_node;
16081 else if (arg != NULL_TREE)
16083 if (ARGUMENT_PACK_P (arg))
16084 /* If ARG is an argument pack, we don't actually want to
16085 perform a substitution here, because substitutions
16086 for argument packs are only done
16087 element-by-element. We can get to this point when
16088 substituting the type of a non-type template
16089 parameter pack, when that type actually contains
16090 template parameter packs from an outer template, e.g.,
16092 template<typename... Types> struct A {
16093 template<Types... Values> struct B { };
16094 }; */
16095 return t;
16097 if (code == TEMPLATE_TYPE_PARM)
16099 int quals;
16101 /* When building concept checks for the purpose of
16102 deducing placeholders, we can end up with wildcards
16103 where types are expected. Adjust this to the deduced
16104 value. */
16105 if (TREE_CODE (arg) == WILDCARD_DECL)
16106 arg = TREE_TYPE (TREE_TYPE (arg));
16108 gcc_assert (TYPE_P (arg));
16110 quals = cp_type_quals (arg) | cp_type_quals (t);
16112 return cp_build_qualified_type
16113 (arg, quals, complain | tf_ignore_bad_quals);
16115 else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
16117 /* We are processing a type constructed from a
16118 template template parameter. */
16119 tree argvec = tsubst (TYPE_TI_ARGS (t),
16120 args, complain, in_decl);
16121 if (argvec == error_mark_node)
16122 return error_mark_node;
16124 gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
16125 || TREE_CODE (arg) == TEMPLATE_DECL
16126 || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
16128 if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
16129 /* Consider this code:
16131 template <template <class> class Template>
16132 struct Internal {
16133 template <class Arg> using Bind = Template<Arg>;
16136 template <template <class> class Template, class Arg>
16137 using Instantiate = Template<Arg>; //#0
16139 template <template <class> class Template,
16140 class Argument>
16141 using Bind =
16142 Instantiate<Internal<Template>::template Bind,
16143 Argument>; //#1
16145 When #1 is parsed, the
16146 BOUND_TEMPLATE_TEMPLATE_PARM representing the
16147 parameter `Template' in #0 matches the
16148 UNBOUND_CLASS_TEMPLATE representing the argument
16149 `Internal<Template>::template Bind'; We then want
16150 to assemble the type `Bind<Argument>' that can't
16151 be fully created right now, because
16152 `Internal<Template>' not being complete, the Bind
16153 template cannot be looked up in that context. So
16154 we need to "store" `Bind<Argument>' for later
16155 when the context of Bind becomes complete. Let's
16156 store that in a TYPENAME_TYPE. */
16157 return make_typename_type (TYPE_CONTEXT (arg),
16158 build_nt (TEMPLATE_ID_EXPR,
16159 TYPE_IDENTIFIER (arg),
16160 argvec),
16161 typename_type,
16162 complain);
16164 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
16165 are resolving nested-types in the signature of a
16166 member function templates. Otherwise ARG is a
16167 TEMPLATE_DECL and is the real template to be
16168 instantiated. */
16169 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16170 arg = TYPE_NAME (arg);
16172 r = lookup_template_class (arg,
16173 argvec, in_decl,
16174 DECL_CONTEXT (arg),
16175 /*entering_scope=*/0,
16176 complain);
16177 return cp_build_qualified_type
16178 (r, cp_type_quals (t) | cp_type_quals (r), complain);
16180 else if (code == TEMPLATE_TEMPLATE_PARM)
16181 return arg;
16182 else
16183 /* TEMPLATE_PARM_INDEX. */
16184 return convert_from_reference (unshare_expr (arg));
16187 if (level == 1)
16188 /* This can happen during the attempted tsubst'ing in
16189 unify. This means that we don't yet have any information
16190 about the template parameter in question. */
16191 return t;
16193 /* Early in template argument deduction substitution, we don't
16194 want to reduce the level of 'auto', or it will be confused
16195 with a normal template parm in subsequent deduction.
16196 Similarly, don't reduce the level of template parameters to
16197 avoid mismatches when deducing their types. */
16198 if (complain & tf_partial)
16199 return t;
16201 /* If we get here, we must have been looking at a parm for a
16202 more deeply nested template. Make a new version of this
16203 template parameter, but with a lower level. */
16204 int quals;
16205 switch (code)
16207 case TEMPLATE_TYPE_PARM:
16208 case TEMPLATE_TEMPLATE_PARM:
16209 quals = cp_type_quals (t);
16210 if (quals)
16212 gcc_checking_assert (code == TEMPLATE_TYPE_PARM);
16213 t = TYPE_MAIN_VARIANT (t);
16216 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
16217 && (arg = TEMPLATE_TYPE_PARM_INDEX (t),
16218 r = TEMPLATE_PARM_DESCENDANTS (arg))
16219 && (TEMPLATE_PARM_LEVEL (r)
16220 == TEMPLATE_PARM_LEVEL (arg) - levels))
16221 /* Cache the simple case of lowering a type parameter. */
16222 r = TREE_TYPE (r);
16223 else
16225 r = copy_type (t);
16226 TEMPLATE_TYPE_PARM_INDEX (r)
16227 = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
16228 r, levels, args, complain);
16229 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
16230 TYPE_MAIN_VARIANT (r) = r;
16231 TYPE_POINTER_TO (r) = NULL_TREE;
16232 TYPE_REFERENCE_TO (r) = NULL_TREE;
16234 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
16235 if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t))
16236 /* Propagate constraints on placeholders since they are
16237 only instantiated during satisfaction. */
16238 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (r) = ci;
16240 if (TYPE_STRUCTURAL_EQUALITY_P (t))
16241 SET_TYPE_STRUCTURAL_EQUALITY (r);
16242 else
16243 TYPE_CANONICAL (r) = canonical_type_parameter (r);
16246 if (quals)
16247 r = cp_build_qualified_type (r, quals,
16248 complain | tf_ignore_bad_quals);
16249 break;
16251 case BOUND_TEMPLATE_TEMPLATE_PARM:
16253 tree tinfo = TYPE_TEMPLATE_INFO (t);
16254 /* We might need to substitute into the types of non-type
16255 template parameters. This also lowers the level of
16256 the ttp appropriately. */
16257 tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
16258 complain, in_decl);
16259 if (tmpl == error_mark_node)
16260 return error_mark_node;
16261 tree argvec = tsubst (TI_ARGS (tinfo), args,
16262 complain, in_decl);
16263 if (argvec == error_mark_node)
16264 return error_mark_node;
16265 r = lookup_template_class (tmpl, argvec, in_decl, NULL_TREE,
16266 /*entering_scope=*/false, complain);
16267 r = cp_build_qualified_type (r, cp_type_quals (t), complain);
16268 break;
16271 case TEMPLATE_PARM_INDEX:
16272 /* OK, now substitute the type of the non-type parameter. We
16273 couldn't do it earlier because it might be an auto parameter,
16274 and we wouldn't need to if we had an argument. */
16275 type = tsubst (type, args, complain, in_decl);
16276 if (type == error_mark_node)
16277 return error_mark_node;
16278 r = reduce_template_parm_level (t, type, levels, args, complain);
16279 break;
16281 default:
16282 gcc_unreachable ();
16285 return r;
16288 case TREE_LIST:
16289 return tsubst_tree_list (t, args, complain, in_decl);
16291 case TREE_BINFO:
16292 /* We should never be tsubsting a binfo. */
16293 gcc_unreachable ();
16295 case TREE_VEC:
16296 /* A vector of template arguments. */
16297 gcc_assert (!type);
16298 return tsubst_template_args (t, args, complain, in_decl);
16300 case POINTER_TYPE:
16301 case REFERENCE_TYPE:
16303 if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
16304 return t;
16306 /* [temp.deduct]
16308 Type deduction may fail for any of the following
16309 reasons:
16311 -- Attempting to create a pointer to reference type.
16312 -- Attempting to create a reference to a reference type or
16313 a reference to void.
16315 Core issue 106 says that creating a reference to a reference
16316 during instantiation is no longer a cause for failure. We
16317 only enforce this check in strict C++98 mode. */
16318 if ((TYPE_REF_P (type)
16319 && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
16320 || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
16322 static location_t last_loc;
16324 /* We keep track of the last time we issued this error
16325 message to avoid spewing a ton of messages during a
16326 single bad template instantiation. */
16327 if (complain & tf_error
16328 && last_loc != input_location)
16330 if (VOID_TYPE_P (type))
16331 error ("forming reference to void");
16332 else if (code == POINTER_TYPE)
16333 error ("forming pointer to reference type %qT", type);
16334 else
16335 error ("forming reference to reference type %qT", type);
16336 last_loc = input_location;
16339 return error_mark_node;
16341 else if (TREE_CODE (type) == FUNCTION_TYPE
16342 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
16343 || type_memfn_rqual (type) != REF_QUAL_NONE))
16345 if (complain & tf_error)
16347 if (code == POINTER_TYPE)
16348 error ("forming pointer to qualified function type %qT",
16349 type);
16350 else
16351 error ("forming reference to qualified function type %qT",
16352 type);
16354 return error_mark_node;
16356 else if (code == POINTER_TYPE)
16358 r = build_pointer_type (type);
16359 if (TREE_CODE (type) == METHOD_TYPE)
16360 r = build_ptrmemfunc_type (r);
16362 else if (TYPE_REF_P (type))
16363 /* In C++0x, during template argument substitution, when there is an
16364 attempt to create a reference to a reference type, reference
16365 collapsing is applied as described in [14.3.1/4 temp.arg.type]:
16367 "If a template-argument for a template-parameter T names a type
16368 that is a reference to a type A, an attempt to create the type
16369 'lvalue reference to cv T' creates the type 'lvalue reference to
16370 A,' while an attempt to create the type type rvalue reference to
16371 cv T' creates the type T"
16373 r = cp_build_reference_type
16374 (TREE_TYPE (type),
16375 TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
16376 else
16377 r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
16378 r = cp_build_qualified_type (r, cp_type_quals (t), complain);
16380 if (r != error_mark_node)
16381 /* Will this ever be needed for TYPE_..._TO values? */
16382 layout_type (r);
16384 return r;
16386 case OFFSET_TYPE:
16388 r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
16389 if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
16391 /* [temp.deduct]
16393 Type deduction may fail for any of the following
16394 reasons:
16396 -- Attempting to create "pointer to member of T" when T
16397 is not a class type. */
16398 if (complain & tf_error)
16399 error ("creating pointer to member of non-class type %qT", r);
16400 return error_mark_node;
16402 if (TYPE_REF_P (type))
16404 if (complain & tf_error)
16405 error ("creating pointer to member reference type %qT", type);
16406 return error_mark_node;
16408 if (VOID_TYPE_P (type))
16410 if (complain & tf_error)
16411 error ("creating pointer to member of type void");
16412 return error_mark_node;
16414 gcc_assert (TREE_CODE (type) != METHOD_TYPE);
16415 if (TREE_CODE (type) == FUNCTION_TYPE)
16417 /* The type of the implicit object parameter gets its
16418 cv-qualifiers from the FUNCTION_TYPE. */
16419 tree memptr;
16420 tree method_type
16421 = build_memfn_type (type, r, type_memfn_quals (type),
16422 type_memfn_rqual (type));
16423 memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
16424 return cp_build_qualified_type (memptr, cp_type_quals (t),
16425 complain);
16427 else
16428 return cp_build_qualified_type (build_ptrmem_type (r, type),
16429 cp_type_quals (t),
16430 complain);
16432 case FUNCTION_TYPE:
16433 case METHOD_TYPE:
16435 tree fntype;
16436 tree specs;
16437 fntype = tsubst_function_type (t, args, complain, in_decl);
16438 if (fntype == error_mark_node)
16439 return error_mark_node;
16441 /* Substitute the exception specification. */
16442 specs = tsubst_exception_specification (t, args, complain, in_decl,
16443 /*defer_ok*/fndecl_type);
16444 if (specs == error_mark_node)
16445 return error_mark_node;
16446 if (specs)
16447 fntype = build_exception_variant (fntype, specs);
16448 return fntype;
16450 case ARRAY_TYPE:
16452 tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
16453 if (domain == error_mark_node)
16454 return error_mark_node;
16456 /* As an optimization, we avoid regenerating the array type if
16457 it will obviously be the same as T. */
16458 if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
16459 return t;
16461 /* These checks should match the ones in create_array_type_for_decl.
16463 [temp.deduct]
16465 The deduction may fail for any of the following reasons:
16467 -- Attempting to create an array with an element type that
16468 is void, a function type, or a reference type, or [DR337]
16469 an abstract class type. */
16470 if (VOID_TYPE_P (type)
16471 || TREE_CODE (type) == FUNCTION_TYPE
16472 || (TREE_CODE (type) == ARRAY_TYPE
16473 && TYPE_DOMAIN (type) == NULL_TREE)
16474 || TYPE_REF_P (type))
16476 if (complain & tf_error)
16477 error ("creating array of %qT", type);
16478 return error_mark_node;
16481 if (!verify_type_context (input_location, TCTX_ARRAY_ELEMENT, type,
16482 !(complain & tf_error)))
16483 return error_mark_node;
16485 r = build_cplus_array_type (type, domain);
16487 if (!valid_array_size_p (input_location, r, in_decl,
16488 (complain & tf_error)))
16489 return error_mark_node;
16491 if (TYPE_USER_ALIGN (t))
16493 SET_TYPE_ALIGN (r, TYPE_ALIGN (t));
16494 TYPE_USER_ALIGN (r) = 1;
16497 return r;
16500 case TYPENAME_TYPE:
16502 tree ctx = TYPE_CONTEXT (t);
16503 if (TREE_CODE (ctx) == TYPE_PACK_EXPANSION)
16505 ctx = tsubst_pack_expansion (ctx, args,
16506 complain | tf_qualifying_scope,
16507 in_decl);
16508 if (ctx == error_mark_node
16509 || TREE_VEC_LENGTH (ctx) > 1)
16510 return error_mark_node;
16511 if (TREE_VEC_LENGTH (ctx) == 0)
16513 if (complain & tf_error)
16514 error ("%qD is instantiated for an empty pack",
16515 TYPENAME_TYPE_FULLNAME (t));
16516 return error_mark_node;
16518 ctx = TREE_VEC_ELT (ctx, 0);
16520 else
16521 ctx = tsubst_aggr_type (ctx, args,
16522 complain | tf_qualifying_scope,
16523 in_decl, /*entering_scope=*/1);
16524 if (ctx == error_mark_node)
16525 return error_mark_node;
16527 tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
16528 complain, in_decl);
16529 if (f == error_mark_node)
16530 return error_mark_node;
16532 if (!MAYBE_CLASS_TYPE_P (ctx))
16534 if (complain & tf_error)
16535 error ("%qT is not a class, struct, or union type", ctx);
16536 return error_mark_node;
16538 else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
16540 /* Normally, make_typename_type does not require that the CTX
16541 have complete type in order to allow things like:
16543 template <class T> struct S { typename S<T>::X Y; };
16545 But, such constructs have already been resolved by this
16546 point, so here CTX really should have complete type, unless
16547 it's a partial instantiation. */
16548 if (!complete_type_or_maybe_complain (ctx, NULL_TREE, complain))
16549 return error_mark_node;
16552 /* FIXME: TYPENAME_IS_CLASS_P conflates 'class' vs 'struct' vs 'union'
16553 tags. TYPENAME_TYPE should probably remember the exact tag that
16554 was written. */
16555 enum tag_types tag_type
16556 = TYPENAME_IS_CLASS_P (t) ? class_type
16557 : TYPENAME_IS_ENUM_P (t) ? enum_type
16558 : typename_type;
16559 tsubst_flags_t tcomplain = complain | tf_keep_type_decl;
16560 tcomplain |= tst_ok_flag | qualifying_scope_flag;
16561 f = make_typename_type (ctx, f, tag_type, tcomplain);
16562 if (f == error_mark_node)
16563 return f;
16564 if (TREE_CODE (f) == TYPE_DECL)
16566 complain |= tf_ignore_bad_quals;
16567 f = TREE_TYPE (f);
16570 if (TREE_CODE (f) != TYPENAME_TYPE)
16572 if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
16574 if (complain & tf_error)
16575 error ("%qT resolves to %qT, which is not an enumeration type",
16576 t, f);
16577 else
16578 return error_mark_node;
16580 else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
16582 if (complain & tf_error)
16583 error ("%qT resolves to %qT, which is not a class type",
16584 t, f);
16585 else
16586 return error_mark_node;
16590 return cp_build_qualified_type
16591 (f, cp_type_quals (f) | cp_type_quals (t), complain);
16594 case UNBOUND_CLASS_TEMPLATE:
16596 tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
16597 in_decl, /*entering_scope=*/1);
16598 tree name = TYPE_IDENTIFIER (t);
16599 tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
16601 if (ctx == error_mark_node || name == error_mark_node)
16602 return error_mark_node;
16604 if (parm_list)
16605 parm_list = tsubst_template_parms (parm_list, args, complain);
16606 return make_unbound_class_template (ctx, name, parm_list, complain);
16609 case TYPEOF_TYPE:
16611 tree type;
16613 ++cp_unevaluated_operand;
16614 ++c_inhibit_evaluation_warnings;
16616 type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args, complain, in_decl);
16618 --cp_unevaluated_operand;
16619 --c_inhibit_evaluation_warnings;
16621 type = finish_typeof (type);
16622 return cp_build_qualified_type (type,
16623 cp_type_quals (t)
16624 | cp_type_quals (type),
16625 complain);
16628 case DECLTYPE_TYPE:
16630 tree type;
16632 ++cp_unevaluated_operand;
16633 ++c_inhibit_evaluation_warnings;
16635 type = tsubst_copy_and_build (DECLTYPE_TYPE_EXPR (t), args,
16636 complain|tf_decltype, in_decl);
16638 --cp_unevaluated_operand;
16639 --c_inhibit_evaluation_warnings;
16641 if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
16642 type = lambda_capture_field_type (type,
16643 false /*explicit_init*/,
16644 DECLTYPE_FOR_REF_CAPTURE (t));
16645 else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
16646 type = lambda_proxy_type (type);
16647 else
16649 bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
16650 if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
16651 && EXPR_P (type))
16652 /* In a template ~id could be either a complement expression
16653 or an unqualified-id naming a destructor; if instantiating
16654 it produces an expression, it's not an id-expression or
16655 member access. */
16656 id = false;
16657 type = finish_decltype_type (type, id, complain);
16659 return cp_build_qualified_type (type,
16660 cp_type_quals (t)
16661 | cp_type_quals (type),
16662 complain | tf_ignore_bad_quals);
16665 case TRAIT_TYPE:
16667 tree type1 = TRAIT_TYPE_TYPE1 (t);
16668 if (TYPE_P (type1))
16669 type1 = tsubst (type1, args, complain, in_decl);
16670 else
16671 type1 = tsubst_copy_and_build (type1, args, complain, in_decl);
16672 tree type2 = tsubst (TRAIT_TYPE_TYPE2 (t), args, complain, in_decl);
16673 type = finish_trait_type (TRAIT_TYPE_KIND (t), type1, type2, complain);
16674 return cp_build_qualified_type (type,
16675 cp_type_quals (t) | cp_type_quals (type),
16676 complain | tf_ignore_bad_quals);
16679 case TYPE_ARGUMENT_PACK:
16680 case NONTYPE_ARGUMENT_PACK:
16681 return tsubst_argument_pack (t, args, complain, in_decl);
16683 case VOID_CST:
16684 case INTEGER_CST:
16685 case REAL_CST:
16686 case STRING_CST:
16687 case PLUS_EXPR:
16688 case MINUS_EXPR:
16689 case NEGATE_EXPR:
16690 case NOP_EXPR:
16691 case INDIRECT_REF:
16692 case ADDR_EXPR:
16693 case CALL_EXPR:
16694 case ARRAY_REF:
16695 case SCOPE_REF:
16696 /* We should use one of the expression tsubsts for these codes. */
16697 gcc_unreachable ();
16699 default:
16700 sorry ("use of %qs in template", get_tree_code_name (code));
16701 return error_mark_node;
16705 /* Convenience wrapper over tsubst for substituting into the LHS
16706 of the :: scope resolution operator. */
16708 static tree
16709 tsubst_scope (tree t, tree args, tsubst_flags_t complain, tree in_decl)
16711 gcc_checking_assert (TYPE_P (t));
16712 return tsubst (t, args, complain | tf_qualifying_scope, in_decl);
16715 /* OLDFNS is a lookup set of member functions from some class template, and
16716 NEWFNS is a lookup set of member functions from NEWTYPE, a specialization
16717 of that class template. Return the subset of NEWFNS which are
16718 specializations of a function from OLDFNS. */
16720 static tree
16721 filter_memfn_lookup (tree oldfns, tree newfns, tree newtype)
16723 /* Record all member functions from the old lookup set OLDFNS into
16724 VISIBLE_SET. */
16725 hash_set<tree> visible_set;
16726 bool seen_dep_using = false;
16727 for (tree fn : lkp_range (oldfns))
16729 if (TREE_CODE (fn) == USING_DECL)
16731 /* Imprecisely handle dependent using-decl by keeping all members
16732 in the new lookup set that are defined in a base class, i.e.
16733 members that could plausibly have been introduced by this
16734 dependent using-decl.
16735 FIXME: Track which members are introduced by a dependent
16736 using-decl precisely, perhaps by performing another lookup
16737 from the substituted USING_DECL_SCOPE. */
16738 gcc_checking_assert (DECL_DEPENDENT_P (fn));
16739 seen_dep_using = true;
16741 else
16742 visible_set.add (fn);
16745 /* Returns true iff (a less specialized version of) FN appeared in
16746 the old lookup set OLDFNS. */
16747 auto visible_p = [newtype, seen_dep_using, &visible_set] (tree fn) {
16748 if (DECL_CONTEXT (fn) != newtype)
16749 /* FN is a member function from a base class, introduced via a
16750 using-decl; if it might have been introduced by a dependent
16751 using-decl then just conservatively keep it, otherwise look
16752 in the old lookup set for FN exactly. */
16753 return seen_dep_using || visible_set.contains (fn);
16754 else if (TREE_CODE (fn) == TEMPLATE_DECL)
16755 /* FN is a member function template from the current class;
16756 look in the old lookup set for the TEMPLATE_DECL from which
16757 it was specialized. */
16758 return visible_set.contains (DECL_TI_TEMPLATE (fn));
16759 else
16760 /* FN is a non-template member function from the current class;
16761 look in the old lookup set for the FUNCTION_DECL from which
16762 it was specialized. */
16763 return visible_set.contains (DECL_TEMPLATE_RESULT
16764 (DECL_TI_TEMPLATE (fn)));
16767 bool lookup_changed_p = false;
16768 for (tree fn : lkp_range (newfns))
16769 if (!visible_p (fn))
16771 lookup_changed_p = true;
16772 break;
16774 if (!lookup_changed_p)
16775 return newfns;
16777 /* Filter out from NEWFNS the member functions that weren't
16778 previously visible according to OLDFNS. */
16779 tree filtered_fns = NULL_TREE;
16780 unsigned filtered_size = 0;
16781 for (tree fn : lkp_range (newfns))
16782 if (visible_p (fn))
16784 filtered_fns = lookup_add (fn, filtered_fns);
16785 filtered_size++;
16787 gcc_checking_assert (seen_dep_using
16788 ? filtered_size >= visible_set.elements ()
16789 : filtered_size == visible_set.elements ());
16791 return filtered_fns;
16794 /* tsubst a BASELINK. OBJECT_TYPE, if non-NULL, is the type of the
16795 expression on the left-hand side of the "." or "->" operator. We
16796 only do the lookup if we had a dependent BASELINK. Otherwise we
16797 adjust it onto the instantiated heirarchy. */
16799 static tree
16800 tsubst_baselink (tree baselink, tree object_type,
16801 tree args, tsubst_flags_t complain, tree in_decl)
16803 bool qualified_p = BASELINK_QUALIFIED_P (baselink);
16804 tree qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
16805 qualifying_scope = tsubst (qualifying_scope, args, complain, in_decl);
16807 tree optype = BASELINK_OPTYPE (baselink);
16808 optype = tsubst (optype, args, complain, in_decl);
16810 tree template_args = NULL_TREE;
16811 bool template_id_p = false;
16812 tree fns = BASELINK_FUNCTIONS (baselink);
16813 if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
16815 template_id_p = true;
16816 template_args = TREE_OPERAND (fns, 1);
16817 fns = TREE_OPERAND (fns, 0);
16818 if (template_args)
16819 template_args = tsubst_template_args (template_args, args,
16820 complain, in_decl);
16823 tree binfo_type = BINFO_TYPE (BASELINK_BINFO (baselink));
16824 binfo_type = tsubst (binfo_type, args, complain, in_decl);
16825 bool dependent_p = (binfo_type != BINFO_TYPE (BASELINK_BINFO (baselink))
16826 || optype != BASELINK_OPTYPE (baselink));
16828 if (dependent_p)
16830 tree name = OVL_NAME (fns);
16831 if (IDENTIFIER_CONV_OP_P (name))
16832 name = make_conv_op_name (optype);
16834 /* See maybe_dependent_member_ref. */
16835 if ((complain & tf_dguide) && dependent_scope_p (qualifying_scope))
16837 if (template_id_p)
16838 name = build2 (TEMPLATE_ID_EXPR, unknown_type_node, name,
16839 template_args);
16840 return build_qualified_name (NULL_TREE, qualifying_scope, name,
16841 /* ::template */false);
16844 if (name == complete_dtor_identifier)
16845 /* Treat as-if non-dependent below. */
16846 dependent_p = false;
16848 bool maybe_incomplete = BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (baselink);
16849 baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1,
16850 complain);
16851 if (maybe_incomplete)
16853 /* Filter out from the new lookup set those functions which didn't
16854 appear in the original lookup set (in a less specialized form).
16855 This is needed to preserve the consistency of member lookup
16856 performed in an incomplete-class context, within which
16857 later-declared members ought to remain invisible. */
16858 BASELINK_FUNCTIONS (baselink)
16859 = filter_memfn_lookup (fns, BASELINK_FUNCTIONS (baselink),
16860 binfo_type);
16861 BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (baselink) = true;
16864 if (!baselink)
16866 if ((complain & tf_error)
16867 && constructor_name_p (name, qualifying_scope))
16868 error ("cannot call constructor %<%T::%D%> directly",
16869 qualifying_scope, name);
16870 return error_mark_node;
16873 fns = BASELINK_FUNCTIONS (baselink);
16875 else
16877 /* We're going to overwrite pieces below, make a duplicate. */
16878 baselink = copy_node (baselink);
16880 if (qualifying_scope != BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink)))
16882 /* The decl we found was from non-dependent scope, but we still need
16883 to update the binfos for the instantiated qualifying_scope. */
16884 BASELINK_ACCESS_BINFO (baselink) = TYPE_BINFO (qualifying_scope);
16885 BASELINK_BINFO (baselink) = lookup_base (qualifying_scope, binfo_type,
16886 ba_unique, nullptr, complain);
16890 /* If lookup found a single function, mark it as used at this point.
16891 (If lookup found multiple functions the one selected later by
16892 overload resolution will be marked as used at that point.) */
16893 if (!template_id_p && !really_overloaded_fn (fns))
16895 tree fn = OVL_FIRST (fns);
16896 bool ok = mark_used (fn, complain);
16897 if (!ok && !(complain & tf_error))
16898 return error_mark_node;
16899 if (ok && BASELINK_P (baselink))
16900 /* We might have instantiated an auto function. */
16901 TREE_TYPE (baselink) = TREE_TYPE (fn);
16904 if (BASELINK_P (baselink))
16906 /* Add back the template arguments, if present. */
16907 if (template_id_p)
16908 BASELINK_FUNCTIONS (baselink)
16909 = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, template_args);
16911 /* Update the conversion operator type. */
16912 BASELINK_OPTYPE (baselink) = optype;
16915 if (!object_type)
16916 object_type = current_class_type;
16918 if (qualified_p || !dependent_p)
16920 baselink = adjust_result_of_qualified_name_lookup (baselink,
16921 qualifying_scope,
16922 object_type);
16923 if (!qualified_p)
16924 /* We need to call adjust_result_of_qualified_name_lookup in case the
16925 destructor names a base class, but we unset BASELINK_QUALIFIED_P
16926 so that we still get virtual function binding. */
16927 BASELINK_QUALIFIED_P (baselink) = false;
16930 return baselink;
16933 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID. DONE is
16934 true if the qualified-id will be a postfix-expression in-and-of
16935 itself; false if more of the postfix-expression follows the
16936 QUALIFIED_ID. ADDRESS_P is true if the qualified-id is the operand
16937 of "&". */
16939 static tree
16940 tsubst_qualified_id (tree qualified_id, tree args,
16941 tsubst_flags_t complain, tree in_decl,
16942 bool done, bool address_p)
16944 tree expr;
16945 tree scope;
16946 tree name;
16947 bool is_template;
16948 tree template_args;
16949 location_t loc = EXPR_LOCATION (qualified_id);
16951 gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
16953 /* Figure out what name to look up. */
16954 name = TREE_OPERAND (qualified_id, 1);
16955 if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
16957 is_template = true;
16958 template_args = TREE_OPERAND (name, 1);
16959 if (template_args)
16960 template_args = tsubst_template_args (template_args, args,
16961 complain, in_decl);
16962 if (template_args == error_mark_node)
16963 return error_mark_node;
16964 name = TREE_OPERAND (name, 0);
16966 else
16968 is_template = false;
16969 template_args = NULL_TREE;
16972 /* Substitute into the qualifying scope. When there are no ARGS, we
16973 are just trying to simplify a non-dependent expression. In that
16974 case the qualifying scope may be dependent, and, in any case,
16975 substituting will not help. */
16976 scope = TREE_OPERAND (qualified_id, 0);
16977 if (args)
16979 scope = tsubst_scope (scope, args, complain, in_decl);
16980 expr = tsubst_copy (name, args, complain, in_decl);
16982 else
16983 expr = name;
16985 if (dependent_scope_p (scope))
16987 if (TREE_CODE (expr) == SCOPE_REF)
16988 /* We built one in tsubst_baselink. */
16989 gcc_checking_assert (same_type_p (scope, TREE_OPERAND (expr, 0)));
16990 else
16992 if (is_template)
16993 expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr,
16994 template_args);
16995 expr = build_qualified_name (NULL_TREE, scope, expr,
16996 QUALIFIED_NAME_IS_TEMPLATE
16997 (qualified_id));
16999 REF_PARENTHESIZED_P (expr) = REF_PARENTHESIZED_P (qualified_id);
17000 return expr;
17003 if (!BASELINK_P (name) && !DECL_P (expr))
17005 if (TREE_CODE (expr) == BIT_NOT_EXPR)
17007 /* A BIT_NOT_EXPR is used to represent a destructor. */
17008 if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
17010 error ("qualifying type %qT does not match destructor name ~%qT",
17011 scope, TREE_OPERAND (expr, 0));
17012 expr = error_mark_node;
17014 else
17015 expr = lookup_qualified_name (scope, complete_dtor_identifier,
17016 LOOK_want::NORMAL, false);
17018 else
17019 expr = lookup_qualified_name (scope, expr, LOOK_want::NORMAL, false);
17020 if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
17021 ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
17023 if (complain & tf_error)
17025 error ("dependent-name %qE is parsed as a non-type, but "
17026 "instantiation yields a type", qualified_id);
17027 inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
17029 return error_mark_node;
17033 if (DECL_P (expr))
17035 if (!check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
17036 scope, complain))
17037 return error_mark_node;
17038 /* Remember that there was a reference to this entity. */
17039 if (!mark_used (expr, complain) && !(complain & tf_error))
17040 return error_mark_node;
17043 if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
17045 if (complain & tf_error)
17046 qualified_name_lookup_error (scope,
17047 TREE_OPERAND (qualified_id, 1),
17048 expr, input_location);
17049 return error_mark_node;
17052 if (is_template)
17054 /* We may be repeating a check already done during parsing, but
17055 if it was well-formed and passed then, it will pass again
17056 now, and if it didn't, we wouldn't have got here. The case
17057 we want to catch is when we couldn't tell then, and can now,
17058 namely when templ prior to substitution was an
17059 identifier. */
17060 if (flag_concepts && check_auto_in_tmpl_args (expr, template_args))
17061 return error_mark_node;
17063 if (variable_template_p (expr))
17064 expr = lookup_and_finish_template_variable (expr, template_args,
17065 complain);
17066 else
17067 expr = lookup_template_function (expr, template_args);
17070 if (expr == error_mark_node && complain & tf_error)
17071 qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
17072 expr, input_location);
17073 else if (TYPE_P (scope))
17075 expr = (adjust_result_of_qualified_name_lookup
17076 (expr, scope, current_nonlambda_class_type ()));
17077 expr = (finish_qualified_id_expr
17078 (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
17079 QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
17080 /*template_arg_p=*/false, complain));
17083 /* Expressions do not generally have reference type. */
17084 if (TREE_CODE (expr) != SCOPE_REF
17085 /* However, if we're about to form a pointer-to-member, we just
17086 want the referenced member referenced. */
17087 && TREE_CODE (expr) != OFFSET_REF)
17088 expr = convert_from_reference (expr);
17090 if (REF_PARENTHESIZED_P (qualified_id))
17091 expr = force_paren_expr (expr);
17093 expr = maybe_wrap_with_location (expr, loc);
17095 return expr;
17098 /* tsubst the initializer for a VAR_DECL. INIT is the unsubstituted
17099 initializer, DECL is the substituted VAR_DECL. Other arguments are as
17100 for tsubst. */
17102 static tree
17103 tsubst_init (tree init, tree decl, tree args,
17104 tsubst_flags_t complain, tree in_decl)
17106 if (!init)
17107 return NULL_TREE;
17109 init = tsubst_expr (init, args, complain, in_decl);
17111 tree type = TREE_TYPE (decl);
17113 if (!init && type != error_mark_node)
17115 if (tree auto_node = type_uses_auto (type))
17117 if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
17119 if (complain & tf_error)
17120 error ("initializer for %q#D expands to an empty list "
17121 "of expressions", decl);
17122 return error_mark_node;
17125 else if (!dependent_type_p (type))
17127 /* If we had an initializer but it
17128 instantiated to nothing,
17129 value-initialize the object. This will
17130 only occur when the initializer was a
17131 pack expansion where the parameter packs
17132 used in that expansion were of length
17133 zero. */
17134 init = build_value_init (type, complain);
17135 if (TREE_CODE (init) == AGGR_INIT_EXPR)
17136 init = get_target_expr (init, complain);
17137 if (TREE_CODE (init) == TARGET_EXPR)
17138 TARGET_EXPR_DIRECT_INIT_P (init) = true;
17142 return init;
17145 /* If T is a reference to a dependent member of the current instantiation C and
17146 we are trying to refer to that member in a partial instantiation of C,
17147 return a SCOPE_REF; otherwise, return NULL_TREE.
17149 This can happen when forming a C++17 deduction guide, as in PR96199. */
17151 static tree
17152 maybe_dependent_member_ref (tree t, tree args, tsubst_flags_t complain,
17153 tree in_decl)
17155 if (!(complain & tf_dguide))
17156 return NULL_TREE;
17158 tree decl = (t && TYPE_P (t)) ? TYPE_NAME (t) : t;
17159 if (!decl || !DECL_P (decl))
17160 return NULL_TREE;
17162 tree ctx = context_for_name_lookup (decl);
17163 if (!CLASS_TYPE_P (ctx))
17164 return NULL_TREE;
17166 ctx = tsubst (ctx, args, complain, in_decl);
17167 if (!dependent_scope_p (ctx))
17168 return NULL_TREE;
17170 if (TYPE_P (t))
17172 if (typedef_variant_p (t))
17173 t = strip_typedefs (t);
17174 tree decl = TYPE_NAME (t);
17175 if (decl)
17176 decl = maybe_dependent_member_ref (decl, args, complain, in_decl);
17177 if (!decl)
17178 return NULL_TREE;
17179 return cp_build_qualified_type (TREE_TYPE (decl), cp_type_quals (t),
17180 complain);
17183 tree name = DECL_NAME (t);
17184 tree fullname = name;
17185 if (instantiates_primary_template_p (t))
17187 tree tinfo = get_template_info (t);
17188 name = DECL_NAME (TI_TEMPLATE (tinfo));
17189 tree targs = INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo));
17190 targs = tsubst_template_args (targs, args, complain, in_decl);
17191 fullname = build_nt (TEMPLATE_ID_EXPR, name, targs);
17194 if (TREE_CODE (t) == TYPE_DECL)
17196 if (TREE_CODE (TREE_TYPE (t)) == TYPENAME_TYPE
17197 && TYPE_NAME (TREE_TYPE (t)) == t)
17198 /* The TYPE_DECL for a typename has DECL_CONTEXT of the typename
17199 scope, but it doesn't need to be rewritten again. */
17200 return NULL_TREE;
17201 tree type = build_typename_type (ctx, name, fullname, typename_type);
17202 return TYPE_NAME (type);
17204 else if (DECL_TYPE_TEMPLATE_P (t))
17205 return make_unbound_class_template (ctx, name,
17206 NULL_TREE, complain);
17207 else
17208 return build_qualified_name (NULL_TREE, ctx, fullname,
17209 TREE_CODE (t) == TEMPLATE_DECL);
17212 /* Like tsubst, but deals with expressions. This function just replaces
17213 template parms; to finish processing the resultant expression, use
17214 tsubst_copy_and_build or tsubst_expr. */
17216 static tree
17217 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
17219 enum tree_code code;
17220 tree r;
17222 if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
17223 return t;
17225 if (TYPE_P (t))
17226 return tsubst (t, args, complain, in_decl);
17228 if (tree d = maybe_dependent_member_ref (t, args, complain, in_decl))
17229 return d;
17231 code = TREE_CODE (t);
17233 switch (code)
17235 case PARM_DECL:
17236 r = retrieve_local_specialization (t);
17238 if (r == NULL_TREE)
17240 /* We get here for a use of 'this' in an NSDMI. */
17241 if (DECL_NAME (t) == this_identifier && current_class_ptr)
17242 return current_class_ptr;
17244 /* This can happen for a parameter name used later in a function
17245 declaration (such as in a late-specified return type). Just
17246 make a dummy decl, since it's only used for its type. */
17247 gcc_assert (cp_unevaluated_operand);
17248 r = tsubst_decl (t, args, complain);
17249 /* Give it the template pattern as its context; its true context
17250 hasn't been instantiated yet and this is good enough for
17251 mangling. */
17252 DECL_CONTEXT (r) = DECL_CONTEXT (t);
17255 if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
17256 r = argument_pack_select_arg (r);
17257 if (!mark_used (r, complain) && !(complain & tf_error))
17258 return error_mark_node;
17259 return r;
17261 case CONST_DECL:
17263 tree enum_type;
17264 tree v;
17266 if (DECL_TEMPLATE_PARM_P (t))
17267 return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
17268 if (!uses_template_parms (DECL_CONTEXT (t)))
17269 return t;
17271 /* Unfortunately, we cannot just call lookup_name here.
17272 Consider:
17274 template <int I> int f() {
17275 enum E { a = I };
17276 struct S { void g() { E e = a; } };
17279 When we instantiate f<7>::S::g(), say, lookup_name is not
17280 clever enough to find f<7>::a. */
17281 enum_type
17282 = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
17283 /*entering_scope=*/0);
17285 for (v = TYPE_VALUES (enum_type);
17286 v != NULL_TREE;
17287 v = TREE_CHAIN (v))
17288 if (TREE_PURPOSE (v) == DECL_NAME (t))
17289 return TREE_VALUE (v);
17291 /* We didn't find the name. That should never happen; if
17292 name-lookup found it during preliminary parsing, we
17293 should find it again here during instantiation. */
17294 gcc_unreachable ();
17296 return t;
17298 case FIELD_DECL:
17299 if (DECL_CONTEXT (t))
17301 tree ctx;
17303 ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
17304 /*entering_scope=*/1);
17305 if (ctx != DECL_CONTEXT (t))
17307 tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
17308 if (!r)
17310 if (complain & tf_error)
17311 error ("using invalid field %qD", t);
17312 return error_mark_node;
17314 return r;
17318 return t;
17320 case VAR_DECL:
17321 case FUNCTION_DECL:
17322 if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
17323 r = tsubst (t, args, complain, in_decl);
17324 else if (DECL_LOCAL_DECL_P (t))
17326 /* Local specialization will usually have been created when
17327 we instantiated the DECL_EXPR_DECL. */
17328 r = retrieve_local_specialization (t);
17329 if (!r)
17331 /* We're in a generic lambda referencing a local extern
17332 from an outer block-scope of a non-template. */
17333 gcc_checking_assert (LAMBDA_FUNCTION_P (current_function_decl));
17334 r = t;
17337 else if (local_variable_p (t)
17338 && uses_template_parms (DECL_CONTEXT (t)))
17340 r = retrieve_local_specialization (t);
17341 if (r == NULL_TREE)
17343 /* First try name lookup to find the instantiation. */
17344 r = lookup_name (DECL_NAME (t));
17345 if (r)
17347 if (!VAR_P (r))
17349 /* During error-recovery we may find a non-variable,
17350 even an OVERLOAD: just bail out and avoid ICEs and
17351 duplicate diagnostics (c++/62207). */
17352 gcc_assert (seen_error ());
17353 return error_mark_node;
17355 if (!is_capture_proxy (r))
17357 /* Make sure the one we found is the one we want. */
17358 tree ctx = enclosing_instantiation_of (DECL_CONTEXT (t));
17359 if (ctx != DECL_CONTEXT (r))
17360 r = NULL_TREE;
17364 if (r)
17365 /* OK */;
17366 else
17368 /* This can happen for a variable used in a
17369 late-specified return type of a local lambda, or for a
17370 local static or constant. Building a new VAR_DECL
17371 should be OK in all those cases. */
17372 r = tsubst_decl (t, args, complain);
17373 if (local_specializations)
17374 /* Avoid infinite recursion (79640). */
17375 register_local_specialization (r, t);
17376 if (decl_maybe_constant_var_p (r))
17378 /* We can't call cp_finish_decl, so handle the
17379 initializer by hand. */
17380 tree init = tsubst_init (DECL_INITIAL (t), r, args,
17381 complain, in_decl);
17382 if (!processing_template_decl)
17383 init = maybe_constant_init (init);
17384 if (processing_template_decl
17385 ? potential_constant_expression (init)
17386 : reduced_constant_expression_p (init))
17387 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
17388 = TREE_CONSTANT (r) = true;
17389 DECL_INITIAL (r) = init;
17390 if (tree auto_node = type_uses_auto (TREE_TYPE (r)))
17391 TREE_TYPE (r)
17392 = do_auto_deduction (TREE_TYPE (r), init, auto_node,
17393 complain, adc_variable_type);
17395 gcc_assert (cp_unevaluated_operand
17396 || processing_contract_condition
17397 || TREE_STATIC (r)
17398 || decl_constant_var_p (r)
17399 || seen_error ());
17400 if (!processing_template_decl
17401 && !TREE_STATIC (r))
17402 r = process_outer_var_ref (r, complain);
17404 /* Remember this for subsequent uses. */
17405 if (local_specializations)
17406 register_local_specialization (r, t);
17408 if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
17409 r = argument_pack_select_arg (r);
17411 else
17412 r = t;
17413 if (!mark_used (r, complain))
17414 return error_mark_node;
17415 return r;
17417 case NAMESPACE_DECL:
17418 return t;
17420 case OVERLOAD:
17421 return t;
17423 case BASELINK:
17424 return tsubst_baselink (t, current_nonlambda_class_type (),
17425 args, complain, in_decl);
17427 case TEMPLATE_DECL:
17428 if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
17429 return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
17430 args, complain, in_decl);
17431 else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
17432 return tsubst (t, args, complain, in_decl);
17433 else if (DECL_CLASS_SCOPE_P (t)
17434 && uses_template_parms (DECL_CONTEXT (t)))
17436 /* Template template argument like the following example need
17437 special treatment:
17439 template <template <class> class TT> struct C {};
17440 template <class T> struct D {
17441 template <class U> struct E {};
17442 C<E> c; // #1
17444 D<int> d; // #2
17446 We are processing the template argument `E' in #1 for
17447 the template instantiation #2. Originally, `E' is a
17448 TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT. Now we
17449 have to substitute this with one having context `D<int>'. */
17451 tree context = tsubst_aggr_type (DECL_CONTEXT (t), args, complain,
17452 in_decl, /*entering_scope=*/true);
17453 return lookup_field (context, DECL_NAME(t), 0, false);
17455 else
17456 /* Ordinary template template argument. */
17457 return t;
17459 case NON_LVALUE_EXPR:
17460 case VIEW_CONVERT_EXPR:
17462 /* Handle location wrappers by substituting the wrapped node
17463 first, *then* reusing the resulting type. Doing the type
17464 first ensures that we handle template parameters and
17465 parameter pack expansions. */
17466 if (location_wrapper_p (t))
17468 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args,
17469 complain, in_decl);
17470 return maybe_wrap_with_location (op0, EXPR_LOCATION (t));
17472 tree op = TREE_OPERAND (t, 0);
17473 /* force_paren_expr can also create a VIEW_CONVERT_EXPR. */
17474 if (code == VIEW_CONVERT_EXPR && REF_PARENTHESIZED_P (t))
17476 op = tsubst_copy (op, args, complain, in_decl);
17477 op = build1 (code, TREE_TYPE (op), op);
17478 REF_PARENTHESIZED_P (op) = true;
17479 return op;
17481 /* We shouldn't see any other uses of these in templates
17482 (tsubst_copy_and_build handles C++20 tparm object wrappers). */
17483 gcc_unreachable ();
17486 case CAST_EXPR:
17487 case REINTERPRET_CAST_EXPR:
17488 case CONST_CAST_EXPR:
17489 case STATIC_CAST_EXPR:
17490 case DYNAMIC_CAST_EXPR:
17491 case IMPLICIT_CONV_EXPR:
17492 CASE_CONVERT:
17494 tsubst_flags_t tcomplain = complain;
17495 if (code == CAST_EXPR)
17496 tcomplain |= tf_tst_ok;
17497 tree type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
17498 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17499 return build1 (code, type, op0);
17502 case BIT_CAST_EXPR:
17504 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17505 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17506 r = build_min (BIT_CAST_EXPR, type, op0);
17507 SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
17508 return r;
17511 case SIZEOF_EXPR:
17512 if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
17513 || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
17515 tree expanded, op = TREE_OPERAND (t, 0);
17516 int len = 0;
17518 if (SIZEOF_EXPR_TYPE_P (t))
17519 op = TREE_TYPE (op);
17521 ++cp_unevaluated_operand;
17522 ++c_inhibit_evaluation_warnings;
17523 /* We only want to compute the number of arguments. */
17524 if (PACK_EXPANSION_P (op))
17525 expanded = tsubst_pack_expansion (op, args, complain, in_decl);
17526 else
17527 expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
17528 args, complain, in_decl);
17529 --cp_unevaluated_operand;
17530 --c_inhibit_evaluation_warnings;
17532 if (TREE_CODE (expanded) == TREE_VEC)
17534 len = TREE_VEC_LENGTH (expanded);
17535 /* Set TREE_USED for the benefit of -Wunused. */
17536 for (int i = 0; i < len; i++)
17537 if (DECL_P (TREE_VEC_ELT (expanded, i)))
17538 TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
17541 if (expanded == error_mark_node)
17542 return error_mark_node;
17543 else if (PACK_EXPANSION_P (expanded)
17544 || (TREE_CODE (expanded) == TREE_VEC
17545 && pack_expansion_args_count (expanded)))
17548 if (PACK_EXPANSION_P (expanded))
17549 /* OK. */;
17550 else if (TREE_VEC_LENGTH (expanded) == 1)
17551 expanded = TREE_VEC_ELT (expanded, 0);
17552 else
17553 expanded = make_argument_pack (expanded);
17555 if (TYPE_P (expanded))
17556 return cxx_sizeof_or_alignof_type (input_location,
17557 expanded, SIZEOF_EXPR,
17558 false,
17559 complain & tf_error);
17560 else
17561 return cxx_sizeof_or_alignof_expr (input_location,
17562 expanded, SIZEOF_EXPR,
17563 false,
17564 complain & tf_error);
17566 else
17567 return build_int_cst (size_type_node, len);
17569 if (SIZEOF_EXPR_TYPE_P (t))
17571 r = tsubst (TREE_TYPE (TREE_OPERAND (t, 0)),
17572 args, complain, in_decl);
17573 r = build1 (NOP_EXPR, r, error_mark_node);
17574 r = build1 (SIZEOF_EXPR,
17575 tsubst (TREE_TYPE (t), args, complain, in_decl), r);
17576 SIZEOF_EXPR_TYPE_P (r) = 1;
17577 return r;
17579 /* Fall through */
17581 case INDIRECT_REF:
17582 case NEGATE_EXPR:
17583 case TRUTH_NOT_EXPR:
17584 case BIT_NOT_EXPR:
17585 case ADDR_EXPR:
17586 case UNARY_PLUS_EXPR: /* Unary + */
17587 case ALIGNOF_EXPR:
17588 case AT_ENCODE_EXPR:
17589 case ARROW_EXPR:
17590 case THROW_EXPR:
17591 case TYPEID_EXPR:
17592 case REALPART_EXPR:
17593 case IMAGPART_EXPR:
17594 case PAREN_EXPR:
17596 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17597 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17598 r = build1_loc (EXPR_LOCATION (t), code, type, op0);
17599 if (code == ALIGNOF_EXPR)
17600 ALIGNOF_EXPR_STD_P (r) = ALIGNOF_EXPR_STD_P (t);
17601 /* For addresses of immediate functions ensure we have EXPR_LOCATION
17602 set for possible later diagnostics. */
17603 if (code == ADDR_EXPR
17604 && EXPR_LOCATION (r) == UNKNOWN_LOCATION
17605 && TREE_CODE (op0) == FUNCTION_DECL
17606 && DECL_IMMEDIATE_FUNCTION_P (op0))
17607 SET_EXPR_LOCATION (r, input_location);
17608 return r;
17611 case EXCESS_PRECISION_EXPR:
17613 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17614 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17615 if (TREE_CODE (op0) == EXCESS_PRECISION_EXPR)
17617 gcc_checking_assert (same_type_p (type, TREE_TYPE (op0)));
17618 return op0;
17620 return build1_loc (EXPR_LOCATION (t), code, type, op0);
17623 case COMPONENT_REF:
17625 tree object;
17626 tree name;
17628 object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17629 name = TREE_OPERAND (t, 1);
17630 if (TREE_CODE (name) == BIT_NOT_EXPR)
17632 name = tsubst_copy (TREE_OPERAND (name, 0), args,
17633 complain, in_decl);
17634 name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
17636 else if (TREE_CODE (name) == SCOPE_REF
17637 && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
17639 tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
17640 complain, in_decl);
17641 name = TREE_OPERAND (name, 1);
17642 name = tsubst_copy (TREE_OPERAND (name, 0), args,
17643 complain, in_decl);
17644 name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
17645 name = build_qualified_name (/*type=*/NULL_TREE,
17646 base, name,
17647 /*template_p=*/false);
17649 else if (BASELINK_P (name))
17650 name = tsubst_baselink (name,
17651 non_reference (TREE_TYPE (object)),
17652 args, complain,
17653 in_decl);
17654 else
17655 name = tsubst_copy (name, args, complain, in_decl);
17656 return build_nt (COMPONENT_REF, object, name, NULL_TREE);
17659 case PLUS_EXPR:
17660 case MINUS_EXPR:
17661 case MULT_EXPR:
17662 case TRUNC_DIV_EXPR:
17663 case CEIL_DIV_EXPR:
17664 case FLOOR_DIV_EXPR:
17665 case ROUND_DIV_EXPR:
17666 case EXACT_DIV_EXPR:
17667 case BIT_AND_EXPR:
17668 case BIT_IOR_EXPR:
17669 case BIT_XOR_EXPR:
17670 case TRUNC_MOD_EXPR:
17671 case FLOOR_MOD_EXPR:
17672 case TRUTH_ANDIF_EXPR:
17673 case TRUTH_ORIF_EXPR:
17674 case TRUTH_AND_EXPR:
17675 case TRUTH_OR_EXPR:
17676 case RSHIFT_EXPR:
17677 case LSHIFT_EXPR:
17678 case EQ_EXPR:
17679 case NE_EXPR:
17680 case MAX_EXPR:
17681 case MIN_EXPR:
17682 case LE_EXPR:
17683 case GE_EXPR:
17684 case LT_EXPR:
17685 case GT_EXPR:
17686 case COMPOUND_EXPR:
17687 case DOTSTAR_EXPR:
17688 case MEMBER_REF:
17689 case PREDECREMENT_EXPR:
17690 case PREINCREMENT_EXPR:
17691 case POSTDECREMENT_EXPR:
17692 case POSTINCREMENT_EXPR:
17694 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17695 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17696 return build_nt (code, op0, op1);
17699 case SCOPE_REF:
17701 tree op0 = tsubst_scope (TREE_OPERAND (t, 0), args, complain, in_decl);
17702 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17703 return build_qualified_name (/*type=*/NULL_TREE, op0, op1,
17704 QUALIFIED_NAME_IS_TEMPLATE (t));
17707 case ARRAY_REF:
17709 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17710 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17711 return build_nt (ARRAY_REF, op0, op1, NULL_TREE, NULL_TREE);
17714 case CALL_EXPR:
17716 int n = VL_EXP_OPERAND_LENGTH (t);
17717 tree result = build_vl_exp (CALL_EXPR, n);
17718 int i;
17719 for (i = 0; i < n; i++)
17720 TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
17721 complain, in_decl);
17722 return result;
17725 case COND_EXPR:
17726 case MODOP_EXPR:
17727 case PSEUDO_DTOR_EXPR:
17728 case VEC_PERM_EXPR:
17730 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17731 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17732 tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
17733 r = build_nt (code, op0, op1, op2);
17734 copy_warning (r, t);
17735 return r;
17738 case NEW_EXPR:
17740 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17741 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17742 tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
17743 r = build_nt (code, op0, op1, op2);
17744 NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
17745 return r;
17748 case DELETE_EXPR:
17750 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17751 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17752 r = build_nt (code, op0, op1);
17753 DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
17754 DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
17755 return r;
17758 case TEMPLATE_ID_EXPR:
17760 /* Substituted template arguments */
17761 tree tmpl = TREE_OPERAND (t, 0);
17762 tree targs = TREE_OPERAND (t, 1);
17764 tmpl = tsubst_copy (tmpl, args, complain, in_decl);
17765 if (targs)
17766 targs = tsubst_template_args (targs, args, complain, in_decl);
17768 if (variable_template_p (tmpl))
17769 return lookup_template_variable (tmpl, targs);
17770 else
17771 return lookup_template_function (tmpl, targs);
17774 case TREE_LIST:
17776 tree purpose, value, chain;
17778 if (t == void_list_node)
17779 return t;
17781 purpose = TREE_PURPOSE (t);
17782 if (purpose)
17783 purpose = tsubst_copy (purpose, args, complain, in_decl);
17784 value = TREE_VALUE (t);
17785 if (value)
17786 value = tsubst_copy (value, args, complain, in_decl);
17787 chain = TREE_CHAIN (t);
17788 if (chain && chain != void_type_node)
17789 chain = tsubst_copy (chain, args, complain, in_decl);
17790 if (purpose == TREE_PURPOSE (t)
17791 && value == TREE_VALUE (t)
17792 && chain == TREE_CHAIN (t))
17793 return t;
17794 return tree_cons (purpose, value, chain);
17797 case TEMPLATE_PARM_INDEX:
17798 case TYPE_DECL:
17799 return tsubst (t, args, complain, in_decl);
17801 case USING_DECL:
17802 t = DECL_NAME (t);
17803 /* Fall through. */
17804 case IDENTIFIER_NODE:
17805 if (IDENTIFIER_CONV_OP_P (t))
17807 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17808 return make_conv_op_name (new_type);
17810 else
17811 return t;
17813 case CONSTRUCTOR:
17814 /* This is handled by tsubst_copy_and_build. */
17815 gcc_unreachable ();
17817 case VA_ARG_EXPR:
17819 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17820 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17821 return build_x_va_arg (EXPR_LOCATION (t), op0, type);
17824 case CLEANUP_POINT_EXPR:
17825 /* We shouldn't have built any of these during initial template
17826 generation. Instead, they should be built during instantiation
17827 in response to the saved STMT_IS_FULL_EXPR_P setting. */
17828 gcc_unreachable ();
17830 case OFFSET_REF:
17832 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17833 tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17834 tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17835 r = build2 (code, type, op0, op1);
17836 PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
17837 if (!mark_used (TREE_OPERAND (r, 1), complain)
17838 && !(complain & tf_error))
17839 return error_mark_node;
17840 return r;
17843 case EXPR_PACK_EXPANSION:
17844 error ("invalid use of pack expansion expression");
17845 return error_mark_node;
17847 case NONTYPE_ARGUMENT_PACK:
17848 error ("use %<...%> to expand argument pack");
17849 return error_mark_node;
17851 case VOID_CST:
17852 gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
17853 return t;
17855 case INTEGER_CST:
17856 case REAL_CST:
17857 case COMPLEX_CST:
17858 case VECTOR_CST:
17860 /* Instantiate any typedefs in the type. */
17861 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17862 r = fold_convert (type, t);
17863 gcc_assert (TREE_CODE (r) == code);
17864 return r;
17867 case STRING_CST:
17869 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17870 r = t;
17871 if (type != TREE_TYPE (t))
17873 r = copy_node (t);
17874 TREE_TYPE (r) = type;
17876 return r;
17879 case PTRMEM_CST:
17880 /* These can sometimes show up in a partial instantiation, but never
17881 involve template parms. */
17882 gcc_assert (!uses_template_parms (t));
17883 return t;
17885 case UNARY_LEFT_FOLD_EXPR:
17886 return tsubst_unary_left_fold (t, args, complain, in_decl);
17887 case UNARY_RIGHT_FOLD_EXPR:
17888 return tsubst_unary_right_fold (t, args, complain, in_decl);
17889 case BINARY_LEFT_FOLD_EXPR:
17890 return tsubst_binary_left_fold (t, args, complain, in_decl);
17891 case BINARY_RIGHT_FOLD_EXPR:
17892 return tsubst_binary_right_fold (t, args, complain, in_decl);
17893 case PREDICT_EXPR:
17894 return t;
17896 case DEBUG_BEGIN_STMT:
17897 /* ??? There's no point in copying it for now, but maybe some
17898 day it will contain more information, such as a pointer back
17899 to the containing function, inlined copy or so. */
17900 return t;
17902 case CO_AWAIT_EXPR:
17903 return tsubst_expr (t, args, complain, in_decl);
17905 default:
17906 /* We shouldn't get here, but keep going if !flag_checking. */
17907 if (flag_checking)
17908 gcc_unreachable ();
17909 return t;
17913 /* Helper function for tsubst_omp_clauses, used for instantiation of
17914 OMP_CLAUSE_DECL of clauses. */
17916 static tree
17917 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
17918 tree in_decl, tree *iterator_cache)
17920 if (decl == NULL_TREE || decl == ridpointers[RID_OMP_ALL_MEMORY])
17921 return decl;
17923 /* Handle OpenMP iterators. */
17924 if (TREE_CODE (decl) == TREE_LIST
17925 && TREE_PURPOSE (decl)
17926 && TREE_CODE (TREE_PURPOSE (decl)) == TREE_VEC)
17928 tree ret;
17929 if (iterator_cache[0] == TREE_PURPOSE (decl))
17930 ret = iterator_cache[1];
17931 else
17933 tree *tp = &ret;
17934 begin_scope (sk_omp, NULL);
17935 for (tree it = TREE_PURPOSE (decl); it; it = TREE_CHAIN (it))
17937 *tp = copy_node (it);
17938 TREE_VEC_ELT (*tp, 0)
17939 = tsubst_decl (TREE_VEC_ELT (it, 0), args, complain);
17940 DECL_CONTEXT (TREE_VEC_ELT (*tp, 0)) = current_function_decl;
17941 pushdecl (TREE_VEC_ELT (*tp, 0));
17942 TREE_VEC_ELT (*tp, 1)
17943 = tsubst_expr (TREE_VEC_ELT (it, 1), args, complain, in_decl);
17944 TREE_VEC_ELT (*tp, 2)
17945 = tsubst_expr (TREE_VEC_ELT (it, 2), args, complain, in_decl);
17946 TREE_VEC_ELT (*tp, 3)
17947 = tsubst_expr (TREE_VEC_ELT (it, 3), args, complain, in_decl);
17948 TREE_CHAIN (*tp) = NULL_TREE;
17949 tp = &TREE_CHAIN (*tp);
17951 TREE_VEC_ELT (ret, 5) = poplevel (1, 1, 0);
17952 iterator_cache[0] = TREE_PURPOSE (decl);
17953 iterator_cache[1] = ret;
17955 return build_tree_list (ret, tsubst_omp_clause_decl (TREE_VALUE (decl),
17956 args, complain,
17957 in_decl, NULL));
17960 /* Handle an OpenMP array section represented as a TREE_LIST (or
17961 OMP_CLAUSE_DOACROSS_KIND). An OMP_CLAUSE_DOACROSS (with a depend
17962 kind of OMP_CLAUSE_DOACROSS_SINK) can also be represented as a
17963 TREE_LIST. We can handle it exactly the same as an array section
17964 (purpose, value, and a chain), even though the nomenclature
17965 (low_bound, length, etc) is different. */
17966 if (TREE_CODE (decl) == TREE_LIST)
17968 tree low_bound
17969 = tsubst_expr (TREE_PURPOSE (decl), args, complain, in_decl);
17970 tree length = tsubst_expr (TREE_VALUE (decl), args, complain, in_decl);
17971 tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
17972 in_decl, NULL);
17973 if (TREE_PURPOSE (decl) == low_bound
17974 && TREE_VALUE (decl) == length
17975 && TREE_CHAIN (decl) == chain)
17976 return decl;
17977 tree ret = tree_cons (low_bound, length, chain);
17978 OMP_CLAUSE_DOACROSS_SINK_NEGATIVE (ret)
17979 = OMP_CLAUSE_DOACROSS_SINK_NEGATIVE (decl);
17980 return ret;
17982 tree ret = tsubst_expr (decl, args, complain, in_decl);
17983 /* Undo convert_from_reference tsubst_expr could have called. */
17984 if (decl
17985 && REFERENCE_REF_P (ret)
17986 && !REFERENCE_REF_P (decl))
17987 ret = TREE_OPERAND (ret, 0);
17988 return ret;
17991 /* Like tsubst_copy, but specifically for OpenMP clauses. */
17993 static tree
17994 tsubst_omp_clauses (tree clauses, enum c_omp_region_type ort,
17995 tree args, tsubst_flags_t complain, tree in_decl)
17997 tree new_clauses = NULL_TREE, nc, oc;
17998 tree linear_no_step = NULL_TREE;
17999 tree iterator_cache[2] = { NULL_TREE, NULL_TREE };
18001 for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
18003 nc = copy_node (oc);
18004 OMP_CLAUSE_CHAIN (nc) = new_clauses;
18005 new_clauses = nc;
18007 switch (OMP_CLAUSE_CODE (nc))
18009 case OMP_CLAUSE_LASTPRIVATE:
18010 if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
18012 OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
18013 tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args,
18014 complain, in_decl);
18015 OMP_CLAUSE_LASTPRIVATE_STMT (nc)
18016 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
18018 /* FALLTHRU */
18019 case OMP_CLAUSE_PRIVATE:
18020 case OMP_CLAUSE_SHARED:
18021 case OMP_CLAUSE_FIRSTPRIVATE:
18022 case OMP_CLAUSE_COPYIN:
18023 case OMP_CLAUSE_COPYPRIVATE:
18024 case OMP_CLAUSE_UNIFORM:
18025 case OMP_CLAUSE_DEPEND:
18026 case OMP_CLAUSE_DOACROSS:
18027 case OMP_CLAUSE_AFFINITY:
18028 case OMP_CLAUSE_FROM:
18029 case OMP_CLAUSE_TO:
18030 case OMP_CLAUSE_MAP:
18031 case OMP_CLAUSE__CACHE_:
18032 case OMP_CLAUSE_NONTEMPORAL:
18033 case OMP_CLAUSE_USE_DEVICE_PTR:
18034 case OMP_CLAUSE_USE_DEVICE_ADDR:
18035 case OMP_CLAUSE_IS_DEVICE_PTR:
18036 case OMP_CLAUSE_HAS_DEVICE_ADDR:
18037 case OMP_CLAUSE_INCLUSIVE:
18038 case OMP_CLAUSE_EXCLUSIVE:
18039 OMP_CLAUSE_DECL (nc)
18040 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
18041 in_decl, iterator_cache);
18042 break;
18043 case OMP_CLAUSE_NUM_TEAMS:
18044 if (OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (oc))
18045 OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (nc)
18046 = tsubst_expr (OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (oc), args,
18047 complain, in_decl);
18048 /* FALLTHRU */
18049 case OMP_CLAUSE_TILE:
18050 case OMP_CLAUSE_IF:
18051 case OMP_CLAUSE_NUM_THREADS:
18052 case OMP_CLAUSE_SCHEDULE:
18053 case OMP_CLAUSE_COLLAPSE:
18054 case OMP_CLAUSE_FINAL:
18055 case OMP_CLAUSE_DEVICE:
18056 case OMP_CLAUSE_DIST_SCHEDULE:
18057 case OMP_CLAUSE_THREAD_LIMIT:
18058 case OMP_CLAUSE_SAFELEN:
18059 case OMP_CLAUSE_SIMDLEN:
18060 case OMP_CLAUSE_NUM_TASKS:
18061 case OMP_CLAUSE_GRAINSIZE:
18062 case OMP_CLAUSE_PRIORITY:
18063 case OMP_CLAUSE_ORDERED:
18064 case OMP_CLAUSE_HINT:
18065 case OMP_CLAUSE_FILTER:
18066 case OMP_CLAUSE_NUM_GANGS:
18067 case OMP_CLAUSE_NUM_WORKERS:
18068 case OMP_CLAUSE_VECTOR_LENGTH:
18069 case OMP_CLAUSE_WORKER:
18070 case OMP_CLAUSE_VECTOR:
18071 case OMP_CLAUSE_ASYNC:
18072 case OMP_CLAUSE_WAIT:
18073 case OMP_CLAUSE_DETACH:
18074 OMP_CLAUSE_OPERAND (nc, 0)
18075 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, in_decl);
18076 break;
18077 case OMP_CLAUSE_REDUCTION:
18078 case OMP_CLAUSE_IN_REDUCTION:
18079 case OMP_CLAUSE_TASK_REDUCTION:
18080 if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
18082 tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
18083 if (TREE_CODE (placeholder) == SCOPE_REF)
18085 tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
18086 complain, in_decl);
18087 OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
18088 = build_qualified_name (NULL_TREE, scope,
18089 TREE_OPERAND (placeholder, 1),
18090 false);
18092 else
18093 gcc_assert (identifier_p (placeholder));
18095 OMP_CLAUSE_DECL (nc)
18096 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
18097 in_decl, NULL);
18098 break;
18099 case OMP_CLAUSE_GANG:
18100 case OMP_CLAUSE_ALIGNED:
18101 OMP_CLAUSE_DECL (nc)
18102 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
18103 in_decl, NULL);
18104 OMP_CLAUSE_OPERAND (nc, 1)
18105 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain, in_decl);
18106 break;
18107 case OMP_CLAUSE_ALLOCATE:
18108 OMP_CLAUSE_DECL (nc)
18109 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
18110 in_decl, NULL);
18111 OMP_CLAUSE_OPERAND (nc, 1)
18112 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain, in_decl);
18113 OMP_CLAUSE_OPERAND (nc, 2)
18114 = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 2), args, complain, in_decl);
18115 break;
18116 case OMP_CLAUSE_LINEAR:
18117 OMP_CLAUSE_DECL (nc)
18118 = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
18119 in_decl, NULL);
18120 if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
18122 gcc_assert (!linear_no_step);
18123 linear_no_step = nc;
18125 else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
18126 OMP_CLAUSE_LINEAR_STEP (nc)
18127 = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
18128 complain, in_decl, NULL);
18129 else
18130 OMP_CLAUSE_LINEAR_STEP (nc)
18131 = tsubst_expr (OMP_CLAUSE_LINEAR_STEP (oc), args,
18132 complain, in_decl);
18133 break;
18134 case OMP_CLAUSE_NOWAIT:
18135 case OMP_CLAUSE_DEFAULT:
18136 case OMP_CLAUSE_UNTIED:
18137 case OMP_CLAUSE_MERGEABLE:
18138 case OMP_CLAUSE_INBRANCH:
18139 case OMP_CLAUSE_NOTINBRANCH:
18140 case OMP_CLAUSE_PROC_BIND:
18141 case OMP_CLAUSE_FOR:
18142 case OMP_CLAUSE_PARALLEL:
18143 case OMP_CLAUSE_SECTIONS:
18144 case OMP_CLAUSE_TASKGROUP:
18145 case OMP_CLAUSE_NOGROUP:
18146 case OMP_CLAUSE_THREADS:
18147 case OMP_CLAUSE_SIMD:
18148 case OMP_CLAUSE_DEFAULTMAP:
18149 case OMP_CLAUSE_ORDER:
18150 case OMP_CLAUSE_BIND:
18151 case OMP_CLAUSE_INDEPENDENT:
18152 case OMP_CLAUSE_AUTO:
18153 case OMP_CLAUSE_SEQ:
18154 case OMP_CLAUSE_IF_PRESENT:
18155 case OMP_CLAUSE_FINALIZE:
18156 case OMP_CLAUSE_NOHOST:
18157 break;
18158 default:
18159 gcc_unreachable ();
18161 if ((ort & C_ORT_OMP_DECLARE_SIMD) == C_ORT_OMP)
18162 switch (OMP_CLAUSE_CODE (nc))
18164 case OMP_CLAUSE_SHARED:
18165 case OMP_CLAUSE_PRIVATE:
18166 case OMP_CLAUSE_FIRSTPRIVATE:
18167 case OMP_CLAUSE_LASTPRIVATE:
18168 case OMP_CLAUSE_COPYPRIVATE:
18169 case OMP_CLAUSE_LINEAR:
18170 case OMP_CLAUSE_REDUCTION:
18171 case OMP_CLAUSE_IN_REDUCTION:
18172 case OMP_CLAUSE_TASK_REDUCTION:
18173 case OMP_CLAUSE_USE_DEVICE_PTR:
18174 case OMP_CLAUSE_USE_DEVICE_ADDR:
18175 case OMP_CLAUSE_IS_DEVICE_PTR:
18176 case OMP_CLAUSE_HAS_DEVICE_ADDR:
18177 case OMP_CLAUSE_INCLUSIVE:
18178 case OMP_CLAUSE_EXCLUSIVE:
18179 case OMP_CLAUSE_ALLOCATE:
18180 /* tsubst_expr on SCOPE_REF results in returning
18181 finish_non_static_data_member result. Undo that here. */
18182 if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
18183 && (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
18184 == IDENTIFIER_NODE))
18186 tree t = OMP_CLAUSE_DECL (nc);
18187 tree v = t;
18188 while (v)
18189 switch (TREE_CODE (v))
18191 case COMPONENT_REF:
18192 case MEM_REF:
18193 case INDIRECT_REF:
18194 CASE_CONVERT:
18195 case POINTER_PLUS_EXPR:
18196 v = TREE_OPERAND (v, 0);
18197 continue;
18198 case PARM_DECL:
18199 if (DECL_CONTEXT (v) == current_function_decl
18200 && DECL_ARTIFICIAL (v)
18201 && DECL_NAME (v) == this_identifier)
18202 OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
18203 /* FALLTHRU */
18204 default:
18205 v = NULL_TREE;
18206 break;
18209 else if (VAR_P (OMP_CLAUSE_DECL (oc))
18210 && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
18211 && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
18212 && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
18213 && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
18215 tree decl = OMP_CLAUSE_DECL (nc);
18216 if (VAR_P (decl))
18218 retrofit_lang_decl (decl);
18219 DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
18222 break;
18223 default:
18224 break;
18228 new_clauses = nreverse (new_clauses);
18229 if (ort != C_ORT_OMP_DECLARE_SIMD)
18231 new_clauses = finish_omp_clauses (new_clauses, ort);
18232 if (linear_no_step)
18233 for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
18234 if (nc == linear_no_step)
18236 OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
18237 break;
18240 return new_clauses;
18243 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes. */
18245 static tree
18246 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
18247 tree in_decl)
18249 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
18251 tree purpose, value, chain;
18253 if (t == NULL)
18254 return t;
18256 if (TREE_CODE (t) != TREE_LIST)
18257 return tsubst_copy_and_build (t, args, complain, in_decl);
18259 if (t == void_list_node)
18260 return t;
18262 purpose = TREE_PURPOSE (t);
18263 if (purpose)
18264 purpose = RECUR (purpose);
18265 value = TREE_VALUE (t);
18266 if (value)
18268 if (TREE_CODE (value) != LABEL_DECL)
18269 value = RECUR (value);
18270 else
18272 value = lookup_label (DECL_NAME (value));
18273 gcc_assert (TREE_CODE (value) == LABEL_DECL);
18274 TREE_USED (value) = 1;
18277 chain = TREE_CHAIN (t);
18278 if (chain && chain != void_type_node)
18279 chain = RECUR (chain);
18280 return tree_cons (purpose, value, chain);
18281 #undef RECUR
18284 /* Used to temporarily communicate the list of #pragma omp parallel
18285 clauses to #pragma omp for instantiation if they are combined
18286 together. */
18288 static tree *omp_parallel_combined_clauses;
18290 static tree tsubst_decomp_names (tree, tree, tree, tsubst_flags_t, tree,
18291 tree *, unsigned int *);
18293 /* Substitute one OMP_FOR iterator. */
18295 static bool
18296 tsubst_omp_for_iterator (tree t, int i, tree declv, tree &orig_declv,
18297 tree initv, tree condv, tree incrv, tree *clauses,
18298 tree args, tsubst_flags_t complain, tree in_decl)
18300 #define RECUR(NODE) \
18301 tsubst_expr ((NODE), args, complain, in_decl)
18302 tree decl, init, cond = NULL_TREE, incr = NULL_TREE;
18303 bool ret = false;
18305 init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
18306 gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
18308 decl = TREE_OPERAND (init, 0);
18309 init = TREE_OPERAND (init, 1);
18310 tree decl_expr = NULL_TREE;
18311 bool range_for = TREE_VEC_ELT (OMP_FOR_COND (t), i) == global_namespace;
18312 if (range_for)
18314 bool decomp = false;
18315 if (decl != error_mark_node && DECL_HAS_VALUE_EXPR_P (decl))
18317 tree v = DECL_VALUE_EXPR (decl);
18318 if (TREE_CODE (v) == ARRAY_REF
18319 && VAR_P (TREE_OPERAND (v, 0))
18320 && DECL_DECOMPOSITION_P (TREE_OPERAND (v, 0)))
18322 tree decomp_first = NULL_TREE;
18323 unsigned decomp_cnt = 0;
18324 tree d = tsubst_decl (TREE_OPERAND (v, 0), args, complain);
18325 maybe_push_decl (d);
18326 d = tsubst_decomp_names (d, TREE_OPERAND (v, 0), args, complain,
18327 in_decl, &decomp_first, &decomp_cnt);
18328 decomp = true;
18329 if (d == error_mark_node)
18330 decl = error_mark_node;
18331 else
18332 for (unsigned int i = 0; i < decomp_cnt; i++)
18334 if (!DECL_HAS_VALUE_EXPR_P (decomp_first))
18336 tree v = build_nt (ARRAY_REF, d,
18337 size_int (decomp_cnt - i - 1),
18338 NULL_TREE, NULL_TREE);
18339 SET_DECL_VALUE_EXPR (decomp_first, v);
18340 DECL_HAS_VALUE_EXPR_P (decomp_first) = 1;
18342 fit_decomposition_lang_decl (decomp_first, d);
18343 decomp_first = DECL_CHAIN (decomp_first);
18347 decl = tsubst_decl (decl, args, complain);
18348 if (!decomp)
18349 maybe_push_decl (decl);
18351 else if (init && TREE_CODE (init) == DECL_EXPR)
18353 /* We need to jump through some hoops to handle declarations in the
18354 init-statement, since we might need to handle auto deduction,
18355 but we need to keep control of initialization. */
18356 decl_expr = init;
18357 init = DECL_INITIAL (DECL_EXPR_DECL (init));
18358 decl = tsubst_decl (decl, args, complain);
18360 else
18362 if (TREE_CODE (decl) == SCOPE_REF)
18364 decl = RECUR (decl);
18365 if (TREE_CODE (decl) == COMPONENT_REF)
18367 tree v = decl;
18368 while (v)
18369 switch (TREE_CODE (v))
18371 case COMPONENT_REF:
18372 case MEM_REF:
18373 case INDIRECT_REF:
18374 CASE_CONVERT:
18375 case POINTER_PLUS_EXPR:
18376 v = TREE_OPERAND (v, 0);
18377 continue;
18378 case PARM_DECL:
18379 if (DECL_CONTEXT (v) == current_function_decl
18380 && DECL_ARTIFICIAL (v)
18381 && DECL_NAME (v) == this_identifier)
18383 decl = TREE_OPERAND (decl, 1);
18384 decl = omp_privatize_field (decl, false);
18386 /* FALLTHRU */
18387 default:
18388 v = NULL_TREE;
18389 break;
18393 else
18394 decl = RECUR (decl);
18396 if (init && TREE_CODE (init) == TREE_VEC)
18398 init = copy_node (init);
18399 TREE_VEC_ELT (init, 0)
18400 = tsubst_decl (TREE_VEC_ELT (init, 0), args, complain);
18401 TREE_VEC_ELT (init, 1) = RECUR (TREE_VEC_ELT (init, 1));
18402 TREE_VEC_ELT (init, 2) = RECUR (TREE_VEC_ELT (init, 2));
18404 else
18405 init = RECUR (init);
18407 if (orig_declv && OMP_FOR_ORIG_DECLS (t))
18409 tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
18410 if (TREE_CODE (o) == TREE_LIST)
18411 TREE_VEC_ELT (orig_declv, i)
18412 = tree_cons (RECUR (TREE_PURPOSE (o)),
18413 RECUR (TREE_VALUE (o)),
18414 NULL_TREE);
18415 else
18416 TREE_VEC_ELT (orig_declv, i) = RECUR (o);
18419 if (range_for)
18421 tree this_pre_body = NULL_TREE;
18422 tree orig_init = NULL_TREE;
18423 tree orig_decl = NULL_TREE;
18424 cp_convert_omp_range_for (this_pre_body, NULL, decl, orig_decl, init,
18425 orig_init, cond, incr);
18426 if (orig_decl)
18428 if (orig_declv == NULL_TREE)
18429 orig_declv = copy_node (declv);
18430 TREE_VEC_ELT (orig_declv, i) = orig_decl;
18431 ret = true;
18433 else if (orig_declv)
18434 TREE_VEC_ELT (orig_declv, i) = decl;
18437 tree auto_node = type_uses_auto (TREE_TYPE (decl));
18438 if (!range_for && auto_node && init)
18439 TREE_TYPE (decl)
18440 = do_auto_deduction (TREE_TYPE (decl), init, auto_node, complain);
18442 gcc_assert (!type_dependent_expression_p (decl));
18444 if (!CLASS_TYPE_P (TREE_TYPE (decl)) || range_for)
18446 if (decl_expr)
18448 /* Declare the variable, but don't let that initialize it. */
18449 tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
18450 DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
18451 RECUR (decl_expr);
18452 DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
18455 if (!range_for)
18457 cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
18458 if (COMPARISON_CLASS_P (cond)
18459 && TREE_CODE (TREE_OPERAND (cond, 1)) == TREE_VEC)
18461 tree lhs = RECUR (TREE_OPERAND (cond, 0));
18462 tree rhs = copy_node (TREE_OPERAND (cond, 1));
18463 TREE_VEC_ELT (rhs, 0)
18464 = tsubst_decl (TREE_VEC_ELT (rhs, 0), args, complain);
18465 TREE_VEC_ELT (rhs, 1) = RECUR (TREE_VEC_ELT (rhs, 1));
18466 TREE_VEC_ELT (rhs, 2) = RECUR (TREE_VEC_ELT (rhs, 2));
18467 cond = build2 (TREE_CODE (cond), TREE_TYPE (cond),
18468 lhs, rhs);
18470 else
18471 cond = RECUR (cond);
18472 incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
18473 if (TREE_CODE (incr) == MODIFY_EXPR)
18475 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18476 tree rhs = RECUR (TREE_OPERAND (incr, 1));
18477 incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
18478 NOP_EXPR, rhs, NULL_TREE, complain);
18480 else
18481 incr = RECUR (incr);
18482 if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
18483 TREE_VEC_ELT (orig_declv, i) = decl;
18485 TREE_VEC_ELT (declv, i) = decl;
18486 TREE_VEC_ELT (initv, i) = init;
18487 TREE_VEC_ELT (condv, i) = cond;
18488 TREE_VEC_ELT (incrv, i) = incr;
18489 return ret;
18492 if (decl_expr)
18494 /* Declare and initialize the variable. */
18495 RECUR (decl_expr);
18496 init = NULL_TREE;
18498 else if (init)
18500 tree *pc;
18501 int j;
18502 for (j = ((omp_parallel_combined_clauses == NULL
18503 || TREE_CODE (t) == OMP_LOOP) ? 1 : 0); j < 2; j++)
18505 for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
18507 if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
18508 && OMP_CLAUSE_DECL (*pc) == decl)
18509 break;
18510 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
18511 && OMP_CLAUSE_DECL (*pc) == decl)
18513 if (j)
18514 break;
18515 /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES. */
18516 tree c = *pc;
18517 *pc = OMP_CLAUSE_CHAIN (c);
18518 OMP_CLAUSE_CHAIN (c) = *clauses;
18519 *clauses = c;
18521 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
18522 && OMP_CLAUSE_DECL (*pc) == decl)
18524 error ("iteration variable %qD should not be firstprivate",
18525 decl);
18526 *pc = OMP_CLAUSE_CHAIN (*pc);
18528 else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
18529 && OMP_CLAUSE_DECL (*pc) == decl)
18531 error ("iteration variable %qD should not be reduction",
18532 decl);
18533 *pc = OMP_CLAUSE_CHAIN (*pc);
18535 else
18536 pc = &OMP_CLAUSE_CHAIN (*pc);
18538 if (*pc)
18539 break;
18541 if (*pc == NULL_TREE)
18543 tree c = build_omp_clause (input_location,
18544 TREE_CODE (t) == OMP_LOOP
18545 ? OMP_CLAUSE_LASTPRIVATE
18546 : OMP_CLAUSE_PRIVATE);
18547 OMP_CLAUSE_DECL (c) = decl;
18548 c = finish_omp_clauses (c, C_ORT_OMP);
18549 if (c)
18551 OMP_CLAUSE_CHAIN (c) = *clauses;
18552 *clauses = c;
18556 cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
18557 if (COMPARISON_CLASS_P (cond))
18559 tree op0 = RECUR (TREE_OPERAND (cond, 0));
18560 tree op1 = RECUR (TREE_OPERAND (cond, 1));
18561 cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
18563 else
18564 cond = RECUR (cond);
18565 incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
18566 switch (TREE_CODE (incr))
18568 case PREINCREMENT_EXPR:
18569 case PREDECREMENT_EXPR:
18570 case POSTINCREMENT_EXPR:
18571 case POSTDECREMENT_EXPR:
18572 incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
18573 RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
18574 break;
18575 case MODIFY_EXPR:
18576 if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
18577 || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
18579 tree rhs = TREE_OPERAND (incr, 1);
18580 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18581 tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
18582 tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
18583 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18584 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
18585 rhs0, rhs1));
18587 else
18588 incr = RECUR (incr);
18589 break;
18590 case MODOP_EXPR:
18591 if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
18592 || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
18594 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18595 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18596 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
18597 TREE_TYPE (decl), lhs,
18598 RECUR (TREE_OPERAND (incr, 2))));
18600 else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
18601 && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
18602 || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
18604 tree rhs = TREE_OPERAND (incr, 2);
18605 tree lhs = RECUR (TREE_OPERAND (incr, 0));
18606 tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
18607 tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
18608 incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
18609 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
18610 rhs0, rhs1));
18612 else
18613 incr = RECUR (incr);
18614 break;
18615 default:
18616 incr = RECUR (incr);
18617 break;
18620 if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
18621 TREE_VEC_ELT (orig_declv, i) = decl;
18622 TREE_VEC_ELT (declv, i) = decl;
18623 TREE_VEC_ELT (initv, i) = init;
18624 TREE_VEC_ELT (condv, i) = cond;
18625 TREE_VEC_ELT (incrv, i) = incr;
18626 return false;
18627 #undef RECUR
18630 /* Helper function of tsubst_expr, find OMP_TEAMS inside
18631 of OMP_TARGET's body. */
18633 static tree
18634 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
18636 *walk_subtrees = 0;
18637 switch (TREE_CODE (*tp))
18639 case OMP_TEAMS:
18640 return *tp;
18641 case BIND_EXPR:
18642 case STATEMENT_LIST:
18643 *walk_subtrees = 1;
18644 break;
18645 default:
18646 break;
18648 return NULL_TREE;
18651 /* Helper function for tsubst_expr. For decomposition declaration
18652 artificial base DECL, which is tsubsted PATTERN_DECL, tsubst
18653 also the corresponding decls representing the identifiers
18654 of the decomposition declaration. Return DECL if successful
18655 or error_mark_node otherwise, set *FIRST to the first decl
18656 in the list chained through DECL_CHAIN and *CNT to the number
18657 of such decls. */
18659 static tree
18660 tsubst_decomp_names (tree decl, tree pattern_decl, tree args,
18661 tsubst_flags_t complain, tree in_decl, tree *first,
18662 unsigned int *cnt)
18664 tree decl2, decl3, prev = decl;
18665 *cnt = 0;
18666 gcc_assert (DECL_NAME (decl) == NULL_TREE);
18667 for (decl2 = DECL_CHAIN (pattern_decl);
18668 decl2
18669 && VAR_P (decl2)
18670 && DECL_DECOMPOSITION_P (decl2)
18671 && DECL_NAME (decl2);
18672 decl2 = DECL_CHAIN (decl2))
18674 if (TREE_TYPE (decl2) == error_mark_node && *cnt == 0)
18676 gcc_assert (errorcount);
18677 return error_mark_node;
18679 (*cnt)++;
18680 gcc_assert (DECL_DECOMP_BASE (decl2) == pattern_decl);
18681 gcc_assert (DECL_HAS_VALUE_EXPR_P (decl2));
18682 tree v = DECL_VALUE_EXPR (decl2);
18683 DECL_HAS_VALUE_EXPR_P (decl2) = 0;
18684 SET_DECL_VALUE_EXPR (decl2, NULL_TREE);
18685 decl3 = tsubst (decl2, args, complain, in_decl);
18686 SET_DECL_VALUE_EXPR (decl2, v);
18687 DECL_HAS_VALUE_EXPR_P (decl2) = 1;
18688 if (VAR_P (decl3))
18689 DECL_TEMPLATE_INSTANTIATED (decl3) = 1;
18690 else
18692 gcc_assert (errorcount);
18693 decl = error_mark_node;
18694 continue;
18696 maybe_push_decl (decl3);
18697 if (error_operand_p (decl3))
18698 decl = error_mark_node;
18699 else if (decl != error_mark_node
18700 && DECL_CHAIN (decl3) != prev
18701 && decl != prev)
18703 gcc_assert (errorcount);
18704 decl = error_mark_node;
18706 else
18707 prev = decl3;
18709 *first = prev;
18710 return decl;
18713 /* Return the proper local_specialization for init-capture pack DECL. */
18715 static tree
18716 lookup_init_capture_pack (tree decl)
18718 /* We handle normal pack captures by forwarding to the specialization of the
18719 captured parameter. We can't do that for pack init-captures; we need them
18720 to have their own local_specialization. We created the individual
18721 VAR_DECLs (if any) under build_capture_proxy, and we need to collect them
18722 when we process the DECL_EXPR for the pack init-capture in the template.
18723 So, how do we find them? We don't know the capture proxy pack when
18724 building the individual resulting proxies, and we don't know the
18725 individual proxies when instantiating the pack. What we have in common is
18726 the FIELD_DECL.
18728 So...when we instantiate the FIELD_DECL, we stick the result in
18729 local_specializations. Then at the DECL_EXPR we look up that result, see
18730 how many elements it has, synthesize the names, and look them up. */
18732 tree cname = DECL_NAME (decl);
18733 tree val = DECL_VALUE_EXPR (decl);
18734 tree field = TREE_OPERAND (val, 1);
18735 gcc_assert (TREE_CODE (field) == FIELD_DECL);
18736 tree fpack = retrieve_local_specialization (field);
18737 if (fpack == error_mark_node)
18738 return error_mark_node;
18740 int len = 1;
18741 tree vec = NULL_TREE;
18742 tree r = NULL_TREE;
18743 if (TREE_CODE (fpack) == TREE_VEC)
18745 len = TREE_VEC_LENGTH (fpack);
18746 vec = make_tree_vec (len);
18747 r = make_node (NONTYPE_ARGUMENT_PACK);
18748 ARGUMENT_PACK_ARGS (r) = vec;
18750 for (int i = 0; i < len; ++i)
18752 tree ename = vec ? make_ith_pack_parameter_name (cname, i) : cname;
18753 tree elt = lookup_name (ename);
18754 if (vec)
18755 TREE_VEC_ELT (vec, i) = elt;
18756 else
18757 r = elt;
18759 return r;
18762 /* T is an operand of a template tree being substituted. Return whether
18763 T is dependent such that we should suppress some warnings that would
18764 make sense if the substituted expression were written directly, like
18765 template <int I> bool f() { return I == 2; }
18766 We don't want to warn when instantiating f that comparing two constants
18767 always has the same value.
18769 This is a more limited concept of dependence than instantiation-dependent;
18770 here we don't care whether substitution could fail. */
18772 static bool
18773 dependent_operand_p (tree t)
18775 while (TREE_CODE (t) == IMPLICIT_CONV_EXPR)
18776 t = TREE_OPERAND (t, 0);
18777 ++processing_template_decl;
18778 bool r = (potential_constant_expression (t)
18779 ? value_dependent_expression_p (t)
18780 : type_dependent_expression_p (t));
18781 --processing_template_decl;
18782 return r;
18785 /* Like tsubst_copy for expressions, etc. but also does semantic
18786 processing. */
18788 tree
18789 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
18791 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
18792 #define RECUR(NODE) \
18793 tsubst_expr ((NODE), args, complain, in_decl)
18795 tree stmt, tmp;
18796 tree r;
18797 location_t loc;
18799 if (t == NULL_TREE || t == error_mark_node)
18800 return t;
18802 loc = input_location;
18803 if (location_t eloc = cp_expr_location (t))
18804 input_location = eloc;
18805 if (STATEMENT_CODE_P (TREE_CODE (t)))
18806 current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
18808 switch (TREE_CODE (t))
18810 case STATEMENT_LIST:
18812 for (tree stmt : tsi_range (t))
18813 RECUR (stmt);
18814 break;
18817 case CTOR_INITIALIZER:
18818 finish_mem_initializers (tsubst_initializer_list
18819 (TREE_OPERAND (t, 0), args));
18820 break;
18822 case RETURN_EXPR:
18823 finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
18824 break;
18826 case CO_RETURN_EXPR:
18827 finish_co_return_stmt (input_location, RECUR (TREE_OPERAND (t, 0)));
18828 break;
18830 case CO_YIELD_EXPR:
18831 stmt = finish_co_yield_expr (input_location,
18832 RECUR (TREE_OPERAND (t, 0)));
18833 RETURN (stmt);
18835 case CO_AWAIT_EXPR:
18836 stmt = finish_co_await_expr (input_location,
18837 RECUR (TREE_OPERAND (t, 0)));
18838 RETURN (stmt);
18840 case EXPR_STMT:
18841 tmp = RECUR (EXPR_STMT_EXPR (t));
18842 if (EXPR_STMT_STMT_EXPR_RESULT (t))
18843 finish_stmt_expr_expr (tmp, cur_stmt_expr);
18844 else
18845 finish_expr_stmt (tmp);
18846 break;
18848 case USING_STMT:
18849 finish_using_directive (USING_STMT_NAMESPACE (t), /*attribs=*/NULL_TREE);
18850 break;
18852 case PRECONDITION_STMT:
18853 case POSTCONDITION_STMT:
18854 gcc_unreachable ();
18856 case ASSERTION_STMT:
18858 r = tsubst_contract (NULL_TREE, t, args, complain, in_decl);
18859 if (r != error_mark_node)
18860 add_stmt (r);
18861 RETURN (r);
18863 break;
18865 case DECL_EXPR:
18867 tree decl, pattern_decl;
18868 tree init;
18870 pattern_decl = decl = DECL_EXPR_DECL (t);
18871 if (TREE_CODE (decl) == LABEL_DECL)
18872 finish_label_decl (DECL_NAME (decl));
18873 else if (TREE_CODE (decl) == USING_DECL)
18875 tree scope = USING_DECL_SCOPE (decl);
18876 if (DECL_DEPENDENT_P (decl))
18878 scope = tsubst (scope, args, complain, in_decl);
18879 if (!MAYBE_CLASS_TYPE_P (scope)
18880 && TREE_CODE (scope) != ENUMERAL_TYPE)
18882 if (complain & tf_error)
18883 error_at (DECL_SOURCE_LOCATION (decl), "%qT is not a "
18884 "class, namespace, or enumeration", scope);
18885 return error_mark_node;
18887 finish_nonmember_using_decl (scope, DECL_NAME (decl));
18889 else
18891 /* This is a non-dependent using-decl, and we'll have
18892 used the names it found during template parsing. We do
18893 not want to do the lookup again, because we might not
18894 find the things we found then. */
18895 gcc_checking_assert (scope == tsubst (scope, args,
18896 complain, in_decl));
18897 /* We still need to push the bindings so that we can look up
18898 this name later. */
18899 push_using_decl_bindings (DECL_NAME (decl),
18900 USING_DECL_DECLS (decl));
18903 else if (is_capture_proxy (decl)
18904 && !DECL_TEMPLATE_INSTANTIATION (current_function_decl))
18906 /* We're in tsubst_lambda_expr, we've already inserted a new
18907 capture proxy, so look it up and register it. */
18908 tree inst;
18909 if (!DECL_PACK_P (decl))
18911 inst = lookup_name (DECL_NAME (decl), LOOK_where::BLOCK,
18912 LOOK_want::HIDDEN_LAMBDA);
18913 gcc_assert (inst != decl && is_capture_proxy (inst));
18915 else if (is_normal_capture_proxy (decl))
18917 inst = (retrieve_local_specialization
18918 (DECL_CAPTURED_VARIABLE (decl)));
18919 gcc_assert (TREE_CODE (inst) == NONTYPE_ARGUMENT_PACK
18920 || DECL_PACK_P (inst));
18922 else
18923 inst = lookup_init_capture_pack (decl);
18925 register_local_specialization (inst, decl);
18926 break;
18928 else if (DECL_PRETTY_FUNCTION_P (decl))
18929 decl = make_fname_decl (DECL_SOURCE_LOCATION (decl),
18930 DECL_NAME (decl),
18931 true/*DECL_PRETTY_FUNCTION_P (decl)*/);
18932 else if (DECL_IMPLICIT_TYPEDEF_P (decl)
18933 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
18934 /* Don't copy the old closure; we'll create a new one in
18935 tsubst_lambda_expr. */
18936 break;
18937 else
18939 init = DECL_INITIAL (decl);
18940 decl = tsubst (decl, args, complain, in_decl);
18941 if (decl != error_mark_node)
18943 /* By marking the declaration as instantiated, we avoid
18944 trying to instantiate it. Since instantiate_decl can't
18945 handle local variables, and since we've already done
18946 all that needs to be done, that's the right thing to
18947 do. */
18948 if (VAR_P (decl))
18949 DECL_TEMPLATE_INSTANTIATED (decl) = 1;
18950 if (VAR_P (decl) && !DECL_NAME (decl)
18951 && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
18952 /* Anonymous aggregates are a special case. */
18953 finish_anon_union (decl);
18954 else if (is_capture_proxy (DECL_EXPR_DECL (t)))
18956 DECL_CONTEXT (decl) = current_function_decl;
18957 if (DECL_NAME (decl) == this_identifier)
18959 tree lam = DECL_CONTEXT (current_function_decl);
18960 lam = CLASSTYPE_LAMBDA_EXPR (lam);
18961 LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
18963 insert_capture_proxy (decl);
18965 else if (DECL_IMPLICIT_TYPEDEF_P (t))
18966 /* We already did a pushtag. */;
18967 else if (VAR_OR_FUNCTION_DECL_P (decl)
18968 && DECL_LOCAL_DECL_P (decl))
18970 if (TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL)
18971 DECL_CONTEXT (decl) = NULL_TREE;
18972 decl = pushdecl (decl);
18973 if (TREE_CODE (decl) == FUNCTION_DECL
18974 && DECL_OMP_DECLARE_REDUCTION_P (decl)
18975 && cp_check_omp_declare_reduction (decl))
18976 instantiate_body (pattern_decl, args, decl, true);
18978 else
18980 bool const_init = false;
18981 unsigned int cnt = 0;
18982 tree first = NULL_TREE, ndecl = error_mark_node;
18983 tree asmspec_tree = NULL_TREE;
18984 maybe_push_decl (decl);
18986 if (VAR_P (decl)
18987 && DECL_LANG_SPECIFIC (decl)
18988 && DECL_OMP_PRIVATIZED_MEMBER (decl))
18989 break;
18991 if (VAR_P (decl)
18992 && DECL_DECOMPOSITION_P (decl)
18993 && TREE_TYPE (pattern_decl) != error_mark_node)
18994 ndecl = tsubst_decomp_names (decl, pattern_decl, args,
18995 complain, in_decl, &first,
18996 &cnt);
18998 init = tsubst_init (init, decl, args, complain, in_decl);
19000 if (VAR_P (decl))
19001 const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
19002 (pattern_decl));
19004 if (ndecl != error_mark_node)
19005 cp_maybe_mangle_decomp (ndecl, first, cnt);
19007 /* In a non-template function, VLA type declarations are
19008 handled in grokdeclarator; for templates, handle them
19009 now. */
19010 predeclare_vla (decl);
19012 if (VAR_P (decl) && DECL_HARD_REGISTER (pattern_decl))
19014 tree id = DECL_ASSEMBLER_NAME (pattern_decl);
19015 const char *asmspec = IDENTIFIER_POINTER (id);
19016 gcc_assert (asmspec[0] == '*');
19017 asmspec_tree
19018 = build_string (IDENTIFIER_LENGTH (id) - 1,
19019 asmspec + 1);
19020 TREE_TYPE (asmspec_tree) = char_array_type_node;
19023 cp_finish_decl (decl, init, const_init, asmspec_tree, 0);
19025 if (ndecl != error_mark_node)
19026 cp_finish_decomp (ndecl, first, cnt);
19031 break;
19034 case FOR_STMT:
19035 stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
19036 RECUR (FOR_INIT_STMT (t));
19037 finish_init_stmt (stmt);
19038 tmp = RECUR (FOR_COND (t));
19039 finish_for_cond (tmp, stmt, false, 0);
19040 tmp = RECUR (FOR_EXPR (t));
19041 finish_for_expr (tmp, stmt);
19043 bool prev = note_iteration_stmt_body_start ();
19044 RECUR (FOR_BODY (t));
19045 note_iteration_stmt_body_end (prev);
19047 finish_for_stmt (stmt);
19048 break;
19050 case RANGE_FOR_STMT:
19052 /* Construct another range_for, if this is not a final
19053 substitution (for inside a generic lambda of a
19054 template). Otherwise convert to a regular for. */
19055 tree decl, expr;
19056 stmt = (processing_template_decl
19057 ? begin_range_for_stmt (NULL_TREE, NULL_TREE)
19058 : begin_for_stmt (NULL_TREE, NULL_TREE));
19059 RECUR (RANGE_FOR_INIT_STMT (t));
19060 decl = RANGE_FOR_DECL (t);
19061 decl = tsubst (decl, args, complain, in_decl);
19062 maybe_push_decl (decl);
19063 expr = RECUR (RANGE_FOR_EXPR (t));
19065 tree decomp_first = NULL_TREE;
19066 unsigned decomp_cnt = 0;
19067 if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
19068 decl = tsubst_decomp_names (decl, RANGE_FOR_DECL (t), args,
19069 complain, in_decl,
19070 &decomp_first, &decomp_cnt);
19072 if (processing_template_decl)
19074 RANGE_FOR_IVDEP (stmt) = RANGE_FOR_IVDEP (t);
19075 RANGE_FOR_UNROLL (stmt) = RANGE_FOR_UNROLL (t);
19076 finish_range_for_decl (stmt, decl, expr);
19077 if (decomp_first && decl != error_mark_node)
19078 cp_finish_decomp (decl, decomp_first, decomp_cnt);
19080 else
19082 unsigned short unroll = (RANGE_FOR_UNROLL (t)
19083 ? tree_to_uhwi (RANGE_FOR_UNROLL (t)) : 0);
19084 stmt = cp_convert_range_for (stmt, decl, expr,
19085 decomp_first, decomp_cnt,
19086 RANGE_FOR_IVDEP (t), unroll);
19089 bool prev = note_iteration_stmt_body_start ();
19090 RECUR (RANGE_FOR_BODY (t));
19091 note_iteration_stmt_body_end (prev);
19092 finish_for_stmt (stmt);
19094 break;
19096 case WHILE_STMT:
19097 stmt = begin_while_stmt ();
19098 tmp = RECUR (WHILE_COND (t));
19099 finish_while_stmt_cond (tmp, stmt, false, 0);
19101 bool prev = note_iteration_stmt_body_start ();
19102 RECUR (WHILE_BODY (t));
19103 note_iteration_stmt_body_end (prev);
19105 finish_while_stmt (stmt);
19106 break;
19108 case DO_STMT:
19109 stmt = begin_do_stmt ();
19111 bool prev = note_iteration_stmt_body_start ();
19112 RECUR (DO_BODY (t));
19113 note_iteration_stmt_body_end (prev);
19115 finish_do_body (stmt);
19116 tmp = RECUR (DO_COND (t));
19117 finish_do_stmt (tmp, stmt, false, 0);
19118 break;
19120 case IF_STMT:
19121 stmt = begin_if_stmt ();
19122 IF_STMT_CONSTEXPR_P (stmt) = IF_STMT_CONSTEXPR_P (t);
19123 IF_STMT_CONSTEVAL_P (stmt) = IF_STMT_CONSTEVAL_P (t);
19124 if (IF_STMT_CONSTEXPR_P (t))
19125 args = add_extra_args (IF_STMT_EXTRA_ARGS (t), args, complain, in_decl);
19127 tree cond = IF_COND (t);
19128 bool was_dep = dependent_operand_p (cond);
19129 cond = RECUR (cond);
19130 warning_sentinel s1(warn_address, was_dep);
19131 tmp = finish_if_stmt_cond (cond, stmt);
19133 if (IF_STMT_CONSTEXPR_P (t)
19134 && instantiation_dependent_expression_p (tmp))
19136 /* We're partially instantiating a generic lambda, but the condition
19137 of the constexpr if is still dependent. Don't substitute into the
19138 branches now, just remember the template arguments. */
19139 do_poplevel (IF_SCOPE (stmt));
19140 IF_COND (stmt) = IF_COND (t);
19141 THEN_CLAUSE (stmt) = THEN_CLAUSE (t);
19142 ELSE_CLAUSE (stmt) = ELSE_CLAUSE (t);
19143 IF_STMT_EXTRA_ARGS (stmt) = build_extra_args (t, args, complain);
19144 add_stmt (stmt);
19145 break;
19147 if (IF_STMT_CONSTEXPR_P (t) && integer_zerop (tmp))
19148 /* Don't instantiate the THEN_CLAUSE. */;
19149 else if (IF_STMT_CONSTEVAL_P (t))
19151 bool save_in_consteval_if_p = in_consteval_if_p;
19152 in_consteval_if_p = true;
19153 RECUR (THEN_CLAUSE (t));
19154 in_consteval_if_p = save_in_consteval_if_p;
19156 else
19158 tree folded = fold_non_dependent_expr (tmp, complain);
19159 bool inhibit = integer_zerop (folded);
19160 if (inhibit)
19161 ++c_inhibit_evaluation_warnings;
19162 RECUR (THEN_CLAUSE (t));
19163 if (inhibit)
19164 --c_inhibit_evaluation_warnings;
19166 finish_then_clause (stmt);
19168 if (IF_STMT_CONSTEXPR_P (t) && integer_nonzerop (tmp))
19169 /* Don't instantiate the ELSE_CLAUSE. */;
19170 else if (ELSE_CLAUSE (t))
19172 tree folded = fold_non_dependent_expr (tmp, complain);
19173 bool inhibit = integer_nonzerop (folded);
19174 begin_else_clause (stmt);
19175 if (inhibit)
19176 ++c_inhibit_evaluation_warnings;
19177 RECUR (ELSE_CLAUSE (t));
19178 if (inhibit)
19179 --c_inhibit_evaluation_warnings;
19180 finish_else_clause (stmt);
19183 finish_if_stmt (stmt);
19184 break;
19186 case BIND_EXPR:
19187 if (BIND_EXPR_BODY_BLOCK (t))
19188 stmt = begin_function_body ();
19189 else
19190 stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
19191 ? BCS_TRY_BLOCK : 0);
19193 RECUR (BIND_EXPR_BODY (t));
19195 if (BIND_EXPR_BODY_BLOCK (t))
19196 finish_function_body (stmt);
19197 else
19198 finish_compound_stmt (stmt);
19199 break;
19201 case BREAK_STMT:
19202 finish_break_stmt ();
19203 break;
19205 case CONTINUE_STMT:
19206 finish_continue_stmt ();
19207 break;
19209 case SWITCH_STMT:
19210 stmt = begin_switch_stmt ();
19211 tmp = RECUR (SWITCH_STMT_COND (t));
19212 finish_switch_cond (tmp, stmt);
19213 RECUR (SWITCH_STMT_BODY (t));
19214 finish_switch_stmt (stmt);
19215 break;
19217 case CASE_LABEL_EXPR:
19219 tree decl = CASE_LABEL (t);
19220 tree low = RECUR (CASE_LOW (t));
19221 tree high = RECUR (CASE_HIGH (t));
19222 tree l = finish_case_label (EXPR_LOCATION (t), low, high);
19223 if (l && TREE_CODE (l) == CASE_LABEL_EXPR)
19225 tree label = CASE_LABEL (l);
19226 FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
19227 if (DECL_ATTRIBUTES (decl) != NULL_TREE)
19228 cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
19231 break;
19233 case LABEL_EXPR:
19235 tree decl = LABEL_EXPR_LABEL (t);
19236 tree label;
19238 label = finish_label_stmt (DECL_NAME (decl));
19239 if (TREE_CODE (label) == LABEL_DECL)
19240 FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
19241 if (DECL_ATTRIBUTES (decl) != NULL_TREE)
19242 cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
19244 break;
19246 case GOTO_EXPR:
19247 tmp = GOTO_DESTINATION (t);
19248 if (TREE_CODE (tmp) != LABEL_DECL)
19249 /* Computed goto's must be tsubst'd into. On the other hand,
19250 non-computed gotos must not be; the identifier in question
19251 will have no binding. */
19252 tmp = RECUR (tmp);
19253 else
19254 tmp = DECL_NAME (tmp);
19255 finish_goto_stmt (tmp);
19256 break;
19258 case ASM_EXPR:
19260 tree string = RECUR (ASM_STRING (t));
19261 tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
19262 complain, in_decl);
19263 tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
19264 complain, in_decl);
19265 tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
19266 complain, in_decl);
19267 tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
19268 complain, in_decl);
19269 tmp = finish_asm_stmt (EXPR_LOCATION (t), ASM_VOLATILE_P (t), string,
19270 outputs, inputs, clobbers, labels,
19271 ASM_INLINE_P (t));
19272 tree asm_expr = tmp;
19273 if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
19274 asm_expr = TREE_OPERAND (asm_expr, 0);
19275 ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
19277 break;
19279 case TRY_BLOCK:
19280 if (CLEANUP_P (t))
19282 stmt = begin_try_block ();
19283 RECUR (TRY_STMTS (t));
19284 finish_cleanup_try_block (stmt);
19285 finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
19287 else
19289 tree compound_stmt = NULL_TREE;
19291 if (FN_TRY_BLOCK_P (t))
19292 stmt = begin_function_try_block (&compound_stmt);
19293 else
19294 stmt = begin_try_block ();
19296 RECUR (TRY_STMTS (t));
19298 if (FN_TRY_BLOCK_P (t))
19299 finish_function_try_block (stmt);
19300 else
19301 finish_try_block (stmt);
19303 RECUR (TRY_HANDLERS (t));
19304 if (FN_TRY_BLOCK_P (t))
19305 finish_function_handler_sequence (stmt, compound_stmt);
19306 else
19307 finish_handler_sequence (stmt);
19309 break;
19311 case HANDLER:
19313 tree decl = HANDLER_PARMS (t);
19315 if (decl)
19317 decl = tsubst (decl, args, complain, in_decl);
19318 /* Prevent instantiate_decl from trying to instantiate
19319 this variable. We've already done all that needs to be
19320 done. */
19321 if (decl != error_mark_node)
19322 DECL_TEMPLATE_INSTANTIATED (decl) = 1;
19324 stmt = begin_handler ();
19325 finish_handler_parms (decl, stmt);
19326 RECUR (HANDLER_BODY (t));
19327 finish_handler (stmt);
19329 break;
19331 case TAG_DEFN:
19332 tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
19333 if (CLASS_TYPE_P (tmp))
19335 /* Local classes are not independent templates; they are
19336 instantiated along with their containing function. And this
19337 way we don't have to deal with pushing out of one local class
19338 to instantiate a member of another local class. */
19339 /* Closures are handled by the LAMBDA_EXPR. */
19340 gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
19341 complete_type (tmp);
19342 if (dependent_type_p (tmp))
19344 /* This is a partial instantiation, try again when full. */
19345 add_stmt (build_min (TAG_DEFN, tmp));
19346 break;
19348 tree save_ccp = current_class_ptr;
19349 tree save_ccr = current_class_ref;
19350 for (tree fld = TYPE_FIELDS (tmp); fld; fld = DECL_CHAIN (fld))
19351 if ((VAR_P (fld)
19352 || (TREE_CODE (fld) == FUNCTION_DECL
19353 && !DECL_ARTIFICIAL (fld)))
19354 && DECL_TEMPLATE_INSTANTIATION (fld))
19355 instantiate_decl (fld, /*defer_ok=*/false,
19356 /*expl_inst_class=*/false);
19357 else if (TREE_CODE (fld) == FIELD_DECL)
19358 maybe_instantiate_nsdmi_init (fld, tf_warning_or_error);
19359 current_class_ptr = save_ccp;
19360 current_class_ref = save_ccr;
19362 break;
19364 case STATIC_ASSERT:
19366 tree condition;
19368 ++c_inhibit_evaluation_warnings;
19369 condition = tsubst_expr (STATIC_ASSERT_CONDITION (t), args,
19370 complain, in_decl);
19371 --c_inhibit_evaluation_warnings;
19373 finish_static_assert (condition,
19374 STATIC_ASSERT_MESSAGE (t),
19375 STATIC_ASSERT_SOURCE_LOCATION (t),
19376 /*member_p=*/false, /*show_expr_p=*/true);
19378 break;
19380 case OACC_KERNELS:
19381 case OACC_PARALLEL:
19382 case OACC_SERIAL:
19383 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_ACC, args, complain,
19384 in_decl);
19385 stmt = begin_omp_parallel ();
19386 RECUR (OMP_BODY (t));
19387 finish_omp_construct (TREE_CODE (t), stmt, tmp);
19388 break;
19390 case OMP_PARALLEL:
19391 r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
19392 tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), C_ORT_OMP, args,
19393 complain, in_decl);
19394 if (OMP_PARALLEL_COMBINED (t))
19395 omp_parallel_combined_clauses = &tmp;
19396 stmt = begin_omp_parallel ();
19397 RECUR (OMP_PARALLEL_BODY (t));
19398 gcc_assert (omp_parallel_combined_clauses == NULL);
19399 OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
19400 = OMP_PARALLEL_COMBINED (t);
19401 pop_omp_privatization_clauses (r);
19402 break;
19404 case OMP_TASK:
19405 if (OMP_TASK_BODY (t) == NULL_TREE)
19407 tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
19408 complain, in_decl);
19409 t = copy_node (t);
19410 OMP_TASK_CLAUSES (t) = tmp;
19411 add_stmt (t);
19412 break;
19414 r = push_omp_privatization_clauses (false);
19415 tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
19416 complain, in_decl);
19417 stmt = begin_omp_task ();
19418 RECUR (OMP_TASK_BODY (t));
19419 finish_omp_task (tmp, stmt);
19420 pop_omp_privatization_clauses (r);
19421 break;
19423 case OMP_FOR:
19424 case OMP_LOOP:
19425 case OMP_SIMD:
19426 case OMP_DISTRIBUTE:
19427 case OMP_TASKLOOP:
19428 case OACC_LOOP:
19430 tree clauses, body, pre_body;
19431 tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
19432 tree orig_declv = NULL_TREE;
19433 tree incrv = NULL_TREE;
19434 enum c_omp_region_type ort = C_ORT_OMP;
19435 bool any_range_for = false;
19436 int i;
19438 if (TREE_CODE (t) == OACC_LOOP)
19439 ort = C_ORT_ACC;
19441 r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
19442 clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), ort, args, complain,
19443 in_decl);
19444 if (OMP_FOR_INIT (t) != NULL_TREE)
19446 declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19447 if (OMP_FOR_ORIG_DECLS (t))
19448 orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19449 initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19450 condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19451 incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
19454 keep_next_level (true);
19455 stmt = begin_omp_structured_block ();
19457 pre_body = push_stmt_list ();
19458 RECUR (OMP_FOR_PRE_BODY (t));
19459 pre_body = pop_stmt_list (pre_body);
19461 if (OMP_FOR_INIT (t) != NULL_TREE)
19462 for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
19463 any_range_for
19464 |= tsubst_omp_for_iterator (t, i, declv, orig_declv, initv,
19465 condv, incrv, &clauses, args,
19466 complain, in_decl);
19467 omp_parallel_combined_clauses = NULL;
19469 if (any_range_for)
19471 gcc_assert (orig_declv);
19472 body = begin_omp_structured_block ();
19473 for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
19474 if (TREE_VEC_ELT (orig_declv, i) != TREE_VEC_ELT (declv, i)
19475 && TREE_CODE (TREE_VEC_ELT (orig_declv, i)) == TREE_LIST
19476 && TREE_CHAIN (TREE_VEC_ELT (orig_declv, i)))
19477 cp_finish_omp_range_for (TREE_VEC_ELT (orig_declv, i),
19478 TREE_VEC_ELT (declv, i));
19480 else
19481 body = push_stmt_list ();
19482 RECUR (OMP_FOR_BODY (t));
19483 if (any_range_for)
19484 body = finish_omp_structured_block (body);
19485 else
19486 body = pop_stmt_list (body);
19488 if (OMP_FOR_INIT (t) != NULL_TREE)
19489 t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
19490 orig_declv, initv, condv, incrv, body, pre_body,
19491 NULL, clauses);
19492 else
19494 t = make_node (TREE_CODE (t));
19495 TREE_TYPE (t) = void_type_node;
19496 OMP_FOR_BODY (t) = body;
19497 OMP_FOR_PRE_BODY (t) = pre_body;
19498 OMP_FOR_CLAUSES (t) = clauses;
19499 SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
19500 add_stmt (t);
19503 add_stmt (finish_omp_for_block (finish_omp_structured_block (stmt),
19504 t));
19505 pop_omp_privatization_clauses (r);
19507 break;
19509 case OMP_SECTIONS:
19510 case OMP_MASKED:
19511 omp_parallel_combined_clauses = NULL;
19512 /* FALLTHRU */
19513 case OMP_SINGLE:
19514 case OMP_SCOPE:
19515 case OMP_TEAMS:
19516 case OMP_CRITICAL:
19517 case OMP_TASKGROUP:
19518 case OMP_SCAN:
19519 r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
19520 && OMP_TEAMS_COMBINED (t));
19521 tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_OMP, args, complain,
19522 in_decl);
19523 if (TREE_CODE (t) == OMP_TEAMS)
19525 keep_next_level (true);
19526 stmt = begin_omp_structured_block ();
19527 RECUR (OMP_BODY (t));
19528 stmt = finish_omp_structured_block (stmt);
19530 else
19532 stmt = push_stmt_list ();
19533 RECUR (OMP_BODY (t));
19534 stmt = pop_stmt_list (stmt);
19537 if (TREE_CODE (t) == OMP_CRITICAL
19538 && tmp != NULL_TREE
19539 && integer_nonzerop (OMP_CLAUSE_HINT_EXPR (tmp)))
19541 error_at (OMP_CLAUSE_LOCATION (tmp),
19542 "%<#pragma omp critical%> with %<hint%> clause requires "
19543 "a name, except when %<omp_sync_hint_none%> is used");
19544 RETURN (error_mark_node);
19546 t = copy_node (t);
19547 OMP_BODY (t) = stmt;
19548 OMP_CLAUSES (t) = tmp;
19549 add_stmt (t);
19550 pop_omp_privatization_clauses (r);
19551 break;
19553 case OMP_DEPOBJ:
19554 r = RECUR (OMP_DEPOBJ_DEPOBJ (t));
19555 if (OMP_DEPOBJ_CLAUSES (t) && OMP_DEPOBJ_CLAUSES (t) != error_mark_node)
19557 enum omp_clause_depend_kind kind = OMP_CLAUSE_DEPEND_INVALID;
19558 if (TREE_CODE (OMP_DEPOBJ_CLAUSES (t)) == OMP_CLAUSE)
19560 tmp = tsubst_omp_clauses (OMP_DEPOBJ_CLAUSES (t), C_ORT_OMP,
19561 args, complain, in_decl);
19562 if (tmp == NULL_TREE)
19563 tmp = error_mark_node;
19565 else
19567 kind = (enum omp_clause_depend_kind)
19568 tree_to_uhwi (OMP_DEPOBJ_CLAUSES (t));
19569 tmp = NULL_TREE;
19571 finish_omp_depobj (EXPR_LOCATION (t), r, kind, tmp);
19573 else
19574 finish_omp_depobj (EXPR_LOCATION (t), r,
19575 OMP_CLAUSE_DEPEND_INVALID,
19576 OMP_DEPOBJ_CLAUSES (t));
19577 break;
19579 case OACC_DATA:
19580 case OMP_TARGET_DATA:
19581 case OMP_TARGET:
19582 tmp = tsubst_omp_clauses (OMP_CLAUSES (t),
19583 TREE_CODE (t) == OACC_DATA
19584 ? C_ORT_ACC
19585 : TREE_CODE (t) == OMP_TARGET
19586 ? C_ORT_OMP_TARGET : C_ORT_OMP,
19587 args, complain, in_decl);
19588 keep_next_level (true);
19589 stmt = begin_omp_structured_block ();
19591 RECUR (OMP_BODY (t));
19592 stmt = finish_omp_structured_block (stmt);
19594 t = copy_node (t);
19595 OMP_BODY (t) = stmt;
19596 OMP_CLAUSES (t) = tmp;
19598 if (TREE_CODE (t) == OMP_TARGET)
19599 finish_omp_target_clauses (EXPR_LOCATION (t), OMP_BODY (t),
19600 &OMP_CLAUSES (t));
19602 if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
19604 tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
19605 if (teams)
19606 /* For combined target teams, ensure the num_teams and
19607 thread_limit clause expressions are evaluated on the host,
19608 before entering the target construct. */
19609 for (tree c = OMP_TEAMS_CLAUSES (teams);
19610 c; c = OMP_CLAUSE_CHAIN (c))
19611 if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
19612 || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
19613 for (int i = 0;
19614 i <= (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS); ++i)
19615 if (OMP_CLAUSE_OPERAND (c, i)
19616 && TREE_CODE (OMP_CLAUSE_OPERAND (c, i)) != INTEGER_CST)
19618 tree expr = OMP_CLAUSE_OPERAND (c, i);
19619 expr = force_target_expr (TREE_TYPE (expr), expr,
19620 tf_none);
19621 if (expr == error_mark_node)
19622 continue;
19623 tmp = TARGET_EXPR_SLOT (expr);
19624 add_stmt (expr);
19625 OMP_CLAUSE_OPERAND (c, i) = expr;
19626 tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
19627 OMP_CLAUSE_FIRSTPRIVATE);
19628 OMP_CLAUSE_DECL (tc) = tmp;
19629 OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
19630 OMP_TARGET_CLAUSES (t) = tc;
19633 add_stmt (t);
19634 break;
19636 case OACC_DECLARE:
19637 t = copy_node (t);
19638 tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), C_ORT_ACC, args,
19639 complain, in_decl);
19640 OACC_DECLARE_CLAUSES (t) = tmp;
19641 add_stmt (t);
19642 break;
19644 case OMP_TARGET_UPDATE:
19645 case OMP_TARGET_ENTER_DATA:
19646 case OMP_TARGET_EXIT_DATA:
19647 tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_OMP, args,
19648 complain, in_decl);
19649 t = copy_node (t);
19650 OMP_STANDALONE_CLAUSES (t) = tmp;
19651 add_stmt (t);
19652 break;
19654 case OACC_CACHE:
19655 case OACC_ENTER_DATA:
19656 case OACC_EXIT_DATA:
19657 case OACC_UPDATE:
19658 tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_ACC, args,
19659 complain, in_decl);
19660 t = copy_node (t);
19661 OMP_STANDALONE_CLAUSES (t) = tmp;
19662 add_stmt (t);
19663 break;
19665 case OMP_ORDERED:
19666 tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), C_ORT_OMP, args,
19667 complain, in_decl);
19668 if (OMP_BODY (t))
19670 stmt = push_stmt_list ();
19671 RECUR (OMP_BODY (t));
19672 stmt = pop_stmt_list (stmt);
19674 else
19675 stmt = NULL_TREE;
19677 t = copy_node (t);
19678 OMP_BODY (t) = stmt;
19679 OMP_ORDERED_CLAUSES (t) = tmp;
19680 add_stmt (t);
19681 break;
19683 case OMP_MASTER:
19684 omp_parallel_combined_clauses = NULL;
19685 /* FALLTHRU */
19686 case OMP_SECTION:
19687 stmt = push_stmt_list ();
19688 RECUR (OMP_BODY (t));
19689 stmt = pop_stmt_list (stmt);
19691 t = copy_node (t);
19692 OMP_BODY (t) = stmt;
19693 add_stmt (t);
19694 break;
19696 case OMP_ATOMIC:
19697 gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
19698 tmp = NULL_TREE;
19699 if (TREE_CODE (TREE_OPERAND (t, 0)) == OMP_CLAUSE)
19700 tmp = tsubst_omp_clauses (TREE_OPERAND (t, 0), C_ORT_OMP, args,
19701 complain, in_decl);
19702 if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
19704 tree op1 = TREE_OPERAND (t, 1);
19705 tree rhs1 = NULL_TREE;
19706 tree r = NULL_TREE;
19707 tree lhs, rhs;
19708 if (TREE_CODE (op1) == COMPOUND_EXPR)
19710 rhs1 = RECUR (TREE_OPERAND (op1, 0));
19711 op1 = TREE_OPERAND (op1, 1);
19713 if (TREE_CODE (op1) == COND_EXPR)
19715 gcc_assert (rhs1 == NULL_TREE);
19716 tree c = TREE_OPERAND (op1, 0);
19717 if (TREE_CODE (c) == MODIFY_EXPR)
19719 r = RECUR (TREE_OPERAND (c, 0));
19720 c = TREE_OPERAND (c, 1);
19722 gcc_assert (TREE_CODE (c) == EQ_EXPR);
19723 rhs = RECUR (TREE_OPERAND (c, 1));
19724 lhs = RECUR (TREE_OPERAND (op1, 2));
19725 rhs1 = RECUR (TREE_OPERAND (op1, 1));
19727 else
19729 lhs = RECUR (TREE_OPERAND (op1, 0));
19730 rhs = RECUR (TREE_OPERAND (op1, 1));
19732 finish_omp_atomic (EXPR_LOCATION (t), OMP_ATOMIC, TREE_CODE (op1),
19733 lhs, rhs, NULL_TREE, NULL_TREE, rhs1, r,
19734 tmp, OMP_ATOMIC_MEMORY_ORDER (t),
19735 OMP_ATOMIC_WEAK (t));
19737 else
19739 tree op1 = TREE_OPERAND (t, 1);
19740 tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
19741 tree rhs1 = NULL_TREE, r = NULL_TREE;
19742 enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
19743 enum tree_code opcode = NOP_EXPR;
19744 if (code == OMP_ATOMIC_READ)
19746 v = RECUR (TREE_OPERAND (op1, 0));
19747 lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19749 else if (code == OMP_ATOMIC_CAPTURE_OLD
19750 || code == OMP_ATOMIC_CAPTURE_NEW)
19752 tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
19753 v = RECUR (TREE_OPERAND (op1, 0));
19754 lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
19755 if (TREE_CODE (op11) == COMPOUND_EXPR)
19757 rhs1 = RECUR (TREE_OPERAND (op11, 0));
19758 op11 = TREE_OPERAND (op11, 1);
19760 if (TREE_CODE (op11) == COND_EXPR)
19762 gcc_assert (rhs1 == NULL_TREE);
19763 tree c = TREE_OPERAND (op11, 0);
19764 if (TREE_CODE (c) == MODIFY_EXPR)
19766 r = RECUR (TREE_OPERAND (c, 0));
19767 c = TREE_OPERAND (c, 1);
19769 gcc_assert (TREE_CODE (c) == EQ_EXPR);
19770 rhs = RECUR (TREE_OPERAND (c, 1));
19771 lhs = RECUR (TREE_OPERAND (op11, 2));
19772 rhs1 = RECUR (TREE_OPERAND (op11, 1));
19774 else
19776 lhs = RECUR (TREE_OPERAND (op11, 0));
19777 rhs = RECUR (TREE_OPERAND (op11, 1));
19779 opcode = TREE_CODE (op11);
19780 if (opcode == MODIFY_EXPR)
19781 opcode = NOP_EXPR;
19783 else
19785 code = OMP_ATOMIC;
19786 lhs = RECUR (TREE_OPERAND (op1, 0));
19787 rhs = RECUR (TREE_OPERAND (op1, 1));
19789 finish_omp_atomic (EXPR_LOCATION (t), code, opcode, lhs, rhs, v,
19790 lhs1, rhs1, r, tmp,
19791 OMP_ATOMIC_MEMORY_ORDER (t), OMP_ATOMIC_WEAK (t));
19793 break;
19795 case TRANSACTION_EXPR:
19797 int flags = 0;
19798 flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
19799 flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
19801 if (TRANSACTION_EXPR_IS_STMT (t))
19803 tree body = TRANSACTION_EXPR_BODY (t);
19804 tree noex = NULL_TREE;
19805 if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
19807 noex = MUST_NOT_THROW_COND (body);
19808 if (noex == NULL_TREE)
19809 noex = boolean_true_node;
19810 body = TREE_OPERAND (body, 0);
19812 stmt = begin_transaction_stmt (input_location, NULL, flags);
19813 RECUR (body);
19814 finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
19816 else
19818 stmt = build_transaction_expr (EXPR_LOCATION (t),
19819 RECUR (TRANSACTION_EXPR_BODY (t)),
19820 flags, NULL_TREE);
19821 RETURN (stmt);
19824 break;
19826 case MUST_NOT_THROW_EXPR:
19828 tree op0 = RECUR (TREE_OPERAND (t, 0));
19829 tree cond = RECUR (MUST_NOT_THROW_COND (t));
19830 RETURN (build_must_not_throw_expr (op0, cond));
19833 case EXPR_PACK_EXPANSION:
19834 error ("invalid use of pack expansion expression");
19835 RETURN (error_mark_node);
19837 case NONTYPE_ARGUMENT_PACK:
19838 error ("use %<...%> to expand argument pack");
19839 RETURN (error_mark_node);
19841 case COMPOUND_EXPR:
19842 tmp = RECUR (TREE_OPERAND (t, 0));
19843 if (tmp == NULL_TREE)
19844 /* If the first operand was a statement, we're done with it. */
19845 RETURN (RECUR (TREE_OPERAND (t, 1)));
19846 RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
19847 RECUR (TREE_OPERAND (t, 1)),
19848 templated_operator_saved_lookups (t),
19849 complain));
19851 case ANNOTATE_EXPR:
19852 tmp = RECUR (TREE_OPERAND (t, 0));
19853 RETURN (build3_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
19854 TREE_TYPE (tmp), tmp,
19855 RECUR (TREE_OPERAND (t, 1)),
19856 RECUR (TREE_OPERAND (t, 2))));
19858 case PREDICT_EXPR:
19859 RETURN (add_stmt (copy_node (t)));
19861 default:
19862 gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
19864 RETURN (tsubst_copy_and_build (t, args, complain, in_decl));
19867 RETURN (NULL_TREE);
19868 out:
19869 input_location = loc;
19870 return r;
19871 #undef RECUR
19872 #undef RETURN
19875 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
19876 function. For description of the body see comment above
19877 cp_parser_omp_declare_reduction_exprs. */
19879 static void
19880 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19882 if (t == NULL_TREE || t == error_mark_node)
19883 return;
19885 gcc_assert (TREE_CODE (t) == STATEMENT_LIST && current_function_decl);
19887 tree_stmt_iterator tsi;
19888 int i;
19889 tree stmts[7];
19890 memset (stmts, 0, sizeof stmts);
19891 for (i = 0, tsi = tsi_start (t);
19892 i < 7 && !tsi_end_p (tsi);
19893 i++, tsi_next (&tsi))
19894 stmts[i] = tsi_stmt (tsi);
19895 gcc_assert (tsi_end_p (tsi));
19897 if (i >= 3)
19899 gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
19900 && TREE_CODE (stmts[1]) == DECL_EXPR);
19901 tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
19902 args, complain, in_decl);
19903 tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
19904 args, complain, in_decl);
19905 /* tsubsting a local var_decl leaves DECL_CONTEXT null, as we
19906 expect to be pushing it. */
19907 DECL_CONTEXT (omp_out) = current_function_decl;
19908 DECL_CONTEXT (omp_in) = current_function_decl;
19909 keep_next_level (true);
19910 tree block = begin_omp_structured_block ();
19911 tsubst_expr (stmts[2], args, complain, in_decl);
19912 block = finish_omp_structured_block (block);
19913 block = maybe_cleanup_point_expr_void (block);
19914 add_decl_expr (omp_out);
19915 copy_warning (omp_out, DECL_EXPR_DECL (stmts[0]));
19916 add_decl_expr (omp_in);
19917 finish_expr_stmt (block);
19919 if (i >= 6)
19921 gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
19922 && TREE_CODE (stmts[4]) == DECL_EXPR);
19923 tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
19924 args, complain, in_decl);
19925 tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
19926 args, complain, in_decl);
19927 DECL_CONTEXT (omp_priv) = current_function_decl;
19928 DECL_CONTEXT (omp_orig) = current_function_decl;
19929 keep_next_level (true);
19930 tree block = begin_omp_structured_block ();
19931 tsubst_expr (stmts[5], args, complain, in_decl);
19932 block = finish_omp_structured_block (block);
19933 block = maybe_cleanup_point_expr_void (block);
19934 cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
19935 add_decl_expr (omp_priv);
19936 add_decl_expr (omp_orig);
19937 finish_expr_stmt (block);
19938 if (i == 7)
19939 add_decl_expr (omp_orig);
19943 /* T is a postfix-expression that is not being used in a function
19944 call. Return the substituted version of T. */
19946 static tree
19947 tsubst_non_call_postfix_expression (tree t, tree args,
19948 tsubst_flags_t complain,
19949 tree in_decl)
19951 if (TREE_CODE (t) == SCOPE_REF)
19952 t = tsubst_qualified_id (t, args, complain, in_decl,
19953 /*done=*/false, /*address_p=*/false);
19954 else
19955 t = tsubst_copy_and_build (t, args, complain, in_decl);
19957 return t;
19960 /* Subroutine of tsubst_lambda_expr: add the FIELD/INIT capture pair to the
19961 LAMBDA_EXPR_CAPTURE_LIST passed in LIST. Do deduction for a previously
19962 dependent init-capture. EXPLICIT_P is true if the original list had
19963 explicit captures. */
19965 static void
19966 prepend_one_capture (tree field, tree init, tree &list, bool explicit_p,
19967 tsubst_flags_t complain)
19969 if (tree auto_node = type_uses_auto (TREE_TYPE (field)))
19971 tree type = NULL_TREE;
19972 if (!init)
19974 if (complain & tf_error)
19975 error ("empty initializer in lambda init-capture");
19976 init = error_mark_node;
19978 else if (TREE_CODE (init) == TREE_LIST)
19979 init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19980 if (!type)
19981 type = do_auto_deduction (TREE_TYPE (field), init, auto_node, complain);
19982 TREE_TYPE (field) = type;
19983 cp_apply_type_quals_to_decl (cp_type_quals (type), field);
19985 list = tree_cons (field, init, list);
19986 LAMBDA_CAPTURE_EXPLICIT_P (list) = explicit_p;
19989 /* T is a LAMBDA_EXPR. Generate a new LAMBDA_EXPR for the current
19990 instantiation context. Instantiating a pack expansion containing a lambda
19991 might result in multiple lambdas all based on the same lambda in the
19992 template. */
19994 tree
19995 tsubst_lambda_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19997 tree oldfn = lambda_function (t);
19998 in_decl = oldfn;
20000 tree r = build_lambda_expr ();
20002 LAMBDA_EXPR_LOCATION (r)
20003 = LAMBDA_EXPR_LOCATION (t);
20004 LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
20005 = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
20006 LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
20007 if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
20008 LAMBDA_EXPR_REGEN_INFO (r)
20009 = build_template_info (t, add_to_template_args (TI_ARGS (ti),
20010 preserve_args (args)));
20011 else
20012 LAMBDA_EXPR_REGEN_INFO (r)
20013 = build_template_info (t, preserve_args (args));
20015 gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
20016 && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
20018 vec<tree,va_gc>* field_packs = NULL;
20020 for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t); cap;
20021 cap = TREE_CHAIN (cap))
20023 tree ofield = TREE_PURPOSE (cap);
20024 tree init = TREE_VALUE (cap);
20025 if (PACK_EXPANSION_P (init))
20026 init = tsubst_pack_expansion (init, args, complain, in_decl);
20027 else
20028 init = tsubst_copy_and_build (init, args, complain, in_decl);
20030 if (init == error_mark_node)
20031 return error_mark_node;
20033 if (init && TREE_CODE (init) == TREE_LIST)
20034 init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
20036 if (!processing_template_decl
20037 && init && TREE_CODE (init) != TREE_VEC
20038 && variably_modified_type_p (TREE_TYPE (init), NULL_TREE))
20040 /* For a VLA, simply tsubsting the field type won't work, we need to
20041 go through add_capture again. XXX do we want to do this for all
20042 captures? */
20043 tree name = (get_identifier
20044 (IDENTIFIER_POINTER (DECL_NAME (ofield)) + 2));
20045 tree ftype = TREE_TYPE (ofield);
20046 bool by_ref = (TYPE_REF_P (ftype)
20047 || (TREE_CODE (ftype) == DECLTYPE_TYPE
20048 && DECLTYPE_FOR_REF_CAPTURE (ftype)));
20049 add_capture (r, name, init, by_ref, !DECL_NORMAL_CAPTURE_P (ofield));
20050 continue;
20053 if (PACK_EXPANSION_P (ofield))
20054 ofield = PACK_EXPANSION_PATTERN (ofield);
20055 tree field = tsubst_decl (ofield, args, complain);
20057 if (DECL_PACK_P (ofield) && !DECL_NORMAL_CAPTURE_P (ofield))
20059 /* Remember these for when we've pushed local_specializations. */
20060 vec_safe_push (field_packs, ofield);
20061 vec_safe_push (field_packs, field);
20064 if (field == error_mark_node)
20065 return error_mark_node;
20067 if (TREE_CODE (field) == TREE_VEC)
20069 int len = TREE_VEC_LENGTH (field);
20070 gcc_assert (TREE_CODE (init) == TREE_VEC
20071 && TREE_VEC_LENGTH (init) == len);
20072 for (int i = 0; i < len; ++i)
20073 prepend_one_capture (TREE_VEC_ELT (field, i),
20074 TREE_VEC_ELT (init, i),
20075 LAMBDA_EXPR_CAPTURE_LIST (r),
20076 LAMBDA_CAPTURE_EXPLICIT_P (cap),
20077 complain);
20079 else
20081 prepend_one_capture (field, init, LAMBDA_EXPR_CAPTURE_LIST (r),
20082 LAMBDA_CAPTURE_EXPLICIT_P (cap), complain);
20084 if (id_equal (DECL_NAME (field), "__this"))
20085 LAMBDA_EXPR_THIS_CAPTURE (r) = field;
20089 tree type = begin_lambda_type (r);
20090 if (type == error_mark_node)
20091 return error_mark_node;
20093 if (LAMBDA_EXPR_EXTRA_SCOPE (t))
20094 record_lambda_scope (r);
20095 else if (TYPE_NAMESPACE_SCOPE_P (TREE_TYPE (t)))
20096 /* If we're pushed into another scope (PR105652), fix it. */
20097 TYPE_CONTEXT (type) = DECL_CONTEXT (TYPE_NAME (type))
20098 = TYPE_CONTEXT (TREE_TYPE (t));
20099 record_lambda_scope_discriminator (r);
20101 /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set. */
20102 determine_visibility (TYPE_NAME (type));
20104 register_capture_members (LAMBDA_EXPR_CAPTURE_LIST (r));
20106 tree oldtmpl = (generic_lambda_fn_p (oldfn)
20107 ? DECL_TI_TEMPLATE (oldfn)
20108 : NULL_TREE);
20110 tree tparms = NULL_TREE;
20111 if (oldtmpl)
20112 tparms = tsubst_template_parms (DECL_TEMPLATE_PARMS (oldtmpl), args, complain);
20114 tree fntype = static_fn_type (oldfn);
20116 tree saved_ctp = current_template_parms;
20117 if (oldtmpl)
20119 ++processing_template_decl;
20120 current_template_parms = tparms;
20122 fntype = tsubst (fntype, args, complain, in_decl);
20123 if (oldtmpl)
20125 current_template_parms = saved_ctp;
20126 --processing_template_decl;
20129 if (fntype == error_mark_node)
20130 r = error_mark_node;
20131 else
20133 /* The body of a lambda-expression is not a subexpression of the
20134 enclosing expression. Parms are to have DECL_CHAIN tsubsted,
20135 which would be skipped if cp_unevaluated_operand. */
20136 cp_evaluated ev;
20138 /* Fix the type of 'this'. */
20139 fntype = build_memfn_type (fntype, type,
20140 type_memfn_quals (fntype),
20141 type_memfn_rqual (fntype));
20142 tree inst = (oldtmpl
20143 ? tsubst_template_decl (oldtmpl, args, complain,
20144 fntype, tparms)
20145 : tsubst_function_decl (oldfn, args, complain, fntype));
20146 if (inst == error_mark_node)
20148 r = error_mark_node;
20149 goto out;
20151 finish_member_declaration (inst);
20152 record_lambda_scope_sig_discriminator (r, inst);
20154 tree fn = oldtmpl ? DECL_TEMPLATE_RESULT (inst) : inst;
20156 /* Let finish_function set this. */
20157 DECL_DECLARED_CONSTEXPR_P (fn) = false;
20159 bool nested = cfun;
20160 if (nested)
20161 push_function_context ();
20162 else
20163 /* Still increment function_depth so that we don't GC in the
20164 middle of an expression. */
20165 ++function_depth;
20167 local_specialization_stack s (lss_copy);
20169 bool save_in_consteval_if_p = in_consteval_if_p;
20170 in_consteval_if_p = false;
20172 tree body = start_lambda_function (fn, r);
20174 /* Now record them for lookup_init_capture_pack. */
20175 int fplen = vec_safe_length (field_packs);
20176 for (int i = 0; i < fplen; )
20178 tree pack = (*field_packs)[i++];
20179 tree inst = (*field_packs)[i++];
20180 register_local_specialization (inst, pack);
20182 release_tree_vector (field_packs);
20184 register_parameter_specializations (oldfn, fn);
20186 if (oldtmpl)
20188 /* We might not partially instantiate some parts of the function, so
20189 copy these flags from the original template. */
20190 language_function *ol = DECL_STRUCT_FUNCTION (oldfn)->language;
20191 current_function_returns_value = ol->returns_value;
20192 current_function_returns_null = ol->returns_null;
20193 current_function_returns_abnormally = ol->returns_abnormally;
20194 current_function_infinite_loop = ol->infinite_loop;
20197 /* [temp.deduct] A lambda-expression appearing in a function type or a
20198 template parameter is not considered part of the immediate context for
20199 the purposes of template argument deduction. */
20200 complain = tf_warning_or_error;
20202 tree saved = DECL_SAVED_TREE (oldfn);
20203 if (TREE_CODE (saved) == BIND_EXPR && BIND_EXPR_BODY_BLOCK (saved))
20204 /* We already have a body block from start_lambda_function, we don't
20205 need another to confuse NRV (91217). */
20206 saved = BIND_EXPR_BODY (saved);
20208 tsubst_expr (saved, args, complain, r);
20210 finish_lambda_function (body);
20212 in_consteval_if_p = save_in_consteval_if_p;
20214 if (nested)
20215 pop_function_context ();
20216 else
20217 --function_depth;
20219 /* The capture list was built up in reverse order; fix that now. */
20220 LAMBDA_EXPR_CAPTURE_LIST (r)
20221 = nreverse (LAMBDA_EXPR_CAPTURE_LIST (r));
20223 LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
20225 maybe_add_lambda_conv_op (type);
20228 out:
20229 finish_struct (type, /*attr*/NULL_TREE);
20231 insert_pending_capture_proxies ();
20233 return r;
20236 /* Subroutine of maybe_fold_fn_template_args. */
20238 static bool
20239 fold_targs_r (tree targs, tsubst_flags_t complain)
20241 int len = TREE_VEC_LENGTH (targs);
20242 for (int i = 0; i < len; ++i)
20244 tree &elt = TREE_VEC_ELT (targs, i);
20245 if (!elt || TYPE_P (elt)
20246 || TREE_CODE (elt) == TEMPLATE_DECL)
20247 continue;
20248 if (TREE_CODE (elt) == NONTYPE_ARGUMENT_PACK)
20250 if (!fold_targs_r (ARGUMENT_PACK_ARGS (elt), complain))
20251 return false;
20253 else if (/* We can only safely preevaluate scalar prvalues. */
20254 SCALAR_TYPE_P (TREE_TYPE (elt))
20255 && !glvalue_p (elt)
20256 && !TREE_CONSTANT (elt))
20258 elt = cxx_constant_value (elt, complain);
20259 if (elt == error_mark_node)
20260 return false;
20264 return true;
20267 /* Try to do constant evaluation of any explicit template arguments in FN
20268 before overload resolution, to get any errors only once. Return true iff
20269 we didn't have any problems folding. */
20271 static bool
20272 maybe_fold_fn_template_args (tree fn, tsubst_flags_t complain)
20274 if (processing_template_decl || fn == NULL_TREE)
20275 return true;
20276 if (fn == error_mark_node)
20277 return false;
20278 if (TREE_CODE (fn) == OFFSET_REF
20279 || TREE_CODE (fn) == COMPONENT_REF)
20280 fn = TREE_OPERAND (fn, 1);
20281 if (BASELINK_P (fn))
20282 fn = BASELINK_FUNCTIONS (fn);
20283 if (TREE_CODE (fn) != TEMPLATE_ID_EXPR)
20284 return true;
20285 tree targs = TREE_OPERAND (fn, 1);
20286 if (targs == NULL_TREE)
20287 return true;
20288 if (targs == error_mark_node)
20289 return false;
20290 return fold_targs_r (targs, complain);
20293 /* Helper function for tsubst_copy_and_build CALL_EXPR and ARRAY_REF
20294 handling. */
20296 static void
20297 tsubst_copy_and_build_call_args (tree t, tree args, tsubst_flags_t complain,
20298 tree in_decl, releasing_vec &call_args)
20300 unsigned int nargs = call_expr_nargs (t);
20301 for (unsigned int i = 0; i < nargs; ++i)
20303 tree arg = CALL_EXPR_ARG (t, i);
20305 if (!PACK_EXPANSION_P (arg))
20306 vec_safe_push (call_args,
20307 tsubst_copy_and_build (arg, args, complain, in_decl));
20308 else
20310 /* Expand the pack expansion and push each entry onto CALL_ARGS. */
20311 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
20312 if (TREE_CODE (arg) == TREE_VEC)
20314 unsigned int len, j;
20316 len = TREE_VEC_LENGTH (arg);
20317 for (j = 0; j < len; ++j)
20319 tree value = TREE_VEC_ELT (arg, j);
20320 if (value != NULL_TREE)
20321 value = convert_from_reference (value);
20322 vec_safe_push (call_args, value);
20325 else
20326 /* A partial substitution. Add one entry. */
20327 vec_safe_push (call_args, arg);
20332 /* Like tsubst but deals with expressions and performs semantic
20333 analysis. */
20335 tree
20336 tsubst_copy_and_build (tree t,
20337 tree args,
20338 tsubst_flags_t complain,
20339 tree in_decl)
20341 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
20342 #define RECUR(NODE) \
20343 tsubst_copy_and_build (NODE, args, complain, in_decl)
20345 tree retval, op1;
20346 location_t save_loc;
20348 if (t == NULL_TREE || t == error_mark_node)
20349 return t;
20351 save_loc = input_location;
20352 if (location_t eloc = cp_expr_location (t))
20353 input_location = eloc;
20355 /* N3276 decltype magic only applies to calls at the top level or on the
20356 right side of a comma. */
20357 tsubst_flags_t decltype_flag = (complain & tf_decltype);
20358 complain &= ~tf_decltype;
20360 switch (TREE_CODE (t))
20362 case USING_DECL:
20363 t = DECL_NAME (t);
20364 /* Fall through. */
20365 case IDENTIFIER_NODE:
20367 tree decl;
20368 cp_id_kind idk;
20369 const char *error_msg;
20371 if (IDENTIFIER_CONV_OP_P (t))
20373 tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20374 t = make_conv_op_name (new_type);
20377 /* Look up the name. */
20378 decl = lookup_name (t);
20380 /* By convention, expressions use ERROR_MARK_NODE to indicate
20381 failure, not NULL_TREE. */
20382 if (decl == NULL_TREE)
20383 decl = error_mark_node;
20385 decl = finish_id_expression (t, decl, NULL_TREE,
20386 &idk,
20387 /*i_c_e_p=*/false,
20388 /*allow_i_c_e_p=*/true,
20389 /*non_i_c_e_p=*/nullptr,
20390 /*template_p=*/false,
20391 /*done=*/true,
20392 /*address_p=*/false,
20393 /*template_arg_p=*/false,
20394 &error_msg,
20395 input_location);
20396 if (error_msg)
20397 error (error_msg);
20398 if (identifier_p (decl))
20400 if (complain & tf_error)
20401 unqualified_name_lookup_error (decl);
20402 decl = error_mark_node;
20404 RETURN (decl);
20407 case TEMPLATE_ID_EXPR:
20409 tree object;
20410 tree templ = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
20411 complain, in_decl);
20412 tree targs = TREE_OPERAND (t, 1);
20414 if (targs)
20415 targs = tsubst_template_args (targs, args, complain, in_decl);
20416 if (targs == error_mark_node)
20417 RETURN (error_mark_node);
20419 if (TREE_CODE (templ) == SCOPE_REF)
20421 tree name = TREE_OPERAND (templ, 1);
20422 tree tid = lookup_template_function (name, targs);
20423 TREE_OPERAND (templ, 1) = tid;
20424 RETURN (templ);
20427 if (concept_definition_p (templ))
20429 tree check = build_concept_check (templ, targs, complain);
20430 if (check == error_mark_node)
20431 RETURN (error_mark_node);
20433 tree id = unpack_concept_check (check);
20435 /* If we built a function concept check, return the underlying
20436 template-id. So we can evaluate it as a function call. */
20437 if (function_concept_p (TREE_OPERAND (id, 0)))
20438 RETURN (id);
20440 RETURN (check);
20443 if (variable_template_p (templ))
20445 tree r = lookup_and_finish_template_variable (templ, targs,
20446 complain);
20447 r = convert_from_reference (r);
20448 r = maybe_wrap_with_location (r, EXPR_LOCATION (t));
20449 RETURN (r);
20452 if (TREE_CODE (templ) == COMPONENT_REF)
20454 object = TREE_OPERAND (templ, 0);
20455 templ = TREE_OPERAND (templ, 1);
20457 else
20458 object = NULL_TREE;
20460 tree tid = lookup_template_function (templ, targs);
20461 protected_set_expr_location (tid, EXPR_LOCATION (t));
20463 if (object)
20464 RETURN (build3 (COMPONENT_REF, TREE_TYPE (tid),
20465 object, tid, NULL_TREE));
20466 else if (identifier_p (templ))
20468 /* C++20 P0846: we can encounter an IDENTIFIER_NODE here when
20469 name lookup found nothing when parsing the template name. */
20470 gcc_assert (cxx_dialect >= cxx20 || seen_error ());
20471 RETURN (tid);
20473 else
20474 RETURN (baselink_for_fns (tid));
20477 case INDIRECT_REF:
20479 tree r = RECUR (TREE_OPERAND (t, 0));
20481 if (REFERENCE_REF_P (t))
20483 /* A type conversion to reference type will be enclosed in
20484 such an indirect ref, but the substitution of the cast
20485 will have also added such an indirect ref. */
20486 r = convert_from_reference (r);
20488 else
20489 r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
20490 templated_operator_saved_lookups (t),
20491 complain|decltype_flag);
20493 if (REF_PARENTHESIZED_P (t))
20494 r = force_paren_expr (r);
20496 RETURN (r);
20499 case NOP_EXPR:
20501 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20502 tree op0 = RECUR (TREE_OPERAND (t, 0));
20503 RETURN (build_nop (type, op0));
20506 case IMPLICIT_CONV_EXPR:
20508 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20509 tree expr = RECUR (TREE_OPERAND (t, 0));
20510 if (dependent_type_p (type) || type_dependent_expression_p (expr))
20512 retval = copy_node (t);
20513 TREE_TYPE (retval) = type;
20514 TREE_OPERAND (retval, 0) = expr;
20515 RETURN (retval);
20517 if (IMPLICIT_CONV_EXPR_NONTYPE_ARG (t))
20518 /* We'll pass this to convert_nontype_argument again, we don't need
20519 to actually perform any conversion here. */
20520 RETURN (expr);
20521 int flags = LOOKUP_IMPLICIT;
20522 if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
20523 flags = LOOKUP_NORMAL;
20524 if (IMPLICIT_CONV_EXPR_BRACED_INIT (t))
20525 flags |= LOOKUP_NO_NARROWING;
20526 RETURN (perform_implicit_conversion_flags (type, expr, complain,
20527 flags));
20530 case CONVERT_EXPR:
20532 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20533 tree op0 = RECUR (TREE_OPERAND (t, 0));
20534 if (op0 == error_mark_node)
20535 RETURN (error_mark_node);
20536 RETURN (build1 (CONVERT_EXPR, type, op0));
20539 case CAST_EXPR:
20540 case REINTERPRET_CAST_EXPR:
20541 case CONST_CAST_EXPR:
20542 case DYNAMIC_CAST_EXPR:
20543 case STATIC_CAST_EXPR:
20545 tree type;
20546 tree op, r = NULL_TREE;
20548 tsubst_flags_t tcomplain = complain;
20549 if (TREE_CODE (t) == CAST_EXPR)
20550 tcomplain |= tf_tst_ok;
20551 type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
20553 op = RECUR (TREE_OPERAND (t, 0));
20555 warning_sentinel s(warn_useless_cast);
20556 warning_sentinel s2(warn_ignored_qualifiers);
20557 warning_sentinel s3(warn_int_in_bool_context);
20558 switch (TREE_CODE (t))
20560 case CAST_EXPR:
20561 r = build_functional_cast (input_location, type, op, complain);
20562 break;
20563 case REINTERPRET_CAST_EXPR:
20564 r = build_reinterpret_cast (input_location, type, op, complain);
20565 break;
20566 case CONST_CAST_EXPR:
20567 r = build_const_cast (input_location, type, op, complain);
20568 break;
20569 case DYNAMIC_CAST_EXPR:
20570 r = build_dynamic_cast (input_location, type, op, complain);
20571 break;
20572 case STATIC_CAST_EXPR:
20573 r = build_static_cast (input_location, type, op, complain);
20574 if (IMPLICIT_RVALUE_P (t))
20575 set_implicit_rvalue_p (r);
20576 break;
20577 default:
20578 gcc_unreachable ();
20581 RETURN (r);
20584 case BIT_CAST_EXPR:
20586 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20587 tree op0 = RECUR (TREE_OPERAND (t, 0));
20588 RETURN (cp_build_bit_cast (EXPR_LOCATION (t), type, op0, complain));
20591 case POSTDECREMENT_EXPR:
20592 case POSTINCREMENT_EXPR:
20593 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20594 args, complain, in_decl);
20595 RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
20596 templated_operator_saved_lookups (t),
20597 complain|decltype_flag));
20599 case PREDECREMENT_EXPR:
20600 case PREINCREMENT_EXPR:
20601 case NEGATE_EXPR:
20602 case BIT_NOT_EXPR:
20603 case ABS_EXPR:
20604 case TRUTH_NOT_EXPR:
20605 case UNARY_PLUS_EXPR: /* Unary + */
20606 case REALPART_EXPR:
20607 case IMAGPART_EXPR:
20608 RETURN (build_x_unary_op (input_location, TREE_CODE (t),
20609 RECUR (TREE_OPERAND (t, 0)),
20610 templated_operator_saved_lookups (t),
20611 complain|decltype_flag));
20613 case EXCESS_PRECISION_EXPR:
20615 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20616 tree op0 = RECUR (TREE_OPERAND (t, 0));
20617 if (TREE_CODE (op0) == EXCESS_PRECISION_EXPR)
20618 RETURN (op0);
20619 RETURN (build1_loc (EXPR_LOCATION (t), EXCESS_PRECISION_EXPR,
20620 type, op0));
20623 case FIX_TRUNC_EXPR:
20624 /* convert_like should have created an IMPLICIT_CONV_EXPR. */
20625 gcc_unreachable ();
20627 case ADDR_EXPR:
20628 op1 = TREE_OPERAND (t, 0);
20629 if (TREE_CODE (op1) == LABEL_DECL)
20630 RETURN (finish_label_address_expr (DECL_NAME (op1),
20631 EXPR_LOCATION (op1)));
20632 if (TREE_CODE (op1) == SCOPE_REF)
20633 op1 = tsubst_qualified_id (op1, args, complain, in_decl,
20634 /*done=*/true, /*address_p=*/true);
20635 else
20636 op1 = tsubst_non_call_postfix_expression (op1, args, complain,
20637 in_decl);
20638 RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
20639 templated_operator_saved_lookups (t),
20640 complain|decltype_flag));
20642 case PLUS_EXPR:
20643 case MINUS_EXPR:
20644 case MULT_EXPR:
20645 case TRUNC_DIV_EXPR:
20646 case CEIL_DIV_EXPR:
20647 case FLOOR_DIV_EXPR:
20648 case ROUND_DIV_EXPR:
20649 case EXACT_DIV_EXPR:
20650 case BIT_AND_EXPR:
20651 case BIT_IOR_EXPR:
20652 case BIT_XOR_EXPR:
20653 case TRUNC_MOD_EXPR:
20654 case FLOOR_MOD_EXPR:
20655 case TRUTH_ANDIF_EXPR:
20656 case TRUTH_ORIF_EXPR:
20657 case TRUTH_AND_EXPR:
20658 case TRUTH_OR_EXPR:
20659 case RSHIFT_EXPR:
20660 case LSHIFT_EXPR:
20661 case EQ_EXPR:
20662 case NE_EXPR:
20663 case MAX_EXPR:
20664 case MIN_EXPR:
20665 case LE_EXPR:
20666 case GE_EXPR:
20667 case LT_EXPR:
20668 case GT_EXPR:
20669 case SPACESHIP_EXPR:
20670 case MEMBER_REF:
20671 case DOTSTAR_EXPR:
20673 /* If either OP0 or OP1 was value- or type-dependent, suppress
20674 warnings that depend on the range of the types involved. */
20675 tree op0 = TREE_OPERAND (t, 0);
20676 tree op1 = TREE_OPERAND (t, 1);
20677 const bool was_dep = (dependent_operand_p (op0)
20678 || dependent_operand_p (op1));
20679 op0 = RECUR (op0);
20680 op1 = RECUR (op1);
20682 warning_sentinel s1(warn_type_limits, was_dep);
20683 warning_sentinel s2(warn_div_by_zero, was_dep);
20684 warning_sentinel s3(warn_logical_op, was_dep);
20685 warning_sentinel s4(warn_tautological_compare, was_dep);
20686 warning_sentinel s5(warn_address, was_dep);
20688 tree r = build_x_binary_op
20689 (input_location, TREE_CODE (t),
20690 op0,
20691 (warning_suppressed_p (TREE_OPERAND (t, 0))
20692 ? ERROR_MARK
20693 : TREE_CODE (TREE_OPERAND (t, 0))),
20694 op1,
20695 (warning_suppressed_p (TREE_OPERAND (t, 1))
20696 ? ERROR_MARK
20697 : TREE_CODE (TREE_OPERAND (t, 1))),
20698 templated_operator_saved_lookups (t),
20699 /*overload=*/NULL,
20700 complain|decltype_flag);
20701 if (EXPR_P (r))
20702 copy_warning (r, t);
20704 RETURN (r);
20707 case POINTER_PLUS_EXPR:
20709 tree op0 = RECUR (TREE_OPERAND (t, 0));
20710 if (op0 == error_mark_node)
20711 RETURN (error_mark_node);
20712 tree op1 = RECUR (TREE_OPERAND (t, 1));
20713 if (op1 == error_mark_node)
20714 RETURN (error_mark_node);
20715 RETURN (fold_build_pointer_plus (op0, op1));
20718 case SCOPE_REF:
20719 RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
20720 /*address_p=*/false));
20722 case BASELINK:
20723 RETURN (tsubst_baselink (t, current_nonlambda_class_type (),
20724 args, complain, in_decl));
20726 case ARRAY_REF:
20727 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20728 args, complain, in_decl);
20729 if (TREE_CODE (TREE_OPERAND (t, 1)) == CALL_EXPR
20730 && (CALL_EXPR_FN (TREE_OPERAND (t, 1))
20731 == ovl_op_identifier (ARRAY_REF)))
20733 tree c = TREE_OPERAND (t, 1);
20734 releasing_vec index_exp_list;
20735 tsubst_copy_and_build_call_args (c, args, complain, in_decl,
20736 index_exp_list);
20738 tree r;
20739 if (vec_safe_length (index_exp_list) == 1
20740 && !PACK_EXPANSION_P (index_exp_list[0]))
20741 r = grok_array_decl (EXPR_LOCATION (t), op1,
20742 index_exp_list[0], NULL,
20743 complain | decltype_flag);
20744 else
20745 r = grok_array_decl (EXPR_LOCATION (t), op1,
20746 NULL_TREE, &index_exp_list,
20747 complain | decltype_flag);
20748 RETURN (r);
20750 RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
20751 RECUR (TREE_OPERAND (t, 1)),
20752 complain|decltype_flag));
20754 case SIZEOF_EXPR:
20755 if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
20756 || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
20757 RETURN (tsubst_copy (t, args, complain, in_decl));
20758 /* Fall through */
20760 case ALIGNOF_EXPR:
20762 tree r;
20764 op1 = TREE_OPERAND (t, 0);
20765 if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
20766 op1 = TREE_TYPE (op1);
20767 bool std_alignof = (TREE_CODE (t) == ALIGNOF_EXPR
20768 && ALIGNOF_EXPR_STD_P (t));
20769 if (!args)
20771 /* When there are no ARGS, we are trying to evaluate a
20772 non-dependent expression from the parser. Trying to do
20773 the substitutions may not work. */
20774 if (!TYPE_P (op1))
20775 op1 = TREE_TYPE (op1);
20777 else
20779 ++cp_unevaluated_operand;
20780 ++c_inhibit_evaluation_warnings;
20781 if (TYPE_P (op1))
20782 op1 = tsubst (op1, args, complain, in_decl);
20783 else
20784 op1 = tsubst_copy_and_build (op1, args, complain, in_decl);
20785 --cp_unevaluated_operand;
20786 --c_inhibit_evaluation_warnings;
20788 if (TYPE_P (op1))
20789 r = cxx_sizeof_or_alignof_type (input_location,
20790 op1, TREE_CODE (t), std_alignof,
20791 complain & tf_error);
20792 else
20793 r = cxx_sizeof_or_alignof_expr (input_location,
20794 op1, TREE_CODE (t), std_alignof,
20795 complain & tf_error);
20796 if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
20798 if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
20800 if (!processing_template_decl && TYPE_P (op1))
20802 r = build_min (SIZEOF_EXPR, size_type_node,
20803 build1 (NOP_EXPR, op1, error_mark_node));
20804 SIZEOF_EXPR_TYPE_P (r) = 1;
20806 else
20807 r = build_min (SIZEOF_EXPR, size_type_node, op1);
20808 TREE_SIDE_EFFECTS (r) = 0;
20809 TREE_READONLY (r) = 1;
20811 SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
20813 RETURN (r);
20816 case AT_ENCODE_EXPR:
20818 op1 = TREE_OPERAND (t, 0);
20819 ++cp_unevaluated_operand;
20820 ++c_inhibit_evaluation_warnings;
20821 op1 = tsubst_copy_and_build (op1, args, complain, in_decl);
20822 --cp_unevaluated_operand;
20823 --c_inhibit_evaluation_warnings;
20824 RETURN (objc_build_encode_expr (op1));
20827 case NOEXCEPT_EXPR:
20828 op1 = TREE_OPERAND (t, 0);
20829 ++cp_unevaluated_operand;
20830 ++c_inhibit_evaluation_warnings;
20831 ++cp_noexcept_operand;
20832 op1 = tsubst_copy_and_build (op1, args, complain, in_decl);
20833 --cp_unevaluated_operand;
20834 --c_inhibit_evaluation_warnings;
20835 --cp_noexcept_operand;
20836 RETURN (finish_noexcept_expr (op1, complain));
20838 case MODOP_EXPR:
20840 warning_sentinel s(warn_div_by_zero);
20841 tree lhs = RECUR (TREE_OPERAND (t, 0));
20842 tree rhs = RECUR (TREE_OPERAND (t, 2));
20844 tree r = build_x_modify_expr
20845 (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
20846 templated_operator_saved_lookups (t),
20847 complain|decltype_flag);
20848 /* TREE_NO_WARNING must be set if either the expression was
20849 parenthesized or it uses an operator such as >>= rather
20850 than plain assignment. In the former case, it was already
20851 set and must be copied. In the latter case,
20852 build_x_modify_expr sets it and it must not be reset
20853 here. */
20854 if (warning_suppressed_p (t, OPT_Wparentheses))
20855 suppress_warning (r, OPT_Wparentheses);
20857 RETURN (r);
20860 case ARROW_EXPR:
20861 op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20862 args, complain, in_decl);
20863 /* Remember that there was a reference to this entity. */
20864 if (DECL_P (op1)
20865 && !mark_used (op1, complain) && !(complain & tf_error))
20866 RETURN (error_mark_node);
20867 RETURN (build_x_arrow (input_location, op1, complain));
20869 case NEW_EXPR:
20871 tree placement = RECUR (TREE_OPERAND (t, 0));
20872 tree init = RECUR (TREE_OPERAND (t, 3));
20873 vec<tree, va_gc> *placement_vec;
20874 vec<tree, va_gc> *init_vec;
20875 tree ret;
20876 location_t loc = EXPR_LOCATION (t);
20878 if (placement == NULL_TREE)
20879 placement_vec = NULL;
20880 else if (placement == error_mark_node)
20881 RETURN (error_mark_node);
20882 else
20884 placement_vec = make_tree_vector ();
20885 for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
20886 vec_safe_push (placement_vec, TREE_VALUE (placement));
20889 /* If there was an initializer in the original tree, but it
20890 instantiated to an empty list, then we should pass a
20891 non-NULL empty vector to tell build_new that it was an
20892 empty initializer() rather than no initializer. This can
20893 only happen when the initializer is a pack expansion whose
20894 parameter packs are of length zero. */
20895 if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
20896 init_vec = NULL;
20897 else if (init == error_mark_node)
20898 RETURN (error_mark_node);
20899 else
20901 init_vec = make_tree_vector ();
20902 if (init == void_node)
20903 gcc_assert (init_vec != NULL);
20904 else
20906 for (; init != NULL_TREE; init = TREE_CHAIN (init))
20907 vec_safe_push (init_vec, TREE_VALUE (init));
20911 /* Avoid passing an enclosing decl to valid_array_size_p. */
20912 in_decl = NULL_TREE;
20914 tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
20915 tree op2 = RECUR (TREE_OPERAND (t, 2));
20916 ret = build_new (loc, &placement_vec, op1, op2,
20917 &init_vec, NEW_EXPR_USE_GLOBAL (t),
20918 complain);
20920 if (placement_vec != NULL)
20921 release_tree_vector (placement_vec);
20922 if (init_vec != NULL)
20923 release_tree_vector (init_vec);
20925 RETURN (ret);
20928 case DELETE_EXPR:
20930 tree op0 = RECUR (TREE_OPERAND (t, 0));
20931 tree op1 = RECUR (TREE_OPERAND (t, 1));
20932 RETURN (delete_sanity (input_location, op0, op1,
20933 DELETE_EXPR_USE_VEC (t),
20934 DELETE_EXPR_USE_GLOBAL (t),
20935 complain));
20938 case COMPOUND_EXPR:
20940 tree op0 = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
20941 complain & ~tf_decltype, in_decl);
20942 RETURN (build_x_compound_expr (EXPR_LOCATION (t),
20943 op0,
20944 RECUR (TREE_OPERAND (t, 1)),
20945 templated_operator_saved_lookups (t),
20946 complain|decltype_flag));
20949 case CALL_EXPR:
20951 tree function;
20952 unsigned int nargs;
20953 bool qualified_p;
20954 bool koenig_p;
20955 tree ret;
20957 function = CALL_EXPR_FN (t);
20958 /* Internal function with no arguments. */
20959 if (function == NULL_TREE && call_expr_nargs (t) == 0)
20960 RETURN (t);
20962 /* When we parsed the expression, we determined whether or
20963 not Koenig lookup should be performed. */
20964 koenig_p = KOENIG_LOOKUP_P (t);
20965 if (function == NULL_TREE)
20967 koenig_p = false;
20968 qualified_p = false;
20970 else if (TREE_CODE (function) == SCOPE_REF)
20972 qualified_p = true;
20973 function = tsubst_qualified_id (function, args, complain, in_decl,
20974 /*done=*/false,
20975 /*address_p=*/false);
20977 else if (koenig_p
20978 && (identifier_p (function)
20979 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
20980 && identifier_p (TREE_OPERAND (function, 0)))))
20982 /* Do nothing; calling tsubst_copy_and_build on an identifier
20983 would incorrectly perform unqualified lookup again.
20985 Note that we can also have an IDENTIFIER_NODE if the earlier
20986 unqualified lookup found a dependent local extern declaration
20987 (as per finish_call_expr); in that case koenig_p will be false
20988 and we do want to do the lookup again to find the substituted
20989 declaration. */
20990 qualified_p = false;
20992 if (TREE_CODE (function) == TEMPLATE_ID_EXPR)
20993 /* Use tsubst_copy to substitute through the template arguments
20994 of the template-id without performing unqualified lookup of
20995 the template name. */
20996 function = tsubst_copy (function, args, complain, in_decl);
20998 else
21000 if (TREE_CODE (function) == COMPONENT_REF)
21002 tree op = TREE_OPERAND (function, 1);
21004 qualified_p = (TREE_CODE (op) == SCOPE_REF
21005 || (BASELINK_P (op)
21006 && BASELINK_QUALIFIED_P (op)));
21008 else
21009 qualified_p = false;
21011 if (TREE_CODE (function) == ADDR_EXPR
21012 && TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
21013 /* Avoid error about taking the address of a constructor. */
21014 function = TREE_OPERAND (function, 0);
21016 tsubst_flags_t subcomplain = complain;
21017 if (koenig_p && TREE_CODE (function) == FUNCTION_DECL)
21018 /* When KOENIG_P, we don't want to mark_used the callee before
21019 augmenting the overload set via ADL, so during this initial
21020 substitution we disable mark_used by setting tf_conv (68942). */
21021 subcomplain |= tf_conv;
21022 function = tsubst_copy_and_build (function, args, subcomplain, in_decl);
21024 if (BASELINK_P (function))
21025 qualified_p = true;
21028 nargs = call_expr_nargs (t);
21029 releasing_vec call_args;
21030 tsubst_copy_and_build_call_args (t, args, complain, in_decl,
21031 call_args);
21033 /* Stripped-down processing for a call in a thunk. Specifically, in
21034 the thunk template for a generic lambda. */
21035 if (call_from_lambda_thunk_p (t))
21037 /* Now that we've expanded any packs, the number of call args
21038 might be different. */
21039 unsigned int cargs = call_args->length ();
21040 tree thisarg = NULL_TREE;
21041 if (TREE_CODE (function) == COMPONENT_REF)
21043 thisarg = TREE_OPERAND (function, 0);
21044 if (TREE_CODE (thisarg) == INDIRECT_REF)
21045 thisarg = TREE_OPERAND (thisarg, 0);
21046 function = TREE_OPERAND (function, 1);
21047 if (TREE_CODE (function) == BASELINK)
21048 function = BASELINK_FUNCTIONS (function);
21050 /* We aren't going to do normal overload resolution, so force the
21051 template-id to resolve. */
21052 function = resolve_nondeduced_context (function, complain);
21053 for (unsigned i = 0; i < cargs; ++i)
21055 /* In a thunk, pass through args directly, without any
21056 conversions. */
21057 tree arg = (*call_args)[i];
21058 while (TREE_CODE (arg) != PARM_DECL)
21059 arg = TREE_OPERAND (arg, 0);
21060 (*call_args)[i] = arg;
21062 if (thisarg)
21064 /* If there are no other args, just push 'this'. */
21065 if (cargs == 0)
21066 vec_safe_push (call_args, thisarg);
21067 else
21069 /* Otherwise, shift the other args over to make room. */
21070 tree last = (*call_args)[cargs - 1];
21071 vec_safe_push (call_args, last);
21072 for (int i = cargs - 1; i > 0; --i)
21073 (*call_args)[i] = (*call_args)[i - 1];
21074 (*call_args)[0] = thisarg;
21077 ret = build_call_a (function, call_args->length (),
21078 call_args->address ());
21079 /* The thunk location is not interesting. */
21080 SET_EXPR_LOCATION (ret, UNKNOWN_LOCATION);
21081 CALL_FROM_THUNK_P (ret) = true;
21082 if (CLASS_TYPE_P (TREE_TYPE (ret)))
21083 CALL_EXPR_RETURN_SLOT_OPT (ret) = true;
21085 RETURN (ret);
21088 /* We do not perform argument-dependent lookup if normal
21089 lookup finds a non-function, in accordance with the
21090 resolution of DR 218. */
21091 if (koenig_p
21092 && ((is_overloaded_fn (function)
21093 /* If lookup found a member function, the Koenig lookup is
21094 not appropriate, even if an unqualified-name was used
21095 to denote the function. */
21096 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
21097 || identifier_p (function)
21098 /* C++20 P0846: Lookup found nothing. */
21099 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
21100 && identifier_p (TREE_OPERAND (function, 0))))
21101 /* Only do this when substitution turns a dependent call
21102 into a non-dependent call. */
21103 && type_dependent_expression_p_push (t)
21104 && !any_type_dependent_arguments_p (call_args))
21105 function = perform_koenig_lookup (function, call_args, tf_none);
21107 if (function != NULL_TREE
21108 && (identifier_p (function)
21109 || (TREE_CODE (function) == TEMPLATE_ID_EXPR
21110 && identifier_p (TREE_OPERAND (function, 0))
21111 && !any_dependent_template_arguments_p (TREE_OPERAND
21112 (function, 1))))
21113 && !any_type_dependent_arguments_p (call_args))
21115 bool template_id_p = (TREE_CODE (function) == TEMPLATE_ID_EXPR);
21116 if (template_id_p)
21117 function = TREE_OPERAND (function, 0);
21118 if (koenig_p && (complain & tf_warning_or_error))
21120 /* For backwards compatibility and good diagnostics, try
21121 the unqualified lookup again if we aren't in SFINAE
21122 context. */
21123 tree unq = tsubst_copy_and_build (function, args,
21124 complain, in_decl);
21125 if (unq == error_mark_node)
21126 RETURN (error_mark_node);
21128 if (unq != function)
21130 char const *const msg
21131 = G_("%qD was not declared in this scope, "
21132 "and no declarations were found by "
21133 "argument-dependent lookup at the point "
21134 "of instantiation");
21136 bool in_lambda = (current_class_type
21137 && LAMBDA_TYPE_P (current_class_type));
21138 /* In a lambda fn, we have to be careful to not
21139 introduce new this captures. Legacy code can't
21140 be using lambdas anyway, so it's ok to be
21141 stricter. Be strict with C++20 template-id ADL too.
21142 And be strict if we're already failing anyway. */
21143 bool strict = in_lambda || template_id_p || seen_error();
21144 bool diag = true;
21145 if (strict)
21146 error_at (cp_expr_loc_or_input_loc (t),
21147 msg, function);
21148 else
21149 diag = permerror (cp_expr_loc_or_input_loc (t),
21150 msg, function);
21151 if (diag)
21153 tree fn = unq;
21155 if (INDIRECT_REF_P (fn))
21156 fn = TREE_OPERAND (fn, 0);
21157 if (is_overloaded_fn (fn))
21158 fn = get_first_fn (fn);
21160 if (!DECL_P (fn))
21161 /* Can't say anything more. */;
21162 else if (DECL_CLASS_SCOPE_P (fn))
21164 location_t loc = cp_expr_loc_or_input_loc (t);
21165 inform (loc,
21166 "declarations in dependent base %qT are "
21167 "not found by unqualified lookup",
21168 DECL_CLASS_CONTEXT (fn));
21169 if (current_class_ptr)
21170 inform (loc,
21171 "use %<this->%D%> instead", function);
21172 else
21173 inform (loc,
21174 "use %<%T::%D%> instead",
21175 current_class_name, function);
21177 else
21178 inform (DECL_SOURCE_LOCATION (fn),
21179 "%qD declared here, later in the "
21180 "translation unit", fn);
21181 if (strict)
21182 RETURN (error_mark_node);
21185 function = unq;
21188 if (identifier_p (function))
21190 if (complain & tf_error)
21191 unqualified_name_lookup_error (function);
21192 RETURN (error_mark_node);
21196 /* Remember that there was a reference to this entity. */
21197 if (function != NULL_TREE
21198 && DECL_P (function)
21199 && !mark_used (function, complain) && !(complain & tf_error))
21200 RETURN (error_mark_node);
21202 if (!maybe_fold_fn_template_args (function, complain))
21203 return error_mark_node;
21205 /* Put back tf_decltype for the actual call. */
21206 complain |= decltype_flag;
21208 if (function == NULL_TREE)
21209 switch (CALL_EXPR_IFN (t))
21211 case IFN_LAUNDER:
21212 gcc_assert (nargs == 1);
21213 if (vec_safe_length (call_args) != 1)
21215 error_at (cp_expr_loc_or_input_loc (t),
21216 "wrong number of arguments to "
21217 "%<__builtin_launder%>");
21218 ret = error_mark_node;
21220 else
21221 ret = finish_builtin_launder (cp_expr_loc_or_input_loc (t),
21222 (*call_args)[0], complain);
21223 break;
21225 case IFN_VEC_CONVERT:
21226 gcc_assert (nargs == 1);
21227 if (vec_safe_length (call_args) != 1)
21229 error_at (cp_expr_loc_or_input_loc (t),
21230 "wrong number of arguments to "
21231 "%<__builtin_convertvector%>");
21232 ret = error_mark_node;
21233 break;
21235 ret = cp_build_vec_convert ((*call_args)[0], input_location,
21236 tsubst (TREE_TYPE (t), args,
21237 complain, in_decl),
21238 complain);
21239 if (TREE_CODE (ret) == VIEW_CONVERT_EXPR)
21240 RETURN (ret);
21241 break;
21243 case IFN_SHUFFLEVECTOR:
21245 ret = build_x_shufflevector (input_location, call_args,
21246 complain);
21247 if (ret != error_mark_node)
21248 RETURN (ret);
21249 break;
21252 case IFN_ASSUME:
21253 gcc_assert (nargs == 1);
21254 if (vec_safe_length (call_args) != 1)
21256 error_at (cp_expr_loc_or_input_loc (t),
21257 "wrong number of arguments to "
21258 "%<assume%> attribute");
21259 ret = error_mark_node;
21261 else
21263 tree &arg = (*call_args)[0];
21264 if (!type_dependent_expression_p (arg))
21265 arg = contextual_conv_bool (arg, tf_warning_or_error);
21266 if (error_operand_p (arg))
21268 ret = error_mark_node;
21269 break;
21271 ret = build_assume_call (EXPR_LOCATION (t), arg);
21272 RETURN (ret);
21274 break;
21276 default:
21277 /* Unsupported internal function with arguments. */
21278 gcc_unreachable ();
21280 else if (TREE_CODE (function) == OFFSET_REF
21281 || TREE_CODE (function) == DOTSTAR_EXPR
21282 || TREE_CODE (function) == MEMBER_REF)
21283 ret = build_offset_ref_call_from_tree (function, &call_args,
21284 complain);
21285 else if (TREE_CODE (function) == COMPONENT_REF)
21287 tree instance = TREE_OPERAND (function, 0);
21288 tree fn = TREE_OPERAND (function, 1);
21290 if (processing_template_decl
21291 && (type_dependent_expression_p (instance)
21292 || (!BASELINK_P (fn)
21293 && TREE_CODE (fn) != FIELD_DECL)
21294 || type_dependent_expression_p (fn)
21295 || any_type_dependent_arguments_p (call_args)))
21296 ret = build_min_nt_call_vec (function, call_args);
21297 else if (!BASELINK_P (fn))
21298 ret = finish_call_expr (function, &call_args,
21299 /*disallow_virtual=*/false,
21300 /*koenig_p=*/false,
21301 complain);
21302 else
21303 ret = (build_new_method_call
21304 (instance, fn,
21305 &call_args, NULL_TREE,
21306 qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
21307 /*fn_p=*/NULL,
21308 complain));
21310 else if (concept_check_p (function))
21312 /* FUNCTION is a template-id referring to a concept definition. */
21313 tree id = unpack_concept_check (function);
21314 tree tmpl = TREE_OPERAND (id, 0);
21315 tree args = TREE_OPERAND (id, 1);
21317 /* Calls to standard and variable concepts should have been
21318 previously diagnosed. */
21319 gcc_assert (function_concept_p (tmpl));
21321 /* Ensure the result is wrapped as a call expression. */
21322 ret = build_concept_check (tmpl, args, tf_warning_or_error);
21324 else
21325 ret = finish_call_expr (function, &call_args,
21326 /*disallow_virtual=*/qualified_p,
21327 koenig_p,
21328 complain);
21330 if (ret != error_mark_node)
21332 bool op = CALL_EXPR_OPERATOR_SYNTAX (t);
21333 bool ord = CALL_EXPR_ORDERED_ARGS (t);
21334 bool rev = CALL_EXPR_REVERSE_ARGS (t);
21335 if (op || ord || rev)
21336 if (tree call = extract_call_expr (ret))
21338 CALL_EXPR_OPERATOR_SYNTAX (call) = op;
21339 CALL_EXPR_ORDERED_ARGS (call) = ord;
21340 CALL_EXPR_REVERSE_ARGS (call) = rev;
21342 if (warning_suppressed_p (t, OPT_Wpessimizing_move))
21343 /* This also suppresses -Wredundant-move. */
21344 suppress_warning (ret, OPT_Wpessimizing_move);
21347 RETURN (ret);
21350 case COND_EXPR:
21352 tree cond = RECUR (TREE_OPERAND (t, 0));
21353 cond = mark_rvalue_use (cond);
21354 tree folded_cond = fold_non_dependent_expr (cond, complain);
21355 tree exp1, exp2;
21357 if (TREE_CODE (folded_cond) == INTEGER_CST)
21359 if (integer_zerop (folded_cond))
21361 ++c_inhibit_evaluation_warnings;
21362 exp1 = RECUR (TREE_OPERAND (t, 1));
21363 --c_inhibit_evaluation_warnings;
21364 exp2 = RECUR (TREE_OPERAND (t, 2));
21366 else
21368 exp1 = RECUR (TREE_OPERAND (t, 1));
21369 ++c_inhibit_evaluation_warnings;
21370 exp2 = RECUR (TREE_OPERAND (t, 2));
21371 --c_inhibit_evaluation_warnings;
21373 cond = folded_cond;
21375 else
21377 exp1 = RECUR (TREE_OPERAND (t, 1));
21378 exp2 = RECUR (TREE_OPERAND (t, 2));
21381 warning_sentinel s(warn_duplicated_branches);
21382 RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
21383 cond, exp1, exp2, complain));
21386 case PSEUDO_DTOR_EXPR:
21388 tree op0 = RECUR (TREE_OPERAND (t, 0));
21389 tree op1 = RECUR (TREE_OPERAND (t, 1));
21390 tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
21391 RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
21392 input_location));
21395 case TREE_LIST:
21396 RETURN (tsubst_tree_list (t, args, complain, in_decl));
21398 case COMPONENT_REF:
21400 tree object;
21401 tree object_type;
21402 tree member;
21403 tree r;
21405 object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
21406 args, complain, in_decl);
21407 /* Remember that there was a reference to this entity. */
21408 if (DECL_P (object)
21409 && !mark_used (object, complain) && !(complain & tf_error))
21410 RETURN (error_mark_node);
21411 object_type = TREE_TYPE (object);
21413 member = TREE_OPERAND (t, 1);
21414 if (BASELINK_P (member))
21415 member = tsubst_baselink (member,
21416 non_reference (TREE_TYPE (object)),
21417 args, complain, in_decl);
21418 else
21419 member = tsubst_copy (member, args, complain, in_decl);
21420 if (member == error_mark_node)
21421 RETURN (error_mark_node);
21423 if (object_type && TYPE_PTRMEMFUNC_P (object_type)
21424 && TREE_CODE (member) == FIELD_DECL)
21426 r = build_ptrmemfunc_access_expr (object, DECL_NAME (member));
21427 RETURN (r);
21429 else if (TREE_CODE (member) == FIELD_DECL)
21431 r = finish_non_static_data_member (member, object, NULL_TREE,
21432 complain);
21433 if (TREE_CODE (r) == COMPONENT_REF)
21434 REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
21435 RETURN (r);
21437 else if (type_dependent_expression_p (object))
21438 /* We can't do much here. */;
21439 else if (!CLASS_TYPE_P (object_type))
21441 if (scalarish_type_p (object_type))
21443 tree s = NULL_TREE;
21444 tree dtor = member;
21446 if (TREE_CODE (dtor) == SCOPE_REF)
21448 s = TREE_OPERAND (dtor, 0);
21449 dtor = TREE_OPERAND (dtor, 1);
21451 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
21453 dtor = TREE_OPERAND (dtor, 0);
21454 if (TYPE_P (dtor))
21455 RETURN (finish_pseudo_destructor_expr
21456 (object, s, dtor, input_location));
21460 else if (TREE_CODE (member) == SCOPE_REF
21461 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
21463 /* Lookup the template functions now that we know what the
21464 scope is. */
21465 tree scope = TREE_OPERAND (member, 0);
21466 tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
21467 tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
21468 member = lookup_qualified_name (scope, tmpl, LOOK_want::NORMAL,
21469 /*complain=*/false);
21470 if (BASELINK_P (member))
21472 BASELINK_FUNCTIONS (member)
21473 = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
21474 args);
21475 member = (adjust_result_of_qualified_name_lookup
21476 (member, BINFO_TYPE (BASELINK_BINFO (member)),
21477 object_type));
21479 else
21481 qualified_name_lookup_error (scope, tmpl, member,
21482 input_location);
21483 RETURN (error_mark_node);
21486 else if (TREE_CODE (member) == SCOPE_REF
21487 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
21488 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
21490 if (complain & tf_error)
21492 if (TYPE_P (TREE_OPERAND (member, 0)))
21493 error ("%qT is not a class or namespace",
21494 TREE_OPERAND (member, 0));
21495 else
21496 error ("%qD is not a class or namespace",
21497 TREE_OPERAND (member, 0));
21499 RETURN (error_mark_node);
21502 r = finish_class_member_access_expr (object, member,
21503 /*template_p=*/false,
21504 complain);
21505 if (REF_PARENTHESIZED_P (t))
21506 r = force_paren_expr (r);
21507 RETURN (r);
21510 case THROW_EXPR:
21511 RETURN (build_throw
21512 (input_location, RECUR (TREE_OPERAND (t, 0))));
21514 case CONSTRUCTOR:
21516 vec<constructor_elt, va_gc> *n;
21517 constructor_elt *ce;
21518 unsigned HOST_WIDE_INT idx;
21519 bool process_index_p;
21520 int newlen;
21521 bool need_copy_p = false;
21522 tree r;
21524 tsubst_flags_t tcomplain = complain;
21525 if (COMPOUND_LITERAL_P (t))
21526 tcomplain |= tf_tst_ok;
21527 tree type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
21528 if (type == error_mark_node)
21529 RETURN (error_mark_node);
21531 /* We do not want to process the index of aggregate
21532 initializers as they are identifier nodes which will be
21533 looked up by digest_init. */
21534 process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
21536 if (null_member_pointer_value_p (t))
21538 gcc_assert (same_type_p (type, TREE_TYPE (t)));
21539 RETURN (t);
21542 n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
21543 newlen = vec_safe_length (n);
21544 FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
21546 if (ce->index && process_index_p
21547 /* An identifier index is looked up in the type
21548 being initialized, not the current scope. */
21549 && TREE_CODE (ce->index) != IDENTIFIER_NODE)
21550 ce->index = RECUR (ce->index);
21552 if (PACK_EXPANSION_P (ce->value))
21554 /* Substitute into the pack expansion. */
21555 ce->value = tsubst_pack_expansion (ce->value, args, complain,
21556 in_decl);
21558 if (ce->value == error_mark_node
21559 || PACK_EXPANSION_P (ce->value))
21561 else if (TREE_VEC_LENGTH (ce->value) == 1)
21562 /* Just move the argument into place. */
21563 ce->value = TREE_VEC_ELT (ce->value, 0);
21564 else
21566 /* Update the length of the final CONSTRUCTOR
21567 arguments vector, and note that we will need to
21568 copy.*/
21569 newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
21570 need_copy_p = true;
21573 else
21574 ce->value = RECUR (ce->value);
21577 if (need_copy_p)
21579 vec<constructor_elt, va_gc> *old_n = n;
21581 vec_alloc (n, newlen);
21582 FOR_EACH_VEC_ELT (*old_n, idx, ce)
21584 if (TREE_CODE (ce->value) == TREE_VEC)
21586 int i, len = TREE_VEC_LENGTH (ce->value);
21587 for (i = 0; i < len; ++i)
21588 CONSTRUCTOR_APPEND_ELT (n, 0,
21589 TREE_VEC_ELT (ce->value, i));
21591 else
21592 CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
21596 r = build_constructor (init_list_type_node, n);
21597 CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
21598 CONSTRUCTOR_IS_DESIGNATED_INIT (r)
21599 = CONSTRUCTOR_IS_DESIGNATED_INIT (t);
21601 if (TREE_HAS_CONSTRUCTOR (t))
21603 fcl_t cl = fcl_functional;
21604 if (CONSTRUCTOR_C99_COMPOUND_LITERAL (t))
21605 cl = fcl_c99;
21606 RETURN (finish_compound_literal (type, r, complain, cl));
21609 TREE_TYPE (r) = type;
21610 RETURN (r);
21613 case TYPEID_EXPR:
21615 tree operand_0 = TREE_OPERAND (t, 0);
21616 if (TYPE_P (operand_0))
21618 operand_0 = tsubst (operand_0, args, complain, in_decl);
21619 RETURN (get_typeid (operand_0, complain));
21621 else
21623 operand_0 = RECUR (operand_0);
21624 RETURN (build_typeid (operand_0, complain));
21628 case VAR_DECL:
21629 if (!args)
21630 RETURN (t);
21631 /* Fall through */
21633 case PARM_DECL:
21635 tree r = tsubst_copy (t, args, complain, in_decl);
21636 /* ??? We're doing a subset of finish_id_expression here. */
21637 if (tree wrap = maybe_get_tls_wrapper_call (r))
21638 /* Replace an evaluated use of the thread_local variable with
21639 a call to its wrapper. */
21640 r = wrap;
21641 else if (outer_automatic_var_p (r))
21642 r = process_outer_var_ref (r, complain);
21644 if (!TYPE_REF_P (TREE_TYPE (t)))
21645 /* If the original type was a reference, we'll be wrapped in
21646 the appropriate INDIRECT_REF. */
21647 r = convert_from_reference (r);
21648 RETURN (r);
21651 case VA_ARG_EXPR:
21653 tree op0 = RECUR (TREE_OPERAND (t, 0));
21654 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21655 RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
21658 case OFFSETOF_EXPR:
21660 tree object_ptr
21661 = tsubst_copy_and_build (TREE_OPERAND (t, 1), args,
21662 complain, in_decl);
21663 RETURN (finish_offsetof (object_ptr,
21664 RECUR (TREE_OPERAND (t, 0)),
21665 EXPR_LOCATION (t)));
21668 case ADDRESSOF_EXPR:
21669 RETURN (cp_build_addressof (EXPR_LOCATION (t),
21670 RECUR (TREE_OPERAND (t, 0)), complain));
21672 case TRAIT_EXPR:
21674 tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
21675 complain, in_decl);
21676 tree type2 = tsubst (TRAIT_EXPR_TYPE2 (t), args,
21677 complain, in_decl);
21678 RETURN (finish_trait_expr (TRAIT_EXPR_LOCATION (t),
21679 TRAIT_EXPR_KIND (t), type1, type2));
21682 case STMT_EXPR:
21684 tree old_stmt_expr = cur_stmt_expr;
21685 tree stmt_expr = begin_stmt_expr ();
21687 cur_stmt_expr = stmt_expr;
21688 tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl);
21689 stmt_expr = finish_stmt_expr (stmt_expr, false);
21690 cur_stmt_expr = old_stmt_expr;
21692 /* If the resulting list of expression statement is empty,
21693 fold it further into void_node. */
21694 if (empty_expr_stmt_p (stmt_expr))
21695 stmt_expr = void_node;
21697 RETURN (stmt_expr);
21700 case LAMBDA_EXPR:
21702 if (complain & tf_partial)
21704 /* We don't have a full set of template arguments yet; don't touch
21705 the lambda at all. */
21706 gcc_assert (processing_template_decl);
21707 return t;
21709 tree r = tsubst_lambda_expr (t, args, complain, in_decl);
21711 RETURN (build_lambda_object (r));
21714 case TRANSACTION_EXPR:
21715 RETURN (tsubst_expr (t, args, complain, in_decl));
21717 case PAREN_EXPR:
21718 if (REF_PARENTHESIZED_P (t))
21719 RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
21720 else
21721 /* Recreate the PAREN_EXPR from __builtin_assoc_barrier. */
21723 tree op0 = RECUR (TREE_OPERAND (t, 0));
21724 RETURN (build1_loc (input_location, PAREN_EXPR,
21725 TREE_TYPE (op0), op0));
21728 case VEC_PERM_EXPR:
21730 tree op0 = RECUR (TREE_OPERAND (t, 0));
21731 tree op1 = RECUR (TREE_OPERAND (t, 1));
21732 tree op2 = RECUR (TREE_OPERAND (t, 2));
21733 RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
21734 complain));
21737 case REQUIRES_EXPR:
21739 tree r = tsubst_requires_expr (t, args, tf_none, in_decl);
21740 RETURN (r);
21743 case RANGE_EXPR:
21744 /* No need to substitute further, a RANGE_EXPR will always be built
21745 with constant operands. */
21746 RETURN (t);
21748 case NON_LVALUE_EXPR:
21749 case VIEW_CONVERT_EXPR:
21751 tree op = RECUR (TREE_OPERAND (t, 0));
21753 if (location_wrapper_p (t))
21754 /* We need to do this here as well as in tsubst_copy so we get the
21755 other tsubst_copy_and_build semantics for a PARM_DECL operand. */
21756 RETURN (maybe_wrap_with_location (op, EXPR_LOCATION (t)));
21758 gcc_checking_assert (TREE_CODE (t) == VIEW_CONVERT_EXPR);
21759 if (REF_PARENTHESIZED_P (t))
21760 /* force_paren_expr can also create a VIEW_CONVERT_EXPR. */
21761 RETURN (finish_parenthesized_expr (op));
21763 /* Otherwise, we're dealing with a wrapper to make a C++20 template
21764 parameter object const. */
21765 if (TREE_TYPE (op) == NULL_TREE
21766 || !CP_TYPE_CONST_P (TREE_TYPE (op)))
21768 /* The template argument is not const, presumably because
21769 it is still dependent, and so not the const template parm
21770 object. */
21771 tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
21772 if (TREE_CODE (op) == CONSTRUCTOR
21773 || TREE_CODE (op) == IMPLICIT_CONV_EXPR)
21775 /* Don't add a wrapper to these. */
21776 op = copy_node (op);
21777 TREE_TYPE (op) = type;
21779 else
21780 /* Do add a wrapper otherwise (in particular, if op is
21781 another TEMPLATE_PARM_INDEX). */
21782 op = build1 (VIEW_CONVERT_EXPR, type, op);
21784 RETURN (op);
21787 default:
21788 /* Handle Objective-C++ constructs, if appropriate. */
21790 tree subst
21791 = objcp_tsubst_copy_and_build (t, args, complain, in_decl);
21792 if (subst)
21793 RETURN (subst);
21795 RETURN (tsubst_copy (t, args, complain, in_decl));
21798 #undef RECUR
21799 #undef RETURN
21800 out:
21801 input_location = save_loc;
21802 return retval;
21805 /* Verify that the instantiated ARGS are valid. For type arguments,
21806 make sure that the type's linkage is ok. For non-type arguments,
21807 make sure they are constants if they are integral or enumerations.
21808 Emit an error under control of COMPLAIN, and return TRUE on error. */
21810 static bool
21811 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
21813 if (dependent_template_arg_p (t))
21814 return false;
21815 if (ARGUMENT_PACK_P (t))
21817 tree vec = ARGUMENT_PACK_ARGS (t);
21818 int len = TREE_VEC_LENGTH (vec);
21819 bool result = false;
21820 int i;
21822 for (i = 0; i < len; ++i)
21823 if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
21824 result = true;
21825 return result;
21827 else if (TYPE_P (t))
21829 /* [basic.link]: A name with no linkage (notably, the name
21830 of a class or enumeration declared in a local scope)
21831 shall not be used to declare an entity with linkage.
21832 This implies that names with no linkage cannot be used as
21833 template arguments
21835 DR 757 relaxes this restriction for C++0x. */
21836 tree nt = (cxx_dialect > cxx98 ? NULL_TREE
21837 : no_linkage_check (t, /*relaxed_p=*/false));
21839 if (nt)
21841 /* DR 488 makes use of a type with no linkage cause
21842 type deduction to fail. */
21843 if (complain & tf_error)
21845 if (TYPE_UNNAMED_P (nt))
21846 error ("%qT is/uses unnamed type", t);
21847 else
21848 error ("template argument for %qD uses local type %qT",
21849 tmpl, t);
21851 return true;
21853 /* In order to avoid all sorts of complications, we do not
21854 allow variably-modified types as template arguments. */
21855 else if (variably_modified_type_p (t, NULL_TREE))
21857 if (complain & tf_error)
21858 error ("%qT is a variably modified type", t);
21859 return true;
21862 /* Class template and alias template arguments should be OK. */
21863 else if (DECL_TYPE_TEMPLATE_P (t))
21865 /* A non-type argument of integral or enumerated type must be a
21866 constant. */
21867 else if (TREE_TYPE (t)
21868 && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
21869 && !REFERENCE_REF_P (t)
21870 && !TREE_CONSTANT (t))
21872 if (complain & tf_error)
21873 error ("integral expression %qE is not constant", t);
21874 return true;
21876 return false;
21879 static bool
21880 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
21882 int ix, len = DECL_NTPARMS (tmpl);
21883 bool result = false;
21885 for (ix = 0; ix != len; ix++)
21887 if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
21888 result = true;
21890 if (result && (complain & tf_error))
21891 error (" trying to instantiate %qD", tmpl);
21892 return result;
21895 /* Call mark_used on each entity within the non-type template arguments in
21896 ARGS for an instantiation of TMPL, to ensure that each such entity is
21897 considered odr-used (and therefore marked for instantiation) regardless of
21898 whether the specialization was first formed in a template context (which
21899 inhibits mark_used).
21901 This function assumes push_to_top_level has been called beforehand. */
21903 static void
21904 mark_template_arguments_used (tree tmpl, tree args)
21906 /* It suffices to do this only when instantiating a primary template. */
21907 if (TREE_CODE (tmpl) != TEMPLATE_DECL || !PRIMARY_TEMPLATE_P (tmpl))
21908 return;
21910 /* We already marked outer arguments when specializing the context. */
21911 args = INNERMOST_TEMPLATE_ARGS (args);
21913 for (tree arg : tree_vec_range (args))
21915 /* A (pointer/reference to) function or variable NTTP argument. */
21916 if (TREE_CODE (arg) == ADDR_EXPR
21917 || TREE_CODE (arg) == INDIRECT_REF)
21919 while (TREE_CODE (arg) == ADDR_EXPR
21920 || REFERENCE_REF_P (arg)
21921 || CONVERT_EXPR_P (arg))
21922 arg = TREE_OPERAND (arg, 0);
21923 if (VAR_OR_FUNCTION_DECL_P (arg))
21925 /* Pass tf_none to avoid duplicate diagnostics: if this call
21926 fails then an earlier call to mark_used for this argument
21927 must have also failed and emitted a diagnostic. */
21928 bool ok = mark_used (arg, tf_none);
21929 gcc_checking_assert (ok || seen_error ());
21932 /* A class NTTP argument. */
21933 else if (VAR_P (arg)
21934 && DECL_NTTP_OBJECT_P (arg))
21936 auto mark_used_r = [](tree *tp, int *, void *) {
21937 if (VAR_OR_FUNCTION_DECL_P (*tp))
21939 bool ok = mark_used (*tp, tf_none);
21940 gcc_checking_assert (ok || seen_error ());
21942 return NULL_TREE;
21944 cp_walk_tree_without_duplicates (&DECL_INITIAL (arg),
21945 mark_used_r, nullptr);
21950 /* We're out of SFINAE context now, so generate diagnostics for the access
21951 errors we saw earlier when instantiating D from TMPL and ARGS. */
21953 static void
21954 recheck_decl_substitution (tree d, tree tmpl, tree args)
21956 tree pattern = DECL_TEMPLATE_RESULT (tmpl);
21957 tree type = TREE_TYPE (pattern);
21958 location_t loc = input_location;
21960 push_access_scope (d);
21961 push_deferring_access_checks (dk_no_deferred);
21962 input_location = DECL_SOURCE_LOCATION (pattern);
21963 tsubst (type, args, tf_warning_or_error, d);
21964 input_location = loc;
21965 pop_deferring_access_checks ();
21966 pop_access_scope (d);
21969 /* Instantiate the indicated variable, function, or alias template TMPL with
21970 the template arguments in TARG_PTR. */
21972 tree
21973 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
21975 auto_timevar tv (TV_TEMPLATE_INST);
21977 tree targ_ptr = orig_args;
21978 tree fndecl;
21979 tree gen_tmpl;
21980 tree spec;
21981 bool access_ok = true;
21983 if (tmpl == error_mark_node)
21984 return error_mark_node;
21986 gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
21988 if (modules_p ())
21989 lazy_load_pendings (tmpl);
21991 /* If this function is a clone, handle it specially. */
21992 if (DECL_CLONED_FUNCTION_P (tmpl))
21994 tree spec;
21995 tree clone;
21997 /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
21998 DECL_CLONED_FUNCTION. */
21999 spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
22000 targ_ptr, complain);
22001 if (spec == error_mark_node)
22002 return error_mark_node;
22004 /* Look for the clone. */
22005 FOR_EACH_CLONE (clone, spec)
22006 if (DECL_NAME (clone) == DECL_NAME (tmpl))
22007 return clone;
22008 /* We should always have found the clone by now. */
22009 gcc_unreachable ();
22010 return NULL_TREE;
22013 if (targ_ptr == error_mark_node)
22014 return error_mark_node;
22016 /* Check to see if we already have this specialization. */
22017 gen_tmpl = most_general_template (tmpl);
22018 if (TMPL_ARGS_DEPTH (targ_ptr)
22019 < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)))
22020 /* targ_ptr only has the innermost template args, so add the outer ones
22021 from tmpl, which could be either a partial instantiation or gen_tmpl (in
22022 the case of a non-dependent call within a template definition). */
22023 targ_ptr = (add_outermost_template_args
22024 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (tmpl)),
22025 targ_ptr));
22027 /* It would be nice to avoid hashing here and then again in tsubst_decl,
22028 but it doesn't seem to be on the hot path. */
22029 spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
22031 gcc_checking_assert (tmpl == gen_tmpl
22032 || ((fndecl
22033 = retrieve_specialization (tmpl, orig_args, 0))
22034 == spec)
22035 || fndecl == NULL_TREE);
22037 if (spec != NULL_TREE)
22039 if (FNDECL_HAS_ACCESS_ERRORS (spec))
22041 if (complain & tf_error)
22042 recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
22043 return error_mark_node;
22045 return spec;
22048 if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
22049 complain))
22050 return error_mark_node;
22052 /* We are building a FUNCTION_DECL, during which the access of its
22053 parameters and return types have to be checked. However this
22054 FUNCTION_DECL which is the desired context for access checking
22055 is not built yet. We solve this chicken-and-egg problem by
22056 deferring all checks until we have the FUNCTION_DECL. */
22057 push_deferring_access_checks (dk_deferred);
22059 /* Instantiation of the function happens in the context of the function
22060 template, not the context of the overload resolution we're doing. */
22061 push_to_top_level ();
22062 /* If there are dependent arguments, e.g. because we're doing partial
22063 ordering, make sure processing_template_decl stays set. */
22064 if (uses_template_parms (targ_ptr))
22065 ++processing_template_decl;
22066 if (DECL_CLASS_SCOPE_P (gen_tmpl))
22068 tree ctx;
22069 if (!uses_template_parms (DECL_CONTEXT (tmpl)))
22070 /* If the context of the partially instantiated template is
22071 already non-dependent, then we might as well use it. */
22072 ctx = DECL_CONTEXT (tmpl);
22073 else
22074 ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
22075 complain, gen_tmpl, true);
22076 push_nested_class (ctx);
22079 tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
22081 fndecl = NULL_TREE;
22082 if (VAR_P (pattern))
22084 /* We need to determine if we're using a partial or explicit
22085 specialization now, because the type of the variable could be
22086 different. */
22087 tree tid = lookup_template_variable (tmpl, targ_ptr);
22088 tree elt = most_specialized_partial_spec (tid, complain);
22089 if (elt == error_mark_node)
22090 pattern = error_mark_node;
22091 else if (elt)
22093 tree partial_tmpl = TREE_VALUE (elt);
22094 tree partial_args = TREE_PURPOSE (elt);
22095 tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
22096 fndecl = tsubst (partial_pat, partial_args, complain, gen_tmpl);
22100 /* Substitute template parameters to obtain the specialization. */
22101 if (fndecl == NULL_TREE)
22102 fndecl = tsubst (pattern, targ_ptr, complain, gen_tmpl);
22103 if (DECL_CLASS_SCOPE_P (gen_tmpl))
22104 pop_nested_class ();
22105 pop_from_top_level ();
22107 if (fndecl == error_mark_node)
22109 pop_deferring_access_checks ();
22110 return error_mark_node;
22113 /* The DECL_TI_TEMPLATE should always be the immediate parent
22114 template, not the most general template. */
22115 DECL_TI_TEMPLATE (fndecl) = tmpl;
22116 DECL_TI_ARGS (fndecl) = targ_ptr;
22118 set_instantiating_module (fndecl);
22120 /* Now we know the specialization, compute access previously
22121 deferred. Do no access control for inheriting constructors,
22122 as we already checked access for the inherited constructor. */
22123 if (!(flag_new_inheriting_ctors
22124 && DECL_INHERITED_CTOR (fndecl)))
22126 push_access_scope (fndecl);
22127 if (!perform_deferred_access_checks (complain))
22128 access_ok = false;
22129 pop_access_scope (fndecl);
22131 pop_deferring_access_checks ();
22133 /* If we've just instantiated the main entry point for a function,
22134 instantiate all the alternate entry points as well. We do this
22135 by cloning the instantiation of the main entry point, not by
22136 instantiating the template clones. */
22137 if (tree chain = DECL_CHAIN (gen_tmpl))
22138 if (DECL_P (chain) && DECL_CLONED_FUNCTION_P (chain))
22139 clone_cdtor (fndecl, /*update_methods=*/false);
22141 if (!access_ok)
22143 if (!(complain & tf_error))
22145 /* Remember to reinstantiate when we're out of SFINAE so the user
22146 can see the errors. */
22147 FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
22149 return error_mark_node;
22152 return fndecl;
22155 /* Instantiate the alias template TMPL with ARGS. Also push a template
22156 instantiation level, which instantiate_template doesn't do because
22157 functions and variables have sufficient context established by the
22158 callers. */
22160 static tree
22161 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
22163 if (tmpl == error_mark_node || args == error_mark_node)
22164 return error_mark_node;
22166 args = coerce_template_parms (DECL_TEMPLATE_PARMS (tmpl),
22167 args, tmpl, complain);
22168 if (args == error_mark_node)
22169 return error_mark_node;
22171 /* FIXME check for satisfaction in check_instantiated_args. */
22172 if (!constraints_satisfied_p (tmpl, args))
22174 if (complain & tf_error)
22176 auto_diagnostic_group d;
22177 error ("template constraint failure for %qD", tmpl);
22178 diagnose_constraints (input_location, tmpl, args);
22180 return error_mark_node;
22183 if (!push_tinst_level (tmpl, args))
22184 return error_mark_node;
22185 tree r = instantiate_template (tmpl, args, complain);
22186 pop_tinst_level ();
22188 if (tree d = dependent_alias_template_spec_p (TREE_TYPE (r), nt_opaque))
22190 /* An alias template specialization can be dependent
22191 even if its underlying type is not. */
22192 TYPE_DEPENDENT_P (d) = true;
22193 TYPE_DEPENDENT_P_VALID (d) = true;
22194 /* Sometimes a dependent alias spec is equivalent to its expansion,
22195 sometimes not. So always use structural_comptypes. */
22196 SET_TYPE_STRUCTURAL_EQUALITY (d);
22199 return r;
22202 /* PARM is a template parameter pack for FN. Returns true iff
22203 PARM is used in a deducible way in the argument list of FN. */
22205 static bool
22206 pack_deducible_p (tree parm, tree fn)
22208 tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
22209 for (; t; t = TREE_CHAIN (t))
22211 tree type = TREE_VALUE (t);
22212 tree packs;
22213 if (!PACK_EXPANSION_P (type))
22214 continue;
22215 for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
22216 packs; packs = TREE_CHAIN (packs))
22217 if (template_args_equal (TREE_VALUE (packs), parm))
22219 /* The template parameter pack is used in a function parameter
22220 pack. If this is the end of the parameter list, the
22221 template parameter pack is deducible. */
22222 if (TREE_CHAIN (t) == void_list_node)
22223 return true;
22224 else
22225 /* Otherwise, not. Well, it could be deduced from
22226 a non-pack parameter, but doing so would end up with
22227 a deduction mismatch, so don't bother. */
22228 return false;
22231 /* The template parameter pack isn't used in any function parameter
22232 packs, but it might be used deeper, e.g. tuple<Args...>. */
22233 return true;
22236 /* Subroutine of fn_type_unification: check non-dependent parms for
22237 convertibility. */
22239 static int
22240 check_non_deducible_conversions (tree parms, const tree *args, unsigned nargs,
22241 tree fn, unification_kind_t strict, int flags,
22242 struct conversion **convs, bool explain_p)
22244 /* Non-constructor methods need to leave a conversion for 'this', which
22245 isn't included in nargs here. */
22246 unsigned offset = (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
22247 && !DECL_CONSTRUCTOR_P (fn));
22249 for (unsigned ia = 0;
22250 parms && parms != void_list_node && ia < nargs; )
22252 tree parm = TREE_VALUE (parms);
22254 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
22255 && (!TREE_CHAIN (parms)
22256 || TREE_CHAIN (parms) == void_list_node))
22257 /* For a function parameter pack that occurs at the end of the
22258 parameter-declaration-list, the type A of each remaining
22259 argument of the call is compared with the type P of the
22260 declarator-id of the function parameter pack. */
22261 break;
22263 parms = TREE_CHAIN (parms);
22265 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
22266 /* For a function parameter pack that does not occur at the
22267 end of the parameter-declaration-list, the type of the
22268 parameter pack is a non-deduced context. */
22269 continue;
22271 if (!uses_template_parms (parm))
22273 tree arg = args[ia];
22274 conversion **conv_p = convs ? &convs[ia+offset] : NULL;
22275 int lflags = conv_flags (ia, nargs, fn, arg, flags);
22277 if (check_non_deducible_conversion (parm, arg, strict, lflags,
22278 conv_p, explain_p))
22279 return 1;
22282 ++ia;
22285 return 0;
22288 /* The FN is a TEMPLATE_DECL for a function. ARGS is an array with
22289 NARGS elements of the arguments that are being used when calling
22290 it. TARGS is a vector into which the deduced template arguments
22291 are placed.
22293 Returns either a FUNCTION_DECL for the matching specialization of FN or
22294 NULL_TREE if no suitable specialization can be found. If EXPLAIN_P is
22295 true, diagnostics will be printed to explain why it failed.
22297 If FN is a conversion operator, or we are trying to produce a specific
22298 specialization, RETURN_TYPE is the return type desired.
22300 The EXPLICIT_TARGS are explicit template arguments provided via a
22301 template-id.
22303 The parameter STRICT is one of:
22305 DEDUCE_CALL:
22306 We are deducing arguments for a function call, as in
22307 [temp.deduct.call]. If RETURN_TYPE is non-null, we are
22308 deducing arguments for a call to the result of a conversion
22309 function template, as in [over.call.object].
22311 DEDUCE_CONV:
22312 We are deducing arguments for a conversion function, as in
22313 [temp.deduct.conv].
22315 DEDUCE_EXACT:
22316 We are deducing arguments when doing an explicit instantiation
22317 as in [temp.explicit], when determining an explicit specialization
22318 as in [temp.expl.spec], or when taking the address of a function
22319 template, as in [temp.deduct.funcaddr]. */
22321 tree
22322 fn_type_unification (tree fn,
22323 tree explicit_targs,
22324 tree targs,
22325 const tree *args,
22326 unsigned int nargs,
22327 tree return_type,
22328 unification_kind_t strict,
22329 int flags,
22330 struct conversion **convs,
22331 bool explain_p,
22332 bool decltype_p)
22334 tree parms;
22335 tree fntype;
22336 tree decl = NULL_TREE;
22337 tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
22338 bool ok;
22339 static int deduction_depth;
22340 /* type_unification_real will pass back any access checks from default
22341 template argument substitution. */
22342 vec<deferred_access_check, va_gc> *checks = NULL;
22343 /* We don't have all the template args yet. */
22344 bool incomplete = true;
22346 tree orig_fn = fn;
22347 if (flag_new_inheriting_ctors)
22348 fn = strip_inheriting_ctors (fn);
22350 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
22351 tree r = error_mark_node;
22353 tree full_targs = targs;
22354 if (TMPL_ARGS_DEPTH (targs)
22355 < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (fn)))
22356 full_targs = (add_outermost_template_args
22357 (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (fn)),
22358 targs));
22360 if (decltype_p)
22361 complain |= tf_decltype;
22363 /* In C++0x, it's possible to have a function template whose type depends
22364 on itself recursively. This is most obvious with decltype, but can also
22365 occur with enumeration scope (c++/48969). So we need to catch infinite
22366 recursion and reject the substitution at deduction time; this function
22367 will return error_mark_node for any repeated substitution.
22369 This also catches excessive recursion such as when f<N> depends on
22370 f<N-1> across all integers, and returns error_mark_node for all the
22371 substitutions back up to the initial one.
22373 This is, of course, not reentrant. */
22374 if (excessive_deduction_depth)
22375 return error_mark_node;
22376 ++deduction_depth;
22378 gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
22380 fntype = TREE_TYPE (fn);
22381 if (explicit_targs)
22383 /* [temp.deduct]
22385 The specified template arguments must match the template
22386 parameters in kind (i.e., type, nontype, template), and there
22387 must not be more arguments than there are parameters;
22388 otherwise type deduction fails.
22390 Nontype arguments must match the types of the corresponding
22391 nontype template parameters, or must be convertible to the
22392 types of the corresponding nontype parameters as specified in
22393 _temp.arg.nontype_, otherwise type deduction fails.
22395 All references in the function type of the function template
22396 to the corresponding template parameters are replaced by the
22397 specified template argument values. If a substitution in a
22398 template parameter or in the function type of the function
22399 template results in an invalid type, type deduction fails. */
22400 int i, len = TREE_VEC_LENGTH (tparms);
22401 location_t loc = input_location;
22402 incomplete = false;
22404 if (explicit_targs == error_mark_node)
22405 goto fail;
22407 if (TMPL_ARGS_DEPTH (explicit_targs)
22408 < TMPL_ARGS_DEPTH (full_targs))
22409 explicit_targs = add_outermost_template_args (full_targs,
22410 explicit_targs);
22412 /* Adjust any explicit template arguments before entering the
22413 substitution context. */
22414 explicit_targs
22415 = (coerce_template_parms (tparms, explicit_targs, fn,
22416 complain|tf_partial,
22417 /*require_all_args=*/false));
22418 if (explicit_targs == error_mark_node)
22419 goto fail;
22421 /* Substitute the explicit args into the function type. This is
22422 necessary so that, for instance, explicitly declared function
22423 arguments can match null pointed constants. If we were given
22424 an incomplete set of explicit args, we must not do semantic
22425 processing during substitution as we could create partial
22426 instantiations. */
22427 for (i = 0; i < len; i++)
22429 tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
22430 bool parameter_pack = false;
22431 tree targ = TREE_VEC_ELT (explicit_targs, i);
22433 /* Dig out the actual parm. */
22434 if (TREE_CODE (parm) == TYPE_DECL
22435 || TREE_CODE (parm) == TEMPLATE_DECL)
22437 parm = TREE_TYPE (parm);
22438 parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
22440 else if (TREE_CODE (parm) == PARM_DECL)
22442 parm = DECL_INITIAL (parm);
22443 parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
22446 if (targ == NULL_TREE)
22447 /* No explicit argument for this template parameter. */
22448 incomplete = true;
22449 else if (parameter_pack && pack_deducible_p (parm, fn))
22451 /* Mark the argument pack as "incomplete". We could
22452 still deduce more arguments during unification.
22453 We remove this mark in type_unification_real. */
22454 ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
22455 ARGUMENT_PACK_EXPLICIT_ARGS (targ)
22456 = ARGUMENT_PACK_ARGS (targ);
22458 /* We have some incomplete argument packs. */
22459 incomplete = true;
22463 if (incomplete)
22465 if (!push_tinst_level (fn, explicit_targs))
22467 excessive_deduction_depth = true;
22468 goto fail;
22470 ++processing_template_decl;
22471 input_location = DECL_SOURCE_LOCATION (fn);
22472 /* Ignore any access checks; we'll see them again in
22473 instantiate_template and they might have the wrong
22474 access path at this point. */
22475 push_deferring_access_checks (dk_deferred);
22476 tsubst_flags_t ecomplain = complain | tf_partial | tf_fndecl_type;
22477 fntype = tsubst (TREE_TYPE (fn), explicit_targs, ecomplain, NULL_TREE);
22478 pop_deferring_access_checks ();
22479 input_location = loc;
22480 --processing_template_decl;
22481 pop_tinst_level ();
22483 if (fntype == error_mark_node)
22484 goto fail;
22487 /* Place the explicitly specified arguments in TARGS. */
22488 explicit_targs = INNERMOST_TEMPLATE_ARGS (explicit_targs);
22489 for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
22490 TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
22491 if (!incomplete && CHECKING_P
22492 && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
22493 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
22494 (targs, NUM_TMPL_ARGS (explicit_targs));
22497 if (return_type && strict != DEDUCE_CALL)
22499 tree *new_args = XALLOCAVEC (tree, nargs + 1);
22500 new_args[0] = return_type;
22501 memcpy (new_args + 1, args, nargs * sizeof (tree));
22502 args = new_args;
22503 ++nargs;
22506 if (!incomplete)
22507 goto deduced;
22509 /* Never do unification on the 'this' parameter. */
22510 parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
22512 if (return_type && strict == DEDUCE_CALL)
22514 /* We're deducing for a call to the result of a template conversion
22515 function. The parms we really want are in return_type. */
22516 if (INDIRECT_TYPE_P (return_type))
22517 return_type = TREE_TYPE (return_type);
22518 parms = TYPE_ARG_TYPES (return_type);
22520 else if (return_type)
22522 parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
22525 /* We allow incomplete unification without an error message here
22526 because the standard doesn't seem to explicitly prohibit it. Our
22527 callers must be ready to deal with unification failures in any
22528 event. */
22530 /* If we aren't explaining yet, push tinst context so we can see where
22531 any errors (e.g. from class instantiations triggered by instantiation
22532 of default template arguments) come from. If we are explaining, this
22533 context is redundant. */
22534 if (!explain_p && !push_tinst_level (fn, targs))
22536 excessive_deduction_depth = true;
22537 goto fail;
22540 ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
22541 full_targs, parms, args, nargs, /*subr=*/0,
22542 strict, &checks, explain_p);
22543 if (!explain_p)
22544 pop_tinst_level ();
22545 if (!ok)
22546 goto fail;
22548 /* Now that we have bindings for all of the template arguments,
22549 ensure that the arguments deduced for the template template
22550 parameters have compatible template parameter lists. We cannot
22551 check this property before we have deduced all template
22552 arguments, because the template parameter types of a template
22553 template parameter might depend on prior template parameters
22554 deduced after the template template parameter. The following
22555 ill-formed example illustrates this issue:
22557 template<typename T, template<T> class C> void f(C<5>, T);
22559 template<int N> struct X {};
22561 void g() {
22562 f(X<5>(), 5l); // error: template argument deduction fails
22565 The template parameter list of 'C' depends on the template type
22566 parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
22567 'long'. Thus, we can't check that 'C' cannot bind to 'X' at the
22568 time that we deduce 'C'. */
22569 if (!template_template_parm_bindings_ok_p
22570 (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
22572 unify_inconsistent_template_template_parameters (explain_p);
22573 goto fail;
22576 deduced:
22578 /* CWG2369: Check satisfaction before non-deducible conversions. */
22579 if (!constraints_satisfied_p (fn, targs))
22581 if (explain_p)
22582 diagnose_constraints (DECL_SOURCE_LOCATION (fn), fn, targs);
22583 goto fail;
22586 /* DR 1391: All parameters have args, now check non-dependent parms for
22587 convertibility. We don't do this if all args were explicitly specified,
22588 as the standard says that we substitute explicit args immediately. */
22589 if (incomplete
22590 && check_non_deducible_conversions (parms, args, nargs, fn, strict, flags,
22591 convs, explain_p))
22592 goto fail;
22594 /* All is well so far. Now, check:
22596 [temp.deduct]
22598 When all template arguments have been deduced, all uses of
22599 template parameters in nondeduced contexts are replaced with
22600 the corresponding deduced argument values. If the
22601 substitution results in an invalid type, as described above,
22602 type deduction fails. */
22603 if (!push_tinst_level (fn, targs))
22605 excessive_deduction_depth = true;
22606 goto fail;
22609 /* Also collect access checks from the instantiation. */
22610 reopen_deferring_access_checks (checks);
22612 decl = instantiate_template (fn, targs, complain);
22614 checks = get_deferred_access_checks ();
22615 pop_deferring_access_checks ();
22617 pop_tinst_level ();
22619 if (decl == error_mark_node)
22620 goto fail;
22622 /* Now perform any access checks encountered during substitution. */
22623 push_access_scope (decl);
22624 ok = perform_access_checks (checks, complain);
22625 pop_access_scope (decl);
22626 if (!ok)
22627 goto fail;
22629 /* If we're looking for an exact match, check that what we got
22630 is indeed an exact match. It might not be if some template
22631 parameters are used in non-deduced contexts. But don't check
22632 for an exact match if we have dependent template arguments;
22633 in that case we're doing partial ordering, and we already know
22634 that we have two candidates that will provide the actual type. */
22635 if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
22637 tree substed = TREE_TYPE (decl);
22638 unsigned int i;
22640 tree sarg
22641 = skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
22642 if (return_type)
22643 sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
22644 for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
22645 if (!same_type_p (args[i], TREE_VALUE (sarg)))
22647 unify_type_mismatch (explain_p, args[i],
22648 TREE_VALUE (sarg));
22649 goto fail;
22651 if ((i < nargs || sarg)
22652 /* add_candidates uses DEDUCE_EXACT for x.operator foo(), but args
22653 doesn't contain the trailing void, and conv fns are always (). */
22654 && !DECL_CONV_FN_P (decl))
22656 unsigned nsargs = i + list_length (sarg);
22657 unify_arity (explain_p, nargs, nsargs);
22658 goto fail;
22662 /* After doing deduction with the inherited constructor, actually return an
22663 instantiation of the inheriting constructor. */
22664 if (orig_fn != fn)
22665 decl = instantiate_template (orig_fn, targs, complain);
22667 r = decl;
22669 fail:
22670 --deduction_depth;
22671 if (excessive_deduction_depth)
22673 if (deduction_depth == 0)
22674 /* Reset once we're all the way out. */
22675 excessive_deduction_depth = false;
22678 return r;
22681 /* Returns true iff PARM is a forwarding reference in the context of
22682 template argument deduction for TMPL. */
22684 static bool
22685 forwarding_reference_p (tree parm, tree tmpl)
22687 /* [temp.deduct.call], "A forwarding reference is an rvalue reference to a
22688 cv-unqualified template parameter ..." */
22689 if (TYPE_REF_P (parm)
22690 && TYPE_REF_IS_RVALUE (parm)
22691 && TREE_CODE (TREE_TYPE (parm)) == TEMPLATE_TYPE_PARM
22692 && cp_type_quals (TREE_TYPE (parm)) == TYPE_UNQUALIFIED)
22694 parm = TREE_TYPE (parm);
22695 /* [temp.deduct.call], "... that does not represent a template parameter
22696 of a class template (during class template argument deduction)." */
22697 if (tmpl
22698 && deduction_guide_p (tmpl)
22699 && DECL_ARTIFICIAL (tmpl))
22701 /* Since the template parameters of a synthesized guide consist of
22702 the template parameters of the class template followed by those of
22703 the constructor (if any), we can tell if PARM represents a template
22704 parameter of the class template by comparing its index with the
22705 arity of the class template. */
22706 tree ctmpl = CLASSTYPE_TI_TEMPLATE (TREE_TYPE (TREE_TYPE (tmpl)));
22707 if (TEMPLATE_TYPE_IDX (parm)
22708 < TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (ctmpl)))
22709 return false;
22711 return true;
22713 return false;
22716 /* Adjust types before performing type deduction, as described in
22717 [temp.deduct.call] and [temp.deduct.conv]. The rules in these two
22718 sections are symmetric. PARM is the type of a function parameter
22719 or the return type of the conversion function. ARG is the type of
22720 the argument passed to the call, or the type of the value
22721 initialized with the result of the conversion function.
22722 ARG_EXPR is the original argument expression, which may be null. */
22724 static int
22725 maybe_adjust_types_for_deduction (tree tparms,
22726 unification_kind_t strict,
22727 tree* parm,
22728 tree* arg,
22729 tree arg_expr)
22731 int result = 0;
22733 switch (strict)
22735 case DEDUCE_CALL:
22736 break;
22738 case DEDUCE_CONV:
22739 /* [temp.deduct.conv] First remove a reference type on parm.
22740 DRs 322 & 976 affected this. */
22741 if (TYPE_REF_P (*parm))
22742 *parm = TREE_TYPE (*parm);
22744 /* Swap PARM and ARG throughout the remainder of this
22745 function; the handling is precisely symmetric since PARM
22746 will initialize ARG rather than vice versa. */
22747 std::swap (parm, arg);
22749 break;
22751 case DEDUCE_EXACT:
22752 /* Core issue #873: Do the DR606 thing (see below) for these cases,
22753 too, but here handle it by stripping the reference from PARM
22754 rather than by adding it to ARG. */
22755 if (forwarding_reference_p (*parm, TPARMS_PRIMARY_TEMPLATE (tparms))
22756 && TYPE_REF_P (*arg)
22757 && !TYPE_REF_IS_RVALUE (*arg))
22758 *parm = TREE_TYPE (*parm);
22759 /* Nothing else to do in this case. */
22760 return 0;
22762 default:
22763 gcc_unreachable ();
22766 if (!TYPE_REF_P (*parm))
22768 /* [temp.deduct.call]
22770 If P is not a reference type:
22772 --If A is an array type, the pointer type produced by the
22773 array-to-pointer standard conversion (_conv.array_) is
22774 used in place of A for type deduction; otherwise,
22776 --If A is a function type, the pointer type produced by
22777 the function-to-pointer standard conversion
22778 (_conv.func_) is used in place of A for type deduction;
22779 otherwise,
22781 --If A is a cv-qualified type, the top level
22782 cv-qualifiers of A's type are ignored for type
22783 deduction. */
22784 if (TREE_CODE (*arg) == ARRAY_TYPE)
22785 *arg = build_pointer_type (TREE_TYPE (*arg));
22786 else if (TREE_CODE (*arg) == FUNCTION_TYPE)
22787 *arg = build_pointer_type (*arg);
22788 else
22789 *arg = TYPE_MAIN_VARIANT (*arg);
22792 /* [temp.deduct.call], "If P is a forwarding reference and the argument is
22793 an lvalue, the type 'lvalue reference to A' is used in place of A for
22794 type deduction." */
22795 if (forwarding_reference_p (*parm, TPARMS_PRIMARY_TEMPLATE (tparms))
22796 && (arg_expr ? lvalue_p (arg_expr)
22797 /* try_one_overload doesn't provide an arg_expr, but
22798 functions are always lvalues. */
22799 : TREE_CODE (*arg) == FUNCTION_TYPE))
22800 *arg = build_reference_type (*arg);
22802 /* [temp.deduct.call]
22804 If P is a cv-qualified type, the top level cv-qualifiers
22805 of P's type are ignored for type deduction. If P is a
22806 reference type, the type referred to by P is used for
22807 type deduction. */
22808 *parm = TYPE_MAIN_VARIANT (*parm);
22809 if (TYPE_REF_P (*parm))
22811 *parm = TREE_TYPE (*parm);
22812 result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
22815 return result;
22818 /* Subroutine of fn_type_unification. PARM is a function parameter of a
22819 template which doesn't contain any deducible template parameters; check if
22820 ARG is a suitable match for it. STRICT, FLAGS and EXPLAIN_P are as in
22821 unify_one_argument. */
22823 static int
22824 check_non_deducible_conversion (tree parm, tree arg, unification_kind_t strict,
22825 int flags, struct conversion **conv_p,
22826 bool explain_p)
22828 tree type;
22830 if (!TYPE_P (arg))
22831 type = TREE_TYPE (arg);
22832 else
22833 type = arg;
22835 if (same_type_p (parm, type))
22836 return unify_success (explain_p);
22838 tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
22839 if (strict == DEDUCE_CONV)
22841 if (can_convert_arg (type, parm, NULL_TREE, flags, complain))
22842 return unify_success (explain_p);
22844 else if (strict == DEDUCE_CALL)
22846 bool ok = false;
22847 tree conv_arg = TYPE_P (arg) ? NULL_TREE : arg;
22848 if (conv_p)
22849 /* Avoid recalculating this in add_function_candidate. */
22850 ok = (*conv_p
22851 = good_conversion (parm, type, conv_arg, flags, complain));
22852 else
22853 ok = can_convert_arg (parm, type, conv_arg, flags, complain);
22854 if (ok)
22855 return unify_success (explain_p);
22858 if (strict == DEDUCE_EXACT)
22859 return unify_type_mismatch (explain_p, parm, arg);
22860 else
22861 return unify_arg_conversion (explain_p, parm, type, arg);
22864 static bool uses_deducible_template_parms (tree type);
22866 /* Returns true iff the expression EXPR is one from which a template
22867 argument can be deduced. In other words, if it's an undecorated
22868 use of a template non-type parameter. */
22870 static bool
22871 deducible_expression (tree expr)
22873 /* Strip implicit conversions and implicit INDIRECT_REFs. */
22874 while (CONVERT_EXPR_P (expr)
22875 || TREE_CODE (expr) == VIEW_CONVERT_EXPR
22876 || REFERENCE_REF_P (expr))
22877 expr = TREE_OPERAND (expr, 0);
22878 return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
22881 /* Returns true iff the array domain DOMAIN uses a template parameter in a
22882 deducible way; that is, if it has a max value of <PARM> - 1. */
22884 static bool
22885 deducible_array_bound (tree domain)
22887 if (domain == NULL_TREE)
22888 return false;
22890 tree max = TYPE_MAX_VALUE (domain);
22891 if (TREE_CODE (max) != MINUS_EXPR)
22892 return false;
22894 return deducible_expression (TREE_OPERAND (max, 0));
22897 /* Returns true iff the template arguments ARGS use a template parameter
22898 in a deducible way. */
22900 static bool
22901 deducible_template_args (tree args)
22903 for (tree elt : tree_vec_range (args))
22905 bool deducible;
22906 if (ARGUMENT_PACK_P (elt))
22907 deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
22908 else
22910 if (PACK_EXPANSION_P (elt))
22911 elt = PACK_EXPANSION_PATTERN (elt);
22912 if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
22913 deducible = true;
22914 else if (TYPE_P (elt))
22915 deducible = uses_deducible_template_parms (elt);
22916 else
22917 deducible = deducible_expression (elt);
22919 if (deducible)
22920 return true;
22922 return false;
22925 /* Returns true iff TYPE contains any deducible references to template
22926 parameters, as per 14.8.2.5. */
22928 static bool
22929 uses_deducible_template_parms (tree type)
22931 if (PACK_EXPANSION_P (type))
22932 type = PACK_EXPANSION_PATTERN (type);
22934 /* T
22935 cv-list T
22936 TT<T>
22937 TT<i>
22938 TT<> */
22939 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
22940 || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
22941 return true;
22943 /* T*
22945 T&& */
22946 if (INDIRECT_TYPE_P (type))
22947 return uses_deducible_template_parms (TREE_TYPE (type));
22949 /* T[integer-constant ]
22950 type [i] */
22951 if (TREE_CODE (type) == ARRAY_TYPE)
22952 return (uses_deducible_template_parms (TREE_TYPE (type))
22953 || deducible_array_bound (TYPE_DOMAIN (type)));
22955 /* T type ::*
22956 type T::*
22957 T T::*
22958 T (type ::*)()
22959 type (T::*)()
22960 type (type ::*)(T)
22961 type (T::*)(T)
22962 T (type ::*)(T)
22963 T (T::*)()
22964 T (T::*)(T) */
22965 if (TYPE_PTRMEM_P (type))
22966 return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
22967 || (uses_deducible_template_parms
22968 (TYPE_PTRMEM_POINTED_TO_TYPE (type))));
22970 /* template-name <T> (where template-name refers to a class template)
22971 template-name <i> (where template-name refers to a class template) */
22972 if (CLASS_TYPE_P (type)
22973 && CLASSTYPE_TEMPLATE_INFO (type)
22974 && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
22975 return deducible_template_args (INNERMOST_TEMPLATE_ARGS
22976 (CLASSTYPE_TI_ARGS (type)));
22978 /* type (T)
22980 T(T) */
22981 if (FUNC_OR_METHOD_TYPE_P (type))
22983 if (uses_deducible_template_parms (TREE_TYPE (type)))
22984 return true;
22985 tree parm = TYPE_ARG_TYPES (type);
22986 if (TREE_CODE (type) == METHOD_TYPE)
22987 parm = TREE_CHAIN (parm);
22988 for (; parm; parm = TREE_CHAIN (parm))
22989 if (uses_deducible_template_parms (TREE_VALUE (parm)))
22990 return true;
22991 if (flag_noexcept_type
22992 && TYPE_RAISES_EXCEPTIONS (type)
22993 && TREE_PURPOSE (TYPE_RAISES_EXCEPTIONS (type))
22994 && deducible_expression (TREE_PURPOSE (TYPE_RAISES_EXCEPTIONS (type))))
22995 return true;
22998 return false;
23001 /* Subroutine of type_unification_real and unify_pack_expansion to
23002 handle unification of a single P/A pair. Parameters are as
23003 for those functions. */
23005 static int
23006 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
23007 int subr, unification_kind_t strict,
23008 bool explain_p)
23010 tree arg_expr = NULL_TREE;
23011 int arg_strict;
23013 if (arg == error_mark_node || parm == error_mark_node)
23014 return unify_invalid (explain_p);
23015 if (arg == unknown_type_node)
23016 /* We can't deduce anything from this, but we might get all the
23017 template args from other function args. */
23018 return unify_success (explain_p);
23020 /* Implicit conversions (Clause 4) will be performed on a function
23021 argument to convert it to the type of the corresponding function
23022 parameter if the parameter type contains no template-parameters that
23023 participate in template argument deduction. */
23024 if (strict != DEDUCE_EXACT
23025 && TYPE_P (parm) && !uses_deducible_template_parms (parm))
23026 /* For function parameters with no deducible template parameters,
23027 just return. We'll check non-dependent conversions later. */
23028 return unify_success (explain_p);
23030 switch (strict)
23032 case DEDUCE_CALL:
23033 arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
23034 | UNIFY_ALLOW_MORE_CV_QUAL
23035 | UNIFY_ALLOW_DERIVED);
23036 break;
23038 case DEDUCE_CONV:
23039 arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
23040 break;
23042 case DEDUCE_EXACT:
23043 arg_strict = UNIFY_ALLOW_NONE;
23044 break;
23046 default:
23047 gcc_unreachable ();
23050 /* We only do these transformations if this is the top-level
23051 parameter_type_list in a call or declaration matching; in other
23052 situations (nested function declarators, template argument lists) we
23053 won't be comparing a type to an expression, and we don't do any type
23054 adjustments. */
23055 if (!subr)
23057 if (!TYPE_P (arg))
23059 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
23060 if (type_unknown_p (arg))
23062 /* [temp.deduct.type] A template-argument can be
23063 deduced from a pointer to function or pointer
23064 to member function argument if the set of
23065 overloaded functions does not contain function
23066 templates and at most one of a set of
23067 overloaded functions provides a unique
23068 match. */
23069 resolve_overloaded_unification (tparms, targs, parm,
23070 arg, strict,
23071 arg_strict, explain_p);
23072 /* If a unique match was not found, this is a
23073 non-deduced context, so we still succeed. */
23074 return unify_success (explain_p);
23077 arg_expr = arg;
23078 arg = unlowered_expr_type (arg);
23079 if (arg == error_mark_node)
23080 return unify_invalid (explain_p);
23083 arg_strict |= maybe_adjust_types_for_deduction (tparms, strict,
23084 &parm, &arg, arg_expr);
23086 else
23087 if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
23088 != (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
23089 return unify_template_argument_mismatch (explain_p, parm, arg);
23091 /* For deduction from an init-list we need the actual list. */
23092 if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
23093 arg = arg_expr;
23094 return unify (tparms, targs, parm, arg, arg_strict, explain_p);
23097 /* for_each_template_parm callback that always returns 0. */
23099 static int
23100 zero_r (tree, void *)
23102 return 0;
23105 /* for_each_template_parm any_fn callback to handle deduction of a template
23106 type argument from the type of an array bound. */
23108 static int
23109 array_deduction_r (tree t, void *data)
23111 tree_pair_p d = (tree_pair_p)data;
23112 tree &tparms = d->purpose;
23113 tree &targs = d->value;
23115 if (TREE_CODE (t) == ARRAY_TYPE)
23116 if (tree dom = TYPE_DOMAIN (t))
23117 if (tree max = TYPE_MAX_VALUE (dom))
23119 if (TREE_CODE (max) == MINUS_EXPR)
23120 max = TREE_OPERAND (max, 0);
23121 if (TREE_CODE (max) == TEMPLATE_PARM_INDEX)
23122 unify (tparms, targs, TREE_TYPE (max), size_type_node,
23123 UNIFY_ALLOW_NONE, /*explain*/false);
23126 /* Keep walking. */
23127 return 0;
23130 /* Try to deduce any not-yet-deduced template type arguments from the type of
23131 an array bound. This is handled separately from unify because 14.8.2.5 says
23132 "The type of a type parameter is only deduced from an array bound if it is
23133 not otherwise deduced." */
23135 static void
23136 try_array_deduction (tree tparms, tree targs, tree parm)
23138 tree_pair_s data = { tparms, targs };
23139 hash_set<tree> visited;
23140 for_each_template_parm (parm, zero_r, &data, &visited,
23141 /*nondeduced*/false, array_deduction_r);
23144 /* Most parms like fn_type_unification.
23146 If SUBR is 1, we're being called recursively (to unify the
23147 arguments of a function or method parameter of a function
23148 template).
23150 CHECKS is a pointer to a vector of access checks encountered while
23151 substituting default template arguments. */
23153 static int
23154 type_unification_real (tree tparms,
23155 tree full_targs,
23156 tree xparms,
23157 const tree *xargs,
23158 unsigned int xnargs,
23159 int subr,
23160 unification_kind_t strict,
23161 vec<deferred_access_check, va_gc> **checks,
23162 bool explain_p)
23164 tree parm, arg;
23165 int i;
23166 int ntparms = TREE_VEC_LENGTH (tparms);
23167 int saw_undeduced = 0;
23168 tree parms;
23169 const tree *args;
23170 unsigned int nargs;
23171 unsigned int ia;
23173 gcc_assert (TREE_CODE (tparms) == TREE_VEC);
23174 gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
23175 gcc_assert (ntparms > 0);
23177 tree targs = INNERMOST_TEMPLATE_ARGS (full_targs);
23179 /* Reset the number of non-defaulted template arguments contained
23180 in TARGS. */
23181 NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
23183 again:
23184 parms = xparms;
23185 args = xargs;
23186 nargs = xnargs;
23188 /* Only fn_type_unification cares about terminal void. */
23189 if (nargs && args[nargs-1] == void_type_node)
23190 --nargs;
23192 ia = 0;
23193 while (parms && parms != void_list_node
23194 && ia < nargs)
23196 parm = TREE_VALUE (parms);
23198 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
23199 && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
23200 /* For a function parameter pack that occurs at the end of the
23201 parameter-declaration-list, the type A of each remaining
23202 argument of the call is compared with the type P of the
23203 declarator-id of the function parameter pack. */
23204 break;
23206 parms = TREE_CHAIN (parms);
23208 if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
23209 /* For a function parameter pack that does not occur at the
23210 end of the parameter-declaration-list, the type of the
23211 parameter pack is a non-deduced context. */
23212 continue;
23214 arg = args[ia];
23215 ++ia;
23217 if (unify_one_argument (tparms, full_targs, parm, arg, subr, strict,
23218 explain_p))
23219 return 1;
23222 if (parms
23223 && parms != void_list_node
23224 && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
23226 /* Unify the remaining arguments with the pack expansion type. */
23227 tree argvec;
23228 tree parmvec = make_tree_vec (1);
23230 /* Allocate a TREE_VEC and copy in all of the arguments */
23231 argvec = make_tree_vec (nargs - ia);
23232 for (i = 0; ia < nargs; ++ia, ++i)
23233 TREE_VEC_ELT (argvec, i) = args[ia];
23235 /* Copy the parameter into parmvec. */
23236 TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
23237 if (unify_pack_expansion (tparms, full_targs, parmvec, argvec, strict,
23238 /*subr=*/subr, explain_p))
23239 return 1;
23241 /* Advance to the end of the list of parameters. */
23242 parms = TREE_CHAIN (parms);
23245 /* Fail if we've reached the end of the parm list, and more args
23246 are present, and the parm list isn't variadic. */
23247 if (ia < nargs && parms == void_list_node)
23248 return unify_too_many_arguments (explain_p, nargs, ia);
23249 /* Fail if parms are left and they don't have default values and
23250 they aren't all deduced as empty packs (c++/57397). This is
23251 consistent with sufficient_parms_p. */
23252 if (parms && parms != void_list_node
23253 && TREE_PURPOSE (parms) == NULL_TREE)
23255 unsigned int count = nargs;
23256 tree p = parms;
23257 bool type_pack_p;
23260 type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
23261 if (!type_pack_p)
23262 count++;
23263 p = TREE_CHAIN (p);
23265 while (p && p != void_list_node);
23266 if (count != nargs)
23267 return unify_too_few_arguments (explain_p, ia, count,
23268 type_pack_p);
23271 if (!subr)
23273 tsubst_flags_t complain = (explain_p
23274 ? tf_warning_or_error
23275 : tf_none);
23276 bool tried_array_deduction = (cxx_dialect < cxx17);
23278 for (i = 0; i < ntparms; i++)
23280 tree targ = TREE_VEC_ELT (targs, i);
23281 tree tparm = TREE_VEC_ELT (tparms, i);
23283 /* Clear the "incomplete" flags on all argument packs now so that
23284 substituting them into later default arguments works. */
23285 if (targ && ARGUMENT_PACK_P (targ))
23287 ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
23288 ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
23291 if (targ || tparm == error_mark_node)
23292 continue;
23293 tparm = TREE_VALUE (tparm);
23295 if (TREE_CODE (tparm) == TYPE_DECL
23296 && !tried_array_deduction)
23298 try_array_deduction (tparms, targs, xparms);
23299 tried_array_deduction = true;
23300 if (TREE_VEC_ELT (targs, i))
23301 continue;
23304 /* If this is an undeduced nontype parameter that depends on
23305 a type parameter, try another pass; its type may have been
23306 deduced from a later argument than the one from which
23307 this parameter can be deduced. */
23308 if (TREE_CODE (tparm) == PARM_DECL
23309 && !is_auto (TREE_TYPE (tparm))
23310 && uses_template_parms (TREE_TYPE (tparm))
23311 && saw_undeduced < 2)
23313 saw_undeduced = 1;
23314 continue;
23317 /* Core issue #226 (C++0x) [temp.deduct]:
23319 If a template argument has not been deduced, its
23320 default template argument, if any, is used.
23322 When we are in C++98 mode, TREE_PURPOSE will either
23323 be NULL_TREE or ERROR_MARK_NODE, so we do not need
23324 to explicitly check cxx_dialect here. */
23325 if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
23326 /* OK, there is a default argument. Wait until after the
23327 conversion check to do substitution. */
23328 continue;
23330 /* If the type parameter is a parameter pack, then it will
23331 be deduced to an empty parameter pack. */
23332 if (template_parameter_pack_p (tparm))
23334 tree arg;
23336 if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
23338 arg = make_node (NONTYPE_ARGUMENT_PACK);
23339 TREE_CONSTANT (arg) = 1;
23341 else
23342 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
23344 ARGUMENT_PACK_ARGS (arg) = make_tree_vec (0);
23346 TREE_VEC_ELT (targs, i) = arg;
23347 continue;
23350 return unify_parameter_deduction_failure (explain_p, tparm);
23353 /* During partial ordering, we deduce dependent template args. */
23354 bool any_dependent_targs = false;
23356 /* Now substitute into the default template arguments. */
23357 for (i = 0; i < ntparms; i++)
23359 tree targ = TREE_VEC_ELT (targs, i);
23360 tree tparm = TREE_VEC_ELT (tparms, i);
23362 if (targ)
23364 if (!any_dependent_targs && dependent_template_arg_p (targ))
23365 any_dependent_targs = true;
23366 continue;
23368 if (tparm == error_mark_node)
23369 continue;
23371 tree parm = TREE_VALUE (tparm);
23372 tree arg = TREE_PURPOSE (tparm);
23373 reopen_deferring_access_checks (*checks);
23374 location_t save_loc = input_location;
23375 if (DECL_P (parm))
23376 input_location = DECL_SOURCE_LOCATION (parm);
23378 if (saw_undeduced == 1
23379 && TREE_CODE (parm) == PARM_DECL
23380 && !is_auto (TREE_TYPE (parm))
23381 && uses_template_parms (TREE_TYPE (parm)))
23383 /* The type of this non-type parameter depends on undeduced
23384 parameters. Don't try to use its default argument yet,
23385 since we might deduce an argument for it on the next pass,
23386 but do check whether the arguments we already have cause
23387 substitution failure, so that that happens before we try
23388 later default arguments (78489). */
23389 ++processing_template_decl;
23390 tree type = tsubst (TREE_TYPE (parm), full_targs, complain,
23391 NULL_TREE);
23392 --processing_template_decl;
23393 if (type == error_mark_node)
23394 arg = error_mark_node;
23395 else
23396 arg = NULL_TREE;
23398 else
23400 /* Even if the call is happening in template context, getting
23401 here means it's non-dependent, and a default argument is
23402 considered a separate definition under [temp.decls], so we can
23403 do this substitution without processing_template_decl. This
23404 is important if the default argument contains something that
23405 might be instantiation-dependent like access (87480). */
23406 processing_template_decl_sentinel s (!any_dependent_targs);
23407 tree substed = NULL_TREE;
23408 if (saw_undeduced == 1 && !any_dependent_targs)
23410 /* First instatiate in template context, in case we still
23411 depend on undeduced template parameters. */
23412 ++processing_template_decl;
23413 substed = tsubst_template_arg (arg, full_targs, complain,
23414 NULL_TREE);
23415 --processing_template_decl;
23416 if (substed != error_mark_node
23417 && !uses_template_parms (substed))
23418 /* We replaced all the tparms, substitute again out of
23419 template context. */
23420 substed = NULL_TREE;
23422 if (!substed)
23423 substed = tsubst_template_arg (arg, full_targs, complain,
23424 NULL_TREE);
23426 if (!uses_template_parms (substed))
23427 arg = convert_template_argument (parm, substed, full_targs,
23428 complain, i, NULL_TREE);
23429 else if (saw_undeduced == 1)
23430 arg = NULL_TREE;
23431 else if (!any_dependent_targs)
23432 arg = error_mark_node;
23435 input_location = save_loc;
23436 *checks = get_deferred_access_checks ();
23437 pop_deferring_access_checks ();
23439 if (arg == error_mark_node)
23440 return 1;
23441 else if (arg)
23443 TREE_VEC_ELT (targs, i) = arg;
23444 /* The position of the first default template argument,
23445 is also the number of non-defaulted arguments in TARGS.
23446 Record that. */
23447 if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
23448 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
23452 if (saw_undeduced++ == 1)
23453 goto again;
23456 if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
23457 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
23459 return unify_success (explain_p);
23462 /* Subroutine of type_unification_real. Args are like the variables
23463 at the call site. ARG is an overloaded function (or template-id);
23464 we try deducing template args from each of the overloads, and if
23465 only one succeeds, we go with that. Modifies TARGS and returns
23466 true on success. */
23468 static bool
23469 resolve_overloaded_unification (tree tparms,
23470 tree targs,
23471 tree parm,
23472 tree arg,
23473 unification_kind_t strict,
23474 int sub_strict,
23475 bool explain_p)
23477 tree tempargs = copy_node (targs);
23478 int good = 0;
23479 tree goodfn = NULL_TREE;
23480 bool addr_p;
23482 if (TREE_CODE (arg) == ADDR_EXPR)
23484 arg = TREE_OPERAND (arg, 0);
23485 addr_p = true;
23487 else
23488 addr_p = false;
23490 if (TREE_CODE (arg) == COMPONENT_REF)
23491 /* Handle `&x' where `x' is some static or non-static member
23492 function name. */
23493 arg = TREE_OPERAND (arg, 1);
23495 if (TREE_CODE (arg) == OFFSET_REF)
23496 arg = TREE_OPERAND (arg, 1);
23498 /* Strip baselink information. */
23499 if (BASELINK_P (arg))
23500 arg = BASELINK_FUNCTIONS (arg);
23502 if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
23504 /* If we got some explicit template args, we need to plug them into
23505 the affected templates before we try to unify, in case the
23506 explicit args will completely resolve the templates in question. */
23508 int ok = 0;
23509 tree expl_subargs = TREE_OPERAND (arg, 1);
23510 arg = TREE_OPERAND (arg, 0);
23512 for (lkp_iterator iter (arg); iter; ++iter)
23514 tree fn = *iter;
23515 tree subargs, elem;
23517 if (TREE_CODE (fn) != TEMPLATE_DECL)
23518 continue;
23520 subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
23521 expl_subargs, NULL_TREE, tf_none);
23522 if (subargs != error_mark_node
23523 && !any_dependent_template_arguments_p (subargs))
23525 fn = instantiate_template (fn, subargs, tf_none);
23526 if (!constraints_satisfied_p (fn))
23527 continue;
23528 if (undeduced_auto_decl (fn))
23530 /* Instantiate the function to deduce its return type. */
23531 ++function_depth;
23532 instantiate_decl (fn, /*defer*/false, /*class*/false);
23533 --function_depth;
23536 if (flag_noexcept_type)
23537 maybe_instantiate_noexcept (fn, tf_none);
23539 elem = TREE_TYPE (fn);
23540 if (try_one_overload (tparms, targs, tempargs, parm,
23541 elem, strict, sub_strict, addr_p, explain_p)
23542 && (!goodfn || !same_type_p (goodfn, elem)))
23544 goodfn = elem;
23545 ++good;
23548 else if (subargs)
23549 ++ok;
23551 /* If no templates (or more than one) are fully resolved by the
23552 explicit arguments, this template-id is a non-deduced context; it
23553 could still be OK if we deduce all template arguments for the
23554 enclosing call through other arguments. */
23555 if (good != 1)
23556 good = ok;
23558 else if (!OVL_P (arg))
23559 /* If ARG is, for example, "(0, &f)" then its type will be unknown
23560 -- but the deduction does not succeed because the expression is
23561 not just the function on its own. */
23562 return false;
23563 else
23564 for (lkp_iterator iter (arg); iter; ++iter)
23566 tree fn = *iter;
23567 if (try_one_overload (tparms, targs, tempargs, parm, TREE_TYPE (fn),
23568 strict, sub_strict, addr_p, explain_p)
23569 && (!goodfn || !decls_match (goodfn, fn)))
23571 goodfn = fn;
23572 ++good;
23576 /* [temp.deduct.type] A template-argument can be deduced from a pointer
23577 to function or pointer to member function argument if the set of
23578 overloaded functions does not contain function templates and at most
23579 one of a set of overloaded functions provides a unique match.
23581 So if we found multiple possibilities, we return success but don't
23582 deduce anything. */
23584 if (good == 1)
23586 int i = TREE_VEC_LENGTH (targs);
23587 for (; i--; )
23588 if (TREE_VEC_ELT (tempargs, i))
23590 tree old = TREE_VEC_ELT (targs, i);
23591 tree new_ = TREE_VEC_ELT (tempargs, i);
23592 if (new_ && old && ARGUMENT_PACK_P (old)
23593 && ARGUMENT_PACK_EXPLICIT_ARGS (old))
23594 /* Don't forget explicit template arguments in a pack. */
23595 ARGUMENT_PACK_EXPLICIT_ARGS (new_)
23596 = ARGUMENT_PACK_EXPLICIT_ARGS (old);
23597 TREE_VEC_ELT (targs, i) = new_;
23600 if (good)
23601 return true;
23603 return false;
23606 /* Core DR 115: In contexts where deduction is done and fails, or in
23607 contexts where deduction is not done, if a template argument list is
23608 specified and it, along with any default template arguments, identifies
23609 a single function template specialization, then the template-id is an
23610 lvalue for the function template specialization. */
23612 tree
23613 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
23615 tree expr, offset, baselink;
23616 bool addr;
23618 if (!type_unknown_p (orig_expr))
23619 return orig_expr;
23621 expr = orig_expr;
23622 addr = false;
23623 offset = NULL_TREE;
23624 baselink = NULL_TREE;
23626 if (TREE_CODE (expr) == ADDR_EXPR)
23628 expr = TREE_OPERAND (expr, 0);
23629 addr = true;
23631 if (TREE_CODE (expr) == OFFSET_REF)
23633 offset = expr;
23634 expr = TREE_OPERAND (expr, 1);
23636 if (BASELINK_P (expr))
23638 baselink = expr;
23639 expr = BASELINK_FUNCTIONS (expr);
23642 if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
23644 int good = 0;
23645 tree goodfn = NULL_TREE;
23647 /* If we got some explicit template args, we need to plug them into
23648 the affected templates before we try to unify, in case the
23649 explicit args will completely resolve the templates in question. */
23651 tree expl_subargs = TREE_OPERAND (expr, 1);
23652 tree arg = TREE_OPERAND (expr, 0);
23653 tree badfn = NULL_TREE;
23654 tree badargs = NULL_TREE;
23656 for (lkp_iterator iter (arg); iter; ++iter)
23658 tree fn = *iter;
23659 tree subargs, elem;
23661 if (TREE_CODE (fn) != TEMPLATE_DECL)
23662 continue;
23664 subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
23665 expl_subargs, NULL_TREE, tf_none);
23666 if (subargs != error_mark_node
23667 && !any_dependent_template_arguments_p (subargs))
23669 elem = instantiate_template (fn, subargs, tf_none);
23670 if (elem == error_mark_node)
23672 badfn = fn;
23673 badargs = subargs;
23675 else if (elem && (!goodfn || !decls_match (goodfn, elem))
23676 && constraints_satisfied_p (elem))
23678 goodfn = elem;
23679 ++good;
23683 if (good == 1)
23685 mark_used (goodfn);
23686 expr = goodfn;
23687 if (baselink)
23688 expr = build_baselink (BASELINK_BINFO (baselink),
23689 BASELINK_ACCESS_BINFO (baselink),
23690 expr, BASELINK_OPTYPE (baselink));
23691 if (offset)
23693 tree base
23694 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
23695 expr = build_offset_ref (base, expr, addr, complain);
23697 if (addr)
23698 expr = cp_build_addr_expr (expr, complain);
23699 return expr;
23701 else if (good == 0 && badargs && (complain & tf_error))
23702 /* There were no good options and at least one bad one, so let the
23703 user know what the problem is. */
23704 instantiate_template (badfn, badargs, complain);
23706 return orig_expr;
23709 /* As above, but error out if the expression remains overloaded. */
23711 tree
23712 resolve_nondeduced_context_or_error (tree exp, tsubst_flags_t complain)
23714 exp = resolve_nondeduced_context (exp, complain);
23715 if (type_unknown_p (exp))
23717 if (complain & tf_error)
23718 cxx_incomplete_type_error (exp, TREE_TYPE (exp));
23719 return error_mark_node;
23721 return exp;
23724 /* Subroutine of resolve_overloaded_unification; does deduction for a single
23725 overload. Fills TARGS with any deduced arguments, or error_mark_node if
23726 different overloads deduce different arguments for a given parm.
23727 ADDR_P is true if the expression for which deduction is being
23728 performed was of the form "& fn" rather than simply "fn".
23730 Returns 1 on success. */
23732 static int
23733 try_one_overload (tree tparms,
23734 tree orig_targs,
23735 tree targs,
23736 tree parm,
23737 tree arg,
23738 unification_kind_t strict,
23739 int sub_strict,
23740 bool addr_p,
23741 bool explain_p)
23743 int nargs;
23744 tree tempargs;
23745 int i;
23747 if (arg == error_mark_node)
23748 return 0;
23750 /* [temp.deduct.type] A template-argument can be deduced from a pointer
23751 to function or pointer to member function argument if the set of
23752 overloaded functions does not contain function templates and at most
23753 one of a set of overloaded functions provides a unique match.
23755 So if this is a template, just return success. */
23757 if (uses_template_parms (arg))
23758 return 1;
23760 if (TREE_CODE (arg) == METHOD_TYPE)
23761 arg = build_ptrmemfunc_type (build_pointer_type (arg));
23762 else if (addr_p)
23763 arg = build_pointer_type (arg);
23765 sub_strict |= maybe_adjust_types_for_deduction (tparms, strict,
23766 &parm, &arg, NULL_TREE);
23768 /* We don't copy orig_targs for this because if we have already deduced
23769 some template args from previous args, unify would complain when we
23770 try to deduce a template parameter for the same argument, even though
23771 there isn't really a conflict. */
23772 nargs = TREE_VEC_LENGTH (targs);
23773 tempargs = make_tree_vec (nargs);
23775 if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
23776 return 0;
23778 /* First make sure we didn't deduce anything that conflicts with
23779 explicitly specified args. */
23780 for (i = nargs; i--; )
23782 tree elt = TREE_VEC_ELT (tempargs, i);
23783 tree oldelt = TREE_VEC_ELT (orig_targs, i);
23785 if (!elt)
23786 /*NOP*/;
23787 else if (uses_template_parms (elt))
23788 /* Since we're unifying against ourselves, we will fill in
23789 template args used in the function parm list with our own
23790 template parms. Discard them. */
23791 TREE_VEC_ELT (tempargs, i) = NULL_TREE;
23792 else if (oldelt && ARGUMENT_PACK_P (oldelt))
23794 /* Check that the argument at each index of the deduced argument pack
23795 is equivalent to the corresponding explicitly specified argument.
23796 We may have deduced more arguments than were explicitly specified,
23797 and that's OK. */
23799 /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
23800 that's wrong if we deduce the same argument pack from multiple
23801 function arguments: it's only incomplete the first time. */
23803 tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
23804 tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
23806 if (TREE_VEC_LENGTH (deduced_pack)
23807 < TREE_VEC_LENGTH (explicit_pack))
23808 return 0;
23810 for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
23811 if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
23812 TREE_VEC_ELT (deduced_pack, j)))
23813 return 0;
23815 else if (oldelt && !template_args_equal (oldelt, elt))
23816 return 0;
23819 for (i = nargs; i--; )
23821 tree elt = TREE_VEC_ELT (tempargs, i);
23823 if (elt)
23824 TREE_VEC_ELT (targs, i) = elt;
23827 return 1;
23830 /* PARM is a template class (perhaps with unbound template
23831 parameters). ARG is a fully instantiated type. If ARG can be
23832 bound to PARM, return ARG, otherwise return NULL_TREE. TPARMS and
23833 TARGS are as for unify. */
23835 static tree
23836 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
23837 bool explain_p)
23839 if (!CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
23840 return NULL_TREE;
23841 else if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23842 /* Matches anything. */;
23843 else if (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
23844 != most_general_template (CLASSTYPE_TI_TEMPLATE (parm)))
23845 return NULL_TREE;
23847 /* We need to make a new template argument vector for the call to
23848 unify. If we used TARGS, we'd clutter it up with the result of
23849 the attempted unification, even if this class didn't work out.
23850 We also don't want to commit ourselves to all the unifications
23851 we've already done, since unification is supposed to be done on
23852 an argument-by-argument basis. In other words, consider the
23853 following pathological case:
23855 template <int I, int J, int K>
23856 struct S {};
23858 template <int I, int J>
23859 struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
23861 template <int I, int J, int K>
23862 void f(S<I, J, K>, S<I, I, I>);
23864 void g() {
23865 S<0, 0, 0> s0;
23866 S<0, 1, 2> s2;
23868 f(s0, s2);
23871 Now, by the time we consider the unification involving `s2', we
23872 already know that we must have `f<0, 0, 0>'. But, even though
23873 `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
23874 because there are two ways to unify base classes of S<0, 1, 2>
23875 with S<I, I, I>. If we kept the already deduced knowledge, we
23876 would reject the possibility I=1. */
23877 targs = copy_template_args (targs);
23878 for (tree& targ : tree_vec_range (INNERMOST_TEMPLATE_ARGS (targs)))
23879 targ = NULL_TREE;
23881 int err;
23882 if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23883 err = unify_bound_ttp_args (tparms, targs, parm, arg, explain_p);
23884 else
23885 err = unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
23886 CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p);
23888 return err ? NULL_TREE : arg;
23891 /* Given a template type PARM and a class type ARG, find the unique
23892 base type in ARG that is an instance of PARM. We do not examine
23893 ARG itself; only its base-classes. If there is not exactly one
23894 appropriate base class, return NULL_TREE. PARM may be the type of
23895 a partial specialization, as well as a plain template type. Used
23896 by unify. */
23898 static enum template_base_result
23899 get_template_base (tree tparms, tree targs, tree parm, tree arg,
23900 bool explain_p, tree *result)
23902 tree rval = NULL_TREE;
23903 tree binfo;
23905 gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
23907 binfo = TYPE_BINFO (complete_type (arg));
23908 if (!binfo)
23910 /* The type could not be completed. */
23911 *result = NULL_TREE;
23912 return tbr_incomplete_type;
23915 /* Walk in inheritance graph order. The search order is not
23916 important, and this avoids multiple walks of virtual bases. */
23917 for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
23919 tree r = try_class_unification (tparms, targs, parm,
23920 BINFO_TYPE (binfo), explain_p);
23922 if (r)
23924 /* If there is more than one satisfactory baseclass, then:
23926 [temp.deduct.call]
23928 If they yield more than one possible deduced A, the type
23929 deduction fails.
23931 applies. */
23932 if (rval && !same_type_p (r, rval))
23934 /* [temp.deduct.call]/4.3: If there is a class C that is a
23935 (direct or indirect) base class of D and derived (directly or
23936 indirectly) from a class B and that would be a valid deduced
23937 A, the deduced A cannot be B or pointer to B, respectively. */
23938 if (DERIVED_FROM_P (r, rval))
23939 /* Ignore r. */
23940 continue;
23941 else if (DERIVED_FROM_P (rval, r))
23942 /* Ignore rval. */;
23943 else
23945 *result = NULL_TREE;
23946 return tbr_ambiguous_baseclass;
23950 rval = r;
23954 *result = rval;
23955 return tbr_success;
23958 /* Returns the level of DECL, which declares a template parameter. */
23960 static int
23961 template_decl_level (tree decl)
23963 switch (TREE_CODE (decl))
23965 case TYPE_DECL:
23966 case TEMPLATE_DECL:
23967 return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
23969 case PARM_DECL:
23970 return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
23972 default:
23973 gcc_unreachable ();
23975 return 0;
23978 /* Decide whether ARG can be unified with PARM, considering only the
23979 cv-qualifiers of each type, given STRICT as documented for unify.
23980 Returns nonzero iff the unification is OK on that basis. */
23982 static int
23983 check_cv_quals_for_unify (int strict, tree arg, tree parm)
23985 int arg_quals = cp_type_quals (arg);
23986 int parm_quals = cp_type_quals (parm);
23988 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
23989 && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
23991 /* Although a CVR qualifier is ignored when being applied to a
23992 substituted template parameter ([8.3.2]/1 for example), that
23993 does not allow us to unify "const T" with "int&" because both
23994 types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
23995 It is ok when we're allowing additional CV qualifiers
23996 at the outer level [14.8.2.1]/3,1st bullet. */
23997 if ((TYPE_REF_P (arg)
23998 || FUNC_OR_METHOD_TYPE_P (arg))
23999 && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
24000 return 0;
24002 if ((!INDIRECT_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
24003 && (parm_quals & TYPE_QUAL_RESTRICT))
24004 return 0;
24007 if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
24008 && (arg_quals & parm_quals) != parm_quals)
24009 return 0;
24011 if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
24012 && (parm_quals & arg_quals) != arg_quals)
24013 return 0;
24015 return 1;
24018 /* Determines the LEVEL and INDEX for the template parameter PARM. */
24019 void
24020 template_parm_level_and_index (tree parm, int* level, int* index)
24022 if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
24023 || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24024 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24026 *index = TEMPLATE_TYPE_IDX (parm);
24027 *level = TEMPLATE_TYPE_LEVEL (parm);
24029 else
24031 *index = TEMPLATE_PARM_IDX (parm);
24032 *level = TEMPLATE_PARM_LEVEL (parm);
24036 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP) \
24037 do { \
24038 if (unify (TP, TA, P, A, S, EP)) \
24039 return 1; \
24040 } while (0)
24042 /* Unifies the remaining arguments in PACKED_ARGS with the pack
24043 expansion at the end of PACKED_PARMS. Returns 0 if the type
24044 deduction succeeds, 1 otherwise. STRICT is the same as in
24045 fn_type_unification. CALL_ARGS_P is true iff PACKED_ARGS is actually a
24046 function call argument list. We'll need to adjust the arguments to make them
24047 types. SUBR tells us if this is from a recursive call to
24048 type_unification_real, or for comparing two template argument
24049 lists. */
24051 static int
24052 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
24053 tree packed_args, unification_kind_t strict,
24054 bool subr, bool explain_p)
24056 tree parm
24057 = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
24058 tree pattern = PACK_EXPANSION_PATTERN (parm);
24059 tree pack, packs = NULL_TREE;
24060 int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
24062 /* Add in any args remembered from an earlier partial instantiation. */
24063 targs = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (parm), targs);
24064 int levels = TMPL_ARGS_DEPTH (targs);
24066 packed_args = expand_template_argument_pack (packed_args);
24068 int len = TREE_VEC_LENGTH (packed_args);
24070 /* Determine the parameter packs we will be deducing from the
24071 pattern, and record their current deductions. */
24072 for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
24073 pack; pack = TREE_CHAIN (pack))
24075 tree parm_pack = TREE_VALUE (pack);
24076 int idx, level;
24078 /* Only template parameter packs can be deduced, not e.g. function
24079 parameter packs or __bases or __integer_pack. */
24080 if (!TEMPLATE_PARM_P (parm_pack))
24081 continue;
24083 /* Determine the index and level of this parameter pack. */
24084 template_parm_level_and_index (parm_pack, &level, &idx);
24085 if (level > levels)
24086 continue;
24088 /* Keep track of the parameter packs and their corresponding
24089 argument packs. */
24090 packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
24091 TREE_TYPE (packs) = make_tree_vec (len - start);
24094 /* Loop through all of the arguments that have not yet been
24095 unified and unify each with the pattern. */
24096 for (i = start; i < len; i++)
24098 tree parm;
24099 bool any_explicit = false;
24100 tree arg = TREE_VEC_ELT (packed_args, i);
24102 /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
24103 or the element of its argument pack at the current index if
24104 this argument was explicitly specified. */
24105 for (pack = packs; pack; pack = TREE_CHAIN (pack))
24107 int idx, level;
24108 tree arg, pargs;
24109 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
24111 arg = NULL_TREE;
24112 if (TREE_VALUE (pack)
24113 && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
24114 && (i - start < TREE_VEC_LENGTH (pargs)))
24116 any_explicit = true;
24117 arg = TREE_VEC_ELT (pargs, i - start);
24119 TMPL_ARG (targs, level, idx) = arg;
24122 /* If we had explicit template arguments, substitute them into the
24123 pattern before deduction. */
24124 if (any_explicit)
24126 /* Some arguments might still be unspecified or dependent. */
24127 bool dependent;
24128 ++processing_template_decl;
24129 dependent = any_dependent_template_arguments_p (targs);
24130 if (!dependent)
24131 --processing_template_decl;
24132 parm = tsubst (pattern, targs,
24133 explain_p ? tf_warning_or_error : tf_none,
24134 NULL_TREE);
24135 if (dependent)
24136 --processing_template_decl;
24137 if (parm == error_mark_node)
24138 return 1;
24140 else
24141 parm = pattern;
24143 /* Unify the pattern with the current argument. */
24144 if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
24145 explain_p))
24146 return 1;
24148 /* For each parameter pack, collect the deduced value. */
24149 for (pack = packs; pack; pack = TREE_CHAIN (pack))
24151 int idx, level;
24152 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
24154 TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
24155 TMPL_ARG (targs, level, idx);
24159 /* Verify that the results of unification with the parameter packs
24160 produce results consistent with what we've seen before, and make
24161 the deduced argument packs available. */
24162 for (pack = packs; pack; pack = TREE_CHAIN (pack))
24164 tree old_pack = TREE_VALUE (pack);
24165 tree new_args = TREE_TYPE (pack);
24166 int i, len = TREE_VEC_LENGTH (new_args);
24167 int idx, level;
24168 bool nondeduced_p = false;
24170 /* By default keep the original deduced argument pack.
24171 If necessary, more specific code is going to update the
24172 resulting deduced argument later down in this function. */
24173 template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
24174 TMPL_ARG (targs, level, idx) = old_pack;
24176 /* If NEW_ARGS contains any NULL_TREE entries, we didn't
24177 actually deduce anything. */
24178 for (i = 0; i < len && !nondeduced_p; ++i)
24179 if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
24180 nondeduced_p = true;
24181 if (nondeduced_p)
24182 continue;
24184 if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
24186 /* If we had fewer function args than explicit template args,
24187 just use the explicits. */
24188 tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
24189 int explicit_len = TREE_VEC_LENGTH (explicit_args);
24190 if (len < explicit_len)
24191 new_args = explicit_args;
24194 if (!old_pack)
24196 tree result;
24197 /* Build the deduced *_ARGUMENT_PACK. */
24198 if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
24200 result = make_node (NONTYPE_ARGUMENT_PACK);
24201 TREE_CONSTANT (result) = 1;
24203 else
24204 result = cxx_make_type (TYPE_ARGUMENT_PACK);
24206 ARGUMENT_PACK_ARGS (result) = new_args;
24208 /* Note the deduced argument packs for this parameter
24209 pack. */
24210 TMPL_ARG (targs, level, idx) = result;
24212 else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
24213 && (ARGUMENT_PACK_ARGS (old_pack)
24214 == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
24216 /* We only had the explicitly-provided arguments before, but
24217 now we have a complete set of arguments. */
24218 tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
24220 ARGUMENT_PACK_ARGS (old_pack) = new_args;
24221 ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
24222 ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
24224 else
24226 tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
24227 tree old_args = ARGUMENT_PACK_ARGS (old_pack);
24228 temp_override<int> ovl (TREE_VEC_LENGTH (old_args));
24229 /* During template argument deduction for the aggregate deduction
24230 candidate, the number of elements in a trailing parameter pack
24231 is only deduced from the number of remaining function
24232 arguments if it is not otherwise deduced. */
24233 if (cxx_dialect >= cxx20
24234 && TREE_VEC_LENGTH (new_args) < TREE_VEC_LENGTH (old_args)
24235 /* FIXME This isn't set properly for partial instantiations. */
24236 && TPARMS_PRIMARY_TEMPLATE (tparms)
24237 && builtin_guide_p (TPARMS_PRIMARY_TEMPLATE (tparms)))
24238 TREE_VEC_LENGTH (old_args) = TREE_VEC_LENGTH (new_args);
24239 if (!comp_template_args (old_args, new_args,
24240 &bad_old_arg, &bad_new_arg))
24241 /* Inconsistent unification of this parameter pack. */
24242 return unify_parameter_pack_inconsistent (explain_p,
24243 bad_old_arg,
24244 bad_new_arg);
24248 return unify_success (explain_p);
24251 /* Handle unification of the domain of an array. PARM_DOM and ARG_DOM are
24252 INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs. The other
24253 parameters and return value are as for unify. */
24255 static int
24256 unify_array_domain (tree tparms, tree targs,
24257 tree parm_dom, tree arg_dom,
24258 bool explain_p)
24260 tree parm_max;
24261 tree arg_max;
24262 bool parm_cst;
24263 bool arg_cst;
24265 /* Our representation of array types uses "N - 1" as the
24266 TYPE_MAX_VALUE for an array with "N" elements, if "N" is
24267 not an integer constant. We cannot unify arbitrarily
24268 complex expressions, so we eliminate the MINUS_EXPRs
24269 here. */
24270 parm_max = TYPE_MAX_VALUE (parm_dom);
24271 parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
24272 if (!parm_cst)
24274 gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
24275 parm_max = TREE_OPERAND (parm_max, 0);
24277 arg_max = TYPE_MAX_VALUE (arg_dom);
24278 arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
24279 if (!arg_cst)
24281 /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
24282 trying to unify the type of a variable with the type
24283 of a template parameter. For example:
24285 template <unsigned int N>
24286 void f (char (&) [N]);
24287 int g();
24288 void h(int i) {
24289 char a[g(i)];
24290 f(a);
24293 Here, the type of the ARG will be "int [g(i)]", and
24294 may be a SAVE_EXPR, etc. */
24295 if (TREE_CODE (arg_max) != MINUS_EXPR)
24296 return unify_vla_arg (explain_p, arg_dom);
24297 arg_max = TREE_OPERAND (arg_max, 0);
24300 /* If only one of the bounds used a MINUS_EXPR, compensate
24301 by adding one to the other bound. */
24302 if (parm_cst && !arg_cst)
24303 parm_max = fold_build2_loc (input_location, PLUS_EXPR,
24304 integer_type_node,
24305 parm_max,
24306 integer_one_node);
24307 else if (arg_cst && !parm_cst)
24308 arg_max = fold_build2_loc (input_location, PLUS_EXPR,
24309 integer_type_node,
24310 arg_max,
24311 integer_one_node);
24313 return unify (tparms, targs, parm_max, arg_max,
24314 UNIFY_ALLOW_INTEGER, explain_p);
24317 /* Returns whether T, a P or A in unify, is a type, template or expression. */
24319 enum pa_kind_t { pa_type, pa_tmpl, pa_expr };
24321 static pa_kind_t
24322 pa_kind (tree t)
24324 if (PACK_EXPANSION_P (t))
24325 t = PACK_EXPANSION_PATTERN (t);
24326 if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
24327 || TREE_CODE (t) == UNBOUND_CLASS_TEMPLATE
24328 || DECL_TYPE_TEMPLATE_P (t))
24329 return pa_tmpl;
24330 else if (TYPE_P (t))
24331 return pa_type;
24332 else
24333 return pa_expr;
24336 /* Deduce the value of template parameters. TPARMS is the (innermost)
24337 set of template parameters to a template. TARGS is the bindings
24338 for those template parameters, as determined thus far; TARGS may
24339 include template arguments for outer levels of template parameters
24340 as well. PARM is a parameter to a template function, or a
24341 subcomponent of that parameter; ARG is the corresponding argument.
24342 This function attempts to match PARM with ARG in a manner
24343 consistent with the existing assignments in TARGS. If more values
24344 are deduced, then TARGS is updated.
24346 Returns 0 if the type deduction succeeds, 1 otherwise. The
24347 parameter STRICT is a bitwise or of the following flags:
24349 UNIFY_ALLOW_NONE:
24350 Require an exact match between PARM and ARG.
24351 UNIFY_ALLOW_MORE_CV_QUAL:
24352 Allow the deduced ARG to be more cv-qualified (by qualification
24353 conversion) than ARG.
24354 UNIFY_ALLOW_LESS_CV_QUAL:
24355 Allow the deduced ARG to be less cv-qualified than ARG.
24356 UNIFY_ALLOW_DERIVED:
24357 Allow the deduced ARG to be a template base class of ARG,
24358 or a pointer to a template base class of the type pointed to by
24359 ARG.
24360 UNIFY_ALLOW_INTEGER:
24361 Allow any integral type to be deduced. See the TEMPLATE_PARM_INDEX
24362 case for more information.
24363 UNIFY_ALLOW_OUTER_LEVEL:
24364 This is the outermost level of a deduction. Used to determine validity
24365 of qualification conversions. A valid qualification conversion must
24366 have const qualified pointers leading up to the inner type which
24367 requires additional CV quals, except at the outer level, where const
24368 is not required [conv.qual]. It would be normal to set this flag in
24369 addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
24370 UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
24371 This is the outermost level of a deduction, and PARM can be more CV
24372 qualified at this point.
24373 UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
24374 This is the outermost level of a deduction, and PARM can be less CV
24375 qualified at this point. */
24377 static int
24378 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
24379 bool explain_p)
24381 int idx;
24382 tree targ;
24383 tree tparm;
24384 int strict_in = strict;
24385 tsubst_flags_t complain = (explain_p
24386 ? tf_warning_or_error
24387 : tf_none);
24389 /* I don't think this will do the right thing with respect to types.
24390 But the only case I've seen it in so far has been array bounds, where
24391 signedness is the only information lost, and I think that will be
24392 okay. VIEW_CONVERT_EXPR can appear with class NTTP, thanks to
24393 finish_id_expression_1, and are also OK. */
24394 while (CONVERT_EXPR_P (parm) || TREE_CODE (parm) == VIEW_CONVERT_EXPR)
24395 parm = TREE_OPERAND (parm, 0);
24397 if (arg == error_mark_node)
24398 return unify_invalid (explain_p);
24399 if (arg == unknown_type_node
24400 || arg == init_list_type_node)
24401 /* We can't deduce anything from this, but we might get all the
24402 template args from other function args. */
24403 return unify_success (explain_p);
24405 if (parm == any_targ_node || arg == any_targ_node)
24406 return unify_success (explain_p);
24408 /* If PARM uses template parameters, then we can't bail out here,
24409 even if ARG == PARM, since we won't record unifications for the
24410 template parameters. We might need them if we're trying to
24411 figure out which of two things is more specialized. */
24412 if (arg == parm && !uses_template_parms (parm))
24413 return unify_success (explain_p);
24415 /* Handle init lists early, so the rest of the function can assume
24416 we're dealing with a type. */
24417 if (BRACE_ENCLOSED_INITIALIZER_P (arg))
24419 tree elttype;
24420 tree orig_parm = parm;
24422 if (!is_std_init_list (parm)
24423 && TREE_CODE (parm) != ARRAY_TYPE)
24424 /* We can only deduce from an initializer list argument if the
24425 parameter is std::initializer_list or an array; otherwise this
24426 is a non-deduced context. */
24427 return unify_success (explain_p);
24429 if (TREE_CODE (parm) == ARRAY_TYPE)
24430 elttype = TREE_TYPE (parm);
24431 else
24433 elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
24434 /* Deduction is defined in terms of a single type, so just punt
24435 on the (bizarre) std::initializer_list<T...>. */
24436 if (PACK_EXPANSION_P (elttype))
24437 return unify_success (explain_p);
24440 if (strict != DEDUCE_EXACT
24441 && TYPE_P (elttype)
24442 && !uses_deducible_template_parms (elttype))
24443 /* If ELTTYPE has no deducible template parms, skip deduction from
24444 the list elements. */;
24445 else
24446 for (auto &e: CONSTRUCTOR_ELTS (arg))
24448 tree elt = e.value;
24449 int elt_strict = strict;
24451 if (elt == error_mark_node)
24452 return unify_invalid (explain_p);
24454 if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
24456 tree type = TREE_TYPE (elt);
24457 if (type == error_mark_node)
24458 return unify_invalid (explain_p);
24459 /* It should only be possible to get here for a call. */
24460 gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
24461 elt_strict |= maybe_adjust_types_for_deduction
24462 (tparms, DEDUCE_CALL, &elttype, &type, elt);
24463 elt = type;
24466 RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
24467 explain_p);
24470 if (TREE_CODE (parm) == ARRAY_TYPE
24471 && deducible_array_bound (TYPE_DOMAIN (parm)))
24473 /* Also deduce from the length of the initializer list. */
24474 tree max = size_int (CONSTRUCTOR_NELTS (arg));
24475 tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
24476 if (idx == error_mark_node)
24477 return unify_invalid (explain_p);
24478 return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
24479 idx, explain_p);
24482 /* If the std::initializer_list<T> deduction worked, replace the
24483 deduced A with std::initializer_list<A>. */
24484 if (orig_parm != parm)
24486 idx = TEMPLATE_TYPE_IDX (orig_parm);
24487 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24488 targ = listify (targ);
24489 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
24491 return unify_success (explain_p);
24494 /* If parm and arg aren't the same kind of thing (template, type, or
24495 expression), fail early. */
24496 if (pa_kind (parm) != pa_kind (arg))
24497 return unify_invalid (explain_p);
24499 /* Immediately reject some pairs that won't unify because of
24500 cv-qualification mismatches. */
24501 if (TREE_CODE (arg) == TREE_CODE (parm)
24502 && TYPE_P (arg)
24503 /* It is the elements of the array which hold the cv quals of an array
24504 type, and the elements might be template type parms. We'll check
24505 when we recurse. */
24506 && TREE_CODE (arg) != ARRAY_TYPE
24507 /* We check the cv-qualifiers when unifying with template type
24508 parameters below. We want to allow ARG `const T' to unify with
24509 PARM `T' for example, when computing which of two templates
24510 is more specialized, for example. */
24511 && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
24512 && !check_cv_quals_for_unify (strict_in, arg, parm))
24513 return unify_cv_qual_mismatch (explain_p, parm, arg);
24515 if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
24516 && TYPE_P (parm) && !CP_TYPE_CONST_P (parm)
24517 && !FUNC_OR_METHOD_TYPE_P (parm))
24518 strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
24519 /* PMFs recurse at the same level, so don't strip this yet. */
24520 if (!TYPE_PTRMEMFUNC_P (parm))
24521 strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
24522 strict &= ~UNIFY_ALLOW_DERIVED;
24523 strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
24524 strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
24526 switch (TREE_CODE (parm))
24528 case TYPENAME_TYPE:
24529 case SCOPE_REF:
24530 case UNBOUND_CLASS_TEMPLATE:
24531 /* In a type which contains a nested-name-specifier, template
24532 argument values cannot be deduced for template parameters used
24533 within the nested-name-specifier. */
24534 return unify_success (explain_p);
24536 case TEMPLATE_TYPE_PARM:
24537 case TEMPLATE_TEMPLATE_PARM:
24538 case BOUND_TEMPLATE_TEMPLATE_PARM:
24539 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
24540 if (error_operand_p (tparm))
24541 return unify_invalid (explain_p);
24543 if (TEMPLATE_TYPE_LEVEL (parm)
24544 != template_decl_level (tparm))
24545 /* The PARM is not one we're trying to unify. Just check
24546 to see if it matches ARG. */
24548 if (TREE_CODE (arg) == TREE_CODE (parm)
24549 && (is_auto (parm) ? is_auto (arg)
24550 : same_type_p (parm, arg)))
24551 return unify_success (explain_p);
24552 else
24553 return unify_type_mismatch (explain_p, parm, arg);
24555 idx = TEMPLATE_TYPE_IDX (parm);
24556 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24557 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
24558 if (error_operand_p (tparm))
24559 return unify_invalid (explain_p);
24561 /* Check for mixed types and values. */
24562 if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
24563 && TREE_CODE (tparm) != TYPE_DECL)
24564 || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24565 && TREE_CODE (tparm) != TEMPLATE_DECL))
24566 gcc_unreachable ();
24568 if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24570 if ((strict_in & UNIFY_ALLOW_DERIVED)
24571 && CLASS_TYPE_P (arg))
24573 /* First try to match ARG directly. */
24574 tree t = try_class_unification (tparms, targs, parm, arg,
24575 explain_p);
24576 if (!t)
24578 /* Otherwise, look for a suitable base of ARG, as below. */
24579 enum template_base_result r;
24580 r = get_template_base (tparms, targs, parm, arg,
24581 explain_p, &t);
24582 if (!t)
24583 return unify_no_common_base (explain_p, r, parm, arg);
24584 arg = t;
24587 /* ARG must be constructed from a template class or a template
24588 template parameter. */
24589 else if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
24590 && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
24591 return unify_template_deduction_failure (explain_p, parm, arg);
24593 /* Deduce arguments T, i from TT<T> or TT<i>. */
24594 if (unify_bound_ttp_args (tparms, targs, parm, arg, explain_p))
24595 return 1;
24597 arg = TYPE_TI_TEMPLATE (arg);
24598 if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
24599 /* If the template is a template template parameter, use the
24600 TEMPLATE_TEMPLATE_PARM for matching. */
24601 arg = TREE_TYPE (arg);
24603 /* Fall through to deduce template name. */
24606 if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
24607 || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
24609 /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>. */
24611 /* Simple cases: Value already set, does match or doesn't. */
24612 if (targ != NULL_TREE && template_args_equal (targ, arg))
24613 return unify_success (explain_p);
24614 else if (targ)
24615 return unify_inconsistency (explain_p, parm, targ, arg);
24617 else
24619 /* If PARM is `const T' and ARG is only `int', we don't have
24620 a match unless we are allowing additional qualification.
24621 If ARG is `const int' and PARM is just `T' that's OK;
24622 that binds `const int' to `T'. */
24623 if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
24624 arg, parm))
24625 return unify_cv_qual_mismatch (explain_p, parm, arg);
24627 /* Consider the case where ARG is `const volatile int' and
24628 PARM is `const T'. Then, T should be `volatile int'. */
24629 arg = cp_build_qualified_type
24630 (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
24631 if (arg == error_mark_node)
24632 return unify_invalid (explain_p);
24634 /* Simple cases: Value already set, does match or doesn't. */
24635 if (targ != NULL_TREE && same_type_p (targ, arg))
24636 return unify_success (explain_p);
24637 else if (targ)
24638 return unify_inconsistency (explain_p, parm, targ, arg);
24640 /* Make sure that ARG is not a variable-sized array. (Note
24641 that were talking about variable-sized arrays (like
24642 `int[n]'), rather than arrays of unknown size (like
24643 `int[]').) We'll get very confused by such a type since
24644 the bound of the array is not constant, and therefore
24645 not mangleable. Besides, such types are not allowed in
24646 ISO C++, so we can do as we please here. We do allow
24647 them for 'auto' deduction, since that isn't ABI-exposed. */
24648 if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
24649 return unify_vla_arg (explain_p, arg);
24651 /* Strip typedefs as in convert_template_argument. */
24652 arg = canonicalize_type_argument (arg, tf_none);
24655 /* If ARG is a parameter pack or an expansion, we cannot unify
24656 against it unless PARM is also a parameter pack. */
24657 if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
24658 && !template_parameter_pack_p (parm))
24659 return unify_parameter_pack_mismatch (explain_p, parm, arg);
24661 /* If the argument deduction results is a METHOD_TYPE,
24662 then there is a problem.
24663 METHOD_TYPE doesn't map to any real C++ type the result of
24664 the deduction cannot be of that type. */
24665 if (TREE_CODE (arg) == METHOD_TYPE)
24666 return unify_method_type_error (explain_p, arg);
24668 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
24669 return unify_success (explain_p);
24671 case TEMPLATE_PARM_INDEX:
24672 tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
24673 if (error_operand_p (tparm))
24674 return unify_invalid (explain_p);
24676 if (TEMPLATE_PARM_LEVEL (parm)
24677 != template_decl_level (tparm))
24679 /* The PARM is not one we're trying to unify. Just check
24680 to see if it matches ARG. */
24681 int result = !(TREE_CODE (arg) == TREE_CODE (parm)
24682 && cp_tree_equal (parm, arg));
24683 if (result)
24684 unify_expression_unequal (explain_p, parm, arg);
24685 return result;
24688 idx = TEMPLATE_PARM_IDX (parm);
24689 targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
24691 if (targ)
24693 if ((strict & UNIFY_ALLOW_INTEGER)
24694 && TREE_TYPE (targ) && TREE_TYPE (arg)
24695 && CP_INTEGRAL_TYPE_P (TREE_TYPE (targ)))
24696 /* We're deducing from an array bound, the type doesn't matter.
24697 This conversion should match the one below. */
24698 arg = fold (build_nop (TREE_TYPE (targ), arg));
24699 int x = !cp_tree_equal (targ, arg);
24700 if (x)
24701 unify_inconsistency (explain_p, parm, targ, arg);
24702 return x;
24705 /* [temp.deduct.type] If, in the declaration of a function template
24706 with a non-type template-parameter, the non-type
24707 template-parameter is used in an expression in the function
24708 parameter-list and, if the corresponding template-argument is
24709 deduced, the template-argument type shall match the type of the
24710 template-parameter exactly, except that a template-argument
24711 deduced from an array bound may be of any integral type.
24712 The non-type parameter might use already deduced type parameters. */
24713 tparm = TREE_TYPE (parm);
24714 if (TEMPLATE_PARM_LEVEL (parm) > TMPL_ARGS_DEPTH (targs))
24715 /* We don't have enough levels of args to do any substitution. This
24716 can happen in the context of -fnew-ttp-matching. */;
24717 else
24719 ++processing_template_decl;
24720 tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
24721 --processing_template_decl;
24723 if (tree a = type_uses_auto (tparm))
24725 tparm = do_auto_deduction (tparm, arg, a,
24726 complain, adc_unify, targs,
24727 LOOKUP_NORMAL,
24728 TPARMS_PRIMARY_TEMPLATE (tparms));
24729 if (tparm == error_mark_node)
24730 return 1;
24734 if (!TREE_TYPE (arg)
24735 || TREE_CODE (TREE_TYPE (arg)) == DEPENDENT_OPERATOR_TYPE)
24736 /* Template-parameter dependent expression. Just accept it for now.
24737 It will later be processed in convert_template_argument. */
24739 else if (same_type_ignoring_top_level_qualifiers_p
24740 (non_reference (TREE_TYPE (arg)),
24741 non_reference (tparm)))
24742 /* OK. Ignore top-level quals here because a class-type template
24743 parameter object is const. */;
24744 else if ((strict & UNIFY_ALLOW_INTEGER)
24745 && CP_INTEGRAL_TYPE_P (tparm))
24746 /* Convert the ARG to the type of PARM; the deduced non-type
24747 template argument must exactly match the types of the
24748 corresponding parameter. This conversion should match the
24749 one above. */
24750 arg = fold (build_nop (tparm, arg));
24751 else if (uses_template_parms (tparm))
24753 /* We haven't deduced the type of this parameter yet. */
24754 if (cxx_dialect >= cxx17
24755 /* We deduce from array bounds in try_array_deduction. */
24756 && !(strict & UNIFY_ALLOW_INTEGER)
24757 && TEMPLATE_PARM_LEVEL (parm) <= TMPL_ARGS_DEPTH (targs))
24759 /* Deduce it from the non-type argument. As above, ignore
24760 top-level quals here too. */
24761 tree atype = cv_unqualified (TREE_TYPE (arg));
24762 RECUR_AND_CHECK_FAILURE (tparms, targs,
24763 tparm, atype,
24764 UNIFY_ALLOW_NONE, explain_p);
24765 /* Now check whether the type of this parameter is still
24766 dependent, and give up if so. */
24767 ++processing_template_decl;
24768 tparm = tsubst (TREE_TYPE (parm), targs, tf_none, NULL_TREE);
24769 --processing_template_decl;
24770 if (uses_template_parms (tparm))
24771 return unify_success (explain_p);
24773 else
24774 /* Try again later. */
24775 return unify_success (explain_p);
24777 else
24778 return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
24780 /* If ARG is a parameter pack or an expansion, we cannot unify
24781 against it unless PARM is also a parameter pack. */
24782 if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
24783 && !TEMPLATE_PARM_PARAMETER_PACK (parm))
24784 return unify_parameter_pack_mismatch (explain_p, parm, arg);
24787 bool removed_attr = false;
24788 arg = strip_typedefs_expr (arg, &removed_attr);
24790 TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
24791 return unify_success (explain_p);
24793 case PTRMEM_CST:
24795 /* A pointer-to-member constant can be unified only with
24796 another constant. */
24797 if (TREE_CODE (arg) != PTRMEM_CST)
24798 return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
24800 /* Just unify the class member. It would be useless (and possibly
24801 wrong, depending on the strict flags) to unify also
24802 PTRMEM_CST_CLASS, because we want to be sure that both parm and
24803 arg refer to the same variable, even if through different
24804 classes. For instance:
24806 struct A { int x; };
24807 struct B : A { };
24809 Unification of &A::x and &B::x must succeed. */
24810 return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
24811 PTRMEM_CST_MEMBER (arg), strict, explain_p);
24814 case POINTER_TYPE:
24816 if (!TYPE_PTR_P (arg))
24817 return unify_type_mismatch (explain_p, parm, arg);
24819 /* [temp.deduct.call]
24821 A can be another pointer or pointer to member type that can
24822 be converted to the deduced A via a qualification
24823 conversion (_conv.qual_).
24825 We pass down STRICT here rather than UNIFY_ALLOW_NONE.
24826 This will allow for additional cv-qualification of the
24827 pointed-to types if appropriate. */
24829 if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
24830 /* The derived-to-base conversion only persists through one
24831 level of pointers. */
24832 strict |= (strict_in & UNIFY_ALLOW_DERIVED);
24834 return unify (tparms, targs, TREE_TYPE (parm),
24835 TREE_TYPE (arg), strict, explain_p);
24838 case REFERENCE_TYPE:
24839 if (!TYPE_REF_P (arg))
24840 return unify_type_mismatch (explain_p, parm, arg);
24841 return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24842 strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
24844 case ARRAY_TYPE:
24845 if (TREE_CODE (arg) != ARRAY_TYPE)
24846 return unify_type_mismatch (explain_p, parm, arg);
24847 if ((TYPE_DOMAIN (parm) == NULL_TREE)
24848 != (TYPE_DOMAIN (arg) == NULL_TREE))
24849 return unify_type_mismatch (explain_p, parm, arg);
24850 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
24851 strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
24852 if (TYPE_DOMAIN (parm) != NULL_TREE)
24853 return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
24854 TYPE_DOMAIN (arg), explain_p);
24855 return unify_success (explain_p);
24857 case REAL_TYPE:
24858 case COMPLEX_TYPE:
24859 case VECTOR_TYPE:
24860 case INTEGER_TYPE:
24861 case BOOLEAN_TYPE:
24862 case ENUMERAL_TYPE:
24863 case VOID_TYPE:
24864 case OPAQUE_TYPE:
24865 case NULLPTR_TYPE:
24866 if (TREE_CODE (arg) != TREE_CODE (parm))
24867 return unify_type_mismatch (explain_p, parm, arg);
24869 /* We have already checked cv-qualification at the top of the
24870 function. */
24871 if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
24872 return unify_type_mismatch (explain_p, parm, arg);
24874 /* As far as unification is concerned, this wins. Later checks
24875 will invalidate it if necessary. */
24876 return unify_success (explain_p);
24878 /* Types INTEGER_CST and MINUS_EXPR can come from array bounds. */
24879 /* Type INTEGER_CST can come from ordinary constant template args. */
24880 case INTEGER_CST:
24881 while (CONVERT_EXPR_P (arg))
24882 arg = TREE_OPERAND (arg, 0);
24884 if (TREE_CODE (arg) != INTEGER_CST)
24885 return unify_template_argument_mismatch (explain_p, parm, arg);
24886 return (tree_int_cst_equal (parm, arg)
24887 ? unify_success (explain_p)
24888 : unify_template_argument_mismatch (explain_p, parm, arg));
24890 case TREE_VEC:
24892 int i, len, argslen;
24893 int parm_variadic_p = 0;
24895 if (TREE_CODE (arg) != TREE_VEC)
24896 return unify_template_argument_mismatch (explain_p, parm, arg);
24898 len = TREE_VEC_LENGTH (parm);
24899 argslen = TREE_VEC_LENGTH (arg);
24901 /* Check for pack expansions in the parameters. */
24902 for (i = 0; i < len; ++i)
24904 if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
24906 if (i == len - 1)
24907 /* We can unify against something with a trailing
24908 parameter pack. */
24909 parm_variadic_p = 1;
24910 else
24911 /* [temp.deduct.type]/9: If the template argument list of
24912 P contains a pack expansion that is not the last
24913 template argument, the entire template argument list
24914 is a non-deduced context. */
24915 return unify_success (explain_p);
24919 /* If we don't have enough arguments to satisfy the parameters
24920 (not counting the pack expression at the end), or we have
24921 too many arguments for a parameter list that doesn't end in
24922 a pack expression, we can't unify. */
24923 if (parm_variadic_p
24924 ? argslen < len - parm_variadic_p
24925 : argslen != len)
24926 return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
24928 /* Unify all of the parameters that precede the (optional)
24929 pack expression. */
24930 for (i = 0; i < len - parm_variadic_p; ++i)
24932 RECUR_AND_CHECK_FAILURE (tparms, targs,
24933 TREE_VEC_ELT (parm, i),
24934 TREE_VEC_ELT (arg, i),
24935 UNIFY_ALLOW_NONE, explain_p);
24937 if (parm_variadic_p)
24938 return unify_pack_expansion (tparms, targs, parm, arg,
24939 DEDUCE_EXACT,
24940 /*subr=*/true, explain_p);
24941 return unify_success (explain_p);
24944 case RECORD_TYPE:
24945 case UNION_TYPE:
24946 if (TREE_CODE (arg) != TREE_CODE (parm))
24947 return unify_type_mismatch (explain_p, parm, arg);
24949 if (TYPE_PTRMEMFUNC_P (parm))
24951 if (!TYPE_PTRMEMFUNC_P (arg))
24952 return unify_type_mismatch (explain_p, parm, arg);
24954 return unify (tparms, targs,
24955 TYPE_PTRMEMFUNC_FN_TYPE (parm),
24956 TYPE_PTRMEMFUNC_FN_TYPE (arg),
24957 strict, explain_p);
24959 else if (TYPE_PTRMEMFUNC_P (arg))
24960 return unify_type_mismatch (explain_p, parm, arg);
24962 if (CLASSTYPE_TEMPLATE_INFO (parm))
24964 tree t = NULL_TREE;
24966 if (strict_in & UNIFY_ALLOW_DERIVED)
24968 /* First, we try to unify the PARM and ARG directly. */
24969 t = try_class_unification (tparms, targs,
24970 parm, arg, explain_p);
24972 if (!t)
24974 /* Fallback to the special case allowed in
24975 [temp.deduct.call]:
24977 If P is a class, and P has the form
24978 template-id, then A can be a derived class of
24979 the deduced A. Likewise, if P is a pointer to
24980 a class of the form template-id, A can be a
24981 pointer to a derived class pointed to by the
24982 deduced A. */
24983 enum template_base_result r;
24984 r = get_template_base (tparms, targs, parm, arg,
24985 explain_p, &t);
24987 if (!t)
24989 /* Don't give the derived diagnostic if we're
24990 already dealing with the same template. */
24991 bool same_template
24992 = (CLASSTYPE_TEMPLATE_INFO (arg)
24993 && (CLASSTYPE_TI_TEMPLATE (parm)
24994 == CLASSTYPE_TI_TEMPLATE (arg)));
24995 return unify_no_common_base (explain_p && !same_template,
24996 r, parm, arg);
25000 else if (CLASSTYPE_TEMPLATE_INFO (arg)
25001 && (CLASSTYPE_TI_TEMPLATE (parm)
25002 == CLASSTYPE_TI_TEMPLATE (arg)))
25003 /* Perhaps PARM is something like S<U> and ARG is S<int>.
25004 Then, we should unify `int' and `U'. */
25005 t = arg;
25006 else
25007 /* There's no chance of unification succeeding. */
25008 return unify_type_mismatch (explain_p, parm, arg);
25010 return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
25011 CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
25013 else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
25014 return unify_type_mismatch (explain_p, parm, arg);
25015 return unify_success (explain_p);
25017 case METHOD_TYPE:
25018 case FUNCTION_TYPE:
25020 unsigned int nargs;
25021 tree *args;
25022 tree a;
25023 unsigned int i;
25025 if (TREE_CODE (arg) != TREE_CODE (parm))
25026 return unify_type_mismatch (explain_p, parm, arg);
25028 /* CV qualifications for methods can never be deduced, they must
25029 match exactly. We need to check them explicitly here,
25030 because type_unification_real treats them as any other
25031 cv-qualified parameter. */
25032 if (TREE_CODE (parm) == METHOD_TYPE
25033 && (!check_cv_quals_for_unify
25034 (UNIFY_ALLOW_NONE,
25035 class_of_this_parm (arg),
25036 class_of_this_parm (parm))))
25037 return unify_cv_qual_mismatch (explain_p, parm, arg);
25038 if (TREE_CODE (arg) == FUNCTION_TYPE
25039 && type_memfn_quals (parm) != type_memfn_quals (arg))
25040 return unify_cv_qual_mismatch (explain_p, parm, arg);
25041 if (type_memfn_rqual (parm) != type_memfn_rqual (arg))
25042 return unify_type_mismatch (explain_p, parm, arg);
25044 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
25045 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
25047 nargs = list_length (TYPE_ARG_TYPES (arg));
25048 args = XALLOCAVEC (tree, nargs);
25049 for (a = TYPE_ARG_TYPES (arg), i = 0;
25050 a != NULL_TREE && a != void_list_node;
25051 a = TREE_CHAIN (a), ++i)
25052 args[i] = TREE_VALUE (a);
25053 nargs = i;
25055 if (type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
25056 args, nargs, 1, DEDUCE_EXACT,
25057 NULL, explain_p))
25058 return 1;
25060 if (flag_noexcept_type)
25062 tree pspec = TYPE_RAISES_EXCEPTIONS (parm);
25063 tree aspec = canonical_eh_spec (TYPE_RAISES_EXCEPTIONS (arg));
25064 if (pspec == NULL_TREE) pspec = noexcept_false_spec;
25065 if (aspec == NULL_TREE) aspec = noexcept_false_spec;
25066 if (TREE_PURPOSE (pspec) && TREE_PURPOSE (aspec)
25067 && uses_template_parms (TREE_PURPOSE (pspec)))
25068 RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_PURPOSE (pspec),
25069 TREE_PURPOSE (aspec),
25070 UNIFY_ALLOW_NONE, explain_p);
25071 else
25073 bool pn = nothrow_spec_p (pspec);
25074 bool an = nothrow_spec_p (aspec);
25075 /* Here "less cv-qual" means the deduced arg (i.e. parm) has
25076 /more/ noexcept, since function pointer conversions are the
25077 reverse of qualification conversions. */
25078 if (an == pn
25079 || (an < pn && (strict & UNIFY_ALLOW_LESS_CV_QUAL))
25080 || (an > pn && (strict & UNIFY_ALLOW_MORE_CV_QUAL)))
25081 /* OK. */;
25082 else
25083 return unify_type_mismatch (explain_p, parm, arg);
25086 if (flag_tm)
25088 /* As for noexcept. */
25089 bool pn = tx_safe_fn_type_p (parm);
25090 bool an = tx_safe_fn_type_p (arg);
25091 if (an == pn
25092 || (an < pn && (strict & UNIFY_ALLOW_LESS_CV_QUAL))
25093 || (an > pn && (strict & UNIFY_ALLOW_MORE_CV_QUAL)))
25094 /* OK. */;
25095 else
25096 return unify_type_mismatch (explain_p, parm, arg);
25099 return 0;
25102 case OFFSET_TYPE:
25103 /* Unify a pointer to member with a pointer to member function, which
25104 deduces the type of the member as a function type. */
25105 if (TYPE_PTRMEMFUNC_P (arg))
25107 /* Check top-level cv qualifiers */
25108 if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
25109 return unify_cv_qual_mismatch (explain_p, parm, arg);
25111 RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
25112 TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
25113 UNIFY_ALLOW_NONE, explain_p);
25115 /* Determine the type of the function we are unifying against. */
25116 tree fntype = static_fn_type (arg);
25118 return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
25121 if (TREE_CODE (arg) != OFFSET_TYPE)
25122 return unify_type_mismatch (explain_p, parm, arg);
25123 RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
25124 TYPE_OFFSET_BASETYPE (arg),
25125 UNIFY_ALLOW_NONE, explain_p);
25126 return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
25127 strict, explain_p);
25129 case CONST_DECL:
25130 if (DECL_TEMPLATE_PARM_P (parm))
25131 return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
25132 if (arg != scalar_constant_value (parm))
25133 return unify_template_argument_mismatch (explain_p, parm, arg);
25134 return unify_success (explain_p);
25136 case FIELD_DECL:
25137 case TEMPLATE_DECL:
25138 /* Matched cases are handled by the ARG == PARM test above. */
25139 return unify_template_argument_mismatch (explain_p, parm, arg);
25141 case VAR_DECL:
25142 /* We might get a variable as a non-type template argument in parm if the
25143 corresponding parameter is type-dependent. Make any necessary
25144 adjustments based on whether arg is a reference. */
25145 if (CONSTANT_CLASS_P (arg))
25146 parm = fold_non_dependent_expr (parm, complain);
25147 else if (REFERENCE_REF_P (arg))
25149 tree sub = TREE_OPERAND (arg, 0);
25150 STRIP_NOPS (sub);
25151 if (TREE_CODE (sub) == ADDR_EXPR)
25152 arg = TREE_OPERAND (sub, 0);
25154 /* Now use the normal expression code to check whether they match. */
25155 goto expr;
25157 case TYPE_ARGUMENT_PACK:
25158 case NONTYPE_ARGUMENT_PACK:
25159 return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
25160 ARGUMENT_PACK_ARGS (arg), strict, explain_p);
25162 case TYPEOF_TYPE:
25163 case DECLTYPE_TYPE:
25164 case TRAIT_TYPE:
25165 /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
25166 or TRAIT_TYPE nodes. */
25167 return unify_success (explain_p);
25169 case ERROR_MARK:
25170 /* Unification fails if we hit an error node. */
25171 return unify_invalid (explain_p);
25173 case INDIRECT_REF:
25174 if (REFERENCE_REF_P (parm))
25176 bool pexp = PACK_EXPANSION_P (arg);
25177 if (pexp)
25178 arg = PACK_EXPANSION_PATTERN (arg);
25179 if (REFERENCE_REF_P (arg))
25180 arg = TREE_OPERAND (arg, 0);
25181 if (pexp)
25182 arg = make_pack_expansion (arg, complain);
25183 return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
25184 strict, explain_p);
25186 /* FALLTHRU */
25188 default:
25189 /* An unresolved overload is a nondeduced context. */
25190 if (is_overloaded_fn (parm) || type_unknown_p (parm))
25191 return unify_success (explain_p);
25192 gcc_assert (EXPR_P (parm)
25193 || TREE_CODE (parm) == CONSTRUCTOR
25194 || TREE_CODE (parm) == TRAIT_EXPR);
25195 expr:
25196 /* We must be looking at an expression. This can happen with
25197 something like:
25199 template <int I>
25200 void foo(S<I>, S<I + 2>);
25204 template<typename T>
25205 void foo(A<T, T{}>);
25207 This is a "non-deduced context":
25209 [deduct.type]
25211 The non-deduced contexts are:
25213 --A non-type template argument or an array bound in which
25214 a subexpression references a template parameter.
25216 In these cases, we assume deduction succeeded, but don't
25217 actually infer any unifications. */
25219 if (!uses_template_parms (parm)
25220 && !template_args_equal (parm, arg))
25221 return unify_expression_unequal (explain_p, parm, arg);
25222 else
25223 return unify_success (explain_p);
25226 #undef RECUR_AND_CHECK_FAILURE
25228 /* Note that DECL can be defined in this translation unit, if
25229 required. */
25231 static void
25232 mark_definable (tree decl)
25234 tree clone;
25235 DECL_NOT_REALLY_EXTERN (decl) = 1;
25236 FOR_EACH_CLONE (clone, decl)
25237 DECL_NOT_REALLY_EXTERN (clone) = 1;
25240 /* Called if RESULT is explicitly instantiated, or is a member of an
25241 explicitly instantiated class. */
25243 void
25244 mark_decl_instantiated (tree result, int extern_p)
25246 SET_DECL_EXPLICIT_INSTANTIATION (result);
25248 /* If this entity has already been written out, it's too late to
25249 make any modifications. */
25250 if (TREE_ASM_WRITTEN (result))
25251 return;
25253 /* consteval functions are never emitted. */
25254 if (TREE_CODE (result) == FUNCTION_DECL
25255 && DECL_IMMEDIATE_FUNCTION_P (result))
25256 return;
25258 /* For anonymous namespace we don't need to do anything. */
25259 if (decl_internal_context_p (result))
25261 gcc_assert (!TREE_PUBLIC (result));
25262 return;
25265 if (TREE_CODE (result) != FUNCTION_DECL)
25266 /* The TREE_PUBLIC flag for function declarations will have been
25267 set correctly by tsubst. */
25268 TREE_PUBLIC (result) = 1;
25270 if (extern_p)
25272 DECL_EXTERNAL (result) = 1;
25273 DECL_NOT_REALLY_EXTERN (result) = 0;
25275 else
25277 mark_definable (result);
25278 mark_needed (result);
25279 /* Always make artificials weak. */
25280 if (DECL_ARTIFICIAL (result) && flag_weak)
25281 comdat_linkage (result);
25282 /* For WIN32 we also want to put explicit instantiations in
25283 linkonce sections. */
25284 else if (TREE_PUBLIC (result))
25285 maybe_make_one_only (result);
25286 if (TREE_CODE (result) == FUNCTION_DECL
25287 && DECL_TEMPLATE_INSTANTIATED (result))
25288 /* If the function has already been instantiated, clear DECL_EXTERNAL,
25289 since start_preparsed_function wouldn't have if we had an earlier
25290 extern explicit instantiation. */
25291 DECL_EXTERNAL (result) = 0;
25294 /* If EXTERN_P, then this function will not be emitted -- unless
25295 followed by an explicit instantiation, at which point its linkage
25296 will be adjusted. If !EXTERN_P, then this function will be
25297 emitted here. In neither circumstance do we want
25298 import_export_decl to adjust the linkage. */
25299 DECL_INTERFACE_KNOWN (result) = 1;
25302 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
25303 important template arguments. If any are missing, we check whether
25304 they're important by using error_mark_node for substituting into any
25305 args that were used for partial ordering (the ones between ARGS and END)
25306 and seeing if it bubbles up. */
25308 static bool
25309 check_undeduced_parms (tree targs, tree args, tree end)
25311 bool found = false;
25312 for (tree& targ : tree_vec_range (targs))
25313 if (targ == NULL_TREE)
25315 found = true;
25316 targ = error_mark_node;
25318 if (found)
25320 tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
25321 if (substed == error_mark_node)
25322 return true;
25324 return false;
25327 /* Given two function templates PAT1 and PAT2, return:
25329 1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
25330 -1 if PAT2 is more specialized than PAT1.
25331 0 if neither is more specialized.
25333 LEN indicates the number of parameters we should consider
25334 (defaulted parameters should not be considered).
25336 The 1998 std underspecified function template partial ordering, and
25337 DR214 addresses the issue. We take pairs of arguments, one from
25338 each of the templates, and deduce them against each other. One of
25339 the templates will be more specialized if all the *other*
25340 template's arguments deduce against its arguments and at least one
25341 of its arguments *does* *not* deduce against the other template's
25342 corresponding argument. Deduction is done as for class templates.
25343 The arguments used in deduction have reference and top level cv
25344 qualifiers removed. Iff both arguments were originally reference
25345 types *and* deduction succeeds in both directions, an lvalue reference
25346 wins against an rvalue reference and otherwise the template
25347 with the more cv-qualified argument wins for that pairing (if
25348 neither is more cv-qualified, they both are equal). Unlike regular
25349 deduction, after all the arguments have been deduced in this way,
25350 we do *not* verify the deduced template argument values can be
25351 substituted into non-deduced contexts.
25353 The logic can be a bit confusing here, because we look at deduce1 and
25354 targs1 to see if pat2 is at least as specialized, and vice versa; if we
25355 can find template arguments for pat1 to make arg1 look like arg2, that
25356 means that arg2 is at least as specialized as arg1. */
25359 more_specialized_fn (tree pat1, tree pat2, int len)
25361 tree decl1 = DECL_TEMPLATE_RESULT (pat1);
25362 tree decl2 = DECL_TEMPLATE_RESULT (pat2);
25363 tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
25364 tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
25365 tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
25366 tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
25367 tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
25368 tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
25369 tree origs1, origs2;
25370 bool lose1 = false;
25371 bool lose2 = false;
25373 /* Remove the this parameter from non-static member functions. If
25374 one is a non-static member function and the other is not a static
25375 member function, remove the first parameter from that function
25376 also. This situation occurs for operator functions where we
25377 locate both a member function (with this pointer) and non-member
25378 operator (with explicit first operand). */
25379 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
25381 len--; /* LEN is the number of significant arguments for DECL1 */
25382 args1 = TREE_CHAIN (args1);
25383 if (!DECL_STATIC_FUNCTION_P (decl2))
25384 args2 = TREE_CHAIN (args2);
25386 else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
25388 args2 = TREE_CHAIN (args2);
25389 if (!DECL_STATIC_FUNCTION_P (decl1))
25391 len--;
25392 args1 = TREE_CHAIN (args1);
25396 /* If only one is a conversion operator, they are unordered. */
25397 if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
25398 return 0;
25400 /* Consider the return type for a conversion function */
25401 if (DECL_CONV_FN_P (decl1))
25403 args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
25404 args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
25405 len++;
25408 processing_template_decl++;
25410 origs1 = args1;
25411 origs2 = args2;
25413 while (len--
25414 /* Stop when an ellipsis is seen. */
25415 && args1 != NULL_TREE && args2 != NULL_TREE)
25417 tree arg1 = TREE_VALUE (args1);
25418 tree arg2 = TREE_VALUE (args2);
25419 int deduce1, deduce2;
25420 int quals1 = -1;
25421 int quals2 = -1;
25422 int ref1 = 0;
25423 int ref2 = 0;
25425 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
25426 && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25428 /* When both arguments are pack expansions, we need only
25429 unify the patterns themselves. */
25430 arg1 = PACK_EXPANSION_PATTERN (arg1);
25431 arg2 = PACK_EXPANSION_PATTERN (arg2);
25433 /* This is the last comparison we need to do. */
25434 len = 0;
25437 if (TYPE_REF_P (arg1))
25439 ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
25440 arg1 = TREE_TYPE (arg1);
25441 quals1 = cp_type_quals (arg1);
25444 if (TYPE_REF_P (arg2))
25446 ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
25447 arg2 = TREE_TYPE (arg2);
25448 quals2 = cp_type_quals (arg2);
25451 arg1 = TYPE_MAIN_VARIANT (arg1);
25452 arg2 = TYPE_MAIN_VARIANT (arg2);
25454 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
25456 int i, len2 = remaining_arguments (args2);
25457 tree parmvec = make_tree_vec (1);
25458 tree argvec = make_tree_vec (len2);
25459 tree ta = args2;
25461 /* Setup the parameter vector, which contains only ARG1. */
25462 TREE_VEC_ELT (parmvec, 0) = arg1;
25464 /* Setup the argument vector, which contains the remaining
25465 arguments. */
25466 for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
25467 TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
25469 deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
25470 argvec, DEDUCE_EXACT,
25471 /*subr=*/true, /*explain_p=*/false)
25472 == 0);
25474 /* We cannot deduce in the other direction, because ARG1 is
25475 a pack expansion but ARG2 is not. */
25476 deduce2 = 0;
25478 else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25480 int i, len1 = remaining_arguments (args1);
25481 tree parmvec = make_tree_vec (1);
25482 tree argvec = make_tree_vec (len1);
25483 tree ta = args1;
25485 /* Setup the parameter vector, which contains only ARG1. */
25486 TREE_VEC_ELT (parmvec, 0) = arg2;
25488 /* Setup the argument vector, which contains the remaining
25489 arguments. */
25490 for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
25491 TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
25493 deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
25494 argvec, DEDUCE_EXACT,
25495 /*subr=*/true, /*explain_p=*/false)
25496 == 0);
25498 /* We cannot deduce in the other direction, because ARG2 is
25499 a pack expansion but ARG1 is not.*/
25500 deduce1 = 0;
25503 else
25505 /* The normal case, where neither argument is a pack
25506 expansion. */
25507 deduce1 = (unify (tparms1, targs1, arg1, arg2,
25508 UNIFY_ALLOW_NONE, /*explain_p=*/false)
25509 == 0);
25510 deduce2 = (unify (tparms2, targs2, arg2, arg1,
25511 UNIFY_ALLOW_NONE, /*explain_p=*/false)
25512 == 0);
25515 /* If we couldn't deduce arguments for tparms1 to make arg1 match
25516 arg2, then arg2 is not as specialized as arg1. */
25517 if (!deduce1)
25518 lose2 = true;
25519 if (!deduce2)
25520 lose1 = true;
25522 /* "If, for a given type, deduction succeeds in both directions
25523 (i.e., the types are identical after the transformations above)
25524 and both P and A were reference types (before being replaced with
25525 the type referred to above):
25526 - if the type from the argument template was an lvalue reference and
25527 the type from the parameter template was not, the argument type is
25528 considered to be more specialized than the other; otherwise,
25529 - if the type from the argument template is more cv-qualified
25530 than the type from the parameter template (as described above),
25531 the argument type is considered to be more specialized than the other;
25532 otherwise,
25533 - neither type is more specialized than the other." */
25535 if (deduce1 && deduce2)
25537 if (ref1 && ref2 && ref1 != ref2)
25539 if (ref1 > ref2)
25540 lose1 = true;
25541 else
25542 lose2 = true;
25544 else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
25546 if ((quals1 & quals2) == quals2)
25547 lose2 = true;
25548 if ((quals1 & quals2) == quals1)
25549 lose1 = true;
25553 if (lose1 && lose2)
25554 /* We've failed to deduce something in either direction.
25555 These must be unordered. */
25556 break;
25558 if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
25559 || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
25560 /* We have already processed all of the arguments in our
25561 handing of the pack expansion type. */
25562 len = 0;
25564 args1 = TREE_CHAIN (args1);
25565 args2 = TREE_CHAIN (args2);
25568 /* "In most cases, all template parameters must have values in order for
25569 deduction to succeed, but for partial ordering purposes a template
25570 parameter may remain without a value provided it is not used in the
25571 types being used for partial ordering."
25573 Thus, if we are missing any of the targs1 we need to substitute into
25574 origs1, then pat2 is not as specialized as pat1. This can happen when
25575 there is a nondeduced context. */
25576 if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
25577 lose2 = true;
25578 if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
25579 lose1 = true;
25581 processing_template_decl--;
25583 /* If both deductions succeed, the partial ordering selects the more
25584 constrained template. */
25585 /* P2113: If the corresponding template-parameters of the
25586 template-parameter-lists are not equivalent ([temp.over.link]) or if
25587 the function parameters that positionally correspond between the two
25588 templates are not of the same type, neither template is more
25589 specialized than the other. */
25590 if (!lose1 && !lose2
25591 && comp_template_parms (DECL_TEMPLATE_PARMS (pat1),
25592 DECL_TEMPLATE_PARMS (pat2))
25593 && compparms (origs1, origs2))
25595 int winner = more_constrained (decl1, decl2);
25596 if (winner > 0)
25597 lose2 = true;
25598 else if (winner < 0)
25599 lose1 = true;
25602 /* All things being equal, if the next argument is a pack expansion
25603 for one function but not for the other, prefer the
25604 non-variadic function. FIXME this is bogus; see c++/41958. */
25605 if (lose1 == lose2
25606 && args1 && TREE_VALUE (args1)
25607 && args2 && TREE_VALUE (args2))
25609 lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
25610 lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
25613 if (lose1 == lose2)
25614 return 0;
25615 else if (!lose1)
25616 return 1;
25617 else
25618 return -1;
25621 /* Determine which of two partial specializations of TMPL is more
25622 specialized.
25624 PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
25625 to the first partial specialization. The TREE_PURPOSE is the
25626 innermost set of template parameters for the partial
25627 specialization. PAT2 is similar, but for the second template.
25629 Return 1 if the first partial specialization is more specialized;
25630 -1 if the second is more specialized; 0 if neither is more
25631 specialized.
25633 See [temp.class.order] for information about determining which of
25634 two templates is more specialized. */
25636 static int
25637 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
25639 tree targs;
25640 int winner = 0;
25641 bool any_deductions = false;
25643 tree tmpl1 = TREE_VALUE (pat1);
25644 tree tmpl2 = TREE_VALUE (pat2);
25645 tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
25646 tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
25648 /* Just like what happens for functions, if we are ordering between
25649 different template specializations, we may encounter dependent
25650 types in the arguments, and we need our dependency check functions
25651 to behave correctly. */
25652 ++processing_template_decl;
25653 targs = get_partial_spec_bindings (tmpl, tmpl1, specargs2);
25654 if (targs)
25656 --winner;
25657 any_deductions = true;
25660 targs = get_partial_spec_bindings (tmpl, tmpl2, specargs1);
25661 if (targs)
25663 ++winner;
25664 any_deductions = true;
25666 --processing_template_decl;
25668 /* If both deductions succeed, the partial ordering selects the more
25669 constrained template. */
25670 if (!winner && any_deductions)
25671 winner = more_constrained (tmpl1, tmpl2);
25673 /* In the case of a tie where at least one of the templates
25674 has a parameter pack at the end, the template with the most
25675 non-packed parameters wins. */
25676 if (winner == 0
25677 && any_deductions
25678 && (template_args_variadic_p (TREE_PURPOSE (pat1))
25679 || template_args_variadic_p (TREE_PURPOSE (pat2))))
25681 tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
25682 tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
25683 int len1 = TREE_VEC_LENGTH (args1);
25684 int len2 = TREE_VEC_LENGTH (args2);
25686 /* We don't count the pack expansion at the end. */
25687 if (template_args_variadic_p (TREE_PURPOSE (pat1)))
25688 --len1;
25689 if (template_args_variadic_p (TREE_PURPOSE (pat2)))
25690 --len2;
25692 if (len1 > len2)
25693 return 1;
25694 else if (len1 < len2)
25695 return -1;
25698 return winner;
25701 /* Return the template arguments that will produce the function signature
25702 DECL from the function template FN, with the explicit template
25703 arguments EXPLICIT_ARGS. If CHECK_RETTYPE is true, the return type must
25704 also match. Return NULL_TREE if no satisfactory arguments could be
25705 found. */
25707 static tree
25708 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
25710 int ntparms = DECL_NTPARMS (fn);
25711 tree targs = make_tree_vec (ntparms);
25712 tree decl_type = TREE_TYPE (decl);
25713 tree decl_arg_types;
25714 tree *args;
25715 unsigned int nargs, ix;
25716 tree arg;
25718 gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
25720 /* Never do unification on the 'this' parameter. */
25721 decl_arg_types = skip_artificial_parms_for (decl,
25722 TYPE_ARG_TYPES (decl_type));
25724 nargs = list_length (decl_arg_types);
25725 args = XALLOCAVEC (tree, nargs);
25726 for (arg = decl_arg_types, ix = 0;
25727 arg != NULL_TREE;
25728 arg = TREE_CHAIN (arg), ++ix)
25729 args[ix] = TREE_VALUE (arg);
25731 if (fn_type_unification (fn, explicit_args, targs,
25732 args, ix,
25733 (check_rettype || DECL_CONV_FN_P (fn)
25734 ? TREE_TYPE (decl_type) : NULL_TREE),
25735 DEDUCE_EXACT, LOOKUP_NORMAL, NULL,
25736 /*explain_p=*/false,
25737 /*decltype*/false)
25738 == error_mark_node)
25739 return NULL_TREE;
25741 return targs;
25744 /* Return the innermost template arguments that, when applied to a partial
25745 specialization SPEC_TMPL of TMPL, yield the ARGS.
25747 For example, suppose we have:
25749 template <class T, class U> struct S {};
25750 template <class T> struct S<T*, int> {};
25752 Then, suppose we want to get `S<double*, int>'. SPEC_TMPL will be the
25753 partial specialization and the ARGS will be {double*, int}. The resulting
25754 vector will be {double}, indicating that `T' is bound to `double'. */
25756 static tree
25757 get_partial_spec_bindings (tree tmpl, tree spec_tmpl, tree args)
25759 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
25760 tree spec_args
25761 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (spec_tmpl)));
25762 int i, ntparms = TREE_VEC_LENGTH (tparms);
25763 tree deduced_args;
25764 tree innermost_deduced_args;
25766 innermost_deduced_args = make_tree_vec (ntparms);
25767 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
25769 deduced_args = copy_node (args);
25770 SET_TMPL_ARGS_LEVEL (deduced_args,
25771 TMPL_ARGS_DEPTH (deduced_args),
25772 innermost_deduced_args);
25774 else
25775 deduced_args = innermost_deduced_args;
25777 bool tried_array_deduction = (cxx_dialect < cxx17);
25778 again:
25779 if (unify (tparms, deduced_args,
25780 INNERMOST_TEMPLATE_ARGS (spec_args),
25781 INNERMOST_TEMPLATE_ARGS (args),
25782 UNIFY_ALLOW_NONE, /*explain_p=*/false))
25783 return NULL_TREE;
25785 for (i = 0; i < ntparms; ++i)
25786 if (! TREE_VEC_ELT (innermost_deduced_args, i))
25788 if (!tried_array_deduction)
25790 try_array_deduction (tparms, innermost_deduced_args,
25791 INNERMOST_TEMPLATE_ARGS (spec_args));
25792 tried_array_deduction = true;
25793 if (TREE_VEC_ELT (innermost_deduced_args, i))
25794 goto again;
25796 return NULL_TREE;
25799 if (!push_tinst_level (spec_tmpl, deduced_args))
25801 excessive_deduction_depth = true;
25802 return NULL_TREE;
25805 /* Verify that nondeduced template arguments agree with the type
25806 obtained from argument deduction.
25808 For example:
25810 struct A { typedef int X; };
25811 template <class T, class U> struct C {};
25812 template <class T> struct C<T, typename T::X> {};
25814 Then with the instantiation `C<A, int>', we can deduce that
25815 `T' is `A' but unify () does not check whether `typename T::X'
25816 is `int'. */
25817 spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
25819 if (spec_args != error_mark_node)
25820 spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
25821 INNERMOST_TEMPLATE_ARGS (spec_args),
25822 tmpl, tf_none, false);
25824 pop_tinst_level ();
25826 if (spec_args == error_mark_node
25827 /* We only need to check the innermost arguments; the other
25828 arguments will always agree. */
25829 || !comp_template_args_porder (INNERMOST_TEMPLATE_ARGS (spec_args),
25830 INNERMOST_TEMPLATE_ARGS (args)))
25831 return NULL_TREE;
25833 /* Now that we have bindings for all of the template arguments,
25834 ensure that the arguments deduced for the template template
25835 parameters have compatible template parameter lists. See the use
25836 of template_template_parm_bindings_ok_p in fn_type_unification
25837 for more information. */
25838 if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
25839 return NULL_TREE;
25841 return deduced_args;
25844 // Compare two function templates T1 and T2 by deducing bindings
25845 // from one against the other. If both deductions succeed, compare
25846 // constraints to see which is more constrained.
25847 static int
25848 more_specialized_inst (tree t1, tree t2)
25850 int fate = 0;
25851 int count = 0;
25853 if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
25855 --fate;
25856 ++count;
25859 if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
25861 ++fate;
25862 ++count;
25865 // If both deductions succeed, then one may be more constrained.
25866 if (count == 2 && fate == 0)
25867 fate = more_constrained (t1, t2);
25869 return fate;
25872 /* TEMPLATES is a TREE_LIST. Each TREE_VALUE is a TEMPLATE_DECL.
25873 Return the TREE_LIST node with the most specialized template, if
25874 any. If there is no most specialized template, the error_mark_node
25875 is returned.
25877 Note that this function does not look at, or modify, the
25878 TREE_PURPOSE or TREE_TYPE of any of the nodes. Since the node
25879 returned is one of the elements of INSTANTIATIONS, callers may
25880 store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
25881 and retrieve it from the value returned. */
25883 tree
25884 most_specialized_instantiation (tree templates)
25886 tree fn, champ;
25888 ++processing_template_decl;
25890 champ = templates;
25891 for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
25893 gcc_assert (TREE_VALUE (champ) != TREE_VALUE (fn));
25894 int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
25895 if (fate == -1)
25896 champ = fn;
25897 else if (!fate)
25899 /* Equally specialized, move to next function. If there
25900 is no next function, nothing's most specialized. */
25901 fn = TREE_CHAIN (fn);
25902 champ = fn;
25903 if (!fn)
25904 break;
25908 if (champ)
25909 /* Now verify that champ is better than everything earlier in the
25910 instantiation list. */
25911 for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
25912 if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
25914 champ = NULL_TREE;
25915 break;
25919 processing_template_decl--;
25921 if (!champ)
25922 return error_mark_node;
25924 return champ;
25927 /* If DECL is a specialization of some template, return the most
25928 general such template. Otherwise, returns NULL_TREE.
25930 For example, given:
25932 template <class T> struct S { template <class U> void f(U); };
25934 if TMPL is `template <class U> void S<int>::f(U)' this will return
25935 the full template. This function will not trace past partial
25936 specializations, however. For example, given in addition:
25938 template <class T> struct S<T*> { template <class U> void f(U); };
25940 if TMPL is `template <class U> void S<int*>::f(U)' this will return
25941 `template <class T> template <class U> S<T*>::f(U)'. */
25943 tree
25944 most_general_template (tree decl)
25946 if (TREE_CODE (decl) != TEMPLATE_DECL)
25948 if (tree tinfo = get_template_info (decl))
25949 decl = TI_TEMPLATE (tinfo);
25950 /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
25951 template friend, or a FIELD_DECL for a capture pack. */
25952 if (TREE_CODE (decl) != TEMPLATE_DECL)
25953 return NULL_TREE;
25956 /* Look for more and more general templates. */
25957 while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
25959 /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
25960 (See cp-tree.h for details.) */
25961 if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
25962 break;
25964 if (CLASS_TYPE_P (TREE_TYPE (decl))
25965 && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
25966 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
25967 break;
25969 /* Stop if we run into an explicitly specialized class template. */
25970 if (!DECL_NAMESPACE_SCOPE_P (decl)
25971 && DECL_CONTEXT (decl)
25972 && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
25973 break;
25975 decl = DECL_TI_TEMPLATE (decl);
25978 return decl;
25981 /* Return the most specialized of the template partial specializations
25982 which can produce TARGET, a specialization of some class or variable
25983 template. The value returned is actually a TREE_LIST; the TREE_VALUE is
25984 a TEMPLATE_DECL node corresponding to the partial specialization, while
25985 the TREE_PURPOSE is the set of template arguments that must be
25986 substituted into the template pattern in order to generate TARGET.
25988 If the choice of partial specialization is ambiguous, a diagnostic
25989 is issued, and the error_mark_node is returned. If there are no
25990 partial specializations matching TARGET, then NULL_TREE is
25991 returned, indicating that the primary template should be used. */
25993 tree
25994 most_specialized_partial_spec (tree target, tsubst_flags_t complain)
25996 tree tmpl, args, decl;
25997 if (TYPE_P (target))
25999 tree tinfo = CLASSTYPE_TEMPLATE_INFO (target);
26000 tmpl = TI_TEMPLATE (tinfo);
26001 args = TI_ARGS (tinfo);
26002 decl = TYPE_NAME (target);
26004 else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
26006 tmpl = TREE_OPERAND (target, 0);
26007 args = TREE_OPERAND (target, 1);
26008 decl = DECL_TEMPLATE_RESULT (tmpl);
26010 else if (VAR_P (target))
26012 tree tinfo = DECL_TEMPLATE_INFO (target);
26013 tmpl = TI_TEMPLATE (tinfo);
26014 args = TI_ARGS (tinfo);
26015 decl = target;
26017 else
26018 gcc_unreachable ();
26020 tree main_tmpl = most_general_template (tmpl);
26021 tree specs = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl);
26022 if (!specs)
26023 /* There are no partial specializations of this template. */
26024 return NULL_TREE;
26026 push_access_scope_guard pas (decl);
26027 deferring_access_check_sentinel acs (dk_no_deferred);
26029 /* For determining which partial specialization to use, only the
26030 innermost args are interesting. */
26031 tree outer_args = NULL_TREE;
26032 if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
26034 outer_args = strip_innermost_template_args (args, 1);
26035 args = INNERMOST_TEMPLATE_ARGS (args);
26038 /* The caller hasn't called push_to_top_level yet, but we need
26039 get_partial_spec_bindings to be done in non-template context so that we'll
26040 fully resolve everything. */
26041 processing_template_decl_sentinel ptds;
26043 tree list = NULL_TREE;
26044 for (tree t = specs; t; t = TREE_CHAIN (t))
26046 const tree ospec_tmpl = TREE_VALUE (t);
26048 tree spec_tmpl;
26049 if (outer_args)
26051 /* Substitute in the template args from the enclosing class. */
26052 ++processing_template_decl;
26053 spec_tmpl = tsubst (ospec_tmpl, outer_args, tf_none, NULL_TREE);
26054 --processing_template_decl;
26055 if (spec_tmpl == error_mark_node)
26056 return error_mark_node;
26058 else
26059 spec_tmpl = ospec_tmpl;
26061 tree spec_args = get_partial_spec_bindings (tmpl, spec_tmpl, args);
26062 if (spec_args)
26064 if (outer_args)
26065 spec_args = add_to_template_args (outer_args, spec_args);
26067 /* Keep the candidate only if its constraints are satisfied. */
26068 if (constraints_satisfied_p (ospec_tmpl, spec_args))
26070 list = tree_cons (spec_args, ospec_tmpl, list);
26071 TREE_TYPE (list) = TREE_TYPE (t);
26076 if (! list)
26077 return NULL_TREE;
26079 tree champ = list;
26080 bool ambiguous_p = false;
26081 for (tree t = TREE_CHAIN (list); t; t = TREE_CHAIN (t))
26083 int fate = more_specialized_partial_spec (tmpl, champ, t);
26084 if (fate == 1)
26086 else
26088 if (fate == 0)
26090 t = TREE_CHAIN (t);
26091 if (! t)
26093 ambiguous_p = true;
26094 break;
26097 champ = t;
26101 if (!ambiguous_p)
26102 for (tree t = list; t && t != champ; t = TREE_CHAIN (t))
26104 int fate = more_specialized_partial_spec (tmpl, champ, t);
26105 if (fate != 1)
26107 ambiguous_p = true;
26108 break;
26112 if (ambiguous_p)
26114 const char *str;
26115 char *spaces = NULL;
26116 if (!(complain & tf_error))
26117 return error_mark_node;
26118 if (TYPE_P (target))
26119 error ("ambiguous template instantiation for %q#T", target);
26120 else
26121 error ("ambiguous template instantiation for %q#D", target);
26122 str = ngettext ("candidate is:", "candidates are:", list_length (list));
26123 for (tree t = list; t; t = TREE_CHAIN (t))
26125 tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
26126 inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
26127 "%s %#qS", spaces ? spaces : str, subst);
26128 spaces = spaces ? spaces : get_spaces (str);
26130 free (spaces);
26131 return error_mark_node;
26134 return champ;
26137 /* Explicitly instantiate DECL. */
26139 void
26140 do_decl_instantiation (tree decl, tree storage)
26142 tree result = NULL_TREE;
26143 int extern_p = 0;
26145 if (!decl || decl == error_mark_node)
26146 /* An error occurred, for which grokdeclarator has already issued
26147 an appropriate message. */
26148 return;
26149 else if (! DECL_LANG_SPECIFIC (decl))
26151 error ("explicit instantiation of non-template %q#D", decl);
26152 return;
26154 else if (DECL_DECLARED_CONCEPT_P (decl))
26156 if (VAR_P (decl))
26157 error ("explicit instantiation of variable concept %q#D", decl);
26158 else
26159 error ("explicit instantiation of function concept %q#D", decl);
26160 return;
26163 bool var_templ = (DECL_TEMPLATE_INFO (decl)
26164 && variable_template_p (DECL_TI_TEMPLATE (decl)));
26166 if (VAR_P (decl) && !var_templ)
26168 /* There is an asymmetry here in the way VAR_DECLs and
26169 FUNCTION_DECLs are handled by grokdeclarator. In the case of
26170 the latter, the DECL we get back will be marked as a
26171 template instantiation, and the appropriate
26172 DECL_TEMPLATE_INFO will be set up. This does not happen for
26173 VAR_DECLs so we do the lookup here. Probably, grokdeclarator
26174 should handle VAR_DECLs as it currently handles
26175 FUNCTION_DECLs. */
26176 if (!DECL_CLASS_SCOPE_P (decl))
26178 error ("%qD is not a static data member of a class template", decl);
26179 return;
26181 result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
26182 if (!result || !VAR_P (result))
26184 error ("no matching template for %qD found", decl);
26185 return;
26187 if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
26189 error ("type %qT for explicit instantiation %qD does not match "
26190 "declared type %qT", TREE_TYPE (result), decl,
26191 TREE_TYPE (decl));
26192 return;
26195 else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
26197 error ("explicit instantiation of %q#D", decl);
26198 return;
26200 else
26201 result = decl;
26203 /* Check for various error cases. Note that if the explicit
26204 instantiation is valid the RESULT will currently be marked as an
26205 *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
26206 until we get here. */
26208 if (DECL_TEMPLATE_SPECIALIZATION (result))
26210 /* DR 259 [temp.spec].
26212 Both an explicit instantiation and a declaration of an explicit
26213 specialization shall not appear in a program unless the explicit
26214 instantiation follows a declaration of the explicit specialization.
26216 For a given set of template parameters, if an explicit
26217 instantiation of a template appears after a declaration of an
26218 explicit specialization for that template, the explicit
26219 instantiation has no effect. */
26220 return;
26222 else if (DECL_EXPLICIT_INSTANTIATION (result))
26224 /* [temp.spec]
26226 No program shall explicitly instantiate any template more
26227 than once.
26229 We check DECL_NOT_REALLY_EXTERN so as not to complain when
26230 the first instantiation was `extern' and the second is not,
26231 and EXTERN_P for the opposite case. */
26232 if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
26233 permerror (input_location, "duplicate explicit instantiation of %q#D", result);
26234 /* If an "extern" explicit instantiation follows an ordinary
26235 explicit instantiation, the template is instantiated. */
26236 if (extern_p)
26237 return;
26239 else if (!DECL_IMPLICIT_INSTANTIATION (result))
26241 error ("no matching template for %qD found", result);
26242 return;
26244 else if (!DECL_TEMPLATE_INFO (result))
26246 permerror (input_location, "explicit instantiation of non-template %q#D", result);
26247 return;
26250 if (storage == NULL_TREE)
26252 else if (storage == ridpointers[(int) RID_EXTERN])
26254 if (cxx_dialect == cxx98)
26255 pedwarn (input_location, OPT_Wpedantic,
26256 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
26257 "instantiations");
26258 extern_p = 1;
26260 else
26261 error ("storage class %qD applied to template instantiation", storage);
26263 check_explicit_instantiation_namespace (result);
26264 mark_decl_instantiated (result, extern_p);
26265 if (! extern_p)
26266 instantiate_decl (result, /*defer_ok=*/true,
26267 /*expl_inst_class_mem_p=*/false);
26270 static void
26271 mark_class_instantiated (tree t, int extern_p)
26273 SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
26274 SET_CLASSTYPE_INTERFACE_KNOWN (t);
26275 CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
26276 TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
26277 if (! extern_p)
26279 CLASSTYPE_DEBUG_REQUESTED (t) = 1;
26280 rest_of_type_compilation (t, 1);
26284 /* Perform an explicit instantiation of template class T. STORAGE, if
26285 non-null, is the RID for extern, inline or static. COMPLAIN is
26286 nonzero if this is called from the parser, zero if called recursively,
26287 since the standard is unclear (as detailed below). */
26289 void
26290 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
26292 if (!(CLASS_TYPE_P (t) && CLASSTYPE_TEMPLATE_INFO (t)))
26294 if (tree ti = TYPE_TEMPLATE_INFO (t))
26295 error ("explicit instantiation of non-class template %qD",
26296 TI_TEMPLATE (ti));
26297 else
26298 error ("explicit instantiation of non-template type %qT", t);
26299 return;
26302 complete_type (t);
26304 if (!COMPLETE_TYPE_P (t))
26306 if (complain & tf_error)
26307 error ("explicit instantiation of %q#T before definition of template",
26309 return;
26312 /* At most one of these will be true. */
26313 bool extern_p = false;
26314 bool nomem_p = false;
26315 bool static_p = false;
26317 if (storage != NULL_TREE)
26319 if (storage == ridpointers[(int) RID_EXTERN])
26321 if (cxx_dialect == cxx98)
26322 pedwarn (input_location, OPT_Wpedantic,
26323 "ISO C++ 1998 forbids the use of %<extern%> on "
26324 "explicit instantiations");
26326 else
26327 pedwarn (input_location, OPT_Wpedantic,
26328 "ISO C++ forbids the use of %qE"
26329 " on explicit instantiations", storage);
26331 if (storage == ridpointers[(int) RID_INLINE])
26332 nomem_p = true;
26333 else if (storage == ridpointers[(int) RID_EXTERN])
26334 extern_p = true;
26335 else if (storage == ridpointers[(int) RID_STATIC])
26336 static_p = true;
26337 else
26338 error ("storage class %qD applied to template instantiation",
26339 storage);
26342 if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
26343 /* DR 259 [temp.spec].
26345 Both an explicit instantiation and a declaration of an explicit
26346 specialization shall not appear in a program unless the
26347 explicit instantiation follows a declaration of the explicit
26348 specialization.
26350 For a given set of template parameters, if an explicit
26351 instantiation of a template appears after a declaration of an
26352 explicit specialization for that template, the explicit
26353 instantiation has no effect. */
26354 return;
26356 if (CLASSTYPE_EXPLICIT_INSTANTIATION (t) && !CLASSTYPE_INTERFACE_ONLY (t))
26358 /* We've already instantiated the template. */
26360 /* [temp.spec]
26362 No program shall explicitly instantiate any template more
26363 than once.
26365 If EXTERN_P then this is ok. */
26366 if (!extern_p && (complain & tf_error))
26367 permerror (input_location,
26368 "duplicate explicit instantiation of %q#T", t);
26370 return;
26373 check_explicit_instantiation_namespace (TYPE_NAME (t));
26374 mark_class_instantiated (t, extern_p);
26376 if (nomem_p)
26377 return;
26379 /* In contrast to implicit instantiation, where only the
26380 declarations, and not the definitions, of members are
26381 instantiated, we have here:
26383 [temp.explicit]
26385 An explicit instantiation that names a class template
26386 specialization is also an explicit instantiation of the same
26387 kind (declaration or definition) of each of its members (not
26388 including members inherited from base classes and members
26389 that are templates) that has not been previously explicitly
26390 specialized in the translation unit containing the explicit
26391 instantiation, provided that the associated constraints, if
26392 any, of that member are satisfied by the template arguments
26393 of the explicit instantiation. */
26394 for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
26395 if ((VAR_P (fld)
26396 || (TREE_CODE (fld) == FUNCTION_DECL
26397 && !static_p
26398 && user_provided_p (fld)))
26399 && DECL_TEMPLATE_INSTANTIATION (fld)
26400 && constraints_satisfied_p (fld))
26402 mark_decl_instantiated (fld, extern_p);
26403 if (! extern_p)
26404 instantiate_decl (fld, /*defer_ok=*/true,
26405 /*expl_inst_class_mem_p=*/true);
26407 else if (DECL_IMPLICIT_TYPEDEF_P (fld))
26409 tree type = TREE_TYPE (fld);
26411 if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
26412 && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
26413 do_type_instantiation (type, storage, 0);
26417 /* Given a function DECL, which is a specialization of TMPL, modify
26418 DECL to be a re-instantiation of TMPL with the same template
26419 arguments. TMPL should be the template into which tsubst'ing
26420 should occur for DECL, not the most general template.
26422 One reason for doing this is a scenario like this:
26424 template <class T>
26425 void f(const T&, int i);
26427 void g() { f(3, 7); }
26429 template <class T>
26430 void f(const T& t, const int i) { }
26432 Note that when the template is first instantiated, with
26433 instantiate_template, the resulting DECL will have no name for the
26434 first parameter, and the wrong type for the second. So, when we go
26435 to instantiate the DECL, we regenerate it. */
26437 static void
26438 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
26440 /* The arguments used to instantiate DECL, from the most general
26441 template. */
26442 tree code_pattern = DECL_TEMPLATE_RESULT (tmpl);
26444 /* Make sure that we can see identifiers, and compute access correctly. */
26445 push_access_scope (decl);
26447 if (TREE_CODE (decl) == FUNCTION_DECL)
26449 tree specs;
26450 int args_depth;
26451 int parms_depth;
26453 /* Don't bother with this for unique friends that can't be redeclared and
26454 might change type if regenerated (PR69836). */
26455 if (DECL_UNIQUE_FRIEND_P (decl))
26456 goto done;
26458 /* Use the source location of the definition. */
26459 DECL_SOURCE_LOCATION (decl) = DECL_SOURCE_LOCATION (tmpl);
26461 args_depth = TMPL_ARGS_DEPTH (args);
26462 parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
26463 if (args_depth > parms_depth)
26464 args = get_innermost_template_args (args, parms_depth);
26466 /* Instantiate a dynamic exception-specification. noexcept will be
26467 handled below. */
26468 if (tree raises = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (code_pattern)))
26469 if (TREE_VALUE (raises))
26471 specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
26472 args, tf_error, NULL_TREE,
26473 /*defer_ok*/false);
26474 if (specs && specs != error_mark_node)
26475 TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
26476 specs);
26479 /* Merge parameter declarations. */
26480 if (tree pattern_parm
26481 = skip_artificial_parms_for (code_pattern,
26482 DECL_ARGUMENTS (code_pattern)))
26484 tree *p = &DECL_ARGUMENTS (decl);
26485 for (int skip = num_artificial_parms_for (decl); skip; --skip)
26486 p = &DECL_CHAIN (*p);
26487 *p = tsubst_decl (pattern_parm, args, tf_error);
26488 for (tree t = *p; t; t = DECL_CHAIN (t))
26489 DECL_CONTEXT (t) = decl;
26492 if (DECL_CONTRACTS (decl))
26494 /* If we're regenerating a specialization, the contracts will have
26495 been copied from the most general template. Replace those with
26496 the ones from the actual specialization. */
26497 tree tmpl = DECL_TI_TEMPLATE (decl);
26498 if (DECL_TEMPLATE_SPECIALIZATION (tmpl))
26500 remove_contract_attributes (decl);
26501 copy_contract_attributes (decl, code_pattern);
26504 tsubst_contract_attributes (decl, args, tf_warning_or_error, code_pattern);
26507 /* Merge additional specifiers from the CODE_PATTERN. */
26508 if (DECL_DECLARED_INLINE_P (code_pattern)
26509 && !DECL_DECLARED_INLINE_P (decl))
26510 DECL_DECLARED_INLINE_P (decl) = 1;
26512 maybe_instantiate_noexcept (decl, tf_error);
26514 else if (VAR_P (decl))
26516 start_lambda_scope (decl);
26517 DECL_INITIAL (decl) =
26518 tsubst_init (DECL_INITIAL (code_pattern), decl, args,
26519 tf_error, DECL_TI_TEMPLATE (decl));
26520 finish_lambda_scope ();
26521 if (VAR_HAD_UNKNOWN_BOUND (decl))
26522 TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
26523 tf_error, DECL_TI_TEMPLATE (decl));
26525 else
26526 gcc_unreachable ();
26528 done:
26529 pop_access_scope (decl);
26532 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
26533 substituted to get DECL. */
26535 tree
26536 template_for_substitution (tree decl)
26538 tree tmpl = DECL_TI_TEMPLATE (decl);
26540 /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
26541 for the instantiation. This is not always the most general
26542 template. Consider, for example:
26544 template <class T>
26545 struct S { template <class U> void f();
26546 template <> void f<int>(); };
26548 and an instantiation of S<double>::f<int>. We want TD to be the
26549 specialization S<T>::f<int>, not the more general S<T>::f<U>. */
26550 while (/* An instantiation cannot have a definition, so we need a
26551 more general template. */
26552 DECL_TEMPLATE_INSTANTIATION (tmpl)
26553 /* We must also deal with friend templates. Given:
26555 template <class T> struct S {
26556 template <class U> friend void f() {};
26559 S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
26560 so far as the language is concerned, but that's still
26561 where we get the pattern for the instantiation from. On
26562 other hand, if the definition comes outside the class, say:
26564 template <class T> struct S {
26565 template <class U> friend void f();
26567 template <class U> friend void f() {}
26569 we don't need to look any further. That's what the check for
26570 DECL_INITIAL is for. */
26571 || (TREE_CODE (decl) == FUNCTION_DECL
26572 && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
26573 && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
26575 /* The present template, TD, should not be a definition. If it
26576 were a definition, we should be using it! Note that we
26577 cannot restructure the loop to just keep going until we find
26578 a template with a definition, since that might go too far if
26579 a specialization was declared, but not defined. */
26581 /* Fetch the more general template. */
26582 tmpl = DECL_TI_TEMPLATE (tmpl);
26585 return tmpl;
26588 /* Returns true if we need to instantiate this template instance even if we
26589 know we aren't going to emit it. */
26591 bool
26592 always_instantiate_p (tree decl)
26594 /* We always instantiate inline functions so that we can inline them. An
26595 explicit instantiation declaration prohibits implicit instantiation of
26596 non-inline functions. With high levels of optimization, we would
26597 normally inline non-inline functions -- but we're not allowed to do
26598 that for "extern template" functions. Therefore, we check
26599 DECL_DECLARED_INLINE_P, rather than possibly_inlined_p. */
26600 return ((TREE_CODE (decl) == FUNCTION_DECL
26601 && (DECL_DECLARED_INLINE_P (decl)
26602 || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
26603 /* And we need to instantiate static data members so that
26604 their initializers are available in integral constant
26605 expressions. */
26606 || (VAR_P (decl)
26607 && decl_maybe_constant_var_p (decl)));
26610 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
26611 instantiate it now, modifying TREE_TYPE (fn). Returns false on
26612 error, true otherwise. */
26614 bool
26615 maybe_instantiate_noexcept (tree fn, tsubst_flags_t complain)
26617 if (fn == error_mark_node)
26618 return false;
26620 /* Don't instantiate a noexcept-specification from template context. */
26621 if (processing_template_decl
26622 && (!flag_noexcept_type || type_dependent_expression_p (fn)))
26623 return true;
26625 tree fntype = TREE_TYPE (fn);
26626 tree spec = TYPE_RAISES_EXCEPTIONS (fntype);
26628 if ((!spec || UNEVALUATED_NOEXCEPT_SPEC_P (spec))
26629 && DECL_MAYBE_DELETED (fn))
26631 if (fn == current_function_decl)
26632 /* We're in start_preparsed_function, keep going. */
26633 return true;
26635 ++function_depth;
26636 maybe_synthesize_method (fn);
26637 --function_depth;
26638 return !DECL_DELETED_FN (fn);
26641 if (!spec || !TREE_PURPOSE (spec))
26642 return true;
26644 tree noex = TREE_PURPOSE (spec);
26645 if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
26646 && TREE_CODE (noex) != DEFERRED_PARSE)
26647 return true;
26649 tree orig_fn = NULL_TREE;
26650 /* For a member friend template we can get a TEMPLATE_DECL. Let's use
26651 its FUNCTION_DECL for the rest of this function -- push_access_scope
26652 doesn't accept TEMPLATE_DECLs. */
26653 if (DECL_FUNCTION_TEMPLATE_P (fn))
26655 orig_fn = fn;
26656 fn = DECL_TEMPLATE_RESULT (fn);
26659 if (DECL_CLONED_FUNCTION_P (fn))
26661 tree prime = DECL_CLONED_FUNCTION (fn);
26662 if (!maybe_instantiate_noexcept (prime, complain))
26663 return false;
26664 spec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (prime));
26666 else if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
26668 static hash_set<tree>* fns = new hash_set<tree>;
26669 bool added = false;
26670 if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
26672 spec = get_defaulted_eh_spec (fn, complain);
26673 if (spec == error_mark_node)
26674 /* This might have failed because of an unparsed DMI, so
26675 let's try again later. */
26676 return false;
26678 else if (!(added = !fns->add (fn)))
26680 /* If hash_set::add returns true, the element was already there. */
26681 location_t loc = cp_expr_loc_or_loc (DEFERRED_NOEXCEPT_PATTERN (noex),
26682 DECL_SOURCE_LOCATION (fn));
26683 error_at (loc,
26684 "exception specification of %qD depends on itself",
26685 fn);
26686 spec = noexcept_false_spec;
26688 else if (push_tinst_level (fn))
26690 push_to_top_level ();
26691 push_access_scope (fn);
26692 push_deferring_access_checks (dk_no_deferred);
26693 input_location = DECL_SOURCE_LOCATION (fn);
26695 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
26696 && !DECL_LOCAL_DECL_P (fn))
26698 /* If needed, set current_class_ptr for the benefit of
26699 tsubst_copy/PARM_DECL. */
26700 tree this_parm = DECL_ARGUMENTS (fn);
26701 current_class_ptr = NULL_TREE;
26702 current_class_ref = cp_build_fold_indirect_ref (this_parm);
26703 current_class_ptr = this_parm;
26706 /* If this function is represented by a TEMPLATE_DECL, then
26707 the deferred noexcept-specification might still contain
26708 dependent types, even after substitution. And we need the
26709 dependency check functions to work in build_noexcept_spec. */
26710 if (orig_fn)
26711 ++processing_template_decl;
26713 /* Do deferred instantiation of the noexcept-specifier. */
26714 noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
26715 DEFERRED_NOEXCEPT_ARGS (noex),
26716 tf_warning_or_error, fn);
26718 /* Build up the noexcept-specification. */
26719 spec = build_noexcept_spec (noex, tf_warning_or_error);
26721 if (orig_fn)
26722 --processing_template_decl;
26724 pop_deferring_access_checks ();
26725 pop_access_scope (fn);
26726 pop_tinst_level ();
26727 pop_from_top_level ();
26729 else
26730 spec = noexcept_false_spec;
26732 if (added)
26733 fns->remove (fn);
26736 if (spec == error_mark_node)
26738 /* This failed with a hard error, so let's go with false. */
26739 gcc_assert (seen_error ());
26740 spec = noexcept_false_spec;
26743 TREE_TYPE (fn) = build_exception_variant (fntype, spec);
26744 if (orig_fn)
26745 TREE_TYPE (orig_fn) = TREE_TYPE (fn);
26747 return true;
26750 /* We're starting to process the function INST, an instantiation of PATTERN;
26751 add their parameters to local_specializations. */
26753 void
26754 register_parameter_specializations (tree pattern, tree inst)
26756 tree tmpl_parm = DECL_ARGUMENTS (pattern);
26757 tree spec_parm = DECL_ARGUMENTS (inst);
26758 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (inst))
26760 register_local_specialization (spec_parm, tmpl_parm);
26761 spec_parm = skip_artificial_parms_for (inst, spec_parm);
26762 tmpl_parm = skip_artificial_parms_for (pattern, tmpl_parm);
26764 for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
26766 if (!DECL_PACK_P (tmpl_parm))
26768 register_local_specialization (spec_parm, tmpl_parm);
26769 spec_parm = DECL_CHAIN (spec_parm);
26771 else
26773 /* Register the (value) argument pack as a specialization of
26774 TMPL_PARM, then move on. */
26775 tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
26776 register_local_specialization (argpack, tmpl_parm);
26779 gcc_assert (!spec_parm);
26782 /* Instantiate the body of D using PATTERN with ARGS. We have
26783 already determined PATTERN is the correct template to use.
26784 NESTED_P is true if this is a nested function, in which case
26785 PATTERN will be a FUNCTION_DECL not a TEMPLATE_DECL. */
26787 static void
26788 instantiate_body (tree pattern, tree args, tree d, bool nested_p)
26790 tree td = NULL_TREE;
26791 tree code_pattern = pattern;
26793 if (!nested_p)
26795 td = pattern;
26796 code_pattern = DECL_TEMPLATE_RESULT (td);
26798 else
26799 /* Only OMP reductions are nested. */
26800 gcc_checking_assert (DECL_OMP_DECLARE_REDUCTION_P (code_pattern));
26802 vec<tree> omp_privatization_save;
26803 if (current_function_decl)
26804 save_omp_privatization_clauses (omp_privatization_save);
26806 bool push_to_top = maybe_push_to_top_level (d);
26808 mark_template_arguments_used (pattern, args);
26810 if (VAR_P (d))
26812 /* The variable might be a lambda's extra scope, and that
26813 lambda's visibility depends on D's. */
26814 maybe_commonize_var (d);
26815 determine_visibility (d);
26818 /* Mark D as instantiated so that recursive calls to
26819 instantiate_decl do not try to instantiate it again. */
26820 DECL_TEMPLATE_INSTANTIATED (d) = 1;
26822 if (td)
26823 /* Regenerate the declaration in case the template has been modified
26824 by a subsequent redeclaration. */
26825 regenerate_decl_from_template (d, td, args);
26827 /* We already set the file and line above. Reset them now in case
26828 they changed as a result of calling regenerate_decl_from_template. */
26829 input_location = DECL_SOURCE_LOCATION (d);
26831 if (VAR_P (d))
26833 /* Clear out DECL_RTL; whatever was there before may not be right
26834 since we've reset the type of the declaration. */
26835 SET_DECL_RTL (d, NULL);
26836 DECL_IN_AGGR_P (d) = 0;
26838 /* The initializer is placed in DECL_INITIAL by
26839 regenerate_decl_from_template so we don't need to
26840 push/pop_access_scope again here. Pull it out so that
26841 cp_finish_decl can process it. */
26842 bool const_init = false;
26843 tree init = DECL_INITIAL (d);
26844 DECL_INITIAL (d) = NULL_TREE;
26845 DECL_INITIALIZED_P (d) = 0;
26847 /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
26848 initializer. That function will defer actual emission until
26849 we have a chance to determine linkage. */
26850 DECL_EXTERNAL (d) = 0;
26852 /* Enter the scope of D so that access-checking works correctly. */
26853 bool enter_context = DECL_CLASS_SCOPE_P (d);
26854 if (enter_context)
26855 push_nested_class (DECL_CONTEXT (d));
26857 const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
26858 cp_finish_decl (d, init, const_init, NULL_TREE, 0);
26860 if (enter_context)
26861 pop_nested_class ();
26863 else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
26864 synthesize_method (d);
26865 else if (TREE_CODE (d) == FUNCTION_DECL)
26867 /* Set up the list of local specializations. */
26868 local_specialization_stack lss (push_to_top ? lss_blank : lss_copy);
26869 tree block = NULL_TREE;
26871 /* Set up context. */
26872 if (nested_p)
26873 block = push_stmt_list ();
26874 else
26876 start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
26878 perform_instantiation_time_access_checks (code_pattern, args);
26881 /* Create substitution entries for the parameters. */
26882 register_parameter_specializations (code_pattern, d);
26884 /* Substitute into the body of the function. */
26885 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
26886 tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
26887 tf_warning_or_error, d);
26888 else
26890 tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
26891 tf_warning_or_error, DECL_TI_TEMPLATE (d));
26893 /* Set the current input_location to the end of the function
26894 so that finish_function knows where we are. */
26895 input_location
26896 = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
26898 /* Remember if we saw an infinite loop in the template. */
26899 current_function_infinite_loop
26900 = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
26903 /* Finish the function. */
26904 if (nested_p)
26905 DECL_SAVED_TREE (d) = pop_stmt_list (block);
26906 else
26908 d = finish_function (/*inline_p=*/false);
26909 expand_or_defer_fn (d);
26912 if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
26913 cp_check_omp_declare_reduction (d);
26916 /* We're not deferring instantiation any more. */
26917 if (!nested_p)
26918 TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
26920 maybe_pop_from_top_level (push_to_top);
26922 if (current_function_decl)
26923 restore_omp_privatization_clauses (omp_privatization_save);
26926 /* Produce the definition of D, a _DECL generated from a template. If
26927 DEFER_OK is true, then we don't have to actually do the
26928 instantiation now; we just have to do it sometime. Normally it is
26929 an error if this is an explicit instantiation but D is undefined.
26930 EXPL_INST_CLASS_MEM_P is true iff D is a member of an explicitly
26931 instantiated class template. */
26933 tree
26934 instantiate_decl (tree d, bool defer_ok, bool expl_inst_class_mem_p)
26936 tree tmpl = DECL_TI_TEMPLATE (d);
26937 tree gen_args;
26938 tree args;
26939 tree td;
26940 tree code_pattern;
26941 tree spec;
26942 tree gen_tmpl;
26943 bool pattern_defined;
26944 location_t saved_loc = input_location;
26945 int saved_unevaluated_operand = cp_unevaluated_operand;
26946 int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
26947 bool external_p;
26948 bool deleted_p;
26950 /* This function should only be used to instantiate templates for
26951 functions and static member variables. */
26952 gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
26954 /* A concept is never instantiated. */
26955 gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
26957 gcc_checking_assert (!DECL_FUNCTION_SCOPE_P (d));
26959 if (modules_p ())
26960 /* We may have a pending instantiation of D itself. */
26961 lazy_load_pendings (d);
26963 /* Variables are never deferred; if instantiation is required, they
26964 are instantiated right away. That allows for better code in the
26965 case that an expression refers to the value of the variable --
26966 if the variable has a constant value the referring expression can
26967 take advantage of that fact. */
26968 if (VAR_P (d))
26969 defer_ok = false;
26971 /* Don't instantiate cloned functions. Instead, instantiate the
26972 functions they cloned. */
26973 if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
26974 d = DECL_CLONED_FUNCTION (d);
26976 if (DECL_TEMPLATE_INSTANTIATED (d)
26977 || TREE_TYPE (d) == error_mark_node
26978 || (TREE_CODE (d) == FUNCTION_DECL
26979 && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
26980 || DECL_TEMPLATE_SPECIALIZATION (d))
26981 /* D has already been instantiated or explicitly specialized, so
26982 there's nothing for us to do here.
26984 It might seem reasonable to check whether or not D is an explicit
26985 instantiation, and, if so, stop here. But when an explicit
26986 instantiation is deferred until the end of the compilation,
26987 DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
26988 the instantiation. */
26989 return d;
26991 /* Check to see whether we know that this template will be
26992 instantiated in some other file, as with "extern template"
26993 extension. */
26994 external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
26996 /* In general, we do not instantiate such templates. */
26997 if (external_p && !always_instantiate_p (d))
26998 return d;
27000 gen_tmpl = most_general_template (tmpl);
27001 gen_args = DECL_TI_ARGS (d);
27003 /* We should already have the extra args. */
27004 gcc_checking_assert (tmpl == gen_tmpl
27005 || (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
27006 == TMPL_ARGS_DEPTH (gen_args)));
27007 /* And what's in the hash table should match D. */
27008 gcc_checking_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0))
27009 == d
27010 || spec == NULL_TREE);
27012 /* This needs to happen before any tsubsting. */
27013 if (! push_tinst_level (d))
27014 return d;
27016 auto_timevar tv (TV_TEMPLATE_INST);
27018 /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
27019 for the instantiation. */
27020 td = template_for_substitution (d);
27021 args = gen_args;
27023 if (variable_template_specialization_p (d))
27025 /* Look up an explicit specialization, if any. */
27026 tree elt = most_specialized_partial_spec (d, tf_warning_or_error);
27027 if (elt && elt != error_mark_node)
27029 td = TREE_VALUE (elt);
27030 args = TREE_PURPOSE (elt);
27034 code_pattern = DECL_TEMPLATE_RESULT (td);
27036 /* We should never be trying to instantiate a member of a class
27037 template or partial specialization. */
27038 gcc_assert (d != code_pattern);
27040 if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
27041 || DECL_TEMPLATE_SPECIALIZATION (td))
27042 /* In the case of a friend template whose definition is provided
27043 outside the class, we may have too many arguments. Drop the
27044 ones we don't need. The same is true for specializations. */
27045 args = get_innermost_template_args
27046 (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
27048 if (TREE_CODE (d) == FUNCTION_DECL)
27050 deleted_p = DECL_DELETED_FN (code_pattern);
27051 pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
27052 && DECL_INITIAL (code_pattern) != error_mark_node)
27053 || DECL_DEFAULTED_FN (code_pattern)
27054 || deleted_p);
27056 else
27058 deleted_p = false;
27059 if (DECL_CLASS_SCOPE_P (code_pattern))
27060 pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
27061 else
27062 pattern_defined = ! DECL_EXTERNAL (code_pattern);
27065 /* We may be in the middle of deferred access check. Disable it now. */
27066 push_deferring_access_checks (dk_no_deferred);
27068 /* Unless an explicit instantiation directive has already determined
27069 the linkage of D, remember that a definition is available for
27070 this entity. */
27071 if (pattern_defined
27072 && !DECL_INTERFACE_KNOWN (d)
27073 && !DECL_NOT_REALLY_EXTERN (d))
27074 mark_definable (d);
27076 DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
27077 DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
27078 input_location = DECL_SOURCE_LOCATION (d);
27080 /* If D is a member of an explicitly instantiated class template,
27081 and no definition is available, treat it like an implicit
27082 instantiation. */
27083 if (!pattern_defined && expl_inst_class_mem_p
27084 && DECL_EXPLICIT_INSTANTIATION (d))
27086 /* Leave linkage flags alone on instantiations with anonymous
27087 visibility. */
27088 if (TREE_PUBLIC (d))
27090 DECL_NOT_REALLY_EXTERN (d) = 0;
27091 DECL_INTERFACE_KNOWN (d) = 0;
27093 SET_DECL_IMPLICIT_INSTANTIATION (d);
27096 /* Defer all other templates, unless we have been explicitly
27097 forbidden from doing so. */
27098 if (/* If there is no definition, we cannot instantiate the
27099 template. */
27100 ! pattern_defined
27101 /* If it's OK to postpone instantiation, do so. */
27102 || defer_ok
27103 /* If this is a static data member that will be defined
27104 elsewhere, we don't want to instantiate the entire data
27105 member, but we do want to instantiate the initializer so that
27106 we can substitute that elsewhere. */
27107 || (external_p && VAR_P (d))
27108 /* Handle here a deleted function too, avoid generating
27109 its body (c++/61080). */
27110 || deleted_p)
27112 /* The definition of the static data member is now required so
27113 we must substitute the initializer. */
27114 if (VAR_P (d)
27115 && !DECL_INITIAL (d)
27116 && DECL_INITIAL (code_pattern))
27118 tree ns;
27119 tree init;
27120 bool const_init = false;
27121 bool enter_context = DECL_CLASS_SCOPE_P (d);
27123 ns = decl_namespace_context (d);
27124 push_nested_namespace (ns);
27125 if (enter_context)
27126 push_nested_class (DECL_CONTEXT (d));
27127 init = tsubst_expr (DECL_INITIAL (code_pattern),
27128 args,
27129 tf_warning_or_error, NULL_TREE);
27130 /* If instantiating the initializer involved instantiating this
27131 again, don't call cp_finish_decl twice. */
27132 if (!DECL_INITIAL (d))
27134 /* Make sure the initializer is still constant, in case of
27135 circular dependency (template/instantiate6.C). */
27136 const_init
27137 = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
27138 cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
27139 /*asmspec_tree=*/NULL_TREE, 0);
27141 if (enter_context)
27142 pop_nested_class ();
27143 pop_nested_namespace (ns);
27146 /* We restore the source position here because it's used by
27147 add_pending_template. */
27148 input_location = saved_loc;
27150 if (at_eof && !pattern_defined
27151 && DECL_EXPLICIT_INSTANTIATION (d)
27152 && DECL_NOT_REALLY_EXTERN (d))
27153 /* [temp.explicit]
27155 The definition of a non-exported function template, a
27156 non-exported member function template, or a non-exported
27157 member function or static data member of a class template
27158 shall be present in every translation unit in which it is
27159 explicitly instantiated. */
27160 permerror (input_location, "explicit instantiation of %qD "
27161 "but no definition available", d);
27163 /* If we're in unevaluated context, we just wanted to get the
27164 constant value; this isn't an odr use, so don't queue
27165 a full instantiation. */
27166 if (!cp_unevaluated_operand
27167 /* ??? Historically, we have instantiated inline functions, even
27168 when marked as "extern template". */
27169 && !(external_p && VAR_P (d)))
27170 add_pending_template (d);
27172 else
27174 set_instantiating_module (d);
27175 if (variable_template_p (gen_tmpl))
27176 note_variable_template_instantiation (d);
27177 instantiate_body (td, args, d, false);
27180 pop_deferring_access_checks ();
27181 pop_tinst_level ();
27182 input_location = saved_loc;
27183 cp_unevaluated_operand = saved_unevaluated_operand;
27184 c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
27186 return d;
27189 /* Run through the list of templates that we wish we could
27190 instantiate, and instantiate any we can. RETRIES is the
27191 number of times we retry pending template instantiation. */
27193 void
27194 instantiate_pending_templates (int retries)
27196 int reconsider;
27197 location_t saved_loc = input_location;
27199 /* Instantiating templates may trigger vtable generation. This in turn
27200 may require further template instantiations. We place a limit here
27201 to avoid infinite loop. */
27202 if (pending_templates && retries >= max_tinst_depth)
27204 tree decl = pending_templates->tinst->maybe_get_node ();
27206 fatal_error (input_location,
27207 "template instantiation depth exceeds maximum of %d"
27208 " instantiating %q+D, possibly from virtual table generation"
27209 " (use %<-ftemplate-depth=%> to increase the maximum)",
27210 max_tinst_depth, decl);
27211 if (TREE_CODE (decl) == FUNCTION_DECL)
27212 /* Pretend that we defined it. */
27213 DECL_INITIAL (decl) = error_mark_node;
27214 return;
27219 struct pending_template **t = &pending_templates;
27220 struct pending_template *last = NULL;
27221 reconsider = 0;
27222 while (*t)
27224 tree instantiation = reopen_tinst_level ((*t)->tinst);
27225 bool complete = false;
27227 if (TYPE_P (instantiation))
27229 if (!COMPLETE_TYPE_P (instantiation))
27231 instantiate_class_template (instantiation);
27232 if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
27233 for (tree fld = TYPE_FIELDS (instantiation);
27234 fld; fld = TREE_CHAIN (fld))
27235 if ((VAR_P (fld)
27236 || (TREE_CODE (fld) == FUNCTION_DECL
27237 && !DECL_ARTIFICIAL (fld)))
27238 && DECL_TEMPLATE_INSTANTIATION (fld))
27239 instantiate_decl (fld,
27240 /*defer_ok=*/false,
27241 /*expl_inst_class_mem_p=*/false);
27243 if (COMPLETE_TYPE_P (instantiation))
27244 reconsider = 1;
27247 complete = COMPLETE_TYPE_P (instantiation);
27249 else
27251 if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
27252 && !DECL_TEMPLATE_INSTANTIATED (instantiation))
27254 instantiation
27255 = instantiate_decl (instantiation,
27256 /*defer_ok=*/false,
27257 /*expl_inst_class_mem_p=*/false);
27258 if (DECL_TEMPLATE_INSTANTIATED (instantiation))
27259 reconsider = 1;
27262 complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
27263 || DECL_TEMPLATE_INSTANTIATED (instantiation));
27266 if (complete)
27268 /* If INSTANTIATION has been instantiated, then we don't
27269 need to consider it again in the future. */
27270 struct pending_template *drop = *t;
27271 *t = (*t)->next;
27272 set_refcount_ptr (drop->tinst);
27273 pending_template_freelist ().free (drop);
27275 else
27277 last = *t;
27278 t = &(*t)->next;
27280 tinst_depth = 0;
27281 set_refcount_ptr (current_tinst_level);
27283 last_pending_template = last;
27285 while (reconsider);
27287 input_location = saved_loc;
27290 /* Substitute ARGVEC into T, which is a list of initializers for
27291 either base class or a non-static data member. The TREE_PURPOSEs
27292 are DECLs, and the TREE_VALUEs are the initializer values. Used by
27293 instantiate_decl. */
27295 static tree
27296 tsubst_initializer_list (tree t, tree argvec)
27298 tree inits = NULL_TREE;
27299 tree target_ctor = error_mark_node;
27301 for (; t; t = TREE_CHAIN (t))
27303 tree decl;
27304 tree init;
27305 tree expanded_bases = NULL_TREE;
27306 tree expanded_arguments = NULL_TREE;
27307 int i, len = 1;
27309 if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
27311 tree expr;
27312 tree arg;
27314 /* Expand the base class expansion type into separate base
27315 classes. */
27316 expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
27317 tf_warning_or_error,
27318 NULL_TREE);
27319 if (expanded_bases == error_mark_node)
27320 continue;
27322 /* We'll be building separate TREE_LISTs of arguments for
27323 each base. */
27324 len = TREE_VEC_LENGTH (expanded_bases);
27325 expanded_arguments = make_tree_vec (len);
27326 for (i = 0; i < len; i++)
27327 TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
27329 /* Build a dummy EXPR_PACK_EXPANSION that will be used to
27330 expand each argument in the TREE_VALUE of t. */
27331 expr = make_node (EXPR_PACK_EXPANSION);
27332 PACK_EXPANSION_LOCAL_P (expr) = true;
27333 PACK_EXPANSION_PARAMETER_PACKS (expr) =
27334 PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
27336 if (TREE_VALUE (t) == void_type_node)
27337 /* VOID_TYPE_NODE is used to indicate
27338 value-initialization. */
27340 for (i = 0; i < len; i++)
27341 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
27343 else
27345 /* Substitute parameter packs into each argument in the
27346 TREE_LIST. */
27347 in_base_initializer = 1;
27348 for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
27350 tree expanded_exprs;
27352 /* Expand the argument. */
27353 tree value;
27354 if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
27355 value = TREE_VALUE (arg);
27356 else
27358 value = expr;
27359 PACK_EXPANSION_PATTERN (value) = TREE_VALUE (arg);
27361 expanded_exprs
27362 = tsubst_pack_expansion (value, argvec,
27363 tf_warning_or_error,
27364 NULL_TREE);
27365 if (expanded_exprs == error_mark_node)
27366 continue;
27368 /* Prepend each of the expanded expressions to the
27369 corresponding TREE_LIST in EXPANDED_ARGUMENTS. */
27370 for (i = 0; i < len; i++)
27371 if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
27372 for (int j = 0; j < TREE_VEC_LENGTH (expanded_exprs); j++)
27373 TREE_VEC_ELT (expanded_arguments, i)
27374 = tree_cons (NULL_TREE,
27375 TREE_VEC_ELT (expanded_exprs, j),
27376 TREE_VEC_ELT (expanded_arguments, i));
27377 else
27378 TREE_VEC_ELT (expanded_arguments, i)
27379 = tree_cons (NULL_TREE,
27380 TREE_VEC_ELT (expanded_exprs, i),
27381 TREE_VEC_ELT (expanded_arguments, i));
27383 in_base_initializer = 0;
27385 /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
27386 since we built them backwards. */
27387 for (i = 0; i < len; i++)
27389 TREE_VEC_ELT (expanded_arguments, i) =
27390 nreverse (TREE_VEC_ELT (expanded_arguments, i));
27395 for (i = 0; i < len; ++i)
27397 if (expanded_bases)
27399 decl = TREE_VEC_ELT (expanded_bases, i);
27400 decl = expand_member_init (decl);
27401 init = TREE_VEC_ELT (expanded_arguments, i);
27403 else
27405 tree tmp;
27406 decl = tsubst_copy (TREE_PURPOSE (t), argvec,
27407 tf_warning_or_error, NULL_TREE);
27409 decl = expand_member_init (decl);
27410 if (decl && !DECL_P (decl))
27411 in_base_initializer = 1;
27413 init = TREE_VALUE (t);
27414 tmp = init;
27415 if (init != void_type_node)
27416 init = tsubst_expr (init, argvec,
27417 tf_warning_or_error, NULL_TREE);
27418 if (init == NULL_TREE && tmp != NULL_TREE)
27419 /* If we had an initializer but it instantiated to nothing,
27420 value-initialize the object. This will only occur when
27421 the initializer was a pack expansion where the parameter
27422 packs used in that expansion were of length zero. */
27423 init = void_type_node;
27424 in_base_initializer = 0;
27427 if (target_ctor != error_mark_node
27428 && init != error_mark_node)
27430 error ("mem-initializer for %qD follows constructor delegation",
27431 decl);
27432 return inits;
27434 /* Look for a target constructor. */
27435 if (init != error_mark_node
27436 && decl && CLASS_TYPE_P (decl)
27437 && same_type_p (decl, current_class_type))
27439 maybe_warn_cpp0x (CPP0X_DELEGATING_CTORS);
27440 if (inits)
27442 error ("constructor delegation follows mem-initializer for %qD",
27443 TREE_PURPOSE (inits));
27444 continue;
27446 target_ctor = init;
27449 if (decl)
27451 init = build_tree_list (decl, init);
27452 /* Carry over the dummy TREE_TYPE node containing the source
27453 location. */
27454 TREE_TYPE (init) = TREE_TYPE (t);
27455 TREE_CHAIN (init) = inits;
27456 inits = init;
27460 return inits;
27463 /* Instantiate an enumerated type. TAG is the template type, NEWTAG
27464 is the instantiation (which should have been created with
27465 start_enum) and ARGS are the template arguments to use. */
27467 static void
27468 tsubst_enum (tree tag, tree newtag, tree args)
27470 tree e;
27472 if (SCOPED_ENUM_P (newtag))
27473 begin_scope (sk_scoped_enum, newtag);
27475 for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
27477 tree value;
27478 tree decl = TREE_VALUE (e);
27480 /* Note that in a template enum, the TREE_VALUE is the
27481 CONST_DECL, not the corresponding INTEGER_CST. */
27482 value = tsubst_expr (DECL_INITIAL (decl),
27483 args, tf_warning_or_error, NULL_TREE);
27485 /* Give this enumeration constant the correct access. */
27486 set_current_access_from_decl (decl);
27488 /* Actually build the enumerator itself. Here we're assuming that
27489 enumerators can't have dependent attributes. */
27490 tree newdecl = build_enumerator (DECL_NAME (decl), value, newtag,
27491 DECL_ATTRIBUTES (decl),
27492 DECL_SOURCE_LOCATION (decl));
27493 /* Attribute deprecated without an argument isn't sticky: it'll
27494 melt into a tree flag, so we need to propagate the flag here,
27495 since we just created a new enumerator. */
27496 TREE_DEPRECATED (newdecl) = TREE_DEPRECATED (decl);
27497 TREE_UNAVAILABLE (newdecl) = TREE_UNAVAILABLE (decl);
27500 if (SCOPED_ENUM_P (newtag))
27501 finish_scope ();
27503 finish_enum_value_list (newtag);
27504 finish_enum (newtag);
27506 DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
27507 = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
27508 TREE_DEPRECATED (newtag) = TREE_DEPRECATED (tag);
27509 TREE_UNAVAILABLE (newtag) = TREE_UNAVAILABLE (tag);
27512 /* DECL is a FUNCTION_DECL that is a template specialization. Return
27513 its type -- but without substituting the innermost set of template
27514 arguments. So, innermost set of template parameters will appear in
27515 the type. */
27517 tree
27518 get_mostly_instantiated_function_type (tree decl)
27520 /* For a function, DECL_TI_TEMPLATE is partially instantiated. */
27521 return TREE_TYPE (DECL_TI_TEMPLATE (decl));
27524 /* Return truthvalue if we're processing a template different from
27525 the last one involved in diagnostics. */
27526 bool
27527 problematic_instantiation_changed (void)
27529 return current_tinst_level != last_error_tinst_level;
27532 /* Remember current template involved in diagnostics. */
27533 void
27534 record_last_problematic_instantiation (void)
27536 set_refcount_ptr (last_error_tinst_level, current_tinst_level);
27539 struct tinst_level *
27540 current_instantiation (void)
27542 return current_tinst_level;
27545 /* Return TRUE if current_function_decl is being instantiated, false
27546 otherwise. */
27548 bool
27549 instantiating_current_function_p (void)
27551 return (current_instantiation ()
27552 && (current_instantiation ()->maybe_get_node ()
27553 == current_function_decl));
27556 /* [temp.param] Check that template non-type parm TYPE is of an allowable
27557 type. Return false for ok, true for disallowed. Issue error and
27558 inform messages under control of COMPLAIN. */
27560 static bool
27561 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
27563 if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
27564 return false;
27565 else if (TYPE_PTR_P (type))
27566 return false;
27567 else if (TYPE_REF_P (type)
27568 && !TYPE_REF_IS_RVALUE (type))
27569 return false;
27570 else if (TYPE_PTRMEM_P (type))
27571 return false;
27572 else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
27574 if (CLASS_PLACEHOLDER_TEMPLATE (type) && cxx_dialect < cxx20)
27576 if (complain & tf_error)
27577 error ("non-type template parameters of deduced class type only "
27578 "available with %<-std=c++20%> or %<-std=gnu++20%>");
27579 return true;
27581 return false;
27583 else if (TREE_CODE (type) == NULLPTR_TYPE)
27584 return false;
27585 else if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM
27586 && cxx_dialect < cxx11)
27587 /* Fall through; before C++11 alias templates, a bound ttp
27588 always instantiates into a class type. */;
27589 else if (WILDCARD_TYPE_P (type))
27590 /* Any other wildcard type not already handled above is allowed. */
27591 return false;
27592 else if (TREE_CODE (type) == COMPLEX_TYPE)
27593 /* Fall through. */;
27594 else if (VOID_TYPE_P (type))
27595 /* Fall through. */;
27596 else if (cxx_dialect >= cxx20)
27598 if (dependent_type_p (type))
27599 return false;
27600 if (!complete_type_or_maybe_complain (type, NULL_TREE, complain))
27601 return true;
27602 if (structural_type_p (type))
27603 return false;
27604 if (complain & tf_error)
27606 auto_diagnostic_group d;
27607 error ("%qT is not a valid type for a template non-type "
27608 "parameter because it is not structural", type);
27609 structural_type_p (type, true);
27611 return true;
27613 else if (CLASS_TYPE_P (type))
27615 if (complain & tf_error)
27616 error ("non-type template parameters of class type only available "
27617 "with %<-std=c++20%> or %<-std=gnu++20%>");
27618 return true;
27621 if (complain & tf_error)
27623 if (type == error_mark_node)
27624 inform (input_location, "invalid template non-type parameter");
27625 else
27626 error ("%q#T is not a valid type for a template non-type parameter",
27627 type);
27629 return true;
27632 /* Returns true iff the noexcept-specifier for TYPE is value-dependent. */
27634 static bool
27635 value_dependent_noexcept_spec_p (tree type)
27637 if (tree spec = TYPE_RAISES_EXCEPTIONS (type))
27638 if (tree noex = TREE_PURPOSE (spec))
27639 /* Treat DEFERRED_NOEXCEPT as non-dependent, since it doesn't
27640 affect overload resolution and treating it as dependent breaks
27641 things. Same for an unparsed noexcept expression. */
27642 if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
27643 && TREE_CODE (noex) != DEFERRED_PARSE
27644 && value_dependent_expression_p (noex))
27645 return true;
27647 return false;
27650 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
27651 Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
27653 static bool
27654 dependent_type_p_r (tree type)
27656 tree scope;
27658 /* [temp.dep.type]
27660 A type is dependent if it is:
27662 -- a template parameter. Template template parameters are types
27663 for us (since TYPE_P holds true for them) so we handle
27664 them here. */
27665 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
27666 || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
27667 return true;
27668 /* -- a qualified-id with a nested-name-specifier which contains a
27669 class-name that names a dependent type or whose unqualified-id
27670 names a dependent type. */
27671 if (TREE_CODE (type) == TYPENAME_TYPE)
27672 return true;
27674 /* An alias template specialization can be dependent even if the
27675 resulting type is not. */
27676 if (dependent_alias_template_spec_p (type, nt_transparent))
27677 return true;
27679 /* -- a cv-qualified type where the cv-unqualified type is
27680 dependent.
27681 No code is necessary for this bullet; the code below handles
27682 cv-qualified types, and we don't want to strip aliases with
27683 TYPE_MAIN_VARIANT because of DR 1558. */
27684 /* -- a compound type constructed from any dependent type. */
27685 if (TYPE_PTRMEM_P (type))
27686 return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
27687 || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
27688 (type)));
27689 else if (INDIRECT_TYPE_P (type))
27690 return dependent_type_p (TREE_TYPE (type));
27691 else if (FUNC_OR_METHOD_TYPE_P (type))
27693 tree arg_type;
27695 if (dependent_type_p (TREE_TYPE (type)))
27696 return true;
27697 for (arg_type = TYPE_ARG_TYPES (type);
27698 arg_type;
27699 arg_type = TREE_CHAIN (arg_type))
27700 if (dependent_type_p (TREE_VALUE (arg_type)))
27701 return true;
27702 if (cxx_dialect >= cxx17
27703 && value_dependent_noexcept_spec_p (type))
27704 /* A value-dependent noexcept-specifier makes the type dependent. */
27705 return true;
27706 return false;
27708 /* -- an array type constructed from any dependent type or whose
27709 size is specified by a constant expression that is
27710 value-dependent.
27712 We checked for type- and value-dependence of the bounds in
27713 compute_array_index_type, so TYPE_DEPENDENT_P is already set. */
27714 if (TREE_CODE (type) == ARRAY_TYPE)
27716 if (TYPE_DOMAIN (type)
27717 && dependent_type_p (TYPE_DOMAIN (type)))
27718 return true;
27719 return dependent_type_p (TREE_TYPE (type));
27722 /* -- a template-id in which either the template name is a template
27723 parameter ... */
27724 if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
27725 return true;
27726 /* ... or any of the template arguments is a dependent type or
27727 an expression that is type-dependent or value-dependent. */
27728 else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
27729 && (any_dependent_template_arguments_p
27730 (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
27731 return true;
27733 /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and TRAIT_TYPEs are
27734 dependent; if the argument of the `typeof' expression is not
27735 type-dependent, then it should already been have resolved. */
27736 if (TREE_CODE (type) == TYPEOF_TYPE
27737 || TREE_CODE (type) == DECLTYPE_TYPE
27738 || TREE_CODE (type) == TRAIT_TYPE)
27739 return true;
27741 /* A template argument pack is dependent if any of its packed
27742 arguments are. */
27743 if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
27745 tree args = ARGUMENT_PACK_ARGS (type);
27746 for (tree arg : tree_vec_range (args))
27747 if (dependent_template_arg_p (arg))
27748 return true;
27751 /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
27752 be template parameters. */
27753 if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
27754 return true;
27756 if (TREE_CODE (type) == DEPENDENT_OPERATOR_TYPE)
27757 return true;
27759 if (any_dependent_type_attributes_p (TYPE_ATTRIBUTES (type)))
27760 return true;
27762 /* The standard does not specifically mention types that are local
27763 to template functions or local classes, but they should be
27764 considered dependent too. For example:
27766 template <int I> void f() {
27767 enum E { a = I };
27768 S<sizeof (E)> s;
27771 The size of `E' cannot be known until the value of `I' has been
27772 determined. Therefore, `E' must be considered dependent. */
27773 scope = TYPE_CONTEXT (type);
27774 if (scope && TYPE_P (scope))
27775 return dependent_type_p (scope);
27776 /* Don't use type_dependent_expression_p here, as it can lead
27777 to infinite recursion trying to determine whether a lambda
27778 nested in a lambda is dependent (c++/47687). */
27779 else if (scope && TREE_CODE (scope) == FUNCTION_DECL
27780 && DECL_LANG_SPECIFIC (scope)
27781 && DECL_TEMPLATE_INFO (scope)
27782 && (any_dependent_template_arguments_p
27783 (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
27784 return true;
27786 /* Other types are non-dependent. */
27787 return false;
27790 /* Returns TRUE if TYPE is dependent, in the sense of
27791 [temp.dep.type]. Note that a NULL type is considered dependent. */
27793 bool
27794 dependent_type_p (tree type)
27796 /* If there are no template parameters in scope, then there can't be
27797 any dependent types. */
27798 if (!processing_template_decl)
27800 /* If we are not processing a template, then nobody should be
27801 providing us with a dependent type. */
27802 gcc_assert (type);
27803 gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
27804 return false;
27807 /* If the type is NULL, we have not computed a type for the entity
27808 in question; in that case, the type is dependent. */
27809 if (!type)
27810 return true;
27812 /* Erroneous types can be considered non-dependent. */
27813 if (type == error_mark_node)
27814 return false;
27816 /* If we have not already computed the appropriate value for TYPE,
27817 do so now. */
27818 if (!TYPE_DEPENDENT_P_VALID (type))
27820 TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
27821 TYPE_DEPENDENT_P_VALID (type) = 1;
27824 return TYPE_DEPENDENT_P (type);
27827 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
27828 lookup. In other words, a dependent type that is not the current
27829 instantiation. */
27831 bool
27832 dependent_scope_p (tree scope)
27834 return (scope && TYPE_P (scope) && dependent_type_p (scope)
27835 && !currently_open_class (scope));
27838 /* True if we might find more declarations in SCOPE during instantiation than
27839 we can when parsing the template. */
27841 bool
27842 dependentish_scope_p (tree scope)
27844 return dependent_scope_p (scope) || any_dependent_bases_p (scope);
27847 /* T is a SCOPE_REF. Return whether it represents a non-static member of
27848 an unknown base of 'this' (and is therefore instantiation-dependent). */
27850 static bool
27851 unknown_base_ref_p (tree t)
27853 if (!current_class_ptr)
27854 return false;
27856 tree mem = TREE_OPERAND (t, 1);
27857 if (shared_member_p (mem))
27858 return false;
27860 tree cur = current_nonlambda_class_type ();
27861 if (!any_dependent_bases_p (cur))
27862 return false;
27864 tree ctx = TREE_OPERAND (t, 0);
27865 if (DERIVED_FROM_P (ctx, cur))
27866 return false;
27868 return true;
27871 /* T is a SCOPE_REF; return whether we need to consider it
27872 instantiation-dependent so that we can check access at instantiation
27873 time even though we know which member it resolves to. */
27875 static bool
27876 instantiation_dependent_scope_ref_p (tree t)
27878 if (DECL_P (TREE_OPERAND (t, 1))
27879 && CLASS_TYPE_P (TREE_OPERAND (t, 0))
27880 && !dependent_scope_p (TREE_OPERAND (t, 0))
27881 && !unknown_base_ref_p (t)
27882 && accessible_in_template_p (TREE_OPERAND (t, 0),
27883 TREE_OPERAND (t, 1)))
27884 return false;
27885 else
27886 return true;
27889 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
27890 [temp.dep.constexpr]. EXPRESSION is already known to be a constant
27891 expression. */
27893 /* Note that this predicate is not appropriate for general expressions;
27894 only constant expressions (that satisfy potential_constant_expression)
27895 can be tested for value dependence. */
27897 bool
27898 value_dependent_expression_p (tree expression)
27900 if (!processing_template_decl || expression == NULL_TREE)
27901 return false;
27903 /* A type-dependent expression is also value-dependent. */
27904 if (type_dependent_expression_p (expression))
27905 return true;
27907 switch (TREE_CODE (expression))
27909 case BASELINK:
27910 /* A dependent member function of the current instantiation. */
27911 return dependent_type_p (BINFO_TYPE (BASELINK_BINFO (expression)));
27913 case FUNCTION_DECL:
27914 /* A dependent member function of the current instantiation. */
27915 if (DECL_CLASS_SCOPE_P (expression)
27916 && dependent_type_p (DECL_CONTEXT (expression)))
27917 return true;
27918 break;
27920 case IDENTIFIER_NODE:
27921 /* A name that has not been looked up -- must be dependent. */
27922 return true;
27924 case TEMPLATE_PARM_INDEX:
27925 /* A non-type template parm. */
27926 return true;
27928 case CONST_DECL:
27929 /* A non-type template parm. */
27930 if (DECL_TEMPLATE_PARM_P (expression))
27931 return true;
27932 return value_dependent_expression_p (DECL_INITIAL (expression));
27934 case VAR_DECL:
27935 /* A constant with literal type and is initialized
27936 with an expression that is value-dependent. */
27937 if (DECL_DEPENDENT_INIT_P (expression))
27938 return true;
27939 if (DECL_HAS_VALUE_EXPR_P (expression))
27941 tree value_expr = DECL_VALUE_EXPR (expression);
27942 if (value_dependent_expression_p (value_expr)
27943 /* __PRETTY_FUNCTION__ inside a template function is dependent
27944 on the name of the function. */
27945 || (DECL_PRETTY_FUNCTION_P (expression)
27946 /* It might be used in a template, but not a template
27947 function, in which case its DECL_VALUE_EXPR will be
27948 "top level". */
27949 && value_expr == error_mark_node))
27950 return true;
27952 else if (TYPE_REF_P (TREE_TYPE (expression)))
27953 /* FIXME cp_finish_decl doesn't fold reference initializers. */
27954 return true;
27955 return false;
27957 case DYNAMIC_CAST_EXPR:
27958 case STATIC_CAST_EXPR:
27959 case CONST_CAST_EXPR:
27960 case REINTERPRET_CAST_EXPR:
27961 case CAST_EXPR:
27962 case IMPLICIT_CONV_EXPR:
27963 /* These expressions are value-dependent if the type to which
27964 the cast occurs is dependent or the expression being casted
27965 is value-dependent. */
27967 tree type = TREE_TYPE (expression);
27969 if (dependent_type_p (type))
27970 return true;
27972 /* A functional cast has a list of operands. */
27973 expression = TREE_OPERAND (expression, 0);
27974 if (!expression)
27976 /* If there are no operands, it must be an expression such
27977 as "int()". This should not happen for aggregate types
27978 because it would form non-constant expressions. */
27979 gcc_assert (cxx_dialect >= cxx11
27980 || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
27982 return false;
27985 if (TREE_CODE (expression) == TREE_LIST)
27986 return any_value_dependent_elements_p (expression);
27988 if (TREE_CODE (type) == REFERENCE_TYPE
27989 && has_value_dependent_address (expression))
27990 return true;
27992 return value_dependent_expression_p (expression);
27995 case SIZEOF_EXPR:
27996 if (SIZEOF_EXPR_TYPE_P (expression))
27997 return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
27998 /* FALLTHRU */
27999 case ALIGNOF_EXPR:
28000 case TYPEID_EXPR:
28001 /* A `sizeof' expression is value-dependent if the operand is
28002 type-dependent or is a pack expansion. */
28003 expression = TREE_OPERAND (expression, 0);
28004 if (PACK_EXPANSION_P (expression))
28005 return true;
28006 else if (TYPE_P (expression))
28007 return dependent_type_p (expression);
28008 return instantiation_dependent_uneval_expression_p (expression);
28010 case AT_ENCODE_EXPR:
28011 /* An 'encode' expression is value-dependent if the operand is
28012 type-dependent. */
28013 expression = TREE_OPERAND (expression, 0);
28014 return dependent_type_p (expression);
28016 case NOEXCEPT_EXPR:
28017 expression = TREE_OPERAND (expression, 0);
28018 return instantiation_dependent_uneval_expression_p (expression);
28020 case SCOPE_REF:
28021 /* All instantiation-dependent expressions should also be considered
28022 value-dependent. */
28023 return instantiation_dependent_scope_ref_p (expression);
28025 case COMPONENT_REF:
28026 return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
28027 || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
28029 case NONTYPE_ARGUMENT_PACK:
28030 /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
28031 is value-dependent. */
28032 for (tree arg : tree_vec_range (ARGUMENT_PACK_ARGS (expression)))
28033 if (value_dependent_expression_p (arg))
28034 return true;
28035 return false;
28037 case TRAIT_EXPR:
28039 if (dependent_type_p (TRAIT_EXPR_TYPE1 (expression)))
28040 return true;
28042 tree type2 = TRAIT_EXPR_TYPE2 (expression);
28043 if (!type2)
28044 return false;
28046 if (TREE_CODE (type2) != TREE_VEC)
28047 return dependent_type_p (type2);
28049 for (tree arg : tree_vec_range (type2))
28050 if (dependent_type_p (arg))
28051 return true;
28053 return false;
28056 case MODOP_EXPR:
28057 return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
28058 || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
28060 case ARRAY_REF:
28061 return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
28062 || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
28064 case ADDR_EXPR:
28066 tree op = TREE_OPERAND (expression, 0);
28067 return (value_dependent_expression_p (op)
28068 || has_value_dependent_address (op));
28071 case REQUIRES_EXPR:
28072 /* Treat all requires-expressions as value-dependent so
28073 we don't try to fold them. */
28074 return true;
28076 case TYPE_REQ:
28077 return dependent_type_p (TREE_OPERAND (expression, 0));
28079 case CALL_EXPR:
28081 if (value_dependent_expression_p (CALL_EXPR_FN (expression)))
28082 return true;
28083 tree fn = get_callee_fndecl (expression);
28084 int i, nargs;
28085 nargs = call_expr_nargs (expression);
28086 for (i = 0; i < nargs; ++i)
28088 tree op = CALL_EXPR_ARG (expression, i);
28089 /* In a call to a constexpr member function, look through the
28090 implicit ADDR_EXPR on the object argument so that it doesn't
28091 cause the call to be considered value-dependent. We also
28092 look through it in potential_constant_expression. */
28093 if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
28094 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
28095 && TREE_CODE (op) == ADDR_EXPR)
28096 op = TREE_OPERAND (op, 0);
28097 if (value_dependent_expression_p (op))
28098 return true;
28100 return false;
28103 case TEMPLATE_ID_EXPR:
28104 return concept_definition_p (TREE_OPERAND (expression, 0))
28105 && any_dependent_template_arguments_p (TREE_OPERAND (expression, 1));
28107 case CONSTRUCTOR:
28109 unsigned ix;
28110 tree val;
28111 if (dependent_type_p (TREE_TYPE (expression)))
28112 return true;
28113 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
28114 if (value_dependent_expression_p (val))
28115 return true;
28116 return false;
28119 case STMT_EXPR:
28120 /* Treat a GNU statement expression as dependent to avoid crashing
28121 under instantiate_non_dependent_expr; it can't be constant. */
28122 return true;
28124 case NEW_EXPR:
28125 case VEC_NEW_EXPR:
28126 /* The second operand is a type, which type_dependent_expression_p
28127 (and therefore value_dependent_expression_p) doesn't want to see. */
28128 return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
28129 || value_dependent_expression_p (TREE_OPERAND (expression, 2))
28130 || value_dependent_expression_p (TREE_OPERAND (expression, 3)));
28132 default:
28133 /* A constant expression is value-dependent if any subexpression is
28134 value-dependent. */
28135 switch (TREE_CODE_CLASS (TREE_CODE (expression)))
28137 case tcc_reference:
28138 case tcc_unary:
28139 case tcc_comparison:
28140 case tcc_binary:
28141 case tcc_expression:
28142 case tcc_vl_exp:
28144 int i, len = cp_tree_operand_length (expression);
28146 for (i = 0; i < len; i++)
28148 tree t = TREE_OPERAND (expression, i);
28150 /* In some cases, some of the operands may be missing.
28151 (For example, in the case of PREDECREMENT_EXPR, the
28152 amount to increment by may be missing.) That doesn't
28153 make the expression dependent. */
28154 if (t && value_dependent_expression_p (t))
28155 return true;
28158 break;
28159 default:
28160 break;
28162 break;
28165 /* The expression is not value-dependent. */
28166 return false;
28169 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
28170 [temp.dep.expr]. Note that an expression with no type is
28171 considered dependent. Other parts of the compiler arrange for an
28172 expression with type-dependent subexpressions to have no type, so
28173 this function doesn't have to be fully recursive. */
28175 bool
28176 type_dependent_expression_p (tree expression)
28178 if (!processing_template_decl)
28179 return false;
28181 if (expression == NULL_TREE || expression == error_mark_node)
28182 return false;
28184 gcc_checking_assert (!TYPE_P (expression));
28186 STRIP_ANY_LOCATION_WRAPPER (expression);
28188 /* An unresolved name is always dependent. */
28189 if (identifier_p (expression)
28190 || TREE_CODE (expression) == USING_DECL
28191 || TREE_CODE (expression) == WILDCARD_DECL)
28192 return true;
28194 /* A lambda-expression in template context is dependent. dependent_type_p is
28195 true for a lambda in the scope of a class or function template, but that
28196 doesn't cover all template contexts, like a default template argument. */
28197 if (TREE_CODE (expression) == LAMBDA_EXPR)
28198 return true;
28200 /* A fold expression is type-dependent. */
28201 if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
28202 || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
28203 || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
28204 || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
28205 return true;
28207 /* Some expression forms are never type-dependent. */
28208 if (TREE_CODE (expression) == SIZEOF_EXPR
28209 || TREE_CODE (expression) == ALIGNOF_EXPR
28210 || TREE_CODE (expression) == AT_ENCODE_EXPR
28211 || TREE_CODE (expression) == NOEXCEPT_EXPR
28212 || TREE_CODE (expression) == TRAIT_EXPR
28213 || TREE_CODE (expression) == TYPEID_EXPR
28214 || TREE_CODE (expression) == DELETE_EXPR
28215 || TREE_CODE (expression) == VEC_DELETE_EXPR
28216 || TREE_CODE (expression) == THROW_EXPR
28217 || TREE_CODE (expression) == REQUIRES_EXPR)
28218 return false;
28220 /* The types of these expressions depends only on the type to which
28221 the cast occurs. */
28222 if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
28223 || TREE_CODE (expression) == STATIC_CAST_EXPR
28224 || TREE_CODE (expression) == CONST_CAST_EXPR
28225 || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
28226 || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
28227 || TREE_CODE (expression) == CAST_EXPR)
28228 return dependent_type_p (TREE_TYPE (expression));
28230 /* The types of these expressions depends only on the type created
28231 by the expression. */
28232 if (TREE_CODE (expression) == NEW_EXPR
28233 || TREE_CODE (expression) == VEC_NEW_EXPR)
28235 /* For NEW_EXPR tree nodes created inside a template, either
28236 the object type itself or a TREE_LIST may appear as the
28237 operand 1. */
28238 tree type = TREE_OPERAND (expression, 1);
28239 if (TREE_CODE (type) == TREE_LIST)
28240 /* This is an array type. We need to check array dimensions
28241 as well. */
28242 return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
28243 || value_dependent_expression_p
28244 (TREE_OPERAND (TREE_VALUE (type), 1));
28245 /* Array type whose dimension has to be deduced. */
28246 else if (TREE_CODE (type) == ARRAY_TYPE
28247 && TREE_OPERAND (expression, 2) == NULL_TREE)
28248 return true;
28249 else
28250 return dependent_type_p (type);
28253 if (TREE_CODE (expression) == SCOPE_REF)
28255 tree scope = TREE_OPERAND (expression, 0);
28256 tree name = TREE_OPERAND (expression, 1);
28258 /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
28259 contains an identifier associated by name lookup with one or more
28260 declarations declared with a dependent type, or...a
28261 nested-name-specifier or qualified-id that names a member of an
28262 unknown specialization. */
28263 return (type_dependent_expression_p (name)
28264 || dependent_scope_p (scope));
28267 if (TREE_CODE (expression) == TEMPLATE_DECL
28268 && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
28269 return uses_outer_template_parms (expression);
28271 if (TREE_CODE (expression) == STMT_EXPR)
28272 expression = stmt_expr_value_expr (expression);
28274 if (BRACE_ENCLOSED_INITIALIZER_P (expression))
28276 for (auto &elt : CONSTRUCTOR_ELTS (expression))
28277 if (type_dependent_expression_p (elt.value))
28278 return true;
28279 return false;
28282 /* A static data member of the current instantiation with incomplete
28283 array type is type-dependent, as the definition and specializations
28284 can have different bounds. */
28285 if (VAR_P (expression)
28286 && DECL_CLASS_SCOPE_P (expression)
28287 && dependent_type_p (DECL_CONTEXT (expression))
28288 && VAR_HAD_UNKNOWN_BOUND (expression))
28289 return true;
28291 /* An array of unknown bound depending on a variadic parameter, eg:
28293 template<typename... Args>
28294 void foo (Args... args)
28296 int arr[] = { args... };
28299 template<int... vals>
28300 void bar ()
28302 int arr[] = { vals... };
28305 If the array has no length and has an initializer, it must be that
28306 we couldn't determine its length in cp_complete_array_type because
28307 it is dependent. */
28308 if (((VAR_P (expression) && DECL_INITIAL (expression))
28309 || COMPOUND_LITERAL_P (expression))
28310 && TREE_TYPE (expression) != NULL_TREE
28311 && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
28312 && !TYPE_DOMAIN (TREE_TYPE (expression)))
28313 return true;
28315 /* Pull a FUNCTION_DECL out of a BASELINK if we can. */
28316 if (BASELINK_P (expression))
28318 if (BASELINK_OPTYPE (expression)
28319 && dependent_type_p (BASELINK_OPTYPE (expression)))
28320 return true;
28321 expression = BASELINK_FUNCTIONS (expression);
28324 /* A function or variable template-id is type-dependent if it has any
28325 dependent template arguments. */
28326 if (VAR_OR_FUNCTION_DECL_P (expression)
28327 && DECL_LANG_SPECIFIC (expression)
28328 && DECL_TEMPLATE_INFO (expression))
28330 /* Consider the innermost template arguments, since those are the ones
28331 that come from the template-id; the template arguments for the
28332 enclosing class do not make it type-dependent unless they are used in
28333 the type of the decl. */
28334 if (instantiates_primary_template_p (expression)
28335 && (any_dependent_template_arguments_p
28336 (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
28337 return true;
28340 /* Otherwise, if the function decl isn't from a dependent scope, it can't be
28341 type-dependent. Checking this is important for functions with auto return
28342 type, which looks like a dependent type. */
28343 if (TREE_CODE (expression) == FUNCTION_DECL
28344 && !(DECL_CLASS_SCOPE_P (expression)
28345 && dependent_type_p (DECL_CONTEXT (expression)))
28346 && !(DECL_LANG_SPECIFIC (expression)
28347 && DECL_UNIQUE_FRIEND_P (expression)
28348 && (!DECL_FRIEND_CONTEXT (expression)
28349 || dependent_type_p (DECL_FRIEND_CONTEXT (expression))))
28350 && !DECL_LOCAL_DECL_P (expression))
28352 gcc_assert (!dependent_type_p (TREE_TYPE (expression))
28353 || undeduced_auto_decl (expression));
28354 return false;
28357 /* Otherwise, its constraints could still depend on outer template parameters
28358 from its (dependent) scope. */
28359 if (TREE_CODE (expression) == FUNCTION_DECL
28360 /* As an optimization, check this cheaper sufficient condition first.
28361 (At this point we've established that we're looking at a member of
28362 a dependent class, so it makes sense to start treating say undeduced
28363 auto as dependent.) */
28364 && !dependent_type_p (TREE_TYPE (expression))
28365 && uses_outer_template_parms_in_constraints (expression))
28366 return true;
28368 /* Always dependent, on the number of arguments if nothing else. */
28369 if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
28370 return true;
28372 if (TREE_TYPE (expression) == unknown_type_node)
28374 if (TREE_CODE (expression) == ADDR_EXPR)
28375 return type_dependent_expression_p (TREE_OPERAND (expression, 0));
28376 if (TREE_CODE (expression) == COMPONENT_REF
28377 || TREE_CODE (expression) == OFFSET_REF)
28379 if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
28380 return true;
28381 expression = TREE_OPERAND (expression, 1);
28382 if (identifier_p (expression))
28383 return false;
28385 /* SCOPE_REF with non-null TREE_TYPE is always non-dependent. */
28386 if (TREE_CODE (expression) == SCOPE_REF)
28387 return false;
28389 /* CO_AWAIT/YIELD_EXPR with unknown type is always dependent. */
28390 if (TREE_CODE (expression) == CO_AWAIT_EXPR
28391 || TREE_CODE (expression) == CO_YIELD_EXPR)
28392 return true;
28394 if (BASELINK_P (expression))
28396 if (BASELINK_OPTYPE (expression)
28397 && dependent_type_p (BASELINK_OPTYPE (expression)))
28398 return true;
28399 expression = BASELINK_FUNCTIONS (expression);
28402 if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
28404 if (any_dependent_template_arguments_p
28405 (TREE_OPERAND (expression, 1)))
28406 return true;
28407 expression = TREE_OPERAND (expression, 0);
28408 if (identifier_p (expression))
28409 return true;
28412 gcc_assert (OVL_P (expression));
28414 for (lkp_iterator iter (expression); iter; ++iter)
28415 if (type_dependent_expression_p (*iter))
28416 return true;
28418 return false;
28421 /* The type of a non-type template parm declared with a placeholder type
28422 depends on the corresponding template argument, even though
28423 placeholders are not normally considered dependent. */
28424 if (TREE_CODE (expression) == TEMPLATE_PARM_INDEX
28425 && is_auto (TREE_TYPE (expression)))
28426 return true;
28428 gcc_assert (TREE_CODE (expression) != TYPE_DECL);
28430 /* Dependent type attributes might not have made it from the decl to
28431 the type yet. */
28432 if (DECL_P (expression)
28433 && any_dependent_type_attributes_p (DECL_ATTRIBUTES (expression)))
28434 return true;
28436 return (dependent_type_p (TREE_TYPE (expression)));
28439 /* [temp.dep.expr]/5: A class member access expression (5.2.5) is
28440 type-dependent if the expression refers to a member of the current
28441 instantiation and the type of the referenced member is dependent, or the
28442 class member access expression refers to a member of an unknown
28443 specialization.
28445 This function returns true if the OBJECT in such a class member access
28446 expression is of an unknown specialization. */
28448 bool
28449 type_dependent_object_expression_p (tree object)
28451 /* An IDENTIFIER_NODE can sometimes have a TREE_TYPE, but it's still
28452 dependent. */
28453 if (TREE_CODE (object) == IDENTIFIER_NODE)
28454 return true;
28455 tree scope = TREE_TYPE (object);
28456 return (!scope || dependent_scope_p (scope));
28459 /* walk_tree callback function for instantiation_dependent_expression_p,
28460 below. Returns non-zero if a dependent subexpression is found. */
28462 static tree
28463 instantiation_dependent_r (tree *tp, int *walk_subtrees,
28464 void * /*data*/)
28466 if (TYPE_P (*tp))
28468 /* We don't have to worry about decltype currently because decltype
28469 of an instantiation-dependent expr is a dependent type. This
28470 might change depending on the resolution of DR 1172. */
28471 *walk_subtrees = false;
28472 return NULL_TREE;
28474 enum tree_code code = TREE_CODE (*tp);
28475 switch (code)
28477 /* Don't treat an argument list as dependent just because it has no
28478 TREE_TYPE. */
28479 case TREE_LIST:
28480 case TREE_VEC:
28481 case NONTYPE_ARGUMENT_PACK:
28482 return NULL_TREE;
28484 case TEMPLATE_PARM_INDEX:
28485 if (dependent_type_p (TREE_TYPE (*tp)))
28486 return *tp;
28487 if (TEMPLATE_PARM_PARAMETER_PACK (*tp))
28488 return *tp;
28489 /* We'll check value-dependence separately. */
28490 return NULL_TREE;
28492 /* Handle expressions with type operands. */
28493 case SIZEOF_EXPR:
28494 case ALIGNOF_EXPR:
28495 case TYPEID_EXPR:
28496 case AT_ENCODE_EXPR:
28498 tree op = TREE_OPERAND (*tp, 0);
28499 if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
28500 op = TREE_TYPE (op);
28501 if (TYPE_P (op))
28503 if (dependent_type_p (op))
28504 return *tp;
28505 else
28507 *walk_subtrees = false;
28508 return NULL_TREE;
28511 break;
28514 case COMPONENT_REF:
28515 if (identifier_p (TREE_OPERAND (*tp, 1)))
28516 /* In a template, finish_class_member_access_expr creates a
28517 COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
28518 type-dependent, so that we can check access control at
28519 instantiation time (PR 42277). See also Core issue 1273. */
28520 return *tp;
28521 break;
28523 case SCOPE_REF:
28524 if (instantiation_dependent_scope_ref_p (*tp))
28525 return *tp;
28526 else
28527 break;
28529 /* Treat statement-expressions as dependent. */
28530 case BIND_EXPR:
28531 return *tp;
28533 /* Treat requires-expressions as dependent. */
28534 case REQUIRES_EXPR:
28535 return *tp;
28537 case CONSTRUCTOR:
28538 if (CONSTRUCTOR_IS_DEPENDENT (*tp))
28539 return *tp;
28540 break;
28542 case TEMPLATE_DECL:
28543 case FUNCTION_DECL:
28544 /* Before C++17, a noexcept-specifier isn't part of the function type
28545 so it doesn't affect type dependence, but we still want to consider it
28546 for instantiation dependence. */
28547 if (cxx_dialect < cxx17
28548 && DECL_DECLARES_FUNCTION_P (*tp)
28549 && value_dependent_noexcept_spec_p (TREE_TYPE (*tp)))
28550 return *tp;
28551 break;
28553 default:
28554 break;
28557 if (type_dependent_expression_p (*tp))
28558 return *tp;
28559 else
28560 return NULL_TREE;
28563 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
28564 sense defined by the ABI:
28566 "An expression is instantiation-dependent if it is type-dependent
28567 or value-dependent, or it has a subexpression that is type-dependent
28568 or value-dependent."
28570 Except don't actually check value-dependence for unevaluated expressions,
28571 because in sizeof(i) we don't care about the value of i. Checking
28572 type-dependence will in turn check value-dependence of array bounds/template
28573 arguments as needed. */
28575 bool
28576 instantiation_dependent_uneval_expression_p (tree expression)
28578 tree result;
28580 if (!processing_template_decl)
28581 return false;
28583 if (expression == error_mark_node)
28584 return false;
28586 result = cp_walk_tree_without_duplicates (&expression,
28587 instantiation_dependent_r, NULL);
28588 return result != NULL_TREE;
28591 /* As above, but also check value-dependence of the expression as a whole. */
28593 bool
28594 instantiation_dependent_expression_p (tree expression)
28596 return (instantiation_dependent_uneval_expression_p (expression)
28597 || (processing_template_decl
28598 && potential_constant_expression (expression)
28599 && value_dependent_expression_p (expression)));
28602 /* Like type_dependent_expression_p, but it also works while not processing
28603 a template definition, i.e. during substitution or mangling. */
28605 bool
28606 type_dependent_expression_p_push (tree expr)
28608 bool b;
28609 ++processing_template_decl;
28610 b = type_dependent_expression_p (expr);
28611 --processing_template_decl;
28612 return b;
28615 /* Returns TRUE if ARGS contains a type-dependent expression. */
28617 bool
28618 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
28620 if (!processing_template_decl || !args)
28621 return false;
28623 for (tree arg : *args)
28624 if (type_dependent_expression_p (arg))
28625 return true;
28627 return false;
28630 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
28631 expressions) contains any type-dependent expressions. */
28633 bool
28634 any_type_dependent_elements_p (const_tree list)
28636 for (; list; list = TREE_CHAIN (list))
28637 if (type_dependent_expression_p (TREE_VALUE (list)))
28638 return true;
28640 return false;
28643 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
28644 expressions) contains any value-dependent expressions. */
28646 bool
28647 any_value_dependent_elements_p (const_tree list)
28649 for (; list; list = TREE_CHAIN (list))
28650 if (value_dependent_expression_p (TREE_VALUE (list)))
28651 return true;
28653 return false;
28656 /* Returns TRUE if the ARG (a template argument) is dependent. */
28658 bool
28659 dependent_template_arg_p (tree arg)
28661 if (!processing_template_decl)
28662 return false;
28664 /* Assume a template argument that was wrongly written by the user
28665 is dependent. This is consistent with what
28666 any_dependent_template_arguments_p [that calls this function]
28667 does. */
28668 if (!arg || arg == error_mark_node)
28669 return true;
28671 if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
28672 arg = argument_pack_select_arg (arg);
28674 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
28675 return true;
28676 if (TREE_CODE (arg) == TEMPLATE_DECL)
28678 if (DECL_TEMPLATE_PARM_P (arg))
28679 return true;
28680 /* A member template of a dependent class is not necessarily
28681 type-dependent, but it is a dependent template argument because it
28682 will be a member of an unknown specialization to that template. */
28683 tree scope = CP_DECL_CONTEXT (arg);
28684 return TYPE_P (scope) && dependent_type_p (scope);
28686 else if (ARGUMENT_PACK_P (arg))
28688 tree args = ARGUMENT_PACK_ARGS (arg);
28689 for (tree arg : tree_vec_range (args))
28690 if (dependent_template_arg_p (arg))
28691 return true;
28692 return false;
28694 else if (TYPE_P (arg))
28695 return dependent_type_p (arg);
28696 else
28697 return value_dependent_expression_p (arg);
28700 /* Identify any expressions that use function parms. */
28702 static tree
28703 find_parm_usage_r (tree *tp, int *walk_subtrees, void*)
28705 tree t = *tp;
28706 if (TREE_CODE (t) == PARM_DECL)
28708 *walk_subtrees = 0;
28709 return t;
28711 return NULL_TREE;
28714 /* Returns true if a type specialization formed using the template
28715 arguments ARGS needs to use structural equality. */
28717 bool
28718 any_template_arguments_need_structural_equality_p (tree args)
28720 int i;
28721 int j;
28723 if (!args)
28724 return false;
28725 if (args == error_mark_node)
28726 return true;
28728 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
28730 tree level = TMPL_ARGS_LEVEL (args, i + 1);
28731 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
28733 tree arg = TREE_VEC_ELT (level, j);
28734 tree packed_args = NULL_TREE;
28735 int k, len = 1;
28737 if (ARGUMENT_PACK_P (arg))
28739 /* Look inside the argument pack. */
28740 packed_args = ARGUMENT_PACK_ARGS (arg);
28741 len = TREE_VEC_LENGTH (packed_args);
28744 for (k = 0; k < len; ++k)
28746 if (packed_args)
28747 arg = TREE_VEC_ELT (packed_args, k);
28749 if (error_operand_p (arg))
28750 return true;
28751 else if (TREE_CODE (arg) == TEMPLATE_DECL)
28752 continue;
28753 else if (arg == any_targ_node)
28754 /* An any_targ_node argument (added by add_defaults_to_ttp)
28755 makes the corresponding specialization not canonicalizable,
28756 since template_args_equal always return true for it. We
28757 may see this when called from bind_template_template_parm. */
28758 return true;
28759 /* Checking current_function_decl because this structural
28760 comparison is only necessary for redeclaration. */
28761 else if (!current_function_decl
28762 && dependent_template_arg_p (arg)
28763 && (cp_walk_tree_without_duplicates
28764 (&arg, find_parm_usage_r, NULL)))
28765 /* The identity of a class template specialization that uses
28766 a function parameter depends on the identity of the function.
28767 And if this specialization appeared in the trailing return
28768 type thereof, we don't know the identity of the function
28769 (e.g. if it's a redeclaration or a new function) until we
28770 form its signature and go through duplicate_decls. Thus
28771 it's unsafe to decide on a canonical type now (which depends
28772 on the DECL_CONTEXT of the function parameter, which can get
28773 mutated after the fact by duplicate_decls), so just require
28774 structural equality in this case (PR52830). */
28775 return true;
28780 return false;
28783 /* Returns true if ARGS (a collection of template arguments) contains
28784 any dependent arguments. */
28786 bool
28787 any_dependent_template_arguments_p (const_tree args)
28789 if (args == error_mark_node)
28790 return true;
28791 if (!processing_template_decl || !args)
28792 return false;
28794 for (int i = 0, depth = TMPL_ARGS_DEPTH (args); i < depth; ++i)
28796 const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
28797 for (tree arg : tree_vec_range (CONST_CAST_TREE (level)))
28798 if (dependent_template_arg_p (arg))
28799 return true;
28802 return false;
28805 /* Returns true if ARGS contains any errors. */
28807 bool
28808 any_erroneous_template_args_p (const_tree args)
28810 int i;
28811 int j;
28813 if (args == error_mark_node)
28814 return true;
28816 if (args && TREE_CODE (args) != TREE_VEC)
28818 if (tree ti = get_template_info (args))
28819 args = TI_ARGS (ti);
28820 else
28821 args = NULL_TREE;
28824 if (!args)
28825 return false;
28827 for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
28829 const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
28830 for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
28831 if (error_operand_p (TREE_VEC_ELT (level, j)))
28832 return true;
28835 return false;
28838 /* Returns TRUE if the template TMPL is type-dependent. */
28840 bool
28841 dependent_template_p (tree tmpl)
28843 if (TREE_CODE (tmpl) == OVERLOAD)
28845 for (lkp_iterator iter (tmpl); iter; ++iter)
28846 if (dependent_template_p (*iter))
28847 return true;
28848 return false;
28851 /* Template template parameters are dependent. */
28852 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
28853 || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
28854 return true;
28855 /* So are names that have not been looked up. */
28856 if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
28857 return true;
28858 return false;
28861 /* Returns TRUE if the specialization TMPL<ARGS> is dependent. */
28863 bool
28864 dependent_template_id_p (tree tmpl, tree args)
28866 return (dependent_template_p (tmpl)
28867 || any_dependent_template_arguments_p (args));
28870 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
28871 are dependent. */
28873 bool
28874 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
28876 int i;
28878 if (!processing_template_decl)
28879 return false;
28881 for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
28883 tree decl = TREE_VEC_ELT (declv, i);
28884 tree init = TREE_VEC_ELT (initv, i);
28885 tree cond = TREE_VEC_ELT (condv, i);
28886 tree incr = TREE_VEC_ELT (incrv, i);
28888 if (type_dependent_expression_p (decl)
28889 || TREE_CODE (decl) == SCOPE_REF)
28890 return true;
28892 if (init && type_dependent_expression_p (init))
28893 return true;
28895 if (cond == global_namespace)
28896 return true;
28898 if (type_dependent_expression_p (cond))
28899 return true;
28901 if (COMPARISON_CLASS_P (cond)
28902 && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
28903 || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
28904 return true;
28906 if (TREE_CODE (incr) == MODOP_EXPR)
28908 if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
28909 || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
28910 return true;
28912 else if (type_dependent_expression_p (incr))
28913 return true;
28914 else if (TREE_CODE (incr) == MODIFY_EXPR)
28916 if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
28917 return true;
28918 else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
28920 tree t = TREE_OPERAND (incr, 1);
28921 if (type_dependent_expression_p (TREE_OPERAND (t, 0))
28922 || type_dependent_expression_p (TREE_OPERAND (t, 1)))
28923 return true;
28925 /* If this loop has a class iterator with != comparison
28926 with increment other than i++/++i/i--/--i, make sure the
28927 increment is constant. */
28928 if (CLASS_TYPE_P (TREE_TYPE (decl))
28929 && TREE_CODE (cond) == NE_EXPR)
28931 if (TREE_OPERAND (t, 0) == decl)
28932 t = TREE_OPERAND (t, 1);
28933 else
28934 t = TREE_OPERAND (t, 0);
28935 if (TREE_CODE (t) != INTEGER_CST)
28936 return true;
28942 return false;
28945 /* TYPE is a TYPENAME_TYPE. Returns the ordinary TYPE to which the
28946 TYPENAME_TYPE corresponds. Returns the original TYPENAME_TYPE if
28947 no such TYPE can be found. Note that this function peers inside
28948 uninstantiated templates and therefore should be used only in
28949 extremely limited situations. ONLY_CURRENT_P restricts this
28950 peering to the currently open classes hierarchy (which is required
28951 when comparing types). */
28953 tree
28954 resolve_typename_type (tree type, bool only_current_p)
28956 tree scope;
28957 tree name;
28958 tree decl;
28959 int quals;
28960 tree pushed_scope;
28961 tree result;
28963 gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
28965 scope = TYPE_CONTEXT (type);
28966 /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope. */
28967 gcc_checking_assert (uses_template_parms (scope));
28969 /* Usually the non-qualified identifier of a TYPENAME_TYPE is
28970 TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of a
28971 TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL
28972 representing the typedef. In that case TYPE_IDENTIFIER (type) is
28973 not the non-qualified identifier of the TYPENAME_TYPE anymore.
28974 So by getting the TYPE_IDENTIFIER of the _main declaration_ of
28975 the TYPENAME_TYPE instead, we avoid messing up with a possible
28976 typedef variant case. */
28977 name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
28979 /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
28980 it first before we can figure out what NAME refers to. */
28981 if (TREE_CODE (scope) == TYPENAME_TYPE)
28983 if (TYPENAME_IS_RESOLVING_P (scope))
28984 /* Given a class template A with a dependent base with nested type C,
28985 typedef typename A::C::C C will land us here, as trying to resolve
28986 the initial A::C leads to the local C typedef, which leads back to
28987 A::C::C. So we break the recursion now. */
28988 return type;
28989 else
28990 scope = resolve_typename_type (scope, only_current_p);
28992 /* If we don't know what SCOPE refers to, then we cannot resolve the
28993 TYPENAME_TYPE. */
28994 if (!CLASS_TYPE_P (scope))
28995 return type;
28996 /* If this is a typedef, we don't want to look inside (c++/11987). */
28997 if (typedef_variant_p (type))
28998 return type;
28999 /* If SCOPE isn't the template itself, it will not have a valid
29000 TYPE_FIELDS list. */
29001 if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
29002 /* scope is either the template itself or a compatible instantiation
29003 like X<T>, so look up the name in the original template. */
29004 scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
29005 /* If scope has no fields, it can't be a current instantiation. Check this
29006 before currently_open_class to avoid infinite recursion (71515). */
29007 if (!TYPE_FIELDS (scope))
29008 return type;
29009 /* If the SCOPE is not the current instantiation, there's no reason
29010 to look inside it. */
29011 if (only_current_p && !currently_open_class (scope))
29012 return type;
29013 /* Enter the SCOPE so that name lookup will be resolved as if we
29014 were in the class definition. In particular, SCOPE will no
29015 longer be considered a dependent type. */
29016 pushed_scope = push_scope (scope);
29017 /* Look up the declaration. */
29018 decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
29019 tf_warning_or_error);
29021 result = NULL_TREE;
29023 /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
29024 find a TEMPLATE_DECL. Otherwise, we want to find a TYPE_DECL. */
29025 tree fullname = TYPENAME_TYPE_FULLNAME (type);
29026 if (!decl)
29027 /*nop*/;
29028 else if (identifier_p (fullname)
29029 && TREE_CODE (decl) == TYPE_DECL)
29031 result = TREE_TYPE (decl);
29032 if (result == error_mark_node)
29033 result = NULL_TREE;
29035 else if (TREE_CODE (fullname) == TEMPLATE_ID_EXPR
29036 && DECL_CLASS_TEMPLATE_P (decl))
29038 /* Obtain the template and the arguments. */
29039 tree tmpl = TREE_OPERAND (fullname, 0);
29040 if (TREE_CODE (tmpl) == IDENTIFIER_NODE)
29042 /* We get here with a plain identifier because a previous tentative
29043 parse of the nested-name-specifier as part of a ptr-operator saw
29044 ::template X<A>. The use of ::template is necessary in a
29045 ptr-operator, but wrong in a declarator-id.
29047 [temp.names]: In a qualified-id of a declarator-id, the keyword
29048 template shall not appear at the top level. */
29049 pedwarn (cp_expr_loc_or_input_loc (fullname), OPT_Wpedantic,
29050 "keyword %<template%> not allowed in declarator-id");
29051 tmpl = decl;
29053 tree args = TREE_OPERAND (fullname, 1);
29054 /* Instantiate the template. */
29055 result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
29056 /*entering_scope=*/true,
29057 tf_error | tf_user);
29058 if (result == error_mark_node)
29059 result = NULL_TREE;
29062 /* Leave the SCOPE. */
29063 if (pushed_scope)
29064 pop_scope (pushed_scope);
29066 /* If we failed to resolve it, return the original typename. */
29067 if (!result)
29068 return type;
29070 /* If lookup found a typename type, resolve that too. */
29071 if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
29073 /* Ill-formed programs can cause infinite recursion here, so we
29074 must catch that. */
29075 TYPENAME_IS_RESOLVING_P (result) = 1;
29076 result = resolve_typename_type (result, only_current_p);
29077 TYPENAME_IS_RESOLVING_P (result) = 0;
29080 /* Qualify the resulting type. */
29081 quals = cp_type_quals (type);
29082 if (quals)
29083 result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
29085 return result;
29088 /* EXPR is an expression which is not type-dependent. Return a proxy
29089 for EXPR that can be used to compute the types of larger
29090 expressions containing EXPR. */
29092 tree
29093 build_non_dependent_expr (tree expr)
29095 tree orig_expr = expr;
29096 tree inner_expr;
29098 /* When checking, try to get a constant value for all non-dependent
29099 expressions in order to expose bugs in *_dependent_expression_p
29100 and constexpr. This can affect code generation, see PR70704, so
29101 only do this for -fchecking=2. */
29102 if (flag_checking > 1
29103 && cxx_dialect >= cxx11
29104 /* Don't do this during nsdmi parsing as it can lead to
29105 unexpected recursive instantiations. */
29106 && !parsing_nsdmi ()
29107 /* Don't do this during concept processing either and for
29108 the same reason. */
29109 && !processing_constraint_expression_p ())
29110 fold_non_dependent_expr (expr, tf_none);
29112 STRIP_ANY_LOCATION_WRAPPER (expr);
29114 /* Preserve OVERLOADs; the functions must be available to resolve
29115 types. */
29116 inner_expr = expr;
29117 if (TREE_CODE (inner_expr) == STMT_EXPR)
29118 inner_expr = stmt_expr_value_expr (inner_expr);
29119 if (TREE_CODE (inner_expr) == ADDR_EXPR)
29120 inner_expr = TREE_OPERAND (inner_expr, 0);
29121 if (TREE_CODE (inner_expr) == COMPONENT_REF)
29122 inner_expr = TREE_OPERAND (inner_expr, 1);
29123 if (is_overloaded_fn (inner_expr)
29124 || TREE_CODE (inner_expr) == OFFSET_REF)
29125 return orig_expr;
29126 /* There is no need to return a proxy for a variable, parameter
29127 or enumerator. */
29128 if (VAR_P (expr) || TREE_CODE (expr) == PARM_DECL
29129 || TREE_CODE (expr) == CONST_DECL)
29130 return orig_expr;
29131 /* Preserve string constants; conversions from string constants to
29132 "char *" are allowed, even though normally a "const char *"
29133 cannot be used to initialize a "char *". */
29134 if (TREE_CODE (expr) == STRING_CST)
29135 return orig_expr;
29136 /* Preserve void and arithmetic constants, as an optimization -- there is no
29137 reason to create a new node. */
29138 if (TREE_CODE (expr) == VOID_CST
29139 || TREE_CODE (expr) == INTEGER_CST
29140 || TREE_CODE (expr) == REAL_CST)
29141 return orig_expr;
29142 /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
29143 There is at least one place where we want to know that a
29144 particular expression is a throw-expression: when checking a ?:
29145 expression, there are special rules if the second or third
29146 argument is a throw-expression. */
29147 if (TREE_CODE (expr) == THROW_EXPR)
29148 return orig_expr;
29150 /* Don't wrap an initializer list, we need to be able to look inside. */
29151 if (BRACE_ENCLOSED_INITIALIZER_P (expr))
29152 return orig_expr;
29154 /* Don't wrap a dummy object, we need to be able to test for it. */
29155 if (is_dummy_object (expr))
29156 return orig_expr;
29158 if (TREE_CODE (expr) == COND_EXPR)
29159 return build3 (COND_EXPR,
29160 TREE_TYPE (expr),
29161 build_non_dependent_expr (TREE_OPERAND (expr, 0)),
29162 (TREE_OPERAND (expr, 1)
29163 ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
29164 : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
29165 build_non_dependent_expr (TREE_OPERAND (expr, 2)));
29166 if (TREE_CODE (expr) == COMPOUND_EXPR)
29167 return build2 (COMPOUND_EXPR,
29168 TREE_TYPE (expr),
29169 TREE_OPERAND (expr, 0),
29170 build_non_dependent_expr (TREE_OPERAND (expr, 1)));
29172 /* If the type is unknown, it can't really be non-dependent */
29173 gcc_assert (TREE_TYPE (expr) != unknown_type_node);
29175 /* Otherwise, build a NON_DEPENDENT_EXPR. */
29176 return build1_loc (EXPR_LOCATION (orig_expr), NON_DEPENDENT_EXPR,
29177 TREE_TYPE (expr), expr);
29180 /* ARGS is a vector of expressions as arguments to a function call.
29181 Replace the arguments with equivalent non-dependent expressions.
29182 This modifies ARGS in place. */
29184 void
29185 make_args_non_dependent (vec<tree, va_gc> *args)
29187 unsigned int ix;
29188 tree arg;
29190 FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
29192 tree newarg = build_non_dependent_expr (arg);
29193 if (newarg != arg)
29194 (*args)[ix] = newarg;
29198 /* Returns a type which represents 'auto' or 'decltype(auto)'. We use a
29199 TEMPLATE_TYPE_PARM with a level one deeper than the actual template parms,
29200 by default. If set_canonical is true, we set TYPE_CANONICAL on it. */
29202 static tree
29203 make_auto_1 (tree name, bool set_canonical, int level = -1)
29205 if (level == -1)
29206 level = current_template_depth + 1;
29207 tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
29208 TYPE_NAME (au) = build_decl (input_location, TYPE_DECL, name, au);
29209 TYPE_STUB_DECL (au) = TYPE_NAME (au);
29210 TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
29211 (0, level, level, TYPE_NAME (au), NULL_TREE);
29212 if (set_canonical)
29213 TYPE_CANONICAL (au) = canonical_type_parameter (au);
29214 DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
29215 SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
29216 if (name == decltype_auto_identifier)
29217 AUTO_IS_DECLTYPE (au) = true;
29219 return au;
29222 tree
29223 make_decltype_auto (void)
29225 return make_auto_1 (decltype_auto_identifier, true);
29228 tree
29229 make_auto (void)
29231 return make_auto_1 (auto_identifier, true);
29234 /* Return a C++17 deduction placeholder for class template TMPL.
29235 There are represented as an 'auto' with the special level 0 and
29236 CLASS_PLACEHOLDER_TEMPLATE set. */
29238 tree
29239 make_template_placeholder (tree tmpl)
29241 tree t = make_auto_1 (auto_identifier, false, /*level=*/0);
29242 CLASS_PLACEHOLDER_TEMPLATE (t) = tmpl;
29243 /* Our canonical type depends on the placeholder. */
29244 TYPE_CANONICAL (t) = canonical_type_parameter (t);
29245 return t;
29248 /* True iff T is a C++17 class template deduction placeholder. */
29250 bool
29251 template_placeholder_p (tree t)
29253 return is_auto (t) && CLASS_PLACEHOLDER_TEMPLATE (t);
29256 /* Make a "constrained auto" type-specifier. This is an auto or
29257 decltype(auto) type with constraints that must be associated after
29258 deduction. The constraint is formed from the given concept CON
29259 and its optional sequence of template arguments ARGS.
29261 TYPE must be the result of make_auto_type or make_decltype_auto_type. */
29263 static tree
29264 make_constrained_placeholder_type (tree type, tree con, tree args)
29266 /* Build the constraint. */
29267 tree tmpl = DECL_TI_TEMPLATE (con);
29268 tree expr = tmpl;
29269 if (TREE_CODE (con) == FUNCTION_DECL)
29270 expr = ovl_make (tmpl);
29271 ++processing_template_decl;
29272 expr = build_concept_check (expr, type, args, tf_warning_or_error);
29273 --processing_template_decl;
29275 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (type)
29276 = build_tree_list (current_template_parms, expr);
29278 /* Our canonical type depends on the constraint. */
29279 TYPE_CANONICAL (type) = canonical_type_parameter (type);
29281 /* Attach the constraint to the type declaration. */
29282 return TYPE_NAME (type);
29285 /* Make a "constrained auto" type-specifier. */
29287 tree
29288 make_constrained_auto (tree con, tree args)
29290 tree type = make_auto_1 (auto_identifier, false);
29291 return make_constrained_placeholder_type (type, con, args);
29294 /* Make a "constrained decltype(auto)" type-specifier. */
29296 tree
29297 make_constrained_decltype_auto (tree con, tree args)
29299 tree type = make_auto_1 (decltype_auto_identifier, false);
29300 return make_constrained_placeholder_type (type, con, args);
29303 /* Returns true if the placeholder type constraint T has any dependent
29304 (explicit) template arguments. */
29306 static bool
29307 placeholder_type_constraint_dependent_p (tree t)
29309 tree id = unpack_concept_check (t);
29310 tree args = TREE_OPERAND (id, 1);
29311 tree first = TREE_VEC_ELT (args, 0);
29312 if (ARGUMENT_PACK_P (first))
29314 args = expand_template_argument_pack (args);
29315 first = TREE_VEC_ELT (args, 0);
29317 gcc_checking_assert (TREE_CODE (first) == WILDCARD_DECL
29318 || is_auto (first));
29319 for (int i = 1; i < TREE_VEC_LENGTH (args); ++i)
29320 if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
29321 return true;
29322 return false;
29325 /* Build and return a concept definition. Like other templates, the
29326 CONCEPT_DECL node is wrapped by a TEMPLATE_DECL. This returns the
29327 the TEMPLATE_DECL. */
29329 tree
29330 finish_concept_definition (cp_expr id, tree init, tree attrs)
29332 gcc_assert (identifier_p (id));
29333 gcc_assert (processing_template_decl);
29335 location_t loc = id.get_location();
29337 /* A concept-definition shall not have associated constraints. */
29338 if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
29340 error_at (loc, "a concept cannot be constrained");
29341 TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
29344 /* A concept-definition shall appear in namespace scope. Templates
29345 aren't allowed in block scope, so we only need to check for class
29346 scope. */
29347 if (TYPE_P (current_scope()) || !DECL_NAMESPACE_SCOPE_P (current_scope ()))
29349 error_at (loc, "concept %qE not in namespace scope", *id);
29350 return error_mark_node;
29353 if (current_template_depth > 1)
29355 error_at (loc, "concept %qE has multiple template parameter lists", *id);
29356 return error_mark_node;
29359 /* Initially build the concept declaration; its type is bool. */
29360 tree decl = build_lang_decl_loc (loc, CONCEPT_DECL, *id, boolean_type_node);
29361 DECL_CONTEXT (decl) = current_scope ();
29362 DECL_INITIAL (decl) = init;
29364 if (attrs)
29365 cplus_decl_attributes (&decl, attrs, 0);
29367 set_originating_module (decl, false);
29369 /* Push the enclosing template. */
29370 return push_template_decl (decl);
29373 /* Given type ARG, return std::initializer_list<ARG>. */
29375 static tree
29376 listify (tree arg)
29378 tree std_init_list = lookup_qualified_name (std_node, init_list_identifier);
29380 if (std_init_list == error_mark_node
29381 || !DECL_CLASS_TEMPLATE_P (std_init_list))
29383 gcc_rich_location richloc (input_location);
29384 maybe_add_include_fixit (&richloc, "<initializer_list>", false);
29385 error_at (&richloc,
29386 "deducing from brace-enclosed initializer list"
29387 " requires %<#include <initializer_list>%>");
29389 return error_mark_node;
29391 tree argvec = make_tree_vec (1);
29392 TREE_VEC_ELT (argvec, 0) = arg;
29394 return lookup_template_class (std_init_list, argvec, NULL_TREE,
29395 NULL_TREE, 0, tf_warning_or_error);
29398 /* Replace auto in TYPE with std::initializer_list<auto>. */
29400 static tree
29401 listify_autos (tree type, tree auto_node)
29403 tree init_auto = listify (strip_top_quals (auto_node));
29404 tree argvec = make_tree_vec (1);
29405 TREE_VEC_ELT (argvec, 0) = init_auto;
29406 if (processing_template_decl)
29407 argvec = add_to_template_args (current_template_args (), argvec);
29408 return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
29411 /* Hash traits for hashing possibly constrained 'auto'
29412 TEMPLATE_TYPE_PARMs for use by do_auto_deduction. */
29414 struct auto_hash : default_hash_traits<tree>
29416 static inline hashval_t hash (tree);
29417 static inline bool equal (tree, tree);
29420 /* Hash the 'auto' T. */
29422 inline hashval_t
29423 auto_hash::hash (tree t)
29425 if (tree c = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (t)))
29426 /* Matching constrained-type-specifiers denote the same template
29427 parameter, so hash the constraint. */
29428 return hash_placeholder_constraint (c);
29429 else
29430 /* But unconstrained autos are all separate, so just hash the pointer. */
29431 return iterative_hash_object (t, 0);
29434 /* Compare two 'auto's. */
29436 inline bool
29437 auto_hash::equal (tree t1, tree t2)
29439 if (t1 == t2)
29440 return true;
29442 tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
29443 tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
29445 /* Two unconstrained autos are distinct. */
29446 if (!c1 || !c2)
29447 return false;
29449 return equivalent_placeholder_constraints (c1, c2);
29452 /* for_each_template_parm callback for extract_autos: if t is a (possibly
29453 constrained) auto, add it to the vector. */
29455 static int
29456 extract_autos_r (tree t, void *data)
29458 hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
29459 if (is_auto (t) && !template_placeholder_p (t))
29461 /* All the autos were built with index 0; fix that up now. */
29462 tree *p = hash.find_slot (t, INSERT);
29463 int idx;
29464 if (*p)
29465 /* If this is a repeated constrained-type-specifier, use the index we
29466 chose before. */
29467 idx = TEMPLATE_TYPE_IDX (*p);
29468 else
29470 /* Otherwise this is new, so use the current count. */
29471 *p = t;
29472 idx = hash.elements () - 1;
29474 if (idx != TEMPLATE_TYPE_IDX (t))
29476 gcc_checking_assert (TEMPLATE_TYPE_IDX (t) == 0);
29477 gcc_checking_assert (TYPE_CANONICAL (t) != t);
29478 TEMPLATE_TYPE_IDX (t) = idx;
29479 TYPE_CANONICAL (t) = canonical_type_parameter (t);
29483 /* Always keep walking. */
29484 return 0;
29487 /* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
29488 says they can appear anywhere in the type. */
29490 static tree
29491 extract_autos (tree type)
29493 hash_set<tree> visited;
29494 hash_table<auto_hash> hash (2);
29496 for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
29498 tree tree_vec = make_tree_vec (hash.elements());
29499 for (tree elt : hash)
29501 unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
29502 TREE_VEC_ELT (tree_vec, i)
29503 = build_tree_list (NULL_TREE, TYPE_NAME (elt));
29506 return tree_vec;
29509 /* The stem for deduction guide names. */
29510 const char *const dguide_base = "__dguide_";
29512 /* Return the name for a deduction guide for class template TMPL. */
29514 tree
29515 dguide_name (tree tmpl)
29517 tree type = (TYPE_P (tmpl) ? tmpl : TREE_TYPE (tmpl));
29518 tree tname = TYPE_IDENTIFIER (type);
29519 char *buf = (char *) alloca (1 + strlen (dguide_base)
29520 + IDENTIFIER_LENGTH (tname));
29521 memcpy (buf, dguide_base, strlen (dguide_base));
29522 memcpy (buf + strlen (dguide_base), IDENTIFIER_POINTER (tname),
29523 IDENTIFIER_LENGTH (tname) + 1);
29524 tree dname = get_identifier (buf);
29525 TREE_TYPE (dname) = type;
29526 return dname;
29529 /* True if NAME is the name of a deduction guide. */
29531 bool
29532 dguide_name_p (tree name)
29534 return (TREE_CODE (name) == IDENTIFIER_NODE
29535 && TREE_TYPE (name)
29536 && startswith (IDENTIFIER_POINTER (name), dguide_base));
29539 /* True if FN is a deduction guide. */
29541 bool
29542 deduction_guide_p (const_tree fn)
29544 if (DECL_P (fn))
29545 if (tree name = DECL_NAME (fn))
29546 return dguide_name_p (name);
29547 return false;
29550 /* True if FN is the copy deduction guide, i.e. A(A)->A. */
29552 bool
29553 copy_guide_p (const_tree fn)
29555 gcc_assert (deduction_guide_p (fn));
29556 if (!DECL_ARTIFICIAL (fn))
29557 return false;
29558 tree parms = FUNCTION_FIRST_USER_PARMTYPE (DECL_TI_TEMPLATE (fn));
29559 return (TREE_CHAIN (parms) == void_list_node
29560 && same_type_p (TREE_VALUE (parms), TREE_TYPE (DECL_NAME (fn))));
29563 /* True if FN is a guide generated from a constructor template. */
29565 bool
29566 template_guide_p (const_tree fn)
29568 gcc_assert (deduction_guide_p (fn));
29569 if (!DECL_ARTIFICIAL (fn))
29570 return false;
29571 tree tmpl = DECL_TI_TEMPLATE (fn);
29572 if (tree org = DECL_ABSTRACT_ORIGIN (tmpl))
29573 return PRIMARY_TEMPLATE_P (org);
29574 return false;
29577 /* True if FN is an aggregate initialization guide or the copy deduction
29578 guide. */
29580 bool
29581 builtin_guide_p (const_tree fn)
29583 if (!deduction_guide_p (fn))
29584 return false;
29585 if (!DECL_ARTIFICIAL (fn))
29586 /* Explicitly declared. */
29587 return false;
29588 if (DECL_ABSTRACT_ORIGIN (fn))
29589 /* Derived from a constructor. */
29590 return false;
29591 return true;
29594 /* OLDDECL is a _DECL for a template parameter. Return a similar parameter at
29595 LEVEL:INDEX, using tsubst_args and complain for substitution into non-type
29596 template parameter types. Note that the handling of template template
29597 parameters relies on current_template_parms being set appropriately for the
29598 new template. */
29600 static tree
29601 rewrite_template_parm (tree olddecl, unsigned index, unsigned level,
29602 tree tsubst_args, tsubst_flags_t complain)
29604 if (olddecl == error_mark_node)
29605 return error_mark_node;
29607 tree oldidx = get_template_parm_index (olddecl);
29609 tree newtype;
29610 if (TREE_CODE (olddecl) == TYPE_DECL
29611 || TREE_CODE (olddecl) == TEMPLATE_DECL)
29613 tree oldtype = TREE_TYPE (olddecl);
29614 newtype = cxx_make_type (TREE_CODE (oldtype));
29615 TYPE_MAIN_VARIANT (newtype) = newtype;
29617 else
29619 newtype = TREE_TYPE (olddecl);
29620 if (type_uses_auto (newtype))
29622 // Substitute once to fix references to other template parameters.
29623 newtype = tsubst (newtype, tsubst_args,
29624 complain|tf_partial, NULL_TREE);
29625 // Now substitute again to reduce the level of the auto.
29626 newtype = tsubst (newtype, current_template_args (),
29627 complain, NULL_TREE);
29629 else
29630 newtype = tsubst (newtype, tsubst_args,
29631 complain, NULL_TREE);
29634 tree newdecl
29635 = build_decl (DECL_SOURCE_LOCATION (olddecl), TREE_CODE (olddecl),
29636 DECL_NAME (olddecl), newtype);
29637 SET_DECL_TEMPLATE_PARM_P (newdecl);
29639 tree newidx;
29640 if (TREE_CODE (olddecl) == TYPE_DECL
29641 || TREE_CODE (olddecl) == TEMPLATE_DECL)
29643 newidx = TEMPLATE_TYPE_PARM_INDEX (newtype)
29644 = build_template_parm_index (index, level, level,
29645 newdecl, newtype);
29646 TEMPLATE_PARM_PARAMETER_PACK (newidx)
29647 = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
29648 TYPE_STUB_DECL (newtype) = TYPE_NAME (newtype) = newdecl;
29650 if (TREE_CODE (olddecl) == TEMPLATE_DECL)
29652 DECL_TEMPLATE_RESULT (newdecl)
29653 = build_decl (DECL_SOURCE_LOCATION (olddecl), TYPE_DECL,
29654 DECL_NAME (olddecl), newtype);
29655 DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (newdecl)) = true;
29656 // First create a copy (ttargs) of tsubst_args with an
29657 // additional level for the template template parameter's own
29658 // template parameters (ttparms).
29659 tree ttparms = (INNERMOST_TEMPLATE_PARMS
29660 (DECL_TEMPLATE_PARMS (olddecl)));
29661 const int depth = TMPL_ARGS_DEPTH (tsubst_args);
29662 tree ttargs = make_tree_vec (depth + 1);
29663 for (int i = 0; i < depth; ++i)
29664 TREE_VEC_ELT (ttargs, i) = TMPL_ARGS_LEVEL (tsubst_args, i + 1);
29665 TREE_VEC_ELT (ttargs, depth)
29666 = template_parms_level_to_args (ttparms);
29667 // Substitute ttargs into ttparms to fix references to
29668 // other template parameters.
29669 ttparms = tsubst_template_parms_level (ttparms, ttargs,
29670 complain|tf_partial);
29671 // Now substitute again with args based on tparms, to reduce
29672 // the level of the ttparms.
29673 ttargs = current_template_args ();
29674 ttparms = tsubst_template_parms_level (ttparms, ttargs,
29675 complain);
29676 // Finally, tack the adjusted parms onto tparms.
29677 ttparms = tree_cons (size_int (level + 1), ttparms,
29678 copy_node (current_template_parms));
29679 // As with all template template parms, the parameter list captured
29680 // by this template template parm that corresponds to its own level
29681 // should be empty. This avoids infinite recursion when structurally
29682 // comparing two such rewritten template template parms (PR102479).
29683 gcc_assert (!TREE_VEC_LENGTH
29684 (TREE_VALUE (TREE_CHAIN (DECL_TEMPLATE_PARMS (olddecl)))));
29685 gcc_assert (TMPL_PARMS_DEPTH (TREE_CHAIN (ttparms)) == level);
29686 TREE_VALUE (TREE_CHAIN (ttparms)) = make_tree_vec (0);
29687 // All done.
29688 DECL_TEMPLATE_PARMS (newdecl) = ttparms;
29691 if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (olddecl)))
29692 SET_TYPE_STRUCTURAL_EQUALITY (newtype);
29693 else
29694 TYPE_CANONICAL (newtype) = canonical_type_parameter (newtype);
29696 else
29698 tree oldconst = TEMPLATE_PARM_DECL (oldidx);
29699 tree newconst
29700 = build_decl (DECL_SOURCE_LOCATION (oldconst),
29701 TREE_CODE (oldconst),
29702 DECL_NAME (oldconst), newtype);
29703 TREE_CONSTANT (newconst) = TREE_CONSTANT (newdecl)
29704 = TREE_READONLY (newconst) = TREE_READONLY (newdecl) = true;
29705 SET_DECL_TEMPLATE_PARM_P (newconst);
29706 newidx = build_template_parm_index (index, level, level,
29707 newconst, newtype);
29708 TEMPLATE_PARM_PARAMETER_PACK (newidx)
29709 = TEMPLATE_PARM_PARAMETER_PACK (oldidx);
29710 DECL_INITIAL (newdecl) = DECL_INITIAL (newconst) = newidx;
29713 return newdecl;
29716 /* As rewrite_template_parm, but for the whole TREE_LIST representing a
29717 template parameter. */
29719 static tree
29720 rewrite_tparm_list (tree oldelt, unsigned index, unsigned level,
29721 tree targs, unsigned targs_index, tsubst_flags_t complain)
29723 tree olddecl = TREE_VALUE (oldelt);
29724 tree newdecl = rewrite_template_parm (olddecl, index, level,
29725 targs, complain);
29726 if (newdecl == error_mark_node)
29727 return error_mark_node;
29728 tree newdef = tsubst_template_arg (TREE_PURPOSE (oldelt),
29729 targs, complain, NULL_TREE);
29730 tree list = build_tree_list (newdef, newdecl);
29731 TEMPLATE_PARM_CONSTRAINTS (list)
29732 = tsubst_constraint_info (TEMPLATE_PARM_CONSTRAINTS (oldelt),
29733 targs, complain, NULL_TREE);
29734 int depth = TMPL_ARGS_DEPTH (targs);
29735 TMPL_ARG (targs, depth, targs_index) = template_parm_to_arg (list);
29736 return list;
29739 /* Returns a C++17 class deduction guide template based on the constructor
29740 CTOR. As a special case, CTOR can be a RECORD_TYPE for an implicit default
29741 guide, REFERENCE_TYPE for an implicit copy/move guide, or TREE_LIST for an
29742 aggregate initialization guide. OUTER_ARGS are the template arguments
29743 for the enclosing scope of the class. */
29745 static tree
29746 build_deduction_guide (tree type, tree ctor, tree outer_args, tsubst_flags_t complain)
29748 tree tparms, targs, fparms, fargs, ci;
29749 bool memtmpl = false;
29750 bool explicit_p;
29751 location_t loc;
29752 tree fn_tmpl = NULL_TREE;
29754 if (outer_args)
29756 ++processing_template_decl;
29757 type = tsubst (type, outer_args, complain, CLASSTYPE_TI_TEMPLATE (type));
29758 --processing_template_decl;
29761 if (!DECL_DECLARES_FUNCTION_P (ctor))
29763 if (TYPE_P (ctor))
29765 bool copy_p = TYPE_REF_P (ctor);
29766 if (copy_p)
29767 fparms = tree_cons (NULL_TREE, type, void_list_node);
29768 else
29769 fparms = void_list_node;
29771 else if (TREE_CODE (ctor) == TREE_LIST)
29772 fparms = ctor;
29773 else
29774 gcc_unreachable ();
29776 tree ctmpl = CLASSTYPE_TI_TEMPLATE (type);
29777 tparms = DECL_TEMPLATE_PARMS (ctmpl);
29778 targs = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
29779 ci = NULL_TREE;
29780 fargs = NULL_TREE;
29781 loc = DECL_SOURCE_LOCATION (ctmpl);
29782 explicit_p = false;
29784 else
29786 ++processing_template_decl;
29787 bool ok = true;
29789 complain |= tf_dguide;
29791 fn_tmpl
29792 = (TREE_CODE (ctor) == TEMPLATE_DECL ? ctor
29793 : DECL_TI_TEMPLATE (ctor));
29794 if (outer_args)
29795 fn_tmpl = tsubst (fn_tmpl, outer_args, complain, ctor);
29796 ctor = DECL_TEMPLATE_RESULT (fn_tmpl);
29798 tparms = DECL_TEMPLATE_PARMS (fn_tmpl);
29799 /* If type is a member class template, DECL_TI_ARGS (ctor) will have
29800 fully specialized args for the enclosing class. Strip those off, as
29801 the deduction guide won't have those template parameters. */
29802 targs = get_innermost_template_args (DECL_TI_ARGS (ctor),
29803 TMPL_PARMS_DEPTH (tparms));
29804 /* Discard the 'this' parameter. */
29805 fparms = FUNCTION_ARG_CHAIN (ctor);
29806 fargs = TREE_CHAIN (DECL_ARGUMENTS (ctor));
29807 ci = get_constraints (ctor);
29808 loc = DECL_SOURCE_LOCATION (ctor);
29809 explicit_p = DECL_NONCONVERTING_P (ctor);
29811 if (PRIMARY_TEMPLATE_P (fn_tmpl))
29813 memtmpl = true;
29815 /* For a member template constructor, we need to flatten the two
29816 template parameter lists into one, and then adjust the function
29817 signature accordingly. This gets...complicated. */
29818 tree save_parms = current_template_parms;
29820 /* For a member template we should have two levels of parms/args, one
29821 for the class and one for the constructor. We stripped
29822 specialized args for further enclosing classes above. */
29823 const int depth = 2;
29824 gcc_assert (TMPL_ARGS_DEPTH (targs) == depth);
29826 /* Template args for translating references to the two-level template
29827 parameters into references to the one-level template parameters we
29828 are creating. */
29829 tree tsubst_args = copy_node (targs);
29830 TMPL_ARGS_LEVEL (tsubst_args, depth)
29831 = copy_node (TMPL_ARGS_LEVEL (tsubst_args, depth));
29833 /* Template parms for the constructor template. */
29834 tree ftparms = TREE_VALUE (tparms);
29835 unsigned flen = TREE_VEC_LENGTH (ftparms);
29836 /* Template parms for the class template. */
29837 tparms = TREE_CHAIN (tparms);
29838 tree ctparms = TREE_VALUE (tparms);
29839 unsigned clen = TREE_VEC_LENGTH (ctparms);
29840 /* Template parms for the deduction guide start as a copy of the
29841 template parms for the class. We set current_template_parms for
29842 lookup_template_class_1. */
29843 current_template_parms = tparms = copy_node (tparms);
29844 tree new_vec = TREE_VALUE (tparms) = make_tree_vec (flen + clen);
29845 for (unsigned i = 0; i < clen; ++i)
29846 TREE_VEC_ELT (new_vec, i) = TREE_VEC_ELT (ctparms, i);
29848 /* Now we need to rewrite the constructor parms to append them to the
29849 class parms. */
29850 for (unsigned i = 0; i < flen; ++i)
29852 unsigned index = i + clen;
29853 unsigned level = 1;
29854 tree oldelt = TREE_VEC_ELT (ftparms, i);
29855 tree newelt
29856 = rewrite_tparm_list (oldelt, index, level,
29857 tsubst_args, i, complain);
29858 if (newelt == error_mark_node)
29859 ok = false;
29860 TREE_VEC_ELT (new_vec, index) = newelt;
29863 /* Now we have a final set of template parms to substitute into the
29864 function signature. */
29865 targs = template_parms_to_args (tparms);
29866 fparms = tsubst_arg_types (fparms, tsubst_args, NULL_TREE,
29867 complain, ctor);
29868 if (fparms == error_mark_node)
29869 ok = false;
29870 if (ci)
29872 if (outer_args)
29873 /* FIXME: We'd like to avoid substituting outer template
29874 arguments into the constraint ahead of time, but the
29875 construction of tsubst_args assumes that outer arguments
29876 are already substituted in. */
29877 ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
29878 ci = tsubst_constraint_info (ci, tsubst_args, complain, ctor);
29881 /* Parms are to have DECL_CHAIN tsubsted, which would be skipped if
29882 cp_unevaluated_operand. */
29883 cp_evaluated ev;
29884 fargs = tsubst (fargs, tsubst_args, complain, ctor);
29885 current_template_parms = save_parms;
29887 else
29889 /* Substitute in the same arguments to rewrite class members into
29890 references to members of an unknown specialization. */
29891 cp_evaluated ev;
29892 fparms = tsubst_arg_types (fparms, targs, NULL_TREE, complain, ctor);
29893 fargs = tsubst (fargs, targs, complain, ctor);
29894 if (ci)
29896 if (outer_args)
29897 /* FIXME: As above. */
29898 ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
29899 ci = tsubst_constraint_info (ci, targs, complain, ctor);
29903 --processing_template_decl;
29904 if (!ok)
29905 return error_mark_node;
29908 if (!memtmpl)
29910 /* Copy the parms so we can set DECL_PRIMARY_TEMPLATE. */
29911 tparms = copy_node (tparms);
29912 INNERMOST_TEMPLATE_PARMS (tparms)
29913 = copy_node (INNERMOST_TEMPLATE_PARMS (tparms));
29916 tree fntype = build_function_type (type, fparms);
29917 tree ded_fn = build_lang_decl_loc (loc,
29918 FUNCTION_DECL,
29919 dguide_name (type), fntype);
29920 DECL_ARGUMENTS (ded_fn) = fargs;
29921 DECL_ARTIFICIAL (ded_fn) = true;
29922 DECL_NONCONVERTING_P (ded_fn) = explicit_p;
29923 tree ded_tmpl = build_template_decl (ded_fn, tparms, /*member*/false);
29924 DECL_ARTIFICIAL (ded_tmpl) = true;
29925 DECL_TEMPLATE_INFO (ded_fn) = build_template_info (ded_tmpl, targs);
29926 DECL_PRIMARY_TEMPLATE (ded_tmpl) = ded_tmpl;
29927 if (DECL_P (ctor))
29928 DECL_ABSTRACT_ORIGIN (ded_tmpl) = fn_tmpl;
29929 if (ci)
29930 set_constraints (ded_tmpl, ci);
29932 return ded_tmpl;
29935 /* Add to LIST the member types for the reshaped initializer CTOR. */
29937 static tree
29938 collect_ctor_idx_types (tree ctor, tree list, tree elt = NULL_TREE)
29940 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (ctor);
29941 tree idx, val; unsigned i;
29942 FOR_EACH_CONSTRUCTOR_ELT (v, i, idx, val)
29944 tree ftype = elt ? elt : TREE_TYPE (idx);
29945 if (BRACE_ENCLOSED_INITIALIZER_P (val)
29946 && CONSTRUCTOR_BRACES_ELIDED_P (val))
29948 tree subelt = NULL_TREE;
29949 if (TREE_CODE (ftype) == ARRAY_TYPE)
29950 subelt = TREE_TYPE (ftype);
29951 list = collect_ctor_idx_types (val, list, subelt);
29952 continue;
29954 tree arg = NULL_TREE;
29955 if (i == v->length() - 1
29956 && PACK_EXPANSION_P (ftype))
29957 /* Give the trailing pack expansion parameter a default argument to
29958 match aggregate initialization behavior, even if we deduce the
29959 length of the pack separately to more than we have initializers. */
29960 arg = build_constructor (init_list_type_node, NULL);
29961 /* if ei is of array type and xi is a braced-init-list or string literal,
29962 Ti is an rvalue reference to the declared type of ei */
29963 STRIP_ANY_LOCATION_WRAPPER (val);
29964 if (TREE_CODE (ftype) == ARRAY_TYPE
29965 && (BRACE_ENCLOSED_INITIALIZER_P (val)
29966 || TREE_CODE (val) == STRING_CST))
29968 if (TREE_CODE (val) == STRING_CST)
29969 ftype = cp_build_qualified_type
29970 (ftype, cp_type_quals (ftype) | TYPE_QUAL_CONST);
29971 ftype = (cp_build_reference_type
29972 (ftype, BRACE_ENCLOSED_INITIALIZER_P (val)));
29974 list = tree_cons (arg, ftype, list);
29977 return list;
29980 /* Return whether ETYPE is, or is derived from, a specialization of TMPL. */
29982 static bool
29983 is_spec_or_derived (tree etype, tree tmpl)
29985 if (!etype || !CLASS_TYPE_P (etype))
29986 return false;
29988 etype = cv_unqualified (etype);
29989 tree type = TREE_TYPE (tmpl);
29990 tree tparms = (INNERMOST_TEMPLATE_PARMS
29991 (DECL_TEMPLATE_PARMS (tmpl)));
29992 tree targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
29993 int err = unify (tparms, targs, type, etype,
29994 UNIFY_ALLOW_DERIVED, /*explain*/false);
29995 ggc_free (targs);
29996 return !err;
29999 static tree alias_ctad_tweaks (tree, tree);
30001 /* Return a C++20 aggregate deduction candidate for TYPE initialized from
30002 INIT. */
30004 static tree
30005 maybe_aggr_guide (tree tmpl, tree init, vec<tree,va_gc> *args)
30007 if (cxx_dialect < cxx20)
30008 return NULL_TREE;
30010 if (init == NULL_TREE)
30011 return NULL_TREE;
30013 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30015 tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30016 tree tinfo = get_template_info (under);
30017 if (tree guide = maybe_aggr_guide (TI_TEMPLATE (tinfo), init, args))
30018 return alias_ctad_tweaks (tmpl, guide);
30019 return NULL_TREE;
30022 /* We might be creating a guide for a class member template, e.g.,
30024 template<typename U> struct A {
30025 template<typename T> struct B { T t; };
30028 At this point, A will have been instantiated. Below, we need to
30029 use both A<U>::B<T> (TEMPLATE_TYPE) and A<int>::B<T> (TYPE) types. */
30030 const bool member_template_p
30031 = (DECL_TEMPLATE_INFO (tmpl)
30032 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (tmpl)));
30033 tree type = TREE_TYPE (tmpl);
30034 tree template_type = (member_template_p
30035 ? TREE_TYPE (DECL_TI_TEMPLATE (tmpl))
30036 : type);
30037 if (!CP_AGGREGATE_TYPE_P (template_type))
30038 return NULL_TREE;
30040 /* No aggregate candidate for copy-initialization. */
30041 if (args->length() == 1)
30043 tree val = (*args)[0];
30044 if (is_spec_or_derived (TREE_TYPE (val), tmpl))
30045 return NULL_TREE;
30048 /* If we encounter a problem, we just won't add the candidate. */
30049 tsubst_flags_t complain = tf_none;
30051 tree parms = NULL_TREE;
30052 if (BRACE_ENCLOSED_INITIALIZER_P (init))
30054 init = reshape_init (template_type, init, complain);
30055 if (init == error_mark_node)
30056 return NULL_TREE;
30057 parms = collect_ctor_idx_types (init, parms);
30058 /* If we're creating a deduction guide for a member class template,
30059 we've used the original template pattern type for the reshape_init
30060 above; this is done because we want PARMS to be a template parameter
30061 type, something that can be deduced when used as a function template
30062 parameter. At this point the outer class template has already been
30063 partially instantiated (we deferred the deduction until the enclosing
30064 scope is non-dependent). Therefore we have to partially instantiate
30065 PARMS, so that its template level is properly reduced and we don't get
30066 mismatches when deducing types using the guide with PARMS. */
30067 if (member_template_p)
30069 ++processing_template_decl;
30070 parms = tsubst (parms, DECL_TI_ARGS (tmpl), complain, init);
30071 --processing_template_decl;
30074 else if (TREE_CODE (init) == TREE_LIST)
30076 int len = list_length (init);
30077 for (tree field = TYPE_FIELDS (type);
30078 len;
30079 --len, field = DECL_CHAIN (field))
30081 field = next_aggregate_field (field);
30082 if (!field)
30083 return NULL_TREE;
30084 tree ftype = finish_decltype_type (field, true, complain);
30085 parms = tree_cons (NULL_TREE, ftype, parms);
30088 else
30089 /* Aggregate initialization doesn't apply to an initializer expression. */
30090 return NULL_TREE;
30092 if (parms)
30094 tree last = parms;
30095 parms = nreverse (parms);
30096 TREE_CHAIN (last) = void_list_node;
30097 tree guide = build_deduction_guide (type, parms, NULL_TREE, complain);
30098 return guide;
30101 return NULL_TREE;
30104 /* UGUIDES are the deduction guides for the underlying template of alias
30105 template TMPL; adjust them to be deduction guides for TMPL. */
30107 static tree
30108 alias_ctad_tweaks (tree tmpl, tree uguides)
30110 /* [over.match.class.deduct]: When resolving a placeholder for a deduced
30111 class type (9.2.8.2) where the template-name names an alias template A,
30112 the defining-type-id of A must be of the form
30114 typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
30116 as specified in 9.2.8.2. The guides of A are the set of functions or
30117 function templates formed as follows. For each function or function
30118 template f in the guides of the template named by the simple-template-id
30119 of the defining-type-id, the template arguments of the return type of f
30120 are deduced from the defining-type-id of A according to the process in
30121 13.10.2.5 with the exception that deduction does not fail if not all
30122 template arguments are deduced. Let g denote the result of substituting
30123 these deductions into f. If substitution succeeds, form a function or
30124 function template f' with the following properties and add it to the set
30125 of guides of A:
30127 * The function type of f' is the function type of g.
30129 * If f is a function template, f' is a function template whose template
30130 parameter list consists of all the template parameters of A (including
30131 their default template arguments) that appear in the above deductions or
30132 (recursively) in their default template arguments, followed by the
30133 template parameters of f that were not deduced (including their default
30134 template arguments), otherwise f' is not a function template.
30136 * The associated constraints (13.5.2) are the conjunction of the
30137 associated constraints of g and a constraint that is satisfied if and only
30138 if the arguments of A are deducible (see below) from the return type.
30140 * If f is a copy deduction candidate (12.4.1.8), then f' is considered to
30141 be so as well.
30143 * If f was generated from a deduction-guide (12.4.1.8), then f' is
30144 considered to be so as well.
30146 * The explicit-specifier of f' is the explicit-specifier of g (if
30147 any). */
30149 tsubst_flags_t complain = tf_warning_or_error;
30150 tree atype = TREE_TYPE (tmpl);
30151 tree aguides = NULL_TREE;
30152 tree fullatparms = DECL_TEMPLATE_PARMS (tmpl);
30153 tree atparms = INNERMOST_TEMPLATE_PARMS (fullatparms);
30154 unsigned natparms = TREE_VEC_LENGTH (atparms);
30155 tree utype = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30156 for (ovl_iterator iter (uguides); iter; ++iter)
30158 tree f = *iter;
30159 tree in_decl = f;
30160 location_t loc = DECL_SOURCE_LOCATION (f);
30161 tree ret = TREE_TYPE (TREE_TYPE (f));
30162 tree fprime = f;
30163 if (TREE_CODE (f) == TEMPLATE_DECL)
30165 processing_template_decl_sentinel ptds (/*reset*/false);
30166 ++processing_template_decl;
30168 /* Deduce template arguments for f from the type-id of A. */
30169 tree ftparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (f));
30170 unsigned len = TREE_VEC_LENGTH (ftparms);
30171 tree targs = make_tree_vec (len);
30172 int err = unify (ftparms, targs, ret, utype, UNIFY_ALLOW_NONE, false);
30173 if (err)
30174 /* CWG2664: Discard any deductions, still build the guide. */
30175 for (unsigned i = 0; i < len; ++i)
30176 TREE_VEC_ELT (targs, i) = NULL_TREE;
30178 /* The number of parms for f' is the number of parms of A used in
30179 the deduced arguments plus non-deduced parms of f. */
30180 unsigned ndlen = 0;
30181 unsigned j;
30182 for (unsigned i = 0; i < len; ++i)
30183 if (TREE_VEC_ELT (targs, i) == NULL_TREE)
30184 ++ndlen;
30185 find_template_parameter_info ftpi (fullatparms);
30186 ftpi.find_in_recursive (targs);
30187 unsigned nusedatparms = ftpi.num_found ();
30188 unsigned nfparms = nusedatparms + ndlen;
30189 tree gtparms = make_tree_vec (nfparms);
30191 /* Set current_template_parms as in build_deduction_guide. */
30192 auto ctp = make_temp_override (current_template_parms);
30193 current_template_parms = copy_node (DECL_TEMPLATE_PARMS (tmpl));
30194 TREE_VALUE (current_template_parms) = gtparms;
30196 j = 0;
30197 unsigned level = 1;
30199 /* First copy over the used parms of A. */
30200 tree atargs = make_tree_vec (natparms);
30201 for (unsigned i = 0; i < natparms; ++i)
30203 tree elt = TREE_VEC_ELT (atparms, i);
30204 if (ftpi.found (elt))
30206 unsigned index = j++;
30207 tree nelt = rewrite_tparm_list (elt, index, level,
30208 atargs, i, complain);
30209 TREE_VEC_ELT (gtparms, index) = nelt;
30212 gcc_checking_assert (j == nusedatparms);
30214 /* Adjust the deduced template args for f to refer to the A parms
30215 with their new indexes. */
30216 if (nusedatparms && nusedatparms != natparms)
30217 targs = tsubst_template_args (targs, atargs, complain, in_decl);
30219 /* Now rewrite the non-deduced parms of f. */
30220 for (unsigned i = 0; ndlen && i < len; ++i)
30221 if (TREE_VEC_ELT (targs, i) == NULL_TREE)
30223 --ndlen;
30224 unsigned index = j++;
30225 tree oldlist = TREE_VEC_ELT (ftparms, i);
30226 tree list = rewrite_tparm_list (oldlist, index, level,
30227 targs, i, complain);
30228 TREE_VEC_ELT (gtparms, index) = list;
30230 gtparms = build_tree_list (size_one_node, gtparms);
30232 /* Substitute the deduced arguments plus the rewritten template
30233 parameters into f to get g. This covers the type, copyness,
30234 guideness, and explicit-specifier. */
30235 tree g;
30237 /* Parms are to have DECL_CHAIN tsubsted, which would be skipped
30238 if cp_unevaluated_operand. */
30239 cp_evaluated ev;
30240 g = tsubst_decl (DECL_TEMPLATE_RESULT (f), targs, complain);
30242 if (g == error_mark_node)
30243 continue;
30244 if (nfparms == 0)
30246 /* The targs are all non-dependent, so g isn't a template. */
30247 fprime = g;
30248 ret = TREE_TYPE (TREE_TYPE (fprime));
30249 goto non_template;
30251 DECL_USE_TEMPLATE (g) = 0;
30252 fprime = build_template_decl (g, gtparms, false);
30253 DECL_TEMPLATE_RESULT (fprime) = g;
30254 TREE_TYPE (fprime) = TREE_TYPE (g);
30255 tree gtargs = template_parms_to_args (gtparms);
30256 DECL_TEMPLATE_INFO (g) = build_template_info (fprime, gtargs);
30257 DECL_PRIMARY_TEMPLATE (fprime) = fprime;
30259 /* Substitute the associated constraints. */
30260 tree ci = get_constraints (f);
30261 if (ci)
30262 ci = tsubst_constraint_info (ci, targs, complain, in_decl);
30263 if (ci == error_mark_node)
30264 continue;
30266 /* Add a constraint that the return type matches the instantiation of
30267 A with the same template arguments. */
30268 ret = TREE_TYPE (TREE_TYPE (fprime));
30269 if (!same_type_p (atype, ret)
30270 /* FIXME this should mean they don't compare as equivalent. */
30271 || dependent_alias_template_spec_p (atype, nt_opaque))
30273 tree same = finish_trait_expr (loc, CPTK_IS_DEDUCIBLE, tmpl, ret);
30274 ci = append_constraint (ci, same);
30277 if (ci)
30279 remove_constraints (fprime);
30280 set_constraints (fprime, ci);
30283 else
30285 /* For a non-template deduction guide, if the arguments of A aren't
30286 deducible from the return type, don't add the candidate. */
30287 non_template:
30288 if (!type_targs_deducible_from (tmpl, ret))
30289 continue;
30292 aguides = lookup_add (fprime, aguides);
30295 return aguides;
30298 /* True iff template arguments for TMPL can be deduced from TYPE.
30299 Used to implement CPTK_IS_DEDUCIBLE for alias CTAD according to
30300 [over.match.class.deduct].
30302 This check is specified in terms of partial specialization, so the behavior
30303 should be parallel to that of get_partial_spec_bindings. */
30305 bool
30306 type_targs_deducible_from (tree tmpl, tree type)
30308 tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
30309 int len = TREE_VEC_LENGTH (tparms);
30310 tree targs = make_tree_vec (len);
30311 bool tried_array_deduction = (cxx_dialect < cxx17);
30313 /* If tmpl is a class template, this is trivial: it's deducible if TYPE is a
30314 specialization of TMPL. */
30315 if (DECL_CLASS_TEMPLATE_P (tmpl))
30316 return (CLASS_TYPE_P (type)
30317 && CLASSTYPE_TEMPLATE_INFO (type)
30318 && CLASSTYPE_TI_TEMPLATE (type) == tmpl);
30320 /* Otherwise it's an alias template. */
30321 again:
30322 if (unify (tparms, targs, TREE_TYPE (tmpl), type,
30323 UNIFY_ALLOW_NONE, false))
30324 return false;
30326 /* We don't fail on an undeduced targ the second time through (like
30327 get_partial_spec_bindings) because we're going to try defaults. */
30328 for (int i = 0; i < len; ++i)
30329 if (! TREE_VEC_ELT (targs, i))
30331 tree tparm = TREE_VEC_ELT (tparms, i);
30332 tparm = TREE_VALUE (tparm);
30334 if (!tried_array_deduction
30335 && TREE_CODE (tparm) == TYPE_DECL)
30337 try_array_deduction (tparms, targs, TREE_TYPE (tmpl));
30338 tried_array_deduction = true;
30339 if (TREE_VEC_ELT (targs, i))
30340 goto again;
30342 /* If the type parameter is a parameter pack, then it will be deduced
30343 to an empty parameter pack. This is another case that doesn't model
30344 well as partial specialization. */
30345 if (template_parameter_pack_p (tparm))
30347 tree arg;
30348 if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
30350 arg = make_node (NONTYPE_ARGUMENT_PACK);
30351 TREE_CONSTANT (arg) = 1;
30353 else
30354 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
30355 ARGUMENT_PACK_ARGS (arg) = make_tree_vec (0);
30356 TREE_VEC_ELT (targs, i) = arg;
30360 /* Maybe add in default template args. This seems like a flaw in the
30361 specification in terms of partial specialization, since it says the
30362 partial specialization has the the template parameter list of A, but a
30363 partial specialization can't have default targs. */
30364 targs = coerce_template_parms (tparms, targs, tmpl, tf_none);
30365 if (targs == error_mark_node)
30366 return false;
30368 /* I believe we don't need the template_template_parm_bindings_ok_p call
30369 because coerce_template_parms did coerce_template_template_parms. */
30371 return constraints_satisfied_p (tmpl, targs);
30374 /* Return artificial deduction guides built from the constructors of class
30375 template TMPL. */
30377 static tree
30378 ctor_deduction_guides_for (tree tmpl, tsubst_flags_t complain)
30380 tree outer_args = outer_template_args (tmpl);
30381 tree type = TREE_TYPE (most_general_template (tmpl));
30383 tree cands = NULL_TREE;
30385 for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (type)); iter; ++iter)
30387 /* Skip inherited constructors. */
30388 if (iter.using_p ())
30389 continue;
30391 tree guide = build_deduction_guide (type, *iter, outer_args, complain);
30392 cands = lookup_add (guide, cands);
30395 /* Add implicit default constructor deduction guide. */
30396 if (!TYPE_HAS_USER_CONSTRUCTOR (type))
30398 tree guide = build_deduction_guide (type, type, outer_args,
30399 complain);
30400 cands = lookup_add (guide, cands);
30403 /* Add copy guide. */
30405 tree gtype = build_reference_type (type);
30406 tree guide = build_deduction_guide (type, gtype, outer_args,
30407 complain);
30408 cands = lookup_add (guide, cands);
30411 return cands;
30414 static GTY((deletable)) hash_map<tree, tree_pair_p> *dguide_cache;
30416 /* Return the non-aggregate deduction guides for deducible template TMPL. The
30417 aggregate candidate is added separately because it depends on the
30418 initializer. Set ANY_DGUIDES_P if we find a non-implicit deduction
30419 guide. */
30421 static tree
30422 deduction_guides_for (tree tmpl, bool &any_dguides_p, tsubst_flags_t complain)
30424 tree guides = NULL_TREE;
30425 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30427 tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30428 tree tinfo = get_template_info (under);
30429 guides = deduction_guides_for (TI_TEMPLATE (tinfo), any_dguides_p,
30430 complain);
30432 else
30434 guides = lookup_qualified_name (CP_DECL_CONTEXT (tmpl),
30435 dguide_name (tmpl),
30436 LOOK_want::NORMAL, /*complain*/false);
30437 if (guides == error_mark_node)
30438 guides = NULL_TREE;
30439 else
30440 any_dguides_p = true;
30443 /* Cache the deduction guides for a template. We also remember the result of
30444 lookup, and rebuild everything if it changes; should be very rare. */
30445 tree_pair_p cache = NULL;
30446 if (tree_pair_p &r
30447 = hash_map_safe_get_or_insert<hm_ggc> (dguide_cache, tmpl))
30449 cache = r;
30450 if (cache->purpose == guides)
30451 return cache->value;
30453 else
30455 r = cache = ggc_cleared_alloc<tree_pair_s> ();
30456 cache->purpose = guides;
30459 tree cands = NULL_TREE;
30460 if (DECL_ALIAS_TEMPLATE_P (tmpl))
30461 cands = alias_ctad_tweaks (tmpl, guides);
30462 else
30464 cands = ctor_deduction_guides_for (tmpl, complain);
30465 for (ovl_iterator it (guides); it; ++it)
30466 cands = lookup_add (*it, cands);
30469 cache->value = cands;
30470 return cands;
30473 /* Return whether TMPL is a (class template argument-) deducible template. */
30475 bool
30476 ctad_template_p (tree tmpl)
30478 /* A deducible template is either a class template or is an alias template
30479 whose defining-type-id is of the form
30481 typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
30483 where the nested-name-specifier (if any) is non-dependent and the
30484 template-name of the simple-template-id names a deducible template. */
30486 if (DECL_CLASS_TEMPLATE_P (tmpl)
30487 || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
30488 return true;
30489 if (!DECL_ALIAS_TEMPLATE_P (tmpl))
30490 return false;
30491 tree orig = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
30492 if (tree tinfo = get_template_info (orig))
30493 return ctad_template_p (TI_TEMPLATE (tinfo));
30494 return false;
30497 /* Deduce template arguments for the class template placeholder PTYPE for
30498 template TMPL based on the initializer INIT, and return the resulting
30499 type. */
30501 static tree
30502 do_class_deduction (tree ptype, tree tmpl, tree init,
30503 int flags, tsubst_flags_t complain)
30505 /* We should have handled this in the caller. */
30506 if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
30507 return ptype;
30509 /* If the class was erroneous, don't try to deduce, because that
30510 can generate a lot of diagnostic. */
30511 if (TREE_TYPE (tmpl)
30512 && TYPE_LANG_SPECIFIC (TREE_TYPE (tmpl))
30513 && CLASSTYPE_ERRONEOUS (TREE_TYPE (tmpl)))
30514 return ptype;
30516 /* Wait until the enclosing scope is non-dependent. */
30517 if (DECL_CLASS_SCOPE_P (tmpl)
30518 && dependent_type_p (DECL_CONTEXT (tmpl)))
30519 return ptype;
30521 /* Initializing one placeholder from another. */
30522 if (init
30523 && (TREE_CODE (init) == TEMPLATE_PARM_INDEX
30524 || (TREE_CODE (init) == EXPR_PACK_EXPANSION
30525 && (TREE_CODE (PACK_EXPANSION_PATTERN (init))
30526 == TEMPLATE_PARM_INDEX)))
30527 && is_auto (TREE_TYPE (init))
30528 && CLASS_PLACEHOLDER_TEMPLATE (TREE_TYPE (init)) == tmpl)
30529 return cp_build_qualified_type (TREE_TYPE (init), cp_type_quals (ptype));
30531 if (!ctad_template_p (tmpl))
30533 if (complain & tf_error)
30534 error ("non-deducible template %qT used without template arguments", tmpl);
30535 return error_mark_node;
30537 else if (cxx_dialect < cxx20 && DECL_ALIAS_TEMPLATE_P (tmpl))
30539 if (complain & tf_error)
30541 /* Be permissive with equivalent alias templates. */
30542 tree u = get_underlying_template (tmpl);
30543 diagnostic_t dk = (u == tmpl) ? DK_ERROR : DK_PEDWARN;
30544 bool complained
30545 = emit_diagnostic (dk, input_location, 0,
30546 "alias template deduction only available "
30547 "with %<-std=c++20%> or %<-std=gnu++20%>");
30548 if (u == tmpl)
30549 return error_mark_node;
30550 else if (complained)
30552 inform (input_location, "use %qD directly instead", u);
30553 tmpl = u;
30556 else
30557 return error_mark_node;
30560 /* Wait until the initializer is non-dependent. */
30561 if (type_dependent_expression_p (init))
30562 return ptype;
30564 /* Don't bother with the alias rules for an equivalent template. */
30565 tmpl = get_underlying_template (tmpl);
30567 tree type = TREE_TYPE (tmpl);
30569 bool try_list_cand = false;
30570 bool list_init_p = false;
30572 releasing_vec rv_args = NULL;
30573 vec<tree,va_gc> *&args = *&rv_args;
30574 if (init == NULL_TREE)
30575 args = make_tree_vector ();
30576 else if (BRACE_ENCLOSED_INITIALIZER_P (init))
30578 list_init_p = true;
30579 try_list_cand = true;
30580 if (CONSTRUCTOR_NELTS (init) == 1
30581 && !CONSTRUCTOR_IS_DESIGNATED_INIT (init))
30583 /* As an exception, the first phase in 16.3.1.7 (considering the
30584 initializer list as a single argument) is omitted if the
30585 initializer list consists of a single expression of type cv U,
30586 where U is a specialization of C or a class derived from a
30587 specialization of C. */
30588 tree elt = CONSTRUCTOR_ELT (init, 0)->value;
30589 if (is_spec_or_derived (TREE_TYPE (elt), tmpl))
30590 try_list_cand = false;
30592 if (try_list_cand || is_std_init_list (type))
30593 args = make_tree_vector_single (init);
30594 else
30595 args = make_tree_vector_from_ctor (init);
30597 else if (TREE_CODE (init) == TREE_LIST)
30598 args = make_tree_vector_from_list (init);
30599 else
30600 args = make_tree_vector_single (init);
30602 /* Do this now to avoid problems with erroneous args later on. */
30603 args = resolve_args (args, complain);
30604 if (args == NULL)
30605 return error_mark_node;
30607 bool any_dguides_p = false;
30608 tree cands = deduction_guides_for (tmpl, any_dguides_p, complain);
30609 if (cands == error_mark_node)
30610 return error_mark_node;
30612 /* Prune explicit deduction guides in copy-initialization context (but
30613 not copy-list-initialization). */
30614 bool elided = false;
30615 if (!list_init_p && (flags & LOOKUP_ONLYCONVERTING))
30617 for (lkp_iterator iter (cands); !elided && iter; ++iter)
30618 if (DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
30619 elided = true;
30621 if (elided)
30623 /* Found a nonconverting guide, prune the candidates. */
30624 tree pruned = NULL_TREE;
30625 for (lkp_iterator iter (cands); iter; ++iter)
30626 if (!DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
30627 pruned = lookup_add (*iter, pruned);
30629 cands = pruned;
30633 if (!any_dguides_p)
30634 if (tree guide = maybe_aggr_guide (tmpl, init, args))
30635 cands = lookup_add (guide, cands);
30637 tree fndecl = error_mark_node;
30639 /* If this is list-initialization and the class has a list guide, first
30640 try deducing from the list as a single argument, as [over.match.list]. */
30641 if (try_list_cand)
30643 tree list_cands = NULL_TREE;
30644 for (tree dg : lkp_range (cands))
30645 if (is_list_ctor (dg))
30646 list_cands = lookup_add (dg, list_cands);
30647 if (list_cands)
30648 fndecl = perform_dguide_overload_resolution (list_cands, args, tf_none);
30649 if (fndecl == error_mark_node)
30651 /* That didn't work, now try treating the list as a sequence of
30652 arguments. */
30653 release_tree_vector (args);
30654 args = make_tree_vector_from_ctor (init);
30655 args = resolve_args (args, complain);
30656 if (args == NULL)
30657 return error_mark_node;
30661 if (elided && !cands)
30663 error ("cannot deduce template arguments for copy-initialization"
30664 " of %qT, as it has no non-explicit deduction guides or "
30665 "user-declared constructors", type);
30666 return error_mark_node;
30668 else if (!cands && fndecl == error_mark_node)
30670 error ("cannot deduce template arguments of %qT, as it has no viable "
30671 "deduction guides", type);
30672 return error_mark_node;
30675 if (fndecl == error_mark_node)
30676 fndecl = perform_dguide_overload_resolution (cands, args, tf_none);
30678 if (fndecl == error_mark_node)
30680 if (complain & tf_warning_or_error)
30682 error ("class template argument deduction failed:");
30683 perform_dguide_overload_resolution (cands, args, complain);
30684 if (elided)
30685 inform (input_location, "explicit deduction guides not considered "
30686 "for copy-initialization");
30688 return error_mark_node;
30690 /* [over.match.list]/1: In copy-list-initialization, if an explicit
30691 constructor is chosen, the initialization is ill-formed. */
30692 else if (flags & LOOKUP_ONLYCONVERTING)
30694 if (DECL_NONCONVERTING_P (fndecl))
30696 if (complain & tf_warning_or_error)
30698 // TODO: Pass down location from cp_finish_decl.
30699 error ("class template argument deduction for %qT failed: "
30700 "explicit deduction guide selected in "
30701 "copy-list-initialization", type);
30702 inform (DECL_SOURCE_LOCATION (fndecl),
30703 "explicit deduction guide declared here");
30706 return error_mark_node;
30710 /* If CTAD succeeded but the type doesn't have any explicit deduction
30711 guides, this deduction might not be what the user intended. */
30712 if (fndecl != error_mark_node && !any_dguides_p && (complain & tf_warning))
30714 if ((!DECL_IN_SYSTEM_HEADER (fndecl)
30715 || global_dc->dc_warn_system_headers)
30716 && warning (OPT_Wctad_maybe_unsupported,
30717 "%qT may not intend to support class template argument "
30718 "deduction", type))
30719 inform (input_location, "add a deduction guide to suppress this "
30720 "warning");
30723 return cp_build_qualified_type (TREE_TYPE (TREE_TYPE (fndecl)),
30724 cp_type_quals (ptype));
30727 /* Return true if INIT is an unparenthesized id-expression or an
30728 unparenthesized class member access. Used for the argument of
30729 decltype(auto). */
30731 bool
30732 unparenthesized_id_or_class_member_access_p (tree init)
30734 STRIP_ANY_LOCATION_WRAPPER (init);
30736 /* We need to be able to tell '(r)' and 'r' apart (when it's of
30737 reference type). Only the latter is an id-expression. */
30738 if (REFERENCE_REF_P (init)
30739 && !REF_PARENTHESIZED_P (init))
30740 init = TREE_OPERAND (init, 0);
30741 return (DECL_P (init)
30742 || ((TREE_CODE (init) == COMPONENT_REF
30743 || TREE_CODE (init) == SCOPE_REF)
30744 && !REF_PARENTHESIZED_P (init)));
30747 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
30748 from INIT. AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
30749 The CONTEXT determines the context in which auto deduction is performed
30750 and is used to control error diagnostics. FLAGS are the LOOKUP_* flags.
30752 OUTER_TARGS is used during template argument deduction (context == adc_unify)
30753 to properly substitute the result. It's also used in the adc_unify and
30754 adc_requirement contexts to communicate the necessary template arguments
30755 to satisfaction. OUTER_TARGS is ignored in other contexts.
30757 Additionally for adc_unify contexts TMPL is the template for which TYPE
30758 is a template parameter type.
30760 For partial-concept-ids, extra args from OUTER_TARGS, TMPL and the current
30761 scope may be appended to the list of deduced template arguments prior to
30762 determining constraint satisfaction as appropriate. */
30764 tree
30765 do_auto_deduction (tree type, tree init, tree auto_node,
30766 tsubst_flags_t complain /* = tf_warning_or_error */,
30767 auto_deduction_context context /* = adc_unspecified */,
30768 tree outer_targs /* = NULL_TREE */,
30769 int flags /* = LOOKUP_NORMAL */,
30770 tree tmpl /* = NULL_TREE */)
30772 if (type == error_mark_node || init == error_mark_node)
30773 return error_mark_node;
30775 if (init && type_dependent_expression_p (init)
30776 && context != adc_unify)
30777 /* Defining a subset of type-dependent expressions that we can deduce
30778 from ahead of time isn't worth the trouble. */
30779 return type;
30781 /* Similarly, we can't deduce from another undeduced decl. */
30782 if (init && undeduced_auto_decl (init))
30783 return type;
30785 /* We may be doing a partial substitution, but we still want to replace
30786 auto_node. */
30787 complain &= ~tf_partial;
30789 if (init && BRACE_ENCLOSED_INITIALIZER_P (init))
30791 /* We don't recurse here because we can't deduce from a nested
30792 initializer_list. */
30793 if (CONSTRUCTOR_ELTS (init))
30794 for (constructor_elt &elt : CONSTRUCTOR_ELTS (init))
30795 elt.value = resolve_nondeduced_context (elt.value, complain);
30797 else if (init)
30798 init = resolve_nondeduced_context (init, complain);
30800 /* In C++23, we must deduce the type to int&& for code like
30801 decltype(auto) f(int&& x) { return (x); }
30803 auto&& f(int x) { return x; }
30804 so we use treat_lvalue_as_rvalue_p. But don't do it for
30805 decltype(auto) f(int x) { return x; }
30806 where we should deduce 'int' rather than 'int&&'; transmogrifying
30807 INIT to an rvalue would break that. */
30808 tree r;
30809 if (cxx_dialect >= cxx23
30810 && context == adc_return_type
30811 && (!AUTO_IS_DECLTYPE (auto_node)
30812 || !unparenthesized_id_or_class_member_access_p (init))
30813 && (r = treat_lvalue_as_rvalue_p (maybe_undo_parenthesized_ref (init),
30814 /*return*/true)))
30815 init = r;
30817 if (tree ctmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
30818 /* C++17 class template argument deduction. */
30819 return do_class_deduction (type, ctmpl, init, flags, complain);
30821 if (init == NULL_TREE || TREE_TYPE (init) == NULL_TREE)
30822 /* Nothing we can do with this, even in deduction context. */
30823 return type;
30825 location_t loc = cp_expr_loc_or_input_loc (init);
30827 /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
30828 with either a new invented type template parameter U or, if the
30829 initializer is a braced-init-list (8.5.4), with
30830 std::initializer_list<U>. */
30831 if (BRACE_ENCLOSED_INITIALIZER_P (init))
30833 if (!DIRECT_LIST_INIT_P (init))
30834 type = listify_autos (type, auto_node);
30835 else if (CONSTRUCTOR_NELTS (init) == 1)
30836 init = CONSTRUCTOR_ELT (init, 0)->value;
30837 else
30839 if (complain & tf_warning_or_error)
30841 if (permerror (loc, "direct-list-initialization of "
30842 "%<auto%> requires exactly one element"))
30843 inform (loc,
30844 "for deduction to %<std::initializer_list%>, use copy-"
30845 "list-initialization (i.e. add %<=%> before the %<{%>)");
30847 type = listify_autos (type, auto_node);
30851 if (type == error_mark_node || init == error_mark_node)
30852 return error_mark_node;
30854 tree targs;
30855 if (context == adc_decomp_type
30856 && auto_node == type
30857 && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
30859 /* [dcl.struct.bind]/1 - if decomposition declaration has no ref-qualifiers
30860 and initializer has array type, deduce cv-qualified array type. */
30861 targs = make_tree_vec (1);
30862 TREE_VEC_ELT (targs, 0) = TREE_TYPE (init);
30864 else if (AUTO_IS_DECLTYPE (auto_node))
30866 const bool id = unparenthesized_id_or_class_member_access_p (init);
30867 tree deduced = finish_decltype_type (init, id, complain);
30868 deduced = canonicalize_type_argument (deduced, complain);
30869 if (deduced == error_mark_node)
30870 return error_mark_node;
30871 targs = make_tree_vec (1);
30872 TREE_VEC_ELT (targs, 0) = deduced;
30874 else
30876 if (error_operand_p (init))
30877 return error_mark_node;
30879 tree parms = build_tree_list (NULL_TREE, type);
30880 tree tparms;
30882 if (flag_concepts_ts)
30883 tparms = extract_autos (type);
30884 else
30886 tparms = make_tree_vec (1);
30887 TREE_VEC_ELT (tparms, 0)
30888 = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
30891 targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
30892 int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
30893 DEDUCE_CALL,
30894 NULL, /*explain_p=*/false);
30895 if (val > 0)
30897 if (processing_template_decl)
30898 /* Try again at instantiation time. */
30899 return type;
30900 if (type && type != error_mark_node
30901 && (complain & tf_error))
30902 /* If type is error_mark_node a diagnostic must have been
30903 emitted by now. Also, having a mention to '<type error>'
30904 in the diagnostic is not really useful to the user. */
30906 if (cfun
30907 && FNDECL_USED_AUTO (current_function_decl)
30908 && (auto_node
30909 == DECL_SAVED_AUTO_RETURN_TYPE (current_function_decl))
30910 && LAMBDA_FUNCTION_P (current_function_decl))
30911 error_at (loc, "unable to deduce lambda return type from %qE",
30912 init);
30913 else
30914 error_at (loc, "unable to deduce %qT from %qE", type, init);
30915 type_unification_real (tparms, targs, parms, &init, 1, 0,
30916 DEDUCE_CALL,
30917 NULL, /*explain_p=*/true);
30919 return error_mark_node;
30923 /* Check any placeholder constraints against the deduced type. */
30924 if (processing_template_decl && context == adc_unify)
30925 /* Constraints will be checked after deduction. */;
30926 else if (tree constr = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (auto_node)))
30928 if (processing_template_decl)
30930 gcc_checking_assert (context == adc_variable_type
30931 || context == adc_return_type
30932 || context == adc_decomp_type);
30933 gcc_checking_assert (!type_dependent_expression_p (init));
30934 /* If the constraint is dependent, we need to wait until
30935 instantiation time to resolve the placeholder. */
30936 if (placeholder_type_constraint_dependent_p (constr))
30937 return type;
30940 if (context == adc_return_type
30941 || context == adc_variable_type
30942 || context == adc_decomp_type)
30943 if (tree fn = current_function_decl)
30944 if (DECL_TEMPLATE_INFO (fn) || LAMBDA_FUNCTION_P (fn))
30946 outer_targs = DECL_TEMPLATE_INFO (fn)
30947 ? DECL_TI_ARGS (fn) : NULL_TREE;
30948 if (LAMBDA_FUNCTION_P (fn))
30950 /* As in satisfy_declaration_constraints. */
30951 tree regen_args = lambda_regenerating_args (fn);
30952 if (outer_targs)
30953 outer_targs = add_to_template_args (regen_args, outer_targs);
30954 else
30955 outer_targs = regen_args;
30959 tree full_targs = outer_targs;
30960 if (context == adc_unify && tmpl)
30961 full_targs = add_outermost_template_args (tmpl, full_targs);
30962 full_targs = add_to_template_args (full_targs, targs);
30964 /* HACK: Compensate for callers not always communicating all levels of
30965 outer template arguments by filling in the outermost missing levels
30966 with dummy levels before checking satisfaction. We'll still crash
30967 if the constraint depends on a template argument belonging to one of
30968 these missing levels, but this hack otherwise allows us to handle a
30969 large subset of possible constraints (including all non-dependent
30970 constraints). */
30971 if (int missing_levels = (TEMPLATE_TYPE_ORIG_LEVEL (auto_node)
30972 - TMPL_ARGS_DEPTH (full_targs)))
30974 tree dummy_levels = make_tree_vec (missing_levels);
30975 for (int i = 0; i < missing_levels; ++i)
30976 TREE_VEC_ELT (dummy_levels, i) = make_tree_vec (0);
30977 full_targs = add_to_template_args (dummy_levels, full_targs);
30980 if (!constraints_satisfied_p (auto_node, full_targs))
30982 if (complain & tf_warning_or_error)
30984 auto_diagnostic_group d;
30985 switch (context)
30987 case adc_unspecified:
30988 case adc_unify:
30989 error_at (loc, "placeholder constraints not satisfied");
30990 break;
30991 case adc_variable_type:
30992 case adc_decomp_type:
30993 error_at (loc, "deduced initializer does not satisfy "
30994 "placeholder constraints");
30995 break;
30996 case adc_return_type:
30997 error_at (loc, "deduced return type does not satisfy "
30998 "placeholder constraints");
30999 break;
31000 case adc_requirement:
31001 error_at (loc, "deduced expression type does not satisfy "
31002 "placeholder constraints");
31003 break;
31005 diagnose_constraints (loc, auto_node, full_targs);
31007 return error_mark_node;
31011 if (TEMPLATE_TYPE_LEVEL (auto_node) == 1)
31012 /* The outer template arguments are already substituted into type
31013 (but we still may have used them for constraint checking above). */;
31014 else if (context == adc_unify)
31015 targs = add_to_template_args (outer_targs, targs);
31016 else if (processing_template_decl)
31017 targs = add_to_template_args (current_template_args (), targs);
31018 return tsubst (type, targs, complain, NULL_TREE);
31021 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
31022 result. */
31024 tree
31025 splice_late_return_type (tree type, tree late_return_type)
31027 if (late_return_type)
31029 gcc_assert (is_auto (type) || seen_error ());
31030 return late_return_type;
31033 if (tree auto_node = find_type_usage (type, is_auto))
31034 if (TEMPLATE_TYPE_LEVEL (auto_node) <= current_template_depth)
31036 /* In an abbreviated function template we didn't know we were dealing
31037 with a function template when we saw the auto return type, so rebuild
31038 the return type using an auto with the correct level. */
31039 tree new_auto = make_auto_1 (TYPE_IDENTIFIER (auto_node), false);
31040 tree auto_vec = make_tree_vec (1);
31041 TREE_VEC_ELT (auto_vec, 0) = new_auto;
31042 tree targs = add_outermost_template_args (current_template_args (),
31043 auto_vec);
31044 /* Also rebuild the constraint info in terms of the new auto. */
31045 if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (auto_node))
31046 PLACEHOLDER_TYPE_CONSTRAINTS_INFO (new_auto)
31047 = build_tree_list (current_template_parms,
31048 tsubst_constraint (TREE_VALUE (ci), targs,
31049 tf_none, NULL_TREE));
31050 TYPE_CANONICAL (new_auto) = canonical_type_parameter (new_auto);
31051 return tsubst (type, targs, tf_none, NULL_TREE);
31053 return type;
31056 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
31057 'decltype(auto)' or a deduced class template. */
31059 bool
31060 is_auto (const_tree type)
31062 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
31063 && (TYPE_IDENTIFIER (type) == auto_identifier
31064 || TYPE_IDENTIFIER (type) == decltype_auto_identifier))
31065 return true;
31066 else
31067 return false;
31070 /* for_each_template_parm callback for type_uses_auto. */
31073 is_auto_r (tree tp, void */*data*/)
31075 return is_auto (tp);
31078 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
31079 a use of `auto'. Returns NULL_TREE otherwise. */
31081 tree
31082 type_uses_auto (tree type)
31084 if (type == NULL_TREE)
31085 return NULL_TREE;
31086 else if (flag_concepts_ts)
31088 /* The Concepts TS allows multiple autos in one type-specifier; just
31089 return the first one we find, do_auto_deduction will collect all of
31090 them. */
31091 if (uses_template_parms (type))
31092 return for_each_template_parm (type, is_auto_r, /*data*/NULL,
31093 /*visited*/NULL, /*nondeduced*/false);
31094 else
31095 return NULL_TREE;
31097 else
31098 return find_type_usage (type, is_auto);
31101 /* Report ill-formed occurrences of auto types in ARGUMENTS. If
31102 concepts are enabled, auto is acceptable in template arguments, but
31103 only when TEMPL identifies a template class. Return TRUE if any
31104 such errors were reported. */
31106 bool
31107 check_auto_in_tmpl_args (tree tmpl, tree args)
31109 if (!flag_concepts_ts)
31110 /* Only the concepts TS allows 'auto' as a type-id; it'd otherwise
31111 have already been rejected by the parser more generally. */
31112 return false;
31114 /* If there were previous errors, nevermind. */
31115 if (!args || TREE_CODE (args) != TREE_VEC)
31116 return false;
31118 /* If TMPL is an identifier, we're parsing and we can't tell yet
31119 whether TMPL is supposed to be a type, a function or a variable.
31120 We'll only be able to tell during template substitution, so we
31121 expect to be called again then. If concepts are enabled and we
31122 know we have a type, we're ok. */
31123 if (identifier_p (tmpl)
31124 || (DECL_P (tmpl)
31125 && (DECL_TYPE_TEMPLATE_P (tmpl)
31126 || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))))
31127 return false;
31129 /* Quickly search for any occurrences of auto; usually there won't
31130 be any, and then we'll avoid allocating the vector. */
31131 if (!type_uses_auto (args))
31132 return false;
31134 bool errors = false;
31136 tree vec = extract_autos (args);
31137 for (int i = 0; i < TREE_VEC_LENGTH (vec); i++)
31139 tree xauto = TREE_VALUE (TREE_VEC_ELT (vec, i));
31140 error_at (DECL_SOURCE_LOCATION (xauto),
31141 "invalid use of %qT in template argument", xauto);
31142 errors = true;
31145 return errors;
31148 /* Recursively walk over && expressions searching for EXPR. Return a reference
31149 to that expression. */
31151 static tree *find_template_requirement (tree *t, tree key)
31153 if (*t == key)
31154 return t;
31155 if (TREE_CODE (*t) == TRUTH_ANDIF_EXPR)
31157 if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 0), key))
31158 return p;
31159 if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 1), key))
31160 return p;
31162 return 0;
31165 /* Convert the generic type parameters in PARM that match the types given in the
31166 range [START_IDX, END_IDX) from the current_template_parms into generic type
31167 packs. */
31169 tree
31170 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
31172 tree current = current_template_parms;
31173 int depth = TMPL_PARMS_DEPTH (current);
31174 current = INNERMOST_TEMPLATE_PARMS (current);
31175 tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
31177 for (int i = 0; i < start_idx; ++i)
31178 TREE_VEC_ELT (replacement, i)
31179 = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
31181 for (int i = start_idx; i < end_idx; ++i)
31183 /* Create a distinct parameter pack type from the current parm and add it
31184 to the replacement args to tsubst below into the generic function
31185 parameter. */
31186 tree node = TREE_VEC_ELT (current, i);
31187 tree o = TREE_TYPE (TREE_VALUE (node));
31188 tree t = copy_type (o);
31189 TEMPLATE_TYPE_PARM_INDEX (t)
31190 = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
31191 t, 0, 0, tf_none);
31192 TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
31193 TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
31194 TYPE_MAIN_VARIANT (t) = t;
31195 TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
31196 TYPE_CANONICAL (t) = canonical_type_parameter (t);
31197 TREE_VEC_ELT (replacement, i) = t;
31199 /* Replace the current template parameter with new pack. */
31200 TREE_VALUE (node) = TREE_CHAIN (t);
31202 /* Surgically adjust the associated constraint of adjusted parameter
31203 and it's corresponding contribution to the current template
31204 requirements. */
31205 if (tree constr = TEMPLATE_PARM_CONSTRAINTS (node))
31207 tree id = unpack_concept_check (constr);
31208 TREE_VEC_ELT (TREE_OPERAND (id, 1), 0) = t;
31209 tree fold = finish_left_unary_fold_expr (constr, TRUTH_ANDIF_EXPR);
31210 TEMPLATE_PARM_CONSTRAINTS (node) = fold;
31212 /* If there was a constraint, we also need to replace that in
31213 the template requirements, which we've already built. */
31214 tree *reqs = &TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
31215 reqs = find_template_requirement (reqs, constr);
31216 *reqs = fold;
31220 for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
31221 TREE_VEC_ELT (replacement, i)
31222 = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
31224 /* If there are more levels then build up the replacement with the outer
31225 template parms. */
31226 if (depth > 1)
31227 replacement = add_to_template_args (template_parms_to_args
31228 (TREE_CHAIN (current_template_parms)),
31229 replacement);
31231 return tsubst (parm, replacement, tf_none, NULL_TREE);
31234 /* __integer_pack(N) in a pack expansion expands to a sequence of numbers from
31235 0..N-1. */
31237 void
31238 declare_integer_pack (void)
31240 tree ipfn = push_library_fn (get_identifier ("__integer_pack"),
31241 build_function_type_list (integer_type_node,
31242 integer_type_node,
31243 NULL_TREE),
31244 NULL_TREE, ECF_CONST);
31245 DECL_DECLARED_CONSTEXPR_P (ipfn) = true;
31246 set_decl_built_in_function (ipfn, BUILT_IN_FRONTEND,
31247 CP_BUILT_IN_INTEGER_PACK);
31250 /* Walk the decl or type specialization table calling FN on each
31251 entry. */
31253 void
31254 walk_specializations (bool decls_p,
31255 void (*fn) (bool decls_p, spec_entry *entry, void *data),
31256 void *data)
31258 spec_hash_table *table = decls_p ? decl_specializations
31259 : type_specializations;
31260 spec_hash_table::iterator end (table->end ());
31261 for (spec_hash_table::iterator iter (table->begin ()); iter != end; ++iter)
31262 fn (decls_p, *iter, data);
31265 /* Lookup the specialization of *ELT, in the decl or type
31266 specialization table. Return the SPEC that's already there, or
31267 NULL if nothing. */
31269 tree
31270 match_mergeable_specialization (bool decl_p, spec_entry *elt)
31272 hash_table<spec_hasher> *specializations
31273 = decl_p ? decl_specializations : type_specializations;
31274 hashval_t hash = spec_hasher::hash (elt);
31275 auto *slot = specializations->find_slot_with_hash (elt, hash, NO_INSERT);
31277 if (slot)
31278 return (*slot)->spec;
31280 return NULL_TREE;
31283 /* Return flags encoding whether SPEC is on the instantiation and/or
31284 specialization lists of TMPL. */
31286 unsigned
31287 get_mergeable_specialization_flags (tree tmpl, tree decl)
31289 unsigned flags = 0;
31291 for (tree inst = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
31292 inst; inst = TREE_CHAIN (inst))
31293 if (TREE_VALUE (inst) == decl)
31295 flags |= 1;
31296 break;
31299 if (CLASS_TYPE_P (TREE_TYPE (decl))
31300 && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl))
31301 && CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)) == 2)
31302 /* Only need to search if DECL is a partial specialization. */
31303 for (tree part = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
31304 part; part = TREE_CHAIN (part))
31305 if (TREE_VALUE (part) == decl)
31307 flags |= 2;
31308 break;
31311 return flags;
31314 /* Add a new specialization described by SPEC. DECL is the
31315 maybe-template decl and FLAGS is as returned from
31316 get_mergeable_specialization_flags. */
31318 void
31319 add_mergeable_specialization (bool decl_p, bool alias_p, spec_entry *elt,
31320 tree decl, unsigned flags)
31322 hashval_t hash = spec_hasher::hash (elt);
31323 if (decl_p)
31325 auto *slot = decl_specializations->find_slot_with_hash (elt, hash, INSERT);
31327 gcc_checking_assert (!*slot);
31328 auto entry = ggc_alloc<spec_entry> ();
31329 *entry = *elt;
31330 *slot = entry;
31332 if (alias_p)
31334 elt->spec = TREE_TYPE (elt->spec);
31335 gcc_checking_assert (elt->spec);
31339 if (!decl_p || alias_p)
31341 auto *slot = type_specializations->find_slot_with_hash (elt, hash, INSERT);
31343 /* We don't distinguish different constrained partial type
31344 specializations, so there could be duplicates. Everything else
31345 must be new. */
31346 if (!(flags & 2 && *slot))
31348 gcc_checking_assert (!*slot);
31350 auto entry = ggc_alloc<spec_entry> ();
31351 *entry = *elt;
31352 *slot = entry;
31356 if (flags & 1)
31357 DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl)
31358 = tree_cons (elt->args, decl, DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl));
31360 if (flags & 2)
31362 /* A partial specialization. */
31363 tree cons = tree_cons (elt->args, decl,
31364 DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl));
31365 TREE_TYPE (cons) = decl_p ? TREE_TYPE (elt->spec) : elt->spec;
31366 DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl) = cons;
31370 /* Set up the hash tables for template instantiations. */
31372 void
31373 init_template_processing (void)
31375 decl_specializations = hash_table<spec_hasher>::create_ggc (37);
31376 type_specializations = hash_table<spec_hasher>::create_ggc (37);
31378 if (cxx_dialect >= cxx11)
31379 declare_integer_pack ();
31382 /* Print stats about the template hash tables for -fstats. */
31384 void
31385 print_template_statistics (void)
31387 fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
31388 "%f collisions\n", (long) decl_specializations->size (),
31389 (long) decl_specializations->elements (),
31390 decl_specializations->collisions ());
31391 fprintf (stderr, "type_specializations: size %ld, %ld elements, "
31392 "%f collisions\n", (long) type_specializations->size (),
31393 (long) type_specializations->elements (),
31394 type_specializations->collisions ());
31397 #if CHECKING_P
31399 namespace selftest {
31401 /* Verify that build_non_dependent_expr () works, for various expressions,
31402 and that location wrappers don't affect the results. */
31404 static void
31405 test_build_non_dependent_expr ()
31407 location_t loc = BUILTINS_LOCATION;
31409 /* Verify constants, without and with location wrappers. */
31410 tree int_cst = build_int_cst (integer_type_node, 42);
31411 ASSERT_EQ (int_cst, build_non_dependent_expr (int_cst));
31413 tree wrapped_int_cst = maybe_wrap_with_location (int_cst, loc);
31414 ASSERT_TRUE (location_wrapper_p (wrapped_int_cst));
31415 ASSERT_EQ (wrapped_int_cst, build_non_dependent_expr (wrapped_int_cst));
31417 tree string_lit = build_string (4, "foo");
31418 TREE_TYPE (string_lit) = char_array_type_node;
31419 string_lit = fix_string_type (string_lit);
31420 ASSERT_EQ (string_lit, build_non_dependent_expr (string_lit));
31422 tree wrapped_string_lit = maybe_wrap_with_location (string_lit, loc);
31423 ASSERT_TRUE (location_wrapper_p (wrapped_string_lit));
31424 ASSERT_EQ (wrapped_string_lit,
31425 build_non_dependent_expr (wrapped_string_lit));
31428 /* Verify that type_dependent_expression_p () works correctly, even
31429 in the presence of location wrapper nodes. */
31431 static void
31432 test_type_dependent_expression_p ()
31434 location_t loc = BUILTINS_LOCATION;
31436 tree name = get_identifier ("foo");
31438 /* If no templates are involved, nothing is type-dependent. */
31439 gcc_assert (!processing_template_decl);
31440 ASSERT_FALSE (type_dependent_expression_p (name));
31442 ++processing_template_decl;
31444 /* Within a template, an unresolved name is always type-dependent. */
31445 ASSERT_TRUE (type_dependent_expression_p (name));
31447 /* Ensure it copes with NULL_TREE and errors. */
31448 ASSERT_FALSE (type_dependent_expression_p (NULL_TREE));
31449 ASSERT_FALSE (type_dependent_expression_p (error_mark_node));
31451 /* A USING_DECL in a template should be type-dependent, even if wrapped
31452 with a location wrapper (PR c++/83799). */
31453 tree using_decl = build_lang_decl (USING_DECL, name, NULL_TREE);
31454 TREE_TYPE (using_decl) = integer_type_node;
31455 ASSERT_TRUE (type_dependent_expression_p (using_decl));
31456 tree wrapped_using_decl = maybe_wrap_with_location (using_decl, loc);
31457 ASSERT_TRUE (location_wrapper_p (wrapped_using_decl));
31458 ASSERT_TRUE (type_dependent_expression_p (wrapped_using_decl));
31460 --processing_template_decl;
31463 /* Run all of the selftests within this file. */
31465 void
31466 cp_pt_cc_tests ()
31468 test_build_non_dependent_expr ();
31469 test_type_dependent_expression_p ();
31472 } // namespace selftest
31474 #endif /* #if CHECKING_P */
31476 #include "gt-cp-pt.h"